diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.dockerignore b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..18d980937cfd3d63813511927c8fe676774c5b80 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.dockerignore @@ -0,0 +1,20 @@ +gha-creds-*.json +/site +.vscode +.DS_Store + +# training +outputs/ +/*.ipynb + +# Dataset +datasets/* +!datasets/README + +# No DVC caches +asset_pipeline/.dvc +asset_pipeline/tmp +asset_pipeline/logs +asset_pipeline/artifacts +asset_pipeline/cad +.git \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.gitattributes b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..73704d2e782de0f35ea2faaee40a607ed5c10d8c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.gitattributes @@ -0,0 +1 @@ +*.ipynb linguist-detectable=false \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/ISSUE_TEMPLATE/bug_report.md b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000000000000000000000000000000000000..dc614362f9087fc726cb62076fcbd073ef9eda3b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,32 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - OS: [e.g. Ubuntu 22.04] + - Isaac Sim Version [e.g. 4.1.0] + - OmniGibson Version [e.g. 1.1.0] + +**Additional context** +Add any other context about the problem here. diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/ISSUE_TEMPLATE/feature_request.md b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000000000000000000000000000000000000..4fc8f7307e4fe2d79452421e00f8aac99d161944 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: enhancement +assignees: cgokmen + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/ISSUE_TEMPLATE/question.md b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 0000000000000000000000000000000000000000..119339947609549d8f2b41a3f9383d76dfa4bf87 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,10 @@ +--- +name: Question +about: PLEASE POST QUESTIONS IN THE DISCUSSIONS TAB +title: '' +labels: question +assignees: '' + +--- + +**PLEASE POST QUESTIONS IN THE DISCUSSIONS TAB** diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/scripts/check_types_diff.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/scripts/check_types_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..dbc69b139b032e5ab002f23ce7ae9723270859f2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/scripts/check_types_diff.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Run pyright on the files changed between two git refs, but only fail CI on +errors that land on lines actually touched by the diff. Pre-existing errors +in the rest of a changed file are reported but do not fail the build, so we +can turn on type checking without first fixing the entire legacy codebase. +""" + +import argparse +import json +import re +import subprocess +import sys +from pathlib import Path + +HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@") + + +def run(cmd, cwd=None): + return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True) + + +def changed_python_files(base, head, package_dir): + result = run( + ["git", "diff", "--name-only", "--diff-filter=ACMR", f"{base}", f"{head}", "--", package_dir] + ) + if result.returncode != 0: + print(result.stderr, file=sys.stderr) + sys.exit(2) + files = [line.strip() for line in result.stdout.splitlines() if line.strip()] + return [f for f in files if f.endswith(".py") and Path(f).exists()] + + +def added_lines_for_file(base, head, repo_relative_path): + """Return the set of 1-indexed line numbers introduced/modified in `head`.""" + result = run(["git", "diff", "--no-color", "--unified=0", f"{base}", f"{head}", "--", repo_relative_path]) + if result.returncode != 0: + print(result.stderr, file=sys.stderr) + sys.exit(2) + lines = set() + for line in result.stdout.splitlines(): + match = HUNK_RE.match(line) + if not match: + continue + new_start = int(match.group(1)) + new_count = int(match.group(2)) if match.group(2) is not None else 1 + if new_count == 0: + # Pure deletion at this point in the file; nothing was added. + continue + lines.update(range(new_start, new_start + new_count)) + return lines + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--package-dir", required=True, help="Repo-relative package directory, e.g. OmniGibson") + parser.add_argument("--base", required=True, help="Base git ref/sha to diff against") + parser.add_argument("--head", required=True, help="Head git ref/sha being checked") + args = parser.parse_args() + + package_dir = args.package_dir.rstrip("/") + changed_files = changed_python_files(args.base, args.head, package_dir) + + if not changed_files: + print(f"No changed Python files under {package_dir}/ — skipping type check.") + return 0 + + print(f"Type-checking {len(changed_files)} changed file(s) under {package_dir}/:") + for f in changed_files: + print(f" {f}") + + relative_files = [str(Path(f).relative_to(package_dir)) for f in changed_files] + pyright_result = run(["pyright", "--outputjson", *relative_files], cwd=package_dir) + + try: + report = json.loads(pyright_result.stdout) + except json.JSONDecodeError: + print("Failed to parse pyright output as JSON:", file=sys.stderr) + print(pyright_result.stdout, file=sys.stderr) + print(pyright_result.stderr, file=sys.stderr) + return 2 + + added_lines = {f: added_lines_for_file(args.base, args.head, f) for f in changed_files} + + blocking, pre_existing = [], [] + for diag in report.get("generalDiagnostics", []): + if diag.get("severity") != "error": + continue + diag_file = str(Path(package_dir) / Path(diag["file"]).relative_to(Path(package_dir).resolve())) + line = diag["range"]["start"]["line"] + 1 + entry = f"{diag_file}:{line}: {diag['message'].splitlines()[0]}" + if line in added_lines.get(diag_file, ()): + blocking.append(entry) + else: + pre_existing.append(entry) + + if pre_existing: + print(f"\n{len(pre_existing)} pre-existing type error(s) in touched files (not blocking):") + for entry in pre_existing: + print(f" {entry}") + + if blocking: + print(f"\n{len(blocking)} new type error(s) on lines you touched (blocking):") + for entry in blocking: + print(f" {entry}") + return 1 + + print("\nNo new type errors on touched lines.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/scripts/cprofile_to_html.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/scripts/cprofile_to_html.py new file mode 100644 index 0000000000000000000000000000000000000000..16d2b41fd9e9aac8512242de6149453e690d6d53 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/scripts/cprofile_to_html.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Convert a cProfile .prof file into an HTML summary. + +This uses snakeviz to parse profile stats and render function tables inspired by +https://gist.github.com/MSSandroid/6402e2e99e31633386a312b283839e0d. +""" + +import argparse +import html +import os +from pstats import Stats + + +def _format_time(seconds): + return f"{seconds:.6f}" + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--profile", required=True, help="Path to .prof file") + parser.add_argument("--output", required=True, help="Output html path") + parser.add_argument("--limit", type=int, default=200, help="Number of functions to include") + args = parser.parse_args() + + import snakeviz.stats as snakeviz_stats + + stats = Stats(args.profile) + snake_stats = snakeviz_stats.json_stats(stats) + + rows = [] + for idx, (func_name, data) in enumerate(sorted(snake_stats.items(), key=lambda item: item[1]["stats"][3], reverse=True)): + if idx >= args.limit: + break + ccalls, ncalls, tottime, cumtime = data["stats"] + rows.append( + "" + f"{idx + 1}" + f"{html.escape(func_name)}" + f"{ncalls}" + f"{ccalls}" + f"{_format_time(tottime)}" + f"{_format_time(cumtime)}" + "" + ) + + total_calls = stats.total_calls + primitive_calls = stats.prim_calls + total_time = stats.total_tt + + os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True) + with open(args.output, "w", encoding="utf-8") as f: + f.write( + """ + + + + cProfile report + + + +""" + ) + f.write(f"

cProfile report: {html.escape(os.path.basename(args.profile))}

\n") + f.write("

Generated with snakeviz.stats.json_stats and pstats.Stats.

\n") + f.write( + f"\n" + ) + f.write( + "" + ) + f.write("\n".join(rows)) + f.write("
#FunctionCallsPrimitive CallsTotal Time (s)Cumulative Time (s)
\n\n") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/scripts/resolve_diff_range.sh b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/scripts/resolve_diff_range.sh new file mode 100644 index 0000000000000000000000000000000000000000..f161df416756abac99d537ca8d656556f59f3743 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/scripts/resolve_diff_range.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Determines the base commit to diff against for diff-scoped type checking, +# and writes it to $GITHUB_OUTPUT as `base_sha`. +set -euo pipefail + +if [ "$EVENT_NAME" = "pull_request" ]; then + git fetch --depth=1 origin "$BASE_REF" + base_sha=$(git merge-base "origin/$BASE_REF" HEAD) +else + base_sha="$BEFORE_SHA" + if [ -z "$base_sha" ] || [ "$base_sha" = "0000000000000000000000000000000000000000" ]; then + base_sha=$(git rev-parse HEAD~1) + fi +fi + +echo "base_sha=$base_sha" >> "$GITHUB_OUTPUT" diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/build-push-containers.yml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/build-push-containers.yml new file mode 100644 index 0000000000000000000000000000000000000000..86ceae8a0714f8955f4904a1d5bed08a848d48df --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/build-push-containers.yml @@ -0,0 +1,157 @@ +name: build-push-containers + +on: + release: + types: [published] + push: + branches: + - 'main' + workflow_dispatch: + inputs: + image_tag: + description: > + Tag to publish the manually-built behavior-dev/behavior-gha images under (e.g. the branch + name). + required: true + type: string + +jobs: + docker: + runs-on: docker-builder # This is a larger runner with more disk space. + steps: + - + name: Check disk space + run: df . -h + - + name: Free disk space + run: | + sudo docker rmi $(docker image ls -aq) >/dev/null 2>&1 || true + sudo rm -rf \ + /usr/share/dotnet /usr/local/lib/android /opt/ghc \ + /usr/local/share/powershell /usr/share/swift /usr/local/.ghcup \ + /usr/lib/jvm /opt/hostedtoolcache/CodeQL || true + echo "some directories deleted" + sudo apt-get update >/dev/null 2>&1 + sudo apt install aptitude -y >/dev/null 2>&1 + sudo aptitude purge aria2 ansible azure-cli shellcheck rpm xorriso zsync \ + esl-erlang firefox gfortran-8 gfortran-9 google-chrome-stable \ + google-cloud-sdk imagemagick \ + libmagickcore-dev libmagickwand-dev libmagic-dev ant ant-optional kubectl \ + mercurial apt-transport-https mono-complete libmysqlclient \ + unixodbc-dev yarn chrpath libssl-dev libxft-dev \ + libfreetype6 libfreetype6-dev libfontconfig1 libfontconfig1-dev \ + snmp pollinate libpq-dev postgresql-client powershell ruby-full \ + sphinxsearch subversion mongodb-org azure-cli microsoft-edge-stable \ + -y -f >/dev/null 2>&1 || true + sudo aptitude purge google-cloud-sdk -f -y >/dev/null 2>&1 || true + sudo aptitude purge microsoft-edge-stable -f -y >/dev/null 2>&1 || true + sudo apt purge microsoft-edge-stable -f -y >/dev/null 2>&1 || true + sudo aptitude purge '~n ^mysql' -f -y >/dev/null 2>&1 || true + sudo aptitude purge '~n ^php' -f -y >/dev/null 2>&1 || true + sudo aptitude purge '~n ^dotnet' -f -y >/dev/null 2>&1 || true + sudo apt-get autoremove -y >/dev/null 2>&1 + sudo apt-get autoclean -y >/dev/null 2>&1 + echo "some packages purged" + - + name: Check disk space + run: | + df . -h + - + name: Checkout + uses: actions/checkout@v4 + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - + name: Login to NVCR + uses: docker/login-action@v3 + with: + registry: nvcr.io + username: ${{ secrets.NVCR_USERNAME }} + password: ${{ secrets.NVCR_PASSWORD }} + - + name: Login to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_HUB_USERNAME }} + password: ${{ secrets.DOCKER_HUB_PASSWORD }} + - + name: Metadata for prod Image + id: meta-prod + if: github.event_name != 'workflow_dispatch' + uses: docker/metadata-action@v5 + with: + images: | + stanfordvl/behavior + tags: | + type=ref,event=branch + type=semver,pattern={{version}} + - + name: Metadata for dev Image + id: meta-dev + uses: docker/metadata-action@v5 + with: + images: | + stanfordvl/behavior-dev + tags: | + type=ref,event=branch + type=semver,pattern={{version}} + type=raw,value=${{ github.event.inputs.image_tag }},enable=${{ github.event_name == 'workflow_dispatch' }} + - + name: Metadata for actions Image + id: meta-actions + uses: docker/metadata-action@v5 + with: + images: | + stanfordvl/behavior-gha + tags: | + type=raw,value=latest,enable=${{ github.event_name != 'workflow_dispatch' }} + type=raw,value=${{ github.event.inputs.image_tag }},enable=${{ github.event_name == 'workflow_dispatch' }} + - + name: Build and push prod image + id: build-prod + if: github.event_name != 'workflow_dispatch' + uses: docker/build-push-action@v5 + with: + context: . + push: true + provenance: false + tags: ${{ steps.meta-prod.outputs.tags }} + labels: ${{ steps.meta-prod.outputs.labels }} + file: docker/Dockerfile + cache-from: type=registry,ref=stanfordvl/behavior:build-cache + cache-to: type=registry,ref=stanfordvl/behavior:build-cache,mode=max + + - + name: Build and push dev image + id: build-dev + uses: docker/build-push-action@v5 + with: + context: . + build-args: "DEV_MODE=1" + push: true + provenance: false + tags: ${{ steps.meta-dev.outputs.tags }} + labels: ${{ steps.meta-dev.outputs.labels }} + file: docker/Dockerfile + # Manual workflow_dispatch builds read from the shared cache for speed but never write to + # it, so a broken branch build can never poison the cache used by the real main/release + # builds. + cache-from: type=registry,ref=stanfordvl/behavior:build-cache + cache-to: ${{ github.event_name != 'workflow_dispatch' && 'type=registry,ref=stanfordvl/behavior:build-cache,mode=max' || '' }} + + - name: Update actions image Dockerfile with dev image tag + run: | + sed -i "s/behavior-dev:latest/behavior-dev@${{ steps.build-dev.outputs.digest }}/g" docker/gh-actions/Dockerfile && cat docker/gh-actions/Dockerfile + - + name: Build and push actions image + id: build-actions + uses: docker/build-push-action@v5 + with: + context: docker/gh-actions + push: true + tags: ${{ steps.meta-actions.outputs.tags }} + labels: ${{ steps.meta-actions.outputs.labels }} + file: docker/gh-actions/Dockerfile + cache-from: type=registry,ref=stanfordvl/behavior:build-cache + cache-to: ${{ github.event_name != 'workflow_dispatch' && 'type=registry,ref=stanfordvl/behavior:build-cache,mode=max' || '' }} diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/build-website.yml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/build-website.yml new file mode 100644 index 0000000000000000000000000000000000000000..e89d72bcda845c8f823e2f8678a34aa474778914 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/build-website.yml @@ -0,0 +1,89 @@ +name: Build and deploy BEHAVIOR website + +on: + schedule: + - cron: "0 10 * * *" # Every day at 10am + workflow_dispatch: + push: + branches: + - main + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: "pages" + + +jobs: + build: + runs-on: [self-hosted, linux] + + steps: + - name: Fix home + run: echo "HOME=/root" >> $GITHUB_ENV + + - name: Checkout source + uses: actions/checkout@v4 + + - name: Install BDDL + working-directory: bddl3 + run: pip install -e . + + - name: Install + working-directory: OmniGibson + run: pip install -e .[dev] + + - name: Build docs + run: mkdocs build # TODO: Shouldn't we copy over the src directory here? + + # # See if we need to rebuild the whole thing + # - name: Get BDDL hash + # id: bddl-hash + # working-directory: bddl3 + # run: echo hash=$(git rev-parse HEAD) >> "$GITHUB_OUTPUT" + + # - name: Get knowledgebase hash + # id: website-hash + # working-directory: knowledgebase + # run: echo hash=$(git rev-parse HEAD) >> "$GITHUB_OUTPUT" + + # - name: Check cache for overall data + # id: cache-knowledgebase + # uses: actions/cache@v3 + # with: + # key: knowledgebase-${{ steps.website-hash.outputs.hash }}-${{ steps.bddl-hash.outputs.hash }} + # path: README.md + # lookup-only: true + + # - if: ${{ steps.cache-knowledgebase.outputs.cache-hit != 'true' }} + - name: Install other dependencies + working-directory: knowledgebase + run: pip install -r requirements.txt + + # - if: ${{ steps.cache-knowledgebase.outputs.cache-hit != 'true' }} + - name: Generate static knowledgebase site + working-directory: knowledgebase + run: python build_static_site.py + + - name: Move knowledgebase to combined site + run: cp -R knowledgebase/build/knowledgebase site + + - name: Upload pages artifact + uses: actions/upload-pages-artifact@v3 + with: + path: site/ + + # Deploy on github pages + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + needs: build + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/profiling.yml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/profiling.yml new file mode 100644 index 0000000000000000000000000000000000000000..bc79490e625f56b1caf947e856b785e5a0ea5889 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/profiling.yml @@ -0,0 +1,305 @@ +name: Profiling + +on: + pull_request: + push: + branches: + - main + workflow_dispatch: + +permissions: + pull-requests: write + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }} + cancel-in-progress: true + +jobs: + profile: + name: "Profile: ${{ matrix.label }}" + runs-on: [self-hosted, linux, gpu, dataset-enabled] + + strategy: + fail-fast: false + matrix: + include: + # Baselines (GPU dynamics) + - name: baseline-empty + args: "-g" + label: "Empty scene" + - name: baseline-empty-1robot + args: "-g -r 1" + label: "Empty scene + 1 Robot" + - name: baseline-rs-int + args: "-g -s Rs_int" + label: "Rs_int" + - name: baseline-rs-int-1robot + args: "-g -s Rs_int -r 1" + label: "Rs_int + 1 Robot" + - name: deep-rs-int-1robot + args: "-g -s Rs_int -r 1 -d" + label: "Rs_int + 1 Robot (deep profile)" + deep_profile: true + # Scenes + - name: scene-house + args: "-r 1 -s house_single_floor" + label: "house_single_floor + 1 Robot" + # Non-physics features (GPU dynamics) + - name: feature-fluids + args: "-g -r 1 -w" + label: "1 Robot + fluids" + - name: feature-cloth + args: "-g -r 1 -c" + label: "1 Robot + cloth" + - name: feature-particles + args: "-g -r 1 -p" + label: "1 Robot + macro particles" + + defaults: + run: + working-directory: ${{ github.workspace }}/OmniGibson + + steps: + - name: Checkout source + uses: actions/checkout@v4 + with: + submodules: true + + - name: Install BDDL + run: pip install -e . + working-directory: ${{ github.workspace }}/bddl3 + + - name: Install OmniGibson + run: pip install -e .[dev,primitives,eval] --no-build-isolation + + - name: Install deep profiling dependencies + if: matrix.deep_profile + run: pip install snakeviz + + - name: Run profiling + run: | + rm -f output.json + python tests/benchmark/profiling.py ${{ matrix.args }} + + - name: Convert deep profile to HTML + if: matrix.deep_profile + run: | + for prof in load.prof step.prof pre_physics_step.prof post_physics_step.prof non_physics_step.prof; do + python ../.github/scripts/cprofile_to_html.py \ + --profile "$prof" \ + --output "${prof%.prof}.html" + done + + - name: Upload results + uses: actions/upload-artifact@v4 + if: always() + with: + name: profiling-${{ matrix.name }} + path: OmniGibson/output.json + if-no-files-found: warn + + - name: Upload deep profile outputs + uses: actions/upload-artifact@v4 + if: always() && matrix.deep_profile + with: + name: profiling-deep-${{ matrix.name }} + path: | + OmniGibson/load.prof + OmniGibson/load.html + OmniGibson/step.prof + OmniGibson/step.html + OmniGibson/pre_physics_step.prof + OmniGibson/pre_physics_step.html + OmniGibson/post_physics_step.prof + OmniGibson/post_physics_step.html + OmniGibson/non_physics_step.prof + OmniGibson/non_physics_step.html + if-no-files-found: warn + + report: + name: Compile Profiling Report + runs-on: ubuntu-latest + needs: [profile] + if: always() && github.event_name == 'pull_request' + permissions: + pull-requests: write + steps: + - name: Download PR profiling results + uses: actions/download-artifact@v4 + continue-on-error: true + with: + path: pr-results + pattern: profiling-* + + - name: Restore baseline from main + uses: actions/cache/restore@v4 + continue-on-error: true + with: + path: baseline + key: profiling-baseline-${{ github.event.pull_request.base.sha }} + restore-keys: | + profiling-baseline- + + - name: Generate report + run: | + python3 << 'PYEOF' + import json, os + + SCENARIOS = [ + ("profiling-baseline-empty", "Empty scene", "Baselines (GPU dynamics)"), + ("profiling-baseline-empty-1robot", "Empty scene + 1 Robot", "Baselines (GPU dynamics)"), + ("profiling-baseline-rs-int", "Rs_int", "Baselines (GPU dynamics)"), + ("profiling-baseline-rs-int-1robot", "Rs_int + 1 Robot", "Baselines (GPU dynamics)"), + ("profiling-scene-house", "house_single_floor + 1 Robot", "Scenes"), + ("profiling-feature-fluids", "1 Robot + fluids", "Non-physics features (GPU dynamics)"), + ("profiling-feature-cloth", "1 Robot + cloth", "Non-physics features (GPU dynamics)"), + ("profiling-feature-particles", "1 Robot + macro particles", "Non-physics features (GPU dynamics)"), + ] + + METRICS = ["FPS", "Loading time", "Isaac step time", "Non-Isaac step time", "Memory usage", "Vram usage"] + HEADERS = { + "FPS": "FPS", + "Loading time": "Load (s)", + "Isaac step time": "Isaac (ms)", + "Non-Isaac step time": "Non-Isaac (ms)", + "Memory usage": "Mem (GB)", + "Vram usage": "VRAM (GB)", + } + HIGHER_IS_BETTER = {"FPS"} + + def load_results(base_path): + results = {} + if not os.path.isdir(base_path): + return results + for dir_name, _, _ in SCENARIOS: + json_path = os.path.join(base_path, dir_name, "output.json") + if not os.path.exists(json_path): + continue + with open(json_path) as f: + data = json.load(f) + metrics = {} + for entry in data: + metrics[entry["extra"][0]] = entry["value"] + results[dir_name] = metrics + return results + + def fmt(metric, value): + if value is None: + return "N/A" + return f"{value:.1f}" if metric in ("FPS", "Loading time") else f"{value:.2f}" + + def delta(metric, pr_val, base_val): + if pr_val is None or base_val is None or base_val == 0: + return "" + pct = ((pr_val - base_val) / abs(base_val)) * 100 + is_better = (pct > 0) if metric in HIGHER_IS_BETTER else (pct < 0) + if abs(pct) < 5: + emoji = "⚪" + elif is_better: + emoji = "🟢" + else: + emoji = "🔴" + sign = "+" if pct > 0 else "" + return f" ({sign}{pct:.1f}% {emoji})" + + pr = load_results("pr-results") + base = load_results("baseline") + has_base = len(base) > 0 + + lines = ["## Profiling Report\n"] + if not has_base: + lines.append("> **Note:** No baseline found from `main`. Showing absolute values only.\n") + + current_group = None + for dir_name, label, group in SCENARIOS: + if group != current_group: + current_group = group + lines.append(f"\n### {group}\n") + hdr = "| Scenario |" + "".join(f" {HEADERS[m]} |" for m in METRICS) + sep = "|---|" + "---|" * len(METRICS) + lines.append(hdr) + lines.append(sep) + + pr_m = pr.get(dir_name, {}) + if not pr_m: + lines.append(f"| {label} |" + " N/A |" * len(METRICS)) + continue + + base_m = base.get(dir_name, {}) + row = f"| {label}" + for m in METRICS: + pv, bv = pr_m.get(m), base_m.get(m) + cell = fmt(m, pv) + if has_base and pv is not None: + cell += delta(m, pv, bv) + row += f" | {cell}" + lines.append(row + " |") + + lines.append("") + lines.append("### Deep profile artifacts") + lines.append( + f"Download deep profile HTML reports and raw .prof files from the " + f"[Actions artifacts](https://github.com/{os.environ['GITHUB_REPOSITORY']}/actions/runs/{os.environ['GITHUB_RUN_ID']}#artifacts) " + f"(artifact prefix: `profiling-deep-`). Includes:" + ) + lines.append("- `load` — environment loading") + lines.append("- `step` — full simulation step") + lines.append("- `pre_physics_step` — pre-physics step processing") + lines.append("- `post_physics_step` — post-physics step processing") + lines.append("- `non_physics_step` — non-physics step processing") + + lines.append("") + lines.append("
Legend\n") + lines.append("- 🟢 Improvement >= 5%") + lines.append("- 🔴 Regression >= 5%") + lines.append("- ⚪ Change < 5%") + lines.append("- For **FPS**, higher is better. For all other metrics, lower is better.") + lines.append("\n
") + + report = "\n".join(lines) + with open("profiling-report.md", "w") as f: + f.write(report) + print(report) + PYEOF + + - name: Post PR comment + uses: marocchino/sticky-pull-request-comment@v2 + with: + header: profiling-report + path: profiling-report.md + + save_baseline: + name: Save Baseline + runs-on: ubuntu-latest + needs: [profile] + if: always() && github.event_name == 'push' && github.ref == 'refs/heads/main' + steps: + - name: Restore previous baseline + uses: actions/cache/restore@v4 + continue-on-error: true + with: + path: baseline + key: profiling-baseline-do-not-match + restore-keys: | + profiling-baseline- + + - name: Download new profiling results + uses: actions/download-artifact@v4 + continue-on-error: true + with: + path: new-results + pattern: profiling-* + + - name: Merge into baseline + run: | + mkdir -p baseline + if [ -d new-results ]; then + cp -r new-results/* baseline/ + fi + + - name: Save baseline cache + uses: actions/cache/save@v4 + with: + path: baseline + key: profiling-baseline-${{ github.sha }} diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/profiling_vector.yml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/profiling_vector.yml new file mode 100644 index 0000000000000000000000000000000000000000..f56be3d81ce0cb06ef00ba59eb0888a03d38c42c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/profiling_vector.yml @@ -0,0 +1,306 @@ +name: Vector Profiling + +on: + pull_request: + branches: + - vec/merge-vector-into-main + - main + push: + branches: + - main + workflow_dispatch: + +permissions: + pull-requests: write + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.ref }} + cancel-in-progress: true + +jobs: + profile: + name: "VecProfile: ${{ matrix.label }}" + runs-on: [self-hosted, linux, gpu, dataset-enabled, titanrtx] + + strategy: + fail-fast: false + matrix: + include: + # 1 env + - name: "1env-norender-simple-nostates" + args: "--n-envs 1" + label: "1 env, no render, simple, states off" + - name: "1env-norender-simple-states" + args: "--n-envs 1 --object-states" + label: "1 env, no render, simple, states on" + - name: "1env-norender-behavior-states" + args: "--n-envs 1 --task-type behavior --object-states" + label: "1 env, no render, behavior, states on" + - name: "1env-render-simple-nostates" + args: "--n-envs 1 --rendering" + label: "1 env, render, simple, states off" + - name: "1env-render-simple-states" + args: "--n-envs 1 --rendering --object-states" + label: "1 env, render, simple, states on" + - name: "1env-render-behavior-states" + args: "--n-envs 1 --rendering --task-type behavior --object-states" + label: "1 env, render, behavior, states on" + - name: "1env-norender-navigation-nostates" + args: "--n-envs 1 --task-type navigation" + label: "1 env, no render, navigation, states off" + - name: "1env-norender-navigation-states" + args: "--n-envs 1 --task-type navigation --object-states" + label: "1 env, no render, navigation, states on" + - name: "1env-render-navigation-nostates" + args: "--n-envs 1 --rendering --task-type navigation" + label: "1 env, render, navigation, states off" + - name: "1env-render-navigation-states" + args: "--n-envs 1 --rendering --task-type navigation --object-states" + label: "1 env, render, navigation, states on" + # 10 envs + - name: "10env-norender-simple-nostates" + args: "--n-envs 10" + label: "10 envs, no render, simple, states off" + - name: "10env-norender-simple-states" + args: "--n-envs 10 --object-states" + label: "10 envs, no render, simple, states on" + - name: "10env-norender-behavior-states" + args: "--n-envs 10 --task-type behavior --object-states" + label: "10 envs, no render, behavior, states on" + - name: "10env-render-simple-nostates" + args: "--n-envs 10 --rendering" + label: "10 envs, render, simple, states off" + - name: "10env-render-simple-states" + args: "--n-envs 10 --rendering --object-states" + label: "10 envs, render, simple, states on" + - name: "10env-render-behavior-states" + args: "--n-envs 10 --rendering --task-type behavior --object-states" + label: "10 envs, render, behavior, states on" + - name: "10env-norender-navigation-nostates" + args: "--n-envs 10 --task-type navigation" + label: "10 envs, no render, navigation, states off" + - name: "10env-norender-navigation-states" + args: "--n-envs 10 --task-type navigation --object-states" + label: "10 envs, no render, navigation, states on" + - name: "10env-render-navigation-nostates" + args: "--n-envs 10 --rendering --task-type navigation" + label: "10 envs, render, navigation, states off" + - name: "10env-render-navigation-states" + args: "--n-envs 10 --rendering --task-type navigation --object-states" + label: "10 envs, render, navigation, states on" + + defaults: + run: + working-directory: ${{ github.workspace }}/OmniGibson + + steps: + - name: Checkout source + uses: actions/checkout@v4 + with: + submodules: true + + - name: Install BDDL + run: pip install -e . + working-directory: ${{ github.workspace }}/bddl3 + + - name: Install OmniGibson + run: pip install -e .[dev,primitives,eval] --no-build-isolation + + - name: Run vector profiling + env: + OMNIGIBSON_HEADLESS: "1" + run: | + rm -f vector_output.json + python tests/benchmark/vector_profiling.py -g ${{ matrix.args }} + + - name: Upload results + uses: actions/upload-artifact@v4 + if: always() + with: + name: vec-profiling-${{ matrix.name }} + path: OmniGibson/vector_output.json + if-no-files-found: warn + + report: + name: Compile Vector Profiling Report + runs-on: ubuntu-latest + needs: [profile] + if: always() && github.event_name == 'pull_request' + permissions: + pull-requests: write + + steps: + - name: Download PR profiling results + uses: actions/download-artifact@v4 + continue-on-error: true + with: + path: pr-results + pattern: vec-profiling-* + + - name: Restore baseline from vector + uses: actions/cache/restore@v4 + continue-on-error: true + with: + path: baseline + key: vec-profiling-baseline-${{ github.event.pull_request.base.sha }} + restore-keys: | + vec-profiling-baseline- + + - name: Merge results and build comparison report + run: | + python3 << 'PYEOF' + import json, os + + # Walk a directory of downloaded artifacts and concatenate every vector_output.json found. + def collect(results_dir): + merged = [] + if os.path.isdir(results_dir): + for dirpath, _, filenames in os.walk(results_dir): + for fname in filenames: + if fname == "vector_output.json": + with open(os.path.join(dirpath, fname)) as f: + merged.extend(json.load(f)) + return merged + + # Build lookup: label -> metric -> value + def build_lookup(entries): + result = {} + for e in entries: + label = e["name"] + metric = e["extra"][0] + if label not in result: + result[label] = {} + result[label][metric] = e["value"] + return result + + pr = build_lookup(collect("pr-results")) + base = build_lookup(collect("baseline")) + has_base = len(base) > 0 + + METRICS = ["FPS", "Loading time", "Isaac step time", "Non-Isaac step time", "Memory usage", "Vram usage"] + HEADERS = { + "FPS": "FPS", + "Loading time": "Load (s)", + "Isaac step time": "Isaac (ms)", + "Non-Isaac step time": "Non-Isaac (ms)", + "Memory usage": "Mem (GB)", + "Vram usage": "VRAM (GB)", + } + HIGHER_IS_BETTER = {"FPS"} + N_ENV_GROUPS = ["1 env", "10 envs"] + REFERENCE_GROUP = N_ENV_GROUPS[0] + + def fmt(metric, value): + if value is None: + return "N/A" + return f"{value:.1f}" if metric in ("FPS", "Loading time") else f"{value:.2f}" + + def delta(metric, pr_val, base_val): + if pr_val is None or base_val is None or base_val == 0: + return "" + pct = ((pr_val - base_val) / abs(base_val)) * 100 + is_better = (pct > 0) if metric in HIGHER_IS_BETTER else (pct < 0) + emoji = "⚪" if abs(pct) < 5 else ("🟢" if is_better else "🔴") + sign = "+" if pct > 0 else "" + return f" ({sign}{pct:.1f}% {emoji})" + + # Ratio of this scenario against the same scenario at REFERENCE_GROUP env count, so the + # multi-env rows show how each metric scales with n_envs (e.g. "x4.2" load, "x9.0" FPS). + def scaling(label, metric, value): + if value is None or ", " not in label: + return "" + ref_label = REFERENCE_GROUP + ", " + label.split(", ", 1)[1] + ref_val = pr.get(ref_label, {}).get(metric) + if ref_val is None or ref_val == 0: + return "" + return f" [x{value / ref_val:.1f}]" + + lines = ["## Vector Profiling Report\n"] + if not has_base: + lines.append("> **Note:** No baseline found. Showing absolute values only.\n") + + all_labels = sorted(pr.keys()) + + for group in N_ENV_GROUPS: + group_labels = [l for l in all_labels if l.startswith(group + ",")] + if not group_labels: + continue + lines.append(f"\n### {group}\n") + hdr = "| Scenario |" + "".join(f" {HEADERS[m]} |" for m in METRICS) + sep = "|---|" + "---|" * len(METRICS) + lines.append(hdr) + lines.append(sep) + for label in sorted(group_labels): + pr_m = pr.get(label, {}) + base_m = base.get(label, {}) + row = f"| {label.split(', ', 1)[1] if ', ' in label else label}" + for m in METRICS: + pv = pr_m.get(m) + bv = base_m.get(m) + cell = fmt(m, pv) + if has_base and pv is not None: + cell += delta(m, pv, bv) + if group != REFERENCE_GROUP: + cell += scaling(label, m, pv) + row += f" | {cell}" + lines.append(row + " |") + + lines.append("") + lines.append("
Legend\n") + lines.append("- 🟢 Improvement >= 5%") + lines.append("- 🔴 Regression >= 5%") + lines.append("- ⚪ Change < 5%") + lines.append("- **FPS**: higher is better. All other metrics: lower is better.") + lines.append("- FPS = total throughput across all envs (n_envs × per-env FPS)") + lines.append(f"- `[xN.N]` = ratio against the same scenario at {REFERENCE_GROUP}. " + "For FPS this is the throughput speed-up (higher is better); " + "for every other metric it is the growth factor (lower is better).") + lines.append("\n
") + + report = "\n".join(lines) + with open("profiling-vector-report.md", "w") as f: + f.write(report) + print(report) + PYEOF + + - name: Post PR comment + uses: marocchino/sticky-pull-request-comment@v2 + with: + header: vector-profiling-report + path: profiling-vector-report.md + + save_baseline: + name: Save Vector Profiling Baseline + runs-on: ubuntu-latest + needs: [profile] + if: always() && github.event_name == 'push' && github.ref == 'refs/heads/main' + steps: + - name: Restore previous baseline + uses: actions/cache/restore@v4 + continue-on-error: true + with: + path: baseline + key: vec-profiling-baseline-do-not-match + restore-keys: | + vec-profiling-baseline- + + - name: Download new profiling results + uses: actions/download-artifact@v4 + continue-on-error: true + with: + path: new-results + pattern: vec-profiling-* + + - name: Merge into baseline + run: | + mkdir -p baseline + if [ -d new-results ]; then + cp -r new-results/* baseline/ + fi + + - name: Save baseline cache + uses: actions/cache/save@v4 + with: + path: baseline + key: vec-profiling-baseline-${{ github.sha }} diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/publish-pypi.yml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/publish-pypi.yml new file mode 100644 index 0000000000000000000000000000000000000000..74a8064b67d02bb26761217801e646660d9686ba --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/publish-pypi.yml @@ -0,0 +1,38 @@ +# This workflow will upload a Python Package using Twine when a release is created +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries + +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +name: Upload Python Package + +on: + release: + types: [published] + +jobs: + pypi-publish: + name: Upload release to PyPI + runs-on: ubuntu-latest + environment: + name: pypi + url: https://pypi.org/p/omnigibson + permissions: + id-token: write # IMPORTANT: this permission is mandatory for trusted publishing + contents: read + steps: + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v3 + with: + python-version: '3.x' + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install setuptools wheel twine + - name: Build package + run: python setup.py sdist + - name: Publish package distributions to PyPI + uses: pypa/gh-action-pypi-publish@v1.10.2 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/pull-sheets-bddl.yml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/pull-sheets-bddl.yml new file mode 100644 index 0000000000000000000000000000000000000000..bab0e7ee4d9d9ec3a4de2a1d80bc03afc1d3fed5 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/pull-sheets-bddl.yml @@ -0,0 +1,100 @@ +name: Sync bddl Google Sheets data + +on: + schedule: + - cron: "0 9 * * *" # Every day at 9am + workflow_dispatch: + # push: + # branches: + # - main + +jobs: + pull-sheets: + name: Sync Google Sheets data + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - name: Setup python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + architecture: x64 + + - name: Authenticate on Google Cloud + uses: 'google-github-actions/auth@v1' + with: + credentials_json: '${{ secrets.GCP_CREDENTIALS }}' + + - uses: webfactory/ssh-agent@v0.9.0 + with: + ssh-private-key: ${{ secrets.SHEETS_DEPLOY_KEY }} + + # See if we need to re-pull any asset_pipeline data from DVC. + - name: Check cache for pipeline data + id: cache-pipeline + uses: actions/cache@v3 + with: + key: asset_pipeline-${{ hashFiles('asset_pipeline/dvc.lock') }} + path: | + asset_pipeline/artifacts/pipeline/combined_room_object_list.json + asset_pipeline/artifacts/pipeline/object_inventory.json + + - if: ${{ steps.cache-pipeline.outputs.cache-hit != 'true' }} + name: Install dvc + run: pip install dvc[gs] + + - if: ${{ steps.cache-pipeline.outputs.cache-hit != 'true' }} + name: Pull dvc data + working-directory: asset_pipeline + run: dvc pull combined_room_object_list object_inventory + + - if: ${{ steps.cache-pipeline.outputs.cache-hit != 'true' }} + name: Unprotect data + working-directory: asset_pipeline + run: dvc unprotect artifacts/pipeline/combined_room_object_list.json artifacts/pipeline/object_inventory.json + + - name: Copy over pipeline files + run: cp asset_pipeline/artifacts/pipeline/{combined_room_object_list,object_inventory}.json bddl3/bddl/generated_data + + - name: Combine complaint files from asset_pipeline + run: | + python3 -c " + import glob, json + files = glob.glob('asset_pipeline/cad/*/*/complaints.json') + combined = [] + for file in files: + with open(file) as f: + combined.extend(json.load(f)) + combined.sort(key=lambda x: (x['object'], x['type'], x['additional_info'], x['complaint'], x['processed'])) + with open('bddl3/bddl/generated_data/complaints.json', 'w') as f: + json.dump(combined, f, indent=2) + " + + - name: Install BDDL + working-directory: bddl3 + run: pip install -e . + + - name: Install dev requirements + working-directory: bddl3 + run: pip install -r requirements-dev.txt + + - name: Refresh sheets data + working-directory: bddl3 + run: python -m bddl.data_generation.pull_sheets + + - name: Refresh derivative data + working-directory: bddl3 + run: python -m bddl.data_generation.generate_datafiles + + # Validate that the generated knowledgebase still builds before auto-committing these refreshed files. + # If this step fails, the workflow stops and does not auto-commit/push a broken knowledgebase that + # would block sampling and the website. load_wordnet=True enables deeper WordNet-based synset validation. + - name: Test if knowledgebase builds OK + run: python -c "from bddl.knowledge_base import KnowledgeBase; KnowledgeBase(verbose=False, load_wordnet=True)" + + - uses: stefanzweifel/git-auto-commit-action@v4 + with: + commit_message: "Sync bddl Google Sheets data" \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/pull-sheets.yml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/pull-sheets.yml new file mode 100644 index 0000000000000000000000000000000000000000..fac4dcb4e127a13282f9c5f29b670fbd7ea7f6bf --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/pull-sheets.yml @@ -0,0 +1,44 @@ +name: Sync asset pipeline Google Sheets data + +on: + schedule: + - cron: "0 10 * * *" # Every day at 10am + workflow_dispatch: + # push: + # branches: + # - main + +jobs: + pull-sheets: + name: Sync Google Sheets data + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - name: Setup python + uses: actions/setup-python@v2 + with: + python-version: "3.8" + architecture: x64 + + - name: Install requirements + run: pip install gspread pandas + + - name: Authenticate on Google Cloud + uses: 'google-github-actions/auth@v1' + with: + credentials_json: '${{ secrets.GCP_CREDENTIALS }}' + + - uses: webfactory/ssh-agent@v0.9.0 + with: + ssh-private-key: ${{ secrets.SHEETS_DEPLOY_KEY }} + + - name: Refresh sheets data + run: python -m b1k_pipeline.sync_sheets + working-directory: asset_pipeline + + - uses: stefanzweifel/git-auto-commit-action@v4 + with: + commit_message: "Sync Google Sheets data" diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/tests.yml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..3b568ed1b6c0fb7c8a10f0cf48cc041de824f0b1 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/tests.yml @@ -0,0 +1,249 @@ +name: Tests + +on: + pull_request: + push: + branches: + - main + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }} + cancel-in-progress: true + +jobs: + bddl_tests: + name: BDDL Tests + runs-on: [self-hosted, linux, gpu] + + steps: + - name: Checkout source + uses: actions/checkout@v4 + with: + submodules: true + + - name: Install BDDL + run: pip install -e . + working-directory: ${{ github.workspace }}/bddl3 + + - name: Run BDDL tests + run: pytest tests/test_knowledgebase.py -v --junitxml=bddl_tests.xml -o junit_family=xunit1 + working-directory: ${{ github.workspace }}/bddl3 + + - name: Deploy artifact + if: always() + uses: actions/upload-artifact@v4 + with: + name: ${{ github.run_id }}-tests-bddl + path: bddl3/bddl_tests.xml + overwrite: true + + check_example_list: + name: Check Example List Up To Date + runs-on: [self-hosted, linux, gpu] + defaults: + run: + working-directory: ${{ github.workspace }}/OmniGibson + + steps: + - name: Checkout source + uses: actions/checkout@v4 + with: + submodules: true + + - name: Install BDDL + run: pip install -e . + working-directory: ${{ github.workspace }}/bddl3 + + - name: Install OmniGibson + run: pip install -e .[dev,primitives,eval] --no-build-isolation + - name: Check example lists are up to date + run: python tests/update_example_tests.py --check + + run_test: + name: Run Tests + runs-on: [self-hosted, linux, gpu, dataset-enabled] + + strategy: + fail-fast: false + matrix: + test_file: + - test_controllers + # - test_curobo + # - test_data_collection # TODO: https://github.com/StanfordVL/BEHAVIOR-1K/issues/2016 + - test_dump_load_states + - test_envs + - test_multiple_envs_dummy_api + - test_multiple_envs_dummy_scene + - test_multiple_envs_heat_narrow_phase + - test_multiple_envs_heat_states + - test_multiple_envs_transition_rules + - test_object_removal + - test_object_states + # - test_primitives + - test_robot_states_flatcache + - test_robot_teleoperation + - test_scene_graph + - test_sensors + - test_symbolic_primitives + - test_systems + - test_transform_utils + - test_snapshots + - test_transition_rules + include: + # The three BehaviorTask multi-env suites share one env (see the `behavior_env` fixture in + # tests/conftest.py), so running them in a single job loads house_double_floor_lower once + # instead of once per file. They stay separate files; only the job is shared. + - test_file: test_multiple_envs_behavior_scene + extra_files: >- + tests/test_multiple_envs_behavior_task.py + # The task-type suites share the same gm macros, so one job pays the Isaac startup cost once. + - test_file: test_multiple_envs_task_tensors + extra_files: >- + tests/test_multiple_envs_grasp.py + tests/test_multiple_envs_point_tasks.py + # --- BEGIN AUTO-GENERATED EXAMPLE INCLUDES --- + - {test_file: test_examples, example: "environments.navigation_env_demo"} + - {test_file: test_examples, example: "environments.vector_env_demo"} + - {test_file: test_examples, example: "object_states.attachment_demo"} + - {test_file: test_examples, example: "object_states.dicing_demo"} + - {test_file: test_examples, example: "object_states.heated_state_demo"} + - {test_file: test_examples, example: "object_states.onfire_demo"} + - {test_file: test_examples, example: "object_states.overlaid_demo"} + - {test_file: test_examples, example: "object_states.particle_applier_remover_demo"} + - {test_file: test_examples, example: "object_states.sample_kinematics_demo"} + - {test_file: test_examples, example: "object_states.slicing_demo"} + - {test_file: test_examples, example: "object_states.temperature_demo"} + - {test_file: test_examples, example: "objects.draw_bounding_box"} + - {test_file: test_examples, example: "objects.highlight_objects"} + - {test_file: test_examples, example: "objects.load_object_selector"} + - {test_file: test_examples, example: "objects.visualize_object"} + - {test_file: test_examples, example: "robots.all_robots_visualizer"} + - {test_file: test_examples, example: "robots.grasping_mode_example"} + - {test_file: test_examples, example: "robots.import_custom_robot", args: "--config tests/data/r1_pro_source_config.yaml"} + - {test_file: test_examples, example: "robots.robot_control_example"} + - {test_file: test_examples, example: "scenes.scene_selector"} + - {test_file: test_examples, example: "scenes.scene_tour_demo"} + - {test_file: test_examples, example: "scenes.traversability_map_example"} + - {test_file: test_examples, example: "simulator.sim_save_load_example"} + # --- END AUTO-GENERATED EXAMPLE INCLUDES --- + + defaults: + run: + working-directory: ${{ github.workspace }}/OmniGibson + + steps: + - name: Checkout source + uses: actions/checkout@v4 + with: + submodules: true + + - name: Install BDDL + run: pip install -e . + working-directory: ${{ github.workspace }}/bddl3 + + - name: Install OmniGibson + run: pip install -e .[dev,primitives,eval] --no-build-isolation + + - name: Print env + run: printenv + + - name: Run tests + run: > + pytest -s tests/${{ matrix.test_file }}.py ${{ matrix.extra_files || '' }} + ${{ matrix.example && format('-k "{0}"', matrix.example) || '' }} + ${{ matrix.args && format('--test-args={0}', matrix.args) || '' }} + --junitxml=${{ matrix.test_file }}${{ matrix.example && format('_{0}', matrix.example) || '' }}.xml + -o junit_family=xunit1 + continue-on-error: true + timeout-minutes: 30 + + - name: Check for failures, errors, or missing XML + if: always() + run: | + xml=${{ matrix.test_file }}${{ matrix.example && format('_{0}', matrix.example) || '' }}.xml + if [ ! -f "$xml" ]; then + cat > "$xml" << 'EOF' + + + + + + + EOF + echo "Error: XML file not found, probably due to segfault or timeout" + exit 1 + elif grep -Eq 'failures="[1-9][0-9]*"|errors="[1-9][0-9]*"' "$xml"; then + echo "Error: Test failures or errors found" + exit 1 + else + echo "All tests passed successfully" + fi + + - name: Deploy snapshot artifacts + if: always() && matrix.test_file == 'test_snapshots' + uses: actions/upload-artifact@v4 + with: + name: ${{ github.run_id }}-snapshots + path: OmniGibson/tests/snapshots/actual/ + overwrite: true + + - name: Deploy artifact + if: always() + uses: actions/upload-artifact@v4 + with: + name: ${{ github.run_id }}-tests-${{ matrix.test_file }}${{ matrix.example && format('-{0}', matrix.example) || '' }} + path: OmniGibson/${{ matrix.test_file }}${{ matrix.example && format('_{0}', matrix.example) || '' }}.xml + overwrite: true + + upload_report: + name: Test Report + runs-on: ubuntu-latest + needs: [bddl_tests, check_example_list, run_test] + if: always() + permissions: + pull-requests: write + steps: + - name: Checkout source + uses: actions/checkout@v4 + + - name: Pull reports + uses: actions/download-artifact@v4 + with: + path: test-results + merge-multiple: true + - name: Upload test results to Trunk + if: ${{ !cancelled() }} + continue-on-error: true + uses: trunk-io/analytics-uploader@v1 + with: + junit-paths: test-results/**/*.xml + org-slug: stanfordvl-behavior + token: ${{ secrets.TRUNK_API_TOKEN }} + + - name: Convert JUnit XML to CTRF + run: npx --yes junit-to-ctrf "test-results/**/test_*.xml" -o ctrf-report.json + + - name: Publish PR comment + uses: ctrf-io/github-test-reporter@v1 + with: + report-path: ctrf-report.json + pull-request-report: true + overwrite-comment: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Fail if any tests failed or were cancelled + run: | + if [[ "${{ needs.run_test.result }}" == "cancelled" || "${{ needs.bddl_tests.result }}" == "cancelled" || "${{ needs.check_example_list.result }}" == "cancelled" ]]; then + echo "One or more test jobs were cancelled" + exit 1 + fi + if grep -rqE 'failures="[1-9][0-9]*"|errors="[1-9][0-9]*"' test-results/; then + echo "Test failures or errors found" + exit 1 + fi + + # - name: Upload coverage to Codecov + # uses: codecov/codecov-action@v2.1.0 + # with: + # token: ${{ secrets.CODECOV_TOKEN }} diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/type-check.yml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/type-check.yml new file mode 100644 index 0000000000000000000000000000000000000000..881a261072cb027e0ee8e394de76b24751ffac3f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.github/workflows/type-check.yml @@ -0,0 +1,104 @@ +name: Type Check + +on: + pull_request: + push: + branches: + - main + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }} + cancel-in-progress: true + +jobs: + typecheck_bddl: + name: Type Check (bddl3) + runs-on: [self-hosted, linux, gpu] + steps: + - name: Checkout source + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Determine diff range + id: range + env: + EVENT_NAME: ${{ github.event_name }} + BASE_REF: ${{ github.base_ref }} + BEFORE_SHA: ${{ github.event.before }} + run: .github/scripts/resolve_diff_range.sh + + - name: Install BDDL + run: pip install -e .[dev] + working-directory: bddl3 + + - name: Check types on changed files + continue-on-error: true # TODO: make blocking once the existing backlog is cleaned up + run: > + python .github/scripts/check_types_diff.py + --package-dir bddl3 + --base ${{ steps.range.outputs.base_sha }} + --head ${{ github.sha }} + + typecheck_omnigibson: + name: Type Check (OmniGibson) + runs-on: [self-hosted, linux, gpu] + steps: + - name: Checkout source + uses: actions/checkout@v4 + with: + fetch-depth: 0 + submodules: true + + - name: Determine diff range + id: range + env: + EVENT_NAME: ${{ github.event_name }} + BASE_REF: ${{ github.base_ref }} + BEFORE_SHA: ${{ github.event.before }} + run: .github/scripts/resolve_diff_range.sh + + - name: Install BDDL + run: pip install -e . + working-directory: bddl3 + + - name: Install OmniGibson + run: pip install -e .[dev,primitives,eval] --no-build-isolation + working-directory: OmniGibson + + - name: Check types on changed files + continue-on-error: true # TODO: make blocking once the existing backlog is cleaned up + run: > + python .github/scripts/check_types_diff.py + --package-dir OmniGibson + --base ${{ steps.range.outputs.base_sha }} + --head ${{ github.sha }} + + typecheck_joylo: + name: Type Check (joylo) + runs-on: [self-hosted, linux, gpu] + steps: + - name: Checkout source + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Determine diff range + id: range + env: + EVENT_NAME: ${{ github.event_name }} + BASE_REF: ${{ github.base_ref }} + BEFORE_SHA: ${{ github.event.before }} + run: .github/scripts/resolve_diff_range.sh + + - name: Install joylo + run: pip install -e .[dev] + working-directory: joylo + + - name: Check types on changed files + continue-on-error: true # TODO: make blocking once the existing backlog is cleaned up + run: > + python .github/scripts/check_types_diff.py + --package-dir joylo + --base ${{ steps.range.outputs.base_sha }} + --head ${{ github.sha }} diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.gitignore b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..0ea1bc6da4d92fa1b89ada6dab235e4454a62d67 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.gitignore @@ -0,0 +1,11 @@ +gha-creds-*.json +/site +.vscode +.DS_Store + +# training +outputs/ +/*.ipynb + +__pycache__/ +.codex diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.pre-commit-config.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a3fe8ec1702bc531e6653d2bdd11f7a7ef76ef85 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/.pre-commit-config.yaml @@ -0,0 +1,12 @@ +repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + # Ruff version. + rev: v0.8.4 + hooks: + # Run the linter. + - id: ruff + args: ["--fix"] + files: ^OmniGibson/ + # Run the formatter. + - id: ruff-format + files: ^OmniGibson/ \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/AGENTS.md b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..e0d3e4ed3f5416da1ec18e1956e5f3906981ecc1 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/AGENTS.md @@ -0,0 +1,109 @@ +# AGENTS.md + +This file provides guidance to AI coding agents when working with code in this repository. + +## General Guidelines + +- **Use `behavior` conda environment by default** when running Python commands, unless explicitly told otherwise. You can do this by using the `conda run` command. The conda binary is usually available as ~/miniconda3/condabin/conda. +- **Make minimal changes** - prefer small, targeted edits over large rewrites. Avoid unnecessary stylistic changes (e.g., reformatting code that isn't relevant to the task). + +## Project Overview + +BEHAVIOR-1K is a monorepo for a simulation benchmark testing embodied AI agents on 1,000+ household activities. It contains three main packages plus supporting tooling: + +- **OmniGibson** (`OmniGibson/`) - Physics simulation engine built on NVIDIA Omniverse/Isaac Sim. Provides environments, robots, objects, sensors, controllers, and tasks as a Gymnasium-compatible interface. +- **BDDL3** (`bddl3/`) - Behavior Domain Definition Language. Defines a symbolic knowledge base with 1,000+ activity definitions, object taxonomy/ontology, and condition evaluation logic. +- **JoyLo** (`joylo/`) - Teleoperation framework for robot control using physical hardware (GELLO devices). + +Supporting components: `asset_pipeline/` (3D asset conversion), `knowledgebase/` (Flask web app for browsing BDDL data), `docs/` (MkDocs site), `eval-jobqueue/` (evaluation infrastructure). + +## Commands + +### Installation +You should not have to install any part of this project, the user should have a pre-installed conda env for you. If that's not the case, refuse running things and ask them to install first. But for general reference, the below are the installation commands. + +```bash +# Modular install via setup script (conda env creation + component selection) +bash setup.sh --new-env behavior --omnigibson --bddl +# Individual packages (editable installs) +cd bddl3 && pip install -e . +cd OmniGibson && pip install -e .[dev] # dev dependencies (pytest, mkdocs) +cd OmniGibson && pip install -e .[dev,primitives] # + motion planning (curobo) +cd OmniGibson && pip install -e .[dev,eval] # + evaluation dependencies +``` + +### Testing (OmniGibson) +Tests require an NVIDIA RTX GPU (2080Ti+) and Isaac Sim runtime. Whenever running any tests, you should set the OMNIGIBSON_HEADLESS=1 environment flag so that a DISPLAY is not needed. Run from the `OmniGibson/` directory: +```bash +pytest tests/ # all tests +pytest tests/test_object_states.py # single test file +pytest tests/test_envs.py -k "test_name" # single test by name +``` + +### Linting +Pre-commit hooks run Ruff on `OmniGibson/` only (not joylo, bddl3): +```bash +ruff check OmniGibson/ # lint +ruff format OmniGibson/ # format +pre-commit run --all-files # run pre-commit hooks +``` + +### Documentation +```bash +mkdocs serve # local docs server (from repo root, uses mkdocs.yml) +``` + +## Architecture + +### OmniGibson Core (`OmniGibson/omnigibson/`) +The simulation engine follows a registry pattern — robots, objects, scenes, tasks, controllers, and sensors each have a `REGISTERED_*` dict populated via class decorators. + +Key module relationships: +- **`simulator.py`** — Singleton wrapper around Isaac Sim. All physics stepping goes through here. +- **`envs/`** — Gymnasium environments. `env_base.py` is the core env; `vec_env_base.py` for vectorized; wrappers in `env_wrapper.py` and `data_wrapper.py`. +- **`robots/`** — Robot definitions in `definitions/` (YAML-configured). `robot.py` is the base class. +- **`objects/`** — Simulated objects with state tracking (temperature, wetness, etc.). +- **`object_states/`** — State logic (e.g., `Cooked`, `Sliced`, `OnTop`). These implement BDDL predicates in simulation. +- **`scenes/`** — Scene loading and management. +- **`tasks/`** — Task definitions that pair with BDDL activity specs. +- **`controllers/`** — Low-level robot control (joint, IK, operational space). +- **`sensors/`** — Vision, scan, and other sensor modalities. +- **`transition_rules.py`** — Rules for state transitions (e.g., cooking, mixing). +- **`systems/`** — Particle systems (water, dust, etc.) and material systems. +- **`macros.py`** — Global configuration via `gm` (global macros) object. +- **`action_primitives/`** — High-level action abstractions (pick, place, navigate). +- **`learning/`** — RL training utilities. + +OmniGibson is based on Isaac Sim, which will be installed in the `behavior` conda env. You can expect to find Isaac Sim source files in the conda env's site packages directory, +under the `isaacsim` package. Everything from isaacsim needs to be imported using the `omnigibson.lazy` module since these imports are only available after the app has launched +(e.g. through simulator.py's launch_app). You can follow most of these imports to the source code by finding the appropriate extension inside the isaacsim directory. Especially +relevant extensions' names start with isaacsim.core. + +OmniGibson currently uses [Isaac Sim 5.1](https://docs.isaacsim.omniverse.nvidia.com/5.1.0/) and [Omniverse Kit 107.3.1](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/107.3.1/). This [documentation for USDRT](https://docs.omniverse.nvidia.com/kit/docs/usdrt.scenegraph/7.6.1/index.html#usdrt-scenegraph-module) may also be especially useful for understanding Fabric and USD syncing. When following the links, make sure not to add an extra "docs/" to the href. + +### BDDL3 (`bddl3/bddl/`) +- **`activity_definitions/`** — One file per activity with symbolic pre/post conditions. +- **`object_taxonomy.py`** — Hierarchical object ontology. +- **`condition_evaluation.py`** — Evaluates symbolic conditions against simulation state. +- **`backend_abc.py`** — Abstract interface that OmniGibson implements to connect simulation to BDDL logic. +- **`knowledge_base/`** — Structured data about objects, scenes, and their properties. + +### Config-Driven Design +OmniGibson uses YAML configs extensively (`OmniGibson/omnigibson/configs/`). Environment creation typically loads a config specifying scene, task, robot, and controller parameters. + +## Code Style + +- **Python 3.10+**, line length 120, indent 4 spaces +- **Ruff** for linting and formatting (rules: E4, E7, E9, F; ignores: E731, E722, E741) +- Ruff config is split: root `ruff.toml` (excludes joylo) and `OmniGibson/pyproject.toml` (detailed rules) +- Pre-commit hooks only apply to `OmniGibson/` directory +- Type checking via Pyright (configured in `OmniGibson/pyproject.toml`) + +## CI/CD + +GitHub Actions workflows (`.github/workflows/`): +- **tests.yml** — Runs pytest matrix across test files on self-hosted GPU runners. Also checks example list is up to date. +- **build-push-containers.yml** — Docker image builds +- **build-website.yml** — MkDocs documentation deployment +- **publish-pypi.yml** — PyPI releases +- **profiling.yml** — Performance benchmarking diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/CLAUDE.md b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..f5d76674e1e22096b6fb8b312ea543d7336e09a9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/CLAUDE.md @@ -0,0 +1,3 @@ +# CLAUDE.md + +@AGENTS.md \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/LICENSE b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3883c7d16fc54952b28c4ad57e3c3f8e8e85a9e2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Stanford Vision and Learning Group + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/.gitignore b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a3bdca721f030f5465f22fcbf4103b03a86061b7 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/.gitignore @@ -0,0 +1,97 @@ +*.pyc +*.pyd +*.pkl +*.so +*.egg-info/ +.DS_Store +*.pth +src/ +pw +*.o +*.ipynb +*.ipynb_checkpoints/ +*.out +npz/ +*.npy +dev/transfer.c +*.jpg +*.png +*.bmp +*.bak +*.zip +.*.swp + +docs/apidoc + +# vscode +.vscode/ + +# Physics +physics/*.txt +physics/*.json +# Physics assets +physics/models + +*/events* +0_VRDemoSettings.txt + +# VR +# This is the folder where the pyd files get put after setup.py builds gibson +Release + +cnn_policy* +*ppo_policy* +checkpoint +*.log +*.log.* +*.model.* +examples/train/models/ + +log_*/ +baselines/ +aws/ +monitor_* +comparison/ +0.monitor.csvpaper/ +0.monitor.csv + +cvpr/ +gibson/cpp-household + +*.idea* + +# Plotting +examples/scripts/plot* + +# Models +nav_models + +gibson/assets +*.pdf +.cache +notebook +build +dist +omnigibson.egg-info + +# Directories used for QC pipeline +omnigibson/utils/data_utils/mesh_decimation/collision +omnigibson/utils/data_utils/mesh_decimation/visual +omnigibson/utils/data_utils/mesh_decimation/final_videos + +# libcryptopp +omnigibson/render/mesh_renderer/libcryptopp.so.8.6 + +# Coverage +.coverage +coverage.xml + +# Doc +docs/reference +site/ + +# Tests of examples +tests/tests_of_examples + +# Appdata directory generated by Omniverse +appdata/ \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/.gitmodules b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/.gitmodules new file mode 100644 index 0000000000000000000000000000000000000000..9a77f3648bb3b8554938d7fd2a2fde3bc94529b0 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/.gitmodules @@ -0,0 +1,15 @@ +[submodule "omnigibson/render/pybind11"] + path = omnigibson/render/pybind11 + url = https://github.com/pybind/pybind11.git +[submodule "omnigibson/render/glfw"] + path = omnigibson/render/glfw + url = https://github.com/glfw/glfw +[submodule "omnigibson/render/glm"] + path = omnigibson/render/glm + url = https://github.com/g-truc/glm +[submodule "omnigibson/render/openvr"] + path = omnigibson/render/openvr + url = https://github.com/ValveSoftware/openvr +[submodule "omnigibson/render/cryptopp"] + path = omnigibson/render/cryptopp + url = https://github.com/fxia22/cryptopp diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/LICENSE b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3883c7d16fc54952b28c4ad57e3c3f8e8e85a9e2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Stanford Vision and Learning Group + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/MANIFEST.in b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..cb116b8f279cf378aa5b98e3c083ff28a6625076 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/MANIFEST.in @@ -0,0 +1,6 @@ +include LICENSE + +graft omnigibson +prune omnigibson/data + +global-exclude *.py[co] \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/README.md b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bf9be69614fee7a41d103068366a2288116fa56a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/README.md @@ -0,0 +1,54 @@ +![splash](./docs/assets/splash.png) + +#

OmniGibson

+[![Tests](https://github.com/StanfordVL/OmniGibson/actions/workflows/tests.yml/badge.svg?branch=main&event=push)](https://github.com/StanfordVL/OmniGibson/actions/workflows/tests.yml) +[![Docker Image Version (latest by date)](https://img.shields.io/docker/v/stanfordvl/omnigibson?label=docker&sort=semver)](https://hub.docker.com/r/stanfordvl/omnigibson) +[![Realtime Speed](https://behavior.stanford.edu/knowledgebase/profile/badge.svg)](https://stanfordvl.github.io/OmniGibson/profiling/) + +------- + +### Need support? Join our Discord! + + +------- + +### Latest Updates +- [10/01/24] **v1.1.0**: Major improvements, stability fixes, pip installation, and much more! [[release notes]](https://github.com/StanfordVL/OmniGibson/releases/tag/v1.1.0) + +- [03/17/24] **v1.0.0**: First full release with 1,004 pre-sampled tasks, all 50 scenes, and many new objects! [[release notes]](https://github.com/StanfordVL/OmniGibson/releases/tag/v1.0.0) + +- [08/04/23] **v0.2.0**: More assets! 600 pre-sampled tasks, 7 new scenes, and many new objects 📈 [[release notes]](https://github.com/StanfordVL/OmniGibson/releases/tag/v0.2.0) + +- [04/10/23] **v0.1.0**: Significantly improved stability, performance, and ease of installation :wrench: [[release notes]](https://github.com/StanfordVL/OmniGibson/releases/tag/v0.1.0) + +------- + +**`OmniGibson`** is a platform for accelerating Embodied AI research built upon NVIDIA's [Omniverse](https://www.nvidia.com/en-us/omniverse/) platform, featuring: + +* 📸 Photorealistic Visuals and 📐 Physical Realism +* 🌊 Fluid and 👕 Soft Body Support +* 🏔️ Large-Scale, High-Quality Scenes and 🎾 Objects +* 🌡️ Dynamic Kinematic and Semantic Object States +* 🤖 Mobile Manipulator Robots with Modular ⚙️ Controllers +* 🌎 OpenAI Gym Interface + +Check out [**`OmniGibson`**'s documentation](https://behavior.stanford.edu/omnigibson/getting_started/installation.html) to get started! + +### Citation +If you use **`OmniGibson`** or its assets and models, please cite: + +``` +@inproceedings{ +li2022behavior, +title={{BEHAVIOR}-1K: A Benchmark for Embodied {AI} with 1,000 Everyday Activities and Realistic Simulation}, +author={Chengshu Li and Ruohan Zhang and Josiah Wong and Cem Gokmen and Sanjana Srivastava and Roberto Mart{\'\i}n-Mart{\'\i}n and Chen Wang and Gabrael Levine and Michael Lingelbach and Jiankai Sun and Mona Anvari and Minjune Hwang and Manasi Sharma and Arman Aydin and Dhruva Bansal and Samuel Hunter and Kyu-Young Kim and Alan Lou and Caleb R Matthews and Ivan Villa-Renteria and Jerry Huayang Tang and Claire Tang and Fei Xia and Silvio Savarese and Hyowon Gweon and Karen Liu and Jiajun Wu and Li Fei-Fei}, +booktitle={6th Annual Conference on Robot Learning}, +year={2022}, +url={https://openreview.net/forum?id=_8DoIe8G3t} +} +``` + +### Profiling +Click on the plot to access our profiling page with more examples. + +[![Profiling](https://behavior.stanford.edu/knowledgebase/profile/plot.png)](https://stanfordvl.github.io/OmniGibson/profiling/) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/.gitignore b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..e4a0c4accdd0142b39c674eb1be981ffab0f93c0 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/.gitignore @@ -0,0 +1,4 @@ +*.tar.gz' +data +render/coord.npy +render/model.pth \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..91cf47570e79ffbb07046ca66e1758c5773f7bd8 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/__init__.py @@ -0,0 +1,199 @@ +import builtins +import logging +import os +import shutil +import signal +import tempfile + +from omnigibson.controllers import REGISTERED_CONTROLLERS +from omnigibson.envs import Environment +from omnigibson.macros import gm +from omnigibson.objects import REGISTERED_OBJECTS +from omnigibson.robots import REGISTERED_ROBOTS +from omnigibson.scenes import REGISTERED_SCENES +from omnigibson.sensors import ALL_SENSOR_MODALITIES +from omnigibson.simulator import _launch_simulator as launch +from omnigibson.tasks import REGISTERED_TASKS + + +# Create logger +RESET = "\033[0m" + + +class LogFormatter(logging.Formatter): + COLORS = { + logging.DEBUG: "\033[32m", # green + logging.INFO: RESET, + logging.WARNING: "\033[33m", # yellow + logging.ERROR: "\033[31m", # red + logging.CRITICAL: "\033[31m" + "\033[1m", # bold red + } + + def format(self, record): + color = self.COLORS.get(record.levelno, RESET) + total_seconds = record.relativeCreated / 1000.0 + hours = int(total_seconds // 3600) + minutes = int((total_seconds % 3600) // 60) + seconds = total_seconds % 60 + # Format as HH:MM:SS.sss, with leading zeros + record.relativeCreated_hms = f"{hours:02d}:{minutes:02d}:{seconds:06.3f}" + return f"{color}{super().format(record)}{RESET}" + + +formatter = LogFormatter("[%(relativeCreated_hms)s] [%(levelname)s] [%(name)s] %(message)s") +_og_handler = logging.StreamHandler() +_og_handler.setFormatter(formatter) +_og_logger = logging.getLogger("omnigibson") +_og_logger.addHandler(_og_handler) +_og_logger.propagate = False # prevent Isaac Sim's Carbonite handler from double-printing +log = logging.getLogger(__name__) + +builtins.ISAAC_LAUNCHED_FROM_JUPYTER = ( + os.getenv("ISAAC_JUPYTER_KERNEL") is not None +) # We set this in the kernel.json file + +__version__ = "3.9.3" + +root_path = os.path.dirname(os.path.realpath(__file__)) + +# Store paths to example configs +# TODO: Move this elsewhere. +example_config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "configs") + +# Initialize global variables +app = None # (this is a singleton so it's okay that it's global) +sim = None # (this is a singleton so it's okay that it's global) + + +# Create and expose a temporary directory for any use cases. It will get destroyed upon omni +# shutdown by the shutdown function. +tempdir = tempfile.mkdtemp() + + +def clear( + gravity=None, + physics_dt=None, + rendering_dt=None, + sim_step_dt=None, + viewer_width=None, + viewer_height=None, + device=None, +): + """ + Clear the stage and then call launch again to make og.sim point to a new simulator instance + + Args: + gravity (None or float): gravity on z direction. + physics_dt (None or float): dt between physics steps. + If None, will use the current simulator value + rendering_dt (None or float): dt between rendering steps. Note: rendering means rendering a frame of the + current application and not only rendering a frame to the viewports/ cameras. So UI elements of + Isaac Sim will be refreshed with this dt as well if running non-headless. + If None, will use the current simulator value + sim_step_dt (None or float): dt between self.step() calls. This is the amount of simulation time that + passes every time step() is called. Note: This must be a multiple of @rendering_dt. If None, will + use the current simulator value + viewer_width (None or int): width of the camera image, in pixels + If None, will use the current simulator value + viewer_height (None or int): height of the camera image, in pixels + If None, will use the current simulator value + device (None or str): specifies the device to be used if running on the gpu with torch backend + If None, will use the current simulator value + + """ + global sim + + import omnigibson.lazy as lazy + + # First save important simulator settings + init_kwargs = dict( + gravity=sim.gravity if gravity is None else gravity, + physics_dt=sim.get_physics_dt() if physics_dt is None else physics_dt, + rendering_dt=sim.get_rendering_dt() if rendering_dt is None else rendering_dt, + sim_step_dt=sim.get_sim_step_dt() if sim_step_dt is None else sim_step_dt, + viewer_width=sim.viewer_width if viewer_width is None else viewer_width, + viewer_height=sim.viewer_height if viewer_height is None else viewer_height, + device=sim.device if device is None else device, + ) + + # Stop the viewport menubar USD watcher before teardown. This revokes the TfNotice + # listener so that prim deletions during _partial_clear() don't queue deferred + # callbacks that later fire on an invalid stage and corrupt CUDA/PhysX state. + usd_watcher = lazy.omni.kit.viewport.menubar.core.utils.usd_watch + usd_watcher.stop() + + # First let the simulator clear everything it owns. + sim._partial_clear() + + usd_watcher.start() + + # Then close the stage and remove pointers to the simulator object. + assert lazy.isaacsim.core.utils.stage.close_stage() + sim = None + lazy.isaacsim.core.api.SimulationContext.clear_instance() + + # Then relaunch the simulator. + launch(**init_kwargs) + + # Check that the device remains the same + assert ( + sim.device == init_kwargs["device"] + ), f"Device changed from {init_kwargs['device']} to {sim.device} after clear." + + +def cleanup(*args, **kwargs): + # TODO: Currently tempfile removal will fail due to CopyPrim command (for example, GranularSystem in dicing_apple example.) + try: + shutil.rmtree(tempdir) + except PermissionError: + log.info("Permission error when removing temp files. Ignoring") + from omnigibson.simulator import logo_small + + log.info(f"{'-' * 10} Shutting Down {logo_small()} {'-' * 10}") + + +def shutdown(due_to_signal=False): + if app is not None: + # If Isaac is running, we do the cleanup in its shutdown callback to avoid open handles. + # TODO: Automated cleanup in callback doesn't work for some reason. Need to investigate. + # Manually call cleanup for now. + cleanup() + if sim is not None: + sim._disable_usd_guard() + app.close() + else: + # Otherwise, we do the cleanup here. + cleanup() + + # If we're not shutting down due to a signal, we need to manually exit + if not due_to_signal: + exit(0) + + +def shutdown_handler(*args, **kwargs): + shutdown(due_to_signal=True) + return signal.default_int_handler(*args, **kwargs) + + +# Something somewhere disables the default SIGINT handler, so we need to re-enable it +signal.signal(signal.SIGINT, shutdown_handler) + +__all__ = [ + "ALL_SENSOR_MODALITIES", + "app", + "cleanup", + "clear", + "Environment", + "example_config_path", + "gm", + "launch", + "log", + "REGISTERED_CONTROLLERS", + "REGISTERED_OBJECTS", + "REGISTERED_ROBOTS", + "REGISTERED_SCENES", + "REGISTERED_TASKS", + "shutdown", + "sim", + "tempdir", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/action_primitives/action_primitive_set_base.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/action_primitives/action_primitive_set_base.py new file mode 100644 index 0000000000000000000000000000000000000000..424a911a28abe8731ae658a220d649de8eb7fbd1 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/action_primitives/action_primitive_set_base.py @@ -0,0 +1,89 @@ +import inspect +from abc import ABCMeta, abstractmethod +from enum import IntEnum +from typing import List + +from future.utils import with_metaclass + +REGISTERED_PRIMITIVE_SETS = {} + + +class ActionPrimitiveError(ValueError): + class Reason(IntEnum): + # A primitive could not be executed because a precondition was not satisfied, e.g. PLACE was called without an + # object currently in hand. + PRE_CONDITION_ERROR = 0 + + # A sampling error occurred: e.g. a position to place an object could not be found, or the robot could not + # find a pose near the object to navigate to. + SAMPLING_ERROR = 1 + + # The planning for a primitive failed possibly due to not being able to find a path. + PLANNING_ERROR = 2 + + # The planning for a primitive was successfully completed, but an error occurred during execution. + EXECUTION_ERROR = 3 + + # The execution of the primitive happened correctly, but while checking post-conditions, an error was found. + POST_CONDITION_ERROR = 4 + + def __init__(self, reason: Reason, message, metadata=None): + self.reason = reason + self.metadata = metadata if metadata is not None else {} + super().__init__(f"{reason.name}: {message}. Additional info: {metadata}") + + +class ActionPrimitiveErrorGroup(ValueError): + def __init__(self, exceptions: List[ActionPrimitiveError]) -> None: + self._exceptions = tuple(exceptions) + submessages = [f"Attempt {i}: {e}" for i, e in enumerate(exceptions)] + submessages = "\n\n".join(submessages) + message = "An error occurred during each attempt of this action.\n\n" + submessages + super().__init__(message) + + @property + def exceptions(self): + return self._exceptions + + +class BaseActionPrimitiveSet(with_metaclass(ABCMeta, object)): + def __init_subclass__(cls, **kwargs): + """ + Registers all subclasses as part of this registry. This is useful to decouple internal codebase from external + user additions. This way, users can add their custom primitive set by simply extending this class, + and it will automatically be registered internally. This allows users to then specify their primitive set + directly in string-from in e.g., their config files, without having to manually set the str-to-class mapping + in our code. + """ + if not inspect.isabstract(cls): + REGISTERED_PRIMITIVE_SETS[cls.__name__] = cls + + def __init__(self, env, robot): + self.env = env + self.robot = robot + + @abstractmethod + def get_action_space(self): + """Get the higher-level action space as an OpenAI Gym Space object.""" + pass + + @abstractmethod + def apply(self, action): + """ + Apply a primitive action. + + Given a higher-level action in the same format as the action space (e.g. as a number), + generates a sequence of lower level actions (or raise ActionPrimitiveError). The action + will get resolved and passed into apply_ref. + """ + pass + + @abstractmethod + def apply_ref(self, primitive, *args): + """ + Apply a primitive action by reference. + + Given a higher-level action from the corresponding action set enum and any necessary arguments, + generates a sequence of lower level actions (or raise ActionPrimitiveError) + """ + pass diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/action_primitives/curobo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/action_primitives/curobo.py new file mode 100644 index 0000000000000000000000000000000000000000..afd943b51566dd923a466d09765a82427ef10302 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/action_primitives/curobo.py @@ -0,0 +1,1006 @@ +import math +from enum import Enum +from typing import Dict, Any, Optional + +import torch as th # MUST come before importing omni!!! + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros +from omnigibson.prims.rigid_dynamic_prim import RigidDynamicPrim +from omnigibson.utils.constants import JointType +from omnigibson.utils.python_utils import multi_dim_linspace + + +# Gives 1 - 5% better speedup, according to https://github.com/NVlabs/curobo/discussions/245#discussioncomment-9265692 +th.backends.cudnn.benchmark = True +th.backends.cuda.matmul.allow_tf32 = True +th.backends.cudnn.allow_tf32 = True + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.HOLONOMIC_BASE_PRISMATIC_JOINT_LIMIT = 5.0 # meters +m.HOLONOMIC_BASE_REVOLUTE_JOINT_LIMIT = math.pi * 2 # radians + +m.DEFAULT_COLLISION_ACTIVATION_DISTANCE = 0.005 +m.DEFAULT_ATTACHED_OBJECT_SCALE = 0.8 + + +class CuRoboEmbodimentSelection(str, Enum): + BASE = "base" + ARM = "arm" + DEFAULT = "default" + + +def create_world_mesh_collision(tensor_args, obb_cache_size=10, mesh_cache_size=2048, max_distance=0.05): + """ + Creates a CuRobo WorldMeshCollision to use for collision checking + + Args: + tensor_args (TensorDeviceType): Tensor device information + obb_cache_size (int): Cache size for number of oriented bounding boxes supported in the collision world + mesh_cache_size (int): Cache size for number of meshes supported in the collision world + max_distance (float): maximum distance when checking collisions (see curobo source code) + + Returns: + MeshCollisionWorld: collision world used to check against for collisions + """ + world_cfg = lazy.curobo.geom.sdf.world.WorldCollisionConfig.load_from_dict( + dict( + cache={"obb": obb_cache_size, "mesh": mesh_cache_size}, + n_envs=1, + checker_type=lazy.curobo.geom.sdf.world.CollisionCheckerType.MESH, + max_distance=max_distance, + ), + tensor_args=tensor_args, + ) + + # To update, run world_coll_checker.load_collision_model(obstacles) + return lazy.curobo.geom.sdf.utils.create_collision_checker(world_cfg) + + +class CuRoboMotionGenerator: + """ + Class for motion generator using CuRobo backend + """ + + def __init__( + self, + robot, + robot_cfg_path=None, + robot_usd_path=None, + device="cuda:0", + motion_cfg_kwargs=None, + batch_size=2, + use_cuda_graph=True, + debug=False, + use_default_embodiment_only=False, + collision_activation_distance=m.DEFAULT_COLLISION_ACTIVATION_DISTANCE, + ): + """ + Args: + robot (BaseRobot): Robot for which to generate motion plans + robot_cfg_path (None or str): If specified, the path to the robot configuration to use. If None, will + try to use a pre-configured one directly from curobo based on the robot class of @robot + robot_usd_path (None or str): If specified, the path to the robot USD file to use. If None, will + try to use a pre-configured one directly from curobo based on the robot class of @robot + device (str): Which device to use for curobo + motion_cfg_kwargs (None or dict): If specified, keyward arguments to pass to + MotionGenConfig.load_from_robot_config(...) + batch_size (int): Size of batches for computing trajectories. This must be FIXED + use_cuda_graph (bool): Whether to use CUDA graph for motion generation or not + debug (bool): Whether to debug generation or not, setting this True will set use_cuda_graph to False implicitly + use_default_embodiment_only (bool): Whether to use only the default embodiment for the robot or not + collision_activation_distance (float): Distance threshold at which a collision with the world is detected. + Increasing this value will make the motion planner more conservative in its planning with respect + to the underlying sphere representation of the robot. Note that this does not affect self-collisions detection. + """ + # Store internal variables + self._tensor_args = lazy.curobo.types.base.TensorDeviceType(device=th.device(device)) + self.debug = debug + self.robot = robot + self.robot_joint_names = list(robot.joints.keys()) + self.batch_size = batch_size + + # Load robot config and usd paths and make sure paths point correctly + robot_cfg_path_dict = robot.curobo_path if robot_cfg_path is None else robot_cfg_path + if not isinstance(robot_cfg_path_dict, dict): + robot_cfg_path_dict = {CuRoboEmbodimentSelection.DEFAULT: robot_cfg_path_dict} + if use_default_embodiment_only: + robot_cfg_path_dict = { + CuRoboEmbodimentSelection.DEFAULT: robot_cfg_path_dict[CuRoboEmbodimentSelection.DEFAULT] + } + print("!" * 100) + # TODO [Wensi]: Check whether this is still true for future releases. + print( + """ + NOTE: Currently (v3.9.3), for cuda architecture 12.0 (e.g. RTX 50-series), using Default embodiment for Tiago or non-DEFAULT embodiment for R1Pro + will raise CUDA illegal memory access error during mg.warmup() due to cuRobo compatibility issues. + Therefore, we automatically exclude these incompatible embodiments when we detect such GPU is being used. + """ + ) + if th.cuda.get_device_capability(device) == (12, 0): + if robot.model == "tiago": + print("Detected you are using Tiago with cuda architecture 12.0 GPU: excluding non-DEFAULT embodiment.") + robot_cfg_path_dict = { + CuRoboEmbodimentSelection.DEFAULT: robot_cfg_path_dict[CuRoboEmbodimentSelection.DEFAULT] + } + elif robot.model == "r1pro": + print("Detected you are using R1Pro with cuda architecture 12.0 GPU: excluding DEFAULT embodiment.") + robot_cfg_path_dict = { + k: v for k, v in robot_cfg_path_dict.items() if k != CuRoboEmbodimentSelection.DEFAULT + } + print("!" * 100) + robot_usd_path = robot.usd_path if robot_usd_path is None else robot_usd_path + + # This will be shared across all MotionGen instances + world_coll_checker = create_world_mesh_collision( + self._tensor_args, obb_cache_size=10, mesh_cache_size=2048, max_distance=0.05 + ) + + usd_help = lazy.curobo.util.usd_helper.UsdHelper() + usd_help.stage = og.sim.stage + self.usd_help = usd_help + + self.mg = dict() + self.ee_link = dict() + self.additional_links = dict() + self.base_link = dict() + + # Grab mapping from robot joint name to index + reset_qpos = self.robot.reset_joint_pos + joint_idx_mapping = {joint.joint_name: i for i, joint in enumerate(self.robot.joints.values())} + for emb_sel, robot_cfg_path in robot_cfg_path_dict.items(): + content_path = lazy.curobo.types.file_path.ContentPath( + robot_config_absolute_path=robot_cfg_path, robot_usd_absolute_path=robot_usd_path + ) + robot_cfg_dict = lazy.curobo.cuda_robot_model.util.load_robot_yaml(content_path)["robot_cfg"] + robot_cfg_dict["kinematics"]["use_usd_kinematics"] = True + + # Automatically populate the locked joints and retract config from the robot values + for joint_name, lock_val in robot_cfg_dict["kinematics"]["lock_joints"].items(): + if lock_val is None: + joint_idx = joint_idx_mapping[joint_name] + robot_cfg_dict["kinematics"]["lock_joints"][joint_name] = reset_qpos[joint_idx] + if robot_cfg_dict["kinematics"]["cspace"]["retract_config"] is None: + robot_cfg_dict["kinematics"]["cspace"]["retract_config"] = [ + reset_qpos[joint_idx_mapping[joint_name]] + for joint_name in robot_cfg_dict["kinematics"]["cspace"]["joint_names"] + ] + + self.ee_link[emb_sel] = robot_cfg_dict["kinematics"]["ee_link"] + # RobotConfig.from_dict will append ee_link to link_names, so we make a copy here. + self.additional_links[emb_sel] = robot_cfg_dict["kinematics"]["link_names"].copy() + self.base_link[emb_sel] = robot_cfg_dict["kinematics"]["base_link"] + + robot_cfg_obj = lazy.curobo.types.robot.RobotConfig.from_dict(robot_cfg_dict, self._tensor_args) + + if robot.is_holonomic_base: + self.update_joint_limits(robot_cfg_obj, emb_sel) + + motion_kwargs = dict( + trajopt_tsteps=32, + collision_checker_type=lazy.curobo.geom.sdf.world.CollisionCheckerType.MESH, + use_cuda_graph=use_cuda_graph, + num_ik_seeds=128, + num_batch_ik_seeds=128, + num_batch_trajopt_seeds=1, + num_trajopt_noisy_seeds=1, + ik_opt_iters=100, + optimize_dt=True, + num_trajopt_seeds=4, + num_graph_seeds=4, + interpolation_dt=og.sim.get_sim_step_dt(), + collision_activation_distance=collision_activation_distance, + self_collision_check=True, + maximum_trajectory_dt=None, + fixed_iters_trajopt=True, + finetune_trajopt_iters=100, + finetune_dt_scale=1.05, + ) + if motion_cfg_kwargs is not None: + motion_kwargs.update(motion_cfg_kwargs) + + motion_gen_config = lazy.curobo.wrap.reacher.motion_gen.MotionGenConfig.load_from_robot_config( + robot_cfg=robot_cfg_obj, + world_model=None, + world_coll_checker=world_coll_checker, + tensor_args=self._tensor_args, + store_trajopt_debug=self.debug, + **motion_kwargs, + ) + self.mg[emb_sel] = lazy.curobo.wrap.reacher.motion_gen.MotionGen(motion_gen_config) + + for mg in self.mg.values(): + mg.warmup( + enable_graph=False, + warmup_js_trajopt=False, + batch=batch_size, + warmup_joint_delta=0.0, + ) + + # Make sure all cuda graphs have been warmed up + for solver in [mg.ik_solver, mg.trajopt_solver, mg.finetune_trajopt_solver]: + if solver.solver.use_cuda_graph_metrics: + assert solver.solver.safety_rollout._metrics_cuda_graph_init + if isinstance(solver, lazy.curobo.wrap.reacher.trajopt.TrajOptSolver): + assert solver.interpolate_rollout._metrics_cuda_graph_init + for opt in solver.solver.optimizers: + if opt.use_cuda_graph: + assert opt.cu_opt_init + + def update_joint_limits(self, robot_cfg_obj, emb_sel): + joint_limits = robot_cfg_obj.kinematics.kinematics_config.joint_limits + for joint_name in self.robot.base_joint_names: + if joint_name in joint_limits.joint_names: + joint_idx = joint_limits.joint_names.index(joint_name) + # Manually specify joint limits for the base_footprint_x/y/rz + if self.robot.joints[joint_name].joint_type == JointType.JOINT_PRISMATIC: + joint_limits.position[0][joint_idx] = -m.HOLONOMIC_BASE_PRISMATIC_JOINT_LIMIT + else: + # Needs to be -2pi to 2pi, instead of -pi to pi, otherwise the planning success rate is much lower + joint_limits.position[0][joint_idx] = -m.HOLONOMIC_BASE_REVOLUTE_JOINT_LIMIT + + joint_limits.position[1][joint_idx] = -joint_limits.position[0][joint_idx] + + def save_visualization(self, q, file_path, emb_sel=CuRoboEmbodimentSelection.DEFAULT): + # Update obstacles + self.update_obstacles() + + # Get robot collision spheres + cu_js = lazy.curobo.types.state.JointState( + position=self.tensor_args.to_device(q), + joint_names=self.robot_joint_names, + ).get_ordered_joint_state(self.mg[emb_sel].kinematics.joint_names) + sph = self.mg[emb_sel].kinematics.get_robot_as_spheres(cu_js.position) + robot_world = lazy.curobo.geom.types.WorldConfig(sphere=sph[0]) + + # Combine all obstacles into a single mesh + mesh_world = self.mg[emb_sel].world_model.get_mesh_world(merge_meshes=True) + robot_world.add_obstacle(mesh_world.mesh[0]) + robot_world.save_world_as_mesh(file_path) + + def update_obstacles(self, ignore_objects=None): + """ + Updates internal world collision cache representation based on sim state + + Args: + ignore_objects (None or list of DatasetObject): If specified, objects that should + be ignored when updating obstacles + """ + obstacles = {"cuboid": None, "sphere": None, "mesh": [], "cylinder": None, "capsule": None} + robot_transform = T.pose_inv(T.pose2mat(self.robot.root_link.get_position_orientation())) + + if og.sim.floor_plane is not None: + prim = og.sim.floor_plane.prim.GetChildren()[0] + m = lazy.curobo.util.usd_helper.get_mesh_attrs( + prim, cache=self.usd_help._xform_cache, transform=robot_transform.numpy() + ) + obstacles["mesh"].append(m) + + for obj in self.robot.scene.objects: + if obj == self.robot: + continue + if obj.visual_only: + continue + if ignore_objects is not None and obj in ignore_objects: + continue + for link in obj.links.values(): + for collision_mesh in link.collision_meshes.values(): + assert ( + collision_mesh.geom_type == "Mesh" + ), f"collision_mesh {collision_mesh.prim_path} is not a mesh, but a {collision_mesh.geom_type}" + obj_pose = T.pose2mat(collision_mesh.get_position_orientation()) + pose = robot_transform @ obj_pose + pos, orn = T.mat2pose(pose) + # xyzw -> wxyz + orn = orn[[3, 0, 1, 2]] + m = lazy.curobo.geom.types.Mesh( + name=collision_mesh.prim_path, + pose=th.cat([pos, orn]).tolist(), + vertices=collision_mesh.points.numpy(), + faces=collision_mesh.faces.numpy(), + scale=collision_mesh.get_world_scale().numpy(), + ) + obstacles["mesh"].append(m) + + world = lazy.curobo.geom.types.WorldConfig(**obstacles) + world = world.get_collision_check_world() + self.mg[CuRoboEmbodimentSelection.DEFAULT].update_world(world) + + def check_collisions( + self, + q, + initial_joint_pos=None, + self_collision_check=True, + skip_obstacle_update=False, + attached_obj=None, + attached_obj_scale=None, + ): + """ + Checks collisions between the sphere representation of the robot and the rest of the current scene + + Args: + q (th.tensor): (N, D)-shaped tensor, representing N-total different joint configurations to check + collisions against the world + initial_joint_pos (None or th.tensor): If specified, the initial joint positions to set the locked joints. + Default is the current joint positions of the robot + self_collision_check (bool): Whether to check self-collisions or not + skip_obstacle_update (bool): Whether to skip updating the obstacles in the world collision checker + attached_obj (None or Dict[str, USDObject]): If specified, a dictionary where the keys are the end-effector + link names and the values are the corresponding USDObject instances to attach to that link + attached_obj_scale (None or Dict[str, float]): If specified, a dictionary where the keys are the end-effector + link names and the values are the corresponding scale to apply to the attached object + + Returns: + th.tensor: (N,)-shaped tensor, where each value is True if in collision, else False + """ + # check_collisions only makes sense for the default embodiment where all the joints are actuated + emb_sel = CuRoboEmbodimentSelection.DEFAULT + + # Update obstacles + if not skip_obstacle_update: + self.update_obstacles() + + q_pos = self.robot.get_joint_positions() if initial_joint_pos is None else initial_joint_pos + q_pos = q_pos.unsqueeze(0) + cu_joint_state = lazy.curobo.types.state.JointState( + position=self._tensor_args.to_device(q_pos), + joint_names=self.robot_joint_names, + ) + + # Update the locked joints with the current joint positions + self.update_locked_joints(cu_joint_state, emb_sel) + + # Compute kinematics to get corresponding sphere representation + cu_js = lazy.curobo.types.state.JointState( + position=self.tensor_args.to_device(q), + joint_names=self.robot_joint_names, + ).get_ordered_joint_state(self.mg[emb_sel].kinematics.joint_names) + + # Attach objects if specified + attached_info = self._attach_objects_to_robot( + attached_obj=attached_obj, + attached_obj_scale=attached_obj_scale, + cu_js_batch=cu_js, + emb_sel=emb_sel, + ) + + robot_spheres = self.mg[emb_sel].compute_kinematics(cu_js).robot_spheres + # (N_samples, n_spheres, 4) --> (N_samples, 1, n_spheres, 4) + robot_spheres = robot_spheres.unsqueeze(dim=1) + + with th.no_grad(): + collision_dist = ( + self.mg[emb_sel].rollout_fn.primitive_collision_constraint.forward(robot_spheres).squeeze(1) + ) + collision_results = collision_dist > 0.0 + if self_collision_check: + self_collision_dist = ( + self.mg[emb_sel].rollout_fn.robot_self_collision_constraint.forward(robot_spheres).squeeze(1) + ) + self_collision_results = self_collision_dist > 0.0 + collision_results = collision_results | self_collision_results + + # Detach objects before returning + self._detach_objects_from_robot(attached_info, emb_sel) + + # Return results + return collision_results # shape (B,) + + def update_locked_joints(self, cu_joint_state, emb_sel): + """ + Updates the locked joints and fixed transforms for the given embodiment selection + This is needed to update curobo robot model about the current joint positions from Isaac. + + Args: + cu_joint_state (JointState): JointState object representing the current joint positions + emb_sel (CuRoboEmbodimentSelection): Which embodiment selection to use for updating locked joints + """ + kc = self.mg[emb_sel].kinematics.kinematics_config + # Update the lock joint state position + kc.lock_jointstate.position = cu_joint_state.get_ordered_joint_state(kc.lock_jointstate.joint_names).position[0] + # Update all the fixed transforms between the parent links and the child links of these joints + for i, joint_name in enumerate(kc.lock_jointstate.joint_names): + joint = self.robot.joints[joint_name] + joint_pos = kc.lock_jointstate.position[i] + child_link_name = joint.body1.split("/")[-1] + + # Compute the fixed transform between the parent link and the child link + # Note that we cannot directly query the parent and child link poses from OG + # because the cu_joint_state might not represent the current joint position in OG + + jf_to_cf_pose = joint.local_position_1, joint.local_orientation_1 + # Compute the transform from child frame to joint frame + cf_to_jf_pose = T.invert_pose_transform(*jf_to_cf_pose) + + # Compute the transform from the joint frame to the joint frame moved by the joint position + if joint.joint_type == JointType.JOINT_FIXED: + jf_to_jf_moved_pos = th.zeros(3) + jf_to_jf_moved_quat = th.tensor([0.0, 0.0, 0.0, 1.0]) + elif joint.joint_type == JointType.JOINT_PRISMATIC: + jf_to_jf_moved_pos = th.tensor([0.0, 0.0, 0.0]) + jf_to_jf_moved_pos[["X", "Y", "Z"].index(joint.axis)] = joint_pos + jf_to_jf_moved_quat = th.tensor([0.0, 0.0, 0.0, 1.0]) + elif joint.joint_type == JointType.JOINT_REVOLUTE: + jf_to_jf_moved_pos = th.zeros(3) + axis = th.zeros(3) + axis[["X", "Y", "Z"].index(joint.axis)] = 1.0 + jf_to_jf_moved_quat = T.axisangle2quat(axis * joint_pos.cpu()) + else: + raise NotImplementedError(f"Joint type {joint.joint_type} not supported") + + # Compute the transform from the child frame to the joint frame moved by the joint position + cf_to_jf_moved_pose = T.pose_transform(jf_to_jf_moved_pos, jf_to_jf_moved_quat, *cf_to_jf_pose) + + # Compute the transform from the joint frame moved by the joint position to the parent frame + jf_moved_to_pf_pose = joint.local_position_0, joint.local_orientation_0 + + # Compute the transform from the child frame to the parent frame + cf_to_pf_pose = T.pose_transform(*jf_moved_to_pf_pose, *cf_to_jf_moved_pose) + cf_to_pf_pose = T.pose2mat(cf_to_pf_pose) + + link_idx = kc.link_name_to_idx_map[child_link_name] + kc.fixed_transforms[link_idx] = cf_to_pf_pose + + def solve_ik_batch( + self, + start_state: Any, + goal_pose: Any, + plan_config: Any, + link_poses: Optional[Any] = None, + emb_sel=CuRoboEmbodimentSelection.DEFAULT, + ): + """Find IK solutions to reach a batch of goal poses from a batch of start joint states. + + Args: + start_state: Start joint states of the robot. When planning from a non-static state, + i.e, when velocity or acceleration is non-zero, set :attr:`MotionGen.optimize_dt` + to False. + goal_pose: Goal poses for the end-effector.ik_ + plan_config: Planning parameters for motion generation. + link_poses: Goal poses for each link in the robot when planning for multiple links. + + Returns: + IKResult: Result of IK solution. Check :attr:`IKResult.success` + attribute to check which indices of the batch were successful. + bool: Whether the IK solution was successful for the batch. + JointState: Joint state of the robot at the goal pose. + """ + solve_state = self.mg[emb_sel]._get_solve_state( + lazy.curobo.wrap.reacher.types.ReacherSolveType.BATCH, plan_config, goal_pose, start_state + ) + result = self.mg[emb_sel]._solve_ik_from_solve_state( + goal_pose, + solve_state, + start_state, + plan_config.use_nn_ik_seed, + plan_config.partial_ik_opt, + link_poses, + ) + # If any of the IK seeds is successful + success = result.success.any(dim=1) + # Set non-successful error to infinity + result.error[~result.success].fill_(float("inf")) + # Get the index of the minimum error + min_error_idx = result.error.argmin(dim=1) + # Get the joint state with the minimum error + joint_state = result.js_solution[range(result.js_solution.shape[0]), min_error_idx] + joint_state = [joint_state[i] for i in range(joint_state.shape[0])] + return result, success, joint_state + + def plan_batch( + self, + start_state: Any, + goal_pose: Any, + plan_config: Any, + link_poses: Optional[Any] = None, + emb_sel=CuRoboEmbodimentSelection.DEFAULT, + ): + """Plan a batch of trajectories from a batch of start joint states to a batch of goal poses. + + Args: + start_state: Start joint states of the robot. When planning from a non-static state, + i.e, when velocity or acceleration is non-zero, set :attr:`MotionGen.optimize_dt` + to False. + goal_pose: Goal poses for the end-effector. + plan_config: Planning parameters for motion generation. + link_poses: Goal poses for each link in the robot when planning for multiple links. + + Returns: + MotionGenResult: Result of IK solution. Check :attr:`MotionGenResult.success` + attribute to check which indices of the batch were successful. + bool: Whether the IK solution was successful for the batch. + JointState: Joint state of the robot at the goal pose. + """ + result = self.mg[emb_sel].plan_batch(start_state, goal_pose, plan_config, link_poses=link_poses) + success = result.success + if result.interpolated_plan is None: + joint_state = [None] * goal_pose.batch + else: + joint_state = result.get_paths() + + return result, success, joint_state + + def compute_trajectories( + self, + target_pos, + target_quat, + initial_joint_pos=None, + is_local=False, + max_attempts=5, + timeout=2.0, + ik_fail_return=5, + enable_finetune_trajopt=True, + finetune_attempts=1, + return_full_result=False, + success_ratio=None, + attached_obj=None, + attached_obj_scale=None, + motion_constraint=None, + skip_obstacle_update=False, + ik_only=False, + ik_world_collision_check=True, + emb_sel=CuRoboEmbodimentSelection.DEFAULT, + ): + """ + Computes the robot joint trajectory to reach the desired @target_pos and @target_quat + + Args: + target_pos (Dict[str, th.Tensor] or th.Tensor): The torch tensor shape is either (3,) or (N, 3) + where each entry is an individual (x,y,z) position to reach with the default end-effector link specified + @self.ee_link[emb_sel]. If a dictionary is given, the keys should be the end-effector links and + the values should be the corresponding (N, 3) tensors + target_quat (Dict[str, th.Tensor] or th.Tensor): The torch tensor shape is either (4,) or (N, 4) + where each entry is an individual (x,y,z,w) quaternion to reach with the default end-effector link specified + @self.ee_link[emb_sel]. If a dictionary is given, the keys should be the end-effector links and + the values should be the corresponding (N, 4) tensors + initial_joint_pos (None or th.Tensor): If specified, the initial joint positions to start the trajectory. + Default is the current joint positions of the robot + is_local (bool): Whether @target_pos and @target_quat are specified in the robot's local frame or the world + global frame + max_attempts (int): Maximum number of attempts for trying to compute a valid trajectory + timeout (float): Maximum time in seconds allowed to solve the motion generation problem + ik_fail_return (None or int): Number of IK attempts allowed before returning a failure. Set this to a + low value (5) to save compute time when an unreachable goal is given + enable_finetune_trajopt (bool): Whether to enable timing reparameterization for a smoother trajectory + finetune_attempts (int): Number of attempts to run finetuning trajectory optimization. Every attempt will + increase the `MotionGenPlanConfig.finetune_dt_scale` by `MotionGenPlanConfig.finetune_dt_decay` as a + path couldn't be found with the previous smaller dt + return_full_result (bool): Whether to return a list of raw MotionGenResult object(s) or a 2-tuple of + (success, results); the default is the latter + success_ratio (None or float): If set, specifies the fraction of successes necessary given self.batch_size. + If None, will automatically be the smallest ratio (1 / self.batch_size), i.e: any nonzero number of + successes + attached_obj (None or Dict[str, USDObject]): If specified, a dictionary where the keys are the end-effector + link names and the values are the corresponding USDObject instances to attach to that link + attached_obj_scale (None or Dict[str, float]): If specified, a dictionary where the keys are the end-effector + link names and the values are the corresponding scale to apply to the attached object + motion_constraint (None or List[float]): If specified, the motion constraint vector is a 6D vector controlling + end-effector movement (angular first, linear next): [qx, qy, qz, x, y, z]. Setting any component to 1.0 + locks that axis, forcing the planner to reach the target using only the remaining unlocked axes. + Details can be found here: https://curobo.org/advanced_examples/3_constrained_planning.html + skip_obstacle_update (bool): Whether to skip updating the obstacles in the world collision checker + ik_only (bool): Whether to only run the IK solver and not the trajectory optimization + ik_world_collision_check (bool): Whether to check for collisions in the world when running the IK solver for ik_only mode + emb_sel (CuRoboEmbodimentSelection): Which embodiment selection to use for computing trajectories + Returns: + 2-tuple or list of MotionGenResult: If @return_full_result is True, will return a list of raw MotionGenResult + object(s) computed from internal batch trajectory computations. If it is False, will return 2-tuple + (success, results), where success is a (N,)-shaped boolean tensor representing whether each requested + target pos / quat successfully generated a motion plan, and results is a (N,)-shaped array of + corresponding JointState objects. + """ + # Previously, this would silently fail so we explicitly check for out-of-range joint limits here + # This may be fixed in a recent version of CuRobo? See https://github.com/NVlabs/curobo/discussions/288 + # relevant_joint_positions_normalized = ( + # lazy.curobo.types.state.JointState( + # position=self.tensor_args.to_device(self.robot.get_joint_positions(normalized=True)), + # joint_names=self.robot_joint_names, + # ) + # .get_ordered_joint_state(self.mg[emb_sel].kinematics.joint_names) + # .position + # ) + + # if not th.all(th.abs(relevant_joint_positions_normalized) < 0.99): + # print("Robot is near joint limits! No trajectory will be computed") + # return None, None if not return_full_result else None + + if not skip_obstacle_update: + self.update_obstacles() + + # If target_pos and target_quat are torch tensors, it's assumed that they correspond to the default ee_link + if isinstance(target_pos, th.Tensor): + target_pos = {self.ee_link[emb_sel]: target_pos} + if isinstance(target_quat, th.Tensor): + target_quat = {self.ee_link[emb_sel]: target_quat} + + assert target_pos.keys() == target_quat.keys(), "Expected target_pos and target_quat to have the same keys!" + + # Make sure tensor shapes are (N, 3) and (N, 4) + target_pos = {k: v if len(v.shape) == 2 else v.unsqueeze(0) for k, v in target_pos.items()} + target_quat = {k: v if len(v.shape) == 2 else v.unsqueeze(0) for k, v in target_quat.items()} + + for link_name in target_pos.keys(): + target_pos_link = target_pos[link_name] + target_quat_link = target_quat[link_name] + if not is_local: + # Convert target pose to base link *in the eyes of curobo*. + # For stationary arms (e.g. Franka), it is @robot.root_link / @robot.base_footprint_link_name ("base_link") + # For holonomic robots (e.g. Tiago, R1), it is @robot.root_link ("base_footprint_x"), not @robot.base_footprint_link_name ("base_link") + curobo_base_link_name = self.base_link[emb_sel] + robot_pos, robot_quat = self.robot.links[curobo_base_link_name].get_position_orientation() + target_pose = th.zeros((target_pos_link.shape[0], 4, 4)) + target_pose[:, 3, 3] = 1.0 + target_pose[:, :3, :3] = T.quat2mat(target_quat_link) + target_pose[:, :3, 3] = target_pos_link + inv_robot_pose = T.pose_inv(T.pose2mat((robot_pos, robot_quat))) + target_pose = inv_robot_pose.view(1, 4, 4) @ target_pose + target_pos_link = target_pose[:, :3, 3] + target_quat_link = T.mat2quat(target_pose[:, :3, :3]) + + # Map xyzw -> wxyz quat + target_quat_link = target_quat_link[:, [3, 0, 1, 2]] + + # Make sure tensors are on device and contiguous + target_pos_link = self._tensor_args.to_device(target_pos_link).contiguous() + target_quat_link = self._tensor_args.to_device(target_quat_link).contiguous() + + target_pos[link_name] = target_pos_link + target_quat[link_name] = target_quat_link + + # Define the plan config + plan_cfg = lazy.curobo.wrap.reacher.motion_gen.MotionGenPlanConfig( + enable_graph=False, + max_attempts=max_attempts, + timeout=timeout, + enable_graph_attempt=None, + ik_fail_return=ik_fail_return, + enable_finetune_trajopt=enable_finetune_trajopt, + finetune_attempts=finetune_attempts, + success_ratio=1.0 / self.batch_size if success_ratio is None else success_ratio, + ) + + # Add the pose cost metric + if self.ee_link[emb_sel] in target_pos and motion_constraint is not None: + plan_cfg.pose_cost_metric = lazy.curobo.wrap.reacher.motion_gen.PoseCostMetric( + hold_partial_pose=True, hold_vec_weight=self._tensor_args.to_device(motion_constraint) + ) + + # Construct initial state + if initial_joint_pos is None: + q_pos = th.stack([self.robot.get_joint_positions()] * self.batch_size, axis=0) + q_vel = th.stack([self.robot.get_joint_velocities()] * self.batch_size, axis=0) + q_eff = th.stack([self.robot.get_joint_efforts()] * self.batch_size, axis=0) + else: + q_pos = th.stack([initial_joint_pos] * self.batch_size, axis=0) + q_vel = th.zeros_like(q_pos) + q_eff = th.zeros_like(q_pos) + + cu_joint_state = lazy.curobo.types.state.JointState( + position=self._tensor_args.to_device(q_pos), + # TODO: Ideally these should be nonzero, but curobo fails to compute a solution if so + # See this note from https://curobo.org/get_started/2b_isaacsim_examples.html + # Motion generation only generates motions when the robot is static. + # cuRobo has an experimental mode to optimize from non-static states. + # You can try this by passing --reactive to motion_gen_reacher.py. + # This mode will have lower success than the static mode as now the optimization + # has to account for the robot’s current velocity and acceleration. + # The weights have also not been tuned for reactive mode. + velocity=self._tensor_args.to_device(q_vel) * 0.0, + acceleration=self._tensor_args.to_device(q_eff) * 0.0, + jerk=self._tensor_args.to_device(q_eff) * 0.0, + joint_names=self.robot_joint_names, + ) + + # Update the locked joints with the current joint positions + self.update_locked_joints(cu_joint_state, emb_sel) + + cu_js_batch = cu_joint_state.get_ordered_joint_state(self.mg[emb_sel].kinematics.joint_names) + + # Attach object to robot if requested + attached_info = self._attach_objects_to_robot( + attached_obj=attached_obj, + attached_obj_scale=attached_obj_scale, + cu_js_batch=cu_js_batch, + emb_sel=emb_sel, + ) + + all_rollout_fns = [ + fn + for fn in self.mg[emb_sel].get_all_rollout_instances() + if isinstance(fn, lazy.curobo.rollout.arm_reacher.ArmReacher) + ] + + # Enable/disable costs based on whether the end-effector is in the target position + for rollout_fn in all_rollout_fns: + ( + rollout_fn.goal_cost.enable_cost() + if self.ee_link[emb_sel] in target_pos + else rollout_fn.goal_cost.disable_cost() + ) + ( + rollout_fn.pose_convergence.enable_cost() + if self.ee_link[emb_sel] in target_pos + else rollout_fn.pose_convergence.disable_cost() + ) + for additional_link in self.additional_links[emb_sel]: + ( + rollout_fn._link_pose_costs[additional_link].enable_cost() + if additional_link in target_pos + else rollout_fn._link_pose_costs[additional_link].disable_cost() + ) + ( + rollout_fn._link_pose_convergence[additional_link].enable_cost() + if additional_link in target_pos + else rollout_fn._link_pose_convergence[additional_link].disable_cost() + ) + + if ik_only: + for rollout_fn in self.mg[emb_sel].ik_solver.get_all_rollout_instances(): + ( + rollout_fn.primitive_collision_cost.enable_cost() + if ik_world_collision_check + else rollout_fn.primitive_collision_cost.disable_cost() + ) + ( + rollout_fn.primitive_collision_constraint.enable_cost() + if ik_world_collision_check + else rollout_fn.primitive_collision_constraint.disable_cost() + ) + + # Determine how many internal batches we need to run based on submitted size + num_targets = next(iter(target_pos.values())).shape[0] + remainder = num_targets % self.batch_size + n_batches = math.ceil(num_targets / self.batch_size) + + # If ee_link is not in target_pos, add trivial target poses to avoid errors + if self.ee_link[emb_sel] not in target_pos: + target_pos[self.ee_link[emb_sel]] = self._tensor_args.to_device(th.zeros((num_targets, 3))) + target_quat[self.ee_link[emb_sel]] = self._tensor_args.to_device(th.zeros((num_targets, 4))) + target_quat[self.ee_link[emb_sel]][..., 0] = 1.0 + + # Run internal batched calls + results, successes, paths = [], self._tensor_args.to_device(th.tensor([], dtype=th.bool)), [] + for i in range(n_batches): + # We're using a remainder if we're on the final batch and our remainder is nonzero + using_remainder = (i == n_batches - 1) and remainder > 0 + offset_idx = self.batch_size * i + end_idx = remainder if using_remainder else self.batch_size + + ik_goal_batch_by_link = dict() + for link_name in target_pos.keys(): + target_pos_link = target_pos[link_name] + target_quat_link = target_quat[link_name] + + batch_target_pos = target_pos_link[offset_idx : offset_idx + end_idx] + batch_target_quat = target_quat_link[offset_idx : offset_idx + end_idx] + + # Pad the goal if we're in our final batch + if using_remainder: + new_batch_target_pos = self._tensor_args.to_device(th.zeros((self.batch_size, 3))) + new_batch_target_pos[:end_idx] = batch_target_pos + new_batch_target_pos[end_idx:] = batch_target_pos[-1] + batch_target_pos = new_batch_target_pos + new_batch_target_quat = self._tensor_args.to_device(th.zeros((self.batch_size, 4))) + new_batch_target_quat[:end_idx] = batch_target_quat + new_batch_target_quat[end_idx:] = batch_target_quat[-1] + batch_target_quat = new_batch_target_quat + + # Create IK goal + ik_goal_batch = lazy.curobo.types.math.Pose( + position=batch_target_pos, + quaternion=batch_target_quat, + name=link_name, + ) + + ik_goal_batch_by_link[link_name] = ik_goal_batch + + # Run batched planning + if self.debug: + self.mg[emb_sel].store_debug_in_result = True + + # Pop the main ee_link goal + main_ik_goal_batch = ik_goal_batch_by_link.pop(self.ee_link[emb_sel]) + + # If no other goals (e.g. no second end-effector), set to None + if len(ik_goal_batch_by_link) == 0: + ik_goal_batch_by_link = None + + plan_fn = self.plan_batch if not ik_only else self.solve_ik_batch + result, success, joint_state = plan_fn( + cu_js_batch, main_ik_goal_batch, plan_cfg, link_poses=ik_goal_batch_by_link, emb_sel=emb_sel + ) + if self.debug: + breakpoint() + + # Append results + results.append(result) + successes = th.concatenate([successes, success[:end_idx]]) + paths += joint_state[:end_idx] + + # Detach attached object if it was attached + self._detach_objects_from_robot(attached_info, emb_sel) + + if return_full_result: + return results + else: + return successes, paths + + def path_to_joint_trajectory(self, path, get_full_js=True, emb_sel=CuRoboEmbodimentSelection.DEFAULT): + """ + Converts raw path from motion generator into joint trajectory sequence + + Args: + path (JointState): Joint state path to convert into joint trajectory + get_full_js (bool): Whether to get the full joint state + emb_sel (CuRoboEmbodimentSelection): Which embodiment to use for the robot + + Returns: + torch.tensor: (T, D) tensor representing the interpolated joint trajectory + to reach the desired @target_pos, @target_quat configuration, where T is the number of interpolated + steps and D is the number of robot joints. + """ + cmd_plan = self.mg[emb_sel].get_full_js(path) if get_full_js else path + return cmd_plan.get_ordered_joint_state(self.robot_joint_names).position + + def add_linearly_interpolated_waypoints(self, traj: th.Tensor, max_inter_dist=0.01): + """ + Adds waypoints to the joint trajectory so that the joint position distance + between each pairs of neighboring waypoints is less than @max_inter_dist + + Args: + traj: (T, D) tensor representing the joint trajectory + max_inter_dist (float): Maximum joint position distance between two neighboring waypoints + + Returns: + torch.tensor: (T', D) tensor representing the interpolated joint trajectory + """ + assert len(traj) > 1, "Plan must have at least 2 waypoints to interpolate" + interpolated_plan = [] + for i in range(len(traj) - 1): + # Calculate maximum difference across all dimensions + max_diff = (traj[i + 1] - traj[i]).abs().max() + num_intervals = math.ceil(max_diff.item() / max_inter_dist) + interpolated_plan += multi_dim_linspace(traj[i], traj[i + 1], num_intervals, endpoint=False) + + interpolated_plan.append(traj[-1]) + return th.stack(interpolated_plan) + + def path_to_eef_trajectory( + self, path, return_axisangle=False, emb_sel=CuRoboEmbodimentSelection.DEFAULT + ) -> Dict[str, th.Tensor]: + """ + Converts raw path from motion generator into end-effector trajectory sequence in the robot frame. + This trajectory sequence can be executed by an IKController, although there is no guaranteee that + the controller will output the same joint trajectory as the one computed by cuRobo. + + Args: + path (JointState): Joint state path to convert into joint trajectory + return_axisangle (bool): Whether to return the interpolated orientations in quaternion or axis-angle representation + emb_sel (CuRoboEmbodimentSelection): Which embodiment to use for the robot + + Returns: + Dict[str, torch.Tensor]: Mapping eef link names to (T, [6, 7])-shaped array where each entry is is the (x,y,z) position + and (x,y,z,w) quaternion (if @return_axisangle is False) or (ax, ay, az) axis-angle orientation, specified in the robot frame. + """ + # If the base-only embodiment is selected, the eef links stay the same, return the current eef poses in the robot frame + if emb_sel == CuRoboEmbodimentSelection.BASE: + link_poses = dict() + for arm_name in self.robot.arm_names: + link_name = self.robot.eef_link_names[arm_name] + position, orientation = self.robot.get_relative_eef_pose(arm_name) + if return_axisangle: + orientation = T.quat2axisangle(orientation) + link_poses[link_name] = th.cat([position, orientation], dim=-1) + return link_poses + + cmd_plan = self.mg[emb_sel].get_full_js(path) + robot_state = self.mg[emb_sel].kinematics.compute_kinematics(path) + + link_poses = dict() + + for link_name, poses in robot_state.link_poses.items(): + position = poses.position + # wxyz -> xyzw + orientation = poses.quaternion[:, [1, 2, 3, 0]] + + # If the robot is holonomic, we need to transform the poses to the base link frame + if self.robot.is_holonomic_base: + base_link_position = th.zeros_like(position) + base_link_position[:, 0] = cmd_plan.position[:, cmd_plan.joint_names.index("base_footprint_x_joint")] + base_link_position[:, 1] = cmd_plan.position[:, cmd_plan.joint_names.index("base_footprint_y_joint")] + base_link_euler = th.zeros_like(position) + base_link_euler[:, 2] = cmd_plan.position[:, cmd_plan.joint_names.index("base_footprint_rz_joint")] + base_link_orientation = T.euler2quat(base_link_euler) + position, orientation = T.relative_pose_transform( + position, orientation, base_link_position, base_link_orientation + ) + + if return_axisangle: + orientation = T.quat2axisangle(orientation) + link_poses[link_name] = th.cat([position, orientation], dim=-1) + + return link_poses + + @property + def tensor_args(self): + """ + Returns: + TensorDeviceType: tensor arguments used by this CuRobo instance + """ + return self._tensor_args + + def _attach_objects_to_robot( + self, + attached_obj, + attached_obj_scale, + cu_js_batch, + emb_sel, + ): + """ + Helper function to attach objects to the robot. + + Args: + attached_obj (None or Dict[str, USDObject]): Dictionary mapping end-effector + link names to corresponding USDObject instances + attached_obj_scale (None or Dict[str, float]): Dictionary mapping end-effector + link names to corresponding scale values + cu_js_batch (JointState): CuRobo joint state object ordered according to kinematics + emb_sel (CuRoboEmbodimentSelection): Which embodiment selection to use + + Returns: + list: List of attached object information for detachment + """ + if attached_obj is None: + return [] + + attached_info = [] + for ee_link_name, obj in attached_obj.items(): + assert isinstance(obj, RigidDynamicPrim), "attached_object should be a RigidDynamicPrim object" + obj_paths = [geom.prim_path for geom in obj.collision_meshes.values()] + assert len(obj_paths) <= 32, f"Expected obj_paths to be at most 32, got: {len(obj_paths)}" + + position, quaternion = self.robot.links[ee_link_name].get_position_orientation() + # xyzw to wxyz + quaternion = quaternion[[3, 0, 1, 2]] + ee_pose = lazy.curobo.types.math.Pose(position=position, quaternion=quaternion).to(self._tensor_args) + + scale = m.DEFAULT_ATTACHED_OBJECT_SCALE if attached_obj_scale is None else attached_obj_scale[ee_link_name] + + self.mg[emb_sel].attach_objects_to_robot( + joint_state=cu_js_batch, + object_names=obj_paths, + ee_pose=ee_pose, + link_name=self.robot.curobo_attached_object_link_names[ee_link_name], + scale=scale, + pitch_scale=1.0, + merge_meshes=True, + ) + + attached_info.append( + {"obj_paths": obj_paths, "link_name": self.robot.curobo_attached_object_link_names[ee_link_name]} + ) + + return attached_info + + def _detach_objects_from_robot( + self, + attached_info, + emb_sel, + ): + """ + Helper function to detach previously attached objects from the robot. + + Args: + attached_info (list): List of dictionaries containing object paths and link names + returned by _attach_objects_to_robot + emb_sel (CuRoboEmbodimentSelection): Which embodiment selection to use + """ + for info in attached_info: + self.mg[emb_sel].detach_object_from_robot( + object_names=info["obj_paths"], + link_name=info["link_name"], + ) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/action_primitives/starter_semantic_action_primitives.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/action_primitives/starter_semantic_action_primitives.py new file mode 100644 index 0000000000000000000000000000000000000000..28f7d2fd6cccbb0aa33061618709a63bfeeb9595 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/action_primitives/starter_semantic_action_primitives.py @@ -0,0 +1,2093 @@ +""" +WARNING! +The StarterSemanticActionPrimitive is a work-in-progress and is only provided as an example. +It currently only works with Tiago and R1 with their JointControllers set to absolute position mode. +See provided tiago_primitives.yaml config file for an example. See examples/action_primitives for +runnable examples. +""" + +import inspect +import math +import random +from typing import Any + +import cv2 +import gymnasium as gym +import torch as th +from aenum import IntEnum, auto +from matplotlib import pyplot as plt + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson import object_states +from omnigibson.action_primitives.action_primitive_set_base import ( + ActionPrimitiveError, + ActionPrimitiveErrorGroup, + BaseActionPrimitiveSet, +) +from omnigibson.action_primitives.curobo import ( + CuRoboEmbodimentSelection, + CuRoboMotionGenerator, +) +from omnigibson.controllers import ( + ControllerView, + InverseKinematicsController, + HolonomicBaseJointController, + DifferentialDriveController, +) +from omnigibson.macros import create_module_macros +from omnigibson.macros import macros +from omnigibson.objects.usd_object import USDObject +from omnigibson.robots import Robot +from omnigibson.tasks.behavior_task import BehaviorTask +from omnigibson.utils.geometry_utils import wrap_angle +from omnigibson.utils.grasping_planning_utils import get_grasp_poses_for_object_sticky, get_grasp_position_for_open +from omnigibson.utils.motion_planning_utils import detect_robot_collision_in_sim +from omnigibson.utils.object_state_utils import sample_cuboid_for_predicate +from omnigibson.utils.python_utils import multi_dim_linspace +from omnigibson.utils.ui_utils import create_module_logger + +m = create_module_macros(module_path=__file__) + +m.DEFAULT_COLLISION_ACTIVATION_DISTANCE = 0.02 +m.MAX_PLANNING_ATTEMPTS = 100 +m.MAX_IK_FAILURES_BEFORE_RETURN = 50 + +m.MAX_STEPS_FOR_SETTLING = 500 + +m.MAX_STEPS_FOR_JOINT_MOTION = 10 + +m.MAX_CARTESIAN_HAND_STEP = 0.002 +m.MAX_STEPS_FOR_HAND_MOVE_JOINT = 500 +m.MAX_STEPS_FOR_HAND_MOVE_IK = 1000 +m.MAX_STEPS_FOR_GRASP_OR_RELEASE = 250 +m.MAX_STEPS_FOR_WAYPOINT_NAVIGATION = 500 +m.MAX_ATTEMPTS_FOR_OPEN_CLOSE = 20 + +m.MAX_ATTEMPTS_FOR_SAMPLING_POSE_WITH_OBJECT_AND_PREDICATE = 20 +m.MAX_ATTEMPTS_FOR_SAMPLING_POSE_NEAR_OBJECT = 200 +m.MAX_ATTEMPTS_FOR_SAMPLING_POSE_FOR_CORRECT_ROOM = 20 +m.MAX_ATTEMPTS_FOR_SAMPLING_POSE_IN_ROOM = 60 +m.MAX_ATTEMPTS_FOR_SAMPLING_PLACE_POSE = 50 +m.PREDICATE_SAMPLING_Z_OFFSET = 0.02 +m.BASE_POSE_SAMPLING_LOWER_BOUND = 0.0 +m.BASE_POSE_SAMPLING_UPPER_BOUND = 1.5 + +m.GRASP_APPROACH_DISTANCE = 0.01 +m.OPEN_GRASP_APPROACH_DISTANCE = 0.4 + +m.HAND_DIST_THRESHOLD = 0.002 +m.DEFAULT_DIST_THRESHOLD = 0.005 +m.DEFAULT_ANGLE_THRESHOLD = 0.03 +m.LOW_PRECISION_DIST_THRESHOLD = 0.1 +m.LOW_PRECISION_ANGLE_THRESHOLD = 0.2 + +m.JOINT_POS_DIFF_THRESHOLD = 0.005 +m.LOW_PRECISION_JOINT_POS_DIFF_THRESHOLD = 0.05 +m.JOINT_CONTROL_MIN_ACTION = 0.0 +m.MAX_ALLOWED_JOINT_ERROR_FOR_LINEAR_MOTION = math.radians(45) +m.TIME_BEFORE_JOINT_STUCK_CHECK = 1.0 + +log = create_module_logger(module_name=__name__) + + +def indented_print(msg, *args, **kwargs): + print(" " * len(inspect.stack()) + str(msg), *args, **kwargs) + + +class StarterSemanticActionPrimitiveSet(IntEnum): + _init_ = "value __doc__" + GRASP = auto(), "Grasp an object" + PLACE_ON_TOP = auto(), "Place the currently grasped object on top of another object" + PLACE_INSIDE = auto(), "Place the currently grasped object inside another object" + OPEN = auto(), "Open an object" + CLOSE = auto(), "Close an object" + NAVIGATE_TO = auto(), "Navigate to an object (mostly for debugging purposes - other primitives also navigate first)" + RELEASE = ( + auto(), + "Release an object, letting it fall to the ground. You can then grasp it again, as a way of reorienting your grasp of the object.", + ) + TOGGLE_ON = auto(), "Toggle an object on" + TOGGLE_OFF = auto(), "Toggle an object off" + + +# (TODO) execution failure: overwrite_head_action might move the head that causes self-collision with curobo-generated motion plans (at the time of curobo planning, it assumes the head doesn't move). +# (TODO) R1 improvement: create a new CuRoboEmbodimentSelection type that only allows for arm movement, and not torso movement. + + +class StarterSemanticActionPrimitives(BaseActionPrimitiveSet): + def __init__( + self, + env, + robot, + enable_head_tracking=True, + always_track_eef=False, + task_relevant_objects_only=False, + curobo_batch_size=3, + debug_visual_marker=None, + skip_curobo_initilization=False, + ): + """ + Initializes a StarterSemanticActionPrimitives generator. + + Args: + env (Environment): The environment that the primitives will run on. + robot (BaseRobot): The robot that the primitives will run on. + enable_head_tracking (bool): Whether to enable head tracking. Defaults to True. + always_track_eef (bool, optional): Whether to always track the end effector, as opposed + to switching between target object and end effector based on context. Defaults to False. + task_relevant_objects_only (bool): Whether to only consider objects relevant to the task + when computing the action space. Defaults to False. + curobo_batch_size (int): The batch size for curobo motion planning and collision checking. Defaults to 3. + debug_visual_marker (PrimitiveObject): The object to use for debug visual markers. Defaults to None. + skip_curobo_initilization (bool): Whether to skip curobo initialization. Defaults to False. + """ + log.warning( + "The StarterSemanticActionPrimitive is a work-in-progress and is only provided as an example. " + "It currently only works with Tiago and R1 with their HolonomicBaseJointController/JointControllers set to absolute position mode." + ) + super().__init__(env, robot) + # Resolve which env this primitive controller is bound to, based on the robot's scene. + # Used by get_action_space() to pick the right per-env BehaviorTask object_scope. + self._env_idx = next(i for i, s in enumerate(env.scenes) if s is robot.scene) + self.controller_functions = { + StarterSemanticActionPrimitiveSet.GRASP: self._grasp, + StarterSemanticActionPrimitiveSet.PLACE_ON_TOP: self._place_on_top, + StarterSemanticActionPrimitiveSet.PLACE_INSIDE: self._place_inside, + StarterSemanticActionPrimitiveSet.OPEN: self._open, + StarterSemanticActionPrimitiveSet.CLOSE: self._close, + StarterSemanticActionPrimitiveSet.NAVIGATE_TO: self._navigate_to_obj, + StarterSemanticActionPrimitiveSet.RELEASE: self._execute_release, + StarterSemanticActionPrimitiveSet.TOGGLE_ON: self._toggle_on, + StarterSemanticActionPrimitiveSet.TOGGLE_OFF: self._toggle_off, + } + self._motion_generator = ( + None + if skip_curobo_initilization + else CuRoboMotionGenerator( + robot=self.robot, + batch_size=curobo_batch_size, + collision_activation_distance=m.DEFAULT_COLLISION_ACTIVATION_DISTANCE, + ) + ) + + self._task_relevant_objects_only = task_relevant_objects_only + + self._enable_head_tracking = enable_head_tracking + self._always_track_eef = always_track_eef + self._tracking_object = None + + # Store the current position of the arm as the arm target + self._arm_targets = {} + self._reset_eef_pose = {} + if self.robot.is_manipulation: + # Batched read of joint positions for all controllers + joint_positions = self.robot.get_joint_positions() + for arm_name in self.robot.arm_names: + arm = f"arm_{arm_name}" + arm_group_key, _ = self.robot.controllers[arm] + if ControllerView.is_controller_type(arm_group_key, InverseKinematicsController): + # Use the current relative end-effector pose as the IK target + pos_relative_np, quat_relative_np = self.robot.get_relative_eef_pose(arm_name) + pos_relative = pos_relative_np + quat_relative = quat_relative_np + quat_relative_axis_angle = T.quat2axisangle(quat_relative) + self._arm_targets[arm] = (pos_relative, quat_relative_axis_angle) + else: + # Use the current joint positions for this arm as the target + arm_target = joint_positions[ControllerView.get_dof_idx(arm_group_key)] + self._arm_targets[arm] = arm_target + + self._reset_eef_pose[arm_name] = self.robot.get_relative_eef_pose(arm_name) + + self._curobo_batch_size = curobo_batch_size + self.debug_visual_marker = debug_visual_marker + + # Action primitives uses assisted grasping; we ignore delayed AG here + with macros.unlocked(): + macros.robots.manipulation_robot.GRASP_WINDOW = 0.0 + + @property + def arm(self): + assert self.robot.is_manipulation, "Cannot use arm for non-manipulation robot" + return self.robot.default_arm + + def _postprocess_action(self, action): + """Postprocesses action by applying head tracking.""" + if self._enable_head_tracking: + action = self._overwrite_head_action(action) + return action + + def get_action_space(self): + # TODO: Figure out how to implement what happens when the set of objects in scene changes. + if self._task_relevant_objects_only: + assert isinstance( + self.env.task, BehaviorTask + ), "Activity relevant objects can only be used for BEHAVIOR tasks" + self.addressable_objects = sorted( + set(self.env.task.object_scopes[self._env_idx].values()), key=lambda obj: obj.name + ) + else: + self.addressable_objects = sorted(set(self.env.scene.objects_by_name.values()), key=lambda obj: obj.name) + + # Filter out the robots. + self.addressable_objects = [obj for obj in self.addressable_objects if not isinstance(obj, Robot)] + + self.num_objects = len(self.addressable_objects) + return gym.spaces.Tuple( + [gym.spaces.Discrete(self.num_objects), gym.spaces.Discrete(len(StarterSemanticActionPrimitiveSet))] + ) + + def get_action_from_primitive_and_object(self, primitive: StarterSemanticActionPrimitiveSet, obj: USDObject): + assert obj in self.addressable_objects + primitive_int = int(primitive) + return primitive_int, self.addressable_objects.index(obj) + + def _get_obj_in_hand(self): + """ + Get object in the robot's hand + + Returns: + StatefulObject or None: Object if robot is holding something or None if it is not + """ + obj_in_hand = self.robot._ag_obj_in_hand[self.arm] # TODO(MP): Expose this interface. + return obj_in_hand + + def apply(self, action): + # Decompose the tuple + action_idx, obj_idx = action + + # Find the target object. + target_obj = self.addressable_objects[obj_idx] + + # Find the appropriate action generator. + action = StarterSemanticActionPrimitiveSet(action_idx) + return self.apply_ref(action, target_obj) + + def apply_ref(self, primitive, *args: Any, attempts=5): + """ + Yields action for robot to execute the primitive with the given arguments. + + Args: + primitive (StarterSemanticActionPrimitiveSet): Primitive to execute + args: Arguments for the primitive + attempts (int): Number of attempts to make before raising an error + + Yields: + th.tensor or None: Action array for one step for the robot to execute the primitve or None if primitive completed + + Raises: + ActionPrimitiveError: If primitive fails to execute + """ + ctrl = self.controller_functions[primitive] + + errors = [] + for _ in range(attempts): + # Attempt + success = False + try: + yield from ctrl(*args) + success = True + except ActionPrimitiveError as e: + errors.append(e) + + try: + # If we're not holding anything, release the hand so it doesn't stick to anything else. + if not self._get_obj_in_hand(): + yield from self._execute_release() + except ActionPrimitiveError: + pass + + try: + # Make sure we retract the arms after every step + yield from self._reset_robot() + except ActionPrimitiveError: + pass + + try: + # Settle before returning. + yield from self._settle_robot() + except ActionPrimitiveError: + pass + + # Stop on success + if success: + return + + raise ActionPrimitiveErrorGroup(errors) + + # # One-attempt debug version + # ctrl = self.controller_functions[primitive] + # yield from ctrl(*args) + # if not self._get_obj_in_hand(): + # yield from self._execute_release() + # yield from self._reset_robot() + # yield from self._settle_robot() + + def _open(self, obj): + yield from self._open_or_close(obj, True) + + def _close(self, obj): + yield from self._open_or_close(obj, False) + + def _open_or_close(self, obj, should_open): + raise NotImplementedError("Open/close is not implemented correctly yet.") + + # Update the tracking to track the eef. + self._tracking_object = self.robot + + if self._get_obj_in_hand(): + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "Cannot open or close an object while holding an object", + {"object in hand": self._get_obj_in_hand().name}, + ) + + # Open the hand first + yield from self._execute_release() + + for _ in range(m.MAX_ATTEMPTS_FOR_OPEN_CLOSE): + try: + # TODO: This needs to be fixed. Many assumptions (None relevant joint, 3 waypoints, etc.) + if should_open: + grasp_data = get_grasp_position_for_open(self.robot, obj, should_open, None) + else: + grasp_data = get_grasp_position_for_open(self.robot, obj, should_open, None, num_waypoints=3) + + if grasp_data is None: + # We were trying to do something but didn't have the data. + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.SAMPLING_ERROR, + "Could not sample grasp position for target object", + {"target object": obj.name}, + ) + + relevant_joint, grasp_pose, target_poses, object_direction, grasp_required, pos_change = grasp_data + if abs(pos_change) < 0.1: + indented_print("Yaw change is small and done,", pos_change) + return + + # Prepare data for the approach later. + approach_pos = grasp_pose[0] + object_direction * m.OPEN_GRASP_APPROACH_DISTANCE + approach_pose = (approach_pos, grasp_pose[1]) + + # If the grasp pose is too far, navigate + yield from self._navigate_if_needed(obj, eef_pose=grasp_pose) + + yield from self._move_hand(grasp_pose, stop_if_stuck=True) + + # We can pre-grasp in sticky grasping mode only for opening + if should_open: + yield from self._execute_grasp() + + # Since the grasp pose is slightly off the object, we want to move towards the object, around 5cm. + # It's okay if we can't go all the way because we run into the object. + yield from self._navigate_if_needed(obj, eef_pose=approach_pose) + + if should_open: + yield from self._move_hand_linearly_cartesian( + approach_pose, ignore_failure=False, stop_on_contact=True, stop_if_stuck=True + ) + else: + yield from self._move_hand_linearly_cartesian( + approach_pose, ignore_failure=False, stop_if_stuck=True + ) + + # Step once to update + empty_action = self._empty_action() + yield self._postprocess_action(empty_action) + + for i, target_pose in enumerate(target_poses): + yield from self._move_hand_linearly_cartesian(target_pose, ignore_failure=False, stop_if_stuck=True) + + # Moving to target pose often fails. This might leave the robot's motors with torques that + # try to get to a far-away position thus applying large torques, but unable to move due to + # the sticky grasp joint. Thus if we release the joint, the robot might suddenly launch in an + # arbitrary direction. To avoid this, we command the hand to apply torques with its current + # position as its target. This prevents the hand from jerking into some other position when we do a release. + yield from self._move_hand_linearly_cartesian( + self.robot.eef_links[self.arm].get_position_orientation(), ignore_failure=True, stop_if_stuck=True + ) + + if should_open: + yield from self._execute_release() + yield from self._move_base_backward() + + except ActionPrimitiveError as e: + indented_print(e) + if should_open: + yield from self._execute_release() + yield from self._move_base_backward() + else: + yield from self._move_hand_backward() + + if obj.states[object_states.Open].get_value() != should_open: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.POST_CONDITION_ERROR, + "Despite executing the planned trajectory, the object did not open or close as expected. Maybe try again", + {"target object": obj.name, "is it currently open": obj.states[object_states.Open].get_value()}, + ) + + # TODO: Figure out how to generalize out of this "backing out" behavior. + def _move_base_backward(self, steps=5, speed=0.2): + """ + Yields action for the robot to move base so the eef is in the target pose using the planner + + Args: + steps (int): steps to move base + speed (float): base speed + + Returns: + th.tensor or None: Action array for one step for the robot to move base or None if its at the target pose + """ + for _ in range(steps): + action = self._empty_action() + action[self.robot.controller_action_idx["gripper_{}".format(self.arm)]] = 1.0 + action[self.robot.base_control_idx[0]] = -speed + yield self._postprocess_action(action) + + def _move_hand_backward(self, steps=5, speed=0.2): + """ + Yields action for the robot to move its base backwards. + + Args: + steps (int): steps to move eef + speed (float): eef speed + + Returns: + th.tensor or None: Action array for one step for the robot to move hand or None if its at the target pose + """ + for _ in range(steps): + action = self._empty_action() + action[self.robot.controller_action_idx["gripper_{}".format(self.arm)]] = 1.0 + action[self.robot.controller_action_idx["arm_{}".format(self.arm)][0]] = -speed + yield self._postprocess_action(action) + + def _move_hand_upward(self, steps=5, speed=0.1): + """ + Yields action for the robot to move hand upward. + + Args: + steps (int): steps to move eef + speed (float): eef speed + + Returns: + th.tensor or None: Action array for one step for the robot to move hand or None if its at the target pose + """ + # TODO: Combine these movement functions. + for _ in range(steps): + action = self._empty_action() + action[self.robot.controller_action_idx["gripper_{}".format(self.arm)]] = 1.0 + action[self.robot.controller_action_idx["arm_{}".format(self.arm)][2]] = speed + yield self._postprocess_action(action) + + def _sample_grasp_pose(self, obj): + """ + Samples an eef grasp pose for the object + + Args: + obj (USDObject): Object to sample grasp pose for + + Returns: + Tuple[th.tensor, th.tensor]: Pregrasp pose and grasp pose of the robot eef in the world frame + """ + indented_print("Sampling grasp pose") + grasp_poses = get_grasp_poses_for_object_sticky(obj) + grasp_pos, grasp_quat = random.choice(grasp_poses) + + # Identity quaternion for top-down grasping (x-forward, y-right, z-down) + approach_dir = T.quat2mat(grasp_quat) @ th.tensor([0.0, 0.0, -1.0]) + + avg_finger_offset = th.mean( + th.tensor([length for length in self.robot.eef_to_fingertip_lengths[self.arm].values()]) + ) + pregrasp_offset = avg_finger_offset + m.GRASP_APPROACH_DISTANCE + + pregrasp_pos = grasp_pos - approach_dir * pregrasp_offset + + # The sampled grasp pose is robot-agnostic + # We need to multiply by the quaternion of the robot's eef frame of top-down grasping (x-forward, y-right, z-down) + grasp_quat = T.quat_multiply(grasp_quat, th.tensor([1.0, 0.0, 0.0, 0.0])) + + pregrasp_pose = (pregrasp_pos, grasp_quat) + grasp_pose = (grasp_pos, grasp_quat) + + return pregrasp_pose, grasp_pose + + def _grasp(self, obj): + """ + Yields action for the robot to navigate to object if needed, then to grasp it + + Args: + StatefulObject: Object for robot to grasp + + Returns: + th.tensor or None: Action array for one step for the robot to grasp or None if grasp completed + """ + if obj is None or not isinstance(obj, USDObject): + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "You need to provide an object to grasp", + {"provided object": obj}, + ) + if self.robot.grasping_mode not in ["sticky", "assisted"]: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "Grasping mode not supported", + {"grasping mode": self.robot.grasping_mode}, + ) + + # Update the tracking to track the object. + self._tracking_object = obj + + # Don't do anything if the object is already grasped. + obj_in_hand = self._get_obj_in_hand() + if obj_in_hand is not None: + if obj_in_hand == obj: + return + else: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "Cannot grasp when your hand is already full", + {"target object": obj.name, "object currently in hand": obj_in_hand.name}, + ) + + # Open the hand first + indented_print("Opening hand before grasping") + yield from self._execute_release() + + pregrasp_pose, grasp_pose = self._sample_grasp_pose(obj) + + # If the pre-grasp pose is too far, navigate. + indented_print("Navigating to grasp pose if needed") + yield from self._navigate_if_needed(obj, eef_pose=pregrasp_pose) + + indented_print("Moving hand to grasp pose") + yield from self._move_hand(pregrasp_pose) + + if self.robot.grasping_mode == "sticky": + indented_print("Sticky grasping: close gripper") + # Close the gripper + yield from self._execute_grasp() + + indented_print("Sticky grasping: approach") + # Only translate in the z-axis of the goal frame (assuming z-axis points out of the gripper) + # This is the same as requesting the end-effector to move along the approach_dir direction. + # By default, it's NOT the z-axis of the world frame unless `project_pose_to_goal_frame=False` is set in curobo. + # For sticky grasping, we also need to ignore the object during motion planning because the fingers are already closed. + yield from self._move_hand( + grasp_pose, motion_constraint=[1, 1, 1, 1, 1, 0], stop_on_ag=True, ignore_objects=[obj] + ) + elif self.robot.grasping_mode == "assisted": + indented_print("Assisted grasping: approach") + # Same as above in terms of moving along the approach_dir direction, but we don't ignore the object. + # For this approach motion, we expect the fingers to move towards and eventually "wrap" around the object without collisions. + yield from self._move_hand(grasp_pose, motion_constraint=[1, 1, 1, 1, 1, 0]) + + # Now we close the fingers to grasp the object with AG. + indented_print("Assisted grasping: close gripper") + yield from self._execute_grasp() + + # Step a few times to update + yield from self._settle_robot() + + indented_print("Checking grasp") + obj_in_hand = self._get_obj_in_hand() + if obj_in_hand is None: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.POST_CONDITION_ERROR, + "Grasp completed, but no object detected in hand after executing grasp", + {"target object": obj.name}, + ) + + indented_print("Done with grasp") + + if self._get_obj_in_hand() != obj: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.POST_CONDITION_ERROR, + "An unexpected object was detected in hand after executing grasp. Consider releasing it", + {"expected object": obj.name, "actual object": self._get_obj_in_hand().name}, + ) + + def _place_on_top(self, obj): + """ + Yields action for the robot to navigate to the object if needed, then to place an object on it + + Args: + obj (StatefulObject): Object for robot to place the object in its hand on + + Returns: + th.tensor or None: Action array for one step for the robot to place or None if place completed + """ + yield from self._place_with_predicate(obj, object_states.OnTop) + + def _place_inside(self, obj): + """ + Yields action for the robot to navigate to the object if needed, then to place an object in it + + Args: + obj (StatefulObject): Object for robot to place the object in its hand on + + Returns: + th.tensor or None: Action array for one step for the robot to place or None if place completed + """ + yield from self._place_with_predicate(obj, object_states.Inside) + + def _toggle_on(self, obj): + yield from self._toggle(obj, True) + + def _toggle_off(self, obj): + yield from self._toggle(obj, False) + + def _toggle(self, obj, value): + raise NotImplementedError("Toggle is not implemented correctly yet.") + + if obj.states[object_states.ToggledOn].get_value() == value: + return + + # Put the hand in the toggle marker. + toggle_state = obj.states[object_states.ToggledOn] + toggle_position = toggle_state.get_link_position() + yield from self._navigate_if_needed(obj, toggle_position) + + # Just keep the current hand orientation. + hand_orientation = self.robot.eef_links[self.arm].get_position_orientation()[1] + desired_hand_pose = (toggle_position, hand_orientation) + + yield from self._move_hand(desired_hand_pose) + + if obj.states[object_states.ToggledOn].get_value() != value: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.POST_CONDITION_ERROR, + "The object did not toggle as expected - maybe try again", + { + "target object": obj.name, + "is it currently toggled on": obj.states[object_states.ToggledOn].get_value(), + }, + ) + + def _place_with_predicate(self, obj, predicate): + """ + Yields action for the robot to navigate to the object if needed, then to place it + + Args: + obj (StatefulObject): Object for robot to place the object in its hand on + predicate (object_states.OnTop or object_states.Inside): Determines whether to place on top or inside + + Returns: + th.tensor or None: Action array for one step for the robot to place or None if place completed + """ + if obj is None or not isinstance(obj, USDObject): + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "You need to provide an object to place the object in your hand on", + {"provided object": obj}, + ) + # Update the tracking to track the object. + self._tracking_object = obj + + obj_in_hand = self._get_obj_in_hand() + if obj_in_hand is None: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "You need to be grasping an object first to place it somewhere.", + ) + + self._motion_generator.update_obstacles() + target_in_reach = False + valid_navigation_pose = None + for _ in range(m.MAX_ATTEMPTS_FOR_SAMPLING_PLACE_POSE): + # Sample one pose at a time + obj_pose = self._sample_pose_with_object_and_predicate(predicate, obj_in_hand, obj, world_aligned=True) + hand_pose = self._get_hand_pose_for_object_pose(obj_pose) + + # First check if we can directly move the hand there + # We want to plan with the fingers at their upper (open) limits to avoid collisions + # because later we will open-loop open the gripper with _execute_release after placing. + initial_joint_pos = self._get_joint_position_with_fingers_at_limit("upper") + target_in_reach = self._target_in_reach_of_robot( + hand_pose, initial_joint_pos=initial_joint_pos, skip_obstacle_update=True + ) + if target_in_reach: + yield from self._move_hand(hand_pose) + break + + # If not, try to find a valid navigation pose for this hand pose + valid_navigation_pose = self._sample_pose_near_object( + obj, eef_pose=hand_pose, plan_with_open_gripper=True, sampling_attempts=10, skip_obstacle_update=True + ) + + if valid_navigation_pose is not None: + yield from self._navigate_to_pose(valid_navigation_pose, skip_obstacle_update=True) + yield from self._move_hand(hand_pose) + break + + if not target_in_reach and valid_navigation_pose is None: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PLANNING_ERROR, + "Could not find a valid pose to place the object", + {"target object": obj.name}, + ) + + yield from self._execute_release() + + if self._get_obj_in_hand() is not None: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.EXECUTION_ERROR, + "Could not release object - the object is still in your hand", + {"object": self._get_obj_in_hand().name}, + ) + + if not obj_in_hand.states[predicate].get_value(obj): + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.EXECUTION_ERROR, + "Failed to place object at the desired place (probably dropped). The object was still released, so you need to grasp it again to continue", + {"dropped object": obj_in_hand.name, "target object": obj.name}, + ) + + def _convert_cartesian_to_joint_space(self, target_pose): + """ + Gets joint positions for the arm so eef is at the target pose + + Args: + target_pose (Tuple[th.tensor, th.tensor]): target pose to reach for the default end-effector in the world frame + + Returns: + 2-tuple + - th.tensor or None: Joint positions to reach target pose or None if impossible to reach target pose + - th.tensor: Indices for joints in the robot + """ + joint_pos = self._ik_solver_cartesian_to_joint_space(target_pose) + if joint_pos is None: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PLANNING_ERROR, + "Could not find joint positions for target pose. You cannot reach it. Try again for a new pose", + ) + return joint_pos + + def _target_in_reach_of_robot(self, target_pose, initial_joint_pos=None, skip_obstacle_update=False): + """ + Determines whether the eef for the robot can reach the target pose in the world frame + + Args: + target_pose (Tuple[th.tensor, th.tensor]): target pose to reach for the default end-effector in the world frame + skip_obstacle_update (bool): Whether to skip updating obstacles + + Returns: + bool: Whether the default eef can reach the target pose + """ + return ( + self._ik_solver_cartesian_to_joint_space( + target_pose, + initial_joint_pos=initial_joint_pos, + skip_obstacle_update=skip_obstacle_update, + ) + is not None + ) + + def _manipulation_control_idx(self): + """The appropriate manipulation control idx for the current settings.""" + return th.cat([self.robot.trunk_control_idx, self.robot.arm_control_idx[self.arm]]) + + def _ik_solver_cartesian_to_joint_space(self, target_pose, initial_joint_pos=None, skip_obstacle_update=False): + """ + Get joint positions for the arm so eef is at the target pose in the world frame + + Args: + target_pose (Tuple[th.tensor, th.tensor]): target pose to reach for the default end-effector in the world frame + initial_joint_pos (None or th.tensor): If specified, the initial joint positions to set the locked joints. + Default is the current joint positions of the robot + skip_obstacle_update (bool): Whether to skip updating obstacles + + Returns: + 2-tuple + - th.tensor or None: Joint positions to reach target pose or None if impossible to reach the target pose + - th.tensor: Indices for joints in the robot + """ + target_pos = {self.robot.eef_link_names[self.arm]: target_pose[0]} + target_quat = {self.robot.eef_link_names[self.arm]: target_pose[1]} + + target_pos = {k: th.stack([v for _ in range(self._motion_generator.batch_size)]) for k, v in target_pos.items()} + target_quat = { + k: th.stack([v for _ in range(self._motion_generator.batch_size)]) for k, v in target_quat.items() + } + + successes, joint_states = self._motion_generator.compute_trajectories( + target_pos=target_pos, + target_quat=target_quat, + initial_joint_pos=initial_joint_pos, + is_local=False, + max_attempts=math.ceil(m.MAX_PLANNING_ATTEMPTS / self._motion_generator.batch_size), + timeout=60.0, + ik_fail_return=m.MAX_IK_FAILURES_BEFORE_RETURN, + enable_finetune_trajopt=False, + finetune_attempts=0, + return_full_result=False, + success_ratio=1.0 / self._motion_generator.batch_size, + attached_obj=None, + attached_obj_scale=None, + motion_constraint=None, + skip_obstacle_update=skip_obstacle_update, + ik_only=True, + ik_world_collision_check=True, + emb_sel=CuRoboEmbodimentSelection.ARM, + ) + + # Grab the first successful joint state if found + success_idx = th.where(successes)[0].cpu() + if len(success_idx) == 0: + return None + + joint_state = joint_states[success_idx[0]] + joint_pos = self._motion_generator.path_to_joint_trajectory( + joint_state, get_full_js=False, emb_sel=CuRoboEmbodimentSelection.ARM + ) + return joint_pos[self._manipulation_control_idx()].cpu() + + def _move_hand( + self, + target_pose, + stop_on_contact=False, + stop_on_ag=False, + motion_constraint=None, + low_precision=False, + lock_auxiliary_arm=False, + ignore_objects=None, + ): + """ + Yields action for the robot to move hand so the eef is in the target pose using the planner + + Args: + target_pose (Tuple[th.tensor, th.tensor]): target pose to reach for the default end-effector in the world frame + stop_on_contact (bool): Whether to stop executing motion plan if contact is detected + stop_on_ag (bool): Whether to stop executing motion plan if assisted grasping is activated + motion_constraint (MotionConstraint): Motion constraint for the motion + low_precision (bool): Whether to use low precision for the motion + lock_auxiliary_arm (bool): Whether to lock the other arm in place + ignore_objects (None or list of str): If specified, objects that should be ignored when planning + + Returns: + th.tensor or None: Action array for one step for the robot to move hand or None if its at the target pose + """ + if self.debug_visual_marker is not None: + self.debug_visual_marker.set_position_orientation(*target_pose) + + yield from self._settle_robot() + # curobo motion generator takes a pose but outputs joint positions + if not lock_auxiliary_arm: + target_pos = { + self.robot.eef_link_names[self.arm]: target_pose[0], + } + target_quat = { + self.robot.eef_link_names[self.arm]: target_pose[1], + } + else: + left_hand_pos, left_hand_quat = target_pose if self.arm == "left" else self.robot.get_eef_pose(arm="left") + right_hand_pos, right_hand_quat = ( + target_pose if self.arm == "right" else self.robot.get_eef_pose(arm="right") + ) + target_pos = { + self.robot.eef_link_names["left"]: left_hand_pos, + self.robot.eef_link_names["right"]: right_hand_pos, + } + target_quat = { + self.robot.eef_link_names["left"]: left_hand_quat, + self.robot.eef_link_names["right"]: right_hand_quat, + } + q_traj = self._plan_joint_motion( + target_pos=target_pos, + target_quat=target_quat, + embodiment_selection=CuRoboEmbodimentSelection.ARM, + motion_constraint=motion_constraint, + ignore_objects=ignore_objects, + ) + + indented_print(f"Plan has {len(q_traj)} steps") + yield from self._execute_motion_plan( + q_traj, stop_on_contact=stop_on_contact, stop_on_ag=stop_on_ag, low_precision=low_precision + ) + + def _plan_joint_motion( + self, + target_pos, + target_quat, + embodiment_selection=CuRoboEmbodimentSelection.DEFAULT, + motion_constraint=None, + skip_obstacle_update=False, + ignore_objects=None, + ): + # If an object is grasped, we need to pass it to the motion planner + obj_in_hand = self._get_obj_in_hand() + attached_obj = {self.robot.eef_link_names[self.arm]: obj_in_hand.root_link} if obj_in_hand is not None else None + + # Aggregate target_pos and target_quat to match batch_size + target_pos = {k: th.stack([v for _ in range(self._motion_generator.batch_size)]) for k, v in target_pos.items()} + target_quat = { + k: th.stack([v for _ in range(self._motion_generator.batch_size)]) for k, v in target_quat.items() + } + + if not skip_obstacle_update: + self._motion_generator.update_obstacles(ignore_objects=ignore_objects) + + successes, traj_paths = self._motion_generator.compute_trajectories( + target_pos=target_pos, + target_quat=target_quat, + initial_joint_pos=None, + is_local=False, + max_attempts=math.ceil(m.MAX_PLANNING_ATTEMPTS / self._motion_generator.batch_size), + timeout=60.0, + ik_fail_return=m.MAX_IK_FAILURES_BEFORE_RETURN, + enable_finetune_trajopt=True, + finetune_attempts=1, + return_full_result=False, + success_ratio=1.0 / self._motion_generator.batch_size, + attached_obj=attached_obj, + attached_obj_scale=None, + motion_constraint=motion_constraint, + skip_obstacle_update=True, + ik_only=False, + ik_world_collision_check=True, + emb_sel=embodiment_selection, + ) + # Grab the first successful trajectory if found + success_idx = th.where(successes)[0].cpu() + if len(success_idx) == 0: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PLANNING_ERROR, + "There is no accessible path from where you are to the desired pose. Try again", + ) + + traj_path = traj_paths[success_idx[0]] + q_traj = ( + self._motion_generator.path_to_joint_trajectory(traj_path, get_full_js=True, emb_sel=embodiment_selection) + .cpu() + .float() + ) + q_traj = self._motion_generator.add_linearly_interpolated_waypoints(traj=q_traj, max_inter_dist=0.01) + + return q_traj + + def _execute_motion_plan( + self, + q_traj, + stop_on_contact=False, + stop_on_ag=False, + ignore_failure=False, + low_precision=False, + ignore_physics=False, + ): + for joint_pos in q_traj: + if ignore_physics: + self.robot.set_joint_positions(joint_pos) + og.sim.step() + if stop_on_contact and detect_robot_collision_in_sim(self.robot): + return + else: + # Convert target joint positions to command + base_target_reached = False + articulation_target_reached = False + collision_detected = False + articulation_control_idx = [self.robot.trunk_control_idx] + for arm in self.robot.arm_names: + articulation_control_idx.append(self.robot.arm_control_idx[arm]) + articulation_control_idx = th.cat(articulation_control_idx) + for _ in range(m.MAX_STEPS_FOR_JOINT_MOTION): + # We need to call @q_to_action for every step because as the robot base moves, the same base joint_pos will be + # converted to different actions, since HolonomicBaseJointController accepts an action in the robot local frame. + action = self.robot.q_to_action(joint_pos) + yield self._postprocess_action(action) + + current_joint_pos = self.robot.get_joint_positions() + joint_pos_diff = joint_pos - current_joint_pos + base_joint_diff = joint_pos_diff[self.robot.base_control_idx] + articulation_joint_diff = joint_pos_diff[articulation_control_idx] # Gets all non-base joints + articulation_threshold = ( + m.JOINT_POS_DIFF_THRESHOLD if not low_precision else m.LOW_PRECISION_JOINT_POS_DIFF_THRESHOLD + ) + max_articulation_joint_diff = th.max(th.abs(articulation_joint_diff)).item() + if max_articulation_joint_diff < articulation_threshold: + articulation_target_reached = True + + max_base_pos_diff = th.max(th.abs(base_joint_diff[:2])).item() + max_base_orn_diff = th.abs(wrap_angle(base_joint_diff[2])) + if max_base_pos_diff < m.DEFAULT_DIST_THRESHOLD and max_base_orn_diff < m.DEFAULT_ANGLE_THRESHOLD: + base_target_reached = True + + # Early stopping if the base, trunk and arm joints are at the target positions + if base_target_reached and articulation_target_reached: + break + + collision_detected = detect_robot_collision_in_sim(self.robot) + if stop_on_contact and collision_detected: + return + + if stop_on_ag and self._get_obj_in_hand() is not None: + return + + if not ignore_failure: + if not base_target_reached: + indented_print(f"max base pos diff: {max_base_pos_diff}") + indented_print(f"max base angle diff: {max_base_orn_diff}") + # breakpoint() + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.EXECUTION_ERROR, + "Could not reach the target base joint positions. Try again", + ) + if not articulation_target_reached: + indented_print(f"max articulation joint diff: {max_articulation_joint_diff}") + # breakpoint() + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.EXECUTION_ERROR, + "Could not reach the target articulation joint positions. Try again", + ) + + def _move_hand_direct_joint(self, joint_pos, stop_on_contact=False, ignore_failure=False): + """ + Yields action for the robot to move its arm to reach the specified joint positions by directly actuating with no planner + + Args: + joint_pos (th.tensor): Array of joint positions for the arm + stop_on_contact (boolean): Determines whether to stop move once an object is hit + ignore_failure (boolean): Determines whether to throw error for not reaching final joint positions + + Returns: + th.tensor or None: Action array for one step for the robot to move arm or None if its at the joint positions + """ + + # Store the previous eef pose for checking if we got stuck + prev_eef_pos = th.zeros(3) + + # All we need to do here is save the target joint position so that empty action takes us towards it + controller_name = f"arm_{self.arm}" + self._arm_targets[controller_name] = joint_pos + + for i in range(m.MAX_STEPS_FOR_HAND_MOVE_JOINT): + current_joint_pos = self.robot.get_joint_positions()[self._manipulation_control_idx()] + diff_joint_pos = joint_pos - current_joint_pos + if th.max(th.abs(diff_joint_pos)).item() < m.JOINT_POS_DIFF_THRESHOLD: + return + if stop_on_contact and detect_robot_collision_in_sim(self.robot): + return + # check if the eef stayed in the same pose for sufficiently long + if ( + og.sim.get_sim_step_dt() * i > m.TIME_BEFORE_JOINT_STUCK_CHECK + and th.max(th.abs(self.robot.get_eef_position(self.arm) - prev_eef_pos)).item() < 0.0001 + ): + # We're stuck! + break + + # Since we set the new joint target as the arm_target, the empty action will take us towards it. + action = self._empty_action() + + prev_eef_pos = self.robot.get_eef_position(self.arm) + yield self._postprocess_action(action) + + if not ignore_failure: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.EXECUTION_ERROR, + "Your hand was obstructed from moving to the desired joint position", + ) + + def _move_hand_direct_ik( + self, + target_pose, + stop_on_contact=False, + ignore_failure=False, + pos_thresh=0.02, + ori_thresh=0.4, + in_world_frame=True, + stop_if_stuck=False, + ): + """ + Moves the hand to a target pose using inverse kinematics. + + Args: + target_pose (tuple): A tuple of two elements, representing the target pose of the hand as a position and a quaternion. + stop_on_contact (bool, optional): Whether to stop the movement if the hand collides with an object. Defaults to False. + ignore_failure (bool, optional): Whether to raise an exception if the movement fails. Defaults to False. + pos_thresh (float, optional): The position threshold for considering the target pose reached. Defaults to 0.04. + ori_thresh (float, optional): The orientation threshold for considering the target pose reached. Defaults to 0.4. + in_world_frame (bool, optional): Whether the target pose is given in the world frame. Defaults to True. + stop_if_stuck (bool, optional): Whether to stop the movement if the hand is stuck. Defaults to False. + + Yields: + numpy.ndarray: The action to be executed by the robot controller. + + Raises: + ActionPrimitiveError: If the movement fails and ignore_failure is False. + """ + # make sure controller is InverseKinematicsController and in expected mode + controller_config = self.robot._controller_config["arm_" + self.arm] + assert ( + controller_config["name"] == "InverseKinematicsController" + ), "Controller must be InverseKinematicsController" + assert controller_config["mode"] == "pose_absolute_ori", "Controller must be in pose_absolute_ori mode" + if in_world_frame: + target_pose = self._world_pose_to_robot_pose(target_pose) + target_pos = target_pose[0] + target_orn = target_pose[1] + target_orn_axisangle = T.quat2axisangle(target_pose[1]) + prev_pos = prev_orn = None + + # All we need to do here is save the target IK position so that empty action takes us towards it + controller_name = f"arm_{self.arm}" + self._arm_targets[controller_name] = (target_pos, target_orn_axisangle) + + for i in range(m.MAX_STEPS_FOR_HAND_MOVE_IK): + current_pose = self._world_pose_to_robot_pose( + (self.robot.get_eef_position(self.arm), self.robot.get_eef_orientation(self.arm)) + ) + current_pos = current_pose[0] + current_orn = current_pose[1] + + delta_pos = target_pos - current_pos + target_pos_diff = th.norm(delta_pos) + target_orn_diff = T.get_orientation_diff_in_radian(current_orn, target_orn) + reached_goal = target_pos_diff < pos_thresh and target_orn_diff < ori_thresh + if reached_goal: + return + + if stop_on_contact and detect_robot_collision_in_sim(self.robot): + return + + # if i > 0 and stop_if_stuck and detect_robot_collision_in_sim(self.robot): + if i > 0 and stop_if_stuck: + pos_diff = th.norm(prev_pos - current_pos) + orn_diff = T.get_orientation_diff_in_radian(current_orn, prev_orn) + if pos_diff < 0.0003 and orn_diff < 0.01: + raise ActionPrimitiveError(ActionPrimitiveError.Reason.EXECUTION_ERROR, "Hand is stuck") + + prev_pos = current_pos + prev_orn = current_orn + + # Since we set the new IK target as the arm_target, the empty action will take us towards it. + action = self._empty_action() + yield self._postprocess_action(action) + + if not ignore_failure: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.EXECUTION_ERROR, + "Your hand was obstructed from moving to the desired joint position", + ) + + def _move_hand_linearly_cartesian( + self, target_pose, stop_on_contact=False, ignore_failure=False, stop_if_stuck=False + ): + """ + Yields action for the robot to move its arm to reach the specified target pose by moving the eef along a line in cartesian + space from its current pose + + Args: + target_pose (Tuple[th.tensor, th.tensor]): target pose to reach for the default end-effector in the world frame + stop_on_contact (boolean): Determines whether to stop move once an object is hit + ignore_failure (boolean): Determines whether to throw error for not reaching final joint positions + + Returns: + th.tensor or None: Action array for one step for the robot to move arm or None if its at the target pose + """ + # To make sure that this happens in a roughly linear fashion, we will divide the trajectory + # into 1cm-long pieces + start_pos, start_orn = self.robot.eef_links[self.arm].get_position_orientation() + travel_distance = th.norm(target_pose[0] - start_pos) + num_poses = int( + th.max(th.tensor([2, int(travel_distance / m.MAX_CARTESIAN_HAND_STEP) + 1], dtype=th.float32)).item() + ) + pos_waypoints = multi_dim_linspace(start_pos, target_pose[0], num_poses) + + # Also interpolate the rotations + t_values = th.linspace(0, 1, num_poses) + quat_waypoints = [T.quat_slerp(start_orn, target_pose[1], t) for t in t_values] + + controller_config = self.robot._controller_config["arm_" + self.arm] + if controller_config["name"] == "InverseKinematicsController": + waypoints = list(zip(pos_waypoints, quat_waypoints)) + + for i, waypoint in enumerate(waypoints): + if i < len(waypoints) - 1: + yield from self._move_hand_direct_ik( + waypoint, + stop_on_contact=stop_on_contact, + ignore_failure=ignore_failure, + stop_if_stuck=stop_if_stuck, + ) + else: + yield from self._move_hand_direct_ik( + waypoints[-1], + pos_thresh=0.01, + ori_thresh=0.1, + stop_on_contact=stop_on_contact, + ignore_failure=ignore_failure, + stop_if_stuck=stop_if_stuck, + ) + + # Also decide if we can stop early. + current_pos, current_orn = self.robot.eef_links[self.arm].get_position_orientation() + pos_diff = th.norm(current_pos - target_pose[0]) + orn_diff = T.get_orientation_diff_in_radian(target_pose[1], current_orn).item() + if pos_diff < m.HAND_DIST_THRESHOLD and orn_diff < th.deg2rad(th.tensor([0.1])).item(): + return + + if stop_on_contact and detect_robot_collision_in_sim(self.robot): + return + + if not ignore_failure: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.EXECUTION_ERROR, + "Your hand was obstructed from moving to the desired world position", + ) + else: + # Use joint positions + joint_space_data = [ + self._convert_cartesian_to_joint_space(waypoint) for waypoint in zip(pos_waypoints, quat_waypoints) + ] + joints = list(self.robot.joints.values()) + + for joint_pos in joint_space_data: + # Check if the movement can be done roughly linearly. + current_joint_positions = self.robot.get_joint_positions()[self._manipulation_control_idx()] + + failed_joints = [] + for joint_idx, target_joint_pos, current_joint_pos in zip( + self._manipulation_control_idx(), joint_pos, current_joint_positions + ): + if th.abs(target_joint_pos - current_joint_pos) > m.MAX_ALLOWED_JOINT_ERROR_FOR_LINEAR_MOTION: + failed_joints.append(joints[joint_idx].joint_name) + + if failed_joints: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.EXECUTION_ERROR, + "You cannot reach the target position in a straight line - it requires rotating your arm which might cause collisions. You might need to get closer and retry", + {"failed joints": failed_joints}, + ) + + # Otherwise, move the joint + yield from self._move_hand_direct_joint( + joint_pos, stop_on_contact=stop_on_contact, ignore_failure=ignore_failure + ) + + # Also decide if we can stop early. + current_pos, current_orn = self.robot.eef_links[self.arm].get_position_orientation() + pos_diff = th.norm(current_pos - target_pose[0]) + orn_diff = T.get_orientation_diff_in_radian(target_pose[1], current_orn) + if pos_diff < 0.001 and orn_diff < th.deg2rad(th.tensor([0.1])).item(): + return + + if stop_on_contact and detect_robot_collision_in_sim(self.robot): + return + + if not ignore_failure: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.EXECUTION_ERROR, + "Your hand was obstructed from moving to the desired world position", + ) + + def _get_joint_position_with_fingers_at_limit(self, limit_type): + """ + Helper function to get the joint positions when the robot's fingers are at their limit positions. + + Args: + limit_type (str): Either 'lower' for grasping or 'upper' for releasing. + + Yields: + th.tensor: Joint positions for the robot with fingers at their limit positions. + """ + target_joint_positions = self.robot.get_joint_positions() + gripper_ctrl_idx = self.robot.gripper_control_idx[self.arm] + if limit_type == self.robot._grasping_direction: + finger_joint_limits = self.robot.joint_lower_limits[gripper_ctrl_idx] + else: + finger_joint_limits = self.robot.joint_upper_limits[gripper_ctrl_idx] + target_joint_positions[gripper_ctrl_idx] = finger_joint_limits + return target_joint_positions + + def _move_fingers_to_limit(self, limit_type): + """ + Helper function to move the robot's fingers to their limit positions. + + Args: + limit_type (str): Either 'lower' for grasping or 'upper' for releasing. + + Yields: + th.tensor or None: Action array for one step for the robot to move fingers or None if done. + """ + target_joint_positions = self._get_joint_position_with_fingers_at_limit(limit_type) + action = self.robot.q_to_action(target_joint_positions) + for _ in range(m.MAX_STEPS_FOR_GRASP_OR_RELEASE): + yield self._postprocess_action(action) + current_joint_positions = self.robot.get_joint_positions() + if th.allclose(current_joint_positions, target_joint_positions, atol=m.JOINT_POS_DIFF_THRESHOLD): + break + elif limit_type == "lower" and self._get_obj_in_hand() is not None: + # If we are grasping an object, we should stop when object is detected in hand + break + + def _execute_grasp(self): + """ + Yields action for the robot to grasp. + + Returns: + th.tensor or None: Action array for one step for the robot to grasp or None if done grasping. + """ + yield from self._move_fingers_to_limit("lower") + + def _execute_release(self): + """ + Yields action for the robot to release its grasp. + + Returns: + th.tensor or None: Action array for one step for the robot to release or None if done releasing. + """ + yield from self._move_fingers_to_limit("upper") + + if self._get_obj_in_hand() is not None: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.EXECUTION_ERROR, + "An object was still detected in your hand after executing release", + {"object in hand": self._get_obj_in_hand().name}, + ) + + def _overwrite_head_action(self, action): + """ + Overwrites camera control actions to track an object of interest. + If self._always_track_eef is true, always tracks the end effector of the robot. + Otherwise, tracks the object of interest or the end effector as specified by the primitive. + + Args: + action (array) : action array to overwrite + """ + if self._always_track_eef: + target_obj_pose = (self.robot.get_eef_position(self.arm), self.robot.get_eef_orientation(self.arm)) + else: + if self._tracking_object is None: + return action + + if self._tracking_object == self.robot: + target_obj_pose = (self.robot.get_eef_position(self.arm), self.robot.get_eef_orientation(self.arm)) + else: + target_obj_pose = self._tracking_object.get_position_orientation() + + assert self.robot.model == "tiago", "Tracking object with camera is currently only supported for Tiago" + + head_q = self._get_head_goal_q(target_obj_pose) + head_idx = self.robot.controller_action_idx["camera"] + + config = self.robot._controller_config["camera"] + assert config["name"] == "JointController", "Camera controller must be JointController" + assert config["motor_type"] == "position", "Camera controller must be in position control mode" + use_delta = config["use_delta_commands"] + + if use_delta: + cur_head_q = self.robot.get_joint_positions()[self.robot.camera_control_idx] + head_action = head_q - cur_head_q + else: + head_action = head_q + action[head_idx] = head_action + return action + + def _get_head_goal_q(self, target_obj_pose): + """ + Get goal joint positions for head to look at an object of interest, + If the object cannot be seen, return the reset (default) head joint positions. + """ + + # get current head joint positions + head1_joint = self.robot.joints["head_1_joint"] + head2_joint = self.robot.joints["head_2_joint"] + head1_joint_limits = [head1_joint.lower_limit, head1_joint.upper_limit] + head2_joint_limits = [head2_joint.lower_limit, head2_joint.upper_limit] + head1_joint_goal = head1_joint.get_state()[0][0] + head2_joint_goal = head2_joint.get_state()[0][0] + + # grab robot and object poses + robot_pose = self.robot.get_position_orientation() + # obj_pose = obj.get_position_orientation() + obj_in_base = T.relative_pose_transform(*target_obj_pose, *robot_pose) + + # compute angle between base and object in xy plane (parallel to floor) + theta = th.arctan2(obj_in_base[0][1], obj_in_base[0][0]) + + # if it is possible to get object in view, compute both head joint positions + if head1_joint_limits[0] < theta < head1_joint_limits[1]: + head1_joint_goal = theta + + # compute angle between base and object in xz plane (perpendicular to floor) + head2_pose = self.robot.links["head_2_link"].get_position_orientation() + head2_in_base = T.relative_pose_transform(*head2_pose, *robot_pose) + + phi = th.arctan2(obj_in_base[0][2] - head2_in_base[0][2], obj_in_base[0][0]) + if head2_joint_limits[0] < phi < head2_joint_limits[1]: + head2_joint_goal = phi + + # if not possible to look at object, return the reset (default) head joint positions + else: + default_head_pos = self.robot.reset_joint_pos[self.robot.controller_action_idx["camera"]] + head1_joint_goal = default_head_pos[0] + head2_joint_goal = default_head_pos[1] + + return th.tensor([head1_joint_goal, head2_joint_goal]) + + def _empty_action(self, follow_arm_targets=True): + """ + Generate a no-op action that will keep the robot still but aim to move the arms to the saved pose targets, if possible + + Args: + follow_arm_targets (bool): Whether to move the arms to the saved pose targets or keep them still. + + Returns: + th.tensor or None: Action array for one step for the robot to do nothing + """ + action = th.zeros(self.robot.action_dim) + for name, (group_key, controller_idx) in self.robot.controllers.items(): + # if desired arm targets are available, generate an action that moves the arms to the saved pose targets + if follow_arm_targets and name in self._arm_targets: + if ControllerView.is_controller_type(group_key, InverseKinematicsController): + arm = name.replace("arm_", "") + target_pos, target_orn_axisangle = self._arm_targets[name] + current_pos, current_orn = self._world_pose_to_robot_pose( + (self.robot.get_eef_position(arm), self.robot.get_eef_orientation(arm)) + ) + delta_pos = target_pos - current_pos + mode = ControllerView.get_mode(group_key) + if mode == "pose_delta_ori": + delta_orn = T.orientation_error( + T.quat2mat(T.axisangle2quat(target_orn_axisangle)), T.quat2mat(current_orn) + ) + partial_action = th.cat((delta_pos, delta_orn)) + elif mode == "pose_absolute_ori": + partial_action = th.cat((delta_pos, target_orn_axisangle)) + elif mode == "absolute_pose": + partial_action = th.cat((target_pos, target_orn_axisangle)) + else: + raise ValueError("Unexpected IK control mode") + else: + target_joint_pos = self._arm_targets[name] + current_joint_pos = self.robot.get_joint_positions()[self._manipulation_control_idx()] + if ControllerView.get_use_delta_commands(group_key): + partial_action = target_joint_pos - current_joint_pos + else: + partial_action = target_joint_pos + else: + partial_action = ControllerView.compute_no_op_action(group_key, controller_idx) + action_idx = self.robot.controller_action_idx[name] + action[action_idx] = partial_action + return action + + def _reset_robot(self): + """ + Yields action to move both hands to the position optimal for executing subsequent action primitives + + Returns: + th.tensor or None: Action array for one step for the robot to reset its hands or None if it is done resetting + """ + indented_print("Resetting robot") + target_pos = dict() + target_quat = dict() + for arm in self.robot.arm_names: + reset_eef_pose = self._get_reset_eef_pose("world")[arm] + target_pos[self.robot.eef_link_names[arm]] = reset_eef_pose[0] + target_quat[self.robot.eef_link_names[arm]] = reset_eef_pose[1] + q_traj = self._plan_joint_motion( + target_pos=target_pos, + target_quat=target_quat, + embodiment_selection=CuRoboEmbodimentSelection.ARM, + ) + indented_print(f"Plan has {len(q_traj)} steps") + yield from self._execute_motion_plan(q_traj) + + def _reset_hand(self): + """ + Yields action to move the hand to the position optimal for executing subsequent action primitives + + Returns: + th.tensor or None: Action array for one step for the robot to reset its hand or None if it is done resetting + """ + indented_print("Resetting hand") + # TODO: make this work with both hands + reset_eef_pose = self._get_reset_eef_pose("world")[self.arm] + if self.debug_visual_marker is not None: + self.debug_visual_marker.set_position_orientation(*reset_eef_pose) + yield from self._move_hand(reset_eef_pose) + + def _get_reset_eef_pose(self, frame="robot"): + """ + Get the reset eef pose for the robot + + Args: + frame (str): The frame in which the reset eef pose is specified, one of "robot" or "world" + + Returns: + dict of th.tensor: The reset eef pose for each robot arm + """ + pose = self._reset_eef_pose + if frame == "robot": + return pose + elif frame == "world": + return {arm: self._robot_pose_to_world_pose(pose[arm]) for arm in pose} + else: + raise ValueError(f"Unsupported frame: {frame}") + + def _navigate_to_pose(self, pose_2d, skip_obstacle_update=False): + """ + Yields the action to navigate robot to the specified 2d pose + + Args: + pose_2d (Iterable): (x, y, yaw) 2d pose + skip_obstacle_update (bool): Determines whether to skip updating the obstacles in the scene + + Returns: + th.tensor or None: Action array for one step for the robot to navigate or None if it is done navigating + """ + pose_3d = self._get_robot_pose_from_2d_pose(pose_2d) + if self.debug_visual_marker is not None: + self.debug_visual_marker.set_position_orientation(*pose_3d) + target_pos = {self.robot.base_footprint_link_name: pose_3d[0]} + target_quat = {self.robot.base_footprint_link_name: pose_3d[1]} + q_traj = self._plan_joint_motion( + target_pos, + target_quat, + embodiment_selection=CuRoboEmbodimentSelection.BASE, + skip_obstacle_update=skip_obstacle_update, + ) + yield from self._execute_motion_plan(q_traj) + + # (TODO) add a function to draw curobo-generated plans. + def _draw_plan(self, plan): + SEARCHED = [] + trav_map = self.robot.scene._trav_map + for q in plan: + # The below code is useful for plotting the RRT tree. + map_point = trav_map.world_to_map((q[0], q[1])) + SEARCHED.append(th.flip(map_point, dims=tuple(range(map_point.dim())))) + + fig = plt.figure() + plt.imshow(trav_map.floor_map[0]) + plt.scatter(*zip(*SEARCHED), 5) + fig.canvas.draw() + + # Convert the canvas to image + img = th.frombuffer(fig.canvas.tostring_rgb(), dtype=th.uint8) + img = img.reshape(fig.canvas.get_width_height()[::-1] + (3,)) + plt.close(fig) + + # Convert to BGR for cv2-based viewing. + img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) + + cv2.imshow("SceneGraph", img) + cv2.waitKey(1) + + def _navigate_if_needed(self, obj, eef_pose=None): + """ + Yields action to navigate the robot to be in range of the object if it not in the range + + Args: + obj (StatefulObject): Object for the robot to be in range of + eef_pose (Tuple[th.tensor, th.tensor]): target pose to reach for the default end-effector in the world frame + + Returns: + th.tensor or None: Action array for one step for the robot to navigate or None if it is done navigating + """ + self._motion_generator.update_obstacles() + + if eef_pose is None: + eef_pose, _ = self._sample_grasp_pose(obj) + + if self._target_in_reach_of_robot(eef_pose, skip_obstacle_update=True): + # No need to navigate. + return + + yield from self._navigate_to_obj(obj, eef_pose=eef_pose, skip_obstacle_update=True) + + def _navigate_to_obj(self, obj, eef_pose=None, skip_obstacle_update=False): + """ + Yields action to navigate the robot to be in range of the pose + + Args: + obj (StatefulObject or list of StatefulObject): object(s) to be in range of + eef_pose (Tuple[th.tensor, th.tensor]): target pose to reach for the default end-effector in the world frame + + Returns: + th.tensor or None: Action array for one step for the robot to navigate in range or None if it is done navigating + """ + pose = self._sample_pose_near_object(obj, eef_pose=eef_pose, skip_obstacle_update=skip_obstacle_update) + if pose is None: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PLANNING_ERROR, + "Could not find a valid pose near the object", + {"object": obj.name}, + ) + yield from self._navigate_to_pose(pose, skip_obstacle_update=skip_obstacle_update) + + def _navigate_to_pose_direct(self, pose_2d, low_precision=False): + """ + Yields action to navigate the robot to the 2d pose without planning + + Args: + pose_2d (Iterable): (x, y, yaw) 2d pose + low_precision (bool): Determines whether to navigate to the pose within a large range (low precision) or small range (high precison) + + Returns: + th.tensor or None: Action array for one step for the robot to navigate or None if it is done navigating + """ + dist_threshold = m.LOW_PRECISION_DIST_THRESHOLD if low_precision else m.DEFAULT_DIST_THRESHOLD + angle_threshold = m.LOW_PRECISION_ANGLE_THRESHOLD if low_precision else m.DEFAULT_ANGLE_THRESHOLD + + end_pose = self._get_robot_pose_from_2d_pose(pose_2d) + + for _ in range(m.MAX_STEPS_FOR_WAYPOINT_NAVIGATION): + body_target_pose = self._world_pose_to_robot_pose(end_pose) + if th.norm(body_target_pose[0][:2]) < dist_threshold: + break + + diff_pos = end_pose[0] - self.robot.get_position_orientation()[0] + intermediate_pose = ( + end_pose[0], + T.euler2quat(th.tensor([0, 0, math.atan2(diff_pos[1], diff_pos[0])], dtype=th.float32)), + ) + body_intermediate_pose = self._world_pose_to_robot_pose(intermediate_pose) + diff_yaw = T.quat2euler(body_intermediate_pose[1])[2].item() + if abs(diff_yaw) > m.DEFAULT_ANGLE_THRESHOLD: + yield from self._rotate_in_place(intermediate_pose, angle_threshold=m.DEFAULT_ANGLE_THRESHOLD) + else: + action = self._empty_action() + base_group_key, _ = self.robot.controllers["base"] + if ControllerView.is_controller_type(base_group_key, HolonomicBaseJointController): + assert ( + ControllerView.get_motor_type(base_group_key) == "velocity" + ), "Holonomic base controller must be in velocity mode" + direction_vec = ( + body_target_pose[0][:2] + / th.norm(body_target_pose[0][:2]) + * self.robot.linear_velocity_gain_for_primitives + ) + base_action = th.tensor([direction_vec[0], direction_vec[1], 0.0], dtype=th.float32) + action[self.robot.controller_action_idx["base"]] = base_action + elif ControllerView.is_controller_type(base_group_key, DifferentialDriveController): + base_action = th.tensor([self.robot.linear_velocity_gain_for_primitives, 0.0], dtype=th.float32) + action[self.robot.controller_action_idx["base"]] = base_action + else: + raise ValueError( + f"Unsupported base controller: {ControllerView.get_controller_type_str(base_group_key)}" + ) + + yield self._postprocess_action(action) + else: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.EXECUTION_ERROR, + "Could not navigate to the target position", + {"target pose": end_pose}, + ) + + # Rotate in place to final orientation once at location + yield from self._rotate_in_place(end_pose, angle_threshold=angle_threshold) + + def _rotate_in_place(self, end_pose, angle_threshold=m.DEFAULT_ANGLE_THRESHOLD): + """ + Yields action to rotate the robot to the 2d end pose + + Args: + end_pose (Iterable): (x, y, yaw) 2d pose + angle_threshold (float): The angle difference between the robot's current and end pose that determines when the robot is done rotating + + Returns: + th.tensor or None: Action array for one step for the robot to rotate or None if it is done rotating + """ + for _ in range(m.MAX_STEPS_FOR_WAYPOINT_NAVIGATION): + body_target_pose = self._world_pose_to_robot_pose(end_pose) + diff_yaw = T.quat2euler(body_target_pose[1])[2].item() + if abs(diff_yaw) < angle_threshold: + break + + action = self._empty_action() + + direction = -1.0 if diff_yaw < 0.0 else 1.0 + ang_vel = self.robot.angular_velocity_gain_for_primitives * direction + + base_action = action[self.robot.controller_action_idx["base"]] + + base_group_key, _ = self.robot.controllers["base"] + if ControllerView.is_controller_type(base_group_key, HolonomicBaseJointController): + assert ( + ControllerView.get_motor_type(base_group_key) == "velocity" + ), "Holonomic base controller must be in velocity mode" + base_action[0] = 0.0 + base_action[1] = 0.0 + base_action[2] = ang_vel + elif ControllerView.is_controller_type(base_group_key, DifferentialDriveController): + base_action[0] = 0.0 + base_action[1] = ang_vel + else: + raise ValueError( + f"Unsupported base controller: {ControllerView.get_controller_type_str(base_group_key)}" + ) + + action[self.robot.controller_action_idx["base"]] = base_action + yield self._postprocess_action(action) + else: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.EXECUTION_ERROR, + "Could not rotate in place to the desired orientation", + {"target pose": end_pose}, + ) + + empty_action = self._empty_action() + yield self._postprocess_action(empty_action) + + def _sample_pose_near_object( + self, + obj, + eef_pose=None, + plan_with_open_gripper=False, + sampling_attempts=m.MAX_ATTEMPTS_FOR_SAMPLING_POSE_NEAR_OBJECT, + skip_obstacle_update=False, + ): + """ + Returns a 2d pose for the robot within in the range of the object and where the robot is not in collision with anything + + Args: + obj (StatefulObject or list of StatefulObject): object(s) to sample a 2d pose near + eef_pose (Tuple[th.tensor, th.tensor]): target pose to reach for the default end-effector in the world frame + plan_with_open_gripper (bool): Determines whether to plan with the gripper open even though it might be closed now. + This is useful for the placing primitive because we will open-loop open the gripper after placing + sampling_attempts (int): Number of attempts to sample a valid pose + skip_obstacle_update (bool): Determines whether to skip updating the obstacles in the scene + Returns: + 2-tuple: + - 3-array: (x,y,z) Position in the world frame + - 4-array: (x,y,z,w) Quaternion orientation in the world frame + """ + distance_lo, distance_hi = m.BASE_POSE_SAMPLING_LOWER_BOUND, m.BASE_POSE_SAMPLING_UPPER_BOUND + yaw_lo, yaw_hi = -math.pi, math.pi + avg_arm_workspace_range = th.mean(self.robot.arm_workspace_range[self.arm]) + + if eef_pose is None: + eef_pose, _ = self._sample_grasp_pose(obj) + + target_pose = eef_pose + + obj_rooms = ( + obj.in_rooms if obj.in_rooms else [self.robot.scene._seg_map.get_room_instance_by_point(target_pose[0][:2])] + ) + + attempt = 0 + if not skip_obstacle_update: + # Update obstacle once before sampling + self._motion_generator.update_obstacles() + while attempt < sampling_attempts: + candidate_poses = [] + for _ in range(self._curobo_batch_size): + for _ in range(m.MAX_ATTEMPTS_FOR_SAMPLING_POSE_FOR_CORRECT_ROOM): + distance = (th.rand(1) * (distance_hi - distance_lo) + distance_lo).item() + yaw = th.rand(1) * (yaw_hi - yaw_lo) + yaw_lo + candidate_2d_pose = th.cat( + [ + target_pose[0][0] + distance * th.cos(yaw), + target_pose[0][1] + distance * th.sin(yaw), + yaw + math.pi - avg_arm_workspace_range, + ] + ) + + # Check room + if self.robot.scene._seg_map.get_room_instance_by_point(candidate_2d_pose[:2]) in obj_rooms: + break + candidate_poses.append(candidate_2d_pose) + + # Normally candidate_poses will have length equal to self._curobo_batch_size + # In case we are unable to find a valid pose in the room, we will have less than self._curobo_batch_size. + # We skip the following steps if the list is empty. + if len(candidate_poses) > 0: + result = self._validate_poses( + candidate_poses, + eef_pose=target_pose, + plan_with_open_gripper=plan_with_open_gripper, + skip_obstacle_update=True, + ) + + # If anything in result is true, return the pose + for i, res in enumerate(result): + if res: + indented_print("Found valid position near object.") + return candidate_poses[i] + + attempt += self._curobo_batch_size + return None + + @staticmethod + def _sample_position_on_aabb_side(target_obj): + """ + Returns a position on one of the axis-aligned bounding box (AABB) side faces of the target object. + + Args: + target_obj (StatefulObject): Object to sample a position on + + Returns: + 3-array: (x,y,z) Position in the world frame + """ + aabb_center, aabb_extent = target_obj.aabb_center, target_obj.aabb_extent + # We want to sample only from the side-facing faces. + face_normal_axis = random.choice([0, 1]) + face_normal_direction = random.choice([-1, 1]) + face_center = aabb_center + th.eye(3)[face_normal_axis] * aabb_extent * face_normal_direction + face_lateral_axis = 0 if face_normal_axis == 1 else 1 + face_lateral_half_extent = th.eye(3)[face_lateral_axis] * aabb_extent / 2 + face_vertical_half_extent = th.eye(3)[2] * aabb_extent / 2 + face_min = face_center - face_vertical_half_extent - face_lateral_half_extent + face_max = face_center + face_vertical_half_extent + face_lateral_half_extent + return th.rand(face_min.size()) * (face_max - face_min) + face_min + + # def _sample_pose_in_room(self, room: str): + # """ + # Returns a pose for the robot within in the room where the robot is not in collision with anything + + # Args: + # room (str): Name of room + + # Returns: + # 2-tuple: + # - 3-array: (x,y,z) Position in the world frame + # - 4-array: (x,y,z,w) Quaternion orientation in the world frame + # """ + # # TODO(MP): Bias the sampling near the agent. + # for _ in range(m.MAX_ATTEMPTS_FOR_SAMPLING_POSE_IN_ROOM): + # _, pos = self.env.scene.get_random_point_by_room_instance(room) + # yaw_lo, yaw_hi = -math.pi, math.pi + # yaw = (th.rand(1) * (yaw_hi - yaw_lo) + yaw_lo).item() + # pose = (pos[0], pos[1], yaw) + # if self._test_pose(pose): + # return pose + + # raise ActionPrimitiveError( + # ActionPrimitiveError.Reason.SAMPLING_ERROR, + # "Could not find valid position in the given room to travel to", + # {"room": room} + # ) + + def _sample_pose_with_object_and_predicate( + self, predicate, held_obj, target_obj, world_aligned=False, near_poses=None, near_poses_threshold=None + ): + """ + Returns a pose for the held object relative to the target object that satisfies the predicate + + Args: + predicate (object_states.OnTop or object_states.Inside): Relation between held object and the target object + held_obj (StatefulObject): Object held by the robot + target_obj (StatefulObject): Object to sample a pose relative to + world_aligned (bool): Whether to align the current world-aligned bbox to the sampled cuboid on the target_obj + If True, align the current world-aligned bbox; if False, align the base-link aligned bbox + near_poses (Iterable of arrays): Poses in the world frame to sample near + near_poses_threshold (float): The distance threshold to check if the sampled pose is near the poses in near_poses + + Returns: + 2-tuple: + - 3-array: (x,y,z) Position in the world frame + - 4-array: (x,y,z,w) Quaternion orientation in the world frame + """ + pred_map = {object_states.OnTop: "onTop", object_states.Inside: "inside"} + + for _ in range(m.MAX_ATTEMPTS_FOR_SAMPLING_POSE_WITH_OBJECT_AND_PREDICATE): + if world_aligned: + # Take the bbox in the world frame because we want to keep the x-y component of the current orientation + bb_extents = held_obj.aabb_extent + bb_center = held_obj.aabb_center + # Compute bbox pose in the object base link frame + bb_pos_in_base, bb_orn_in_base = T.relative_pose_transform( + bb_center, th.tensor([0, 0, 0, 1], dtype=th.float32), *held_obj.get_position_orientation() + ) + else: + _, _, bb_extents, bb_pos_in_base = held_obj.get_base_aligned_bbox() + bb_orn_in_base = th.tensor([0, 0, 0, 1], dtype=th.float32) + + sampling_results = sample_cuboid_for_predicate(pred_map[predicate], target_obj, bb_extents) + if sampling_results[0][0] is None: + continue + sampled_bb_center = sampling_results[0][0] + th.tensor([0, 0, m.PREDICATE_SAMPLING_Z_OFFSET]) + sampled_bb_orn = sampling_results[0][2] + + # Tobj_in_world @ Tbbox_in_obj = Tbbox_in_world + # Tobj_in_world = Tbbox_in_world @ inv(Tbbox_in_obj) + sampled_obj_pose = T.pose2mat((sampled_bb_center, sampled_bb_orn)) @ T.pose_inv( + T.pose2mat((bb_pos_in_base, bb_orn_in_base)) + ) + + # Check that the pose is near one of the poses in the near_poses list if provided. + if near_poses: + sampled_pos = th.tensor([sampled_obj_pose[0]]) + if not th.any(th.norm(near_poses - sampled_pos, dim=1) < near_poses_threshold): + continue + + # Return the pose + return T.mat2pose(sampled_obj_pose) + + # If we get here, sampling failed. + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.SAMPLING_ERROR, + "Could not find a position to put this object in the desired relation to the target object", + {"target object": target_obj.name, "object in hand": held_obj.name, "relation": pred_map[predicate]}, + ) + + def _validate_poses(self, candidate_poses, eef_pose=None, plan_with_open_gripper=False, skip_obstacle_update=False): + """ + Determines whether the robot can reach all poses on the objects and is not in collision at the specified 2d poses + + Args: + candidate_poses (list of arrays): Candidate 2d poses (x, y, yaw) + eef_pose (Tuple[th.tensor, th.tensor]): target pose to reach for the default end-effector in the world frame + plan_with_open_gripper (bool): Determines whether to plan with the gripper open even though it might be closed now. + This is useful for the placing primitive because we will open-loop open the gripper after placing + skip_obstacle_update (bool): Whether to skip updating the obstacles in the motion generator + + Returns: + list of bool: Whether the default arm can reach all poses on the objects and is not in collision + at the specified 2d poses + """ + # First check collisions for all candidate poses + candidate_joint_positions = [] + if plan_with_open_gripper: + current_joint_pos = self._get_joint_position_with_fingers_at_limit("upper") + else: + current_joint_pos = self.robot.get_joint_positions() + + # For holonomic robots, base joints are relative to root_link, but candidate + # poses are in world frame. Convert (x, y) from world to root_link-relative. + root_pos = self.robot.root_link.get_position_orientation()[0] if self.robot.is_holonomic_base else None + + for pose in candidate_poses: + joint_pos = current_joint_pos.clone() + if root_pos is not None: + joint_pos[self.robot.base_control_idx] = th.tensor( + [pose[0] - root_pos[0], pose[1] - root_pos[1], pose[2]] + ) + else: + joint_pos[self.robot.base_control_idx] = pose + candidate_joint_positions.append(joint_pos) + + candidate_joint_positions = th.stack(candidate_joint_positions) + + # If an object is grasped, we need to pass it to the collision checker + obj_in_hand = self._get_obj_in_hand() + attached_obj = {self.robot.eef_link_names[self.arm]: obj_in_hand.root_link} if obj_in_hand is not None else None + + # No need to check for self-collision here because we are only testing for new base poses + # This assumes the robot doesn't have self collisions currently. + invalid_results = self._motion_generator.check_collisions( + candidate_joint_positions, + self_collision_check=False, + skip_obstacle_update=skip_obstacle_update, + attached_obj=attached_obj, + ).cpu() + + # For each candidate that passed collision check, verify reachability + for i in range(len(candidate_poses)): + if invalid_results[i].item(): + continue + + if eef_pose is not None: + # Use the candidate joint position as the initial joint position to update the lock joints in curobo + # This effectively moves the robot base in curobo when testing for arm reachability to the target eef_pose + candidate_joint_position = candidate_joint_positions[i] + if not self._target_in_reach_of_robot( + eef_pose, initial_joint_pos=candidate_joint_position, skip_obstacle_update=skip_obstacle_update + ): + invalid_results[i] = True + + return ~invalid_results + + def _get_robot_pose_from_2d_pose(self, pose_2d): + """ + Gets 3d pose from 2d pose + + Args: + pose_2d (Iterable): (x, y, yaw) 2d pose in the world frame + + Returns: + th.tensor: (x,y,z) Position in the world frame + th.tensor: (x,y,z,w) Quaternion orientation in the world frame + """ + if self.robot.is_holonomic_base: + base_joints = self.robot.get_joint_positions()[self.robot.base_idx] + # base_joints[2] (z) is relative to root_link; convert to world frame + root_pos = self.robot.root_link.get_position_orientation()[0] + pos = th.tensor([pose_2d[0], pose_2d[1], root_pos[2] + base_joints[2]], dtype=th.float32) + euler_intrinsic_xyz = th.tensor([base_joints[3], base_joints[4], pose_2d[2]], dtype=th.float32) + mat = T.euler_intrinsic2mat(euler_intrinsic_xyz) + orn = T.mat2quat(mat) + else: + pos = th.tensor([pose_2d[0], pose_2d[1], 0.0], dtype=th.float32) + orn = T.euler2quat(th.tensor([0.0, 0.0, pose_2d[2]], dtype=th.float32)) + return pos, orn + + def _world_pose_to_robot_pose(self, pose): + """ + Converts the pose in the world frame to the robot frame + + Args: + pose (Iterable): (pos, quat) Pose in the world frame + + Returns: + 2-tuple: + - 3-array: (x,y,z) Position in the world frame + - 4-array: (x,y,z,w) Quaternion orientation in the world frame + """ + body_pose = self.robot.get_position_orientation() + return T.relative_pose_transform(*pose, *body_pose) + + def _robot_pose_to_world_pose(self, pose): + """ + Converts the pose in the robot frame to the world frame + + Args: + pose (Iterable): (pos, quat) Pose in the robot frame + + Returns: + 2-tuple: + - 3-array: (x,y,z) Position in the world frame + - 4-array: (x,y,z,w) Quaternion orientation in the world frame + """ + body_pose = self.robot.get_position_orientation() + inverse_body_pose = T.invert_pose_transform(body_pose[0], body_pose[1]) + return T.relative_pose_transform(*pose, *inverse_body_pose) + + def _get_hand_pose_for_object_pose(self, desired_pose): + """ + Gets the pose of the hand for the desired object pose + + Args: + desired_pose (Iterable of arrays): Pose of the object in the world frame + + Returns: + 2-tuple: + - 3-array: (x,y,z) Position of the hand in the world frame + - 4-array: (x,y,z,w) Quaternion orientation of the hand in the world frame + """ + obj_in_hand = self._get_obj_in_hand() + + assert obj_in_hand is not None + + # Get the object pose & the robot hand pose + obj_in_world = obj_in_hand.get_position_orientation() + hand_in_world = self.robot.eef_links[self.arm].get_position_orientation() + + # Get the hand pose relative to the obj pose + hand_in_obj = T.relative_pose_transform(*hand_in_world, *obj_in_world) + + # Now apply desired obj pose. + desired_hand_pose = T.pose_transform(*desired_pose, *hand_in_obj) + + return desired_hand_pose + + # Function that is particularly useful for Fetch, where it gives time for the base of robot to settle due to its uneven base. + def _settle_robot(self): + """ + Yields a no op action for a few steps to allow the robot and physics to settle + + Returns: + th.tensor or None: Action array for one step for the robot to do nothing + """ + for _ in range(50): + empty_action = self.robot.q_to_action(self.robot.get_joint_positions()) + yield self._postprocess_action(empty_action) + + for _ in range(m.MAX_STEPS_FOR_SETTLING): + if th.norm(self.robot.get_linear_velocity()) < 0.01: + break + empty_action = self.robot.q_to_action(self.robot.get_joint_positions()) + yield self._postprocess_action(empty_action) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/action_primitives/symbolic_semantic_action_primitives.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/action_primitives/symbolic_semantic_action_primitives.py new file mode 100644 index 0000000000000000000000000000000000000000..2f4bc924ac548dfc91c6c2bf5e66062fadb38261 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/action_primitives/symbolic_semantic_action_primitives.py @@ -0,0 +1,622 @@ +""" +WARNING! +A set of action primitives that work without executing low-level physics but instead teleporting +objects directly into their post-condition states. Useful for learning high-level methods. +""" + +import torch as th +from aenum import IntEnum, auto +from typing import Any + +from omnigibson import object_states +from omnigibson.action_primitives.action_primitive_set_base import ActionPrimitiveError, ActionPrimitiveErrorGroup +from omnigibson.action_primitives.starter_semantic_action_primitives import StarterSemanticActionPrimitives +from omnigibson.objects import DatasetObject +from omnigibson.robots.robot import Robot +from omnigibson.transition_rules import SlicingRule + + +class SymbolicSemanticActionPrimitiveSet(IntEnum): + _init_ = "value __doc__" + GRASP = auto(), "Grasp an object" + PLACE_ON_TOP = auto(), "Place the currently grasped object on top of another object" + PLACE_INSIDE = auto(), "Place the currently grasped object inside another object" + OPEN = auto(), "Open an object" + CLOSE = auto(), "Close an object" + TOGGLE_ON = auto(), "Toggle an object on" + TOGGLE_OFF = auto(), "Toggle an object off" + SOAK_UNDER = auto(), "Soak the currently grasped object under a fluid source." + SOAK_INSIDE = auto(), "Soak the currently grasped object inside the fluid within a container." + WIPE = auto(), "Wipe the given object with the currently grasped object." + CUT = auto(), "Cut (slice or dice) the given object with the currently grasped object." + PLACE_NEAR_HEATING_ELEMENT = ( + auto(), + "Place the currently grasped object near the heating element of another object.", + ) + NAVIGATE_TO = auto(), "Navigate to an object" + RELEASE = ( + auto(), + "Release an object, letting it fall to the ground. You can then grasp it again, as a way of reorienting your grasp of the object.", + ) + + +class SymbolicSemanticActionPrimitives(StarterSemanticActionPrimitives): + def __init__(self, env, robot): + super().__init__(env, robot, skip_curobo_initilization=True) + self.controller_functions = { + SymbolicSemanticActionPrimitiveSet.GRASP: self._grasp, + SymbolicSemanticActionPrimitiveSet.PLACE_ON_TOP: self._place_on_top, + SymbolicSemanticActionPrimitiveSet.PLACE_INSIDE: self._place_inside, + SymbolicSemanticActionPrimitiveSet.OPEN: self._open, + SymbolicSemanticActionPrimitiveSet.CLOSE: self._close, + SymbolicSemanticActionPrimitiveSet.TOGGLE_ON: self._toggle_on, + SymbolicSemanticActionPrimitiveSet.TOGGLE_OFF: self._toggle_off, + SymbolicSemanticActionPrimitiveSet.SOAK_UNDER: self._soak_under, + SymbolicSemanticActionPrimitiveSet.SOAK_INSIDE: self._soak_inside, + SymbolicSemanticActionPrimitiveSet.WIPE: self._wipe, + SymbolicSemanticActionPrimitiveSet.CUT: self._cut, + SymbolicSemanticActionPrimitiveSet.PLACE_NEAR_HEATING_ELEMENT: self._place_near_heating_element, + SymbolicSemanticActionPrimitiveSet.NAVIGATE_TO: self._navigate_to_obj, + SymbolicSemanticActionPrimitiveSet.RELEASE: self._release, + } + + def apply_ref(self, primitive, *args: Any, attempts=3): + """ + Yields action for robot to execute the primitive with the given arguments. + + Args: + primitive (SymbolicSemanticActionPrimitiveSet): Primitive to execute + args: Arguments for the primitive + attempts (int): Number of attempts to make before raising an error + + Returns: + th.tensor or None: Action array for one step for the robot tto execute the primitve or None if primitive completed + + Raises: + ActionPrimitiveError: If primitive fails to execute + """ + assert attempts > 0, "Must make at least one attempt" + ctrl = self.controller_functions[primitive] + + if any(isinstance(arg, Robot) for arg in args): + raise ActionPrimitiveErrorGroup( + [ + ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "Cannot call a symbolic semantic action primitive with a robot as an argument.", + ) + ] + ) + + errors = [] + for _ in range(attempts): + # Attempt + success = False + try: + yield from ctrl(*args) + success = True + except ActionPrimitiveError as e: + errors.append(e) + + try: + # Settle before returning. + yield from self._settle_robot() + except ActionPrimitiveError: + pass + + # Stop on success + if success: + return + + raise ActionPrimitiveErrorGroup(errors) + + def _open_or_close(self, obj, should_open): + if self._get_obj_in_hand(): + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "Cannot open or close an object while holding an object", + {"object in hand": self._get_obj_in_hand().name}, + ) + + if object_states.Open not in obj.states: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object is not openable.", + {"target object": obj.name}, + ) + + # Don't do anything if the object is already closed and we're trying to close. + if should_open == obj.states[object_states.Open].get_value(): + return + + # Set the value + obj.states[object_states.Open].set_value(should_open) + + # Settle + yield from self._settle_robot() + + if obj.states[object_states.Open].get_value() != should_open: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.POST_CONDITION_ERROR, + "The object did not open or close as expected. Maybe try again", + {"target object": obj.name, "is it currently open": obj.states[object_states.Open].get_value()}, + ) + + def _grasp(self, obj: DatasetObject): + """ + Yields action for the robot to navigate to object if needed, then to grasp it + + Args: + DatasetObject: Object for robot to grasp + + Returns: + th.tensor or None: Action array for one step for the robot to grasp or None if grasp completed + """ + # Don't do anything if the object is already grasped. + obj_in_hand = self._get_obj_in_hand() + if obj_in_hand is not None: + if obj_in_hand == obj: + return + else: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "Cannot grasp when your hand is already full", + {"target object": obj.name, "object currently in hand": obj_in_hand.name}, + ) + + # Get close + # yield from self._navigate_if_needed(obj) + + # Perform forced assisted grasp + eef_pos_world = self.robot.get_eef_position(self.arm) + obj.set_position_orientation(position=eef_pos_world) + self.robot._establish_grasp(obj, obj.root_link_name, self.arm, eef_pos_world, "FixedJoint") + + # Execute for a moment + yield from self._settle_robot() + + # Verify + if self._get_obj_in_hand() is None: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.POST_CONDITION_ERROR, + "Grasp completed, but no object detected in hand after executing grasp", + {"target object": obj.name}, + ) + + if self._get_obj_in_hand() != obj: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.POST_CONDITION_ERROR, + "An unexpected object was detected in hand after executing grasp. Consider releasing it", + {"expected object": obj.name, "actual object": self._get_obj_in_hand().name}, + ) + + def _release(self): + if not self._get_obj_in_hand(): + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "Cannot release an object if you're not already holding an object", + ) + + for arm in self.robot.arm_names: + self.robot.release_grasp_immediately(arm=arm) + yield from self._settle_robot() + + def _toggle(self, obj, value): + if self._get_obj_in_hand(): + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "Cannot toggle an object while holding an object", + {"object in hand": self._get_obj_in_hand()}, + ) + + if object_states.ToggledOn not in obj.states: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object is not toggleable.", + {"target object": obj.name}, + ) + + if obj.states[object_states.ToggledOn].get_value() == value: + return + + # Call the setter + obj.states[object_states.ToggledOn].set_value(value) + + # Yield some actions + yield from self._settle_robot() + + # Check that it actually happened + if obj.states[object_states.ToggledOn].get_value() != value: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.POST_CONDITION_ERROR, + "The object did not toggle as expected - maybe try again", + { + "target object": obj.name, + "is it currently toggled on": obj.states[object_states.ToggledOn].get_value(), + }, + ) + + def _place_with_predicate(self, obj, predicate, near_poses=None, near_poses_threshold=None): + """ + Yields action for the robot to navigate to the object if needed, then to place it + + Args: + obj (StatefulObject): Object for robot to place the object in its hand on + predicate (object_states.OnTop or object_states.Inside): Determines whether to place on top or inside + + Returns: + th.tensor or None: Action array for one step for the robot to place or None if place completed + """ + obj_in_hand = self._get_obj_in_hand() + if obj_in_hand is None: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "You need to be grasping an object first to place it somewhere.", + ) + + # Find a spot to put it + obj_pose = self._sample_pose_with_object_and_predicate( + predicate, obj_in_hand, obj, near_poses=near_poses, near_poses_threshold=near_poses_threshold + ) + + # Get close, release the object. + # yield from self._navigate_if_needed(obj, pose_on_obj=obj_pose) + yield from self._release() + + # Actually move the object to the spot and step a bit to settle it. + obj_in_hand.set_position_orientation(*obj_pose) + yield from self._settle_robot() + + if not obj_in_hand.states[predicate].get_value(obj): + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.EXECUTION_ERROR, + "Failed to place object at the desired place (probably dropped). The object was still released, so you need to grasp it again to continue", + {"dropped object": obj_in_hand.name, "target object": obj.name}, + ) + + def _soak_under(self, obj): + # Check that our current object is a particle remover + obj_in_hand = self._get_obj_in_hand() + if obj_in_hand is None: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, "You need to be grasping a soakable object first." + ) + + # Check that the target object is a particle source + if object_states.ParticleSource not in obj.states: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object is not a particle source, so you can not soak anything under it.", + {"target object": obj.name}, + ) + + # Check if the target object has any particles in it + producing_systems = { + ps + for ps in obj.scene.system_registry.objects + if obj.states[object_states.ParticleSource].check_conditions_for_system(ps.name) + } + if not producing_systems: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object currently is not producing any particles - try toggling it on.", + {"target object": obj.name}, + ) + + # Check that the current object can remove those particles + if object_states.Saturated not in obj_in_hand.states: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The currently grasped object cannot soak particles.", + {"object in hand": obj_in_hand.name}, + ) + + supported_systems = { + x for x in producing_systems if obj_in_hand.states[object_states.ParticleRemover].supports_system(x.name) + } + + if not supported_systems: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object only contains particles that this object cannot soak.", + { + "target object": obj.name, + "cleaning tool": obj_in_hand.name, + "particles the target object is producing": sorted(x.name for x in producing_systems), + "particles the grasped object can remove": sorted( + [x for x in obj_in_hand.states[object_states.ParticleRemover].conditions.keys()] + ), + }, + ) + + currently_removable_systems = { + x + for x in supported_systems + if obj_in_hand.states[object_states.ParticleRemover].check_conditions_for_system(x.name) + } + if not currently_removable_systems: + # TODO: This needs to be far more descriptive. + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object is covered by some particles that this object can normally soak, but needs to be in a different state to do so (e.g. toggled on, soaked by another fluid first, etc.).", + { + "target object": obj.name, + "cleaning tool": obj_in_hand.name, + "particles the target object is producing": sorted(x.name for x in producing_systems), + }, + ) + + # If so, remove the particles. + for system in currently_removable_systems: + obj_in_hand.states[object_states.Saturated].set_value(system, True) + + # Yield some actions + yield from self._settle_robot() + + def _soak_inside(self, obj): + # Check that our current object is a particle remover + obj_in_hand = self._get_obj_in_hand() + if obj_in_hand is None: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, "You need to be grasping a soakable object first." + ) + + # Check that the target object is fillable + if object_states.Contains not in obj.states: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object is not fillable by particles, so you can not soak anything in it.", + {"target object": obj.name}, + ) + + # Check if the target object has any particles in it + contained_systems = { + ps for ps in obj.scene.system_registry.objects if obj.states[object_states.Contains].get_value(ps.states) + } + if not contained_systems: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object currently does not contain any particles.", + {"target object": obj.name}, + ) + + # Check that the current object can remove those particles + if object_states.Saturated not in obj_in_hand.states: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The currently grasped object cannot soak particles.", + {"object in hand": obj_in_hand.name}, + ) + + supported_systems = { + x for x in contained_systems if obj_in_hand.states[object_states.ParticleRemover].supports_system(x.name) + } + if not supported_systems: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object only contains particles that this object cannot soak.", + { + "target object": obj.name, + "cleaning tool": obj_in_hand.name, + "particles the target object contains": sorted(x.name for x in contained_systems), + "particles the grasped object can remove": sorted( + [x for x in obj_in_hand.states[object_states.ParticleRemover].conditions.keys()] + ), + }, + ) + + currently_removable_systems = { + x + for x in supported_systems + if obj_in_hand.states[object_states.ParticleRemover].check_conditions_for_system(x.name) + } + if not currently_removable_systems: + # TODO: This needs to be far more descriptive. + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object is covered by some particles that this object can normally soak, but needs to be in a different state to do so (e.g. toggled on, soaked by another fluid first, etc.).", + { + "target object": obj.name, + "cleaning tool": obj_in_hand.name, + "particles the target object contains": sorted(x.name for x in contained_systems), + }, + ) + + # If so, remove the particles. + for system in currently_removable_systems: + obj_in_hand.states[object_states.Saturated].set_value(system, True) + + # Yield some actions + yield from self._settle_robot() + + def _wipe(self, obj): + # Check that our current object is a particle remover + obj_in_hand = self._get_obj_in_hand() + if obj_in_hand is None: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "You need to be grasping a wiping tool (particle remover) first to wipe an object.", + ) + + # Check that the target object is coverable + if object_states.Covered not in obj.states: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object is not coverable by any particles, so there is no need to wipe it.", + {"target object": obj.name}, + ) + + # Check if the target object has any particles on it + covering_systems = { + ps for ps in obj.scene.system_registry.objects if obj.states[object_states.Covered].get_value(ps) + } + if not covering_systems: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object is not covered by any particles.", + {"target object": obj.name}, + ) + + # Check that the current object can remove those particles + if object_states.ParticleRemover not in obj_in_hand.states: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The currently grasped object is not a particle remover.", + {"object in hand": obj_in_hand.name}, + ) + + supported_systems = { + x for x in covering_systems if obj_in_hand.states[object_states.ParticleRemover].supports_system(x.name) + } + if not supported_systems: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object is covered only by particles that this cleaning tool cannot remove.", + { + "target object": obj.name, + "cleaning tool": obj_in_hand.name, + "particles the target object is covered by": sorted(x.name for x in covering_systems), + "particles the grasped object can remove": sorted( + [x for x in obj_in_hand.states[object_states.ParticleRemover].conditions.keys()] + ), + }, + ) + + currently_removable_systems = { + x + for x in supported_systems + if obj_in_hand.states[object_states.ParticleRemover].check_conditions_for_system(x.name) + } + if not currently_removable_systems: + # TODO: This needs to be far more descriptive. + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object is covered by some particles that this cleaning tool can normally remove, but needs to be in a different state to do so (e.g. toggled on, soaked by another fluid first, etc.).", + { + "target object": obj.name, + "cleaning tool": obj_in_hand.name, + "particles the target object is covered by": sorted(x.name for x in covering_systems), + }, + ) + # If so, remove the particles on the target object + for system in currently_removable_systems: + obj.states[object_states.Covered].set_value(system, False) + + # Yield some actions + yield from self._settle_robot() + + def _cut(self, obj): + # Check that our current object is a slicer + obj_in_hand = self._get_obj_in_hand() + if obj_in_hand is None: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "You need to be grasping a cutting tool first to slice an object.", + ) + + if "slicer" not in obj_in_hand._abilities: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The current object is not a cutting tool.", + {"object in hand": obj_in_hand.name}, + ) + + # Check that the target object is sliceable + if "sliceable" not in obj._abilities and "diceable" not in obj._abilities: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object is not sliceable or diceable.", + {"target object": obj.name}, + ) + + # Get close + # yield from self._navigate_if_needed(obj) + + # TODO: Do some more validation + added_obj_attrs = [] + removed_objs = [] + (slicing_rule,) = [rule for rule in obj.scene.transition_rule_api.active_rules if isinstance(rule, SlicingRule)] + output = slicing_rule.transition({"sliceable": [obj]}) + added_obj_attrs += output.add + removed_objs += output.remove + + obj.scene.transition_rule_api.execute_transition(added_obj_attrs=added_obj_attrs, removed_objs=removed_objs) + yield from self._settle_robot() + + def _place_near_heating_element(self, heat_source_obj): + obj_in_hand = self._get_obj_in_hand() + if obj_in_hand is None: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "You need to be grasping an object first to place it somewhere.", + ) + + if object_states.HeatSourceOrSink not in heat_source_obj.states: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The target object is not a heat source or sink.", + {"target object": heat_source_obj.name}, + ) + + if heat_source_obj.states[object_states.HeatSourceOrSink].requires_inside: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "The heat source object has no explicit heating element, it just requires the cookable object to be placed inside it.", + {"target object": heat_source_obj.name}, + ) + + # Get the position of the heat source on the thing we're placing near + heating_element_positions = th.tensor( + [ + link.get_position_orientation()[0] + for link in heat_source_obj.states[object_states.HeatSourceOrSink].links.values() + ] + ) + heating_distance_threshold = heat_source_obj.states[object_states.HeatSourceOrSink].distance_threshold + + # Call place-with-predicate + yield from self._place_with_predicate( + heat_source_obj, + object_states.OnTop, + near_poses=heating_element_positions, + near_poses_threshold=heating_distance_threshold, + ) + + def _wait_for_cooked(self, obj): + # Check that the current object is cookable + if object_states.Cooked not in obj.states: + raise ActionPrimitiveError( + ActionPrimitiveError.Reason.PRE_CONDITION_ERROR, + "Target object is not cookable.", + {"target object": obj.name}, + ) + + # Keep waiting as long as the thing is warming up. + prev_temp = obj.states[object_states.Temperature].get_value() + while not obj.states[object_states.Cooked].get_value(): + # Pass some time + for _ in range(10): + yield from self._empty_action() + + # Check that we are still heating up + new_temp = obj.states[object_states.Temperature].get_value() + if new_temp - prev_temp < 1e-2: + raise ActionPrimitiveError( + ActionPrimitiveError.PRE_CONDITION_ERROR, + "Target object is not currently heating up.", + {"target object": obj.name}, + ) + + def _navigate_to_pose(self, pose_2d): + """ + Yields the action to navigate robot to the specified 2d pose + + Args: + pose_2d (Iterable): (x, y, yaw) 2d pose + + Returns: + th.tensor or None: Action array for one step for the robot to navigate or None if it is done navigating + """ + robot_pose = self._get_robot_pose_from_2d_pose(pose_2d) + self.robot.set_position_orientation(*robot_pose) + yield from self._settle_robot() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/avg_category_specs.json b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/avg_category_specs.json new file mode 100644 index 0000000000000000000000000000000000000000..6c1c46f506b386a153589bb91d150bc099024c3e --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/avg_category_specs.json @@ -0,0 +1,9127 @@ +{ + "ceilings": { + "mass": 2000.0, + "volume": 2.049506745528556, + "density": 975.844555946661 + }, + "walls": { + "mass": 2000.0, + "volume": 0.8257256371381512, + "density": 2422.1120309788594 + }, + "floors": { + "mass": 2000.0, + "volume": 4.202978695726735, + "density": 475.8529949327238 + }, + "armchair": { + "mass": 20.0, + "volume": 0.08338315221811032, + "density": 239.85660733579365 + }, + "bathtub": { + "mass": 110.0, + "volume": 0.24395564798785854, + "density": 450.90163276512703 + }, + "bed": { + "mass": 50.0, + "volume": 1.3161169053882489, + "density": 37.990546124966166 + }, + "bench": { + "mass": 25.0, + "volume": 0.17590564975337367, + "density": 142.1216432505206 + }, + "bottom_cabinet": { + "mass": 50.0, + "volume": 0.022965389239366214, + "density": 2177.1893120928385 + }, + "bottom_cabinet_no_top": { + "mass": 40.0, + "volume": 0.045932306362725196, + "density": 870.84675618337 + }, + "breakfast_table": { + "mass": 18.0, + "volume": 0.07168814910614167, + "density": 251.08752596400765 + }, + "burner": { + "mass": 0.5, + "volume": 0.011834090390862162, + "density": 42.25081805916246 + }, + "carpet": { + "mass": 8.0, + "volume": 0.014290755065373494, + "density": 559.8024711363225 + }, + "chaise_longue": { + "mass": 25.0, + "volume": 0.026702239838261865, + "density": 936.2510467821238 + }, + "coffee_maker": { + "mass": 3.0, + "volume": 0.010983397662690058, + "density": 273.13952313598 + }, + "coffee_table": { + "mass": 22.5, + "volume": 0.037415965006639844, + "density": 601.3475797298598 + }, + "console_table": { + "mass": 20.0, + "volume": 0.028800087361872742, + "density": 694.4423379241961 + }, + "countertop": { + "mass": 221.126, + "volume": 0.07598052940035455, + "density": 2910.298226995088 + }, + "crib": { + "mass": 30.0, + "volume": 0.235268763474665, + "density": 127.51374027275219 + }, + "desk": { + "mass": 37.5, + "volume": 0.10622511878526202, + "density": 353.02384623177153 + }, + "dishwasher": { + "mass": 50.0, + "volume": 0.10401114128846511, + "density": 480.71773254876325 + }, + "door": { + "mass": 20.0, + "volume": 0.12247368207354925, + "density": 163.30038961341407 + }, + "sliding_door": { + "mass": 20.0, + "volume": 0.21260078181945122, + "density": 94.07303128821404 + }, + "floor_lamp": { + "mass": 5.0, + "volume": 0.014093647704271794, + "density": 354.7697590372219 + }, + "folding_chair": { + "mass": 5.0, + "volume": 0.009899407026768548, + "density": 505.0807575120127 + }, + "fridge": { + "mass": 75.0, + "volume": 0.23908442092754567, + "density": 313.6967256546117 + }, + "gaming_table": { + "mass": 45.25, + "volume": 0.10400401526751502, + "density": 435.07935615379597 + }, + "grandfather_clock": { + "mass": 31.5, + "volume": 0.0324558055713858, + "density": 970.5505516021309 + }, + "guitar": { + "mass": 3.0, + "volume": 0.005521784079779874, + "density": 543.3026638954697 + }, + "highchair": { + "mass": 7.5, + "volume": 0.009030767132395884, + "density": 830.4942304508556 + }, + "laptop": { + "mass": 1.5, + "volume": 0.00239957527746424, + "density": 625.1106244039697 + }, + "loudspeaker": { + "mass": 1.75, + "volume": 0.0010749318545967557, + "density": 1628.0101780558787 + }, + "microwave": { + "mass": 13.5, + "volume": 0.028750610596187224, + "density": 469.55524491679176 + }, + "mirror": { + "mass": 4.511, + "volume": 0.00903646545542408, + "density": 499.19960655549244 + }, + "monitor": { + "mass": 3.8, + "volume": 0.009254524032734832, + "density": 410.60998778097616 + }, + "oven": { + "mass": 47.0, + "volume": 0.08435044880911374, + "density": 557.1991692226993 + }, + "pedestal_table": { + "mass": 20.25, + "volume": 0.02941334825181562, + "density": 688.4629327689687 + }, + "piano": { + "mass": 260.0, + "volume": 0.5156960152632958, + "density": 504.1729862257194 + }, + "picture": { + "mass": 0.472, + "volume": 0.005395903810837677, + "density": 87.4737609391753 + }, + "pillow": { + "mass": 1.069, + "volume": 0.025050557845665955, + "density": 42.67370038567623 + }, + "pool_table": { + "mass": 283.75, + "volume": 0.41456414400060587, + "density": 684.4537910629948 + }, + "pot_plant": { + "mass": 1.5, + "volume": 0.013452350896132368, + "density": 111.50467391028724 + }, + "rail_fence": { + "mass": 4.799, + "volume": 2.7647635622103737, + "density": 1.7357722973472982 + }, + "range_hood": { + "mass": 15.25, + "volume": 0.040576942253298255, + "density": 375.8292062719541 + }, + "rocking_chair": { + "mass": 12.25, + "volume": 0.015312423538302922, + "density": 800.0039947535091 + }, + "shelf": { + "mass": 6.86, + "volume": 0.024246124696669563, + "density": 282.9318122306897 + }, + "commercial_kitchen_shelf": { + "mass": 50.0, + "volume": 0.13094433905842515, + "density": 381.8416310283627 + }, + "shower": { + "mass": 4.0, + "volume": 0.025357195563636477, + "density": 157.74615098746196 + }, + "sofa": { + "mass": 49.95, + "volume": 1.2476829177700286, + "density": 40.03421004534962 + }, + "stand": { + "mass": 10.115, + "volume": 0.06304538231538509, + "density": 160.43998193871872 + }, + "standing_tv": { + "mass": 10.5, + "volume": 0.017482069699975195, + "density": 600.6153836587723 + }, + "stove": { + "mass": 50.0, + "volume": 0.10364785860601862, + "density": 482.40263399997156 + }, + "straight_chair": { + "mass": 5.0, + "volume": 0.01663165172081144, + "density": 300.6315959432594 + }, + "swivel_chair": { + "mass": 13.75, + "volume": 0.040080623839351105, + "density": 343.0585325994918 + }, + "table_lamp": { + "mass": 1.5, + "volume": 0.0011507458173564474, + "density": 1303.502456733562 + }, + "toilet": { + "mass": 30.0, + "volume": 0.033053544775232015, + "density": 907.6182359260866 + }, + "top_cabinet": { + "mass": 25.0, + "volume": 0.02056306714222912, + "density": 1215.77193845071 + }, + "towel_rack": { + "mass": 1.792, + "volume": 0.00033526682886532894, + "density": 5344.996419910711 + }, + "trash_can": { + "mass": 3.75, + "volume": 0.008772401544415507, + "density": 427.4770119691161 + }, + "treadmill": { + "mass": 83.09, + "volume": 0.15700281214752132, + "density": 529.2261894132689 + }, + "wall_clock": { + "mass": 1.5, + "volume": 0.004496521177964841, + "density": 333.5912232217955 + }, + "wall_mounted_tv": { + "mass": 11.25, + "volume": 0.049087980183450335, + "density": 229.18034023719838 + }, + "washer": { + "mass": 70.0, + "volume": 0.07067668237507721, + "density": 990.4256630003359 + }, + "openable_window": { + "mass": 20.0, + "volume": 0.04454008300688002, + "density": 449.0337388215159 + }, + "apple": { + "mass": 0.163, + "volume": 0.0002085242064750455, + "density": 781.6838282490073 + }, + "apricot": { + "mass": 0.06, + "volume": 0.0003855006241149206, + "density": 155.64177136614325 + }, + "artichoke": { + "mass": 0.25, + "volume": 9.657364036556011e-05, + "density": 2588.698106995607 + }, + "banana": { + "mass": 0.12, + "volume": 0.00023010380003534033, + "density": 521.5037734342931 + }, + "beet": { + "mass": 0.222, + "volume": 0.0002390935395755088, + "density": 928.5068948083792 + }, + "bell_pepper": { + "mass": 0.15, + "volume": 0.00018619058455818601, + "density": 805.6261295700687 + }, + "bowl": { + "mass": 0.5, + "volume": 0.00041911672625917956, + "density": 1192.985077123366 + }, + "broccoli": { + "mass": 0.036, + "volume": 5.107689225881101e-06, + "density": 7048.197023731377 + }, + "bucket": { + "mass": 1.55, + "volume": 0.001899842728403441, + "density": 815.8570058599345 + }, + "bulldog_clip": { + "mass": 0.028, + "volume": 4.6832073116737864e-07, + "density": 59788.08567838683 + }, + "bulletin_board": { + "mass": 2.0, + "volume": 0.026054318119283375, + "density": 76.76270746536083 + }, + "butter": { + "mass": 0.071, + "volume": 2.2040900778288554e-05, + "density": 3221.283953600423 + }, + "caliper": { + "mass": 0.2, + "volume": 3.5703841844428776e-05, + "density": 5601.63807781397 + }, + "canned_food": { + "mass": 0.443, + "volume": 0.000717732336277101, + "density": 617.221737978052 + }, + "cantaloup": { + "mass": 1.225, + "volume": 0.0020526294451320656, + "density": 596.7954921942494 + }, + "carafe": { + "mass": 1.35, + "volume": 0.0006757093451152613, + "density": 1997.900443081366 + }, + "carrot": { + "mass": 0.065, + "volume": 7.783006353626228e-05, + "density": 835.1528579918922 + }, + "carving_knife": { + "mass": 0.245, + "volume": 6.145575573493691e-05, + "density": 3986.6078786290186 + }, + "casserole": { + "mass": 1.643, + "volume": 0.001053403155066439, + "density": 1559.706739150952 + }, + "cherry": { + "mass": 0.005, + "volume": 5.54609458782269e-07, + "density": 9015.352913342436 + }, + "chestnut": { + "mass": 0.012, + "volume": 4.886924700064221e-06, + "density": 2455.5320035609107 + }, + "chip": { + "mass": 0.003, + "volume": 9.361387595506953e-06, + "density": 320.4653123688486 + }, + "chives": { + "mass": 0.006, + "volume": 4.824791864152753e-05, + "density": 124.35769601956947 + }, + "chopping_board": { + "mass": 1.65, + "volume": 0.001739423404395618, + "density": 948.5902028398374 + }, + "garlic_clove": { + "mass": 0.005, + "volume": 3.1461630051045654e-07, + "density": 15892.374272685915 + }, + "coatrack": { + "mass": 5.0, + "volume": 0.00817858398161497, + "density": 611.3527734433906 + }, + "colander": { + "mass": 0.5, + "volume": 0.0008329645796633445, + "density": 600.2656201804916 + }, + "cruet": { + "mass": 0.375, + "volume": 0.00068943454888437, + "density": 543.9240035284248 + }, + "cucumber": { + "mass": 0.18, + "volume": 0.00011626379819503392, + "density": 1548.2033340941418 + }, + "digital_scale": { + "mass": 1.0, + "volume": 0.002681756603749173, + "density": 372.8899179746481 + }, + "dinner_napkin": { + "mass": 0.031, + "volume": 0.0003261548997848811, + "density": 95.04686276504316 + }, + "dipper": { + "mass": 0.075, + "volume": 4.31724836430919e-05, + "density": 1737.2176365860034 + }, + "dish_rack": { + "mass": 2.25, + "volume": 0.0022892553889200806, + "density": 982.8523330729829 + }, + "egg": { + "mass": 0.058, + "volume": 9.327128902059112e-05, + "density": 621.8419473885 + }, + "eggplant": { + "mass": 0.325, + "volume": 0.0005117019785300655, + "density": 635.1353202377824 + }, + "frying_pan": { + "mass": 1.45, + "volume": 0.0017377199644919013, + "density": 834.4267371204262 + }, + "gooseberry": { + "mass": 0.005, + "volume": 1.180149927677323e-06, + "density": 4236.749825372274 + }, + "grape": { + "mass": 0.11, + "volume": 0.000413676497333416, + "density": 265.9082657803059 + }, + "grater": { + "mass": 0.275, + "volume": 0.00026469143540315077, + "density": 1038.945591802577 + }, + "half_apple": { + "mass": 0.102, + "volume": 0.00019545961291153182, + "density": 521.8469354391224 + }, + "half_chestnut": { + "mass": 0.005, + "volume": 1.1687054905640932e-06, + "density": 4278.2377941825835 + }, + "half_coconut_fruit": { + "mass": 0.475, + "volume": 0.0010617745241170784, + "density": 447.36428423444005 + }, + "half_lemon": { + "mass": 0.055, + "volume": 0.00011167797232135347, + "density": 492.4874517038817 + }, + "half_mushroom": { + "mass": 0.013, + "volume": 5.324532940531821e-06, + "density": 2441.528702177875 + }, + "half_orange": { + "mass": 0.084, + "volume": 0.00018180196321429992, + "density": 462.04121514895087 + }, + "half_pineapple": { + "mass": 0.55, + "volume": 0.0009604414410097969, + "density": 572.6533409696863 + }, + "half_plum": { + "mass": 0.053, + "volume": 1.6691399664956034e-05, + "density": 3175.2879365338476 + }, + "half_pomegranate": { + "mass": 0.238, + "volume": 0.00017289199184011202, + "density": 1376.5819773775231 + }, + "half_pomelo": { + "mass": 0.353, + "volume": 0.00011447184803295429, + "density": 3083.727624440709 + }, + "half_beefsteak_tomato": { + "mass": 0.133, + "volume": 7.471603098912112e-05, + "density": 1780.0731414569545 + }, + "head_cabbage": { + "mass": 1.135, + "volume": 0.0017915657550725793, + "density": 633.5240539100499 + }, + "honing_steel": { + "mass": 0.405, + "volume": 7.566616152927504e-05, + "density": 5352.458639563823 + }, + "kettle": { + "mass": 1.365, + "volume": 0.000791634233215614, + "density": 1724.2811676490762 + }, + "kitchen_analog_scale": { + "mass": 1.5, + "volume": 0.0014682021864036777, + "density": 1021.657653074479 + }, + "kiwi": { + "mass": 0.078, + "volume": 0.0005522296036694467, + "density": 141.24559690698726 + }, + "lemon": { + "mass": 0.118, + "volume": 0.00023870882088158617, + "density": 494.32609806461676 + }, + "lettuce": { + "mass": 0.143, + "volume": 0.0012012552811152346, + "density": 119.04214054088493 + }, + "lid": { + "mass": 0.346, + "volume": 0.00038464619583820794, + "density": 899.5279395549682 + }, + "mug": { + "mass": 0.3, + "volume": 0.00017696155077084693, + "density": 1695.283516069993 + }, + "mushroom": { + "mass": 0.017, + "volume": 1.140811397728985e-05, + "density": 1490.1674399328342 + }, + "olive": { + "mass": 0.004, + "volume": 4.707602164175861e-06, + "density": 849.6894725810506 + }, + "bottle_of_olive_oil": { + "mass": 0.65, + "volume": 0.0005884192299163445, + "density": 1104.6545846103813 + }, + "orange": { + "mass": 0.145, + "volume": 0.0003254713164597514, + "density": 445.5077687865347 + }, + "paper_clip": { + "mass": 0.001, + "volume": 4.0552311342663924e-08, + "density": 24659.506866330667 + }, + "paper_towel": { + "mass": 0.021, + "volume": 7.347601308593121e-05, + "density": 285.80755974661025 + }, + "paper_towel_holder": { + "mass": 0.5, + "volume": 0.00033614250151111497, + "density": 1487.464387134237 + }, + "parsley": { + "mass": 0.006, + "volume": 2.082794183549663e-06, + "density": 2880.7455135938226 + }, + "peach": { + "mass": 0.15, + "volume": 0.00039761987642602734, + "density": 377.24472264380324 + }, + "pear": { + "mass": 0.174, + "volume": 0.00025432478219679345, + "density": 684.1645493491897 + }, + "pen": { + "mass": 0.05, + "volume": 1.1604410275345979e-05, + "density": 4308.7066738950925 + }, + "pencil": { + "mass": 0.05, + "volume": 3.20298626024316e-06, + "density": 15610.43224587675 + }, + "pepper_grinder": { + "mass": 0.25, + "volume": 0.00015336478818383723, + "density": 1630.1003832791585 + }, + "pineapple": { + "mass": 1.3, + "volume": 0.0014478213528610552, + "density": 897.9008338501543 + }, + "plum": { + "mass": 0.079, + "volume": 4.0422998974572206e-05, + "density": 1954.332978849352 + }, + "pomegranate": { + "mass": 0.475, + "volume": 0.00027378282077572536, + "density": 1734.9518083499684 + }, + "pomelo": { + "mass": 0.952, + "volume": 0.0002263340824775438, + "density": 4206.171644937543 + }, + "pop_case": { + "mass": 6.75, + "volume": 0.006446524218749723, + "density": 1047.0758770078949 + }, + "potato": { + "mass": 0.187, + "volume": 0.00021601408570241554, + "density": 865.6842880959819 + }, + "pumpkin": { + "mass": 1.65, + "volume": 0.0010201587025884247, + "density": 1617.3954070219602 + }, + "radish": { + "mass": 0.083, + "volume": 2.9543555395346468e-05, + "density": 2809.411355177437 + }, + "raspberry": { + "mass": 0.004, + "volume": 1.795549539758634e-06, + "density": 2227.7302360243975 + }, + "rosehip": { + "mass": 0.011, + "volume": 6.748160064587276e-05, + "density": 163.00739601191972 + }, + "saucepan": { + "mass": 1.25, + "volume": 0.0004268705170184748, + "density": 2928.2884391519137 + }, + "soup_ladle": { + "mass": 0.212, + "volume": 0.00018367494642821232, + "density": 1154.2129404287496 + }, + "spatula": { + "mass": 0.13, + "volume": 0.00010987874077708626, + "density": 1183.1224045762797 + }, + "spinach": { + "mass": 0.006, + "volume": 4.353612902715414e-06, + "density": 1378.1657060639704 + }, + "sticky_note": { + "mass": 0.02, + "volume": 3.7968711582037996e-05, + "density": 526.7495041749448 + }, + "straight_pin": { + "mass": 0.001, + "volume": 1.6871080990997296e-08, + "density": 59273.02468250953 + }, + "strawberry": { + "mass": 0.016, + "volume": 2.4909476451111947e-05, + "density": 642.3258245271458 + }, + "sweet_corn": { + "mass": 0.275, + "volume": 0.0005797142801820558, + "density": 474.3716161582874 + }, + "table_knife": { + "mass": 0.078, + "volume": 1.1446892196533303e-05, + "density": 6814.076577363273 + }, + "tablefork": { + "mass": 0.046, + "volume": 1.641020418857141e-05, + "density": 2803.133920297949 + }, + "teapot": { + "mass": 1.1, + "volume": 0.0006905234075239319, + "density": 1592.9945140373488 + }, + "thumbtack": { + "mass": 0.002, + "volume": 2.1365691868288893e-08, + "density": 93608.01477102708 + }, + "toasting_fork": { + "mass": 0.15, + "volume": 0.00010965035924822403, + "density": 1367.9845741356246 + }, + "tongs": { + "mass": 0.125, + "volume": 6.1433098158471e-05, + "density": 2034.7337794612558 + }, + "vidalia_onion": { + "mass": 0.267, + "volume": 0.00025479732485515305, + "density": 1047.8916925512617 + }, + "walnut": { + "mass": 0.016, + "volume": 9.172339816290268e-06, + "density": 1744.374970886236 + }, + "watermelon": { + "mass": 5.148, + "volume": 0.017937296315662214, + "density": 286.9997746262879 + }, + "whiteboard": { + "mass": 9.04, + "volume": 0.015543399318432615, + "density": 581.5973594192899 + }, + "bottle_of_wine": { + "mass": 1.215, + "volume": 0.0012329327811299241, + "density": 985.4551834419639 + }, + "zucchini": { + "mass": 0.273, + "volume": 0.00040831525454931616, + "density": 668.6010305966347 + }, + "gym_shoe": { + "mass": 0.4, + "volume": 0.0022721009423888787, + "density": 176.048516391812 + }, + "video_game": { + "mass": 0.055, + "volume": 2.8559817748640377e-05, + "density": 1925.7825972162702 + }, + "board_game": { + "mass": 0.725, + "volume": 0.0008476446133425257, + "density": 855.3112809165389 + }, + "walker": { + "mass": 0.5, + "volume": 0.0005275196674711705, + "density": 947.8319593218304 + }, + "sandal": { + "mass": 0.475, + "volume": 0.00045467193442971093, + "density": 1044.7093036340284 + }, + "hat": { + "mass": 0.225, + "volume": 0.0062397474299115754, + "density": 36.05915183704615 + }, + "bottle_of_protein_powder": { + "mass": 1.2, + "volume": 0.004056890772990049, + "density": 295.793026519066 + }, + "keyboard": { + "mass": 0.635, + "volume": 0.0008585560379955168, + "density": 739.6139237254026 + }, + "headset": { + "mass": 0.265, + "volume": 4.442503128472321e-05, + "density": 5965.105534796274 + }, + "mouse": { + "mass": 0.093, + "volume": 0.00010533845054442862, + "density": 882.8685016662114 + }, + "hard_drive": { + "mass": 0.35, + "volume": 0.00018666922274992542, + "density": 1874.9743254081225 + }, + "hammer": { + "mass": 0.867, + "volume": 0.0003954488724928832, + "density": 2192.4452446519576 + }, + "bath_towel": { + "mass": 0.5, + "volume": 0.013723456585505684, + "density": 36.433969596849636 + }, + "dishtowel": { + "mass": 0.123, + "volume": 0.0006781745735888513, + "density": 181.36922967945085 + }, + "hand_towel": { + "mass": 0.125, + "volume": 0.0024242525618073376, + "density": 51.56228437964795 + }, + "envelope": { + "mass": 0.006, + "volume": 4.895265985109068e-06, + "density": 1225.6739507621091 + }, + "box_of_chocolates": { + "mass": 0.4, + "volume": 0.0009340426730656594, + "density": 428.24595870672994 + }, + "box_of_crackers": { + "mass": 0.232, + "volume": 0.001770224517749137, + "density": 131.0568222696356 + }, + "t_shirt": { + "mass": 0.25, + "volume": 0.022916283322769626, + "density": 10.909273396511027 + }, + "candy_cane": { + "mass": 0.023, + "volume": 2.4729767072776635e-06, + "density": 9300.532403849116 + }, + "folderal": { + "mass": 0.125, + "volume": 0.00019474370257235052, + "density": 641.8692792058856 + }, + "light_bulb": { + "mass": 0.07, + "volume": 0.00019723178633548888, + "density": 354.91236631062526 + }, + "wall_socket": { + "mass": 0.1, + "volume": 1.7066912884782567e-05, + "density": 5859.290468937904 + }, + "bell": { + "mass": 0.225, + "volume": 2.026737077282335e-05, + "density": 11101.587991951279 + }, + "baseboard": { + "mass": 2.277, + "volume": 0.15855326191736774, + "density": 14.361104732028098 + }, + "plywood": { + "mass": 0.079, + "volume": 8.54180948712697e-05, + "density": 924.8625846673102 + }, + "tile": { + "mass": 0.915, + "volume": 0.00026441828954022024, + "density": 3460.4262874214714 + }, + "clout_nail": { + "mass": 0.01, + "volume": 6.620498107843105e-07, + "density": 15104.603667439012 + }, + "hinge": { + "mass": 0.045, + "volume": 1.5216089349194933e-05, + "density": 2957.395883218897 + }, + "screwdriver": { + "mass": 0.125, + "volume": 3.171949977697749e-05, + "density": 3940.7935458908764 + }, + "pocketknife": { + "mass": 0.068, + "volume": 2.5977862330616885e-05, + "density": 2617.6133792139176 + }, + "hardback": { + "mass": 0.8, + "volume": 0.0009539525277055248, + "density": 838.6161541226627 + }, + "notebook": { + "mass": 0.475, + "volume": 0.0003540765081532828, + "density": 1341.5179743988222 + }, + "hairbrush": { + "mass": 0.075, + "volume": 0.00010442921623007398, + "density": 718.1898199327974 + }, + "chili": { + "mass": 0.015, + "volume": 7.589263153060116e-06, + "density": 1976.4764638516656 + }, + "hamburger": { + "mass": 0.215, + "volume": 0.0004447533579145877, + "density": 483.41400053305387 + }, + "tray": { + "mass": 0.581, + "volume": 0.0005421830632978356, + "density": 1071.5937832252816 + }, + "toothpick": { + "mass": 0.001, + "volume": 5.8089221406332974e-08, + "density": 17214.897631438704 + }, + "plate": { + "mass": 0.5, + "volume": 0.00032643332083734166, + "density": 1531.7063794757178 + }, + "dart": { + "mass": 0.019, + "volume": 1.455823307089926e-06, + "density": 13051.034357994637 + }, + "dartboard": { + "mass": 1.7, + "volume": 0.002630400313410534, + "density": 646.2894607079056 + }, + "blender": { + "mass": 2.5, + "volume": 0.0030302142000610396, + "density": 825.024184742333 + }, + "straw": { + "mass": 0.005, + "volume": 1.0656228342721848e-05, + "density": 469.20916474307495 + }, + "folder": { + "mass": 0.19, + "volume": 0.0015536327844151998, + "density": 122.29402076599303 + }, + "calculator": { + "mass": 0.175, + "volume": 0.00026210793165826543, + "density": 667.6638852278755 + }, + "necklace": { + "mass": 0.038, + "volume": 3.565014220843411e-05, + "density": 1065.914401626425 + }, + "bracelet": { + "mass": 0.04, + "volume": 1.5549823316613677e-06, + "density": 25723.76494931834 + }, + "ring": { + "mass": 0.006, + "volume": 1.269962670455282e-07, + "density": 47245.48319084842 + }, + "platter": { + "mass": 0.607, + "volume": 0.00029900963545812875, + "density": 2030.034915329677 + }, + "cauldron": { + "mass": 5.22, + "volume": 0.004057748398645252, + "density": 1286.427714873299 + }, + "coffee_cup": { + "mass": 0.275, + "volume": 9.044704211189832e-05, + "density": 3040.4532152613506 + }, + "bow": { + "mass": 0.008, + "volume": 1.2419864318553748e-05, + "density": 644.1294200009082 + }, + "wreath": { + "mass": 0.519, + "volume": 0.0008985315656721635, + "density": 577.6090900176137 + }, + "chopstick": { + "mass": 0.013, + "volume": 4.233635214449215e-06, + "density": 3070.647172347669 + }, + "sushi": { + "mass": 0.043, + "volume": 2.5491996018804008e-05, + "density": 1686.8039665580256 + }, + "broom": { + "mass": 0.5, + "volume": 0.00011563255403798713, + "density": 4324.041825070663 + }, + "carpet_sweeper": { + "mass": 3.1, + "volume": 0.003011232348302394, + "density": 1029.4788450142846 + }, + "jeans": { + "mass": 0.562, + "volume": 0.010625322563932208, + "density": 52.89251188549477 + }, + "paintbrush": { + "mass": 0.05, + "volume": 7.747592301465764e-05, + "density": 645.3617853709277 + }, + "pajamas": { + "mass": 0.5, + "volume": 0.009164949848289083, + "density": 54.555672237894484 + }, + "pegboard": { + "mass": 1.5, + "volume": 0.00088446133565571, + "density": 1695.947510116935 + }, + "scrub_brush": { + "mass": 0.106, + "volume": 7.199596771056971e-05, + "density": 1472.3046772026119 + }, + "sock": { + "mass": 0.05, + "volume": 0.000736113132626106, + "density": 67.92434176744474 + }, + "trowel": { + "mass": 0.238, + "volume": 8.895795104639503e-05, + "density": 2675.421333342915 + }, + "vacuum": { + "mass": 3.5, + "volume": 0.017708420975656947, + "density": 197.64608063086536 + }, + "umbrella": { + "mass": 0.435, + "volume": 0.0027985008043103126, + "density": 155.44036983302038 + }, + "toaster": { + "mass": 2.0, + "volume": 0.0037152338400331013, + "density": 538.3241233564402 + }, + "iron": { + "mass": 1.4, + "volume": 0.002578510857159131, + "density": 542.949042123657 + }, + "hook": { + "mass": 0.089, + "volume": 2.6638811448780688e-05, + "density": 3340.9899000607893 + }, + "car": { + "mass": 1000.0, + "volume": 11.071928886479682, + "density": 90.31849917507462 + }, + "drill": { + "mass": 1.5, + "volume": 0.0005056814533511214, + "density": 2966.2942749028816 + }, + "dustpan": { + "mass": 0.3, + "volume": 0.0002689737383855158, + "density": 1115.3505238121602 + }, + "lawn_mower": { + "mass": 22.5, + "volume": 0.05656544401484642, + "density": 397.7693517988571 + }, + "painting": { + "mass": 2.25, + "volume": 0.005501479375174043, + "density": 408.9809025102125 + }, + "bottle_of_powder": { + "mass": 0.385, + "volume": 0.0006037340374126406, + "density": 637.69801956165 + }, + "rake": { + "mass": 1.522, + "volume": 0.0022845211211502767, + "density": 666.2227746153029 + }, + "scraper": { + "mass": 0.149, + "volume": 4.0907111353755826e-05, + "density": 3642.3984747170316 + }, + "ladder": { + "mass": 10.0, + "volume": 0.10899603796551462, + "density": 91.74645415243361 + }, + "toothbrush": { + "mass": 0.1, + "volume": 1.3851777159539178e-05, + "density": 7219.290264941485 + }, + "chicken": { + "mass": 1.77, + "volume": 0.0029528283348326453, + "density": 599.4252964591376 + }, + "dress": { + "mass": 0.5, + "volume": 0.04336172518233211, + "density": 11.530906528685044 + }, + "hanger": { + "mass": 0.125, + "volume": 0.000379560672254059, + "density": 329.32811309895465 + }, + "pork": { + "mass": 0.152, + "volume": 0.00014140136467258714, + "density": 1074.9542647763963 + }, + "rib": { + "mass": 0.875, + "volume": 0.0029026383722260277, + "density": 301.44988379277993 + }, + "steak": { + "mass": 0.5, + "volume": 0.0018008635911658786, + "density": 277.64457144491445 + }, + "jar_of_sugar": { + "mass": 0.675, + "volume": 0.0006071482441448681, + "density": 1111.7548416049478 + }, + "crab": { + "mass": 0.5, + "volume": 0.00013274247428825457, + "density": 3766.6918797538297 + }, + "fillet": { + "mass": 0.363, + "volume": 0.0002986344652257877, + "density": 1215.532841212911 + }, + "magazine": { + "mass": 0.225, + "volume": 0.0005894273597898073, + "density": 381.7264269514671 + }, + "newspaper": { + "mass": 0.344, + "volume": 0.0005342487859025268, + "density": 643.8947716443897 + }, + "muffin": { + "mass": 0.103, + "volume": 0.00018890927603465717, + "density": 545.2352693422195 + }, + "ice_cube": { + "mass": 0.009, + "volume": 8.099750577587745e-06, + "density": 1111.14532648737 + }, + "lime": { + "mass": 0.099, + "volume": 0.00012626620269969255, + "density": 784.0577912638935 + }, + "bagel": { + "mass": 0.115, + "volume": 0.0005354760826182396, + "density": 214.7621597545519 + }, + "baguette": { + "mass": 0.25, + "volume": 0.00020319122402827773, + "density": 1230.3680987974558 + }, + "basil": { + "mass": 0.005, + "volume": 4.8760295318166975e-05, + "density": 102.54244703348041 + }, + "celery": { + "mass": 0.3, + "volume": 0.0004737150615199923, + "density": 633.2920870985205 + }, + "cupcake": { + "mass": 0.066, + "volume": 0.00024393502419419287, + "density": 270.5638528867361 + }, + "green_onion": { + "mass": 0.04, + "volume": 4.343363264078653e-05, + "density": 920.9453036271675 + }, + "lasagna": { + "mass": 0.203, + "volume": 0.00011038731277769278, + "density": 1838.9794523653131 + }, + "mousetrap": { + "mass": 0.088, + "volume": 6.597284267148446e-05, + "density": 1333.8821920741088 + }, + "pretzel": { + "mass": 0.085, + "volume": 0.0011141018031598227, + "density": 76.29464359443855 + }, + "prosciutto": { + "mass": 2.0, + "volume": 0.0037676627334459166, + "density": 530.8330764974797 + }, + "razor": { + "mass": 0.062, + "volume": 4.4142886256471475e-06, + "density": 14045.298180046082 + }, + "tinsel": { + "mass": 0.05, + "volume": 0.003018059909670426, + "density": 16.566934221481386 + }, + "christmas_tree": { + "mass": 45.0, + "volume": 1.1513220168651626, + "density": 39.08550287479666 + }, + "christmas_tree_decorated": { + "mass": 16.32, + "volume": 1.3394350451079533, + "density": 12.184241452846765 + }, + "fire_alarm": { + "mass": 0.21, + "volume": 0.00026706000359117625, + "density": 786.340137707309 + }, + "comb": { + "mass": 0.023, + "volume": 4.526207460656585e-06, + "density": 5081.516965345542 + }, + "dental_floss": { + "mass": 0.023, + "volume": 1.9242580333693295e-05, + "density": 1195.2658947577604 + }, + "facsimile": { + "mass": 0.8, + "volume": 0.0001702515025943447, + "density": 4698.930627978927 + }, + "gingerbread": { + "mass": 0.065, + "volume": 0.00020150036519632486, + "density": 322.5800605208309 + }, + "lipstick": { + "mass": 0.016, + "volume": 5.8243549157507375e-05, + "density": 274.7085339310518 + }, + "lollipop": { + "mass": 0.048, + "volume": 1.902081454253511e-05, + "density": 2523.551233447993 + }, + "modem": { + "mass": 0.5, + "volume": 0.0008147775481780796, + "density": 613.6644303933605 + }, + "printer": { + "mass": 11.75, + "volume": 0.04132654021713329, + "density": 284.32092157399245 + }, + "scanner": { + "mass": 1.75, + "volume": 0.0032832772249245107, + "density": 533.0040322867454 + }, + "watch": { + "mass": 0.068, + "volume": 4.9877445983307536e-06, + "density": 13633.416599309743 + }, + "carton": { + "mass": 1.71, + "volume": 0.015060649704620867, + "density": 113.54091845555259 + }, + "briefcase": { + "mass": 1.5, + "volume": 0.006693059127510826, + "density": 224.1127668862916 + }, + "tea_bag": { + "mass": 0.002, + "volume": 1.5614056368189504e-05, + "density": 128.0897130661445 + }, + "shoulder_bag": { + "mass": 0.793, + "volume": 0.0051314185952503165, + "density": 154.5381623580675 + }, + "paper_bag": { + "mass": 0.05, + "volume": 0.0013647630517829809, + "density": 36.63639628481883 + }, + "backpack": { + "mass": 1.175, + "volume": 0.009639100625701414, + "density": 121.89933953661763 + }, + "eames_chair": { + "mass": 6.0, + "volume": 0.049846926746438966, + "density": 120.36850397058102 + }, + "shower_stall": { + "mass": 175.0, + "volume": 0.20604021684477902, + "density": 849.3487469576716 + }, + "soap_dispenser": { + "mass": 0.275, + "volume": 0.0003791108254765714, + "density": 725.3815547321918 + }, + "toilet_paper": { + "mass": 0.169, + "volume": 0.0006093174087656369, + "density": 277.3595462213404 + }, + "room_light": { + "mass": 3.75, + "volume": 0.02465903603425386, + "density": 152.07407113525753 + }, + "architectural_plan": { + "mass": 0.143, + "volume": 0.0033472264792981793, + "density": 42.72193736647994 + }, + "urinal": { + "mass": 17.15, + "volume": 0.02279130397797534, + "density": 752.4799816883279 + }, + "bicycle": { + "mass": 13.75, + "volume": 0.10735846990372239, + "density": 128.07559582705318 + }, + "square_light": { + "mass": 2.35, + "volume": 0.014404600319025764, + "density": 163.14232592042785 + }, + "downlight": { + "mass": 2.25, + "volume": 0.0002495602150698566, + "density": 9015.86015771858 + }, + "toilet_paper_dispenser": { + "mass": 1.5, + "volume": 0.005376795372846022, + "density": 278.97658288714575 + }, + "vending_machine": { + "mass": 160.0, + "volume": 0.8607563026940427, + "density": 185.88304204014906 + }, + "desktop_computer": { + "mass": 8.25, + "volume": 0.05486701339237111, + "density": 150.36356983752114 + }, + "magazine_stand": { + "mass": 20.0, + "volume": 0.32600817991761005, + "density": 61.34815391765468 + }, + "motorcycle": { + "mass": 225.0, + "volume": 0.33297711408220504, + "density": 675.722115678053 + }, + "locker": { + "mass": 42.5, + "volume": 0.2837893342364063, + "density": 149.75897566536463 + }, + "photocopier": { + "mass": 41.25, + "volume": 0.19586884037817115, + "density": 210.6001134246627 + }, + "shredder": { + "mass": 8.25, + "volume": 0.03401453577627098, + "density": 242.54336599693704 + }, + "conference_table": { + "mass": 82.0, + "volume": 0.47806438396035167, + "density": 171.52501368267727 + }, + "electric_mixer": { + "mass": 9.15, + "volume": 0.047655166988062325, + "density": 192.00436339446856 + }, + "paper_towel_dispenser": { + "mass": 2.0, + "volume": 0.005726499731003235, + "density": 349.25348711220784 + }, + "jug": { + "mass": 1.35, + "volume": 0.0015633740780069505, + "density": 863.5169400538048 + }, + "commercial_kitchen_sink": { + "mass": 67.5, + "volume": 0.0921556200400451, + "density": 732.4566854486867 + }, + "commercial_kitchen_table": { + "mass": 57.555, + "volume": 0.16496700161237277, + "density": 348.88795600006404 + }, + "room_ventilator": { + "mass": 1.5, + "volume": 0.004854527606476474, + "density": 308.9899000674823 + }, + "deep_fryer": { + "mass": 15.25, + "volume": 0.2704243976097417, + "density": 56.39284078949036 + }, + "metal_bottom_cabinet": { + "mass": 42.5, + "volume": 0.1000314455047693, + "density": 424.8663986163599 + }, + "gravy_boat": { + "mass": 0.5, + "volume": 0.0004910015842547152, + "density": 1018.3266531796296 + }, + "croissant": { + "mass": 0.065, + "volume": 0.0003616417690044609, + "density": 179.73587558465408 + }, + "flower": { + "mass": 0.075, + "volume": 0.0014552667413786481, + "density": 51.536943618287246 + }, + "electric_switch": { + "mass": 0.09, + "volume": 5.312219718967332e-05, + "density": 1694.207031359304 + }, + "pillar": { + "mass": 2000.0, + "volume": 0.6957910012137086, + "density": 2874.4263672730517 + }, + "chess_set": { + "mass": 1.5, + "volume": 0.005864429158678926, + "density": 255.7793707474682 + }, + "cloche": { + "mass": 0.375, + "volume": 0.001720845783970546, + "density": 217.91609887014636 + }, + "wall_mounted_soap_dispenser": { + "mass": 0.5, + "volume": 0.00037248426684481693, + "density": 1342.3385750902285 + }, + "cleaver": { + "mass": 1.05, + "volume": 0.00016071381632026582, + "density": 6533.352415125222 + }, + "can_of_corn": { + "mass": 0.378, + "volume": 0.0004915878357901936, + "density": 768.9368460315765 + }, + "booth": { + "mass": 67.5, + "volume": 0.07806817563011365, + "density": 864.6288894954383 + }, + "food_slicer": { + "mass": 12.75, + "volume": 0.031896300200573435, + "density": 399.7328818647994 + }, + "fire_extinguisher": { + "mass": 4.088, + "volume": 0.0068208271715167555, + "density": 599.3407980004494 + }, + "jukebox": { + "mass": 95.0, + "volume": 0.654978582619684, + "density": 145.0429105941654 + }, + "pay_phone": { + "mass": 27.5, + "volume": 0.018172828796023707, + "density": 1513.2481744403556 + }, + "menu": { + "mass": 0.1, + "volume": 4.600467302025753e-05, + "density": 2173.692223743583 + }, + "pepper_shaker": { + "mass": 0.135, + "volume": 0.000760292344622507, + "density": 177.5632767511672 + }, + "salt_shaker": { + "mass": 0.135, + "volume": 0.0002049831826699654, + "density": 658.5906133448894 + }, + "bar": { + "mass": 150.0, + "volume": 1.3786655089641393, + "density": 108.80086505732818 + }, + "chandelier": { + "mass": 8.75, + "volume": 0.027260849198585995, + "density": 320.9731265618042 + }, + "popcorn_machine": { + "mass": 13.5, + "volume": 0.08814233971317888, + "density": 153.16135291994644 + }, + "beer_tap": { + "mass": 4.5, + "volume": 0.005326425486432758, + "density": 844.844260275903 + }, + "ceiling_air_conditioner": { + "mass": 16.625, + "volume": 0.008591977423168619, + "density": 1934.9445629559043 + }, + "phonograph_record": { + "mass": 0.155, + "volume": 0.0002620371648673422, + "density": 591.5191460664354 + }, + "hanging_plant": { + "mass": 4.25, + "volume": 0.039149696320943936, + "density": 108.55767475586714 + }, + "room_divider": { + "mass": 20.0, + "volume": 0.23711094942188105, + "density": 84.34869856817487 + }, + "cake_stand": { + "mass": 1.58, + "volume": 0.0032504692776715275, + "density": 486.0836590130249 + }, + "skeletal_frame": { + "mass": 2000.0, + "volume": 1.6713532433610818, + "density": 1196.635126622312 + }, + "ottoman": { + "mass": 9.0, + "volume": 0.0845452539989218, + "density": 106.45186541298672 + }, + "key_chain": { + "mass": 0.05, + "volume": 5.06974955547374e-05, + "density": 986.2420116199957 + }, + "curtain": { + "mass": 2.672, + "volume": 0.7821850172972837, + "density": 3.4160715699115185 + }, + "handle": { + "mass": 0.412, + "volume": 0.0006642548202751951, + "density": 620.243899516321 + }, + "l_shaped_handle": { + "mass": 0.5, + "volume": 0.0018026199392330434, + "density": 277.37405379679416 + }, + "wall_mounted_light": { + "mass": 2.625, + "volume": 0.0024487334395745554, + "density": 1071.9827473161265 + }, + "pasta_server": { + "mass": 0.175, + "volume": 0.00012548730347259176, + "density": 1394.5633953176987 + }, + "handset": { + "mass": 0.625, + "volume": 0.004917959583095879, + "density": 127.0852249677415 + }, + "potato_masher": { + "mass": 0.25, + "volume": 0.00010707960521354697, + "density": 2334.711633475202 + }, + "skimmer": { + "mass": 0.125, + "volume": 0.00013209209161994437, + "density": 946.3094911060251 + }, + "whisk": { + "mass": 0.11, + "volume": 0.00032091141464391784, + "density": 342.77372190719865 + }, + "bunch_of_bananas": { + "mass": 1.18, + "volume": 0.0056285271989365854, + "density": 209.6463174634638 + }, + "wok": { + "mass": 1.5, + "volume": 0.0004715848753626831, + "density": 3180.763587564997 + }, + "ceiling_rack": { + "mass": 3.85, + "volume": 0.0005554055077320939, + "density": 6931.87220220562 + }, + "arbor": { + "mass": 85.0, + "volume": 1.2327702371920923, + "density": 68.95039921924653 + }, + "freezer": { + "mass": 72.5, + "volume": 0.4897722774398628, + "density": 148.02797818400816 + }, + "canister": { + "mass": 0.425, + "volume": 0.00036425947736354856, + "density": 1166.750699463145 + }, + "shopping_basket": { + "mass": 1.43, + "volume": 0.006341551919749199, + "density": 225.4968528360728 + }, + "kebab": { + "mass": 0.175, + "volume": 0.00011543595857396148, + "density": 1515.9920891363756 + }, + "paper_cup": { + "mass": 0.011, + "volume": 3.880017783661964e-05, + "density": 283.5038552224931 + }, + "box_of_granola_bars": { + "mass": 0.275, + "volume": 0.0006817725145363547, + "density": 403.36034987713776 + }, + "box_of_rice": { + "mass": 1.0, + "volume": 0.001416323272631079, + "density": 706.0534973363231 + }, + "tissue_dispenser": { + "mass": 0.5, + "volume": 0.0024145370777466178, + "density": 207.07903167369383 + }, + "bottle_of_water": { + "mass": 0.675, + "volume": 0.0006676081832663798, + "density": 1011.0720882680835 + }, + "security_camera": { + "mass": 0.5, + "volume": 0.004196043213598364, + "density": 119.1598786160306 + }, + "grocery_fridge": { + "mass": 110.0, + "volume": 1.5620468085605737, + "density": 70.42042491758939 + }, + "umbrella_rack": { + "mass": 3.25, + "volume": 0.004029747474348014, + "density": 806.5021494990398 + }, + "snack_rack": { + "mass": 16.18, + "volume": 0.03187907682739401, + "density": 507.5429281595873 + }, + "oden_cooker": { + "mass": 10.0, + "volume": 0.018402229860450793, + "density": 543.4124057699947 + }, + "crock_pot": { + "mass": 3.2, + "volume": 0.01861434465065461, + "density": 171.91043037271075 + }, + "greenery": { + "mass": 27.7, + "volume": 0.7581144596217939, + "density": 36.53801830111366 + }, + "box_of_beer": { + "mass": 6.8, + "volume": 0.01362721194754113, + "density": 499.0015585122663 + }, + "coaster": { + "mass": 0.033, + "volume": 1.1767813360490903e-05, + "density": 2804.259295171502 + }, + "wineglass": { + "mass": 0.225, + "volume": 0.0001555927194559012, + "density": 1446.0830865789355 + }, + "credit_card_terminal": { + "mass": 0.45, + "volume": 0.0013824983899999887, + "density": 325.4976665831804 + }, + "cash_register": { + "mass": 12.75, + "volume": 0.03731068388961274, + "density": 341.7251754945609 + }, + "showerhead": { + "mass": 0.5, + "volume": 0.005825196466160011, + "density": 85.83401485333964 + }, + "bush": { + "mass": 60.0, + "volume": 0.5584408072694562, + "density": 107.44200498773559 + }, + "hand_dryer": { + "mass": 3.25, + "volume": 0.005376826914366453, + "density": 604.4457171043128 + }, + "vase": { + "mass": 1.5, + "volume": 0.0005082627014229208, + "density": 2951.229739661466 + }, + "window_blind": { + "mass": 3.5, + "volume": 0.145596742039413, + "density": 24.038999437587353 + }, + "flat_bench": { + "mass": 25.0, + "volume": 0.05671016880429838, + "density": 440.83804592916516 + }, + "free_weight": { + "mass": 7.5, + "volume": 0.029291595464853843, + "density": 256.0461415971362 + }, + "free_weight_rack": { + "mass": 20.0, + "volume": 0.05434370327654573, + "density": 368.0279184917423 + }, + "ceiling_fan": { + "mass": 5.5, + "volume": 0.0198365785493759, + "density": 277.2655569764596 + }, + "weight_bar": { + "mass": 7.75, + "volume": 0.002730601176917356, + "density": 2838.202834420942 + }, + "soda_cup": { + "mass": 0.025, + "volume": 0.00018113729785755673, + "density": 138.01685404217287 + }, + "exercise_bike": { + "mass": 35.0, + "volume": 0.09795874878993294, + "density": 357.2932528472321 + }, + "elliptical_machine": { + "mass": 65.0, + "volume": 0.1741313402456727, + "density": 373.2814547243187 + }, + "spotlight": { + "mass": 2.714, + "volume": 0.000637065186000515, + "density": 4260.160592102746 + }, + "hot_tub": { + "mass": 325.0, + "volume": 0.6909300770974637, + "density": 470.38044915528405 + }, + "water_glass": { + "mass": 0.25, + "volume": 0.00020405662982867154, + "density": 1225.150097842462 + }, + "dessert_stand": { + "mass": 6.5, + "volume": 0.01553949891237968, + "density": 418.2889060098146 + }, + "turnstile": { + "mass": 65.0, + "volume": 0.05177406715659272, + "density": 1255.4547782271948 + }, + "checkout_counter": { + "mass": 175.0, + "volume": 0.8378299077259934, + "density": 208.87294471855088 + }, + "box_of_candy": { + "mass": 0.475, + "volume": 0.002584782282441735, + "density": 183.76789535685285 + }, + "candle_holder": { + "mass": 0.85, + "volume": 0.0006389058038957596, + "density": 1330.3995593984014 + }, + "bottle_of_whiskey": { + "mass": 1.338, + "volume": 0.0009738537499127673, + "density": 1373.9229325962456 + }, + "bouquet": { + "mass": 0.6, + "volume": 0.005546490348423767, + "density": 108.17651565381546 + }, + "reed_diffuser": { + "mass": 0.5, + "volume": 0.00808762026838848, + "density": 61.82288280204194 + }, + "massage_bed": { + "mass": 42.5, + "volume": 0.38401438525439097, + "density": 110.67293734802618 + }, + "wine_fridge": { + "mass": 115.0, + "volume": 0.6114936158012141, + "density": 188.06410570504548 + }, + "sauna_heater": { + "mass": 22.5, + "volume": 0.10275112367176135, + "density": 218.97570747621495 + }, + "beer_glass": { + "mass": 0.375, + "volume": 0.0001300453206513529, + "density": 2883.610099323468 + }, + "jam_dispenser": { + "mass": 1.5, + "volume": 0.003421376975250783, + "density": 438.41997267490575 + }, + "soap_dish": { + "mass": 0.15, + "volume": 0.00011245339096499843, + "density": 1333.8859656681059 + }, + "grocery_shelf": { + "mass": 60.0, + "volume": 0.6260232311376532, + "density": 95.84308858788484 + }, + "sauna_bench": { + "mass": 82.5, + "volume": 1.6464625757406186, + "density": 50.10742498224687 + }, + "statue": { + "mass": 2.183, + "volume": 0.0008292610584453904, + "density": 2632.464141138442 + }, + "hammam_bench": { + "mass": 2000.0, + "volume": 5.923839091109848, + "density": 337.6188936329286 + }, + "bag_of_rice": { + "mass": 5.0, + "volume": 0.005185515250348878, + "density": 964.2243361763527 + }, + "carton_of_eggs": { + "mass": 1.035, + "volume": 0.004208372654704735, + "density": 245.9382960876636 + }, + "mango": { + "mass": 0.285, + "volume": 0.0005456455597885312, + "density": 522.3170882403107 + }, + "microscope": { + "mass": 3.5, + "volume": 0.008306473999285073, + "density": 421.3580877158275 + }, + "test_tube_rack": { + "mass": 0.5, + "volume": 0.0003270144516305712, + "density": 1528.9844149299277 + }, + "test_tube": { + "mass": 0.033, + "volume": 2.3938492642487392e-05, + "density": 1378.5329131972885 + }, + "gate": { + "mass": 60.0, + "volume": 0.17779484535860451, + "density": 337.46760137495886 + }, + "plant_stem": { + "mass": 0.05, + "volume": 9.071513786324415e-05, + "density": 551.1759247434153 + }, + "garden_light": { + "mass": 2.75, + "volume": 0.003987369516684147, + "density": 689.6777407996212 + }, + "fire_sprinkler": { + "mass": 0.45, + "volume": 0.00012097819006666405, + "density": 3719.678726818703 + }, + "blackboard": { + "mass": 18.265, + "volume": 0.10015593288045264, + "density": 182.36563201704016 + }, + "blackboard_eraser": { + "mass": 0.093, + "volume": 0.00023614490063830111, + "density": 393.82599306027964 + }, + "round_bottom_flask": { + "mass": 0.3, + "volume": 0.00017157400405760733, + "density": 1748.5166336694726 + }, + "buret": { + "mass": 0.2, + "volume": 0.0001362034074297152, + "density": 1468.3920452078678 + }, + "candy_dispenser_shelf": { + "mass": 47.5, + "volume": 0.4522439872381459, + "density": 105.03179995843064 + }, + "dry_food_dispenser_shelf": { + "mass": 32.5, + "volume": 0.8608888404528466, + "density": 37.75167997636522 + }, + "drinking_fountain": { + "mass": 45.0, + "volume": 0.15376004755582917, + "density": 292.66380126255376 + }, + "bottle_of_pop": { + "mass": 1.075, + "volume": 0.00040822289071515704, + "density": 2633.36531206452 + }, + "can_of_soda": { + "mass": 0.353, + "volume": 0.0005387482367044112, + "density": 655.2225621365262 + }, + "projector": { + "mass": 3.5, + "volume": 0.045916672358772045, + "density": 76.22503592273821 + }, + "ceiling_mounted_projector": { + "mass": 5.0, + "volume": 0.018253914845938857, + "density": 273.9138449039277 + }, + "table_runner": { + "mass": 0.571, + "volume": 0.0041234863807230295, + "density": 138.4750541845802 + }, + "durian": { + "mass": 1.5, + "volume": 0.0009114539254785185, + "density": 1645.7222445034636 + }, + "alarm_clock": { + "mass": 0.484, + "volume": 0.0006125696937973034, + "density": 790.1141778655367 + }, + "place_mat": { + "mass": 0.348, + "volume": 0.0005937259320890785, + "density": 586.1290221492103 + }, + "wafer": { + "mass": 0.021, + "volume": 0.00011589035158595371, + "density": 181.2057665941646 + }, + "chocolate_bar": { + "mass": 0.118, + "volume": 0.00012528488512774, + "density": 941.8534397001491 + }, + "graduated_cylinder": { + "mass": 0.335, + "volume": 0.0003101350838186067, + "density": 1080.1744706701304 + }, + "box_of_oatmeal": { + "mass": 0.5, + "volume": 0.00295651383450008, + "density": 169.11809921719697 + }, + "display_case": { + "mass": 60.0, + "volume": 0.38620338396605736, + "density": 155.3585558568624 + }, + "pack_of_cigarettes": { + "mass": 0.028, + "volume": 9.641525202634209e-05, + "density": 290.4104839382672 + }, + "desk_organizer": { + "mass": 0.5, + "volume": 0.001438726340140908, + "density": 347.5296072990714 + }, + "magazine_rack": { + "mass": 1.65, + "volume": 0.0007107014720615368, + "density": 2321.6498978309883 + }, + "cubicle": { + "mass": 62.5, + "volume": 0.3237196589954823, + "density": 193.0682869058386 + }, + "desk_phone": { + "mass": 1.1, + "volume": 0.0030075747165531613, + "density": 365.7431996438173 + }, + "erlenmeyer_flask": { + "mass": 0.267, + "volume": 0.0004900424727696796, + "density": 544.8507320007142 + }, + "bed_screen": { + "mass": 12.5, + "volume": 0.16745938591049223, + "density": 74.64496499874485 + }, + "first_aid_kit": { + "mass": 0.625, + "volume": 0.0017933423562886785, + "density": 348.51125765714767 + }, + "hospital_bed": { + "mass": 135.0, + "volume": 0.6746201055778112, + "density": 200.11262469619504 + }, + "gym_mat": { + "mass": 6.75, + "volume": 0.07346199947893861, + "density": 91.88424012247597 + }, + "globe": { + "mass": 1.5, + "volume": 0.015560493360721062, + "density": 96.39797178837594 + }, + "pedestal": { + "mass": 50.582, + "volume": 0.08092221177306047, + "density": 625.0694202705798 + }, + "tree": { + "mass": 1500.0, + "volume": 70.51818317623233, + "density": 21.271109555550275 + }, + "ceiling_mounted_basketball_hoop": { + "mass": 77.07, + "volume": 0.6318298101996065, + "density": 121.97904998444467 + }, + "pommel_horse": { + "mass": 55.0, + "volume": 0.1041684904506239, + "density": 527.9907557657286 + }, + "parallel_bars": { + "mass": 54.5, + "volume": 0.06584017200443214, + "density": 827.7621145389967 + }, + "scoreboard": { + "mass": 67.841, + "volume": 0.4337138131478451, + "density": 156.41881338207284 + }, + "volleyball_net": { + "mass": 4.5, + "volume": 1.982548645897697, + "density": 2.2698055905520556 + }, + "lab_table": { + "mass": 210.0, + "volume": 0.92243804168806, + "density": 227.6575666975967 + }, + "display_fridge": { + "mass": 65.0, + "volume": 0.12877476222242562, + "density": 504.75729000166234 + }, + "bookcase": { + "mass": 35.875, + "volume": 0.0943966344774658, + "density": 380.04532893134046 + }, + "funnel": { + "mass": 0.1, + "volume": 0.00042271463174852375, + "density": 236.56621391684115 + }, + "gooseneck_microphone": { + "mass": 0.5, + "volume": 0.0006227228720728777, + "density": 802.9253820975515 + }, + "magnetic_stirrer": { + "mass": 1.2, + "volume": 0.0021215513902826597, + "density": 565.6238191996475 + }, + "classroom_mock_up": { + "mass": 0.5, + "volume": 0.011092491547306738, + "density": 45.075535813358385 + }, + "elevator_door": { + "mass": 137.5, + "volume": 0.4168292079522349, + "density": 329.87131750075525 + }, + "information_bulletin": { + "mass": 1.0, + "volume": 0.11732975899764149, + "density": 8.522986909229921 + }, + "saucepot": { + "mass": 2.045, + "volume": 0.0021060869551186245, + "density": 970.9950460639059 + }, + "stockpot": { + "mass": 2.5, + "volume": 0.0030744089198384795, + "density": 813.1644375177466 + }, + "specimen_bottle": { + "mass": 0.225, + "volume": 0.00017547967375271053, + "density": 1282.1997852416487 + }, + "pencil_holder": { + "mass": 0.3, + "volume": 0.00046379522288040833, + "density": 646.8371927956583 + }, + "periodic_table": { + "mass": 1.0, + "volume": 0.051412140389283795, + "density": 19.450658782695562 + }, + "petri_dish": { + "mass": 0.05, + "volume": 2.3583088109468412e-05, + "density": 2120.163388607509 + }, + "clipboard": { + "mass": 0.39, + "volume": 0.0004190714121451647, + "density": 930.6289780151014 + }, + "test_tube_holder": { + "mass": 0.1, + "volume": 2.6149333694635675e-05, + "density": 3824.1892190359786 + }, + "paperback_book": { + "mass": 0.275, + "volume": 0.0004343150378826158, + "density": 633.180930922142 + }, + "paper_sheet": { + "mass": 0.005, + "volume": 0.00018779843473469711, + "density": 26.62429006431018 + }, + "saucer": { + "mass": 0.175, + "volume": 0.00010911363672199437, + "density": 1603.8325296211551 + }, + "webcam": { + "mass": 0.14, + "volume": 0.00016665599682554014, + "density": 840.0537794421864 + }, + "spirit_lamp": { + "mass": 0.175, + "volume": 0.00015176242935722588, + "density": 1153.1180723792736 + }, + "buret_clamp": { + "mass": 1.5, + "volume": 0.0010015148558459044, + "density": 1497.7311532069714 + }, + "flask_clamp": { + "mass": 1.4, + "volume": 0.00019998019761693783, + "density": 7000.6931520374865 + }, + "test_tube_clamp": { + "mass": 0.5, + "volume": 0.00014745584622859417, + "density": 3390.8455499612573 + }, + "playground": { + "mass": 1000.0, + "volume": 7.056752586581781, + "density": 141.70824153612418 + }, + "sandbox": { + "mass": 2000.0, + "volume": 1.0664887919272261, + "density": 1875.3127225892813 + }, + "toy_box": { + "mass": 1.35, + "volume": 0.000620327103913303, + "density": 2176.2711825480324 + }, + "toilet_paper_holder": { + "mass": 0.45, + "volume": 0.00011440799543930528, + "density": 3933.291535019771 + }, + "electric_fan": { + "mass": 3.5, + "volume": 0.04484706879982231, + "density": 78.0430046748979 + }, + "terrarium": { + "mass": 39.862, + "volume": 0.14587156018963326, + "density": 273.2677976994236 + }, + "trophy": { + "mass": 1.625, + "volume": 0.0025492818933963305, + "density": 637.4344101409131 + }, + "lab_exhaust_hood": { + "mass": 165.0, + "volume": 0.37341389125751556, + "density": 441.86893916651826 + }, + "water_cooler": { + "mass": 20.0, + "volume": 0.07579849894785967, + "density": 263.8574678603809 + }, + "map": { + "mass": 0.175, + "volume": 0.0001225070787364598, + "density": 1428.4888824788995 + }, + "garden_plant": { + "mass": 4.3, + "volume": 0.7859830817287795, + "density": 5.470855671017875 + }, + "bottle_of_champagne": { + "mass": 1.5, + "volume": 0.0017230517231071262, + "density": 870.5484460414781 + }, + "pill_bottle": { + "mass": 0.023, + "volume": 1.3406101529291e-05, + "density": 1715.6367158451906 + }, + "picture_frame": { + "mass": 0.5, + "volume": 0.0007427882476861158, + "density": 673.1393523760863 + }, + "bench_press_machine": { + "mass": 142.5, + "volume": 0.08436300878244338, + "density": 1689.1289447426086 + }, + "pine_cone": { + "mass": 0.062, + "volume": 0.00016999869503307684, + "density": 364.70868195745027 + }, + "sound_system": { + "mass": 2.385, + "volume": 0.007949248410648365, + "density": 300.02836454389677 + }, + "drink_dispenser": { + "mass": 39.54, + "volume": 0.09049842836634414, + "density": 436.913664842214 + }, + "eyeglasses": { + "mass": 0.028, + "volume": 5.292513951817309e-05, + "density": 529.0491485692833 + }, + "seashell": { + "mass": 0.062, + "volume": 7.569832562643111e-05, + "density": 819.0405730500312 + }, + "structural_element": { + "mass": 117.138, + "volume": 0.8485747875803771, + "density": 138.0408677165708 + }, + "swing": { + "mass": 7.25, + "volume": 0.03199670258039547, + "density": 226.5858483943314 + }, + "shopping_cart": { + "mass": 12.5, + "volume": 0.048335745765449835, + "density": 258.6077819230616 + }, + "box_of_sake": { + "mass": 4.41, + "volume": 0.005477846572822295, + "density": 805.0608832090528 + }, + "bottle_of_sake": { + "mass": 1.65, + "volume": 0.0009101756026869017, + "density": 1812.8369900589348 + }, + "motion_sensor": { + "mass": 0.05, + "volume": 8.851085435336219e-05, + "density": 564.9024672204025 + }, + "hair_dryer": { + "mass": 0.5, + "volume": 0.0013954011700583148, + "density": 358.31989447099625 + }, + "wood_fireplace": { + "mass": 285.0, + "volume": 0.6343364112123577, + "density": 449.28841378552073 + }, + "gas_fireplace": { + "mass": 92.5, + "volume": 0.8312163156966583, + "density": 111.28270493881485 + }, + "tiramisu": { + "mass": 0.162, + "volume": 0.0001830496952438833, + "density": 885.0055706684566 + }, + "storage_box": { + "mass": 1.0, + "volume": 0.0004851520259012276, + "density": 2061.209572695035 + }, + "chalice": { + "mass": 0.4, + "volume": 0.00026855039859552626, + "density": 1489.478332901136 + }, + "reagent_bottle": { + "mass": 1.15, + "volume": 0.0002904561093604116, + "density": 3959.2901059382634 + }, + "marker": { + "mass": 0.02, + "volume": 2.2079525292019253e-05, + "density": 905.8165760125781 + }, + "wall_mounted_loudspeaker": { + "mass": 2.5, + "volume": 0.004971818308565282, + "density": 502.8341433340562 + }, + "projection_screen": { + "mass": 5.01, + "volume": 0.09110200640564584, + "density": 54.993300341731185 + }, + "stadium_stand": { + "mass": 5000.0, + "volume": 19.138535219094663, + "density": 261.25301350186203 + }, + "notepad": { + "mass": 0.358, + "volume": 0.0005801159165981229, + "density": 617.1180444407727 + }, + "stairs": { + "mass": 195.0, + "volume": 27.758307157962115, + "density": 7.024924066526396 + }, + "lawn": { + "mass": 2000.0, + "volume": 53.8504990874943, + "density": 37.1398600549732 + }, + "blanket": { + "mass": 1.85, + "volume": 0.058660648470356104, + "density": 31.537326099197305 + }, + "background": { + "mass": 10000.0, + "volume": 398.38080204740857, + "density": 25.101611193628674 + }, + "soccer_ball": { + "mass": 0.43, + "volume": 0.007691476636032205, + "density": 55.906039938492704 + }, + "hammock": { + "mass": 3.75, + "volume": 0.11252035304391109, + "density": 33.32730389262609 + }, + "fairy_light": { + "mass": 0.5, + "volume": 0.02098907256465598, + "density": 23.821919642221946 + }, + "railing": { + "mass": 24.3, + "volume": 0.012417965596876796, + "density": 1956.842271016729 + }, + "cigar": { + "mass": 0.01, + "volume": 1.0661905783791035e-05, + "density": 937.9186238170187 + }, + "stapler": { + "mass": 0.2, + "volume": 0.00010865615274506362, + "density": 1840.6688894024571 + }, + "garden_umbrella": { + "mass": 11.5, + "volume": 1.5037758568416466, + "density": 7.6474163005604066 + }, + "weed": { + "mass": 0.007, + "volume": 8.934009671918514e-07, + "density": 7835.227694013455 + }, + "hall_tree": { + "mass": 27.5, + "volume": 0.35272662195913923, + "density": 77.96406136644165 + }, + "pergola": { + "mass": 135.0, + "volume": 3.3369781334445996, + "density": 40.45576404800894 + }, + "rose": { + "mass": 0.075, + "volume": 0.0009114621079735777, + "density": 82.28537351568559 + }, + "garage_door": { + "mass": 140.0, + "volume": 1.1679362455450224, + "density": 119.86955669371183 + }, + "knife_block": { + "mass": 2.125, + "volume": 0.00806513924278072, + "density": 263.47964195436964 + }, + "garden_chair": { + "mass": 5.0, + "volume": 0.1202309873719929, + "density": 41.58661680561662 + }, + "postcard": { + "mass": 0.009, + "volume": 2.0093646711240365e-05, + "density": 447.9027689366813 + }, + "paper_coffee_filter": { + "mass": 0.01, + "volume": 0.00016572511948424276, + "density": 30.170441364354563 + }, + "colored_pencil": { + "mass": 0.006, + "volume": 2.7909250358384454e-06, + "density": 2149.824851242373 + }, + "comic_book": { + "mass": 0.189, + "volume": 0.00039433959156105265, + "density": 479.28233442605915 + }, + "cookie_cutter": { + "mass": 0.038, + "volume": 1.0936384552233644e-05, + "density": 3474.6400712691557 + }, + "bottle_of_orange_juice": { + "mass": 1.0, + "volume": 0.0007196576022973676, + "density": 1389.5496925311336 + }, + "corkscrew": { + "mass": 0.125, + "volume": 3.1440816997392825e-05, + "density": 3975.723659164627 + }, + "mannequin": { + "mass": 11.0, + "volume": 0.08554557205960434, + "density": 128.58643334965006 + }, + "ceremonial_robe": { + "mass": 2.0, + "volume": 0.14011402308681298, + "density": 14.27408874528443 + }, + "cotton_ball": { + "mass": 0.002, + "volume": 3.283102885151762e-05, + "density": 60.91798125015353 + }, + "lobster": { + "mass": 0.75, + "volume": 0.0015498556403088907, + "density": 483.91603739979473 + }, + "crayon": { + "mass": 0.015, + "volume": 7.286834027401262e-06, + "density": 2058.507157373738 + }, + "sliced_cucumber": { + "mass": 0.005, + "volume": 4.164742809046622e-06, + "density": 1200.5543269416394 + }, + "chopped_lettuce": { + "mass": 0.018, + "volume": 0.00013972948567023103, + "density": 128.82034105872935 + }, + "crystal": { + "mass": 1.955, + "volume": 0.0003817371024716394, + "density": 5121.325612160646 + }, + "garden_coffee_table": { + "mass": 22.5, + "volume": 0.08802561726985288, + "density": 255.6074095001641 + }, + "garden_statue": { + "mass": 5000.0, + "volume": 10.263358673305003, + "density": 487.1699566541507 + }, + "driveway": { + "mass": 2000.0, + "volume": 14.442763488745928, + "density": 138.47765364006946 + }, + "hanging_banners": { + "mass": 0.45, + "volume": 0.02587225938721982, + "density": 17.39314658472725 + }, + "nightstand": { + "mass": 17.5, + "volume": 0.0383726160737687, + "density": 456.0543895771261 + }, + "suitcase": { + "mass": 3.75, + "volume": 0.010418347071560332, + "density": 359.94193457392385 + }, + "teaspoon": { + "mass": 0.027, + "volume": 7.572821668622615e-06, + "density": 3565.381727113997 + }, + "wardrobe": { + "mass": 66.275, + "volume": 0.6101782688654722, + "density": 108.61579866360637 + }, + "pestle": { + "mass": 0.299, + "volume": 0.00011767110832376947, + "density": 2540.9805708407885 + }, + "skirt": { + "mass": 0.25, + "volume": 0.019441641473443367, + "density": 12.858996517423266 + }, + "hourglass": { + "mass": 0.5, + "volume": 0.000523215433773543, + "density": 955.6293024345474 + }, + "pants": { + "mass": 0.55, + "volume": 0.056914450921248395, + "density": 9.663626567548304 + }, + "ashtray": { + "mass": 0.225, + "volume": 0.00011051475888222158, + "density": 2035.9271673368828 + }, + "tennis_racket": { + "mass": 0.3, + "volume": 0.003368638412613737, + "density": 89.05675327950352 + }, + "poster": { + "mass": 0.165, + "volume": 0.005608611949796485, + "density": 29.419043691547824 + }, + "curtain_rod": { + "mass": 1.677, + "volume": 0.0004870705719822223, + "density": 3443.0328918767223 + }, + "bottle_of_coke": { + "mass": 1.52, + "volume": 0.0031082961599804386, + "density": 489.01389113756966 + }, + "cymbal": { + "mass": 1.95, + "volume": 0.009703577277378162, + "density": 200.95681667275556 + }, + "dahlia_flower": { + "mass": 0.075, + "volume": 0.0002789330608538676, + "density": 268.8817158152949 + }, + "flower_petal": { + "mass": 0.001, + "volume": 6.6111457427079e-08, + "density": 15125.971184389651 + }, + "spray_bottle": { + "mass": 0.4, + "volume": 0.00107569945803389, + "density": 371.851075142401 + }, + "decanter": { + "mass": 1.35, + "volume": 0.0015727738450271658, + "density": 858.3560848678038 + }, + "dehumidifier": { + "mass": 14.5, + "volume": 0.05572467314790653, + "density": 260.20789680566725 + }, + "denture": { + "mass": 0.053, + "volume": 0.00017399251032507455, + "density": 304.6108128503852 + }, + "diamond": { + "mass": 0.004, + "volume": 2.0564434925306044e-07, + "density": 19451.057199134157 + }, + "diaper": { + "mass": 0.1, + "volume": 0.02020951092590147, + "density": 4.948165265683657 + }, + "dice": { + "mass": 0.013, + "volume": 4.9530841655977724e-06, + "density": 2624.6273161059985 + }, + "dowel": { + "mass": 0.02, + "volume": 1.7014499414700441e-06, + "density": 11754.680236269603 + }, + "dried_apricot": { + "mass": 0.008, + "volume": 1.3719534828428239e-05, + "density": 583.1101491446492 + }, + "bay_leaf": { + "mass": 0.002, + "volume": 3.856153134225771e-06, + "density": 518.651601838306 + }, + "drumstick": { + "mass": 0.075, + "volume": 4.7789836363963565e-05, + "density": 1569.3713497741655 + }, + "duct_tape": { + "mass": 0.265, + "volume": 0.0004349228969967002, + "density": 609.3034002806493 + }, + "dumpling": { + "mass": 0.043, + "volume": 2.29978909324599e-05, + "density": 1869.7366696051477 + }, + "dutch_oven": { + "mass": 5.108, + "volume": 0.005311342547899944, + "density": 961.7154144990433 + }, + "mattress": { + "mass": 37.5, + "volume": 1.277041283509339, + "density": 29.36475154268242 + }, + "easter_egg": { + "mass": 0.048, + "volume": 5.190864124973917e-05, + "density": 924.7015303110287 + }, + "electric_hand_mixer": { + "mass": 1.015, + "volume": 0.0014708330879446702, + "density": 690.0851009670665 + }, + "electric_kettle": { + "mass": 1.293, + "volume": 0.002428301641987332, + "density": 532.4709161510114 + }, + "feather": { + "mass": 0.007, + "volume": 4.071584132980022e-05, + "density": 171.92325570039614 + }, + "sliced_chocolate_cake": { + "mass": 0.199, + "volume": 0.0008302915474018534, + "density": 239.67484749508822 + }, + "firewood": { + "mass": 0.46, + "volume": 0.0007739589168136964, + "density": 594.3467928424022 + }, + "fishing_rod": { + "mass": 0.299, + "volume": 0.0021427257520234555, + "density": 139.54188944508797 + }, + "flag_pole": { + "mass": 3.65, + "volume": 0.012362199815225253, + "density": 295.25489431942924 + }, + "flashlight": { + "mass": 0.2, + "volume": 0.0003319410125738701, + "density": 602.5166894840753 + }, + "fountain": { + "mass": 1000.0, + "volume": 3.7289261851041506, + "density": 268.17371821267886 + }, + "frame": { + "mass": 3.0, + "volume": 0.06955864687013803, + "density": 43.12907359455721 + }, + "french_fry_holder": { + "mass": 0.12, + "volume": 0.0003095880505635014, + "density": 387.61185963599104 + }, + "french_fries": { + "mass": 0.006, + "volume": 3.3584766226248306e-06, + "density": 1786.5242710281773 + }, + "french_toast": { + "mass": 0.09, + "volume": 0.00029491126090137296, + "density": 305.17654607329035 + }, + "garlic": { + "mass": 0.05, + "volume": 0.00010183250710539194, + "density": 491.00234710171986 + }, + "beer_keg": { + "mass": 50.0, + "volume": 0.026355017320950136, + "density": 1897.171965060861 + }, + "coffee_grinder": { + "mass": 1.5, + "volume": 0.0008575986476602921, + "density": 1749.0699222676162 + }, + "geode": { + "mass": 13.08, + "volume": 0.025566409572277883, + "density": 511.60879524447887 + }, + "bottle_of_gin": { + "mass": 1.25, + "volume": 0.0014705919766409125, + "density": 849.9978375070542 + }, + "granola_bar": { + "mass": 0.041, + "volume": 5.1446656960333195e-05, + "density": 796.9419671255247 + }, + "dreidel": { + "mass": 0.025, + "volume": 5.0605135443453405e-06, + "density": 4940.210075701745 + }, + "goggles": { + "mass": 0.132, + "volume": 0.0009268523845487134, + "density": 142.4175005648511 + }, + "french_press": { + "mass": 0.555, + "volume": 0.001275583715988034, + "density": 435.0949240286526 + }, + "heap_of_granola": { + "mass": 0.13, + "volume": 6.0931293618982314e-05, + "density": 2133.550631846429 + }, + "heap_of_raisins": { + "mass": 0.05, + "volume": 4.048704328646043e-05, + "density": 1234.9629891773518 + }, + "grapefruit": { + "mass": 0.45, + "volume": 0.0006357261750024178, + "density": 707.8519301148621 + }, + "heap_of_gravel": { + "mass": 0.1, + "volume": 7.110944996868513e-06, + "density": 14062.828505077394 + }, + "green_bean": { + "mass": 0.006, + "volume": 8.302536834475419e-06, + "density": 722.6706872393057 + }, + "portafilter": { + "mass": 0.375, + "volume": 0.00021297022632629664, + "density": 1760.80951064706 + }, + "hamster_wheel": { + "mass": 1.75, + "volume": 0.00242082048285136, + "density": 722.8954036024863 + }, + "hazelnut": { + "mass": 0.004, + "volume": 3.3739152626211006e-06, + "density": 1185.5662305201204 + }, + "heatgun": { + "mass": 1.065, + "volume": 0.007773285019549332, + "density": 137.0077126107676 + }, + "hockey_puck": { + "mass": 0.165, + "volume": 0.00010618458329178721, + "density": 1553.8978906814793 + }, + "hiking_boot": { + "mass": 1.45, + "volume": 0.0017773251726456675, + "density": 815.8327031634723 + }, + "hockey_stick": { + "mass": 0.475, + "volume": 0.0004649058629205951, + "density": 1021.7122172131628 + }, + "hoe": { + "mass": 2.0, + "volume": 0.0038883192295428395, + "density": 514.3610598647132 + }, + "hoodie": { + "mass": 0.55, + "volume": 0.07108838711870866, + "density": 7.73684735710165 + }, + "hotdog_frank": { + "mass": 0.05, + "volume": 7.212110095245527e-05, + "density": 693.278379554435 + }, + "hotdog_bun": { + "mass": 0.054, + "volume": 0.0003271442888581483, + "density": 165.06477979022497 + }, + "ice_bucket": { + "mass": 1.96, + "volume": 0.005970850752795917, + "density": 328.261428923208 + }, + "ironing_board": { + "mass": 4.75, + "volume": 0.040581795521727804, + "density": 117.04755639648359 + }, + "jade_roller": { + "mass": 0.338, + "volume": 2.1384817858693256e-05, + "density": 15805.605744853134 + }, + "quilt": { + "mass": 2.15, + "volume": 0.0578842301603501, + "density": 37.143104331596 + }, + "jersey": { + "mass": 0.313, + "volume": 0.016498633586525664, + "density": 18.971268036137566 + }, + "jigger": { + "mass": 0.074, + "volume": 4.1901232254799164e-05, + "density": 1766.057846461649 + }, + "kale": { + "mass": 0.019, + "volume": 3.202298904666317e-05, + "density": 593.3237516433469 + }, + "juicer": { + "mass": 1.4, + "volume": 0.009288362976792149, + "density": 150.726237066535 + }, + "keys": { + "mass": 0.04, + "volume": 4.699738486017751e-06, + "density": 8511.111866969723 + }, + "kayak": { + "mass": 23.5, + "volume": 0.25183238747807934, + "density": 93.31603546047289 + }, + "paddle": { + "mass": 0.865, + "volume": 0.007978409323270466, + "density": 108.41760117233792 + }, + "holly_decoration": { + "mass": 0.05, + "volume": 5.2704420202234033e-05, + "density": 948.6870324755153 + }, + "jade": { + "mass": 0.101, + "volume": 2.3407810930622177e-05, + "density": 4314.79903436299 + }, + "work_helmet": { + "mass": 0.465, + "volume": 0.0009610046210251078, + "density": 483.8686410310728 + }, + "air_conditioner": { + "mass": 17.5, + "volume": 0.05040470042072981, + "density": 347.18984249339616 + }, + "allen_wrench": { + "mass": 0.066, + "volume": 4.793304075658214e-06, + "density": 13769.207827887889 + }, + "antlers": { + "mass": 3.0, + "volume": 0.0010041569108105346, + "density": 2987.580892689831 + }, + "apple_pie": { + "mass": 0.89, + "volume": 0.0006482665951389064, + "density": 1372.891965548983 + }, + "apron": { + "mass": 0.4, + "volume": 0.017210909876606985, + "density": 23.241072254040372 + }, + "arugula": { + "mass": 0.032, + "volume": 0.0001498937559792357, + "density": 213.48454304149172 + }, + "asparagus": { + "mass": 0.02, + "volume": 1.1926760877117165e-05, + "density": 1676.901231278331 + }, + "avocado": { + "mass": 0.2, + "volume": 0.00032725071183401373, + "density": 611.1522229520555 + }, + "axe": { + "mass": 1.55, + "volume": 0.0009096797564189263, + "density": 1703.8963317176347 + }, + "baby_bottle": { + "mass": 0.225, + "volume": 0.0003430856074105107, + "density": 655.8129957657529 + }, + "bacon": { + "mass": 0.023, + "volume": 1.3528732459937156e-05, + "density": 1700.0853604068418 + }, + "bait": { + "mass": 0.033, + "volume": 1.2932926530809472e-05, + "density": 2551.6266501155583 + }, + "baking_sheet": { + "mass": 1.037, + "volume": 0.0007417691724063147, + "density": 1398.0090283827114 + }, + "balloon": { + "mass": 0.04, + "volume": 0.01992561440985896, + "density": 2.0074663283762266 + }, + "bandage": { + "mass": 0.003, + "volume": 4.0033456345106344e-07, + "density": 7493.732177753164 + }, + "bandana": { + "mass": 0.056, + "volume": 0.0019929646972818337, + "density": 28.098841929501976 + }, + "baseball": { + "mass": 0.145, + "volume": 0.00020087194961182546, + "density": 721.852903206271 + }, + "baseball_bat": { + "mass": 0.879, + "volume": 0.0015215345023104486, + "density": 577.7062555369197 + }, + "baseball_cap": { + "mass": 0.15, + "volume": 0.00037996689962786534, + "density": 394.77122914366504 + }, + "baseball_glove": { + "mass": 0.45, + "volume": 0.0035865143831907836, + "density": 125.47001124798288 + }, + "battery": { + "mass": 0.075, + "volume": 5.3331749173506524e-05, + "density": 1406.2917710799097 + }, + "batting_gloves": { + "mass": 0.214, + "volume": 0.0009088732286242351, + "density": 235.45637968007114 + }, + "bed_sheet": { + "mass": 0.825, + "volume": 0.008875345280913348, + "density": 92.95413010851343 + }, + "beeswax_candle": { + "mass": 0.188, + "volume": 0.00046563824153889846, + "density": 403.74690742468766 + }, + "bikini": { + "mass": 0.1, + "volume": 0.0004276600012912234, + "density": 233.83061239786852 + }, + "birdcage": { + "mass": 2.5, + "volume": 0.0017065791141384168, + "density": 1464.9189007930345 + }, + "biscuit": { + "mass": 0.024, + "volume": 2.4967871808677204e-05, + "density": 961.2353100779364 + }, + "blouse": { + "mass": 0.3, + "volume": 0.01654789237088889, + "density": 18.12919695608856 + }, + "bobby_pin": { + "mass": 0.002, + "volume": 4.6957978357113595e-07, + "density": 4259.127138715551 + }, + "bookend": { + "mass": 1.625, + "volume": 0.0006459945533944753, + "density": 2515.5010850497015 + }, + "bowling_ball": { + "mass": 7.03, + "volume": 0.005366124365728789, + "density": 1310.0702706216975 + }, + "boxing_gloves": { + "mass": 0.505, + "volume": 0.007831968474762196, + "density": 64.4793198066765 + }, + "bra": { + "mass": 0.177, + "volume": 0.001999170103798533, + "density": 88.53673815134104 + }, + "branch": { + "mass": 1.93, + "volume": 0.004839601701008417, + "density": 398.7931485348991 + }, + "bratwurst": { + "mass": 0.133, + "volume": 0.00041988947738216267, + "density": 316.75001914599056 + }, + "brisket": { + "mass": 0.25, + "volume": 4.1088260320163846e-05, + "density": 6084.463008459714 + }, + "brownie": { + "mass": 0.118, + "volume": 0.0002631135849120096, + "density": 448.475513111425 + }, + "brussels_sprouts": { + "mass": 0.063, + "volume": 8.235397299814233e-05, + "density": 764.990415233775 + }, + "bottle_of_bug_repellent": { + "mass": 0.298, + "volume": 0.00029750959298789853, + "density": 1001.6483737790646 + }, + "burrito": { + "mass": 0.25, + "volume": 0.000361909490488028, + "density": 690.7804480697088 + }, + "butternut_squash": { + "mass": 1.115, + "volume": 0.0029854602102174343, + "density": 373.4767578492675 + }, + "candied_yam": { + "mass": 0.25, + "volume": 0.00011308786512842448, + "density": 2210.6704350293976 + }, + "can_of_coffee": { + "mass": 0.4, + "volume": 0.0006770282858412122, + "density": 590.8172647513499 + }, + "can_of_sardines": { + "mass": 0.3, + "volume": 0.0006659235605885003, + "density": 450.50215633590034 + }, + "can_of_tomatoes": { + "mass": 0.48, + "volume": 0.0006659170356921597, + "density": 720.8105128307523 + }, + "canvas": { + "mass": 1.83, + "volume": 0.008874685007136549, + "density": 206.20450174044618 + }, + "cardigan": { + "mass": 0.475, + "volume": 0.014759877734625393, + "density": 32.181838395970665 + }, + "cardstock": { + "mass": 0.054, + "volume": 6.451307099466456e-05, + "density": 837.0396753313134 + }, + "cauliflower": { + "mass": 0.925, + "volume": 0.005731786146402203, + "density": 161.38075922120981 + }, + "ceramic_tile": { + "mass": 0.475, + "volume": 0.00010014631438658732, + "density": 4743.06022053286 + }, + "charcoal_grill": { + "mass": 25.15, + "volume": 0.05065267325086911, + "density": 496.5187103835328 + }, + "chard": { + "mass": 0.211, + "volume": 0.0001399250580841416, + "density": 1507.9500619046994 + }, + "cheese_danish": { + "mass": 0.095, + "volume": 0.00023958603861521746, + "density": 396.5172618116238 + }, + "cherry_tomato": { + "mass": 0.014, + "volume": 7.966650915226077e-06, + "density": 1757.325650260742 + }, + "chicken_breast": { + "mass": 0.328, + "volume": 0.0016563067420918773, + "density": 198.03095143218675 + }, + "chicken_coop": { + "mass": 200.0, + "volume": 0.5753548165741019, + "density": 347.6115854749976 + }, + "chicken_leg": { + "mass": 0.16, + "volume": 9.566305005700414e-05, + "density": 1672.5370966601888 + }, + "chicken_wing": { + "mass": 0.105, + "volume": 0.0004514010042888096, + "density": 232.60914132308898 + }, + "china": { + "mass": 2.25, + "volume": 0.0036999763073765684, + "density": 608.1120020996406 + }, + "chisel": { + "mass": 0.302, + "volume": 6.663056947174243e-05, + "density": 4532.454133204972 + }, + "chorizo": { + "mass": 0.24, + "volume": 0.0003216629980015331, + "density": 746.1224992961612 + }, + "cigarette": { + "mass": 0.001, + "volume": 2.3350039007368812e-06, + "density": 428.2648091870081 + }, + "cinnamon_stick": { + "mass": 0.005, + "volume": 1.8986116287753973e-05, + "density": 263.3503305373198 + }, + "clamp": { + "mass": 0.535, + "volume": 0.00023041116833636313, + "density": 2321.9360583206903 + }, + "clothesline": { + "mass": 4.25, + "volume": 0.021284925166171604, + "density": 199.67183191015292 + }, + "compost_bin": { + "mass": 5.995, + "volume": 0.06593170575487398, + "density": 90.9274215092914 + }, + "cooler": { + "mass": 6.0, + "volume": 0.13870159065971846, + "density": 43.258335909932086 + }, + "crawfish": { + "mass": 0.025, + "volume": 1.9497053621823534e-05, + "density": 1282.2450245516525 + }, + "credit_card": { + "mass": 0.005, + "volume": 1.9409240206783317e-06, + "density": 2576.092596480183 + }, + "cutting_board": { + "mass": 1.45, + "volume": 0.0022401289424861504, + "density": 647.2841685580627 + }, + "bottle_of_dish_soap": { + "mass": 0.65, + "volume": 0.0006330291843677241, + "density": 1026.8088992598762 + }, + "donut": { + "mass": 0.07, + "volume": 0.00019901220833894311, + "density": 351.73721544148236 + }, + "drying_rack": { + "mass": 4.0, + "volume": 0.010899453381392449, + "density": 366.99088110499207 + }, + "duck": { + "mass": 1.57, + "volume": 0.012766880077708563, + "density": 122.97444563149591 + }, + "easel": { + "mass": 4.25, + "volume": 0.04748730008235303, + "density": 89.49761289080661 + }, + "firewood_grate": { + "mass": 3.75, + "volume": 0.0020412532121927285, + "density": 1837.1067232622863 + }, + "food_processor": { + "mass": 4.0, + "volume": 0.014750690042967522, + "density": 271.173754472 + }, + "fuel_can": { + "mass": 4.5, + "volume": 0.006742588120624615, + "density": 667.3995088377328 + }, + "goalkeeper_gloves": { + "mass": 0.25, + "volume": 0.0005202014222622782, + "density": 480.5830766720848 + }, + "goblet": { + "mass": 0.5, + "volume": 0.0007305251113349879, + "density": 684.4391688141726 + }, + "golf_club": { + "mass": 0.415, + "volume": 0.0005996832913049525, + "density": 692.0319542285914 + }, + "hanging_basket": { + "mass": 3.0, + "volume": 0.017865532649427574, + "density": 167.92110590087123 + }, + "headstone": { + "mass": 537.5, + "volume": 0.21373645916658082, + "density": 2514.779191607577 + }, + "inhaler": { + "mass": 0.075, + "volume": 8.969459775285774e-05, + "density": 836.1707603244192 + }, + "instant_pot": { + "mass": 5.75, + "volume": 0.005929948137323305, + "density": 969.6543488819566 + }, + "letter": { + "mass": 0.029, + "volume": 2.39859614921424e-05, + "density": 1209.0405468840663 + }, + "life_jacket": { + "mass": 1.5, + "volume": 0.024817956553560838, + "density": 60.44010903003949 + }, + "lighter": { + "mass": 0.04, + "volume": 8.892717714901557e-05, + "density": 449.80624913992114 + }, + "bottle_of_lighter_fluid": { + "mass": 0.188, + "volume": 0.0008148348697666525, + "density": 230.7215940008045 + }, + "lint_roller": { + "mass": 0.185, + "volume": 0.00028436127813634806, + "density": 650.5808428364658 + }, + "lip_balm": { + "mass": 0.015, + "volume": 4.0123319695156465e-05, + "density": 373.8474312186771 + }, + "litter_box": { + "mass": 3.5, + "volume": 0.020173390428994686, + "density": 173.49587380064492 + }, + "log": { + "mass": 2.75, + "volume": 0.0017854109252888062, + "density": 1540.2616624826371 + }, + "longboard": { + "mass": 4.0, + "volume": 0.016100880296148746, + "density": 248.433621418624 + }, + "loofah": { + "mass": 0.11, + "volume": 0.0018781550911841052, + "density": 58.568113206587846 + }, + "magnifying_glass": { + "mass": 0.15, + "volume": 9.730683354914592e-05, + "density": 1541.515580447295 + }, + "mailbox": { + "mass": 10.25, + "volume": 0.07061146898706494, + "density": 145.1605546101535 + }, + "marshmallow": { + "mass": 0.022, + "volume": 0.00019977613314019565, + "density": 110.12326474735195 + }, + "match": { + "mass": 0.002, + "volume": 5.813382012357127e-07, + "density": 3440.3381641680016 + }, + "match_box": { + "mass": 0.025, + "volume": 2.7722392749402143e-05, + "density": 901.7980600011213 + }, + "measuring_cup": { + "mass": 0.225, + "volume": 0.001092530280258127, + "density": 205.943948708534 + }, + "meat_thermometer": { + "mass": 0.067, + "volume": 4.5196711157549176e-05, + "density": 1482.40874798274 + }, + "microfiber_cloth": { + "mass": 0.04, + "volume": 3.252878974357688e-05, + "density": 1229.6799332320188 + }, + "microphone": { + "mass": 0.35, + "volume": 0.0006782476883613515, + "density": 516.035669573163 + }, + "mint": { + "mass": 0.004, + "volume": 7.276383027972691e-06, + "density": 549.7236724101452 + }, + "mixing_bowl": { + "mass": 0.751, + "volume": 0.0012865605458472946, + "density": 583.7269007075072 + }, + "mortar": { + "mass": 0.971, + "volume": 0.00042342000326503596, + "density": 2293.2312892931777 + }, + "moth_ball": { + "mass": 0.001, + "volume": 1.473036205678551e-08, + "density": 67886.99396151991 + }, + "mussel": { + "mass": 0.04, + "volume": 0.0001612793173509638, + "density": 248.01692279584145 + }, + "name_tag": { + "mass": 0.03, + "volume": 3.131178388857349e-05, + "density": 958.1057440469817 + }, + "nativity_figurine": { + "mass": 1.0, + "volume": 0.002089154548759205, + "density": 478.66252910485827 + }, + "nectarine": { + "mass": 0.15, + "volume": 0.00024309991380278386, + "density": 617.0302475783201 + }, + "nickel": { + "mass": 0.005, + "volume": 6.499274824022044e-07, + "density": 7693.165984487136 + }, + "okra": { + "mass": 0.021, + "volume": 1.7866967537619516e-05, + "density": 1175.3533416223977 + }, + "omelet": { + "mass": 0.176, + "volume": 0.0005682172590795684, + "density": 309.7406796215502 + }, + "onesie": { + "mass": 0.5, + "volume": 0.04233505391240566, + "density": 11.810543599035842 + }, + "outlet": { + "mass": 0.315, + "volume": 9.092619672665405e-05, + "density": 3464.348134421211 + }, + "oyster": { + "mass": 0.09, + "volume": 0.00016774361160136976, + "density": 536.533100371526 + }, + "pallet": { + "mass": 24.15, + "volume": 0.03778821454196316, + "density": 639.0881467337347 + }, + "papaya": { + "mass": 0.69, + "volume": 0.0005293197652487125, + "density": 1303.559861732706 + }, + "paper_liners": { + "mass": 0.008, + "volume": 5.703002065921184e-05, + "density": 140.27699635258315 + }, + "paraffin_wax": { + "mass": 0.8, + "volume": 0.0011553947511270045, + "density": 692.4040456473059 + }, + "feta": { + "mass": 1.215, + "volume": 0.0006620707898597683, + "density": 1835.151193209032 + }, + "parsnip": { + "mass": 0.14, + "volume": 0.00016916110142917948, + "density": 827.6134336865383 + }, + "pastry_cutter": { + "mass": 0.093, + "volume": 4.319271122666719e-05, + "density": 2153.141059192917 + }, + "paver": { + "mass": 1000.0, + "volume": 0.23929225175035188, + "density": 4178.990304472028 + }, + "pea_pod": { + "mass": 0.02, + "volume": 1.7469376127115807e-05, + "density": 1144.860575127018 + }, + "pearl": { + "mass": 0.002, + "volume": 7.516261432749761e-07, + "density": 2660.8973329288747 + }, + "pencil_case": { + "mass": 0.118, + "volume": 0.00010604795109832367, + "density": 1112.7041944506295 + }, + "pennant": { + "mass": 0.04, + "volume": 0.00025407277677846863, + "density": 157.4352061924243 + }, + "penny": { + "mass": 0.003, + "volume": 4.156224789059457e-07, + "density": 7218.088896194887 + }, + "pet_bed": { + "mass": 4.0, + "volume": 0.08314106191838203, + "density": 48.11100445080582 + }, + "cell_phone": { + "mass": 0.161, + "volume": 0.00012919194666478987, + "density": 1246.2077099723674 + }, + "pickle": { + "mass": 0.065, + "volume": 6.276461375335943e-05, + "density": 1035.6153907904982 + }, + "pickup_truck": { + "mass": 1500.0, + "volume": 6.693554127288118, + "density": 224.09619336382696 + }, + "pillowcase": { + "mass": 0.2, + "volume": 0.022951377777487937, + "density": 8.714073810251678 + }, + "pipe_cleaner": { + "mass": 0.013, + "volume": 0.00012060066444670448, + "density": 107.7937676350442 + }, + "pitcher": { + "mass": 1.425, + "volume": 0.0024335863325052353, + "density": 585.555556820146 + }, + "pizza": { + "mass": 0.832, + "volume": 0.0027581604169326333, + "density": 301.65033001426076 + }, + "pizza_box": { + "mass": 0.119, + "volume": 0.001674478113065018, + "density": 71.06691874412058 + }, + "plant_pot": { + "mass": 1.691, + "volume": 0.00195420105316525, + "density": 865.3152638829362 + }, + "plastic_bag": { + "mass": 0.032, + "volume": 0.00471012504937085, + "density": 6.793874825950612 + }, + "plier": { + "mass": 0.239, + "volume": 3.411350778829228e-05, + "density": 7006.022408578708 + }, + "plug": { + "mass": 0.05, + "volume": 5.44911940200221e-06, + "density": 9175.79452959466 + }, + "poker": { + "mass": 1.275, + "volume": 0.000274472087884429, + "density": 4645.281091521626 + }, + "pole": { + "mass": 5.808, + "volume": 0.004243342543436441, + "density": 1368.7323001966352 + }, + "pork_chop": { + "mass": 0.28, + "volume": 0.00024362492296204084, + "density": 1149.3077005246575 + }, + "pork_rib": { + "mass": 0.65, + "volume": 0.00017943208072174893, + "density": 3622.5406147297363 + }, + "power_drill": { + "mass": 1.5, + "volume": 0.0011488577461389465, + "density": 1305.6446762370397 + }, + "power_strip": { + "mass": 0.5, + "volume": 0.0029742834092221357, + "density": 168.10771913990706 + }, + "pressure_cooker": { + "mass": 5.0, + "volume": 0.012555497825064616, + "density": 398.2319195674161 + }, + "pump": { + "mass": 20.0, + "volume": 0.021303822607924183, + "density": 938.798654498784 + }, + "punching_bag": { + "mass": 23.84, + "volume": 0.05042334449181973, + "density": 472.79688089447546 + }, + "putty_knife": { + "mass": 0.163, + "volume": 0.0001733462963149403, + "density": 940.3142926333836 + }, + "jigsaw_puzzle": { + "mass": 0.225, + "volume": 9.15826149739581e-05, + "density": 2456.7981604803454 + }, + "jigsaw_puzzle_piece": { + "mass": 0.005, + "volume": 9.125707048430961e-07, + "density": 5479.027513665016 + }, + "quail_breast": { + "mass": 0.073, + "volume": 0.00013824061774966737, + "density": 528.0647698796589 + }, + "quail_breast_raw": { + "mass": 0.075, + "volume": 0.0002927426712103518, + "density": 256.1977032248515 + }, + "quail_leg": { + "mass": 0.025, + "volume": 1.0214401387560919e-05, + "density": 2447.524730176059 + }, + "quarter": { + "mass": 0.006, + "volume": 7.459926965088721e-07, + "density": 8042.974184705899 + }, + "quartz": { + "mass": 0.342, + "volume": 4.4745270386802215e-05, + "density": 7643.265914890397 + }, + "radio": { + "mass": 1.85, + "volume": 0.004800169556545512, + "density": 385.40305258120304 + }, + "raincoat": { + "mass": 1.0, + "volume": 0.037155621741167336, + "density": 26.913827656180207 + }, + "retainer": { + "mass": 0.015, + "volume": 2.7804002903179338e-05, + "density": 539.4906644282064 + }, + "rhubarb": { + "mass": 0.063, + "volume": 3.824812229804508e-05, + "density": 1647.1396820235545 + }, + "rice_cooker": { + "mass": 2.5, + "volume": 0.01983046502971164, + "density": 126.06865226076611 + }, + "sliced_roast_beef": { + "mass": 0.099, + "volume": 0.0007315862207649959, + "density": 135.32239562478216 + }, + "roasting_pan": { + "mass": 1.955, + "volume": 0.0016110291534853956, + "density": 1213.510007420063 + }, + "rolling_pin": { + "mass": 0.51, + "volume": 0.0009608602320733035, + "density": 530.7743863012663 + }, + "rope": { + "mass": 0.2, + "volume": 0.0001876239119732188, + "density": 1065.962210768464 + }, + "ruler": { + "mass": 0.047, + "volume": 1.1649522300474529e-05, + "density": 4034.5001956076358 + }, + "rutabaga": { + "mass": 0.855, + "volume": 0.0006853419995948492, + "density": 1247.5523176829186 + }, + "salmon": { + "mass": 0.161, + "volume": 0.0001101444137076348, + "density": 1461.7173452605168 + }, + "sauna_suit": { + "mass": 0.5, + "volume": 0.09771935506271442, + "density": 5.116693613860933 + }, + "scone": { + "mass": 0.12, + "volume": 0.00021713706467740867, + "density": 552.6463212454258 + }, + "screw": { + "mass": 0.01, + "volume": 5.319879271468436e-06, + "density": 1879.741905729323 + }, + "shaker": { + "mass": 0.15, + "volume": 8.202727505873296e-05, + "density": 1828.6600389028818 + }, + "shoe_box": { + "mass": 0.2, + "volume": 0.007899316124882934, + "density": 25.318647442149807 + }, + "shorts": { + "mass": 0.3, + "volume": 0.006695819644114952, + "density": 44.804074175396 + }, + "shovel": { + "mass": 1.5, + "volume": 0.0016446487781449637, + "density": 912.048833728429 + }, + "shrimp": { + "mass": 0.016, + "volume": 2.3447924875185414e-05, + "density": 682.3631551691194 + }, + "shutter": { + "mass": 4.75, + "volume": 0.007391057043543013, + "density": 642.6685617518948 + }, + "skates": { + "mass": 1.355, + "volume": 0.0075446761066687755, + "density": 179.59684164603289 + }, + "ski": { + "mass": 3.15, + "volume": 0.02222245379174105, + "density": 141.74852289132417 + }, + "smoker": { + "mass": 14.75, + "volume": 0.20465967201393168, + "density": 72.0708669903269 + }, + "snow_globe": { + "mass": 0.35, + "volume": 0.0006373795528173871, + "density": 549.1233574295047 + }, + "sod": { + "mass": 12.345, + "volume": 0.01295449655748071, + "density": 952.9509653442495 + }, + "softball": { + "mass": 0.18, + "volume": 0.0004600961844943159, + "density": 391.22254447259763 + }, + "sparkler": { + "mass": 0.023, + "volume": 1.9942727556970332e-06, + "density": 11533.026229384102 + }, + "sponge": { + "mass": 0.053, + "volume": 0.00015435000000000215, + "density": 343.3754454162569 + }, + "squid": { + "mass": 0.037, + "volume": 8.889803203461851e-06, + "density": 4162.0718876646815 + }, + "star_anise": { + "mass": 0.003, + "volume": 1.7271440458699053e-06, + "density": 1736.9715092229028 + }, + "steamer_basket": { + "mass": 0.275, + "volume": 0.0012012433783242884, + "density": 228.9294617245839 + }, + "steel_wool": { + "mass": 0.092, + "volume": 0.00021737080461282747, + "density": 423.23991100767586 + }, + "sticker": { + "mass": 0.005, + "volume": 1.7063338178512207e-06, + "density": 2930.2589843155542 + }, + "stroller": { + "mass": 10.0, + "volume": 0.04761998394969176, + "density": 209.99587086305033 + }, + "sunflower": { + "mass": 0.05, + "volume": 0.00010953164579501217, + "density": 456.48907799280863 + }, + "sunglasses": { + "mass": 0.03, + "volume": 3.144210390885797e-05, + "density": 954.1346242911025 + }, + "sweatshirt": { + "mass": 0.525, + "volume": 0.04519319405196087, + "density": 11.616793435674879 + }, + "syringe": { + "mass": 0.023, + "volume": 3.1061082746832294e-05, + "density": 740.4764408074477 + }, + "tablet": { + "mass": 0.556, + "volume": 0.00030997714115450433, + "density": 1793.680649899499 + }, + "tackle_box": { + "mass": 2.5, + "volume": 0.03335786609046672, + "density": 74.94484189186402 + }, + "taco": { + "mass": 0.123, + "volume": 0.00038250526909938416, + "density": 321.5641977680616 + }, + "tag": { + "mass": 0.01, + "volume": 1.9118897357035e-05, + "density": 523.0427159712949 + }, + "tank_top": { + "mass": 0.143, + "volume": 0.0021361950530654596, + "density": 66.9414526518979 + }, + "tarp": { + "mass": 2.825, + "volume": 0.1341947433314612, + "density": 21.051495236458305 + }, + "tassel": { + "mass": 0.05, + "volume": 8.279428441687724e-05, + "density": 603.9064212240203 + }, + "teacup": { + "mass": 0.25, + "volume": 6.0194391248056624e-05, + "density": 4153.210869261366 + }, + "teddy_bear": { + "mass": 0.4, + "volume": 0.0048208277571571735, + "density": 82.9733025425241 + }, + "tennis_ball": { + "mass": 0.057, + "volume": 0.00015201153993238994, + "density": 374.9715319333772 + }, + "tent": { + "mass": 5.5, + "volume": 1.0101466269404358, + "density": 5.4447541112507345 + }, + "textbook": { + "mass": 1.365, + "volume": 0.0027083198104082733, + "density": 504.00251652489635 + }, + "thermostat": { + "mass": 0.225, + "volume": 0.0004254458742685174, + "density": 528.8569324754874 + }, + "ticket": { + "mass": 0.002, + "volume": 8.245651709951091e-07, + "density": 2425.520832496893 + }, + "tights": { + "mass": 0.125, + "volume": 0.04372129567818464, + "density": 2.8590186558073696 + }, + "toolbox": { + "mass": 9.085, + "volume": 0.009085616869310191, + "density": 999.9321048511 + }, + "tortilla": { + "mass": 0.054, + "volume": 2.2722397630987595e-05, + "density": 2376.5097714141607 + }, + "tortilla_chips": { + "mass": 0.006, + "volume": 2.493776977984338e-05, + "density": 240.59890090290517 + }, + "tote": { + "mass": 0.574, + "volume": 0.009494671882690578, + "density": 60.454959064613945 + }, + "toy_train": { + "mass": 0.5, + "volume": 0.0009428956003721149, + "density": 530.2814010402365 + }, + "trombone": { + "mass": 1.6, + "volume": 0.0016819554783561238, + "density": 951.2736933820486 + }, + "trumpet": { + "mass": 1.45, + "volume": 0.0049524682432213404, + "density": 292.78330092972897 + }, + "tulip": { + "mass": 0.05, + "volume": 0.0001448463120672742, + "density": 345.1934625493081 + }, + "tuna": { + "mass": 28.92, + "volume": 0.008574052877406962, + "density": 3372.967301870225 + }, + "tupperware": { + "mass": 0.35, + "volume": 0.0006122002877463825, + "density": 571.7083232489351 + }, + "twine": { + "mass": 0.033, + "volume": 6.853483229512779e-05, + "density": 481.5069782018859 + }, + "utility_knife": { + "mass": 0.185, + "volume": 8.345245542671885e-05, + "density": 2216.831117239587 + }, + "valentine_wreath": { + "mass": 0.5, + "volume": 0.0008274552716972406, + "density": 604.2622690340972 + }, + "vest": { + "mass": 0.46, + "volume": 0.016994711457283686, + "density": 27.067243898562968 + }, + "violin": { + "mass": 0.5, + "volume": 0.0033890972225591575, + "density": 147.53191400701175 + }, + "violin_case": { + "mass": 2.125, + "volume": 0.011690219158305055, + "density": 181.77589070178735 + }, + "bottle_of_vodka": { + "mass": 1.1, + "volume": 0.001446895738157386, + "density": 760.2482825755255 + }, + "waffle": { + "mass": 0.188, + "volume": 0.0026135380277408663, + "density": 71.93314120724946 + }, + "waffle_maker": { + "mass": 2.25, + "volume": 0.0020887715106768573, + "density": 1077.1881886070428 + }, + "wallet": { + "mass": 0.1, + "volume": 0.00026976285540273595, + "density": 370.69595756875947 + }, + "water_dispenser": { + "mass": 14.83, + "volume": 0.01921714267513086, + "density": 771.706816705466 + }, + "water_filter": { + "mass": 0.35, + "volume": 0.000737347646859156, + "density": 474.67432966101944 + }, + "watering_can": { + "mass": 1.9, + "volume": 0.013800392956807054, + "density": 137.67723904287982 + }, + "white_chocolate": { + "mass": 0.128, + "volume": 0.00015605355282880098, + "density": 820.2312454905963 + }, + "whitewall_tire": { + "mass": 5.85, + "volume": 0.004005681846711295, + "density": 1460.4255215133742 + }, + "wire_cutter": { + "mass": 0.275, + "volume": 7.16745761968618e-05, + "density": 3836.7858533921913 + }, + "wrapping_paper": { + "mass": 0.085, + "volume": 0.00010657449118680308, + "density": 797.5642112239838 + }, + "zipper": { + "mass": 0.01, + "volume": 8.320545742401491e-07, + "density": 12018.442431053545 + }, + "bottle_of_lemon_juice": { + "mass": 0.75, + "volume": 0.0006064723656625717, + "density": 1236.659809191181 + }, + "bar_soap": { + "mass": 0.179, + "volume": 0.0002144842280069672, + "density": 834.560198963373 + }, + "bottle_of_liquid_soap": { + "mass": 0.4, + "volume": 0.00034001651707892276, + "density": 1176.4134384893844 + }, + "cocktail_glass": { + "mass": 0.199, + "volume": 9.176087561899402e-05, + "density": 2168.6802644111654 + }, + "drip_pot": { + "mass": 0.675, + "volume": 0.0006084685609507491, + "density": 1109.3424431745393 + }, + "pool_stick": { + "mass": 0.525, + "volume": 0.0005566732381099721, + "density": 943.1026391397767 + }, + "pool_ball": { + "mass": 0.17, + "volume": 0.00010239731069940199, + "density": 1660.199851332549 + }, + "date": { + "mass": 0.017, + "volume": 9.182203296294014e-06, + "density": 1851.4074946327198 + }, + "cap": { + "mass": 0.016, + "volume": 2.5484219095832638e-05, + "density": 627.8395245242746 + }, + "bookcase_back": { + "mass": 5.3, + "volume": 0.03231999658208001, + "density": 163.9851658566886 + }, + "bookcase_shelf": { + "mass": 3.845, + "volume": 0.0044286290047480135, + "density": 868.2145187320288 + }, + "bookcase_top": { + "mass": 4.36, + "volume": 0.0076960234862680265, + "density": 566.5263376313137 + }, + "bookcase_baseboard": { + "mass": 0.55, + "volume": 0.000996873155590554, + "density": 551.7251587281198 + }, + "bookcase_side": { + "mass": 4.506, + "volume": 0.015755955836618263, + "density": 285.98709254615005 + }, + "bottle_of_beer": { + "mass": 0.428, + "volume": 0.0005413581881597983, + "density": 790.6040942224795 + }, + "box_of_cereal": { + "mass": 0.5, + "volume": 0.0013404348644840806, + "density": 373.0132759508943 + }, + "bag_of_chips": { + "mass": 0.15, + "volume": 0.002497264160770227, + "density": 60.06573207446975 + }, + "coconut_fruit": { + "mass": 1.32, + "volume": 0.0015471966698554773, + "density": 853.1559211042643 + }, + "bottle_of_cologne": { + "mass": 0.225, + "volume": 0.00032040333650030367, + "density": 702.239878203599 + }, + "boxed_cpu_board": { + "mass": 1.365, + "volume": 0.00408718709823888, + "density": 333.9705198688267 + }, + "bottle_of_detergent": { + "mass": 1.884, + "volume": 0.0025541725317342495, + "density": 737.6165770292694 + }, + "ginger_root": { + "mass": 0.05, + "volume": 9.237108512147592e-05, + "density": 541.2949294061632 + }, + "boxed_ink_cartridge": { + "mass": 0.125, + "volume": 0.00018977483046488455, + "density": 658.6753348365113 + }, + "jar_of_jam": { + "mass": 0.477, + "volume": 0.000501281725721068, + "density": 951.5607202992688 + }, + "tube_of_lotion": { + "mass": 0.225, + "volume": 0.0002602288425790078, + "density": 864.6236050167574 + }, + "jar_of_mayonnaise": { + "mass": 0.475, + "volume": 0.0002531380450805868, + "density": 1876.4465051027123 + }, + "bottle_of_medicine": { + "mass": 0.1, + "volume": 0.00016148352368824882, + "density": 619.2582234770557 + }, + "jug_of_milk": { + "mass": 2.735, + "volume": 0.002608420261414507, + "density": 1048.5273559855154 + }, + "bucket_of_paint": { + "mass": 4.75, + "volume": 0.0029958901953800843, + "density": 1585.5053724348447 + }, + "pack_of_pasta": { + "mass": 0.5, + "volume": 0.00033002858365805776, + "density": 1515.0202884185614 + }, + "bottle_of_perfume": { + "mass": 0.22, + "volume": 0.00020409368067539577, + "density": 1077.9363636932135 + }, + "wading_pool": { + "mass": 25.0, + "volume": 2.2170019581033698, + "density": 11.276489814825121 + }, + "pack_of_protein_powder": { + "mass": 0.85, + "volume": 0.0027845900154811285, + "density": 305.2513997659849 + }, + "jar_of_puree": { + "mass": 0.435, + "volume": 0.000246747738322289, + "density": 1762.934091950321 + }, + "boxed_router": { + "mass": 1.1, + "volume": 0.011151259529727786, + "density": 98.64356551540615 + }, + "jar_of_spaghetti_sauce": { + "mass": 0.6, + "volume": 0.0007450007655063513, + "density": 805.3682999804714 + }, + "bottle_of_sunscreen": { + "mass": 0.15, + "volume": 8.32821310719414e-05, + "density": 1801.1066488011197 + }, + "tube_of_toothpaste": { + "mass": 0.135, + "volume": 6.677750242424507e-05, + "density": 2021.6389517285274 + }, + "cup_of_yogurt": { + "mass": 0.175, + "volume": 0.00012871741756453312, + "density": 1359.5673632300995 + }, + "bag_of_cookies": { + "mass": 0.275, + "volume": 0.00044704809255663436, + "density": 615.1463446075695 + }, + "hose_cart": { + "mass": 8.0, + "volume": 0.027128010926577163, + "density": 294.8981413216125 + }, + "jar_of_grains": { + "mass": 1.5, + "volume": 0.007583296888550837, + "density": 197.8031484254138 + }, + "paint_roller": { + "mass": 0.5, + "volume": 0.0025156223494652583, + "density": 198.7579733922638 + }, + "half_watermelon": { + "mass": 3.75, + "volume": 0.008534017912878314, + "density": 439.4178730678592 + }, + "box_of_flour": { + "mass": 1.25, + "volume": 0.0031001778411320715, + "density": 403.2026754773351 + }, + "bottle_of_apple_juice": { + "mass": 1.125, + "volume": 0.000393339624858215, + "density": 2860.1237426956986 + }, + "bag_of_auricularia": { + "mass": 0.375, + "volume": 0.00043433674605253167, + "density": 863.385387969557 + }, + "bag_of_shiitake": { + "mass": 0.25, + "volume": 0.0004307795029580118, + "density": 580.3433039021998 + }, + "bottle_of_barbecue_sauce": { + "mass": 0.5, + "volume": 0.0002357727762407876, + "density": 2120.6858907635933 + }, + "box_of_brown_sugar": { + "mass": 1.0, + "volume": 0.001320677953653049, + "density": 757.1868654534281 + }, + "box_of_cane_sugar": { + "mass": 1.0, + "volume": 0.0011987658603875503, + "density": 834.1912570622497 + }, + "box_of_corn_flakes": { + "mass": 0.439, + "volume": 0.004550673002551612, + "density": 96.46924746160578 + }, + "box_of_lasagna": { + "mass": 0.5, + "volume": 0.002640291648908971, + "density": 189.37301877488096 + }, + "box_of_milk": { + "mass": 1.265, + "volume": 0.007057874999999999, + "density": 179.23241768946036 + }, + "box_of_sanitary_napkins": { + "mass": 0.25, + "volume": 0.0007273410862677424, + "density": 343.7176927304396 + }, + "box_of_tissues": { + "mass": 0.175, + "volume": 0.0010038957316442657, + "density": 174.32089258250966 + }, + "box_of_yogurt": { + "mass": 0.35, + "volume": 0.001055809176633656, + "density": 331.4992971702904 + }, + "bottle_of_carrot_juice": { + "mass": 0.495, + "volume": 0.0003933677585058146, + "density": 1258.3644421704253 + }, + "bottle_of_catsup": { + "mass": 0.56, + "volume": 0.0005617074847008346, + "density": 996.9601888040642 + }, + "bottle_of_garlic_sauce": { + "mass": 0.475, + "volume": 0.0003707753933479991, + "density": 1281.0990387222885 + }, + "bottle_of_hot_sauce": { + "mass": 0.4, + "volume": 0.00034837636667662446, + "density": 1148.183511458728 + }, + "bottle_of_lime_juice": { + "mass": 1.05, + "volume": 0.0021242656091449196, + "density": 494.28847102724427 + }, + "bottle_of_pesto": { + "mass": 0.3, + "volume": 0.0003080942258859369, + "density": 973.7280831451429 + }, + "bottle_of_tomato_paste": { + "mass": 0.425, + "volume": 0.00036135768769610197, + "density": 1176.1199898905168 + }, + "pack_of_bread": { + "mass": 0.5, + "volume": 0.003847333185557048, + "density": 129.96015054713956 + }, + "bottle_of_coffee": { + "mass": 0.875, + "volume": 0.003587162160662171, + "density": 243.92540978367134 + }, + "bottle_of_milk": { + "mass": 1.0, + "volume": 0.00045905062676277614, + "density": 2178.4089634121565 + }, + "bottle_of_soup": { + "mass": 0.825, + "volume": 0.0010944832636049508, + "density": 753.7803705491656 + }, + "box_of_fruit": { + "mass": 9.5, + "volume": 0.03310341991328149, + "density": 286.9794125466924 + }, + "box_of_lemons": { + "mass": 1.25, + "volume": 0.0006647389642059911, + "density": 1880.437385663234 + }, + "box_of_raspberries": { + "mass": 0.298, + "volume": 0.000857217143457871, + "density": 347.6365379230724 + }, + "bag_of_flour": { + "mass": 1.25, + "volume": 0.002383332328960051, + "density": 524.4757454976613 + }, + "bottle_of_ginger_beer": { + "mass": 0.425, + "volume": 0.00031067401949184774, + "density": 1367.993373553247 + }, + "bottle_of_lemon_sauce": { + "mass": 0.417, + "volume": 0.0005442363515016117, + "density": 766.211222108645 + }, + "can_of_baking_mix": { + "mass": 0.5, + "volume": 0.0007656260003630039, + "density": 653.0603712033507 + }, + "box_of_baking_mix": { + "mass": 0.387, + "volume": 0.0008787095482988878, + "density": 440.4185669191844 + }, + "bottle_of_mushroom_sauce": { + "mass": 0.425, + "volume": 0.000731877039881199, + "density": 580.6986376686822 + }, + "can_of_oatmeal": { + "mass": 0.452, + "volume": 0.0008808057977031577, + "density": 513.1664677715139 + }, + "jar_of_orange_sauce": { + "mass": 0.486, + "volume": 0.0005298444212062004, + "density": 917.2503862428375 + }, + "box_of_apple_juice": { + "mass": 1.0, + "volume": 0.0004755802700054454, + "density": 2102.6944620485415 + }, + "bag_of_cream_cheese": { + "mass": 0.305, + "volume": 0.00021757430034344426, + "density": 1401.8199737678253 + }, + "bag_of_ice_cream": { + "mass": 0.5, + "volume": 0.00031494183021852224, + "density": 1587.594762032961 + }, + "bottle_of_lemonade": { + "mass": 0.425, + "volume": 0.00023566255898045674, + "density": 1803.4260590170577 + }, + "bottle_of_papaya_juice": { + "mass": 1.365, + "volume": 0.0014383058798840922, + "density": 949.0331779148398 + }, + "bottle_of_soy_milk": { + "mass": 1.0, + "volume": 0.0007227228655242694, + "density": 1383.6562363010216 + }, + "bottle_of_tonic": { + "mass": 0.875, + "volume": 0.001933559334932324, + "density": 452.53330693915615 + }, + "box_of_ice_cream": { + "mass": 1.25, + "volume": 0.0022595837083421444, + "density": 553.199244349803 + }, + "can_of_icetea": { + "mass": 0.35, + "volume": 0.000592454552231711, + "density": 590.7626140799975 + }, + "carton_of_milk": { + "mass": 0.965, + "volume": 0.0011553488450475138, + "density": 835.2455659920743 + }, + "carton_of_orange_juice": { + "mass": 1.347, + "volume": 0.002072163093791199, + "density": 650.0453579334572 + }, + "carton_of_pineapple_juice": { + "mass": 0.33, + "volume": 0.00022918023361193112, + "density": 1439.914755295983 + }, + "pack_of_chocolate_bar": { + "mass": 0.125, + "volume": 2.2003058183309915e-05, + "density": 5681.0284715247835 + }, + "bottle_of_coconut_water": { + "mass": 0.5, + "volume": 0.0006101567043043214, + "density": 819.4616177660162 + }, + "box_of_cream": { + "mass": 0.031, + "volume": 6.12025361664007e-06, + "density": 5065.149574147639 + }, + "bottle_of_fruit_punch": { + "mass": 1.35, + "volume": 0.001348976047842208, + "density": 1000.7590588131123 + }, + "bottle_of_lotion": { + "mass": 0.45, + "volume": 0.0005738053556509359, + "density": 784.2380618589928 + }, + "bag_of_popcorn": { + "mass": 0.23, + "volume": 0.002240883983738409, + "density": 102.63806679375563 + }, + "boxed_cake": { + "mass": 0.5, + "volume": 0.0010380593830840038, + "density": 481.6680125895438 + }, + "box_of_champagne": { + "mass": 4.375, + "volume": 0.003554194246765692, + "density": 1230.9400376699273 + }, + "box_of_rum": { + "mass": 3.5, + "volume": 0.004044514822254593, + "density": 865.3695569964418 + }, + "box_of_whiskey": { + "mass": 2.771, + "volume": 0.004078134970624932, + "density": 679.4772659462453 + }, + "box_of_butter": { + "mass": 0.477, + "volume": 0.000686497230230829, + "density": 694.8316453361548 + }, + "carton_of_soy_milk": { + "mass": 1.0, + "volume": 0.0015925191130576216, + "density": 627.9359486493129 + }, + "box_of_coffee": { + "mass": 0.55, + "volume": 0.0018029502655761511, + "density": 305.0555583818292 + }, + "pack_of_ramen": { + "mass": 0.2, + "volume": 0.0013159113908989238, + "density": 151.98591742820636 + }, + "bottle_of_rum": { + "mass": 1.4, + "volume": 0.0011776575522035688, + "density": 1188.8005960479734 + }, + "bottle_of_soda": { + "mass": 0.725, + "volume": 0.00048177695749949837, + "density": 1504.8457355928128 + }, + "bottle_of_tea": { + "mass": 0.5, + "volume": 0.0008745659009486394, + "density": 571.7122054011611 + }, + "box_of_vegetable_juice": { + "mass": 0.612, + "volume": 0.0003296050353897181, + "density": 1856.7677501540109 + }, + "shampoo_dispenser": { + "mass": 0.26, + "volume": 0.00029031188964517173, + "density": 895.5885352052929 + }, + "conditioner_dispenser": { + "mass": 0.3, + "volume": 0.0004828997967352254, + "density": 621.2468964125293 + }, + "bag_of_tea": { + "mass": 0.35, + "volume": 0.0013421489766903328, + "density": 260.7758200308591 + }, + "wrapped_hamburger": { + "mass": 0.205, + "volume": 0.0003010463472810737, + "density": 680.9582705502835 + }, + "bottle_of_mustard": { + "mass": 0.5, + "volume": 0.0008186716481300097, + "density": 610.7454693735738 + }, + "isopropanol_dispenser": { + "mass": 0.253, + "volume": 0.0001801466589387808, + "density": 1404.4112807330885 + }, + "bottle_of_cooking_oil": { + "mass": 0.92, + "volume": 0.0003453949209029744, + "density": 2663.617628177107 + }, + "can_of_tomato_paste": { + "mass": 0.425, + "volume": 0.0006052984079283818, + "density": 702.1330213878333 + }, + "roof": { + "mass": 5000.0, + "volume": 85.6889389033127, + "density": 58.3505883488855 + }, + "bottle_of_shampoo": { + "mass": 0.5, + "volume": 0.00045600326601881577, + "density": 1096.4833747032171 + }, + "bottle_of_vinegar": { + "mass": 0.462, + "volume": 0.0002156367932813497, + "density": 2142.4915153380653 + }, + "glue_stick": { + "mass": 0.023, + "volume": 2.9297103430954984e-05, + "density": 785.0605454632919 + }, + "bottle_of_glue": { + "mass": 0.225, + "volume": 0.00016054266289521518, + "density": 1401.4966236535865 + }, + "spray_can": { + "mass": 0.25, + "volume": 0.00018279425553565222, + "density": 1367.657858106159 + }, + "hamper": { + "mass": 2.0, + "volume": 0.004980712770432549, + "density": 401.5489533692404 + }, + "volleyball": { + "mass": 0.265, + "volume": 0.006564140691412824, + "density": 40.3708592575829 + }, + "loin": { + "mass": 0.68, + "volume": 0.0005091322234750803, + "density": 1335.605896948856 + }, + "air_filter": { + "mass": 0.3, + "volume": 0.001005833945207648, + "density": 298.2599676908566 + }, + "air_freshener_atomizer": { + "mass": 0.25, + "volume": 0.0061153609782876265, + "density": 40.88066115599982 + }, + "bottle_of_alfredo_sauce": { + "mass": 0.45, + "volume": 0.0002933279706958854, + "density": 1534.1189554219088 + }, + "box_of_almond_milk": { + "mass": 1.043, + "volume": 0.0010414680204504645, + "density": 1001.4709808841493 + }, + "bottle_of_antihistamines": { + "mass": 0.15, + "volume": 0.0003975144617090834, + "density": 377.3447621379266 + }, + "bottle_of_apple_cider": { + "mass": 1.5, + "volume": 0.0010346634539248518, + "density": 1449.7467696476172 + }, + "arepa": { + "mass": 0.175, + "volume": 0.0006194886027365472, + "density": 282.4910728412917 + }, + "bottle_of_aspirin": { + "mass": 0.083, + "volume": 0.00013436701636192097, + "density": 617.7111187498381 + }, + "bottle_of_baby_oil": { + "mass": 0.275, + "volume": 0.0004332270345733802, + "density": 634.7710970318507 + }, + "box_of_baking_powder": { + "mass": 0.316, + "volume": 0.0020996804588094883, + "density": 150.4990907898295 + }, + "box_of_baking_soda": { + "mass": 0.5, + "volume": 0.0004918197919220324, + "density": 1016.632531289559 + }, + "box_of_barley": { + "mass": 0.75, + "volume": 0.000915091611959826, + "density": 819.5900718549327 + }, + "can_of_bay_leaves": { + "mass": 0.125, + "volume": 0.0002488694708694606, + "density": 502.2713294776369 + }, + "bird_feeder": { + "mass": 0.2, + "volume": 9.431857581363844e-05, + "density": 2120.473069856087 + }, + "bottle_of_bleach_agent": { + "mass": 1.5, + "volume": 0.007993905454691703, + "density": 187.64294980742298 + }, + "bag_of_breadcrumbs": { + "mass": 0.46, + "volume": 0.0013247224801448518, + "density": 347.24254090539876 + }, + "broccolini": { + "mass": 0.105, + "volume": 3.334884149000393e-05, + "density": 3148.5351607033476 + }, + "bag_of_brown_rice": { + "mass": 2.25, + "volume": 0.010415478158711031, + "density": 216.02464771319237 + }, + "cactus": { + "mass": 0.5, + "volume": 0.001609093614614083, + "density": 310.7339408092285 + }, + "calendar": { + "mass": 0.485, + "volume": 0.0006412438568755474, + "density": 756.342528352874 + }, + "catalog": { + "mass": 0.3, + "volume": 0.00038232450764306, + "density": 784.6737365842146 + }, + "bottle_of_caulk": { + "mass": 0.5, + "volume": 0.0005116900666195152, + "density": 977.1540090728246 + }, + "cd": { + "mass": 0.016, + "volume": 2.8901322241882134e-05, + "density": 553.6078891509579 + }, + "centerpiece": { + "mass": 2.925, + "volume": 0.024404389280397967, + "density": 119.85548855137347 + }, + "charger": { + "mass": 0.055, + "volume": 1.9204817988040246e-05, + "density": 2863.864684073086 + }, + "cheesecake": { + "mass": 0.203, + "volume": 0.00023566067554124518, + "density": 861.408037356114 + }, + "bouillon_cube": { + "mass": 0.011, + "volume": 6.959943507696409e-06, + "density": 1580.4725983531384 + }, + "chicken_tender": { + "mass": 0.073, + "volume": 4.550852011725448e-05, + "density": 1604.0952290233267 + }, + "chicken_wire": { + "mass": 6.05, + "volume": 0.4318782899549305, + "density": 14.008576352914982 + }, + "bottle_of_chocolate_sauce": { + "mass": 0.725, + "volume": 0.0005704509029956234, + "density": 1270.924449751572 + }, + "cilantro": { + "mass": 0.002, + "volume": 8.899326018183823e-07, + "density": 2247.361200065531 + }, + "sliced_lemon": { + "mass": 0.025, + "volume": 1.1817781180249487e-05, + "density": 2115.4563296349866 + }, + "bottle_of_cleaner": { + "mass": 0.6, + "volume": 0.00046858494442890647, + "density": 1280.4508705060023 + }, + "bottle_of_cocoa": { + "mass": 0.625, + "volume": 0.0010092389752694936, + "density": 619.2785012420952 + }, + "box_of_coconut_milk": { + "mass": 0.8, + "volume": 0.0010683508377742406, + "density": 748.8176839610928 + }, + "bottle_of_coconut_milk": { + "mass": 1.115, + "volume": 0.001718105639606446, + "density": 648.9705721793713 + }, + "bottle_of_coconut_oil": { + "mass": 0.5, + "volume": 0.0006061749398829629, + "density": 824.8443924398085 + }, + "copper_wire": { + "mass": 4.0, + "volume": 0.056613215441851564, + "density": 70.65488099873909 + }, + "bottle_of_cranberry_juice": { + "mass": 1.035, + "volume": 0.0011299892996233796, + "density": 915.9378768851712 + }, + "bottle_of_skin_cream": { + "mass": 0.15, + "volume": 8.15541467262647e-05, + "density": 1839.2688296215374 + }, + "bottle_of_chili_pepper": { + "mass": 0.225, + "volume": 0.0002488848323614403, + "density": 904.0325915612495 + }, + "jar_of_cumin": { + "mass": 0.325, + "volume": 0.0008705028821390341, + "density": 373.34741408483006 + }, + "jar_of_curry_powder": { + "mass": 0.175, + "volume": 0.00025180600897705313, + "density": 694.979443544366 + }, + "jar_of_dill_seed": { + "mass": 0.225, + "volume": 0.00026715614916678526, + "density": 842.2040843968475 + }, + "doll": { + "mass": 0.428, + "volume": 0.012965799093546207, + "density": 33.00992070847675 + }, + "bottle_of_essential_oil": { + "mass": 0.035, + "volume": 2.1695753004726964e-05, + "density": 1613.2189554506072 + }, + "bottle_of_fabric_softener": { + "mass": 1.4, + "volume": 0.001439158108151982, + "density": 972.7909616530842 + }, + "bottle_of_face_cream": { + "mass": 0.225, + "volume": 0.0002407576022827062, + "density": 934.5499285035949 + }, + "bottle_of_fennel": { + "mass": 0.385, + "volume": 0.00026037373397851636, + "density": 1478.6437714633944 + }, + "bag_of_fertilizer": { + "mass": 17.5, + "volume": 0.016687211596231825, + "density": 1048.7072629888455 + }, + "bottle_of_frosting": { + "mass": 0.529, + "volume": 0.00022499677474982147, + "density": 2351.144813467686 + }, + "bottle_of_ginger": { + "mass": 0.425, + "volume": 0.0003539057132649737, + "density": 1200.884823472169 + }, + "bottle_of_glass_cleaner": { + "mass": 0.75, + "volume": 0.0008334316157484756, + "density": 899.8938675087954 + }, + "bottle_of_ground_cloves": { + "mass": 0.118, + "volume": 0.00026609329722176013, + "density": 443.4534850446071 + }, + "bottle_of_ground_mace": { + "mass": 0.125, + "volume": 0.0002670761729217496, + "density": 468.03126850489815 + }, + "bottle_of_ground_nutmeg": { + "mass": 0.11, + "volume": 0.00026947354314116784, + "density": 408.20333869427327 + }, + "bottle_of_conditioner": { + "mass": 0.46, + "volume": 0.0002699565222296224, + "density": 1703.9780932157973 + }, + "icicle_lights": { + "mass": 0.5, + "volume": 0.017877366399757934, + "density": 27.96832535729481 + }, + "kabob": { + "mass": 0.23, + "volume": 0.00022416734875548984, + "density": 1026.0191828867644 + }, + "skiff": { + "mass": 125.0, + "volume": 0.1814832069916557, + "density": 688.7689614485779 + }, + "farm_stand": { + "mass": 150.0, + "volume": 2.993832973206053, + "density": 50.10299550524596 + }, + "sourdough": { + "mass": 0.5, + "volume": 0.0009650653156996029, + "density": 518.0996476259598 + }, + "toast": { + "mass": 0.041, + "volume": 0.00015911816197554038, + "density": 257.67014582724073 + }, + "hamburger_bun": { + "mass": 0.05, + "volume": 9.695153124573966e-05, + "density": 515.7216122071012 + }, + "fruitcake": { + "mass": 1.45, + "volume": 0.0018784977001445175, + "density": 771.8934124265619 + }, + "digital_camera": { + "mass": 0.471, + "volume": 0.0007547828813724461, + "density": 624.020511890208 + }, + "pillar_candle": { + "mass": 1.123, + "volume": 0.0008767356773909578, + "density": 1280.887762366293 + }, + "cedar_chest": { + "mass": 5.75, + "volume": 0.01506939470231446, + "density": 381.56807977940053 + }, + "key": { + "mass": 0.013, + "volume": 3.259031367868098e-07, + "density": 39889.15273467888 + }, + "bottle_of_lacquer": { + "mass": 0.5, + "volume": 0.0006906842678470979, + "density": 723.9197753244451 + }, + "bottle_of_lavender_oil": { + "mass": 0.1, + "volume": 2.85606603465478e-05, + "density": 3501.3196048909726 + }, + "leaf": { + "mass": 0.02, + "volume": 3.970956032059996e-05, + "density": 503.65704980180016 + }, + "leaf_blower": { + "mass": 3.75, + "volume": 0.013090510823338635, + "density": 286.4670485825695 + }, + "leek": { + "mass": 0.222, + "volume": 0.00038805903379674357, + "density": 572.0779073945706 + }, + "legging": { + "mass": 0.225, + "volume": 0.022856665739409313, + "density": 9.843955481750625 + }, + "leotard": { + "mass": 0.325, + "volume": 0.007883669252762925, + "density": 41.224459015210456 + }, + "chocolate_chip_cookie": { + "mass": 0.043, + "volume": 9.32668664921667e-05, + "density": 461.0426147812255 + }, + "chocolate_biscuit": { + "mass": 0.023, + "volume": 4.241411523407786e-05, + "density": 542.2723042332973 + }, + "butter_cookie": { + "mass": 0.019, + "volume": 1.124887529824478e-05, + "density": 1689.0577498858636 + }, + "bottle_of_sour_cream": { + "mass": 0.463, + "volume": 0.001718260976406464, + "density": 269.4584852693965 + }, + "cookie_dough": { + "mass": 1.95, + "volume": 0.0018757690506209781, + "density": 1039.5736081445887 + }, + "chocolate_cake": { + "mass": 0.25, + "volume": 0.00013899918866246198, + "density": 1798.5716492711788 + }, + "cinnamon_roll": { + "mass": 0.088, + "volume": 6.0986531161190676e-05, + "density": 1442.9415532326518 + }, + "clothes_dryer": { + "mass": 49.5, + "volume": 0.07284889532667432, + "density": 679.4886837752102 + }, + "rubber_eraser": { + "mass": 0.012, + "volume": 1.1897094316002641e-05, + "density": 1008.649648499377 + }, + "license_plate": { + "mass": 0.35, + "volume": 0.0001979597992482577, + "density": 1768.035739221333 + }, + "lock": { + "mass": 0.26, + "volume": 2.7377488381345902e-05, + "density": 9496.85363311688 + }, + "skyrocket": { + "mass": 0.15, + "volume": 0.00012875807597006523, + "density": 1164.9754694600535 + }, + "national_flag": { + "mass": 0.45, + "volume": 0.0047545207035819565, + "density": 94.64676421768011 + }, + "canteen": { + "mass": 0.5, + "volume": 0.0006129207836617952, + "density": 815.766104410478 + }, + "bottle_of_lubricant": { + "mass": 0.8, + "volume": 0.0018842968322549305, + "density": 424.56155861740916 + }, + "lunch_box": { + "mass": 0.4, + "volume": 0.0007677032682964444, + "density": 521.0346451795256 + }, + "mac_and_cheese": { + "mass": 0.059, + "volume": 3.222649604139005e-05, + "density": 1830.791654302827 + }, + "lily": { + "mass": 0.1, + "volume": 0.0015215355477343829, + "density": 65.72307833944684 + }, + "macaron": { + "mass": 0.023, + "volume": 4.6574336095847223e-05, + "density": 493.83419986207343 + }, + "mail": { + "mass": 0.028, + "volume": 7.496994137024885e-05, + "density": 373.4830185036206 + }, + "mallet": { + "mass": 0.725, + "volume": 0.0002647516888787954, + "density": 2738.415014726907 + }, + "bottle_of_maple_syrup": { + "mass": 0.62, + "volume": 0.000597707680267365, + "density": 1037.2963581840932 + }, + "marigold": { + "mass": 0.363, + "volume": 0.0015639230852300024, + "density": 232.10860139366412 + }, + "bottle_of_mayonnaise": { + "mass": 0.7, + "volume": 0.001336990901257919, + "density": 523.5637724545464 + }, + "rubber_glove": { + "mass": 0.053, + "volume": 0.0002850841754632042, + "density": 185.9100032959939 + }, + "sliced_melon": { + "mass": 0.5, + "volume": 0.0012240674974927806, + "density": 408.4742067117495 + }, + "bottle_of_milkshake": { + "mass": 0.487, + "volume": 0.0005590829188798201, + "density": 871.0693593997727 + }, + "bottle_of_cold_cream": { + "mass": 0.25, + "volume": 0.00027095257837105063, + "density": 922.6706809840446 + }, + "bottle_of_molasses": { + "mass": 1.145, + "volume": 0.0008419356762223995, + "density": 1359.9613751223737 + }, + "money": { + "mass": 0.001, + "volume": 1.158240427633537e-05, + "density": 86.33786009724713 + }, + "mop": { + "mass": 1.5, + "volume": 0.003962565874261777, + "density": 378.54260284807225 + }, + "mop_bucket": { + "mass": 3.125, + "volume": 0.018741817097508245, + "density": 166.73943533551363 + }, + "mousepad": { + "mass": 0.191, + "volume": 0.0025272424864498716, + "density": 75.57644390044506 + }, + "bottle_of_mustard_seeds": { + "mass": 0.2, + "volume": 0.00026009655768991755, + "density": 768.9452016448308 + }, + "bottle_of_oil": { + "mass": 1.25, + "volume": 0.009213696954223222, + "density": 135.66758340440595 + }, + "sliced_onion": { + "mass": 0.038, + "volume": 9.374261531831564e-05, + "density": 405.36526393002686 + }, + "bottle_of_onion_powder": { + "mass": 0.2, + "volume": 0.000266712853338564, + "density": 749.8701224800778 + }, + "storage_organizer": { + "mass": 4.0, + "volume": 0.05000517077103274, + "density": 79.99172762183909 + }, + "bottle_of_paint_remover": { + "mass": 0.625, + "volume": 0.0007920304740600171, + "density": 789.1110512404853 + }, + "virginia_ham": { + "mass": 4.016, + "volume": 0.0056526323360682005, + "density": 710.4654541875631 + }, + "serving_cart": { + "mass": 17.5, + "volume": 0.03764174406516871, + "density": 464.90938277733505 + }, + "jar_of_pepper": { + "mass": 0.75, + "volume": 0.007568992703243136, + "density": 99.08848236551246 + }, + "ruby": { + "mass": 0.002, + "volume": 2.417499887690988e-08, + "density": 82730.09691471994 + }, + "parer": { + "mass": 0.085, + "volume": 3.840872677682468e-05, + "density": 2213.0387318979783 + }, + "buttermilk_pancake": { + "mass": 0.145, + "volume": 0.0011708202232388481, + "density": 123.84480308931245 + }, + "bottle_of_black_pepper": { + "mass": 0.16, + "volume": 0.0002670308035048201, + "density": 599.1818093642215 + }, + "sliced_papaya": { + "mass": 0.054, + "volume": 6.70901681168002e-05, + "density": 804.886938217073 + }, + "bottle_of_paprika": { + "mass": 0.175, + "volume": 0.00026617570607653156, + "density": 657.4604518929444 + }, + "bottle_of_peanut_butter": { + "mass": 0.477, + "volume": 0.0008803193129562482, + "density": 541.8488416415179 + }, + "peppermint_candy": { + "mass": 0.023, + "volume": 1.587625372312847e-05, + "density": 1448.7044866569297 + }, + "bottle_of_pesticide": { + "mass": 0.45, + "volume": 0.0003960300864243548, + "density": 1136.2773067645555 + }, + "pipe": { + "mass": 2.5, + "volume": 0.00038423934394151023, + "density": 6506.361306874799 + }, + "toy_figure": { + "mass": 0.225, + "volume": 0.0004029157442361023, + "density": 558.4294066904308 + }, + "swimming_pool": { + "mass": 75000.0, + "volume": 0.15956323803082503, + "density": 470033.07858111535 + }, + "shoe_rack": { + "mass": 4.75, + "volume": 0.020434919601212354, + "density": 232.44525022345545 + }, + "whiskey_stone": { + "mass": 0.199, + "volume": 8.297476148752233e-05, + "density": 2398.3196387967378 + }, + "boulder": { + "mass": 164.5, + "volume": 0.020847976950178138, + "density": 7890.453850419976 + }, + "bottle_of_pizza_sauce": { + "mass": 0.525, + "volume": 0.00047867085957773814, + "density": 1096.7870500057834 + }, + "jar_of_bath_salt": { + "mass": 0.45, + "volume": 0.00024695272442380587, + "density": 1822.2111177349727 + }, + "club_sandwich": { + "mass": 0.375, + "volume": 0.0027063572222381484, + "density": 138.56263944708536 + }, + "pack_of_kielbasa": { + "mass": 0.477, + "volume": 0.0005740250731825635, + "density": 830.9741547618678 + }, + "ripsaw": { + "mass": 0.675, + "volume": 5.914981308221088e-05, + "density": 11411.701319526303 + }, + "chainsaw": { + "mass": 4.8, + "volume": 0.01225804330287028, + "density": 391.57962501862403 + }, + "shears": { + "mass": 0.262, + "volume": 9.069289123186586e-06, + "density": 28888.70301093055 + }, + "dress_shirt": { + "mass": 0.275, + "volume": 0.07706870958547882, + "density": 3.568244511671636 + }, + "bottle_of_poppy_seeds": { + "mass": 0.16, + "volume": 0.00036520377766519627, + "density": 438.1115688969718 + }, + "postage_stamp": { + "mass": 0.001, + "volume": 4.3902349621091194e-07, + "density": 2277.782416273202 + }, + "bottle_of_seasoning": { + "mass": 0.175, + "volume": 0.00026587676166737323, + "density": 658.1996820727597 + }, + "power_washer": { + "mass": 12.17, + "volume": 0.027948561354828746, + "density": 435.44280671525 + }, + "pruner": { + "mass": 0.75, + "volume": 0.00017323506583227888, + "density": 4329.377521789544 + }, + "bottle_of_pumpkin_pie_spice": { + "mass": 0.179, + "volume": 0.00022528521353142226, + "density": 794.5483735666188 + }, + "quiche": { + "mass": 0.638, + "volume": 0.0007261549472799501, + "density": 878.6003626221054 + }, + "receipt": { + "mass": 0.001, + "volume": 0.00010942579200033458, + "density": 9.138613317022575 + }, + "bottle_of_sage": { + "mass": 0.168, + "volume": 0.0002658399409483878, + "density": 631.959213505155 + }, + "bottle_of_salsa": { + "mass": 0.79, + "volume": 0.0013728039382358743, + "density": 575.4645495956195 + }, + "bottle_of_disinfectant": { + "mass": 0.5, + "volume": 0.0008750359312872259, + "density": 571.4051070616866 + }, + "saxophone": { + "mass": 2.5, + "volume": 0.01643664533663064, + "density": 152.0991631077243 + }, + "scoop": { + "mass": 0.103, + "volume": 3.260282689677291e-05, + "density": 3159.2352505541517 + }, + "octopus": { + "mass": 0.11, + "volume": 0.00014148799033868363, + "density": 777.4511443458206 + }, + "bottle_of_sealant": { + "mass": 0.545, + "volume": 0.0005432347665351953, + "density": 1003.2494854408225 + }, + "bottle_of_sesame_oil": { + "mass": 0.5, + "volume": 0.0008406300341096898, + "density": 594.7919771026851 + }, + "bottle_of_sesame_seeds": { + "mass": 0.25, + "volume": 0.000254963289539697, + "density": 980.5333169780733 + }, + "shiitake": { + "mass": 0.023, + "volume": 3.565952377666652e-05, + "density": 644.9889837017352 + }, + "sieve": { + "mass": 0.225, + "volume": 0.00011462190548097485, + "density": 1962.9755678537895 + }, + "bottle_of_soy_sauce": { + "mass": 1.05, + "volume": 0.0009986853363179431, + "density": 1051.3822140127231 + }, + "bottle_of_paint": { + "mass": 0.45, + "volume": 0.0004337366609612429, + "density": 1037.495882876754 + }, + "squeegee": { + "mass": 0.225, + "volume": 8.496406322694439e-05, + "density": 2648.1784351462898 + }, + "bottle_of_sriracha": { + "mass": 0.558, + "volume": 0.000833164493142117, + "density": 669.7356939631597 + }, + "stake": { + "mass": 0.205, + "volume": 7.463448520881927e-05, + "density": 2746.7195549943435 + }, + "staple": { + "mass": 0.001, + "volume": 3.392806053089068e-08, + "density": 29474.128033034016 + }, + "bag_of_starch": { + "mass": 6.915, + "volume": 0.03143672446570688, + "density": 219.96566491980767 + }, + "bottle_of_solvent": { + "mass": 1.2, + "volume": 0.0006766793776455343, + "density": 1773.365702639452 + }, + "sugar_cube": { + "mass": 0.006, + "volume": 7.999985507291946e-06, + "density": 750.0013586938416 + }, + "bottle_of_supplements": { + "mass": 0.25, + "volume": 0.00038275158971775474, + "density": 653.1651512782814 + }, + "bottle_of_almond_oil": { + "mass": 0.465, + "volume": 0.0007749894284973405, + "density": 600.0081845007977 + }, + "tablecloth": { + "mass": 1.3, + "volume": 0.5415032602313259, + "density": 2.4007242346881723 + }, + "box_of_takeout": { + "mass": 0.375, + "volume": 0.002603417874893328, + "density": 144.04141709880716 + }, + "tank": { + "mass": 20.0, + "volume": 0.009840827687857026, + "density": 2032.3493749086538 + }, + "bottle_of_tea_leaves": { + "mass": 0.225, + "volume": 0.0002660720646433864, + "density": 845.6355623111548 + }, + "bottle_of_tequila": { + "mass": 1.15, + "volume": 0.0005935671940436435, + "density": 1937.438611062193 + }, + "sliced_tomato": { + "mass": 0.026, + "volume": 9.638301589356785e-05, + "density": 269.7570703609319 + }, + "bag_of_snacks": { + "mass": 0.25, + "volume": 0.001582292804484803, + "density": 157.99856972831296 + }, + "turkey": { + "mass": 5.65, + "volume": 0.007666409951383443, + "density": 736.9811992613868 + }, + "tweezers": { + "mass": 0.02, + "volume": 2.446177805485889e-07, + "density": 81760.20547299243 + }, + "vegetable_peeler": { + "mass": 0.075, + "volume": 7.12570472486563e-05, + "density": 1052.5274747672663 + }, + "wheelbarrow": { + "mass": 22.5, + "volume": 0.08218875442927001, + "density": 273.7600801501749 + }, + "whetstone": { + "mass": 3.085, + "volume": 0.0020667231095739024, + "density": 1492.701168196661 + }, + "whistle": { + "mass": 0.023, + "volume": 1.4601012482186196e-05, + "density": 1575.2332263300846 + }, + "wind_chime": { + "mass": 0.5, + "volume": 0.00021603957363774035, + "density": 2314.390792301833 + }, + "bag_of_yeast": { + "mass": 0.475, + "volume": 0.0013995833893075647, + "density": 339.3867086655003 + }, + "yoga_mat": { + "mass": 1.5, + "volume": 0.015355512625169746, + "density": 97.68478829819713 + }, + "wooden_spoon": { + "mass": 0.05, + "volume": 4.512003570205926e-05, + "density": 1108.1551515199271 + }, + "tablespoon": { + "mass": 0.05, + "volume": 1.586823321877767e-05, + "density": 3150.9494037957875 + }, + "taboret": { + "mass": 6.5, + "volume": 0.006249034924862787, + "density": 1040.1606133034572 + }, + "echeveria_elegans": { + "mass": 0.45, + "volume": 0.0002723056970051716, + "density": 1652.5544817795483 + }, + "maillot": { + "mass": 0.19, + "volume": 0.011238292935954766, + "density": 16.90648224626103 + }, + "cellulose_tape": { + "mass": 0.035, + "volume": 2.4269830344014694e-05, + "density": 1442.1196812622768 + }, + "masking_tape": { + "mass": 0.044, + "volume": 1.2121593660268288e-05, + "density": 3629.885742187644 + }, + "cheese_tart": { + "mass": 0.415, + "volume": 0.0018735346526091272, + "density": 221.50644474179407 + }, + "tartlet": { + "mass": 0.06, + "volume": 0.0002604066610728757, + "density": 230.4088526491601 + }, + "digital_thermometer": { + "mass": 0.048, + "volume": 2.2248917513395793e-05, + "density": 2157.4083310390183 + }, + "cotton_thread": { + "mass": 0.05, + "volume": 0.0003090757908146553, + "density": 161.77261851603154 + }, + "beefsteak_tomato": { + "mass": 0.197, + "volume": 0.00015905942220666278, + "density": 1238.5308412854774 + }, + "camera_tripod": { + "mass": 1.5, + "volume": 0.004811731608327233, + "density": 311.73808559980455 + }, + "lorry": { + "mass": 15000.0, + "volume": 60.70838034648136, + "density": 247.08285601411856 + }, + "tobacco_pipe": { + "mass": 0.085, + "volume": 0.00011266280589178833, + "density": 754.4637232064129 + }, + "white_turnip": { + "mass": 0.142, + "volume": 4.940859344258731e-06, + "density": 28739.939776873776 + }, + "boxers": { + "mass": 0.125, + "volume": 0.002050624898087252, + "density": 60.957028326631274 + }, + "dip_candle": { + "mass": 0.11, + "volume": 0.00010354754112549905, + "density": 1062.3139748599206 + }, + "open_end_wrench": { + "mass": 0.234, + "volume": 5.1453777946929014e-05, + "density": 4547.771015791196 + }, + "rubber_boot": { + "mass": 1.5, + "volume": 0.00450828836547643, + "density": 332.7205090709591 + }, + "packing_box": { + "mass": 3.25, + "volume": 0.013727895511869887, + "density": 236.74422617726606 + }, + "plant_pot_stand": { + "mass": 4.25, + "volume": 0.011447591876541475, + "density": 371.2571207844284 + }, + "slingback": { + "mass": 0.461, + "volume": 0.00034498281755759863, + "density": 1336.2984373070437 + }, + "set_triangle": { + "mass": 0.045, + "volume": 1.2398414684842578e-05, + "density": 3629.4962818927006 + }, + "box_of_shampoo": { + "mass": 0.275, + "volume": 0.0009929177734661733, + "density": 276.96150411327966 + }, + "bottle_of_alcohol": { + "mass": 1.25, + "volume": 0.0013597537044347263, + "density": 919.2841291207566 + }, + "bottle_of_ammonia": { + "mass": 1.4, + "volume": 0.003297620682598806, + "density": 424.5485259683296 + }, + "radiator": { + "mass": 22.5, + "volume": 0.06020163999706586, + "density": 373.7439711126909 + }, + "box_of_cookies": { + "mass": 0.45, + "volume": 0.0018572711868055807, + "density": 242.29094986068185 + }, + "can_of_beans": { + "mass": 0.425, + "volume": 0.0005089682816172836, + "density": 835.0225649612814 + }, + "jar_of_jelly": { + "mass": 0.55, + "volume": 0.001424609369743908, + "density": 386.07074450090806 + }, + "blackberry": { + "mass": 0.005, + "volume": 1.0941586828132886e-05, + "density": 456.97210820866087 + }, + "deodorant_stick": { + "mass": 0.085, + "volume": 0.00023369516303755597, + "density": 363.7216915197346 + }, + "bottle_of_deicer": { + "mass": 0.688, + "volume": 0.0011595296716390099, + "density": 593.3440228636006 + }, + "dvd": { + "mass": 0.016, + "volume": 1.935063176641639e-05, + "density": 826.8463889519353 + }, + "ice_tray": { + "mass": 0.165, + "volume": 0.0008021688280198253, + "density": 205.69236080552622 + }, + "bag_of_oranges": { + "mass": 2.25, + "volume": 0.0013896189359336986, + "density": 1619.148920483156 + }, + "vanilla_flower": { + "mass": 0.008, + "volume": 5.236343107646793e-06, + "density": 1527.7837673236795 + }, + "jar_of_honey": { + "mass": 1.43, + "volume": 0.007864843655617331, + "density": 181.82179616229837 + }, + "clothesline_pole": { + "mass": 2.662, + "volume": 0.0022765005181089567, + "density": 1169.3386313003214 + }, + "burlap_bag": { + "mass": 0.35, + "volume": 0.00917824341313255, + "density": 38.133658505853944 + }, + "trout": { + "mass": 0.4, + "volume": 0.0003087374902323588, + "density": 1295.5990530950944 + }, + "case_of_eyeshadow": { + "mass": 0.125, + "volume": 5.978414373016802e-05, + "density": 2090.8554041382554 + }, + "swiss_cheese": { + "mass": 0.234, + "volume": 0.00011391487014018474, + "density": 2054.1655335430514 + }, + "box_of_aluminium_foil": { + "mass": 0.25, + "volume": 0.0013038169458058726, + "density": 191.74470833823852 + }, + "wicker_basket": { + "mass": 1.5, + "volume": 0.00818931032301882, + "density": 183.16560746070934 + }, + "bust": { + "mass": 2.85, + "volume": 0.0017255726909596245, + "density": 1651.6255820060874 + }, + "bread_slice": { + "mass": 0.044, + "volume": 0.0003678513343972938, + "density": 119.61353918177792 + }, + "wool_coat": { + "mass": 1.5, + "volume": 0.031670075028291514, + "density": 47.36332322105394 + }, + "recycling_bin": { + "mass": 12.5, + "volume": 0.09166669161596278, + "density": 136.3635992489911 + }, + "frail": { + "mass": 0.5, + "volume": 0.0011843523987165889, + "density": 422.1716446404126 + }, + "water_bottle": { + "mass": 0.425, + "volume": 0.000528614517917981, + "density": 803.9885126006742 + }, + "wine_bottle": { + "mass": 0.45, + "volume": 0.00019729453408117936, + "density": 2280.853861946534 + }, + "oil_bottle": { + "mass": 0.258, + "volume": 0.00020612877578413683, + "density": 1251.6447498343657 + }, + "soft_roll": { + "mass": 0.075, + "volume": 0.0004285830167592828, + "density": 174.99526828456754 + }, + "hanging": { + "mass": 5.225, + "volume": 0.07743752189709825, + "density": 67.47375008904812 + }, + "high_heel": { + "mass": 0.45, + "volume": 0.0005157829138349927, + "density": 872.4600756045252 + }, + "music_stool": { + "mass": 6.0, + "volume": 0.021672937200491238, + "density": 276.8429560098575 + }, + "reception_desk": { + "mass": 95.0, + "volume": 1.0034596006504921, + "density": 94.67247105754562 + }, + "cleansing_bottle": { + "mass": 0.367, + "volume": 0.0005105627336662632, + "density": 718.8147034638351 + }, + "beer_bottle": { + "mass": 0.575, + "volume": 0.000246422178775312, + "density": 2333.393864374057 + }, + "ink_bottle": { + "mass": 0.15, + "volume": 0.00021222886005342265, + "density": 706.7841761117772 + }, + "rum_bottle": { + "mass": 0.975, + "volume": 0.0007641163333666977, + "density": 1275.9837179558099 + }, + "toaster_oven": { + "mass": 7.75, + "volume": 0.020811328275346767, + "density": 372.393337775595 + }, + "allspice_shaker": { + "mass": 0.083, + "volume": 0.0007466385113116351, + "density": 111.16490609919413 + }, + "ice_cream_cone": { + "mass": 0.022, + "volume": 6.264556651138416e-05, + "density": 351.18207440908185 + }, + "cork": { + "mass": 0.015, + "volume": 6.725865577930228e-06, + "density": 2230.1962217651094 + }, + "lily_pad": { + "mass": 0.213, + "volume": 0.0006496465814749783, + "density": 327.8705777476701 + }, + "low_resolution_tree": { + "mass": 1500.0, + "volume": 7.840198967582404, + "density": 191.32167515163692 + }, + "rosemary_shaker": { + "mass": 0.12, + "volume": 0.0007793852853863377, + "density": 153.9674949604887 + }, + "acorn": { + "mass": 0.007, + "volume": 6.054350322474617e-06, + "density": 1156.193419137805 + }, + "address": { + "mass": 0.75, + "volume": 0.0028870158958563498, + "density": 259.7838138253597 + }, + "baby_shoe": { + "mass": 0.102, + "volume": 0.00023708962948686433, + "density": 430.21704585206743 + }, + "aluminum_foil": { + "mass": 0.02, + "volume": 0.00010949567249109735, + "density": 182.65562049154153 + }, + "bag_of_mulch": { + "mass": 15.1, + "volume": 0.013628346019950034, + "density": 1107.984782445035 + }, + "bag_of_rubbish": { + "mass": 8.5, + "volume": 0.08258293099068173, + "density": 102.92683848868357 + }, + "belt": { + "mass": 0.4, + "volume": 0.0001858505085157934, + "density": 2152.2674497606145 + }, + "bicycle_chain": { + "mass": 0.28, + "volume": 8.534494170074007e-06, + "density": 32808.03694046838 + }, + "bicycle_rack": { + "mass": 12.13, + "volume": 0.012319882453393532, + "density": 984.5873161443008 + }, + "board": { + "mass": 6.615, + "volume": 0.011635353722757267, + "density": 568.525904550878 + }, + "legal_document": { + "mass": 0.112, + "volume": 0.0010600538218560186, + "density": 105.65501268973526 + }, + "bok_choy": { + "mass": 0.3, + "volume": 0.0002505075668839203, + "density": 1197.568615318568 + }, + "broken_glass": { + "mass": 0.07, + "volume": 6.941991892365769e-05, + "density": 1008.3561186088426 + }, + "broken_light_bulb": { + "mass": 0.06, + "volume": 5.029578488851438e-05, + "density": 1192.9429102855433 + }, + "cat_food_tin": { + "mass": 0.408, + "volume": 0.0003771209934359838, + "density": 1081.8809005637017 + }, + "dog_food_can": { + "mass": 1.315, + "volume": 0.001119149112126878, + "density": 1174.9998152622566 + }, + "can_of_cat_food": { + "mass": 0.418, + "volume": 0.001657417200619956, + "density": 252.19962713289527 + }, + "can_of_dog_food": { + "mass": 2.034, + "volume": 0.001983869682022854, + "density": 1025.2689571454262 + }, + "car_wheel": { + "mass": 12.5, + "volume": 0.019347336770187726, + "density": 646.0837555306954 + }, + "clipper": { + "mass": 0.083, + "volume": 1.0890840558075523e-05, + "density": 7621.083015346852 + }, + "cola_bottle": { + "mass": 0.424, + "volume": 0.00024441615080474604, + "density": 1734.7462457123631 + }, + "cup_holder": { + "mass": 0.115, + "volume": 0.00041668281999901685, + "density": 275.98930044745146 + }, + "daffodil_bulb": { + "mass": 0.031, + "volume": 6.2348116390756455e-06, + "density": 4972.082846210245 + }, + "pottable_daffodil": { + "mass": 0.125, + "volume": 7.394546981664677e-05, + "density": 1690.4348611205892 + }, + "dog_collar": { + "mass": 0.163, + "volume": 0.00022910336694124492, + "density": 711.4692471621443 + }, + "doily": { + "mass": 0.013, + "volume": 1.8958069097856774e-05, + "density": 685.7238431243856 + }, + "emery_paper": { + "mass": 0.029, + "volume": 1.2090818301292359e-05, + "density": 2398.5142508427457 + }, + "flagpole": { + "mass": 5.0, + "volume": 0.0006697055624061934, + "density": 7465.967554510729 + }, + "fur_coat": { + "mass": 2.075, + "volume": 0.041292539620058605, + "density": 50.25120806548869 + }, + "gelatin": { + "mass": 0.007, + "volume": 4.868627336739966e-06, + "density": 1437.7769165399302 + }, + "gourd": { + "mass": 0.534, + "volume": 0.0005128873078933749, + "density": 1041.1643879302512 + }, + "ham_hock": { + "mass": 0.79, + "volume": 0.0008249952320162798, + "density": 957.5812917963758 + }, + "hose": { + "mass": 1.75, + "volume": 0.005401486824368345, + "density": 323.9848687781714 + }, + "hutch": { + "mass": 15.0, + "volume": 0.05545615661132475, + "density": 270.48394473368245 + }, + "ice": { + "mass": 0.008, + "volume": 8.060456559380272e-06, + "density": 992.4996110412733 + }, + "pellet": { + "mass": 0.01, + "volume": 1.8680694872076214e-05, + "density": 535.3119928610331 + }, + "bag_of_jerky": { + "mass": 0.214, + "volume": 0.0010262979399269447, + "density": 208.51644700293681 + }, + "kayak_rack": { + "mass": 5.0, + "volume": 0.008602363372635365, + "density": 581.2356190282894 + }, + "kielbasa": { + "mass": 0.174, + "volume": 0.0001165094058383723, + "density": 1493.4416560443328 + }, + "lace": { + "mass": 0.031, + "volume": 0.0004117604023881153, + "density": 75.28650113077205 + }, + "lamb": { + "mass": 0.85, + "volume": 0.00037768742266974564, + "density": 2250.538273135058 + }, + "lampshade": { + "mass": 0.45, + "volume": 0.0014041603145210594, + "density": 320.4762272130509 + }, + "meat_loaf": { + "mass": 1.526, + "volume": 0.002988511853738657, + "density": 510.62203353517214 + }, + "meatball": { + "mass": 0.028, + "volume": 1.1389040595408625e-05, + "density": 2458.5038366873423 + }, + "mustard_leaf": { + "mass": 0.01, + "volume": 1.305801256934837e-06, + "density": 7658.1332319080675 + }, + "pack_of_ground_beef": { + "mass": 0.477, + "volume": 0.001234239361887193, + "density": 386.47284694489986 + }, + "package": { + "mass": 0.444, + "volume": 0.0013032464705262242, + "density": 340.68766733028014 + }, + "patty": { + "mass": 0.088, + "volume": 0.00011365917298174227, + "density": 774.2445918917248 + }, + "pewter_teapot": { + "mass": 1.5, + "volume": 0.003059103837931463, + "density": 490.3396809878431 + }, + "plastic_wrap": { + "mass": 0.047, + "volume": 5.556422934391184e-05, + "density": 845.8679361697973 + }, + "post_it": { + "mass": 0.011, + "volume": 7.031249661562512e-05, + "density": 156.44445197463713 + }, + "pottable_cactus": { + "mass": 0.5, + "volume": 0.0012000128022917188, + "density": 416.6622214739104 + }, + "pottable_dahlia": { + "mass": 1.0, + "volume": 0.0020498937379317002, + "density": 487.83016480111746 + }, + "pottable_marigold": { + "mass": 0.05, + "volume": 0.0001851076242858252, + "density": 270.11313117386703 + }, + "price_tag": { + "mass": 0.006, + "volume": 1.555708443262996e-05, + "density": 385.6763795287628 + }, + "raw_egg": { + "mass": 0.056, + "volume": 8.797465662100794e-05, + "density": 636.5469573953127 + }, + "recreational_vehicle": { + "mass": 1000.0, + "volume": 10.855425132469897, + "density": 92.11983757401434 + }, + "windshield": { + "mass": 14.263, + "volume": 0.002444537586976317, + "density": 5834.64131457357 + }, + "ribbon": { + "mass": 0.008, + "volume": 3.0115481817180563e-05, + "density": 265.6440978950596 + }, + "router": { + "mass": 0.55, + "volume": 0.0006883075994000194, + "density": 799.0613505929927 + }, + "salad": { + "mass": 0.3, + "volume": 0.000983970742391435, + "density": 304.887114093334 + }, + "sanitary_napkin": { + "mass": 0.015, + "volume": 0.00010673756797968135, + "density": 140.53158867977405 + }, + "scallop": { + "mass": 0.044, + "volume": 0.00018781079808271066, + "density": 234.27832930363613 + }, + "scarf": { + "mass": 0.15, + "volume": 0.0004417461820959939, + "density": 339.56150857553797 + }, + "schnitzel": { + "mass": 0.147, + "volume": 0.00013025680038622904, + "density": 1128.5399270066907 + }, + "cup_of_ranch": { + "mass": 0.052, + "volume": 6.69767447879666e-06, + "density": 7763.888819114809 + }, + "skateboard_wheel": { + "mass": 0.279, + "volume": 0.0001020648343155976, + "density": 2733.556585584572 + }, + "sleeping_bag": { + "mass": 2.0, + "volume": 0.1730883044337618, + "density": 11.554795724314053 + }, + "space_heater": { + "mass": 4.5, + "volume": 0.010263831592918864, + "density": 438.43275868873394 + }, + "tofu": { + "mass": 0.019, + "volume": 1.4871702413020998e-05, + "density": 1277.5941497702677 + }, + "trailer_truck": { + "mass": 12000.0, + "volume": 18.50624467323432, + "density": 648.4297712412537 + }, + "trampoline": { + "mass": 52.55, + "volume": 0.2759193436477728, + "density": 190.45420775965292 + }, + "turkey_leg": { + "mass": 0.355, + "volume": 0.00033891931840465727, + "density": 1047.4469312373128 + }, + "veal": { + "mass": 0.693, + "volume": 0.0006225356375881323, + "density": 1113.1892829218023 + }, + "gift_box": { + "mass": 0.25, + "volume": 0.005745366997567518, + "density": 43.513321273618445 + }, + "wax_paper": { + "mass": 0.021, + "volume": 0.00016795685196823747, + "density": 125.03211243785003 + }, + "ice_lolly": { + "mass": 0.075, + "volume": 0.00017564185647698724, + "density": 427.0052794040387 + }, + "hard_boiled_egg": { + "mass": 0.063, + "volume": 5.637890543489811e-05, + "density": 1117.4392179845954 + }, + "half_hard_boiled_egg": { + "mass": 0.028, + "volume": 2.8745739229696584e-05, + "density": 974.0573994727478 + }, + "half_mango": { + "mass": 0.188, + "volume": 0.00027537012332633736, + "density": 682.7174921122571 + }, + "half_apricot": { + "mass": 0.038, + "volume": 0.00023021835457353218, + "density": 165.06068801678768 + }, + "half_kiwi": { + "mass": 0.065, + "volume": 0.0003147102555728608, + "density": 206.53918596228078 + }, + "half_peach": { + "mass": 0.118, + "volume": 0.00023426624510257572, + "density": 503.7003941747244 + }, + "half_strawberry": { + "mass": 0.011, + "volume": 4.879266461720947e-06, + "density": 2254.4372368874956 + }, + "half_pear": { + "mass": 0.148, + "volume": 0.00011639270383180059, + "density": 1271.5573668077614 + }, + "half_vidalia_onion": { + "mass": 0.132, + "volume": 0.00011093253999532817, + "density": 1189.9123557935216 + }, + "half_lime": { + "mass": 0.045, + "volume": 6.559048709042244e-05, + "density": 686.0751001584027 + }, + "half_bell_pepper": { + "mass": 0.103, + "volume": 0.00010566073131820756, + "density": 974.8181629540826 + }, + "sliced_eggplant": { + "mass": 0.027, + "volume": 2.260894568083952e-05, + "density": 1194.2175624262647 + }, + "half_eggplant": { + "mass": 0.201, + "volume": 0.0002479295391838625, + "density": 810.7142080030249 + }, + "half_potato": { + "mass": 0.094, + "volume": 0.00017293866173798004, + "density": 543.5453186426279 + }, + "infant_car_seat": { + "mass": 4.4, + "volume": 0.06534527112620037, + "density": 67.33463530210693 + }, + "pottable_beefsteak_tomato": { + "mass": 0.55, + "volume": 0.040475134518600124, + "density": 13.588589798194509 + }, + "conch": { + "mass": 0.475, + "volume": 0.00039626120091712166, + "density": 1198.704286214856 + }, + "copper_pot": { + "mass": 1.375, + "volume": 0.0004194740323078726, + "density": 3277.9144693057424 + }, + "signpost": { + "mass": 0.875, + "volume": 0.0008395628270540319, + "density": 1042.2090781107051 + }, + "grocery_sign": { + "mass": 0.2, + "volume": 0.00012480580799074248, + "density": 1602.4895252858353 + }, + "necktie": { + "mass": 0.055, + "volume": 0.0001228954705226968, + "density": 447.53480145423583 + }, + "pottable_chili": { + "mass": 0.575, + "volume": 0.003691287763563751, + "density": 155.77219572956474 + }, + "squeeze_bottle": { + "mass": 0.219, + "volume": 0.000847553674293003, + "density": 258.3907151162804 + }, + "scoop_of_ice_cream": { + "mass": 0.063, + "volume": 5.7528277131040835e-05, + "density": 1095.1136231056494 + }, + "cookie_stick": { + "mass": 0.013, + "volume": 7.4972640686368475e-06, + "density": 1733.9658682135307 + }, + "chopping_block": { + "mass": 1.365, + "volume": 0.0009480561062890203, + "density": 1439.7882055135162 + }, + "sugar_cookie": { + "mass": 0.025, + "volume": 2.083883548448659e-05, + "density": 1199.6831597721082 + }, + "spice_cookie": { + "mass": 0.059, + "volume": 4.1288805168127865e-05, + "density": 1428.9587639979459 + }, + "ammonia_water_atomizer": { + "mass": 0.625, + "volume": 0.0009714936643706969, + "density": 643.3392444250836 + }, + "bleaching_agent_atomizer": { + "mass": 0.5, + "volume": 0.0009718735501328749, + "density": 514.4702208755859 + }, + "conditioner_atomizer": { + "mass": 0.452, + "volume": 0.0009717550721295029, + "density": 465.1377831344762 + }, + "deodorant_atomizer": { + "mass": 0.175, + "volume": 0.00018227170855860986, + "density": 960.1051166079807 + }, + "detergent_atomizer": { + "mass": 0.525, + "volume": 0.0009725200775393958, + "density": 539.834613315459 + }, + "fertilizer_atomizer": { + "mass": 1.0, + "volume": 0.0009717011570982916, + "density": 1029.1229898153201 + }, + "insectifuge_atomizer": { + "mass": 0.225, + "volume": 0.00018280490084412733, + "density": 1230.8203935508889 + }, + "pesticide_atomizer": { + "mass": 0.325, + "volume": 0.00018281315495677407, + "density": 1777.771408610315 + }, + "rubbing_alcohol_atomizer": { + "mass": 0.5, + "volume": 0.0009746631750927974, + "density": 512.9977337580186 + }, + "sealant_atomizer": { + "mass": 0.233, + "volume": 0.00018281303057376478, + "density": 1274.5262154930738 + }, + "spray_paint_can": { + "mass": 0.375, + "volume": 0.00018281260941031266, + "density": 2051.280823623788 + }, + "vinegar_atomizer": { + "mass": 0.5, + "volume": 0.0009719727426501235, + "density": 514.4177177610244 + }, + "water_atomizer": { + "mass": 0.475, + "volume": 0.0009727848921164471, + "density": 488.2888332759388 + }, + "whipped_cream_atomizer": { + "mass": 0.25, + "volume": 0.00018280026155936797, + "density": 1367.61292280103 + }, + "chlorine_bottle": { + "mass": 1.275, + "volume": 0.0005221028308606404, + "density": 2442.047666928515 + }, + "detergent_bottle": { + "mass": 0.5, + "volume": 0.0005215230007862975, + "density": 958.7304859922814 + }, + "disinfectant_bottle": { + "mass": 0.5, + "volume": 0.0005213103438788966, + "density": 959.1215786735912 + }, + "fabric_softener_bottle": { + "mass": 0.95, + "volume": 0.0005051135822394283, + "density": 1880.7651059157058 + }, + "floor_wax_bottle": { + "mass": 1.15, + "volume": 0.0005137786118710221, + "density": 2238.3181655072353 + }, + "herbicide_bottle": { + "mass": 0.865, + "volume": 0.0005093107266863905, + "density": 1698.373811263995 + }, + "hydrogen_peroxide_bottle": { + "mass": 0.75, + "volume": 0.000526265716531198, + "density": 1425.1355853911843 + }, + "liquid_soap_bottle": { + "mass": 0.775, + "volume": 0.0005262571861131629, + "density": 1472.6639758100123 + }, + "lubricant_bottle": { + "mass": 0.551, + "volume": 0.0005093141860106158, + "density": 1081.8469524988163 + }, + "polish_bottle": { + "mass": 0.556, + "volume": 0.0005262669906326971, + "density": 1056.4979561639555 + }, + "saddle_soap_bottle": { + "mass": 0.45, + "volume": 0.0005253078763001705, + "density": 856.6404965587492 + }, + "salt_bottle": { + "mass": 0.175, + "volume": 5.319324068939809e-05, + "density": 3289.8916804457663 + }, + "shampoo_bottle": { + "mass": 0.384, + "volume": 0.0005014033366401239, + "density": 765.850507842973 + }, + "soap_bottle": { + "mass": 0.325, + "volume": 0.0005253056724305165, + "density": 618.6873987030638 + }, + "solvent_bottle": { + "mass": 0.575, + "volume": 0.0005086131939479649, + "density": 1130.5251354899515 + }, + "toilet_soap_bottle": { + "mass": 0.375, + "volume": 0.0005253069484768176, + "density": 713.8683413332942 + }, + "bird_feed_bag": { + "mass": 3.5, + "volume": 0.006888749741569476, + "density": 508.0747786321221 + }, + "brown_rice_sack": { + "mass": 14.75, + "volume": 0.007090300893024958, + "density": 2080.306636141525 + }, + "brown_sugar_sack": { + "mass": 13.8, + "volume": 0.00701424040240429, + "density": 1967.426151414733 + }, + "chia_seed_bag": { + "mass": 0.5, + "volume": 0.007176396080225374, + "density": 69.67285450948766 + }, + "flour_sack": { + "mass": 15.0, + "volume": 0.007410355050783962, + "density": 2024.194508522653 + }, + "granulated_sugar_sack": { + "mass": 14.5, + "volume": 0.007248271369221123, + "density": 2000.4769773897312 + }, + "grated_cheese_sack": { + "mass": 1.25, + "volume": 0.007283862755942031, + "density": 171.6122395332442 + }, + "ground_beef_package": { + "mass": 1.0, + "volume": 0.0073859614027968635, + "density": 135.39198832278316 + }, + "mulch_bag": { + "mass": 13.8, + "volume": 0.0070681615389555546, + "density": 1952.4171772168063 + }, + "pellet_food_bag": { + "mass": 8.5, + "volume": 0.0073046279585602565, + "density": 1163.6458486621339 + }, + "petfood_bag": { + "mass": 7.7, + "volume": 0.0073411515346710025, + "density": 1048.8817678853538 + }, + "popcorn_bag": { + "mass": 0.135, + "volume": 0.007399824906340381, + "density": 18.243674912406124 + }, + "pumpkin_seed_bag": { + "mass": 1.175, + "volume": 0.007399887292735123, + "density": 158.78620221061504 + }, + "soil_bag": { + "mass": 15.09, + "volume": 0.007308471016486882, + "density": 2064.7273507631194 + }, + "sugar_sack": { + "mass": 35.0, + "volume": 0.007103567809186179, + "density": 4927.101555184532 + }, + "sunflower_seed_bag": { + "mass": 0.55, + "volume": 0.007231238684619582, + "density": 76.05889170410288 + }, + "white_rice_sack": { + "mass": 12.5, + "volume": 0.007274778884271754, + "density": 1718.2652832274118 + }, + "beef_broth_carton": { + "mass": 2.625, + "volume": 0.003575088290145246, + "density": 734.2476008874604 + }, + "chicken_broth_carton": { + "mass": 3.75, + "volume": 0.0035750884848115153, + "density": 1048.9250870101769 + }, + "chicken_soup_carton": { + "mass": 0.45, + "volume": 0.0035768418335063133, + "density": 125.80930914657559 + }, + "milk_carton": { + "mass": 2.664, + "volume": 0.0035768421518392107, + "density": 744.7910438625793 + }, + "orange_juice_carton": { + "mass": 1.7, + "volume": 0.0035768417978943373, + "density": 475.27961706351635 + }, + "pineapple_juice_carton": { + "mass": 2.75, + "volume": 0.003576845705374321, + "density": 768.8338347578259 + }, + "shortening_carton": { + "mass": 6.42, + "volume": 0.0035752407863420548, + "density": 1795.6832514680812 + }, + "yogurt_carton": { + "mass": 2.25, + "volume": 0.0035768457066075307, + "density": 629.0458645849778 + }, + "baking_powder_jar": { + "mass": 0.475, + "volume": 0.0010703642277398813, + "density": 443.77417302424453 + }, + "basil_jar": { + "mass": 0.375, + "volume": 0.0010703671099065296, + "density": 350.3470879563434 + }, + "butter_package": { + "mass": 0.35, + "volume": 0.0010703630588032604, + "density": 326.99185301791346 + }, + "chickpea_can": { + "mass": 0.4, + "volume": 0.0010703592123892933, + "density": 373.7063178137235 + }, + "clove_jar": { + "mass": 0.5, + "volume": 0.0010703674764682546, + "density": 467.1292906337006 + }, + "cocoa_powder_jar": { + "mass": 0.5, + "volume": 0.0010703652717432655, + "density": 467.1302528207665 + }, + "coconut_oil_jar": { + "mass": 0.882, + "volume": 0.0010703657467432434, + "density": 824.0174002985653 + }, + "coffee_bean_jar": { + "mass": 1.102, + "volume": 0.0010703655682623675, + "density": 1029.5547920034348 + }, + "cornstarch_jar": { + "mass": 0.45, + "volume": 0.0010703701672481099, + "density": 420.4153046949512 + }, + "cream_carton": { + "mass": 0.75, + "volume": 0.0010703665127041926, + "density": 700.6945668593339 + }, + "cream_cheese_box": { + "mass": 0.238, + "volume": 0.0010703700879559422, + "density": 222.35299984372918 + }, + "feta_box": { + "mass": 0.25, + "volume": 0.0010703703037588297, + "density": 233.56402837604202 + }, + "frosting_jar": { + "mass": 0.646, + "volume": 0.0010703651420432337, + "density": 603.5323597766295 + }, + "gelatin_box": { + "mass": 0.05, + "volume": 0.0010703609675703262, + "density": 46.71321312612685 + }, + "granola_box": { + "mass": 0.395, + "volume": 0.0010703607827277728, + "density": 369.03444742562215 + }, + "granulated_sugar_jar": { + "mass": 1.25, + "volume": 0.001070361650248377, + "density": 1167.8295833094712 + }, + "honey_jar": { + "mass": 1.1, + "volume": 0.0010703603018368088, + "density": 1027.6913279690284 + }, + "hummus_box": { + "mass": 0.2, + "volume": 0.0010703610517163156, + "density": 186.85283781514804 + }, + "ice_cream_carton": { + "mass": 0.75, + "volume": 0.0010703664993213435, + "density": 700.6945756201553 + }, + "instant_coffee_jar": { + "mass": 0.5, + "volume": 0.0010703790171902603, + "density": 467.12425409131953 + }, + "jelly_jar": { + "mass": 0.458, + "volume": 0.0011737730458169983, + "density": 390.1946816994861 + }, + "jelly_bean_jar": { + "mass": 0.886, + "volume": 0.0011737725115196947, + "density": 754.8311033906282 + }, + "jimmies_jar": { + "mass": 0.631, + "volume": 0.001070379325406064, + "density": 589.5106389135655 + }, + "maple_syrup_jar": { + "mass": 1.3, + "volume": 0.0010703678662261388, + "density": 1214.5357133930872 + }, + "marinara_jar": { + "mass": 0.625, + "volume": 0.0010703697225533972, + "density": 583.9103880003677 + }, + "noodle_jar": { + "mass": 0.875, + "volume": 0.001066008423541094, + "density": 820.8190298284911 + }, + "oat_box": { + "mass": 0.195, + "volume": 0.0010703713643933103, + "density": 182.17976161061316 + }, + "pasta_box": { + "mass": 0.459, + "volume": 0.001070370277474654, + "density": 428.8235666286697 + }, + "peanut_butter_jar": { + "mass": 0.495, + "volume": 0.0010699054116973877, + "density": 462.6577215033341 + }, + "raisin_box": { + "mass": 0.265, + "volume": 0.0010703720484744176, + "density": 247.57746652456015 + }, + "refried_beans_can": { + "mass": 0.431, + "volume": 0.0010703732054790898, + "density": 402.6632933202846 + }, + "sodium_carbonate_jar": { + "mass": 1.293, + "volume": 0.0010703383426061384, + "density": 1208.0292263955605 + }, + "tomato_sauce_jar": { + "mass": 0.683, + "volume": 0.0010703611392577882, + "density": 638.102388950338 + }, + "yeast_jar": { + "mass": 0.85, + "volume": 0.0010703632510637635, + "density": 794.1229289731697 + }, + "cooking_oil_bottle": { + "mass": 0.92, + "volume": 0.0003424348009880958, + "density": 2686.6428217731946 + }, + "lemon_juice_bottle": { + "mass": 0.846, + "volume": 0.0003661229184317562, + "density": 2310.6993782955187 + }, + "lime_juice_bottle": { + "mass": 0.475, + "volume": 0.00035178598534458497, + "density": 1350.252766706221 + }, + "olive_oil_bottle": { + "mass": 1.0, + "volume": 0.0003517847196156694, + "density": 2842.6476314619817 + }, + "sesame_oil_bottle": { + "mass": 0.71, + "volume": 0.0003734501736708005, + "density": 1901.1907077753056 + }, + "vinegar_bottle": { + "mass": 0.73, + "volume": 0.0004235309012406352, + "density": 1723.605049505561 + }, + "cayenne_shaker": { + "mass": 0.05, + "volume": 0.0005043069588370323, + "density": 99.14596482131351 + }, + "cinnamon_shaker": { + "mass": 0.121, + "volume": 0.0007671705482812176, + "density": 157.72242596003005 + }, + "coriander_shaker": { + "mass": 0.1, + "volume": 0.0005050018262800972, + "density": 198.01908586472203 + }, + "cream_of_tartar_shaker": { + "mass": 0.145, + "volume": 0.000503152857704073, + "density": 288.18280126967113 + }, + "cumin_shaker": { + "mass": 0.153, + "volume": 0.0007673199079797121, + "density": 199.39532183237102 + }, + "curry_powder_shaker": { + "mass": 0.15, + "volume": 0.0005031480284466703, + "density": 298.12300062684 + }, + "ginger_shaker": { + "mass": 0.15, + "volume": 0.0007672729168222887, + "density": 195.49758203539213 + }, + "lemon_pepper_seasoning_shaker": { + "mass": 0.16, + "volume": 0.0005029761523709219, + "density": 318.1065329753593 + }, + "marjoram_shaker": { + "mass": 0.09, + "volume": 0.0005029814217755307, + "density": 178.93305021545103 + }, + "mustard_seed_shaker": { + "mass": 0.093, + "volume": 0.0007673103361032229, + "density": 121.20258990944846 + }, + "nutmeg_shaker": { + "mass": 0.166, + "volume": 0.0005035276105503517, + "density": 329.67407649912843 + }, + "onion_powder_shaker": { + "mass": 0.138, + "volume": 0.000526866421787556, + "density": 261.9259726816385 + }, + "paprika_shaker": { + "mass": 0.1, + "volume": 0.0005036598468859782, + "density": 198.54669896414964 + }, + "parmesan_shaker": { + "mass": 0.225, + "volume": 0.0005035136851301164, + "density": 446.8597510748019 + }, + "saffron_shaker": { + "mass": 0.145, + "volume": 0.0007904820451131625, + "density": 183.4323763536493 + }, + "sage_shaker": { + "mass": 0.085, + "volume": 0.0007671302767247421, + "density": 110.80256193629455 + }, + "sesame_seed_shaker": { + "mass": 0.118, + "volume": 0.0005036761398903918, + "density": 234.27752608189607 + }, + "thyme_shaker": { + "mass": 0.06, + "volume": 0.0007672864048066061, + "density": 78.19765816797307 + }, + "yeast_shaker": { + "mass": 0.2, + "volume": 0.0007671351505369328, + "density": 260.71025406672624 + }, + "barbecue_sauce_bottle": { + "mass": 0.548, + "volume": 0.0008576383281865311, + "density": 638.9639804913353 + }, + "catsup_bottle": { + "mass": 0.535, + "volume": 0.0008578096501191742, + "density": 623.6814891574993 + }, + "chocolate_sauce_bottle": { + "mass": 0.585, + "volume": 0.000858130469041121, + "density": 681.7145190680407 + }, + "glaze_bottle": { + "mass": 0.353, + "volume": 0.0008579854540151779, + "density": 411.42888652487034 + }, + "hot_sauce_bottle": { + "mass": 0.225, + "volume": 0.0008573667920960255, + "density": 262.4314378329688 + }, + "mustard_bottle": { + "mass": 0.347, + "volume": 0.0008577527599947651, + "density": 404.54547765269535 + }, + "salsa_bottle": { + "mass": 0.465, + "volume": 0.0008578603135134638, + "density": 542.0462896756933 + }, + "soy_sauce_bottle": { + "mass": 0.55, + "volume": 0.0008581416150921428, + "density": 640.919855565965 + }, + "sugar_syrup_bottle": { + "mass": 0.572, + "volume": 0.00085784675067583, + "density": 666.7857627826487 + }, + "vanilla_bottle": { + "mass": 0.24, + "volume": 0.00085789425400658, + "density": 279.754758677005 + }, + "white_sauce_bottle": { + "mass": 0.425, + "volume": 0.0008576908754648902, + "density": 495.5165225112593 + }, + "wine_sauce_bottle": { + "mass": 0.32, + "volume": 0.0008572004451428761, + "density": 373.3082522450897 + }, + "lemonade_bottle": { + "mass": 1.175, + "volume": 0.0005852741800172752, + "density": 2007.606076121995 + }, + "soda_water_bottle": { + "mass": 0.625, + "volume": 0.0005818154456562448, + "density": 1074.223801836416 + }, + "tomato_paste_can": { + "mass": 0.65, + "volume": 0.0005887013656194339, + "density": 1104.1251778243584 + }, + "vodka_bottle": { + "mass": 1.35, + "volume": 0.0005228118669960112, + "density": 2582.190813220963 + }, + "whiskey_bottle": { + "mass": 1.1, + "volume": 0.0005253057080858529, + "density": 2094.0187457856873 + }, + "portrait": { + "mass": 1.035, + "volume": 0.034460444884861864, + "density": 30.03443523315235 + }, + "bap": { + "mass": 0.11, + "volume": 0.00044883873807632924, + "density": 245.07688545656117 + }, + "ramen": { + "mass": 0.2, + "volume": 0.00019587099572147026, + "density": 1021.0802230484458 + }, + "rag": { + "mass": 0.042, + "volume": 0.00010473156234668758, + "density": 401.02524070985913 + }, + "lens": { + "mass": 0.37, + "volume": 0.0010176302195026667, + "density": 363.58983146238063 + }, + "paving_stone": { + "mass": 3.635, + "volume": 0.000220329207258124, + "density": 16498.039661811425 + }, + "cheddar": { + "mass": 0.196, + "volume": 0.00018573258665419452, + "density": 1055.2806243145787 + }, + "half_zucchini": { + "mass": 0.15, + "volume": 0.00016639931878202038, + "density": 901.445998084264 + }, + "lint_screen": { + "mass": 0.1, + "volume": 0.001204724811824436, + "density": 83.00650822369961 + }, + "lemon_peel": { + "mass": 0.004, + "volume": 1.4203264972228972e-06, + "density": 2816.253873895211 + }, + "can": { + "mass": 0.588, + "volume": 0.0024559660295920124, + "density": 239.41699230167248 + }, + "clam": { + "mass": 0.024, + "volume": 4.38236513183959e-07, + "density": 54764.94832808579 + }, + "edible_cookie_dough": { + "mass": 0.709, + "volume": 0.0018875106941428365, + "density": 375.627010856208 + }, + "half_apple_pie": { + "mass": 0.338, + "volume": 0.0002874466896761162, + "density": 1175.8702122499492 + }, + "half_feta": { + "mass": 0.255, + "volume": 0.00040854978863507914, + "density": 624.158932628328 + }, + "half_log": { + "mass": 3.117, + "volume": 0.0037906504908797253, + "density": 822.2863087745696 + }, + "hotdog": { + "mass": 0.163, + "volume": 0.0003952097803010748, + "density": 412.43918578084015 + }, + "cast": { + "mass": 0.245, + "volume": 7.43559237592669e-05, + "density": 3294.962763063863 + }, + "pastry": { + "mass": 0.502, + "volume": 0.001887510225588624, + "density": 265.9588240606486 + }, + "pebble": { + "mass": 0.84, + "volume": 0.0007347159568942857, + "density": 1143.2989744101378 + }, + "pepperoni": { + "mass": 0.01, + "volume": 4.252982364284138e-06, + "density": 2351.291198378435 + }, + "pizza_dough": { + "mass": 0.45, + "volume": 0.0018455358129085928, + "density": 243.8316270280299 + }, + "sugar_cookie_dough": { + "mass": 1.843, + "volume": 0.0018455444826757585, + "density": 998.62128347507 + }, + "poinsettia": { + "mass": 1.35, + "volume": 0.008561405298758661, + "density": 157.6843932614357 + }, + "acetone_atomizer": { + "mass": 0.45, + "volume": 0.0009736976824293569, + "density": 462.15576777101774 + }, + "hard_candy": { + "mass": 0.013, + "volume": 1.1127365033384166e-05, + "density": 1168.2909620559387 + }, + "beaker": { + "mass": 0.225, + "volume": 7.394951421278485e-05, + "density": 3042.6163362287593 + }, + "stone_wall": { + "mass": 6000.0, + "volume": 9.611715356338209, + "density": 624.2382111371461 + }, + "bagel_dough": { + "mass": 0.425, + "volume": 0.0018875092908376067, + "density": 225.16445458734708 + }, + "biscuit_dough": { + "mass": 0.638, + "volume": 0.001887509293946411, + "density": 338.01158068263993 + }, + "half_papaya": { + "mass": 0.5, + "volume": 0.00036119349381608676, + "density": 1384.2995750487992 + }, + "liquid_carton": { + "mass": 1.25, + "volume": 0.0031385443725769823, + "density": 398.2738019961959 + }, + "roll_dough": { + "mass": 0.515, + "volume": 0.0018455370239186452, + "density": 279.05156782305886 + }, + "sliced_brisket": { + "mass": 0.033, + "volume": 6.552484946037176e-06, + "density": 5036.257278234238 + }, + "spice_cookie_dough": { + "mass": 1.25, + "volume": 0.001887509104999221, + "density": 662.2484610480943 + }, + "toy_dice": { + "mass": 0.1, + "volume": 7.108593298057035e-05, + "density": 1406.7480837218895 + }, + "toy_car": { + "mass": 0.75, + "volume": 0.02138137226206005, + "density": 35.0772621517296 + }, + "beach_toy": { + "mass": 0.153, + "volume": 0.00027333070926842016, + "density": 559.7614714040373 + }, + "alphabet_abacus": { + "mass": 0.7, + "volume": 0.004602964701477639, + "density": 152.07590007702788 + }, + "electric_cauldron": { + "mass": 70.0, + "volume": 0.5056138640418186, + "density": 138.44557077693264 + }, + "agave": { + "mass": 0.058, + "volume": 9.760159370913721e-06, + "density": 5942.525915390886 + }, + "auricularia": { + "mass": 0.009, + "volume": 2.3313101190326062e-05, + "density": 386.04902567551215 + }, + "banana_bread": { + "mass": 0.675, + "volume": 0.0014654289741660737, + "density": 460.6159779146716 + }, + "bean_curd": { + "mass": 0.062, + "volume": 5.598215281181591e-05, + "density": 1107.495815825681 + }, + "bleu": { + "mass": 0.225, + "volume": 0.00010198672299266618, + "density": 2206.1695228326894 + }, + "broccoli_rabe": { + "mass": 0.057, + "volume": 1.4675159785059044e-05, + "density": 3884.1144379247157 + }, + "chanterelle": { + "mass": 0.075, + "volume": 0.00024838066742443915, + "density": 301.95586789304383 + }, + "chocolate_cookie_dough": { + "mass": 1.385, + "volume": 0.0018875093468191345, + "density": 733.7712008335362 + }, + "cold_cuts": { + "mass": 0.019, + "volume": 6.577688506594625e-06, + "density": 2888.552715889644 + }, + "enchilada": { + "mass": 0.225, + "volume": 0.0004061778075549854, + "density": 553.944592281894 + }, + "garlic_bread": { + "mass": 0.275, + "volume": 0.0006791235209317331, + "density": 404.9336998705477 + }, + "half_agave": { + "mass": 0.064, + "volume": 4.511909446040261e-06, + "density": 14184.681843774068 + }, + "half_arepa": { + "mass": 0.125, + "volume": 0.00029873773482858945, + "density": 418.42722035675484 + }, + "half_arugula": { + "mass": 0.012, + "volume": 0.00010242398892119914, + "density": 117.16005328822249 + }, + "half_artichoke": { + "mass": 0.125, + "volume": 4.55475088565345e-05, + "density": 2744.387193462652 + }, + "half_asparagus": { + "mass": 0.017, + "volume": 4.981825286231971e-06, + "density": 3412.403892802519 + }, + "half_auricularia": { + "mass": 0.012, + "volume": 9.674194876388205e-06, + "density": 1240.4133008823694 + }, + "half_avocado": { + "mass": 0.13, + "volume": 0.00017231432134133637, + "density": 754.4352610279201 + }, + "half_bacon": { + "mass": 0.037, + "volume": 2.1141125867231657e-06, + "density": 17501.43309886315 + }, + "half_bagel": { + "mass": 0.072, + "volume": 0.0002642711503904496, + "density": 272.44744609323794 + }, + "half_bagel_dough": { + "mass": 0.198, + "volume": 0.0009856557156325896, + "density": 200.8815013799463 + }, + "half_baguette": { + "mass": 0.14, + "volume": 0.00032399321773178276, + "density": 432.10781071318223 + }, + "half_banana": { + "mass": 0.062, + "volume": 0.00014336868019079307, + "density": 432.45149440931766 + }, + "half_banana_bread": { + "mass": 0.25, + "volume": 0.0007410263270709707, + "density": 337.36992987572575 + }, + "half_bay_leaf": { + "mass": 0.001, + "volume": 6.936275961896141e-07, + "density": 1441.695811258689 + }, + "half_bean_curd": { + "mass": 0.041, + "volume": 2.827773223001929e-05, + "density": 1449.9041035714636 + }, + "half_beet": { + "mass": 0.185, + "volume": 0.00010443945832675801, + "density": 1771.3611595072962 + }, + "half_biscuit_dough": { + "mass": 0.191, + "volume": 0.0009601929144664638, + "density": 198.91836017778797 + }, + "half_blackberry": { + "mass": 0.005, + "volume": 5.381121541970695e-06, + "density": 929.1743293664541 + }, + "half_bleu": { + "mass": 0.125, + "volume": 5.07184207825873e-05, + "density": 2464.587778389881 + }, + "half_bok_choy": { + "mass": 0.238, + "volume": 0.0001557631953119859, + "density": 1527.9604371449743 + }, + "half_branch": { + "mass": 0.5, + "volume": 0.0004540747999562548, + "density": 1101.1401646780873 + }, + "half_bratwurst": { + "mass": 0.083, + "volume": 0.00016746514599804788, + "density": 495.6255195989709 + }, + "half_brisket": { + "mass": 0.145, + "volume": 2.677599134966356e-05, + "density": 5415.29903063036 + }, + "half_broccoli": { + "mass": 0.069, + "volume": 3.4866192121000935e-06, + "density": 19789.944299205326 + }, + "half_broccoli_rabe": { + "mass": 0.035, + "volume": 5.9743502621786445e-06, + "density": 5858.377641761614 + }, + "half_broccolini": { + "mass": 0.05, + "volume": 1.5507967267223727e-05, + "density": 3224.1491833475557 + }, + "half_brownie": { + "mass": 0.064, + "volume": 0.00012511967190645913, + "density": 511.5102927047884 + }, + "half_brussels_sprouts": { + "mass": 0.031, + "volume": 4.426434170064407e-05, + "density": 700.3379878469746 + }, + "half_burrito": { + "mass": 0.204, + "volume": 0.00018651525675475233, + "density": 1093.7443056909722 + }, + "half_butter": { + "mass": 0.048, + "volume": 1.0882510955709052e-05, + "density": 4410.746765645921 + }, + "half_butter_cookie": { + "mass": 0.011, + "volume": 5.920341033247763e-06, + "density": 1858.0010743005546 + }, + "half_buttermilk_pancake": { + "mass": 0.083, + "volume": 0.0006334535333560247, + "density": 131.0277638839073 + }, + "half_butternut_squash": { + "mass": 0.6, + "volume": 0.00048035882459563495, + "density": 1249.0662589681344 + }, + "half_candied_yam": { + "mass": 0.143, + "volume": 0.0002240541048779176, + "density": 638.2386972018106 + }, + "half_cantaloup": { + "mass": 0.7, + "volume": 0.0012281618411700672, + "density": 569.9574571809783 + }, + "half_cardstock": { + "mass": 0.016, + "volume": 5.6356754546763694e-05, + "density": 283.9056316971469 + }, + "half_carrot": { + "mass": 0.028, + "volume": 1.8995269072080965e-05, + "density": 1474.0512436938359 + }, + "half_cauliflower": { + "mass": 0.5, + "volume": 0.0029088891830238994, + "density": 171.88691921231293 + }, + "half_celery": { + "mass": 0.07, + "volume": 0.000200913202726027, + "density": 348.40915903100057 + }, + "half_chanterelle": { + "mass": 0.035, + "volume": 0.00011552522104175104, + "density": 302.9641465680549 + }, + "half_chard": { + "mass": 0.063, + "volume": 4.912114324084647e-05, + "density": 1282.5434394127176 + }, + "half_cheddar": { + "mass": 0.069, + "volume": 8.540192475095108e-05, + "density": 807.9443197705165 + }, + "half_cheese_danish": { + "mass": 0.065, + "volume": 0.00010176230905112676, + "density": 638.7433678155153 + }, + "half_cheese_tart": { + "mass": 0.15, + "volume": 0.00140878660295863, + "density": 106.47460707319406 + }, + "half_cheesecake": { + "mass": 0.243, + "volume": 0.00010983505821292605, + "density": 2212.408350791972 + }, + "half_cherry": { + "mass": 0.002, + "volume": 2.820741827988734e-07, + "density": 7090.333401501173 + }, + "half_cherry_tomato": { + "mass": 0.013, + "volume": 9.562393906243304e-06, + "density": 1359.492207439005 + }, + "half_chicken": { + "mass": 0.792, + "volume": 0.0014438426566294564, + "density": 548.5362247496312 + }, + "half_chicken_breast": { + "mass": 0.201, + "volume": 0.0008338843034682219, + "density": 241.0406325721897 + }, + "half_chicken_leg": { + "mass": 0.106, + "volume": 4.702475856659832e-05, + "density": 2254.1317219072716 + }, + "half_chicken_tender": { + "mass": 0.027, + "volume": 2.5257808271488323e-05, + "density": 1068.9763620732804 + }, + "half_chicken_wing": { + "mass": 0.083, + "volume": 0.00020475184971494958, + "density": 405.3687432643492 + }, + "half_chili": { + "mass": 0.005, + "volume": 3.921502558153811e-07, + "density": 12750.214811421494 + }, + "half_chives": { + "mass": 0.007, + "volume": 8.544966278670012e-06, + "density": 819.1957430509042 + }, + "half_chocolate_biscuit": { + "mass": 0.012, + "volume": 2.2555659245280022e-05, + "density": 532.0172587068636 + }, + "half_chocolate_cake": { + "mass": 0.15, + "volume": 8.701686169071553e-05, + "density": 1723.8038362397594 + }, + "half_chocolate_chip_cookie": { + "mass": 0.023, + "volume": 4.676932792153804e-05, + "density": 491.77529423954206 + }, + "half_chocolate_cookie_dough": { + "mass": 0.294, + "volume": 0.0009854984181542274, + "density": 298.3262018326141 + }, + "half_chorizo": { + "mass": 0.125, + "volume": 0.0001522264414889191, + "density": 821.145122866838 + }, + "half_cinnamon_roll": { + "mass": 0.051, + "volume": 2.945610279504133e-05, + "density": 1731.389938270632 + }, + "half_club_sandwich": { + "mass": 0.25, + "volume": 0.0014611136208217226, + "density": 171.1023676990988 + }, + "half_cold_cuts": { + "mass": 0.02, + "volume": 2.3306939243085465e-06, + "density": 8581.13533973941 + }, + "half_cookie_dough": { + "mass": 0.225, + "volume": 0.0009597741668624264, + "density": 234.4301480165296 + }, + "half_crab": { + "mass": 0.08, + "volume": 7.252910146405032e-05, + "density": 1103.0055299892651 + }, + "half_crawfish": { + "mass": 0.028, + "volume": 7.854391671517322e-06, + "density": 3564.884611183507 + }, + "half_croissant": { + "mass": 0.031, + "volume": 0.0002615315937713566, + "density": 118.53252432324363 + }, + "half_cucumber": { + "mass": 0.109, + "volume": 5.915421381877048e-05, + "density": 1842.6413430823543 + }, + "half_cupcake": { + "mass": 0.045, + "volume": 0.00012204945864492688, + "density": 368.7029872939995 + }, + "half_date": { + "mass": 0.007, + "volume": 4.899425551005419e-06, + "density": 1428.7389260488953 + }, + "half_doughnut": { + "mass": 0.07, + "volume": 0.0001547358239263534, + "density": 452.3839290978704 + }, + "half_dried_apricot": { + "mass": 0.007, + "volume": 7.099633976330041e-06, + "density": 985.9663221143206 + }, + "half_duck": { + "mass": 1.05, + "volume": 0.006074476414136542, + "density": 172.8544039707581 + }, + "half_durian": { + "mass": 0.813, + "volume": 0.0004988530378100568, + "density": 1629.7384968708113 + }, + "half_edible_cookie_dough": { + "mass": 0.22, + "volume": 0.0009605699247909394, + "density": 229.03069763284677 + }, + "half_enchilada": { + "mass": 0.145, + "volume": 0.00019288054196583341, + "density": 751.7606417016657 + }, + "half_fennel": { + "mass": 0.123, + "volume": 0.00020432428742233065, + "density": 601.9842357054872 + }, + "half_fillet": { + "mass": 0.182, + "volume": 0.00013884547654548275, + "density": 1310.8097183157477 + }, + "half_french_fries": { + "mass": 0.004, + "volume": 1.1512151556747866e-06, + "density": 3474.5894199554677 + }, + "half_french_toast": { + "mass": 0.064, + "volume": 0.0001739081157362135, + "density": 368.01042739762755 + }, + "half_fruitcake": { + "mass": 0.55, + "volume": 0.0016702702544062749, + "density": 329.2880290174997 + }, + "half_garlic": { + "mass": 0.025, + "volume": 5.930040645363765e-05, + "density": 421.5822705961644 + }, + "half_garlic_bread": { + "mass": 0.138, + "volume": 0.00030594121621140306, + "density": 451.0670438880751 + }, + "half_garlic_clove": { + "mass": 0.002, + "volume": 5.895052001292569e-07, + "density": 3392.675755127306 + }, + "half_gelatin": { + "mass": 0.006, + "volume": 2.575044704415805e-06, + "density": 2330.0566354094453 + }, + "half_ginger_root": { + "mass": 0.047, + "volume": 5.994065530965933e-05, + "density": 784.1088783096109 + }, + "half_gingerbread": { + "mass": 0.08, + "volume": 9.855489685119527e-05, + "density": 811.7303407134535 + }, + "half_gooseberry": { + "mass": 0.003, + "volume": 6.08826781879928e-07, + "density": 4927.509908050753 + }, + "half_gourd": { + "mass": 0.352, + "volume": 0.0002864920007088674, + "density": 1228.655596418211 + }, + "half_granola_bar": { + "mass": 0.023, + "volume": 2.4148015334291183e-05, + "density": 952.4592262180257 + }, + "half_grapefruit": { + "mass": 0.25, + "volume": 0.0003235428111586715, + "density": 772.695270541478 + }, + "half_green_bean": { + "mass": 0.004, + "volume": 4.152383978229743e-06, + "density": 963.3020503333347 + }, + "half_green_onion": { + "mass": 0.025, + "volume": 2.8400468808923972e-05, + "density": 880.2671592570515 + }, + "half_ham_hock": { + "mass": 0.45, + "volume": 0.0004364522912980686, + "density": 1031.0405260140544 + }, + "half_hamburger": { + "mass": 0.135, + "volume": 0.00021807220594072946, + "density": 619.0610097129576 + }, + "half_hamburger_bun": { + "mass": 0.046, + "volume": 5.6829575106618714e-05, + "density": 809.4376900354929 + }, + "half_hazelnut": { + "mass": 0.004, + "volume": 2.7236925700480325e-06, + "density": 1468.5945264114223 + }, + "half_head_cabbage": { + "mass": 0.5, + "volume": 0.000756532506010717, + "density": 660.910134101914 + }, + "half_hotdog": { + "mass": 0.08, + "volume": 0.00020369591081891619, + "density": 392.74229746869725 + }, + "half_hotdog_bun": { + "mass": 0.05, + "volume": 0.000134884042930967, + "density": 370.6887702468243 + }, + "half_hotdog_frank": { + "mass": 0.043, + "volume": 3.63782508041082e-05, + "density": 1182.0249475861 + }, + "half_kale": { + "mass": 0.021, + "volume": 7.853001228657056e-06, + "density": 2674.1368539924724 + }, + "half_kielbasa": { + "mass": 0.108, + "volume": 5.741446177228728e-05, + "density": 1881.0591733549832 + }, + "half_lamb": { + "mass": 0.325, + "volume": 0.00019016804574092583, + "density": 1709.0147755041958 + }, + "half_leaf": { + "mass": 0.005, + "volume": 5.209630309455038e-06, + "density": 959.7610008766694 + }, + "half_leek": { + "mass": 0.113, + "volume": 0.000181243110536244, + "density": 623.471974552119 + }, + "half_lettuce": { + "mass": 0.143, + "volume": 0.00014553552952498925, + "density": 982.577934520423 + }, + "half_lobster": { + "mass": 0.475, + "volume": 0.0005067761157768254, + "density": 937.2975268810437 + }, + "half_macaroon": { + "mass": 0.015, + "volume": 2.5027606694031523e-05, + "density": 599.3381701805764 + }, + "half_marshmallow": { + "mass": 0.014, + "volume": 9.802386294642954e-05, + "density": 142.82236568916957 + }, + "half_meat_loaf": { + "mass": 0.534, + "volume": 0.0015297727859180789, + "density": 349.07144702507236 + }, + "half_meatball": { + "mass": 0.017, + "volume": 5.951640808924246e-06, + "density": 2856.355170915084 + }, + "half_mozzarella": { + "mass": 0.2, + "volume": 2.7013788351528583e-05, + "density": 7403.626525736178 + }, + "half_muffin": { + "mass": 0.055, + "volume": 9.171232708614263e-05, + "density": 599.7012805960114 + }, + "half_mustard_leaf": { + "mass": 0.002, + "volume": 3.619382128689428e-07, + "density": 5525.805037679724 + }, + "half_nectarine": { + "mass": 0.073, + "volume": 0.00012254830832069126, + "density": 595.683457408237 + }, + "half_olive": { + "mass": 0.002, + "volume": 3.6002473461002864e-06, + "density": 555.5173874834902 + }, + "half_omelet": { + "mass": 0.11, + "volume": 0.00026113162431759334, + "density": 421.24350234277205 + }, + "half_oyster": { + "mass": 0.05, + "volume": 5.599914016924475e-05, + "density": 892.8708521039126 + }, + "half_parsley": { + "mass": 0.004, + "volume": 6.656131418598629e-07, + "density": 6009.496730823493 + }, + "half_parsnip": { + "mass": 0.058, + "volume": 8.510333596598713e-05, + "density": 681.5244002089484 + }, + "half_pastry": { + "mass": 0.453, + "volume": 0.000959920164186958, + "density": 471.91424547653514 + }, + "half_peppermint": { + "mass": 0.002, + "volume": 4.621936757940462e-08, + "density": 43271.903203002745 + }, + "half_peppermint_candy": { + "mass": 0.008, + "volume": 7.300412863808187e-06, + "density": 1095.8284345341642 + }, + "half_pepperoni": { + "mass": 0.011, + "volume": 1.225499495627621e-06, + "density": 8975.931886749995 + }, + "half_pickle": { + "mass": 0.026, + "volume": 2.5078769214967702e-05, + "density": 1036.7334926660787 + }, + "half_pita": { + "mass": 0.064, + "volume": 7.186301716941238e-05, + "density": 890.5832585504193 + }, + "half_pizza": { + "mass": 0.5, + "volume": 0.0014066257472557747, + "density": 355.46057718299545 + }, + "half_pizza_dough": { + "mass": 0.439, + "volume": 0.0009685029902299965, + "density": 453.2768658729158 + }, + "half_pork": { + "mass": 0.139, + "volume": 5.531206539904827e-05, + "density": 2513.0140955176066 + }, + "half_pork_chop": { + "mass": 0.166, + "volume": 9.912366462615807e-05, + "density": 1674.6757762242148 + }, + "half_pork_rib": { + "mass": 0.218, + "volume": 7.291316727305966e-05, + "density": 2989.857774023044 + }, + "half_pretzel": { + "mass": 0.038, + "volume": 0.000527347315844739, + "density": 72.05877200518059 + }, + "half_prosciutto": { + "mass": 0.738, + "volume": 0.0018135279493587287, + "density": 406.94161910267775 + }, + "half_pumpkin": { + "mass": 1.038, + "volume": 0.0006250174472008576, + "density": 1660.7536391962913 + }, + "half_quail_breast": { + "mass": 0.065, + "volume": 7.162745282894314e-05, + "density": 907.4732861886006 + }, + "half_quiche": { + "mass": 0.275, + "volume": 0.00027060596438564235, + "density": 1016.2377633631744 + }, + "half_radish": { + "mass": 0.022, + "volume": 1.2383009238720652e-06, + "density": 17766.27924269636 + }, + "half_ramen": { + "mass": 0.107, + "volume": 9.772903913928545e-05, + "density": 1094.8639313592491 + }, + "half_rhubarb": { + "mass": 0.043, + "volume": 1.7368841275386177e-05, + "density": 2475.697677134996 + }, + "half_roll_dough": { + "mass": 0.595, + "volume": 0.0009669255381451157, + "density": 615.3524511736525 + }, + "half_rope": { + "mass": 0.143, + "volume": 0.00017115917219486437, + "density": 835.4796191535372 + }, + "half_rosehip": { + "mass": 0.009, + "volume": 3.535235478498161e-05, + "density": 254.57992981625597 + }, + "half_rutabaga": { + "mass": 0.463, + "volume": 0.00035584675097608096, + "density": 1301.1218979237542 + }, + "half_salmon": { + "mass": 0.143, + "volume": 5.044290044845575e-05, + "density": 2834.8885319574792 + }, + "half_scone": { + "mass": 0.074, + "volume": 0.0001429728090910272, + "density": 517.5809335388105 + }, + "half_shiitake": { + "mass": 0.011, + "volume": 1.870153728244251e-05, + "density": 588.1869406707589 + }, + "half_shrimp": { + "mass": 0.011, + "volume": 9.92963919714182e-06, + "density": 1107.7945312621505 + }, + "half_snapper": { + "mass": 0.275, + "volume": 0.0006658020424501811, + "density": 413.03568097806937 + }, + "half_sourdough": { + "mass": 0.225, + "volume": 0.00011928135613621927, + "density": 1886.2964614776015 + }, + "half_spice_cookie": { + "mass": 0.015, + "volume": 2.0987850173321155e-05, + "density": 714.6992129316488 + }, + "half_spice_cookie_dough": { + "mass": 0.602, + "volume": 0.0009854227911931458, + "density": 610.9052940323218 + }, + "half_spinach": { + "mass": 0.023, + "volume": 2.4168417481920187e-06, + "density": 9516.551928650582 + }, + "half_squid": { + "mass": 0.035, + "volume": 2.7299252584238577e-06, + "density": 12820.863828413936 + }, + "half_steak": { + "mass": 0.46, + "volume": 0.00020172730663581907, + "density": 2280.3060610452903 + }, + "half_sugar_cookie": { + "mass": 0.018, + "volume": 2.1956731199736214e-05, + "density": 819.7941595339223 + }, + "half_sugar_cookie_dough": { + "mass": 0.514, + "volume": 0.0009590751822348277, + "density": 535.9329586678306 + }, + "half_sunflower": { + "mass": 0.05, + "volume": 4.8832008848918935e-05, + "density": 1023.9185562628543 + }, + "half_sushi": { + "mass": 0.04, + "volume": 6.237313321757149e-06, + "density": 6413.017582501591 + }, + "half_sweet_corn": { + "mass": 0.126, + "volume": 0.00024812943015341965, + "density": 507.79949771413084 + }, + "half_swiss_cheese": { + "mass": 0.096, + "volume": 6.085865210830414e-05, + "density": 1577.425668730853 + }, + "half_taco": { + "mass": 0.08, + "volume": 0.000161123804326078, + "density": 496.5126061577975 + }, + "half_tenderloin": { + "mass": 0.235, + "volume": 0.00017071148466099156, + "density": 1376.591624556931 + }, + "half_tiramisu": { + "mass": 0.11, + "volume": 8.91298946702092e-05, + "density": 1234.1538201858375 + }, + "half_toast": { + "mass": 0.054, + "volume": 0.0002676237746558111, + "density": 201.77579540326334 + }, + "half_tofu": { + "mass": 0.048, + "volume": 8.088137447457253e-06, + "density": 5934.617248015516 + }, + "half_tortilla": { + "mass": 0.041, + "volume": 1.1373064491628491e-05, + "density": 3605.0090131977504 + }, + "half_tortilla_chip": { + "mass": 0.004, + "volume": 4.5033458760321726e-06, + "density": 888.2284661475608 + }, + "half_trout": { + "mass": 0.188, + "volume": 9.42556313116421e-05, + "density": 1994.5757869724116 + }, + "half_tuna": { + "mass": 1.375, + "volume": 0.0040162207959063435, + "density": 342.36165536553943 + }, + "half_turkey": { + "mass": 2.175, + "volume": 0.003521927423993214, + "density": 617.5595741078481 + }, + "half_turkey_leg": { + "mass": 0.2, + "volume": 0.00016045523222779005, + "density": 1246.4535884755087 + }, + "half_vanilla_flower": { + "mass": 0.003, + "volume": 1.0688827804455155e-06, + "density": 2806.668846091417 + }, + "half_veal": { + "mass": 0.494, + "volume": 0.0003078430243247289, + "density": 1604.7139644746442 + }, + "half_venison": { + "mass": 0.375, + "volume": 7.922332018129697e-05, + "density": 4733.454734563497 + }, + "half_virginia_ham": { + "mass": 1.325, + "volume": 0.0026795486460988193, + "density": 494.48626429271224 + }, + "half_waffle": { + "mass": 0.113, + "volume": 0.001286357130455105, + "density": 87.84496725261772 + }, + "half_walnut": { + "mass": 0.008, + "volume": 2.0889632978552503e-05, + "density": 382.96508168495075 + }, + "half_white_turnip": { + "mass": 0.07, + "volume": 1.6507749769531592e-06, + "density": 42404.32583319093 + }, + "half_wrapping_paper": { + "mass": 0.008, + "volume": 0.00015577904164249334, + "density": 51.3547901928918 + }, + "mat": { + "mass": 1.2, + "volume": 0.0031813439676883254, + "density": 377.19907441255447 + }, + "mozzarella": { + "mass": 0.116, + "volume": 5.281627930532997e-05, + "density": 2196.2925356670066 + }, + "peppermint": { + "mass": 0.002, + "volume": 4.599654844770609e-07, + "density": 4348.152345113066 + }, + "pita": { + "mass": 0.069, + "volume": 0.00014095985202699428, + "density": 489.5010813915034 + }, + "snapper": { + "mass": 1.632, + "volume": 0.0014689174076359447, + "density": 1111.0223022181472 + }, + "tenderloin": { + "mass": 0.45, + "volume": 0.0003361315176272818, + "density": 1338.7616941621668 + }, + "venison": { + "mass": 0.285, + "volume": 0.00016796746412684827, + "density": 1696.757175453749 + }, + "half_kabob": { + "mass": 0.103, + "volume": 4.1170233924378776e-05, + "density": 2501.807499787097 + }, + "espresso_machine": { + "mass": 10.0, + "volume": 0.043125965498890334, + "density": 231.87886657882032 + }, + "outline_vase": { + "mass": 0.512, + "volume": 0.0020934897725887755, + "density": 244.56771019562666 + }, + "jar_of_sesame_seed": { + "mass": 0.475, + "volume": 0.0010284980688903293, + "density": 461.8384947601201 + }, + "jar_of_clove": { + "mass": 0.25, + "volume": 0.0010527824092924588, + "density": 237.46597377896632 + }, + "jar_of_coffee": { + "mass": 0.536, + "volume": 0.0003580332055873834, + "density": 1497.067846320699 + }, + "jar_of_strawberry_jam": { + "mass": 1.0, + "volume": 0.001178339411372904, + "density": 848.6519167129294 + }, + "jar_of_peppercorns": { + "mass": 0.3, + "volume": 0.00038753848072713376, + "density": 774.1166746515433 + }, + "jar_of_pepper_seasoning": { + "mass": 0.4, + "volume": 0.0009993827585549507, + "density": 400.24704906694285 + }, + "jar_of_kidney_beans": { + "mass": 0.727, + "volume": 0.0007132627443510748, + "density": 1019.259740898739 + }, + "jar_of_tumeric": { + "mass": 0.3, + "volume": 0.0004131008194788482, + "density": 726.2149718765222 + }, + "bottle_of_strawberry_juice": { + "mass": 0.9, + "volume": 0.00017146149234406258, + "density": 5248.991990539884 + }, + "jar_of_chilli_powder": { + "mass": 0.375, + "volume": 0.0007646527985001681, + "density": 490.41865894631593 + }, + "jar_of_cocoa": { + "mass": 0.61, + "volume": 0.0005533025317701796, + "density": 1102.4710081271962 + }, + "outline_tray": { + "mass": 0.338, + "volume": 0.00018652453820346197, + "density": 1812.0940185966729 + }, + "skateboard_deck": { + "mass": 1.78, + "volume": 0.011889114053805439, + "density": 149.71679066618609 + }, + "glass_lantern": { + "mass": 1.5, + "volume": 0.005543740878033013, + "density": 270.57541703360033 + }, + "paper_lantern": { + "mass": 0.35, + "volume": 0.016278295644652357, + "density": 21.501022443647518 + }, + "hitch": { + "mass": 3.25, + "volume": 0.001226797855122898, + "density": 2649.1732003186635 + }, + "poster_roll": { + "mass": 0.275, + "volume": 0.001085941344093551, + "density": 253.2365136438801 + }, + "decorative_sign": { + "mass": 1.73, + "volume": 0.013903858025603436, + "density": 124.42589652557366 + }, + "wall_nail": { + "mass": 0.006, + "volume": 3.755404820773653e-07, + "density": 15976.972620394989 + }, + "clothesline_rope": { + "mass": 0.162, + "volume": 8.413066560639245e-06, + "density": 19255.761122575837 + }, + "trampoline_top": { + "mass": 4.5, + "volume": 0.3116610779703758, + "density": 14.438761584556083 + }, + "trampoline_leg": { + "mass": 2.75, + "volume": 0.002177314508080847, + "density": 1263.0237798874246 + }, + "desk_top": { + "mass": 7.435, + "volume": 0.021896798328496066, + "density": 339.54735703640455 + }, + "desk_bracket": { + "mass": 1.315, + "volume": 0.006768796976537539, + "density": 194.27381328737465 + }, + "desk_leg": { + "mass": 1.95, + "volume": 0.0010408984374880026, + "density": 1873.3816189655638 + }, + "cabinet_base": { + "mass": 9.25, + "volume": 0.004801083333429428, + "density": 1926.648499432043 + }, + "cabinet_door": { + "mass": 2.445, + "volume": 0.000990984963821368, + "density": 2467.2422784012374 + }, + "box_of_wagashi": { + "mass": 0.434, + "volume": 0.0017296867176324893, + "density": 250.91248928247424 + }, + "satchel": { + "mass": 1.5, + "volume": 0.010910087618081196, + "density": 137.4874384614531 + }, + "bottle_of_tomato_juice": { + "mass": 0.676, + "volume": 0.00039301027585550717, + "density": 1720.0568064752993 + }, + "hook_rack": { + "mass": 0.65, + "volume": 0.0004457036402907248, + "density": 1458.3681649447967 + }, + "soupspoon": { + "mass": 0.05, + "volume": 6.571104644940499e-05, + "density": 760.9070727324074 + }, + "cooking_oil_atomizer": { + "mass": 0.225, + "volume": 0.00031491234368921764, + "density": 714.4845367574706 + }, + "cellulose_tape_dispenser": { + "mass": 0.175, + "volume": 0.0002441033552385748, + "density": 716.9094412035569 + }, + "fried_chicken": { + "mass": 0.197, + "volume": 0.0002805096185446727, + "density": 702.2932084185437 + }, + "half_fried_chicken": { + "mass": 0.11, + "volume": 2.376313226898517e-05, + "density": 4629.019388305483 + }, + "gaming_controller": { + "mass": 0.265, + "volume": 0.0006085433204712169, + "density": 435.46612227179 + }, + "bar_stool": { + "mass": 5.0, + "volume": 0.04023512990204321, + "density": 124.26951303930278 + }, + "pattypan_squash": { + "mass": 0.375, + "volume": 0.0021995197299707905, + "density": 170.49176458398034 + }, + "skateboard_wheel_assembly": { + "mass": 0.475, + "volume": 0.0015263608741690206, + "density": 311.1977043165489 + }, + "jar_of_vegetable": { + "mass": 1.1, + "volume": 0.007454056927459374, + "density": 147.57064652240615 + }, + "sliced_watermelon": { + "mass": 0.3, + "volume": 0.00012806273028079934, + "density": 2342.6019368960738 + }, + "christmas_stocking": { + "mass": 0.35, + "volume": 0.0014476030626584349, + "density": 241.77898557167066 + }, + "gold_coin": { + "mass": 0.03, + "volume": 1.0444718049751925e-06, + "density": 28722.651829469476 + }, + "standing_mirror": { + "mass": 10.0, + "volume": 0.025330502959314535, + "density": 394.7809491213754 + }, + "furniture_sink": { + "mass": 32.5, + "volume": 0.17519422471194268, + "density": 185.50839819883933 + }, + "multi_station_furniture_sink": { + "mass": 80.0, + "volume": 1.1428601845034736, + "density": 69.99981369965806 + }, + "pedestal_sink": { + "mass": 35.0, + "volume": 0.035296892529840654, + "density": 991.5887062978801 + }, + "wall_mounted_sink": { + "mass": 22.5, + "volume": 0.16178761157388558, + "density": 139.07121677066505 + }, + "drop_in_sink": { + "mass": 20.0, + "volume": 0.015256797194599731, + "density": 1310.89112248796 + }, + "multi_station_wall_mounted_sink": { + "mass": 70.0, + "volume": 0.365133889800833, + "density": 191.7104984097269 + }, + "tabletop_sink": { + "mass": 17.5, + "volume": 0.014549537089518606, + "density": 1202.7874077593087 + }, + "multi_station_tabletop_sink": { + "mass": 30.0, + "volume": 0.030887314216686695, + "density": 971.2725356933971 + }, + "track_light": { + "mass": 3.75, + "volume": 0.021715829136284174, + "density": 172.685094198603 + }, + "swing_set": { + "mass": 50.0, + "volume": 0.6962321656430577, + "density": 71.81512499328257 + }, + "rectangular_light": { + "mass": 5.0, + "volume": 0.010945328694363857, + "density": 456.8158837088812 + }, + "public_trash_can": { + "mass": 20.0, + "volume": 0.05291603457776693, + "density": 377.95727060022654 + }, + "flat_top_grill": { + "mass": 57.379, + "volume": 0.4452275101186243, + "density": 128.87568421976488 + }, + "griddle_pan": { + "mass": 1.5, + "volume": 0.00031873494298596816, + "density": 4706.104658459224 + }, + "makeup_mirror": { + "mass": 2.625, + "volume": 0.01034538583202024, + "density": 253.7363074343059 + }, + "vine": { + "mass": 0.75, + "volume": 0.09411049806100784, + "density": 7.96935533710391 + }, + "dish_rack_cart": { + "mass": 17.5, + "volume": 0.037065969092326956, + "density": 472.1311874083088 + }, + "green_onion_stalk": { + "mass": 0.019, + "volume": 1.0291974783346869e-05, + "density": 1846.0985768001804 + }, + "cream_pitcher": { + "mass": 0.379, + "volume": 0.0007736343250200455, + "density": 489.89553299639306 + }, + "footstool": { + "mass": 4.9, + "volume": 0.017515502510291547, + "density": 279.752179369157 + }, + "sliced_mushroom": { + "mass": 0.014, + "volume": 5.6563356750123865e-06, + "density": 2475.1006312880013 + }, + "rolled_yoga_mat": { + "mass": 1.15, + "volume": 0.006659689598233547, + "density": 172.6807207808953 + }, + "standing_loudspeaker": { + "mass": 5.25, + "volume": 0.006805928950649687, + "density": 771.3862483825725 + }, + "bunk_bed": { + "mass": 50.0, + "volume": 0.974369214655533, + "density": 51.31525016179459 + }, + "silver_coin": { + "mass": 0.02, + "volume": 9.097848282375306e-07, + "density": 21983.219965038057 + }, + "walnut_meat": { + "mass": 0.009, + "volume": 1.4272828626328284e-05, + "density": 630.5687706078251 + }, + "game_console": { + "mass": 2.305, + "volume": 0.004069555525611385, + "density": 566.4009215487264 + }, + "portable_game_console": { + "mass": 0.293, + "volume": 8.638386880913e-05, + "density": 3391.836971870291 + }, + "firewood_chopping_block": { + "mass": 35.56, + "volume": 0.0859191526291383, + "density": 413.8774523707339 + }, + "fixed_window": { + "mass": 20.0, + "volume": 0.2923179406857379, + "density": 68.41865385710756 + }, + "hinged_jar": { + "mass": 1.01, + "volume": 0.0009034844174013143, + "density": 1117.8942110645978 + }, + "hingeless_jar": { + "mass": 0.595, + "volume": 0.0006600326952157746, + "density": 901.4704942843559 + } +} diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/dd.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/dd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..486fb1c2b3155851c1e8a23eb4df7dfc1a8d4d5c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/dd.yaml @@ -0,0 +1,10 @@ +# Example Differential Drive control config (shown for base control) +# See omnigibson/controllers/dd_controller for docstring of arguments +# Arguments below are the arguments that should be specified by external user (other kwargs +# used in constructor are generated automatically at runtime) +robot: + controller_config: + base: + name: DifferentialDriveController + command_input_limits: default + command_output_limits: default \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/ik.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/ik.yaml new file mode 100644 index 0000000000000000000000000000000000000000..69db5015746a7563278f538a450a422d2be49958 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/ik.yaml @@ -0,0 +1,17 @@ +# Example IK config (shown for arm control) +# See omnigibson/controllers/ik_controller for docstring of arguments +# Arguments below are the arguments that should be specified by external user (other kwargs +# used in constructor are generated automatically at runtime) +robot: + controller_config: + arm: + name: InverseKinematicsController + command_input_limits: default + command_output_limits: + - [-0.2, -0.2, -0.2, -0.5, -0.5, -0.5] + - [0.2, 0.2, 0.2, 0.5, 0.5, 0.5] + kv: 2.0 + mode: pose_delta_ori + smoothing_filter_size: 2 + workspace_pose_limiter: null + joint_range_tolerance: 0.01 \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/joint.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/joint.yaml new file mode 100644 index 0000000000000000000000000000000000000000..665ad5a9afcfb8b22e5947ec51261a2c515e3753 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/joint.yaml @@ -0,0 +1,12 @@ +# Example Joint control config (shown for arm control) +# See omnigibson/controllers/joint_controller for docstring of arguments +# Arguments below are the arguments that should be specified by external user (other kwargs +# used in constructor are generated automatically at runtime) +robot: + controller_config: + arm: + name: JointController + motor_type: velocity + command_input_limits: default + command_output_limits: default + use_delta_commands: false diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/multi_finger_gripper.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/multi_finger_gripper.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d72d40dee5e6d6eb071d64f4bbacc72b8f1e14e1 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/multi_finger_gripper.yaml @@ -0,0 +1,15 @@ +# Example Multi Finger Gripper control config (shown for arm control) +# See omnigibson/controllers/parallel_jaw_gripper_controller for docstring of arguments +# Arguments below are the arguments that should be specified by external user (other kwargs +# used in constructor are generated automatically at runtime) +robot: + controller_config: + arm: + name: MultiFingerGripperController + motor_type: position + command_input_limits: default + command_output_limits: default + mode: binary + open_qpos: null + closed_qpos: null + limit_tolerance: 0.01 \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/null_gripper.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/null_gripper.yaml new file mode 100644 index 0000000000000000000000000000000000000000..caf867b1f7c6f119f8ba404d84f6f3a3a1b2dbdc --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/controllers/null_gripper.yaml @@ -0,0 +1,9 @@ +# Example Null Gripper control config (shown for gripper control) +# See omnigibson/controllers/null_gripper_controller for docstring of arguments +# Arguments below are the arguments that should be specified by external user (other kwargs +# used in constructor are generated automatically at runtime) +robot: + controller_config: + gripper: + name: NullJointController + # no other args to specify (this is a dummy controller) \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/default_cfg.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/default_cfg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5f1df58db832fb3d92b23bb197203aba950666f2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/default_cfg.yaml @@ -0,0 +1,16 @@ +env: + device: null # (None or str): specifies the device to be used if running on the gpu with torch backend + +render: + viewer_width: 1280 + viewer_height: 720 + +scene: + type: Scene + +robots: [] + +objects: [] + +task: + type: DummyTask diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/franka_vector_env.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/franka_vector_env.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c8299b5a61eb00ec614663e11e2e3ebfb0dbe1e3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/franka_vector_env.yaml @@ -0,0 +1,64 @@ +env: + action_frequency: 30 # (int): environment executes action at the action_frequency rate + physics_frequency: 120 # (int): physics frequency (1 / physics_timestep for physx) + device: null # (None or str): specifies the device to be used if running on the gpu with torch backend + automatic_reset: false # (bool): whether to automatic reset after an episode finishes + flatten_action_space: false # (bool): whether to flatten the action space as a sinle 1D-array + flatten_obs_space: false # (bool): whether the observation space should be flattened when generated + use_external_obs: false # (bool): Whether to use external observations or not + initial_pos_z_offset: 0.1 + external_sensors: null # (None or list): If specified, list of sensor configurations for external sensors to add. Should specify sensor "type" and any additional kwargs to instantiate the sensor. Each entry should be the kwargs passed to @create_sensor, in addition to position, orientation + +render: + viewer_width: 1280 + viewer_height: 720 + +scene: + type: InteractiveTraversableScene + scene_model: Rs_int + trav_map_resolution: 0.1 + default_erosion_radius: 0.0 + trav_map_with_objects: true + num_waypoints: 1 + waypoint_resolution: 0.2 + load_object_categories: null + not_load_object_categories: null + load_room_types: null + load_room_instances: null + load_task_relevant_only: false + seg_map_resolution: 1.0 + scene_source: OG + include_robots: false + +robots: + - type: Franka + obs_modalities: [rgb] + include_sensor_names: null + exclude_sensor_names: null + scale: 1.0 + self_collisions: true + action_normalize: false + action_type: continuous + grasping_mode: physical + sensor_config: + VisionSensor: + sensor_kwargs: + image_height: 128 + image_width: 128 + controller_config: + arm_0: + name: JointController + motor_type: position + command_input_limits: default + command_output_limits: default + use_delta_commands: false + use_impedances: False + gripper_0: + name: MultiFingerGripperController + mode: smooth + command_input_limits: default + command_output_limits: default +objects: [] + +task: + type: DummyTask diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/r1_primitives.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/r1_primitives.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1f8bb1865749c27b93cb5c7126114352d42641d4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/r1_primitives.yaml @@ -0,0 +1,114 @@ +env: + action_frequency: 30 # (int): environment executes action at the action_frequency rate + physics_frequency: 120 # (int): physics frequency (1 / physics_timestep for physx) + device: null # (None or str): specifies the device to be used if running on the gpu with torch backend + automatic_reset: false # (bool): whether to automatic reset after an episode finishes + flatten_action_space: false # (bool): whether to flatten the action space as a sinle 1D-array + flatten_obs_space: false # (bool): whether the observation space should be flattened when generated + use_external_obs: false # (bool): Whether to use external observations or not + external_sensors: null # (None or list): If specified, list of sensor configurations for external sensors to add. Should specify sensor "type" and any additional kwargs to instantiate the sensor. Each entry should be the kwargs passed to @create_sensor, in addition to position, orientation + +render: + viewer_width: 1280 + viewer_height: 720 + +scene: + type: InteractiveTraversableScene + scene_model: Rs_int + trav_map_resolution: 0.1 + default_erosion_radius: 0.0 + trav_map_with_objects: true + num_waypoints: 1 + waypoint_resolution: 0.2 + load_object_categories: null + not_load_object_categories: null + load_room_types: null + load_room_instances: null + load_task_relevant_only: false + seg_map_resolution: 1.0 + scene_source: OG + include_robots: false + +robots: + - type: R1 + obs_modalities: [rgb] + include_sensor_names: null + exclude_sensor_names: null + scale: 1.0 + self_collisions: true + action_normalize: false + action_type: continuous + grasping_mode: sticky + reset_joint_pos: [ + 0.0000, + -0.0000, + 0.0247, + 0.0009, + 0.0004, + -0.0000, + 0.0000, + 0.0000, + 0.0000, + 0.0000, + -0.0464, + 0.0464, + 2.6172, + 2.6168, + -1.4584, + -1.4570, + -0.0433, + 0.0418, + 1.5899, + -1.5896, + -1.1587, + 1.1593, + 0.0300, + 0.0300, + 0.0300, + 0.0300, + ] + sensor_config: + VisionSensor: + sensor_kwargs: + image_height: 128 + image_width: 128 + controller_config: + base: + name: HolonomicBaseJointController + motor_type: position + command_input_limits: null + use_impedances: false + trunk: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false + arm_left: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false + arm_right: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false + gripper_left: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false + gripper_right: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false + +objects: [] +task: + type: DummyTask \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/r1pro_behavior.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/r1pro_behavior.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9e9482caa70ddcad7ba2be0182ba1f244d4a3f6b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/r1pro_behavior.yaml @@ -0,0 +1,114 @@ +env: + device: null # (None or str): specifies the device to be used if running on the gpu with torch backend + automatic_reset: false # (bool): whether to automatic reset after an episode finishes + flatten_action_space: false # (bool): whether to flatten the action space as a sinle 1D-array + flatten_obs_space: false # (bool): whether the observation space should be flattened when generated + use_external_obs: false # (bool): Whether to use external observations or not + initial_pos_z_offset: 0.1 + external_sensors: # (None or list): If specified, list of sensor configurations for external sensors to add. Should specify sensor "type" and any additional kwargs to instantiate the sensor. Each entry should be the kwargs passed to @create_sensor, in addition to position, orientation + - sensor_type: VisionSensor + name: external_sensor0 + relative_prim_path: /external_sensor0 + modalities: [rgb, depth] + sensor_kwargs: + image_height: 128 + image_width: 128 + position: [0, 0, 1.0] + orientation: [0.707, 0.0, 0.0, 0.707] + pose_frame: parent + + +render: + viewer_width: 1280 + viewer_height: 720 + +scene: + type: InteractiveTraversableScene + scene_model: house_double_floor_lower + trav_map_resolution: 0.1 + default_erosion_radius: 0.0 + trav_map_with_objects: true + num_waypoints: 1 + waypoint_resolution: 0.2 + not_load_object_categories: null + load_room_types: ["living_room", "kitchen"] + load_room_instances: null + seg_map_resolution: 1.0 + scene_source: OG + include_robots: true + +robots: + - type: R1Pro + obs_modalities: [rgb, depth] + include_sensor_names: null + exclude_sensor_names: null + scale: 1.0 + self_collision: false + action_normalize: true + action_type: continuous + grasping_mode: physical + default_reset_mode: tuck + sensor_config: + VisionSensor: + sensor_kwargs: + image_height: 128 + image_width: 128 + controller_config: + base: + name: HolonomicBaseJointController + motor_type: velocity + vel_kp: 150 + command_input_limits: default + command_output_limits: default + use_impedances: false + trunk: + name: JointController + motor_type: position + pos_kp: 150 + command_input_limits: default + command_output_limits: default + use_impedances: false + use_delta_commands: false + arm_left: + name: JointController + motor_type: position + pos_kp: 150 + command_input_limits: default + command_output_limits: default + use_impedances: false + use_delta_commands: false + arm_right: + name: JointController + motor_type: position + pos_kp: 150 + command_input_limits: default + command_output_limits: default + use_impedances: false + use_delta_commands: false + gripper_left: + name: MultiFingerGripperController + mode: smooth + command_input_limits: default + command_output_limits: default + gripper_right: + name: MultiFingerGripperController + mode: smooth + command_input_limits: default + command_output_limits: default + +objects: [] + +task: + type: BehaviorTask + activity_name: picking_up_trash + activity_definition_id: 0 + activity_instance_id: 0 + predefined_problem: null + online_object_sampling: false + debug_object_sampling: null + highlight_task_relevant_objects: false + use_presampled_robot_pose: true + termination_config: + max_steps: 500 + reward_config: + r_potential: 1.0 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/r1pro_primitives.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/r1pro_primitives.yaml new file mode 100644 index 0000000000000000000000000000000000000000..aa412ebbdf017e1b05136e7acbe88da09598a40a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/r1pro_primitives.yaml @@ -0,0 +1,117 @@ +env: + action_frequency: 30 # (int): environment executes action at the action_frequency rate + physics_frequency: 120 # (int): physics frequency (1 / physics_timestep for physx) + device: null # (None or str): specifies the device to be used if running on the gpu with torch backend + automatic_reset: false # (bool): whether to automatic reset after an episode finishes + flatten_action_space: false # (bool): whether to flatten the action space as a sinle 1D-array + flatten_obs_space: false # (bool): whether the observation space should be flattened when generated + use_external_obs: false # (bool): Whether to use external observations or not + external_sensors: null # (None or list): If specified, list of sensor configurations for external sensors to add. Should specify sensor "type" and any additional kwargs to instantiate the sensor. Each entry should be the kwargs passed to @create_sensor, in addition to position, orientation + +render: + viewer_width: 1280 + viewer_height: 720 + +scene: + type: InteractiveTraversableScene + scene_model: Rs_int + trav_map_resolution: 0.1 + default_erosion_radius: 0.0 + trav_map_with_objects: true + num_waypoints: 1 + waypoint_resolution: 0.2 + load_object_categories: null + not_load_object_categories: null + load_room_types: ["living_room"] + load_room_instances: null + load_task_relevant_only: false + seg_map_resolution: 1.0 + scene_source: OG + include_robots: false + +robots: + - type: R1Pro + obs_modalities: [rgb] + include_sensor_names: null + exclude_sensor_names: null + scale: 1.0 + self_collisions: true + action_normalize: false + action_type: continuous + grasping_mode: sticky + reset_joint_pos: [ + 0.0000, + -0.0000, + 0.0247, + 0.0009, + 0.0004, + -0.0000, + 0.0000, + 0.0000, + 0.0000, + 0.0000, + 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.0300, + 0.0300, + 0.0300, + 0.0300, + ] + sensor_config: + VisionSensor: + sensor_kwargs: + image_height: 128 + image_width: 128 + controller_config: + base: + name: HolonomicBaseJointController + motor_type: position + command_input_limits: null + use_impedances: false + trunk: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false + arm_left: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false + arm_right: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false + gripper_left: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false + gripper_right: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false + +objects: [] + +task: + type: DummyTask \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/fetch.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/fetch.yaml new file mode 100644 index 0000000000000000000000000000000000000000..30af214a486ba33a9580014e6173588453c86ecf --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/fetch.yaml @@ -0,0 +1,42 @@ +# Example Fetch config +robot: + name: Fetch + action_type: continuous + action_normalize: true + proprio_obs: + - eef_0_pos + - eef_0_quat + - trunk_qpos + - arm_0_qpos_sin + - arm_0_qpos_cos + - gripper_0_qpos + - grasp_main + reset_joint_pos: null + base_name: null + scale: 1.0 + self_collision: true + grasping_mode: physical + default_arm_pose: vertical + include_sensor_names: null + exclude_sensor_names: null + sensor_config: + VisionSensor: + sensor_kwargs: + image_height: 128 + image_width: 128 + ScanSensor: + sensor_kwargs: + min_range: 0.05 + max_range: 10.0 + controller_config: + base: + name: DifferentialDriveController + trunk: + name: JointController + arm_0: + name: InverseKinematicsController + subsume_controllers: [trunk] + gripper_0: + name: MultiFingerGripperController + camera: + name: JointController \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/freight.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/freight.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e4d5d6c7d508f4846bfd724b396e1d4608e8e21d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/freight.yaml @@ -0,0 +1,26 @@ +# Example Freight config +robot: + name: Freight + action_type: continuous + action_normalize: true + proprio_obs: + - dd_base_lin_vel + - dd_base_ang_vel + reset_joint_pos: null + base_name: null + scale: 1.0 + self_collision: false + include_sensor_names: null + exclude_sensor_names: null + sensor_config: + VisionSensor: + sensor_kwargs: + image_height: 128 + image_width: 128 + ScanSensor: + sensor_kwargs: + min_range: 0.05 + max_range: 10.0 + controller_config: + base: + name: DifferentialDriveController \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/husky.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/husky.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0de969c48377d9a560eb5db1d4aaf64e0006a4a8 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/husky.yaml @@ -0,0 +1,26 @@ +# Example Husky config +robot: + name: Husky + action_type: continuous + action_normalize: true + proprio_obs: + - joint_qpos + - joint_qvel + reset_joint_pos: null + base_name: null + scale: 1.0 + self_collision: false + include_sensor_names: null + exclude_sensor_names: null + sensor_config: + VisionSensor: + sensor_kwargs: + image_height: 128 + image_width: 128 + ScanSensor: + sensor_kwargs: + min_range: 0.05 + max_range: 10.0 + controller_config: + base: + name: JointController \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/locobot.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/locobot.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6a067926fd0dab20324fa142179f5f7a9e149766 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/locobot.yaml @@ -0,0 +1,26 @@ +# Example Locobot config +robot: + name: Locobot + action_type: continuous + action_normalize: true + proprio_obs: + - dd_base_lin_vel + - dd_base_ang_vel + reset_joint_pos: null + base_name: null + scale: 1.0 + self_collision: false + include_sensor_names: null + exclude_sensor_names: null + sensor_config: + VisionSensor: + sensor_kwargs: + image_height: 128 + image_width: 128 + ScanSensor: + sensor_kwargs: + min_range: 0.05 + max_range: 10.0 + controller_config: + base: + name: DifferentialDriveController \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/turtlebot.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/turtlebot.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ec3b3d2aba45ca58710d41c63c94ee9cb0a63772 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/robots/turtlebot.yaml @@ -0,0 +1,26 @@ +# Example Turtlebot config +robot: + name: Turtlebot + action_type: continuous + action_normalize: true + proprio_obs: + - dd_base_lin_vel + - dd_base_ang_vel + reset_joint_pos: null + base_name: null + scale: 1.0 + self_collision: false + include_sensor_names: null + exclude_sensor_names: null + sensor_config: + VisionSensor: + sensor_kwargs: + image_height: 128 + image_width: 128 + ScanSensor: + sensor_kwargs: + min_range: 0.05 + max_range: 10.0 + controller_config: + base: + name: DifferentialDriveController \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/sensors/scan.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/sensors/scan.yaml new file mode 100644 index 0000000000000000000000000000000000000000..318b761de5a360f761cda75503d74ee6e36854ed --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/sensors/scan.yaml @@ -0,0 +1,30 @@ +# Example ScanSensor sensor config +# See omnigibson/sensors/__init__/create_sensor and omnigibson/sensors/scan_sensor for docstring of arguments +# Arguments below are the arguments that should be specified by external user (other kwargs +# used in constructor are generated automatically at runtime) +robot: + sensor_config: + ScanSensor: + modalities: [scan, occupancy_grid] # if specified, this will override the values in robots_config["obs_modalities"] + enabled: true + noise_type: null + noise_kwargs: null + sensor_kwargs: + + # Basic LIDAR kwargs + min_range: 0.05 + max_range: 10.0 + horizontal_fov: 360.0 + vertical_fov: 1.0 + yaw_offset: 0.0 + horizontal_resolution: 1.0 + vertical_resolution: 1.0 + rotation_rate: 0.0 + draw_points: false + draw_lines: false + + # Occupancy Grid kwargs + occupancy_grid_resolution: 128 + occupancy_grid_range: 5.0 + occupancy_grid_inner_radius: 0.5 + occupancy_grid_local_link: null \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/sensors/vision.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/sensors/vision.yaml new file mode 100644 index 0000000000000000000000000000000000000000..44fdfc6c64311b61739f82e9d203d58f093fd2a4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/sensors/vision.yaml @@ -0,0 +1,14 @@ +# Example VisionSensor sensor config +# See omnigibson/sensors/__init__/create_sensor and omnigibson/sensors/vision_sensor for docstring of arguments +# Arguments below are the arguments that should be specified by external user (other kwargs +# used in constructor are generated automatically at runtime) +robot: + sensor_config: + VisionSensor: + modalities: [rgb, depth] # if specified, this will override the values in robots_config["obs_modalities"] + enabled: true + noise_type: null + noise_kwargs: null + sensor_kwargs: + image_height: 128 + image_width: 128 \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/tiago_primitives.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/tiago_primitives.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8d2b7b026811bf8bcb441f02aae700e867951f65 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/tiago_primitives.yaml @@ -0,0 +1,122 @@ +env: + action_frequency: 30 # (int): environment executes action at the action_frequency rate + physics_frequency: 120 # (int): physics frequency (1 / physics_timestep for physx) + device: null # (None or str): specifies the device to be used if running on the gpu with torch backend + automatic_reset: false # (bool): whether to automatic reset after an episode finishes + flatten_action_space: false # (bool): whether to flatten the action space as a sinle 1D-array + flatten_obs_space: false # (bool): whether the observation space should be flattened when generated + use_external_obs: false # (bool): Whether to use external observations or not + initial_pos_z_offset: 0.1 + external_sensors: null # (None or list): If specified, list of sensor configurations for external sensors to add. Should specify sensor "type" and any additional kwargs to instantiate the sensor. Each entry should be the kwargs passed to @create_sensor, in addition to position, orientation + +render: + viewer_width: 1280 + viewer_height: 720 + +scene: + type: InteractiveTraversableScene + scene_model: Rs_int + trav_map_resolution: 0.1 + default_erosion_radius: 0.0 + trav_map_with_objects: true + num_waypoints: 1 + waypoint_resolution: 0.2 + load_object_categories: null + not_load_object_categories: null + load_room_types: null + load_room_instances: null + load_task_relevant_only: false + seg_map_resolution: 1.0 + scene_source: OG + include_robots: false + +robots: + - type: Tiago + obs_modalities: [rgb] + include_sensor_names: null + exclude_sensor_names: null + scale: 1.0 + self_collisions: true + action_normalize: false + action_type: continuous + grasping_mode: sticky + reset_joint_pos: [ + 0.0000, + 0.0000, + -0.0000, + -0.0000, + -0.0000, + -0.0000, + 0.3500, + 0.9052, + 0.9052, + 0.0000, + -0.4281, + -0.4281, + -0.4500, + 2.2350, + 2.2350, + 1.6463, + 1.6463, + 0.7687, + 0.7687, + -0.7946, + -0.7946, + -1.0891, + -1.0891, + 0.0450, + 0.0450, + 0.0450, + 0.0450, + ] + sensor_config: + VisionSensor: + sensor_kwargs: + image_height: 128 + image_width: 128 + controller_config: + base: + name: HolonomicBaseJointController + motor_type: position + command_input_limits: null + use_impedances: false + trunk: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false + arm_left: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: False + arm_right: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false + gripper_left: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false + gripper_right: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false + camera: + name: JointController + motor_type: position + command_input_limits: null + use_delta_commands: false + use_impedances: false +objects: [] + +task: + type: DummyTask \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/turtlebot_nav.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/turtlebot_nav.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d1c55f103f2f11090bca029fef9ff065255ba788 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/configs/turtlebot_nav.yaml @@ -0,0 +1,75 @@ +env: + device: null # (None or str): specifies the device to be used if running on the gpu with torch backend + automatic_reset: false # (bool): whether to automatic reset after an episode finishes + flatten_action_space: false # (bool): whether to flatten the action space as a sinle 1D-array + flatten_obs_space: false # (bool): whether the observation space should be flattened when generated + use_external_obs: false # (bool): Whether to use external observations or not + initial_pos_z_offset: 0.1 + external_sensors: null # (None or list): If specified, list of sensor configurations for external sensors to add. Should specify sensor "type" and any additional kwargs to instantiate the sensor. Each entry should be the kwargs passed to @create_sensor, in addition to position, orientation + +render: + viewer_width: 1280 + viewer_height: 720 + +scene: + type: InteractiveTraversableScene + scene_model: Rs_int + trav_map_resolution: 0.1 + default_erosion_radius: 0.0 + trav_map_with_objects: true + num_waypoints: 1 + waypoint_resolution: 0.2 + load_object_categories: null + not_load_object_categories: null + load_room_types: null + load_room_instances: null + seg_map_resolution: 1.0 + scene_source: OG + include_robots: true + +robots: + - type: Turtlebot + obs_modalities: [scan, rgb, depth] + include_sensor_names: null + exclude_sensor_names: null + scale: 1.0 + self_collision: false + action_normalize: true + action_type: continuous + sensor_config: + VisionSensor: + sensor_kwargs: + image_height: 128 + image_width: 128 + ScanSensor: + sensor_kwargs: + min_range: 0.05 + max_range: 10.0 + controller_config: + base: + name: DifferentialDriveController + +objects: [] + +task: + type: PointNavigationTask + robot_idn: 0 + floor: 0 + initial_pos: null + initial_quat: null + goal_pos: null + goal_tolerance: 0.36 # turtlebot bodywidth + goal_in_polar: false + path_range: [1.0, 10.0] + visualize_goal: true + visualize_path: false + n_vis_waypoints: 25 + reward_type: geodesic + termination_config: + max_collisions: 500 + max_steps: 500 + fall_height: 0.03 + reward_config: + r_potential: 1.0 + r_collision: 0.1 + r_pointgoal: 10.0 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..938643e90832e94bd7d71582087fb2bff78a9702 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/__init__.py @@ -0,0 +1,58 @@ +from typing import Any +from omnigibson.controllers.controller_view import ControllerView +from omnigibson.controllers.controller_base import ( + REGISTERED_CONTROLLERS, + REGISTERED_LOCOMOTION_CONTROLLERS, + REGISTERED_MANIPULATION_CONTROLLERS, + ControlType, + GripperController, + IsGraspingState, + LocomotionController, + ManipulationController, +) +from omnigibson.controllers.dd_controller import DifferentialDriveController +from omnigibson.controllers.holonomic_base_joint_controller import HolonomicBaseJointController +from omnigibson.controllers.ik_controller import InverseKinematicsController +from omnigibson.controllers.joint_controller import JointController +from omnigibson.controllers.multi_finger_gripper_controller import MultiFingerGripperController +from omnigibson.controllers.null_joint_controller import NullJointController +from omnigibson.controllers.osc_controller import OperationalSpaceController +from omnigibson.utils.python_utils import assert_valid_key + + +def create_controller(name, **kwargs: Any): + """ + Creates a controller of type @name with corresponding necessary keyword arguments @kwargs + + Args: + name (str): type of controller to use (e.g. JointController, InverseKinematicsController, etc.) + **kwargs: Any relevant keyword arguments to pass to the controller + + Returns: + Controller: created controller + """ + assert_valid_key(key=name, valid_keys=REGISTERED_CONTROLLERS, name="controller") + controller_cls = REGISTERED_CONTROLLERS[name] + + return controller_cls(**kwargs) + + +__all__ = [ + "ControllerView", + "ControlType", + "create_controller", + "DifferentialDriveController", + "GripperController", + "HolonomicBaseJointController", + "InverseKinematicsController", + "IsGraspingState", + "JointController", + "LocomotionController", + "ManipulationController", + "MultiFingerGripperController", + "NullJointController", + "OperationalSpaceController", + "REGISTERED_CONTROLLERS", + "REGISTERED_LOCOMOTION_CONTROLLERS", + "REGISTERED_MANIPULATION_CONTROLLERS", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/controller_base.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/controller_base.py new file mode 100644 index 0000000000000000000000000000000000000000..9a084927f3af047055ffa4e9413c9fae586d7f9e --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/controller_base.py @@ -0,0 +1,860 @@ +import math +from collections.abc import Iterable +from enum import IntEnum + +import torch as th + +from omnigibson.macros import create_module_macros +from omnigibson.utils.backend_utils import _compute_backend as cb +from omnigibson.utils.python_utils import Recreatable, Registerable, Serializable, assert_valid_key, classproperty +from omnigibson.utils.usd_utils import ControllableObjectViewAPI + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# Set default isaac kp / kd for controllers +m.DEFAULT_ISAAC_KP = 1e7 +m.DEFAULT_ISAAC_KD = 1e5 + +# Global dicts that will contain mappings +REGISTERED_CONTROLLERS = dict() +REGISTERED_LOCOMOTION_CONTROLLERS = dict() +REGISTERED_MANIPULATION_CONTROLLERS = dict() +REGISTERED_GRIPPER_CONTROLLERS = dict() + + +def register_locomotion_controller(cls): + if cls.__name__ not in REGISTERED_LOCOMOTION_CONTROLLERS: + REGISTERED_LOCOMOTION_CONTROLLERS[cls.__name__] = cls + + +def register_manipulation_controller(cls): + if cls.__name__ not in REGISTERED_MANIPULATION_CONTROLLERS: + REGISTERED_MANIPULATION_CONTROLLERS[cls.__name__] = cls + + +def register_gripper_controller(cls): + if cls.__name__ not in REGISTERED_GRIPPER_CONTROLLERS: + REGISTERED_GRIPPER_CONTROLLERS[cls.__name__] = cls + + +class IsGraspingState(IntEnum): + TRUE = 1 + UNKNOWN = 0 + FALSE = -1 + + +# Define macros +class ControlType: + NONE = -1 + POSITION = 0 + VELOCITY = 1 + EFFORT = 2 + _MAPPING = { + "none": NONE, + "position": POSITION, + "velocity": VELOCITY, + "effort": EFFORT, + } + VALID_TYPES = set(_MAPPING.values()) + VALID_TYPES_STR = set(_MAPPING.keys()) + + @classmethod + def get_type(cls, type_str): + """ + Args: + type_str (str): One of "position", "velocity", or "effort" (any case), and maps it + to the corresponding type + + Returns: + ControlType: control type corresponding to the associated string + """ + assert_valid_key(key=type_str.lower(), valid_keys=cls._MAPPING, name="control type") + return cls._MAPPING[type_str.lower()] + + +class BaseController(Serializable, Registerable, Recreatable): + """ + An abstract class with interface for mapping specific types of commands to deployable control signals. + + Each instance represents a group of controllers that share the same + (robot kinematic tree pattern, body_part, controller_config) key. Members are added via + add_member() and assigned a controller_idx. All members are stepped together in a single + batched call, with per-member state stored in indexed compute-backend arrays (``cb.arr_type``). + + External command vectors may be plain Python iterables or torch tensors; they are converted + inside :meth:`update_goal`. Subclasses' :meth:`_update_goal` and :meth:`compute_no_op_goal` + must return ``dict`` values as **compute-backend float arrays** (``cb.arr_type``), which are + copied into the group's batched goal buffers. Per-member ``_goal_set`` is a compute-backend **bool** + vector (``cb.bool_zeros`` / ``cb.bool_array``). Internal goals, controls, and + :meth:`compute_control` I/O use ``cb``. Serialized / :meth:`_dump_state` goal payloads use + ``cb.to_torch``; :meth:`_load_state` accepts torch tensors and ``cb.from_torch``. + """ + + def __init__( + self, + control_freq, + control_limits, + dof_idx, + command_input_limits="default", + command_output_limits="default", + isaac_kp=None, + isaac_kd=None, + ): + """ + Args: + control_freq (int): controller loop frequency + control_limits (Dict[str, Tuple[Array[float], Array[float]]]): The min/max limits to the outputted + control signal. Should specify per-dof type limits, i.e.: + + "position": [[min], [max]] + "velocity": [[min], [max]] + "effort": [[min], [max]] + "has_limit": [...bool...] + + Values outside of this range will be clipped, if the corresponding joint index in has_limit is True. + dof_idx (Array[int]): specific dof indices controlled by this robot. Used for inferring + controller-relevant values during control computations + command_input_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max acceptable inputted command. Values outside this range will be clipped. + If None, no clipping will be used. If "default", range will be set to (-1, 1) + command_output_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max scaled command. If both this value and @command_input_limits is not None, + then all inputted command values will be scaled from the input range to the output range. + If either is None, no scaling will be used. If "default", then this range will automatically be set + to the @control_limits entry corresponding to self.control_type + isaac_kp (None or float or Array[float]): If specified, stiffness gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers. + Should only be nonzero if self.control_type is position + isaac_kd (None or float or Array[float]): If specified, damping gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers + Should only be nonzero if self.control_type is position or velocity + """ + # Store arguments + self._control_freq = control_freq + self._control_limits = {} + for motor_type in {"position", "velocity", "effort"}: + if motor_type not in control_limits: + continue + + self._control_limits[ControlType.get_type(motor_type)] = [ + cb.from_torch(control_limits[motor_type][0]), + cb.from_torch(control_limits[motor_type][1]), + ] + assert "has_limit" in control_limits, "Expected has_limit specified in control_limits, but does not exist." + self._dof_has_limits = cb.array(control_limits["has_limit"]) + self._dof_idx = cb.int_array(dof_idx) + + # Generate goal information + self._goal_shapes = self._get_goal_shapes() + self._goal_dim = int(sum(cb.prod(cb.array(shape)) for shape in self._goal_shapes.values())) + + # Multi-controller batching state + # List of articulation root paths for each group member + self._articulation_root_paths = [] + # Batched goals: key -> (N, *shape) compute-backend array + self._goals = {} + # Per-member flag: True if goal set this step (compute-backend bool vector) + self._goal_set = cb.bool_zeros(0) + # Per-member control enabled mask (1 enabled, 0 disabled) + self._control_enabled = cb.int_array([]) + # Per-member last deployed control (N, control_dim) + self._controls = cb.zeros((0, self.control_dim)) + # Per-member tombstone mask: 0 = active, 1 = unregistered + self._unregistered_controllers = cb.int_array([]) + + # Cached control limits for this controller's dof_idx — used by clip_control every step + self._clip_lo = cb.array(self._control_limits[self.control_type][0][self.dof_idx]) + self._clip_hi = cb.array(self._control_limits[self.control_type][1][self.dof_idx]) + + # Initialize command scaling variables + self._command_scale_factor = None + self._command_output_transform = None + self._command_input_transform = None + + # Standardize command input / output limits to be (min_array, max_array) + command_input_limits = ( + self._generate_default_command_input_limits() + if type(command_input_limits) is str and command_input_limits == "default" + else command_input_limits + ) + command_output_limits = ( + self._generate_default_command_output_limits() + if type(command_output_limits) is str and command_output_limits == "default" + else command_output_limits + ) + self._command_input_limits = ( + None + if command_input_limits is None + else ( + self.nums2array(command_input_limits[0], self.command_dim), + self.nums2array(command_input_limits[1], self.command_dim), + ) + ) + self._command_output_limits = ( + None + if command_output_limits is None + else ( + self.nums2array(command_output_limits[0], self.command_dim), + self.nums2array(command_output_limits[1], self.command_dim), + ) + ) + + # Set gains + if self.control_type == ControlType.POSITION: + # Set default kp / kd values if not specified + isaac_kp = m.DEFAULT_ISAAC_KP if isaac_kp is None else isaac_kp + isaac_kd = m.DEFAULT_ISAAC_KD if isaac_kd is None else isaac_kd + elif self.control_type == ControlType.VELOCITY: + # No kp should be specified, but kd should be + assert ( + isaac_kp is None + ), f"Control type for controller {self.__class__.__name__} is VELOCITY, so no isaac_kp should be set!" + isaac_kd = m.DEFAULT_ISAAC_KP if isaac_kd is None else isaac_kd + elif self.control_type == ControlType.EFFORT: + # Neither kp nor kd should be specified + assert ( + isaac_kp is None + ), f"Control type for controller {self.__class__.__name__} is EFFORT, so no isaac_kp should be set!" + assert ( + isaac_kd is None + ), f"Control type for controller {self.__class__.__name__} is EFFORT, so no isaac_kd should be set!" + else: + raise ValueError( + f"Expected control type to be one of: [POSITION, VELOCITY, EFFORT], but got: {self.control_type}" + ) + + self._isaac_kp = None if isaac_kp is None else self.nums2array(isaac_kp, self.control_dim) + self._isaac_kd = None if isaac_kd is None else self.nums2array(isaac_kd, self.control_dim) + + def add_member(self, articulation_root_path, control_enabled=True): + """ + Register a controller as a member of this controller group. + + Reuses the first tombstoned (unregistered) slot if one exists, otherwise appends a new slot. + + Args: + articulation_root_path (str): articulation root prim path of the new group member + + Returns: + int: controller_idx — index into this group's member arrays for the added controller, + used to access goal, control, and articulation_root_path + """ + # Reuse the first tombstoned slot if available + tombstone_indices = cb.indices_where(self._unregistered_controllers == 1) + if len(tombstone_indices) > 0: + controller_idx = int(cb.to_torch(tombstone_indices[0]).item()) + # Reset the reused slot in-place + self._articulation_root_paths[controller_idx] = articulation_root_path + self._goal_set[controller_idx] = False + self._control_enabled[controller_idx] = 1 if control_enabled else 0 + self._unregistered_controllers[controller_idx] = 0 + for key, shape in self._goal_shapes.items(): + self._goals[key][controller_idx] = cb.zeros(shape) + else: + # No tombstone available — append a new slot + controller_idx = len(self._articulation_root_paths) + self._articulation_root_paths.append(articulation_root_path) + self._goal_set = cb.cat([self._goal_set, cb.bool_zeros(1)], dim=0) + self._control_enabled = cb.cat([self._control_enabled, cb.int_array([1 if control_enabled else 0])], dim=0) + self._controls = cb.cat([self._controls, cb.zeros((1, self.control_dim))], dim=0) + self._unregistered_controllers = cb.cat([self._unregistered_controllers, cb.int_array([0])], dim=0) + for key, shape in self._goal_shapes.items(): + new_row = cb.zeros((1, *shape)) + if key in self._goals: + self._goals[key] = cb.cat([self._goals[key], new_row], dim=0) + else: + self._goals[key] = new_row + + return controller_idx + + @property + def n_members(self): + """ + Returns: + int: Number of controllers registered in this controller group + """ + return len(self._articulation_root_paths) + + def _generate_default_command_input_limits(self): + """ + Generates default command input limits based on the control limits + + Returns: + 2-tuple: + - int or array: min command input limits + - int or array: max command input limits + """ + return (-1.0, 1.0) + + def _generate_default_command_output_limits(self): + """ + Generates default command output limits based on the control limits + + Returns: + 2-tuple: + - int or array: min command output limits + - int or array: max command output limits + """ + return ( + self._control_limits[self.control_type][0][self.dof_idx], + self._control_limits[self.control_type][1][self.dof_idx], + ) + + def _preprocess_command(self, command): + """ + Clips + scales inputted @command according to self.command_input_limits and self.command_output_limits. + If self.command_input_limits is None, then no clipping will occur. If either self.command_input_limits + or self.command_output_limits is None, then no scaling will occur. + + Args: + command (Array[float] or float): Inputted command vector + + Returns: + Array[float]: Processed command vector + """ + command = cb.array([command]) if type(command) in {int, float} else command + # We only clip and / or scale if self.command_input_limits exists + if self._command_input_limits is not None: + # Clip + command = command.clip(*self._command_input_limits) + if self._command_output_limits is not None: + # If we haven't calculated how to scale the command, do that now (once) + if self._command_scale_factor is None: + self._command_scale_factor = abs( + self._command_output_limits[1] - self._command_output_limits[0] + ) / abs(self._command_input_limits[1] - self._command_input_limits[0]) + self._command_output_transform = ( + self._command_output_limits[1] + self._command_output_limits[0] + ) / 2.0 + self._command_input_transform = ( + self._command_input_limits[1] + self._command_input_limits[0] + ) / 2.0 + # Scale command + command = ( + command - self._command_input_transform + ) * self._command_scale_factor + self._command_output_transform + + # Return processed command + return command + + def _reverse_preprocess_command(self, processed_command): + """ + Reverses the scaling operation performed by _preprocess_command. + Note: This method does not reverse the clipping operation as it's not reversible. + + Args: + processed_command (cb.arr_type): Processed command vector + + Returns: + cb.arr_type: Original command vector (before scaling, clipping not reversed) + """ + # We only reverse the scaling if both input and output limits exist + if self._command_input_limits is not None and self._command_output_limits is not None: + # If we haven't calculated how to scale the command, do that now (once) + if self._command_scale_factor is None: + self._command_scale_factor = abs(self._command_output_limits[1] - self._command_output_limits[0]) / abs( + self._command_input_limits[1] - self._command_input_limits[0] + ) + self._command_output_transform = (self._command_output_limits[1] + self._command_output_limits[0]) / 2.0 + self._command_input_transform = (self._command_input_limits[1] + self._command_input_limits[0]) / 2.0 + + original_command = ( + processed_command - self._command_output_transform + ) / self._command_scale_factor + self._command_input_transform + else: + original_command = processed_command + + return original_command + + def update_goal(self, controller_idx, command): + """ + Updates the goal for controller at @controller_idx with the given @command. + + Args: + controller_idx (int): index of the controller in this controller group + command (Array[float]): inputted command to preprocess and extract relevant goal(s) + """ + # Sanity check the command + assert ( + len(command) == self.command_dim + ), f"Commands must be dimension {self.command_dim}, got dim {len(command)} instead." + + preprocessed = self._preprocess_command(command) + goal_dict = self._update_goal(controller_idx, preprocessed) + for k, v in goal_dict.items(): + self._goals[k][controller_idx] = cb.copy(v) + + self._goal_set[controller_idx] = True + + def _update_goal(self, controller_idx, command): + """ + Updates the goal for the controller at @controller_idx. + + Args: + controller_idx (int): index of the controller in this controller group + command (Array[float]): preprocessed command + + Returns: + dict: Keyword-mapped compute-backend goal arrays for controller at controller_idx + """ + raise NotImplementedError + + def compute_control(self, goals): + """ + Converts batched @goals into deployable (non-clipped!) control signals for all member controllers. + + Args: + goals (Dict[str, cb.arr_type]): batched goals, each value has shape (N, *shape) + + Returns: + cb.arr_type: (N, control_dim) control signals + """ + raise NotImplementedError + + @property + def view_row_indices(self): + return ControllableObjectViewAPI.get_member_view_indices(self.routing_path, self._articulation_root_paths) + + def clip_control(self, control): + """ + Clips the inputted @control signal based on @control_limits. + + Args: + control (cb.arr_type): (N, control_dim) control signal to clip + + Returns: + cb.arr_type: Clipped (N, control_dim) control signal + """ + clipped_control = control.clip(self._clip_lo, self._clip_hi) + # Undo the clipping of unlimited position joints + if self.control_type == ControlType.POSITION: + no_limit_mask = ~(self._dof_has_limits[self.dof_idx] > 0) + clipped_control[:, no_limit_mask] = control[:, no_limit_mask] + return clipped_control + + def step(self): + """ + Take a batched controller step across all member controller. + + For any controller that has not received a goal yet, a no-op goal is computed. + The control is then computed for all controllers, clipped, written to Isaac, and the + goal_set flags are reset. + """ + N = self.n_members + # active_mask: True for members that are enabled and registered + active_mask = (self._control_enabled != 0) & (self._unregistered_controllers == 0) + + # If no active members, early return + if not bool(cb.to_torch(active_mask).any().item()): + return + + # Fill in no-op goals for any active controllers that haven't received a goal. + for i in cb.indices_where(active_mask).tolist(): + if not cb.item_bool(self._goal_set[i]): + no_op = self.compute_no_op_goal(i) + for k, v in no_op.items(): + self._goals[k][i] = cb.copy(v) + self._goal_set[i] = True + + # Compute batched control: (N, control_dim) + control_output = self.compute_control(self._goals) + assert control_output.shape == ( + N, + self.control_dim, + ), f"compute_control must return shape ({N}, {self.control_dim}), got {control_output.shape}" + + control_output = self.clip_control(control_output) + self._controls[active_mask] = control_output[active_mask] + + # Write batched control signals to Isaac (view layer converts to sim torch tensors on flush). + all_view_rows = cb.int_array(self.view_row_indices) + enabled_rows = all_view_rows[active_mask] + enabled_controls = control_output[active_mask] # (N_en, control_dim) + routing_path = self.routing_path + + if self.control_type == ControlType.POSITION: + ControllableObjectViewAPI.set_all_joint_position_targets( + routing_path, enabled_rows, enabled_controls, self.dof_idx + ) + ControllableObjectViewAPI.set_all_joint_velocity_targets( + routing_path, enabled_rows, enabled_controls * 0, self.dof_idx + ) + elif self.control_type == ControlType.VELOCITY: + ControllableObjectViewAPI.set_all_joint_velocity_targets( + routing_path, enabled_rows, enabled_controls, self.dof_idx + ) + elif self.control_type == ControlType.EFFORT: + ControllableObjectViewAPI.set_all_joint_efforts(routing_path, enabled_rows, enabled_controls, self.dof_idx) + + def reset(self, controller_idx): + """ + Resets the goal state for the controller at @controller_idx. Can be extended by subclass + + Args: + controller_idx (int): index of the controller in this controller group + """ + if self._unregistered_controllers[controller_idx] == 1: + return + self._goal_set[controller_idx] = False + self._controls[controller_idx] = cb.zeros(self.control_dim) + for k in self._goals: + self._goals[k][controller_idx] = cb.zeros(self._goal_shapes[k]) + + def unregister_member(self, controller_idx): + """Mark member at controller_idx as a tombstone (can be reused by new member).""" + self._unregistered_controllers[controller_idx] = 1 + + def has_no_active_members(self): + """Return True if all members have been unregistered.""" + return cb.item_bool(cb.all(self._unregistered_controllers == 1)) + + def set_control_enabled(self, controller_idx, enabled): + self._control_enabled[controller_idx] = 1 if enabled else 0 + + def compute_no_op_goal(self, controller_idx): + """ + Compute no-op goal for the controller at @controller_idx. + + Args: + controller_idx (int): index of the controller in this controller group + + Returns: + dict: Maps relevant goal keys to compute-backend arrays for that controller + """ + raise NotImplementedError + + def compute_no_op_action(self, controller_idx): + """ + Compute a no-op action that updates the goal to match the current position + Disclaimer: this no-op might cause drift under external load (e.g. when the controller cannot reach the goal position) + + Args: + controller_idx (int): index of the controller in this group + + Returns: + cb.arr_type: no-op action command + """ + if not cb.item_bool(self._goal_set[controller_idx]): + no_op_goal = self.compute_no_op_goal(controller_idx) + for k, v in no_op_goal.items(): + self._goals[k][controller_idx] = cb.copy(v) + command = self._compute_no_op_command(controller_idx) + return self._reverse_preprocess_command(cb.as_float32(command)) + + def _compute_no_op_command(self, controller_idx): + """ + Compute no-op command for the controller at @controller_idx. + + Args: + controller_idx (int): index of the controller in this group + + Returns: + Array: no-op command + """ + raise NotImplementedError + + def _dump_state(self, controller_idx: int) -> dict: + """Dump state for one controller member (goal tensors as torch for serialization).""" + goals = {k: cb.to_torch(cb.copy(v[controller_idx])) for k, v in self._goals.items()} + return { + "goal_set": cb.item_bool(self._goal_set[controller_idx]), + "goals": goals, + } + + def dump_state(self, controller_idx: int, serialized: bool = False): + """ + Dumps the state for a single controller member. + + Args: + controller_idx (int): member index in this controller group + serialized (bool): whether to return flattened serialized state + + Returns: + dict or th.Tensor: member state for this controller_idx + """ + state = self._dump_state(controller_idx=controller_idx) + return self.serialize(state=state, controller_idx=controller_idx) if serialized else state + + def _load_state(self, controller_idx: int, state: dict): + """Load state for one controller member (accepts torch goal tensors from dump / disk).""" + self._goal_set[controller_idx] = state["goal_set"] + self._controls[controller_idx] = cb.zeros(self.control_dim) + self._unregistered_controllers[controller_idx] = 0 # we won't load a unregistered controller + for name, val in state["goals"].items(): + if name in self._goals: + self._goals[name][controller_idx] = cb.from_torch(val) + + def load_state(self, controller_idx: int, state, serialized: bool = False): + """ + Loads state for a single controller member. + + Args: + controller_idx (int): member index in this controller group + state (dict or th.Tensor): member state payload + serialized (bool): whether @state is serialized + """ + if serialized: + orig_state_len = len(state) + state, deserialized_items = self.deserialize(state=state, controller_idx=controller_idx) + assert deserialized_items == orig_state_len, ( + f"Invalid state deserialization occurred! Expected {orig_state_len} total " + f"values to be deserialized, only {deserialized_items} were." + ) + self._load_state(controller_idx=controller_idx, state=state) + + def serialize(self, state, controller_idx: int): + goal_set_tensor = th.tensor([float(state["goal_set"])], dtype=th.float32) + goals = state["goals"] + goal_flat = th.cat([v.flatten() for v in goals.values()]) if goals else th.zeros(self.goal_dim) + return th.cat([goal_set_tensor, goal_flat]) + + def deserialize(self, state, controller_idx: int): + goal_set = bool(state[0].item()) + idx = 1 + goals = {} + for key, shape in self._goal_shapes.items(): + length = math.prod(shape) + goals[key] = state[idx : idx + length].reshape(*shape) + idx += length + return dict(goal_set=goal_set, goals=goals), idx + + def _get_goal_shapes(self): + """ + Returns: + dict: Maps keyword in @self.goal to its corresponding numerical shape. This should be static + and analytically computed prior to any controller steps being taken + """ + raise NotImplementedError + + @staticmethod + def nums2array(nums, dim): + """ + Convert input @nums into numpy array of length @dim. If @nums is a single number, broadcasts it to the + corresponding dimension size @dim before converting into a numpy array + + Args: + nums (numeric or Iterable): Either single value or array of numbers + dim (int): Size of array to broadcast input to + + Returns: + cb.Array: Array filled with values specified in @nums + """ + # First run sanity check to make sure no strings are being inputted + if isinstance(nums, str): + raise TypeError("Error: Only numeric inputs are supported for this function, nums2array!") + + # Check if input is an Iterable, if so, convert via cb.array; else broadcast a scalar with cb.ones + return ( + nums + if isinstance(nums, cb.arr_type) + else cb.array(nums) + if isinstance(nums, Iterable) + else cb.ones(dim) * nums + ) + + @property + def state_size(self): + # goal_set + goal vector for one controller_idx + return 1 + self.goal_dim + + def get_goal(self, controller_idx): + """ + Returns the current goal for the controller at @controller_idx. + + Args: + controller_idx (int): index of the controller in this group + + Returns: + dict: Maps goal keys to per-controller compute-backend arrays of shape (*shape). + """ + return {k: v[controller_idx] for k, v in self._goals.items()} + + @property + def goal_dim(self): + """ + Returns: + int: Expected size of flattened goals for a single group member + """ + return self._goal_dim + + def get_control(self, controller_idx): + """ + Returns the last deployed control signal for the controller at @controller_idx. + + Args: + controller_idx (int): index of the controller in this group + + Returns: + cb.arr_type: last control vector of shape (control_dim,). + """ + return self._controls[controller_idx] + + @property + def control_freq(self): + """ + Returns: + float: Control frequency (Hz) of this controller + """ + return self._control_freq + + @property + def control_dim(self): + """ + Returns: + int: Expected size of outputted controls + """ + return len(self.dof_idx) + + @property + def control_type(self): + """ + Returns: + ControlType: Type of control returned by this controller + """ + raise NotImplementedError + + @property + def isaac_kp(self): + """ + Returns: + None or Array[float]: Stiffness gains that should be applied to the underlying Isaac joint motors. + None if not specified. + """ + return self._isaac_kp + + @property + def isaac_kd(self): + """ + Returns: + None or Array[float]: Stiffness gains that should be applied to the underlying Isaac joint motors. + None if not specified. + """ + return self._isaac_kd + + @property + def command_input_limits(self): + """ + Returns: + None or 2-tuple: If specified, returns (min, max) command input limits for this controller, where + @min and @max are numpy float arrays of length self.command_dim. Otherwise, returns None + """ + return self._command_input_limits + + @property + def command_output_limits(self): + """ + Returns: + None or 2-tuple: If specified, returns (min, max) command output limits for this controller, where + @min and @max are numpy float arrays of length self.command_dim. Otherwise, returns None + """ + return self._command_output_limits + + @property + def command_dim(self): + """ + Returns: + int: Expected size of inputted commands + """ + raise NotImplementedError + + @property + def routing_path(self): + """ + Returns: + str: Articulation root path of the first member, used as a routing key for + ControllableObjectViewAPI pattern lookups. All members in a group share the + same view pattern, so any member's path works; index 0 is canonical. + """ + return self._articulation_root_paths[0] + + @property + def dof_idx(self): + """ + Returns: + Array[int]: DOF indices corresponding to the specific DOFs being controlled by this controller group + """ + return self._dof_idx + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("BaseController") + return classes + + @classproperty + def _cls_registry(cls): + # Global registry + global REGISTERED_CONTROLLERS + return REGISTERED_CONTROLLERS + + +class LocomotionController(BaseController): + """ + Controller to control locomotion. All implemented controllers that encompass locomotion capabilities should extend + from this class. + """ + + def __init_subclass__(cls, **kwargs): + # Register as part of locomotion controllers + super().__init_subclass__(**kwargs) + register_locomotion_controller(cls) + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("LocomotionController") + return classes + + +class ManipulationController(BaseController): + """ + Controller to control manipulation. All implemented controllers that encompass manipulation capabilities + should extend from this class. + """ + + def __init_subclass__(cls, **kwargs): + # Register as part of manipulation controllers + super().__init_subclass__(**kwargs) + register_manipulation_controller(cls) + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("ManipulationController") + return classes + + +class GripperController(BaseController): + """ + Controller to control a gripper. All implemented controllers that encompass gripper capabilities + should extend from this class. + """ + + def __init_subclass__(cls, **kwargs): + # Register as part of gripper controllers + super().__init_subclass__(**kwargs) + register_gripper_controller(cls) + + def is_grasping(self, controller_idx): + """ + Checks whether the current state of this gripper being controlled is in a grasping state. + Should be implemented by subclass. + + Args: + controller_idx (int): index of the controller in this group. Used for MultiFingerGripperController. + + Returns: + IsGraspingState: Grasping state of gripper + """ + raise NotImplementedError() + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("GripperController") + return classes diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/controller_view.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/controller_view.py new file mode 100644 index 0000000000000000000000000000000000000000..f033b21283dd0155f2f89f66f0fb531a6a240ece --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/controller_view.py @@ -0,0 +1,323 @@ +import torch as th +from typing import Dict, Optional, Tuple +import hashlib + +from omnigibson.utils.backend_utils import _compute_backend as cb + + +class ControllerView: + """ + A registry that maps group keys to batched controller instances. + + Controllers with the same (robot kinematic tree pattern, body_part, controller_config) key are + grouped into a single controller instance. Each member is assigned a controller_idx that + indexes into the group's batched state. + + **Torch boundary:** Callers interact with this view using **torch tensors** (and plain Python + scalars / lists where controllers already accept them). Batched controllers internally use + compute-backend arrays (``cb``). The view translates **on the way in** (e.g. ``torch.Tensor`` + → ``cb`` for :meth:`update_goal`) and **on the way out** (e.g. ``cb`` → ``torch.Tensor`` for + :meth:`get_control`, :meth:`get_goal`, :meth:`get_dof_idx`, gains, and command limits) so that + **no ``cb`` array is returned from or required by** the public view API. If a compute-backend + array is passed in, it is normalized through torch and re-imported into ``cb`` before reaching + the controller—prefer passing ``torch.Tensor`` from new code. + + Usage: + # At controller load time: + group_key, controller_idx = ControllerView.register( + body_part, controller_cfg, + articulation_root_path, link_name + ) + + # At action time: + ControllerView.update_goal(group_key, controller_idx, command) + + # At sim step time (called once for all groups): + ControllerView.step_all() + """ + + # Maps group_key -> BaseController instance + _controller_groups: Dict[str, object] = {} + + @classmethod + def register( + cls, + body_part: str, + controller_cfg: dict, + articulation_root_path: str, + link_name: Optional[str] = None, + control_enabled: bool = True, + ) -> Tuple[str, int]: + """ + Register a controller into the appropriate group. + + If no group exists for the given key, one is created. A new member is then + added to that group's controller via add_member(). + + Args: + body_part (str): name of the body part being controlled (e.g., "arm_right", "base") + controller_cfg (dict): controller configuration dict (must include "name" key) + articulation_root_path (str): articulation root prim path of the new group member + link_name (None or str): if specified, the name of the EEF or trunk link (for IK/OSC controllers) + control_enabled (bool): if set to False, the controller is disabled. Default is true. + + Returns: + 2-tuple: + - str: group_key identifying the controller group + - int: controller_idx — the member's index within that group + """ + # Build a unique string key for a controller group. + group_key = cls._make_key(articulation_root_path, body_part, controller_cfg) + + if group_key not in cls._controller_groups: + from omnigibson.controllers import create_controller + + controller_name = controller_cfg.get("name") + if controller_name in { + "InverseKinematicsController", + "OperationalSpaceController", + }: + assert link_name is not None + cls._controller_groups[group_key] = create_controller(**controller_cfg, link_name=link_name) + else: + cls._controller_groups[group_key] = create_controller(**controller_cfg) + + controller = cls._controller_groups[group_key] + controller_idx = controller.add_member( + articulation_root_path, + control_enabled=control_enabled, + ) + + return group_key, controller_idx + + @classmethod + def step_all(cls): + """ + Run a batched controller step for all registered controller groups. + """ + for controller in cls._controller_groups.values(): + controller.step() + + @classmethod + def update_goal(cls, group_key: str, controller_idx: int, command): + """ + Update the goal for the controller at @controller_idx in the group identified by @group_key. + + Args: + group_key (str): key identifying the controller group + controller_idx (int): index of the controller within the group + command (torch.Tensor or array-like): action command for this controller (see class docstring) + """ + cmd = cb.from_torch(command) + cls._controller_groups[group_key].update_goal(controller_idx, cmd) + + @classmethod + def set_control_enabled(cls, group_key: str, controller_idx: int, enabled: bool): + cls._controller_groups[group_key].set_control_enabled(controller_idx, enabled) + + @classmethod + def compute_no_op_action(cls, group_key: str, controller_idx: int) -> th.Tensor: + """ + Compute the no-op action command for the controller at @controller_idx in group @group_key. + + Args: + group_key (str): key identifying the controller group + controller_idx (int): index of the controller within the group + + Returns: + torch.Tensor: no-op command for this controller + """ + out = cls._controller_groups[group_key].compute_no_op_action(controller_idx) + return cb.to_torch(out) + + @classmethod + def reverse_preprocess_command(cls, group_key: str, command) -> th.Tensor: + """ + Undo command scaling (same as :meth:`BaseController._reverse_preprocess_command`). + + Args: + command: torch tensor or array-like in *scaled* command space + + Returns: + torch.Tensor: command in normalized input space (for stacking into a flat action vector) + """ + controller = cls._controller_groups[group_key] + cmd = cb.from_torch(command) + return cb.to_torch(controller._reverse_preprocess_command(cmd)) + + @classmethod + def reset(cls, group_key: str, controller_idx: int): + """ + Reset the goal state for the controller at @controller_idx in the group @group_key. + + Args: + group_key (str): key identifying the controller group + controller_idx (int): index of the controller within the group + """ + cls._controller_groups[group_key].reset(controller_idx) + + @classmethod + def clear(cls): + """ + Remove all registered controller groups. Call this inside simulator._partial_clear(). + """ + cls._controller_groups.clear() + + @classmethod + def unregister_robot(cls, controllers: dict): + """ + Unregister one robot from controller groups without reindexing members. + + For each (group_key, controller_idx) in @controllers: + - Locate the shared controller group. + - Mark controller_idx as a tombstoned (unregistered) slot. + - Keep the group if any active members remain; delete it only when all members + are tombstoned. + + Controller logic must mask tombstoned slots during goal updates, batched + compute, and writeback. + + Tombstoned slots will be reused for new controller members. + + Args: + controllers (dict): The robot.controllers dict, + mapping controller_name -> (group_key, controller_idx) + + """ + for group_key, controller_idx in controllers.values(): + if group_key not in cls._controller_groups: + continue + controller = cls._controller_groups[group_key] + controller.unregister_member(controller_idx) + if controller.has_no_active_members(): + del cls._controller_groups[group_key] + + @classmethod + def get_command_dim(cls, group_key: str) -> int: + return cls._controller_groups[group_key].command_dim + + @classmethod + def get_control_dim(cls, group_key: str) -> int: + return cls._controller_groups[group_key].control_dim + + @classmethod + def get_dof_idx(cls, group_key: str) -> th.Tensor: + return cb.to_torch(cls._controller_groups[group_key].dof_idx) + + @classmethod + def get_control_type(cls, group_key: str): + return cls._controller_groups[group_key].control_type + + @classmethod + def get_mode(cls, group_key: str) -> str: + controller = cls._controller_groups[group_key] + assert hasattr(controller, "mode"), f"Controller {type(controller).__name__} does not have a 'mode' attribute" + return controller.mode + + @classmethod + def get_goal_dim(cls, group_key: str) -> int: + return cls._controller_groups[group_key].goal_dim + + @classmethod + def get_goal(cls, group_key: str, controller_idx: int) -> dict: + raw = cls._controller_groups[group_key].get_goal(controller_idx) + return {k: cb.to_torch(v) for k, v in raw.items()} + + @classmethod + def get_control(cls, group_key: str, controller_idx: int) -> th.Tensor: + return cb.to_torch(cls._controller_groups[group_key].get_control(controller_idx)) + + @classmethod + def get_use_delta_commands(cls, group_key: str) -> bool: + return cls._controller_groups[group_key].use_delta_commands + + @classmethod + def get_controller_type_str(cls, group_key: str) -> str: + """Python class name of the batched controller (e.g. ``JointController``), for UI / diagnostics.""" + return type(cls._controller_groups[group_key]).__name__ + + @classmethod + def is_controller_type(cls, group_key: str, controller_cls) -> bool: + return isinstance(cls._controller_groups[group_key], controller_cls) + + @classmethod + def get_isaac_kp(cls, group_key: str): + isaac_kp = cls._controller_groups[group_key].isaac_kp + if isaac_kp is None: + return None + return cb.to_torch(isaac_kp) + + @classmethod + def get_isaac_kd(cls, group_key: str): + isaac_kd = cls._controller_groups[group_key].isaac_kd + if isaac_kd is None: + return None + return cb.to_torch(isaac_kd) + + @classmethod + def get_command_input_limits(cls, group_key: str): + limits = cls._controller_groups[group_key].command_input_limits + if limits is None: + return None + lo, hi = limits + return (cb.to_torch(lo), cb.to_torch(hi)) + + @classmethod + def get_motor_type(cls, group_key: str) -> str: + controller = cls._controller_groups[group_key] + assert hasattr( + controller, "motor_type" + ), f"Controller {type(controller).__name__} does not have a 'motor_type' attribute" + return controller.motor_type + + @classmethod + def is_grasping(cls, group_key: str, controller_idx: int): + return cls._controller_groups[group_key].is_grasping(controller_idx) + + @classmethod + def dump_state(cls, group_key: str, controller_idx: int) -> dict: + controller = cls._controller_groups[group_key] + return controller.dump_state(controller_idx=controller_idx) + + @classmethod + def load_state(cls, group_key: str, controller_idx: int, state: dict): + controller = cls._controller_groups[group_key] + controller.load_state(controller_idx=controller_idx, state=state) + + @classmethod + def serialize(cls, group_key: str, controller_idx: int, state: dict) -> th.Tensor: + controller = cls._controller_groups[group_key] + return controller.serialize(state=state, controller_idx=controller_idx) + + @classmethod + def deserialize(cls, group_key: str, controller_idx: int, state: th.Tensor) -> Tuple[dict, int]: + controller = cls._controller_groups[group_key] + return controller.deserialize(state=state, controller_idx=controller_idx) + + @staticmethod + def _freeze_for_hash(value): + """ + Recursively convert nested structures into hashable representations. + """ + if isinstance(value, dict): + return tuple(sorted((k, ControllerView._freeze_for_hash(v)) for k, v in value.items())) + if isinstance(value, (list, tuple)): + return tuple(ControllerView._freeze_for_hash(v) for v in value) + if isinstance(value, set): + return tuple(sorted(ControllerView._freeze_for_hash(v) for v in value)) + # Fallback for custom / array-like objects + try: + hash(value) + return value + except TypeError: + return str(value) + + @classmethod + def _make_key(cls, articulation_root_path: str, body_part: str, controller_cfg: dict) -> str: + from omnigibson.utils.usd_utils import get_robot_kinematic_tree_pattern + + pattern = get_robot_kinematic_tree_pattern(articulation_root_path) + frozen_cfg = cls._freeze_for_hash(controller_cfg) + cfg_bytes = repr(frozen_cfg).encode("utf-8") + cfg_hash = hashlib.sha256(cfg_bytes).hexdigest() + return f"{pattern}__{body_part}__{cfg_hash}" diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/dd_controller.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/dd_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..b74007a9a9027bcea062faa6ca3941a9cb581440 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/dd_controller.py @@ -0,0 +1,136 @@ +from omnigibson.controllers import ControlType, LocomotionController +from omnigibson.utils.backend_utils import _compute_backend as cb + + +class DifferentialDriveController(LocomotionController): + """ + Differential drive (DD) controller for controlling two independently controlled wheeled joints. + + Each controller step consists of the following: + 1. Clip + Scale inputted command according to @command_input_limits and @command_output_limits + 2. Convert desired (lin_vel, ang_vel) command into (left, right) wheel joint velocity control signals + 3. Clips the resulting command by the joint velocity limits + """ + + def __init__( + self, + wheel_radius, + wheel_axle_length, + control_freq, + control_limits, + dof_idx, + command_input_limits="default", + command_output_limits="default", + isaac_kp=None, + isaac_kd=None, + ): + """ + Args: + wheel_radius (float): radius of the wheels (both assumed to be same radius) + wheel_axle_length (float): perpendicular distance between the two wheels + control_freq (int): controller loop frequency + control_limits (Dict[str, Tuple[Array[float], Array[float]]]): The min/max limits to the outputted + control signal. Should specify per-dof type limits, i.e.: + + "position": [[min], [max]] + "velocity": [[min], [max]] + "effort": [[min], [max]] + "has_limit": [...bool...] + + Values outside of this range will be clipped, if the corresponding joint index in has_limit is True. + dof_idx (Array[int]): specific dof indices controlled by this controller. Used for inferring + controller-relevant values during control computations + command_input_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max acceptable inputted command. Values outside this range will be clipped. + If None, no clipping will be used. If "default", range will be set to (-1, 1) + command_output_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max scaled command. If both this value and @command_input_limits is not None, + then all inputted command values will be scaled from the input range to the output range. + If either is None, no scaling will be used. If "default", then this range will automatically be set + to the maximum linear and angular velocities calculated from @wheel_radius, @wheel_axle_length, and + @control_limits velocity limits entry + isaac_kp (None or float or Array[float]): If specified, stiffness gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers. + Should only be nonzero if self.control_type is position + isaac_kd (None or float or Array[float]): If specified, damping gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers + Should only be nonzero if self.control_type is position or velocity + """ + # Store internal variables + self._wheel_radius = wheel_radius + self._wheel_axle_halflength = wheel_axle_length / 2.0 + + # Precompute (2, 2) transform: vel_batch (N, 2) @ _wheel_vel_transform -> (N, 2) [left, right] wheel vels + # left = lin_vel / r - ang_vel * half / r + # right = lin_vel / r + ang_vel * half / r + inv_r = 1.0 / wheel_radius + half_inv_r = self._wheel_axle_halflength / wheel_radius + self._wheel_vel_transform = cb.array([[inv_r, inv_r], [-half_inv_r, half_inv_r]]) # (2, 2) + + # If we're using default command output limits, map this to maximum linear / angular velocities + if type(command_output_limits) is str and command_output_limits == "default": + min_vels = control_limits["velocity"][0][dof_idx] + assert ( + min_vels[0] == min_vels[1] + ), "Differential drive requires both wheel joints to have same min velocities!" + max_vels = control_limits["velocity"][1][dof_idx] + assert ( + max_vels[0] == max_vels[1] + ), "Differential drive requires both wheel joints to have same max velocities!" + assert abs(min_vels[0]) == abs( + max_vels[0] + ), "Differential drive requires both wheel joints to have same min and max absolute velocities!" + max_lin_vel = max_vels[0] * wheel_radius + max_ang_vel = max_lin_vel * 2.0 / wheel_axle_length + command_output_limits = ((-max_lin_vel, -max_ang_vel), (max_lin_vel, max_ang_vel)) + + # Run super init + super().__init__( + control_freq=control_freq, + control_limits=control_limits, + dof_idx=dof_idx, + command_input_limits=command_input_limits, + command_output_limits=command_output_limits, + isaac_kp=isaac_kp, + isaac_kd=isaac_kd, + ) + + def _update_goal(self, controller_idx, command): + # Directly store command as the velocity goal (compute-backend array) + return dict(vel=command) + + def compute_control(self, goals): + """ + Converts the (already preprocessed) batched goals into deployable (non-clipped!) joint control signals + for all N group members. + + Args: + goals (Dict[str, Tensor]): batched goals with shape (N, *shape) per key. + Must include: + vel: (N, 2) desired (lin_vel, ang_vel) of the controlled bodies + + Returns: + Tensor: (N, 2) outputted (non-clipped!) velocity control signal to deploy to the [left, right] wheel joints + """ + # (N, 2) @ (2, 2) -> (N, 2) [left, right] wheel joint velocities + return goals["vel"] @ self._wheel_vel_transform + + def compute_no_op_goal(self, controller_idx): + # Zero (lin, ang) velocity as ``cb`` array + return dict(vel=cb.zeros(2)) + + def _compute_no_op_command(self, controller_idx): + return cb.zeros(2) + + def _get_goal_shapes(self): + # Add (2, )-array representing linear, angular velocity + return dict(vel=(2,)) + + @property + def control_type(self): + return ControlType.VELOCITY + + @property + def command_dim(self): + # [lin_vel, ang_vel] + return 2 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/holonomic_base_joint_controller.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/holonomic_base_joint_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..67fdabfbcd7d7fe58319364cee2d504daf4356e3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/holonomic_base_joint_controller.py @@ -0,0 +1,169 @@ +from omnigibson.utils.backend_utils import _compute_backend as cb +from omnigibson.controllers.joint_controller import JointController +from omnigibson.utils.geometry_utils import wrap_angle +from omnigibson.utils.usd_utils import ControllableObjectViewAPI + + +class HolonomicBaseJointController(JointController): + """ + Controller class for holonomic base joint control. This is a very specific type of controller used to model control of a 3DOF + holonomic robot base -- i.e.: free motion along (x, y, rz). + + NOTE: Inputted commands are ALWAYS assumed to be in the form of absolute values (defined in the robot's local frame), not deltas! + NOTE: Also assumes commands are ALWAYS inputted in the form of [x, y, rz]! + + Each controller step consists of the following: + 1. Clip + Scale inputted command according to @command_input_limits and @command_output_limits + 2a. If using delta commands, then adds the command to the current joint state + 2b. Clips the resulting command by the motor limits + """ + + def __init__( + self, + control_freq, + motor_type, + control_limits, + dof_idx, + command_input_limits=None, + command_output_limits=None, + isaac_kp=None, + isaac_kd=None, + pos_kp=None, + pos_damping_ratio=None, + vel_kp=None, + use_impedances=False, + use_gravity_compensation=False, + use_cc_compensation=True, + ): + """ + Args: + control_freq (int): controller loop frequency + motor_type (str): type of motor being controlled, one of {position, velocity, effort} + control_limits (Dict[str, Tuple[Array[float], Array[float]]]): The min/max limits to the outputted + control signal. Should specify per-dof type limits, i.e.: + + "position": [[min], [max]] + "velocity": [[min], [max]] + "effort": [[min], [max]] + "has_limit": [...bool...] + + Values outside of this range will be clipped, if the corresponding joint index in has_limit is True. + dof_idx (Array[int]): specific dof indices controlled by this controller group. Used for inferring + controller-relevant values during control computations + command_input_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max acceptable inputted command. Values outside this range will be clipped. + If None, no clipping will be used. If "default", range will be set to (-1, 1) + command_output_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max scaled command. If both this value and @command_input_limits is not None, + then all inputted command values will be scaled from the input range to the output range. + If either is None, no scaling will be used. If "default", then this range will automatically be set + to the @control_limits entry corresponding to self.control_type + isaac_kp (None or float or Array[float]): If specified, stiffness gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers. + Should only be nonzero if self.control_type is position + isaac_kd (None or float or Array[float]): If specified, damping gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers + Should only be nonzero if self.control_type is position or velocity + pos_kp (None or float): If @motor_type is "position" and @use_impedances=True, this is the + proportional gain applied to the joint controller. If None, a default value will be used. + pos_damping_ratio (None or float): If @motor_type is "position" and @use_impedances=True, this is the + damping ratio applied to the joint controller. If None, a default value will be used. + vel_kp (None or float): If @motor_type is "velocity" and @use_impedances=True, this is the + proportional gain applied to the joint controller. If None, a default value will be used. + use_impedances (bool): If True, will use impedances via the mass matrix to modify the desired efforts + applied + use_gravity_compensation (bool): If True, will add gravity compensation to the computed efforts. This is + an experimental feature that only works on fixed base robots. We do not recommend enabling this. + use_cc_compensation (bool): If True, will add Coriolis / centrifugal compensation to the computed efforts. + """ + # Make sure we're controlling exactly 3 DOFs + assert len(dof_idx) == 3, f"Expected 3 DOFs for holonomic base control, got {len(dof_idx)}" + + # Run super init + super().__init__( + control_freq=control_freq, + motor_type=motor_type, + control_limits=control_limits, + dof_idx=dof_idx, + command_input_limits=command_input_limits, + command_output_limits=command_output_limits, + isaac_kp=isaac_kp, + isaac_kd=isaac_kd, + pos_kp=pos_kp, + pos_damping_ratio=pos_damping_ratio, + vel_kp=vel_kp, + use_impedances=use_impedances, + use_gravity_compensation=use_gravity_compensation, + use_cc_compensation=use_cc_compensation, + use_delta_commands=False, + compute_delta_in_quat_space=None, + ) + + def _update_goal(self, controller_idx, command): + """ + Updates the goal command by transforming it from the robot's local frame to its canonical frame. + """ + prim_path = self._articulation_root_paths[controller_idx] + + root_pos, root_quat = ControllableObjectViewAPI.get_position_orientation(prim_path) + canonical_pos, canonical_quat = ControllableObjectViewAPI.get_root_position_orientation(prim_path) + + base_pose = cb.T.pose2mat((root_pos, root_quat)) + canonical_pose = cb.T.pose2mat((canonical_pos, canonical_quat)) + canonical_to_base_pose = cb.T.pose_inv(canonical_pose) @ base_pose + + if self.motor_type == "position": + # Handle position control mode + command_in_base_frame = cb.as_float32(cb.eye(4)) + command_in_base_frame[:2, 3] = command[:2] # Set x,y translation + + # Transform command to canonical frame + command_in_canonical_frame = canonical_to_base_pose @ command_in_base_frame + + # Extract x,y translation from transformed command + position = command_in_canonical_frame[:2, 3] + + # Since our virtual joints are in the order of ["x", "y", "z", "rx", "ry", "rz"], + # the "base_footprint_rz_link" is aligned with @self.base_footprint_link in the z-axis + # We just need to directly apply the command as delta to the current joint position of "base_footprint_rz_joint" + # Note that the current joint position is guaranteed to be in the range of [-pi, pi] because + # @HolonomicBaseRobot.apply_action explicitly wraps the joint position to [-pi, pi] if it's out of range + rz_joint_pos = ControllableObjectViewAPI.get_joint_positions(prim_path)[self.dof_idx][2:3] + + # Wrap the delta joint position to [-pi, pi]. In other words, we don't expect the commanded delta joint position + # to have a magnitude greater than pi, because the robot can't reasonably rotate more than pi in a single step + delta_joint_pos = wrap_angle(command[2]) + + # Calculate the new joint position. This is guaranteed to be in the range of [-pi * 2, pi * 2], because both quantities + # are in the range of [-pi, pi]. This is important because revolute joints in Isaac Sim have a joint position (target) range of [-pi * 2, pi * 2] + new_joint_pos = rz_joint_pos + delta_joint_pos + + command = cb.cat([position, new_joint_pos]) + else: + # Handle velocity/effort control modes + # Note: Only rotate the commands, don't translate + command_in_base_frame = cb.as_float32(cb.eye(4)) + command_in_base_frame[:2, 3] = command[:2] # Set x,y linear velocity + + canonical_to_base_pose_rotation = cb.as_float32(cb.eye(4)) + canonical_to_base_pose_rotation[:3, :3] = canonical_to_base_pose[:3, :3] + + # Transform command to canonical frame + command_in_canonical_frame = canonical_to_base_pose_rotation @ command_in_base_frame + + # Extract x,y linear velocity from transformed command + linear_velocity = command_in_canonical_frame[:2, 3] + + angular_velocity = command[2:3] + + command = cb.cat([linear_velocity, angular_velocity]) + + return super()._update_goal(controller_idx=controller_idx, command=command) + + # For "position" control mode, this controller behaves similar to use_delta_commands=True, + # where the command [dx, dy, drz] means the robot should move by [dx, dy] and rotate by drz (in the base link frame) + # For "velocity" and "effort" control modes, this controller behaves similar to use_delta_commands=False, + # where the command [vx, vy, vrz] means the robot should move with linear velocity [vx, vy] and angular velocity vrz (in the base link frame) + # In all cases, no-op commands should be [0, 0, 0]. + def _compute_no_op_command(self, controller_idx): + return cb.zeros(self.command_dim) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/ik_controller.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/ik_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..7c533afb49be5919bf82e3ee51a04fa3d990a1d2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/ik_controller.py @@ -0,0 +1,546 @@ +import math +from collections.abc import Iterable + +import numpy as np +import torch as th + +import omnigibson.utils.transform_utils as TT +import omnigibson.utils.transform_utils_np as NT +from omnigibson.controllers import ManipulationController +from omnigibson.controllers.joint_controller import JointController +from omnigibson.utils.backend_utils import _compute_backend as cb +from omnigibson.utils.backend_utils import add_compute_function +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import ControllableObjectViewAPI + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Different modes +IK_MODE_COMMAND_DIMS = { + "absolute_pose": 6, # 6DOF (x,y,z,ax,ay,az) control of pose, whether both position and orientation is given in absolute coordinates + "pose_absolute_ori": 6, # 6DOF (dx,dy,dz,ax,ay,az) control over pose, where the orientation is given in absolute axis-angle coordinates + "pose_delta_ori": 6, # 6DOF (dx,dy,dz,dax,day,daz) control over pose + "position_fixed_ori": 3, # 3DOF (dx,dy,dz) control over position, with orientation commands being kept as fixed initial absolute orientation + "position_compliant_ori": 3, # 3DOF (dx,dy,dz) control over position, with orientation commands automatically being sent as 0s (so can drift over time) +} +IK_MODES = set(IK_MODE_COMMAND_DIMS.keys()) + + +class InverseKinematicsController(JointController, ManipulationController): + """ + Controller class to convert (delta) EEF commands into joint velocities using Inverse Kinematics (IK). + + Each controller step consists of the following: + 1. Clip + Scale inputted command according to @command_input_limits and @command_output_limits + 2. Run Inverse Kinematics to back out joint velocities for a desired task frame command + 3. Clips the resulting command by the motor (velocity) limits + """ + + def __init__( + self, + control_freq, + reset_joint_pos, + control_limits, + dof_idx, + command_input_limits="default", + command_output_limits=( + (-0.2, -0.2, -0.2, -0.5, -0.5, -0.5), + (0.2, 0.2, 0.2, 0.5, 0.5, 0.5), + ), + isaac_kp=None, + isaac_kd=None, + pos_kp=None, + pos_damping_ratio=None, + vel_kp=None, + use_impedances=False, + mode="pose_delta_ori", + smoothing_filter_size=None, + workspace_pose_limiter=None, + condition_on_current_position=True, + link_name=None, + ): + """ + Args: + control_freq (int): controller loop frequency + reset_joint_pos (Array[float]): reset joint positions, used as part of nullspace controller in IK. + Note that this should correspond to ALL the joints; the exact indices will be extracted via @dof_idx + control_limits (Dict[str, Tuple[Array[float], Array[float]]]): The min/max limits to the outputted + control signal. Should specify per-dof type limits, i.e.: + + "position": [[min], [max]] + "velocity": [[min], [max]] + "effort": [[min], [max]] + "has_limit": [...bool...] + + Values outside of this range will be clipped, if the corresponding joint index in has_limit is True. + dof_idx (Array[int]): specific dof indices controlled by this controller group. Used for inferring + controller-relevant values during control computations + command_input_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max acceptable inputted command. Values outside this range will be clipped. + If None, no clipping will be used. If "default", range will be set to (-1, 1) + command_output_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max scaled command. If both this value and @command_input_limits is not None, + then all inputted command values will be scaled from the input range to the output range. + If either is None, no scaling will be used. If "default", then this range will automatically be set + to the @control_limits entry corresponding to self.control_type + isaac_kp (None or float or Array[float]): If specified, stiffness gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers. + Should only be nonzero if self.control_type is position + isaac_kd (None or float or Array[float]): If specified, damping gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers + Should only be nonzero if self.control_type is position or velocity + pos_kp (None or float): If @motor_type is "position" and @use_impedances=True, this is the + proportional gain applied to the joint controller. If None, a default value will be used. + pos_damping_ratio (None or float): If @motor_type is "position" and @use_impedances=True, this is the + damping ratio applied to the joint controller. If None, a default value will be used. + vel_kp (None or float): If @motor_type is "velocity" and @use_impedances=True, this is the + proportional gain applied to the joint controller. If None, a default value will be used. + use_impedances (bool): If True, will use impedances via the mass matrix to modify the desired efforts + applied + mode (str): mode to use when computing IK. In all cases, position commands are 3DOF delta (dx,dy,dz) + cartesian values, relative to the robot base frame. Valid options are: + - "absolute_pose": 6DOF (dx,dy,dz,ax,ay,az) control over pose, + where both the position and the orientation is given in absolute axis-angle coordinates + - "pose_absolute_ori": 6DOF (dx,dy,dz,ax,ay,az) control over pose, + where the orientation is given in absolute axis-angle coordinates + - "pose_delta_ori": 6DOF (dx,dy,dz,dax,day,daz) control over pose + - "position_fixed_ori": 3DOF (dx,dy,dz) control over position, + with orientation commands being kept as fixed initial absolute orientation + - "position_compliant_ori": 3DOF (dx,dy,dz) control over position, + with orientation commands automatically being sent as 0s (so can drift over time) + smoothing_filter_size (None or int): if specified, sets the size of a moving average filter to apply + on all outputted IK joint positions. + workspace_pose_limiter (None or function): if specified, callback method that should clip absolute + target (x,y,z) cartesian position and absolute quaternion orientation (x,y,z,w) to a specific workspace + range (i.e.: this can be unique to each robot, and implemented by each embodiment). + Function signature should be: + + def limiter(target_pos: Array[float], target_quat: Array[float]) --> Tuple[Array[float], Array[float]] + + where target_pos is (x,y,z) cartesian position values, target_quat is (x,y,z,w) quarternion orientation + values, and the returned tuple is the processed (pos, quat) command. + condition_on_current_position (bool): if True, will use the current joint position as the initial guess for the IK algorithm. + Otherwise, will use the reset_joint_pos as the initial guess. + link_name (str or None): name of the EEF or trunk link. + """ + # Store arguments + assert mode in IK_MODES, f"Invalid ik mode specified! Valid options are: {IK_MODES}, got: {mode}" + + # If mode is absolute pose, make sure command input limits / output limits are None + if mode == "absolute_pose": + assert command_input_limits is None, "command_input_limits should be None if using absolute_pose mode!" + assert command_output_limits is None, "command_output_limits should be None if using absolute_pose mode!" + + self.mode = mode + self.workspace_pose_limiter = workspace_pose_limiter + self.reset_joint_pos = reset_joint_pos[dof_idx] + self.condition_on_current_position = condition_on_current_position + + self._link_name = link_name # eef/trunk link name (same for all members in the group) + self._fixed_quat_targets = [] # per-member fixed quat target for position_fixed_ori mode + + # If the mode is set as absolute orientation and using default config, + # change input and output limits accordingly. + # By default, the input limits are set as 1, so we modify this to have a correct range. + # The output orientation limits are also set to be values assuming delta commands, so those are updated too + if self.mode == "pose_absolute_ori": + if command_input_limits is not None: + if type(command_input_limits) is str and command_input_limits == "default": + command_input_limits = [ + cb.array([-1.0, -1.0, -1.0, -math.pi, -math.pi, -math.pi]), + cb.array([1.0, 1.0, 1.0, math.pi, math.pi, math.pi]), + ] + else: + command_input_limits[0][3:] = cb.full((len(command_input_limits[0][3:]),), -math.pi) + command_input_limits[1][3:] = cb.full((len(command_input_limits[1][3:]),), math.pi) + if command_output_limits is not None: + if not isinstance(command_output_limits, str) and isinstance(command_output_limits, Iterable): + command_output_limits = [ + cb.array(list(command_output_limits[0])), + cb.array(list(command_output_limits[1])), + ] + if type(command_output_limits) is str and command_output_limits == "default": + command_output_limits = [ + cb.array([-1.0, -1.0, -1.0, -math.pi, -math.pi, -math.pi]), + cb.array([1.0, 1.0, 1.0, math.pi, math.pi, math.pi]), + ] + else: + command_output_limits[0][3:] = cb.full((len(command_output_limits[0][3:]),), -math.pi) + command_output_limits[1][3:] = cb.full((len(command_output_limits[1][3:]),), math.pi) + # Run super init + super().__init__( + control_freq=control_freq, + control_limits=control_limits, + dof_idx=dof_idx, + pos_kp=pos_kp, + pos_damping_ratio=pos_damping_ratio, + vel_kp=vel_kp, + motor_type="position", + smoothing_filter_size=smoothing_filter_size, + use_delta_commands=False, + use_impedances=use_impedances, + command_input_limits=command_input_limits, + command_output_limits=command_output_limits, + isaac_kp=isaac_kp, + isaac_kd=isaac_kd, + ) + # Reuse the limits already cached by the base class; adding a leading dim lets clip() broadcast over N + self._q_lower = cb.view(self._clip_lo, (1, -1)) + self._q_upper = cb.view(self._clip_hi, (1, -1)) + + def add_member(self, articulation_root_path, control_enabled=True): + """ + Register a member and store its EEF link name. + + Reuses a tombstoned slot when available (tombstone reuse is handled by the base class). + + Args: + articulation_root_path (str): articulation root prim path of the new group member + + Returns: + int: controller_idx + """ + idx = super().add_member(articulation_root_path, control_enabled=control_enabled) + if idx < len(self._fixed_quat_targets): + # Reusing a tombstoned slot — reset the fixed orientation target + self._fixed_quat_targets[idx] = None + else: + self._fixed_quat_targets.append(None) + return idx + + def reset(self, controller_idx): + # Call super first + super().reset(controller_idx) + self._fixed_quat_targets[controller_idx] = None + + def _load_state(self, controller_idx, state): + # Run super first + super()._load_state(controller_idx=controller_idx, state=state) + + # Restore per-member fixed orientation targets from loaded goals. + if self.mode == "position_fixed_ori": + if cb.item_bool(self._goal_set[controller_idx]): + self._fixed_quat_targets[controller_idx] = cb.T.mat2quat(self._goals["target_ori_mat"][controller_idx]) + else: + self._fixed_quat_targets[controller_idx] = None + + def _update_goal(self, controller_idx, command): + """ + Returns: + dict: ``target_pos`` and ``target_ori_mat`` as compute-backend (``cb``) arrays + """ + prim_path = self._articulation_root_paths[controller_idx] + link_name = self._link_name + + # Get current EEF pose relative to robot base + pos_relative, quat_relative = ControllableObjectViewAPI.get_link_relative_position_orientation( + prim_path, link_name + ) + + # Convert position command to absolute values if needed + if self.mode == "absolute_pose": + target_pos = command[:3] + else: + dpos = command[:3] + target_pos = pos_relative + dpos + + # Compute orientation + if self.mode == "position_fixed_ori": + # We need to grab the current robot orientation as the commanded orientation if there is none saved + if self._fixed_quat_targets[controller_idx] is None: + self._fixed_quat_targets[controller_idx] = cb.copy(quat_relative) + target_quat = self._fixed_quat_targets[controller_idx] + elif self.mode == "position_compliant_ori": + # Target quat is simply the current robot orientation + target_quat = quat_relative + elif self.mode == "pose_absolute_ori" or self.mode == "absolute_pose": + # Received "delta" ori is in fact the desired absolute orientation + target_quat = cb.T.axisangle2quat(command[3:6]) + else: # pose_delta_ori control + # Grab dori and compute target ori + dori = cb.T.quat2mat(cb.T.axisangle2quat(command[3:6])) + target_quat = cb.T.mat2quat(dori @ cb.T.quat2mat(quat_relative)) + + # Possibly limit to workspace if specified + if self.workspace_pose_limiter is not None: + target_pos, target_quat = self.workspace_pose_limiter(target_pos, target_quat) + return dict( + target_pos=target_pos, + target_ori_mat=cb.T.quat2mat(target_quat), + ) + + def compute_control(self, goals): + """ + Converts the (already preprocessed) batched goals into deployable (non-clipped!) joint control signals + for all N group members. + + Args: + goals (Dict[str, Array]): batched goals with shape (N, *shape) per key. + Must include: + target_pos: (N, 3) desired EEF positions + target_ori_mat: (N, 3, 3) desired EEF orientation matrices + + Returns: + Array: (N, control_dim) outputted (non-clipped!) control signal to deploy + """ + + link_name = self._link_name + rows = self.view_row_indices + + # Batched state reads — convert from Isaac (torch) to compute backend type + all_q = ControllableObjectViewAPI.get_all_joint_positions(self.routing_path) # (N_view, n_joint_dof) + q_all = all_q[rows, :][:, self.dof_idx] # (N, ctrl_dim) + jac_all = ControllableObjectViewAPI.get_all_relative_jacobians( + self.routing_path + ) # (N_view, n_links, 6, n_dof_total) + eef_body_idx = ControllableObjectViewAPI.get_link_index(self.routing_path, link_name) + jac_row = eef_body_idx - 1 # Jacobian excludes root body (index 0) + # Floating-base robots expose Jacobian columns as [virtual_base(6), joints]. + # dof_idx indexes the joint block, so we need an offset for the Jacobian columns. + # Compute offset from full tensor shapes before row-slicing. + jac_col_offset = jac_all.shape[-1] - all_q.shape[-1] + jac_dof_idx = self.dof_idx + jac_col_offset + j_eef_all = jac_all[rows][:, jac_row, :, :][:, :, jac_dof_idx] # (N, 6, ctrl_dim) + ee_pos_all, ee_quat_all = ControllableObjectViewAPI.get_all_link_relative_position_orientation( + self.routing_path, link_name + ) # (N_view, 3), (N_view, 4) + ee_pos_all = ee_pos_all[rows] + ee_quat_all = ee_quat_all[rows] + ee_mat_all = cb.T.quat2mat(ee_quat_all) # (N, 3, 3) + + target_joint_pos_batch = cb.get_custom_method("compute_ik_qpos_batch")( + q=q_all, + j_eef=j_eef_all, + ee_pos=ee_pos_all, + ee_mat=ee_mat_all, + goal_pos=goals["target_pos"], + goal_ori_mat=goals["target_ori_mat"], + q_lower_limit=self._q_lower, # (1, ctrl_dim) broadcasts over N via clip() + q_upper_limit=self._q_upper, + ) # (N, ctrl_dim) + + # Delegate to JointController.compute_control for impedance handling + return super().compute_control(dict(target=target_joint_pos_batch)) + + def compute_no_op_goal(self, controller_idx): + """ + Returns: + dict: Current relative EEF pose as ``cb`` arrays (``target_pos``, ``target_ori_mat``). + """ + prim_path = self._articulation_root_paths[controller_idx] + link_name = self._link_name + + pos_relative, quat_relative = ControllableObjectViewAPI.get_link_relative_position_orientation( + prim_path, link_name + ) + return dict( + target_pos=cb.copy(pos_relative), + target_ori_mat=cb.T.quat2mat(quat_relative), + ) + + def _compute_no_op_command(self, controller_idx): + prim_path = self._articulation_root_paths[controller_idx] + link_name = self._link_name + + pos_relative, quat_relative = ControllableObjectViewAPI.get_link_relative_position_orientation( + prim_path, link_name + ) + + command = cb.zeros(6) + + # Handle position + if self.mode == "absolute_pose": + command[:3] = pos_relative + else: + # We can leave it as zero for delta mode. + pass + + # Handle orientation + if self.mode in ("pose_absolute_ori", "absolute_pose"): + command[3:] = cb.T.quat2axisangle(quat_relative) + else: + # For these modes, we don't need to add orientation to the command + pass + + return command + + def _get_goal_shapes(self): + return dict( + target_pos=(3,), + target_ori_mat=(3, 3), + ) + + @property + def command_dim(self): + return IK_MODE_COMMAND_DIMS[self.mode] + + +def _jparse_compute_torch( + jacobian: th.Tensor, + gamma: float = 0.1, + singular_direction_gain: float = 1.0, +) -> th.Tensor: + """Batched J-PARSE pseudo-inverse (torch implementation). + + Vectorized over the batch dimension for use with the IK controller. + J-PARSE: Jacobian-based Projection Algorithm for Resolving Singularities + Effectively. Clamps small singular values and adds smooth feedback in + singular directions for singularity-robust IK control. + Reference: https://github.com/armlabstanford/jparse + """ + J = jacobian.double() + N, m, _ = J.shape + + U, S, Vh = th.linalg.svd(J, full_matrices=False) + + sigma_max = S[:, 0] # (N,) + threshold = gamma * sigma_max # (N,) + + nonsing_mask = S > threshold[:, None] # (N, k) + sing_mask = ~nonsing_mask + + # ---- J_safety: clamp singular values below threshold ---- + S_safety = th.clamp(S, min=threshold[:, None]) # (N, k) + J_safety = U @ (S_safety.unsqueeze(-1) * Vh) # (N, m, n) + + # ---- J_proj: retain only non-singular directions ---- + n_nonsing = nonsing_mask.sum(dim=1) # (N,) + + if (n_nonsing > 0).all(): + S_proj = S * nonsing_mask # (N, k) + J_proj = U @ (S_proj.unsqueeze(-1) * Vh) + else: + J_proj = th.zeros_like(J) + has_nonsing = n_nonsing > 0 + S_proj = S * nonsing_mask + J_proj[has_nonsing] = (U[has_nonsing] * S_proj[has_nonsing, None, :]) @ Vh[has_nonsing] + + # ---- Phi_singular: smooth feedback in singular directions ---- + n_sing = sing_mask.sum(dim=1) # (N,) + Phi_singular = th.zeros(N, m, m, dtype=J.dtype, device=J.device) + + has_sing = n_sing > 0 + if has_sing.any(): + gains = th.full((m,), singular_direction_gain, dtype=J.dtype, device=J.device) + Kp = th.diag(gains) # (m, m) + + S_ratio = S[has_sing] / sigma_max[has_sing, None] # (N_sing, k) + phi_vals = S_ratio / gamma # (N_sing, k) + phi_vals = phi_vals * sing_mask[has_sing] # zero out non-singular + + U_sing = U[has_sing] # (N_sing, m, k) + Phi_mat = th.diag_embed(phi_vals) # (N_sing, k, k) + Phi_singular[has_sing] = U_sing @ Phi_mat @ U_sing.transpose(-2, -1) @ Kp + + # ---- Combine ---- + J_safety_pinv = th.linalg.pinv(J_safety) + J_proj_pinv = th.linalg.pinv(J_proj) + + J_parse = J_safety_pinv @ J_proj @ J_proj_pinv + J_parse = J_parse + J_safety_pinv @ Phi_singular + + return J_parse.float() + + +def _jparse_compute_numpy( + jacobian, + gamma=0.1, + singular_direction_gain=1.0, +): + """Batched J-PARSE pseudo-inverse (numpy implementation). + + Vectorized over the batch dimension for use with the IK controller. + J-PARSE: Jacobian-based Projection Algorithm for Resolving Singularities + Effectively. Clamps small singular values and adds smooth feedback in + singular directions for singularity-robust IK control. + Reference: https://github.com/armlabstanford/jparse + """ + J = jacobian.astype(np.float64) + N, m, _ = J.shape + + U, S, Vh = np.linalg.svd(J, full_matrices=False) + + sigma_max = S[:, 0] # (N,) + threshold = gamma * sigma_max # (N,) + + nonsing_mask = S > threshold[:, None] # (N, k) + sing_mask = ~nonsing_mask + + # ---- J_safety: clamp singular values below threshold ---- + S_safety = np.clip(S, threshold[:, None], None) # (N, k) + J_safety = U @ (S_safety[:, :, None] * Vh) # (N, m, n) + + # ---- J_proj: retain only non-singular directions ---- + S_proj = S * nonsing_mask # (N, k) + J_proj = U @ (S_proj[:, :, None] * Vh) + + # ---- Phi_singular: smooth feedback in singular directions ---- + n_sing = sing_mask.sum(axis=1) # (N,) + Phi_singular = np.zeros((N, m, m), dtype=np.float64) + + has_sing = n_sing > 0 + if has_sing.any(): + gains = np.full(m, singular_direction_gain, dtype=np.float64) + Kp = np.diag(gains) # (m, m) + + S_ratio = S[has_sing] / sigma_max[has_sing, None] # (N_sing, k) + phi_vals = (S_ratio / gamma) * sing_mask[has_sing] # (N_sing, k) + + U_sing = U[has_sing] # (N_sing, m, k) + Phi_mat = np.apply_along_axis(np.diag, -1, phi_vals) # (N_sing, k, k) + Phi_singular[has_sing] = U_sing @ Phi_mat @ U_sing.transpose(0, 2, 1) @ Kp + + # ---- Combine ---- + J_safety_pinv = np.linalg.pinv(J_safety) + J_proj_pinv = np.linalg.pinv(J_proj) + + J_parse = J_safety_pinv @ J_proj @ J_proj_pinv + J_parse = J_parse + J_safety_pinv @ Phi_singular + + return J_parse.astype(np.float32) + + +def _compute_ik_qpos_batch_torch( + q: th.Tensor, + j_eef: th.Tensor, + ee_pos: th.Tensor, + ee_mat: th.Tensor, + goal_pos: th.Tensor, + goal_ori_mat: th.Tensor, + q_lower_limit: th.Tensor, + q_upper_limit: th.Tensor, +): + pos_err = goal_pos - ee_pos + ori_err = TT.orientation_error(goal_ori_mat, ee_mat) + err = th.cat([pos_err, ori_err], dim=-1) + j_eef_pinv = _jparse_compute_torch(j_eef) + delta_j = (j_eef_pinv @ err.unsqueeze(-1)).squeeze(-1) + target_joint_pos = q + delta_j + return target_joint_pos.clip(min=q_lower_limit, max=q_upper_limit) + + +def _compute_ik_qpos_batch_numpy( + q, + j_eef, + ee_pos, + ee_mat, + goal_pos, + goal_ori_mat, + q_lower_limit, + q_upper_limit, +): + pos_err = goal_pos - ee_pos + ori_err = NT.orientation_error(goal_ori_mat, ee_mat).astype(np.float32) + err = np.concatenate([pos_err, ori_err], axis=-1) + j_eef_pinv = _jparse_compute_numpy(j_eef) + delta_j = (j_eef_pinv @ err[..., None])[..., 0] + target_joint_pos = q + delta_j + return target_joint_pos.clip(q_lower_limit, q_upper_limit) + + +add_compute_function( + name="compute_ik_qpos_batch", + np_function=_compute_ik_qpos_batch_numpy, + th_function=_compute_ik_qpos_batch_torch, +) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/joint_controller.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/joint_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..422bf71b6482c05404788a42c307be4455e01528 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/joint_controller.py @@ -0,0 +1,510 @@ +import math + +import numpy as np +import torch as th +from numba import jit + +from omnigibson.controllers import ( + ControlType, + GripperController, + IsGraspingState, + LocomotionController, + ManipulationController, +) +from omnigibson.macros import create_module_macros +from omnigibson.utils.backend_utils import _compute_backend as cb +from omnigibson.utils.backend_utils import add_compute_function +from omnigibson.utils.python_utils import assert_valid_key, torch_compile +from omnigibson.utils.processing_utils import MovingAverageFilter +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import ControllableObjectViewAPI + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Create settings for this module +m = create_module_macros(module_path=__file__) +m.DEFAULT_JOINT_POS_KP = 50.0 +m.DEFAULT_JOINT_POS_DAMPING_RATIO = 1.0 # critically damped +m.DEFAULT_JOINT_VEL_KP = 2.0 + + +class JointController(LocomotionController, ManipulationController, GripperController): + """ + Controller class for joint control. Because omniverse can handle direct position / velocity / effort + control signals, this is merely a pass-through operation from command to control (with clipping / scaling built in). + + Each controller step consists of the following: + 1. Clip + Scale inputted command according to @command_input_limits and @command_output_limits + 2a. If using delta commands, then adds the command to the current joint state + 2b. Clips the resulting command by the motor limits + """ + + def __init__( + self, + control_freq, + motor_type, + control_limits, + dof_idx, + command_input_limits="default", + command_output_limits="default", + isaac_kp=None, + isaac_kd=None, + pos_kp=None, + pos_damping_ratio=None, + vel_kp=None, + smoothing_filter_size=None, + use_impedances=False, + use_gravity_compensation=False, + use_cc_compensation=True, + use_delta_commands=False, + compute_delta_in_quat_space=None, + ): + """ + Args: + control_freq (int): controller loop frequency + motor_type (str): type of motor being controlled, one of {position, velocity, effort} + control_limits (Dict[str, Tuple[Array[float], Array[float]]]): The min/max limits to the outputted + control signal. Should specify per-dof type limits, i.e.: + + "position": [[min], [max]] + "velocity": [[min], [max]] + "effort": [[min], [max]] + "has_limit": [...bool...] + + Values outside of this range will be clipped, if the corresponding joint index in has_limit is True. + dof_idx (Array[int]): specific dof indices controlled by this controller. Used for inferring + controller-relevant values during control computations + command_input_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max acceptable inputted command. Values outside this range will be clipped. + If None, no clipping will be used. If "default", range will be set to (-1, 1) + command_output_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max scaled command. If both this value and @command_input_limits is not None, + then all inputted command values will be scaled from the input range to the output range. + If either is None, no scaling will be used. If "default", then this range will automatically be set + to the @control_limits entry corresponding to self.control_type + isaac_kp (None or float or Array[float]): If specified, stiffness gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers. + Should only be nonzero if self.control_type is position + isaac_kd (None or float or Array[float]): If specified, damping gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers + Should only be nonzero if self.control_type is position or velocity + pos_kp (None or float): If @motor_type is "position" and @use_impedances=True, this is the + proportional gain applied to the joint controller. If None, a default value will be used. + pos_damping_ratio (None or float): If @motor_type is "position" and @use_impedances=True, this is the + damping ratio applied to the joint controller. If None, a default value will be used. + vel_kp (None or float): If @motor_type is "velocity" and @use_impedances=True, this is the + proportional gain applied to the joint controller. If None, a default value will be used. + smoothing_filter_size (None or int): if specified, sets the size of a moving average filter to apply + on all outputted joint positions. + use_impedances (bool): If True, will use impedances via the mass matrix to modify the desired efforts + applied + use_gravity_compensation (bool): If True, will add gravity compensation to the computed efforts. This is + an experimental feature that only works on fixed base robots. We do not recommend enabling this. + use_cc_compensation (bool): If True, will add Coriolis / centrifugal compensation to the computed efforts. + use_delta_commands (bool): whether inputted commands should be interpreted as delta or absolute values + compute_delta_in_quat_space (None or List[(rx_idx, ry_idx, rz_idx), ...]): if specified, groups of + joints that need to be processed in quaternion space to avoid gimbal lock issues normally faced by + 3 DOF rotation joints. Each group needs to consist of three idxes corresponding to the indices in + the input space. This is only used in the delta_commands mode. + """ + # Store arguments + assert_valid_key(key=motor_type.lower(), valid_keys=ControlType.VALID_TYPES_STR, name="motor_type") + self._motor_type = motor_type.lower() + self._use_delta_commands = use_delta_commands + self._compute_delta_in_quat_space = [] if compute_delta_in_quat_space is None else compute_delta_in_quat_space + + # Possibly create control filter + command_dim = len(dof_idx) + self.control_filter = ( + None + if smoothing_filter_size in {None, 0} + else MovingAverageFilter(obs_dim=command_dim, filter_width=smoothing_filter_size) + ) + + # Store control gains + if self._motor_type == "position": + pos_kp = m.DEFAULT_JOINT_POS_KP if pos_kp is None else pos_kp + pos_damping_ratio = m.DEFAULT_JOINT_POS_DAMPING_RATIO if pos_damping_ratio is None else pos_damping_ratio + elif self._motor_type == "velocity": + vel_kp = m.DEFAULT_JOINT_VEL_KP if vel_kp is None else vel_kp + assert ( + pos_damping_ratio is None + ), "Cannot set pos_damping_ratio for JointController with motor_type=velocity!" + else: # effort + assert pos_kp is None, "Cannot set pos_kp for JointController with motor_type=effort!" + assert pos_damping_ratio is None, "Cannot set pos_damping_ratio for JointController with motor_type=effort!" + assert vel_kp is None, "Cannot set vel_kp for JointController with motor_type=effort!" + self.pos_kp = pos_kp + self.pos_kd = None if pos_kp is None or pos_damping_ratio is None else 2 * math.sqrt(pos_kp) * pos_damping_ratio + self.vel_kp = vel_kp + self._use_impedances = use_impedances + self._use_gravity_compensation = use_gravity_compensation + self._use_cc_compensation = use_cc_compensation + self._smoothing_filter_size = smoothing_filter_size + self._filter_obs_dim = len(dof_idx) + self._control_filter = None # single batched filter for all members + + # Warn the user about gravity compensation being experimental. + if self._use_gravity_compensation: + log.warning( + "JointController is using gravity compensation. This is an experimental feature that only works on " + "fixed base robots. We do not recommend enabling this." + ) + + # When in delta mode, it doesn't make sense to infer output range using the joint limits (since that's an + # absolute range and our values are relative). So reject the default mode option in that case. + assert not ( + self._use_delta_commands and type(command_output_limits) is str and command_output_limits == "default" + ), "Cannot use 'default' command output limits in delta commands mode of JointController. Try None instead." + + # Run super init + super().__init__( + control_freq=control_freq, + control_limits=control_limits, + dof_idx=dof_idx, + command_input_limits=command_input_limits, + command_output_limits=command_output_limits, + isaac_kp=isaac_kp, + isaac_kd=isaac_kd, + ) + + def add_member(self, articulation_root_path, control_enabled=True): + idx = super().add_member(articulation_root_path, control_enabled=control_enabled) + if self._smoothing_filter_size not in {None, 0}: + if self._control_filter is None: + # First-ever member: create the batched filter (idx is always 0 here) + self._control_filter = MovingAverageFilter( + obs_dim=self._filter_obs_dim, + filter_width=self._smoothing_filter_size, + n_members=1, + ) + else: + # Pass idx so the filter reuses the slot in-place or appends as appropriate + self._control_filter.add_member(idx) + return idx + + def unregister_member(self, controller_idx): + """Mark member at controller_idx as a tombstone in both controller and smoothing filter. + + Args: + controller_idx (int): index of the member to unregister + """ + super().unregister_member(controller_idx) + if self._control_filter is not None: + self._control_filter.unregister_member(controller_idx) + + def reset(self, controller_idx): + super().reset(controller_idx) + if self._control_filter is not None: + self._control_filter.reset(controller_idx) + + @property + def state_size(self): + if self._control_filter is None: + return super().state_size + return super().state_size + self._control_filter.state_size + + def _dump_state(self, controller_idx): + state = super()._dump_state(controller_idx=controller_idx) + state["control_filter"] = ( + None if self._control_filter is None else self._control_filter.dump_state(controller_idx) + ) + return state + + def _load_state(self, controller_idx, state): + super()._load_state(controller_idx=controller_idx, state=state) + if self._control_filter is not None and state.get("control_filter") is not None: + self._control_filter.load_state(controller_idx, state["control_filter"]) + + def serialize(self, state, controller_idx): + state_flat = super().serialize(state=state, controller_idx=controller_idx) + filter_part = ( + th.tensor([]) + if self._control_filter is None or state.get("control_filter") is None + else self._control_filter.serialize(state["control_filter"], controller_idx) + ) + return th.cat([state_flat, filter_part]) + + def deserialize(self, state, controller_idx): + state_dict, idx = super().deserialize(state=state, controller_idx=controller_idx) + state_dict["control_filter"] = None + if self._control_filter is not None: + state_dict["control_filter"], samples_len = self._control_filter.deserialize(state[idx:], controller_idx) + idx += samples_len + return state_dict, idx + + def _generate_default_command_output_limits(self): + # Use motor type instead of default control type, since, e.g, use_impedances is commanding joint positions + # but controls low-level efforts + return ( + self._control_limits[ControlType.get_type(self._motor_type)][0][self.dof_idx], + self._control_limits[ControlType.get_type(self._motor_type)][1][self.dof_idx], + ) + + def _update_goal(self, controller_idx, command): + """ + Returns: + dict: ``target`` joint setpoint as a compute-backend array + """ + # If we're using delta commands, add this value + if self._use_delta_commands: + prim_path = self._articulation_root_paths[controller_idx] + # Compute the base value for the command + if self._motor_type == "position": + base_value = ControllableObjectViewAPI.get_joint_positions(prim_path)[self.dof_idx] + elif self._motor_type == "velocity": + base_value = ControllableObjectViewAPI.get_joint_velocities(prim_path, estimate=True)[self.dof_idx] + else: + base_value = ControllableObjectViewAPI.get_joint_efforts(prim_path)[self.dof_idx] + + # Apply the command to the base value. + target = base_value + command + + # Correct any gimbal lock issues using the compute_delta_in_quat_space group. + for rx_ind, ry_ind, rz_ind in self._compute_delta_in_quat_space: + # Grab the starting rotations of these joints. + start_rots = base_value[[rx_ind, ry_ind, rz_ind]] + + # Grab the delta rotations. + delta_rots = command[[rx_ind, ry_ind, rz_ind]] + + # Compute the final rotations in the quaternion space. + _, end_quat = cb.T.pose_transform( + cb.zeros(3), cb.T.euler2quat(delta_rots), cb.zeros(3), cb.T.euler2quat(start_rots) + ) + end_rots = cb.T.quat2euler(end_quat) + + # Update the command + target[[rx_ind, ry_ind, rz_ind]] = end_rots + + # Otherwise, goal is simply the command itself + else: + target = command + + # Clip the command based on the limits + target = target.clip( + self._control_limits[ControlType.get_type(self._motor_type)][0][self.dof_idx], + self._control_limits[ControlType.get_type(self._motor_type)][1][self.dof_idx], + ) + + return dict(target=target) + + def compute_control(self, goals): + """ + Converts the (already preprocessed) batched goals into deployable (non-clipped!) joint control signals + for all N group members. + + Args: + goals (Dict[str, Array]): batched goals with shape (N, *shape) per key. + Must include: + target: (N, control_dim) desired joint values used as setpoint + + Returns: + Array: (N, control_dim) outputted (non-clipped!) control signal to deploy + """ + + target = goals["target"] # (N, control_dim) + + # Optionally pass through smoothing filter for better stability + if self._control_filter is not None: + target = self._control_filter.estimate_batch(target) + + # Convert control into efforts + if self._use_impedances: + rows = self.view_row_indices + # Joint indices are defined over actuated joints; generalized dynamics tensors may include extra base DoFs. + all_joint_positions = ControllableObjectViewAPI.get_all_joint_positions(self.routing_path)[rows, :] + + if self._motor_type == "position": + base_value = all_joint_positions[:, self.dof_idx] + vel_base = ControllableObjectViewAPI.get_all_joint_velocities(self.routing_path, estimate=True)[ + rows, : + ][:, self.dof_idx] + position_error = target - base_value + vel_pos_error = -vel_base + u = position_error * self.pos_kp + vel_pos_error * self.pos_kd + elif self._motor_type == "velocity": + base_value = ControllableObjectViewAPI.get_all_joint_velocities(self.routing_path, estimate=True)[ + rows, : + ][:, self.dof_idx] + velocity_error = target - base_value + u = velocity_error * self.vel_kp + else: # effort + u = target + + # Apply impedances via mass matrix (batched over all N members) + all_mm = ControllableObjectViewAPI.get_all_generalized_mass_matrices(self.routing_path)[ + rows, :, : + ] # (N, n_dof_total, n_dof_total) + + # Compute offset between generalized DoFs and actuated joint DoFs (handles floating-base robots). + base_dof_offset = all_mm.shape[-1] - all_joint_positions.shape[-1] + if base_dof_offset < 0: + base_dof_offset = 0 + effective_dof_idx = [idx + base_dof_offset for idx in self.dof_idx] + dof_idx_arr = cb.int_array(effective_dof_idx) + + u = cb.get_custom_method("compute_joint_torques_batch")(u, all_mm, dof_idx_arr) # (N, control_dim) + + if self._use_gravity_compensation: + u = ( + u + + ControllableObjectViewAPI.get_all_gravity_compensation_forces(self.routing_path)[rows, :][ + :, effective_dof_idx + ] + ) + + if self._use_cc_compensation: + u = ( + u + + ControllableObjectViewAPI.get_all_coriolis_and_centrifugal_compensation_forces(self.routing_path)[ + rows, : + ][:, effective_dof_idx] + ) + + else: + u = target + + return u + + def compute_no_op_goal(self, controller_idx): + """ + Returns: + dict: ``target`` as a compute-backend array (hold position or zeros by motor type) + """ + prim_path = self._articulation_root_paths[controller_idx] + + if self._motor_type == "position": + target = ControllableObjectViewAPI.get_joint_positions(prim_path)[self.dof_idx] + else: + target = cb.zeros(self.control_dim) + + return dict(target=target) + + def _compute_no_op_command(self, controller_idx): + prim_path = self._articulation_root_paths[controller_idx] + + if self.motor_type == "position": + if self._use_delta_commands: + return cb.zeros(self.command_dim) + else: + return ControllableObjectViewAPI.get_joint_positions(prim_path)[self.dof_idx] + elif self.motor_type == "velocity": + if self._use_delta_commands: + return -ControllableObjectViewAPI.get_joint_velocities(prim_path, estimate=True)[self.dof_idx] + else: + return cb.zeros(self.command_dim) + + raise ValueError("Cannot compute noop action for effort motor type.") + + def _get_goal_shapes(self): + return dict(target=(self.control_dim,)) + + def is_grasping(self, controller_idx): + # No good heuristic to determine grasping, so return UNKNOWN + return IsGraspingState.UNKNOWN + + @property + def use_delta_commands(self): + """ + Returns: + bool: Whether this controller is using delta commands or not + """ + return self._use_delta_commands + + @property + def motor_type(self): + """ + Returns: + str: The type of motor being simulated by this controller. One of {"position", "velocity", "effort"} + """ + return self._motor_type + + @property + def control_type(self): + return ControlType.EFFORT if self._use_impedances else ControlType.get_type(type_str=self._motor_type) + + @property + def command_dim(self): + return len(self.dof_idx) + + +@torch_compile +def _compute_joint_torques_torch( + u: th.Tensor, + mm: th.Tensor, + dof_idx: th.Tensor, +): + dof_idxs_mat = th.meshgrid(dof_idx, dof_idx, indexing="xy") + return mm[dof_idxs_mat] @ u + + +# Use numba since faster +@jit(nopython=True, cache=True) +def numba_ix(arr, rows, cols): + """ + Numba compatible implementation of arr[np.ix_(rows, cols)] for 2D arrays. + + Implementation from: + https://github.com/numba/numba/issues/5894#issuecomment-974701551 + + :param arr: 2D array to be indexed + :param rows: Row indices + :param cols: Column indices + :return: 2D array with the given rows and columns of the input array + """ + one_d_index = np.zeros(len(rows) * len(cols), dtype=np.int32) + for i, r in enumerate(rows): + start = i * len(cols) + one_d_index[start : start + len(cols)] = cols + arr.shape[1] * r + + arr_1d = arr.reshape((arr.shape[0] * arr.shape[1], 1)) + slice_1d = np.take(arr_1d, one_d_index) + return slice_1d.reshape((len(rows), len(cols))) + + +@jit(nopython=True, cache=True) +def _compute_joint_torques_numpy( + u, + mm, + dof_idx, +): + return numba_ix(mm, dof_idx, dof_idx) @ u + + +# Set these as part of the backend values +add_compute_function( + name="compute_joint_torques", np_function=_compute_joint_torques_numpy, th_function=_compute_joint_torques_torch +) + + +@torch_compile +def _compute_joint_torques_batch_torch( + u: th.Tensor, + mm: th.Tensor, + dof_idx: th.Tensor, +): + dof_idxs_mat = th.meshgrid(dof_idx, dof_idx, indexing="xy") + mm_sub = mm[:, dof_idxs_mat[0], dof_idxs_mat[1]] # (N, ctrl_dim, ctrl_dim) + return (mm_sub @ u.unsqueeze(-1)).squeeze(-1) # (N, ctrl_dim) + + +@jit(nopython=True, cache=True) +def _compute_joint_torques_batch_numpy( + u, + mm, + dof_idx, +): + N = u.shape[0] + result = np.zeros_like(u) + for i in range(N): + result[i] = numba_ix(mm[i], dof_idx, dof_idx) @ u[i] + return result + + +add_compute_function( + name="compute_joint_torques_batch", + np_function=_compute_joint_torques_batch_numpy, + th_function=_compute_joint_torques_batch_torch, +) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/multi_finger_gripper_controller.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/multi_finger_gripper_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..dab62453638c9895ca0c8238453190b1c0f64005 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/multi_finger_gripper_controller.py @@ -0,0 +1,441 @@ +import torch as th + +from omnigibson.controllers import ControlType, GripperController, IsGraspingState +from omnigibson.macros import create_module_macros +from omnigibson.utils.backend_utils import _compute_backend as cb +from omnigibson.utils.processing_utils import MovingAverageFilter +from omnigibson.utils.python_utils import assert_valid_key +from omnigibson.utils.usd_utils import ControllableObjectViewAPI + +VALID_MODES = { + "binary", + "smooth", + "independent", +} + + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# is_grasping heuristics parameters +m.POS_TOLERANCE = 0.002 # arbitrary heuristic +m.VEL_TOLERANCE = 0.02 # arbitrary heuristic + + +class MultiFingerGripperController(GripperController): + """ + Controller class for multi finger gripper control. This either interprets an input as a binary + command (open / close), continuous command (open / close with scaled velocities), or per-joint continuous command + + Each controller step consists of the following: + 1. Clip + Scale inputted command according to @command_input_limits and @command_output_limits + 2a. Convert command into gripper joint control signals + 2b. Clips the resulting control by the motor limits + """ + + def __init__( + self, + control_freq, + motor_type, + control_limits, + dof_idx, + command_input_limits="default", + command_output_limits="default", + isaac_kp=None, + isaac_kd=None, + inverted=False, + mode="binary", + open_qpos=None, + closed_qpos=None, + limit_tolerance=0.001, + ): + """ + Args: + control_freq (int): controller loop frequency + motor_type (str): type of motor being controlled, one of {position, velocity, effort} + control_limits (Dict[str, Tuple[Array[float], Array[float]]]): The min/max limits to the outputted + control signal. Should specify per-dof type limits, i.e.: + + "position": [[min], [max]] + "velocity": [[min], [max]] + "effort": [[min], [max]] + "has_limit": [...bool...] + + Values outside of this range will be clipped, if the corresponding joint index in has_limit is True. + dof_idx (Array[int]): specific dof indices controlled by this robot. Used for inferring + controller-relevant values during control computations + command_input_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max acceptable inputted command. Values outside this range will be clipped. + If None, no clipping will be used. If "default", range will be set to (-1, 1) + command_output_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max scaled command. If both this value and @command_input_limits is not None, + then all inputted command values will be scaled from the input range to the output range. + If either is None, no scaling will be used. If "default", then this range will automatically be set + to the @control_limits entry corresponding to self.control_type + isaac_kp (None or float or Array[float]): If specified, stiffness gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers. + Should only be nonzero if self.control_type is position + isaac_kd (None or float or Array[float]): If specified, damping gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers + Should only be nonzero if self.control_type is position or velocity + inverted (bool): whether or not the command direction (grasp is negative) and the control direction are + inverted, e.g. to grasp you need to move the joint in the positive direction. + mode (str): mode for this controller. Valid options are: + + "binary": 1D command, if preprocessed value > 0 is interpreted as an max open + (send max pos / vel / tor signal), otherwise send max close control signals + "smooth": 1D command, sends symmetric signal to all finger joints equal to the preprocessed commands + "independent": n-dimensional command, sends independent signals to each finger joint equal to the preprocessed command + + open_qpos (None or Array[float]): If specified, the joint positions representing a fully-opened gripper. + This is to allow representing the open state as a partially opened gripper, rather than the full + opened gripper. If None, will simply use the native joint limits of the gripper joints. Only relevant + if using @mode=binary and @motor_type=position + closed_qpos (None or Array[float]): If specified, the joint positions representing a fully-closed gripper. + This is to allow representing the closed state as a partially closed gripper, rather than the full + closed gripper. If None, will simply use the native joint limits of the gripper joints. Only relevant + if using @mode=binary and @motor_type=position + limit_tolerance (float): sets the tolerance from the joint limit ends, below which controls will be zeroed + out if the control is using velocity or torque control + """ + # Store arguments + assert_valid_key(key=motor_type.lower(), valid_keys=ControlType.VALID_TYPES_STR, name="motor_type") + self._motor_type = motor_type.lower() + assert_valid_key(key=mode, valid_keys=VALID_MODES, name="mode for multi finger gripper") + self._inverted = inverted + self._mode = mode + self._limit_tolerance = limit_tolerance + self._open_qpos = open_qpos if open_qpos is None else cb.array(open_qpos) + self._closed_qpos = closed_qpos if closed_qpos is None else cb.array(closed_qpos) + + # Per-member grasping state and velocity filters (indexed by controller_idx) + self._is_grasping = [] # list of IsGraspingState per member + self._vel_filter = None # single batched MovingAverageFilter for all members + # Last control per member (for grasping heuristic) + self._controls = [] + + # If we're using binary signal, these values will be overridden manually, so set to default for now + if mode == "binary": + command_output_limits = "default" + + # Run super init + super().__init__( + control_freq=control_freq, + control_limits=control_limits, + dof_idx=dof_idx, + command_input_limits=command_input_limits, + command_output_limits=command_output_limits, + isaac_kp=isaac_kp, + isaac_kd=isaac_kd, + ) + + def add_member(self, articulation_root_path, control_enabled=True): + idx = super().add_member(articulation_root_path, control_enabled=control_enabled) + if idx < len(self._is_grasping): + # Reusing a tombstoned slot — reset per-member grasping state + self._is_grasping[idx] = IsGraspingState.FALSE + else: + # New slot — append state + self._is_grasping.append(IsGraspingState.FALSE) + if self._vel_filter is None: + # First-ever member: create the batched filter (idx is always 0 here) + self._vel_filter = MovingAverageFilter(obs_dim=len(self.dof_idx), filter_width=5, n_members=1) + else: + # Pass idx so the filter reuses the slot in-place or appends as appropriate + self._vel_filter.add_member(idx) + # Note: _controls is managed by BaseController.add_member; do not append here + return idx + + def unregister_member(self, controller_idx): + """Mark member at controller_idx as a tombstone in both controller and velocity filter. + + Args: + controller_idx (int): index of the member to unregister + """ + super().unregister_member(controller_idx) + if self._vel_filter is not None: + self._vel_filter.unregister_member(controller_idx) + + def _generate_default_command_output_limits(self): + # By default (independent mode), this is simply the super call + command_output_limits = super()._generate_default_command_output_limits() + + # If we're in binary mode, output limits should just be (-1.0, 1.0) + if self._mode == "binary": + command_output_limits = (-1.0, 1.0) + # If we're in smoothing mode, output limits should be the average of the independent limits + elif self._mode == "smooth": + command_output_limits = ( + cb.mean(command_output_limits[0]), + cb.mean(command_output_limits[1]), + ) + elif self._mode == "independent": + pass + else: + raise ValueError(f"Invalid mode {self._mode}") + + return command_output_limits + + def reset(self, controller_idx): + # Call super first + super().reset(controller_idx) + + # Reset the filter and grasping state + self._vel_filter.reset(controller_idx) + self._is_grasping[controller_idx] = IsGraspingState.FALSE + + def _preprocess_command(self, command): + # We extend this method to make sure command is always n-dimensional + if self._mode != "independent": + command = ( + cb.array([command] * self.command_dim) + if type(command) in {int, float} + else cb.array([command[0]] * self.command_dim) + ) + + # Flip the command if the direction is inverted. + if self._inverted: + command = self._command_input_limits[1] - (command - self._command_input_limits[0]) + + # Return from super method + return super()._preprocess_command(command=command) + + def _update_goal(self, controller_idx, command): + # Directly store command as the goal (compute-backend array) + return dict(target=command) + + def compute_control(self, goals): + """ + Converts the (already preprocessed) batched goals into deployable (non-clipped!) gripper + joint control signals for all N group members. + + Args: + goal_dict (Dict[str, Any]): dictionary that should include any relevant keyword-mapped + goals necessary for controller computation. Must include the following keys: + target: (N, command_dim) desired gripper target + + Returns: + Array: (N, control_dim) outputted (non-clipped!) control signal to deploy + """ + target_batch = goals["target"] # (N, command_dim) + + rows = self.view_row_indices + all_joint_pos = ControllableObjectViewAPI.get_all_joint_positions(self.routing_path)[rows, :][ + :, self.dof_idx + ] # (N, ctrl_dim) + + unregistered_mask = self._unregistered_controllers == 1 # (N,) + + # Choose what to do based on control mode + if self._mode == "binary": + should_open = target_batch[:, 0] >= 0.0 if not self._inverted else target_batch[:, 0] > 0.0 # (N,) + open_limit = ( + self._control_limits[ControlType.get_type(self._motor_type)][1][self.dof_idx] + if self._open_qpos is None + else self._open_qpos + ) # (ctrl_dim,) + closed_limit = ( + self._control_limits[ControlType.get_type(self._motor_type)][0][self.dof_idx] + if self._closed_qpos is None + else self._closed_qpos + ) # (ctrl_dim,) + u = cb.where(should_open[:, None], open_limit, closed_limit) # (N, ctrl_dim) + else: + # Broadcast single-column target across control_dim if needed + if target_batch.shape[1] == 1: + u = target_batch * cb.ones(self.control_dim) + else: + u = target_batch # (N, ctrl_dim) + + # If we're near the joint limits and we're using velocity / effort control, we zero out the action + if self._motor_type in {"velocity", "effort"}: + pos_hi = self._control_limits[ControlType.POSITION][1][self.dof_idx] # (ctrl_dim,) + pos_lo = self._control_limits[ControlType.POSITION][0][self.dof_idx] # (ctrl_dim,) + violate_upper_limit = all_joint_pos > pos_hi - self._limit_tolerance # (N, ctrl_dim) + violate_lower_limit = all_joint_pos < pos_lo + self._limit_tolerance # (N, ctrl_dim) + violation = (violate_upper_limit & (u > 0)) | (violate_lower_limit & (u < 0)) + u = u * ~violation + + # Update grasping state for all members + self._update_grasping_state(all_joint_pos, u) + + # Zero out unregistered members + u[unregistered_mask] = 0.0 + + return u # array with shape (N, control_dim) + + def _update_grasping_state(self, joint_pos, control): + """ + Updates internal inferred grasping state for the controller at @controller_idx. + + Args: + joint_pos (Array): joint positions for this group's members' controlled DOFs, shape (N, ctrl_dim) + control (Array): the control signal being applied, shape (N, ctrl_dim) + """ + rows = self.view_row_indices + all_joint_vel = ControllableObjectViewAPI.get_all_joint_velocities(self.routing_path, estimate=True)[rows, :][ + :, self.dof_idx + ] # (N, ctrl_dim) + + # Update velocity history for all members + finger_vels = self._vel_filter.estimate_batch(all_joint_vel) # (N, ctrl_dim) + + # Calculate grasping state based on mode of this controller + if self._mode == "independent": + is_grasping_result = [IsGraspingState.UNKNOWN] * self.n_members + + else: + # Different values in the command for non-independent mode - cannot use heuristics + non_uniform_mask = ~cb.all(control == control[:, :1], 1) # (N,) + + # Joint position tolerance for is_grasping heuristics checking is smaller than or equal to the gripper + # controller's tolerance of zero-ing out velocities, which makes the heuristics invalid. + if not m.POS_TOLERANCE > self._limit_tolerance: + is_grasping_result = [IsGraspingState.UNKNOWN] * self.n_members + + else: + # For joint position control, if the desired positions are the same as the current positions, is_grasping unknown + if self._motor_type == "position": + no_move_mask = cb.mean(cb.abs(control - joint_pos), dim=1) < m.POS_TOLERANCE # (N,) + # For joint velocity / effort control, if the desired velocities / efforts are zeros, is_grasping unknown + elif self._motor_type in {"velocity", "effort"}: + no_move_mask = cb.mean(cb.abs(control), dim=1) < m.VEL_TOLERANCE # (N,) + else: + no_move_mask = cb.bool_zeros(self.n_members) # all-False + + # Otherwise, the last control signal intends to "move" the gripper + min_pos = self._control_limits[ControlType.POSITION][0][self.dof_idx] # (ctrl_dim,) + max_pos = self._control_limits[ControlType.POSITION][1][self.dof_idx] # (ctrl_dim,) + # Make sure we don't have any invalid values (i.e.: fingers should be within the limits) + finger_pos = joint_pos.clip(min_pos, max_pos) # (N, ctrl_dim) + # Check distance from both ends of the joint limits + dist_from_lower_limit = finger_pos - min_pos # (N, ctrl_dim) + dist_from_upper_limit = max_pos - finger_pos # (N, ctrl_dim) + + # If either of the joint positions are not near the joint limits with some tolerance (m.POS_TOLERANCE) + valid_grasp_pos = (cb.mean(dist_from_lower_limit, dim=1) > m.POS_TOLERANCE) | ( + cb.mean(dist_from_upper_limit, dim=1) > m.POS_TOLERANCE + ) # (N,) + + # And the joint velocities are close to zero with some tolerance (m.VEL_TOLERANCE) + valid_grasp_vel = cb.all(cb.abs(finger_vels) < m.VEL_TOLERANCE, 1) # (N,) + + # Then the gripper is grasping something, which stops the gripper from reaching its desired state + is_grasping_true = valid_grasp_pos & valid_grasp_vel # (N,) + + # Build per-member result: UNKNOWN overrides where non_uniform or no_move + is_grasping_result = [ + IsGraspingState.UNKNOWN + if (non_uniform_mask[i] or no_move_mask[i]) + else (IsGraspingState.TRUE if is_grasping_true[i] else IsGraspingState.FALSE) + for i in range(self.n_members) + ] + + # Store calculated state + self._is_grasping = is_grasping_result + + def compute_no_op_goal(self, controller_idx): + """ + Returns: + dict: ``target`` as a compute-backend array (shape matches command space). + """ + prim_path = self._articulation_root_paths[controller_idx] + + # Take care of the special case of binary control + if self._mode == "binary": + goal_sign = -1 if self._is_grasping[controller_idx] == IsGraspingState.TRUE else 1 + if self._inverted: + goal_sign = -1 * goal_sign + target = cb.array([goal_sign]) + + else: + if self._motor_type == "position": + target = ControllableObjectViewAPI.get_joint_positions(prim_path)[self.dof_idx] + elif self._motor_type == "velocity": + target = cb.zeros(self.command_dim) + else: + raise ValueError("Cannot compute noop action for effort motor type.") + + # Convert to binary / smooth mode if necessary + if self._mode == "smooth": + target = cb.mean(target, dim=-1, keepdim=True) + + return dict(target=target) + + def _compute_no_op_command(self, controller_idx): + prim_path = self._articulation_root_paths[controller_idx] + + # Take care of the special case of binary control + if self._mode == "binary": + command_val = -1 if self._is_grasping[controller_idx] == IsGraspingState.TRUE else 1 + if self._inverted: + command_val = -1 * command_val + return cb.array([command_val]) + + if self._motor_type == "position": + command = ControllableObjectViewAPI.get_joint_positions(prim_path)[self.dof_idx] + elif self._motor_type == "velocity": + command = cb.zeros(self.command_dim) + else: + raise ValueError("Cannot compute noop action for effort motor type.") + + # Convert to binary / smooth mode if necessary + if self._mode == "smooth": + command = cb.mean(command, dim=-1, keepdim=True) + + return command + + def _get_goal_shapes(self): + return dict(target=(self.command_dim,)) + + def is_grasping(self, controller_idx=0): + # Return cached value for this member + return self._is_grasping[controller_idx] + + def _dump_state(self, controller_idx): + # Run super first + state = super()._dump_state(controller_idx=controller_idx) + state["vel_filter"] = None if self._vel_filter is None else self._vel_filter.dump_state(controller_idx) + return state + + def _load_state(self, controller_idx, state): + # Run super first + super()._load_state(controller_idx=controller_idx, state=state) + + # Also load velocity filter state for this single member. + if self._vel_filter is not None and state.get("vel_filter") is not None: + self._vel_filter.load_state(controller_idx, state["vel_filter"]) + elif self._vel_filter is not None and not state["goal_set"]: + self._vel_filter.reset(controller_idx) + + def serialize(self, state, controller_idx): + # Run super first + state_flat = super().serialize(state=state, controller_idx=controller_idx) + filter_flat = ( + self._vel_filter.serialize(state["vel_filter"], controller_idx) + if self._vel_filter is not None and state.get("vel_filter") is not None + else th.tensor([]) + ) + return th.cat([state_flat, filter_flat]) + + def deserialize(self, state, controller_idx): + state_dict, idx = super().deserialize(state=state, controller_idx=controller_idx) + state_dict["vel_filter"] = None + if self._vel_filter is not None: + state_dict["vel_filter"], samples_len = self._vel_filter.deserialize(state[idx:], controller_idx) + idx += samples_len + return state_dict, idx + + @property + def state_size(self): + if self._vel_filter is None: + return super().state_size + return super().state_size + self._vel_filter.state_size + + @property + def control_type(self): + return ControlType.get_type(type_str=self._motor_type) + + @property + def command_dim(self): + return len(self.dof_idx) if self._mode == "independent" else 1 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/null_joint_controller.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/null_joint_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..fdd0bf6fbaf96f8cb3caf0b8e74521b6e89f418d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/null_joint_controller.py @@ -0,0 +1,116 @@ +from omnigibson.controllers import JointController +from omnigibson.utils.backend_utils import _compute_backend as cb + + +class NullJointController(JointController): + """ + Dummy Controller class for a null-type of joint control (i.e.: no control or constant pass-through control). + This class has a zero-size command space, and returns either an empty array for control if dof_idx is None + else constant values as specified by @default_command (if not specified, uses zeros) + """ + + def __init__( + self, + control_freq, + motor_type, + control_limits, + dof_idx, + command_input_limits="default", + command_output_limits="default", + isaac_kp=None, + isaac_kd=None, + default_goal=None, + pos_kp=None, + pos_damping_ratio=None, + vel_kp=None, + use_impedances=False, + ): + """ + Args: + control_freq (int): controller loop frequency + control_limits (Dict[str, Tuple[Array[float], Array[float]]]): The min/max limits to the outputted + control signal. Should specify per-dof type limits, i.e.: + + "position": [[min], [max]] + "velocity": [[min], [max]] + "effort": [[min], [max]] + "has_limit": [...bool...] + + Values outside of this range will be clipped, if the corresponding joint index in has_limit is True. + dof_idx (Array[int]): specific dof indices controlled by this controller. Used for inferring + controller-relevant values during control computations + command_input_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max acceptable inputted command. Values outside this range will be clipped. + If None, no clipping will be used. If "default", range will be set to (-1, 1) + command_output_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max scaled command. If both this value and @command_input_limits is not None, + then all inputted command values will be scaled from the input range to the output range. + If either is None, no scaling will be used. If "default", then this range will automatically be set + to the @control_limits entry corresponding to self.control_type + isaac_kp (None or float or Array[float]): If specified, stiffness gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers. + Should only be nonzero if self.control_type is position + isaac_kd (None or float or Array[float]): If specified, damping gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers + Should only be nonzero if self.control_type is position or velocity + default_goal (None or n-array): if specified, should be the same length as @dof_idx, specifying + the default joint goal for this controller to converge to + pos_kp (None or float): If @motor_type is "position" and @use_impedances=True, this is the + proportional gain applied to the joint controller. If None, a default value will be used. + pos_damping_ratio (None or float): If @motor_type is "position" and @use_impedances=True, this is the + damping ratio applied to the joint controller. If None, a default value will be used. + vel_kp (None or float): If @motor_type is "velocity" and @use_impedances=True, this is the + proportional gain applied to the joint controller. If None, a default value will be used. + use_impedances (bool): If True, will use impedances via the mass matrix to modify the desired efforts + applied + """ + # Store values + self.default_goal = cb.zeros(len(dof_idx)) if default_goal is None else cb.from_torch(default_goal) + + # Run super init + super().__init__( + control_freq=control_freq, + motor_type=motor_type, + control_limits=control_limits, + dof_idx=dof_idx, + command_input_limits=command_input_limits, + command_output_limits=command_output_limits, + isaac_kp=isaac_kp, + isaac_kd=isaac_kd, + pos_kp=pos_kp, + pos_damping_ratio=pos_damping_ratio, + vel_kp=vel_kp, + use_impedances=use_impedances, + use_delta_commands=False, + ) + + def compute_no_op_goal(self, controller_idx): + # Set the goal to be internal stored default value (``cb`` array) + return dict(target=self.default_goal) + + def _preprocess_command(self, command): + # Override super and force the processed goal to be internal stored default value + return cb.array(self.default_goal) + + def update_default_goal(self, target): + """ + Updates the internal default command value. + + Args: + target (torch.Tensor): New default command values to set for this controller. + Should be of dimension @command_dim + """ + assert ( + len(target) == self.control_dim + ), f"Default goal must be length: {self.control_dim}, got length: {len(target)}" + + self.default_goal = cb.from_torch(target) + + def _compute_no_op_command(self, controller_idx): + # Empty tensor since no action should be received + return cb.array([]) + + @property + def command_dim(self): + # Auto-generates control, so no command should be received + return 0 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/osc_controller.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/osc_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..1ad579c6b66e7702348feeb4261c95c101ca88ac --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/controllers/osc_controller.py @@ -0,0 +1,696 @@ +import math + +import numpy as np +import torch as th + +import omnigibson.utils.transform_utils as TT +import omnigibson.utils.transform_utils_np as NT +from omnigibson.controllers import ControlType, ManipulationController +from omnigibson.utils.backend_utils import _compute_backend as cb +from omnigibson.utils.backend_utils import add_compute_function +from omnigibson.utils.python_utils import assert_valid_key +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import ControllableObjectViewAPI + +# Create module logger +log = create_module_logger(module_name=__name__) + + +@th.jit.script +def _quat_multiply_batch(q1: th.Tensor, q0: th.Tensor) -> th.Tensor: + """Batched quaternion multiplication q1 * q0. Inputs are (N, 4) in (x,y,z,w) convention.""" + x0, y0, z0, w0 = q0[..., 0], q0[..., 1], q0[..., 2], q0[..., 3] + x1, y1, z1, w1 = q1[..., 0], q1[..., 1], q1[..., 2], q1[..., 3] + return th.stack( + [ + x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0, + -x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0, + x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0, + -x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0, + ], + dim=-1, + ) + + +# Different modes +OSC_MODE_COMMAND_DIMS = { + "absolute_pose": 6, # 6DOF (x,y,z,ax,ay,az) control of pose, whether both position and orientation is given in absolute coordinates + "pose_absolute_ori": 6, # 6DOF (dx,dy,dz,ax,ay,az) control over pose, where the orientation is given in absolute axis-angle coordinates + "pose_delta_ori": 6, # 6DOF (dx,dy,dz,dax,day,daz) control over pose + "position_fixed_ori": 3, # 3DOF (dx,dy,dz) control over position, with orientation commands being kept as fixed initial absolute orientation + "position_compliant_ori": 3, # 3DOF (dx,dy,dz) control over position, with orientation commands automatically being sent as 0s (so can drift over time) +} +OSC_MODES = set(OSC_MODE_COMMAND_DIMS.keys()) + + +class OperationalSpaceController(ManipulationController): + """ + Controller class to convert (delta or absolute) EEF commands into joint efforts using Operational Space Control + + This controller expects 6DOF delta commands (dx, dy, dz, dax, day, daz), where the delta orientation + commands are in axis-angle form, and outputs low-level torque commands. + + Gains may also be considered part of the action space as well. In this case, the action space would be: + ( + dx, dy, dz, dax, day, daz <-- 6DOF delta eef commands + [, kpx, kpy, kpz, kpax, kpay, kpaz] <-- kp gains + [, drx dry, drz, drax, dray, draz] <-- damping ratio gains + [, kpnx, kpny, kpnz, kpnax, kpnay, kpnaz] <-- kp null gains + ) + + Note that in this case, we ASSUME that the inputted gains are normalized to be in the range [-1, 1], and will + be mapped appropriately to their respective ranges, as defined by XX_limits + + Alternatively, parameters (in this case, kp or damping_ratio) can either be set during initialization or provided + from an external source; if the latter, the control_dict should include the respective parameter(s) as + a part of its keys + + Each controller step consists of the following: + 1. Clip + Scale inputted command according to @command_input_limits and @command_output_limits + 2. Run OSC to back out joint efforts for a desired task frame command + 3. Clips the resulting command by the motor (effort) limits + """ + + def __init__( + self, + control_freq, + reset_joint_pos, + control_limits, + dof_idx, + command_input_limits="default", + command_output_limits=((-0.2, -0.2, -0.2, -0.5, -0.5, -0.5), (0.2, 0.2, 0.2, 0.5, 0.5, 0.5)), + isaac_kp=None, + isaac_kd=None, + kp=150.0, + kp_limits=(10.0, 300.0), + damping_ratio=1.0, + damping_ratio_limits=(0.0, 2.0), + kp_null=10.0, + kp_null_limits=(0.0, 50.0), + mode="pose_delta_ori", + decouple_pos_ori=False, + workspace_pose_limiter=None, + use_gravity_compensation=False, + use_cc_compensation=True, + link_name=None, + ): + """ + Args: + control_freq (int): controller loop frequency + reset_joint_pos (Array[float]): reset joint positions, used as part of nullspace controller in IK. + Note that this should correspond to ALL the joints; the exact indices will be extracted via @dof_idx + control_limits (Dict[str, Tuple[Array[float], Array[float]]]): The min/max limits to the outputted + control signal. Should specify per-dof type limits, i.e.: + + "position": [[min], [max]] + "velocity": [[min], [max]] + "effort": [[min], [max]] + "has_limit": [...bool...] + + Values outside of this range will be clipped, if the corresponding joint index in has_limit is True. + dof_idx (Array[int]): specific dof indices controlled by this robot. Used for inferring + controller-relevant values during control computations + command_input_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max acceptable inputted command. Values outside this range will be clipped. + If None, no clipping will be used. If "default", range will be set to (-1, 1) + command_output_limits (None or "default" or Tuple[float, float] or Tuple[Array[float], Array[float]]): + if set, is the min/max scaled command. If both this value and @command_input_limits is not None, + then all inputted command values will be scaled from the input range to the output range. + If either is None, no scaling will be used. If "default", then this range will automatically be set + to the @control_limits entry corresponding to self.control_type + isaac_kp (None or float or Array[float]): If specified, stiffness gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers. + Should only be nonzero if self.control_type is position + isaac_kd (None or float or Array[float]): If specified, damping gains to apply to the underlying + isaac DOFs. Can either be a single number or a per-DOF set of numbers + Should only be nonzero if self.control_type is position or velocity + kp (None, int, float, or array): Gain values to apply to 6DOF error. + If None, will be variable (part of action space) + kp_limits (2-array): (min, max) values of kp + damping_ratio (None, int, float, or array): Damping ratio to apply to 6DOF error controller gain + If None, will be variable (part of action space) + damping_ratio_limits (2-array): (min, max) values of damping ratio + kp_null (None, int, float, or array): Gain applied when calculating null torques + If None, will be variable (part of action space) + kp_null_limits (2-array): (min, max) values of kp_null + mode (str): mode to use when computing IK. In all cases, position commands are 3DOF delta (dx,dy,dz) + cartesian values, relative to the robot base frame. Valid options are: + - "pose_absolute_ori": 6DOF (dx,dy,dz,ax,ay,az) control over pose, + where the orientation is given in absolute axis-angle coordinates + - "pose_delta_ori": 6DOF (dx,dy,dz,dax,day,daz) control over pose + - "position_fixed_ori": 3DOF (dx,dy,dz) control over position, + with orientation commands being kept as fixed initial absolute orientation + - "position_compliant_ori": 3DOF (dx,dy,dz) control over position, + with orientation commands automatically being sent as 0s (so can drift over time) + decouple_pos_ori (bool): Whether to decouple position and orientation control or not + workspace_pose_limiter (None or function): if specified, callback method that should clip absolute + target (x,y,z) cartesian position and absolute quaternion orientation (x,y,z,w) to a specific workspace + range (i.e.: this can be unique to each robot, and implemented by each embodiment). + Function signature should be: + + def limiter(target_pos: Array[float], target_quat: Array[float]) --> Tuple[Array[float], Array[float]] + + where target_pos is (x,y,z) cartesian position values, target_quat is (x,y,z,w) quarternion orientation + values, and the returned tuple is the processed (pos, quat) command. + use_gravity_compensation (bool): If True, will add gravity compensation to the computed efforts. This is + an experimental feature that only works on fixed base robots. We do not recommend enabling this. + use_cc_compensation (bool): If True, will add Coriolis / centrifugal compensation to the computed efforts. + link_name (str or None): name of eef or trunk link + """ + # Store arguments + control_dim = len(dof_idx) + self._use_gravity_compensation = use_gravity_compensation + self._use_cc_compensation = use_cc_compensation + + # Warn the user about gravity compensation and Coriolis / centrifugal compensation being experimental. + if self._use_gravity_compensation: + log.warning( + "OperationalSpaceController is using gravity compensation. This is an experimental feature that only works on " + "fixed base robots. We do not recommend enabling this." + ) + + # Store gains for direct use in the solver + self.kp = self.nums2array(nums=kp, dim=6) if kp is not None else None + self.damping_ratio = damping_ratio + self.kp_null = self.nums2array(nums=kp_null, dim=control_dim) if kp_null is not None else None + self.kd_null = 2 * cb.sqrt(self.kp_null) if kp_null is not None else None # critically damped + self.kp_limits = cb.array(list(kp_limits)) + self.damping_ratio_limits = cb.array(list(damping_ratio_limits)) + self.kp_null_limits = cb.array(list(kp_null_limits)) + + # Store settings for whether we're learning gains or not + self.variable_kp = self.kp is None + self.variable_damping_ratio = self.damping_ratio is None + self.variable_kp_null = self.kp_null is None + + # TODO: Add support for variable gains -- for now, just raise an error + assert True not in { + self.variable_kp, + self.variable_damping_ratio, + self.variable_kp_null, + }, "Variable gains with OSC is not supported yet!" + + # If the mode is set as absolute orientation and using default config, + # change input and output limits accordingly. + # By default, the input limits are set as 1, so we modify this to have a correct range. + # The output orientation limits are also set to be values assuming delta commands, so those are updated too + assert_valid_key(key=mode, valid_keys=OSC_MODES, name="OSC mode") + + # If mode is absolute pose, make sure command input limits / output limits are None + if mode == "absolute_pose": + assert command_input_limits is None, "command_input_limits should be None if using absolute_pose mode!" + assert command_output_limits is None, "command_output_limits should be None if using absolute_pose mode!" + + self.mode = mode + if self.mode == "pose_absolute_ori": + if command_input_limits is not None: + if type(command_input_limits) is str and command_input_limits == "default": + command_input_limits = [ + [-1.0, -1.0, -1.0, -math.pi, -math.pi, -math.pi], + [1.0, 1.0, 1.0, math.pi, math.pi, math.pi], + ] + else: + command_input_limits[0][3:] = -math.pi + command_input_limits[1][3:] = math.pi + if command_output_limits is not None: + if type(command_output_limits) is str and command_output_limits == "default": + command_output_limits = [ + [-1.0, -1.0, -1.0, -math.pi, -math.pi, -math.pi], + [1.0, 1.0, 1.0, math.pi, math.pi, math.pi], + ] + else: + command_output_limits[0][3:] = -math.pi + command_output_limits[1][3:] = math.pi + + is_input_limits_numeric = not (command_input_limits is None or isinstance(command_input_limits, str)) + is_output_limits_numeric = not (command_output_limits is None or isinstance(command_output_limits, str)) + command_input_limits = ( + [self.nums2array(lim, dim=6) for lim in command_input_limits] + if is_input_limits_numeric + else command_input_limits + ) + command_output_limits = ( + [self.nums2array(lim, dim=6) for lim in command_output_limits] + if is_output_limits_numeric + else command_output_limits + ) + + # Modify input / output scaling based on whether we expect gains to be part of the action space + self._command_dim = OSC_MODE_COMMAND_DIMS[self.mode] + for variable_gain, gain_limits, dim in zip( + (self.variable_kp, self.variable_damping_ratio, self.variable_kp_null), + (self.kp_limits, self.damping_ratio_limits, self.kp_null_limits), + (6, 6, control_dim), + ): + if variable_gain: + # Add this to input / output limits + if is_input_limits_numeric: + command_input_limits = [ + cb.cat([lim, self.nums2array(nums=val, dim=dim)]) + for lim, val in zip(command_input_limits, (-1, 1)) + ] + if is_output_limits_numeric: + command_output_limits = [ + cb.cat([lim, self.nums2array(nums=val, dim=dim)]) + for lim, val in zip(command_output_limits, gain_limits) + ] + # Update command dim + self._command_dim += dim + + # Other values + self.decouple_pos_ori = decouple_pos_ori + self.workspace_pose_limiter = workspace_pose_limiter + self.reset_joint_pos = cb.array(reset_joint_pos[dof_idx]) + + # member state that will be filled in at runtime + self._link_name = link_name # eef/trunk link name (same for all members in the group) + self._fixed_quat_targets = [] # per-member fixed quat target for position_fixed_ori mode + + # Run super init + super().__init__( + control_freq=control_freq, + control_limits=control_limits, + dof_idx=dof_idx, + command_input_limits=command_input_limits, + command_output_limits=command_output_limits, + isaac_kp=isaac_kp, + isaac_kd=isaac_kd, + ) + + def add_member(self, articulation_root_path, control_enabled=True): + """ + Register a member and store its EEF link name. + + Reuses a tombstoned slot when available (tombstone reuse is handled by the base class). + + Args: + articulation_root_path (str): articulation root prim path of the new group member + + Returns: + int: controller_idx + """ + idx = super().add_member(articulation_root_path, control_enabled=control_enabled) + if idx < len(self._fixed_quat_targets): + # Reusing a tombstoned slot — reset the fixed orientation target + self._fixed_quat_targets[idx] = None + else: + self._fixed_quat_targets.append(None) + return idx + + def reset(self, controller_idx): + # Call super first + super().reset(controller_idx) + + # Clear internal variables + self._fixed_quat_targets[controller_idx] = None + self._clear_variable_gains() + + def _load_state(self, controller_idx, state): + # Run super first + super()._load_state(controller_idx=controller_idx, state=state) + + # Restore per-member fixed orientation targets from loaded goals. + if self.mode == "position_fixed_ori": + if cb.item_bool(self._goal_set[controller_idx]): + self._fixed_quat_targets[controller_idx] = cb.T.mat2quat(self._goals["target_ori_mat"][controller_idx]) + + def _clear_variable_gains(self): + """ + Helper function to clear any gains that are variable and considered part of actions + """ + if self.variable_kp: + self.kp = None + if self.variable_damping_ratio: + self.damping_ratio = None + if self.variable_kp_null: + self.kp_null = None + self.kd_null = None + + def _update_variable_gains(self, gains): + """ + Helper function to update any gains that are variable and considered part of actions + + Args: + gains (n-array): array where n dim is parsed based on which gains are being learned + """ + idx = 0 + if self.variable_kp: + self.kp = gains[:, idx : idx + 6] + idx += 6 + if self.variable_damping_ratio: + self.damping_ratio = gains[:, idx : idx + 6] + idx += 6 + if self.variable_kp_null: + self.kp_null = gains[:, idx : idx + self.control_dim] + self.kd_null = 2 * cb.sqrt(self.kp_null) # critically damped + idx += self.control_dim + + def _update_goal(self, controller_idx, command): + """ + Updates the internal goal (ee pos and ee ori mat) based on the inputted delta command + + Args: + command (n-array): Preprocessed command + controller_idx (int): idx of the controller that need to update goal + + Returns: + dict: ``target_pos`` and ``target_ori_mat`` as compute-backend (``cb``) arrays + """ + prim_path = self._articulation_root_paths[controller_idx] + link_name = self._link_name + + # Get current EEF pose + pos_relative, quat_relative = ControllableObjectViewAPI.get_link_relative_position_orientation( + prim_path, link_name + ) + + # Convert position command to absolute values if needed + if self.mode == "absolute_pose": + target_pos = command[:3] + else: + dpos = command[:3] + target_pos = pos_relative + dpos + + # Compute orientation + if self.mode == "position_fixed_ori": + # We need to grab the current robot orientation as the commanded orientation if there is none saved + if self._fixed_quat_targets[controller_idx] is None: + self._fixed_quat_targets[controller_idx] = ( + cb.copy(quat_relative) + if not cb.item_bool(self._goal_set[controller_idx]) + else cb.T.mat2quat(self._goals["target_ori_mat"][controller_idx]) + ) + target_quat = self._fixed_quat_targets[controller_idx] + elif self.mode == "position_compliant_ori": + # Target quat is simply the current robot orientation + target_quat = quat_relative + elif self.mode == "pose_absolute_ori" or self.mode == "absolute_pose": + # Received "delta" ori is in fact the desired absolute orientation + target_quat = cb.T.axisangle2quat(command[3:6]) + else: # pose_delta_ori control + # Grab dori and compute target ori + dori = cb.T.quat2mat(cb.T.axisangle2quat(command[3:6])) + target_quat = cb.T.mat2quat(dori @ cb.T.quat2mat(quat_relative)) + + # Possibly limit to workspace if specified + if self.workspace_pose_limiter is not None: + target_pos, target_quat = self.workspace_pose_limiter(target_pos, target_quat) + + gains = None # TODO! command[OSC_MODE_COMMAND_DIMS[self.mode]:] + if gains is not None: + self._update_variable_gains(gains=gains) + + # Set goals and return + return dict( + target_pos=target_pos, + target_ori_mat=cb.T.quat2mat(target_quat), + ) + + def compute_control(self, goals): + """ + Computes low-level torque controls for all N group members using internal EEF goal pos/ori. + + Args: + goals (Dict[str, Array]): batched goals with shape (N, *shape) per key. + Must include: + target_pos: (N, 3) desired EEF positions + target_ori_mat: (N, 3, 3) desired EEF orientation matrices + + Returns: + Array: (N, control_dim) low-level effort control actions + """ + link_name = self._link_name + rows = self.view_row_indices + + kp = self.kp # (6,) + kd = 2 * cb.sqrt(kp) * self.damping_ratio # (6,) + + # Batched joint state reads — convert from Isaac (torch) to compute backend type + all_q = ControllableObjectViewAPI.get_all_joint_positions(self.routing_path) # (N_view, n_joint_dof) + q_all = all_q[rows, :][:, self.dof_idx] # (N, ctrl_dim) + qd_all = ControllableObjectViewAPI.get_all_joint_velocities(self.routing_path, estimate=True)[rows, :][ + :, self.dof_idx + ] # (N, ctrl_dim) + + # Batched mass matrix: slice to (N, ctrl_dim, ctrl_dim) + all_mm_full = ControllableObjectViewAPI.get_all_generalized_mass_matrices( + self.routing_path + ) # (N_view, n_dof_total, n_dof_total) + mm_col_offset = all_mm_full.shape[-1] - all_q.shape[-1] + mm_dof_idx = self.dof_idx + mm_col_offset + mm_dof_idx_arr = cb.int_array(mm_dof_idx) + dof_idxs_mat = cb.meshgrid(mm_dof_idx_arr, mm_dof_idx_arr) + mm_all = all_mm_full[rows, :, :][:, dof_idxs_mat[0], dof_idxs_mat[1]] # (N, ctrl_dim, ctrl_dim) + + # Batched jacobians + jac_all = ControllableObjectViewAPI.get_all_relative_jacobians( + self.routing_path + ) # (N_view, n_links, 6, n_dof_total) + eef_body_idx = ControllableObjectViewAPI.get_link_index(self.routing_path, link_name) + jac_row = eef_body_idx - 1 # Jacobian excludes root body (index 0) + jac_col_offset = jac_all.shape[-1] - all_q.shape[-1] + jac_dof_idx = self.dof_idx + jac_col_offset + j_eef_all = jac_all[rows][:, jac_row, :, :][:, :, jac_dof_idx] # (N, 6, ctrl_dim) + + # Batched EEF pose and velocities + ee_pos_all, ee_quat_all = ControllableObjectViewAPI.get_all_link_relative_position_orientation( + self.routing_path, link_name + ) # (N_view, 3), (N_view, 4) + ee_pos_all = ee_pos_all[rows] + ee_quat_all = ee_quat_all[rows] + ee_mat_all = cb.T.quat2mat(ee_quat_all) # (N, 3, 3) + ee_lin_vel_all = ControllableObjectViewAPI.get_all_link_relative_linear_velocity( + self.routing_path, link_name, estimate=True + )[rows] # (N, 3) + ee_ang_vel_all = ControllableObjectViewAPI.get_all_link_relative_angular_velocity( + self.routing_path, link_name, estimate=True + )[rows] # (N, 3) + base_lin_vel_all = ControllableObjectViewAPI.get_all_relative_linear_velocity(self.routing_path, estimate=True)[ + rows + ] # (N, 3) + base_ang_vel_all = ControllableObjectViewAPI.get_all_relative_angular_velocity( + self.routing_path, estimate=True + )[rows] # (N, 3) + + # Batched angular velocity error + ee_ang_vel_err_all = cb.T.quat2axisangle( + cb.T.quat_multiply( + cb.T.axisangle2quat(-ee_ang_vel_all), + cb.T.axisangle2quat(base_ang_vel_all), + ) + ) # (N, 3) + + # Add leading dim (1, *) — broadcasts over N in the batch solver + kp_batch = cb.view(kp, (1, -1)) + kd_batch = cb.view(kd, (1, -1)) + kp_null_batch = cb.view(self.kp_null, (1, -1)) + kd_null_batch = cb.view(self.kd_null, (1, -1)) + rest_qpos_batch = cb.view(self.reset_joint_pos, (1, -1)) + + u = cb.get_custom_method("compute_osc_torques_batch")( + q=q_all, + qd=qd_all, + mm=mm_all, + j_eef=j_eef_all, + ee_pos=ee_pos_all, + ee_mat=ee_mat_all, + ee_lin_vel=ee_lin_vel_all, + ee_ang_vel_err=ee_ang_vel_err_all, + goal_pos=goals["target_pos"], + goal_ori_mat=goals["target_ori_mat"], + kp=kp_batch, + kd=kd_batch, + kp_null=kp_null_batch, + kd_null=kd_null_batch, + rest_qpos=rest_qpos_batch, + control_dim=self.control_dim, + decouple_pos_ori=self.decouple_pos_ori, + base_lin_vel=base_lin_vel_all, + base_ang_vel=base_ang_vel_all, + ) # (N, ctrl_dim) + + if self._use_gravity_compensation: + all_gravity = ControllableObjectViewAPI.get_all_gravity_compensation_forces(self.routing_path) + gravity_col_offset = all_gravity.shape[-1] - all_q.shape[-1] + gravity_dof_idx = self.dof_idx + gravity_col_offset + u = u + all_gravity[rows][:, gravity_dof_idx] + + if self._use_cc_compensation: + all_cc = ControllableObjectViewAPI.get_all_coriolis_and_centrifugal_compensation_forces(self.routing_path) + cc_col_offset = all_cc.shape[-1] - all_q.shape[-1] + cc_dof_idx = self.dof_idx + cc_col_offset + u = u + all_cc[rows][:, cc_dof_idx] + + return u + + def compute_no_op_goal(self, controller_idx): + """ + Returns: + dict: Current EEF pose as ``cb`` arrays (``target_pos``, ``target_ori_mat``). + """ + # No-op is maintaining current pose + prim_path = self._articulation_root_paths[controller_idx] + link_name = self._link_name + + target_pos, target_quat = ControllableObjectViewAPI.get_link_relative_position_orientation(prim_path, link_name) + + # Convert quat into eef ori mat + return dict( + target_pos=cb.copy(target_pos), + target_ori_mat=cb.T.quat2mat(target_quat), + ) + + def _compute_no_op_command(self, controller_idx): + prim_path = self._articulation_root_paths[controller_idx] + link_name = self._link_name + + pos_relative, quat_relative = ControllableObjectViewAPI.get_link_relative_position_orientation( + prim_path, link_name + ) + + command = cb.zeros(6) + + # Handle position + if self.mode == "absolute_pose": + command[:3] = pos_relative + else: + # We can leave it as zero for delta mode. + pass + + # Handle orientation + if self.mode in ("pose_absolute_ori", "absolute_pose"): + command[3:] = cb.T.quat2axisangle(quat_relative) + else: + # For these modes, we don't need to add orientation to the command + pass + + return command + + def _get_goal_shapes(self): + return dict( + target_pos=(3,), + target_ori_mat=(3, 3), + ) + + @property + def control_type(self): + return ControlType.EFFORT + + @property + def command_dim(self): + return self._command_dim + + +def _compute_osc_torques_batch_torch( + q: th.Tensor, + qd: th.Tensor, + mm: th.Tensor, + j_eef: th.Tensor, + ee_pos: th.Tensor, + ee_mat: th.Tensor, + ee_lin_vel: th.Tensor, + ee_ang_vel_err: th.Tensor, + goal_pos: th.Tensor, + goal_ori_mat: th.Tensor, + kp: th.Tensor, + kd: th.Tensor, + kp_null: th.Tensor, + kd_null: th.Tensor, + rest_qpos: th.Tensor, + control_dim: int, + decouple_pos_ori: bool, + base_lin_vel: th.Tensor, + base_ang_vel: th.Tensor, +): + mm_inv = th.linalg.inv(mm) + pos_err = goal_pos - ee_pos + ori_err = TT.orientation_error(goal_ori_mat, ee_mat) + lin_vel_err = base_lin_vel + th.linalg.cross(base_ang_vel, ee_pos) - ee_lin_vel + vel_err = th.cat([lin_vel_err, ee_ang_vel_err], dim=-1) + task_err = th.cat([pos_err, ori_err], dim=-1) + err = (kp * task_err + kd * vel_err).unsqueeze(-1) + j_eef_T = j_eef.transpose(-2, -1) + + if decouple_pos_ori: + j_pos = j_eef[:, :3, :] + j_ori = j_eef[:, 3:, :] + m_eef_pos = th.linalg.inv(j_pos @ mm_inv @ j_pos.transpose(-2, -1)) + m_eef_ori = th.linalg.inv(j_ori @ mm_inv @ j_ori.transpose(-2, -1)) + wrench = th.cat([m_eef_pos @ err[:, :3, :], m_eef_ori @ err[:, 3:, :]], dim=1) + m_eef = th.linalg.inv(j_eef @ mm_inv @ j_eef_T) + else: + m_eef = th.linalg.inv(j_eef @ mm_inv @ j_eef_T) + wrench = m_eef @ err + + u = j_eef_T @ wrench + + j_eef_inv = m_eef @ j_eef @ mm_inv + angle_diff = (rest_qpos - q + math.pi) % (2 * math.pi) - math.pi + u_null = (kd_null * (-qd) + kp_null * angle_diff).unsqueeze(-1) + u_null = mm @ u_null + eye = th.eye(control_dim, dtype=th.float32).unsqueeze(0) + nullspace_proj = eye - j_eef_T @ j_eef_inv + u = u + nullspace_proj @ u_null + + return u.squeeze(-1) + + +def _compute_osc_torques_batch_numpy( + q, + qd, + mm, + j_eef, + ee_pos, + ee_mat, + ee_lin_vel, + ee_ang_vel_err, + goal_pos, + goal_ori_mat, + kp, + kd, + kp_null, + kd_null, + rest_qpos, + control_dim, + decouple_pos_ori, + base_lin_vel, + base_ang_vel, +): + mm_inv = np.linalg.inv(mm) + pos_err = goal_pos - ee_pos + ori_err = NT.orientation_error(goal_ori_mat, ee_mat).astype(np.float32) + lin_vel_err = base_lin_vel + np.cross(base_ang_vel, ee_pos) - ee_lin_vel + vel_err = np.concatenate([lin_vel_err, ee_ang_vel_err], axis=-1) + task_err = np.concatenate([pos_err, ori_err], axis=-1) + err = np.expand_dims(kp * task_err + kd * vel_err, axis=-1) + j_eef_T = np.swapaxes(j_eef, -2, -1) + + if decouple_pos_ori: + j_pos = j_eef[:, :3, :] + j_ori = j_eef[:, 3:, :] + m_eef_pos = np.linalg.inv(j_pos @ mm_inv @ np.swapaxes(j_pos, -2, -1)) + m_eef_ori = np.linalg.inv(j_ori @ mm_inv @ np.swapaxes(j_ori, -2, -1)) + wrench = np.concatenate([m_eef_pos @ err[:, :3, :], m_eef_ori @ err[:, 3:, :]], axis=1) + m_eef = np.linalg.inv(j_eef @ mm_inv @ j_eef_T) + else: + m_eef = np.linalg.inv(j_eef @ mm_inv @ j_eef_T) + wrench = m_eef @ err + + u = j_eef_T @ wrench + + j_eef_inv = m_eef @ j_eef @ mm_inv + angle_diff = (rest_qpos - q + math.pi) % (2 * math.pi) - math.pi + u_null = np.expand_dims(kd_null * (-qd) + kp_null * angle_diff, axis=-1) + u_null = mm @ u_null + eye = np.eye(control_dim, dtype=np.float32)[None] + nullspace_proj = eye - j_eef_T @ j_eef_inv + u = u + nullspace_proj @ u_null + + return u[..., 0] + + +add_compute_function( + name="compute_osc_torques_batch", + np_function=_compute_osc_torques_batch_numpy, + th_function=_compute_osc_torques_batch_torch, +) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a656669dabb81a60ea4c6c720f8b022a34ed4f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/__init__.py @@ -0,0 +1,22 @@ +from omnigibson.envs.data_wrapper import DataWrapper, DataPlaybackWrapper +from omnigibson.envs.hdf5_data_wrapper import HDF5CollectionWrapper, HDF5PlaybackWrapper +from omnigibson.envs.lerobot_data_wrapper import LeRobotDataWrapper, LeRobotPlaybackWrapper +from omnigibson.envs.metrics_wrapper import MetricsWrapper +from omnigibson.metrics.metric_base import MetricBase +from omnigibson.envs.env_base import Environment +from omnigibson.envs.env_wrapper import REGISTERED_ENV_WRAPPERS, EnvironmentWrapper, create_wrapper + +__all__ = [ + "create_wrapper", + "DataWrapper", + "DataPlaybackWrapper", + "HDF5CollectionWrapper", + "HDF5PlaybackWrapper", + "LeRobotDataWrapper", + "LeRobotPlaybackWrapper", + "MetricsWrapper", + "MetricBase", + "Environment", + "EnvironmentWrapper", + "REGISTERED_ENV_WRAPPERS", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/data_wrapper.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/data_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..55b68b8f4185e05eab52768ed27a801196039765 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/data_wrapper.py @@ -0,0 +1,909 @@ +import h5py +import numpy as np +import json +import logging +import os +import torch as th +from typing import Any, Callable + +import omnigibson as og +from omnigibson.controllers import ControllerView, ControlType +from omnigibson.envs.env_base import Environment +from omnigibson.envs.env_wrapper import EnvironmentWrapper, create_wrapper +from omnigibson.eval.utils.obs_utils import create_video_writer, write_video +from omnigibson.macros import gm, macros +from omnigibson.systems.macro_particle_system import MacroPhysicalParticleSystem +from omnigibson.utils.data_utils import merge_scene_files +from omnigibson.utils.python_utils import create_object_from_init_info, h5py_group_to_torch +from omnigibson.utils.ui_utils import create_module_logger + +# Create module logger +log = create_module_logger(module_name=__name__) +log.setLevel(logging.INFO) + + +def _is_system_particle_template_info(obj_info: dict, system_names: set[str]) -> bool: + args = obj_info.get("args", {}) + category = args.get("category") + return ( + category in system_names + and args.get("name") == f"{category}_template" + and args.get("relative_prim_path") == f"/{category}/template" + ) + + +def _is_system_particle_template_name(obj_name: str, system_names: set[str]) -> bool: + return any(obj_name == f"{system_name}_template" for system_name in system_names) + + +def _align_scene_object_states_with_recorded_schema(scene, recorded_scene_file: dict) -> None: + """Tells each object which non-kinematic states the demo saved for it, and in what order. + + Reading a frame back walks the saved numbers in that order, so it has to follow the recording + rather than whatever states the current code gives the object. + """ + state = recorded_scene_file.get("state", {}) + object_registry_state = ( + state.get("registry", {}).get("object_registry", {}) + if "registry" in state + else state.get("object_registry", {}) + ) + + for obj_name, recorded_obj_state in object_registry_state.items(): + obj = scene.object_registry("name", obj_name, None) + if obj is None or obj.states is None: + continue + + recorded_names = tuple(recorded_obj_state.get("non_kin", {})) + obj._recorded_non_kin_state_names = set(recorded_names) + obj._recorded_non_kin_state_order = recorded_names + + +def _add_recorded_non_kin_states_to_scene_file(scene_file: dict, recorded_scene_files: list[dict]) -> None: + """Passes each object the list of non-kinematic states the recording saved for it, as a + constructor arg. + + Which states an object gets is decided by its synset abilities, which may have changed since the + demo was recorded; without this list an object can be built without a state that every saved + frame still contains. Edits @scene_file in place. If several demos share one environment, each + object gets the combined list from all of them, ordered by where each name first appears. + """ + init_info = scene_file["objects_info"]["init_info"] + names_by_object = {} + for recorded_scene_file in recorded_scene_files: + state = recorded_scene_file.get("state", {}) + object_registry_state = ( + state.get("registry", {}).get("object_registry", {}) + if "registry" in state + else state.get("object_registry", {}) + ) + for obj_name, recorded_obj_state in object_registry_state.items(): + ordered_names = names_by_object.setdefault(obj_name, []) + for state_name in recorded_obj_state.get("non_kin", {}): + if state_name not in ordered_names: + ordered_names.append(state_name) + + for obj_name, state_names in names_by_object.items(): + if obj_name not in init_info: + raise ValueError( + f"Recorded state schema names object {obj_name!r}, but that object has no init_info " + "in the replay scene file." + ) + init_info[obj_name].setdefault("args", {})["recorded_non_kin_state_names"] = state_names + + +def _recorded_non_kin_state_name_union(recorded_scene_file: dict) -> set[str] | None: + """Returns every non-kinematic state name that appears anywhere in one demo, pooled across all + its objects. + + Each frame is one flat array of numbers, read back one object and one state at a time, so an + object that expects a state the recording never saved eats the numbers meant for whatever comes + next, and everything after it is off by that much. Objects created mid-episode (e.g. the halves + left by slicing) are not in the recorded scene file, so their own list is unknown; this pooled + list is the safe stand-in, because a name missing from it was never saved for anything. + Returns None if the recording has no per-object state at all. + """ + state = recorded_scene_file.get("state", {}) + object_registry_state = ( + state.get("registry", {}).get("object_registry", {}) + if "registry" in state + else state.get("object_registry", {}) + ) + if not object_registry_state: + return None + + names: set[str] = set() + for recorded_obj_state in object_registry_state.values(): + names.update(recorded_obj_state.get("non_kin", {})) + return names + + +class DataWrapper(EnvironmentWrapper): + """ + An OmniGibson environment wrapper for writing data to a dataset file. + """ + + def __init__( + self, + env: Environment, + output_path: str, + overwrite: bool = True, + only_successes: bool = True, + flush_every_n_traj: int = 10, + ) -> None: + """ + Args: + env (Environment): The environment to wrap + output_path (str): path to store data file + overwrite (bool): If set, will overwrite any pre-existing data found at @output_path. + Otherwise, will load the data and append to it + only_successes (bool): Whether to only save successful episodes + flush_every_n_traj (int): How often to flush (write) current data to file + + Note: + ``self._fps`` is only initialized from ``env.env_config["rendering_frequency"]`` if it does not + already exist. This allows subclasses (e.g. playback wrappers) to set an FPS sourced from recorded + dataset metadata before calling ``super().__init__``. + """ + # Make sure the wrapped environment inherits correct omnigibson format + assert isinstance( + env, (Environment, EnvironmentWrapper) + ), "Expected wrapped @env to be a subclass of OmniGibson's Environment class or EnvironmentWrapper!" + + # DataWrapper is single-env only: create_dataset, step, and trajectory-processing + # all assume one env's worth of state/obs/rewards at a time. + assert env.num_envs == 1, f"DataWrapper is single-env only; got num_envs={env.num_envs}." + + self.traj_count = 0 + self.step_count = 0 + self.only_successes = only_successes + self.flush_every_n_traj = flush_every_n_traj + self.current_obs = None + self.current_traj_history = [] + + if not hasattr(self, "_fps"): + self._fps = int(env.env_config["rendering_frequency"]) + + # Create dataset + self.create_dataset(output_path, env, overwrite=overwrite) + + # Run super + super().__init__(env=env) + + def create_dataset(self, output_path: str, env: Environment, overwrite: bool = True) -> None: + """ + Creates a dataset at @output_path, possibly overwriting it if @overwrite is set + + Args: + output_path (str): path to store data. May be either directory or filepath depending on the + dataset type + env (Environment): The wrapped environment + overwrite (bool): Whether to overwrite any pre-existing data or not + """ + raise NotImplementedError + + @property + def fps(self) -> int: + """ + Returns: + int: Frames per second used by this wrapper. + """ + return self._fps + + def step(self, action: th.Tensor | dict, n_render_iterations: int = 1) -> tuple[dict, float, bool, bool, dict]: + """ + Run the environment step() function and collect data + + Args: + action (th.Tensor | dict): action to take in environment + n_render_iterations (int): Number of rendering iterations to use before returning observations + + Returns: + 5-tuple: + - dict: state, i.e. next observation + - float: reward, i.e. reward at this current timestep + - bool: terminated, i.e. whether this episode ended due to a failure or success + - bool: truncated, i.e. whether this episode ended due to a time limit etc. + - dict: info, i.e. dictionary with any useful information + """ + # Make sure actions are always flattened numpy arrays + if isinstance(action, dict): + action = th.cat([act for act in action.values()]) + + obs_list, rewards, terminateds, truncateds, infos = self.env.step( + action, n_render_iterations=n_render_iterations + ) + self.step_count += 1 + + next_obs = obs_list[0] + reward = rewards[0].item() + terminated = terminateds[0].item() + truncated = truncateds[0].item() + info = infos[0] + + self._record_step_trajectory(action, next_obs, reward, terminated, truncated, info) + + return next_obs, reward, terminated, truncated, info + + def _record_step_trajectory( + self, action: th.Tensor, obs: dict, reward: float, terminated: bool, truncated: bool, info: dict + ) -> None: + """ + Record the current step data to the trajectory history + + Args: + action (th.Tensor): action deployed resulting in @obs + obs (dict): state, i.e. observation + reward (float): reward, i.e. reward at this current timestep + terminated (bool): terminated, i.e. whether this episode ended due to a failure or success + truncated (bool): truncated, i.e. whether this episode ended due to a time limit etc. + info (dict): info, i.e. dictionary with any useful information + """ + # Aggregate step data + step_data = self._parse_step_data(action, obs, reward, terminated, truncated, info) + + # Update obs and traj history + self.current_traj_history.append(step_data) + self.current_obs = obs + + def _parse_step_data( + self, action: th.Tensor, obs: dict, reward: float, terminated: bool, truncated: bool, info: dict + ) -> dict: + """ + Parse the output from the internal self.env.step() call and write relevant data to record to a dictionary + + Args: + action (th.Tensor): action deployed resulting in @obs + obs (dict): state, i.e. observation + reward (float): reward, i.e. reward at this current timestep + terminated (bool): terminated, i.e. whether this episode ended due to a failure or success + truncated (bool): truncated, i.e. whether this episode ended due to a time limit etc. + info (dict): info, i.e. dictionary with any useful information + + Returns: + dict: Keyword-mapped data that should be recorded in the dataset. + """ + raise NotImplementedError() + + def _process_obs(self, obs: dict, info: dict) -> dict: + """ + Pre-process the raw observation data from the environment into the desired format for storing in the dataset. + """ + # Default is no-op + return obs + + def reset(self) -> tuple[dict, dict]: + """ + Run the environment reset() function and flush data + + Returns: + 2-tuple: + - dict: Environment observation space after reset occurs + - dict: Information related to observation metadata + """ + if len(self.current_traj_history) > 0: + self.flush_current_traj() + + obs_list, info = self.env.reset() + self.current_obs = obs_list[0] + # Store initial obs as the first entry in the trajectory + self.current_traj_history.append({"obs": self._process_obs(self.current_obs, info)}) + + return self.current_obs, info + + def process_traj_to_dataset(self, traj_data: list[dict]) -> Any: + """ + Process the given trajectory data and write it to the dataset. + This is called at the end of every episode for any trajectories that should be saved, + and is where the logic for how trajectory data should be stored in the dataset should be implemented. + + Args: + traj_data (list of dict): Trajectory data, where each entry is a keyword-mapped set of data for a single + sim step + """ + raise NotImplementedError() + + @property + def should_save_current_episode(self) -> bool: + """ + Returns: + bool: Whether the current episode should be saved or discarded + """ + # Only save successful demos and if actually recording, + # or there's only one observation in the trajectory (i.e. the initial obs after reset). + # Single-env data wrapper: index task.success (now a (num_envs,) bool tensor) at scene 0. + return (bool(self.env.task.success[0]) or not self.only_successes) and not ( + len(self.current_traj_history) == 1 and set(self.current_traj_history[0].keys()) == {"obs"} + ) + + def flush_current_traj(self) -> None: + """ + Flush current trajectory data + """ + # Only save successful demos and if actually recording + if self.should_save_current_episode: + self.process_traj_to_dataset(self.current_traj_history) + self.traj_count += 1 + + # Potentially write to disk + if self.traj_count % self.flush_every_n_traj == 0: + self.flush_current_file() + else: + # Remove this demo + self.step_count -= len(self.current_traj_history) + + # Clear trajectory and transition buffers + self.current_traj_history = [] + + def flush_current_file(self) -> None: + raise NotImplementedError + + def save_data(self) -> None: + """ + Flushes any remaining data and saves the dataset to disk + """ + if len(self.current_traj_history) > 0: + self.flush_current_traj() + + self.close_dataset() + + def close_dataset(self) -> None: + """ + Closes the active dataset, if open + """ + raise NotImplementedError + + +class DataPlaybackWrapper(DataWrapper): + """ + An OmniGibson environment wrapper for playing back data and collecting observations. + + NOTE: This assumes a HDF5CollectionWrapper environment has been used to collect data! + """ + + @classmethod + def create_from_hdf5( + cls, + input_path: str, + output_path: str, + robot_obs_modalities: tuple[str, ...] = tuple(), + robot_proprio_keys: list[str] | None = None, + robot_sensor_config: dict[str, Any] | None = None, + external_sensors_config: list[dict[str, Any]] | None = None, + include_sensor_names: list[str] | None = None, + exclude_sensor_names: list[str] | None = None, + n_render_iterations: int = 1, + overwrite: bool = True, + only_successes: bool = False, + flush_every_n_traj: int = 10, + flush_every_n_steps: int = 0, + include_env_wrapper: bool = False, + additional_wrapper_configs: list[dict[str, Any]] | None = None, + full_scene_file: str | None = None, + include_task: bool = True, + include_task_obs: bool = True, + include_robot_control: bool = True, + include_contacts: bool = True, + load_room_instances: list[str] | None = None, + **kwargs, + ) -> "DataPlaybackWrapper": + """ + Create a DataPlaybackWrapper environment instance form the recorded demonstration info + from @hdf5_path, and aggregate observation_modalities @obs during playback + + Args: + input_path (str): Absolute path to the input hdf5 file containing the relevant collected data to playback + output_path (str): Absolute path to the output hdf5 file that will contain the recorded observations from + the replayed data + robot_obs_modalities (list): Robot observation modalities to use. This list is directly passed into + the robot_cfg (`obs_modalities` kwarg) when spawning the robot. + This will be the default value for robot sensors if not specified in @robot_sensor_config. + robot_proprio_keys (None or list of str): If specified, a list of proprioception keys to use for the robot. + robot_sensor_config (None or dict): If specified, the sensor configuration to use for the robot. See the + example sensor_config in fetch_behavior.yaml env config. This can be used to specify relevant sensor + params, such as image_height and image_width. Supports both class-level keys (e.g., "VisionSensor") + and instance-level keys (e.g., "wrist:Camera:0") for specifying per-sensor kwargs. Instance-level + keys take precedence over class-level keys. + external_sensors_config (None or list): If specified, external sensor(s) to use. This will override the + external_sensors kwarg in the env config when the environment is loaded. Each entry should be a + dictionary specifying an individual external sensor's relevant parameters. See the example + external_sensors key in fetch_behavior.yaml env config. This can be used to specify additional sensors + to collect observations during playback. + include_sensor_names (None or list of str): If specified, substring(s) to check for in all raw sensor prim + paths found on the robot. A sensor must include one of the specified substrings in order to be included + in this robot's set of sensors during playback + exclude_sensor_names (None or list of str): If specified, substring(s) to check against in all raw sensor + prim paths found on the robot. A sensor must not include any of the specified substrings in order to + be included in this robot's set of sensors during playback + n_render_iterations (int): Number of rendering iterations to use when loading each stored frame from the + recorded data. This is needed because the omniverse real-time raytracing always lags behind the + underlying physical state by a few frames, and additionally produces transient visual artifacts when + the physical state changes. Increasing this number will improve the rendered quality at the expense of + speed. + overwrite (bool): If set, will overwrite any pre-existing data found at @output_path. + Otherwise, will load the data and append to it + only_successes (bool): Whether to only save successful episodes + flush_every_n_traj (int): How often to flush (write) current data to file + flush_every_n_steps (int): How often to flush (write) current data to file within an episode. + This is useful when collecting very long trajectories that may have a large memory footprint before writing to disk. + If this is greater than 0, flush_every_n_traj must be set to 1. + include_env_wrapper (bool): Whether to include environment wrapper stored in the underlying env config + additional_wrapper_configs (None or list of dict): If specified, list of wrapper config(s) specifying + environment wrappers to wrap the internal environment class in + full_scene_file (None or str): If specified, the full scene file to use for playback. During data collection + the scene file stored may be partial, and will be used to fill in the missing scene objects from the + full scene file. + include_task (bool): Whether to include the original task or not. If False, will use a DummyTask instead + include_task_obs (bool): Whether to include task observations or not. If False, will not include task obs + include_robot_control (bool): Whether or not to include robot control. If False, will disable all joint control. + include_contacts (bool): Whether or not to include (enable) contacts in the sim. If False, will set all + objects to be visual_only + load_room_instances (None or list of str): If specified, list of room instance names to load during + playback + kwargs (dict): Any remaining keyword arguments to pass into class constructor + + Returns: + DataPlaybackWrapper: Generated playback environment + """ + # Read from the HDF5 file + f = h5py.File(input_path, "r") + config = json.loads(f["data"].attrs["config"]) + + # Hot swap in additional info for playing back data + + if include_contacts: + # Minimize physics leakage during playback (we need to take an env step when loading state) + config["env"]["action_frequency"] = 1000.0 + config["env"]["rendering_frequency"] = 1000.0 + config["env"]["physics_frequency"] = 1000.0 + else: + # Since we are setting all objects to be visual-only, preserve frequencies from the input dataset config + # Simulator-level visual-only set to True + gm.VISUAL_ONLY = True + + # Make sure obs space is flattened for recording + config["env"]["flatten_obs_space"] = True + + # Set the scene file either to the one stored in the hdf5 or the hot swap scene file + recorded_scene_file = json.loads(f["data"].attrs["scene_file"]) + config["scene"]["scene_file"] = recorded_scene_file + if full_scene_file: + with open(full_scene_file, "r") as json_file: + full_scene_json = json.load(json_file) + config["scene"]["scene_file"] = merge_scene_files( + scene_a=full_scene_json, scene_b=config["scene"]["scene_file"], keep_robot_from="b" + ) + # Overwrite rooms type to avoid loading room types from the hdf5 file + config["scene"]["load_room_types"] = None + config["scene"]["load_room_instances"] = load_room_instances + else: + config["scene"]["scene_file"] = recorded_scene_file + + _add_recorded_non_kin_states_to_scene_file( + scene_file=config["scene"]["scene_file"], + recorded_scene_files=[recorded_scene_file], + ) + + # Use dummy task if not loading task + if not include_task: + config["task"] = {"type": "DummyTask"} + + # Maybe include task observations + config["task"]["include_obs"] = include_task_obs + + # Set scene file and disable online object sampling if BehaviorTask is being used + if config["task"]["type"] == "BehaviorTask": + config["task"]["online_object_sampling"] = False + # Don't use presampled robot pose + config["task"]["use_presampled_robot_pose"] = False + + # Because we're loading directly from the cached scene file, we need to disable any additional objects that are being added since + # they will already be cached in the original scene file + config["objects"] = [] + + # Set observation modalities and update sensor config + for robot_cfg in config["robots"]: + robot_cfg["obs_modalities"] = list(robot_obs_modalities) + robot_cfg["include_sensor_names"] = include_sensor_names + robot_cfg["exclude_sensor_names"] = exclude_sensor_names + if robot_proprio_keys is not None: + robot_cfg["proprio_obs"] = robot_proprio_keys + if robot_sensor_config is not None: + robot_cfg["sensor_config"] = robot_sensor_config + # Extract modalities from sensor_config and add to obs_modalities + for sensor_cfg in robot_cfg["sensor_config"].values(): + if "modalities" in sensor_cfg: + modalities = sensor_cfg["modalities"] + if isinstance(modalities, list): + robot_cfg["obs_modalities"].extend(modalities) + else: + robot_cfg["obs_modalities"].append(modalities) + if external_sensors_config is not None: + config["env"]["external_sensors"] = external_sensors_config + + # Load env + env = Environment(configs=config) + + # Optionally include the desired environment wrapper specified in the config + if include_env_wrapper: + env = create_wrapper(env=env) + + if additional_wrapper_configs is not None: + for wrapper_cfg in additional_wrapper_configs: + env = create_wrapper(env=env, wrapper_cfg=wrapper_cfg) + + # Wrap and return env + return cls( + env=env, + input_path=input_path, + output_path=output_path, + n_render_iterations=n_render_iterations, + overwrite=overwrite, + only_successes=only_successes, + flush_every_n_traj=flush_every_n_traj, + flush_every_n_steps=flush_every_n_steps, + full_scene_file=full_scene_file, + load_room_instances=load_room_instances, + include_robot_control=include_robot_control, + include_contacts=include_contacts, + **kwargs, + ) + + def __init__( + self, + env: Environment, + input_path: str, + output_path: str, + n_render_iterations: int = 1, + overwrite: bool = True, + only_successes: bool = False, + flush_every_n_traj: int = 10, + flush_every_n_steps: int = 0, + full_scene_file: str | None = None, + load_room_instances: list[str] | None = None, + include_robot_control: bool = True, + include_contacts: bool = True, + **kwargs, + ): + """ + Args: + env (Environment): The environment to wrap + input_path (str): path to input hdf5 collected data file + output_path (str): path to store output hdf5 data file + n_render_iterations (int): Number of rendering iterations to use when loading each stored frame from the + recorded data + overwrite (bool): If set, will overwrite any pre-existing data found at @output_path. + Otherwise, will load the data and append to it + only_successes (bool): Whether to only save successful episodes + flush_every_n_traj (int): How often to flush (write) current data to file across episodes + flush_every_n_steps (int): How often to flush (write) current data to file within an episode. + This is useful when collecting very long trajectories that may have a large memory footprint before writing to disk. + If this is greater than 0, flush_every_n_traj must be set to 1. + full_scene_file (None or str): If specified, the full scene file to use for playback. During data collection, + the scene file stored may be partial, and this will be used to fill in the missing scene objects from the + full scene file. + load_room_instances (None or list[str]): If specified, the room instances to load for playback. + include_robot_control (bool): Whether or not to include robot control. If False, will disable all joint control. + include_contacts (bool): Whether or not to include (enable) contacts in the sim. If False, will set all objects to be visual_only + kwargs (dict): Arguments to pass to super class + """ + # Playback is single-env only: env.scene reads and indexing on obs_list[0] / infos[0] + # later assume one env. Fail fast before env.scene.save() (below) runs in multi-env. + assert env.num_envs == 1, f"DataPlaybackWrapper is single-env only; got num_envs={env.num_envs}." + + # Make sure transition rules are DISABLED for playback since we manually propagate transitions + assert not gm.ENABLE_TRANSITION_RULES, "Transition rules must be disabled for DataPlaybackWrapper env!" + + # Stabilize skipped objects + # we can do this here because we know that whatever's skipped during load state must have been asleep during data collection + # which means they're not moving and we can safely keep them still + with macros.unlocked(): + macros.utils.registry_utils.STABILIZE_SKIPPED_OBJECTS = True + + # Store scene file so we can restore the data upon each episode reset + self.input_hdf5 = h5py.File(input_path, "r") + input_config = json.loads(self.input_hdf5["data"].attrs["config"]) + self._fps = int( + input_config.get("env", dict()).get("rendering_frequency", env.env_config["rendering_frequency"]) + ) + self.recorded_scene_file = json.loads(self.input_hdf5["data"].attrs["scene_file"]) + self.scene_file = self.recorded_scene_file + assert not ( + load_room_instances and not full_scene_file + ), "Full scene file must be specified in order to load room instances" + if full_scene_file: + with open(full_scene_file, "r") as json_file: + full_scene_json = json.load(json_file) + self.scene_file = merge_scene_files(scene_a=full_scene_json, scene_b=self.scene_file, keep_robot_from="b") + if load_room_instances is not None and full_scene_file is not None: + # we loaded more room than the stored scene file, but still not the full scene + # we need to save the current scene file here to avoid errors + self.scene_file = env.scene.save(as_dict=True) + _align_scene_object_states_with_recorded_schema(scene=env.scene, recorded_scene_file=self.recorded_scene_file) + + # check flush parameters + if flush_every_n_steps > 0: + assert flush_every_n_traj == 1, "flush_every_n_traj must be 1 if flush_every_n_steps is set" + assert not only_successes, "only_successes must be False if flush_every_n_steps is set, since we need to store partial trajectories regardless of success" + self.flush_every_n_steps = flush_every_n_steps + + # Store additional variables + self.current_traj_history = [] + self.n_render_iterations = n_render_iterations + self.current_episode_step_count = 0 + self.current_episode_id = None + self.include_robot_control = include_robot_control + self.include_contacts = include_contacts + + self.video_writers = [] + self.video_output_dir = os.path.dirname(output_path) + + # Run super + super().__init__( + env=env, + output_path=output_path, + overwrite=overwrite, + only_successes=only_successes, + flush_every_n_traj=flush_every_n_traj, + **kwargs, + ) + + def _create_video_writers(self, video_keys): + """Create video writers for each video key.""" + for key in video_keys: + shape = self.env.observation_space[key].shape + fpath = os.path.join(self.video_output_dir, f"{video_keys[key]}.mp4") + container, stream = create_video_writer(fpath=fpath, resolution=(shape[0], shape[1]), rate=self.fps) + self.video_writers.append((container, stream, key)) + + def _extract_frame_from_obs(self, obs: dict, key: str): + """Extract a single video frame from observation dict given a key.""" + current = obs[key] + if len(current.shape) == 4: + current = current[-1] + if current.shape[-1] == 4: + current = current[..., :3] + elif current.shape[-1] == 1: + current = current[..., 0] + return current.numpy() + + def _write_video_frames(self): + """Write current observation to all video writers.""" + if not self.video_writers: + return + for container, stream, key in self.video_writers: + frame = self._extract_frame_from_obs(self.current_obs, key) + if frame is not None: + obs = frame[np.newaxis, ...] # (H, W, C) -> (1, H, W, C) + write_video(obs, (container, stream), mode="rgb") + + def _flush_video_writers(self): + """Flush and close all video writers.""" + for container, stream, _ in self.video_writers: + for packet in stream.encode(): + container.mux(packet) + container.close() + self.video_writers = [] + + def _parse_step_data( + self, + action: th.Tensor, + obs: dict, + reward: float, + terminated: bool, + truncated: bool, + info: dict, + ) -> dict: + # Store action, obs, reward, terminated, truncated, info + step_data = dict() + step_data["obs"] = self._process_obs(obs, info) + step_data["action"] = action + step_data["reward"] = reward + step_data["terminated"] = terminated + step_data["truncated"] = truncated + return step_data + + def playback_episode( + self, + episode_id: int, + record_data: bool = True, + video_keys: dict = None, + post_state_update_callback: Callable[[], None] | None = None, + ) -> None: + """ + Playback episode @episode_id, and optionally record observation data if @record is True + + Args: + episode_id (int): Episode to playback. This should be a valid demo ID number from the inputted collected + data hdf5 file + record_data (bool): Whether to record data during playback or not + video_keys (dict): Optional dictionary of video keys to record during playback. If provided, will recreate + video writers at the start of playback (useful if they were flushed after a previous episode) + It should be a dict mapping from obs keys to the desired output video file name. + post_state_update_callback (None or Callable): Optional callback called after playback restores recorded + state, and after each playback step updates simulator state. This can be used to resync visual state + that is derived from recorded object state but is not directly serialized. + """ + + # Recreate video writers if video_keys are provided + if video_keys: + self._flush_video_writers() # Clear any existing writers first + self._create_video_writers(video_keys) + + data_grp = self.input_hdf5["data"] + assert f"demo_{episode_id}" in data_grp, f"No valid episode with ID {episode_id} found!" + traj_grp = data_grp[f"demo_{episode_id}"] + self.current_episode_id = episode_id + self.current_episode_step_count = 0 + # Grab episode data + # Skip early if found malformed data + try: + transitions = json.loads(traj_grp.attrs["transitions"]) + traj_grp = h5py_group_to_torch(traj_grp) + init_metadata = traj_grp["init_metadata"] + action = traj_grp["action"] + state = traj_grp["state"] + state_size = traj_grp["state_size"] + reward = traj_grp["reward"] + terminated = traj_grp["terminated"] + truncated = traj_grp["truncated"] + except KeyError as e: + print(f"Got error when trying to load episode {episode_id}:") + print(f"Error: {str(e)}") + return + + # Reset environment and update this to be the new initial state + self.scene.restore(self.scene_file, update_initial_file=True) + + # Reset object attributes from the stored metadata + og.sim.stop() + for attr, vals in init_metadata.items(): + assert len(vals) == self.scene.n_objects + for i, obj in enumerate(self.scene.objects): + for attr, vals in init_metadata.items(): + val = vals[i] + setattr(obj, attr, val.item() if val.ndim == 0 else val) + og.sim.play() + self.reset() + _align_scene_object_states_with_recorded_schema( + scene=self.scene, + recorded_scene_file=self.recorded_scene_file, + ) + + # If not controlling robots, disable for all robots + if not self.include_robot_control: + for robot in self.scene.robots: + robot.control_enabled = False + # Set all controllers to effort mode with zero gain, this keeps the robot still + for controller in robot.controllers.values(): + for i, dof in enumerate(ControllerView.get_dof_idx(controller[0]).tolist()): + dof_joint = robot.joints[robot.dof_names_ordered[dof]] + dof_joint.set_control_type( + control_type=ControlType.EFFORT, + kp=None, + kd=None, + ) + + # Restore to initial state + og.sim.load_state(state[0, : int(state_size[0])], serialized=True) + if post_state_update_callback is not None: + post_state_update_callback() + # take one sim step to propagate + og.sim.step() + if post_state_update_callback is not None: + post_state_update_callback() + + # If record, record initial observations + if record_data or self.video_writers: + # Grab initial observations directly from restored state[0], before any action is applied. + first_time_load_n_iteration = 10 + for _ in range(first_time_load_n_iteration): + og.sim.render() + obs_list, init_info = self.env.get_obs() + self.current_obs = obs_list[0] + assert len(self.current_traj_history) == 1 and set(self.current_traj_history[-1].keys()) == { + "obs" + }, "Expected reset() to have inserted an initial obs-only entry into the trajectory history!" + self.current_traj_history[-1]["obs"] = self._process_obs(self.current_obs, init_info) + # Write the initial frame if video_writers are configured + if self.video_writers: + self._write_video_frames() + for i, (a, s, ss, r, te, tr) in enumerate(zip(action, state, state_size, reward, terminated, truncated)): + # Here, state i is the state before taking action i, and reward, terminated, truncated are the results of taking action i + if i % 1000 == 0: + log.info(f"Playing back episode {episode_id}, step {i}/{len(action)}") + # Restore the sim state, and take a very small step with the action to make sure physics are + # properly propagated after the sim state update + og.sim.load_state(s[: int(ss)], serialized=True) + if post_state_update_callback is not None: + post_state_update_callback() + if not self.include_contacts: + # When all objects/systems are visual-only, keep them still on every step + for obj in self.scene.objects: + obj.keep_still() + for system in self.scene.systems: + # TODO: Implement keep_still for other systems + if isinstance(system, MacroPhysicalParticleSystem): + system.set_particles_velocities( + lin_vels=th.zeros((system.n_particles, 3)), ang_vels=th.zeros((system.n_particles, 3)) + ) + # Take a small step with the action to propagate physics after loading the state + obs_list, _, _, _, infos = self.env.step(action=a, n_render_iterations=self.n_render_iterations) + self.current_obs = obs_list[0] + info = infos[0] + if post_state_update_callback is not None: + post_state_update_callback() + og.sim.render() + obs_list, _ = self.env.get_obs() + self.current_obs = obs_list[0] + + # Execute any transitions that should occur at this current step + if str(i) in transitions: + cur_transitions = transitions[str(i)] + scene = og.sim.scenes[0] + added_systems = set(cur_transitions["systems"]["add"]) + removed_systems = set(cur_transitions["systems"]["remove"]) + for add_sys_name in cur_transitions["systems"]["add"]: + scene.get_system(add_sys_name, force_init=True) + for remove_sys_name in cur_transitions["systems"]["remove"]: + scene.clear_system(remove_sys_name) + for remove_obj_name in cur_transitions["objects"]["remove"]: + if _is_system_particle_template_name(remove_obj_name, removed_systems): + continue + obj = scene.object_registry("name", remove_obj_name) + scene.remove_object(obj) + recorded_non_kin_names = _recorded_non_kin_state_name_union(self.recorded_scene_file) + for j, add_obj_info in enumerate(cur_transitions["objects"]["add"]): + if _is_system_particle_template_info(add_obj_info, added_systems): + continue + obj = create_object_from_init_info(add_obj_info) + # Objects created by a transition are not in the recorded scene file, so they + # have no saved state list of their own. Give them the pooled list instead, so + # reading back later frames stays on the right numbers. + if recorded_non_kin_names is not None: + obj._recorded_non_kin_state_names = set(recorded_non_kin_names) + scene.add_object(obj) + obj.set_position(th.ones(3) * 100.0 + th.ones(3) * 5 * j) + # Step physics to initialize any new objects + og.sim.step() + + # Write videos if video_writers are configured + if self.video_writers: + self._write_video_frames() + + # If recording, record data + if record_data: + step_data = self._parse_step_data( + action=a, + obs=self.current_obs, + reward=r, + terminated=te, + truncated=tr, + info=info, + ) + if self.flush_every_n_steps > 0 and i % self.flush_every_n_steps == 0: + self.flush_partial_traj(step_idx=i, total_steps=len(action), step_data=step_data) + # append to current trajectory history + self.current_traj_history.append(step_data) + + self.current_episode_step_count += 1 + self.step_count += 1 + + if record_data: + self.flush_current_traj() + + if self.video_writers: + self._flush_video_writers() + + def playback_dataset(self, record_data: bool = False) -> None: + """ + Playback all episodes from the input HDF5 file, and optionally record observation data if @record is True + + Args: + record_data (bool): Whether to record data during playback or not + """ + for episode_id in range(self.input_hdf5["data"].attrs["n_episodes"]): + self.playback_episode( + episode_id=episode_id, + record_data=record_data, + ) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/env_base.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/env_base.py new file mode 100644 index 0000000000000000000000000000000000000000..408458e80ef10319a17f6324dd0d371992664a13 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/env_base.py @@ -0,0 +1,1063 @@ +from collections import OrderedDict +from collections.abc import Iterable +from copy import deepcopy +import os + +import gymnasium as gym +import torch as th + +import omnigibson as og +from omnigibson.macros import gm +from omnigibson.objects import REGISTERED_OBJECTS +from omnigibson.robots import Robot, REGISTERED_ROBOTS +from omnigibson.scene_graphs.graph_builder import SceneGraphBuilder +from omnigibson.scenes import REGISTERED_SCENES +from omnigibson.sensors import TiledVisionSensor, VisionSensor, create_sensor +from omnigibson.tasks import REGISTERED_TASKS +from omnigibson.utils.config_utils import parse_config +from omnigibson.utils.gym_utils import ( + GymObservable, + maxdim, + recursively_generate_compatible_dict, + recursively_generate_flat_dict, +) +from omnigibson.utils.numpy_utils import NumpyTypes, list_to_np_array +from omnigibson.utils.python_utils import ( + Recreatable, + assert_valid_key, + create_class_from_registry_and_config, + merge_nested_dicts, +) +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.vision_utils import change_pcd_frame + +# Create module logger +log = create_module_logger(module_name=__name__) + + +class Environment(gym.Env, GymObservable, Recreatable): + """ + Core environment class that handles loading scene, robot(s), and task, following OpenAI Gym interface. + """ + + def __init__(self, configs): + """ + Args: + configs (str or dict or list of str or dict): config_file path(s) or raw config dictionaries. + If multiple configs are specified, they will be merged sequentially in the order specified. + This allows procedural generation of a "full" config from small sub-configs. For valid keys, please + see @default_config below + """ + # Call super first + super().__init__() + + # Required render mode metadata for gymnasium + self.render_mode = "rgb_array" + self.metadata = {"render.modes": ["rgb_array"]} + + # Convert config file(s) into a single parsed dict + configs = configs if isinstance(configs, list) or isinstance(configs, tuple) else [configs] + + # Initial default config + self.config = self.default_config + + # Merge in specified configs + for config in configs: + merge_nested_dicts(base_dict=self.config, extra_dict=parse_config(config), inplace=True) + + # Store number of environments + self.num_envs = self.env_config.get("num_envs", 1) + + # Store settings and other initialized values + self._automatic_reset = self.env_config["automatic_reset"] + self._flatten_action_space = self.env_config["flatten_action_space"] + self._flatten_obs_space = self.env_config["flatten_obs_space"] + # Number of render steps performed after a reset so that camera observations reflect the reset state. + # Setting this to 0 skips the extra renders (IsaacLab's num_rerenders_on_reset convention): cheaper, but + # image observations returned by reset() will be stale (last pre-reset frame). + self._num_rerenders_on_reset = self.env_config["num_rerenders_on_reset"] + self.device = self.env_config["device"] if self.env_config["device"] else "cpu" + + physics_dt = 1.0 / self.env_config["physics_frequency"] + rendering_dt = 1.0 / self.env_config["rendering_frequency"] + sim_step_dt = 1.0 / self.env_config["action_frequency"] + viewer_width = self.render_config["viewer_width"] + viewer_height = self.render_config["viewer_height"] + + # If the sim is launched, check that the parameters match + if og.sim is not None: + assert ( + og.sim.initial_physics_dt == physics_dt + ), f"Physics frequency mismatch! Expected {physics_dt}, got {og.sim.initial_physics_dt}" + assert ( + og.sim.initial_rendering_dt == rendering_dt + ), f"Rendering frequency mismatch! Expected {rendering_dt}, got {og.sim.initial_rendering_dt}" + assert og.sim.device == self.device, f"Device mismatch! Expected {self.device}, got {og.sim.device}" + assert ( + og.sim.viewer_width == viewer_width + ), f"Viewer width mismatch! Expected {viewer_width}, got {og.sim.viewer_width}" + assert ( + og.sim.viewer_height == viewer_height + ), f"Viewer height mismatch! Expected {viewer_height}, got {og.sim.viewer_height}" + # Otherwise, launch a simulator instance + else: + og.launch( + physics_dt=physics_dt, + rendering_dt=rendering_dt, + sim_step_dt=sim_step_dt, + device=self.device, + viewer_width=viewer_width, + viewer_height=viewer_height, + ) + + # Initialize other placeholders that will be filled in later + self._task = None + self._tiled_sensor = None + self._external_sensors = None + self._external_sensors_include_in_obs = None + self._loaded = None + self._current_episodes = th.zeros(self.num_envs, dtype=th.int32) + + # Variables reset at the beginning of each episode + self._current_steps = th.zeros(self.num_envs, dtype=th.int32) + + # Scene list + self._scenes = [] + + # Sensor registry for obs-key-first iteration (built in load) + self._robot_sensor_map = {} # (robot_name, sensor_name) -> [sensor_per_env] + self._robot_has_proprio = {} # robot_name -> bool + self._ext_sensor_map = {} # sensor_name -> [sensor_per_env] + + # Create the scene graph builders (one per scene) + self._scene_graph_builders = [] + if "scene_graph" in self.config and self.config["scene_graph"] is not None: + self._scene_graph_builders = [SceneGraphBuilder(**self.config["scene_graph"]) for _ in range(self.num_envs)] + + # Load this environment + self.load() + + def reload(self, configs, overwrite_old=True): + """ + Reload using another set of config file(s). + This allows one to change the configuration and hot-reload the environment on the fly. + + Args: + configs (dict or str or list of dict or list of str): config_file dict(s) or path(s). + If multiple configs are specified, they will be merged sequentially in the order specified. + This allows procedural generation of a "full" config from small sub-configs. + overwrite_old (bool): If True, will overwrite the internal self.config with @configs. Otherwise, will + merge in the new config(s) into the pre-existing one. Setting this to False allows for minor + modifications to be made without having to specify entire configs during each reload. + """ + # Convert config file(s) into a single parsed dict + configs = [configs] if isinstance(configs, dict) or isinstance(configs, str) else configs + + # Initial default config + new_config = self.default_config + + # Merge in specified configs + for config in configs: + merge_nested_dicts(base_dict=new_config, extra_dict=parse_config(config), inplace=True) + + # Either merge in or overwrite the old config + if overwrite_old: + self.config = new_config + else: + merge_nested_dicts(base_dict=self.config, extra_dict=new_config, inplace=True) + + # Load this environment again + self.load() + + def reload_model(self, scene_model): + """ + Reload another scene model. + This allows one to change the scene on the fly. + + Args: + scene_model (str): new scene model to load (eg.: Rs_int) + """ + self.scene_config["model"] = scene_model + self.load() + + def _load_variables(self): + """ + Load variables from config + """ + # Reset bookkeeping variables + self._reset_variables() + self._current_episodes = th.zeros(self.num_envs, dtype=th.int32) + + # - Potentially overwrite the USD entry for the scene if none is specified and we're online sampling - + + # Make sure the requested scene is valid + scene_type = self.scene_config["type"] + assert_valid_key(key=scene_type, valid_keys=REGISTERED_SCENES, name="scene type") + + # Verify scene and task configs are valid for the given task type + REGISTERED_TASKS[self.task_config["type"]].verify_scene_and_task_config( + scene_cfg=self.scene_config, + task_cfg=self.task_config, + ) + + def _load_task(self, task_config=None): + """ + Load task + + Args: + task_confg (None or dict): If specified, custom task configuration to use. Otherwise, will use + self.task_config. Note that if a custom task configuration is specified, the internal task config + will be updated as well + """ + # Update internal config if specified + if task_config is not None: + # Copy task config, in case self.task_config and task_config are the same! + task_config = deepcopy(task_config) + self.task_config.clear() + self.task_config.update(task_config) + + # Sanity check task to make sure it's valid + task_type = self.task_config["type"] + assert_valid_key(key=task_type, valid_keys=REGISTERED_TASKS, name="task type") + + # Grab the kwargs relevant for the specific task and create the task + self._task = create_class_from_registry_and_config( + cls_name=self.task_config["type"], + cls_registry=REGISTERED_TASKS, + cfg=self.task_config, + cls_type_descriptor="task", + ) + assert og.sim.is_stopped(), "Simulator must be stopped before loading tasks!" + + # Load task. Should load additional task-relevant objects and configure the scene into its default initial state + self._task.load(env=self) + + assert og.sim.is_stopped(), "Simulator must be stopped after loading tasks!" + + def _load_scene(self): + """ + Load the scene and robot specified in the config file. + """ + assert og.sim.is_stopped(), "Simulator must be stopped before loading scene!" + + # Create the scene(s) from our scene config + self._scenes = [ + create_class_from_registry_and_config( + cls_name=self.scene_config["type"], + cls_registry=REGISTERED_SCENES, + cfg=deepcopy(self.scene_config), + cls_type_descriptor="scene", + ) + for _ in range(self.num_envs) + ] + og.sim.import_scene(self._scenes) + + assert og.sim.is_stopped(), "Simulator must be stopped after loading scene!" + + def _load_robots(self): + """ + Load robots into the scene + """ + # Only actually load robots if no robot has been imported from the scene loading directly yet + loaded_from_config = False + + # Pre-assign robot names so all scenes share the same names + for i, robot_config in enumerate(self.robots_config): + # Add a name for the robot if necessary. Make sure robots in different scenes share the same relative_prim_path + if "name" not in robot_config: + robot_config["name"] = f"robot_{i}" + + for scene in self._scenes: + if len(scene.robots) == 0: + loaded_from_config = True + assert og.sim.is_stopped(), "Simulator must be stopped before loading robots!" + + # Iterate over all robots to generate in the robot config + for robot_config in self.robots_config: + robot_config = deepcopy(robot_config) + if "model" in robot_config: + assert ( + "type" not in robot_config + ), "CANNOT SPECIFY BOTH TYPE AND MODEL. Robot config key 'type' is deprecated; use 'model' instead." + elif "type" in robot_config: + log.warning( + "Robot config key 'type' is deprecated; use 'model' instead. " + "Model IDs are lowercase (e.g. 'model': 'fetch'). " + ) + robot_config["model"] = robot_config["type"].lower() + del robot_config["type"] + assert ( + robot_config["model"] in REGISTERED_ROBOTS + ), f"{robot_config['model']} is not a registered robot." + position, orientation = robot_config.pop("position", None), robot_config.pop("orientation", None) + pose_frame = robot_config.pop("pose_frame", "scene") + if position is not None: + position = ( + position if isinstance(position, th.Tensor) else th.tensor(position, dtype=th.float32) + ) + if orientation is not None: + orientation = ( + orientation + if isinstance(orientation, th.Tensor) + else th.tensor(orientation, dtype=th.float32) + ) + + robot = Robot(**robot_config) + # Import the robot into the simulator + scene.add_object(robot) + robot.set_position_orientation(position=position, orientation=orientation, frame=pose_frame) + + # Persist scene 0's robot names back to config for downstream use (e.g. data collection). + # Only needed when robots were created from config (ordering matches). When robots come + # from a scene file, names are already correct and ordering may not match config. + if loaded_from_config: + for robot_idx, robot in enumerate(self._scenes[0].robots): + if robot_idx < len(self.robots_config): + self.robots_config[robot_idx]["name"] = robot.name + + assert og.sim.is_stopped(), "Simulator must be stopped after loading robots!" + + def _load_objects(self): + """ + Load any additional custom objects into the scene + """ + assert og.sim.is_stopped(), "Simulator must be stopped before loading objects!" + for scene in self._scenes: + for i, obj_config in enumerate(self.objects_config): + obj_config = deepcopy(obj_config) + # Add a name for the object if necessary + if "name" not in obj_config: + obj_config["name"] = f"obj{i}" + # Pop the desired position and orientation + position, orientation = obj_config.pop("position", None), obj_config.pop("orientation", None) + # Make sure robot exists, grab its corresponding kwargs, and create / import the robot + obj = create_class_from_registry_and_config( + cls_name=obj_config["type"], + cls_registry=REGISTERED_OBJECTS, + cfg=obj_config, + cls_type_descriptor="object", + ) + # Import the robot into the simulator and set the pose + scene.add_object(obj) + obj.set_position_orientation(position=position, orientation=orientation, frame="scene") + + assert og.sim.is_stopped(), "Simulator must be stopped after loading objects!" + + def _load_external_sensors(self): + """ + Load any additional custom external sensors into the scene + """ + assert og.sim.is_stopped(), "Simulator must be stopped before loading external sensors!" + sensors_config = self.env_config["external_sensors"] + if sensors_config is not None: + self._external_sensors = [] + self._external_sensors_include_in_obs = dict() + for i, sensor_config in enumerate(sensors_config): + # Add a name for the object if necessary + if "name" not in sensor_config: + sensor_config["name"] = f"external_sensor{i}" + # Determine prim path if not specified + if "relative_prim_path" not in sensor_config: + sensor_config["relative_prim_path"] = f"/{sensor_config['name']}" + # Create separate sensor instances for each scene + for scene_idx, scene in enumerate(self._scenes): + scene_sensors = dict() + for i, sensor_config in enumerate(sensors_config): + sc = deepcopy(sensor_config) + # Pop the desired position and orientation + position, orientation = sc.pop("position", None), sc.pop("orientation", None) + pose_frame = sc.pop("pose_frame", "scene") + # Pop whether or not to include this sensor in the observation + include_in_obs = sc.pop("include_in_obs", True) + # Make sure sensor exists, grab its corresponding kwargs, and create the sensor + sensor = create_sensor(**sc) + # Load an initialize this sensor + sensor.load(scene) + sensor.initialize() + sensor.set_position_orientation(position=position, orientation=orientation, frame=pose_frame) + scene_sensors[sensor.name] = sensor + # Populate include_in_obs only once (same for all scenes) + if scene_idx == 0: + self._external_sensors_include_in_obs[sensor.name] = include_in_obs + self._external_sensors.append(scene_sensors) + + assert og.sim.is_stopped(), "Simulator must be stopped after loading external sensors!" + + def _load_observation_space(self): + # Grab robot(s) and task obs spaces + # Assumes all scenes share the same robot/sensor configuration + obs_space = dict() + + for robot in self._scenes[0].robots: + # Load the observation space for the robot + robot_obs = robot.load_observation_space() + if maxdim(robot_obs) > 0: + obs_space[robot.name] = robot_obs + + # Also load the task obs space + task_space = self._task.load_observation_space() + if maxdim(task_space) > 0: + obs_space["task"] = task_space + + # Also load any external sensors + if self._external_sensors is not None: + external_obs_space = dict() + for sensor_name, sensor in self._external_sensors[0].items(): + if not self._external_sensors_include_in_obs[sensor_name]: + continue + + # Load the sensor observation space + external_obs_space[sensor_name] = sensor.load_observation_space() + obs_space["external"] = gym.spaces.Dict(external_obs_space) + + return obs_space + + def load_observation_space(self): + # Call super first + obs_space = super().load_observation_space() + + # If we want to flatten it, modify the observation space by recursively searching through all + if self._flatten_obs_space: + self.observation_space = gym.spaces.Dict(recursively_generate_flat_dict(dic=obs_space)) + + return self.observation_space + + def _load_action_space(self): + """ + Load action space for each robot + """ + action_space = gym.spaces.Dict({robot.name: robot.action_space for robot in self._scenes[0].robots}) + + # Convert into flattened 1D Box space if requested + if self._flatten_action_space: + lows = [] + highs = [] + for space in action_space.values(): + assert isinstance( + space, gym.spaces.Box + ), "Can only flatten action space where all individual spaces are gym.space.Box instances!" + assert ( + len(space.shape) == 1 + ), "Can only flatten action space where all individual spaces are 1D instances!" + lows.append(space.low) + highs.append(space.high) + action_space = gym.spaces.Box( + list_to_np_array(lows), + list_to_np_array(highs), + dtype=NumpyTypes.FLOAT32, + ) + + # Store action space + self.action_space = action_space + + def load(self): + """ + Load the scene and robot specified in the config file. + """ + # This environment is not loaded + self._loaded = False + + # Load config variables + self._load_variables() + + # Load the scene, robots, and task + self._load_scene() + self._load_objects() + self._load_robots() + self._load_task() + self._load_external_sensors() + + # When running multiple envs with gm.ENABLE_TILED_RENDERING, batch all per-env robot cameras into a + # single tiled render product so that one render pass serves every env. Must be created before play + # (mirrors camera prims on the stage). Otherwise every env renders through its own per-camera render + # product, exactly as in the single-env case. + if self._tiled_sensor is not None: + # In case of a reload, remove the stale tiled sensor first (no-op if og.clear() already did) + self._tiled_sensor.remove() + self._tiled_sensor = None + has_vision_sensors = any( + isinstance(sensor, VisionSensor) for robot in self._scenes[0].robots for sensor in robot.sensors.values() + ) + if gm.ENABLE_TILED_RENDERING and self.num_envs > 1 and has_vision_sensors: + # Creating the tiled render product and attaching annotators edits the USD stage + with og.sim.editing_usd(): + self._tiled_sensor = TiledVisionSensor(envs=self._scenes) + + # Play and complete loading + og.sim.play() + # Run any additional task post-loading behavior + self.task.post_play_load(env=self) + + # Save the state for objects from load_robots / load_objects / load_task + for scene in self._scenes: + scene.update_initial_file() + + # Load the obs / action spaces + self.load_observation_space() + self._load_action_space() + + # Build sensor registry for get_obs() + self._build_sensor_registry() + + # When tiled rendering is active, robot camera observations come from the tiled render product. + # Pause the individual render products: hiding their UI viewports is a no-op in headless mode and + # leaves those unused products rendering every frame alongside the tiled product. + keep_individual_render_products = os.getenv("OMNIGIBSON_KEEP_INDIVIDUAL_RENDER_PRODUCTS", "0") == "1" + if self._tiled_sensor is not None and not keep_individual_render_products: + with og.sim.editing_usd(): + for sensors in self._robot_sensor_map.values(): + for sensor in sensors: + if isinstance(sensor, VisionSensor): + sensor.viewer_visibility = False + sensor.render_product.hydra_texture.updates_enabled = False + + self.reset() + + # Start the scene graph builders + for builder, scene in zip(self._scene_graph_builders, self._scenes): + builder.start(scene) + + # Denote that the scene is loaded + self._loaded = True + + def close(self): + """No-op to satisfy certain RL frameworks.""" + pass + + def _build_sensor_registry(self): + """ + Build cross-scene sensor maps for obs-key-first observation gathering. + All scenes share the same robot/sensor configuration, so scene 0 is used as the template. + """ + self._robot_sensor_map = {} + self._robot_has_proprio = {} + + for robot_idx, robot in enumerate(self._scenes[0].robots): + self._robot_has_proprio[robot.name] = "proprio" in robot._obs_modalities + for sensor_name in robot.sensors: + self._robot_sensor_map[(robot.name, sensor_name)] = [ + self._scenes[env_idx].robots[robot_idx].sensors[sensor_name] for env_idx in range(self.num_envs) + ] + + self._ext_sensor_map = {} + if self._external_sensors is not None: + for sensor_name in self._external_sensors[0]: + if not self._external_sensors_include_in_obs.get(sensor_name, False): + continue + self._ext_sensor_map[sensor_name] = [ + self._external_sensors[env_idx][sensor_name] for env_idx in range(self.num_envs) + ] + + def get_obs(self, env_indices=None): + """ + Get the current environment observation. + + Args: + env_indices (None or th.Tensor): Indices of envs to get observations for. If None, gets all. + + Returns: + 2-tuple: + list[dict]: Keyword-mapped observations per env + list[dict]: Additional information about the observations per env + """ + if env_indices is None: + env_indices = list(range(self.num_envs)) + else: + env_indices = [int(i) for i in env_indices] + + # Pre-allocate result dicts for each requested env + all_obs = [{} for _ in env_indices] + all_info = [{} for _ in env_indices] + + # Grab the batched tiled camera buffers once; per-env observations are slices (views) of these + tiled_obs = self._tiled_sensor.get_obs() if self._tiled_sensor is not None else None + + # --- Robot observations --- + for robot_idx, robot_0 in enumerate(self._scenes[0].robots): + robot_name = robot_0.name + if maxdim(robot_0.observation_space) <= 0: + continue + + # Initialize per-env robot obs/info dicts + for i in range(len(env_indices)): + all_obs[i][robot_name] = {} + all_info[i][robot_name] = {} + + # Sensor observations + for (rname, sensor_name), sensors in self._robot_sensor_map.items(): + if rname != robot_name: + continue + if tiled_obs is not None and sensor_name in tiled_obs: + # Vision sensors in multi-env mode: slice the per-env tile out of the batched buffer. + # NOTE: segmentation modalities are raw (unremapped) Replicator IDs in this path, and the + # per-modality info dicts (e.g. seg ID mappings) are not available. + for i, env_idx in enumerate(env_indices): + s_obs = dict() + for modality in self._tiled_sensor.modalities[sensor_name]: + data = tiled_obs[sensor_name][modality][env_idx] + # Match the per-sensor observation space: single-channel modalities are (H, W) + if data.shape[-1] == 1: + data = data.squeeze(-1) + s_obs[modality] = data + all_obs[i][robot_name][sensor_name] = s_obs + all_info[i][robot_name][sensor_name] = dict() + continue + for i, env_idx in enumerate(env_indices): + s_obs, s_info = sensors[env_idx].get_obs() + # Convert pointcloud from world frame to robot base frame + for key in s_obs: + if "pointcloud" in key: + robot = self._scenes[env_idx].robots[robot_idx] + s_obs[key] = change_pcd_frame( + pcd=s_obs[key], + rel_pose=th.cat(robot.get_position_orientation()), + ) + all_obs[i][robot_name][sensor_name] = s_obs + all_info[i][robot_name][sensor_name] = s_info + + # Proprioception + if self._robot_has_proprio.get(robot_name, False): + for i, env_idx in enumerate(env_indices): + robot = self._scenes[env_idx].robots[robot_idx] + all_obs[i][robot_name]["proprio"], all_info[i][robot_name]["proprio"] = robot.get_proprioception() + + # --- Task observations --- + if maxdim(self._task.observation_space) > 0: + for i, env_idx in enumerate(env_indices): + all_obs[i]["task"] = self._task.get_obs(env=self, env_idx=env_idx) + + # --- External sensor observations --- + if self._external_sensors is not None: + for i in range(len(env_indices)): + all_obs[i]["external"] = {} + all_info[i]["external"] = {} + + for sensor_name, sensors in self._ext_sensor_map.items(): + # TODO: Replace with a single batched tiled rendering call + for i, env_idx in enumerate(env_indices): + s_obs, s_info = sensors[env_idx].get_obs() + all_obs[i]["external"][sensor_name] = s_obs + all_info[i]["external"][sensor_name] = s_info + + # --- Flatten if requested --- + if self._flatten_obs_space: + for i in range(len(env_indices)): + all_obs[i] = recursively_generate_flat_dict(dic=all_obs[i]) + + return all_obs, all_info + + def get_scene_graph(self, env_idx=0): + """ + Get the current scene graph for a given environment. + + Args: + env_idx (int): Index of the environment to get the scene graph for. Default is 0. + + Returns: + SceneGraph: Current scene graph + """ + assert self._scene_graph_builders, "Scene graph builder must be specified in config!" + return self._scene_graph_builders[env_idx].get_scene_graph() + + def _populate_info(self, infos): + """ + Populate info dictionary with any useful information. + + Args: + infos (list[dict]): Information dictionaries to populate, one per env + + Returns: + list[dict]: Information dictionaries with added info + """ + for env_idx in range(self.num_envs): + infos[env_idx]["episode_length"] = self._current_steps[env_idx].item() + + for i, builder in enumerate(self._scene_graph_builders): + infos[i]["scene_graph"] = builder.get_scene_graph() + + def _convert_action_dict_to_tensor(self, action_dict): + """Convert a single action dict's values to tensors. + + Args: + action_dict (dict): Maps robot name to action (array, list, or tensor). + + Returns: + dict: Same keys, with values converted to flattened float tensors. + """ + return { + k: th.as_tensor(v, dtype=th.float).flatten() + if isinstance(v, Iterable) and not isinstance(v, (dict, OrderedDict, str)) + else v + for k, v in action_dict.items() + } + + def _convert_action_to_tensor(self, action): + """Convert action to torch tensor format. + + Args: + action: Action in various formats (dict, list of dicts, numpy array, list, torch tensor). + For tensors/arrays, should be (num_envs, action_dim) shaped. + A flat (action_dim,) tensor is accepted for single-env and reshaped to (1, action_dim). + For dicts, should be a list of dicts (one per env), or a single dict for single-env. + + Returns: + th.Tensor of shape (num_envs, action_dim), or list of dicts (one per env). + """ + if isinstance(action, dict): + return [self._convert_action_dict_to_tensor(action)] + elif isinstance(action, list) and len(action) > 0 and isinstance(action[0], dict): + return [self._convert_action_dict_to_tensor(a) for a in action] + elif isinstance(action, Iterable): + # Convert numpy arrays and lists to tensors + action = th.as_tensor(action, dtype=th.float) + if action.dim() == 1: + action = action.unsqueeze(0) + return action + return action + + def step(self, action, n_render_iterations=1): + """ + Apply robot's action and return the next state, reward, done and info, + following OpenAI Gym's convention + + Args: + action (gym.spaces.Dict or dict or list[dict] or th.tensor): robot actions. If a dict is specified, + each entry should map robot name to corresponding action. If a th.tensor, it should be the flattened, + concatenated set of actions. For multi-env, should be (num_envs, action_dim) shaped for tensors, + or a list of dicts (one per env) for dict actions. + n_render_iterations (int): Number of rendering iterations to use before returning observations + Returns: + 5-tuple: + - list[dict]: states, i.e. next observations per env + - th.Tensor: (num_envs,) rewards, i.e. reward at this current timestep + - th.Tensor: (num_envs,) terminated bool, i.e. whether this episode ended due to a failure or success + - th.Tensor: (num_envs,) truncated bool, i.e. whether this episode ended due to a time limit etc. + - list[dict]: info per env, i.e. dictionary with any useful information + """ + # Pre-processing before stepping simulation + action = self._convert_action_to_tensor(action) + if action is not None: + for env_idx in range(self.num_envs): + env_action = action[env_idx] + + scene = self._scenes[env_idx] + + # If the action is not a dictionary, convert into a dictionary + if not isinstance(env_action, dict) and not isinstance(env_action, gym.spaces.Dict): + action_dict = dict() + idx = 0 + for robot in scene.robots: + action_dim = robot.action_dim + action_dict[robot.name] = env_action[idx : idx + action_dim] + idx += action_dim + else: + # Our inputted action is the action dictionary + action_dict = env_action + + # Iterate over all robots and apply actions + for robot in scene.robots: + robot.apply_action(action_dict[robot.name]) + + # Step simulation + og.sim.step() + + # Render any additional times requested + for _ in range(n_render_iterations - 1): + og.sim.render() + + # Grab observations + obs_list, obs_info_list = self.get_obs() + + # Step the scene graph builders if necessary + for builder, scene in zip(self._scene_graph_builders, self._scenes): + builder.step(scene) + + # Grab reward, done, and info, and populate with internal info + rewards, dones, infos = self.task.step(self, action) + self._populate_info(infos) + for env_idx in range(self.num_envs): + infos[env_idx]["obs_info"] = obs_info_list[env_idx] + + # Split terminated vs truncated per env + terminateds = th.zeros(self.num_envs, dtype=th.bool) + truncateds = th.zeros(self.num_envs, dtype=th.bool) + for env_idx in range(self.num_envs): + for tc_name, tc_data in infos[env_idx]["done"]["termination_conditions"].items(): + if tc_data["done"]: + if tc_name == "timeout": + truncateds[env_idx] = True + else: + terminateds[env_idx] = True + + assert th.all((terminateds | truncateds) == dones), "Terminated and truncated must match done!" + + # Auto-reset only done envs + done_mask = dones + if self._automatic_reset and done_mask.any(): + done_indices = th.where(done_mask)[0] + for env_idx in done_indices: + # Add lost observation to our information dict, and reset + infos[env_idx.item()]["last_observation"] = obs_list[env_idx.item()] + reset_obs_list, reset_info = self.reset(env_indices=done_indices) + for i, env_idx in enumerate(done_indices): + obs_list[env_idx.item()] = reset_obs_list[i] + + # Increment step + self._current_steps += 1 + return obs_list, rewards, terminateds, truncateds, infos + + def render(self): + """Render the environment for debug viewing.""" + # Only works if there is an external sensor + if not self._external_sensors: + return None + + # Get the RGB sensors + rgb_sensors = [ + x + for x in self._external_sensors[0].values() + if isinstance(x, VisionSensor) and (x.modalities == "all" or "rgb" in x.modalities) + ] + if not rgb_sensors: + return None + + # Render the external sensor + og.sim.render() + + # Grab the rendered image from each of the rgb sensors, concatenate along dim 1 + rgb_images = [sensor.get_obs()[0]["rgb"] for sensor in rgb_sensors] + return th.cat(rgb_images, dim=1)[:, :, :3] + + def _reset_variables(self): + """ + Reset bookkeeping variables for the next new episode. + """ + self._current_episodes += 1 + self._current_steps[:] = 0 + + def reset(self, env_indices=None, get_obs=True, **kwargs): + """ + Reset episode. + + Args: + env_indices (None or th.Tensor): Indices of envs to reset. If None, resets all. + get_obs (bool): Whether to return observations after reset. + """ + if env_indices is None: + env_indices = th.arange(self.num_envs) + + # Reset the task + self.task.reset(self, env_indices=env_indices) + + # Reset internal variables + self._current_episodes[env_indices] += 1 + self._current_steps[env_indices] = 0 + + if get_obs: + # Run a single simulator step and a replicator step + og.sim.step() + # Render to make sure we can grab updated observations. With 0 rerenders (IsaacLab-style), + # camera observations are one step stale; the default of 3 guarantees fresh annotator data. + for _ in range(self._num_rerenders_on_reset): + og.sim.render() + # Grab and return observations + obs_list, info_list = self.get_obs(env_indices=env_indices) + + if self._loaded: + # Sanity check to make sure received observations match expected observation space + check_obs = recursively_generate_compatible_dict(dic=obs_list[0]) + if not self.observation_space.contains(check_obs): + exp_obs = dict() + for key, value in recursively_generate_flat_dict(dic=self.observation_space).items(): + exp_obs[key] = ("obs_space", key, value.dtype, value.shape) + real_obs = dict() + for key, value in recursively_generate_flat_dict(dic=check_obs).items(): + if isinstance(value, th.Tensor): + real_obs[key] = ("obs", key, value.dtype, value.shape) + else: + real_obs[key] = ("obs", key, type(value), "()") + + exp_keys = set(exp_obs.keys()) + real_keys = set(real_obs.keys()) + shared_keys = exp_keys.intersection(real_keys) + missing_keys = exp_keys - real_keys + extra_keys = real_keys - exp_keys + + if missing_keys: + log.error("MISSING OBSERVATION KEYS:") + log.error(missing_keys) + if extra_keys: + log.error("EXTRA OBSERVATION KEYS:") + log.error(extra_keys) + + mismatched_keys = [] + for k in shared_keys: + if exp_obs[k][2:] != real_obs[k][2:]: # Compare dtypes and shapes + mismatched_keys.append(k) + log.error(f"MISMATCHED OBSERVATION FOR KEY '{k}':") + log.error(f"Expected: {exp_obs[k]}") + log.error(f"Received: {real_obs[k]}") + + raise ValueError("Observation space does not match returned observations!") + + return obs_list, {"obs_info": info_list} + + @property + def episode_steps(self): + """ + Returns: + th.Tensor: (num_envs,) current step count per env + """ + return self._current_steps + + @property + def task(self): + """ + Returns: + BaseTask: Active task instance + """ + return self._task + + @property + def scenes(self): + """ + Returns: + list[Scene]: All scene instances in this environment + """ + return self._scenes + + @property + def scene(self): + """ + Returns: + Scene: Active scene in this environment (first scene, for backward compatibility) + """ + assert ( + len(self._scenes) == 1 + ), "The legacy 'env.scene' property is only supported for single-scene environments!" + return self._scenes[0] + + @property + def robots(self): + """ + Returns: + list[list[BaseRobot]]: Robots per scene. robots[env_idx] -> list of robots in that scene. + """ + return [s.robots for s in self._scenes] + + @property + def external_sensors(self): + """ + Returns: + None or list[dict]: If self.env_config["external_sensors"] is specified, returns a list of dicts + (one per scene), each mapping sensor name to instantiated sensor. Otherwise, returns None + """ + return self._external_sensors + + @property + def env_config(self): + """ + Returns: + dict: Environment-specific configuration kwargs + """ + return self.config["env"] + + @property + def render_config(self): + """ + Returns: + dict: Render-specific configuration kwargs + """ + return self.config["render"] + + @property + def scene_config(self): + """ + Returns: + dict: Scene-specific configuration kwargs + """ + return self.config["scene"] + + @property + def robots_config(self): + """ + Returns: + dict: Robot-specific configuration kwargs + """ + return self.config["robots"] + + @property + def objects_config(self): + """ + Returns: + dict: Object-specific configuration kwargs + """ + return self.config["objects"] + + @property + def task_config(self): + """ + Returns: + dict: Task-specific configuration kwargs + """ + return self.config["task"] + + @property + def wrapper_config(self): + """ + Returns: + dict: Wrapper-specific configuration kwargs + """ + return self.config["wrapper"] + + @property + def default_config(self): + """ + Returns: + dict: Default configuration for this environment. May not be fully specified (i.e.: still requires @config + to be specified during environment creation) + """ + return { + # Environment kwargs + "env": { + "action_frequency": gm.DEFAULT_SIM_STEP_FREQ, + "rendering_frequency": gm.DEFAULT_RENDERING_FREQ, + "physics_frequency": gm.DEFAULT_PHYSICS_FREQ, + "device": None, + "automatic_reset": False, + "flatten_action_space": False, + "flatten_obs_space": False, + "external_sensors": None, + "num_envs": 1, + # Number of render steps after a reset before grabbing observations (see __init__) + "num_rerenders_on_reset": 3, + }, + # Rendering kwargs + "render": { + "viewer_width": 1280, + "viewer_height": 720, + }, + # Scene kwargs + "scene": { + # Traversibility map kwargs + "waypoint_resolution": 0.2, + "num_waypoints": 10, + "trav_map_resolution": 0.1, + "default_erosion_radius": 0.0, + "trav_map_with_objects": True, + "scene_instance": None, + "scene_file": None, + }, + # Robot kwargs + "robots": [], # no robots by default + # Object kwargs + "objects": [], # no objects by default + # Task kwargs + "task": { + "type": "DummyTask", + }, + # Wrapper kwargs + "wrapper": { + "type": None, + }, + } diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/env_wrapper.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/env_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..946a41fb96a6af4896307b888d91892c7513e43c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/env_wrapper.py @@ -0,0 +1,97 @@ +from copy import deepcopy + +from omnigibson.utils.python_utils import Registerable, Wrapper, classproperty, create_class_from_registry_and_config +from omnigibson.utils.ui_utils import create_module_logger + +# Global dicts that will contain mappings +REGISTERED_ENV_WRAPPERS = dict() + +# Create module logger +log = create_module_logger(module_name=__name__) + + +def create_wrapper(env, wrapper_cfg=None): + """ + Wraps environment @env with wrapper defined @wrapper_cfg + + Args: + env (og.Environment): environment to wrap + wrapper_cfg (None or dict): Specified, configuration to wrap environment with + If not specified, will default to env.wrapper_config + """ + wrapper_cfg = deepcopy(env.wrapper_config if wrapper_cfg is None else wrapper_cfg) + wrapper_type = wrapper_cfg.pop("type") + wrapper_cfg["env"] = env + + return create_class_from_registry_and_config( + cls_name=wrapper_type, + cls_registry=REGISTERED_ENV_WRAPPERS, + cfg=wrapper_cfg, + cls_type_descriptor="wrapper", + ) + + +class EnvironmentWrapper(Wrapper, Registerable): + """ + Base class for all environment wrappers in OmniGibson. In general, reset(), step(), and observation_spec() should + be overwritten + + Args: + env (OmniGibsonEnv): The environment to wrap. + """ + + def __init__(self, env): + self.env = env + + # Run super + super().__init__(obj=env) + + def step(self, action, n_render_iterations=1): + """ + By default, run the normal environment step() function + + Args: + action (th.tensor): action to take in environment + n_render_iterations (int): Number of rendering iterations to use before returning observations + Returns: + 4-tuple: + - (dict) observations from the environment + - (float) reward from the environment + - (bool) whether the current episode is terminated + - (bool) whether the current episode is truncated + - (dict) misc information + """ + return self.env.step(action, n_render_iterations=n_render_iterations) + + def reset(self, **kwargs): + """ + By default, run the normal environment reset() function. Keyword arguments (e.g. ``env_indices`` + for vectorized per-env reset, ``seed``, ``options``) are forwarded to the wrapped environment so + the wrapper stays transparent to reset. + + Returns: + dict: Environment observation space after reset occurs + """ + return self.env.reset(**kwargs) + + def observation_spec(self): + """ + By default, grabs the normal environment observation_spec + + Returns: + dict: Observations from the environment + """ + return self.env.observation_spec() + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("EnvironmentWrapper") + return classes + + @classproperty + def _cls_registry(cls): + # Global robot registry + global REGISTERED_ENV_WRAPPERS + return REGISTERED_ENV_WRAPPERS diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/hdf5_data_wrapper.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/hdf5_data_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..a6ecb7fb6b3069353873ebe9fe13ce3af0bd522f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/hdf5_data_wrapper.py @@ -0,0 +1,786 @@ +import h5py +import json +import logging +import os +import torch as th +from collections import defaultdict +from copy import deepcopy +from pathlib import Path +from typing import Any, Union + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.envs.data_wrapper import DataWrapper, DataPlaybackWrapper +from omnigibson.envs.env_base import Environment +from omnigibson.macros import gm +from omnigibson.objects.usd_object import USDObject +from omnigibson.sensors.vision_sensor import VisionSensor +from omnigibson.systems.macro_particle_system import MacroPhysicalParticleSystem +from omnigibson.tasks.behavior_task import BehaviorTask +from omnigibson.utils.asset_utils import get_omnigibson_git_hash +from omnigibson.utils.config_utils import TorchEncoder +from omnigibson.utils.ui_utils import create_module_logger + +# Create module logger +log = create_module_logger(module_name=__name__) +log.setLevel(logging.INFO) + + +class HDF5DataWrapper(DataWrapper): + """ + Specific data wrapper for writing data to HDF5 format + """ + + def __init__( + self, + env: Environment, + output_path: str, + overwrite: bool = True, + only_successes: bool = True, + flush_every_n_traj: int = 10, + compression: dict | None = None, + ): + """ + Args: + env (Environment): The environment to wrap + output_path (str): path to store hdf5 data file. Should end in .hdf5 + overwrite (bool): If set, will overwrite any pre-existing data found at @output_path. + Otherwise, will load the data and append to it + only_successes (bool): Whether to only save successful episodes + flush_every_n_traj (int): How often to flush (write) current data to file + compression (None or dict): If specified, the compression arguments to use for the hdf5 file. + For more information, check out https://docs.h5py.org/en/stable/high/dataset.html#filter-pipeline + Example: {"compression": "gzip", "compression_opts": 9} for gzip with level 9 compression + """ + # HDF5 data wrapper is single-env by design: create_dataset saves env.scene and writes + # task metadata at scene index 0. Fail fast before super().__init__ triggers create_dataset. + assert env.num_envs == 1, f"HDF5DataWrapper is single-env only; got num_envs={env.num_envs}." + + self.compression = dict() if compression is None else compression + self.hdf5_file = None + + # Run super + super().__init__( + env=env, + output_path=output_path, + overwrite=overwrite, + only_successes=only_successes, + flush_every_n_traj=flush_every_n_traj, + ) + + def create_dataset(self, output_path: str, env: Environment, overwrite: bool = True) -> None: + Path(os.path.dirname(output_path)).mkdir(parents=True, exist_ok=True) + log.info(f"\nWriting dataset hdf5 to: {output_path}\n") + self.hdf5_file = h5py.File(output_path, "w" if overwrite else "a") + if "data" not in set(self.hdf5_file.keys()): + data_grp = self.hdf5_file.create_group("data") + else: + data_grp = self.hdf5_file["data"] + + if overwrite or "config" not in set(data_grp.attrs.keys()): + # Single-env data wrapper: scene index 0 + if isinstance(env.task, BehaviorTask): + env.task.update_bddl_scope_metadata(env, env_idx=0) + scene_file = env.scene.save() + config = deepcopy(env.config) + self.add_metadata(group=data_grp, name="config", data=config) + self.add_metadata(group=data_grp, name="scene_file", data=scene_file) + self.add_metadata(group=data_grp, name="omnigibson_git_hash", data=get_omnigibson_git_hash()) + + def process_traj_to_dataset(self, traj_data: list[dict]) -> None: + traj_grp_name = f"demo_{self.traj_count}" + traj_grp = self._process_traj_to_hdf5(traj_data, traj_grp_name, nested_keys=["obs"]) + self._postprocess_traj_group(traj_grp) + + def _process_traj_to_hdf5( + self, + traj_data: list[dict], + traj_grp_name: str, + nested_keys: list[str] = ["obs"], + data_grp: h5py.Group | None = None, + ) -> h5py.Group: + """ + Processes trajectory data @traj_data and stores them as a new group under @traj_grp_name. + + Args: + traj_data (list of dict): Trajectory data, where each entry is a keyword-mapped set of data for a single + sim step + traj_grp_name (str): Name of the trajectory group to store + nested_keys (list of str): Name of key(s) corresponding to nested data in @traj_data. This specific data + is assumed to be its own keyword-mapped dictionary of numpy array values, and will be parsed + differently from the rest of the data + data_grp (None or h5py.Group): If specified, the h5py Group under which a new group wtih name + @traj_grp_name will be created. If None, will default to "data" group + + Returns: + hdf5.Group: Generated hdf5 group storing the recorded trajectory data + """ + assert len(traj_data) > 0, "Expected non-empty trajectory data" + nested_keys = set(nested_keys) + data_grp = self.hdf5_file.require_group("data") if data_grp is None else data_grp + traj_grp = data_grp.create_group(traj_grp_name) + traj_grp.attrs["num_samples"] = len(traj_data) - 1 # account for the initial obs/state from env reset + + # Create the data dictionary -- this will dynamically add keys as we iterate through our trajectory + # We need to do this because we're not guaranteed to have a full set of keys at every trajectory step; e.g. + # if the first step only has state or observations but no actions + data = defaultdict(list) + for key in nested_keys: + data[key] = defaultdict(list) + + for step_data in traj_data: + for k, v in step_data.items(): + if k in nested_keys: + for mod, step_mod_data in v.items(): + data[k][mod].append(step_mod_data) + else: + data[k].append(v) + + for k, dat in data.items(): + # Skip over all entries that have no data + if not dat: + continue + + # Create datasets for all keys with valid data + num_samples = traj_grp.attrs["num_samples"] + if k in nested_keys: + obs_grp = traj_grp.create_group(k) + for mod, traj_mod_data in dat.items(): + obs_grp.create_dataset( + mod, data=th.stack(traj_mod_data, dim=0)[:num_samples].cpu(), **self.compression + ) + else: + traj_data = ( + ( + th.stack(dat, dim=0)[:num_samples] + if isinstance(dat[0], th.Tensor) + else th.tensor(dat)[:num_samples] + ) + .cpu() + .contiguous() + ) + traj_grp.create_dataset(k, data=traj_data, **self.compression) + + return traj_grp + + def _postprocess_traj_group(self, traj_grp: h5py.Group) -> None: + """ + Runs any necessary postprocessing on the given trajectory group @traj_grp. + NOTE: This should be an in-place operation! + + Args: + traj_grp (h5py.Group): Trajectory group to postprocess + """ + # Default is no-op + pass + + def flush_current_file(self) -> None: + self.hdf5_file.flush() # Flush data to disk to avoid large memory footprint + # Retrieve the file descriptor and use os.fsync() to flush to disk + fd = self.hdf5_file.id.get_vfd_handle() + os.fsync(fd) + log.info("Flushing hdf5") + + def add_metadata(self, group: h5py.Group, name: str, data: Any) -> None: + """ + Adds metadata to the current HDF5 file under the @name key under @group + + Args: + group (hdf5.File or hdf5.Group): HDF5 object to add an attribute to + name (str): Name to assign to the data + data (Any): Data to add. Note that this only supports relatively primitive data types -- + if the data is a dictionary it will be converted into a string-json format using TorchEncoder + """ + group.attrs[name] = json.dumps(data, cls=TorchEncoder) if isinstance(data, dict) else data + + def close_dataset(self) -> None: + """ + Closes the active dataset, if open + """ + if self.hdf5_file.id.valid: + log.info( + f"\nSaved:\n" + f"{self.traj_count} trajectories / {self.step_count} total steps\n" + f"to hdf5: {self.hdf5_file.filename}\n" + ) + self.hdf5_file["data"].attrs["n_episodes"] = self.traj_count + self.hdf5_file["data"].attrs["n_steps"] = self.step_count + self.hdf5_file.close() + + +class HDF5CollectionWrapper(HDF5DataWrapper): + """ + An OmniGibson environment wrapper for collecting data in an optimized way. + + NOTE: This does NOT aggregate observations. Please use DataPlaybackWrapper to aggregate an observation + dataset! + """ + + def __init__( + self, + env: Environment, + output_path: str, + overwrite: bool = True, + only_successes: bool = True, + flush_every_n_traj: int = 10, + compression: dict | None = None, + viewport_camera_path: str = "/World/viewer_camera", + use_vr: bool = False, + obj_attr_keys: list[str] | None = None, + keep_checkpoint_rollback_data: bool = False, + enable_dump_filters: bool = True, + ): + """ + Args: + env (Environment): The environment to wrap + output_path (str): path to store hdf5 data file + viewport_camera_path (str): prim path to the camera to use when rendering the main viewport during + data collection + overwrite (bool): If set, will overwrite any pre-existing data found at @output_path. + Otherwise, will load the data and append to it + only_successes (bool): Whether to only save successful episodes + flush_every_n_traj (int): How often to flush (write) current data to file + compression (None or dict): If specified, the compression arguments to use for the hdf5 file. + For more information, check out https://docs.h5py.org/en/stable/high/dataset.html#filter-pipeline + Example: {"compression": "gzip", "compression_opts": 9} for gzip with level 9 compression + use_vr (bool): Whether to use VR headset for data collection + obj_attr_keys (None or list of str): If set, a list of object attributes that should be + cached at the beginning of every episode, e.g.: "scale", "visible", etc. This is useful + for domain randomization settings where specific object attributes not directly tied to + the object's runtime kinematic state are being modified once at the beginning of every episode, + while the simulation is stopped. + keep_checkpoint_rollback_data (bool): Whether to record any trajectory data pruned from rolling back to a + previous checkpoint + enable_dump_filters (bool): Whether to enable dump filters for optimized data collection. Defaults to True. + """ + # Store additional variables needed for optimized data collection + + # Denotes the maximum serialized state size for the current episode + self.max_state_size = 0 + + # Dict capturing serialized per-episode initial information (e.g.: scales / visibilities) about every object + self.obj_attr_keys = [] if obj_attr_keys is None else obj_attr_keys + self.init_metadata = dict() + + # Maps episode step ID to dictionary of systems and objects that should be added / removed to the simulator at + # the given simulator step. See add_transition_info() for more info + self.current_transitions = dict() + + # Cached state to rollback to if requested + self.checkpoint_states = [] + self.checkpoint_step_idxs = [] + + # Info for keeping checkpoint rollback data + self.checkpoint_rollback_trajs = dict() if keep_checkpoint_rollback_data else None + + self._is_recording = True + self.use_vr = use_vr + + # Add callbacks on import / remove objects and systems + og.sim.add_callback_on_system_init( + name="data_collection", callback=lambda system: self.add_transition_info(obj=system, add=True) + ) + og.sim.add_callback_on_system_clear( + name="data_collection", callback=lambda system: self.add_transition_info(obj=system, add=False) + ) + og.sim.add_callback_on_add_obj( + name="data_collection", callback=lambda obj: self.add_transition_info(obj=obj, add=True) + ) + og.sim.add_callback_on_remove_obj( + name="data_collection", callback=lambda obj: self.add_transition_info(obj=obj, add=False) + ) + + # Run super + super().__init__( + env=env, + output_path=output_path, + overwrite=overwrite, + only_successes=only_successes, + flush_every_n_traj=flush_every_n_traj, + compression=compression, + ) + + # Configure the simulator to optimize for data collection + self._enable_dump_filters = enable_dump_filters + if viewport_camera_path: + self._optimize_sim_for_data_collection(viewport_camera_path=viewport_camera_path) + + def update_checkpoint(self) -> None: + """ + Updates the internal cached checkpoint state to be the current simulation state. If @rollback_to_checkpoint() is + called, it will rollback to this cached checkpoint state + """ + # Save the current full state and corresponding step idx + self.disable_dump_filters() + self.checkpoint_states.append(self.scene.save(json_path=None, as_dict=True)) + self.checkpoint_step_idxs.append(len(self.current_traj_history)) + if self._enable_dump_filters: + self.enable_dump_filters() + + def rollback_to_checkpoint(self, index: int = -1) -> None: + """ + Rolls back the current state to the checkpoint stored in @self.checkpoint_states. If no checkpoint + is found, this results in reset() being called + + Args: + index (int): Index of the checkpoint to rollback to. Any checkpoints after this point will be discarded + """ + if len(self.checkpoint_states) == 0: + print("No checkpoint found, resetting environment instead!") + self.reset() + + else: + # Restore to checkpoint + self.scene.restore(self.checkpoint_states[index]) + + # Configure the simulator to optimize for data collection + self._optimize_sim_for_data_collection(viewport_camera_path=og.sim.viewer_camera.active_camera_path) + + # Prune all data stored at the current checkpoint step and beyond + checkpoint_step_idx = self.checkpoint_step_idxs[index] + n_steps_to_remove = len(self.current_traj_history) - checkpoint_step_idx + pruned_traj_history = self.current_traj_history[checkpoint_step_idx:] + self.current_traj_history = self.current_traj_history[:checkpoint_step_idx] + self.step_count -= n_steps_to_remove + + # Also prune any transition info that occurred after the checkpoint step idx + pruned_transitions = dict() + for step in tuple(self.current_transitions.keys()): + if step >= checkpoint_step_idx: + pruned_transitions[step] = self.current_transitions.pop(step) + + # Update environment env step count + self.env._current_step = checkpoint_step_idx - 1 + + # Save checkpoint rollback data if requested + if self.checkpoint_rollback_trajs is not None: + step = self.env.episode_steps + if step not in self.checkpoint_rollback_trajs: + self.checkpoint_rollback_trajs[step] = [] + self.checkpoint_rollback_trajs[step].append( + { + "step_data": pruned_traj_history, + "transitions": pruned_transitions, + } + ) + + # Prune any values after the checkpoint index + if index != -1: + self.checkpoint_states = self.checkpoint_states[: index + 1] + self.checkpoint_step_idxs = self.checkpoint_step_idxs[: index + 1] + + def _process_traj_to_hdf5( + self, + traj_data: list[dict], + traj_grp_name: str, + nested_keys: list[str] = ["obs"], + data_grp: h5py.Group | None = None, + ) -> h5py.Group: + # First pad all state values to be the same max (uniform) size + for step_data in traj_data: + state = step_data["state"] + padded_state = th.zeros(self.max_state_size, dtype=th.float32) + padded_state[: len(state)] = state + step_data["state"] = padded_state + + # Call super + traj_grp = super()._process_traj_to_hdf5(traj_data, traj_grp_name, nested_keys, data_grp) + + return traj_grp + + def _postprocess_traj_group(self, traj_grp: h5py.Group) -> None: + super()._postprocess_traj_group(traj_grp=traj_grp) + + # Add in transition info + self.add_metadata(group=traj_grp, name="transitions", data=self.current_transitions) + + # Add initial metadata information + metadata_grp = traj_grp.create_group("init_metadata") + for name, data in self.init_metadata.items(): + metadata_grp.create_dataset(name, data=data) + + # Potentially save cached checkpoint rollback data + if self.checkpoint_rollback_trajs is not None and len(self.checkpoint_rollback_trajs) > 0: + rollback_grp = traj_grp.create_group("rollbacks") + for step, rollback_trajs in self.checkpoint_rollback_trajs.items(): + for i, rollback_traj in enumerate(rollback_trajs): + rollback_traj_grp = self._process_traj_to_hdf5( + traj_data=rollback_traj["step_data"], + traj_grp_name=f"step_{step}-{i}", + nested_keys=["obs"], + data_grp=rollback_grp, + ) + self.add_metadata(group=rollback_traj_grp, name="transitions", data=rollback_traj["transitions"]) + + @property + def is_recording(self) -> bool: + return self._is_recording + + @is_recording.setter + def is_recording(self, value: bool) -> None: + self._is_recording = value + + def _record_step_trajectory( + self, + action: th.Tensor, + obs: dict, + reward: float, + terminated: bool, + truncated: bool, + info: dict, + ) -> None: + if self.is_recording: + super()._record_step_trajectory(action, obs, reward, terminated, truncated, info) + + def _optimize_sim_for_data_collection(self, viewport_camera_path: str) -> None: + """ + Configures the simulator to optimize for data collection + + Args: + viewport_camera_path (str): Prim path to the camera to use for the viewer for data collection + """ + # Disable all render products to save on speed + # See https://forums.developer.nvidia.com/t/speeding-up-simulation-2023-1-1/300072/6 + for sensor in VisionSensor.SENSORS.values(): + sensor.render_product.hydra_texture.set_updates_enabled(False) + + # Use asynchronous rendering for faster performance + # We have to do a super hacky workaround to avoid the GUI freezing, which is + # toggling these settings to be True -> False -> True + # Only setting it to True once will actually freeze the GUI for some reason! + if not gm.HEADLESS: + # Set the main viewport camera path + og.sim.viewer_camera.active_camera_path = viewport_camera_path + with og.sim.editing_usd(): + # Async rendering does not work in VR mode + if not self.use_vr: + lazy.carb.settings.get_settings().set_bool("/app/asyncRendering", True) + lazy.carb.settings.get_settings().set_bool("/app/asyncRenderingLowLatency", True) + lazy.carb.settings.get_settings().set_bool("/app/asyncRendering", False) + lazy.carb.settings.get_settings().set_bool("/app/asyncRenderingLowLatency", False) + lazy.carb.settings.get_settings().set_bool("/app/asyncRendering", True) + lazy.carb.settings.get_settings().set_bool("/app/asyncRenderingLowLatency", True) + + # Disable mouse grabbing since we're only using the UI passively + lazy.carb.settings.get_settings().set_bool("/physics/mouseInteractionEnabled", False) + lazy.carb.settings.get_settings().set_bool("/physics/mouseGrab", False) + lazy.carb.settings.get_settings().set_bool("/physics/forceGrab", False) + + # Set the dump filter for better performance + # TODO: Possibly remove this feature once we have fully tensorized state saving, which may be more efficient + if self._enable_dump_filters: + self.enable_dump_filters() + + def enable_dump_filters(self) -> None: + """ + Enables dump filters for optimized per-step state caching + """ + self.env.scene.object_registry.set_dump_filter(dump_filter=lambda obj: obj.is_active and obj.initialized) + + def disable_dump_filters(self) -> None: + """ + Disables dump filters for full state caching + """ + self.env.scene.object_registry.set_dump_filter(dump_filter=lambda obj: True) + + def reset(self) -> tuple[dict, dict]: + # Call super first + init_obs, init_info = super().reset() + + # Make sure all objects are awake to begin to guarantee we save their initial states + for obj in self.scene.objects: + obj.wake() + + # Store this initial state on the first reset entry so obs/state share step 0. + state = og.sim.dump_state(serialized=True) + step_data = { + "state": state, + "state_size": len(state), + } + self.current_traj_history = [step_data] + + # Update max state size + self.max_state_size = max(self.max_state_size, len(state)) + + # Also store initial metadata not recorded in serialized state + # This is simply serialized + metadata = {key: [] for key in self.obj_attr_keys} + for obj in self.scene.objects: + for key in self.obj_attr_keys: + metadata[key].append(getattr(obj, key)) + self.init_metadata = { + key: th.stack(vals, dim=0) if isinstance(vals[0], th.Tensor) else th.tensor(vals) + for key, vals in metadata.items() + } + + # Clear checkpoint states + self.checkpoint_states = [] + self.checkpoint_step_idxs = [] + if self.checkpoint_rollback_trajs is not None: + self.checkpoint_rollback_trajs = dict() + + return init_obs, init_info + + def _parse_step_data( + self, + action: th.Tensor, + obs: dict, + reward: float, + terminated: bool, + truncated: bool, + info: dict, + ) -> dict: + # Store dumped state, reward, terminated, truncated + step_data = dict() + state = og.sim.dump_state(serialized=True) + step_data["action"] = action + step_data["state"] = state + step_data["state_size"] = len(state) + step_data["reward"] = reward + step_data["terminated"] = terminated + step_data["truncated"] = truncated + + # Update max state size + self.max_state_size = max(self.max_state_size, len(state)) + + return step_data + + def _process_traj_to_hdf5( + self, + traj_data: list[dict], + traj_grp_name: str, + nested_keys: list[str] = ["obs"], + data_grp: h5py.Group | None = None, + ) -> h5py.Group: + # First pad all state values to be the same max (uniform) size + for step_data in traj_data: + state = step_data["state"] + padded_state = th.zeros(self.max_state_size, dtype=th.float32) + padded_state[: len(state)] = state + step_data["state"] = padded_state + + # Call super + traj_grp = super()._process_traj_to_hdf5(traj_data, traj_grp_name, nested_keys, data_grp) + + return traj_grp + + def flush_current_traj(self) -> None: + # Call super first + super().flush_current_traj() + + # Clear transition buffer and max state size + self.max_state_size = 0 + self.current_transitions = dict() + + @property + def should_save_current_episode(self) -> bool: + # In addition to default conditions, we only save the current episode if we are actually recording + return super().should_save_current_episode and self.is_recording + + def add_transition_info(self, obj: Union[USDObject, "MacroPhysicalParticleSystem"], add: bool = True) -> None: + """ + Adds transition info to the current sim step for specific object @obj. + + Args: + obj (USDObject or BaseSystem): Object / system whose information should be stored + add (bool): If True, assumes the object is being imported. Else, assumes the object is being removed + """ + # If we're at the current checkpoint idx, this means that we JUST created a checkpoint and we're still at + # the same sim step. + # This is dangerous because it means that a transition is happening that will NOT be tracked properly + # if we rollback the state -- i.e.: the state will be rolled back to just BEFORE this transition was executed, + # and will therefore not be tracked properly in subsequent states during playback. So we assert that the current + # idx is NOT the current checkpoint idx + if len(self.checkpoint_step_idxs) > 0: + assert ( + self.checkpoint_step_idxs[-1] - 1 != self.env.episode_steps + ), "A checkpoint was just updated. Any subsequent transitions at this immediate timestep will not be replayed properly!" + + if self.env.episode_steps not in self.current_transitions: + self.current_transitions[self.env.episode_steps] = { + "systems": {"add": [], "remove": []}, + "objects": {"add": [], "remove": []}, + } + + # Add info based on type -- only need to store name unless we're an object being added + info = obj.get_init_info() if isinstance(obj, USDObject) and add else obj.name + dic_key = "objects" if isinstance(obj, USDObject) else "systems" + val_key = "add" if add else "remove" + self.current_transitions[self.env.episode_steps][dic_key][val_key].append(info) + + +class HDF5PlaybackWrapper(DataPlaybackWrapper, HDF5DataWrapper): + """ + Playback wrapper for replaying data and writing to an HDF5 file + """ + + def __init__( + self, + env: Environment, + input_path: str, + output_path: str, + n_render_iterations: int = 1, + overwrite: bool = True, + only_successes: bool = False, + flush_every_n_traj: int = 10, + flush_every_n_steps=0, + full_scene_file: str | None = None, + load_room_instances: list[str] | None = None, + include_robot_control: bool = True, + include_contacts: bool = True, + compression: dict | None = None, + ): + """ + Args: + env (Environment): The environment to wrap + input_path (str): path to input hdf5 collected data file + output_path (str): path to store output hdf5 data file + n_render_iterations (int): Number of rendering iterations to use when loading each stored frame from the + recorded data + overwrite (bool): If set, will overwrite any pre-existing data found at @output_path. + Otherwise, will load the data and append to it + only_successes (bool): Whether to only save successful episodes + flush_every_n_traj (int): How often to flush (write) current data to file across episodes + flush_every_n_steps (int): How often to flush (write) current data to file within an episode. + This is useful when collecting very long trajectories that may have a large memory footprint before writing to disk. + If this is greater than 0, flush_every_n_traj must be set to 1. + full_scene_file (None or str): If specified, the full scene file to use for playback. During data collection, + the scene file stored may be partial, and this will be used to fill in the missing scene objects from the + full scene file. + load_room_instances (None or str): If specified, the room instances to load for playback. + include_robot_control (bool): Whether or not to include robot control. If False, will disable all joint control. + include_contacts (bool): Whether or not to include (enable) contacts in the sim. If False, will set all objects to be visual_only + compression (None or dict): If specified, the compression arguments to use for the hdf5 file. + """ + if flush_every_n_steps > 0: + self.current_traj_grp = None + self.traj_dsets = None + + # Run super + super().__init__( + env=env, + input_path=input_path, + output_path=output_path, + n_render_iterations=n_render_iterations, + overwrite=overwrite, + only_successes=only_successes, + flush_every_n_traj=flush_every_n_traj, + flush_every_n_steps=flush_every_n_steps, + full_scene_file=full_scene_file, + load_room_instances=load_room_instances, + include_robot_control=include_robot_control, + include_contacts=include_contacts, + compression=compression, + ) + + def flush_partial_traj(self, step_idx: int, total_steps: int, step_data: dict) -> None: + """ + Flush the current trajectory data to the currently allocated HDF5 dataset. This is used when flush_every_n_steps + is greater than 0 to incrementally write trajectory data to disk during an episode. + + Args: + step_idx (int): The index of the current step in the overall trajectory. + total_steps (int): The total number of steps in the full trajectory. + step_data (dict): The data for one step, useful for allocating trajectory data. + """ + if step_idx == 0: + self.current_traj_grp, self.traj_dsets = self._allocate_traj_to_hdf5( + step_data, + f"demo_{self.current_episode_id}", + total_step=total_steps, + ) + log.info(f"Flushing partial trajectory at step {self.current_episode_step_count}...") + assert self.flush_every_n_steps > 0, "flush_every_n_steps must be greater than 0 to flush partial trajectory" + assert ( + len(self.current_traj_history) > 0 + ), "Expected non-empty trajectory history when flushing partial trajectory" + data_length_to_flush = len(self.current_traj_history) + # At step 0, we only have observation data, so observation data will only have one more offset than others + if self.current_episode_step_count == 0: + assert data_length_to_flush == 1 + for key, dat in self.current_traj_history[0].items(): + for mod in dat.keys(): + self.traj_dsets[key][mod][0] = self.current_traj_history[0][key][mod] + else: + for key, dat in self.current_traj_history[0].items(): + if isinstance(dat, dict): + for mod in dat.keys(): + obs_data_length = ( + data_length_to_flush + if self.current_episode_step_count < total_steps + else data_length_to_flush - 1 + ) + if obs_data_length > 0: + data_to_write = th.stack( + [self.current_traj_history[i][key][mod] for i in range(obs_data_length)], dim=0 + ) + self.traj_dsets[key][mod][ + self.current_episode_step_count + - data_length_to_flush + + 1 : self.current_episode_step_count + 1 + ] = data_to_write + else: + self.traj_dsets[key][ + self.current_episode_step_count - data_length_to_flush : self.current_episode_step_count + ] = th.stack([self.current_traj_history[i][key] for i in range(data_length_to_flush)], dim=0) + # Reset the current trajectory history + self.current_traj_history = [] + + def _allocate_traj_to_hdf5(self, step_data, traj_grp_name, total_step: int, nested_keys=("obs",)): + """ + Allocate trajectory data space from @step_data given the number of total steps @total_step. + + Args: + step_data (dict): Keyword-mapped set of data for a single sim step + traj_grp_name (str): Name of the trajectory group to store + total_step (int): Total number of steps in the trajectory + nested_keys (list of str): Name of key(s) corresponding to nested data in @step_data. This specific data + is assumed to be its own keyword-mapped dictionary of numpy array values, and will be parsed + differently from the rest of the data. + Returns: + Tuple[h5py.Group, dict(str, hdf5.Dataset)]: Generated hdf5 group and datasets to store the trajectory data in the future + """ + log.info(f"Allocating trajectory data for {traj_grp_name} with total steps {total_step}...") + traj_dsets = dict() + nested_keys = set(nested_keys) + for k in nested_keys: + traj_dsets[k] = dict() + data_grp = self.hdf5_file.require_group("data") + traj_grp = data_grp.create_group(traj_grp_name) + traj_grp.attrs["num_samples"] = total_step + + for k, dat in step_data.items(): + if k in nested_keys: + obs_grp = traj_grp.create_group(k) + for mod, step_mod_data in dat.items(): + traj_dsets[k][mod] = obs_grp.create_dataset( + mod, + shape=(total_step, *step_mod_data.shape), + dtype=step_mod_data.numpy().dtype, + **self.compression, + chunks=(1, *step_mod_data.shape), + shuffle=True, + ) + else: + traj_dsets[k] = traj_grp.create_dataset( + k, shape=(total_step, *dat.shape), dtype=dat.numpy().dtype, **self.compression, shuffle=True + ) + + return traj_grp, traj_dsets + + def flush_current_traj(self): + """ + Flush current trajectory data + """ + super().flush_current_traj() + self.traj_dsets = None + self.current_episode_id = None + self.current_traj_grp = None + + def process_traj_to_dataset(self, traj_data: list[dict]) -> None: + if self.flush_every_n_steps == 0: + traj_grp_name = f"demo_{self.traj_count}" + traj_grp = self._process_traj_to_hdf5(traj_data, traj_grp_name, nested_keys=["obs"]) + self._postprocess_traj_group(traj_grp) + else: + self._postprocess_traj_group(self.current_traj_grp) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/lerobot_data_wrapper.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/lerobot_data_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..0650d85a9bba8423005f3ff4c11a3629195bb285 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/lerobot_data_wrapper.py @@ -0,0 +1,488 @@ +import logging +import os +import shutil +import torch as th +from lerobot.configs import DepthEncoderConfig, VideoEncoderConfig +from lerobot.datasets import LeRobotDataset +from lerobot.datasets.io_utils import write_info +from lerobot.utils.constants import HF_LEROBOT_HOME + +import omnigibson.utils.transform_utils as T +from omnigibson.envs.env_base import Environment +from omnigibson.envs.data_wrapper import DataWrapper, DataPlaybackWrapper +from omnigibson.eval.utils.obs_utils import DEPTH_SHIFT, MAX_DEPTH, MIN_DEPTH +from omnigibson.sensors.vision_sensor import VisionSensor +from omnigibson.utils.asset_utils import get_omnigibson_git_hash +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.tasks.behavior_task import BehaviorTask + + +# Create module logger +log = create_module_logger(module_name=__name__) +log.setLevel(logging.INFO) + + +class LeRobotDataWrapper(DataWrapper): + """ + Specific data wrapper for writing data to LeRobot format. + """ + + def __init__( + self, + env: Environment, + output_path: str, + root_dir: str = HF_LEROBOT_HOME, + overwrite: bool = True, + only_successes: bool = True, + flush_every_n_traj: int = 10, + robot_type: str | None = None, + task_name: str | None = None, + ): + """ + Args: + env (Environment): The environment to wrap + output_path (str): The path to the output lerobot dataset + root_dir (str): Root directory to store output dataset files + overwrite (bool): If set, will overwrite any pre-existing data found at @repo_id. + Otherwise, will load the data and append to it + only_successes (bool): Whether to only save successful episodes + flush_every_n_traj (int): How often to flush (write) current data to file across episodes + robot_type (None or str): Name of the robot within this dataset. If not specified, will be inferred + from environment + task_name (None or str): If specified, task that will be recorded in LeRobot dataset. If not specified, + will try to automatically infer if the wrapped environment is a BehaviorTask + """ + # LeRobot dataset assumes a single scene with a single robot for deterministic obs mapping. + # Fail fast before any env.scene / env.scene.robots[0] reads (e.g., _init_lerobot_kwargs below). + assert env.num_envs == 1, f"LeRobotDataWrapper is single-env only; got num_envs={env.num_envs}." + assert ( + len(env.scene.robots) == 1 + ), f"LeRobotDataWrapper requires exactly one robot per scene; got {len(env.scene.robots)}." + self._init_lerobot_kwargs( + repo_id=output_path, + root_dir=root_dir, + robot_type=robot_type, + env=env, + task_name=task_name, + ) + + # Run super + super().__init__( + env=env, + output_path=output_path, + overwrite=overwrite, + only_successes=only_successes, + flush_every_n_traj=flush_every_n_traj, + ) + + def _init_lerobot_kwargs( + self, + repo_id: str, + root_dir: str, + robot_type: str | None, + env: Environment, + task_name: str | None, + ) -> None: + self.lerobot_dataset_kwargs = { + "repo_id": repo_id, + "root": f"{root_dir}/{repo_id}", + "robot_type": env.scene.robots[0].__class__.__name__.lower() if robot_type is None else robot_type, + "use_videos": True, + "streaming_encoding": True, + "camera_encoder": VideoEncoderConfig( + vcodec="hevc", + pix_fmt="yuv420p", + g=8, + crf=30, + extra_options={"x265-params": "log-level=0:bframes=0"}, + ), + "depth_encoder": DepthEncoderConfig( + vcodec="hevc", + pix_fmt="gray12le", + g=8, + crf=0, + depth_min=MIN_DEPTH, + depth_max=MAX_DEPTH, + shift=DEPTH_SHIFT, + use_log=True, + output_unit="m", + extra_options={"x265-params": "log-level=0:bframes=0"}, + ), + } + self.dataset = None + self.obs_mapping = None + self.controller_action_start_idxs = None + + if task_name is None: + if isinstance(env.task, BehaviorTask): + task_name = env.task.activity_name.replace("_", " ") + else: + raise ValueError("Task name must be specified if environment task is not a BehaviorTask!") + self.task_name = task_name + + def _parse_step_data( + self, + action: th.Tensor, + obs: dict, + reward: float, + terminated: bool, + truncated: bool, + info: dict, + ) -> dict: + step_data = { + "obs": self._process_obs(obs=obs, info=info), + "action": action, + "reward": reward, + "terminated": terminated, + "truncated": truncated, + } + return step_data + + @classmethod + def get_lerobot_obs_mapping( + cls, + env: Environment, + depth_output_unit: str = "m", + ) -> tuple[dict[str, str], dict[str, dict]]: + obs_mapping, obs_features = dict(), dict() + for key, gym_shape in env.observation_space.items(): + modality = key.split("::")[-1] + info = dict() + # Parse the relevant name to assign + obs_name_strs = key.split("::")[-2].split(":") + # TODO @wensi-ai: hacky, fix this + # filter out robot if applicable + if len(obs_name_strs) == 4: + obs_name_strs = obs_name_strs[1:] + # Join with "_" and make lowercase to make final name + obs_name = "_".join(obs_name_strs).lower() + if "rgb" in modality: + info["dtype"] = "video" + info["shape"] = gym_shape.shape[:-1] + (3,) + info["names"] = ["height", "width", "channel"] + info["info"] = {"is_depth_map": False} + elif "depth" in modality: + info["dtype"] = "video" + info["shape"] = gym_shape.shape + (1,) + info["names"] = ["height", "width", "channel"] + info["info"] = { + "is_depth_map": True, + "video.output_unit": depth_output_unit, + } + + # We also add relative camera transforms (wrt robot egocentric frame) in case we + # want to convert depth to point clouds + # So we add an extra entry here + tf_name = f"observation.robot2cam_pose.{obs_name}" + if tf_name not in obs_features: + obs_features[tf_name] = { + "dtype": "float32", + "shape": (7,), + "names": None, + } + + elif "proprio" in modality or "low_dim" in modality: + info["dtype"] = "float32" + info["shape"] = gym_shape.shape + info["names"] = (None,) + else: + raise ValueError(f"Got LeRobot-incompatible observation modality: {modality}") + + # Add this key to features, and store the obs name mapping + lerobot_obs_name = "observation.state" if "proprio" in modality else f"observation.{modality}.{obs_name}" + obs_features[lerobot_obs_name] = info + obs_mapping[key] = lerobot_obs_name + + return obs_mapping, obs_features + + def _validate_video_fps(self) -> None: + for video_key in self.dataset.meta.video_keys: + video_fps = (self.dataset.meta.features[video_key].get("info") or {}).get("video.fps") + if video_fps is not None and video_fps != self.fps: + raise ValueError(f"Encoded video {video_key} has fps={video_fps}, expected fps={self.fps}") + + def _process_obs(self, obs: dict[str, th.Tensor], info: dict) -> dict[str, th.Tensor]: + # Add tfs to flattened obs (single-env wrapper: scene index 0) + robot_tf_inv = T.pose_inv(T.pose2mat(self.env.scene.robots[0].get_position_orientation())) + external_sensors = self.env.external_sensors[0] if self.env.external_sensors is not None else None + for sensor_group in (external_sensors, self.env.scene.robots[0].sensors): + if sensor_group is None: + continue + for name, sensor in sensor_group.items(): + obs[f"{name}::rel_pose"] = th.cat( + T.mat2pose(robot_tf_inv @ T.pose2mat(sensor.get_position_orientation())) + ) + + # Compose lerobot format obs + frame = dict() + for name in self.env.observation_space.keys(): + cur_obs = obs[name] + # Prune alpha channel if keeping RGB + if "rgb" in name: + cur_obs = cur_obs[..., :3] + elif "depth" in name: + # Add channel dim at the end + cur_obs = cur_obs.unsqueeze(-1) + # If we haven't already added the sensor pose obs, do so now + obs_name_strs = name.split("::")[-2].split(":") + # TODO @wensi-ai: hacky, fix this + # filter out robot if applicable + if len(obs_name_strs) == 4: + obs_name_strs = obs_name_strs[1:] + # Join with "_" and make lowercase to make final name + obs_name = "_".join(obs_name_strs).lower() + tf_name = f"observation.robot2cam_pose.{obs_name}" + if tf_name not in frame: + sensor_name = name.split("::")[-2] + frame[tf_name] = obs[f"{sensor_name}::rel_pose"] + elif "proprio" in name: + # Map float64 -> float32 + cur_obs = cur_obs.float() + # Add the observation to the current frame + frame[self.obs_mapping[name]] = cur_obs + + return frame + + def create_dataset(self, output_path: str, env: Environment, overwrite: bool = True) -> None: + # Sanity checks + assert ( + output_path == self.lerobot_dataset_kwargs["repo_id"] + ), f"Expected LeRobot repo_id path ({self.lerobot_dataset_kwargs['repo_id']}) to match output_path ({output_path})!" + + abs_output_path = f"{self.lerobot_dataset_kwargs['root']}" + + resume = False + if os.path.exists(abs_output_path): + if overwrite: + # Remove any data from this path + shutil.rmtree(abs_output_path) + log.info(f"Overwriting existing LeRobot dataset at: {abs_output_path}") + else: + resume = True + log.info(f"Resuming from existing LeRobot dataset at: {abs_output_path}") + + # For now, we only support a single scene with a single robot for the sake of deterministic mapping of robot obs + assert ( + len(env.scenes) == 1 and len(env.scene.robots) == 1 + ), "Only one scene with one robot supported for LeRobot dataset storage!" + robot = env.scene.robots[0] + + # Create LeRobot dataset, define features to store + # Define standard features (RL-related entries, language instructions) + features = { + "action": { + "dtype": "float32", + "shape": env.action_space[robot.name].shape, + "names": ["action"], + }, + # RL-specific fields + "next.reward": { + "dtype": "float32", + "shape": (1,), + "names": ["reward"], + }, + "next.terminated": { + "dtype": "bool", + "shape": (1,), + "names": ["done"], + }, + "next.truncated": { + "dtype": "bool", + "shape": (1,), + "names": ["done"], + }, + } + + obs_mapping, obs_features = self.get_lerobot_obs_mapping( + env=env, + depth_output_unit=self.lerobot_dataset_kwargs["depth_encoder"].output_unit, + ) + self.obs_mapping = obs_mapping + features.update(obs_features) + + if not resume: + self.dataset = LeRobotDataset.create( + fps=self.fps, + features=features, + **self.lerobot_dataset_kwargs, + ) + else: + resume_kwargs = { + key: value + for key, value in self.lerobot_dataset_kwargs.items() + if key not in {"robot_type", "use_videos"} + } + self.dataset = LeRobotDataset.resume( + **resume_kwargs, + ) + + # Add in camera K matrices + cam_intrinsics = dict() + + external_sensors = env.external_sensors[0] if env.external_sensors is not None else {} + for sensor_name, sensor in external_sensors.items(): + if isinstance(sensor, VisionSensor): + K = sensor.intrinsic_matrix.cpu() + cam_intrinsics[sensor_name] = K.numpy().tolist() + for sensor_name, sensor in env.scene.robots[0].sensors.items(): + if isinstance(sensor, VisionSensor): + # Remove robot naming prefix + sensor_name = "_".join(sensor_name.split(":")[1:]).lower() + K = sensor.intrinsic_matrix.cpu() + cam_intrinsics[sensor_name] = K.numpy().tolist() + self.dataset.meta.info["cam_intrinsics"] = cam_intrinsics + self.dataset.meta.info["omnigibson_git_hash"] = get_omnigibson_git_hash() + write_info(self.dataset.meta.info, self.dataset.meta.root) + + def process_traj_to_dataset(self, traj_data: list[dict]) -> None: + # Write to LeRobot dataset + # The dataset length is (N_steps + 1), since the first entry only includes the env reset observations + # LeRobot expects (s,a) tuples to be paired with rewards from the next step, so we match the obs with + # all other entries from the proceeding (i.e.: t+1) step + + for frame_idx, traj_step in enumerate(traj_data): + if frame_idx == 0: + assert ( + len(traj_step.keys()) == 1 + ), f"Expected only one key in 0th traj step, but got: {traj_step.keys()}" + assert "obs" in traj_step, f"Expected 'obs' key in 0th traj step, but got: {traj_step.keys()}" + continue + + # Compose frame to add to dataset + frame = { + "action": traj_step["action"], + "next.reward": th.tensor([traj_step["reward"]]), + "next.terminated": th.tensor([traj_step["terminated"]]), + "next.truncated": th.tensor([traj_step["truncated"]]), + **traj_data[frame_idx - 1]["obs"], + } + frame["task"] = self.task_name + + self.dataset.add_frame(frame=frame) + + self.dataset.save_episode() + self._validate_video_fps() + + def flush_current_file(self) -> None: + # Does nothing currently + pass + + def close_dataset(self) -> None: + self.dataset.finalize() + + +class LeRobotPlaybackWrapper(DataPlaybackWrapper, LeRobotDataWrapper): + """ + An OmniGibson environment wrapper for playing back data and collecting observations to be stored in LeRobotV3 format + + NOTE: This assumes a HDF5CollectionWrapper environment has been used to collect data! + """ + + def __init__( + self, + env: Environment, + input_path: str, + output_path: str, + n_render_iterations: int = 1, + overwrite: bool = True, + only_successes: bool = False, + flush_every_n_traj: int = 10, + flush_every_n_steps: int = 0, + full_scene_file: str | None = None, + load_room_instances: list[str] | None = None, + include_robot_control: bool = True, + include_contacts: bool = True, + root_dir: str = HF_LEROBOT_HOME, + robot_type: str | None = None, + task_name: str | None = None, + ): + """ + Args: + env (Environment): The environment to wrap + input_path (str): path to input hdf5 collected data file + output_path (str): path to the output lerobot dataset. This value is synonymous with lerobot's + @repo_id key, and should specify the name of the repo for saving the dataset, e.g. / + n_render_iterations (int): Number of rendering iterations to use when loading each stored frame from the + recorded data + overwrite (bool): If set, will overwrite any pre-existing data found at @output_path. + Otherwise, will load the data and append to it + only_successes (bool): Whether to only save successful episodes + flush_every_n_traj (int): How often to flush (write) current data to file across episodes + flush_every_n_steps (int): How often to flush (write) current data to file within an episode. + This is useful when collecting very long trajectories that may have a large memory footprint before writing to disk. + If this is greater than 0, flush_every_n_traj must be set to 1. + full_scene_file (None or str): If specified, the full scene file to use for playback. During data collection, + the scene file stored may be partial, and this will be used to fill in the missing scene objects from the + full scene file. + load_room_instances (None or str): If specified, the room instances to load for playback. + include_robot_control (bool): Whether or not to include robot control. If False, will disable all joint control. + include_contacts (bool): Whether or not to include (enable) contacts in the sim. If False, will set all objects to be visual_only + root_dir (str): Root directory to store output dataset files + robot_type (None or str): Name of the robot within this dataset. If not specified, will be inferred + from environment + task_name (None or str): If specified, task that will be recorded in LeRobot dataset. If not specified, + will try to automatically infer if the wrapped environment is a BehaviorTask + """ + # Run super + super().__init__( + env=env, + input_path=input_path, + output_path=output_path, + n_render_iterations=n_render_iterations, + overwrite=overwrite, + only_successes=only_successes, + flush_every_n_traj=flush_every_n_traj, + flush_every_n_steps=flush_every_n_steps, + full_scene_file=full_scene_file, + load_room_instances=load_room_instances, + include_robot_control=include_robot_control, + include_contacts=include_contacts, + root_dir=root_dir, + robot_type=robot_type, + task_name=task_name, + ) + + def flush_partial_traj(self, step_idx: int, total_steps: int, step_data: dict) -> None: + """ + Flush the current trajectory data to the LeRobot dataset. This is used when flush_every_n_steps + is greater than 0 to incrementally write trajectory data to disk during an episode. + + With streaming encoding enabled, video data is written to disk in real-time via encoder threads. + This method adds frames to the dataset, then resets the trajectory history to free memory. + + Args: + step_idx (int): The index of the current step in the overall trajectory. + total_steps (int): The total number of steps in the full trajectory. + step_data (dict): The data for one step, useful for allocating trajectory data. + """ + log.info(f"Flushing partial trajectory at step {self.current_episode_step_count}...") + assert self.flush_every_n_steps > 0, "flush_every_n_steps must be greater than 0 to flush partial trajectory" + assert ( + len(self.current_traj_history) > 0 + ), "Expected non-empty trajectory history when flushing partial trajectory" + # Add frames to the LeRobot dataset incrementally + # Skip the first step (only has obs from reset, no action/reward) + for frame_idx in range(1, len(self.current_traj_history)): + traj_step = self.current_traj_history[frame_idx] + + # Compose frame to add to dataset (same format as process_traj_to_dataset) + frame = { + "action": traj_step["action"], + "next.reward": th.tensor([traj_step["reward"]]), + "next.terminated": th.tensor([traj_step["terminated"]]), + "next.truncated": th.tensor([traj_step["truncated"]]), + **self.current_traj_history[frame_idx - 1]["obs"], + } + if self.task_name: + frame["task"] = self.task_name + + self.dataset.add_frame(frame=frame) + + # Keep the last observation for pairing with next segment's first action + # This is needed because obs[t] pairs with action[t+1], and after reset we need + # the previous observation to pair with the new action + last_step = self.current_traj_history[-1] + assert ( + "obs" in last_step + ), f"Expected 'obs' key in last step of trajectory history to keep for next segment, but got: {last_step.keys()}" + self.current_traj_history = [{"obs": last_step["obs"]}] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/metrics_wrapper.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/metrics_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..0c4548ca39ea9413d2a8aba046aaa0310823bf80 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/envs/metrics_wrapper.py @@ -0,0 +1,85 @@ +from typing import Iterable + +from omnigibson.envs.env_base import Environment +from omnigibson.envs.env_wrapper import EnvironmentWrapper +from omnigibson.metrics.metric_base import MetricBase +from omnigibson.utils.gym_utils import recursively_generate_flat_dict + + +class MetricsWrapper(EnvironmentWrapper): + """ + Wrapper for running programmatic metric checks during env stepping + """ + + def __init__(self, env: Environment) -> None: + """ + Args: + env (Environment): The environment to wrap + """ + # Store variable for tracking QA metrics + self.metrics = dict() + + # Run super init + super().__init__(env=env) + + def add_metric(self, name: str, metric: MetricBase) -> None: + """ + Adds a data metric to track + + Args: + name (str): Name of the metric. This will be the name printed out when displaying the aggregated results + metric (MetricBase): Metric to add + """ + # Validate the metric is compatible, then add + assert metric.is_compatible( + self + ), f"Metric {metric.__class__.__name__} is not compatible with this environment!" + self.metrics[name] = metric + + def remove_metric(self, name: str) -> None: + """ + Removes a metric from the internally tracked ones + + Args: + name (str): Name of the metric to remove + """ + self.metrics.pop(name) + + def reset(self): + # Call super first + ret = super().reset() + + # Reset all owned metrics + for name, metric in self.metrics.items(): + metric.reset(self) + + return ret + + def aggregate_metrics(self, flatten: bool = True) -> dict: + """ + Aggregates metrics information + + Args: + flatten (bool): Whether to flatten the metrics dictionary or not + + Returns: + dict: Keyword-mapped aggregated metrics information + """ + results = dict() + for name, metric in self.metrics.items(): + results[name] = metric.aggregate(self) + + if flatten: + results = recursively_generate_flat_dict(dic=results) + + return results + + def step(self, action: dict | Iterable, n_render_iterations: int = 1) -> tuple: + # Run super first + obs, reward, terminated, truncated, info = super().step(action, n_render_iterations=n_render_iterations) + + # Run all step-wise QA checks + for name, metric in self.metrics.items(): + metric.step(self.env, action, obs, reward, terminated, truncated, info) + + return obs, reward, terminated, truncated, info diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/eval.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/eval.py new file mode 100644 index 0000000000000000000000000000000000000000..caed12dbe2979aebf4f40baa96bc98bd0fca94fc --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/eval.py @@ -0,0 +1,199 @@ +"""Websocket evaluation runner for the BEHAVIOR-1K challenge. + +Drives the OmniGibson ``BatchedEvaluator`` against a policy served over a websocket +(e.g. the openpi or GR00T ``scripts/b1k/serve_b1k.py`` server). For each test instance of a +task it runs a rollout and writes a per-rollout result JSON compatible with +``omnigibson/eval/utils/score_utils.py`` (``q_score``, ``time``, +``agent_distance`` / ``normalized_agent_distance``). + +Example: + python -m omnigibson.eval.eval \ + --task-name turning_on_radio \ + --robot-config omnigibson/eval/r1pro.yaml \ + --mode public_test \ + --host 127.0.0.1 --port 8000 \ + --instance-indices 0 --max-steps 500 \ + --output-dir outputs/b1k_eval --write-video +""" + +import argparse +import logging +import os +from pathlib import Path + +from omegaconf import OmegaConf + +from omnigibson.eval.evaluator import BatchedEvaluator, resolve_instance_ids +from omnigibson.eval.utils.eval_utils import DEFAULT_EVAL_SEED, seed_everything +from omnigibson.macros import gm +from omnigibson.utils.ui_utils import create_module_logger + + +logger = create_module_logger(module_name=__name__) +logger.setLevel(logging.INFO) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--task-name", required=True, help="BEHAVIOR task name, e.g. turning_on_radio.") + parser.add_argument("--host", default="127.0.0.1", help="Policy websocket server host.") + parser.add_argument("--port", type=int, default=8000, help="Policy websocket server port.") + parser.add_argument( + "--robot-config", + type=str, + default=None, + help=( + "Optional path to YAML/JSON file containing one complete robot config dictionary with canonical " + "'model' and 'name' fields. Add eval.camera_sensor_names to configure eval camera roles." + ), + ) + parser.add_argument( + "--instance-indices", + type=int, + nargs="+", + default=[0], + help=( + "Instance indices for the selected mode. For train these are direct train instance IDs; " + "for public_test / hidden_test these index into that 20-instance split." + ), + ) + parser.add_argument( + "--mode", + choices=("train", "public_test", "hidden_test"), + default="public_test", + help="Instance split to evaluate. Default: public_test.", + ) + parser.add_argument("--num-rollouts", type=int, default=1, help="Rollouts per instance.") + parser.add_argument( + "--num-envs", + type=int, + default=1, + help="Number of logical environments in the evaluation batch. Must equal the number of instance indices.", + ) + parser.add_argument( + "--replay-action-chunk-size", + type=int, + default=0, + help=( + "Opt in to exact client-side replay of a complete server-returned action chunk. " + "Use the receding-horizon length (for example 16); 0 keeps one websocket request per step." + ), + ) + parser.add_argument( + "--max-steps", + type=int, + default=None, + help="Episode timeout in steps. Default (None) = 1.5x mean human-demo length.", + ) + parser.add_argument( + "--env-wrapper", + default="omnigibson.eval.wrappers.DefaultWrapper", + help="Target path of the EnvironmentWrapper to apply.", + ) + parser.add_argument( + "--policy", + choices=("websocket", "local"), + default="websocket", + help="Policy backend to use. local emits zero actions and is intended for eval smoke tests.", + ) + parser.add_argument("--output-dir", default="/tmp/b1k_eval", help="Where to write result JSONs.") + parser.add_argument( + "--write-video", + action=argparse.BooleanOptionalAction, + default=False, + help="Save an MP4 rollout video (head + wrist cameras) per rollout under /videos.", + ) + parser.add_argument("--video-fps", type=int, default=30, help="Frame rate for saved rollout videos.") + parser.add_argument( + "--headless", + action=argparse.BooleanOptionalAction, + default=True, + help="Run OmniGibson headless (default: True).", + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + + gm.HEADLESS = args.headless + # Headless evaluation consumes robot-camera observations through VisionSensor / TiledVisionSensor render + # products, not the separate 1280x720 debug viewport. Avoid constructing that unused viewer product: at + # N=10 it accounts for two of five RTX tile passes while policy camera shapes and traces remain unchanged. + # The environment override restores the old path only for controlled performance A/B runs. + if args.headless and os.getenv("OMNIGIBSON_KEEP_VIEWER_CAMERA", "0") != "1": + gm.RENDER_VIEWER_CAMERA = False + + seed = seed_everything(DEFAULT_EVAL_SEED) + logger.info(f"Seeded Python, NumPy, and Torch with seed={seed}") + + instance_ids = resolve_instance_ids(args.task_name, args.instance_indices, mode=args.mode) + logger.info(f"Resolved {args.mode} instance ids for {args.task_name}: {instance_ids}") + if len(instance_ids) != args.num_envs: + raise ValueError( + "Evaluation requires exactly one instance per logical environment: " + f"got {len(instance_ids)} instance indices and --num-envs={args.num_envs}." + ) + + robot_config = None + if args.robot_config is not None: + robot_config_path = Path(args.robot_config).expanduser() + robot_config = OmegaConf.load(str(robot_config_path)) + logger.info(f"Loaded robot config from {robot_config_path}") + + if args.policy == "websocket": + model_cfg = { + "_target_": "omnigibson.eval.policies.WebsocketPolicy", + "host": args.host, + "port": args.port, + "action_chunk_size": args.replay_action_chunk_size, + } + else: + model_cfg = {"_target_": "omnigibson.eval.policies.LocalPolicy", "action_dim": None} + + cfg = OmegaConf.create( + { + "env_wrapper": {"_target_": args.env_wrapper}, + "policy_name": args.policy, + "model": model_cfg, + "headless": args.headless, + "partial_scene_load": True, + "max_steps": args.max_steps, + "write_video": args.write_video, + "mode": args.mode, + "seed": seed, + "num_envs": args.num_envs, + "task": {"name": args.task_name}, + "robot": robot_config, + } + ) + + json_dir = os.path.join(os.path.expanduser(args.output_dir), "json") + os.makedirs(json_dir, exist_ok=True) + video_dir = os.path.join(os.path.expanduser(args.output_dir), "videos") + if args.write_video: + os.makedirs(video_dir, exist_ok=True) + + results = [] + with BatchedEvaluator(cfg) as evaluator: + # Each run() pass evaluates the selected instances together in one parallel batch. The outer + # loop repeats that same batch for additional rollouts. + for rollout_id in range(args.num_rollouts): + rollout_results = evaluator.run( + [int(i) for i in instance_ids], + write_video=args.write_video, + video_path=video_dir, + metrics_dir=json_dir, + rollout_id=rollout_id, + video_fps=args.video_fps, + ) + results.extend(rollout_results.values()) + + n = len(results) + n_success = sum(r["success"] for r in results) + mean_q = (sum(r.get("q_score", {}).get("final", 0.0) for r in results) / n) if n else 0.0 + logger.info(f"Eval summary: {n_success}/{n} success | mean q_score={mean_q:.3f} | task={args.task_name}") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/evaluator.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..eae73ea55075a6715e68cb8ed9b133a60528a1ee --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/evaluator.py @@ -0,0 +1,736 @@ +import cv2 +import json +import logging +import os +import sys +import traceback +from dataclasses import dataclass, field +from signal import SIGINT, signal +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple + +import numpy as np +import torch as th +from hydra.utils import get_class, instantiate +from omegaconf import DictConfig, OmegaConf + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from gello.utils.og_teleop_cfg import DISABLED_TRANSITION_RULES +from gello.utils.og_teleop_utils import load_available_tasks +from omnigibson.envs.env_wrapper import EnvironmentWrapper +from omnigibson.eval.utils.eval_utils import ( + EVAL_TIMEOUT_MULTIPLIER, + NUM_HIDDEN_TEST_INSTANCES, + NUM_PUBLIC_TEST_INSTANCES, + TASK_NAMES_TO_INDICES, + TASK_NAMES_TO_ROOMS, + TEST_INSTANCE_IDS, + flatten_obs_dict, + generate_basic_environment_config, + get_robot_camera_names, +) +from omnigibson.eval.utils.light_utils import LightToggleSynchronizer, set_light_control_toggles +from omnigibson.eval.utils.obs_utils import create_video_writer, write_video +from omnigibson.eval.utils.score_utils import load_human_stats +from omnigibson.macros import gm +from omnigibson.metrics import AgentMetric, MetricBase, TaskMetric +from omnigibson.robots import Robot +from omnigibson.tasks.behavior_task import get_presampled_robot_poses +from omnigibson.utils.asset_utils import get_task_instance_path +from omnigibson.utils.bddl_utils import is_system_bddl_inst +from omnigibson.utils.python_utils import recursively_convert_to_torch +from omnigibson.utils.ui_utils import create_module_logger + +TORCH_NUM_THREADS = None +TORCH_NUM_INTEROP_THREADS = None + +if TORCH_NUM_THREADS is not None: + th.set_num_threads(TORCH_NUM_THREADS) +if TORCH_NUM_INTEROP_THREADS is not None: + th.set_num_interop_threads(TORCH_NUM_INTEROP_THREADS) + +LIGHT_EVAL_TASKS = {"turning_out_all_lights_before_sleep"} +EVAL_BASE_LINK_MASS = 250.0 +EVAL_HEAD_HORIZONTAL_APERTURE = 40.0 +DEFAULT_ROBOT_CONFIG_PATH = os.path.join(os.path.dirname(__file__), "r1pro.yaml") +EVAL_MODES = ("train", "public_test", "hidden_test") + +gm.USE_GPU_DYNAMICS = False +gm.ENABLE_TRANSITION_RULES = True + +logger = create_module_logger(module_name=__name__) +logger.setLevel(logging.INFO) + + +def _to_plain_dict(cfg: Any) -> dict | None: + if cfg is None: + return None + if isinstance(cfg, DictConfig): + cfg = OmegaConf.to_container(cfg, resolve=True) + return dict(cfg) + + +def resolve_instance_ids(task_name: str, instance_indices: list[int], mode: str = "public_test") -> list[int]: + assert mode in EVAL_MODES, f"Mode must be one of {EVAL_MODES}, got {mode}" + if mode == "train": + return [int(instance_id) for instance_id in instance_indices] + + test_instances = ( + TEST_INSTANCE_IDS[:NUM_PUBLIC_TEST_INSTANCES] + if mode == "public_test" + else TEST_INSTANCE_IDS[NUM_PUBLIC_TEST_INSTANCES:] + ) + num_split_instances = NUM_PUBLIC_TEST_INSTANCES if mode == "public_test" else NUM_HIDDEN_TEST_INSTANCES + assert set(instance_indices).issubset( + set(range(num_split_instances)) + ), f"Instance indices must be in range({num_split_instances}) for mode {mode}" + return [int(test_instances[i]) for i in instance_indices] + + +def evaluate_instances_batched( + instances: Sequence, + num_envs: int, + load_fn: Callable[[Dict[int, object]], None], + step_fn: Callable[[List[int]], "tuple[Sequence[bool], Sequence[bool]]"], + record_fn: Callable[..., object], + max_steps: Optional[int] = None, +) -> "Dict[object, object]": + """ + Drive one parallel evaluation batch with exactly one instance per logical environment. Pure + orchestration: all sim work is delegated to the injected load_fn / step_fn / record_fn. When an + instance finishes, its environment is removed from the active list and remains frozen until the + complete batch finishes. Returns {instance id -> record_fn's return}. + """ + if num_envs < 1: + raise ValueError(f"num_envs must be >= 1, got {num_envs}") + + instances = list(instances) + if len(instances) != num_envs: + raise ValueError( + f"Evaluation requires exactly one instance per logical environment: " + f"got {len(instances)} instances and num_envs={num_envs}." + ) + + results: Dict[object, object] = {} + env_idx_to_instance: Dict[int, object] = {env_idx: instance for env_idx, instance in enumerate(instances)} + load_fn(dict(env_idx_to_instance)) + + active = {env_idx: True for env_idx in env_idx_to_instance} + step = 0 + while any(active.values()): + active_env_indices = sorted(env_idx for env_idx, is_active in active.items() if is_active) + terminated, truncated = step_fn(active_env_indices) + step += 1 + + hit_cap = max_steps is not None and step >= max_steps + for env_idx in active_env_indices: + term = bool(terminated[env_idx]) + trunc = bool(truncated[env_idx]) or hit_cap + if term or trunc: + results[env_idx_to_instance[env_idx]] = record_fn( + env_idx=env_idx, + instance=env_idx_to_instance[env_idx], + step=step, + terminated=term, + truncated=trunc, + ) + active[env_idx] = False + + return results + + +@dataclass(frozen=True) +class InstanceEnvAccessor: + """Read-only access to one logical environment inside a shared vectorized environment.""" + + shared_env: EnvironmentWrapper + env_idx: int + + @property + def scene(self): + return self.shared_env.scenes[self.env_idx] + + @property + def robot(self) -> Robot: + robots = self.scene.robots + assert len(robots) == 1, f"Evaluation assumes one robot per environment, got {len(robots)}." + return robots[0] + + @property + def object_scope(self): + return self.shared_env.task.object_scopes[self.env_idx] + + @property + def success(self) -> bool: + return bool(self.shared_env.task.success[self.env_idx]) + + def get_goal_option_satisfaction(self): + return self.shared_env.task.get_goal_option_satisfaction(self.env_idx) + + +@dataclass +class InstanceEvaluationState: + """Mutable rollout state for one task instance assigned to one logical environment.""" + + env_accessor: InstanceEnvAccessor + metrics: List[MetricBase] = field(default_factory=list) + instance_id: Optional[int] = None + obs: Optional[dict] = None + video_writer: Any = None + light_synchronizer: Optional[LightToggleSynchronizer] = None + active: bool = False + + @property + def env_idx(self) -> int: + return self.env_accessor.env_idx + + +class BatchedEvaluator: + """ + Batched evaluator engine for BEHAVIOR tasks. Owns one shared vectorized OmniGibson environment and + one batched policy. Each batch entry is represented by an :class:`InstanceEvaluationState`, + which binds one task instance to one logical environment through an + :class:`InstanceEnvAccessor`. ``num_envs=1`` reproduces single-environment evaluation. + """ + + def __init__(self, cfg: DictConfig) -> None: + self.cfg = cfg + + self.n_trials = 0 + self.n_success_trials = 0 + self.total_time = 0 + self.robot_name = None + self.robot_eval_config = {} + self.robot_camera_names = {} + + # Number of logical environments evaluated concurrently. Defaults to 1. + self.num_envs = int(cfg.get("num_envs", 1)) + self.env = self.load_env(env_wrapper=self.cfg.env_wrapper) + assert ( + self.env.num_envs == self.num_envs + ), f"Env created with num_envs={self.env.num_envs} but BatchedEvaluator expected {self.num_envs}." + + self.instance_eval_states = self._create_instance_eval_states() + # All environments share the same robot config, so resolve eval camera names once and + # validate that the configured camera sensors exist on the robot. + self.robot_camera_names = get_robot_camera_names( + self.instance_eval_states[0].env_accessor.robot.name, self.robot_eval_config + ) + self._validate_robot_eval_config() + self._apply_robot_eval_settings() + self.policy = self.load_policy() + for instance_eval_state in self.instance_eval_states: + instance_eval_state.metrics = self.load_metrics(instance_eval_state.env_accessor) + + # Initialize the physics views so the first reset()/load can read/restore robot joint state. + og.sim.update_handles() + self.env._current_episode = 0 + + @property + def should_sync_lights(self) -> bool: + return self.env.task.activity_name in LIGHT_EVAL_TASKS + + def _reset_light_synchronizer(self, instance_eval_state: InstanceEvaluationState) -> None: + if self.should_sync_lights: + synchronizer = LightToggleSynchronizer(instance_eval_state.env_accessor.scene) + synchronizer.reset_from_current_state() + instance_eval_state.light_synchronizer = synchronizer + else: + instance_eval_state.light_synchronizer = None + + def load_env(self, env_wrapper: DictConfig) -> EnvironmentWrapper: + for rule in DISABLED_TRANSITION_RULES: + rule.ENABLED = False + + available_tasks = load_available_tasks() + task_name = self.cfg.task.name + assert task_name in available_tasks, f"Got invalid task name: {task_name}" + + self.human_stats = load_human_stats(task_name) + + task_cfg = available_tasks[task_name][0] + cfg = generate_basic_environment_config(task_name=task_name, task_cfg=task_cfg) + if self.cfg.partial_scene_load: + cfg["scene"]["load_room_instances"] = TASK_NAMES_TO_ROOMS[task_name] + + robot_cfg = self._build_robot_config(task_name=task_name, task_cfg=task_cfg) + self.robot_name = robot_cfg["name"] + cfg["robots"] = [robot_cfg] + # Lets a custom robot reuse another model's presampled poses on tasks that only store model-specific ones. + cfg["task"]["presampled_pose_key"] = self.robot_eval_config.get("use_presampled_pose_key") + + # Camera resolution + modalities are decided by the chosen eval wrapper and baked into the + # robot config HERE, before env creation. This is required (not just cleaner) whenever + # gm.ENABLE_TILED_RENDERING is set and num_envs > 1: robot cameras are then batched into a single + # TiledVisionSensor whose resolution is fixed at creation -- a post-hoc per-sensor resize in the + # wrapper would be silently ignored. + # Resolve the wrapper class (without instantiating it -- that needs the env) to read its spec. + camera_spec = get_class(env_wrapper["_target_"]).camera_spec() + cfg["robots"][0]["obs_modalities"] = ["proprio", *camera_spec["modalities"]] + # Per-camera resolution via per-link sensor_config overrides. The link key is ":Camera:0" + # (see robots/robot.py), which takes precedence over the class-level VisionSensor default. Map + # each eval camera role to its robot sensor via the (config-driven) eval.camera_sensor_names. + sensor_config = cfg["robots"][0].setdefault("sensor_config", {}) + for camera_id, sensor_name in self.robot_eval_config.get("camera_sensor_names", {}).items(): + if camera_id not in camera_spec["resolution"]: + continue + link_key = sensor_name.split(":", 1)[1] + height, width = camera_spec["resolution"][camera_id] + sensor_config[link_key] = {"sensor_kwargs": {"image_height": height, "image_width": width}} + + if self.cfg.max_steps is None: + max_steps = int(self.human_stats["length"] * EVAL_TIMEOUT_MULTIPLIER) + logger.info( + f"Setting timeout to be {EVAL_TIMEOUT_MULTIPLIER}x the average length of human demos: {max_steps}" + ) + cfg["task"]["termination_config"]["max_steps"] = max_steps + else: + logger.info(f"Setting timeout to be {self.cfg.max_steps} steps through config.") + cfg["task"]["termination_config"]["max_steps"] = self.cfg.max_steps + cfg["task"]["include_obs"] = False + + # Run num_envs instances of the same scene model + task in parallel environments. + cfg.setdefault("env", {}) + cfg["env"]["num_envs"] = self.num_envs + + env = og.Environment(configs=cfg) + env._eval_robot_config = self.robot_eval_config + return instantiate(env_wrapper, env=env) + + def _create_instance_eval_states(self) -> List[InstanceEvaluationState]: + return [ + InstanceEvaluationState(env_accessor=InstanceEnvAccessor(shared_env=self.env, env_idx=env_idx)) + for env_idx in range(self.num_envs) + ] + + def _validate_robot_eval_config(self) -> None: + missing_camera_sensors = [] + for camera_id, camera_name in self.robot_camera_names.items(): + sensor_name = camera_name.split("::", 1)[1] + if sensor_name not in self.instance_eval_states[0].env_accessor.robot.sensors: + missing_camera_sensors.append(f"{camera_id}: {sensor_name}") + if missing_camera_sensors: + raise ValueError( + "Configured eval.camera_sensor_names entries were not found in robot.sensors: " + f"{missing_camera_sensors}" + ) + + if self.cfg.get("write_video", False): + required_camera_ids = {"left_wrist", "right_wrist", "head"} + missing_camera_ids = sorted(required_camera_ids - set(self.robot_camera_names)) + if missing_camera_ids: + raise ValueError( + "--write-video requires eval.camera_sensor_names roles " + f"{sorted(required_camera_ids)}; missing {missing_camera_ids}" + ) + + def _build_robot_config(self, task_name: str, task_cfg: dict) -> dict: + robot_cfg = _to_plain_dict(OmegaConf.select(self.cfg, "robot")) + if robot_cfg is None: + robot_cfg = _to_plain_dict(OmegaConf.load(DEFAULT_ROBOT_CONFIG_PATH)) + else: + robot_cfg = dict(robot_cfg) + assert "model" in robot_cfg, "Robot config must include canonical 'model'" + assert "type" not in robot_cfg, "Robot config must use canonical 'model', not 'type'" + robot_cfg["model"] = robot_cfg["model"].lower() + assert "name" in robot_cfg, "Robot config must include 'name'" + self.robot_eval_config = _to_plain_dict(robot_cfg.pop("eval", None)) or {} + robot_cfg["position"] = task_cfg["robot_start_position"] + robot_cfg["orientation"] = task_cfg["robot_start_orientation"] + + return robot_cfg + + def _apply_robot_eval_settings(self) -> None: + # Heavier base so contact with the (heavy) world does not shove the robot around during eval. + # base mass writes require the sim stopped; do all robots inside a single stop/play (global op). + robots = [instance_eval_state.env_accessor.robot for instance_eval_state in self.instance_eval_states] + if any(robot.model in ("r1", "r1pro") for robot in robots): + og.sim.stop() + for robot in robots: + if robot.model in ("r1", "r1pro"): + robot.base_footprint_link.mass = EVAL_BASE_LINK_MASS + og.sim.play() + + head_camera_name = self.robot_camera_names.get("head") + if head_camera_name is not None: + head_sensor_name = head_camera_name.split("::")[1] + for robot in robots: + if head_sensor_name in robot.sensors: + robot.sensors[head_sensor_name].horizontal_aperture = EVAL_HEAD_HORIZONTAL_APERTURE + + def load_policy(self) -> Any: + # A single policy serves all logical environments in one batched call. It accepts observations + # with a leading num_envs dimension and keeps per-environment state positionally aligned. + policy = instantiate(self.cfg.model) + if hasattr(policy, "set_action_dim"): + policy.set_action_dim(self.instance_eval_states[0].env_accessor.robot.action_dim) + logger.info("") + logger.info("=" * 50) + logger.info(f"Loaded {self.num_envs} policy instance(s) (batched): {self.cfg.policy_name}") + logger.info("=" * 50) + logger.info("") + return policy + + def load_metrics(self, env_accessor: InstanceEnvAccessor) -> List[MetricBase]: + return [ + AgentMetric(self.human_stats, env_accessor=env_accessor), + TaskMetric(self.human_stats, env_accessor=env_accessor), + ] + + def _apply_actions(self, actions: th.Tensor, active_env_indices: List[int]): + """ + Step the complete environment batch with the given ``(num_envs, action_dim)`` actions, then + update observations and metrics only for @active_env_indices. Finished environments are still + advanced by the shared simulator, but their evaluation state is frozen. + """ + obs_list, _, terminated, truncated, info = self.env.step(actions, n_render_iterations=1) + if self.should_sync_lights: + # Re-derive visual light state (toggles drive lights that aren't directly serialized) for + # active environments, then re-read obs so recorded frames match the synced lights. + for env_idx in active_env_indices: + light_synchronizer = self.instance_eval_states[env_idx].light_synchronizer + if light_synchronizer is not None: + light_synchronizer.sync_from_current_state() + for _ in range(3): + og.sim.render() + obs_list, _ = self.env.get_obs() + for env_idx in active_env_indices: + instance_eval_state = self.instance_eval_states[env_idx] + instance_eval_state.obs = self._preprocess_obs(obs_list[env_idx], instance_eval_state) + for metric in instance_eval_state.metrics: + metric.step( + action=actions[env_idx], + obs=obs_list[env_idx], + reward=0.0, + terminated=bool(terminated[env_idx]), + truncated=bool(truncated[env_idx]), + info=info[env_idx], + ) + return terminated, truncated, info + + def _batch_obs(self) -> dict: + """ + Stack every instance's preprocessed observation into one ``(num_envs, ...)`` batch for a + single policy call. Finished instances keep their last observation so the batch size remains + fixed and the policy's per-environment state remains positionally aligned. + """ + keys = self.instance_eval_states[0].obs.keys() + return { + key: th.stack([instance_eval_state.obs[key] for instance_eval_state in self.instance_eval_states], dim=0) + for key in keys + } + + def _step_fn(self, active_env_indices: List[int]) -> Tuple[th.Tensor, th.Tensor]: + """ + ``step_fn`` consumed by :func:`evaluate_instances_batched`: query the policy once with all + logical environments batched together, then step. Finished environments get a zero action but are + still advanced by the shared simulator. + """ + action_dim = self.instance_eval_states[0].env_accessor.robot.action_dim + batched_action = self.policy.forward(obs=self._batch_obs()) # (num_envs, action_dim) + if batched_action.ndim == 1: + batched_action = batched_action.unsqueeze(0) + actions = th.zeros((self.num_envs, action_dim), dtype=th.float32) + for env_idx in active_env_indices: + actions[env_idx] = batched_action[env_idx].to(actions.dtype) + terminated, truncated, _ = self._apply_actions(actions, active_env_indices) + return terminated, truncated + + def _set_video_writer(self, instance_eval_state: InstanceEvaluationState, video_writer) -> None: + existing = instance_eval_state.video_writer + if existing is not None: + container, stream = existing + for packet in stream.encode(): + container.mux(packet) + container.close() + instance_eval_state.video_writer = video_writer + + def _load_instance_state(self, instance_id: int, instance_eval_state: InstanceEvaluationState) -> None: + """ + Load a task instance into its assigned logical environment. Does NOT settle physics or + finalize the scene -- that happens once for the whole batch in :meth:`_settle_and_finalize` so + settling does not disturb the other logical environments. + """ + env_accessor = instance_eval_state.env_accessor + env_idx = env_accessor.env_idx + robot = env_accessor.robot + scene = env_accessor.scene + # Start every instance from a CLEAN robot: reset joints / controllers / velocities (and release + # grasp) to the default config -- the instance TRO only restores the robot's base pose below. + # 2285 got this for free from evaluator.reset() (env.reset) before each load_task_instance; in + # the batched path we must do it explicitly, otherwise the previous episode's/batch's robot + # joint+grasp state carries into the snapshot taken in _settle_and_finalize. + robot.reset() + scene_model = self.env.task.scene_name + tro_filename = self.env.task.get_cached_activity_scene_filename( + scene_model=scene_model, + activity_name=self.env.task.activity_name, + activity_definition_id=self.env.task.activity_definition_id, + activity_instance_id=instance_id, + ) + mode = self.cfg.get("mode", "public_test") + tro_file_path = get_task_instance_path( + scene_model, + f"{scene_model}_task_{self.env.task.activity_name}_instances/{tro_filename}-tro_state", + mode=mode, + ) + if tro_file_path is None: + raise FileNotFoundError( + f"Could not find 2026 {mode} task instance {instance_id} for " + f"{self.env.task.activity_name} in scene {scene_model}." + ) + + with open(tro_file_path, "r") as f: + tro_state = recursively_convert_to_torch(json.load(f)) + for tro_key, tro_state in tro_state.items(): + if tro_key == "robot_poses": + available_poses = get_presampled_robot_poses( + tro_state, + robot_model=robot.model, + pose_key=self.robot_eval_config.get("use_presampled_pose_key"), + ) + # Presampled poses are scene-relative; frame="scene" puts environment N's robot in its own + # scene rather than env 0's geometry (cf. #2257). + robot.set_position_orientation( + available_poses[0]["position"], available_poses[0]["orientation"], frame="scene" + ) + scene.write_task_metadata(key=tro_key, data=tro_state) + else: + # load_state applies the TRO root-link pose in WORLD frame, but the TRO is authored in + # scene-relative (env 0) coordinates. For multi envs (env_idx != 0) the scene prim is + # shifted by its world offset, so add that offset to the root-link position up front -- + # load_state then places the object correctly in a single write. + obj = env_accessor.object_scope[tro_key] + if env_idx != 0 and isinstance(tro_state, dict) and "root_link" in tro_state: + scene_offset = scene._scene_prim.get_position_orientation()[0] + tro_state["root_link"]["pos"] = tro_state["root_link"]["pos"] + scene_offset + obj.load_state(tro_state, serialized=False) + + if self.should_sync_lights: + set_light_control_toggles(env_accessor.object_scope.values(), True) + og.sim.update_handles() + + def _settle_and_finalize(self, env_indices: List[int]) -> None: + """ + Settle physics for all freshly-loaded environments together and finalize each scene. Loading + state can introduce jitter, so keep all loaded task-relevant entities (including the robot, + which _load_instance_state just reset to a clean config) still for a few sub-steps before + snapshotting each scene's initial state -- otherwise the robot drifts under gravity before the + snapshot. + """ + for _ in range(25): + og.sim.step_physics() + for env_idx in env_indices: + for inst, entity in self.instance_eval_states[env_idx].env_accessor.object_scope.items(): + if not is_system_bddl_inst(inst) and entity is not None: + entity.keep_still() + for env_idx in env_indices: + self.instance_eval_states[env_idx].env_accessor.scene.update_initial_file() + # load_batch immediately calls env.reset(), whose task reset restores every selected scene + # from this initial file. Avoid doing the same hard restore and physics step twice. + + def load_batch( + self, + env_idx_to_instance: dict, + write_video: bool = False, + video_path: str = None, + rollout_id: int = 0, + video_fps: int = 30, + ) -> None: + """ + Load one instance per logical environment, settle the complete batch, refresh observations, + and reset policy, metrics, light synchronizers, and video writers. + """ + env_indices = sorted(env_idx_to_instance) + for env_idx in env_indices: + instance_eval_state = self.instance_eval_states[env_idx] + instance_eval_state.instance_id = int(env_idx_to_instance[env_idx]) + instance_eval_state.active = True + self._load_instance_state(instance_eval_state.instance_id, instance_eval_state) + self._settle_and_finalize(env_indices) + obs_list, _ = self.env.reset(env_indices=th.tensor(env_indices, dtype=th.long)) + for env_idx in env_indices: + self._reset_light_synchronizer(self.instance_eval_states[env_idx]) + # Light toggles change visibility after the reset obs was captured; re-render + re-fetch so the + # first obs reflects the synced lights (mirrors single-env _sync_lights_and_get_obs). No-op for + # non-light tasks. + if self.should_sync_lights: + for _ in range(3): + og.sim.render() + obs_list, _ = self.env.get_obs(env_indices=th.tensor(env_indices, dtype=th.long)) + task_name = self.cfg.task.name + # One batched policy for the complete batch: reset its per-environment state once. + self.policy.reset() + for obs_idx, env_idx in enumerate(env_indices): + instance_eval_state = self.instance_eval_states[env_idx] + instance_eval_state.obs = self._preprocess_obs(obs_list[obs_idx], instance_eval_state) + for metric in instance_eval_state.metrics: + metric.reset() + if write_video: + video_name = os.path.join(video_path, f"{task_name}_{instance_eval_state.instance_id}_{rollout_id}.mp4") + self._set_video_writer( + instance_eval_state, + create_video_writer(fpath=video_name, resolution=(448, 672), rate=video_fps), + ) + + def _preprocess_obs(self, obs: dict, instance_eval_state: InstanceEvaluationState) -> dict: + robot = instance_eval_state.env_accessor.robot + obs = flatten_obs_dict(obs) + base_pose = robot.get_position_orientation() + cam_rel_poses = [] + # Camera extrinsics come directly from the sensor prim. Querying camera_parameters just for + # cameraViewTransform lazily creates an annotator and forces global renders per camera. + for camera_name in self.robot_camera_names.values(): + sensor_name = camera_name.split("::")[1] + if sensor_name not in robot.sensors: + continue + camera = robot.sensors[sensor_name] + cam_rel_poses.append(th.cat(T.relative_pose_transform(*(camera.get_position_orientation()), *base_pose))) + if cam_rel_poses: + obs[f"{robot.name}::cam_rel_poses"] = th.cat(cam_rel_poses, axis=-1) + obs["task_id"] = th.tensor([TASK_NAMES_TO_INDICES[self.cfg.task.name]], dtype=th.int64) + return obs + + def _write_video(self, instance_eval_state: InstanceEvaluationState) -> None: + obs = instance_eval_state.obs + required_camera_ids = ("left_wrist", "right_wrist", "head") + if not all(camera_id in self.robot_camera_names for camera_id in required_camera_ids): + return + if obs is None or self.robot_camera_names["head"] + "::rgb" not in obs: + return + # .detach().cpu() is required for num_envs>1: robot cameras come from the TiledVisionSensor, + # whose obs are CUDA tensors (a plain .numpy() would raise). No-op for single-env CPU tensors. + left_wrist_rgb = cv2.resize( + obs[self.robot_camera_names["left_wrist"] + "::rgb"].detach().cpu().numpy(), (224, 224) + ) + right_wrist_rgb = cv2.resize( + obs[self.robot_camera_names["right_wrist"] + "::rgb"].detach().cpu().numpy(), (224, 224) + ) + head_rgb = cv2.resize(obs[self.robot_camera_names["head"] + "::rgb"].detach().cpu().numpy(), (448, 448)) + write_video( + np.expand_dims(np.hstack([np.vstack([left_wrist_rgb, right_wrist_rgb]), head_rgb]), 0), + video_writer=instance_eval_state.video_writer, + batch_size=1, + mode="rgb", + ) + + def reset(self) -> None: + """Reset all logical environments to their loaded instances and reset policy and metrics.""" + obs_list, _ = self.env.reset() + for instance_eval_state in self.instance_eval_states: + self._reset_light_synchronizer(instance_eval_state) + # Refresh obs after light visibility changes so the first obs is in sync (see load_batch). + if self.should_sync_lights: + for _ in range(3): + og.sim.render() + obs_list, _ = self.env.get_obs() + self.policy.reset() + for instance_eval_state in self.instance_eval_states: + env_idx = instance_eval_state.env_idx + instance_eval_state.obs = self._preprocess_obs(obs_list[env_idx], instance_eval_state) + instance_eval_state.active = True + for metric in instance_eval_state.metrics: + metric.reset() + self.n_success_trials, self.n_trials = 0, 0 + + def run( + self, + instances_to_run: List[int], + write_video: bool = False, + video_path: str = None, + metrics_dir: str = None, + rollout_id: int = 0, + video_fps: int = 30, + ) -> dict: + """ + Offline driver for one batch containing exactly ``num_envs`` instances. An environment whose + instance finishes early waits idle rather than receiving a new instance. Writes one result JSON per instance to + @metrics_dir if given. Returns {instance id -> result dict} (result is score_utils-compatible: + q_score/time/agent_distance plus task/instance/success/steps). + """ + task_name = self.cfg.task.name + + def load_fn(env_idx_to_instance): + self.load_batch( + env_idx_to_instance, + write_video=write_video, + video_path=video_path, + rollout_id=rollout_id, + video_fps=video_fps, + ) + + def step_fn(active_env_indices): + terminated, truncated = self._step_fn(active_env_indices) + if write_video: + for env_idx in active_env_indices: + self._write_video(self.instance_eval_states[env_idx]) + return terminated, truncated + + def record_fn(env_idx, instance, step, terminated, truncated): + instance_eval_state = self.instance_eval_states[env_idx] + instance_eval_state.active = False + self.n_trials += 1 + success = instance_eval_state.env_accessor.success + if success: + self.n_success_trials += 1 + result = {"task": task_name, "instance_id": int(instance), "rollout_id": rollout_id, "steps": step} + result["success"] = success + for metric in instance_eval_state.metrics: + result.update(metric.aggregate()) + if metrics_dir is not None: + with open(os.path.join(metrics_dir, f"{task_name}_{instance}_{rollout_id}.json"), "w") as f: + json.dump(result, f, indent=2, default=float) + if write_video: + self._set_video_writer(instance_eval_state, None) + q_score = result.get("q_score", {}).get("final") + logger.info( + f"Instance {instance} (env {env_idx}) finished at step {step}: success={success} q_score={q_score}" + ) + return result + + return evaluate_instances_batched( + list(instances_to_run), + self.num_envs, + load_fn=load_fn, + step_fn=step_fn, + record_fn=record_fn, + ) + + def __enter__(self): + signal(SIGINT, self._sigint_handler) + return self + + def __exit__(self, exc_type, exc_value, exc_tb): + logger.info("") + logger.info("=" * 50) + logger.info(f"Total success trials: {self.n_success_trials}") + logger.info(f"Total trials: {self.n_trials}") + if self.n_trials > 0: + logger.info(f"Success rate: {self.n_success_trials / self.n_trials}") + logger.info("=" * 50) + logger.info("") + if exc_type is not None: + traceback.print_exception(exc_type, exc_value, exc_tb) + for instance_eval_state in self.instance_eval_states: + self._set_video_writer(instance_eval_state, None) + self.env.close() + og.shutdown() + + def _sigint_handler(self, signal_received, frame): + logger.warning("SIGINT or CTRL-C detected.\n") + self.__exit__(None, None, None) + sys.exit(0) + + +# Backward-compatible alias for callers that imported the original class name. +Evaluator = BatchedEvaluator + + +__all__ = [ + "BatchedEvaluator", + "Evaluator", + "InstanceEnvAccessor", + "InstanceEvaluationState", + "resolve_instance_ids", + "evaluate_instances_batched", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/policies.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/policies.py new file mode 100644 index 0000000000000000000000000000000000000000..5c8444000e042a5803466f901a6d4c7dee8d95f1 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/policies.py @@ -0,0 +1,97 @@ +import logging +import torch as th +from omnigibson.eval.utils.network_utils import WebsocketClientPolicy +from typing import Optional + + +__all__ = [ + "LocalPolicy", + "WebsocketPolicy", +] + + +class LocalPolicy: + """ + Local policy that directly queries action from policy, + outputs zero delta action if policy is None. + """ + + def __init__(self, *args, action_dim: Optional[int] = None, **kwargs) -> None: + self.policy = None # To be set later + self.action_dim = action_dim + + def set_action_dim(self, action_dim: int) -> None: + self.action_dim = action_dim + + def act(self, obs: dict) -> th.Tensor: + return self.forward(obs) + + def forward(self, obs: dict, *args, **kwargs) -> th.Tensor: + """ + Directly return a zero action tensor of the specified action dimension. + """ + if self.policy is not None: + return self.policy.act(obs).detach().cpu() + else: + assert self.action_dim is not None + batch_size = None + if obs: + first_obs = next(iter(obs.values())) + if isinstance(first_obs, th.Tensor) and first_obs.ndim > 0: + batch_size = first_obs.shape[0] + shape = (self.action_dim,) if batch_size is None else (batch_size, self.action_dim) + return th.zeros(shape, dtype=th.float32) + + def reset(self) -> None: + if self.policy is not None: + self.policy.reset() + + +class WebsocketPolicy: + """ + Websocket policy for controlling the robot over a websocket connection. ``action_chunk_size`` opts + into the action-chunk protocol documented in ``docs/challenge/evaluation.md``; it is disabled by + default because replaying a chunk is correct only for servers that return actions intended for + open-loop execution from one observation. + """ + + def __init__( + self, + *args, + host: Optional[str] = None, + port: Optional[int] = None, + allow_reconnect: bool = False, + action_chunk_size: int = 0, + **kwargs, + ) -> None: + logging.info(f"Creating websocket client policy with host: {host}, port: {port}") + self.last_action = None + self.policy = None + self._allow_reconnect = allow_reconnect + self._action_chunk_size = action_chunk_size + if host is not None or port is not None: + self.policy = WebsocketClientPolicy( + host=host, + port=port, + allow_reconnect=allow_reconnect, + action_chunk_size=action_chunk_size, + ) + + def update_host(self, host: str, port: int) -> None: + self.policy = WebsocketClientPolicy( + host=host, + port=port, + allow_reconnect=self._allow_reconnect, + action_chunk_size=self._action_chunk_size, + ) + + def forward(self, obs: dict, *args, **kwargs) -> th.Tensor: + if "need_new_action" in obs and not obs["need_new_action"] and self.last_action is not None: + return self.last_action + self.last_action = self.policy.act(obs).detach().cpu() + return self.last_action + + def reset(self) -> None: + if self.policy is not None: + self.policy.reset() + self.last_action = None diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/r1pro.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/r1pro.yaml new file mode 100644 index 0000000000000000000000000000000000000000..858b42fb0d0c525a2efbf5c1c69c90066d59ca7d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/r1pro.yaml @@ -0,0 +1,126 @@ +model: r1pro +name: robot_r1 +eval: + camera_sensor_names: + left_wrist: robot_r1:left_realsense_link:Camera:0 + right_wrist: robot_r1:right_realsense_link:Camera:0 + head: robot_r1:zed_link:Camera:0 +action_normalize: false +self_collisions: true +obs_modalities: + - proprio + - rgb +proprio_obs: + - base_qvel + - arm_left_qpos + - arm_left_qvel + - eef_left_pos + - eef_left_quat + - gripper_left_qpos + - gripper_left_qvel + - arm_right_qpos + - arm_right_qvel + - eef_right_pos + - eef_right_quat + - gripper_right_qpos + - gripper_right_qvel + - trunk_qpos + - trunk_qvel +grasping_mode: assisted +sensor_config: + VisionSensor: + sensor_kwargs: + image_height: 1080 + image_width: 1080 +controller_config: + arm_left: + name: JointController + motor_type: position + pos_kp: 150 + command_input_limits: null + command_output_limits: null + use_impedances: false + use_delta_commands: false + arm_right: + name: JointController + motor_type: position + pos_kp: 150 + command_input_limits: null + command_output_limits: null + use_impedances: false + use_delta_commands: false + gripper_left: + name: MultiFingerGripperController + mode: smooth + command_input_limits: default + command_output_limits: default + gripper_right: + name: MultiFingerGripperController + mode: smooth + command_input_limits: default + command_output_limits: default + base: + name: HolonomicBaseJointController + motor_type: velocity + vel_kp: 150 + command_input_limits: + - [-1.0, -1.0, -1.0] + - [1.0, 1.0, 1.0] + command_output_limits: + - [-0.75, -0.75, -1.0] + - [0.75, 0.75, 1.0] + use_impedances: false + trunk: + name: JointController + motor_type: position + pos_kp: 150 + command_input_limits: null + command_output_limits: null + use_impedances: false + use_delta_commands: false + camera: + name: NullJointController +reset_joint_pos: + # Joint order follows the R1Pro low-level joint vector: + # 6 virtual/mobile base joints, + # 4 torso/trunk joints, + # 7 left arm joints, + # 7 right arm joints, + # 2 left gripper finger joints, + # 2 right gripper finger joints. + # Base virtual joints. + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + # Torso/trunk joints. These come from JoyLo's default trunk pose: + # DEFAULT_TRUNK_TRANSLATE = 0.5, interpolated halfway between + # torso_upright [0.45, -0.4, 0.0, 0.0] and + # torso_downward [1.6, -2.5, -0.94, 0.0]. + - 1.025 + - -1.45 + - -0.47 + - 0.0 + # Left arm joints. + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + # Right arm joints. + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + # Gripper finger joints start open. + - 0.05 + - 0.05 + - 0.05 + - 0.05 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/dataset_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/dataset_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..754a64717dd5cd7bc1852d7f194cd1cb81748dea --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/dataset_utils.py @@ -0,0 +1,73 @@ +import os +from typing import Tuple + + +def makedirs_with_mode(path, mode=0o2775) -> None: + """ + Recursively create directories with specified mode applied to all newly created dirs. + Args: + path (str): The directory path to create. + mode (int): The mode to apply to newly created directories. + """ + # Normalize path + path = os.path.abspath(path) + parts = path.split(os.sep) + if parts[0] == "": + parts[0] = os.sep # for absolute paths on Unix + + current_path = parts[0] + for part in parts[1:]: + current_path = os.path.join(current_path, part) + if not os.path.exists(current_path): + try: + os.makedirs(current_path, exist_ok=True) + # Apply mode explicitly because os.mkdir may be affected by umask + os.chmod(current_path, mode) + except Exception as e: + print(f"Failed to create directory {current_path}: {e}") + else: + pass + + +def check_leaf_folders_have_n(data_dir: str, n: int = 200) -> Tuple[dict, int]: + """ + Recursively find all leaf folders under data_dir. + A leaf folder is one that contains only files (no subdirectories). + For each leaf folder, check it has exactly n files. + Args: + data_dir (str): The root directory to start searching. + n (int): The exact number of files each leaf folder should have. + Returns: + Tuple[dict, int]: A tuple containing: + - A dictionary mapping leaf folder paths to their file counts. + - The total file count across all leaf folders. + """ + data_dir = os.path.expanduser(data_dir) + results = {} + total_count = 0 + for root, dirs, files in os.walk(data_dir): + # ignore hidden folders + dirs[:] = [d for d in dirs if not d.startswith(".")] + # leaf folder: contains files but no subdirs + if not dirs: + count = len([f for f in files if os.path.isfile(os.path.join(root, f))]) + results[root] = count + total_count += count + if count == n: + print(f"✅ {root} has exactly {n} files.") + else: + raise Exception(f"❌ {root} has {count} files (expected {n}).") + print(f"Total files across all leaf folders: {total_count}") + return results, total_count + + +def fix_permissions(root_dir: str): + """Recursively set rw-rw-r-- for all files owned by the current user.""" + for dirpath, _, filenames in os.walk(root_dir): + print(dirpath) + for fname in filenames: + fpath = os.path.join(dirpath, fname) + try: + os.chmod(fpath, 0o664) # rw-rw-r-- + except (PermissionError, FileNotFoundError): + continue diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/eval_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/eval_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b198c84e131a385653597f2d592ee04a23735269 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/eval_utils.py @@ -0,0 +1,258 @@ +import csv +import os +import random +import numpy as np +import torch as th +from collections import OrderedDict +from omnigibson.macros import gm + + +HEAD_RESOLUTION = (720, 720) +WRIST_RESOLUTION = (480, 480) +# Standard eval camera roles. Eval wrappers key their camera_spec() resolution by these roles; the +# Evaluator maps each role to a concrete robot sensor via the robot config's +# eval.camera_sensor_names (see get_robot_camera_names) when baking resolution at env creation. +EVAL_CAMERA_ROLES = ("left_wrist", "right_wrist", "head") +DEFAULT_EVAL_SEED = 0 +EVAL_TIMEOUT_MULTIPLIER = 1.5 +NUM_TEST_INSTANCES = 40 +NUM_PUBLIC_TEST_INSTANCES = 20 +NUM_HIDDEN_TEST_INSTANCES = NUM_TEST_INSTANCES - NUM_PUBLIC_TEST_INSTANCES +TEST_INSTANCE_IDS = list(range(301, 341)) + + +def seed_everything(seed: int, deterministic_torch: bool = False) -> int: + """ + Seed Python, NumPy, and Torch RNGs used by eval. + + Setting PYTHONHASHSEED here helps child processes and documents the intended seed, but + hash randomization for the current Python process is fixed at interpreter startup. + """ + seed = int(seed) + os.environ["PYTHONHASHSEED"] = str(seed) + random.seed(seed) + np.random.seed(seed) + th.manual_seed(seed) + if th.cuda.is_available(): + th.cuda.manual_seed(seed) + th.cuda.manual_seed_all(seed) + try: + import warp as wp + + wp.rand_init(seed) + except ImportError: + pass + + if hasattr(th.backends, "cudnn"): + th.backends.cudnn.benchmark = False + th.backends.cudnn.deterministic = True + + if deterministic_torch: + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + try: + th.use_deterministic_algorithms(True, warn_only=True) + except TypeError: + th.use_deterministic_algorithms(True) + + return seed + + +def _load_challenge_task_misc() -> tuple[dict[str, int], dict[str, list[str]]]: + task_ids = {} + task_rooms = {} + task_misc_path = os.path.join(gm.DATA_PATH, "2026-challenge-task-instances", "metadata", "B100_task_misc.csv") + with open(task_misc_path, newline="", encoding="utf-8") as f: + for row in csv.DictReader(f): + task_ids[row["Task"]] = int(row["Task ID"]) + task_rooms[row["Task"]] = [room.strip() for room in row["Rooms to inlcude"].splitlines() if room.strip()] + return task_ids, task_rooms + + +TASK_NAMES_TO_INDICES, TASK_NAMES_TO_ROOMS = _load_challenge_task_misc() +if not TASK_NAMES_TO_INDICES: + raise RuntimeError( + "Could not load challenge task metadata. Expected one of: " + f"{os.path.join(gm.DATA_PATH, '2026-challenge-task-instances', 'metadata', 'B100_task_misc.csv')}. " + "Please ensure OMNIGIBSON_DATA_PATH / gm.DATA_PATH points at the BEHAVIOR data root." + ) + +# Camera parameteres +CAMERA_INTRINSICS = { + "R1Pro": { + "head": np.array([[306.0, 0.0, 360.0], [0.0, 306.0, 360.0], [0.0, 0.0, 1.0]], dtype=np.float32), # 720x720 + "left_wrist": np.array( + [[388.6639, 0.0, 240.0], [0.0, 388.6639, 240.0], [0.0, 0.0, 1.0]], dtype=np.float32 + ), # 480x480 + "right_wrist": np.array( + [[388.6639, 0.0, 240.0], [0.0, 388.6639, 240.0], [0.0, 0.0, 1.0]], dtype=np.float32 + ), # 480x480 + }, +} + +CAMERA_EXTRINSICS = { + "R1Pro": { + "head": np.array([[306.0, 0.0, 360.0], [0.0, 306.0, 360.0], [0.0, 0.0, 1.0]], dtype=np.float32), # 720x720 + "left_wrist": np.array( + [[388.6639, 0.0, 240.0], [0.0, 388.6639, 240.0], [0.0, 0.0, 1.0]], dtype=np.float32 + ), # 480x480 + "right_wrist": np.array( + [[388.6639, 0.0, 240.0], [0.0, 388.6639, 240.0], [0.0, 0.0, 1.0]], dtype=np.float32 + ), # 480x480 + }, +} + + +# Action indices +ACTION_QPOS_INDICES = { + "R1Pro": OrderedDict( + { + "base": np.s_[0:3], + "torso": np.s_[3:7], + "left_arm": np.s_[7:14], + "left_gripper": np.s_[14:15], + "right_arm": np.s_[15:22], + "right_gripper": np.s_[22:23], + } + ), +} + + +# Proprioception configuration +PROPRIOCEPTION_INDICES = { + "R1Pro": OrderedDict( + { + "base_qvel": np.s_[0:3], + "arm_left_qpos": np.s_[3:10], + "arm_left_qvel": np.s_[10:17], + "eef_left_pos": np.s_[17:20], + "eef_left_quat": np.s_[20:24], + "gripper_left_qpos": np.s_[24:26], + "gripper_left_qvel": np.s_[26:28], + "arm_right_qpos": np.s_[28:35], + "arm_right_qvel": np.s_[35:42], + "eef_right_pos": np.s_[42:45], + "eef_right_quat": np.s_[45:49], + "gripper_right_qpos": np.s_[49:51], + "gripper_right_qvel": np.s_[51:53], + "trunk_qpos": np.s_[53:57], + "trunk_qvel": np.s_[57:61], + } + ), +} + + +def holonomic_base_qvel_to_robot_frame(base_qpos, base_qvel): + """ + Convert holonomic base joint velocities to robot-local [vx, vy, wz]. + + Args: + base_qpos: Base joint positions containing x, y, rz, or the full 6-DoF base virtual joints. + base_qvel: Matching base joint velocities containing x, y, rz, or the full 6-DoF base virtual joints. + """ + yaw = base_qpos[..., -1] + c = np.cos(yaw) + s = np.sin(yaw) + return np.stack( + [ + c * base_qvel[..., 0] + s * base_qvel[..., 1], + -s * base_qvel[..., 0] + c * base_qvel[..., 1], + base_qvel[..., -1], + ], + axis=-1, + ) + + +def get_robot_camera_names(robot_name: str, robot_eval_config: dict | None) -> dict[str, str]: + """ + Return flattened observation names for cameras configured by eval role. + + Robot configs may include: + eval: + camera_sensor_names: + head: robot_r1:zed_link:Camera:0 + + Values are robot sensor names, i.e. keys in robot.sensors. The flattened + observation name adds the robot observation namespace. + """ + robot_eval_config = robot_eval_config or {} + camera_sensor_names = robot_eval_config.get("camera_sensor_names", {}) + return {camera_id: f"{robot_name}::{sensor_name}" for camera_id, sensor_name in camera_sensor_names.items()} + + +def set_sensor_modalities(sensor, modalities: set[str]) -> None: + for modality in tuple(sensor.modalities): + if modality not in modalities: + sensor.remove_modality(modality) + for modality in modalities: + if modality not in sensor.modalities: + sensor.add_modality(modality) + + +def generate_basic_environment_config(task_name, task_cfg): + """ + Generate a basic environment configuration + + Args: + task_name (str): Name of the task + task_cfg: Dictionary of task config + + Returns: + dict: Environment configuration + """ + cfg = { + "env": { + "action_frequency": 30, + "rendering_frequency": 30, + "physics_frequency": 120, + }, + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": task_cfg["scene_model"], + "load_room_types": None, + "load_room_instances": task_cfg.get("load_room_instances", None), + "include_robots": False, + }, + "task": { + "type": "BehaviorTask", + "activity_name": task_name, + "activity_definition_id": 0, + "activity_instance_id": 0, + "online_object_sampling": False, + "debug_object_sampling": False, + "highlight_task_relevant_objects": False, + "termination_config": { + "max_steps": 5000, + }, + "reward_config": { + "r_potential": 1.0, + }, + "include_obs": False, + }, + } + return cfg + + +def flatten_obs_dict(obs: dict, parent_key: str = "") -> dict: + """ + Process the observation dictionary by recursively flattening the keys. + so obs["robot_r1"]["camera"]["rgb"] will become obs["robot_r1::camera:::rgb"]. + """ + processed_obs = {} + for key, value in obs.items(): + new_key = f"{parent_key}::{key}" if parent_key else key + if isinstance(value, dict): + processed_obs.update(flatten_obs_dict(value, parent_key=new_key)) + else: + processed_obs[new_key] = value + return processed_obs + + +def find_start_point(base_vel): + """ + Find the first point where the base velocity is non-zero. + This is used to skip the initial part of the dataset where the robot is not moving. + """ + start_idx = np.where(np.linalg.norm(base_vel, axis=-1) > 1e-5)[0] + if len(start_idx) == 0: + return 0 + return min(start_idx[0], 500) # Limit to the first 100 points to avoid long initial periods diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/light_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/light_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..92cabb85f9ffc2d5a1b6dea7e22c281fd77c1a80 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/light_utils.py @@ -0,0 +1,140 @@ +import omnigibson as og +import omnigibson.lazy as lazy + + +ROOM_LIGHT_CATEGORIES = { + "downlight", + "room_light", + "wall_mounted_light", +} +SELF_LIGHT_CATEGORIES = { + "floor_lamp", + "table_lamp", +} +LIGHT_CONTROL_CATEGORIES = { + "electric_switch", + *SELF_LIGHT_CATEGORIES, +} + + +def _iter_descendant_prims(prim): + for child in prim.GetChildren(): + yield child + yield from _iter_descendant_prims(child) + + +def _set_light_prims_visible(obj, visible): + with og.sim.editing_usd(): + for prim in _iter_descendant_prims(obj.prim): + if "Light" not in prim.GetTypeName(): + continue + imageable = lazy.pxr.UsdGeom.Imageable(prim) + if visible: + imageable.MakeVisible() + else: + imageable.MakeInvisible() + + +def _sync_room_lights_for_switch(scene, switch, visible): + rooms = switch.in_rooms or [] + for room in rooms: + for obj in scene.object_registry("in_rooms", room, default_val=[]): + if getattr(obj, "category", None) in ROOM_LIGHT_CATEGORIES: + obj.visible = visible + + +def sync_light_visibility_from_toggles(scene): + from omnigibson.object_states import ToggledOn + + for obj in scene.objects: + category = getattr(obj, "category", None) + states = getattr(obj, "states", None) + if category not in LIGHT_CONTROL_CATEGORIES or states is None or ToggledOn not in states: + continue + + visible = states[ToggledOn].get_value() + if category == "electric_switch": + _sync_room_lights_for_switch(scene, obj, visible) + else: + _set_light_prims_visible(obj, visible) + + +def set_light_visibility_from_default(scene, visible=True): + for obj in scene.objects: + category = getattr(obj, "category", None) + if category in ROOM_LIGHT_CATEGORIES: + obj.visible = visible + elif category in SELF_LIGHT_CATEGORIES: + _set_light_prims_visible(obj, visible) + + +def set_light_control_toggles(objects, value): + from omnigibson.object_states import ToggledOn + + for obj in objects: + category = getattr(obj, "category", None) + states = getattr(obj, "states", None) + if obj is None or category not in LIGHT_CONTROL_CATEGORIES or states is None or ToggledOn not in states: + continue + states[ToggledOn].set_value(value) + + +class LightToggleSynchronizer: + def __init__(self, scene): + self.scene = scene + self._toggle_values = {} + self._target_visibility = {} + + def reset_from_current_state(self): + self._toggle_values = self._get_toggle_values() + self._target_visibility = {} + set_light_visibility_from_default(self.scene, visible=True) + for obj in self.scene.objects: + category = getattr(obj, "category", None) + if category in ROOM_LIGHT_CATEGORIES or category in SELF_LIGHT_CATEGORIES: + self._target_visibility[obj.name] = True + + def sync_from_current_state(self): + if not self._toggle_values: + self.reset_from_current_state() + return + + current_toggle_values = self._get_toggle_values() + for obj_name, value in current_toggle_values.items(): + if self._toggle_values.get(obj_name) != value: + self._toggle_targets(obj_name) + self._toggle_values = current_toggle_values + + def _get_toggle_values(self): + from omnigibson.object_states import ToggledOn + + values = {} + for obj in self.scene.objects: + category = getattr(obj, "category", None) + states = getattr(obj, "states", None) + if category not in LIGHT_CONTROL_CATEGORIES or states is None or ToggledOn not in states: + continue + values[obj.name] = states[ToggledOn].get_value() + return values + + def _toggle_targets(self, obj_name): + obj = self.scene.object_registry("name", obj_name, None) + if obj is None: + return + + category = getattr(obj, "category", None) + if category == "electric_switch": + for room in obj.in_rooms or []: + for light in self.scene.object_registry("in_rooms", room, default_val=[]): + if getattr(light, "category", None) in ROOM_LIGHT_CATEGORIES: + self._toggle_light(light) + elif category in SELF_LIGHT_CATEGORIES: + self._toggle_light(obj) + + def _toggle_light(self, obj): + visible = not self._target_visibility.get(obj.name, True) + self._target_visibility[obj.name] = visible + if getattr(obj, "category", None) in ROOM_LIGHT_CATEGORIES: + obj.visible = visible + else: + _set_light_prims_visible(obj, visible) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/network_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/network_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..242987dd2ba458cfa16cfae435313b49681668ea --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/network_utils.py @@ -0,0 +1,342 @@ +""" +Adapted from https://github.com/Physical-Intelligence/openpi +""" + +import asyncio +import functools +import http +import logging +import msgpack +import numpy as np +import requests +import time +import torch as th +import traceback +import websockets +import websockets.asyncio.server as _server +import websockets.sync.client +from copy import deepcopy +from omnigibson.macros import gm +from typing import Any, Dict, Optional, Tuple +from urllib.parse import urlparse + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +__all__ = ["WebsocketClientPolicy", "WebsocketPolicyServer"] + +ACTION_CHUNK_REQUEST_KEY = "__action_chunk_size__" + + +class WebsocketClientPolicy: + """Implements the Policy interface by communicating with a server over websocket. + + See WebsocketPolicyServer for a corresponding server implementation. + """ + + def __init__( + self, + host: str = "0.0.0.0", + port: int = 8000, + scheme: str = "ws", + api_key: Optional[str] = None, + allow_reconnect: bool = False, + action_chunk_size: int = 0, + ) -> None: + """ + Initializes the websocket client policy. + + Args: + host (str): Hostname of the websocket server to connect to. + port (int): Port of the websocket server to connect to. Defaults to 8000. + scheme (str): WebSocket scheme to use. Either "wss" (secure) or "ws" (insecure). Defaults to "ws". + api_key (str, optional): API key to include in the Authorization header when connecting to the websocket server, if required. + allow_reconnect (bool): Whether to allow automatic reconnection if the websocket connection is lost. + If False, the client will raise an error if the connection is lost. + If True, the client will attempt to reconnect indefinitely with a delay between attempts. + action_chunk_size (int): Number of server-returned actions to execute before requesting a new + observation-conditioned action. Values <= 1 disable chunk requests. Only enable this when the + server returns an exact open-loop action sequence produced from the current observation. + """ + self._uri = f"{scheme}://{host}:{port}" + self._packer = Packer() + self._api_key = api_key + self._ws, self._server_metadata = None, None + self._allow_reconnect = allow_reconnect + self._action_chunk_size = max(0, int(action_chunk_size)) + self._action_chunk = None + self._action_chunk_index = 0 + self._chunk_requests_supported = self._action_chunk_size > 1 + + def get_server_metadata(self) -> Dict: + return self._server_metadata + + def _wait_for_server(self) -> Tuple[websockets.sync.client.ClientConnection, Dict]: + parsed = urlparse(self._uri) + host = parsed.hostname + port = parsed.port + http_scheme = "https" if parsed.scheme == "wss" else "http" + health_url = f"{http_scheme}://{host}:{port}/healthz" + + # First, wait for the health check to pass + while True: + try: + response = requests.get(health_url, timeout=2) + if response.ok: + logger.info("Health check passed, attempting websocket connection...") + break + except Exception: + pass + logger.info(f"Health check failed, waiting for server at {http_scheme}://{host}:{port}...") + time.sleep(5) + + # Now attempt websocket connection (rest of the code remains the same) + while True: + try: + headers = {"Authorization": f"Api-Key {self._api_key}"} if self._api_key else None + conn = websockets.sync.client.connect( + self._uri, + compression=None, + max_size=None, + additional_headers=headers, + ping_interval=60, + ping_timeout=300, + ) + metadata = unpackb(conn.recv()) + logger.info("Connected to server!") + return conn, metadata + except (ConnectionRefusedError, websockets.exceptions.InvalidMessage, EOFError) as e: + logger.info(f"Websocket connection failed ({e}), retrying...") + time.sleep(5) + + def act(self, obs: Dict) -> th.Tensor: + if self._action_chunk is not None and self._action_chunk_index < self._action_chunk.shape[-2]: + action = self._action_chunk[..., self._action_chunk_index, :].clone() + self._action_chunk_index += 1 + return action + + if self._ws is None: + self._ws, self._server_metadata = self._wait_for_server() + + request = obs + if self._chunk_requests_supported: + request = dict(obs) + request[ACTION_CHUNK_REQUEST_KEY] = self._action_chunk_size + data = self._packer.pack(request) + max_retries = 2 + response = None + + for attempt in range(max_retries + 1): + try: + self._ws.send(data) + response = self._ws.recv() + if isinstance(response, str): + raise RuntimeError(f"Error in inference server:\n{response}") + + action_dict = unpackb(response) + if "action" not in action_dict: + if attempt < max_retries: + logger.warning( + f"Server response missing 'action' key, retrying ({attempt + 1}/{max_retries})..." + ) + continue + raise RuntimeError(f"Server response missing 'action' key: {action_dict}") + action = th.from_numpy(deepcopy(action_dict["action"])).to(th.float32) + if self._chunk_requests_supported: + if "action_chunk" in action_dict: + chunk = th.from_numpy(deepcopy(action_dict["action_chunk"])).to(th.float32) + expected_shape = (*action.shape[:-1], self._action_chunk_size, action.shape[-1]) + if chunk.shape != expected_shape: + raise RuntimeError( + f"Server returned action_chunk shape {tuple(chunk.shape)}, expected {expected_shape}." + ) + if not th.equal(chunk[..., 0, :], action): + raise RuntimeError("Server action must exactly equal action_chunk[..., 0, :].") + self._action_chunk = chunk + self._action_chunk_index = 1 + else: + logger.warning( + "Policy server does not support action chunks; falling back to one request per step." + ) + self._chunk_requests_supported = False + return action + + except websockets.exceptions.ConnectionClosedError as e: + if self._allow_reconnect and attempt < max_retries: + logger.warning(f"Connection lost, reconnecting (attempt {attempt + 1}/{max_retries})...") + self._ws, self._server_metadata = self._wait_for_server() + continue + raise RuntimeError(f"Websocket connection error: {e}") + + def reset(self) -> None: + self._action_chunk = None + self._action_chunk_index = 0 + if self._ws is None: + self._ws, self._server_metadata = self._wait_for_server() + + data = self._packer.pack({"reset": True}) + self._ws.send(data) + + +class WebsocketPolicyServer: + """Serves a policy using the websocket protocol. See websocket_client_policy.py for a client implementation. + + Currently only implements the `load` and `infer` methods. + """ + + def __init__( + self, + policy: Any, + host: str = "0.0.0.0", + port: int = 8000, + metadata: dict | None = None, + ) -> None: + self._policy = policy + self._host = host + self._port = port + self._metadata = metadata or {} + + def serve_forever(self) -> None: + asyncio.run(self.run()) + + async def run(self): + logger.info(f"Starting websocket server on {self._host}:{self._port}...") + async with _server.serve( + self._handler, + self._host, + self._port, + compression=None, + max_size=None, + process_request=_health_check, + ) as server: + await server.serve_forever() + + async def _handler(self, websocket): + logger.info(f"Connection from {websocket.remote_address} opened") + packer = Packer() + + await websocket.send(packer.pack(self._metadata)) + + prev_total_time = None + while True: + try: + start_time = time.monotonic() + result = unpackb(await websocket.recv(), strict_map_key=False) + if "reset" in result: + self._policy.reset() + continue + + obs = deepcopy(result) + + infer_time = time.monotonic() + action = self._policy.act(obs) + infer_time = time.monotonic() - infer_time + + action = { + "action": action.cpu().numpy(), + } + action["server_timing"] = { + "infer_ms": infer_time * 1000, + } + if prev_total_time is not None: + # We can only record the last total time since we also want to include the send time. + action["server_timing"]["prev_total_ms"] = prev_total_time * 1000 + + await websocket.send(packer.pack(action)) + prev_total_time = time.monotonic() - start_time + + except websockets.ConnectionClosed: + logger.info(f"Connection from {websocket.remote_address} closed") + break + except Exception: + logger.error(f"Error in connection from {websocket.remote_address}:\n{traceback.format_exc()}") + if gm.DEBUG: + await websocket.send(traceback.format_exc()) + try: + # Try new websockets API first + await websocket.close( + code=websockets.frames.CloseCode.INTERNAL_ERROR, + reason="Internal server error. Traceback included in previous frame.", + ) + except AttributeError: + # Fallback for older websockets versions + await websocket.close(code=1011, reason="Internal server error") + raise + + +def _health_check(connection, request) -> Optional[Any]: + if hasattr(request, "path") and request.path == "/healthz": + if hasattr(connection, "respond"): + return connection.respond(http.HTTPStatus.OK, "OK\n") + else: + # For older websockets versions, return a simple response + return http.HTTPStatus.OK, {"Content-Type": "text/plain"}, b"OK\n" + # Continue with the normal request handling. + return None + + +""" +Adds NumPy array and PyTorch tensor support to msgpack. + +msgpack is good for (de)serializing data over a network for multiple reasons: +- msgpack is secure (as opposed to pickle/dill/etc which allow for arbitrary code execution) +- msgpack is widely used and has good cross-language support +- msgpack does not require a schema (as opposed to protobuf/flatbuffers/etc) which is convenient in dynamically typed + languages like Python and JavaScript +- msgpack is fast and efficient (as opposed to readable formats like JSON/YAML/etc); I found that msgpack was ~4x faster + than pickle for serializing large arrays using the below strategy + +This module supports serializing both NumPy arrays and PyTorch tensors. PyTorch tensors are converted to +NumPy arrays (zero-copy when possible) before serialization. On deserialization, arrays are returned as NumPy arrays. + +The code below is adapted from https://github.com/lebedov/msgpack-numpy. The reason not to use that library directly is +that it falls back to pickle for object arrays. +""" + + +def pack_data(obj): + if isinstance(obj, th.Tensor): + data = obj.detach().cpu().numpy() + return { + b"__ndarray__": True, + b"data": data.tobytes(), + b"dtype": data.dtype.str, + b"shape": data.shape, + } + + if isinstance(obj, np.ndarray): + if obj.dtype.kind in ("V", "O", "c"): + raise ValueError(f"Unsupported dtype: {obj.dtype}") + return { + b"__ndarray__": True, + b"data": obj.tobytes(), + b"dtype": obj.dtype.str, + b"shape": obj.shape, + } + + if isinstance(obj, np.generic): + return { + b"__npgeneric__": True, + b"data": obj.item(), + b"dtype": obj.dtype.str, + } + + return obj + + +def unpack_data(obj): + if b"__ndarray__" in obj: + return np.ndarray(buffer=obj[b"data"], dtype=np.dtype(obj[b"dtype"]), shape=obj[b"shape"]) + + if b"__npgeneric__" in obj: + return np.dtype(obj[b"dtype"]).type(obj[b"data"]) + + return obj + + +Packer = functools.partial(msgpack.Packer, default=pack_data) +packb = functools.partial(msgpack.packb, default=pack_data) + +Unpacker = functools.partial(msgpack.Unpacker, object_hook=unpack_data) +unpackb = functools.partial(msgpack.unpackb, object_hook=unpack_data) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/obs_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/obs_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b8b7feaa1c45c4acf58619e5cb3d6bca8e743a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/obs_utils.py @@ -0,0 +1,555 @@ +import av +import math +import numpy as np +import omnigibson.utils.transform_utils as T +import torch as th +from av.container import Container +from av.stream import Stream +from tqdm import trange +from typing import Dict, Optional, Tuple, List +from omnigibson.utils.constants import semantic_class_name_to_id +from omnigibson.utils.ui_utils import create_module_logger + +logger = create_module_logger("obs_utils") + +try: + from torch_cluster import fps +except ImportError: + fps = None + +# ============================================== +# Depth +# ============================================== + +MIN_DEPTH = 0.01 +MAX_DEPTH = 10.0 +DEPTH_SHIFT = 3.5 + + +def quantize_depth( + depth: np.ndarray | th.Tensor, + min_depth: float = MIN_DEPTH, + max_depth: float = MAX_DEPTH, + shift: float = DEPTH_SHIFT, + use_log: bool = True, +) -> np.ndarray: + """ + Quantizes depth values to a 12-bit range (0 to 4096) based on the specified min and max depth. + + Args: + depth (np.ndarray or th.tensor): Depth tensor. + min_depth (float): Minimum depth value. + max_depth (float): Maximum depth value. + shift (float): Small value to shift depth to avoid log(0). + use_log (bool): Whether to use logarithmic quantization. If True, uses log scale with shift. If False, uses linear quantization. + Returns: + np.ndarray: Quantized depth tensor. + """ + # convert to numpy if input is torch tensor + if isinstance(depth, th.Tensor): + depth = depth.cpu().numpy() + qmax = (1 << 12) - 1 + + if use_log: + log_min = np.log(min_depth + shift) + log_max = np.log(max_depth + shift) + log_depth = np.log(depth + shift) + norm = (log_depth - log_min) / (log_max - log_min) + else: + norm = (depth - min_depth) / (max_depth - min_depth) + + quantized_depth = np.clip((norm * qmax).round(), 0, qmax).astype(np.uint16) + return quantized_depth + + +def dequantize_depth( + quantized_depth: np.ndarray | th.Tensor, + min_depth: float = MIN_DEPTH, + max_depth: float = MAX_DEPTH, + shift: float = DEPTH_SHIFT, + use_log: bool = True, +) -> np.ndarray | th.Tensor: + """ + Dequantizes a 12-bit depth tensor back to the original depth values. + + Args: + quantized_depth (np.ndarray or th.tensor): Quantized depth tensor. + min_depth (float): Minimum depth value. + max_depth (float): Maximum depth value. + shift (float): Small value to shift depth to avoid log(0). + use_log (bool): Whether to use logarithmic dequantization. If True, uses log scale with shift. If False, uses linear dequantization. + Returns: + np.ndarray or th.tensor: Dequantized depth tensor. + """ + backend = np if isinstance(quantized_depth, np.ndarray) else th + qmax = (1 << 12) - 1 + if use_log: + log_min = math.log(min_depth + shift) + log_max = math.log(max_depth + shift) + log_norm = quantized_depth / qmax + log_depth = log_norm * (log_max - log_min) + log_min + depth = backend.clip(backend.exp(log_depth) - shift, min_depth, max_depth) + else: + norm = quantized_depth / qmax + depth = backend.clip(norm * (max_depth - min_depth) + min_depth, min_depth, max_depth) + + return depth + + +def encode_depth_frame(depth: np.ndarray | th.Tensor) -> av.VideoFrame: + """ + Encodes a depth frame by quantizing it to a 12-bit range and then packing it into YUV420p12le format. + + Args: + depth (np.ndarray or th.tensor): Depth tensor of shape (H, W) with float values. + Returns: + av.VideoFrame: Encoded depth frame in YUV420p12le format, where the Y plane contains the quantized depth values. + """ + quantized_depth = quantize_depth(depth) + H, W = quantized_depth.shape[:2] + # Write depth into the Y plane; set U/V to neutral chroma. + frame = av.VideoFrame(width=W, height=H, format="yuv420p12le") + frame.planes[0].update(quantized_depth.tobytes()) + # Bit depth of 12 → neutral = 2^11 = 2048. + neutral_chroma = np.full((H // 2, W // 2), 2048, dtype=np.uint16) + frame.planes[1].update(neutral_chroma.tobytes()) + frame.planes[2].update(neutral_chroma.tobytes()) + return frame + + +def decode_depth_frame(frame: list[av.VideoFrame]) -> th.Tensor: + """ + Decodes a depth frame by extracting the quantized depth from the Y plane and then dequantizing it back to float values. + Args: + frame (list[av.VideoFrame]): Encoded depth frame. + Returns: + th.Tensor: Decoded depth tensor of shape (N, H, W) with float values. + """ + quantized_depth = th.from_numpy(np.stack([f.reformat(format="gray12le").to_ndarray() for f in frame])) + depth = dequantize_depth(quantized_depth) + return depth + + +# ============================================== +# Video I/O +# ============================================== + + +def create_video_writer( + fpath, + resolution, + codec_name="libx264", + rate=30, + pix_fmt="yuv420p", + stream_options=None, + context_options=None, +) -> Tuple[Container, Stream]: + """ + Creates a video writer to write video frames to when playing back the dataset using PyAV + + Args: + fpath (str): Absolute path that the generated video writer will write to. Should end in .mp4 or .mkv + resolution (tuple): Resolution of the video frames to write (height, width) + codec_name (str): Codec to use for the video writer. Default is "libx264" + rate (int): Frame rate of the video writer. Default is 30 + pix_fmt (str): Pixel format to use for the video writer. Default is "yuv420p" + stream_options (dict): Additional stream options to pass to the video writer. Default is None + context_options (dict): Additional context options to pass to the video writer. Default is None + Returns: + av.Container: PyAV container object that can be used to write video frames + av.Stream: PyAV stream object that can be used to write video frames + """ + assert fpath.endswith(".mp4") or fpath.endswith( + ".mkv" + ), f"Video writer fpath must end with .mp4 or .mkv! Got: {fpath}" + container = av.open(fpath, mode="w") + stream = container.add_stream(codec_name, rate=rate) + stream.height = resolution[0] + stream.width = resolution[1] + stream.pix_fmt = pix_fmt + if stream_options is not None: + stream.options = stream_options + if context_options is not None: + stream.codec_context.options = context_options + return container, stream + + +def write_video(obs, video_writer, mode="rgb", batch_size=None, **kwargs) -> None: + """ + Writes videos to the specified video writers using the current trajectory history + + Args: + obs (np.ndarray): Observation data + video_writer (container, stream): PyAV container and stream objects to write video frames to + mode (str): Mode to write video frames to. Only "rgb", "depth" and "seg" are supported. + batch_size (int): Batch size to write video frames to. If None, write video frames to the entire video. + kwargs (dict): Additional keyword arguments to pass to the video writer. + """ + container, stream = video_writer + batch_size = batch_size or obs.shape[0] + if mode == "rgb": + for i in range(0, obs.shape[0], batch_size): + for frame in obs[i : i + batch_size]: + frame = av.VideoFrame.from_ndarray(frame[..., :3], format="rgb24") + for packet in stream.encode(frame): + container.mux(packet) + elif mode == "depth" or mode == "depth_linear": + reverse_depth = kwargs.get("reverse_depth", False) + use_log = kwargs.get("use_log", True) + for i in range(0, obs.shape[0], batch_size): + quantized_depth = quantize_depth(obs[i : i + batch_size], use_log=use_log) + if reverse_depth: + qmax = (1 << 16) - 1 + quantized_depth = qmax - quantized_depth + for frame in quantized_depth: + frame = av.VideoFrame.from_ndarray(frame, format="gray12le") + for packet in stream.encode(frame): + container.mux(packet) + else: + raise ValueError(f"Unsupported video mode: {mode}.") + + +# ============================================== +# Point Cloud +# ============================================== + + +def depth_to_pcd( + depth: th.Tensor, # (B, [T], H, W) + rel_pose: th.Tensor, # (B, [T], 7) relative pose from camera to base [pos, quat] + K: th.Tensor, # (3, 3) +) -> th.Tensor: + """ + Convert depth images to point clouds with batch processing support. + Args: + depth: (B, H, W) depth tensor + rel_pose: (B, 7) relative pose from camera to base tensor [pos, quat] + K: (3, 3) camera intrinsics tensor + max_depth: maximum depth value to filter + Returns: + pc: (B, H, W, 3) point cloud tensor in base frame + """ + original_shape = depth.shape + depth = depth.view(-1, original_shape[-2], original_shape[-1]) # (B, H, W) + rel_pose = rel_pose.view(-1, 7) # (B, 7) + B, H, W = depth.shape + device = depth.device + + # Get relative pose and convert to transformation matrix + rel_pos = rel_pose[:, :3] # (B, 3) + rel_quat = rel_pose[:, 3:] # (B, 4) + rel_rot = T.quat2mat(rel_quat) # (B, 3, 3) + + # Add camera coordinate system adjustment (180 degree rotation around X-axis) + rot_add = T.euler2mat(th.tensor([np.pi, 0, 0], device=device)) # (3, 3) + rel_rot_matrix = th.matmul(rel_rot, rot_add) # (B, 3, 3) + + # Create camera_to_base transformation matrix + camera_to_base_tf = th.eye(4, device=device).unsqueeze(0).expand(B, 4, 4).clone() + camera_to_base_tf[:, :3, :3] = rel_rot_matrix + camera_to_base_tf[:, :3, 3] = rel_pos + + # Create pixel coordinates + y, x = th.meshgrid(th.arange(H, device=device), th.arange(W, device=device), indexing="ij") + u = x.unsqueeze(0).expand(B, H, W) + v = y.unsqueeze(0).expand(B, H, W) + uv = th.stack([u, v, th.ones_like(u)], dim=-1).float() # (B, H, W, 3) + + # Compute inverse of camera intrinsics + Kinv = th.linalg.inv(K).to(device) # (3, 3) + + # Convert to point cloud in camera frame + pc_camera = depth.unsqueeze(-1) * th.matmul(uv, Kinv.transpose(-2, -1)) # (B, H, W, 3) + + # Add homogeneous coordinate + pc_camera_homo = th.cat([pc_camera, th.ones_like(pc_camera[..., :1])], dim=-1) # (B, H, W, 4) + + # Transform from camera frame to base frame + pc_camera_homo_flat = pc_camera_homo.view(B, -1, 4) # (B, H*W, 4) + pc_base = th.matmul(pc_camera_homo_flat, camera_to_base_tf.transpose(-2, -1)) # (B, H*W, 4) + pc_base = pc_base[..., :3].view(*original_shape, 3) # (B, [T], H, W, 3) + + return pc_base + + +def downsample_pcd(color_pcd, num_points, use_fps=True) -> Tuple[th.Tensor, th.Tensor]: + """ + Downsample point clouds with batch FPS processing or random sampling. + + Args: + color_pcd: (B, [T], N, 6) point cloud tensor [rgb, xyz] for each batch + num_points: target number of points + Returns: + color_pcd: (B, num_points, 6) downsampled point cloud + sampled_idx: (B, num_points) sampled indices + """ + original_shape = color_pcd.shape + color_pcd = color_pcd.view(-1, original_shape[-2], original_shape[-1]) # (B, N, 6) + B, N, C = color_pcd.shape + device = color_pcd.device + + if N > num_points: + if use_fps: + # Initialize output tensors + output_pcd = th.zeros(B, num_points, C, device=device, dtype=color_pcd.dtype) + output_idx = th.zeros(B, num_points, device=device, dtype=th.long) + # True batch FPS - process all batches together + xyz = color_pcd[:, :, 3:6].contiguous() # (B, N, 3) + xyz_flat = xyz.view(-1, 3) # (B*N, 3) + # Create batch indices for all points + batch_indices = th.arange(B, device=device).repeat_interleave(N) # (B*N,) + # Single FPS call for all batches + assert ( + fps is not None + ), "torch_cluster.fps is not available! Please make sure you have omnigibson setup with eval dependencies." + idx_flat = fps(xyz_flat, batch_indices, ratio=float(num_points) / N, random_start=True) + # Vectorized post-processing + batch_idx = idx_flat // N # Which batch each index belongs to + local_idx = idx_flat % N # Local index within each batch + for b in range(B): + batch_mask = batch_idx == b + if batch_mask.sum() > 0: + batch_local_indices = local_idx[batch_mask][:num_points] + output_pcd[b, : len(batch_local_indices)] = color_pcd[b][batch_local_indices] + output_idx[b, : len(batch_local_indices)] = batch_local_indices + else: + # Randomly sample num_points indices without replacement for each batch + output_idx = th.stack( + [th.randperm(N, device=device)[:num_points] for _ in range(B)], dim=0 + ) # (B, num_points) + # Use proper batch indexing + batch_indices = th.arange(B, device=device).unsqueeze(1).expand(B, num_points) + output_pcd = color_pcd[batch_indices, output_idx] # (B, num_points, C) + else: + pad_num = num_points - N + random_idx = th.randint(0, N, (B, pad_num), device=device) # (B, pad_num) + seq_idx = th.arange(N, device=device).unsqueeze(0).expand(B, N) # (B, N) + full_idx = th.cat([seq_idx, random_idx], dim=1) # (B, num_points) + batch_indices = th.arange(B, device=device).unsqueeze(1).expand(B, num_points) # (B, num_points) + output_pcd = color_pcd[batch_indices, full_idx] # (B, num_points, C) + output_idx = full_idx + + output_pcd = output_pcd.view(*original_shape[:-2], num_points, C) # (B, [T], num_points, 6) + return output_pcd, output_idx + + +def process_fused_point_cloud( + obs: dict, + camera_intrinsics: Dict[str, th.Tensor], + pcd_range: Tuple[float, float, float, float, float, float], # x_min, x_max, y_min, y_max, z_min, z_max + pcd_num_points: Optional[int] = None, + use_fps: bool = True, + verbose: bool = False, +) -> Tuple[th.Tensor, Optional[th.Tensor]]: + """ + Given a dictionary of observations, process the fused point cloud from all cameras and return the final point cloud tensor in robot base frame. + Args: + obs (dict): Dictionary of observations containing point cloud data from different cameras. + camera_intrinsics (Dict[str, th.Tensor]): Dictionary of camera intrinsics for each camera. + pcd_range (Tuple[float, float, float, float, float, float]): Range of the point cloud to filter [x_min, x_max, y_min, y_max, z_min, z_max]. + pcd_num_points (Optional[int]): Number of points to sample from the point cloud. If None, no downsampling is performed. + use_fps (bool): Whether to use farthest point sampling for point cloud downsampling. Default is True. + verbose (bool): Whether to print verbose output during processing. Default is False. + """ + if verbose: + print("Processing fused point cloud from observations...") + rgb_pcd = [] + for idx, (camera_name, intrinsics) in enumerate(camera_intrinsics.items()): + if f"{camera_name}::pointcloud" in obs: + # should already be in robot base frame, see BaseRobot._get_obs() + pcd = obs[f"{camera_name}::pointcloud"] + rgb_pcd.append(th.cat([pcd[:, :3] / 255.0, pcd[:, 3:]], dim=-1)) + else: + # need to convert from depth to point cloud in robot base frame + pcd = depth_to_pcd( + obs[f"{camera_name}::depth_linear"], obs["cam_rel_poses"][..., 7 * idx : 7 * idx + 7], intrinsics + ) + rgb_pcd.append( + th.cat([obs[f"{camera_name}::rgb"][..., :3] / 255.0, pcd], dim=-1).flatten(-3, -2) + ) # shape (B, [T], H*W, 6) + # Fuse all point clouds together + fused_pcd_all = th.cat(rgb_pcd, dim=-2).to(device="cuda") + # Now, clip the point cloud to the specified range + x_min, x_max, y_min, y_max, z_min, z_max = pcd_range + mask = ( + (fused_pcd_all[..., 3] >= x_min) + & (fused_pcd_all[..., 3] <= x_max) + & (fused_pcd_all[..., 4] >= y_min) + & (fused_pcd_all[..., 4] <= y_max) + & (fused_pcd_all[..., 5] >= z_min) + & (fused_pcd_all[..., 5] <= z_max) + ) + fused_pcd_all[~mask] = 0.0 + # Now, downsample the point cloud if needed + if pcd_num_points is not None: + if verbose: + print( + f"Downsampling point cloud to {pcd_num_points} points using {'FPS' if use_fps else 'random sampling'}" + ) + fused_pcd = downsample_pcd(fused_pcd_all, pcd_num_points, use_fps=use_fps)[0] + fused_pcd = fused_pcd.float() + else: + fused_pcd = fused_pcd_all.float() + + return fused_pcd + + +def color_pcd_vis(color_pcd: np.ndarray): + import open3d as o3d + + pcd = o3d.geometry.PointCloud() + axis = o3d.geometry.TriangleMesh.create_coordinate_frame(size=0.3, origin=[0, 0, 0]) + + # Rotation matrices + Rz_90 = o3d.geometry.get_rotation_matrix_from_axis_angle([0, 0, np.pi / 2]) # 90 deg about z + Rx_m90 = o3d.geometry.get_rotation_matrix_from_axis_angle([-np.pi / 2, 0, 0]) # -90 deg about x + + # visualize with open3D + if color_pcd.ndim == 2: + colors = color_pcd[:, :3] + points = color_pcd[:, 3:] + points = (points @ Rz_90.T) @ Rx_m90.T + pcd.colors = o3d.utility.Vector3dVector(colors) + pcd.points = o3d.utility.Vector3dVector(points) + o3d.visualization.draw_geometries([pcd, axis]) + print("number points", color_pcd.shape[0]) + else: + # realtime streaming + vis = o3d.visualization.Visualizer() + vis.create_window() + for i in trange(color_pcd.shape[0]): + colors = color_pcd[i, :, :3] + points = color_pcd[i, :, 3:] + points = (points @ Rz_90.T) @ Rx_m90.T + pcd.colors = o3d.utility.Vector3dVector(colors) + pcd.points = o3d.utility.Vector3dVector(points) + vis.clear_geometries() + vis.add_geometry(pcd) + vis.add_geometry(axis) + vis.poll_events() + vis.update_renderer() + vis.destroy_window() + + +# ============================================== +# Segmentation +# ============================================== + + +def instance_id_to_instance( + obs: th.Tensor, instance_id_mapping: Dict[int, str], unique_ins_ids: List[int] +) -> Tuple[th.Tensor, Dict[int, str]]: + """ + Instance_id segmentation map each unique visual meshes of objects (e.g. /World/scene_name/object_name/visual_mesh_0) + This function merges all visual meshes of the same object instance to a single instance id. + Args: + obs (th.Tensor): (N, H, W) instance_id segmentation + instance_id_mapping (Dict[int, str]): Dict mapping instance_id ids to instance names + Returns: + instance_seg (th.Tensor): (N, H, W) instance segmentation + instance_mapping (Dict[int, str]): Dict mapping instance ids to instance names + """ + # trim the instance ids mapping to the valid instance ids + instance_id_mapping = {k: v for k, v in instance_id_mapping.items() if k in unique_ins_ids} + # extract the actual instance name, which is located at /World/scene_name/object_name + # Note that 0, 1 are special cases for background and unlabelled, respectivelly + instance_id_to_instance = {k: v.split("/")[3] for k, v in instance_id_mapping.items() if k not in [0, 1]} + # get all unique instance names + instance_names = set(instance_id_to_instance.values()) + # construct a new instance mapping from instance names to instance ids + instance_mapping = {0: "background", 1: "unlabelled"} + instance_mapping.update({k + 2: v for k, v in enumerate(instance_names)}) # {i: object_name} + reversed_instance_mapping = {v: k for k, v in instance_mapping.items()} # {object_name: i} + # put back the background and unlabelled + instance_id_to_instance.update({0: "background", 1: "unlabelled"}) + # Now, construct the instance segmentation + instance_seg = th.zeros_like(obs) + # Create lookup tensor for faster indexing + lookup = th.full((max(unique_ins_ids) + 1,), -1, dtype=th.long, device=obs.device) + for instance_id in unique_ins_ids: + lookup[instance_id] = reversed_instance_mapping[instance_id_to_instance[instance_id]] + instance_seg = lookup[obs] + # Note that now the returned instance mapping will be unique (i.e. no unused instance ids) + return instance_seg, instance_mapping + + +def instance_to_semantic( + obs, instance_mapping: Dict[int, str], unique_ins_ids: List[int], is_instance_id: bool = True +) -> th.Tensor: + """ + Convert instance / instance id segmentation to semantic segmentation. + Args: + obs (th.Tensor): (N, H, W) instance / instance_id segmentation + instance_mapping (Dict[int, str]): Dict mapping instance IDs to instance names + unique_ins_ids (List[int]): List of unique instance IDs + is_instance_id (bool): Whether the input is instance id segmentation + Returns: + semantic_seg (th.Tensor): (N, H, W) semantic segmentation + """ + # trim the instance ids mapping to the valid instance ids + instance_mapping = {k: v for k, v in instance_mapping.items() if k in unique_ins_ids} + # we remove 0: background, 1: unlabelled from the instance mapping for now + instance_mapping.pop(0, None) + instance_mapping.pop(1, None) + # get semantic name from instance mapping + if is_instance_id: + instance_mapping = {k: v.split("/")[3] for k, v in instance_mapping.items()} + # instance names are of category_model_id, so we extract the category name + # with the exception of robot. We assume that robot is the only instance with "robot" in the name + instance_to_semantic = {} + for k, v in instance_mapping.items(): + if "robot" in v: + instance_to_semantic[k] = "agent" + else: + instance_to_semantic[k] = v.rsplit("_", 2)[0] + instance_to_semantic.update({0: "background", 1: "unlabelled"}) + # Now, construct the semantic segmentation + semantic_seg = th.zeros_like(obs) + semantic_name_to_id = semantic_class_name_to_id() + # Create lookup tensor for faster indexing + lookup = th.full((max(unique_ins_ids) + 1,), -1, dtype=th.long, device=obs.device) + for instance_id in instance_mapping: + lookup[instance_id] = semantic_name_to_id[instance_to_semantic[instance_id]] + semantic_seg = lookup[obs] + return semantic_seg + + +def instance_to_bbox( + obs: th.Tensor, instance_mapping: Dict[int, str], unique_ins_ids: List[int] +) -> List[List[Tuple[int, int, int, int, int]]]: + """ + Convert instance segmentation to bounding boxes. + + Args: + obs (th.Tensor): (N, H, W) tensor of instance IDs + instance_mapping (Dict[int, str]): Dict mapping instance IDs to instance names + Note: this does not need to include all instance IDs, only the ones that we want to generate bbox for + unique_ins_ids (List[int]): List of unique instance IDs + Returns: + List of N lists, each containing tuples (x_min, y_min, x_max, y_max, instance_id) for each instance + """ + if len(obs.shape) == 2: + obs = obs.unsqueeze(0) # Add batch dimension if single frame + N = obs.shape[0] + bboxes = [[] for _ in range(N)] + valid_ids = [id for id in instance_mapping if id in unique_ins_ids] + for instance_id in valid_ids: + # Create mask for this instance + mask = obs == instance_id # (N, H, W) + # Find bounding boxes for each frame + for n in range(N): + frame_mask = mask[n] # (H, W) + if not frame_mask.any(): + continue + # Find non-zero indices (where instance exists) + y_coords, x_coords = th.where(frame_mask) + if len(y_coords) == 0: + continue + # Calculate bounding box + x_min = x_coords.min().item() + x_max = x_coords.max().item() + y_min = y_coords.min().item() + y_max = y_coords.max().item() + bboxes[n].append((x_min, y_min, x_max, y_max, instance_id)) + + return bboxes diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/score_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/score_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..65cfc123519912cf9f9326cee8e98980e5b7e57a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/utils/score_utils.py @@ -0,0 +1,472 @@ +import argparse +import json +import os +from collections import defaultdict +from pathlib import Path +from omnigibson.macros import gm +from omnigibson.eval.utils.eval_utils import ( + EVAL_TIMEOUT_MULTIPLIER, + NUM_HIDDEN_TEST_INSTANCES, + NUM_PUBLIC_TEST_INSTANCES, + PROPRIOCEPTION_INDICES, + TASK_NAMES_TO_INDICES, + TEST_INSTANCE_IDS, +) + + +HUMAN_STATS_KEYS = ( + "length", + "distance_traveled", + "left_eef_displacement", + "right_eef_displacement", +) + + +def default_task_jsonl_path() -> str: + return os.path.join(gm.DATA_PATH, "2026-challenge-task-instances", "metadata", "task.jsonl") + + +def load_human_stats(task_name: str, task_jsonl_path: str | None = None) -> dict[str, float]: + """ + Load task-level human statistics for evaluator metrics. + + The file is one JSON object per task and should contain: + task_name, task_index, length, distance_traveled, left_eef_displacement, right_eef_displacement. + """ + task_jsonl_path = os.path.expanduser(task_jsonl_path or default_task_jsonl_path()) + task_idx = TASK_NAMES_TO_INDICES[task_name] + with open(task_jsonl_path, "r") as f: + for line in f: + if not line.strip(): + continue + task_stats = json.loads(line) + if task_stats.get("task_name") == task_name or task_stats.get("task_index") == task_idx: + return {key: task_stats[key] for key in HUMAN_STATS_KEYS} + + raise ValueError(f"Could not find human stats for task {task_name} in {task_jsonl_path}") + + +def generate_task_jsonl_from_lerobot_v3( + data_dir: str, + output_path: str, + robot_type: str = "R1Pro", + num_tasks: int | None = None, +) -> None: + """ + Aggregate LeRobot v3 per-task datasets into the task-level task.jsonl format. + + Supports both layouts: + data_dir//{meta,data}/... + data_dir/{meta,data}/... where each chunk is one task. + """ + import pandas as pd + + data_dir = Path(os.path.expanduser(data_dir)) + task_names_by_idx = {task_idx: task_name for task_name, task_idx in TASK_NAMES_TO_INDICES.items()} + totals = {} + task_idx_filter = set(range(num_tasks)) if num_tasks is not None else None + + if (data_dir / "meta" / "tasks.parquet").exists(): + with open(data_dir / "meta" / "info.json", "r") as f: + fps = json.load(f).get("fps", 30) + episode_chunk_dirs = sorted((data_dir / "meta" / "episodes").glob("chunk-*")) + for episode_chunk_dir in episode_chunk_dirs: + task_idx = int(episode_chunk_dir.name.split("-")[-1]) + if task_idx_filter is not None and task_idx not in task_idx_filter: + continue + task_totals = _compute_lerobot_v3_task_totals( + episode_paths=sorted(episode_chunk_dir.glob("file-*.parquet")), + data_paths=sorted((data_dir / "data" / f"chunk-{task_idx:03d}").glob("file-*.parquet")), + task_name=task_names_by_idx.get(task_idx, str(task_idx)), + fps=fps, + robot_type=robot_type, + ) + if task_totals is not None: + totals[task_idx] = task_totals + _write_task_jsonl(totals=totals, task_names_by_idx=task_names_by_idx, output_path=output_path) + return + + for task_dir in sorted(path for path in data_dir.iterdir() if path.is_dir()): + task_info_path = task_dir / "meta" / "tasks.parquet" + if not task_info_path.exists(): + continue + + task_info = pd.read_parquet(task_info_path) + task_idx = int(task_info["task_index"].iloc[0]) + if task_idx_filter is not None and task_idx not in task_idx_filter: + continue + task_name = task_names_by_idx.get(task_idx, task_dir.name) + with open(task_dir / "meta" / "info.json", "r") as f: + fps = json.load(f).get("fps", 30) + + task_totals = _compute_lerobot_v3_task_totals( + episode_paths=sorted((task_dir / "meta" / "episodes").glob("chunk-*/file-*.parquet")), + data_paths=sorted((task_dir / "data").glob("chunk-*/file-*.parquet")), + task_name=task_name, + fps=fps, + robot_type=robot_type, + ) + if task_totals is not None: + totals[task_idx] = task_totals + + _write_task_jsonl(totals=totals, task_names_by_idx=task_names_by_idx, output_path=output_path) + + +def _compute_lerobot_v3_task_totals( + episode_paths: list[Path], + data_paths: list[Path], + task_name: str, + fps: int, + robot_type: str, +) -> dict | None: + import numpy as np + import pandas as pd + + if not episode_paths or not data_paths: + return None + + episode_lengths = {} + for path in episode_paths: + episodes = pd.read_parquet(path, columns=["episode_index", "length"]) + episode_lengths.update({int(row.episode_index): float(row.length) for row in episodes.itertuples(index=False)}) + + data_paths = sorted(data_paths) + state_sample = pd.read_parquet(data_paths[0], columns=["observation.state"]).iloc[0]["observation.state"] + base_position_idx, base_velocity_idx, eef_indices = _resolve_lerobot_state_indices( + robot_type=robot_type, + state_dim=len(state_sample), + ) + + episode_totals = defaultdict(lambda: {key: 0.0 for key in HUMAN_STATS_KEYS if key != "length"}) + previous_state = {} + for path in data_paths: + data = pd.read_parquet(path, columns=["episode_index", "observation.state"]) + for episode_idx, group in data.groupby("episode_index", sort=False): + episode_idx = int(episode_idx) + current_values = np.stack(group["observation.state"].to_numpy()) + if base_position_idx is None: + assert base_velocity_idx is not None, "Need either robot_pos or base_qvel to compute base travel" + base_qvel = current_values[:, base_velocity_idx] + episode_totals[episode_idx]["distance_traveled"] += ( + np.linalg.norm(base_qvel[:, :2], axis=-1).sum() / fps + ) + + values = current_values + if episode_idx in previous_state: + values = np.concatenate([previous_state[episode_idx][None, :], values], axis=0) + if len(values) > 1: + if base_position_idx is not None: + robot_positions = values[:, base_position_idx] + episode_totals[episode_idx]["distance_traveled"] += np.linalg.norm( + robot_positions[1:] - robot_positions[:-1], axis=-1 + ).sum() + for key, state_idx in eef_indices.items(): + positions = values[:, state_idx] + episode_totals[episode_idx][key] += np.linalg.norm(positions[1:] - positions[:-1], axis=-1).sum() + previous_state[episode_idx] = values[-1] + + num_episodes = len(episode_lengths) + if num_episodes == 0: + return None + + return { + "task_name": task_name, + "num_episodes": num_episodes, + "length": sum(episode_lengths.values()), + "distance_traveled": sum(stats["distance_traveled"] for stats in episode_totals.values()), + "left_eef_displacement": sum(stats["left_eef_displacement"] for stats in episode_totals.values()), + "right_eef_displacement": sum(stats["right_eef_displacement"] for stats in episode_totals.values()), + } + + +def _resolve_lerobot_state_indices( + robot_type: str, + state_dim: int, +) -> tuple[slice | None, slice | None, dict[str, slice]]: + if robot_type == "R1Pro" and state_dim >= 256: + return ( + slice(140, 143), + None, + { + "left_eef_displacement": slice(186, 189), + "right_eef_displacement": slice(225, 228), + }, + ) + + proprio_indices = PROPRIOCEPTION_INDICES[robot_type] + base_position_idx = proprio_indices.get("robot_pos") + base_velocity_idx = proprio_indices.get("base_qvel") + if base_position_idx is None and base_velocity_idx is None: + raise ValueError( + "This LeRobot dataset does not expose robot_pos or base_qvel in observation.state, " + "so human base distance cannot be computed." + ) + + return ( + base_position_idx, + base_velocity_idx, + { + "left_eef_displacement": proprio_indices["eef_left_pos"], + "right_eef_displacement": proprio_indices["eef_right_pos"], + }, + ) + + +def _write_task_jsonl(totals: dict, task_names_by_idx: dict[int, str], output_path: str) -> None: + output_path = os.path.expanduser(output_path) + output_dir = os.path.dirname(output_path) + if output_dir: + os.makedirs(output_dir, exist_ok=True) + with open(output_path, "w") as f: + for task_idx in sorted(totals): + num_episodes = totals[task_idx]["num_episodes"] + if num_episodes == 0: + continue + task_stats = { + "task_index": task_idx, + "task_name": totals[task_idx].get("task_name", task_names_by_idx.get(task_idx, str(task_idx))), + "num_episodes": num_episodes, + } + for key in HUMAN_STATS_KEYS: + task_stats[key] = round(totals[task_idx][key] / num_episodes, 4) + json.dump(task_stats, f) + f.write("\n") + + +def sanity_check_filename(input_dir: str) -> None: + """ + Sanity check whether the input directory name follows the expected format: + input_dir/ + ..../ + json/ + __.json + In particular, append 0 to rollout_id if missing from json file. + Args: + input_dir (str): Path to the directory containing evaluation result json files. + """ + input_dir = os.path.expanduser(input_dir) + base_name = os.path.basename(os.path.normpath(input_dir)) + track, testset, team, affiliation, date = base_name.split(".") + assert track in ["standard", "privileged"], f"Track {track} not recognized" + assert testset in ["public", "hidden"], f"Testset {testset} not recognized" + assert team != "", "Team name cannot be empty" + assert affiliation != "", "Affiliation name cannot be empty" + assert date != "", "Date cannot be empty" + # Now, check all json files in the json folder + assert os.path.exists(f"{input_dir}/json"), f"Input path {input_dir}/json does not exist" + for file in os.listdir(f"{input_dir}/json"): + if file.endswith(".json") is False: + print(f"Skipping non-json file {file} in input directory") + continue + file_name = os.path.splitext(file)[0] + if not file_name.split("_")[-2].isdigit(): + new_file_name = f"{file_name}_0.json" + os.rename( + os.path.join(f"{input_dir}/json", file), + os.path.join(f"{input_dir}/json", new_file_name), + ) + print(f"Renamed {file} to {new_file_name}") + + +def compute_final_q_score( + input_dir: str, output_dir: str, final_score_only: bool = True, verbose: bool = False +) -> None: + """ + Compute the final Q score from the evaluation result json files stored in the given path. + Args: + input_dir (str): Path to the directory containing evaluation result json files. + Should be of the form ..../ containing a json folder for all results. + output_dir (str): Path to save the computed final scores json file. + final_score_only (bool): Whether to only save the final scores, or also per-rollout scores. + verbose (bool): Whether to print verbose output. + """ + input_dir = os.path.expanduser(input_dir) + output_dir = os.path.expanduser(output_dir) + # get the root of the input dir to extract team, affiliation, date + base_name = os.path.basename(os.path.normpath(input_dir)) + track, testset, team, affiliation, date = base_name.split(".") + # get all possible filenames: + possible_filenames = set() + for task_name in TASK_NAMES_TO_INDICES: + test_instances = ( + TEST_INSTANCE_IDS[:NUM_PUBLIC_TEST_INSTANCES] + if testset == "public" + else TEST_INSTANCE_IDS[NUM_PUBLIC_TEST_INSTANCES:] + ) + for instance_id in test_instances: + for rollout_id in range(1): # 1 rollout per instance + filename = f"{task_name}_{instance_id}_{rollout_id}.json" + possible_filenames.add(filename) + n_instances_per_task = NUM_PUBLIC_TEST_INSTANCES if testset == "public" else NUM_HIDDEN_TEST_INSTANCES + # Initialize score dictionaries + q_score = {task_name: dict() for task_name in TASK_NAMES_TO_INDICES.keys()} + time_score = {task_name: dict() for task_name in TASK_NAMES_TO_INDICES.keys()} + base_distance_score = {task_name: dict() for task_name in TASK_NAMES_TO_INDICES.keys()} + left_distance_score = {task_name: dict() for task_name in TASK_NAMES_TO_INDICES.keys()} + right_distance_score = {task_name: dict() for task_name in TASK_NAMES_TO_INDICES.keys()} + # Load results + n_rollouts = 0 + for file in os.listdir(f"{input_dir}/json"): + if file.endswith(".json") is False: + print(f"Skipping non-json file {file} in input directory") + continue + assert file in possible_filenames, f"File {file} is not a valid evaluation result file" + # get file name without extension + file_name = os.path.splitext(file)[0] + task_name, instance_id, rollout_id = file_name.rsplit("_", 2) + with open(os.path.join(f"{input_dir}/json", file), "r") as f: + result = json.load(f) + # get score + q_score[task_name][f"{instance_id}_{rollout_id}"] = result["q_score"]["final"] + normalized_time = result["time"]["normalized_time"] + time_score[task_name][f"{instance_id}_{rollout_id}"] = EVAL_TIMEOUT_MULTIPLIER / ( + EVAL_TIMEOUT_MULTIPLIER - 1.0 + ) - 1 / ((EVAL_TIMEOUT_MULTIPLIER - 1.0) * normalized_time) + base_distance_score[task_name][f"{instance_id}_{rollout_id}"] = result["normalized_agent_distance"]["base"] + left_distance_score[task_name][f"{instance_id}_{rollout_id}"] = result["normalized_agent_distance"]["left"] + right_distance_score[task_name][f"{instance_id}_{rollout_id}"] = result["normalized_agent_distance"]["right"] + n_rollouts += 1 + + # Now, compute averaged task score + q_score_avg, task_sr, time_score_avg, base_distance_score_avg, left_distance_score_avg, right_distance_score_avg = ( + dict(), + dict(), + dict(), + dict(), + dict(), + dict(), + ) + for task_name in TASK_NAMES_TO_INDICES.keys(): + q_score_avg[task_name] = sum(q_score[task_name].values()) / n_instances_per_task + task_sr[task_name] = sum(1 for v in q_score[task_name].values() if v == 1) / n_instances_per_task + time_score_avg[task_name] = sum(time_score[task_name].values()) / n_instances_per_task + base_distance_score_avg[task_name] = sum(base_distance_score[task_name].values()) / n_instances_per_task + left_distance_score_avg[task_name] = sum(left_distance_score[task_name].values()) / n_instances_per_task + right_distance_score_avg[task_name] = sum(right_distance_score[task_name].values()) / n_instances_per_task + + # Now, compute overall score across tasks + overall_q_score = sum(q_score_avg.values()) / len(TASK_NAMES_TO_INDICES) + overall_task_sr = sum(task_sr.values()) / len(TASK_NAMES_TO_INDICES) + overall_time_score = sum(time_score_avg.values()) / len(TASK_NAMES_TO_INDICES) + overall_base_distance_score = sum(base_distance_score_avg.values()) / len(TASK_NAMES_TO_INDICES) + overall_left_distance_score = sum(left_distance_score_avg.values()) / len(TASK_NAMES_TO_INDICES) + overall_right_distance_score = sum(right_distance_score_avg.values()) / len(TASK_NAMES_TO_INDICES) + + output_json = { + "team": team.replace("_", " "), + "affiliation": affiliation.replace("_", " "), + "date": date, + "track": track, + "testset": testset, + "overall_scores": { + "q_score": overall_q_score, + "task_sr": overall_task_sr, + "time_score": overall_time_score, + "base_distance_score": overall_base_distance_score, + "left_distance_score": overall_left_distance_score, + "right_distance_score": overall_right_distance_score, + }, + } + if not final_score_only: + output_json["per_task_scores"] = { + "q_score": q_score_avg, + "task_sr": task_sr, + "time_score": time_score_avg, + "base_distance_score": base_distance_score_avg, + "left_distance_score": left_distance_score_avg, + "right_distance_score": right_distance_score_avg, + } + output_json["per_rollout_scores"] = { + "q_score": q_score, + "time_score": time_score, + "base_distance_score": base_distance_score, + "left_distance_score": left_distance_score, + "right_distance_score": right_distance_score, + } + with open(f"{output_dir}/{track}.{testset}.{team}.{affiliation}.{date}.json", "w") as f: + json.dump(output_json, f, indent=4) + + print("Total rollouts:", n_rollouts) + print("Final Q Score:", overall_q_score) + print("Final Task Success Rate:", overall_task_sr) + if verbose: + print("Final Time Score:", overall_time_score) + print("Final Base Distance Score:", overall_base_distance_score) + print("Final Left Distance Score:", overall_left_distance_score) + print("Final Right Distance Score:", overall_right_distance_score) + print(f"Final scores saved to {output_dir}/{track}.{team}.{affiliation}.{date}.json") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--generate_task_jsonl", + action="store_true", + help="Generate task-level human stats JSONL instead of scoring submissions.", + ) + parser.add_argument( + "--lerobot_data_dir", + type=str, + default=None, + help="LeRobot v3 directory, either one subdirectory per task or one aggregated dataset with one chunk per task.", + ) + parser.add_argument( + "--task_jsonl", + type=str, + default=default_task_jsonl_path(), + help="Output path for generated task-level human stats, or evaluator input path.", + ) + parser.add_argument( + "--robot_type", + type=str, + default="R1Pro", + help="Robot type used when aggregating LeRobot v3 data.", + ) + parser.add_argument( + "--num_tasks", + type=int, + default=None, + help="Only generate stats for task indices 0 through num_tasks - 1.", + ) + parser.add_argument( + "--input_dir", + "-i", + type=str, + default=None, + help="Path to the directory containing evaluation result json files.", + ) + parser.add_argument( + "--output_dir", "-o", type=str, default=None, help="Path to save the computed final scores json file." + ) + parser.add_argument( + "--final_score_only", + "-f", + action="store_true", + help="Whether to only save the final scores, or also per-rollout scores.", + ) + parser.add_argument("--verbose", "-v", action="store_true", help="Whether to print verbose output.") + args = parser.parse_args() + + if args.generate_task_jsonl: + assert args.lerobot_data_dir is not None, "--lerobot_data_dir is required with --generate_task_jsonl" + generate_task_jsonl_from_lerobot_v3( + args.lerobot_data_dir, + args.task_jsonl, + robot_type=args.robot_type, + num_tasks=args.num_tasks, + ) + print(f"Generated task-level human stats at {args.task_jsonl}") + raise SystemExit(0) + + assert args.input_dir is not None, "--input_dir is required when scoring submissions" + assert args.output_dir is not None, "--output_dir is required when scoring submissions" + assert os.path.exists(args.input_dir), f"Input path {args.input_dir} does not exist" + os.makedirs(args.output_dir, exist_ok=True) + # Iterate through all submission folders in the input directory + for submission in os.listdir(args.input_dir): + submission_path = os.path.join(args.input_dir, submission) + print(f"Processing submission folder: {submission_path}") + sanity_check_filename(submission_path) + compute_final_q_score( + submission_path, args.output_dir, final_score_only=args.final_score_only, verbose=args.verbose + ) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/wrappers/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/wrappers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..723e35c52a29cfd4b228ebeda83ee117a726bfcf --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/wrappers/__init__.py @@ -0,0 +1,4 @@ +from .default_wrapper import DefaultWrapper +from .rgbd_full_res_wrapper import RGBDFullResWrapper + +__all__ = ["DefaultWrapper", "RGBDFullResWrapper"] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/wrappers/default_wrapper.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/wrappers/default_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..31ab3803c967b28e1d68e0f0cf5fe37184382495 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/wrappers/default_wrapper.py @@ -0,0 +1,31 @@ +from omnigibson.envs import Environment, EnvironmentWrapper +from omnigibson.eval.utils.eval_utils import EVAL_CAMERA_ROLES + +EVAL_LOW_RES = (224, 224) # (H, W) + + +class DefaultWrapper(EnvironmentWrapper): + """ + Default eval wrapper: low-resolution (224x224) RGB observations. + + Camera resolution and modalities are declared via :meth:`camera_spec` and baked into the robot + config at env CREATION by the BatchedEvaluator + (see ``omnigibson.eval.evaluator.BatchedEvaluator.load_env``), + not changed at runtime. This is required because in multi-env mode robot cameras are batched into + a single ``TiledVisionSensor`` whose resolution is fixed at creation, so a post-hoc per-sensor + resize would be silently ignored. + + Args: + env (og.Environment): The environment to wrap. + """ + + @classmethod + def camera_spec(cls) -> dict: + """Returns {"modalities": [...], "resolution": {camera_role: (H, W)}} for this eval profile.""" + return { + "modalities": ["rgb"], + "resolution": {role: EVAL_LOW_RES for role in EVAL_CAMERA_ROLES}, + } + + def __init__(self, env: Environment): + super().__init__(env=env) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/wrappers/rgbd_full_res_wrapper.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/wrappers/rgbd_full_res_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec9e08a1307147db9ff7f6a7ba56d9e09d9adf5 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/eval/wrappers/rgbd_full_res_wrapper.py @@ -0,0 +1,25 @@ +from omnigibson.envs import Environment, EnvironmentWrapper +from omnigibson.eval.utils.eval_utils import EVAL_CAMERA_ROLES, HEAD_RESOLUTION, WRIST_RESOLUTION + + +class RGBDFullResWrapper(EnvironmentWrapper): + """ + Eval wrapper: full-resolution RGB-D observations (head at HEAD_RESOLUTION, wrists at + WRIST_RESOLUTION) matching the data-collection cameras, plus a depth modality. + + As with :class:`~omnigibson.eval.wrappers.default_wrapper.DefaultWrapper`, camera resolution and + modalities are declared via :meth:`camera_spec` and baked into the robot config at env CREATION + (multi-env tiled rendering fixes resolution at creation, so a runtime resize would not apply). + + Args: + env (og.Environment): The environment to wrap. + """ + + @classmethod + def camera_spec(cls) -> dict: + """Returns {"modalities": [...], "resolution": {camera_role: (H, W)}} for this eval profile.""" + resolution = {role: (HEAD_RESOLUTION if role == "head" else WRIST_RESOLUTION) for role in EVAL_CAMERA_ROLES} + return {"modalities": ["rgb", "depth_linear"], "resolution": resolution} + + def __init__(self, env: Environment): + super().__init__(env=env) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/environments/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/environments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/environments/behavior_env_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/environments/behavior_env_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..b11d11c6a8043a5b30c668086d9fee162c56d085 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/environments/behavior_env_demo.py @@ -0,0 +1,66 @@ +import os + +import yaml + +import omnigibson as og +from omnigibson.macros import gm +from omnigibson.utils.ui_utils import choose_from_options + +# Make sure object states are enabled +gm.ENABLE_OBJECT_STATES = True +gm.USE_GPU_DYNAMICS = False + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Generates a BEHAVIOR Task environment in an online fashion. + + It steps the environment 100 times with random actions sampled from the action space, + using the Gym interface, resetting it 10 times. + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Ask the user whether they want online object sampling or not + sampling_options = { + False: "Use a pre-sampled cached BEHAVIOR activity scene", + True: "Sample the BEHAVIOR activity in an online fashion", + } + should_sample = choose_from_options( + options=sampling_options, name="online object sampling", random_selection=random_selection + ) + + # Load the pre-selected configuration and set the online_sampling flag + config_filename = os.path.join(og.example_config_path, "r1pro_behavior.yaml") + cfg = yaml.load(open(config_filename, "r"), Loader=yaml.FullLoader) + cfg["task"]["online_object_sampling"] = should_sample + cfg["task"]["use_presampled_robot_pose"] = not should_sample + + # Load the environment + env = og.Environment(configs=cfg) + + # Move camera to a good position + og.sim.viewer_camera.set_position_orientation( + position=[1.6, 6.15, 1.5], orientation=[-0.2322, 0.5895, 0.7199, -0.2835] + ) + + # Allow user to move camera more easily + og.sim.enable_viewer_camera_teleoperation() + + # Run a simple loop and reset periodically + max_iterations = 10 if not short_exec else 1 + for j in range(max_iterations): + og.log.info("Resetting environment") + env.reset() + for i in range(100): + action = env.scene.robots[0].action_space.sample() + state, reward, terminated, truncated, info = env.step(action * 0.1) + if terminated or truncated: + og.log.info("Episode finished after {} timesteps".format(i + 1)) + break + + # Always close the environment at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/environments/navigation_env_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/environments/navigation_env_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..f7b4c2568f71f37eb3ae1183684680f3be9f4925 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/environments/navigation_env_demo.py @@ -0,0 +1,55 @@ +import os + +import yaml + +import omnigibson as og +from omnigibson.utils.ui_utils import choose_from_options + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Prompts the user to select a type of scene and loads a turtlebot into it, generating a Point-Goal navigation + task within the environment. + + It steps the environment 100 times with random actions sampled from the action space, + using the Gym interface, resetting it 10 times. + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Load the config + config_filename = os.path.join(og.example_config_path, "turtlebot_nav.yaml") + config = yaml.load(open(config_filename, "r"), Loader=yaml.FullLoader) + + # check if we want to quick load or full load the scene + load_options = { + "Quick": "Only load the building assets (i.e.: the floors, walls, ceilings)", + "Full": "Load all interactive objects in the scene", + } + load_mode = choose_from_options(options=load_options, name="load mode", random_selection=random_selection) + if load_mode == "Quick": + config["scene"]["load_object_categories"] = ["floors", "walls", "ceilings"] + + # Load the environment + env = og.Environment(configs=config) + + # Allow user to move camera more easily + og.sim.enable_viewer_camera_teleoperation() + + # Run a simple loop and reset periodically + max_iterations = 10 if not short_exec else 1 + for j in range(max_iterations): + og.log.info("Resetting environment") + env.reset() + for i in range(100): + action = env.action_space.sample() + state, reward, terminated, truncated, info = env.step(action) + if terminated or truncated: + og.log.info("Episode finished after {} timesteps".format(i + 1)) + break + + # Always close the environment at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/environments/vector_env_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/environments/vector_env_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..7f3dc2d10fe8645def2957c26e6959b2f3e52d10 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/environments/vector_env_demo.py @@ -0,0 +1,49 @@ +import os +import time + +import torch as th +import yaml + +import omnigibson as og +from omnigibson.macros import gm + +NUM_STEPS = 100 + + +def main(random_selection=False, headless=False, short_exec=False): + # Load the config + gm.RENDER_VIEWER_CAMERA = False + gm.USE_GPU_DYNAMICS = False + gm.ENABLE_TRANSITION_RULES = False + gm.ENABLE_OBJECT_STATES = False + + config_filename = os.path.join(og.example_config_path, "franka_vector_env.yaml") + config = yaml.load(open(config_filename, "r"), Loader=yaml.FullLoader) + + config["scene"]["load_object_categories"] = ["floors", "walls", "coffee_table"] + config["env"] = {"num_envs": 5} + + # Load the environment + env = og.Environment(configs=config) + + max_iterations = 10 if not short_exec else 1 + for _ in range(max_iterations): + start_time = time.time() + for _ in range(NUM_STEPS): + actions = th.stack( + [th.from_numpy(env.scenes[i].robots[0].action_space.sample()).float() for i in range(env.num_envs)] + ) + env.step(actions) + + step_time = time.time() - start_time + fps = NUM_STEPS / step_time + effective_fps = NUM_STEPS * env.num_envs / step_time + print("fps", fps) + print("effective fps", effective_fps) + + # Always close the environment at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/learning/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/learning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/learning/navigation_policy_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/learning/navigation_policy_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..a2d38e607a44c616429a42495621fc8c5dc92446 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/learning/navigation_policy_demo.py @@ -0,0 +1,185 @@ +""" +Example training code using stable-baselines3 PPO for one BEHAVIOR activity. +Note that due to the sparsity of the reward, this training code will not converge and achieve task success. +This only serves as a starting point that users can further build upon. +""" + +import argparse +import os +import time + +import yaml + +import omnigibson as og +from omnigibson import example_config_path +from omnigibson.macros import gm +from omnigibson.utils.python_utils import meets_minimum_version + +try: + import gymnasium as gym + import torch as th + import torch.nn as nn + from stable_baselines3 import PPO + from stable_baselines3.common.callbacks import CallbackList, CheckpointCallback, EvalCallback + from stable_baselines3.common.evaluation import evaluate_policy + from stable_baselines3.common.torch_layers import BaseFeaturesExtractor + from stable_baselines3.common.utils import set_random_seed + +except ModuleNotFoundError: + og.log.error( + "stable-baselines3 is not installed. " + "Run the following command to install stable-baselines3:\n" + "pip install stable-baselines3[extra]\n" + ) + exit(1) + +assert meets_minimum_version(gym.__version__, "0.28.1"), "Please install/update gymnasium to version >= 0.28.1" + +# We don't need object states nor transitions rules, so we disable them now +gm.ENABLE_OBJECT_STATES = False +gm.ENABLE_TRANSITION_RULES = False + + +class CustomCombinedExtractor(BaseFeaturesExtractor): + def __init__(self, observation_space: gym.spaces.Dict): + # We do not know features-dim here before going over all the items, + # so put something dummy for now. PyTorch requires calling + super().__init__(observation_space, features_dim=1) + extractors = {} + self.step_index = 0 + self.img_save_dir = "img_save_dir" + os.makedirs(self.img_save_dir, exist_ok=True) + total_concat_size = 0 + feature_size = 128 + for key, subspace in observation_space.spaces.items(): + # For now, only keep RGB observations + if "rgb" in key: + og.log.info(f"obs {key} shape: {subspace.shape}") + n_input_channels = subspace.shape[0] # channel first + cnn = nn.Sequential( + nn.Conv2d(n_input_channels, 4, kernel_size=8, stride=4, padding=0), + nn.ReLU(), + nn.MaxPool2d(2), + nn.Conv2d(4, 8, kernel_size=4, stride=2, padding=0), + nn.ReLU(), + nn.MaxPool2d(2), + nn.Conv2d(8, 4, kernel_size=3, stride=1, padding=0), + nn.ReLU(), + nn.Flatten(), + ) + test_tensor = th.zeros(subspace.shape) + with th.no_grad(): + n_flatten = cnn(test_tensor[None]).shape[1] + fc = nn.Sequential(nn.Linear(n_flatten, feature_size), nn.ReLU()) + extractors[key] = nn.Sequential(cnn, fc) + total_concat_size += feature_size + self.extractors = nn.ModuleDict(extractors) + + # Update the features dim manually + self._features_dim = total_concat_size + + def forward(self, observations) -> th.Tensor: + encoded_tensor_list = [] + self.step_index += 1 + + # self.extractors contain nn.Modules that do all the processing. + for key, extractor in self.extractors.items(): + encoded_tensor_list.append(extractor(observations[key])) + + feature = th.cat(encoded_tensor_list, dim=1) + return feature + + +def main(): + # Parse args + parser = argparse.ArgumentParser(description="Train or evaluate a PPO agent in BEHAVIOR") + + parser.add_argument( + "--checkpoint", + type=str, + default=None, + help="Absolute path to desired PPO checkpoint to load for evaluation", + ) + + parser.add_argument( + "--eval", + action="store_true", + help="If set, will evaluate the PPO agent found from --checkpoint", + ) + + args = parser.parse_args() + tensorboard_log_dir = os.path.join("log_dir", time.strftime("%Y%m%d-%H%M%S")) + os.makedirs(tensorboard_log_dir, exist_ok=True) + prefix = "" + seed = 0 + + # Load config + with open(f"{example_config_path}/turtlebot_nav.yaml", "r") as f: + cfg = yaml.load(f, Loader=yaml.FullLoader) + + # Make sure flattened obs and action space is used + cfg["env"]["flatten_action_space"] = True + cfg["env"]["flatten_obs_space"] = True + + # Only use RGB obs + cfg["robots"][0]["obs_modalities"] = ["rgb"] + + # If we're not eval, turn off the start / goal markers so the agent doesn't see them + if not args.eval: + cfg["task"]["visualize_goal"] = False + + env = og.Environment(configs=cfg) + + # If we're evaluating, hide the ceilings and enable camera teleoperation so the user can easily + # visualize the rollouts dynamically + if args.eval: + ceiling = env.scene.object_registry("name", "ceilings") + ceiling.visible = False + og.sim.enable_viewer_camera_teleoperation() + + # Set the set + set_random_seed(seed) + env.reset() + + policy_kwargs = dict( + features_extractor_class=CustomCombinedExtractor, + ) + + os.makedirs(tensorboard_log_dir, exist_ok=True) + + if args.eval: + assert args.checkpoint is not None, "If evaluating a PPO policy, @checkpoint argument must be specified!" + model = PPO.load(args.checkpoint) + og.log.info("Starting evaluation...") + mean_reward, std_reward = evaluate_policy(model, env, n_eval_episodes=50) + og.log.info("Finished evaluation!") + og.log.info(f"Mean reward: {mean_reward} +/- {std_reward:.2f}") + + else: + model = PPO( + "MultiInputPolicy", + env, + verbose=1, + tensorboard_log=tensorboard_log_dir, + policy_kwargs=policy_kwargs, + n_steps=20 * 10, + batch_size=8, + device="cuda", + ) + checkpoint_callback = CheckpointCallback(save_freq=1000, save_path=tensorboard_log_dir, name_prefix=prefix) + eval_callback = EvalCallback(eval_env=env, eval_freq=1000, n_eval_episodes=20) + callback = CallbackList([checkpoint_callback, eval_callback]) + + og.log.debug(model.policy) + og.log.info(f"model: {model}") + + og.log.info("Starting training...") + model.learn( + total_timesteps=10000000, + callback=callback, + ) + og.log.info("Finished training!") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/attachment_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/attachment_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..1f056a1957a15f75c794d28ae2a62c1848e135a0 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/attachment_demo.py @@ -0,0 +1,97 @@ +import math + +import torch as th +import yaml + +import omnigibson as og +from omnigibson.macros import gm, macros +import omnigibson.utils.transform_utils as T + +# Make sure object states are enabled +gm.ENABLE_OBJECT_STATES = True + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Demo of attachment of different parts of a bookcase + """ + cfg = yaml.load(open(f"{og.example_config_path}/default_cfg.yaml", "r"), Loader=yaml.FullLoader) + # Add objects that we want to create + obj_cfgs = [] + + base_z = 0.2 + + obj_cfgs.append( + dict( + type="DatasetObject", + name="bookcase_back_panel", + category="bookcase_back", + model="gjsnrt", + position=[0, 0, 0.01], + abilities={"attachable": {}}, + ) + ) + + ys = [-0.93, -0.61, -0.29, 0.03, 0.35, 0.68] + for i in range(6): + obj_cfgs.append( + dict( + type="DatasetObject", + name=f"bookcase_shelf_{i}", + category="bookcase_shelf", + model="ymtnqa", + position=[0, ys[i], base_z], + orientation=T.euler2quat(th.tensor([0.0, -math.pi / 2.0, math.pi / 2.0])), + abilities={"attachable": {}}, + ) + ) + + obj_cfgs.append( + dict( + type="DatasetObject", + name="bookcase_top", + category="bookcase_top", + model="pfiole", + position=[0, 1.0, base_z], + orientation=T.euler2quat(th.tensor([-math.pi / 2.0, math.pi / 2.0, -math.pi])), + abilities={"attachable": {}}, + ) + ) + + cfg["objects"] = obj_cfgs + + env = og.Environment(configs=cfg) + + # Lower the break force to make it easier to break apart the bookcase + with macros.unlocked(): + macros.object_states.attached_to.DEFAULT_BREAK_FORCE = 500.0 + macros.object_states.attached_to.DEFAULT_BREAK_TORQUE = 500.0 + + # Set viewer camera pose + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([-1.689292, -2.11718198, 0.93332228]), + orientation=th.tensor([0.57687967, -0.22995655, -0.29022759, 0.72807814]), + ) + + for _ in range(10): + env.step([]) + + if not headless: + input( + "\n\nbookcase parts fall to their correct poses and get automatically attached to the back panel.\n" + "You can try to drag (Shift + Left-CLICK + Drag) parts of the bookcase to break it apart (you may need to zoom out and drag with a larger force).\n" + "Press [ENTER] to continue.\n" + ) + + steps = 0 + max_steps = -1 if not short_exec else 1000 + + while steps != max_steps: + env.step([]) + steps += 1 + + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/dicing_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/dicing_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..6af8fbd6201d364743b88a3c6af5cdd8a5e75d97 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/dicing_demo.py @@ -0,0 +1,113 @@ +import math + +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.macros import gm + +# Make sure object states, GPU dynamics, and transition rules are enabled +gm.ENABLE_OBJECT_STATES = True +gm.USE_GPU_DYNAMICS = True +gm.ENABLE_TRANSITION_RULES = True + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Demo of dicing an apple into apple dices + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Create the scene config to load -- empty scene with table, knife, and apple + table_cfg = dict( + type="DatasetObject", + name="table", + category="breakfast_table", + model="rjgmmy", + bounding_box=[1.36, 1.08, 0.84], + position=[0, 0, 0.58], + ) + + apple_cfg = dict( + type="DatasetObject", + name="apple", + category="apple", + model="agveuv", + bounding_box=[0.098, 0.098, 0.115], + position=[0.085, 0, 0.92], + abilities={"diceable": {}}, + ) + + knife_cfg = dict( + type="DatasetObject", + name="knife", + category="table_knife", + model="lrdmpf", + bounding_box=[0.401, 0.044, 0.009], + position=[0, 0, 20.0], + ) + + light0_cfg = dict( + type="LightObject", + name="light0", + light_type="Sphere", + radius=0.01, + intensity=1e7, + position=[1.217, -0.848, 1.388], + ) + + light1_cfg = dict( + type="LightObject", + name="light1", + light_type="Sphere", + radius=0.01, + intensity=1e7, + position=[-1.217, 0.848, 1.388], + ) + + cfg = { + "scene": { + "type": "Scene", + }, + "objects": [table_cfg, apple_cfg, knife_cfg, light0_cfg, light1_cfg], + } + + # Create the environment + env = og.Environment(configs=cfg) + + # Grab reference to apple and knife + apple = env.scene.object_registry("name", "apple") + knife = env.scene.object_registry("name", "knife") + + # Update the simulator's viewer camera's pose so it points towards the table + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([0.544888, -0.412084, 1.11569]), + orientation=th.tensor([0.54757518, 0.27792802, 0.35721896, 0.70378409]), + ) + + # Let apple settle + for _ in range(50): + env.step([]) + + knife.keep_still() + knife.set_position_orientation( + position=apple.get_position_orientation()[0] + th.tensor([-0.15, 0.0, 0.2]), + orientation=T.euler2quat(th.tensor([-math.pi / 2, 0, 0])), + ) + + if not short_exec: + input("The knife will fall on the apple and dice it. Press [ENTER] to continue.") + + # Step simulation for a bit so that apple is diced + for _ in range(1000): + env.step([]) + + if not short_exec: + input("Apple has been diced! Press [ENTER] to terminate the demo.") + + # Always close simulator at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/heated_state_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/heated_state_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..cf74b274832134e3ce73fd2d765ba6014d802e80 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/heated_state_demo.py @@ -0,0 +1,107 @@ +import torch as th + +import omnigibson as og +from omnigibson import object_states +from omnigibson.macros import gm + +# Make sure object states are enabled +gm.ENABLE_OBJECT_STATES = True + + +def main(random_selection=False, headless=False, short_exec=False): + # Define object configurations for objects to load -- we want to load a light and three bowls + obj_configs = [] + + obj_configs.append( + dict( + type="LightObject", + light_type="Sphere", + name="light", + radius=0.01, + intensity=1e8, + position=[-2.0, -2.0, 1.0], + ) + ) + + for i, (scale, x) in enumerate(zip([0.5, 1.0, 2.0], [-0.6, 0, 0.8])): + obj_configs.append( + dict( + type="DatasetObject", + name=f"bowl{i}", + category="bowl", + model="ajzltc", + bounding_box=th.tensor([0.329, 0.293, 0.168]) * scale, + abilities={"heatable": {}}, + position=[x, 0, 0.2], + ) + ) + + # Create the scene config to load -- empty scene with light object and bowls + cfg = { + "scene": { + "type": "Scene", + }, + "objects": obj_configs, + } + + # Create the environment + env = og.Environment(configs=cfg) + + # Set camera to appropriate viewing pose + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([0.182103, -2.07295, 0.14017]), + orientation=th.tensor([0.77787037, 0.00267566, 0.00216149, 0.62841535]), + ) + + # Dim the skybox so we can see the bowls' steam effectively + og.sim.skybox.intensity = 100.0 + + # Grab reference to objects of relevance + objs = list(env.scene.object_registry("category", "bowl")) + + def report_states(objs): + for obj in objs: + print("=" * 20) + print("object:", obj.name) + print("temperature:", obj.states[object_states.Temperature].get_value()) + print("obj is heated:", obj.states[object_states.Heated].get_value()) + + # Report default states + print("==== Initial state ====") + report_states(objs) + + if not short_exec: + # Notify user that we're about to heat the object + input("Objects will be heated, and steam will slowly rise. Press ENTER to continue.") + + # Heated. + for obj in objs: + obj.states[object_states.Temperature].set_value(50) + env.step(th.empty(0)) + report_states(objs) + + # Take a look at the steam effect. + # After a while, objects will be below the Steam temperature threshold. + print("==== Objects are now heated... ====") + print() + max_iterations = 2000 if not short_exec else 100 + for _ in range(max_iterations): + env.step(th.empty(0)) + # Also print temperatures + temps = [f"{obj.states[object_states.Temperature].get_value():>7.2f}" for obj in objs] + print("obj temps:", *temps, end="\r") + print() + + # Objects are not heated anymore. + print("==== Objects are no longer heated... ====") + report_states(objs) + + if not short_exec: + # Close environment at the end + input("Demo completed. Press ENTER to shutdown environment.") + + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/object_state_texture_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/object_state_texture_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..979b125daba6fc3092817df9ba8ede0c03460cda --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/object_state_texture_demo.py @@ -0,0 +1,148 @@ +import torch as th + +import omnigibson as og +from omnigibson import object_states +from omnigibson.macros import gm, macros +from omnigibson.utils.constants import ParticleModifyMethod + +# Make sure object states are enabled, we're using GPU dynamics, and HQ rendering is enabled +gm.ENABLE_OBJECT_STATES = True +gm.USE_GPU_DYNAMICS = True +gm.ENABLE_HQ_RENDERING = True + + +def main(random_selection=False, headless=False, short_exec=False): + # Create the scene config to load -- empty scene plus a steak + cfg = { + "env": { + "action_frequency": 60, + "rendering_frequency": 60, # for HQ rendering + }, + "scene": { + "type": "Scene", + "floor_plane_visible": True, + }, + "objects": [ + { + "type": "DatasetObject", + "name": "steak", + "category": "steak", + "model": "ppykkp", + "abilities": { + "freezable": {}, + "cookable": {}, + "burnable": {}, + "saturable": {}, + "particleRemover": { + "method": ParticleModifyMethod.ADJACENCY, + "conditions": { + # For a specific particle system, this specifies what conditions are required in order for the + # particle applier / remover to apply / remover particles associated with that system + # The list should contain functions with signature condition() --> bool, + # where True means the condition is satisfied + # In this case, we only allow our steak to absorb water, with no conditions needed. + # This is needed for the Saturated ("saturable") state so that we can modify the texture + # according to the water. + # NOTE: This will only change color if gm.ENABLE_HQ_RENDERING and gm.USE_GPU_DYNAMICS is + # enabled! + "water": [], + }, + }, + }, + "position": [0, 0, 0.59], + "fixed_base": True, + }, + ], + } + + # Create the environment + env = og.Environment(configs=cfg) + + # Set camera to appropriate viewing pose + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([0.2425, 0.0894, 0.7872]), + orientation=th.tensor([0.2494, 0.3583, 0.7384, 0.5140]), + ) + + # Grab reference to object of interest + obj = env.scene.object_registry("name", "steak") + + # Make sure all the appropriate states are in the object + assert object_states.Frozen in obj.states + assert object_states.Cooked in obj.states + assert object_states.Burnt in obj.states + assert object_states.Saturated in obj.states + + def report_states(): + # Make sure states are propagated before printing + for i in range(5): + env.step(th.empty(0)) + + print("=" * 20) + print("temperature:", obj.states[object_states.Temperature].get_value()) + print("obj is frozen:", obj.states[object_states.Frozen].get_value()) + print("obj is cooked:", obj.states[object_states.Cooked].get_value()) + print("obj is burnt:", obj.states[object_states.Burnt].get_value()) + print("obj is soaked:", obj.states[object_states.Saturated].get_value(env.scene.get_system("water"))) + + # Report default states + print("==== Initial state ====") + report_states() + + # Notify user that we're about to freeze the object, and then freeze the object + if not short_exec: + input("\nObject will be frozen. Press ENTER to continue.") + obj.states[object_states.Temperature].set_value(-50) + for _ in range(50): + og.sim.render() + report_states() + + # Notify user that we're about to cook the object, and then cook the object + if not short_exec: + input("\nObject will be cooked. Press ENTER to continue.") + obj.states[object_states.Temperature].set_value(100) + for _ in range(50): + og.sim.render() + report_states() + + # Notify user that we're about to burn the object, and then burn the object + if not short_exec: + input("\nObject will be burned. Press ENTER to continue.") + obj.states[object_states.Temperature].set_value(250) + for _ in range(50): + og.sim.render() + report_states() + + # Notify user that we're about to reset the object to its default state, and then reset state + if not short_exec: + input("\nObject will be reset to default state. Press ENTER to continue.") + obj.states[object_states.Temperature].set_value(macros.object_states.temperature.DEFAULT_TEMPERATURE) + obj.states[object_states.MaxTemperature].set_value(macros.object_states.temperature.DEFAULT_TEMPERATURE) + for _ in range(50): + og.sim.render() + report_states() + + # Notify user that we're about to soak the object, and then soak the object + if not short_exec: + input("\nObject will be saturated with water. Press ENTER to continue.") + obj.states[object_states.Saturated].set_value(env.scene.get_system("water"), True) + for _ in range(50): + og.sim.render() + report_states() + + # Notify user that we're about to unsoak the object, and then unsoak the object + if not short_exec: + input("\nObject will be unsaturated with water. Press ENTER to continue.") + obj.states[object_states.Saturated].set_value(env.scene.get_system("water"), False) + for _ in range(50): + og.sim.render() + report_states() + + # Close environment at the end + if not short_exec: + input("Demo completed. Press ENTER to shutdown environment.") + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/onfire_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/onfire_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3afb71c46f25cc622a14bb5656893d761c2a1f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/onfire_demo.py @@ -0,0 +1,113 @@ +import torch as th + +import omnigibson as og +from omnigibson import object_states +from omnigibson.macros import gm + +# Make sure object states are enabled +gm.ENABLE_OBJECT_STATES = True + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Demo of on fire state. + Loads a stove (toggled on), and two apples. + The first apple will be ignited by the stove first, then the second apple will be ignited by the first apple. + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Define specific objects we want to load in with the scene directly + obj_configs = [] + + # Light + obj_configs.append( + dict( + type="LightObject", + light_type="Sphere", + name="light", + radius=0.01, + intensity=1e8, + position=[-2.0, -2.0, 1.0], + ) + ) + + # Stove + obj_configs.append( + dict( + type="DatasetObject", + name="stove", + category="stove", + model="ykretu", + position=[0, 0, 0.61], + ) + ) + + # 2 Apples + for i in range(2): + obj_configs.append( + dict( + type="DatasetObject", + name=f"apple{i}", + category="apple", + model="agveuv", + position=[-0.1 * i, -0.2, 1.0], + abilities={"flammable": {"ignition_temperature": 100, "distance_threshold": 0.5}}, + ) + ) + + # Create the scene config to load -- empty scene with desired objects + cfg = { + "scene": { + "type": "Scene", + }, + "objects": obj_configs, + } + + # Create the environment + env = og.Environment(configs=cfg) + + # Get reference to relevant objects + stove = env.scene.object_registry("name", "stove") + apples = list(env.scene.object_registry("category", "apple")) + + # Set camera to appropriate viewing pose + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([1.2299, -0.8270, 1.4666]), + orientation=th.tensor([0.4831, 0.2451, 0.3803, 0.7497]), + ) + + # Let objects settle + for _ in range(10): + env.step([]) + + # Turn on the stove + stove.states[object_states.ToggledOn].set_value(True) + + # The first apple will be affected by the stove + apples[0].set_position_orientation( + position=stove.states[object_states.HeatSourceOrSink].link.get_position_orientation()[0] + + th.tensor([0.11, 0, 0.1]) + ) + + # The second apple will NOT be affected by the stove, but will be affected by the first apple once it's on fire. + apples[1].set_position_orientation( + position=stove.states[object_states.HeatSourceOrSink].link.get_position_orientation()[0] + + th.tensor([0.32, 0, 0.1]) + ) + + steps = 0 + max_steps = -1 if not short_exec else 1000 + + # Main recording loop + while steps != max_steps: + env.step([]) + temps = [f"{apple.states[object_states.Temperature].get_value():>20.2f}" for apple in apples] + print(f"{'Apple temperature:':<20}", *temps, end="\r") + steps += 1 + + # Always close env at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/overlaid_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/overlaid_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..4dd451f353cce748672edfa219aa499979e89440 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/overlaid_demo.py @@ -0,0 +1,85 @@ +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.macros import gm +from omnigibson.object_states import Overlaid +from omnigibson.utils.constants import PrimType +from omnigibson.utils.ui_utils import KeyboardEventHandler + +# Make sure object states and GPU dynamics are enabled (GPU dynamics needed for cloth) +gm.ENABLE_OBJECT_STATES = True +gm.USE_GPU_DYNAMICS = True + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Demo of cloth objects that can be overlaid on rigid objects. + + Loads a carpet on top of a table. Initially Overlaid will be True because the carpet largely covers the table. + If you drag the carpet off the table or even just fold it into half, Overlaid will become False. + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Create the scene config to load -- empty scene + custom cloth object + custom rigid object + cfg = { + "scene": { + "type": "Scene", + }, + "objects": [ + { + "type": "DatasetObject", + "name": "carpet", + "category": "carpet", + "model": "vlccww", + "scale": 0.5, + "prim_type": PrimType.CLOTH, + "abilities": {"cloth": {}}, + "position": [0, 0, 1.0], + }, + { + "type": "DatasetObject", + "name": "breakfast_table", + "category": "breakfast_table", + "model": "rjgmmy", + "bounding_box": [1.36, 1.081, 0.84], + "prim_type": PrimType.RIGID, + "position": [0, 0, 0.58], + }, + ], + } + + # Create the environment + env = og.Environment(configs=cfg) + + KeyboardEventHandler.add_keyboard_callback( + key=lazy.carb.input.KeyboardInput.ESCAPE, + callback_fn=lambda: og.shutdown(), + ) + + # Grab object references + carpet = env.scene.object_registry("name", "carpet") + breakfast_table = env.scene.object_registry("name", "breakfast_table") + + # Set camera pose + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([0.88215526, -1.40086216, 2.00311063]), + orientation=th.tensor([0.42013364, 0.12342107, 0.25339685, 0.86258043]), + ) + + max_steps = 100 if short_exec else -1 + steps = 0 + + print("\nTry dragging cloth around with CTRL + Left-Click to see the Overlaid state change:\n") + + while steps != max_steps: + print(f"Overlaid {carpet.states[Overlaid].get_value(breakfast_table)} ", end="\r") + env.step([]) + steps += 1 + + # Shut down env at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/particle_applier_remover_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/particle_applier_remover_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..035fa397fb3626083638db0b63ab4a4ef9d03931 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/particle_applier_remover_demo.py @@ -0,0 +1,195 @@ +import torch as th + +import omnigibson as og +from omnigibson.macros import gm, macros +from omnigibson.object_states import Covered, ToggledOn +from omnigibson.utils.ui_utils import choose_from_options + +# Set macros for this example +macros.object_states.particle_modifier.VISUAL_PARTICLES_REMOVAL_LIMIT = 1000 +macros.object_states.particle_modifier.PHYSICAL_PARTICLES_REMOVAL_LIMIT = 8000 +macros.object_states.particle_modifier.MAX_VISUAL_PARTICLES_APPLIED_PER_STEP = 4 +macros.object_states.particle_modifier.MAX_PHYSICAL_PARTICLES_APPLIED_PER_STEP = 40 +macros.object_states.covered.MAX_VISUAL_PARTICLES = 300 + +# Make sure object states and GPU dynamics are enabled (GPU dynamics needed for fluids) +gm.ENABLE_OBJECT_STATES = True +gm.USE_GPU_DYNAMICS = True +gm.ENABLE_HQ_RENDERING = True + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Demo of ParticleApplier and ParticleRemover object states, which enable objects to either apply arbitrary + particles and remove arbitrary particles from the simulator, respectively. + + Loads an empty scene with a table, and starts clean to allow particles to be applied or pre-covers the table + with particles to be removed. The ParticleApplier / ParticleRemover state is applied to an imported cloth object + and allowed to interact with the table, applying / removing particles from the table. + + NOTE: The key difference between ParticleApplier/Removers and ParticleSource/Sinks is that Applier/Removers + requires contact (if using ParticleProjectionMethod.ADJACENCY) or overlap + (if using ParticleProjectionMethod.PROJECTION) in order to spawn / remove particles, and generally only spawn + particles at the contact points. ParticleSource/Sinks are special cases of ParticleApplier/Removers that + always use ParticleProjectionMethod.PROJECTION and always spawn / remove particles within their projection volume, + irregardless of overlap with other objects! + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Choose what configuration to load + modifier_type = choose_from_options( + options={ + "particleApplier": "Demo object's ability to apply particles in the simulator", + "particleRemover": "Demo object's ability to remove particles from the simulator", + }, + name="particle modifier type", + random_selection=random_selection, + ) + particle_types = ["salt", "water"] + particle_type = choose_from_options( + options={name: f"{name} particles will be applied or removed from the simulator" for name in particle_types}, + name="particle type", + random_selection=random_selection, + ) + + table_cfg = dict( + type="DatasetObject", + name="table", + category="breakfast_table", + model="kwmfdg", + bounding_box=[3.402, 1.745, 1.175], + position=[0, 0, 0.98], + ) + tool_cfg = dict( + type="DatasetObject", + name="tool", + visual_only=True, + position=[0, 0.3, 5.0], + ) + + if modifier_type == "particleRemover": + if particle_type == "salt": + # only ask this question if the modifier type is salt particleRemover + method_type = choose_from_options( + options={ + "Adjacency": "Close proximity to the object will be used to determine whether particles can be applied / removed", + "Projection": "A Cone or Cylinder shape protruding from the object will be used to determine whether particles can be applied / removed", + }, + name="modifier method type", + random_selection=random_selection, + ) + else: + # If the particle type is water, the remover is always adjacency type + method_type = "Adjacency" + if method_type == "Adjacency": + # use dishtowel to remove adjacent particles + tool_cfg["category"] = "dishtowel" + tool_cfg["model"] = "dtfspn" + tool_cfg["bounding_box"] = [0.34245, 0.46798, 0.07] + elif method_type == "Projection": + # use vacuum to remove projections particles + tool_cfg["category"] = "vacuum" + tool_cfg["model"] = "wikhik" + else: + # If the modifier type is particleApplier, the applier is always projection type + method_type = "Projection" + + if particle_type == "salt": + # use salt shaker to apply salt particles + tool_cfg["category"] = "salt_shaker" + tool_cfg["model"] = "iomwtn" + else: + # use water atomizer to apply water particles + tool_cfg["category"] = "water_atomizer" + tool_cfg["model"] = "lfarai" + + # Create the scene config to load -- empty scene with a light and table + cfg = { + "env": { + "action_frequency": 60, + "rendering_frequency": 60, # for HQ rendering + }, + "scene": { + "type": "Scene", + }, + "objects": [table_cfg, tool_cfg], + } + + # Sanity check inputs: Remover + Adjacency + Fluid will not work because we are using a visual_only + # object, so contacts will not be triggered with this object + + # Load the environment, then immediately stop the simulator since we need to add in the modifier object + env = og.Environment(configs=cfg) + og.sim.stop() + + # Grab references to table and tool + table = env.scene.object_registry("name", "table") + tool = env.scene.object_registry("name", "tool") + + # Set the viewer camera appropriately + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([-1.61340969, -1.79803028, 2.53167412]), + orientation=th.tensor([0.46291845, -0.12381886, -0.22679218, 0.84790371]), + ) + + # Play the simulator and take some environment steps to let the objects settle + og.sim.play() + for _ in range(25): + env.step(th.empty(0)) + + # If we're removing particles, set the table's covered state to be True + if modifier_type == "particleRemover": + table.states[Covered].set_value(env.scene.get_system(particle_type), True) + # Take a few steps to let particles settle + for _ in range(25): + env.step(th.empty(0)) + + # If the particle remover/applier is projection type, set the turn on shaker + if method_type == "Projection": + tool.states[ToggledOn].set_value(True) + + # Enable camera teleoperation for convenience + og.sim.enable_viewer_camera_teleoperation() + + tool.keep_still() + + # Set the modifier object to be in position to modify particles + if modifier_type == "particleRemover" and method_type == "Projection": + tool.set_position_orientation( + position=[0, 0.3, 1.47], + orientation=[0, 0, 0, 1.0], + ) + elif modifier_type == "particleRemover" and method_type == "Adjacency": + tool.set_position_orientation( + position=[0, 0.3, 1.175], + orientation=[0, 0, 0, 1.0], + ) + elif modifier_type == "particleApplier" and particle_type == "water": + tool.set_position_orientation( + position=[0, 0.3, 1.4], + orientation=[0.3827, 0, 0, 0.9239], + ) + else: + tool.set_position_orientation( + position=[0, 0.3, 1.5], + orientation=[0.0, 0.0, 0.0, 1.0], + ) + + # Move object in square around table + deltas = [ + [130, th.tensor([-0.01, 0, 0])], + [60, th.tensor([0, -0.01, 0])], + [130, th.tensor([0.01, 0, 0])], + [60, th.tensor([0, 0.01, 0])], + ] + for t, delta in deltas: + for _ in range(t): + tool.set_position_orientation(position=tool.get_position_orientation()[0] + delta) + env.step(th.empty(0)) + + # Always shut down environment at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/sample_kinematics_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/sample_kinematics_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..6f25bacc9334951b66e476eed73e36953f88454e --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/sample_kinematics_demo.py @@ -0,0 +1,193 @@ +import math + +import torch as th + +import omnigibson as og +from omnigibson import object_states +from omnigibson.macros import gm +import omnigibson.utils.transform_utils as T + +# Make sure object states are enabled +gm.ENABLE_OBJECT_STATES = True + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Demo to use the raycasting-based sampler to load objects onTop and/or inside another + Loads a cabinet, a microwave open on top of it, and two plates with apples on top, one inside and one on top of the cabinet + Then loads a bookcase and cracker boxes inside of it + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Create the scene config to load -- empty scene + cfg = { + "scene": { + "type": "Scene", + }, + } + + # Define objects we want to sample at runtime + microwave_cfg = dict( + type="DatasetObject", + name="microwave", + category="microwave", + model="hjjxmi", + ) + + cabinet_cfg = dict( + type="DatasetObject", + name="cabinet", + category="bottom_cabinet", + model="songes", + ) + + plate_cfgs = [ + dict( + type="DatasetObject", + name=f"plate{i}", + category="plate", + model="iawoof", + scale=0.6, + # bounding_box=th.tensor([0.20, 0.20, 0.02]), + ) + for i in range(2) + ] + + apple_cfgs = [ + dict( + type="DatasetObject", + name=f"apple{i}", + category="apple", + model="agveuv", + ) + for i in range(2) + ] + + bookcase_cfg = dict( + type="DatasetObject", + name="bookcase", + category="bookcase", + model="gsksby", + ) + + box_cfgs = [ + dict( + type="DatasetObject", + name=f"box{i}", + category="box_of_crackers", + model="cmdigf", + ) + for i in range(5) + ] + + # Compose objects cfg + objects_cfg = [ + microwave_cfg, + cabinet_cfg, + *plate_cfgs, + *apple_cfgs, + bookcase_cfg, + *box_cfgs, + ] + + # Update their spawn positions so they don't collide immediately + for i, obj_cfg in enumerate(objects_cfg): + obj_cfg["position"] = [100 + i, 100 + i, 100 + i] + + cfg["objects"] = objects_cfg + + # Create the environment + env = og.Environment(configs=cfg) + env.step([]) + + # Sample microwave and boxes + sample_boxes_on_bookcase(env) + sample_microwave_plates_apples(env) + + max_steps = 100 if short_exec else -1 + step = 0 + while step != max_steps: + env.step(th.empty(0)) + step += 1 + + # Always close environment at the end + og.shutdown() + + +def sample_microwave_plates_apples(env): + microwave = env.scene.object_registry("name", "microwave") + cabinet = env.scene.object_registry("name", "cabinet") + plates = list(env.scene.object_registry("category", "plate")) + apples = list(env.scene.object_registry("category", "apple")) + + # Place the cabinet at a pre-determined location on the floor + og.log.info("Placing cabinet on the floor...") + env.step(th.empty(0)) + offset = cabinet.get_position_orientation()[0][2] - cabinet.aabb_center[2] + cabinet.set_position_orientation( + position=th.tensor([0.5, 0, cabinet.aabb_extent[2] / 2]) + offset, + orientation=T.euler2quat(th.tensor([0.0, 0.0, -math.pi / 2.0])), + ) + env.step(th.empty(0)) + + # Set microwave on top of the cabinet, open it, and step 100 times + og.log.info("Placing microwave OnTop of the cabinet...") + assert microwave.states[object_states.OnTop].set_value(cabinet, True) + assert microwave.states[object_states.Open].set_value(True) + og.log.info("Microwave placed.") + for _ in range(50): + env.step(th.empty(0)) + + og.log.info("Placing plates") + n_apples_per_plate = int(len(apples) / len(plates)) + for i, plate in enumerate(plates): + # Put the 1st plate in the microwave + if i == 0: + og.log.info(f"Placing plate {i} Inside the microwave...") + assert plate.states[object_states.Inside].set_value(microwave, True) + else: + og.log.info(f"Placing plate {i} OnTop the microwave...") + assert plate.states[object_states.OnTop].set_value(microwave, True) + + og.log.info(f"Plate {i} placed.") + for _ in range(50): + env.step(th.empty(0)) + + og.log.info(f"Placing {n_apples_per_plate} apples OnTop of the plate...") + for j in range(n_apples_per_plate): + apple_idx = i * n_apples_per_plate + j + apple = apples[apple_idx] + assert apple.states[object_states.OnTop].set_value(plate, True) + og.log.info(f"Apple {apple_idx} placed.") + for _ in range(50): + env.step(th.empty(0)) + + +def sample_boxes_on_bookcase(env): + bookcase = env.scene.object_registry("name", "bookcase") + boxes = list(env.scene.object_registry("category", "box_of_crackers")) + # Place the bookcase at a pre-determined location on the floor + og.log.info("Placing bookcase on the floor...") + env.step(th.empty(0)) + offset = bookcase.get_position_orientation()[0][2] - bookcase.aabb_center[2] + bookcase.set_position_orientation( + position=th.tensor([-0.5, 0, bookcase.aabb_extent[2] / 2]) + offset, + orientation=T.euler2quat(th.tensor([0.0, 0.0, -math.pi / 2.0])), + ) + env.step(th.empty(0)) # One step is needed for the object to be fully initialized + + og.log.info("bookcase placed.") + for _ in range(50): + env.step(th.empty(0)) + + og.log.info("Placing boxes...") + for i, box in enumerate(boxes): + box.states[object_states.Inside].set_value(bookcase, True) + og.log.info(f"Box {i} placed.") + + for _ in range(50): + env.step(th.empty(0)) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/slicing_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/slicing_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..2f8be01d45f6dd39f52bb5880169f7175e077af4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/slicing_demo.py @@ -0,0 +1,110 @@ +import math + +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.macros import gm + +# Make sure object states and transition rules are enabled +gm.ENABLE_OBJECT_STATES = True +gm.ENABLE_TRANSITION_RULES = True + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Demo of slicing an apple into two apple slices + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Create the scene config to load -- empty scene with table, knife, and apple + table_cfg = dict( + type="DatasetObject", + name="table", + category="breakfast_table", + model="rjgmmy", + bounding_box=[1.36, 1.081, 0.84], + position=[0, 0, 0.58], + ) + + apple_cfg = dict( + type="DatasetObject", + name="apple", + category="apple", + model="agveuv", + position=[0.085, 0, 0.92], + ) + + knife_cfg = dict( + type="DatasetObject", + name="knife", + category="table_knife", + model="lrdmpf", + bounding_box=[0.401, 0.044, 0.009], + position=[0, 0, 20.0], + ) + + light0_cfg = dict( + type="LightObject", + name="light0", + light_type="Sphere", + radius=0.01, + intensity=4000.0, + position=[1.217, -0.848, 1.388], + ) + + light1_cfg = dict( + type="LightObject", + name="light1", + light_type="Sphere", + radius=0.01, + intensity=4000.0, + position=[-1.217, 0.848, 1.388], + ) + + cfg = { + "scene": { + "type": "Scene", + }, + "objects": [table_cfg, apple_cfg, knife_cfg, light0_cfg, light1_cfg], + } + + # Create the environment + env = og.Environment(configs=cfg) + + # Grab reference to apple and knife + apple = env.scene.object_registry("name", "apple") + knife = env.scene.object_registry("name", "knife") + + # Update the simulator's viewer camera's pose so it points towards the table + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([0.544888, -0.412084, 1.11569]), + orientation=th.tensor([0.54757518, 0.27792802, 0.35721896, 0.70378409]), + ) + + # Let apple settle + for _ in range(50): + env.step([]) + + knife.keep_still() + knife.set_position_orientation( + position=apple.get_position_orientation()[0] + th.tensor([-0.15, 0.0, 0.2], dtype=th.float32), + orientation=T.euler2quat(th.tensor([-math.pi / 2, 0, 0], dtype=th.float32)), + ) + + if not short_exec: + input("The knife will fall on the apple and slice it. Press [ENTER] to continue.") + + # Step simulation for a bit so that apple is sliced + for i in range(1000): + env.step([]) + + if not short_exec: + input("Apple has been sliced! Press [ENTER] to terminate the demo.") + + # Always close environment at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/temperature_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/temperature_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..4eecbbacca7fc6b4bf82f4c689c9873fec26fad4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/object_states/temperature_demo.py @@ -0,0 +1,181 @@ +import math + +import torch as th + +import omnigibson as og +from omnigibson import object_states +from omnigibson.macros import gm +import omnigibson.utils.transform_utils as T + +# Make sure object states are enabled +gm.ENABLE_OBJECT_STATES = True + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Demo of temperature change + Loads a stove, a microwave and an oven, all toggled on, and five frozen apples + The user can move the apples to see them change from frozen, to normal temperature, to cooked and burnt + This demo also shows how to load objects ToggledOn and how to set the initial temperature of an object + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Define specific objects we want to load in with the scene directly + obj_configs = [] + + # Light + obj_configs.append( + dict( + type="LightObject", + light_type="Sphere", + name="light", + radius=0.01, + intensity=1e8, + position=[-2.0, -2.0, 1.0], + ) + ) + + # Stove + obj_configs.append( + dict( + type="DatasetObject", + name="stove", + category="stove", + model="ykretu", + position=[0, 0, 0.61], + orientation=T.euler2quat(th.tensor([0.0, 0.0, -math.pi / 2.0])), + ) + ) + + # Microwave + obj_configs.append( + dict( + type="DatasetObject", + name="microwave", + category="microwave", + model="abzvij", + position=[2.5, 0, 0.15], + orientation=T.euler2quat(th.tensor([0.0, 0.0, -math.pi / 2.0])), + ) + ) + + # Oven + obj_configs.append( + dict( + type="DatasetObject", + name="oven", + category="oven", + model="ffitak", + position=[-1.25, 0, 0.36], + orientation=T.euler2quat(th.tensor([0.0, 0.0, -math.pi / 2.0])), + ) + ) + + # Tray + obj_configs.append( + dict( + type="DatasetObject", + name="tray", + category="tray", + model="xzcnjq", + position=[-2.25, -0.12, 0.05], + ) + ) + + # Fridge + obj_configs.append( + dict( + type="DatasetObject", + name="fridge", + category="fridge", + model="petcxr", + abilities={ + "coldSource": { + "temperature": -100.0, + "requires_inside": True, + } + }, + position=[1.25, 0, 1.0], + orientation=T.euler2quat(th.tensor([0.0, 0.0, -math.pi / 2.0])), + ) + ) + + # 5 Apples + for i in range(5): + obj_configs.append( + dict( + type="DatasetObject", + name=f"apple{i}", + category="apple", + model="agveuv", + position=[0, i * 0.1, 5.0], + ) + ) + + # Create the scene config to load -- empty scene with desired objects + cfg = { + "scene": { + "type": "Scene", + }, + "objects": obj_configs, + } + + # Create the environment + env = og.Environment(configs=cfg) + + # Get reference to relevant objects + stove = env.scene.object_registry("name", "stove") + microwave = env.scene.object_registry("name", "microwave") + oven = env.scene.object_registry("name", "oven") + tray = env.scene.object_registry("name", "tray") + fridge = env.scene.object_registry("name", "fridge") + apples = list(env.scene.object_registry("category", "apple")) + + # Set camera to appropriate viewing pose + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([0.1759, -4.8260, 1.7778]), + orientation=th.tensor([0.63311689, 0.00127259, 0.00155577, 0.77405359]), + ) + + # Let objects settle + for _ in range(25): + env.step(th.empty(0)) + + # Turn on all scene objects + stove.states[object_states.ToggledOn].set_value(True) + microwave.states[object_states.ToggledOn].set_value(True) + oven.states[object_states.ToggledOn].set_value(True) + + # Set initial temperature of the apples to -50 degrees Celsius, and move the apples to different objects + for apple in apples: + apple.states[object_states.Temperature].set_value(-50) + apples[0].states[object_states.Inside].set_value(oven, True) + apples[1].set_position_orientation( + position=stove.states[object_states.HeatSourceOrSink].link.get_position_orientation()[0] + + th.tensor([0, 0, 0.1]) + ) + apples[2].states[object_states.OnTop].set_value(tray, True) + apples[3].states[object_states.Inside].set_value(fridge, True) + apples[4].states[object_states.Inside].set_value(microwave, True) + + steps = 0 + max_steps = -1 if not short_exec else 1000 + + # Main recording loop + locations = ["Oven", "Stove", "Tray", "Fridge", "Microwave"] + print() + while steps != max_steps: + env.step(th.empty(0)) + temp_info = [ + f"{loc}: {apple.states[object_states.Temperature].get_value():.1f}°C" + for loc, apple in zip(locations, apples) + ] + print(f"Apple temps: {' | '.join(temp_info):<80}", end="\r") + steps += 1 + + # Always close env at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/draw_bounding_box.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/draw_bounding_box.py new file mode 100644 index 0000000000000000000000000000000000000000..5c819d0d2495ec20fe127407eb0a60eba8eed783 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/draw_bounding_box.py @@ -0,0 +1,91 @@ +import matplotlib.pyplot as plt +import torch as th + +import omnigibson as og + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Shows how to obtain the bounding box of an articulated object. + Draws the bounding box around the loaded object, a cabinet, and writes the visualized image to disk at the + current directory named 'bbox_2d_[loose / tight]_img.png'. + + NOTE: In the GUI, bounding boxes can be natively viewed by clicking on the sensor ((*)) icon at the top, + and then selecting the appropriate bounding box modalities, and clicking "Show". See: + + https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_replicator/visualization.html#the-visualizer + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Specify objects to load + banana_cfg = dict( + type="DatasetObject", + name="banana", + category="banana", + model="vvyyyv", + visual_only=True, + position=[-0.906661, -0.545106, 0.136824], + orientation=[0, 0, 0.76040583, -0.6494482], + ) + + door_cfg = dict( + type="DatasetObject", + name="door", + category="door", + model="ohagsq", + visual_only=True, + position=[-1.0, 1.2, 1.45], + orientation=[0.0, 0.0, 0.0, 1.0], + ) + + # Create the scene config to load -- empty scene with a few objects + cfg = { + "scene": { + "type": "Scene", + }, + "objects": [banana_cfg, door_cfg], + } + + # Create the environment + env = og.Environment(configs=cfg) + + # Set camera to appropriate viewing pose + cam = og.sim.viewer_camera + cam.set_position_orientation( + position=th.tensor([-4.62785, -0.418575, 0.933943]), + orientation=th.tensor([0.52196595, -0.4231939, -0.46640436, 0.5752612]), + ) + + # Add bounding boxes to camera sensor + bbox_modalities = ["bbox_3d", "bbox_2d_loose", "bbox_2d_tight"] + for bbox_modality in bbox_modalities: + cam.add_modality(bbox_modality) + + # Take a few steps to let objects settle + for i in range(100): + env.step([]) + + # Grab observations from viewer camera and write them to disk + obs, _ = cam.get_obs() + + for bbox_modality in bbox_modalities: + # Print out each of the modalities + og.log.info(f"Observation modality {bbox_modality}:\n{obs[bbox_modality]}") + + # Also write the 2d loose bounding box to disk + if "3d" not in bbox_modality: + from omnigibson.utils.deprecated_utils import colorize_bboxes + + colorized_img = colorize_bboxes( + bboxes_2d_data=obs[bbox_modality], bboxes_2d_rgb=obs["rgb"].cpu().numpy(), num_channels=4 + ) + fpath = f"{bbox_modality}_img.png" + plt.imsave(fpath, colorized_img) + og.log.info(f"Saving modality [{bbox_modality}] image to: {fpath}") + + # Always close environment down at end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/highlight_objects.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/highlight_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..3b60c4eefaa3c431a58a4b593c0dc4ed617f35d4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/highlight_objects.py @@ -0,0 +1,46 @@ +import torch as th + +import omnigibson as og + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Highlights visually all object instances of windows and then removes the highlighting + It also demonstrates how to apply an action on all instances of objects of a given category + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Create the scene config to load -- empty scene + cfg = { + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": "Rs_int", + } + } + + # Create the environment + env = og.Environment(configs=cfg) + + # Grab all window objects + windows = env.scene.object_registry("category", "openable_window") + + # Step environment while toggling window highlighting + i = 0 + highlighted = False + max_steps = -1 if not short_exec else 1000 + while i != max_steps: + env.step(th.empty(0)) + if i % 50 == 0: + highlighted = not highlighted + og.log.info(f"Toggling window highlight to: {highlighted}") + for window in windows: + # Note that this property is R/W! + window.highlighted = highlighted + i += 1 + + # Always close the environment at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/import_custom_object.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/import_custom_object.py new file mode 100644 index 0000000000000000000000000000000000000000..60d78409d04a9bf954e7e9e99cb6e6fbaa8f2715 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/import_custom_object.py @@ -0,0 +1,144 @@ +""" +Helper script to download BEHAVIOR-1K dataset and assets. +Improved version that can import obj file and articulated file (glb, gltf). +""" + +import pathlib +from typing import Literal +import click +import shutil +import tempfile +import omnigibson as og + +from omnigibson.utils.asset_conversion_utils import ( + import_og_asset_from_urdf, + generate_urdf_for_mesh, +) + + +@click.command() +@click.option( + "--dataset-name", + default="custom-assets", + type=click.STRING, + help="Name of the dataset to which the imported objects will be written. This is located at get_dataset_path()", +) +@click.option( + "--asset-path", + required=True, + type=click.Path(exists=True, dir_okay=False), + help="Absolute path to asset file to import. This can be a raw visual mesh (for single-bodied, static objects), e.g. .obj, .glb, etc., or a more complex (such as articulated) objects defined in .urdf format.", +) +@click.option("--category", required=True, type=click.STRING, help="Category name to assign to the imported asset") +@click.option( + "--model", + required=True, + type=click.STRING, + help="Model name to assign to the imported asset. This must be unique within the dataset.", +) +@click.option( + "--collision-method", + type=click.Choice(["coacd", "convex", "none"]), + default="coacd", + help="Method to generate the collision mesh. 'coacd' generates a set of convex decompositions, while 'convex' generates a single convex hull. 'none' will not generate any explicit mesh", +) +@click.option( + "--hull-count", + type=int, + default=32, + help="Maximum number of convex hulls to decompose individual visual meshes into. Only relevant if --collision-method=coacd", +) +@click.option("--up-axis", type=click.Choice(["z", "y"]), default="z", help="Up axis for the mesh.") +@click.option("--headless", is_flag=True, help="Run the script in headless mode.") +@click.option("--scale", type=int, default=1, help="User choice scale, will be overwritten if check_scale and rescale") +@click.option("--check_scale", is_flag=True, help="Check meshes scale based on heuristic") +@click.option("--rescale", is_flag=True, help="Rescale meshes based on heuristic if check_scale ") +@click.option("--overwrite", is_flag=True, help="Overwrite any pre-existing files") +@click.option("--no_keep_instanceable", is_flag=True, help="Do not keep instanceable meshes if set") +@click.option("--no_import_inertia", is_flag=True, help="Do not import native inertia tensor if set") +def import_custom_object( + dataset_name: str, + asset_path: str, + category: str, + model: str, + collision_method: Literal["coacd", "convex", "none"], + hull_count: int, + up_axis: Literal["z", "y"], + headless: bool, + scale: int, + check_scale: bool, + rescale: bool, + overwrite: bool, + no_keep_instanceable: bool, + no_import_inertia: bool, +): + """ + Imports a custom-defined object asset into an OmniGibson-compatible USD format and saves the imported asset + files to the selected dataset directory. + """ + + assert len(model) == 6 and model.isalpha(), "Model name must be 6 characters long and contain only letters." + collision_method = None if collision_method == "none" else collision_method + + # Resolve the asset path here + asset_path = pathlib.Path(asset_path).absolute() + + # If we're not a URDF, import the mesh directly first + temp_dir = tempfile.mkdtemp() + + try: + if asset_path.suffix != ".urdf": + # Try to generate URDF, may raise ValueError if too many submeshes + urdf_path = generate_urdf_for_mesh( + asset_path, + temp_dir, + category, + model, + collision_method, + hull_count, + up_axis, + scale=scale, + check_scale=check_scale, + rescale=rescale, + overwrite=True, + ) + if urdf_path is not None: + click.echo("URDF generation complete!") + collision_method = None + else: + # Clean up temp directories before exiting + click.echo("Error during URDF generation") + raise click.Abort() + else: + urdf_path = asset_path + collision_method = collision_method + + # Convert to USD + import_og_asset_from_urdf( + dataset_name=dataset_name, + category=category, + model=model, + urdf_path=str(urdf_path), + collision_method=collision_method, + hull_count=hull_count, + overwrite=overwrite, + keep_instanceable=not no_keep_instanceable, + import_inertia_tensor=not no_import_inertia, + use_usda=False, + ) + + finally: + # Clean up temp directories before exiting + shutil.rmtree(temp_dir) + + # Visualize if not headless + if not headless: + click.echo("The asset has been successfully imported. You can view it and make changes and save if you'd like.") + while True: + og.sim.render() + + og.shutdown() + + +if __name__ == "__main__": + import_custom_object() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/load_object_selector.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/load_object_selector.py new file mode 100644 index 0000000000000000000000000000000000000000..c926c74655f7b5d1f90e4f264b9b362dea27eab4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/load_object_selector.py @@ -0,0 +1,70 @@ +import torch as th + +import omnigibson as og +from omnigibson.utils.asset_utils import get_all_object_categories, get_all_object_category_models +from omnigibson.utils.ui_utils import choose_from_options + + +def main(random_selection=False, headless=False, short_exec=False): + """ + This demo shows how to load any scaled objects from the OG object model dataset + The user selects an object model to load + The objects can be loaded into an empty scene or an interactive scene (OG) + The example also shows how to use the Environment API or directly the Simulator API, loading objects and robots + and executing actions + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + scene_options = ["Scene", "InteractiveTraversableScene"] + scene_type = choose_from_options(options=scene_options, name="scene type", random_selection=random_selection) + + # -- Choose the object to load -- + + # Select a category to load + available_obj_categories = get_all_object_categories() + obj_category = choose_from_options( + options=available_obj_categories, name="object category", random_selection=random_selection + ) + + # Select a model to load + available_obj_models = get_all_object_category_models(obj_category) + obj_model = choose_from_options( + options=available_obj_models, name="object model", random_selection=random_selection + ) + + # Create and load this object into the simulator + obj_cfg = dict( + type="DatasetObject", + name="obj", + category=obj_category, + model=obj_model, + position=[0, 0, 50.0], + ) + + cfg = { + "scene": { + "type": scene_type, + }, + "objects": [obj_cfg], + } + if scene_type == "InteractiveTraversableScene": + cfg["scene"]["scene_model"] = "Rs_int" + + # Create the environment + env = og.Environment(configs=cfg) + + # Place the object so it rests on the floor + obj = env.scene.object_registry("name", "obj") + center_offset = obj.get_position_orientation()[0] - obj.aabb_center + th.tensor([0, 0, obj.aabb_extent[2] / 2.0]) + obj.set_position_orientation(position=center_offset) + + # Step through the environment + max_steps = 100 if short_exec else 10000 + for i in range(max_steps): + env.step([]) + + # Always close the environment at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/visualize_object.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/visualize_object.py new file mode 100644 index 0000000000000000000000000000000000000000..ca67525bc86a1d95ba3419777ac02661df8f1264 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/objects/visualize_object.py @@ -0,0 +1,141 @@ +import argparse +import math + +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.utils.asset_utils import get_all_object_categories, get_all_object_category_models +from omnigibson.utils.ui_utils import choose_from_options + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Visualizes object as specified by its USD path, @usd_path. If None if specified, will instead + result in an object selection from OmniGibson's object dataset + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Assuming that if random_selection=True, headless=True, short_exec=True, we are calling it from tests and we + # do not want to parse args (it would fail because the calling function is pytest "testfile.py") + usd_path = None + if not (random_selection and headless and short_exec): + parser = argparse.ArgumentParser() + parser.add_argument( + "--usd_path", + default=None, + help="USD Model to load", + ) + args = parser.parse_args() + usd_path = args.usd_path + + # Define objects to load + light0_cfg = dict( + type="LightObject", + light_type="Sphere", + name="sphere_light0", + radius=0.01, + intensity=1e5, + position=[-2.0, -2.0, 2.0], + ) + + light1_cfg = dict( + type="LightObject", + light_type="Sphere", + name="sphere_light1", + radius=0.01, + intensity=1e5, + position=[-2.0, 2.0, 2.0], + ) + + # Make sure we have a valid usd path + if usd_path is None: + # Select a category to load + available_obj_categories = get_all_object_categories() + obj_category = choose_from_options( + options=available_obj_categories, name="object category", random_selection=random_selection + ) + + # Select a model to load + available_obj_models = get_all_object_category_models(obj_category) + obj_model = choose_from_options( + options=available_obj_models, name="object model", random_selection=random_selection + ) + + kwargs = { + "type": "DatasetObject", + "category": obj_category, + "model": obj_model, + } + else: + kwargs = { + "type": "USDObject", + "usd_path": usd_path, + } + + # Import the desired object + obj_cfg = dict( + **kwargs, + name="obj", + usd_path=usd_path, + visual_only=True, + position=[0, 0, 10.0], + ) + + # Create the scene config to load -- empty scene + cfg = { + "scene": { + "type": "Scene", + }, + "objects": [light0_cfg, light1_cfg, obj_cfg], + } + + # Create the environment + env = og.Environment(configs=cfg) + + # Set camera to appropriate viewing pose + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([-0.00913503, -1.95750906, 1.36407314]), + orientation=th.tensor([0.6350064, 0.0, 0.0, 0.77250687]), + ) + + # Grab the object references + obj = env.scene.object_registry("name", "obj") + + # Standardize the scale of the object so it fits in a [1,1,1] box -- note that we have to stop the simulator + # in order to set the scale + extents = obj.aabb_extent + og.sim.stop() + obj.scale = (th.ones(3) / extents).min() + og.sim.play() + env.step(th.empty(0)) + + # Move the object so that its center is at [0, 0, 1] + center_offset = obj.get_position_orientation()[0] - obj.aabb_center + th.tensor([0, 0, 1.0]) + obj.set_position_orientation(position=center_offset) + + # Allow the user to easily move the camera around + og.sim.enable_viewer_camera_teleoperation() + + # Rotate the object in place + steps_per_rotate = 360 + steps_per_joint = steps_per_rotate / 10 + max_steps = 100 if short_exec else 10000 + for i in range(max_steps): + z_angle = 2 * math.pi * (i % steps_per_rotate) / steps_per_rotate + quat = T.euler2quat(th.tensor([0, 0, z_angle])) + pos = T.quat2mat(quat) @ center_offset + if obj.n_dof > 0: + frac = (i % steps_per_joint) / steps_per_joint + j_frac = -1.0 + 2.0 * frac if (i // steps_per_joint) % 2 == 0 else 1.0 - 2.0 * frac + obj.set_joint_positions(positions=j_frac * th.ones(obj.n_dof), normalized=True, drive=False) + obj.keep_still() + obj.set_position_orientation(position=pos, orientation=quat) + env.step(th.empty(0)) + + # Shut down at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/robots/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/robots/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/robots/all_robots_visualizer.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/robots/all_robots_visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..5ee6caa16da240ffd80ca91acc312f3c8012b5f8 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/robots/all_robots_visualizer.py @@ -0,0 +1,74 @@ +import torch as th + +import omnigibson as og +from omnigibson.robots import REGISTERED_ROBOTS, Robot + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Robot demo + Loads all robots in an empty scene, generate random actions + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + # Create empty scene with no robots in it initially + cfg = { + "scene": { + "type": "Scene", + } + } + + env = og.Environment(configs=cfg) + + og.sim.stop() + + # Iterate over all robots and demo their motion + for robot_name in REGISTERED_ROBOTS: + # Create and import robot + robot = Robot( + name=robot_name, + model=robot_name, + obs_modalities=[], # We're just moving robots around so don't load any observation modalities + ) + env.scene.add_object(robot) + + # At least one step is always needed while sim is playing for any imported object to be fully initialized + og.sim.play() + og.sim.step() + + # Reset robot and make sure it's not moving + robot.reset() + robot.keep_still() + + # Log information + og.log.info(f"Loaded {robot_name}") + og.log.info(f"Moving {robot_name}") + + if not headless: + # Set viewer in front facing robot + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([2.69918369, -3.63686664, 4.57894564]), + orientation=th.tensor([0.39592411, 0.1348514, 0.29286304, 0.85982]), + ) + + og.sim.enable_viewer_camera_teleoperation() + + # Hold still briefly so viewer can see robot + for _ in range(100): + og.sim.step() + + # Then apply random actions for a bit + for _ in range(10): + action = robot.action_space.sample() * 0.05 + for _ in range(30): + env.step(action) + + # Stop the simulator and remove the robot + og.sim.stop() + env.scene.remove_object(obj=robot) + + # Always shut down the environment cleanly at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/robots/grasping_mode_example.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/robots/grasping_mode_example.py new file mode 100644 index 0000000000000000000000000000000000000000..8f2789b25909d535effe779c9945136ca86994a5 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/robots/grasping_mode_example.py @@ -0,0 +1,127 @@ +""" +Example script demo'ing robot manipulation control with grasping. +""" + +import torch as th + +import omnigibson as og +from omnigibson.macros import gm +from omnigibson.sensors import VisionSensor +from omnigibson.utils.ui_utils import KeyboardRobotController, choose_from_options + +GRASPING_MODES = dict( + sticky="Sticky Mitten - Objects are magnetized when they touch the fingers and a CLOSE command is given", + assisted="Assisted Grasping - Objects are magnetized when they touch the fingers, are within the hand, and a CLOSE command is given", + physical="Physical Grasping - No additional grasping assistance applied", +) + +# Don't use GPU dynamics for performance boost +gm.USE_GPU_DYNAMICS = False + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Robot grasping mode demo with selection + Queries the user to select a type of grasping mode + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Choose type of grasping + grasping_mode = choose_from_options(options=GRASPING_MODES, name="grasping mode", random_selection=random_selection) + + # Create environment configuration to use + scene_cfg = dict(type="Scene") + robot0_cfg = dict( + model="fetch", + obs_modalities=["rgb"], # we're just doing a grasping demo so we don't need all observation modalities + action_type="continuous", + action_normalize=True, + grasping_mode=grasping_mode, + ) + + # Define objects to load + table_cfg = dict( + type="DatasetObject", + name="table", + category="breakfast_table", + model="lcsizg", + bounding_box=[0.5, 0.5, 0.8], + fixed_base=True, + position=[0.7, -0.1, 0.6], + orientation=[0, 0, 0.707, 0.707], + ) + + chair_cfg = dict( + type="DatasetObject", + name="chair", + category="straight_chair", + model="amgwaw", + bounding_box=None, + fixed_base=False, + position=[0.45, 0.65, 0.425], + orientation=[0, 0, -0.9990215, -0.0442276], + ) + + box_cfg = dict( + type="PrimitiveObject", + name="box", + primitive_type="Cube", + rgba=[1.0, 0, 0, 1.0], + size=0.05, + position=[0.53, -0.1, 0.97], + ) + + # Compile config + cfg = dict(scene=scene_cfg, robots=[robot0_cfg], objects=[table_cfg, chair_cfg, box_cfg]) + + # Create the environment + env = og.Environment(configs=cfg) + + # Reset the robot + robot = env.scene.robots[0] + robot.set_position_orientation(position=[0, 0, 0]) + robot.reset() + robot.keep_still() + + # Make the robot's camera(s) high-res + for sensor in robot.sensors.values(): + if isinstance(sensor, VisionSensor): + sensor.image_height = 720 + sensor.image_width = 720 + + # Update the simulator's viewer camera's pose so it points towards the robot + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([-2.39951, 2.26469, 2.66227]), + orientation=th.tensor([-0.23898481, 0.48475231, 0.75464013, -0.37204802]), + ) + + # Create teleop controller + action_generator = KeyboardRobotController(robot=robot) + + # Print out relevant keyboard info if using keyboard teleop + action_generator.print_keyboard_teleop_info() + + # Other helpful user info + print("Running demo with grasping mode {}.".format(grasping_mode)) + print("Press ESC to quit") + + # Loop control until user quits + max_steps = -1 if not short_exec else 100 + step = 0 + while step != max_steps: + if random_selection: + # Sample new random action every 30 steps + if step % 30 == 0: + random_action = action_generator.get_random_action() * 0.05 + action = random_action + else: + action = action_generator.get_teleop_action() + env.step(action=action) + step += 1 + + # Always shut down the environment cleanly at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/robots/import_custom_robot.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/robots/import_custom_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..28448ddd1f6812b25adab45b1730b27386d526cc --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/robots/import_custom_robot.py @@ -0,0 +1,1048 @@ +""" +Helper script to download BEHAVIOR-1K dataset and assets. +""" + +import xml.etree.ElementTree as ET +from copy import deepcopy +from pathlib import Path + +import click +import torch as th +import yaml +from addict import Dict + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.utils.asset_conversion_utils import ( + _add_xform_properties, + _space_string_to_tensor, + find_all_prim_children_with_type, + import_og_asset_from_urdf, +) +from omnigibson.utils.python_utils import assert_valid_key +from omnigibson.utils.usd_utils import create_joint, create_primitive_mesh + + +_DOCSTRING = """ +Imports an custom-defined robot URDF asset into an OmniGibson-compatible USD format and saves the imported asset +files to the custom dataset directory data/custom_dataset + +Note that @config is expected to follow the following format (R1 config shown as an example): + +\b +urdf_path: r1_pro_source.urdf # (str) Absolute path to robot URDF to import +name: r1 # (str) Name to assign to robot +headless: false # (bool) if set, run without GUI +overwrite: true # (bool) if set, overwrite any existing files +merge_fixed_joints: false # (bool) whether to merge fixed joints in the robot hierarchy or not +base_motion: + wheel_links: # (list of str): links corresponding to wheels + - wheel_link1 + - wheel_link2 + - wheel_link3 + wheel_joints: # (list of str): joints corresponding to wheel motion + - servo_joint1 + - servo_joint2 + - servo_joint3 + - wheel_joint1 + - wheel_joint2 + - wheel_joint3 + use_sphere_wheels: true # (bool) whether to use sphere approximation for wheels (better stability) + use_holonomic_joints: true # (bool) whether to use joints to approximate a holonomic base. In this case, all + # wheel-related joints will be made into fixed joints, and 6 additional + # "virtual" joints will be added to the robot's base capturing 6DOF movement, + # with the (x,y,rz) joints being controllable by motors +collision: + decompose_method: coacd # (str) [coacd, convex, or null] collision decomposition method + hull_count: 8 # (int) per-mesh max hull count to use during decomposition, only relevant for coacd + coacd_links: [] # (list of str): links that should use CoACD to decompose collision meshes + convex_links: # (list of str): links that should use convex hull to decompose collision meshes + - base_link + - wheel_link1 + - wheel_link2 + - wheel_link3 + - torso_link1 + - torso_link2 + - torso_link3 + - torso_link4 + - left_arm_link1 + - left_arm_link4 + - left_arm_link5 + - right_arm_link1 + - right_arm_link4 + - right_arm_link5 + no_decompose_links: [] # (list of str): links that should not have any post-processing done to them + no_collision_links: # (list of str) links that will have any associated collision meshes removed + - servo_link1 + - servo_link2 + - servo_link3 +eef_vis_links: # (list of dict) information for adding cameras to robot + - link: left_eef_link # same format as @camera_links + parent_link: left_arm_link6 + offset: + position: [0, 0, 0.06] + orientation: [0, 0, 0, 1] # NOTE: Convention for these eef vis links should be tuned such that: + # z-axis points out from the tips of the fingers + # y-axis points in the direction from the left finger to the right finger + # x-axis is automatically inferred from the above two axes + - link: right_eef_link # same format as @camera_links + parent_link: right_arm_link6 + offset: + position: [0, 0, 0.06] + orientation: [0, 0, 0, 1] +camera_links: # (list of dict) information for adding cameras to robot + - link: eyes # (str) link name to add camera. Must exist if @parent_link is null, else will be + # added as a child of the parent + parent_link: torso_link4 # (str) optional parent link to use if adding new link + offset: # (dict) local pos,ori offset values. if @parent_link is specified, defines offset + # between @parent_link and @link specified in @parent_link's frame. + # Otherwise, specifies offset of generated prim relative to @link's frame + position: [0.0732, 0, 0.4525] # (3-tuple) (x,y,z) offset -- this is done BEFORE the rotation + orientation: [0.4056, -0.4056, -0.5792, 0.5792] # (4-tuple) (x,y,z,w) offset + - link: left_eef_link + parent_link: null + offset: + position: [0.05, 0, -0.05] + orientation: [-0.7011, -0.7011, -0.0923, -0.0923] + - link: right_eef_link + parent_link: null + offset: + position: [0.05, 0, -0.05] + orientation: [-0.7011, -0.7011, -0.0923, -0.0923] +lidar_links: [] # (list of dict) information for adding cameras to robot +curobo: + eef_to_gripper_info: # (dict) Maps EEF link name to corresponding gripper links / joints + right_eef_link: + links: ["right_gripper_link1", "right_gripper_link2"] + joints: ["right_gripper_axis1", "right_gripper_axis2"] + left_eef_link: + links: ["left_gripper_link1", "left_gripper_link2"] + joints: ["left_gripper_axis1", "left_gripper_axis2"] + flip_joint_limits: [] # (list of str) any joints that have a negative axis specified in the + # source URDF + lock_joints: {} # (dict) Maps joint name to "locked" joint configuration. Any joints + # specified here will not be considered active when motion planning + # NOTE: All gripper joints and non-controllable holonomic joints + # will automatically be added here. Null means that the value will be + # dynamically computed at runtime based on the robot's reset qpos + self_collision_ignore: # (dict) Maps link name to list of other ignore links to ignore collisions + # with. Note that bi-directional specification is not necessary, + # e.g.: "torso_link1" does not need to be specified in + # "torso_link2"'s list if "torso_link2" is already specified in + # "torso_link1"'s list + base_link: ["torso_link1", "wheel_link1", "wheel_link2", "wheel_link3"] + torso_link1: ["torso_link2"] + torso_link2: ["torso_link3", "torso_link4"] + torso_link3: ["torso_link4"] + torso_link4: ["left_arm_link1", "right_arm_link1", "left_arm_link2", "right_arm_link2"] + left_arm_link1: ["left_arm_link2"] + left_arm_link2: ["left_arm_link3"] + left_arm_link3: ["left_arm_link4"] + left_arm_link4: ["left_arm_link5"] + left_arm_link5: ["left_arm_link6"] + left_arm_link6: ["left_gripper_link1", "left_gripper_link2"] + right_arm_link1: ["right_arm_link2"] + right_arm_link2: ["right_arm_link3"] + right_arm_link3: ["right_arm_link4"] + right_arm_link4: ["right_arm_link5"] + right_arm_link5: ["right_arm_link6"] + right_arm_link6: ["right_gripper_link1", "right_gripper_link2"] + left_gripper_link1: ["left_gripper_link2"] + right_gripper_link1: ["right_gripper_link2"] + collision_spheres: # (dict) Maps link name to list of collision sphere representations, + # where each sphere is defined by its (x,y,z) "center" and "radius" + # values. This defines the collision geometry during motion planning + base_link: + - "center": [-0.009, -0.094, 0.131] + "radius": 0.09128 + - "center": [-0.021, 0.087, 0.121] + "radius": 0.0906 + - "center": [0.019, 0.137, 0.198] + "radius": 0.07971 + - "center": [0.019, -0.14, 0.209] + "radius": 0.07563 + - "center": [0.007, -0.018, 0.115] + "radius": 0.08448 + - "center": [0.119, -0.176, 0.209] + "radius": 0.05998 + - "center": [0.137, 0.118, 0.208] + "radius": 0.05862 + - "center": [-0.152, -0.049, 0.204] + "radius": 0.05454 + torso_link1: + - "center": [-0.001, -0.014, -0.057] + "radius": 0.1 + - "center": [-0.001, -0.127, -0.064] + "radius": 0.07 + - "center": [-0.001, -0.219, -0.064] + "radius": 0.07 + - "center": [-0.001, -0.29, -0.064] + "radius": 0.07 + - "center": [-0.001, -0.375, -0.064] + "radius": 0.07 + - "center": [-0.001, -0.419, -0.064] + "radius": 0.07 + torso_link2: + - "center": [-0.001, -0.086, -0.064] + "radius": 0.07 + - "center": [-0.001, -0.194, -0.064] + "radius": 0.07 + - "center": [-0.001, -0.31, -0.064] + "radius": 0.07 + torso_link4: + - "center": [0.005, -0.001, 0.062] + "radius": 0.1 + - "center": [0.005, -0.001, 0.245] + "radius": 0.15 + - "center": [0.005, -0.001, 0.458] + "radius": 0.1 + - "center": [0.002, 0.126, 0.305] + "radius": 0.08 + - "center": [0.002, -0.126, 0.305] + "radius": 0.08 + left_arm_link1: + - "center": [0.001, 0.0, 0.069] + "radius": 0.06 + left_arm_link2: + - "center": [-0.062, -0.016, -0.03] + "radius": 0.06 + - "center": [-0.135, -0.019, -0.03] + "radius": 0.06 + - "center": [-0.224, -0.019, -0.03] + "radius": 0.06 + - "center": [-0.31, -0.022, -0.03] + "radius": 0.06 + - "center": [-0.34, -0.027, -0.03] + "radius": 0.06 + left_arm_link3: + - "center": [0.037, -0.058, -0.044] + "radius": 0.05 + - "center": [0.095, -0.08, -0.044] + "radius": 0.03 + - "center": [0.135, -0.08, -0.043] + "radius": 0.03 + - "center": [0.176, -0.08, -0.043] + "radius": 0.03 + - "center": [0.22, -0.077, -0.043] + "radius": 0.03 + left_arm_link4: + - "center": [-0.002, 0.0, 0.276] + "radius": 0.04 + left_arm_link5: + - "center": [0.059, -0.001, -0.021] + "radius": 0.035 + left_arm_link6: + - "center": [0.0, 0.0, 0.04] + "radius": 0.04 + right_arm_link1: + - "center": [0.001, 0.0, 0.069] + "radius": 0.06 + right_arm_link2: + - "center": [-0.062, -0.016, -0.03] + "radius": 0.06 + - "center": [-0.135, -0.019, -0.03] + "radius": 0.06 + - "center": [-0.224, -0.019, -0.03] + "radius": 0.06 + - "center": [-0.31, -0.022, -0.03] + "radius": 0.06 + - "center": [-0.34, -0.027, -0.03] + "radius": 0.06 + right_arm_link3: + - "center": [0.037, -0.058, -0.044] + "radius": 0.05 + - "center": [0.095, -0.08, -0.044] + "radius": 0.03 + - "center": [0.135, -0.08, -0.043] + "radius": 0.03 + - "center": [0.176, -0.08, -0.043] + "radius": 0.03 + - "center": [0.22, -0.077, -0.043] + "radius": 0.03 + right_arm_link4: + - "center": [-0.002, 0.0, 0.276] + "radius": 0.04 + right_arm_link5: + - "center": [0.059, -0.001, -0.021] + "radius": 0.035 + right_arm_link6: + - "center": [-0.0, 0.0, 0.04] + "radius": 0.035 + wheel_link1: + - "center": [-0.0, 0.0, -0.03] + "radius": 0.06 + wheel_link2: + - "center": [0.0, 0.0, 0.03] + "radius": 0.06 + wheel_link3: + - "center": [0.0, 0.0, -0.03] + "radius": 0.06 + left_gripper_link1: + - "center": [-0.03, 0.0, -0.002] + "radius": 0.008 + - "center": [-0.01, 0.0, -0.003] + "radius": 0.007 + - "center": [0.005, 0.0, -0.005] + "radius": 0.005 + - "center": [0.02, 0.0, -0.007] + "radius": 0.003 + left_gripper_link2: + - "center": [-0.03, 0.0, -0.002] + "radius": 0.008 + - "center": [-0.01, 0.0, -0.003] + "radius": 0.007 + - "center": [0.005, 0.0, -0.005] + "radius": 0.005 + - "center": [0.02, 0.0, -0.007] + "radius": 0.003 + right_gripper_link1: + - "center": [-0.03, 0.0, -0.002] + "radius": 0.008 + - "center": [-0.01, -0.0, -0.003] + "radius": 0.007 + - "center": [0.005, -0.0, -0.005] + "radius": 0.005 + - "center": [0.02, -0.0, -0.007] + "radius": 0.003 + right_gripper_link2: + - "center": [-0.03, 0.0, -0.002] + "radius": 0.008 + - "center": [-0.01, 0.0, -0.003] + "radius": 0.007 + - "center": [0.005, 0.0, -0.005] + "radius": 0.005 + - "center": [0.02, 0.0, -0.007] + "radius": 0.003 + +""" + + +def create_rigid_prim(stage, link_prim_path): + """ + Creates a new rigid link prim nested under @root_prim + + Args: + stage (Usd.Stage): Current active omniverse stage + link_prim_path (str): Prim path at which link will be created. Should not already exist on the stage + + Returns: + Usd.Prim: Newly created rigid prim + """ + # Make sure link prim does NOT already exist (this should be a new link) + link_prim_exists = stage.GetPrimAtPath(link_prim_path).IsValid() + assert ( + not link_prim_exists + ), f"Cannot create new link because there already exists a link at prim path {link_prim_path}!" + + # Manually create a new prim (specified offset) + link_prim = lazy.pxr.UsdGeom.Xform.Define(stage, link_prim_path).GetPrim() + _add_xform_properties(prim=link_prim) + + # Add rigid prim API to new link prim + lazy.pxr.UsdPhysics.RigidBodyAPI.Apply(link_prim) + lazy.pxr.PhysxSchema.PhysxRigidBodyAPI.Apply(link_prim) + + return link_prim + + +def add_sensor(stage, root_prim, sensor_type, link_name, parent_link_name=None, pos_offset=None, ori_offset=None): + """ + Adds sensor to robot. This is an in-place operation on @root_prim + + Args: + stage (Usd.Stage): Current active omniverse stage + root_prim (Usd.Prim): Root prim of the current robot, assumed to be on the current stage + sensor_type (str): Sensor to create. Valid options are: {Camera, Lidar, VisualSphere} + link_name (str): Link to attach the created sensor prim to. If this link does not already exist in the robot's + current set of links, a new one will be created as a child of @parent_link_name's link + parent_link_name (None or str): If specified, parent link from which to create a new child link @link_name. If + set, @link_name should NOT be a link already found on the robot! + pos_offset (None or 3-tuple): If specified, (x,y,z) local translation offset to apply. + If @parent_link_name is specified, defines offset of @link_name wrt @parent_link_name + If only @link_name is specified, defines offset of the sensor prim wrt @link_name + ori_offset (None or 3-tuple): If specified, (x,y,z,w) quaternion rotation offset to apply. + If @parent_link_name is specified, defines offset of @link_name wrt @parent_link_name + If only @link_name is specified, defines offset of the sensor prim wrt @link_name + """ + # Make sure pos and ori offsets are defined + if pos_offset is None or pos_offset == {}: # May be {} from empty addict key + pos_offset = (0, 0, 0) + if ori_offset is None or ori_offset == {}: # May be {} from empty addict key + ori_offset = (0, 0, 0, 1) + + pos_offset = th.tensor(pos_offset, dtype=th.float) + ori_offset = th.tensor(ori_offset, dtype=th.float) + + # Sanity check link / parent link combos + root_prim_path = root_prim.GetPrimPath().pathString + if parent_link_name is None or parent_link_name == {}: # May be {} from empty addict key + parent_link_prim = None + else: + parent_path = f"{root_prim_path}/{parent_link_name}" + assert lazy.isaacsim.core.utils.prims.is_prim_path_valid( + parent_path + ), f"Could not find parent link within robot with name {parent_link_name}!" + parent_link_prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(parent_path) + + # If parent link is defined, link prim should NOT exist (this should be a new link) + link_prim_path = f"{root_prim_path}/{link_name}" + link_prim_exists = lazy.isaacsim.core.utils.prims.is_prim_path_valid(link_prim_path) + if parent_link_prim is not None: + assert not link_prim_exists, f"Since parent link is defined, link_name {link_name} must be a link that is NOT pre-existing within the robot's set of links!" + # Manually create a new prim (specified offset) + create_rigid_prim( + stage=stage, + link_prim_path=link_prim_path, + ) + link_prim_xform = lazy.isaacsim.core.prims.SingleXFormPrim(prim_path=link_prim_path) + + # Create fixed joint to connect the two together + create_joint( + prim_path=f"{parent_path}/{parent_link_name}_{link_name}_joint", + joint_type="FixedJoint", + body0=parent_path, + body1=link_prim_path, + joint_frame_in_parent_frame_pos=pos_offset, + joint_frame_in_parent_frame_quat=ori_offset, + ) + + # Set child prim to the appropriate local pose -- this should be the parent local pose transformed by + # the additional offset + parent_prim_xform = lazy.isaacsim.core.prims.SingleXFormPrim(prim_path=parent_path) + parent_pos, parent_quat = parent_prim_xform.get_local_pose() + parent_quat = parent_quat[[1, 2, 3, 0]] + parent_pose = T.pose2mat((th.tensor(parent_pos), th.tensor(parent_quat))) + offset_pose = T.pose2mat((pos_offset, ori_offset)) + child_pose = parent_pose @ offset_pose + link_pos, link_quat = T.mat2pose(child_pose) + link_prim_xform.set_local_pose(link_pos, link_quat[[3, 0, 1, 2]]) + + else: + # Otherwise, link prim MUST exist + assert link_prim_exists, f"Since no parent link is defined, link_name {link_name} must be a link that IS pre-existing within the robot's set of links!" + + # Define functions to generate the desired sensor prim + if sensor_type == "Camera": + create_sensor_prim = lambda parent_prim_path: lazy.pxr.UsdGeom.Camera.Define( + stage, f"{parent_prim_path}/Camera" + ).GetPrim() + elif sensor_type == "Lidar": + create_sensor_prim = lambda parent_prim_path: lazy.omni.kit.commands.execute( + "RangeSensorCreateLidar", + path="/Lidar", + parent=parent_prim_path, + min_range=0.4, + max_range=100.0, + draw_points=False, + draw_lines=False, + horizontal_fov=360.0, + vertical_fov=30.0, + horizontal_resolution=0.4, + vertical_resolution=4.0, + rotation_rate=0.0, + high_lod=False, + yaw_offset=0.0, + enable_semantics=False, + )[1].GetPrim() + elif sensor_type == "VisualSphere": + create_sensor_prim = lambda parent_prim_path: create_primitive_mesh( + prim_path=f"{parent_prim_path}/VisualSphere", + primitive_type="Sphere", + extents=0.01, + stage=stage, + ).GetPrim() + else: + raise ValueError(f"Got unknown sensor type: {sensor_type}!") + + # Create the new prim as a child of the link prim + sensor_prim = create_sensor_prim(parent_prim_path=link_prim_path) + _add_xform_properties(sensor_prim) + + # If sensor prim is a camera, set some default values + if sensor_type == "Camera": + sensor_prim.GetAttribute("focalLength").Set(17.0) + sensor_prim.GetAttribute("clippingRange").Set(lazy.pxr.Gf.Vec2f(0.001, 1000000.0)) + # Refresh visibility + lazy.pxr.UsdGeom.Imageable(sensor_prim).MakeInvisible() + og.sim.render() + lazy.pxr.UsdGeom.Imageable(sensor_prim).MakeVisible() + + # If we didn't have a parent prim defined, we need to add the offset directly to this sensor + if parent_link_prim is None: + sensor_prim.GetAttribute("xformOp:translate").Set(lazy.pxr.Gf.Vec3d(*pos_offset.tolist())) + sensor_prim.GetAttribute("xformOp:orient").Set( + lazy.pxr.Gf.Quatd(*ori_offset[[3, 0, 1, 2]].tolist()) + ) # expects (w,x,y,z) + + +def _find_prim_with_condition(condition, root_prim): + """ + Recursively searches children of @root_prim to find first instance of prim satisfying @condition + + Args: + condition (function): Condition to check. Should satisfy function signature: + + def condition(prim: Usd.Prim) -> bool + + which returns True if the condition is met, else False + + root_prim (Usd.Prim): Root prim to search + + Returns: + None or Usd.Prim: If found, first prim whose prim name includes @name + """ + if condition(root_prim): + return root_prim + + for child in root_prim.GetChildren(): + found_prim = _find_prim_with_condition(condition=condition, root_prim=child) + if found_prim is not None: + return found_prim + + +def _find_prims_with_condition(condition, root_prim): + """ + Recursively searches children of @root_prim to find all instances of prim satisfying @condition + + Args: + condition (function): Condition to check. Should satisfy function signature: + + def condition(prim: Usd.Prim) -> bool + + which returns True if the condition is met, else False + + root_prim (Usd.Prim): Root prim to search + + Returns: + None or Usd.Prim: If found, first prim whose prim name includes @name + """ + found_prims = [] + if condition(root_prim): + found_prims.append(root_prim) + + for child in root_prim.GetChildren(): + found_prims += _find_prims_with_condition(condition=condition, root_prim=child) + + return found_prims + + +def find_prim_with_name(name, root_prim): + """ + Recursively searches children of @root_prim to find first instance of prim including string @name + + Args: + name (str): Name of the prim to search + root_prim (Usd.Prim): Root prim to search + + Returns: + None or Usd.Prim: If found, first prim whose prim name includes @name + """ + return _find_prim_with_condition(condition=lambda prim: name in prim.GetName(), root_prim=root_prim) + + +def find_articulation_root_prim(root_prim): + """ + Recursively searches children of @root_prim to find the articulation root + + Args: + root_prim (Usd.Prim): Root prim to search + + Returns: + None or Usd.Prim: If found, articulation root prim + """ + return _find_prim_with_condition( + condition=lambda prim: prim.HasAPI(lazy.pxr.UsdPhysics.ArticulationRootAPI), root_prim=root_prim + ) + + +def make_joint_fixed(stage, root_prim, joint_name): + """ + Converts a revolute / prismatic joint @joint_name into a fixed joint + + NOTE: This is an in-place operation! + + Args: + stage (Usd.Stage): Current active omniverse stage + root_prim (Usd.Prim): Root prim of the current robot, assumed to be on the current stage + joint_name (str): Joint to convert to be fixed + """ + joint_prim = find_prim_with_name(name=joint_name, root_prim=root_prim) + assert joint_prim is not None, f"Could not find joint prim with name {joint_name}!" + + # Remove its Joint APIs and add Fixed Joint API + joint_type = joint_prim.GetTypeName() + if joint_type != "PhysicsFixedJoint": + assert joint_type in { + "PhysicsRevoluteJoint", + "PhysicsPrismaticJoint", + }, f"Got invalid joint type: {joint_type}. Only PhysicsRevoluteJoint and PhysicsPrismaticJoint are supported!" + + lazy.omni.kit.commands.execute("RemovePhysicsComponentCommand", usd_prim=joint_prim, component=joint_type) + lazy.pxr.UsdPhysics.FixedJoint.Define(stage, joint_prim.GetPrimPath().pathString) + + +def set_link_collision_approximation(stage, root_prim, link_name, approximation_type): + """ + Sets all collision geoms under @link_name to be @approximation type + Args: + approximation_type (str): approximation used for collision. + Can be one of: {"none", "convexHull", "convexDecomposition", "meshSimplification", "sdf", + "boundingSphere", "boundingCube"} + If None, the approximation will use the underlying triangle mesh. + """ + # Sanity check approximation type + assert_valid_key( + key=approximation_type, + valid_keys={ + "none", + "convexHull", + "convexDecomposition", + "meshSimplification", + "sdf", + "boundingSphere", + "boundingCube", + }, + name="collision approximation type", + ) + + # Find the link prim first + link_prim = find_prim_with_name(name=link_name, root_prim=root_prim) + assert link_prim is not None, f"Could not find link prim with name {link_name}!" + + # Iterate through all children that are mesh prims + mesh_prims = find_all_prim_children_with_type(prim_type="Mesh", root_prim=link_prim) + + # For each mesh prim, check if it is collision -- if so, update the approximation type appropriately + for mesh_prim in mesh_prims: + if not mesh_prim.HasAPI(lazy.pxr.UsdPhysics.MeshCollisionAPI): + # This is a visual mesh, so skip + continue + mesh_collision_api = lazy.pxr.UsdPhysics.MeshCollisionAPI(mesh_prim) + + # Make sure to add the appropriate API if we're setting certain values + if approximation_type == "convexHull" and not mesh_prim.HasAPI( + lazy.pxr.PhysxSchema.PhysxConvexHullCollisionAPI + ): + lazy.pxr.PhysxSchema.PhysxConvexHullCollisionAPI.Apply(mesh_prim) + elif approximation_type == "convexDecomposition" and not mesh_prim.HasAPI( + lazy.pxr.PhysxSchema.PhysxConvexDecompositionCollisionAPI + ): + lazy.pxr.PhysxSchema.PhysxConvexDecompositionCollisionAPI.Apply(mesh_prim) + elif approximation_type == "meshSimplification" and not mesh_prim.HasAPI( + lazy.pxr.PhysxSchema.PhysxTriangleMeshSimplificationCollisionAPI + ): + lazy.pxr.PhysxSchema.PhysxTriangleMeshSimplificationCollisionAPI.Apply(mesh_prim) + elif approximation_type == "sdf" and not mesh_prim.HasAPI(lazy.pxr.PhysxSchema.PhysxSDFMeshCollisionAPI): + lazy.pxr.PhysxSchema.PhysxSDFMeshCollisionAPI.Apply(mesh_prim) + elif approximation_type == "none" and not mesh_prim.HasAPI(lazy.pxr.PhysxSchema.PhysxTriangleMeshCollisionAPI): + lazy.pxr.PhysxSchema.PhysxTriangleMeshCollisionAPI.Apply(mesh_prim) + + if approximation_type == "convexHull": + pch_api = lazy.pxr.PhysxSchema.PhysxConvexHullCollisionAPI(mesh_prim) + # Also make sure the maximum vertex count is 60 (max number compatible with GPU) + # https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_physics/rigid-bodies.html#collision-settings + if pch_api.GetHullVertexLimitAttr().Get() is None: + pch_api.CreateHullVertexLimitAttr() + pch_api.GetHullVertexLimitAttr().Set(60) + + mesh_collision_api.GetApproximationAttr().Set(approximation_type) + + +def is_joint(prim, only_articulated=True): + prim_type = prim.GetPrimTypeInfo().GetTypeName().lower() + if only_articulated and "fixed" in prim_type: + return False + return "joint" in prim_type + + +def find_all_joints(root_prim, only_articulated=True): + return _find_prims_with_condition( + condition=lambda x: is_joint(x, only_articulated=only_articulated), + root_prim=root_prim, + ) + + +def is_rigid_body(prim): + prim_type = prim.GetPrimTypeInfo().GetTypeName().lower() + has_rigid_api = prim.HasAPI(lazy.pxr.UsdPhysics.RigidBodyAPI) + return "xform" in prim_type and has_rigid_api + + +def find_all_rigid_bodies(root_prim): + return _find_prims_with_condition( + condition=is_rigid_body, + root_prim=root_prim, + ) + + +def is_mesh(prim): + prim_type = prim.GetPrimTypeInfo().GetTypeName().lower() + return "mesh" in prim_type + + +def find_all_meshes(root_prim): + return _find_prims_with_condition( + condition=is_mesh, + root_prim=root_prim, + ) + + +def create_curobo_cfgs(robot_prim, robot_urdf_path, curobo_cfg, root_link, save_dir, is_holonomic=False): + """ + Creates a set of curobo configs based on @robot_prim and @curobo_cfg + + Args: + robot_prim (Usd.Prim): Top-level prim defining the robot in the current USD stage + robot_urdf_path (str): Path to robot URDF file + curobo_cfg (Dict): Dictionary of relevant curobo information + root_link (str): Name of the robot's root link, BEFORE any holonomic joints are applied + save_dir (str): Path to the directory to save generated curobo files + is_holonomic (bool): Whether the robot has a holonomic base applied or not + """ + robot_name = robot_prim.GetName() + + # Left, then right by default if sorted alphabetically + ee_links = list(sorted(curobo_cfg.eef_to_gripper_info.keys())) + + # Find all joints that have a negative axis specified so we know to flip them in curobo + tree = ET.parse(robot_urdf_path) + root = tree.getroot() + flip_joints = dict() + flip_joint_limits = [] + for joint in root.findall("joint"): + if joint.attrib["type"] != "fixed": + axis = th.round(_space_string_to_tensor(joint.find("axis").attrib["xyz"])) + axis_idx = th.nonzero(axis).squeeze().item() + flip_joints[joint.attrib["name"]] = "XYZ"[axis_idx] + is_negative = (axis[axis_idx] < 0).item() + if is_negative: + flip_joint_limits.append(joint.attrib["name"]) + + def get_joint_upper_limit(root_prim, joint_name): + joint_prim = find_prim_with_name(name=joint_name, root_prim=root_prim) + assert joint_prim is not None, f"Could not find joint prim with name {joint_name}!" + return joint_prim.GetAttribute("physics:upperLimit").Get() + + # The original format from Lula is a list of dicts, so we need to convert to a single dict + if isinstance(curobo_cfg.collision_spheres, list): + collision_spheres = {k: v for c in curobo_cfg.collision_spheres for k, v in c.to_dict().items()} + else: + collision_spheres = curobo_cfg.collision_spheres.to_dict() + + # Generate list of collision link names -- this is simply the list of all link names from the + # collision spheres specification + all_collision_link_names = list(collision_spheres.keys()) + + joint_prims = find_all_joints(robot_prim, only_articulated=True) + all_joint_names = [joint_prim.GetName() for joint_prim in joint_prims] + lock_joints = curobo_cfg.lock_joints.to_dict() if curobo_cfg.lock_joints else {} + if is_holonomic: + # Move the final six joints to the beginning, since the holonomic joints are added at the end + all_joint_names = list(reversed(all_joint_names[-6:])) + all_joint_names[:-6] + lock_joints["base_footprint_z_joint"] = None + lock_joints["base_footprint_rx_joint"] = None + lock_joints["base_footprint_ry_joint"] = None + + default_generated_cfg = { + "usd_robot_root": f"/{robot_prim.GetName()}", + "usd_flip_joints": flip_joints, + "usd_flip_joint_limits": flip_joint_limits, + "base_link": "base_footprint_x" if is_holonomic else root_link, + "ee_link": ee_links[0], + "link_names": ee_links[1:], + "lock_joints": lock_joints, + "extra_links": {}, + "collision_link_names": deepcopy(all_collision_link_names), + "collision_spheres": collision_spheres, + "collision_sphere_buffer": 0.002, + "extra_collision_spheres": {}, + "self_collision_ignore": curobo_cfg.self_collision_ignore.to_dict(), + "self_collision_buffer": curobo_cfg.self_collision_buffer.to_dict(), + "use_global_cumul": True, + "mesh_link_names": deepcopy(all_collision_link_names), + "external_asset_path": None, + "cspace": { + "joint_names": all_joint_names, + "retract_config": None, + "null_space_weight": [1] * len(all_joint_names), + "cspace_distance_weight": [1] * len(all_joint_names), + "max_jerk": 500.0, + "max_acceleration": 15.0, + }, + } + + for eef_link_name, gripper_info in curobo_cfg.eef_to_gripper_info.items(): + attached_obj_link_name = f"attached_object_{eef_link_name}" + for jnt_name in gripper_info["joints"]: + default_generated_cfg["lock_joints"][jnt_name] = None + default_generated_cfg["extra_links"][attached_obj_link_name] = { + "parent_link_name": eef_link_name, + "link_name": attached_obj_link_name, + "fixed_transform": [0, 0, 0, 1, 0, 0, 0], # (x,y,z,w,x,y,z) + "joint_type": "FIXED", + "joint_name": f"{attached_obj_link_name}_joint", + } + default_generated_cfg["collision_link_names"].append(attached_obj_link_name) + default_generated_cfg["extra_collision_spheres"][attached_obj_link_name] = 32 + for link_name in gripper_info["links"]: + if link_name not in default_generated_cfg["self_collision_ignore"]: + default_generated_cfg["self_collision_ignore"][link_name] = [] + default_generated_cfg["self_collision_ignore"][link_name].append(attached_obj_link_name) + default_generated_cfg["mesh_link_names"].append(attached_obj_link_name) + + # Save generated file + Path(save_dir).mkdir(parents=True, exist_ok=True) + save_fpath = f"{save_dir}/{robot_name}_description_curobo_default.yaml" + with open(save_fpath, "w+") as f: + yaml.dump({"robot_cfg": {"kinematics": default_generated_cfg}}, f) + + # Permute the default config to have additional base only / arm only configs + # Only relevant if robot is holonomic + if is_holonomic: + # Create base only config + base_only_cfg = deepcopy(default_generated_cfg) + base_only_cfg["ee_link"] = root_link + base_only_cfg["link_names"] = [] + for jnt_name in all_joint_names: + if jnt_name not in base_only_cfg["lock_joints"] and "base_footprint" not in jnt_name: + # Lock this joint + base_only_cfg["lock_joints"][jnt_name] = None + save_base_fpath = f"{save_dir}/{robot_name}_description_curobo_base.yaml" + with open(save_base_fpath, "w+") as f: + yaml.dump({"robot_cfg": {"kinematics": base_only_cfg}}, f) + + # Create arm only config + arm_only_cfg = deepcopy(default_generated_cfg) + for jnt_name in {"base_footprint_x_joint", "base_footprint_y_joint", "base_footprint_rz_joint"}: + arm_only_cfg["lock_joints"][jnt_name] = None + save_arm_fpath = f"{save_dir}/{robot_name}_description_curobo_arm.yaml" + with open(save_arm_fpath, "w+") as f: + yaml.dump({"robot_cfg": {"kinematics": arm_only_cfg}}, f) + + # Create arm only no torso config + arm_only_no_torso_cfg = deepcopy(arm_only_cfg) + for jnt_name in curobo_cfg.torso_joints: + arm_only_no_torso_cfg["lock_joints"][jnt_name] = None + save_arm_no_torso_fpath = f"{save_dir}/{robot_name}_description_curobo_arm_no_torso.yaml" + with open(save_arm_no_torso_fpath, "w+") as f: + yaml.dump({"robot_cfg": {"kinematics": arm_only_no_torso_cfg}}, f) + + +def resolve_dataset_name(cfg): + """Output dataset for the imported robot (config ``dataset_name`` key, default ``omnigibson-robot-assets``).""" + return cfg.get("dataset_name", "omnigibson-robot-assets") + + +def shift_prim_local_z(prim, z_offset): + """Subtract ``z_offset`` from a prim's local Z translation, adding the translate op if it's missing + or null (5.1 can emit prims without one). + """ + translate_attr = prim.GetAttribute("xformOp:translate") + if translate_attr.IsValid(): + local_pos = translate_attr.Get() + if local_pos is None: + local_pos = lazy.pxr.Gf.Vec3d(0.0, 0.0, 0.0) + translate_attr.Set(lazy.pxr.Gf.Vec3d(local_pos[0], local_pos[1], local_pos[2] - z_offset)) + else: + translate_op = lazy.pxr.UsdGeom.Xformable(prim).AddXformOp( + lazy.pxr.UsdGeom.XformOp.TypeTranslate, lazy.pxr.UsdGeom.XformOp.PrecisionDouble, "" + ) + translate_op.Set(lazy.pxr.Gf.Vec3d(0.0, 0.0, -z_offset)) + + +@click.command(name="import-custom-robot", help=_DOCSTRING) +@click.option( + "--config", + required=True, + type=click.Path(exists=True, dir_okay=False), + help="Absolute path to robot config yaml file to import", +) +def main(config): + # Load config + with open(config, "r") as f: + cfg = Dict(yaml.load(f, yaml.Loader)) + + # Convert URDF -> USD + urdf_path, usd_path, prim = import_og_asset_from_urdf( + category="robot", + model=cfg.name, + dataset_name=resolve_dataset_name(cfg), + urdf_path=cfg.urdf_path, + collision_method=cfg.collision.decompose_method, + coacd_links=cfg.collision.coacd_links, + convex_links=cfg.collision.convex_links, + no_decompose_links=cfg.collision.no_decompose_links, + visual_only_links=cfg.collision.no_collision_links, + merge_fixed_joints=cfg.merge_fixed_joints, + hull_count=cfg.collision.hull_count, + overwrite=cfg.overwrite, + use_usda=True, + ) + + # Get current stage + stage = lazy.isaacsim.core.utils.stage.get_current_stage() + + # Add visual spheres, cameras, and lidars + if cfg.eef_vis_links: + for eef_vis_info in cfg.eef_vis_links: + add_sensor( + stage=stage, + root_prim=prim, + sensor_type="VisualSphere", + link_name=eef_vis_info.link, + parent_link_name=eef_vis_info.parent_link, + pos_offset=eef_vis_info.offset.position, + ori_offset=eef_vis_info.offset.orientation, + ) + if cfg.camera_links: + for camera_info in cfg.camera_links: + add_sensor( + stage=stage, + root_prim=prim, + sensor_type="Camera", + link_name=camera_info.link, + parent_link_name=camera_info.parent_link, + pos_offset=camera_info.offset.position, + ori_offset=camera_info.offset.orientation, + ) + if cfg.lidar_links: + for lidar_info in cfg.lidar_links: + add_sensor( + stage=stage, + root_prim=prim, + sensor_type="Lidar", + link_name=lidar_info.link, + parent_link_name=lidar_info.parent_link, + pos_offset=lidar_info.offset.position, + ori_offset=lidar_info.offset.orientation, + ) + + # Make wheels sphere approximations if requested + if cfg.base_motion.use_sphere_wheels: + for wheel_link in cfg.base_motion.wheel_links: + set_link_collision_approximation( + stage=stage, + root_prim=prim, + link_name=wheel_link, + approximation_type="boundingSphere", + ) + + # Get reference to articulation root link + articulation_root_prim = find_articulation_root_prim(root_prim=prim) + assert articulation_root_prim is not None, "Could not find any valid articulation root prim!" + root_prim_name = articulation_root_prim.GetName() + + # We always want our robot to have its canonical frame corresponding to the bottom surface + # So, we compute the AABB dynamically to calculate the current z-offset, and then apply the offset to the following: + # - root link CoM + # - root link's visual / collision meshes + # - all of the root link's immediate child joints + # - all of the root link's descendant links (all links except self) + + # Compute AABB + bbox_cache = lazy.isaacsim.core.utils.bounds.create_bbox_cache(use_extents_hint=False) + aabb = lazy.isaacsim.core.utils.bounds.compute_aabb(bbox_cache=bbox_cache, prim_path=prim.GetPrimPath().pathString) + z_offset = aabb[2] + + # Update the root link's CoM + com_attr = articulation_root_prim.GetAttribute("physics:centerOfMass") + com = com_attr.Get() + com[2] -= z_offset + com_attr.Set(com) + + # Grab all of the root prim's nested children and joints, and modify their offsets based on AABB z-lower bound + root_meshes = find_all_meshes(root_prim=articulation_root_prim) + for mesh in root_meshes: + shift_prim_local_z(mesh, z_offset) + root_joints = find_all_joints(root_prim=articulation_root_prim, only_articulated=False) + root_prim_path = articulation_root_prim.GetPrimPath().pathString + for joint in root_joints: + body0_targets = joint.GetProperty("physics:body0").GetTargets() + # Don't include any joints where the articulation root link is not the parent + if len(body0_targets) == 0 or body0_targets[0].pathString != root_prim_path: + continue + pos0_attr = joint.GetAttribute("physics:localPos0") + pos0 = pos0_attr.Get() + pos0[2] -= z_offset + pos0_attr.Set(pos0) + + # Update all links that are not the root link + all_links = find_all_rigid_bodies(root_prim=prim) + for link in all_links: + if link == articulation_root_prim: + continue + shift_prim_local_z(link, z_offset) + + # Add holonomic base if requested + if cfg.base_motion.use_holonomic_joints: + # Convert all wheel joints into fixed joints + for wheel_joint in cfg.base_motion.wheel_joints: + make_joint_fixed( + stage=stage, + root_prim=prim, + joint_name=wheel_joint, + ) + + # Remove the articulation root from the original root link + articulation_root_prim.RemoveAPI(lazy.pxr.UsdPhysics.ArticulationRootAPI) + + # Add 6DOF virtual joints ("base_footprint_") + # Create in backwards order so that the child always exists + child_prim = articulation_root_prim + robot_prim_path = prim.GetPrimPath().pathString + for prefix, joint_type, drive_type in zip(("r", ""), ("Revolute", "Prismatic"), ("angular", "linear")): + for axis in ("z", "y", "x"): + joint_suffix = f"{prefix}{axis}" + parent_name = f"base_footprint_{joint_suffix}" + # Create new link + parent_prim_path = f"{robot_prim_path}/{parent_name}" + parent_prim = create_rigid_prim( + stage=stage, + link_prim_path=parent_prim_path, + ) + + # Create new joint + joint_prim_path = f"{parent_prim_path}/{parent_name}_joint" + joint = create_joint( + prim_path=joint_prim_path, + joint_type=f"{joint_type}Joint", + body0=parent_prim_path, + body1=child_prim.GetPrimPath().pathString, + ) + joint.GetAttribute("physics:axis").Set(axis.upper()) + + # Add JointState API, and also Drive API only if the joint is in {x,y,rz} + lazy.pxr.PhysxSchema.JointStateAPI.Apply(joint, drive_type) + if joint_suffix in {"x", "y", "rz"}: + lazy.pxr.UsdPhysics.DriveAPI.Apply(joint, drive_type) + + # Update child + child_prim = parent_prim + + # Re-add the articulation root API to the new virtual footprint link + lazy.pxr.UsdPhysics.ArticulationRootAPI.Apply(parent_prim) + + # Save stage + stage.Save() + + # Import auxiliary files necessary for CuRobo motion planning + if bool(cfg.curobo): + create_curobo_cfgs( + robot_prim=prim, + robot_urdf_path=urdf_path, + root_link=root_prim_name, + curobo_cfg=cfg.curobo, + save_dir="/".join(usd_path.split("/")[:-2]) + "/curobo", + is_holonomic=cfg.base_motion.use_holonomic_joints, + ) + + # Visualize if not headless + if not cfg.headless: + click.echo("The asset has been successfully imported. You can view it and make changes and save if you'd like.") + while True: + og.sim.render() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/robots/robot_control_example.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/robots/robot_control_example.py new file mode 100644 index 0000000000000000000000000000000000000000..b1df3313d776a9c5df6655737afb62a6c871da78 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/robots/robot_control_example.py @@ -0,0 +1,189 @@ +""" +Example script demo'ing robot control. + +Options for random actions, as well as selection of robot action space +""" + +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.macros import gm +from omnigibson.robots import REGISTERED_ROBOTS +from omnigibson.utils.ui_utils import KeyboardRobotController, choose_from_options + +CONTROL_MODES = dict( + random="Use autonomous random actions (default)", + teleop="Use keyboard control", +) + +SCENES = dict( + Rs_int="Realistic interactive home environment (default)", + empty="Empty environment with no objects", +) + +# Don't use GPU dynamics for performance boost +gm.USE_GPU_DYNAMICS = False + + +def choose_controllers(robot, random_selection=False): + """ + For a given robot, iterates over all components of the robot, and returns the requested controller type for each + component. + + :param robot: BaseRobot, robot class from which to infer relevant valid controller options + :param random_selection: bool, if the selection is random (for automatic demo execution). Default False + + :return dict: Mapping from individual robot component (e.g.: base, arm, etc.) to selected controller names + """ + # Create new dict to store responses from user + controller_choices = dict() + + # Grab the default controller config so we have the registry of all possible controller options + default_config = robot._default_controller_config + + # Iterate over all components in robot + controller_names = robot.controller_order + for controller_name in controller_names: + controller_options = default_config[controller_name] + # Select controller + options = list(sorted(controller_options.keys())) + choice = choose_from_options( + options=options, + name=f"{controller_name} controller", + random_selection=random_selection, + ) + + # Add to user responses + controller_choices[controller_name] = choice + + return controller_choices + + +def main(random_selection=False, headless=False, short_exec=False, quickstart=False): + """ + Robot control demo with selection + Queries the user to select a robot, the controllers, a scene and a type of input (random actions or teleop) + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Choose scene to load + scene_model = "Rs_int" + if not quickstart: + scene_model = choose_from_options(options=SCENES, name="scene", random_selection=random_selection) + + # Choose robot to create + robot_name = "fetch" + if not quickstart: + robot_name = choose_from_options( + options=list(sorted(REGISTERED_ROBOTS)), name="robot", random_selection=random_selection + ) + + scene_cfg = dict() + if scene_model == "empty": + scene_cfg["type"] = "Scene" + else: + scene_cfg["type"] = "InteractiveTraversableScene" + scene_cfg["scene_model"] = scene_model + + # Add the robot we want to load + robot0_cfg = dict() + robot0_cfg["model"] = robot_name + robot0_cfg["obs_modalities"] = ["rgb"] + robot0_cfg["action_type"] = "continuous" + robot0_cfg["action_normalize"] = True + + # Compile config + cfg = dict(scene=scene_cfg, robots=[robot0_cfg]) + + # Create the environment + env = og.Environment(configs=cfg) + + # Choose robot controller to use + robot = env.scene.robots[0] + controller_choices = { + "base": "DifferentialDriveController", + "arm_0": "InverseKinematicsController", + "gripper_0": "MultiFingerGripperController", + "camera": "JointController", + } + if not quickstart: + controller_choices = choose_controllers(robot=robot, random_selection=random_selection) + + # Choose control mode + if random_selection: + control_mode = "random" + elif quickstart: + control_mode = "teleop" + else: + control_mode = choose_from_options(options=CONTROL_MODES, name="control mode") + + # Update the control mode of the robot + controller_config = {component: {"name": name} for component, name in controller_choices.items()} + robot.reload_controllers(controller_config=controller_config) + + # Because the controllers have been updated, we need to update the initial state so the correct controller state + # is preserved + env.scene.update_initial_file() + + # Update the simulator's viewer camera's pose so it points towards the robot + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([1.46949, -3.97358, 2.21529]), + orientation=th.tensor([0.56829048, 0.09569975, 0.13571846, 0.80589577]), + ) + + # Reset environment and robot + env.reset() + robot.reset() + + # Create teleop controller + action_generator = KeyboardRobotController(robot=robot) + + # Register custom binding to reset the environment + action_generator.register_custom_keymapping( + key=lazy.carb.input.KeyboardInput.R, + description="Reset the robot", + callback_fn=lambda: env.reset(), + ) + + # Print out relevant keyboard info if using keyboard teleop + if control_mode == "teleop": + action_generator.print_keyboard_teleop_info() + + # Other helpful user info + print("Running demo.") + print("Press ESC to quit") + + # Loop control until user quits + max_steps = -1 if not short_exec else 100 + step = 0 + + random_action = None + while step != max_steps: + if control_mode == "random": + # Sample new random action every 30 steps + if step % 30 == 0: + random_action = action_generator.get_random_action() * 0.05 + action = random_action + else: + action = action_generator.get_teleop_action() + + env.step(action=action) + step += 1 + + # Always shut down the environment cleanly at the end + og.shutdown() + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Teleoperate a robot in a BEHAVIOR scene.") + + parser.add_argument( + "--quickstart", + action="store_true", + help="Whether the example should be loaded with default settings for a quick start.", + ) + args = parser.parse_args() + main(quickstart=args.quickstart) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/scenes/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/scenes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/scenes/scene_selector.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/scenes/scene_selector.py new file mode 100644 index 0000000000000000000000000000000000000000..6c69c3a5c3b07477f61ff7af189887a037544ac2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/scenes/scene_selector.py @@ -0,0 +1,66 @@ +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.macros import gm +from omnigibson.utils.asset_utils import get_available_behavior_1k_scenes +from omnigibson.utils.ui_utils import choose_from_options, KeyboardEventHandler +from omnigibson.utils.constants import STRUCTURE_CATEGORIES + +# Configure macros for maximum performance +gm.USE_GPU_DYNAMICS = True +gm.ENABLE_OBJECT_STATES = False +gm.ENABLE_TRANSITION_RULES = False + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Prompts the user to select any available interactive scene and loads it. + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Choose the scene model to load + scenes = get_available_behavior_1k_scenes() + scene_model = choose_from_options(options=scenes, name="scene model", random_selection=random_selection) + + cfg = { + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": scene_model, + }, + } + + # Check if we want to quick load or full load the scene + load_options = { + "Quick": "Only load the building assets (i.e.: the floors, walls, ceilings)", + "Full": "Load all interactive objects in the scene", + } + load_mode = choose_from_options(options=load_options, name="load mode", random_selection=random_selection) + if load_mode == "Quick": + cfg["scene"]["load_object_categories"] = list(STRUCTURE_CATEGORIES) + + # Load the environment + env = og.Environment(configs=cfg) + + # Allow user to move camera more easily + if not gm.HEADLESS: + og.sim.enable_viewer_camera_teleoperation() + + KeyboardEventHandler.add_keyboard_callback( + key=lazy.carb.input.KeyboardInput.ESCAPE, + callback_fn=lambda: og.shutdown(), + ) + + print("Running demo.") + print("Press ESC to quit") + + # Loop indefinitely + steps = 0 + max_steps = -1 if not short_exec else 100 + while steps != max_steps: + env.step([]) + steps += 1 + + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/scenes/scene_tour_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/scenes/scene_tour_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..605072a55eb662701819d055142d4bdb1bf44801 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/scenes/scene_tour_demo.py @@ -0,0 +1,115 @@ +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.macros import gm +from omnigibson.utils.asset_utils import get_available_behavior_1k_scenes +from omnigibson.utils.ui_utils import KeyboardEventHandler, choose_from_options +from omnigibson.utils.constants import STRUCTURE_CATEGORIES + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Prompts the user to select any available interactive scene and loads it. + + It sets the camera to various poses and records images, and then generates a trajectory from a set of waypoints + and records the resulting video. + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Make sure the example is not being run headless. If so, terminate early + if gm.HEADLESS: + print("This demo should only be run not headless! Exiting early.") + og.shutdown() + + # Choose the scene model to load + scenes = get_available_behavior_1k_scenes() + scene_model = choose_from_options(options=scenes, name="scene model", random_selection=random_selection) + print(f"scene model: {scene_model}") + + cfg = { + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": scene_model, + }, + } + + # Check if we want to quick load or full load the scene + load_options = { + "Quick": "Only load the building assets (i.e.: the floors, walls, ceilings)", + "Full": "Load all interactive objects in the scene", + } + load_mode = choose_from_options(options=load_options, name="load mode", random_selection=random_selection) + if load_mode == "Quick": + cfg["scene"]["load_object_categories"] = list(STRUCTURE_CATEGORIES) + + # Load the environment + env = og.Environment(configs=cfg) + + # Allow user to teleoperate the camera + cam_mover = og.sim.enable_viewer_camera_teleoperation() + + # Create a keyboard event handler for generating waypoints + waypoints = [] + + def add_waypoint(): + nonlocal waypoints + pos = cam_mover.cam.get_position_orientation()[0] + print(f"Added waypoint at {pos}") + waypoints.append(pos) + + def clear_waypoints(): + nonlocal waypoints + print("Cleared all waypoints!") + waypoints = [] + + def record_trajectory(): + if len(waypoints) < 3: + print( + f"Need at least 3 waypoints to record a trajectory (currently have {len(waypoints)}). Press X to add waypoints." + ) + return + cam_mover.record_trajectory_from_waypoints( + waypoints=th.stack(waypoints), + per_step_distance=0.02, + fps=30, + steps_per_frame=1, + fpath=None, # This corresponds to the default path inferred from cam_mover.save_dir + ) + + KeyboardEventHandler.initialize() + KeyboardEventHandler.add_keyboard_callback( + key=lazy.carb.input.KeyboardInput.X, + callback_fn=add_waypoint, + ) + KeyboardEventHandler.add_keyboard_callback( + key=lazy.carb.input.KeyboardInput.C, + callback_fn=clear_waypoints, + ) + KeyboardEventHandler.add_keyboard_callback( + key=lazy.carb.input.KeyboardInput.J, + callback_fn=record_trajectory, + ) + KeyboardEventHandler.add_keyboard_callback( + key=lazy.carb.input.KeyboardInput.ESCAPE, + callback_fn=lambda: og.shutdown(), + ) + + # Print out additional keyboard commands + print("\t X: Save the current camera pose as a waypoint") + print("\t C: Clear all waypoints") + print("\t J: Record the camera trajectory from the current set of waypoints") + print("\t ESC: Terminate the demo") + + # Loop indefinitely + steps = 0 + max_steps = -1 if not short_exec else 100 + while steps != max_steps: + env.step([]) + steps += 1 + + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/scenes/traversability_map_example.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/scenes/traversability_map_example.py new file mode 100644 index 0000000000000000000000000000000000000000..b5420156da76385c13d8b051134b5cd22b772f1c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/scenes/traversability_map_example.py @@ -0,0 +1,39 @@ +import os + +import cv2 +import matplotlib.pyplot as plt +import torch as th + +import omnigibson as og +from omnigibson.utils.asset_utils import get_available_behavior_1k_scenes, get_scene_path +from omnigibson.utils.ui_utils import choose_from_options + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Traversable map demo + Loads the floor plan and obstacles for the requested scene, and overlays them in a visual figure such that the + highlighted area reflects the traversable (free-space) area + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + scenes = get_available_behavior_1k_scenes() + scene_model = choose_from_options(options=scenes, name="scene model", random_selection=random_selection) + print(f"Generating traversability map for scene {scene_model}") + + trav_map_size = 200 + trav_map_erosion = 2 + + trav_map = cv2.imread(os.path.join(get_scene_path(scene_model), "layout", "floor_trav_0.png")) + trav_map = cv2.resize(trav_map, (trav_map_size, trav_map_size)) + trav_map = cv2.erode(trav_map, th.ones((trav_map_erosion, trav_map_erosion)).cpu().numpy()) + + if not headless: + plt.figure(figsize=(12, 12)) + plt.imshow(trav_map) + plt.title(f"Traversable area of {scene_model} scene") + plt.show() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/simulator/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/simulator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/simulator/sim_save_load_example.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/simulator/sim_save_load_example.py new file mode 100644 index 0000000000000000000000000000000000000000..6a29d03996b9396d3b749982feecc2eb17af4c1f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/simulator/sim_save_load_example.py @@ -0,0 +1,94 @@ +import os + +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.utils.ui_utils import KeyboardEventHandler + +TEST_OUT_PATH = "" # Define output directory here. + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Prompts the user to select whether they are saving or loading an environment, and interactively + shows how an environment can be saved or restored. + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + cfg = { + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": "Rs_int", + "load_object_categories": ["floors", "walls", "bed", "bottom_cabinet", "chair"], + }, + "robots": [ + { + "type": "Turtlebot", + "obs_modalities": ["rgb", "depth"], + }, + ], + } + + # Create the environment + env = og.Environment(configs=cfg) + + # Set the camera to a good angle + def set_camera_pose(): + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([-0.229375, -3.40576, 7.26143]), + orientation=th.tensor([0.27619733, -0.00230233, -0.00801152, 0.9610648]), + ) + + set_camera_pose() + + # Give user instructions, and then loop until completed + completed = short_exec + if not short_exec and not random_selection: + # Notify user to manipulate environment until ready, then press Z to exit + print() + print("Modify the scene by SHIFT + left clicking objects and dragging them. Once finished, press Z.") + + # Register callback so user knows to press space once they're done manipulating the scene + def complete_loop(): + nonlocal completed + completed = True + + KeyboardEventHandler.add_keyboard_callback(lazy.carb.input.KeyboardInput.Z, complete_loop) + while not completed: + action_lo, action_hi = -1, 1 + env.step(th.rand(env.scene.robots[0].action_dim) * (action_hi - action_lo) + action_lo) + + print("Completed scene modification, saving scene...") + save_path = os.path.join(TEST_OUT_PATH, "saved_stage.json") + og.sim.save(json_paths=[save_path]) + + print("Re-loading scene...") + og.clear() + og.sim.restore(scene_files=[save_path]) + + # env is no longer valid after og.clear() + del env + + # Take a sim step and play + og.sim.step() + og.sim.play() + set_camera_pose() + + # Loop until user terminates + completed = short_exec + if not short_exec and not random_selection: + # Notify user to manipulate environment until ready, then press Z to exit + print() + print("View reloaded scene. Once finished, press Z.") + # Register callback so user knows to press space once they're done manipulating the scene + KeyboardEventHandler.add_keyboard_callback(lazy.carb.input.KeyboardInput.Z, complete_loop) + while not completed: + og.sim.step() + + # Always shut down the environment cleanly at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/teleoperation/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/teleoperation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/teleoperation/robot_teleoperate_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/teleoperation/robot_teleoperate_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..0eeb775e143ad17643e3e8a02959add0fef8a840 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/teleoperation/robot_teleoperate_demo.py @@ -0,0 +1,140 @@ +""" +Example script for using external devices to teleoperate a robot. +""" + +import omnigibson as og +from omnigibson.utils.ui_utils import choose_from_options + +ROBOTS = { + "FrankaPanda": "Franka Emika Panda (default)", + "Fetch": "Mobile robot with one arm", + "Tiago": "Mobile robot with two arms", +} +TELEOP_METHOD = { + "keyboard": "Keyboard (default)", + "spacemouse": "SpaceMouse", + "oculus": "Oculus Quest", + "vision": "Human Keypoints with Camera", +} + + +def main(): + """ + Spawn a robot in an empty scene with a breakfast table and some toys. + Users can try pick and place the toy into the basket using selected external devices and robot of their choice. + """ + from telemoma.configs.base_config import teleop_config + from telemoma.utils.camera_utils import RealSenseCamera + + from omnigibson.utils.teleop_utils import TeleopSystem + + robot_name = choose_from_options(options=ROBOTS, name="robot") + arm_teleop_method = choose_from_options(options=TELEOP_METHOD, name="robot arm teleop method") + if robot_name != "FrankaPanda": + base_teleop_method = choose_from_options(options=TELEOP_METHOD, name="robot base teleop method") + else: + base_teleop_method = "keyboard" # Dummy value since FrankaPanda does not have a base + # Generate teleop config + teleop_config.arm_left_controller = arm_teleop_method + teleop_config.arm_right_controller = arm_teleop_method + teleop_config.base_controller = base_teleop_method + teleop_config.interface_kwargs["keyboard"] = {"arm_speed_scaledown": 0.04} + teleop_config.interface_kwargs["spacemouse"] = {"arm_speed_scaledown": 0.04} + if arm_teleop_method == "vision" or base_teleop_method == "vision": + teleop_config.interface_kwargs["vision"] = {"camera": RealSenseCamera()} + + # Create the config for generating the environment we want + scene_cfg = {"type": "Scene"} + # Add the robot we want to load + robot_cfg = { + "type": robot_name, + "obs_modalities": ["rgb"], + "action_normalize": False, + "grasping_mode": "assisted", + } + arms = ["left", "right"] if robot_name == "Tiago" else ["0"] + robot_cfg["controller_config"] = {} + for arm in arms: + robot_cfg["controller_config"][f"arm_{arm}"] = { + "name": "InverseKinematicsController", + "command_input_limits": None, + } + robot_cfg["controller_config"][f"gripper_{arm}"] = { + "name": "MultiFingerGripperController", + "command_input_limits": (0.0, 1.0), + "mode": "smooth", + } + object_cfg = [ + { + "type": "DatasetObject", + "prim_path": "/World/breakfast_table", + "name": "breakfast_table", + "category": "breakfast_table", + "model": "kwmfdg", + "bounding_box": [2, 1, 0.4], + "position": [0.8, 0, 0.3], + "orientation": [0, 0, 0.707, 0.707], + }, + { + "type": "DatasetObject", + "prim_path": "/World/frail", + "name": "frail", + "category": "frail", + "model": "zmjovr", + "scale": [2, 2, 2], + "position": [0.6, -0.35, 0.5], + }, + { + "type": "DatasetObject", + "prim_path": "/World/toy_figure1", + "name": "toy_figure1", + "category": "toy_figure", + "model": "issvzv", + "scale": [0.75, 0.75, 0.75], + "position": [0.6, 0, 0.5], + }, + { + "type": "DatasetObject", + "prim_path": "/World/toy_figure2", + "name": "toy_figure2", + "category": "toy_figure", + "model": "nncqfn", + "scale": [0.75, 0.75, 0.75], + "position": [0.6, 0.15, 0.5], + }, + { + "type": "DatasetObject", + "prim_path": "/World/toy_figure3", + "name": "toy_figure3", + "category": "toy_figure", + "model": "eulekw", + "scale": [0.25, 0.25, 0.25], + "position": [0.6, 0.3, 0.5], + }, + ] + cfg = dict(scene=scene_cfg, robots=[robot_cfg], objects=object_cfg) + + # Create the environment + env = og.Environment(configs=cfg) + env.reset() + # update viewer camera pose + og.sim.viewer_camera.set_position_orientation(position=[-0.22, 0.99, 1.09], orientation=[-0.14, 0.47, 0.84, -0.23]) + # Start teleoperation system + robot = env.scene.robots[0] + + # Initialize teleoperation system + teleop_sys = TeleopSystem(config=teleop_config, robot=robot, show_control_marker=True) + teleop_sys.start() + + # main simulation loop + for _ in range(10000): + action = teleop_sys.get_action(teleop_sys.get_obs()) + env.step(action) + + # Shut down the environment cleanly at the end + teleop_sys.stop() + og.clear() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/teleoperation/vr_robot_control_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/teleoperation/vr_robot_control_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1af8c1aa610bab9a3d9ab3a5c674a4676c2a50 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/teleoperation/vr_robot_control_demo.py @@ -0,0 +1,100 @@ +""" +Example script for interacting with OmniGibson scenes with VR and BehaviorRobot. +""" + +import omnigibson as og +from omnigibson.macros import gm +from omnigibson.utils.teleop_utils import OVXRSystem + +gm.ENABLE_OBJECT_STATES = False +gm.ENABLE_TRANSITION_RULES = False + +CONTROLLER_VISIBLE = True +ENABLE_CAMERA_LIMITS = False + + +def main(): + """ + Spawn a BehaviorRobot in Rs_int and users can navigate around and interact with the scene using VR. + """ + # Create the config for generating the environment we want + scene_cfg = {"type": "InteractiveTraversableScene", "scene_model": "Rs_int"} + robot0_cfg = { + "type": "R1", + "obs_modalities": ["rgb"], + "controller_config": { + "arm_left": { + "name": "InverseKinematicsController", + "mode": "absolute_pose", + "command_input_limits": None, + "command_output_limits": None, + }, + "arm_right": { + "name": "InverseKinematicsController", + "mode": "absolute_pose", + "command_input_limits": None, + "command_output_limits": None, + }, + "gripper_left": {"name": "MultiFingerGripperController", "command_input_limits": "default"}, + "gripper_right": {"name": "MultiFingerGripperController", "command_input_limits": "default"}, + }, + "action_normalize": False, + "reset_joint_pos": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + -1.8000, + -0.8000, + 0.0000, + -0.0068, + 0.0059, + 2.6054, + 2.5988, + -1.4515, + -1.4478, + -0.0065, + 0.0052, + 1.5670, + -1.5635, + -1.1428, + 1.1610, + 0.0087, + 0.0087, + 0.0087, + 0.0087, + ], + } + cfg = dict(scene=scene_cfg, robots=[robot0_cfg]) + + # Create the environment + env = og.Environment(configs=cfg) + env.reset() + # start vrsys + vrsys = OVXRSystem( + robot=env.scene.robots[0], + show_control_marker=CONTROLLER_VISIBLE, + system="SteamVR", + eef_tracking_mode="controller", + align_anchor_to="camera", + # roll, pitch, yaw + view_angle_limits=[180, 30, 30] if ENABLE_CAMERA_LIMITS else None, + ) + vrsys.start() + + for _ in range(3000): + # update the VR system + vrsys.update() + # get the action from the VR system and step the environment + env.step(vrsys.get_robot_teleop_action()) + + print("Cleaning up...") + vrsys.stop() + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/teleoperation/vr_scene_tour_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/teleoperation/vr_scene_tour_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..bff08de30c383a925f3f208d88ef713c6d6fa4fb --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/teleoperation/vr_scene_tour_demo.py @@ -0,0 +1,102 @@ +""" +Example script for interacting with OmniGibson scenes with VR. +""" + +import sys +from typing import Optional +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.macros import gm +from omnigibson.utils.asset_utils import get_available_behavior_1k_scenes +from omnigibson.utils.teleop_utils import OVXRSystem +from omnigibson.utils.ui_utils import KeyboardEventHandler, choose_from_options + +gm.ENABLE_OBJECT_STATES = False +gm.ENABLE_TRANSITION_RULES = False + + +def main(scene_model: Optional[str] = None): + """ + Users can navigate around and interact with a selected scene using VR. + """ + + # Choose the scene model to load + if not scene_model: + scenes = get_available_behavior_1k_scenes() + scene_model = choose_from_options(options=scenes, name="scene model") + + # Create the config for generating the environment we want + scene_cfg = {"type": "InteractiveTraversableScene", "scene_model": scene_model} + cfg = dict(scene=scene_cfg) + + # Create the environment + env = og.Environment(configs=cfg) + env.reset() + # start vrsys + vrsys = OVXRSystem( + robot=None, + show_control_marker=True, + system="SteamVR", + eef_tracking_mode="disabled", + align_anchor_to="touchpad", + ) + vrsys.start() + # set headset position to be 1m above ground and facing +x + vrsys.xr_core.schedule_set_camera( + vrsys.og2xr(th.tensor([0.0, 0.0, 1.0]), th.tensor([-0.5, 0.5, 0.5, -0.5])).numpy() + ) + + # main simulation loop + is_done_with_sim = False + + def _exit(): + nonlocal is_done_with_sim + is_done_with_sim = True + + KeyboardEventHandler.add_keyboard_callback( + key=lazy.carb.input.KeyboardInput.SPACE, + callback_fn=_exit, + ) + stepping = False + + def _toggle_stepping(): + nonlocal stepping + stepping = not stepping + + KeyboardEventHandler.add_keyboard_callback( + key="right_a", + callback_fn=_toggle_stepping, + ) + should_reset = False + + def _queue_reset(): + nonlocal should_reset + should_reset = True + + KeyboardEventHandler.add_keyboard_callback( + key="right_b", + callback_fn=_queue_reset, + ) + while not is_done_with_sim: + # step the VR system to get the latest data from VR runtime + vrsys.update(optimized_for_tour=True) + if stepping: + og.sim.step() + else: + og.sim.render() + if should_reset: + env.reset() + should_reset = False + + # Shut down the environment cleanly at the end + vrsys.stop() + og.clear() + + +if __name__ == "__main__": + scene_model = None + if len(sys.argv) > 1: + scene_model = sys.argv[1] + main(scene_model=scene_model) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/curobo_example.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/curobo_example.py new file mode 100644 index 0000000000000000000000000000000000000000..61a77f2270b993fb16b110cb91ce8fcda4c76ba3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/curobo_example.py @@ -0,0 +1,370 @@ +import math + +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.action_primitives.curobo import CuRoboEmbodimentSelection, CuRoboMotionGenerator +from omnigibson.utils.ui_utils import choose_from_options + + +def plan_trajectory( + cmg, target_pos, target_quat, emb_sel=CuRoboEmbodimentSelection.DEFAULT, attached_obj=None, attached_obj_scale=None +): + # Generate collision-free trajectories to the sampled eef poses (including self-collisions) + successes, traj_paths = cmg.compute_trajectories( + target_pos=target_pos, + target_quat=target_quat, + is_local=False, + max_attempts=100, + timeout=60.0, + ik_fail_return=50, + enable_finetune_trajopt=True, + finetune_attempts=1, + return_full_result=False, + success_ratio=1.0, + attached_obj=attached_obj, + attached_obj_scale=attached_obj_scale, + emb_sel=emb_sel, + ) + return successes, traj_paths + + +def execute_trajectory(q_traj, env, robot, attached_obj): + for i, q in enumerate(q_traj): + q = set_gripper_joint_positions(robot, q, attached_obj) + action = robot.q_to_action(q) + print(f"Executing waypoint {i}/{len(q_traj)}") + env.step(action) + + +def plan_and_execute_trajectory( + cmg, target_pos, target_quat, emb_sel, attached_obj, attached_obj_scale, eef_markers, env, robot, dry_run=False +): + successes, traj_paths = plan_trajectory(cmg, target_pos, target_quat, emb_sel, attached_obj, attached_obj_scale) + success, traj_path = successes[0], traj_paths[0] + # Move the markers to the desired eef positions + for marker in eef_markers: + marker.set_position_orientation(position=th.tensor([100, 100, 100])) + for target_link, marker in zip(target_pos.keys(), eef_markers): + marker.set_position_orientation(position=target_pos[target_link]) + if success: + print("Successfully planned trajectory") + if not dry_run: + q_traj = cmg.path_to_joint_trajectory(traj_path, get_full_js=True, emb_sel=emb_sel).cpu().float() + q_traj = cmg.add_linearly_interpolated_waypoints(traj=q_traj, max_inter_dist=0.01) + execute_trajectory(q_traj, env, robot, attached_obj) + else: + print("Failed to plan trajectory") + + +def set_gripper_joint_positions(robot, q, attached_obj): + # Overwrite the gripper joint positions based on attached_obj + joint_names = list(robot.joints.keys()) + for arm, finger_joints in robot.finger_joints.items(): + close_gripper = attached_obj is not None and robot.eef_link_names[arm] in attached_obj + for finger_joint in finger_joints: + idx = joint_names.index(finger_joint.joint_name) + q[idx] = finger_joint.lower_limit if close_gripper else finger_joint.upper_limit + return q + + +def control_gripper(env, robot, attached_obj): + # Control the gripper to open or close, while keeping the rest of the robot still + q = robot.get_joint_positions() + q = set_gripper_joint_positions(robot, q, attached_obj) + action = robot.q_to_action(q) + num_repeat = 30 + print(f"Gripper (attached_obj={attached_obj})") + for _ in range(num_repeat): + env.step(action) + + +def main(random_selection=False, headless=False, short_exec=False): + # Ask the user whether they want online object sampling or not + robot_options = ["R1", "Tiago"] + robot_type = choose_from_options(options=robot_options, name="robot options", random_selection=random_selection) + + robot_cfg = { + "type": robot_type, + "obs_modalities": "rgb", + "position": [0, 0, 0], + "orientation": [0, 0, 0, 1], + "self_collisions": True, + "action_normalize": False, + "grasping_mode": "sticky", + "controller_config": { + "base": { + "name": "HolonomicBaseJointController", + "motor_type": "position", + "command_input_limits": None, + "use_impedances": False, + }, + "trunk": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "arm_left": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "arm_right": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "gripper_left": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "gripper_right": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + }, + } + if robot_type == "Tiago": + robot_cfg["controller_config"]["camera"] = { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + } + + # Create env + cfg = { + "env": { + "action_frequency": 30, + "physics_frequency": 300, + }, + "scene": { + "type": "Scene", + }, + "objects": [ + { + "type": "PrimitiveObject", + "name": "eef_marker_0", + "primitive_type": "Sphere", + "radius": 0.05, + "visual_only": True, + "position": [0, 0, 0], + "orientation": [0, 0, 0, 1], + "rgba": [1, 0, 0, 1], + }, + { + "type": "PrimitiveObject", + "name": "eef_marker_1", + "primitive_type": "Sphere", + "radius": 0.05, + "visual_only": True, + "position": [0, 0, 0], + "orientation": [0, 0, 0, 1], + "rgba": [0, 1, 0, 1], + }, + { + "type": "DatasetObject", + "name": "table", + "category": "breakfast_table", + "model": "rjgmmy", + "position": [2, 0, 0.41], + "orientation": [0, 0, 0, 1], + }, + { + "type": "DatasetObject", + "name": "cologne", + "category": "bottle_of_cologne", + "model": "lyipur", + "position": [1.6, 0.15, 0.65], + "orientation": T.euler2quat(th.tensor([0, 0, math.pi / 2])), + }, + { + "type": "DatasetObject", + "name": "fridge", + "category": "fridge", + "model": "dszchb", + "position": [2, 1, 0.86], + "orientation": T.euler2quat(th.tensor([0, 0, -math.pi / 2])), + }, + ], + "robots": [robot_cfg], + } + + env = og.Environment(configs=cfg) + robot = env.scene.robots[0] + eef_markers = [env.scene.object_registry("name", f"eef_marker_{i}") for i in range(2)] + + # Create CuRobo instance + cmg = CuRoboMotionGenerator( + robot=robot, + batch_size=1, + use_cuda_graph=True, + ) + + table = env.scene.object_registry("name", "table") + cologne = env.scene.object_registry("name", "cologne") + fridge = env.scene.object_registry("name", "fridge") + cologne_scale = 0.95 + fridge_door_scale = 0.6 + if robot_type == "R1": + table_local_pose = (th.tensor([-1.1, 0.0, -0.402]), th.tensor([0.0, 0.0, 0.0, 1.0])) + cologne_local_pose = (th.tensor([0.0, 0.0, 0.04]), th.tensor([0.5, -0.5, 0.5, 0.5])) + fridge_local_pose = (th.tensor([-0.45, -1.2, -0.8576]), T.euler2quat(th.tensor([0.0, 0.0, math.pi / 2.0]))) + fridge_door_local_pose = ( + th.tensor([-0.28, -0.37, 0.15]), + T.euler2quat(th.tensor([-math.pi / 2, -math.pi / 2, 0.0])), + ) + fridge_door_open_local_pose = ( + th.tensor([0.35, -0.90, 0.15]), + T.euler2quat(th.tensor([0.0, -math.pi / 2, 0.0])), + ) + fridge_place_local_pose = ( + th.tensor([-0.15, -0.20, 0.5]), + T.euler2quat(th.tensor([-math.pi / 2, -math.pi / 2, 0.0])), + ) + elif robot_type == "Tiago": + table_local_pose = (th.tensor([-1.1, 0.0, -0.402]), th.tensor([0.0, 0.0, 0.0, 1.0])) + cologne_local_pose = (th.tensor([0.0, 0.0, 0.04]), th.tensor([0.5, -0.5, 0.5, 0.5])) + fridge_local_pose = (th.tensor([-0.55, -1.25, -0.8576]), T.euler2quat(th.tensor([0.0, 0.0, math.pi / 2.0]))) + fridge_door_local_pose = ( + th.tensor([-0.28, -0.37, 0.15]), + T.euler2quat(th.tensor([-math.pi / 2, -math.pi / 2, 0.0])), + ) + fridge_door_open_local_pose = ( + th.tensor([0.35, -0.97, 0.15]), + T.euler2quat(th.tensor([0.0, -math.pi / 2, 0.0])), + ) + fridge_place_local_pose = ( + th.tensor([-0.10, -0.15, 0.5]), + T.euler2quat(th.tensor([-math.pi / 2, -math.pi / 2, 0.0])), + ) + else: + raise ValueError(f"Unknown robot type: {robot_type}") + + # Set random seed for reproducibility + th.manual_seed(1) + + # Navigate to table (base) + table_nav_pos, table_nav_quat = T.pose_transform(*table.get_position_orientation(), *table_local_pose) + target_pos = {robot.base_footprint_link_name: table_nav_pos} + target_quat = {robot.base_footprint_link_name: table_nav_quat} + emb_sel = CuRoboEmbodimentSelection.BASE + attached_obj = None + attached_obj_scale = None + plan_and_execute_trajectory( + cmg, target_pos, target_quat, emb_sel, attached_obj, attached_obj_scale, eef_markers, env, robot + ) + + # Record reset pose + left_hand_reset_pos, left_hand_reset_quat = robot.get_eef_pose(arm="left") + right_hand_reset_pos, right_hand_reset_quat = robot.get_eef_pose(arm="right") + + # Grasp cologne (left hand) + left_hand_pos, left_hand_quat = T.pose_transform(*cologne.get_position_orientation(), *cologne_local_pose) + right_hand_pos, right_hand_quat = robot.get_eef_pose(arm="right") + target_pos = {robot.eef_link_names["left"]: left_hand_pos} + target_quat = {robot.eef_link_names["left"]: left_hand_quat} + emb_sel = CuRoboEmbodimentSelection.ARM + attached_obj = None + attached_obj_scale = None + plan_and_execute_trajectory( + cmg, target_pos, target_quat, emb_sel, attached_obj, attached_obj_scale, eef_markers, env, robot + ) + attached_obj = {robot.eef_link_names["left"]: cologne.root_link} + control_gripper(env, robot, attached_obj) + assert robot._ag_obj_in_hand["left"] == cologne and robot._ag_obj_in_hand["right"] is None + + # Reset to reset pose (both hands) + target_pos = { + robot.eef_link_names["left"]: left_hand_reset_pos, + robot.eef_link_names["right"]: right_hand_reset_pos, + } + target_quat = { + robot.eef_link_names["left"]: left_hand_reset_quat, + robot.eef_link_names["right"]: right_hand_reset_quat, + } + emb_sel = CuRoboEmbodimentSelection.ARM + attached_obj = {robot.eef_link_names["left"]: cologne.root_link} + attached_obj_scale = {robot.eef_link_names["left"]: cologne_scale} + plan_and_execute_trajectory( + cmg, target_pos, target_quat, emb_sel, attached_obj, attached_obj_scale, eef_markers, env, robot + ) + + # Navigate to fridge (base) + fridge_nav_pos, fridge_nav_quat = T.pose_transform(*fridge.get_position_orientation(), *fridge_local_pose) + target_pos = {robot.base_footprint_link_name: fridge_nav_pos} + target_quat = {robot.base_footprint_link_name: fridge_nav_quat} + emb_sel = CuRoboEmbodimentSelection.BASE + attached_obj = {robot.eef_link_names["left"]: cologne.root_link} + attached_obj_scale = {robot.eef_link_names["left"]: cologne_scale} + plan_and_execute_trajectory( + cmg, target_pos, target_quat, emb_sel, attached_obj, attached_obj_scale, eef_markers, env, robot + ) + + # Grasp fridge door (right hand) + right_hand_pos, right_hand_quat = T.pose_transform(*fridge.get_position_orientation(), *fridge_door_local_pose) + target_pos = {robot.eef_link_names["right"]: right_hand_pos} + target_quat = {robot.eef_link_names["right"]: right_hand_quat} + emb_sel = CuRoboEmbodimentSelection.ARM + attached_obj = {robot.eef_link_names["left"]: cologne.root_link} + attached_obj_scale = {robot.eef_link_names["left"]: cologne_scale} + plan_and_execute_trajectory( + cmg, target_pos, target_quat, emb_sel, attached_obj, attached_obj_scale, eef_markers, env, robot + ) + attached_obj = { + robot.eef_link_names["left"]: cologne.root_link, + robot.eef_link_names["right"]: fridge.links["link_0"], + } + control_gripper(env, robot, attached_obj) + assert robot._ag_obj_in_hand["left"] == cologne and robot._ag_obj_in_hand["right"] == fridge + + # Pull fridge door (right hand) + right_hand_pos, right_hand_quat = T.pose_transform(*fridge.get_position_orientation(), *fridge_door_open_local_pose) + target_pos = {robot.eef_link_names["right"]: right_hand_pos} + target_quat = {robot.eef_link_names["right"]: right_hand_quat} + emb_sel = CuRoboEmbodimentSelection.DEFAULT + attached_obj = { + robot.eef_link_names["left"]: cologne.root_link, + robot.eef_link_names["right"]: fridge.links["link_0"], + } + attached_obj_scale = {robot.eef_link_names["left"]: cologne_scale, robot.eef_link_names["right"]: fridge_door_scale} + plan_and_execute_trajectory( + cmg, target_pos, target_quat, emb_sel, attached_obj, attached_obj_scale, eef_markers, env, robot + ) + attached_obj = {robot.eef_link_names["left"]: cologne.root_link} + control_gripper(env, robot, attached_obj) + assert robot._ag_obj_in_hand["left"] == cologne and robot._ag_obj_in_hand["right"] is None + + # Place the cologne (left hand) + left_hand_pos, left_hand_quat = T.pose_transform(*fridge.get_position_orientation(), *fridge_place_local_pose) + target_pos = {robot.eef_link_names["left"]: left_hand_pos} + target_quat = {robot.eef_link_names["left"]: left_hand_quat} + emb_sel = CuRoboEmbodimentSelection.DEFAULT + attached_obj = {robot.eef_link_names["left"]: cologne.root_link} + attached_obj_scale = {robot.eef_link_names["left"]: cologne_scale} + plan_and_execute_trajectory( + cmg, target_pos, target_quat, emb_sel, attached_obj, attached_obj_scale, eef_markers, env, robot + ) + attached_obj = None + control_gripper(env, robot, attached_obj) + assert robot._ag_obj_in_hand["left"] is None and robot._ag_obj_in_hand["right"] is None + + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/folded_unfolded_state_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/folded_unfolded_state_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..4098542e77980e2ddec2570a53b6dfc330dcf98a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/folded_unfolded_state_demo.py @@ -0,0 +1,167 @@ +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.macros import gm +from omnigibson.object_states import Folded, Unfolded +from omnigibson.utils.constants import PrimType +from omnigibson.utils.python_utils import multi_dim_linspace +from omnigibson.utils.ui_utils import KeyboardEventHandler + +# Make sure object states and GPU dynamics are enabled (GPU dynamics needed for cloth) +gm.ENABLE_OBJECT_STATES = True +gm.USE_GPU_DYNAMICS = True +gm.ENABLE_TRANSITION_RULES = False + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Demo of cloth objects that can potentially be folded. + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Create the scene config to load -- empty scene + custom cloth object + cfg = { + "scene": { + "type": "Scene", + }, + "objects": [ + { + "type": "DatasetObject", + "name": "carpet", + "category": "carpet", + "model": "ctclvd", + "bounding_box": [0.897, 0.568, 0.012], + "prim_type": PrimType.CLOTH, + "abilities": {"cloth": {}}, + "position": [0, 0, 0.5], + }, + { + "type": "DatasetObject", + "name": "dishtowel", + "category": "dishtowel", + "model": "dtfspn", + "bounding_box": [0.852, 1.1165, 0.174], + "prim_type": PrimType.CLOTH, + "abilities": {"cloth": {}}, + "position": [1, 1, 0.5], + }, + { + "type": "DatasetObject", + "name": "shirt", + "category": "t_shirt", + "model": "kvidcx", + "bounding_box": [0.472, 1.243, 1.158], + "prim_type": PrimType.CLOTH, + "abilities": {"cloth": {}}, + "position": [-1, 1, 0.5], + "orientation": [0.7071, 0.0, 0.7071, 0.0], + }, + ], + } + + # Create the environment + env = og.Environment(configs=cfg) + + KeyboardEventHandler.add_keyboard_callback( + key=lazy.carb.input.KeyboardInput.ESCAPE, + callback_fn=lambda: og.shutdown(), + ) + + # Grab object references + carpet = env.scene.object_registry("name", "carpet") + dishtowel = env.scene.object_registry("name", "dishtowel") + shirt = env.scene.object_registry("name", "shirt") + objs = [carpet, dishtowel, shirt] + + # Set viewer camera + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([0.46382895, -2.66703958, 1.22616824]), + orientation=th.tensor([0.58779174, -0.00231237, -0.00318273, 0.80900271]), + ) + + def print_state(): + folded = carpet.states[Folded].get_value() + unfolded = carpet.states[Unfolded].get_value() + info = "carpet: [folded] %d [unfolded] %d" % (folded, unfolded) + + folded = dishtowel.states[Folded].get_value() + unfolded = dishtowel.states[Unfolded].get_value() + info += " || dishtowel: [folded] %d [unfolded] %d" % (folded, unfolded) + + folded = shirt.states[Folded].get_value() + unfolded = shirt.states[Unfolded].get_value() + info += " || tshirt: [folded] %d [unfolded] %d" % (folded, unfolded) + + print(f"{info}{' ' * (110 - len(info))}", end="\r") + + for _ in range(100): + og.sim.step() + + print("\nCloth state:\n") + + if not short_exec: + # Fold all three cloths along the x-axis + for i in range(3): + obj = objs[i] + pos = obj.root_link.compute_particle_positions() + x_min, x_max = th.min(pos, dim=0).values[0], th.max(pos, dim=0).values[0] + x_extent = x_max - x_min + # Get indices for the bottom 10 percent vertices in the x-axis + indices = th.argsort(pos, dim=0)[:, 0][: (pos.shape[0] // 10)] + start = th.clone(pos[indices]) + + # lift up a bit + mid = th.clone(start) + mid[:, 2] += x_extent * 0.2 + + # move towards x_max + end = th.clone(mid) + end[:, 0] += x_extent * 0.9 + + increments = 25 + for ctrl_pts in th.cat( + [multi_dim_linspace(start, mid, increments), multi_dim_linspace(mid, end, increments)] + ): + obj.root_link.set_particle_positions(ctrl_pts, idxs=indices) + og.sim.step() + print_state() + + # Fold the t-shirt twice again along the y-axis + for direction in [-1, 1]: + obj = shirt + pos = obj.root_link.compute_particle_positions() + y_min, y_max = th.min(pos, dim=0).values[1], th.max(pos, dim=0).values[1] + y_extent = y_max - y_min + if direction == 1: + indices = th.argsort(pos, dim=0)[:, 1][: (pos.shape[0] // 20)] + else: + indices = th.argsort(pos, dim=0)[:, 1][-(pos.shape[0] // 20) :] + start = th.clone(pos[indices]) + + # lift up a bit + mid = th.clone(start) + mid[:, 2] += y_extent * 0.2 + + # move towards y_max + end = th.clone(mid) + end[:, 1] += direction * y_extent * 0.4 + + increments = 25 + for ctrl_pts in th.cat( + [multi_dim_linspace(start, mid, increments), multi_dim_linspace(mid, end, increments)] + ): + obj.root_link.set_particle_positions(ctrl_pts, idxs=indices) + env.step(th.empty(0)) + print_state() + + while True: + env.step([]) + print_state() + + # Shut down env at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/heat_source_or_sink_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/heat_source_or_sink_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..369abb2cfb498279cc0bd3d044525dc472db3f62 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/heat_source_or_sink_demo.py @@ -0,0 +1,101 @@ +import torch as th + +import omnigibson as og +from omnigibson import object_states +from omnigibson.macros import gm + +# Make sure object states are enabled +gm.ENABLE_OBJECT_STATES = True + + +def main(random_selection=False, headless=False, short_exec=False): + # Create the scene config to load -- empty scene with a stove object added + cfg = { + "scene": { + "type": "Scene", + }, + "objects": [ + { + "type": "DatasetObject", + "name": "stove", + "category": "stove", + "model": "ykretu", + "abilities": { + "heatSource": {"requires_toggled_on": True}, + "toggleable": {}, + }, + "position": [0, 0, 0.61], + } + ], + } + + # Create the environment + env = og.Environment(configs=cfg) + + # Get reference to stove object + stove = env.scene.object_registry("name", "stove") + + # Set camera to appropriate viewing pose + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([1.2299, -0.8270, 1.4666]), + orientation=th.tensor([0.4831, 0.2451, 0.3803, 0.7497]), + ) + + # Make sure necessary object states are included with the stove + assert object_states.HeatSourceOrSink in stove.states + assert object_states.ToggledOn in stove.states + + # Take a few steps so that visibility propagates + for _ in range(40): + env.step([]) + + # Heat source is off. + print("Heat source is OFF.") + heat_source_state = stove.states[object_states.HeatSourceOrSink].get_value() + assert not heat_source_state + + # Toggle on stove, notify user + if not short_exec: + input("Heat source will now turn ON: Press ENTER to continue.") + stove.states[object_states.ToggledOn].set_value(True) + + assert stove.states[object_states.ToggledOn].get_value() + + # Need to take a step to update the state. + env.step([]) + + # Heat source is on + heat_source_state = stove.states[object_states.HeatSourceOrSink].get_value() + assert heat_source_state + for _ in range(500): + env.step([]) + + # Toggle off stove, notify user + if not short_exec: + input("Heat source will now turn OFF: Press ENTER to continue.") + stove.states[object_states.ToggledOn].set_value(False) + assert not stove.states[object_states.ToggledOn].get_value() + for _ in range(200): + env.step([]) + + # Move stove, notify user + if not short_exec: + input("Heat source is now moving: Press ENTER to continue.") + stove.set_position_orientation(position=th.tensor([-0.4, 0.0, 0.61])) + for i in range(100): + env.step([]) + + # Toggle on stove again, notify user + if not short_exec: + input("Heat source will now turn ON: Press ENTER to continue.") + stove.states[object_states.ToggledOn].set_value(True) + assert stove.states[object_states.ToggledOn].get_value() + for i in range(500): + env.step([]) + + # Shutdown environment at end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/particle_source_sink_demo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/particle_source_sink_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..844c69706f44d81d989b2daa23b868090b4daad2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/particle_source_sink_demo.py @@ -0,0 +1,116 @@ +import torch as th + +import omnigibson as og +from omnigibson import object_states +from omnigibson.macros import gm +from omnigibson.utils.constants import ParticleModifyCondition + +# Make sure object states are enabled and GPU dynamics are used +gm.ENABLE_OBJECT_STATES = True +gm.USE_GPU_DYNAMICS = True +gm.ENABLE_HQ_RENDERING = True + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Demo of ParticleSource and ParticleSink object states, which enable objects to either spawn arbitrary + particles and remove arbitrary particles from the simulator, respectively. + + Loads an empty scene with a sink, which is enabled with both the ParticleSource and ParticleSink states. + The sink's particle source is located at the faucet spout and spawns a continuous stream of water particles, + which is then destroyed ("sunk") by the sink's particle sink located at the drain. + + NOTE: The key difference between ParticleApplier/Removers and ParticleSource/Sinks is that Applier/Removers + requires contact (if using ParticleProjectionMethod.ADJACENCY) or overlap + (if using ParticleProjectionMethod.PROJECTION) in order to spawn / remove particles, and generally only spawn + particles at the contact points. ParticleSource/Sinks are special cases of ParticleApplier/Removers that + always use ParticleProjectionMethod.PROJECTION and always spawn / remove particles within their projection volume, + irregardless of overlap with other objects! + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Create the scene config to load -- empty scene + cfg = { + "env": { + "action_frequency": 60, + "rendering_frequency": 60, # for HQ rendering + }, + "scene": { + "type": "Scene", + }, + } + + # Define objects to load into the environment + sink_cfg = dict( + type="DatasetObject", + name="sink", + category="furniture_sink", + model="czyfhq", + abilities={ + "toggleable": {}, + "particleSource": { + "conditions": { + "water": [ + (ParticleModifyCondition.TOGGLEDON, True) + ], # Must be toggled on for water source to be active + }, + "initial_speed": 0.0, # Water merely falls out of the spout + }, + "particleSink": { + "conditions": { + "water": [], # No conditions, always sinking nearby particles + }, + }, + }, + fixed_base=True, + position=[0.0, 0, 0.4], + ) + + cfg["objects"] = [sink_cfg] + + # Create the environment! + env = og.Environment(configs=cfg) + + # Set camera to ideal angle for viewing objects + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([0.4732, -0.5300, 1.1335]), + orientation=th.tensor([0.4920, 0.1984, 0.3171, 0.7861]), + ) + + # Take a few steps to let the objects settle, and then turn on the sink + for _ in range(10): + env.step(th.empty(0)) # Empty action since no robots are in the scene + + sink = env.scene.object_registry("name", "sink") + assert sink.states[object_states.ToggledOn].set_value(True) + + # Take a step, and save the state + env.step(th.empty(0)) + initial_state = og.sim.dump_state() + + # Main simulation loop. + max_steps = 1000 + max_iterations = -1 if not short_exec else 1 + iteration = 0 + + try: + while iteration != max_iterations: + # Keep stepping until table or bowl are clean, or we reach 1000 steps + steps = 0 + while steps != max_steps: + steps += 1 + env.step(th.empty(0)) + og.log.info("Max steps reached; resetting.") + + # Reset to the initial state + og.sim.load_state(initial_state) + + iteration += 1 + + finally: + # Always shut down environment at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/rs_int_primitives_example.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/rs_int_primitives_example.py new file mode 100644 index 0000000000000000000000000000000000000000..34916f1eb6bf50d3e8b68f0f28e8b79192dfd4d5 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/rs_int_primitives_example.py @@ -0,0 +1,91 @@ +import os + +import torch as th +import yaml + +import omnigibson as og +from omnigibson.action_primitives.starter_semantic_action_primitives import ( + StarterSemanticActionPrimitives, + StarterSemanticActionPrimitiveSet, +) +from omnigibson.utils.ui_utils import choose_from_options + + +def execute_controller(ctrl_gen, env): + for action in ctrl_gen: + env.step(action) + + +def main(): + """ + Demonstrates how to use the action primitives to pick and place an object in a crowded scene. + + It loads Rs_int with a robot, and the robot picks and places an apple. + """ + robot_options = ["R1", "R1Pro", "Tiago"] + robot_type = choose_from_options(options=robot_options, name="robot options", random_selection=False) + + # Load the config + config_filename = os.path.join(og.example_config_path, f"{robot_type.lower()}_primitives.yaml") + config = yaml.load(open(config_filename, "r"), Loader=yaml.FullLoader) + + config["scene"]["scene_model"] = "Rs_int" + config["scene"]["not_load_object_categories"] = ["ceilings", "carpet"] + config["objects"] = [ + { + "type": "DatasetObject", + "name": "apple", + "category": "apple", + "model": "agveuv", + "position": [1.2, 0.0, 0.75], + "orientation": [0, 0, 0, 1], + }, + ] + + # Load the environment + env = og.Environment(configs=config) + scene = env.scene + robot = env.scene.robots[0] + + # Open the gripper(s) to match cuRobo's default state + for arm_name in robot.gripper_control_idx.keys(): + grpiper_control_idx = robot.gripper_control_idx[arm_name] + robot.set_joint_positions(th.ones_like(grpiper_control_idx), indices=grpiper_control_idx, normalized=True) + robot.keep_still() + + for _ in range(5): + og.sim.step() + + env.scene.update_initial_file() + env.scene.reset() + + og.sim.viewer_camera.set_position_orientation( + th.tensor([1.8294, -3.2502, 1.6885]), th.tensor([0.5770, 0.1719, 0.2280, 0.7652]) + ) + + # Let the object settle + for _ in range(30): + og.sim.step() + + # Allow user to move camera more easily + og.sim.enable_viewer_camera_teleoperation() + + controller = StarterSemanticActionPrimitives(env, robot, enable_head_tracking=robot.model == "tiago") + coffee_table = scene.object_registry("name", "coffee_table_fqluyq_0") + apple = scene.object_registry("name", "apple") + + # Grasp apple + print("Start executing grasp") + execute_controller(controller.apply_ref(StarterSemanticActionPrimitiveSet.GRASP, apple), env) + print("Finish executing grasp") + + # Place on cabinet + print("Start executing place") + execute_controller(controller.apply_ref(StarterSemanticActionPrimitiveSet.PLACE_ON_TOP, coffee_table), env) + print("Finish executing place") + + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/solve_behavior_task.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/solve_behavior_task.py new file mode 100644 index 0000000000000000000000000000000000000000..fd3033db8eeb7902c2ef70e206e4b847855dcf54 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/solve_behavior_task.py @@ -0,0 +1,63 @@ +import os + +import yaml + +import omnigibson as og +from omnigibson.action_primitives.starter_semantic_action_primitives import ( + StarterSemanticActionPrimitives, + StarterSemanticActionPrimitiveSet, +) + + +def execute_controller(ctrl_gen, env): + for action in ctrl_gen: + env.step(action) + + +def main(): + """ + Demonstrates how to use the action primitives to solve a simple BEHAVIOR-1K task. + + It loads Benevolence_1_int with a robot, and the robot attempts to solve the + picking_up_trash task using a hardcoded sequence of primitives. + """ + # Load the config + config_filename = os.path.join(og.example_config_path, "tiago_primitives.yaml") + config = yaml.load(open(config_filename, "r"), Loader=yaml.FullLoader) + + # Update it to run a grocery shopping task + config["scene"]["scene_model"] = "Benevolence_1_int" + config["scene"]["load_task_relevant_only"] = True + config["scene"]["not_load_object_categories"] = ["ceilings"] + config["task"] = { + "type": "BehaviorTask", + "activity_name": "picking_up_trash", + "activity_definition_id": 0, + "activity_instance_id": 0, + "online_object_sampling": False, + } + + # Load the environment + env = og.Environment(configs=config) + robot = env.scene.robots[0] + + # Allow user to move camera more easily + og.sim.enable_viewer_camera_teleoperation() + + controller = StarterSemanticActionPrimitives(env, robot, enable_head_tracking=False) + + # Grasp can of soda + grasp_obj = env.task.object_scopes[0]["can__of__soda.n.01_2"] + print("Executing controller") + execute_controller(controller.apply_ref(StarterSemanticActionPrimitiveSet.GRASP, grasp_obj), env) + print("Finished executing grasp") + + # Place can in trash can + print("Executing controller") + trash = env.task.object_scopes[0]["ashcan.n.01_1"] + execute_controller(controller.apply_ref(StarterSemanticActionPrimitiveSet.PLACE_INSIDE, trash), env) + print("Finished executing place") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/solve_simple_task.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/solve_simple_task.py new file mode 100644 index 0000000000000000000000000000000000000000..13e19dd43f992ea7dd553ec616b58a7807b1cd12 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/solve_simple_task.py @@ -0,0 +1,81 @@ +import os + +import yaml + +import omnigibson as og +from omnigibson.action_primitives.starter_semantic_action_primitives import ( + StarterSemanticActionPrimitives, + StarterSemanticActionPrimitiveSet, +) + +# Don't use GPU dynamics for performance boost +# gm.USE_GPU_DYNAMICS = True + + +def execute_controller(ctrl_gen, env): + for action in ctrl_gen: + env.step(action) + + +def main(): + """ + Demonstrates how to use the action primitives to pick and place an object in an empty scene. + + It loads Rs_int with a robot, and the robot picks and places a bottle of cologne. + """ + # Load the config + config_filename = os.path.join(og.example_config_path, "tiago_primitives.yaml") + config = yaml.load(open(config_filename, "r"), Loader=yaml.FullLoader) + + # Update it to create a custom environment and run some actions + config["scene"]["scene_model"] = "Rs_int" + config["scene"]["load_object_categories"] = ["floors", "ceilings", "walls", "coffee_table"] + config["objects"] = [ + { + "type": "DatasetObject", + "name": "cologne", + "category": "bottle_of_cologne", + "model": "lyipur", + "position": [-0.3, -0.8, 0.5], + "orientation": [0, 0, 0, 1], + }, + { + "type": "DatasetObject", + "name": "table", + "category": "breakfast_table", + "model": "rjgmmy", + "scale": [0.3, 0.3, 0.3], + "position": [-0.7, 0.5, 0.2], + "orientation": [0, 0, 0, 1], + }, + ] + + # Load the environment + env = og.Environment(configs=config) + scene = env.scene + robot = env.scene.robots[0] + + # Let the objects settle + for _ in range(30): + og.sim.step() + + # Allow user to move camera more easily + og.sim.enable_viewer_camera_teleoperation() + + controller = StarterSemanticActionPrimitives(env, robot, enable_head_tracking=True) + + # Grasp of cologne + grasp_obj = scene.object_registry("name", "cologne") + print("Executing controller") + execute_controller(controller.apply_ref(StarterSemanticActionPrimitiveSet.GRASP, grasp_obj), env) + print("Finished executing grasp") + + # Place cologne on another table + print("Executing controller") + table = scene.object_registry("name", "table") + execute_controller(controller.apply_ref(StarterSemanticActionPrimitiveSet.PLACE_ON_TOP, table), env) + print("Finished executing place") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/view_cloth_configurations.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/view_cloth_configurations.py new file mode 100644 index 0000000000000000000000000000000000000000..c544c3bec6eb8bacf99895e4f8586696d4daf640 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/examples/wip/view_cloth_configurations.py @@ -0,0 +1,117 @@ +from omnigibson.utils.asset_utils import get_all_object_categories, get_all_object_category_models +from omnigibson.macros import gm + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.utils.constants import PrimType +from omnigibson.utils.ui_utils import KeyboardEventHandler, choose_from_options +import torch as th +from omnigibson.utils.bddl_utils import get_knowledge_base + +# Make sure object states and GPU dynamics are enabled (GPU dynamics needed for cloth) +gm.ENABLE_OBJECT_STATES = True +gm.USE_GPU_DYNAMICS = True + + +def main(random_selection=False, headless=False, short_exec=False): + """ + Demo showing the multiple configurations stored on each cloth object. + """ + og.log.info(f"Demo {__file__}\n " + "*" * 80 + "\n Description:\n" + main.__doc__ + "*" * 80) + + # Select a category to load + available_obj_categories = get_all_object_categories() + cloth_obj_categories = [ + category + for category in available_obj_categories + if "cloth" in get_knowledge_base().get_category(category).synset.abilities + ] + obj_category = choose_from_options( + options=cloth_obj_categories, name="object category", random_selection=random_selection + ) + + # Select a model to load + available_obj_models = get_all_object_category_models(obj_category) + obj_model = choose_from_options( + options=available_obj_models, name="object model", random_selection=random_selection + ) + + # Create and load this object into the simulator + obj_cfg = { + "type": "DatasetObject", + "name": "cloth", + "category": obj_category, + "model": obj_model, + "prim_type": PrimType.CLOTH, + "position": [0, 0, 0.5], + "orientation": [0, 0, 0, 1], + "load_config": { + "default_configuration": "settled", + }, + } + + # Create the scene config to load -- empty scene + custom cloth object + cfg = { + "scene": { + "type": "Scene", + }, + "objects": [obj_cfg], + } + + # Create the environment + env = og.Environment(configs=cfg) + + # Grab object references + obj = env.scene.object_registry("name", "cloth") + + # Set viewer camera + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([0.46382895, -2.66703958, 1.22616824]), + orientation=th.tensor([0.58779174, -0.00231237, -0.00318273, 0.80900271]), + ) + + def reset_points_to_configuration(configuration): + print(f"Resetting to {configuration} configuration") + obj.root_link.reset_points_to_configuration(configuration) + obj.set_position_orientation(position=th.zeros(3), orientation=th.tensor([0.0, 0.0, 0.0, 1.0])) + obj.set_position_orientation( + position=th.tensor([0, 0, obj.aabb_extent[2] / 2.0 - obj.aabb_center[2]]), + orientation=th.tensor([0.0, 0.0, 0.0, 1.0]), + ) + + KeyboardEventHandler.initialize() + KeyboardEventHandler.add_keyboard_callback( + key=lazy.carb.input.KeyboardInput.Q, + callback_fn=lambda: reset_points_to_configuration("default"), + ) + print("Press Q to reset to default configuration") + + KeyboardEventHandler.add_keyboard_callback( + key=lazy.carb.input.KeyboardInput.W, + callback_fn=lambda: reset_points_to_configuration("settled"), + ) + print("Press W to reset to settled configuration") + + KeyboardEventHandler.add_keyboard_callback( + key=lazy.carb.input.KeyboardInput.E, + callback_fn=lambda: reset_points_to_configuration("folded"), + ) + print("Press E to reset to folded configuration") + + KeyboardEventHandler.add_keyboard_callback( + key=lazy.carb.input.KeyboardInput.R, + callback_fn=lambda: reset_points_to_configuration("crumpled"), + ) + print("Press R to reset to crumpled configuration") + + # Step through the environment + max_steps = 100 if short_exec else 10000 + for i in range(max_steps): + env.step(th.empty(0)) + + # Always close the environment at the end + og.clear() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/kit_file_changes.patch b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/kit_file_changes.patch new file mode 100644 index 0000000000000000000000000000000000000000..beeab2b9d63a7cd9bb79dc45cb940211dc6e93d8 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/kit_file_changes.patch @@ -0,0 +1,43 @@ +--- isaacsim.exp.base.python.kit 2025-03-11 10:50:57.495966820 -0700 ++++ omnigibson_4_5_0.kit 2025-03-13 23:51:00.615656858 -0700 +@@ -1,21 +1,27 @@ + [package] +-description = "A trimmed down app for use with python samples" +-title = "Isaac Sim Python" +-version = "4.5.0" ++description = "A platform for accelerating Embodied AI research" ++title = "OmniGibson" ++version = "1.5.0" + + keywords = ["experience", "app", "usd", "isaacsim"] # That makes it browsable in UI with "experience" filter + + + [dependencies] + "isaacsim.exp.base" = {} ++"omni.flowusd" = {} + + [settings.app] +-name = "Isaac-Sim Python" +-version = "4.5.0" ++name = "OmniGibson" ++version = "1.5.0" + settings.persistent = false # settings reset on each run with this app +-window.title = "Isaac Sim Python" ++window.title = "OmniGibson" + vulkan = true # Explicitly enable Vulkan (on by default on Linux, off by default on Windows) + ++[settings.app.livestream] ++proto = "ws" ++allowResize = true ++outDirectory = "${data}" ++ + [settings.app.exts.folders] + '++' = [ + "${app}/../exts", +@@ -31,3 +37,6 @@ + { name = "kit/sdk", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/sdk/${kit_version_short}/${kit_git_hash}" }, + { name = "kit/community", url = "https://dw290v42wisod.cloudfront.net/exts/kit/community" }, + ] ++ ++[settings.app.extensions] ++pathStatCacheEnabled = false diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/lazy.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/lazy.py new file mode 100644 index 0000000000000000000000000000000000000000..0c71bb212428b2dd2e58ff811bffaec271c308b3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/lazy.py @@ -0,0 +1,12 @@ +import sys +from typing import TYPE_CHECKING, Any + +from omnigibson.utils.lazy_import_utils import LazyImporter + +sys.modules[__name__] = LazyImporter("", None) + +if TYPE_CHECKING: + # This module's namespace is replaced at runtime (see above) by a LazyImporter + # that resolves arbitrary submodules/attributes on the fly. Pyright can't see + # through that swap, so tell it about the dynamic attribute access via PEP 562. + def __getattr__(name: str) -> Any: ... diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/macros.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/macros.py new file mode 100644 index 0000000000000000000000000000000000000000..dad2a1177d361eaa31966fd4729f2e89ffadf4d2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/macros.py @@ -0,0 +1,279 @@ +""" +Set of macros to use globally for OmniGibson. These are generally magic numbers that were tuned heuristically. + +NOTE: This is generally decentralized -- the monolithic @settings variable is created here with some global values, +but submodules within OmniGibson may import this dictionary and add to it dynamically +""" + +import os +import pathlib +import contextlib + +from addict import Dict + + +class MacroDict(Dict): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self["_read"] = set() + object.__setattr__(self, "__locked", True) # disallow value updates after key is read + + def __setattr__(self, name, value): + if name in self.get("_read", set()) and self.is_locked: + raise AttributeError( + f"Cannot set attribute {name} in MacroDict, it has already been used. " + f"If knowingly overwriting value, set value within context `with unlocked()`" + ) + # Use the super's setattr for setting attributes, but handle _read directly to avoid recursion. + if name == "_read": + self[name] = value + else: + super().__setattr__(name, value) + + def __getattr__(self, item): + # Directly check and modify '_read' to avoid going through __getattr__ or __setattr__. + if item != "_read": + self["_read"].add(item) + # Use direct dictionary access to avoid infinite recursion. + try: + return self[item] + except KeyError: + raise AttributeError(f"'MacroDict' object has no attribute '{item}'") + + @property + def is_locked(self): + """ + Returns True if the config is locked (no value updates allowed after initial read). + """ + return object.__getattribute__(self, "__locked") + + def lock(self): + """ + Lock the config. Afterward, key values cannot be updated after initial read + """ + object.__setattr__(self, "__locked", True) + + for k in self: + if isinstance(self[k], MacroDict): + self[k].lock() + + def unlock(self): + """ + Unlock the config. Afterward, key values can be updated even after initial read + """ + object.__setattr__(self, "__locked", False) + + for k in self: + if isinstance(self[k], MacroDict): + self[k].unlock() + + def _get_lock_state(self): + """ + Retrieves the lock state of this config. + + Returns: + lock_state (dict): a dictionary with a "locked" key that is True + if value updates are locked after the value has been read during runtime + """ + return { + "locked": self.is_locked, + } + + def _set_lock_state(self, lock_state): + """ + Sets the lock state for this config. + + Args: + lock_state (dict): a dictionary with an "locked" key that is True + if value updates are locked after the value has been read during runtime + """ + if lock_state["locked"]: + self.lock() + + @contextlib.contextmanager + def unlocked(self): + """ + A context scope for modifying a Config object. Within the scope, values can be updated, even after an initial + read. Upon leaving the scope, the initial level of locking is restored. + """ + lock_state = self._get_lock_state() + self.unlock() + yield + self._set_lock_state(lock_state) + + +# Initialize settings +macros = MacroDict() +gm = macros.globals + + +def determine_data_path(): + # Start with the default path. Check that it exists. + path = pathlib.Path(__file__).parents[2] / "datasets" + # Override with the environment variable, if set + if "OMNIGIBSON_DATA_PATH" in os.environ: + path = os.environ["OMNIGIBSON_DATA_PATH"] + # Expand the user directory (~) + path = os.path.expanduser(path) + # Make the path absolute if it's not already + if not os.path.isabs(path): + path = os.path.join(os.path.dirname(os.path.realpath(__file__)), path) + assert os.path.exists(path), f"Data path {path} does not exist!" + return path + + +# Path (either relative to OmniGibson/omnigibson directory or global absolute path) for data +# Assets correspond to non-objects / scenes (e.g.: robots), and dataset includes objects + scene +# can override assets_path and dataset_path from environment variable +gm.DATA_PATH = determine_data_path() + +# Where the appdata should be stored. Omniverse uses this for a variety of purposes: logging, caching, +# pointers for extensions, etc. - we default this to be in the OmniGibson directory for easy access +# but on HPC clusters like SLURM you ideally want to put this in a local path rather than a networked +# filesystem where read/writes are slow and race conditions can occur. +gm.APPDATA_PATH = os.getenv("OMNIGIBSON_APPDATA_PATH", str(pathlib.Path(__file__).parents[1] / "appdata")) + +# Which GPU to use -- None will result in omni automatically using an appropriate GPU. Otherwise, set with either +# integer or string-form integer +gm.GPU_ID = os.getenv("OMNIGIBSON_GPU_ID", None) + +# Whether to generate a headless or non-headless application upon OmniGibson startup +gm.HEADLESS = os.getenv("OMNIGIBSON_HEADLESS", "False").lower() in ("true", "1", "t") + +# Whether to enable remote streaming. None disables it, other valid options are "native", "webrtc". +gm.REMOTE_STREAMING = os.getenv("OMNIGIBSON_REMOTE_STREAMING", None) + +# What port the webrtc and http servers should run on. This is only used if REMOTE_STREAMING is set to "webrtc" +gm.HTTP_PORT = os.getenv("OMNIGIBSON_HTTP_PORT", 8211) +gm.WEBRTC_PORT = os.getenv("OMNIGIBSON_WEBRTC_PORT", 49100) + +# Whether to use numpy or torch controller backend. Numpy is significantly faster and should be used +# for single-threaded (i.e.: non-large scale parallelized env) purposes +gm.USE_NUMPY_CONTROLLER_BACKEND = True + +# Whether only the viewport should be shown in the GUI or not (if not, other peripherals are additionally shown) +# CANNOT be set at runtime +gm.GUI_VIEWPORT_ONLY = False + +# Whether to use the viewer camera or not +gm.RENDER_VIEWER_CAMERA = True + +# Whether to batch all per-env robot cameras into a single tiled render product when num_envs > 1. +# Tiled rendering issues one render pass for every env instead of one per camera, which is much faster +# at high env counts, but it fixes camera resolution at creation time and returns raw (unremapped) +# segmentation IDs without the per-modality info dicts. When False, every env renders through its own +# per-camera render product, regardless of num_envs. +gm.ENABLE_TILED_RENDERING = os.getenv("OMNIGIBSON_ENABLE_TILED_RENDERING", "False").lower() in ("true", "1", "t") + +# Do not suppress known omni warnings / errors, and also put omnigibson in a debug state +# This includes extra information for things such as object sampling, and also any debug +# logging messages +gm.DEBUG = os.getenv("OMNIGIBSON_DEBUG", "False").lower() in ("true", "1", "t") + +# Whether to enable profiling or not in simulator.py - this causes a slowdown! +gm.ENABLE_DEEP_PROFILING = False + +# Whether to suppress any omni logs upon startup, and prune the following omni logs to error level +gm.NO_OMNI_LOGS = os.getenv("OMNIGIBSON_NO_OMNI_LOGS", "False").lower() in ("true", "1", "t") + +# Whether to print out disclaimers (i.e.: known failure cases resulting from Omniverse's current bugs / limitations) +gm.SHOW_DISCLAIMERS = False + +# Whether to use omni's GPU dynamics +# This is necessary for certain features; e.g. particles (fluids / cloth) +gm.USE_GPU_DYNAMICS = False + +# Whether to use high-fidelity rendering (this includes, e.g., isosurfaces) +gm.ENABLE_HQ_RENDERING = False + +# Whether to use continuous collision detection or not (slower simulation, but can prevent +# objects from tunneling through each other) +gm.ENABLE_CCD = False + +# Pairs setting -- USD default is 256 * 1024, physx default apparently is 32 * 1024. +gm.GPU_PAIRS_CAPACITY = 256 * 1024 +# Aggregate pairs setting -- default is 1024, but is often insufficient for large scenes +gm.GPU_AGGR_PAIRS_CAPACITY = (2**14) * 1024 + +# Maximum particle contacts allowed +gm.GPU_MAX_PARTICLE_CONTACTS = 1024 * 1024 + +# Maximum rigid contacts -- 524288 is default value from omni, but increasing too much can sometimes lead to crashes +gm.GPU_MAX_RIGID_CONTACT_COUNT = 524288 * 4 + +# Maximum rigid patches -- 81920 is default value from omni, but increasing too much can sometimes lead to crashes +gm.GPU_MAX_RIGID_PATCH_COUNT = 81920 * 4 + +# Whether to enable object state logic or not +gm.ENABLE_OBJECT_STATES = True + +# Whether to enable transition rules or not +gm.ENABLE_TRANSITION_RULES = True + +# Default settings for the omni UI viewer +gm.DEFAULT_VIEWER_WIDTH = 1280 +gm.DEFAULT_VIEWER_HEIGHT = 720 + +# Default physics / rendering / sim step frequencies (Hz) +# rendering must be a multiple of physics frequency, and sim_step must be a multiple of rendering frequency +gm.DEFAULT_SIM_STEP_FREQ = 30 +gm.DEFAULT_RENDERING_FREQ = 30 +gm.DEFAULT_PHYSICS_FREQ = 120 + +# Forced light intensity for all DatasetObjects. None if the USD-provided intensities should be respected. +gm.FORCE_LIGHT_INTENSITY = 10000 + +# Forced roughness for all DatasetObjects. None if the USD-provided roughness maps should be respected. +gm.FORCE_ROUGHNESS = 0.7 + +# Whether to force the category-level mass on DatasetObjects instead of computing a per-model scaled +# mass from the category-level density and the volume of the object. +gm.FORCE_CATEGORY_MASS = True + +# Disable collision and gravity for the simulator, should default to False +gm.VISUAL_ONLY = False + +# Whether to enable VR extension support +gm.ENABLE_VR = os.getenv("OMNIGIBSON_VR", "False").lower() in ("true", "1", "t") + + +# Create helper function for generating sub-dictionaries +def create_module_macros(module_path): + """ + Creates a dictionary that can be populated with module macros based on the module's @module_path + + Args: + module_path (str): Relative path from the package root directory pointing to the module. This will be parsed + to generate the appropriate sub-macros dictionary, e.g., for module "dirty" in + omnigibson/object_states_dirty.py, this would generate a dictionary existing at macros.object_states.dirty + + Returns: + MacroDict: addict/macro dictionary which can be populated with values + """ + # Sanity check module path, make sure omnigibson/ is in the path + module_path = pathlib.Path(module_path) + omnigibson_path = pathlib.Path(__file__).parent + + # Trim the .py, and anything before and including omnigibson/, and split into its appropriate parts + try: + subsections = module_path.with_suffix("").relative_to(omnigibson_path).parts + except ValueError: + raise ValueError( + "module_path is expected to be a filepath including the omnigibson root directory, got: {module_path}!" + ) + + # Create and return the generated sub-dictionary + def _recursively_get_or_create_dict(dic, keys): + # If no entry is in @keys, it returns @dic + # Otherwise, checks whether the dictionary contains the first entry in @keys, if so, it grabs the + # corresponding nested dictionary, otherwise, generates a new MacroDict() as the value + # It then recurisvely calls this function with the new dic and the remaining keys + if len(keys) == 0: + return dic + else: + key = keys[0] + if key not in dic: + dic[key] = MacroDict() + return _recursively_get_or_create_dict(dic=dic[key], keys=keys[1:]) + + return _recursively_get_or_create_dict(dic=macros, keys=subsections) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/maps/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/maps/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f25d9dfac2fc53bb132f815dc51b8cd4718d8bb4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/maps/__init__.py @@ -0,0 +1,9 @@ +from omnigibson.maps.map_base import BaseMap +from omnigibson.maps.segmentation_map import SegmentationMap +from omnigibson.maps.traversable_map import TraversableMap + +__all__ = [ + "BaseMap", + "SegmentationMap", + "TraversableMap", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/maps/map_base.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/maps/map_base.py new file mode 100644 index 0000000000000000000000000000000000000000..8a7961000eb0e740f544a06d47ac60c49f97c162 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/maps/map_base.py @@ -0,0 +1,61 @@ +import torch as th + + +class BaseMap: + """ + Base map class. + Contains basic interface for converting from map to world frame, and vise-versa + """ + + def __init__( + self, + map_resolution=0.1, + ): + """ + Args: + map_resolution (float): map resolution + """ + # Set internal values + self.map_resolution = map_resolution + self.map_size = None + + def load_map(self, *args, **kwargs): + """ + Load's this map internally + """ + # Run internal method and store map size + self.map_size = self._load_map(*args, **kwargs) + + def _load_map(self, *args, **kwargs): + """ + Arbitrary function to load this map. Should be implemented by subclass + + Returns: + int: Size of the loaded map + """ + raise NotImplementedError() + + def map_to_world(self, xy): + """ + Transforms a 2D point in map reference frame into world (simulator) reference frame + + Args: + xy (2-array or (N, 2)-array): 2D location(s) in map reference frame (in image pixel space) + + Returns: + 2-array or (N, 2)-array: 2D location(s) in world reference frame (in metric space) + """ + dims = 0 if xy.dim() == 1 else 1 + return th.flip((xy - self.map_size / 2.0) * self.map_resolution, dims=(dims,)) + + def world_to_map(self, xy): + """ + Transforms a 2D point in world (simulator) reference frame into map reference frame + + xy: 2D location in world reference frame (metric) + :return: 2D location in map reference frame (image) + """ + + xy = th.as_tensor(xy) + point_wrt_map = xy / self.map_resolution + self.map_size / 2.0 + return th.flip(point_wrt_map, dims=tuple(range(point_wrt_map.dim()))).int() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/maps/segmentation_map.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/maps/segmentation_map.py new file mode 100644 index 0000000000000000000000000000000000000000..f5be43cddabfffba00708d03b10094546eb7a362 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/maps/segmentation_map.py @@ -0,0 +1,197 @@ +import os + +import cv2 +import torch as th + +from omnigibson.maps.map_base import BaseMap +from omnigibson.utils.asset_utils import get_dataset_path +from omnigibson.utils.python_utils import torch_delete +from omnigibson.utils.ui_utils import create_module_logger + +# Create module logger +log = create_module_logger(module_name=__name__) + + +class SegmentationMap(BaseMap): + """ + Segmentation map for computing connectivity within the scene + """ + + def __init__( + self, + scene_dir, + map_resolution=0.1, + floor_heights=(0.0,), + ): + """ + Args: + scene_dir (str): path to the scene directory from which segmentation info will be extracted + map_resolution (float): map resolution (m) + floor_heights (list of float): heights of the floors for this segmentation map + """ + # Store internal values + self.scene_dir = scene_dir + self.map_default_resolution = 0.01 # Default floor plan images are in meters + self.floor_heights = floor_heights + + # Other values that will be loaded at runtime + self.room_sem_name_to_sem_id = None + self.room_sem_id_to_sem_name = None + self.room_ins_name_to_ins_id = None + self.room_ins_id_to_ins_name = None + self.room_sem_name_to_ins_name = None + self.room_ins_map = None + self.room_sem_map = None + + # Run super call + super().__init__(map_resolution=map_resolution) + + # Load the map + self.load_map() + + def _load_map(self): + layout_dir = os.path.join(self.scene_dir, "layout") + room_seg_imgs = os.path.join(layout_dir, "floor_insseg_0.png") + img_ins = cv2.imread(room_seg_imgs, cv2.IMREAD_GRAYSCALE) + room_seg_imgs = os.path.join(layout_dir, "floor_semseg_0.png") + img_sem = cv2.imread(room_seg_imgs, cv2.IMREAD_GRAYSCALE) + height = img_ins.shape[0] + width = img_ins.shape[1] + assert height == width, "room seg map is not a square" + assert img_ins.shape == img_sem.shape, "semantic and instance seg maps have different sizes" + map_size = int(height * self.map_default_resolution / self.map_resolution) + img_ins = th.tensor(cv2.resize(img_ins, (map_size, map_size), interpolation=cv2.INTER_NEAREST)) + img_sem = th.tensor(cv2.resize(img_sem, (map_size, map_size), interpolation=cv2.INTER_NEAREST)) + + room_categories = os.path.join(get_dataset_path("behavior-1k-assets"), "metadata", "room_categories.txt") + with open(room_categories, "r") as fp: + room_cats = [line.rstrip() for line in fp.readlines()] + + sem_id_to_ins_id = {} + unique_ins_ids = th.unique(img_ins) + unique_ins_ids = torch_delete(unique_ins_ids, 0) + for ins_id in unique_ins_ids: + ins_id = ins_id.item() + # find one pixel for each ins id + x, y = th.where(img_ins == ins_id) + # retrieve the correspounding sem id + sem_id = img_sem[x[0], y[0]].item() + if sem_id not in sem_id_to_ins_id: + sem_id_to_ins_id[sem_id] = [] + sem_id_to_ins_id[sem_id].append(ins_id) + + room_sem_name_to_sem_id = {} + room_ins_name_to_ins_id = {} + room_sem_name_to_ins_name = {} + for sem_id, ins_ids in sem_id_to_ins_id.items(): + sem_name = room_cats[sem_id - 1] + room_sem_name_to_sem_id[sem_name] = sem_id + for i, ins_id in enumerate(ins_ids): + # valid class start from 1 + ins_name = "{}_{}".format(sem_name, i) + room_ins_name_to_ins_id[ins_name] = ins_id + if sem_name not in room_sem_name_to_ins_name: + room_sem_name_to_ins_name[sem_name] = [] + room_sem_name_to_ins_name[sem_name].append(ins_name) + + self.room_sem_name_to_sem_id = room_sem_name_to_sem_id + self.room_sem_id_to_sem_name = {value: key for key, value in room_sem_name_to_sem_id.items()} + self.room_ins_name_to_ins_id = room_ins_name_to_ins_id + self.room_ins_id_to_ins_name = {value: key for key, value in room_ins_name_to_ins_id.items()} + self.room_sem_name_to_ins_name = room_sem_name_to_ins_name + self.room_ins_map = img_ins + self.room_sem_map = img_sem + + return map_size + + def get_random_point_by_room_type(self, room_type): + """ + Sample a random point on the given a specific room type @room_type. + + Args: + room_type (str): Room type to sample random point (e.g.: "bathroom") + + Returns: + 2-tuple: + - int: floor number. This is always 0 + - 3-array: (x,y,z) randomly sampled point in a room of type @room_type + """ + if room_type not in self.room_sem_name_to_sem_id: + log.warning("room_type [{}] does not exist.".format(room_type)) + return None, None + + sem_id = self.room_sem_name_to_sem_id[room_type] + valid_idx = th.tensor(th.where(self.room_sem_map == sem_id)) + random_point_map = valid_idx[:, th.randint(valid_idx.shape[1])] + + x, y = self.map_to_world(random_point_map) + # assume only 1 floor + floor = 0 + z = self.floor_heights[floor] + return floor, th.tensor([x, y, z]) + + def get_random_point_by_room_instance(self, room_instance): + """ + Sample a random point on the given a specific room instance @room_instance. + + Args: + room_instance (str): Room instance to sample random point (e.g.: "bathroom_1") + + Returns: + 2-tuple: + - int: floor number. This is always 0 + - 3-array: (x,y,z) randomly sampled point in room @room_instance + """ + if room_instance not in self.room_ins_name_to_ins_id: + log.warning("room_instance [{}] does not exist.".format(room_instance)) + return None, None + + ins_id = self.room_ins_name_to_ins_id[room_instance] + valid_idx = th.tensor(th.where(self.room_ins_map == ins_id)) + random_point_map = valid_idx[:, th.randint(valid_idx.shape[1])] + + x, y = self.map_to_world(random_point_map) + # assume only 1 floor + floor = 0 + z = self.floor_heights[floor] + return floor, th.tensor([x, y, z]) + + def get_room_type_by_point(self, xy): + """ + Return the room type given a point + + Args: + xy (2-array): 2D location in world reference frame (in metric space) + + Returns: + None or str: room type that this point is in or None, if this point is not on the room segmentation map + """ + x, y = self.world_to_map(xy) + if x < 0 or x >= self.room_sem_map.shape[0] or y < 0 or y >= self.room_sem_map.shape[1]: + return None + sem_id = self.room_sem_map[x, y] + # room boundary + if sem_id == 0: + return None + else: + return self.room_sem_id_to_sem_name[sem_id] + + def get_room_instance_by_point(self, xy): + """ + Return the room type given a point + + Args: + xy (2-array): 2D location in world reference frame (in metric space) + + Returns: + None or str: room instance that this point is in or None, if this point is not on the room segmentation map + """ + x, y = self.world_to_map(xy) + if x < 0 or x >= self.room_ins_map.shape[0] or y < 0 or y >= self.room_ins_map.shape[1]: + return None + ins_id = self.room_ins_map[x, y].item() + # room boundary + if ins_id == 0: + return None + else: + return self.room_ins_id_to_ins_name[ins_id] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/maps/traversable_map.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/maps/traversable_map.py new file mode 100644 index 0000000000000000000000000000000000000000..ef018a7b2b26ad8fe3dad13948254ece2481763b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/maps/traversable_map.py @@ -0,0 +1,207 @@ +import math +import os + +import cv2 +import torch as th + +from omnigibson.maps.map_base import BaseMap +from omnigibson.utils.motion_planning_utils import astar +from omnigibson.utils.ui_utils import create_module_logger + +# Create module logger +log = create_module_logger(module_name=__name__) + + +class TraversableMap(BaseMap): + """ + Traversable scene class. + Contains the functionalities for navigation such as shortest path computation + """ + + def __init__( + self, + map_resolution=0.1, + default_erosion_radius=0.0, + trav_map_with_objects=True, + num_waypoints=10, + waypoint_resolution=0.2, + ): + """ + Args: + map_resolution (float): map resolution in meters, each pixel represents this many meters; + normally, this should be between 0.01 and 0.1 + default_erosion_radius (float): default map erosion radius in meters + trav_map_with_objects (bool): whether to use objects or not when constructing graph + num_waypoints (int): number of way points returned + waypoint_resolution (float): resolution of adjacent way points + """ + # Set internal values + self.map_default_resolution = 0.01 # each pixel == 0.01m in the dataset representation + self.default_erosion_radius = default_erosion_radius + self.trav_map_with_objects = trav_map_with_objects + self.num_waypoints = num_waypoints + self.waypoint_interval = int(waypoint_resolution / map_resolution) + + # Values loaded at runtime + self.trav_map_original_size = None + self.trav_map_size = None + self.mesh_body_id = None + self.floor_heights = None + self.floor_map = None + + # Run super method + super().__init__(map_resolution=map_resolution) + + def _load_map(self, maps_path, floor_heights=(0.0,)): + """ + Loads the traversability maps for all floors + + Args: + maps_path (str): Path to the folder containing the traversability maps + floor_heights (n-array): Height(s) of the floors for this map + + Returns: + int: Size of the loaded map + """ + if not os.path.exists(maps_path): + log.warning("trav map does not exist: {}".format(maps_path)) + return + + self.floor_heights = floor_heights + self.floor_map = [] + map_size = None + for floor in range(len(self.floor_heights)): + if self.trav_map_with_objects: + # TODO: Shouldn't this be generated dynamically? + trav_map = th.tensor( + cv2.imread(os.path.join(maps_path, "floor_trav_{}.png".format(floor)), cv2.IMREAD_GRAYSCALE) + ) + else: + trav_map = th.tensor( + cv2.imread(os.path.join(maps_path, "floor_trav_no_obj_{}.png".format(floor)), cv2.IMREAD_GRAYSCALE) + ) + + # If we do not initialize the original size of the traversability map, we obtain it from the image + # Then, we compute the final map size as the factor of scaling (default_resolution/resolution) times the + # original map size + if self.trav_map_original_size is None: + height, width = trav_map.shape + assert height == width, "trav map is not a square" + self.trav_map_original_size = height + map_size = int(self.trav_map_original_size * self.map_default_resolution / self.map_resolution) + + # We resize the traversability map to the new size computed before + trav_map = th.tensor(cv2.resize(trav_map.cpu().numpy(), (map_size, map_size))) + + # We make the pixels of the image to be either 0 or 255 + trav_map[trav_map < 255] = 0 + + self.floor_map.append(trav_map) + + return map_size + + @property + def n_floors(self): + """ + Returns: + int: Number of floors belonging to this map's associated scene + """ + return len(self.floor_heights) + + def _erode_trav_map(self, trav_map, robot=None): + # Erode the traversability map to account for the robot's size + if robot: + robot_chassis_extent = robot.reset_joint_pos_aabb_extent[:2] + radius = th.norm(robot_chassis_extent) / 2.0 + 0.2 + else: + radius = self.default_erosion_radius + radius_pixel = int(math.ceil(radius / self.map_resolution)) + trav_map = th.tensor(cv2.erode(trav_map.cpu().numpy(), th.ones((radius_pixel, radius_pixel)).cpu().numpy())) + return trav_map + + def get_random_point(self, floor=None, reference_point=None, robot=None): + """ + Sample a random point on the given floor number. If not given, sample a random floor number. + If @reference_point is given, sample a point in the same connected component as the previous point. + + Args: + floor (None or int): floor number. None means the floor is randomly sampled + Warning: if @reference_point is given, @floor must be given; + otherwise, this would lead to undefined behavior + reference_point (3-array): (x,y,z) if given, sample a point in the same connected component as this point + + Returns: + 2-tuple: + - int: floor number. This is the sampled floor number if @floor is None + - 3-array: (x,y,z) randomly sampled point + """ + if reference_point is not None: + assert floor is not None, "floor must be given if reference_point is given" + + # If nothing is given, sample a random floor and a random point on that floor + if floor is None and reference_point is None: + floor = th.randint(0, self.n_floors) + + # create a deep copy so that we don't erode the original map + trav_map = th.clone(self.floor_map[floor]) + trav_map = self._erode_trav_map(trav_map, robot=robot) + + if reference_point is not None: + # Find connected component + _, component_labels = cv2.connectedComponents(trav_map.cpu().numpy(), connectivity=4) + component_labels = th.tensor(component_labels) + + # If previous point is given, sample a point in the same connected component + prev_xy_map = self.world_to_map(reference_point[:2]) + prev_label = component_labels[prev_xy_map[0]][prev_xy_map[1]] + trav_space = th.where(component_labels == prev_label) + else: + trav_space = th.where(trav_map == 255) + idx = th.randint(0, high=trav_space[0].shape[0], size=(1,)).item() + xy_map = th.tensor([trav_space[0][idx], trav_space[1][idx]]) + x, y = self.map_to_world(xy_map) + z = self.floor_heights[floor] + return floor, th.tensor([x, y, z]) + + def get_shortest_path(self, floor, source_world, target_world, entire_path=False, robot=None): + """ + Get the shortest path from one point to another point. + If any of the given point is not in the graph, add it to the graph and + create an edge between it to its closest node. + + Args: + floor (int): floor number + source_world (2-array): (x,y) 2D source location in world reference frame (metric) + target_world (2-array): (x,y) 2D target location in world reference frame (metric) + entire_path (bool): whether to return the entire path + robot (None or BaseRobot): if given, erode the traversability map to account for the robot's size + + Returns: + 2-tuple: + - (N, 2) array: array of path waypoints, where N is the number of generated waypoints + - float: geodesic distance of the path + """ + source_map = tuple(self.world_to_map(source_world).tolist()) + target_map = tuple(self.world_to_map(target_world).tolist()) + + # create a deep copy so that we don't erode the original map + trav_map = th.clone(self.floor_map[floor]) + + trav_map = self._erode_trav_map(trav_map, robot=robot) + + path_map = astar(trav_map, source_map, target_map) + if path_map is None: + # No traversable path found + return None, None + path_world = self.map_to_world(path_map) + geodesic_distance = th.sum(th.norm(path_world[1:] - path_world[:-1], dim=1)) + path_world = path_world[:: self.waypoint_interval] + + if not entire_path: + path_world = path_world[: self.num_waypoints] + num_remaining_waypoints = self.num_waypoints - path_world.shape[0] + if num_remaining_waypoints > 0: + remaining_waypoints = th.tile(target_world, (num_remaining_waypoints, 1)) + path_world = th.cat((path_world, remaining_waypoints), dim=0) + + return path_world, geodesic_distance diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/materials/omnigibson_vray_mtl.mdl b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/materials/omnigibson_vray_mtl.mdl new file mode 100644 index 0000000000000000000000000000000000000000..be8b8ad16898f683d6bc1abc4ab8895a56a1e91e --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/materials/omnigibson_vray_mtl.mdl @@ -0,0 +1,118 @@ +///\authors: Stanford Vision and Learning Lab, Cem Gokmen +///\description: OmniGibson VRay material baked from 3ds Max, with texture map inputs. + +mdl 1.6; + +// Import +import ::anno::*; +import ::base::*; +import vray_maps::VRayBitmap; +import vray_maps::VRayBitmap_bump; +import vray_maps::vray_mono_output; +import vray_materials::VRayMtl; + +base::texture_return multiply_colors( + color color_1 = color(1.0, 1.0, 1.0), + color color_2 = color(.5, .5, .5), + float weight = 1.0 +) [[ + anno::hidden() +]] +{ + return base::blend_color_layers( + layers: base::color_layer[]( + base::color_layer( + layer_color: color_2, + weight: weight, + mode: base::color_layer_multiply + )), + base: color_1 + ); +} + +export material OmniGibsonVRayMtl( + uniform texture_2d diffuse_texture = texture_2d() [[ + anno::display_name("Diffuse Map"), + anno::in_group("Maps") + ]], + uniform texture_2d normal_texture = texture_2d() [[ + anno::display_name("Normal Map"), + anno::in_group("Maps") + ]], + uniform texture_2d glossiness_texture = texture_2d() [[ + anno::display_name("Reflection Glossiness Map"), + anno::in_group("Maps") + ]], + uniform texture_2d metalness_texture = texture_2d() [[ + anno::display_name("Metalness Map"), + anno::in_group("Maps") + ]], + uniform texture_2d refraction_texture = texture_2d() [[ + anno::display_name("Refraction Map"), + anno::in_group("Maps"), + anno::unused() + ]], + uniform texture_2d reflection_texture = texture_2d() [[ + anno::display_name("Reflection Map"), + anno::in_group("Maps") + ]], + uniform texture_2d reflection_ior_texture = texture_2d() [[ + anno::display_name("Fresnel Reflection IOR Map"), + anno::in_group("Maps") + ]], + color emission_color = color(1.f) + [[ + anno::in_group("Emission"), + anno::display_name("Emission Color") + ]], + uniform float emission_intensity = 0.f + [[ + anno::in_group("Emission"), + anno::display_name("Emission Intensity") + ]], + uniform float albedo_add = float(0.0) + [[ + anno::display_name("Albedo Add"), + anno::soft_range(float(-1.0f), float(1.0f)), + anno::description("Adds a constant value to the diffuse color "), + anno::in_group("Tints") + ]], + color diffuse_tint = color(1.0f) + [[ + anno::display_name("Color Tint"), + anno::description("When enabled, this color value is multiplied over the final albedo color"), + anno::in_group("Tints") + ]] +) +[[ + anno::display_name("OmniGibsonVRayMtl") +]] += vray_materials::VRayMtl( + Diffuse : multiply_colors( + vray_maps::VRayBitmap( + filename : diffuse_texture, + rgb_offset : albedo_add + ).tint, + diffuse_tint, 1.0 + ).tint, + Reflection : vray_maps::VRayBitmap( + filename : reflection_texture + ).tint, + reflection_glossiness : vray_maps::VRayBitmap( + filename : glossiness_texture + ).mono, + reflection_ior : vray_maps::VRayBitmap( + filename : reflection_ior_texture + ).mono, + reflection_metalness : vray_maps::VRayBitmap( + filename : metalness_texture + ).mono, + // Refraction : vray_maps::VRayBitmap( + // filename : refraction_texture + // ).tint, + texmap_bump : vray_maps::VRayBitmap_bump( + filename : normal_texture + ), + self_illumination : emission_color, + self_illumination_multiplier : emission_intensity +); diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/materials/vray_maps.mdl b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/materials/vray_maps.mdl new file mode 100644 index 0000000000000000000000000000000000000000..6d38da12977c333df2c69c5cf8d07aa88f351f42 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/materials/vray_maps.mdl @@ -0,0 +1,983 @@ +// Copyright 2023 NVIDIA Corporation. All rights reserved. +// +// NVIDIA CORPORATION and its licensors retain all intellectual property +// and proprietary rights in and to this software, related documentation +// and any modifications thereto. Any use, reproduction, disclosure or +// distribution of this software and related documentation without an express +// license agreement from NVIDIA CORPORATION is strictly prohibited. + +mdl 1.8; + +import ::anno::*; +import ::base::*; +import ::math::*; +import ::state::*; +import ::tex::*; + +export using ::base import texture_return; + +// Returns the normal n in tangent space, given n is in internal space. +float3 transform_internal_to_tangent(float3 n) +{ + return + n.x * float3(state::texture_tangent_u(0).x, state::texture_tangent_v(0).x, state::normal().x) + + n.y * float3(state::texture_tangent_u(0).y, state::texture_tangent_v(0).y, state::normal().y) + + n.z * float3(state::texture_tangent_u(0).z, state::texture_tangent_v(0).z, state::normal().z); +} + +// 3dsmax Bitmap Transformation Matrix +uniform float4x4 max_rotation_translation_scale +( + uniform float3 rotation = float3(0.) + [[ anno::description("Rotation applied to every UVW coordinate") ]], + uniform float3 translation = float3(0.) + [[ anno::description("Offset applied to every UVW coordinate") ]], + uniform float3 scaling = float3(1.) + [[ anno::description("Scale applied to every UVW coordinate") ]], + uniform bool u_mirror = false + [[ anno::description("Mirror repeat has twice the number of textures in the same space") ]], + uniform bool v_mirror = false + [[ anno::description("Mirror repeat has twice the number of textures in the same space") ]] +) +[[ + anno::description("Construct transformation matrix from Euler rotation, translation and scale") +]] +{ + float4x4 scale = + float4x4(u_mirror?scaling.x*2.:scaling.x , 0. , 0. , 0., + 0. , v_mirror?scaling.y*2.:scaling.y , 0. , 0., + 0. , 0. , scaling.z , 0., + u_mirror?1.:.5 , v_mirror?1.:.5 , .5 , 1.); + + float4x4 translate = + float4x4(1. , 0. , 0. , 0., + 0. , 1. , 0. , 0., + 0. , 0. , 1. , 0., + -0.5-translation.x, -0.5-translation.y, -0.5-translation.z, 1.); + + + // Euler rotation matrix xyz order + float3 s = math::sin(rotation); + float3 c = math::cos(rotation); + float4x4 rotate = + float4x4( c.y*c.z , c.y*s.z , -s.y , 0.0, + -c.x*s.z + s.x*s.y*c.z, c.x*c.z + s.x*s.y*s.z , s.x*c.y , 0.0, + s.x*s.z + c.x*s.y*c.z , -s.x*c.z + c.x*s.y*s.z, c.x*c.y , 0.0, + 0. , 0. , 0. , 1.); + return scale *rotate*translate; +} + +export enum vray_color_mode +[[ + anno::hidden() +]] +{ + mode_color, + mode_temperature +}; + +export enum vray_color_primaries +[[ + anno::hidden() +]] +{ + primaries_none, + primaries_sRGB, + primaries_ACEScg +}; + +export enum vray_bitmap_primaries +[[ + anno::hidden() +]] +{ + bm_primaries_default, + bm_primaries_sRGB, + bm_primaries_ACEScg, + bm_primaries_raw +}; + +export enum vray_rgb_output +[[ + anno::hidden() +]] +{ + rgb_output_rgb_color, + rgb_output_alpha_as_grey, + rgb_output_intensity_as_grey +}; + +export enum vray_mono_output +[[ + anno::hidden() +]] +{ + mono_output_rgb_intensity, + mono_output_alpha +}; + +export enum vray_alpha_source +[[ + anno::hidden() +]] +{ + alpha_source_image_alpha, + alpha_source_intensity, + alpha_source_opaque +}; + +// VRayBitmap map +export texture_return +[[ anno::node_output_port_default(anno::node_port_value_and_fields)]] +VRayBitmap +( + // UVW Coordinates + uniform int mapChannel=1 + [[ + anno::in_group("Coordinates"), + anno::display_name("Map channel") + ]], + uniform float U_Offset = 0.f + [[ + anno::in_group("Coordinates"), + anno::display_name("U Offset") + ]], + uniform float V_Offset = 0.f + [[ + anno::in_group("Coordinates"), + anno::display_name("V Offset") + ]], + uniform float U_Tiling = 1.f + [[ + anno::in_group("Coordinates"), + anno::display_name("U Tiling") + ]], + uniform float V_Tiling = 1.f + [[ + anno::in_group("Coordinates"), + anno::display_name("V Tiling") + ]], + uniform bool U_Tile=true //it is actually an error if both mirror and tile are true + [[ + anno::in_group("Coordinates"), + anno::display_name("U Tile") + ]], + uniform bool U_Mirror=false + [[ + anno::in_group("Coordinates"), + anno::display_name("U Mirror") + ]], + uniform bool V_Tile=true + [[ + anno::in_group("Coordinates"), + anno::display_name("V Tile") + ]], + uniform bool V_Mirror=false + [[ + anno::in_group("Coordinates"), + anno::display_name("V Mirror") + ]], + uniform float U_angle = 0.f + [[ + anno::in_group("Coordinates"), + anno::display_name("U Angle") + ]], + uniform float V_angle = 0.f + [[ + anno::in_group("Coordinates"), + anno::display_name("V Angle") + ]], + uniform float W_angle = 0.f + [[ + anno::in_group("Coordinates"), + anno::display_name("W Angle") + ]], + uniform int UVW_Type = 0 //enum? + [[ + anno::in_group("Coordinates"), + anno::display_name("UVW Type"), + anno::unused(), + anno::hidden() + ]], + + // Bitmap + uniform texture_2d filename = texture_2d() + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("Bitmap") + ]], + uniform float multiplier = 1.f + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("Overall multiplier") + ]], + uniform vray_rgb_output rgb_output = rgb_output_rgb_color + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("RGB output") + ]], + uniform vray_mono_output mono_output = mono_output_rgb_intensity + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("Mono output") + ]], + uniform vray_alpha_source alpha_source = alpha_source_image_alpha + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("Alpha source") + ]], + uniform vray_bitmap_primaries rgb_primaries = bm_primaries_raw + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("RGB primaries"), + anno::unused(), + anno::hidden() + ]], + uniform bool crop_enable = false + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("Crop") + ]], + uniform float crop_u = 0.f //u+w and v+h are always <=1.0 + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("U Crop"), + anno::hard_range(0.f, 1.f) + ]], + uniform float crop_w = 1.f + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("W Crop"), + anno::hard_range(0.f, 1.f) + ]], + uniform float crop_v = 0.f + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("V Crop"), + anno::hard_range(0.f, 1.f) + ]], + uniform float crop_h = 1.f + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("H Crop"), + anno::hard_range(0.f, 1.f) + ]], + + // Output + uniform float bump_amount = 1.f + [[ + anno::in_group("Output"), + anno::display_name("Bump amount"), + anno::unused(), + anno::hidden() + ]], + uniform bool clamp = false + [[ + anno::in_group("Output"), + anno::display_name("Clamp"), + anno::unused(), + anno::hidden() + ]], + uniform bool invert = false + [[ + anno::in_group("Output"), + anno::display_name("Invert") + ]], + uniform bool alphaFromRGB = false + [[ + anno::in_group("Output"), + anno::display_name("Alpha from RGB intensity"), + anno::unused(), + anno::hidden() + ]], + uniform float output_amount = 1.f + [[ + anno::in_group("Output"), + anno::display_name("Output amount") + ]], + uniform float rgb_level = 1.f + [[ + anno::in_group("Output"), + anno::display_name("RGB level") + ]], + uniform float rgb_offset = 0.f + [[ + anno::in_group("Output"), + anno::display_name("RGB Offset") + ]] +) +[[ + anno::author("NVIDIA Corporation"), + anno::display_name("Bitmap"), + anno::description("VRay-MDL Bitmap") +]] +{ + uniform float clip_u = crop_enable ? crop_u : 0.f; + uniform float clip_w = crop_enable ? crop_w : 1.f; + uniform float clip_v = crop_enable ? crop_v : 0.f; + uniform float clip_h = crop_enable ? crop_h : 1.f; + + texture_return bitmap_sample = base::file_texture + ( + texture : filename, + mono_source : (alpha_source == alpha_source_image_alpha) ? base::mono_alpha : base::mono_average, + crop_u : float2(clip_u, clip_w + clip_u), + crop_v : float2(1.f - clip_v - clip_h, 1.f - clip_v), + uvw : base::transform_coordinate + ( + transform : max_rotation_translation_scale + ( + scaling : float3(U_Tiling, V_Tiling, 1.f), + rotation : float3(U_angle, V_angle, W_angle)/180.f*math::PI , + translation : float3(U_Offset, V_Offset, 0.f), u_mirror : U_Mirror, v_mirror : V_Mirror + ), + coordinate : base::coordinate_source(texture_space: mapChannel-1) + ), + wrap_u : U_Tile ? tex::wrap_repeat : U_Mirror ? tex::wrap_mirrored_repeat : tex::wrap_clip, + wrap_v : V_Tile ? tex::wrap_repeat : V_Mirror ? tex::wrap_mirrored_repeat : tex::wrap_clip + ); + + bitmap_sample.tint = invert ? + bitmap_sample.tint * (-rgb_level * output_amount * multiplier ) + (1.f - rgb_offset) : + bitmap_sample.tint * (rgb_level * output_amount * multiplier) + rgb_offset; + + float alpha = (alpha_source != alpha_source_opaque) ? bitmap_sample.mono : 1.f; + bitmap_sample.tint = bitmap_sample.tint*alpha; + + // determinate mono output + if(mono_output == mono_output_alpha) + bitmap_sample.mono = alpha; + else + bitmap_sample.mono = math::average(bitmap_sample.tint); + + // determinate rgb output + if(rgb_output == rgb_output_alpha_as_grey) + bitmap_sample.tint = color(alpha); + else if(rgb_output == rgb_output_intensity_as_grey) + bitmap_sample.tint = color(math::average(bitmap_sample.tint)); + + return bitmap_sample; +} +// VRayBitmap Map for Bump +export float3 +[[ anno::node_output_port_default(anno::node_port_value_and_fields)]] +VRayBitmap_bump +( + // UVW Coordinates + uniform int mapChannel=1 + [[ + anno::in_group("Coordinates"), + anno::display_name("Map channel") + ]], + uniform bool U_Tile=true + [[ + anno::in_group("Coordinates"), + anno::display_name("U Tile") + ]], + uniform bool U_Mirror=false + [[ + anno::in_group("Coordinates"), + anno::display_name("U Mirror") + ]], + uniform bool V_Tile=true + [[ + anno::in_group("Coordinates"), + anno::display_name("V Tile") + ]], + uniform bool V_Mirror=false + [[ + anno::in_group("Coordinates"), + anno::display_name("V Mirror") + ]], + uniform float U_angle = 0.f + [[ + anno::in_group("Coordinates"), + anno::display_name("U Angle") + ]], + uniform float V_angle = 0.f + [[ + anno::in_group("Coordinates"), + anno::display_name("V Angle") + ]], + uniform float W_angle = 0.f + [[ + anno::in_group("Coordinates"), + anno::display_name("W Angle") + ]], + uniform float U_Offset = 0.f + [[ + anno::in_group("Coordinates"), + anno::display_name("U Offset") + ]], + uniform float V_Offset = 0.f + [[ + anno::in_group("Coordinates"), + anno::display_name("V Offset") + ]], + uniform float U_Tiling = 1.f + [[ + anno::in_group("Coordinates"), + anno::display_name("U Tiling") + ]], + uniform float V_Tiling = 1. + [[ + anno::in_group("Coordinates"), + anno::display_name("V Tiling") + ]], + uniform int UVW_Type = 0 //enum? + [[ + anno::in_group("Coordinates"), + anno::display_name("UVW Type"), + anno::unused() + ]], + + // Bitmap + uniform texture_2d filename = texture_2d() + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("Bitmap") + ]], + uniform bool crop_enable = false + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("Crop") + ]], + uniform float crop_u = 0.f //u+w and v+h are always <=1.0 + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("U Crop"), + anno::hard_range(0.f, 1.f) + ]], + uniform float crop_w = 1.f + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("W Crop"), + anno::hard_range(0.f, 1.f) + ]], + uniform float crop_v = 0.f + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("V Crop"), + anno::hard_range(0.f, 1.f) + ]], + uniform float crop_h = 1.f + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("H Crop"), + anno::hard_range(0.f, 1.f) + ]], + uniform float factor = 1.f + [[ + anno::in_group("Bitmap parameters"), + anno::display_name("Bump amount") + ]], + + // Output + uniform float bump_amount = 1.f + [[ + anno::in_group("Output"), + anno::display_name("Bump output") + ]], + uniform bool clamp = false + [[ + anno::in_group("Output"), + anno::display_name("Clamp"), + anno::unused() + ]], + uniform bool invert = false + [[ + anno::in_group("Output"), + anno::display_name("Invert") + ]], + uniform bool alphaFromRGB = false + [[ + anno::in_group("Output"), + anno::display_name("Alpha from RGB intensity"), + anno::unused() + ]], + uniform float output_amount = 1.f + [[ + anno::in_group("Output"), + anno::display_name("Output amount"), + anno::unused() + ]], + uniform float rgb_level = 1.f + [[ + anno::in_group("Output"), + anno::display_name("RGB level"), + anno::unused() + ]], + uniform float rgb_offset = 0.f + [[ + anno::in_group("Output"), + anno::display_name("RGB Offset"), + anno::unused() + ]] +) +[[ + anno::author("NVIDIA Corporation"), + anno::display_name("Bitmap Bump"), + anno::description("VRay-MDL Bitmap for bump") +]] +{ + uniform float clip_u = crop_enable ? crop_u : 0.f; + uniform float clip_w = crop_enable ? crop_w : 1.f; + uniform float clip_v = crop_enable ? crop_v : 0.f; + uniform float clip_h = crop_enable ? crop_h : 1.f; + + return base::file_bump_texture + ( + texture : filename, + crop_u : float2(clip_u, clip_w + clip_u), + crop_v : float2(1.f - clip_v - clip_h, 1.f - clip_v), + uvw : base::transform_coordinate + ( + transform : max_rotation_translation_scale + ( + scaling : float3(U_Tiling, V_Tiling, 1.f), + rotation : float3(U_angle, V_angle,W_angle)/(180.*math::PI), + translation : float3(U_Offset, V_Offset, 0.f), u_mirror : U_Mirror, v_mirror : V_Mirror + ), + coordinate : base::coordinate_source(texture_space: mapChannel - 1) + ), + wrap_u : U_Tile ? tex::wrap_repeat : U_Mirror ? tex::wrap_mirrored_repeat : tex::wrap_clip, + wrap_v : V_Tile ? tex::wrap_repeat : V_Mirror ? tex::wrap_mirrored_repeat : tex::wrap_clip, + factor : invert ? -10.f*factor*bump_amount : 10.f*factor*bump_amount + ); +} + +// VRayBump2Normal Map for Bump +export enum vray_bump2normal_mode +[[ + anno::hidden() +]] +{ + b2n_tangent_space, + b2n_local_XYZ, + b2n_screen_space, + b2n_world_space +}; + +export texture_return +[[ anno::node_output_port_default(anno::node_port_value_and_fields)]] +VRayBump2Normal +( + float3 bump_map = state::normal() + [[ + anno::in_group("Parameters"), + anno::display_name("Bump map") + ]], + uniform float bump_map_mult = 100.f + [[ + anno::in_group("Parameters"), + anno::display_name("Bump map multiplier"), + anno::hard_range(0.f, 100.f) + ]], + uniform vray_bump2normal_mode mode = b2n_tangent_space + [[ + anno::in_group("Parameters"), + anno::display_name("Mode"), + anno::unused(), + anno::hidden() + ]], + uniform int map_channel=1 + [[ + anno::in_group("Coordinates"), + anno::display_name("Map channel"), + anno::unused(), + anno::hidden() + ]] +) +[[ + anno::author("NVIDIA Corporation"), + anno::display_name("Bump to Normal"), + anno::description("VRay-MDL Bump to Normal") +]] +{ + texture_return normal_tex; + + float3 normal_tangent_space = + transform_internal_to_tangent(math::normalize(state::normal() + (bump_map - state::normal())*(bump_map_mult*0.01f))); + + normal_tex.tint = color( (normal_tangent_space + float3(1.f))*0.5f ); + normal_tex.mono = 1.f; + return normal_tex; +} + +// VRayColor Map +export texture_return +[[ anno::node_output_port_default(anno::node_port_value_and_fields)]] +VRayColor +( + uniform vray_color_mode color_mode = mode_color + [[ + anno::in_group("VRayColor Parameters"), + anno::display_name("Color mode") + ]], + uniform float temperature = 6500.f + [[ + anno::in_group("VRayColor Parameters"), + anno::display_name("Temperature"), + anno::hard_range(350.f, 1000000000.f) + ]], + uniform float red = 0.5f + [[ + anno::in_group("VRayColor Parameters"), + anno::display_name("Red"), + anno::soft_range(0.f, 1.f) + ]], + uniform float green = 0.5f + [[ + anno::in_group("VRayColor Parameters"), + anno::display_name("Green"), + anno::soft_range(0.f, 1.f) + ]], + uniform float blue = 0.5f + [[ + anno::in_group("VRayColor Parameters"), + anno::display_name("Blue"), + anno::soft_range(0.f, 1.f) + ]], + uniform float rgb_multiplier = 1.f + [[ + anno::in_group("VRayColor Parameters"), + anno::display_name("RGB Multiplier") + ]], + uniform float alpha = 1.f + [[ + anno::in_group("VRayColor Parameters"), + anno::display_name("Alpha"), + anno::hard_range(0.f, 1.f) + ]], + uniform float color_gamma = 1.0f + [[ + anno::in_group("VRayColor Parameters"), + anno::display_name("Color gamma"), + anno::hard_range(0.05f, 20.f) + ]], + uniform vray_color_primaries rgb_primaries = primaries_none + [[ + anno::in_group("VRayColor Parameters"), + anno::display_name("RGB primaries"), + anno::unused(), + anno::hidden() + ]] +) +[[ + anno::author("NVIDIA Corporation"), + anno::display_name("Color"), + anno::description("VRay-MDL Color") +]] +{ + float3 rgb(red, green, blue); + + // using temperature?. Then convert from Kelvin to RGB + if(color_mode == mode_temperature) + { + float k = temperature*0.01f; + + // red + if (temperature < 6600.f) + { + rgb.x = 1.f; + } + else + { + float r = k - 55.f; + r = (351.9769f + 0.1142f * r - 40.2537f * math::log(r))/255.f; + rgb.x = math::clamp(r, 0.f, 1.f); + } + + // green + if (temperature < 6600.f) + { + float g = k - 2.f; + g = (-155.2549f - 0.4460f * g + 104.4922f * math::log(g))/255.f; + rgb.y = math::clamp(g, 0.f, 1.f); + + } + else + { + float g = k - 50.f; + g = (325.4494f + 0.0794f * g - 28.0853f * math::log(g))/255.f; + rgb.y = math::clamp(g, 0.f, 1.f); + } + + // blue + if (temperature >= 6600.f) + { + rgb.z = 1.f; + } + else if (temperature <= 2000.f) + { + rgb.z = 0.f; + } + else + { + float b = k - 10.f; + b = (-254.7694f + 0.8274f * blue + 115.6799f * math::log(b))/255.f; + rgb.z = math::clamp(b, 0.f, 1.f); + } + } + + // apply gamma + if(color_gamma != 1.f) + rgb = math::pow(rgb, 1.f/color_gamma); + + // apply multiplier + rgb *= rgb_multiplier; + + // fix ranges and return + rgb = math::clamp(rgb, 0.f, 1.f); + return texture_return(color(rgb), alpha); +} + +// VRayColor Map for Bump +export float3 +[[ anno::node_output_port_default(anno::node_port_value_and_fields)]] +VRayColor_bump +( +) +[[ + anno::author("NVIDIA Corporation"), + anno::display_name("Color Bump"), + anno::description("VRay-MDL Color for bump") +]] +{ + return state::normal(); +} + +// VRayColor2Bump Map for Bump +export float3 +[[ anno::node_output_port_default(anno::node_port_value_and_fields)]] +VRayColor2Bump_bump +( + float3 map = state::normal() + [[ + anno::in_group("Parameters"), + anno::display_name("Bump map") + ]], + uniform float height = 2.0f + [[ + anno::in_group("Parameters"), + anno::display_name("Height"), + anno::unused(), + anno::hidden() + ]], + uniform float bump_delta_scale = 1.0f + [[ + anno::in_group("Parameters"), + anno::display_name("Bump delta scale"), + anno::unused(), + anno::hidden(), + anno::hard_range(0.f, 1.f) + ]] +) +[[ + anno::author("NVIDIA Corporation"), + anno::display_name("Color to Bump"), + anno::description("VRay-MDL Color to Bump") +]] +{ + return map; +} + +// VRay Dirt Map +export texture_return +[[ anno::node_output_port_default(anno::node_port_value_and_fields)]] +VRayDirt +( + float radius = 10.f + [[ + anno::in_group("VRayDirt Parameters"), + anno::display_name("Radius"), + anno::unused(), + anno::hidden() + ]], + color occluded_color = color(0.f) + [[ + anno::in_group("VRayDirt Parameters"), + anno::display_name("Occluded color"), + anno::unused(), + anno::hidden() + ]], + color unoccluded_color = color(1.f) + [[ + anno::in_group("VRayDirt Parameters"), + anno::display_name("Unoccluded color") + ]] +) +[[ + anno::author("NVIDIA Corporation"), + anno::display_name("Dirt"), + anno::description("VRay-MDL Dirt") +]] +{ + return texture_return(unoccluded_color, 1.f); +} + +// VRay Edges Tex Map +export texture_return +[[ anno::node_output_port_default(anno::node_port_value_and_fields)]] +VRayEdgesTex +( + color edges_color = color(1.f) + [[ + anno::in_group("VRayEdgesTex params"), + anno::display_name("Color") + ]] +) +[[ + anno::author("NVIDIA Corporation"), + anno::display_name("EdgesTex"), + anno::description("VRay-MDL EdgesTex") +]] +{ + return texture_return(edges_color, 1.f); +} + +// VRay Edges Tex Map for bump +export float3 +[[ anno::node_output_port_default(anno::node_port_value_and_fields)]] +VRayEdgesTex_bump +( + color edges_color = color(1.f) + [[ + anno::in_group("VRayEdgesTex params"), + anno::display_name("Color"), + anno::unused(), + anno::hidden() + ]], + uniform float radius = 0.1f + [[ + anno::in_group("VRayEdgesTex params"), + anno::display_name("Radius"), + anno::hard_range(0.f, 100.f) + + ]], + uniform bool same_object_only = true + [[ + anno::in_group("VRayEdgesTex params"), + anno::display_name("Consider same object only") + ]], + uniform int corners_mode = 0 + [[ + anno::in_group("VRayEdgesTex params"), + anno::display_name("Corners"), + anno::unused(), + anno::hidden() + ]], + float multiplier = 1.f + [[ + anno::in_group("VRayEdgesTex params"), + anno::display_name("Multiplier"), + anno::unused(), + anno::hidden() + ]] +) +[[ + anno::author("NVIDIA Corporation"), + anno::display_name("EdgesTex Bump"), + anno::description("VRay-MDL EdgesTex for bump") +]] +{ + return state::rounded_corner_normal(radius*state::meters_per_scene_unit(), !same_object_only); +} + +// VRay Normap Map for bump +export float3 +[[ anno::node_output_port_default(anno::node_port_value_and_fields)]] +VRayNormalMap_bump +( + texture_return normal_map = texture_return() + [[ + anno::in_group("VRayNormalMap Parameters"), + anno::display_name("Normal map") + ]], + float3 bump_map = state::normal() + [[ + anno::in_group("VRayNormalMap Parameters"), + anno::display_name("Bump map") + ]], + uniform float normal_amount = 1.f + [[ + anno::in_group("VRayNormalMap Parameters"), + anno::display_name("Normal amount"), + anno::hard_range(-1000.f, 1000.f) + ]], + uniform float bump_amount = 1.f + [[ + anno::in_group("VRayNormalMap Parameters"), + anno::display_name("Bump amount"), + anno::hard_range(-1000.f, 1000.f) + ]], + uniform bool flip_red = false + [[ + anno::in_group("VRayNormalMap Parameters"), + anno::display_name("Flip red") + ]], + uniform bool flip_green = false + [[ + anno::in_group("VRayNormalMap Parameters"), + anno::display_name("Flip green") + ]], + uniform bool swap_rg = false + [[ + anno::in_group("VRayNormalMap Parameters"), + anno::display_name("Swap red and green") + ]], + uniform int map_channel = 1 + [[ + anno::in_group("VRayNormalMap Parameters"), + anno::display_name("Map channel"), + anno::hidden(), + anno::unused() + ]], + uniform float map_rotation = 0.f + [[ + anno::in_group("VRayNormalMap Parameters"), + anno::display_name("Map rotation"), + anno::hard_range(0.f, 360.f), + anno::hidden(), + anno::unused() + ]], + uniform float normal_map_amount = 1.0f + [[ + anno::in_group("VRayNormalMap Parameters"), + anno::display_name("Map amount"), + anno::hard_range(-10.f, 10.f) + ]] +) +[[ + anno::author("NVIDIA Corporation"), + anno::display_name("Normal Map"), + anno::description("VRay-MDL Normal Map for bump") +]] +{ + float3 tangent_space_normal = float3(normal_map.tint); + + if(flip_red) + tangent_space_normal.x = 1.f - tangent_space_normal.x; + + if(flip_green) + tangent_space_normal.y = 1.f - tangent_space_normal.y; + + if(swap_rg) + { + float tmp = tangent_space_normal.x; + tangent_space_normal.x = tangent_space_normal.y; + tangent_space_normal.y = tmp; + } + + float normal_factor = normal_amount*(normal_map_amount); + tangent_space_normal = (tangent_space_normal - float3(0.5f))*(2.f*normal_factor); + + float3 mapped_normal = math::normalize( + state::texture_tangent_u(0) * tangent_space_normal.x + + state::texture_tangent_v(0) * tangent_space_normal.y + + state::normal() * (tangent_space_normal.z + (1.f - normal_factor))); + + float3 bumped_normal = math::normalize(math::lerp(state::normal(), bump_map, bump_amount*normal_map_amount)); + + return math::normalize(mapped_normal + bumped_normal); +} diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/materials/vray_materials.mdl b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/materials/vray_materials.mdl new file mode 100644 index 0000000000000000000000000000000000000000..2875cfac20eda7f1fb204bc1fca92acfa3aeef9b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/materials/vray_materials.mdl @@ -0,0 +1,187 @@ +// Copyright 2023 NVIDIA Corporation. All rights reserved. +// +// NVIDIA CORPORATION and its licensors retain all intellectual property +// and proprietary rights in and to this software, related documentation +// and any modifications thereto. Any use, reproduction, disclosure or +// distribution of this software and related documentation without an express +// license agreement from NVIDIA CORPORATION is strictly prohibited. + +mdl 1.8; + +import ::anno::*; +import ::df::*; +import ::math::*; +import ::state::*; + + +// VRay Material +export material VRayMtl( + color Diffuse = color(0.5f) + [[ + anno::in_group("Diffuse Parameters"), + anno::display_name("Diffuse") + ]], + uniform float diffuse_roughness = 0.f + [[ + anno::in_group("Diffuse Parameters"), + anno::display_name("Roughness"), + anno::hard_range(0.f, 1.f) + ]], + color Reflection = color(0.f) + [[ + anno::in_group("Reflections"), + anno::display_name("Reflect") + ]], + float reflection_glossiness = 1.f + [[ + anno::in_group("Reflections"), + anno::display_name("Glossiness"), + anno::hard_range(0.f, 1.f) + ]], + float reflection_ior = 1.6f + [[ + anno::in_group("Reflections"), + anno::display_name("Fresnel IOR"), + anno::soft_range(0.2f, 5.f), + anno::hard_range(1.e-6f, 100.f) + ]], + float reflection_metalness = 0.f + [[ + anno::in_group("Reflections"), + anno::display_name("Metalness"), + anno::hard_range(0.f, 1.f) + ]], + uniform float refraction_ior = 1.6f // not textureable to be physically plausible + [[ + anno::in_group("Refractions"), + anno::display_name("IOR"), + anno::soft_range(0.2,5.), + anno::hard_range(1.e-6f, 100.f) + ]], + color self_illumination = color(0.f) + [[ + anno::in_group("Self-Illumination"), + anno::display_name("Self-illumination") + ]], + uniform float self_illumination_multiplier = 1.f + [[ + anno::in_group("Self-Illumination"), + anno::display_name("Multiplier") + ]], + float3 texmap_bump = state::normal() + [[ + anno::in_group("Maps"), + anno::display_name("Bump Map") + ]], + float texmap_opacity = 1.0f + [[ + anno::in_group("Maps"), + anno::display_name("Opacity Map") + ]], + uniform bool thin_walled = false + [[ + anno::in_group("Options"), + anno::hidden() + ]], + float coat_amount = 1.f + [[ + anno::in_group("Coat Parameters"), + anno::display_name("White coat amount"), + anno::hard_range(0.f, 1.f) + ]] +) +[[ + anno::author("NVIDIA Corporation and Stanford Vision and Learning Lab") +]] + = let + { + float reflection_roughness = math::pow((1.f - reflection_glossiness), 2.f); + float R0 = math::pow((1.f - reflection_ior)/(1.f + reflection_ior), 2.f); + + // diffuse + bsdf diffuse_bsdf = + df::weighted_layer + ( + weight : 1.f, + layer : df::diffuse_reflection_bsdf + ( + tint : Diffuse, + roughness : diffuse_roughness + ), + normal : texmap_bump + ); + + // reflection + bsdf glossy_reflection_bsdf = + df::simple_glossy_bsdf( + mode: df::scatter_reflect, + tint: Reflection, + roughness_u: reflection_roughness + ); + + // diffuse glossy reflection + bsdf diffuse_glossy_reflection_bsdf = + df::simple_glossy_bsdf( + mode: df::scatter_reflect, + tint: Diffuse, + roughness_u: reflection_roughness + ); + + // surface + float reflection_intensity = math::luminance(Reflection); + bsdf surface_bsdf = + df::color_custom_curve_layer + ( + normal_reflectivity : color(R0 * reflection_intensity), + grazing_reflectivity: color(reflection_intensity), + layer : glossy_reflection_bsdf, + base : + df::weighted_layer + ( + weight : reflection_metalness, + layer : diffuse_glossy_reflection_bsdf, + base : diffuse_bsdf, + normal : texmap_bump + ), + normal : texmap_bump + ); + + // coat + bsdf coat_bsdf = + df::fresnel_layer + ( + ior : 1.6f, + weight : coat_amount, + layer : df::simple_glossy_bsdf + ( + tint : color(1.f), + roughness_u : 1.f, + mode : df::scatter_reflect + ), + base : df::tint + ( + tint : color(1.f), + base : surface_bsdf + ), + normal : texmap_bump + ); + +} +in material +( + ior : color(refraction_ior), + thin_walled : thin_walled, + surface : material_surface + ( + scattering : coat_bsdf, + emission : material_emission + ( + emission : df::diffuse_edf(), + intensity : self_illumination*self_illumination_multiplier + ) + ), + geometry : material_geometry + ( + cutout_opacity: texmap_opacity + ) +); diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/metrics/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..21434e2df1e5253c19becc9361f5feba080cf44f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/metrics/__init__.py @@ -0,0 +1,5 @@ +from omnigibson.metrics.agent_metric import AgentMetric +from omnigibson.metrics.metric_base import MetricBase +from omnigibson.metrics.task_metric import TaskMetric + +__all__ = ["AgentMetric", "TaskMetric", "MetricBase"] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/metrics/agent_metric.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/metrics/agent_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..bc5295b01870f4adfc721d9fd2269b21d58fe1f6 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/metrics/agent_metric.py @@ -0,0 +1,66 @@ +import copy +import torch as th +from omnigibson.metrics.metric_base import MetricBase +from typing import Optional + + +class AgentMetric(MetricBase): + def __init__(self, human_stats: Optional[dict] = None, env_idx: int = 0, env_accessor=None): + super().__init__(env_idx=env_idx, env_accessor=env_accessor) + self.initialized = False + self.human_stats = human_stats + if human_stats is None: + print("No human stats provided.") + else: + self.human_stats = { + "base": self.human_stats["distance_traveled"], + "left": self.human_stats["left_eef_displacement"], + "right": self.human_stats["right_eef_displacement"], + } + + def reset(self, env=None): + self.state[self._scene(env)] = dict() + self.initialized = False + + def _compute_step_metrics(self, env, action, obs, reward, terminated, truncated, info): + robot = env.robot if env is self.env_accessor else self._scene(env).robots[0] + self.next_state_cache = { + "base": {"position": robot.get_position_orientation()[0]}, + **{arm: {"position": robot.get_eef_position(arm)} for arm in robot.arm_names}, + } + + if not self.initialized: + self.delta_agent_distance = {part: [] for part in ["base"] + robot.arm_names} + self.state_cache = copy.deepcopy(self.next_state_cache) + self.initialized = True + + distance = th.linalg.norm( + self.next_state_cache["base"]["position"] - self.state_cache["base"]["position"] + ).item() + self.delta_agent_distance["base"].append(distance) + + for arm in robot.arm_names: + eef_distance = th.linalg.norm( + self.next_state_cache[arm]["position"] - self.state_cache[arm]["position"] + ).item() + self.delta_agent_distance[arm].append(eef_distance) + + self.state_cache = copy.deepcopy(self.next_state_cache) + + return self.delta_agent_distance + + def _compute_episode_metrics(self, env, episode_info): + # Use the accumulated state from episode_info + all_distances = episode_info.get("delta_agent_distance", self.delta_agent_distance) + results = { + "agent_distance": {k: sum(v) for k, v in all_distances.items()}, + } + results.update( + { + "normalized_agent_distance": { + k: (self.human_stats[k] / v if v != 0 else float("inf")) + for k, v in results["agent_distance"].items() + } + } + ) + return results diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/metrics/metric_base.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/metrics/metric_base.py new file mode 100644 index 0000000000000000000000000000000000000000..6bcb15f4e1d0a2399416a140ac5b04a71e088aff --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/metrics/metric_base.py @@ -0,0 +1,130 @@ +class MetricBase: + """ + Class for defining a programmatic environment metric that can be tracked over the course of + each environment episode + """ + + def __init__(self, env_idx=0, env_accessor=None): + # Batched evaluation binds a metric to an accessor, which owns the mapping into the shared + # environment. env_idx remains as a compatibility path for MetricsWrapper and external users. + self.env_idx = env_idx + self.env_accessor = env_accessor + self.state = dict() + + def _resolve_env(self, env): + if env is not None: + return env + if self.env_accessor is None: + raise ValueError("Metric is not bound to an environment accessor; pass env explicitly.") + return self.env_accessor + + def _scene(self, env=None): + """Return the scene tracked by this metric for bound and legacy callers.""" + env = self._resolve_env(env) + return env.scene if env is self.env_accessor else env.scenes[self.env_idx] + + @classmethod + def is_compatible(cls, env): + """ + Checks if this metric class is compatible with @env + + Args: + env (og.Environment or EnvironmentWrapper): Environment to check compatibility + + Returns: + bool: Whether this metric is compatible or not + """ + return True + + @classmethod + def validate_episode(cls, episode_metrics, **kwargs): + """ + Validates the given @episode_metrics from self.aggregate_results using any specific @kwargs + + Args: + episode_metrics (dict): Metrics aggregated using self.aggregate_results + kwargs (Any): Any keyword arguments relevant to this specific MetricBase + + Returns: + dict: Keyword-mapped dictionary mapping each validation test name to {"success": bool, "feedback": str} dict + where "success" is True if the given @episode_metrics pass that specific test; if False, "feedback" + provides information as to why the test failed + """ + raise NotImplementedError + + def step(self, env=None, action=None, obs=None, reward=None, terminated=None, truncated=None, info=None): + """ + Steps this metric, updating any internal values being tracked. + + Args: + action (th.Tensor): action deployed resulting in @obs + obs (dict): state, i.e. observation + reward (float): reward, i.e. reward at this current timestep + terminated (bool): terminated, i.e. whether this episode ended due to a failure or success + truncated (bool): truncated, i.e. whether this episode ended due to a time limit etc. + info (dict): info, i.e. dictionary with any useful information + """ + env = self._resolve_env(env) + step_metrics = self._compute_step_metrics(env, action, obs, reward, terminated, truncated, info) + scene = self._scene(env) + assert scene in self.state, f"Environment {scene} is not being tracked, please call 'self.reset()' to track!" + state = self.state[scene] + for k, v in step_metrics.items(): + if k not in state: + state[k] = [] + state[k].append(v) + + def _compute_step_metrics(self, env, action, obs, reward, terminated, truncated, info): + """ + Compute any step-wise metrics at the current environment step that just occurred + + Args: + action (th.Tensor): action deployed resulting in @obs + obs (dict): state, i.e. observation + reward (float): reward, i.e. reward at this current timestep + terminated (bool): terminated, i.e. whether this episode ended due to a failure or success + truncated (bool): truncated, i.e. whether this episode ended due to a time limit etc. + info (dict): info, i.e. dictionary with any useful information + + Returns: + dict: Any per-step information that should be internally tracked + """ + raise NotImplementedError + + def _compute_episode_metrics(self, env, episode_info): + """ + Computes the aggregated metrics over the current trajectory episode in @env + + Args: + episode_info (dict): Internal information that was tracked using @_compute_episode metrics. This + information is is the same key-mapped dict as @_compute_step_metrics mapped to the + list of values aggregated over the current trajectory episode + + Returns: + dict: Any per-step information that should be internally tracked + """ + raise NotImplementedError + + def aggregate(self, env=None): + """ + Aggregates information over the current trajectory tracked by this metric. + + Returns: + dict: Any relevant aggregated metric information + """ + env = self._resolve_env(env) + scene = self._scene(env) + if scene in self.state: + if self.state[scene] == dict(): + return dict() + else: + return self._compute_episode_metrics(env=env, episode_info=self.state[scene]) + else: + print("Environment not yet tracked, skipping metric aggregation!") + return dict() + + def reset(self, env=None): + """ + Resets this metric for its bound logical environment. + """ + self.state[self._scene(env)] = dict() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/metrics/task_metric.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/metrics/task_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..2d4f460c0b7aa449f683e2e00e2d47e2c3e09f86 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/metrics/task_metric.py @@ -0,0 +1,81 @@ +import omnigibson as og +from omnigibson.metrics.metric_base import MetricBase +from typing import Optional, Sequence + + +def compute_q_score( + success: bool, + now_satisfied_options: Sequence[Sequence[bool]], + initial_satisfied_options: Sequence[Sequence[bool]], +) -> float: + """ + Partial-success (Q-score) for one episode/env: a full success scores 1.0; otherwise the fraction + of goal predicates that were NOT satisfied at episode start but ARE satisfied now, maximized over + the alternative goal-state options. Mirrors the pre-refactor inline formula (lives here next to its + only caller, TaskMetric). Empty options/no options return 0.0 instead of raising. + """ + if success: + return 1.0 + if not now_satisfied_options: + return 0.0 + option_scores = [] + for now_opt, init_opt in zip(now_satisfied_options, initial_satisfied_options): + if len(now_opt) == 0: + option_scores.append(0.0) + continue + newly_satisfied = sum(int((not init) and now) for now, init in zip(now_opt, init_opt)) + option_scores.append(newly_satisfied / len(now_opt)) + return max(option_scores) if option_scores else 0.0 + + +class TaskMetric(MetricBase): + def __init__(self, human_stats: Optional[dict] = None, env_idx: int = 0, env_accessor=None): + super().__init__(env_idx=env_idx, env_accessor=env_accessor) + self.timesteps = 0 + self.human_stats = human_stats + if human_stats is None: + print("No human stats provided.") + else: + self.human_stats = { + "steps": self.human_stats["length"], + } + + def reset(self, env=None): + env = self._resolve_env(env) + self.state[self._scene(env)] = dict() + self.timesteps = 0 + self.render_timestep = og.sim.get_rendering_dt() + self.initial_predicate_states = ( + env.get_goal_option_satisfaction() + if env is self.env_accessor + else env.task.get_goal_option_satisfaction(self.env_idx) + ) + + def _compute_step_metrics(self, env, action, obs, reward, terminated, truncated, info): + self.timesteps += 1 + return {"timesteps": self.timesteps} + + def _compute_episode_metrics(self, env, episode_info): + # Use the accumulated state from episode_info + timesteps = episode_info.get("timesteps", [])[-1] if episode_info.get("timesteps") else self.timesteps + + # task.success is a (num_envs,) bool tensor; read THIS env's slot. Partial credit (when not a + # full success) counts newly-satisfied goal predicates per option, max over options. + final_q_score = compute_q_score( + success=env.success if env is self.env_accessor else bool(env.task.success[self.env_idx]), + now_satisfied_options=( + env.get_goal_option_satisfaction() + if env is self.env_accessor + else env.task.get_goal_option_satisfaction(self.env_idx) + ), + initial_satisfied_options=self.initial_predicate_states, + ) + + return { + "q_score": {"final": final_q_score}, + "time": { + "simulator_steps": timesteps, + "simulator_time": timesteps * self.render_timestep, + "normalized_time": self.human_stats["steps"] / timesteps if timesteps > 0 else float("inf"), + }, + } diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a6ca8cea8d9fa3df3d961644c3325a8a54eb451a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/__init__.py @@ -0,0 +1,79 @@ +from omnigibson.object_states.aabb import AABB +from omnigibson.object_states.adjacency import Adjacency +from omnigibson.object_states.attached_to import AttachedTo +from omnigibson.object_states.burnt import Burnt +from omnigibson.object_states.contact_particles import ContactParticles +from omnigibson.object_states.contains import ContainedParticles, Contains +from omnigibson.object_states.cooked import Cooked +from omnigibson.object_states.covered import Covered +from omnigibson.object_states.draped import Draped +from omnigibson.object_states.filled import Filled +from omnigibson.object_states.folded import Folded, FoldedLevel, Unfolded +from omnigibson.object_states.frozen import Frozen +from omnigibson.object_states.heat_source_or_sink import HeatSourceOrSink +from omnigibson.object_states.heated import Heated +from omnigibson.object_states.inside import Inside +from omnigibson.object_states.joint_state import Joint +from omnigibson.object_states.max_temperature import MaxTemperature +from omnigibson.object_states.next_to import NextTo +from omnigibson.object_states.object_state_base import REGISTERED_OBJECT_STATES +from omnigibson.object_states.on_fire import OnFire +from omnigibson.object_states.on_top import OnTop +from omnigibson.object_states.open_state import Open +from omnigibson.object_states.overlaid import Overlaid +from omnigibson.object_states.particle import ParticleRequirement +from omnigibson.object_states.particle_modifier import ParticleApplier, ParticleRemover +from omnigibson.object_states.particle_source_or_sink import ParticleSink, ParticleSource +from omnigibson.object_states.pose import Pose +from omnigibson.object_states.robot_related_states import IsGrasping, ObjectsInFOVOfRobot +from omnigibson.object_states.saturated import Saturated +from omnigibson.object_states.sliceable import SliceableRequirement +from omnigibson.object_states.slicer_active import SlicerActive +from omnigibson.object_states.temperature import Temperature +from omnigibson.object_states.toggle import ToggledOn +from omnigibson.object_states.touching import Touching +from omnigibson.object_states.under import Under + +__all__ = [ + "AABB", + "Adjacency", + "AttachedTo", + "Burnt", + "ContactParticles", + "ContainedParticles", + "Contains", + "Cooked", + "Covered", + "Draped", + "Filled", + "Folded", + "FoldedLevel", + "Frozen", + "Heated", + "HeatSourceOrSink", + "Inside", + "IsGrasping", + "Joint", + "MaxTemperature", + "NextTo", + "ObjectsInFOVOfRobot", + "OnFire", + "OnTop", + "Open", + "Overlaid", + "ParticleApplier", + "ParticleRemover", + "ParticleRequirement", + "ParticleSink", + "ParticleSource", + "Pose", + "REGISTERED_OBJECT_STATES", + "Saturated", + "SliceableRequirement", + "SlicerActive", + "Temperature", + "ToggledOn", + "Touching", + "Under", + "Unfolded", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/aabb.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/aabb.py new file mode 100644 index 0000000000000000000000000000000000000000..c01f9348cc90b2ea8aed396fc8a2ee2e58b87f4e --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/aabb.py @@ -0,0 +1,152 @@ +import torch as th +import warp as wp + +from omnigibson.object_states.tensorized_absolute_state import TensorizedAbsoluteState +from omnigibson.utils.python_utils import classproperty +from omnigibson.utils.usd_utils import RigidBodyViewAPI +from omnigibson.utils.constants import PrimType + + +@wp.kernel +def _aabb_init_kernel(out_values: wp.array2d(dtype=wp.float32)): + """ + Initialize the (S*O, 6) AABB output buffer to [+inf, +inf, +inf, -inf, -inf, -inf]. + Replaces the PyTorch `values.fill_(inf); values[:, :, 3:] = -inf` so AABB._update_values + is fully Warp-only and capturable inside wp.graph. + """ + i = wp.tid() + out_values[i, 0] = wp.float32(wp.inf) + out_values[i, 1] = wp.float32(wp.inf) + out_values[i, 2] = wp.float32(wp.inf) + out_values[i, 3] = wp.float32(-wp.inf) + out_values[i, 4] = wp.float32(-wp.inf) + out_values[i, 5] = wp.float32(-wp.inf) + + +class AABB(TensorizedAbsoluteState): + """ + Axis-aligned bounding box state, computed in bulk across all objects and scenes. + + For rigid objects, batched AABB computation is delegated to RigidBodyViewAPI.get_aabb(), + which uses each link's wp.Mesh (built from collision_mesh_cpu_data) plus POSE_MATRICES. AABB-tracking + config (which links to track, where their AABBs go) is handed off once per + initialize_view() via RigidBodyViewAPI.prepare_aabb_kernel_inputs(...). + + Cloth objects are disabled for now. + + VALUES shape: (S, O, 6) — [lo_x, lo_y, lo_z, hi_x, hi_y, hi_z] + """ + + @classproperty + def value_shape(cls): + return (6,) + + @classproperty + def value_name(cls): + return "aabb" + + @classmethod + def initialize_view(cls): + # Snapshot before super() calls global_initialize() which resets OBJ_IDXS + prev_rel_paths = set(cls.OBJ_IDXS.keys()) if cls.OBJ_IDXS is not None else set() + + # Base class rebuilds OBJ_IDXS, IDX_OBJS, VALUES (S, O, 6) + super().initialize_view() + + S = len(cls.IDX_OBJS) + O = len(cls.OBJ_IDXS) + + if S == 0 or O == 0: + empty = th.zeros((0,), dtype=th.int32) + RigidBodyViewAPI.prepare_aabb_kernel_inputs(empty, empty, empty, empty) + return + + # Build the (link, output-row) mapping AABB-tracked rigid bodies need: + # - prim_body_idx[i] / link_idx[i]: for the i-th tracked link with collision geom, + # its flat body idx in RigidBodyViewAPI and its output row in (S*O,)-flattened VALUES. + # - base_link_*[j]: same but per rigid object's base link, used by the fallback kernel + # to write a point AABB for objects whose links have no collision geometry. + prim_body_idx, link_idx = [], [] + base_link_body_idx, base_link_values_idx = [], [] + + for scene_idx, scene_row in enumerate(cls.IDX_OBJS): + for obj_index, obj in enumerate(scene_row): + if obj is None: + continue + if obj.prim_type == PrimType.CLOTH: + continue + + # Add the base link to the base link indices + this_base_link_body_idx = RigidBodyViewAPI.get_flat_idx(obj.root_link.prim_path) + assert this_base_link_body_idx is not None, "Base link not in RigidBodyViewAPI" + base_link_body_idx.append(this_base_link_body_idx) + base_link_values_idx.append(scene_idx * O + obj_index) + + for link in obj.links.values(): + flat_idx = RigidBodyViewAPI.get_flat_idx(link.prim_path) + assert flat_idx is not None, "Articulated link not in RigidBodyViewAPI" + if RigidBodyViewAPI.LINK_VERTEX_COUNTS[flat_idx].item() == 0: + continue # no collision geometry for this link + + prim_body_idx.append(flat_idx) + link_idx.append(scene_idx * O + obj_index) + + # Hand off the index tensors to RigidBodyViewAPI. It builds the K-length kernel + # input tables and caches them for subsequent get_aabb() calls. We don't keep + # these locally — the only readers are inside RigidBodyViewAPI. + # TODO(vector): Find out if we absolutely need to do this thing where we store this + # info in the RigidBodyViewAPI. Why can't we just pass it in as an argument to get_aabb? + RigidBodyViewAPI.prepare_aabb_kernel_inputs( + th.tensor(prim_body_idx, dtype=th.int32), + th.tensor(link_idx, dtype=th.int32), + th.tensor(base_link_body_idx, dtype=th.int32), + th.tensor(base_link_values_idx, dtype=th.int32), + ) + + # Initialize new VALUE slots for objects that just appeared + for rel_path, obj_idx in cls.OBJ_IDXS.items(): + if rel_path not in prev_rel_paths: + for s_idx in range(S): + if cls.IDX_OBJS[s_idx][obj_idx] is not None: + cls.VALUES[s_idx, obj_idx] = th.nan + + @classmethod + def _update_values(cls, values): + S = values.shape[0] + O = values.shape[1] + + # Init the (S*O, 6) output buffer to [+inf, +inf, +inf, -inf, -inf, -inf] via a Warp + # kernel (no PyTorch CUDA ops — keeps this method graph-capturable). + flat_view = values.view(S * O, 6) + out_arr = wp.from_torch(flat_view) + wp.launch(kernel=_aabb_init_kernel, dim=S * O, inputs=[out_arr], device="cuda") + + # Batched AABB for all rigid links (physx_tracked + physx_untracked kinematic). + # get_aabb() short-circuits internally when nothing is tracked — no guard needed. + # It runs both the per-(link, vertex) reduce kernel and the base-link fallback kernel. + RigidBodyViewAPI.get_aabb(flat_view) + + # Cloth — disabled for now + + def _get_value(self): + s = self.obj.scene.idx + obj_idx = self.OBJ_IDXS[self.obj.relative_prim_path] + v = self.VALUES_CPU[s, obj_idx] # (6,) — CPU mirror, no GPU stall + return v[:3], v[3:] # (lo, hi) — matches EntityPrim.aabb return type + + def _set_value(self, new_value): + raise NotImplementedError("AABB is read-only; it is derived from pose and cannot be set directly.") + + def _dump_state(self): + # Return the raw flat (6,) VALUES_CPU row so serialize() receives a CPU tensor + s = self.obj.scene.idx + if self.obj.relative_prim_path in self.OBJ_IDXS: + obj_idx = self.OBJ_IDXS[self.obj.relative_prim_path] + return {self.value_name: self.VALUES_CPU[s, obj_idx].clone()} + else: + # obj not initialized yet. return a empty (6,) tensor + return {self.value_name: th.zeros(self.value_shape)} + + def _load_state(self, state): + # AABB is fully derived from pose; it will be recomputed on the next step. + pass diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/adjacency.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/adjacency.py new file mode 100644 index 0000000000000000000000000000000000000000..de38ae12808fef93dd05faca3b9793a1796a1880 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/adjacency.py @@ -0,0 +1,309 @@ +import math + +import torch as th +import warp as wp + +import omnigibson.lazy as lazy +from omnigibson.macros import create_module_macros +from omnigibson.object_states.aabb import AABB +from omnigibson.object_states.tensorized_relative_state import TensorizedRelativeState +from omnigibson.utils.constants import PrimType +from omnigibson.utils.python_utils import classproperty +from omnigibson.utils.usd_utils import RigidBodyViewAPI, rigid_inverse_mat44 + +# Create settings for this module +m = create_module_macros(module_path=__file__) +m.MAX_DISTANCE_VERTICAL = 5.0 +m.MAX_DISTANCE_HORIZONTAL = 5.0 + +# Number of horizontal directions +# total 8 * 2 = 16 signed directions, spaced 22.5 degrees apart. +m.HORIZONTAL_AXIS_COUNT = 8 + +_HORIZONTAL_DIRECTION_COUNT = 2 * m.HORIZONTAL_AXIS_COUNT + + +# Tensorized Adjacency state +# +# VALUE is (S, N, N, 18) bool tensor populated by Warp ray casts against per-link wp.Mesh. +# +# Axis layout: +# k=0 : +Z (other above self) +# k=1 : -Z (other below self) +# k=2..9 : positive directions of the 8 unique legacy horizontal axes +# k=10..17 : negative directions of those same axes +# +# VALUES[s, a, b, k] = True iff a ray from object a's AABB center in direction k +# hits any collision-link of object b within max_distances[k]. Self pairs and +# cross-scene pairs are False. +# +# Cloth is skipped via is_compatible — cloth has no collision_mesh_cpu_data. TODO(andi) verrify this + +# Total number of signed ray directions (2 vertical + 16 horizontal) +_ADJ_AXIS_COUNT = 2 + _HORIZONTAL_DIRECTION_COUNT # = 18 + +# Horizontal-direction slice into the K axis: range(_HORIZONTAL_K_START, _HORIZONTAL_K_END). +_HORIZONTAL_K_START = 2 +_HORIZONTAL_K_END = _ADJ_AXIS_COUNT # exclusive + + +@wp.kernel +def _adjacency_ray_cast_kernel( + aabb_values: wp.array3d(dtype=wp.float32), # (S, N_aabb, 6) — [lo_x, lo_y, lo_z, hi_x, hi_y, hi_z] + aabb_obj_idxs: wp.array(dtype=wp.int32), # (N_adj,) — adj_idx → aabb_idx, -1 if no AABB + directions: wp.array2d(dtype=wp.float32), # (K, 3) — world-frame ray directions + max_distances: wp.array(dtype=wp.float32), # (K,) — per-axis max ray distance + link_mesh_ids: wp.array(dtype=wp.uint64), # (L,) — wp.Mesh ids; 0 if link has no collision mesh + link_pose_matrices: wp.array(dtype=wp.mat44), # (L,) — link world transforms + link_to_obj_idx: wp.array(dtype=wp.int32), # (L,) — link → adj_idx of parent obj, -1 if untracked + link_to_scene_idx: wp.array(dtype=wp.int32), # (L,) — link → scene_idx of parent obj + output: wp.array4d(dtype=wp.int32), # (S, N_adj, N_adj, K) — atomic_max target +): + """ + One thread per (scene, origin_obj, target_link, axis). On hit, atomic-OR sets scratch[s, a, b, k]. + """ + s, a, l, k = wp.tid() + + # Skip if origin object has no tracked AABB (e.g. cloth, which is_compatible filters out + # of Adjacency but might still have an Adjacency.OBJ_IDXS entry from a cross-scene partner). + aabb_idx = aabb_obj_idxs[a] + if aabb_idx < 0: + return + + # Skip if target link has no collision mesh + mesh_id = link_mesh_ids[l] + if mesh_id == wp.uint64(0): + return + + # Skip if target link's parent isn't in this scene + if link_to_scene_idx[l] != s: + return + + # Skip if target link is untracked, or belongs to the same object (self-pair) + b = link_to_obj_idx[l] + if b < 0 or b == a: + return + + # Compute origin (AABB center in world frame) — read 6 floats inline + lo_x = aabb_values[s, aabb_idx, 0] + lo_y = aabb_values[s, aabb_idx, 1] + lo_z = aabb_values[s, aabb_idx, 2] + hi_x = aabb_values[s, aabb_idx, 3] + hi_y = aabb_values[s, aabb_idx, 4] + hi_z = aabb_values[s, aabb_idx, 5] + origin_w = wp.vec3((lo_x + hi_x) * 0.5, (lo_y + hi_y) * 0.5, (lo_z + hi_z) * 0.5) + dir_w = wp.vec3(directions[k, 0], directions[k, 1], directions[k, 2]) + t_max = max_distances[k] + + # Transform ray into target link's local frame. + # transform_point applies translation; transform_vector is rotation-only (correct for direction). + inv = rigid_inverse_mat44(link_pose_matrices[l]) + origin_local = wp.transform_point(inv, origin_w) + dir_local = wp.transform_vector(inv, dir_w) + + if wp.mesh_query_ray_anyhit(mesh_id, origin_local, dir_local, t_max): + wp.atomic_max(output, s, a, b, k, wp.int32(1)) + + +@wp.kernel +def _adjacency_finalize_kernel( + output: wp.array4d(dtype=wp.int32), # (S, N, N, K) int32 + values: wp.array4d(dtype=wp.uint8), # (S, N, N, K) uint8 — backed by th.bool storage +): + """Convert int32 scratch to uint8 bool VALUES.""" + s, a, b, k = wp.tid() + if output[s, a, b, k] > wp.int32(0): + values[s, a, b, k] = wp.uint8(1) + else: + values[s, a, b, k] = wp.uint8(0) + + +def _build_adjacency_axis_tables(): + """Build the (18, 3) directions and distance tables. + + Layout matches the kernel's k axis: + [+Z, -Z, axis_0+, ..., axis_7+, axis_0-, ..., axis_7-] + + These are the 16 unique signed directions in the legacy scalar ray set. + Omitting its four duplicate rays preserves the OR-reduced predicate result + while avoiding redundant ray casts. + """ + axis_angles = th.arange(m.HORIZONTAL_AXIS_COUNT, dtype=th.float32) * (math.pi / m.HORIZONTAL_AXIS_COUNT) + axes = th.stack([th.cos(axis_angles), th.sin(axis_angles), th.zeros_like(axis_angles)], dim=1) + horizontal_dirs = th.cat([axes, -axes], dim=0) + + directions = th.zeros((_ADJ_AXIS_COUNT, 3), dtype=th.float32) + directions[0] = th.tensor([0.0, 0.0, 1.0]) + directions[1] = th.tensor([0.0, 0.0, -1.0]) + directions[2:] = horizontal_dirs + + max_distances = th.full((_ADJ_AXIS_COUNT,), m.MAX_DISTANCE_HORIZONTAL, dtype=th.float32) + max_distances[0] = m.MAX_DISTANCE_VERTICAL + max_distances[1] = m.MAX_DISTANCE_VERTICAL + return directions, max_distances + + +class Adjacency(TensorizedRelativeState): + """ + Pairwise adjacency state. + + S = number of scenes + N = number of objects with Adjacency state + VALUES has shape (S, N, N, 18) bool: +Z, -Z, then the positive and negative + directions of the eight unique legacy horizontal axes. VALUES[s, a, b, k] is True iff + object b is adjacent to object a in direction k (from a's AABB center). + + Diagonal and cross-scene cells are always False. + Cloth is excluded via is_compatible (no collision mesh to ray-cast against). + """ + + # Wp kernel inputs (single source of truth). + _aabb_obj_idxs = None # wp.array (N_adj,) int32 + _link_to_obj_idx = None # wp.array (L_total,) int32 + _link_to_scene_idx = None # wp.array (L_total,) int32 + _directions = None # wp.array2d (18, 3) float32 + _max_distances = None # wp.array (18,) float32 + _output = None # wp.array4d (S, N_adj, N_adj, 18) int32 — atomic_max target + + @classproperty + def value_shape(cls): + return (_ADJ_AXIS_COUNT,) + + @classproperty + def value_type(cls): + return th.bool + + @classproperty + def value_name(cls): + return "adjacency" + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(AABB) + return deps + + @classmethod + def is_compatible(cls, obj, **kwargs): + compatible, reason = super().is_compatible(obj, **kwargs) + if not compatible: + return compatible, reason + # Cloth has no collision_mesh_cpu_data — exclude as both origin and target. + # TODO: revisit when cloth gains a queryable mesh proxy. + if obj.prim_type == PrimType.CLOTH: + return False, "Adjacency does not support cloth objects" + return True, None + + @classmethod + def global_initialize(cls): + super().global_initialize() + # Build the constant axis tables (directions + per-axis max distance). + directions_cpu, max_distances_cpu = _build_adjacency_axis_tables() + cls._directions = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + directions_cpu, "float32", device="cuda" + ) + cls._max_distances = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + max_distances_cpu, "float32", device="cuda" + ) + + @classmethod + def initialize_view(cls): + super().initialize_view() + + S = len(cls.IDX_OBJS) + N = len(cls.OBJ_IDXS) + + # Build aabb_obj_idxs: maps Adjacency-N → AABB-N (or -1 if unknown to AABB). + if N > 0 and AABB.OBJ_IDXS is not None: + aabb_obj_idxs_cpu = th.full((N,), -1, dtype=th.int32) + for rel_path, adj_idx in cls.OBJ_IDXS.items(): + aabb_obj_idxs_cpu[adj_idx] = AABB.OBJ_IDXS.get(rel_path, -1) + cls._aabb_obj_idxs = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + aabb_obj_idxs_cpu, "int32", device="cuda" + ) + else: + cls._aabb_obj_idxs = None + + # Build link_to_obj_idx / link_to_scene_idx tables, length = N_links_total in + # RigidBodyViewAPI (whether or not those links belong to Adjacency-tracked objects). + # Untracked link slots stay at -1; the kernel skips them. + if RigidBodyViewAPI._PATH_TO_IDX: + L_total = len(RigidBodyViewAPI._PATH_TO_IDX) + link_to_obj_cpu = th.full((L_total,), -1, dtype=th.int32) + link_to_scene_cpu = th.full((L_total,), -1, dtype=th.int32) + for s_idx, scene_row in enumerate(cls.IDX_OBJS): + for adj_idx, obj in enumerate(scene_row): + if obj is None: + continue + for link in obj.links.values(): + flat_idx = RigidBodyViewAPI.get_flat_idx(link.prim_path) + if flat_idx is None: + continue + link_to_obj_cpu[flat_idx] = adj_idx + link_to_scene_cpu[flat_idx] = s_idx + cls._link_to_obj_idx = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + link_to_obj_cpu, "int32", device="cuda" + ) + cls._link_to_scene_idx = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + link_to_scene_cpu, "int32", device="cuda" + ) + else: + cls._link_to_obj_idx = None + cls._link_to_scene_idx = None + + # Allocate the int32 scratch (S, N, N, K) used as the atomic_max target. + if S > 0 and N > 0: + cls._output = wp.zeros((S, N, N, _ADJ_AXIS_COUNT), dtype=wp.int32, device="cuda") + else: + cls._output = None + + @classmethod + def _update_values(cls, values): + # All required handles must be live; otherwise nothing to do this step. + if ( + cls._output is None + or cls.VALUES_WP is None + or AABB.VALUES_WP is None + or cls._aabb_obj_idxs is None + or RigidBodyViewAPI.LINK_MESH_IDS is None + or RigidBodyViewAPI.POSE_MATRICES is None + or cls._link_to_obj_idx is None + or cls._link_to_scene_idx is None + ): + return + + S = values.shape[0] + N = values.shape[1] + K = _ADJ_AXIS_COUNT + L = RigidBodyViewAPI.LINK_MESH_IDS.shape[0] + if S == 0 or N == 0 or L == 0: + return + + # 1. Zero the int32 scratch via CUDA memset (graph-capturable for contiguous wp.array). + cls._output.zero_() + + # 2. Ray-cast against each link's mesh; atomic_max into scratch on hit. + wp.launch( + kernel=_adjacency_ray_cast_kernel, + dim=(S, N, L, K), + inputs=[ + AABB.VALUES_WP, + cls._aabb_obj_idxs, + cls._directions, + cls._max_distances, + RigidBodyViewAPI.LINK_MESH_IDS, + RigidBodyViewAPI.POSE_MATRICES, + cls._link_to_obj_idx, + cls._link_to_scene_idx, + cls._output, + ], + device="cuda", + ) + + # 3. Convert int32 scratch → uint8 bool VALUES. + wp.launch( + kernel=_adjacency_finalize_kernel, + dim=(S, N, N, K), + inputs=[cls._output, cls.VALUES_WP], + device="cuda", + ) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/attached_to.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/attached_to.py new file mode 100644 index 0000000000000000000000000000000000000000..a412fa1e41254eb74b57d475f397a27273078f2b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/attached_to.py @@ -0,0 +1,572 @@ +from collections import defaultdict + +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros +from omnigibson.object_states.joint_break_subscribed_state_mixin import JointBreakSubscribedStateMixin +from omnigibson.object_states.link_based_state_mixin import LinkBasedStateMixin +from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState +from omnigibson.object_states.update_state_mixin import UpdateStateMixin +from omnigibson.prims.geom_prim import GeomPrim +from omnigibson.prims.material_prim import OmniPBRMaterialPrim +from omnigibson.utils.constants import JointType +from omnigibson.utils.python_utils import classproperty +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import ( + RigidContactAPI, + absolute_prim_path_to_scene_relative, + create_joint, + create_primitive_mesh, + delete_or_deactivate_prim, +) + +# Create module logger +log = create_module_logger(module_name=__name__) + + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.ATTACHMENT_META_LINK_TYPE = "attachment" + +m.DEFAULT_POSITION_THRESHOLD = 0.05 # 5cm +m.DEFAULT_ORIENTATION_THRESHOLD = th.deg2rad(th.tensor([15.0])).item() # 15 degrees +m.DEFAULT_JOINT_TYPE = JointType.JOINT_FIXED +m.DEFAULT_BREAK_FORCE = 5000 # Newton +m.DEFAULT_BREAK_TORQUE = 10000 # Newton-Meter +m.ENABLE_ATTACHMENT_JOINT_VISUALS = False + +# Frame visualizer cylinder configurations +ATTACHMENT_FRAME_CONFIG = { + "width": 0.006, + "lengths": [0.15, 0.15, 0.15], + "directions": [ + th.tensor([1.0, 0.0, 0.0]), # X-axis + th.tensor([0.0, 1.0, 0.0]), # Y-axis + th.tensor([0.0, 0.0, 1.0]), # Z-axis + ], + "quat_offsets": [ + T.euler2quat(th.tensor([0.0, th.pi / 2, 0.0])), # X-axis + T.euler2quat(th.tensor([-th.pi / 2, 0.0, 0.0])), # Y-axis + T.euler2quat(th.tensor([0.0, 0.0, 0.0])), # Z-axis + ], + "colors": [ + th.tensor([1.0, 0.0, 0.0]), # Red for X-axis + th.tensor([0.0, 1.0, 0.0]), # Green for Y-axis + th.tensor([0.0, 0.0, 1.0]), # Blue for Z-axis + ], +} +m.ATTACHMENT_JOINT_VISUAL_WIDTH = ATTACHMENT_FRAME_CONFIG["width"] +m.ATTACHMENT_JOINT_VISUAL_LENGTHS = ATTACHMENT_FRAME_CONFIG["lengths"] +m.ATTACHMENT_JOINT_VISUAL_LENGTH = ATTACHMENT_FRAME_CONFIG["lengths"][0] +m.ATTACHMENT_JOINT_VISUAL_DIRECTIONS = ATTACHMENT_FRAME_CONFIG["directions"] +m.ATTACHMENT_JOINT_VISUAL_COLORS = ATTACHMENT_FRAME_CONFIG["colors"] +m.ATTACHMENT_JOINT_VISUAL_ROTATIONS = ATTACHMENT_FRAME_CONFIG["quat_offsets"] + + +# TODO: Make AttachedTo into a global state that manages all the attachments in the scene. +# When an attachment of a child and a parent is about to happen: +# 1. stop the sim +# 2. remove all existing attachment joints (and save information to restore later) +# 3. disable collision between the child and the parent +# 4. play the sim +# 5. reload the state +# 6. restore all existing attachment joints +# 7. create the joint +class AttachedTo( + RelativeObjectState, + BooleanStateMixin, + UpdateStateMixin, + JointBreakSubscribedStateMixin, + LinkBasedStateMixin, +): + """ + Handles attachment between two rigid objects, by creating a fixed/spherical joint between self.obj (child) and + other (parent). At any given moment, an object can only be attached to at most one other object, i.e. + a parent can have multiple children, but a child can only have one parent. + Note that generally speaking only child.states[AttachedTo].get_value(parent) will return True. + One of the child's male meta links will be attached to one of the parent's female meta links. + + Subclasses UpdateStateMixin, JointBreakSubscribedStateMixin + update function attempts to attach self.obj to any contacting object on each simulation step. + on_joint_break function breaks the current attachment + """ + + # This is to force the __init__ args to be "self" and "obj" only. + # Otherwise, it will inherit from LinkBasedStateMixin and the __init__ args will be "self", "args", "kwargs". + def __init__(self, obj): + # Run super method + super().__init__(obj=obj) + + def initialize(self): + super().initialize() + og.sim.add_callback_on_stop(name=f"{self.obj.name}_detach", callback=self._detach) + self.parents_disabled_collisions = set() + + def remove(self): + super().remove() + og.sim.remove_callback_on_stop(name=f"{self.obj.name}_detach") + + @classproperty + def meta_link_types(cls): + """ + Returns: + list of str: Unique keywords that define the meta links associated with this object state + """ + return [m.ATTACHMENT_META_LINK_TYPE] + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + return deps + + def _initialize(self): + super()._initialize() + self.initialize_link_mixin() + + self.attachment_joint_visuals = defaultdict(list) + if m.ENABLE_ATTACHMENT_JOINT_VISUALS: + self._create_attachment_joint_visuals() + + # Reference to the parent object (DatasetObject) + self.parent = None + + # Reference to the female meta link of the parent object (RigidDynamicPrim) + self.parent_link = None + + # Mapping from the female meta link names of self.obj to their children (Dict[str, Optional[DatasetObject] = None]) + self.children = { + link_name: None + for link_name, link in self.links.items() + if link.is_meta_link and link.meta_link_id.endswith("F") + } + + # Cache of parent link candidates for other objects (Dict[DatasetObject, Dict[str, str]]) + # @other -> (the male meta link names of @self.obj -> the correspounding female meta link names of @other)) + self.parent_link_candidates = dict() + + def _create_attachment_joint_visuals(self): + """ + Creates three visual-only axis cues (X, Y, Z) for each attachment meta link. + The markers start at the attachment point and extend in their respective directions: + X-axis (Red), Y-axis (Green), Z-axis (Blue). + """ + scene = self.obj.scene + + # Create materials for each axis + axis_names = ("x", "y", "z") + axis_materials = [] + for axis, color in zip(axis_names, m.ATTACHMENT_JOINT_VISUAL_COLORS): + mat_prim_path = f"{self.obj.prim_path}/Looks/attachment_joint_visual_{axis}_mat" + mat = OmniPBRMaterialPrim( + relative_prim_path=absolute_prim_path_to_scene_relative(scene, mat_prim_path), + name=f"{self.obj.name}:attachment_joint_visual_{axis}_mat", + ) + mat.load(scene) + mat.diffuse_color_constant = color + axis_materials.append(mat) + + for link_name, link in self.links.items(): + if not link.meta_link_id.endswith(("M", "F")): + continue + + frame_visualizers = [] + + # Create three cylinders (X, Y, Z axes) + for axis, mat, direction, quat_offset, length in zip( + axis_names, + axis_materials, + m.ATTACHMENT_JOINT_VISUAL_DIRECTIONS, + m.ATTACHMENT_JOINT_VISUAL_ROTATIONS, + m.ATTACHMENT_JOINT_VISUAL_LENGTHS, + ): + vis_prim_path = f"{link.prim_path}/attachment_joint_visual_{axis}" + create_primitive_mesh(vis_prim_path, "Cylinder", extents=1.0) + visualizer = GeomPrim( + relative_prim_path=absolute_prim_path_to_scene_relative(scene, vis_prim_path), + name=f"{self.obj.name}:{link_name}:attachment_joint_visual_{axis}", + ) + visualizer.load(scene) + visualizer.material = mat + visualizer.scale = ( + th.tensor( + [ + m.ATTACHMENT_JOINT_VISUAL_WIDTH, + m.ATTACHMENT_JOINT_VISUAL_WIDTH, + length, + ] + ) + / link.scale + ) + visualizer.set_position_orientation( + position=direction * (length / 2.0) / link.scale, + orientation=quat_offset, + frame="parent", + ) + visualizer.visible = True + frame_visualizers.append(visualizer) + + self.attachment_joint_visuals[link_name] = frame_visualizers + + def on_joint_break(self, joint_prim_path): + # Note that when this function is invoked when a joint break event happens, @self.obj is the parent of the + # attachment joint, not the child. We access the child of the broken joint, and call the setter with False + child = self.children[joint_prim_path.split("/")[-2]] + child.states[AttachedTo].set_value(self.obj, False) + + def _update(self): + # If already attached, no-op + if self.parent is not None: + return + + # Attempt to attach to any contacting object in deterministic order + scene_idx = self.obj.scene.idx + my_link_paths = [link.prim_path for link in self.obj.links.values()] + contacting_paths = { + other_contact + for this_contact, other_contact in RigidContactAPI.get_contact_pairs( + scene_idx=scene_idx, query_set=my_link_paths, with_set=None, current_only=False + ) + if other_contact not in self.obj.link_prim_paths + } + for prim_path in sorted(contacting_paths): + # Contact pairs return link prim paths; map to owning object prim path for lookup. + other = og.sim.get_obj_at_prim_path("/".join(prim_path.split("/")[:-1])) + if other is None or other == self.obj or AttachedTo not in other.states: + continue + if self.set_value(other, True): + break + + def _set_value( + self, other, new_value, bypass_alignment_checking=False, check_physics_stability=False, can_joint_break=True + ): + """ + Args: + other (DatasetObject): parent object to attach to. + new_value (bool): whether to attach or detach. + bypass_alignment_checking (bool): whether to bypass alignment checking when finding attachment links. + Normally when finding attachment links, we check if the child and parent links have aligned positions + or poses. This flag allows users to bypass this check and find attachment links solely based on the + attachment meta link types. Default is False. + check_physics_stability (bool): whether to check if the attachment is stable after attachment. + If True, it will check if the child object is not colliding with other objects except the parent object. + If False, it will not check the stability and simply attach the child to the parent. + Default is False. + can_joint_break (bool): whether the joint can break or not. + + Returns: + bool: whether the attachment setting was successful or not. + """ + # Attempt to attach + if new_value: + if self.parent == other: + # Already attached to this object. Do nothing. + return True + elif self.parent is not None: + log.debug( + f"Trying to attach object {self.obj.name} to object {other.name}," + f"but it is already attached to object {self.parent.name}. Try detaching first." + ) + return False + else: + # Find attachment links that satisfy the proximity requirements + child_link, parent_link = self._find_attachment_links(other, bypass_alignment_checking) + if child_link is None: + return False + else: + if check_physics_stability: + state = og.sim.dump_state() + self._attach(other, child_link, parent_link, can_joint_break=can_joint_break) + if not check_physics_stability: + return True + else: + og.sim.step_physics() + # self.obj should not collide with other objects except the parent + success = not RigidContactAPI.is_in_contact( + scene_idx=self.obj.scene.idx, + query_set=[self.obj], + with_set=None, + ignore_set=[other], + current_only=False, + ) + if success: + return True + else: + self._detach() + og.sim.load_state(state) + return False + + # Attempt to detach + else: + if self.parent == other: + self._detach() + + # Wake up objects so that passive forces like gravity can be applied. + self.obj.wake() + other.wake() + return True + + def _get_value(self, other): + # Simply return if the current parent matches other + return other == self.parent + + def _find_attachment_links( + self, + other, + bypass_alignment_checking=False, + pos_thresh=None, + orn_thresh=None, + ): + """ + Args: + other (DatasetObject): parent object to find potential attachment links. + bypass_alignment_checking (bool): whether to bypass alignment checking when finding attachment links. + Normally when finding attachment links, we check if the child and parent links have aligned positions + or poses. This flag allows users to bypass this check and find attachment links solely based on the + attachment meta link types. Default is False. + pos_thresh (float): position difference threshold to activate attachment, in meters. + orn_thresh (float): orientation difference threshold to activate attachment, in radians. + + Returns: + 2-tuple: + - RigidDynamicPrim or None: link belonging to @self.obj that should be aligned to that corresponding link of @other + - RigidDynamicPrim or None: the corresponding link of @other + """ + if pos_thresh is None: + pos_thresh = m.DEFAULT_POSITION_THRESHOLD + if orn_thresh is None: + orn_thresh = m.DEFAULT_ORIENTATION_THRESHOLD + parent_candidates = self._get_parent_candidates(other) + if not parent_candidates: + return None, None + + for child_link_name, parent_link_names in parent_candidates.items(): + child_link = self.links[child_link_name] + for parent_link_name in parent_link_names: + parent_link = other.states[AttachedTo].links[parent_link_name] + if other.states[AttachedTo].children[parent_link_name] is None: + if bypass_alignment_checking: + return child_link, parent_link + + child_pos, child_orn = child_link.get_position_orientation() + parent_pos, parent_orn = parent_link.get_position_orientation() + pos_diff = th.norm(child_pos - parent_pos) + orn_diff = T.get_orientation_diff_in_radian(child_orn, parent_orn) + + if pos_diff < pos_thresh and orn_diff < orn_thresh: + return child_link, parent_link + + return None, None + + def _get_parent_candidates(self, other): + """ + Helper function to return the parent link candidates for @other + + Returns: + Dict[str, str] or None: mapping from the male meta link names of self.obj to the correspounding female meta + link names of @other. Returns None if @other does not have the AttachedTo state. + """ + if AttachedTo not in other.states: + return None + if other not in self.parent_link_candidates: + parent_link_names = defaultdict(set) + for child_link_name, child_link in self.links.items(): + if child_link.meta_link_id.endswith("F"): + continue + assert child_link.meta_link_id.endswith("M") + parent_meta_link_id = child_link.meta_link_id[:-1] + "F" + for parent_link_name, parent_link in other.states[AttachedTo].links.items(): + if parent_link.meta_link_id == parent_meta_link_id: + parent_link_names[child_link_name].add(parent_link_name) + self.parent_link_candidates[other] = parent_link_names + + return self.parent_link_candidates[other] + + @property + def attachment_joint_prim_path(self): + return ( + f"{self.parent_link.prim_path}/{self.obj.name}_attachment_joint" if self.parent_link is not None else None + ) + + def _attach(self, other, child_link, parent_link, joint_type=None, can_joint_break=True): + """ + Creates a fixed or spherical joint between a male meta link of self.obj (@child_link) and a female meta link of + @other (@parent_link) with a given @joint_type, @break_force and @break_torque + + Args: + other (DatasetObject): parent object to attach to. + child_link (RigidDynamicPrim): male meta link of @self.obj. + parent_link (RigidDynamicPrim): female meta link of @other. + joint_type (JointType): joint type of the attachment, {JointType.JOINT_FIXED, JointType.JOINT_SPHERICAL} + can_joint_break (bool): whether the joint can break or not. + """ + if joint_type is None: + joint_type = m.DEFAULT_JOINT_TYPE + assert joint_type in { + JointType.JOINT_FIXED, + JointType.JOINT_SPHERICAL, + }, f"Unsupported joint type {joint_type}" + + # Set pose for self.obj so that child_link and parent_link align (6dof alignment for FixedJoint and 3dof alignment for SphericalJoint) + parent_pos, parent_quat = parent_link.get_position_orientation() + child_pos, child_quat = child_link.get_position_orientation() + + child_root_pos, child_root_quat = self.obj.get_position_orientation() + + if joint_type == JointType.JOINT_FIXED: + # For FixedJoint: find the relation transformation of the two frames and apply it to self.obj. + rel_pos, rel_quat = T.mat2pose( + T.pose2mat((parent_pos, parent_quat)) @ T.pose_inv(T.pose2mat((child_pos, child_quat))) + ) + new_child_root_pos, new_child_root_quat = T.pose_transform( + rel_pos, rel_quat, child_root_pos, child_root_quat + ) + else: + # For SphericalJoint: move the position of self.obj to align the two frames and keep the rotation unchanged. + new_child_root_pos = child_root_pos + (parent_pos - child_pos) + new_child_root_quat = child_root_quat + + # Actually move the object and also keep it still for stability purposes. + self.obj.set_position_orientation(position=new_child_root_pos, orientation=new_child_root_quat) + self.obj.keep_still() + other.keep_still() + + if joint_type == JointType.JOINT_FIXED: + # FixedJoint: the parent link, the child link and the joint frame all align. + parent_local_quat = th.tensor([0.0, 0.0, 0.0, 1.0]) + else: + # SphericalJoint: the same except that the rotation of the parent link doesn't align with the joint frame. + # The child link and the joint frame still align. + _, parent_local_quat = T.relative_pose_transform([0, 0, 0], child_quat, [0, 0, 0], parent_quat) + + # Disable collision between the parent and child objects + # self._disable_collision_between_child_and_parent(child=self.obj, parent=other) + + # Set the parent references + self.parent = other + self.parent_link = parent_link + + # Set the child reference for @other + other.states[AttachedTo].children[parent_link.body_name] = self.obj + + kwargs = ( + {"break_force": m.DEFAULT_BREAK_FORCE, "break_torque": m.DEFAULT_BREAK_TORQUE} + if can_joint_break + else dict() + ) + + # Create the joint + create_joint( + prim_path=self.attachment_joint_prim_path, + joint_type=joint_type, + body0=f"{parent_link.prim_path}", + body1=f"{child_link.prim_path}", + joint_frame_in_parent_frame_pos=th.zeros(3), + joint_frame_in_parent_frame_quat=parent_local_quat, + joint_frame_in_child_frame_pos=th.zeros(3), + joint_frame_in_child_frame_quat=th.tensor([0.0, 0.0, 0.0, 1.0]), + exclude_from_articulation=True, + **kwargs, + ) + + def _disable_collision_between_child_and_parent(self, child, parent): + """ + Disables collision between the child and parent objects + """ + if parent in self.parents_disabled_collisions: + return + self.parents_disabled_collisions.add(parent) + + was_playing = og.sim.is_playing() + if was_playing: + state = og.sim.dump_state() + og.sim.stop() + + for child_link in child.links.values(): + for parent_link in parent.links.values(): + child_link.add_filtered_collision_pair(parent_link) + + if parent.category == "wall_nail": + # Temporary hack to disable collision between the attached child object and all walls/floors so that objects + # attached to the wall_nails do not collide with the walls/floors. + for wall in parent.scene.object_registry("category", "walls", set()): + for wall_link in wall.links.values(): + for child_link in child.links.values(): + child_link.add_filtered_collision_pair(wall_link) + for wall in parent.scene.object_registry("category", "floors", set()): + for floor_link in wall.links.values(): + for child_link in child.links.values(): + child_link.add_filtered_collision_pair(floor_link) + + # Temporary hack to disable gravity for the attached child object if the parent is kinematic_only + # Otherwise, the parent meta link will oscillate due to the gravity force of the child. + if parent.kinematic_only: + child.disable_gravity() + + if was_playing: + og.sim.play() + og.sim.load_state(state) + + def _detach(self): + """ + Removes the current attachment joint + """ + if self.parent_link is not None: + # Remove the attachment joint prim from the stage + delete_or_deactivate_prim(self.attachment_joint_prim_path) + og.sim.update_handles() + + # Remove child reference from the parent object + self.parent.states[AttachedTo].children[self.parent_link.body_name] = None + + # Remove reference to the parent object and link + self.parent = None + self.parent_link = None + + @property + def settable(self): + return True + + @property + def state_size(self): + return 1 + + def _dump_state(self): + return dict(attached_obj_uuid=-1 if self.parent is None else self.parent.uuid) + + def _load_state(self, state): + uuid = state["attached_obj_uuid"] + if uuid == -1: + attached_obj = None + else: + attached_obj = self.obj.scene.object_registry("uuid", uuid) + assert attached_obj is not None, "attached_obj_uuid does not match any object in the scene." + + if self.parent != attached_obj: + # If it's currently attached to something else, detach. + if self.parent is not None: + self.set_value(self.parent, False) + # assert self.parent is None, "parent reference is not cleared after detachment" + if self.parent is not None: + log.warning("parent reference is not cleared after detachment") + + # If the loaded state requires attachment, attach. + if attached_obj is not None: + self.set_value( + attached_obj, + True, + bypass_alignment_checking=True, + check_physics_stability=False, + can_joint_break=True, + ) + # assert self.parent == attached_obj, "parent reference is not updated after attachment" + if self.parent != attached_obj: + log.warning("parent reference is not updated after attachment") + + def serialize(self, state): + return th.tensor([state["attached_obj_uuid"]], dtype=th.float32) + + def deserialize(self, state): + return dict(attached_obj_uuid=int(state[0])), 1 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/burnt.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/burnt.py new file mode 100644 index 0000000000000000000000000000000000000000..6852abc354fd94b776fe21e80f17dc5d78631f55 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/burnt.py @@ -0,0 +1,47 @@ +import torch as th + +from omnigibson.macros import create_module_macros +from omnigibson.object_states.max_temperature import MaxTemperature +from omnigibson.object_states.object_state_base import AbsoluteObjectState, BooleanStateMixin + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.DEFAULT_BURN_TEMPERATURE = 200 + + +class Burnt(AbsoluteObjectState, BooleanStateMixin): + def __init__(self, obj, burn_temperature=None): + super(Burnt, self).__init__(obj) + self.burn_temperature = burn_temperature if burn_temperature is not None else m.DEFAULT_BURN_TEMPERATURE + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(MaxTemperature) + return deps + + def _set_value(self, new_value): + current_max_temp = self.obj.states[MaxTemperature].get_value() + if new_value: + # Set at exactly the burnt temperature (or higher if we have it in history) + desired_max_temp = max(current_max_temp, self.burn_temperature) + else: + # Set at exactly one below burnt temperature (or lower if in history). + desired_max_temp = min(current_max_temp, self.burn_temperature - 1.0) + + return self.obj.states[MaxTemperature].set_value(desired_max_temp) + + def _get_value(self): + return self.obj.states[MaxTemperature].get_value() >= self.burn_temperature + + @staticmethod + def get_texture_change_params(): + # Decrease all channels by 0.3 (to make it black) + albedo_add = -0.3 + # No final scaling + diffuse_tint = th.tensor([1.0, 1.0, 1.0]) + return albedo_add, diffuse_tint + + # Nothing needs to be done to save/load Burnt since it will happen due to + # MaxTemperature caching. diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/cloth_mixin.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/cloth_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..3d947e5ca0fd60f8cb00edb3b81fe8052bf16f1d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/cloth_mixin.py @@ -0,0 +1,38 @@ +from omnigibson.macros import gm +from omnigibson.object_states.object_state_base import BaseObjectState +from omnigibson.utils.constants import PrimType +from omnigibson.utils.python_utils import classproperty + + +class ClothStateMixin(BaseObjectState): + """ + This class is a subclass of BaseObjectState that adds dependencies assuming the owned object is PrimType.CLOTH + """ + + @classmethod + def is_compatible(cls, obj, **kwargs): + # Only compatible with cloth objects + compatible, reason = super().is_compatible(obj, **kwargs) + if not compatible: + return compatible, reason + + # Check for cloth type + if obj.prim_type != PrimType.CLOTH: + return ( + False, + f"Cannot use ClothStateMixin {cls.__name__} with rigid object, make sure object is created " + f"with prim_type=PrimType.CLOTH!", + ) + + # Check for GPU dynamics + if not gm.USE_GPU_DYNAMICS: + return False, f"gm.USE_GPU_DYNAMICS must be True in order to use object state {cls.__name__}." + + return True, None + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("ClothStateMixin") + return classes diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/contact_particles.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/contact_particles.py new file mode 100644 index 0000000000000000000000000000000000000000..92b849a03d54acb160d5225e28819b306883700a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/contact_particles.py @@ -0,0 +1,75 @@ +import omnigibson as og +from omnigibson.macros import create_module_macros +from omnigibson.object_states.aabb import AABB +from omnigibson.object_states.kinematics_mixin import KinematicsMixin +from omnigibson.object_states.object_state_base import RelativeObjectState + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# Distance tolerance for detecting contact +m.CONTACT_AABB_TOLERANCE = 2.5e-2 +m.CONTACT_TOLERANCE = 5e-3 + + +class ContactParticles(RelativeObjectState, KinematicsMixin): + """ + Object state that handles contact checking between rigid bodies and individual particles. + """ + + def _get_value(self, system, link=None): + """ + Args: + system (PhysicalParticleSystem): System whose contact particle info should be aggregated + link (None or RigidPrim): If specified, the specific link to check for particles' contact + + Returns: + set of int: Set of particle IDs in contact + """ + # Make sure system is valid + assert self.obj.scene.is_physical_particle_system( + system_name=system.name + ), "Can only get ContactParticles for a PhysicalParticleSystem!" + + # Variables to update mid-iteration + contacts = set() + idx = 0 + + # Define callback function to use for omni's overlap_sphere() call + def report_hit(hit): + nonlocal link, idx + link_name = None if link is None else link.prim_path.split("/")[-1] + base, body = "/".join(hit.rigid_body.split("/")[:-1]), hit.rigid_body.split("/")[-1] + continue_traversal = True + # If no links are specified, then we assume checking contact with any link owned by this object + # Otherwise, we check for exact match of link name + if (link is None and base == self.obj.prim_path) or (link is not None and link_name == body): + # Add to contacts and terminate early + contacts.add(idx) + continue_traversal = False + return continue_traversal + + # Grab the relaxed AABB of this object or its link for coarse filtering of particles to ignore checking + lower, upper = self.obj.states[AABB].get_value() if link is None else link.visual_aabb + + # Add margin for filtering inbound + lower = lower - (system.particle_radius + m.CONTACT_AABB_TOLERANCE) + upper = upper + (system.particle_radius + m.CONTACT_AABB_TOLERANCE) + + # Iterate over all particles and aggregate contacts + positions = system.get_particles_position_orientation()[0] + # Only check positions that are within the relaxed AABB of this object + inbound_idxs = ((lower < positions) & (positions < upper)).all(dim=-1).nonzero() + dist = system.particle_contact_radius + m.CONTACT_TOLERANCE + for idx in inbound_idxs: + og.sim.psqi.overlap_sphere(dist, positions[idx.item()].cpu().numpy(), report_hit, False) + + # Return contacts + return contacts + + def _set_value(self, system, new_value): + raise NotImplementedError("ContactParticles state currently does not support setting.") + + def _cache_is_valid(self, get_value_args): + # Cache is never valid since particles always change poses + return False diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/contact_subscribed_state_mixin.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/contact_subscribed_state_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..094d21b872bf88c6a2813d380d8362a155112fd2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/contact_subscribed_state_mixin.py @@ -0,0 +1,22 @@ +from abc import abstractmethod + +from omnigibson.object_states.object_state_base import BaseObjectState +from omnigibson.utils.python_utils import classproperty + + +class ContactSubscribedStateMixin(BaseObjectState): + """ + Handles contact events (including CONTACT_FOUND, CONTACT_PERSIST, and CONTACT_LOST). + The subclass should implement its own on_contact method + """ + + @abstractmethod + def on_contact(self, other, contact_headers, contact_data): + raise NotImplementedError("Subclasses of ContactSubscribedStateMixin should implement the on_contact method.") + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("ContactSubscribedStateMixin") + return classes diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/contains.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/contains.py new file mode 100644 index 0000000000000000000000000000000000000000..249fb7bfd33354a5dfa7e9d82aa21dd01115eb38 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/contains.py @@ -0,0 +1,111 @@ +from collections import namedtuple + +import torch as th + +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros +from omnigibson.object_states.link_based_state_mixin import LinkBasedStateMixin +from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState +from omnigibson.utils.python_utils import classproperty + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.CONTAINER_META_LINK_TYPES = ["fillable", "openfillable"] +m.VISUAL_PARTICLE_OFFSET = 0.01 # Offset to visual particles' poses when checking overlaps with container volume + + +""" +ContainedParticlesData contains the following fields: + n_in_volume (int): number of particles in the container volume + positions (th.tensor): (N, 3) array representing the raw global particle positions + in_volume (th.tensor): (N,) boolean array representing whether each particle is inside the container volume or not +""" +ContainedParticlesData = namedtuple("ContainedParticlesData", ("n_in_volume", "positions", "in_volume")) + + +class ContainedParticles(RelativeObjectState, LinkBasedStateMixin): + """ + Object state for computing the number of particles of a given system contained in this object's container volume + """ + + def __init__(self, obj): + super().__init__(obj) + self._compute_info = None # Intermediate computation information to store + + @classproperty + def meta_link_types(cls): + return m.CONTAINER_META_LINK_TYPES + + def _get_value(self, system): + """ + Args: + system (VisualParticleSystem or PhysicalParticleSystem): System whose number of particles will be checked inside this object's + container volume + + Returns: + ContainedParticlesData: namedtuple with the following keys: + - n_in_volume (int): Number of @system's particles inside this object's container volume + - positions (th.tensor): (N, 3) Particle positions of all @system's particles + - in_volume (th.tensor): (N,) boolean array, True if the corresponding particle is inside this + object's container volume, else False + """ + # Value is false by default + n_particles_in_volume, raw_positions, checked_positions, particles_in_volume = ( + 0, + th.empty(0), + th.empty(0), + th.empty(0), + ) + + # Only run additional computations if there are any particles + if system.n_particles > 0: + # First, we check what type of system + # Currently, we support VisualParticleSystems and PhysicalParticleSystems + if self.obj.scene.is_visual_particle_system(system_name=system.name): + # Grab global particle poses and offset them in the direction of their orientation + raw_positions, quats = system.get_particles_position_orientation() + unit_z = th.zeros((len(raw_positions), 3, 1)) + unit_z[:, -1, :] = m.VISUAL_PARTICLE_OFFSET + checked_positions = (T.quat2mat(quats) @ unit_z).reshape(-1, 3) + raw_positions + elif self.obj.scene.is_physical_particle_system(system_name=system.name): + raw_positions = system.get_particles_position_orientation()[0] + checked_positions = raw_positions + else: + raise ValueError( + f"Invalid system {system} received for getting ContainedParticles state!" + f"Currently, only VisualParticleSystems and PhysicalParticleSystems are supported." + ) + + # Only calculate if we have valid positions + if len(checked_positions) > 0: + particles_in_volume = self.link.check_points_in_volume(checked_positions) + n_particles_in_volume = particles_in_volume.sum() + + return ContainedParticlesData(n_particles_in_volume, raw_positions, particles_in_volume) + + def _initialize(self): + super()._initialize() + self.initialize_link_mixin() + + +class Contains(RelativeObjectState, BooleanStateMixin): + def _get_value(self, system): + # Grab value from Contains state; True if value is greater than 0 + return self.obj.states[ContainedParticles].get_value(system=system).n_in_volume > 0 + + def _set_value(self, system, new_value): + if new_value: + # Cannot set contains = True, only False + raise NotImplementedError(f"{self.__class__.__name__} does not support set_value(system, True)") + else: + # Remove all particles from inside the volume + system.remove_particles(idxs=self.obj.states[ContainedParticles].get_value(system).in_volume.nonzero()) + + return True + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(ContainedParticles) + return deps diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/cooked.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/cooked.py new file mode 100644 index 0000000000000000000000000000000000000000..88cc07cedf723b584eeaa286d938a65c8917481f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/cooked.py @@ -0,0 +1,47 @@ +import torch as th + +from omnigibson.macros import create_module_macros +from omnigibson.object_states.max_temperature import MaxTemperature +from omnigibson.object_states.object_state_base import AbsoluteObjectState, BooleanStateMixin + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.DEFAULT_COOK_TEMPERATURE = 70 + + +class Cooked(AbsoluteObjectState, BooleanStateMixin): + def __init__(self, obj, cook_temperature=None): + super(Cooked, self).__init__(obj) + self.cook_temperature = cook_temperature if cook_temperature is not None else m.DEFAULT_COOK_TEMPERATURE + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(MaxTemperature) + return deps + + def _set_value(self, new_value): + current_max_temp = self.obj.states[MaxTemperature].get_value() + if new_value: + # Set at exactly the cook temperature (or higher if we have it in history) + desired_max_temp = max(current_max_temp, self.cook_temperature) + else: + # Set at exactly one below cook temperature (or lower if in history). + desired_max_temp = min(current_max_temp, self.cook_temperature - 1.0) + + return self.obj.states[MaxTemperature].set_value(desired_max_temp) + + def _get_value(self): + return self.obj.states[MaxTemperature].get_value() >= self.cook_temperature + + @staticmethod + def get_texture_change_params(): + # Increase all channels by 0.1 + albedo_add = 0.1 + # Then scale up "brown" color and scale down others + diffuse_tint = th.tensor([1.5, 0.75, 0.25]) + return albedo_add, diffuse_tint + + # Nothing needs to be done to save/load Burnt since it will happen due to + # MaxTemperature caching. diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/covered.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/covered.py new file mode 100644 index 0000000000000000000000000000000000000000..6fa24051e1aa40adefa0ef410a6d96006355d353 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/covered.py @@ -0,0 +1,130 @@ +from omnigibson.macros import create_module_macros +from omnigibson.object_states import AABB +from omnigibson.object_states.contact_particles import ContactParticles +from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState +from omnigibson.systems.system_base import VisualParticleSystem +from omnigibson.utils.constants import PrimType + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# Number of visual particles needed in order for Covered --> True +m.VISUAL_PARTICLE_THRESHOLD = 1 + +# Maximum number of visual particles to sample when setting an object to be covered = True +m.MAX_VISUAL_PARTICLES = 20 + +# Number of physical particles needed in order for Covered --> True +m.PHYSICAL_PARTICLE_THRESHOLD = 1 + +# Maximum number of physical particles to sample when setting an object to be covered = True +m.MAX_PHYSICAL_PARTICLES = 500 + + +class Covered(RelativeObjectState, BooleanStateMixin): + def __init__(self, obj): + # Run super first + super().__init__(obj) + + # Set internal values + self._visual_particle_group = None + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.update({AABB, ContactParticles}) + return deps + + def remove(self): + if self._initialized: + self._clear_attachment_groups() + + def _clear_attachment_groups(self): + """ + Utility function to destroy all corresponding attachment groups for this object + """ + for system in self.obj.scene.active_systems.values(): + if isinstance(system, VisualParticleSystem) and self._visual_particle_group in system.groups: + system.remove_attachment_group(self._visual_particle_group) + + def _initialize(self): + super()._initialize() + # Grab group name + self._visual_particle_group = VisualParticleSystem.get_group_name(obj=self.obj) + + def _get_value(self, system): + # Value is false by default + value = False + # First, we check what type of system + # Currently, we support VisualParticleSystems and PhysicalParticleSystems + if system.n_particles > 0: + if self.obj.scene.is_visual_particle_system(system_name=system.name): + if self._visual_particle_group in system.groups: + # check whether the current number of particles assigned to the group is greater than the threshold + value = system.num_group_particles(group=self._visual_particle_group) >= m.VISUAL_PARTICLE_THRESHOLD + elif self.obj.scene.is_physical_particle_system(system_name=system.name): + # Make sure we're not cloth -- not supported yet + assert ( + self.obj.prim_type != PrimType.CLOTH + ), "Cloth objects currently cannot be Covered by physical particles!" + # We've already cached particle contacts, so we merely search through them to see if any particles are + # touching the object and are visible (the non-visible ones are considered already "removed") + n_near_particles = len(self.obj.states[ContactParticles].get_value(system)) + # Heuristic: If the number of near particles is above the threshold, we consdier this covered + value = n_near_particles >= m.PHYSICAL_PARTICLE_THRESHOLD + else: + raise ValueError( + f"Invalid system {system} received for getting Covered state!" + f"Currently, only VisualParticleSystems and PhysicalParticleSystems are supported." + ) + + return value + + def _set_value(self, system, new_value): + # Default success value is True + success = True + # First, we check what type of system + # Currently, we support VisualParticleSystems and PhysicalParticleSystems + if self.obj.scene.is_visual_particle_system(system_name=system.name): + # Create the group if it doesn't exist already + if self._visual_particle_group not in system.groups: + system.create_attachment_group(obj=self.obj) + + # Check current state and only do something if we're changing state + if self.get_value(system) != new_value: + if new_value: + # Generate particles + success = system.generate_group_particles_on_object( + group=self._visual_particle_group, + max_samples=m.MAX_VISUAL_PARTICLES, + min_samples_for_success=m.VISUAL_PARTICLE_THRESHOLD, + ) + else: + # We remove all of this group's particles + system.remove_all_group_particles(group=self._visual_particle_group) + + elif self.obj.scene.is_physical_particle_system(system_name=system.name): + # Make sure we're not cloth -- not supported yet + assert ( + self.obj.prim_type != PrimType.CLOTH + ), "Cloth objects currently cannot be Covered by physical particles!" + # Check current state and only do something if we're changing state + if self.get_value(system) != new_value: + if new_value: + # Sample particles on top of the object + success = system.generate_particles_on_object( + obj=self.obj, + max_samples=m.MAX_PHYSICAL_PARTICLES, + min_samples_for_success=m.PHYSICAL_PARTICLE_THRESHOLD, + ) + else: + # We remove all particles touching this object + system.remove_particles(idxs=list(self.obj.states[ContactParticles].get_value(system))) + + else: + raise ValueError( + f"Invalid system {system} received for setting Covered state!" + f"Currently, only VisualParticleSystems and PhysicalParticleSystems are supported." + ) + + return success diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/draped.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/draped.py new file mode 100644 index 0000000000000000000000000000000000000000..6adc2de5cc79ab901d657280d49947fd686df3c4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/draped.py @@ -0,0 +1,54 @@ +import torch as th + +import omnigibson as og +from omnigibson.object_states.cloth_mixin import ClothStateMixin +from omnigibson.object_states.kinematics_mixin import KinematicsMixin +from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState +from omnigibson.utils.constants import PrimType +from omnigibson.utils.object_state_utils import sample_cloth_on_rigid + + +class Draped(RelativeObjectState, KinematicsMixin, BooleanStateMixin, ClothStateMixin): + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + return deps + + def _set_value(self, other, new_value): + if not new_value: + raise NotImplementedError("DrapedOver does not support set_value(False)") + + if not (self.obj.prim_type == PrimType.CLOTH and other.prim_type == PrimType.RIGID): + raise ValueError("DrapedOver state requires obj1 is cloth and obj2 is rigid.") + + state = og.sim.dump_state(serialized=False) + + if sample_cloth_on_rigid(self.obj, other, randomize_xy=True) and self.get_value(other): + return True + else: + og.sim.load_state(state, serialized=False) + + return False + + def _get_value(self, other): + """ + Check whether the (cloth) object is draped on the other (rigid) object. + The cloth object should touch the rigid object and its CoM should be below the average position of the contact points. + """ + if not (self.obj.prim_type == PrimType.CLOTH and other.prim_type == PrimType.RIGID): + raise ValueError("Draped state requires obj1 is cloth and obj2 is rigid.") + + # Cloth contact is only available through cloth's get_contacts() method. + contact_link_prim_paths = set(other.link_prim_paths) + contact_positions = [] + for contact_prim_path, contact_position in self.obj.root_link.get_contacts(): + if contact_prim_path in contact_link_prim_paths: + contact_positions.append(contact_position) + + if len(contact_positions) == 0: + return False + + # The center of mass of the cloth needs to be below the average position of the contact points + mean_contact_position = th.mean(th.stack(contact_positions), dim=0) + center_of_mass = th.mean(self.obj.root_link.keypoint_particle_positions, dim=0) + return center_of_mass[2] < mean_contact_position[2] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/factory.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..a6852ee7c9f4fc5c33fe440ef5713aa00f855517 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/factory.py @@ -0,0 +1,281 @@ +from collections import namedtuple + +import networkx as nx + +from omnigibson.object_states import ( + REGISTERED_OBJECT_STATES, + AttachedTo, + Burnt, + Contains, + Cooked, + Covered, + Draped, + Filled, + Folded, + Frozen, + Heated, + HeatSourceOrSink, + Inside, + IsGrasping, + MaxTemperature, + NextTo, + ObjectsInFOVOfRobot, + OnFire, + OnTop, + Open, + Overlaid, + ParticleApplier, + ParticleRemover, + ParticleRequirement, + ParticleSink, + ParticleSource, + Saturated, + SliceableRequirement, + SlicerActive, + ToggledOn, + Touching, + Under, + Unfolded, +) +from omnigibson.object_states.kinematics_mixin import KinematicsMixin +from omnigibson.object_states.link_based_state_mixin import LinkBasedStateMixin + +# states: list of ObjectBaseState +# requirements: list of ObjectBaseRequirement +AbilityDependencies = namedtuple("AbilityDependencies", ("states", "requirements")) + +# Maps ability name to list of Object States and / or Ability Requirements that determine +# whether the given ability can be instantiated for a requested object +_ABILITY_DEPENDENCIES = { + "robot": AbilityDependencies(states=[IsGrasping, ObjectsInFOVOfRobot], requirements=[]), + "attachable": AbilityDependencies(states=[AttachedTo], requirements=[]), + "particleApplier": AbilityDependencies(states=[ParticleApplier], requirements=[]), + "particleRemover": AbilityDependencies(states=[ParticleRemover], requirements=[]), + "particleSource": AbilityDependencies(states=[ParticleSource], requirements=[ParticleRequirement]), + "particleSink": AbilityDependencies(states=[ParticleSink], requirements=[ParticleRequirement]), + "coldSource": AbilityDependencies(states=[HeatSourceOrSink], requirements=[]), + "cookable": AbilityDependencies(states=[Cooked, Burnt], requirements=[]), + "coverable": AbilityDependencies(states=[Covered], requirements=[]), + "freezable": AbilityDependencies(states=[Frozen], requirements=[]), + "heatable": AbilityDependencies(states=[Heated], requirements=[]), + "heatSource": AbilityDependencies(states=[HeatSourceOrSink], requirements=[]), + "meltable": AbilityDependencies(states=[MaxTemperature], requirements=[]), + "mixingTool": AbilityDependencies(states=[], requirements=[]), + "openable": AbilityDependencies(states=[Open], requirements=[]), + # A flammable object is an OnFire threshold detector plus a heat source that is only active + # while the object is on fire (see the per-state param transforms below). + "flammable": AbilityDependencies(states=[OnFire, HeatSourceOrSink], requirements=[]), + "saturable": AbilityDependencies(states=[Saturated], requirements=[]), + "sliceable": AbilityDependencies(states=[], requirements=[SliceableRequirement]), + "slicer": AbilityDependencies(states=[SlicerActive], requirements=[]), + "toggleable": AbilityDependencies(states=[ToggledOn], requirements=[]), + "cloth": AbilityDependencies(states=[Folded, Unfolded, Overlaid, Draped], requirements=[]), + "fillable": AbilityDependencies(states=[Filled, Contains], requirements=[]), +} + +# Per-(ability, state) __init__ kwarg transforms applied when hydrating a state from an ability's +# params. Needed when one ability hydrates multiple states from a single shared param dict whose +# keys don't all match each state's constructor signature. Each entry is (renames, extra_kwargs). +_ABILITY_STATE_PARAM_TRANSFORMS = { + # The flammable params describe both the detector (ignition_temperature, consumed by OnFire + # and by the heat source's self-sustain clamp) and the fire itself (fire_temperature, + # heating_rate, distance_threshold, consumed by the requires_on_fire heat source). + ("flammable", HeatSourceOrSink): ( + {"fire_temperature": "temperature"}, + {"requires_on_fire": True}, + ), +} + + +def transform_ability_params_for_state(ability, state_type, params): + """ + Applies the per-(ability, state) kwarg transform (if any) to @params. + + Args: + ability (str): Ability name + state_type (type): Object state class being hydrated from @ability's params + params (dict): Raw ability params + + Returns: + dict: Transformed copy of @params + """ + transform = _ABILITY_STATE_PARAM_TRANSFORMS.get((ability, state_type), None) + if transform is None: + return dict(params) + renames, extra_kwargs = transform + params = {renames.get(key, key): value for key, value in params.items()} + params.update(extra_kwargs) + return params + + +_DEFAULT_STATE_SET = frozenset( + [ + Inside, + NextTo, + OnTop, + Touching, + Under, + Covered, + ] +) + +_KINEMATIC_STATE_SET = frozenset( + [state for state in REGISTERED_OBJECT_STATES.values() if issubclass(state, KinematicsMixin)] +) + +_FIRE_STATE_SET = frozenset( + [ + HeatSourceOrSink, + OnFire, + ] +) + +_STEAM_STATE_SET = frozenset( + [ + Heated, + ] +) + +_TEXTURE_CHANGE_STATE_SET = frozenset( + [ + Frozen, + Burnt, + Cooked, + Saturated, + ToggledOn, + ] +) + +_SYSTEM_STATE_SET = frozenset( + [ + Covered, + Saturated, + Filled, + Contains, + ] +) + +_VISUAL_STATE_SET = frozenset(_FIRE_STATE_SET | _STEAM_STATE_SET | _TEXTURE_CHANGE_STATE_SET) + +_TEXTURE_CHANGE_PRIORITY = { + Frozen: 4, + Burnt: 3, + Cooked: 2, + Saturated: 1, + ToggledOn: 0, +} + + +def get_system_states(): + return _SYSTEM_STATE_SET + + +def get_fire_states(): + return _FIRE_STATE_SET + + +def get_steam_states(): + return _STEAM_STATE_SET + + +def get_texture_change_states(): + return _TEXTURE_CHANGE_STATE_SET + + +def get_texture_change_priority(): + return _TEXTURE_CHANGE_PRIORITY + + +def get_visual_states(): + return _VISUAL_STATE_SET + + +def get_default_states(): + return _DEFAULT_STATE_SET + + +def get_state_name(state): + # Get the name of the class. + return state.__name__ + + +def get_states_for_ability(ability): + if ability not in _ABILITY_DEPENDENCIES: + return [] + return _ABILITY_DEPENDENCIES[ability].states + + +def get_states_and_params_for_ability(ability, params): + """ + Enumerate the (state_type, params) pairs an @ability contributes, with the per-(ability, state) + param transform (see @transform_ability_params_for_state) applied to each. + + Both object hydration (USDObject) and asset model-validation + (get_all_object_category_models_with_abilities) must instantiate an ability's states with the + SAME kwargs, otherwise a model can pass one path and fail the other. They therefore share this + helper so the two never drift apart -- e.g. `flammable` injects requires_on_fire=True into + HeatSourceOrSink, which flips its meta-link requirement; without the transform, validation + would demand a heatsource meta link that hydration does not. + + Args: + ability (str): Ability name + params (dict): Raw ability params + + Returns: + list of (type, dict): (state_type, transformed_params) for each state @ability contributes + """ + return [ + (state_type, transform_ability_params_for_state(ability, state_type, params)) + for state_type in get_states_for_ability(ability) + ] + + +def get_requirements_for_ability(ability): + if ability not in _ABILITY_DEPENDENCIES: + return [] + return _ABILITY_DEPENDENCIES[ability].requirements + + +def get_state_dependency_graph(states=None): + """ + Args: + states (None or Iterable): If specified, specific state(s) to sort. Otherwise, will generate dependency graph + over all states + + Returns: + nx.DiGraph: State dependency graph of supported object states + """ + states = REGISTERED_OBJECT_STATES.values() if states is None else states + dependencies = {state: set.union(state.get_dependencies(), state.get_optional_dependencies()) for state in states} + return nx.DiGraph(dependencies) + + +def get_states_by_dependency_order(states=None): + """ + Args: + states (None or Iterable): If specified, specific state(s) to sort. Otherwise, will generate dependency graph + over all states + + Returns: + list: all states in topological order of dependency + """ + return list( + reversed( + list( + nx.algorithms.lexicographical_topological_sort( + get_state_dependency_graph(states), key=lambda n: n.__name__ + ) + ) + ) + ) + + +# Define all meta links +META_LINK_TYPES = set() +for state in get_states_by_dependency_order(): + if issubclass(state, LinkBasedStateMixin): + try: + for meta_link_type in state.meta_link_types: + META_LINK_TYPES.add(meta_link_type) + except NotImplementedError: + pass diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/filled.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/filled.py new file mode 100644 index 0000000000000000000000000000000000000000..e00c8cf5e32f597c5d44dd3db4b9714b083535c5 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/filled.py @@ -0,0 +1,72 @@ +from omnigibson.macros import create_module_macros +from omnigibson.object_states.contains import ContainedParticles +from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState +from omnigibson.systems.macro_particle_system import MacroParticleSystem + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# Proportion of object's volume that must be filled for object to be considered filled +m.VOLUME_FILL_PROPORTION = 0.2 +m.N_MAX_MACRO_PARTICLE_SAMPLES = 500 +m.N_MAX_MICRO_PARTICLE_SAMPLES = 100000 + + +class Filled(RelativeObjectState, BooleanStateMixin): + def _get_value(self, system): + # Sanity check to make sure system is valid + assert self.obj.scene.is_physical_particle_system( + system_name=system.name + ), "Can only get Filled state with a valid PhysicalParticleSystem!" + + # Check what volume is filled + if system.n_particles > 0: + # Treat particles as cubes + particle_volume = (system.particle_radius * 2) ** 3 + n_particles = self.obj.states[ContainedParticles].get_value(system).n_in_volume + prop_filled = particle_volume * n_particles / self.obj.states[ContainedParticles].link.volume + # If greater than threshold, then the volume is filled + # Explicit bool cast needed here because the type is bool_ instead of bool which is not JSON-Serializable + # This has to do with numpy, see https://stackoverflow.com/questions/58408054/typeerror-object-of-type-bool-is-not-json-serializable + value = bool(prop_filled > m.VOLUME_FILL_PROPORTION) + else: + # No particles exists, so we're obviously empty + value = False + + return value + + def _set_value(self, system, new_value): + # Sanity check to make sure system is valid + assert self.obj.scene.is_physical_particle_system( + system_name=system.name + ), "Can only set Filled state with a valid PhysicalParticleSystem!" + + # First, check our current state + current_state = self.get_value(system) + + # Only do something if we're changing state + if current_state != new_value: + contained_particles_state = self.obj.states[ContainedParticles] + if new_value: + # Going from False --> True, sample volume with particles + system.generate_particles_from_link( + obj=self.obj, + link=contained_particles_state.link, + check_contact=True, + max_samples=( + m.N_MAX_MACRO_PARTICLE_SAMPLES + if isinstance(system, MacroParticleSystem) + else m.N_MAX_MICRO_PARTICLE_SAMPLES + ), + ) + else: + # Cannot set False + raise NotImplementedError(f"{self.__class__.__name__} does not support set_value(system, False)") + + return True + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(ContainedParticles) + return deps diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/folded.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/folded.py new file mode 100644 index 0000000000000000000000000000000000000000..62c05be0c3e0d0a208de83d03cfd1a4b4ab79728 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/folded.py @@ -0,0 +1,183 @@ +import math +from collections import namedtuple + +import torch as th +from scipy.spatial import ConvexHull, QhullError, distance_matrix + +from omnigibson.macros import create_module_macros +from omnigibson.object_states.cloth_mixin import ClothStateMixin +from omnigibson.object_states.object_state_base import AbsoluteObjectState, BooleanStateMixin + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# Criterion #1: the threshold on the area ratio of the convex hull of the projection on the XY plane +m.FOLDED_AREA_THRESHOLD = 0.75 +m.UNFOLDED_AREA_THRESHOLD = 0.9 + +# Criterion #2: the threshold on the diagonal ratio of the convex hull of the projection on the XY plane +m.FOLDED_DIAGONAL_THRESHOLD = 0.85 +m.UNFOLDED_DIAGONAL_THRESHOLD = 0.9 + +# Criterion #3: the percentage of face normals that need to be close to the z-axis +m.NORMAL_Z_PERCENTAGE = 0.5 + +# Whether to visualize the convex hull of the projection on the XY plane +m.DEBUG_CLOTH_PROJ_VIS = False + +# Angle threshold for checking smoothness of the cloth; surface normals need to be close enough to the z-axis +m.NORMAL_Z_ANGLE_DIFF = th.deg2rad(th.tensor([45.0])).item() + +""" +FoldedLevelData contains the following fields: + smoothness (float): percentage of surface normals that are sufficiently close to the z-axis + area (float): the area of the convex hull of the projected points compared to the initial unfolded state + diagonal (float): the diagonal of the convex hull of the projected points compared to the initial unfolded state +""" +FoldedLevelData = namedtuple("FoldedLevelData", ("smoothness", "area", "diagonal")) + + +class FoldedLevel(AbsoluteObjectState, ClothStateMixin): + """ + State representing the object's folded level. + Value is a FoldedLevelData object. + """ + + def _initialize(self): + super()._initialize() + # Assume the initial state is unfolded + self.area_unfolded, self.diagonal_unfolded = self.calculate_projection_area_and_diagonal_maximum() + + def _get_value(self): + smoothness = self.calculate_smoothness() + area, diagonal = self.calculate_projection_area_and_diagonal([0, 1]) + return FoldedLevelData(smoothness, area / self.area_unfolded, diagonal / self.diagonal_unfolded) + + def calculate_smoothness(self): + """ + Calculate the percantage of surface normals that are sufficiently close to the z-axis. + """ + cloth = self.obj.root_link + normals = cloth.compute_face_normals(face_ids=cloth.keyface_idx) + + # projection onto the z-axis + proj = th.abs(normals @ th.tensor([0.0, 0.0, 1.0], dtype=th.float32)) + percentage = th.mean((proj > math.cos(m.NORMAL_Z_ANGLE_DIFF)).float()).item() + return percentage + + def calculate_projection_area_and_diagonal_maximum(self): + """ + Calculate the maximum projection area and the diagonal length along different axes + + Returns: + area_max (float): area of the convex hull of the projected points + diagonal_max (float): diagonal of the convex hull of the projected points + """ + # use the largest projection area as the unfolded area + area_max = 0.0 + diagonal_max = 0.0 + dims_list = [[0, 1], [0, 2], [1, 2]] # x-y plane, x-z plane, y-z plane + + for dims in dims_list: + area, diagonal = self.calculate_projection_area_and_diagonal(dims) + if area > area_max: + area_max = area + diagonal_max = diagonal + + return area_max, diagonal_max + + def calculate_projection_area_and_diagonal(self, dims): + """ + Calculate the projection area and the diagonal length when projecting to the plane defined by the input dims + E.g. if dims is [0, 1], the points will be projected onto the x-y plane. + + Args: + dims (2-array): Global axes to project area onto. Options are {0, 1, 2}. + E.g. if dims is [0, 1], project onto the x-y plane. + + Returns: + area (float): area of the convex hull of the projected points + diagonal (float): diagonal of the convex hull of the projected points + """ + cloth = self.obj.root_link + points = cloth.keypoint_particle_positions[:, dims] + try: + hull = ConvexHull(points) + + # The points may be 2D-degenerate, so catch the error and return 0 if so + except QhullError: + # This is a degenerate hull, so return 0 area and diagonal + return 0.0, 0.0 + + # When input points are 2-dimensional, this is the area of the convex hull. + # Ref: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html + area = hull.volume + diagonal = distance_matrix(points[hull.vertices], points[hull.vertices]).max() + + if m.DEBUG_CLOTH_PROJ_VIS: + import matplotlib.pyplot as plt + + ax = plt.gca() + ax.set_aspect("equal") + + plt.plot(points[:, 0], points[:, 1], "o") + for simplex in hull.simplices: + plt.plot(points[simplex, 0], points[simplex, 1], "k-") + plt.plot(points[hull.vertices, 0], points[hull.vertices, 1], "r--", lw=2) + plt.plot(points[hull.vertices[0], 0], points[hull.vertices[0], 1], "ro") + plt.show() + + return area, diagonal + + +class Folded(AbsoluteObjectState, BooleanStateMixin, ClothStateMixin): + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(FoldedLevel) + return deps + + def _get_value(self): + # Check the smoothness of the cloth + folded_level = self.obj.states[FoldedLevel].get_value() + return ( + folded_level.smoothness >= m.NORMAL_Z_PERCENTAGE + and folded_level.area < m.FOLDED_AREA_THRESHOLD + and folded_level.diagonal < m.FOLDED_DIAGONAL_THRESHOLD + ) + + def _set_value(self, new_value): + if not new_value: + raise NotImplementedError("Folded does not support set_value(False)") + + # TODO (eric): add this support + raise NotImplementedError("Folded does not support set_value(True)") + + # We don't need to dump / load anything since the cloth objects should handle it themselves + + +class Unfolded(AbsoluteObjectState, BooleanStateMixin, ClothStateMixin): + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(FoldedLevel) + return deps + + def _get_value(self): + # Check the smoothness of the cloth + folded_level = self.obj.states[FoldedLevel].get_value() + return ( + folded_level.smoothness >= m.NORMAL_Z_PERCENTAGE + and folded_level.area >= m.UNFOLDED_AREA_THRESHOLD + and folded_level.diagonal >= m.UNFOLDED_DIAGONAL_THRESHOLD + ) + + def _set_value(self, new_value): + if not new_value: + raise NotImplementedError("Unfolded does not support set_value(False)") + + self.obj.root_link.reset() + + return True + + # We don't need to dump / load anything since the cloth objects should handle it themselves diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/frozen.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/frozen.py new file mode 100644 index 0000000000000000000000000000000000000000..ffc04b440ad66425baa628d56f5223e80e431c1a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/frozen.py @@ -0,0 +1,53 @@ +import torch as th + +from omnigibson.macros import create_module_macros +from omnigibson.object_states.object_state_base import AbsoluteObjectState, BooleanStateMixin +from omnigibson.object_states.temperature import Temperature + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.DEFAULT_FREEZE_TEMPERATURE = 0.0 + +# When an object is set as frozen, we will sample it between +# the freeze temperature and these offsets. +m.FROZEN_SAMPLING_RANGE_MAX = -10.0 +m.FROZEN_SAMPLING_RANGE_MIN = -50.0 + + +class Frozen(AbsoluteObjectState, BooleanStateMixin): + def __init__(self, obj, freeze_temperature=None): + super(Frozen, self).__init__(obj) + self.freeze_temperature = freeze_temperature if freeze_temperature is not None else m.DEFAULT_FREEZE_TEMPERATURE + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(Temperature) + return deps + + def _set_value(self, new_value): + if new_value: + temp_lo, temp_hi = ( + self.freeze_temperature + m.FROZEN_SAMPLING_RANGE_MIN, + self.freeze_temperature + m.FROZEN_SAMPLING_RANGE_MAX, + ) + temperature = (th.rand(1) * (temp_hi - temp_lo) + temp_lo).item() + return self.obj.states[Temperature].set_value(temperature) + else: + # We'll set the temperature just one degree above freezing. Hopefully the object + # isn't in a fridge. + return self.obj.states[Temperature].set_value(self.freeze_temperature + 1.0) + + def _get_value(self): + return self.obj.states[Temperature].get_value() <= self.freeze_temperature + + @staticmethod + def get_texture_change_params(): + # Increase all channels by 0.3 (to make it white) + albedo_add = 0.3 + # No final scaling + diffuse_tint = th.tensor([1.0, 1.0, 1.0]) + return albedo_add, diffuse_tint + + # Nothing needs to be done to save/load Frozen since it will happen due to temperature caching. diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/heat_source_or_sink.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/heat_source_or_sink.py new file mode 100644 index 0000000000000000000000000000000000000000..3afec4331fed7cb40db4b4a05546fe75339d98c4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/heat_source_or_sink.py @@ -0,0 +1,525 @@ +import torch as th +import warp as wp + +import omnigibson.lazy as lazy +from omnigibson.macros import create_module_macros +from omnigibson.object_states.aabb import AABB +from omnigibson.object_states.inside import Inside +from omnigibson.object_states.link_based_state_mixin import LinkBasedStateMixin +from omnigibson.object_states.open_state import Open +from omnigibson.object_states.tensorized_absolute_state import TensorizedAbsoluteState +from omnigibson.object_states.tensorized_state import TensorizedState +from omnigibson.object_states.toggle import ToggledOn +from omnigibson.utils.python_utils import classproperty +from omnigibson.utils.usd_utils import RigidBodyViewAPI + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.HEATSOURCE_META_LINK_TYPE = "heatsource" +m.HEATING_ELEMENT_MARKER_SCALE = [1.0] * 3 + +# TODO: Delete default values for this and make them required. +m.DEFAULT_TEMPERATURE = 200 +m.DEFAULT_FIRE_TEMPERATURE = 1000 +m.DEFAULT_HEATING_RATE = 0.04 +m.DEFAULT_DISTANCE_THRESHOLD = 0.2 +m.DEFAULT_IGNITION_TEMPERATURE = 250 + + +@wp.kernel +def _heatsource_is_active_kernel( + requires_toggled_on: wp.array(dtype=wp.uint8), # (N_hss,) + requires_closed: wp.array(dtype=wp.uint8), # (N_hss,) + requires_on_fire: wp.array(dtype=wp.uint8), # (N_hss,) + toggle_idx: wp.array(dtype=wp.int32), # (N_hss,) into ToggledOn.OBJ_IDXS, -1 if missing + open_idx: wp.array(dtype=wp.int32), # (N_hss,) into Open.OBJ_IDXS, -1 if missing + onfire_idx: wp.array(dtype=wp.int32), # (N_hss,) into OnFire.OBJ_IDXS, -1 if missing + toggle_values: wp.array2d(dtype=wp.uint8), # (S_toggle, N_toggle) + open_values: wp.array2d(dtype=wp.uint8), # (S_open, N_open) + onfire_values: wp.array2d(dtype=wp.uint8), # (S_onfire, N_onfire) — PREVIOUS step's values + n_toggle_scenes: wp.int32, # scene rows in toggle_values (0 if the state tracks nothing) + n_open_scenes: wp.int32, + n_onfire_scenes: wp.int32, + out_values: wp.array2d(dtype=wp.uint8), # (S, N_hss) — set to 1 if gate passes +): + """ + hss = heat_source_or_sink + Per (scene, hss) thread: compute whether this hss is active. 0 not active. 1 active. + + Active iff: + - !requires_toggled_on OR ToggledOn[scene, toggle_idx[h]] is True + - !requires_closed OR Open[scene, open_idx[h]] is False + - !requires_on_fire OR OnFire[scene, onfire_idx[h]] is True (previous step's value — + OnFire runs after this state in the captured graph; see class docstring) + """ + s, h = wp.tid() + active = wp.uint8(1) + if requires_toggled_on[h] != wp.uint8(0): + ti = toggle_idx[h] + if ti < wp.int32(0) or s >= n_toggle_scenes: + active = wp.uint8(0) + elif toggle_values[s, ti] == wp.uint8(0): + active = wp.uint8(0) + if active == wp.uint8(1) and requires_closed[h] != wp.uint8(0): + oi = open_idx[h] + if oi < wp.int32(0) or s >= n_open_scenes: + active = wp.uint8(0) + elif open_values[s, oi] != wp.uint8(0): + active = wp.uint8(0) + if active == wp.uint8(1) and requires_on_fire[h] != wp.uint8(0): + fi = onfire_idx[h] + if fi < wp.int32(0) or s >= n_onfire_scenes: + active = wp.uint8(0) + elif onfire_values[s, fi] == wp.uint8(0): + active = wp.uint8(0) + out_values[s, h] = active + + +class HeatSourceOrSink(TensorizedAbsoluteState, LinkBasedStateMixin): + """ + Boolean state: whether this heat source / sink is currently active, i.e. whether all of its + activation gates are satisfied: + - requires_toggled_on → ToggledOn must be True + - requires_closed → Open must be False + - requires_on_fire → OnFire must be True. OnFire depends on Temperature, which depends + on this state, so inside the captured graph this gate reads the PREVIOUS step's OnFire + values — the deliberate one-step lag that breaks the fire feedback cycle. + + This state only computes its own gate. The actual heat propagation — which targets an + active source influences, by how much, and the self-sustaining fire clamp — is computed by + Temperature (which depends on this state) from the per-source config arrays published here. + `affects_obj()` queries Temperature's influence mask. + + A flammable object is modeled by the `flammable` ability as an OnFire threshold detector + plus an instance of this state with requires_on_fire=True and temperature=fire_temperature. + """ + + # Per-HSS config (N_hss,) — uploaded once in initialize_view as wp.arrays (single source of + # truth). Read by Temperature's kernels (Temperature depends on this state). + _temperatures = None # wp.array (N_hss,) float32 + _heating_rates = None # wp.array (N_hss,) float32 + _distance_thresholds = None # wp.array (N_hss,) float32 + _requires_toggled_on = None # wp.array (N_hss,) uint8 + _requires_closed = None # wp.array (N_hss,) uint8 + _requires_inside = None # wp.array (N_hss,) uint8 + _requires_on_fire = None # wp.array (N_hss,) uint8 + _ignition_temperatures = None # wp.array (N_hss,) float32 — self-clamp threshold (requires_on_fire only) + _link_flat_idx = None # wp.array (S_hss, N_hss) int32 into RigidBodyViewAPI.POSE_MATRICES — -1 if requires_inside + _link_local_offset = None # wp.array (N_hss,) vec3 — offset of heat element in link frame + + # Index maps into the gate states' OBJ_IDXS — rebuilt in pre_update because OnFire's view + # initializes AFTER this state's (OnFire depends on Temperature, which depends on this state). + _self_toggle_idx = None # wp.array (N_hss,) int32 into ToggledOn.OBJ_IDXS + _self_open_idx = None # wp.array (N_hss,) int32 into Open.OBJ_IDXS + _self_onfire_idx = None # wp.array (N_hss,) int32 into OnFire.OBJ_IDXS + + # Placeholder wp.array to fill into kernel arguments when an optional gate state + # (ToggledOn, Open, OnFire) tracks no objects. Warp requires a valid wp.array of the + # correct dtype for the signature. + _placeholder_values = None # wp.array (1, 1) uint8 + + def __init__( + self, + obj, + temperature=None, + heating_rate=None, + distance_threshold=None, + requires_toggled_on=False, + requires_closed=False, + requires_inside=False, + requires_on_fire=False, + ignition_temperature=None, + ): + """ + Args: + obj (StatefulObject): The object with the heat source ability. + temperature (float): The temperature of the heat source. Defaults to + DEFAULT_FIRE_TEMPERATURE when @requires_on_fire, otherwise DEFAULT_TEMPERATURE. + heating_rate (float): Fraction in [0, 1] of the temperature difference with the + heat source temperature should be received every step, per second. + distance_threshold (float): The distance threshold which an object needs + to be closer than in order to receive heat from this heat source. + requires_toggled_on (bool): Whether the heat source object needs to be + toggled on to emit heat. Requires toggleable ability if set to True. + requires_closed (bool): Whether the heat source object needs to be + closed (e.g. in terms of the joints) to emit heat. Requires openable + ability if set to True. + requires_inside (bool): Whether an object needs to be `inside` the + heat source to receive heat. See the Inside state for details. This + will mean that the "heating element" link for the object will be + ignored. + requires_on_fire (bool): Whether this heat source is the object's own fire, i.e. + only active while the object's OnFire state is True. Set (together with + @ignition_temperature) by the flammable ability, which pairs this state with + OnFire. Requires the OnFire state if set to True. + ignition_temperature (float): Only relevant if @requires_on_fire. Threshold at / + above which the fire sustains itself: while active, Temperature holds this + object at @temperature unless it has been cooled below this threshold + (e.g. extinguished). + """ + super().__init__(obj) + default_temperature = m.DEFAULT_FIRE_TEMPERATURE if requires_on_fire else m.DEFAULT_TEMPERATURE + self._temperature = temperature if temperature is not None else default_temperature + self._heating_rate = heating_rate if heating_rate is not None else m.DEFAULT_HEATING_RATE + self.distance_threshold = distance_threshold if distance_threshold is not None else m.DEFAULT_DISTANCE_THRESHOLD + + if requires_toggled_on: + assert ToggledOn in self.obj.states + self.requires_toggled_on = requires_toggled_on + + if requires_closed: + assert Open in self.obj.states + self.requires_closed = requires_closed + + self.requires_inside = requires_inside + + # OnFire is constructed after this state (it depends on Temperature, which depends on + # this state), so its presence is validated in _initialize instead of here. + self.requires_on_fire = requires_on_fire + self.ignition_temperature = ( + ignition_temperature if ignition_temperature is not None else m.DEFAULT_IGNITION_TEMPERATURE + ) + if requires_on_fire: + assert ( + self._temperature > self.ignition_temperature + ), "fire temperature should be higher than ignition temperature." + + @classmethod + def is_compatible(cls, obj, **kwargs): + compatible, reason = super().is_compatible(obj, **kwargs) + if not compatible: + return compatible, reason + for kwarg, state_type in zip(("requires_toggled_on", "requires_closed"), (ToggledOn, Open)): + if kwargs.get(kwarg, False) and state_type not in obj.states: + return False, f"{cls.__name__} has {kwarg} but obj has no {state_type.__name__} state!" + return True, None + + @classmethod + def is_compatible_asset(cls, prim, **kwargs): + compatible, reason = super().is_compatible_asset(prim, **kwargs) + if not compatible: + return compatible, reason + for kwarg, state_type in zip(("requires_toggled_on", "requires_closed"), (ToggledOn, Open)): + if kwargs.get(kwarg, False) and not state_type.is_compatible_asset(prim=prim, **kwargs)[0]: + return False, f"{cls.__name__} has {kwarg} but obj has no {state_type.__name__} state!" + return True, None + + @classproperty + def meta_link_types(cls): + return [m.HEATSOURCE_META_LINK_TYPE] + + @classmethod + def requires_meta_link(cls, **kwargs): + # No meta link required for containment-based sources or fire sources (which fall back + # to the root link). + return not (kwargs.get("requires_inside", False) or kwargs.get("requires_on_fire", False)) + + @property + def _default_link(self): + # Fall back to the root link when no meta link is required + if self.requires_inside or self.requires_on_fire: + return self.obj.root_link + return super()._default_link + + @property + def heating_rate(self): + """ + Returns: + float: Temperature changing rate of this heat source / sink + """ + return self._heating_rate + + @property + def temperature(self): + """ + Returns: + float: Temperature of this heat source / sink + """ + return self._temperature + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + # AABB / Inside are consumed by Temperature's heat-gather kernel, but the source object + # itself must be registered with them (e.g. a target is heated by an oven only if it is + # Inside the oven), so they are required here. + deps.update({AABB, Inside}) + return deps + + @classmethod + def get_optional_dependencies(cls): + deps = super().get_optional_dependencies() + # Gate states. NOTE: OnFire is deliberately NOT listed — it depends on Temperature, + # which depends on this state, so declaring it would create a cycle. Its values are + # read lag-1 instead (see class docstring). + deps.update({ToggledOn, Open}) + return deps + + @classproperty + def value_type(cls): + return th.bool + + @classproperty + def value_name(cls): + return "heat_source_or_sink" + + def _initialize(self): + super()._initialize() + self.initialize_link_mixin() + if self.requires_on_fire: + # Local import to avoid a module-level cycle (on_fire imports temperature, which + # imports this module). + from omnigibson.object_states.on_fire import OnFire + + assert ( + OnFire in self.obj.states + ), f"{type(self).__name__} on {self.obj.name} has requires_on_fire but obj has no OnFire state!" + + @classmethod + def global_initialize(cls): + super().global_initialize() + cls._temperatures = None + cls._heating_rates = None + cls._distance_thresholds = None + cls._requires_toggled_on = None + cls._requires_closed = None + cls._requires_inside = None + cls._requires_on_fire = None + cls._ignition_temperatures = None + cls._link_flat_idx = None + cls._link_local_offset = None + cls._self_toggle_idx = None + cls._self_open_idx = None + cls._self_onfire_idx = None + + # Placeholder wp.array to fill into kernel arguments when an optional gate state is empty. + cls._placeholder_values = wp.zeros((1, 1), dtype=wp.uint8, device="cuda") + + @classmethod + def initialize_view(cls): + # Base class rebuilds OBJ_IDXS, IDX_OBJS, VALUES + super().initialize_view() + + N = len(cls.OBJ_IDXS) + if N == 0: + cls._temperatures = None + cls._heating_rates = None + cls._distance_thresholds = None + cls._requires_toggled_on = None + cls._requires_closed = None + cls._requires_inside = None + cls._requires_on_fire = None + cls._ignition_temperatures = None + cls._link_flat_idx = None + cls._link_local_offset = None + cls._self_toggle_idx = None + cls._self_open_idx = None + cls._self_onfire_idx = None + return + + temperatures = th.zeros(N, dtype=th.float32) + heating_rates = th.zeros(N, dtype=th.float32) + distance_thresholds = th.zeros(N, dtype=th.float32) + requires_toggled_on = th.zeros(N, dtype=th.uint8) + requires_closed = th.zeros(N, dtype=th.uint8) + requires_inside = th.zeros(N, dtype=th.uint8) + requires_on_fire = th.zeros(N, dtype=th.uint8) + ignition_temperatures = th.zeros(N, dtype=th.float32) + # Per (scene, source): each scene's clone of a source is a DIFFERENT rigid body with its + # own flat index into RigidBodyViewAPI.POSE_MATRICES, so the element link index must be + # resolved per scene. (The config arrays above stay (N,) — they are scene-invariant.) + S = len(cls.IDX_OBJS) + link_flat_idx = th.full((S, N), -1, dtype=th.int32) + link_local_offset = th.zeros((N, 3), dtype=th.float32) + + for _, hss_obj_idx in cls.OBJ_IDXS.items(): + hss_state_instance = None + for scene_row in cls.IDX_OBJS: + if scene_row[hss_obj_idx] is not None: + hss_state_instance = scene_row[hss_obj_idx].states[cls] + break + if hss_state_instance is None: + continue + temperatures[hss_obj_idx] = float(hss_state_instance._temperature) + heating_rates[hss_obj_idx] = float(hss_state_instance._heating_rate) + distance_thresholds[hss_obj_idx] = float(hss_state_instance.distance_threshold) + requires_toggled_on[hss_obj_idx] = 1 if hss_state_instance.requires_toggled_on else 0 + requires_closed[hss_obj_idx] = 1 if hss_state_instance.requires_closed else 0 + requires_inside[hss_obj_idx] = 1 if hss_state_instance.requires_inside else 0 + requires_on_fire[hss_obj_idx] = 1 if hss_state_instance.requires_on_fire else 0 + ignition_temperatures[hss_obj_idx] = float(hss_state_instance.ignition_temperature) + if not hss_state_instance.requires_inside: + # Store this hss' heat element link so Temperature can compute source positions: + # the meta link when annotated (e.g. a candle wick), the root link for fire sources + # without one. Resolved PER SCENE: each scene's clone has its own link prim (and + # therefore its own flat pose index). + for s_idx, scene_row in enumerate(cls.IDX_OBJS): + scene_obj = scene_row[hss_obj_idx] + if scene_obj is None: + continue + scene_state = scene_obj.states[cls] + if scene_state._links: + link = scene_state.link + elif scene_state.requires_on_fire: + link = scene_obj.root_link + else: + link = None + if link is not None: + flat = RigidBodyViewAPI.get_flat_idx(link.prim_path) + if flat is not None: + link_flat_idx[s_idx, hss_obj_idx] = int(flat) + + create_tensor_from_list = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list + cls._temperatures = create_tensor_from_list(temperatures, "float32", device="cuda") + cls._heating_rates = create_tensor_from_list(heating_rates, "float32", device="cuda") + cls._distance_thresholds = create_tensor_from_list(distance_thresholds, "float32", device="cuda") + cls._requires_toggled_on = create_tensor_from_list(requires_toggled_on, "uint8", device="cuda") + cls._requires_closed = create_tensor_from_list(requires_closed, "uint8", device="cuda") + cls._requires_inside = create_tensor_from_list(requires_inside, "uint8", device="cuda") + cls._requires_on_fire = create_tensor_from_list(requires_on_fire, "uint8", device="cuda") + cls._ignition_temperatures = create_tensor_from_list(ignition_temperatures, "float32", device="cuda") + # (S, N) int32 — wp.array reinterprets the 2D torch buffer directly. + cls._link_flat_idx = wp.array(link_flat_idx, dtype=wp.int32, device="cuda") + # vec3 has no scalar-only helper — wp.array reinterprets the (N, 3) float32 CPU buffer as (N,) vec3. + cls._link_local_offset = wp.array(link_local_offset, dtype=wp.vec3, device="cuda") + + # Gate index maps are deferred to pre_update — OnFire's view has not been rebuilt yet + # at this point (it initializes after Temperature, which initializes after this state). + cls._self_toggle_idx = None + cls._self_open_idx = None + cls._self_onfire_idx = None + + @classmethod + def _rebuild_cross_state_maps(cls): + """ + Build (or rebuild) the index tables into the gate states' OBJ_IDXS. Called from + pre_update when the captured graph is being rebuilt, because OnFire's view initializes + AFTER this state's. + """ + # Local import to avoid a module-level cycle + from omnigibson.object_states.on_fire import OnFire + + N = len(cls.OBJ_IDXS) if cls.OBJ_IDXS is not None else 0 + if N == 0: + return + + toggle_map = ToggledOn.OBJ_IDXS or {} + open_map = Open.OBJ_IDXS or {} + onfire_map = OnFire.OBJ_IDXS or {} + + self_toggle_idx = th.full((N,), -1, dtype=th.int32) + self_open_idx = th.full((N,), -1, dtype=th.int32) + self_onfire_idx = th.full((N,), -1, dtype=th.int32) + for rel_path, obj_idx in cls.OBJ_IDXS.items(): + self_toggle_idx[obj_idx] = toggle_map.get(rel_path, -1) + self_open_idx[obj_idx] = open_map.get(rel_path, -1) + self_onfire_idx[obj_idx] = onfire_map.get(rel_path, -1) + + create_tensor_from_list = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list + cls._self_toggle_idx = create_tensor_from_list(self_toggle_idx, "int32", device="cuda") + cls._self_open_idx = create_tensor_from_list(self_open_idx, "int32", device="cuda") + cls._self_onfire_idx = create_tensor_from_list(self_onfire_idx, "int32", device="cuda") + + @classmethod + def pre_update(cls, dt=0.0): + super().pre_update(dt) + # Only rebuild when the captured graph is being rebuilt. graph_dirty is the single + # trigger: every event that invalidates the index tables goes through some state's + # initialize_view, which sets graph_dirty. Rebuild reallocates GPU buffers that must be + # baked into the freshly-captured graph, so rebuild and recapture must stay coupled. + if TensorizedState.graph_dirty: + cls._rebuild_cross_state_maps() + + @classmethod + def _update_values(cls, values): + # Local import to avoid a module-level cycle + from omnigibson.object_states.on_fire import OnFire + + if cls.VALUES_WP is None or cls._self_toggle_idx is None: + return + S, N = cls.VALUES.shape[:2] + if S == 0 or N == 0: + return + + # An optional gate state may track no objects; swap in a cached placeholder wp.array to + # satisfy the kernel's signature, with a scene count of 0 so it is never read. + def gate_values(state): + values_wp = state.VALUES_WP + if values_wp is None: + return cls._placeholder_values, 0 + return values_wp, state.VALUES.shape[0] + + toggle_values_wp, n_toggle_scenes = gate_values(ToggledOn) + open_values_wp, n_open_scenes = gate_values(Open) + # NOTE: lag-1 read — OnFire runs after this state in the captured graph, so these are + # the previous step's values. This is the deliberate one-step delay that breaks the + # OnFire → Temperature → HeatSourceOrSink dependency cycle. + onfire_values_wp, n_onfire_scenes = gate_values(OnFire) + + wp.launch( + kernel=_heatsource_is_active_kernel, + dim=(S, N), + inputs=[ + cls._requires_toggled_on, + cls._requires_closed, + cls._requires_on_fire, + cls._self_toggle_idx, + cls._self_open_idx, + cls._self_onfire_idx, + toggle_values_wp, + open_values_wp, + onfire_values_wp, + wp.int32(n_toggle_scenes), + wp.int32(n_open_scenes), + wp.int32(n_onfire_scenes), + cls.VALUES_WP, + ], + device="cuda", + ) + + def _get_value(self): + # Raw read of the CPU mirror. Freshness is handled by the public get_value() wrapper + # (TensorizedState.get_value -> maybe_refresh_caches), matching AABB/ToggledOn. Refreshing + # here would also fire on the _dump_state path (e.g. prim_base.initialize's state-size + # probe), forcing a mid-init cache refresh + post_update. + if self.OBJ_IDXS is None or self.obj.relative_prim_path not in self.OBJ_IDXS: + return False + s = self.obj.scene.idx + obj_idx = self.OBJ_IDXS[self.obj.relative_prim_path] + return bool(self.VALUES_CPU[s, obj_idx].item()) + + def _set_value(self, new_value): + # Boolean gate; setter mostly used for testing / state reset. Write both CPU + GPU + # so the next read is consistent without waiting for the next graph pass. + s = self.obj.scene.idx + if self.obj.relative_prim_path not in self.OBJ_IDXS: + return False + obj_idx = self.OBJ_IDXS[self.obj.relative_prim_path] + self.VALUES[s, obj_idx] = bool(new_value) + self.VALUES_CPU[s, obj_idx] = bool(new_value) + return True + + # The activation gate is fully derived (recomputed every step from ToggledOn / Open / OnFire), + # so loading must be a no-op — matching main, where HeatSourceOrSink is not stateful. The + # inherited TensorizedAbsoluteState._load_state would restore a stale gate value that could + # make a source active (heating) for the first step after a scene load / reset. + def _load_state(self, state): + return + + def affects_obj(self, obj): + """ + Whether this heat source / sink is currently heating @obj. + + Args: + obj (StatefulObject): Object whose temperature delta is being queried. + + Returns: + bool + """ + # Local import to avoid circular dependency at module load time + from omnigibson.object_states.temperature import Temperature + + return Temperature.is_influenced_by(self.obj, obj) + + # Nothing needs to be done to save/load HeatSource diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/heated.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/heated.py new file mode 100644 index 0000000000000000000000000000000000000000..07f6861c02cc710625e5a36c1df552f7a0b4971f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/heated.py @@ -0,0 +1,44 @@ +import torch as th + +from omnigibson.macros import create_module_macros +from omnigibson.object_states.object_state_base import AbsoluteObjectState, BooleanStateMixin +from omnigibson.object_states.temperature import Temperature + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.DEFAULT_HEAT_TEMPERATURE = 40 + +# When an object is set as heated, we will sample it between +# the heat temperature and these offsets. +m.HEATED_SAMPLING_RANGE_MIN = 10.0 +m.HEATED_SAMPLING_RANGE_MAX = 20.0 + + +class Heated(AbsoluteObjectState, BooleanStateMixin): + def __init__(self, obj, heat_temperature=None): + super(Heated, self).__init__(obj) + self.heat_temperature = heat_temperature if heat_temperature is not None else m.DEFAULT_HEAT_TEMPERATURE + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(Temperature) + return deps + + def _set_value(self, new_value): + if new_value: + temp_lo, temp_hi = ( + self.heat_temperature + m.HEATED_SAMPLING_RANGE_MIN, + self.heat_temperature + m.HEATED_SAMPLING_RANGE_MAX, + ) + temperature = (th.rand(1) * (temp_hi - temp_lo) + temp_lo).item() + return self.obj.states[Temperature].set_value(temperature) + else: + # We'll set the temperature just one degree below heating. + return self.obj.states[Temperature].set_value(self.heat_temperature - 1.0) + + def _get_value(self): + return self.obj.states[Temperature].get_value() >= self.heat_temperature + + # Nothing needs to be done to save/load Heated since it will happen due to temperature caching. diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/inside.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/inside.py new file mode 100644 index 0000000000000000000000000000000000000000..40801b3daab720eaf2da4e877da44ce6cb9b58fa --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/inside.py @@ -0,0 +1,723 @@ +import math + +import torch as th +import warp as wp + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.macros import macros, create_module_macros +from omnigibson.object_states.aabb import AABB +from omnigibson.object_states.contains import m as contains_m +from omnigibson.object_states.kinematics_mixin import KinematicsMixin +from omnigibson.object_states.object_state_base import BooleanStateMixin +from omnigibson.object_states.tensorized_relative_state import TensorizedRelativeState +from omnigibson.utils.constants import PrimType +from omnigibson.utils.object_state_utils import ( + m as os_m, + get_reachability_sampling_context, + is_pose_reachable_for_predicate, +) +from omnigibson.utils.python_utils import classproperty +from omnigibson.utils.usd_utils import RigidBodyViewAPI, RigidContactAPI, rigid_inverse_mat44 +import omnigibson.utils.transform_utils as T + + +m = create_module_macros(module_path=__file__) + +m.CONTAINER_POSITION_CHANGE_THRESHOLD = 0.05 # 5cm +m.CONTAINER_ORIENTATION_CHANGE_THRESHOLD = th.deg2rad(th.tensor([10.0])).item() # 10 degrees +m.CONTAINER_JOINT_POSITION_DELTA_THRESHOLD_TRANSLATION = 1e-2 # 1cm +m.CONTAINER_JOINT_POSITION_DELTA_THRESHOLD_ROTATION = math.radians(1) # 1 degree + + +def _orient_face_normals_outward(points, face_centroids, face_normals): + """Return convex-mesh face normals oriented away from the mesh interior.""" + # The mean of the mesh vertices is a convex combination of those vertices, so for a + # full-dimensional convex container mesh it lies inside the hull. An outward normal + # therefore has a non-positive dot product with the vector from its face to this point. + mesh_interior = points.mean(dim=0) + points_toward_interior = mesh_interior.unsqueeze(0) - face_centroids + inward = (points_toward_interior * face_normals).sum(dim=-1) > 0 + return th.where(inward.unsqueeze(-1), -face_normals, face_normals) + + +# Tensorized Inside state. +# +# VALUES shape: (S, N, N) bool — VALUES[s, inner, container] is True iff +# 1. inner's AABB center lies inside container's AABB, AND +# 2. that point lies inside the convex hull of one of container's container-meta-link +# visual meshes. +# +# Inside is NOT symmetric (VALUES[s, a, b] != VALUES[s, b, a] in general). +# Diagonal and cross-scene cells are always False. +# +# Only USD Mesh-typed container visual meshes are supported. Primitive-typed visual meshes +# (Sphere/Cube/Cylinder/Cone) are skipped at initialize_view; container hulls are expected +# to be authored as a merged convex Mesh per asset_pipeline/guide/fillable.md. +# +# Volume check is a convex-hull halfspace test per visual mesh — point is inside iff +# `(p - face_centroid) · face_normal < 0` for every face. The halfspace tests are +# parallelized across (scene, inner, face) and reduced per (scene, inner, mesh) — see +# _inside_halfspace_test_kernel / _inside_mesh_reduce_kernel. +# +# All meshes across all containers are flattened into a single global table (length M), +# all faces into a single global table (length F_total). Per step we recompute each mesh's +# world to local-w-scale inverse from its parent link's current world pose; everything else +# is precomputed once in initialize_view. + + +@wp.kernel +def _inside_inv_world_kernel( + pose_matrices: wp.array(dtype=wp.mat44), # (L,) link world transforms (rigid) + mesh_parent_link: wp.array(dtype=wp.int32), # (M,) flat link idx + mesh_inv_local_w_scale: wp.array(dtype=wp.mat44), # (M,) static inv of mesh→link-local-w-scale + inv_world: wp.array(dtype=wp.mat44), # (M,) output: world → mesh-local-unscaled +): + """Per mesh: compose static inv-local with the link's current rigid world inverse.""" + m = wp.tid() + parent = mesh_parent_link[m] + if parent < 0: + return + inv_world[m] = wp.mul(mesh_inv_local_w_scale[m], rigid_inverse_mat44(pose_matrices[parent])) + + +@wp.kernel +def _inside_aabb_prefilter_kernel( + aabb_values: wp.array3d(dtype=wp.float32), # (S, N_aabb, 6) + aabb_idx: wp.array(dtype=wp.int32), # (N,) Inside-N → AABB-N, -1 if missing + prefilter: wp.array3d(dtype=wp.int32), # (S, N, N) +): + """Check whether this obj's AABB center inside container's AABB.""" + s, i, j = wp.tid() + if i == j: + prefilter[s, i, j] = wp.int32(0) + return + a_i = aabb_idx[i] + a_j = aabb_idx[j] + if a_i < 0 or a_j < 0: + prefilter[s, i, j] = wp.int32(0) + return + + cx = (aabb_values[s, a_i, 0] + aabb_values[s, a_i, 3]) * 0.5 + cy = (aabb_values[s, a_i, 1] + aabb_values[s, a_i, 4]) * 0.5 + cz = (aabb_values[s, a_i, 2] + aabb_values[s, a_i, 5]) * 0.5 + + lo_x = aabb_values[s, a_j, 0] + lo_y = aabb_values[s, a_j, 1] + lo_z = aabb_values[s, a_j, 2] + hi_x = aabb_values[s, a_j, 3] + hi_y = aabb_values[s, a_j, 4] + hi_z = aabb_values[s, a_j, 5] + + inside = cx >= lo_x and cx <= hi_x and cy >= lo_y and cy <= hi_y and cz >= lo_z and cz <= hi_z + if inside: + prefilter[s, i, j] = wp.int32(1) + else: + prefilter[s, i, j] = wp.int32(0) + + +@wp.kernel +def _inside_halfspace_test_kernel( + aabb_values: wp.array3d(dtype=wp.float32), # (S, N_aabb, 6) + aabb_idx: wp.array(dtype=wp.int32), # (N,) Inside-N → AABB-N + prefilter: wp.array3d(dtype=wp.int32), # (S, N, N) + inv_world: wp.array(dtype=wp.mat44), # (M,) per-mesh world → mesh-local-unscaled + face_to_mesh: wp.array(dtype=wp.int32), # (F_total,) face → owning mesh index + mesh_container_idx: wp.array(dtype=wp.int32), # (M,) Inside-N container idx, -1 if untracked + mesh_scene_idx: wp.array(dtype=wp.int32), # (M,) + face_centroid: wp.array(dtype=wp.vec3), # (F_total,) + face_normal: wp.array(dtype=wp.vec3), # (F_total,) + outside_flag: wp.array3d(dtype=wp.int32), # (S, N, M) atomic_max target — 1 means "saw a failing face" +): + """ + Per (scene, inner_i, face f): + test inner_i's AABB center against face f's halfspace; on fail (`>= 0`), + atomic_max outside_flag[s, i, mesh(f)] to 1. The atomic is idempotent so contention + is bounded — at most one transition per mesh per (s, i). + """ + s, i, f = wp.tid() + + m = face_to_mesh[f] + container_j = mesh_container_idx[m] + if container_j < 0: + return + if mesh_scene_idx[m] != s: + return + if i == container_j: + return + + a_i = aabb_idx[i] + if a_i < 0: + return + + if prefilter[s, i, container_j] == wp.int32(0): + return + + # Inner_i's AABB center, world frame. + cx = (aabb_values[s, a_i, 0] + aabb_values[s, a_i, 3]) * 0.5 + cy = (aabb_values[s, a_i, 1] + aabb_values[s, a_i, 4]) * 0.5 + cz = (aabb_values[s, a_i, 2] + aabb_values[s, a_i, 5]) * 0.5 + p_world = wp.vec3(cx, cy, cz) + + # change from world to mesh-local-unscaled + p_local = wp.transform_point(inv_world[m], p_world) + + if wp.dot(p_local - face_centroid[f], face_normal[f]) >= wp.float32(0.0): + wp.atomic_max(outside_flag, s, i, m, wp.int32(1)) + + +@wp.kernel +def _inside_mesh_reduce_kernel( + aabb_idx: wp.array(dtype=wp.int32), # (N,) Inside-N → AABB-N + prefilter: wp.array3d(dtype=wp.int32), # (S, N, N) + mesh_container_idx: wp.array(dtype=wp.int32), # (M,) + mesh_scene_idx: wp.array(dtype=wp.int32), # (M,) + outside_flag: wp.array3d(dtype=wp.int32), # (S, N, M) 1 iff some face said outside + pair_scratch: wp.array3d(dtype=wp.int32), # (S, N, N) atomic_max target +): + """ + Per (scene, inner_i, mesh m): + if all the halfspace tests passed (outside_flag == 0) and the same gates as the test + kernel hold, atomic_max pair_scratch[s, i, container(m)] to 1. + """ + s, i, m = wp.tid() + + container_j = mesh_container_idx[m] + if container_j < 0: + return + if mesh_scene_idx[m] != s: + return + if i == container_j: + return + + a_i = aabb_idx[i] + if a_i < 0: + return + + if prefilter[s, i, container_j] == wp.int32(0): + return + + if outside_flag[s, i, m] == wp.int32(0): + wp.atomic_max(pair_scratch, s, i, container_j, wp.int32(1)) + + +@wp.kernel +def _inside_finalize_kernel( + pair: wp.array3d(dtype=wp.int32), # (S, N, N) + values: wp.array3d(dtype=wp.uint8), # (S, N, N) uint8 view of bool VALUES +): + s, i, j = wp.tid() + if i == j: + values[s, i, j] = wp.uint8(0) + return + if pair[s, i, j] > wp.int32(0): + values[s, i, j] = wp.uint8(1) + else: + values[s, i, j] = wp.uint8(0) + + +class Inside(TensorizedRelativeState, KinematicsMixin, BooleanStateMixin): + # Used by _inside_aabb_prefilter_kernel and the halfspace_test/mesh_reduce kernels to read + # inner AABB centers and container AABBs from AABB.VALUES_WP. + _aabb_idx = None # wp.array (N,) int32 — Inside-N → AABB-N + + # All container-meta-link visual meshes across every scene are flattened into + # one global table of length M. M = total number of containers scross scenes + + # Which *container* object that owns this mesh, or -1 if + # the parent object isn't Inside-tracked. + _mesh_container_idx = None # wp.array (M,) int32 + + # Scene index of the container that owns this mesh. + _mesh_scene_idx = None # wp.array (M,) int32 + + # RigidBodyViewAPI flat index of the parent link. + _mesh_parent_link = None # wp.array (M,) int32 + + # Static matrix transforming a point in parent-link-frame into mesh-local-unscaled frame. + # inv_world_kernel composes this with rigid_inverse_mat44(parent_link_world) each step. + _mesh_inv_local_w_scale = None # wp.array (M,) mat44 + + # Reverse lookup: which mesh does each face belong to. + _face_to_mesh = None # wp.array (F_total,) int32 + + # Flat per-face data for all container meshes, concatenated end-to-end. + _face_centroid = None # wp.array (F_total,) vec3 + _face_normal = None # wp.array (F_total,) vec3 + + # Scratches used by kernels. + + # Per-mesh inverse "world → mesh-local-unscaled" transform. + # Written by inv_world_kernel each step; consumed by halfspace_test_kernel. + _inv_world = None # wp.array (M,) mat44 + + # Scratch written by aabb_prefilter_kernel (1 if inner_i's AABB center + # lies inside container_j's AABB, else 0). + _prefilter = None # wp.array3d (S, N, N) int32 + + # Per-mesh "saw at least one failing halfspace" flag, atomic_max target. + _outside_flag = None # wp.array3d (S, N, M) int32 + + # atomic_max target for "any mesh of container_j contains inner_i's center". + _pair_scratch = None # wp.array3d (S, N, N) int32 + + @classproperty + def value_shape(cls): + return () + + @classproperty + def value_type(cls): + return th.bool + + @classproperty + def value_name(cls): + return "inside" + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(AABB) + return deps + + @classmethod + def global_initialize(cls): + super().global_initialize() + cls._aabb_idx = None + cls._mesh_container_idx = None + cls._mesh_scene_idx = None + cls._mesh_parent_link = None + cls._mesh_inv_local_w_scale = None + cls._face_to_mesh = None + cls._face_centroid = None + cls._face_normal = None + cls._inv_world = None + cls._prefilter = None + cls._outside_flag = None + cls._pair_scratch = None + + @classmethod + def initialize_view(cls): + super().initialize_view() + S = len(cls.IDX_OBJS) + N = len(cls.OBJ_IDXS) + + if S == 0 or N == 0: + cls._aabb_idx = None + cls._inv_world = None + cls._prefilter = None + cls._pair_scratch = None + return + + # Build Inside-N → AABB-N + aabb_idx_cpu = th.full((N,), -1, dtype=th.int32) + aabb_map = AABB.OBJ_IDXS or {} + for rel_path, idx in cls.OBJ_IDXS.items(): + aabb_idx_cpu[idx] = aabb_map.get(rel_path, -1) + cls._aabb_idx = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + aabb_idx_cpu, "int32", device="cuda" + ) + + # Walk every Inside-tracked object's container meta-links and collect each visual mesh. + # Only USD Mesh-typed visual meshes are supported; primitive types are skipped. + mesh_records = [] # list of dicts; rolled into the flat tables below. + face_centroids_list = [] # CPU torch tensors, concatenated at the end + face_normals_list = [] + face_to_mesh_list = [] # CPU ints; for each face f appends the index of its owning mesh in mesh_records. + + for scene_idx, scene_row in enumerate(cls.IDX_OBJS): + for container_idx, container_obj in enumerate(scene_row): + if container_obj is None: + continue + if container_obj.prim_type == PrimType.CLOTH: + continue + for link in container_obj.links.values(): + if not link.is_meta_link: + continue + if link.meta_link_type not in contains_m.CONTAINER_META_LINK_TYPES: + continue + parent_flat = RigidBodyViewAPI.get_flat_idx(link.prim_path) + if parent_flat is None: + continue + # Link's rigid world transform at init time, used to derive the static + # mesh→link-local-w-scale piece. + link_world_init = T.pose2mat(link.get_position_orientation()) + link_world_inv_init = th.linalg.inv(link_world_init) + + for mesh in link.visual_meshes.values(): + if mesh._mesh_type != "Mesh": + continue + + # Build one outward-facing halfspace per convex hull facet, matching + # the hull that GeomPrim.check_local_points_in_volume() tests against. + hull_faces = th.as_tensor(mesh.delaunay_triangulation.convex_hull, dtype=th.long) + hull_vertices = mesh.points[hull_faces] + centroids = hull_vertices.mean(dim=1) # (F_hull, 3) local-unscaled + edge1 = hull_vertices[:, 1] - hull_vertices[:, 0] + edge2 = hull_vertices[:, 2] - hull_vertices[:, 0] + normals = th.cross(edge1, edge2, dim=1) + normal_lengths = th.linalg.vector_norm(normals, dim=1, keepdim=True) + normals = normals / th.clamp(normal_lengths, min=1e-8) + normals = _orient_face_normals_outward( + points=mesh.points, + face_centroids=centroids, + face_normals=normals, + ) # (F_hull, 3) local-unscaled + face_count = centroids.shape[0] + if face_count == 0: + continue + + mesh_scaled_world_init = mesh.scaled_transform + local_w_scale = link_world_inv_init @ mesh_scaled_world_init + inv_local_w_scale = th.linalg.inv(local_w_scale) + + mesh_idx = len(mesh_records) + face_centroids_list.append(centroids.to(th.float32)) + face_normals_list.append(normals.to(th.float32)) + face_to_mesh_list.extend([mesh_idx] * face_count) + + mesh_records.append( + { + "container": container_idx, + "scene": scene_idx, + "parent_link": parent_flat, + "inv_local_w_scale": inv_local_w_scale.to(th.float32), + } + ) + + M = len(mesh_records) + if M == 0: + cls._mesh_container_idx = None + cls._mesh_scene_idx = None + cls._mesh_parent_link = None + cls._mesh_inv_local_w_scale = None + cls._face_to_mesh = None + cls._face_centroid = None + cls._face_normal = None + cls._inv_world = None + cls._outside_flag = None + else: + cls._mesh_container_idx = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + [r["container"] for r in mesh_records], "int32", device="cuda" + ) + cls._mesh_scene_idx = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + [r["scene"] for r in mesh_records], "int32", device="cuda" + ) + cls._mesh_parent_link = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + [r["parent_link"] for r in mesh_records], "int32", device="cuda" + ) + # mat44 / vec3 have no scalar-only helper — wp.array reinterprets the CPU torch + # buffer's (M, 4, 4) float32 as (M,) mat44 and (F, 3) float32 as (F,) vec3. + inv_local_stack_cpu = th.stack([r["inv_local_w_scale"] for r in mesh_records]) # (M, 4, 4) CPU + cls._mesh_inv_local_w_scale = wp.array(inv_local_stack_cpu, dtype=wp.mat44, device="cuda") + + # Flat face arrays. M > 0 here and every retained mesh contributed at least one + # face (zero-face meshes are filtered above), so F_total > 0. + face_centroids_flat_cpu = th.cat(face_centroids_list, dim=0).contiguous() # (F, 3) CPU + face_normals_flat_cpu = th.cat(face_normals_list, dim=0).contiguous() # (F, 3) CPU + cls._face_centroid = wp.array(face_centroids_flat_cpu, dtype=wp.vec3, device="cuda") + cls._face_normal = wp.array(face_normals_flat_cpu, dtype=wp.vec3, device="cuda") + + cls._face_to_mesh = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + face_to_mesh_list, "int32", device="cuda" + ) + + # Per-step scratch — allocate directly as wp.array. + cls._inv_world = wp.zeros(M, dtype=wp.mat44, device="cuda") + cls._outside_flag = wp.zeros((S, N, M), dtype=wp.int32, device="cuda") + + cls._prefilter = wp.zeros((S, N, N), dtype=wp.int32, device="cuda") + cls._pair_scratch = wp.zeros((S, N, N), dtype=wp.int32, device="cuda") + + @classmethod + def _update_values(cls, values): + if ( + cls.VALUES_WP is None + or cls._aabb_idx is None + or cls._prefilter is None + or cls._pair_scratch is None + or AABB.VALUES_WP is None + or RigidBodyViewAPI.POSE_MATRICES is None + ): + return + S, N, _ = values.shape + if S == 0 or N == 0: + return + + cls._pair_scratch.zero_() + + wp.launch( + kernel=_inside_aabb_prefilter_kernel, + dim=(S, N, N), + inputs=[AABB.VALUES_WP, cls._aabb_idx, cls._prefilter], + device="cuda", + ) + + if cls._mesh_container_idx is not None: + M = cls._mesh_parent_link.shape[0] + F_total = cls._face_centroid.shape[0] + + # refresh per-mesh world→local inverse from current link poses. + wp.launch( + kernel=_inside_inv_world_kernel, + dim=M, + inputs=[ + RigidBodyViewAPI.POSE_MATRICES, + cls._mesh_parent_link, + cls._mesh_inv_local_w_scale, + cls._inv_world, + ], + device="cuda", + ) + + # Each face independently votes "outside" via atomic_max into outside_flag. + # Mesh "contains" iff no face voted outside → reduce kernel writes pair_scratch. + cls._outside_flag.zero_() + wp.launch( + kernel=_inside_halfspace_test_kernel, + dim=(S, N, F_total), + inputs=[ + AABB.VALUES_WP, + cls._aabb_idx, + cls._prefilter, + cls._inv_world, + cls._face_to_mesh, + cls._mesh_container_idx, + cls._mesh_scene_idx, + cls._face_centroid, + cls._face_normal, + cls._outside_flag, + ], + device="cuda", + ) + wp.launch( + kernel=_inside_mesh_reduce_kernel, + dim=(S, N, M), + inputs=[ + cls._aabb_idx, + cls._prefilter, + cls._mesh_container_idx, + cls._mesh_scene_idx, + cls._outside_flag, + cls._pair_scratch, + ], + device="cuda", + ) + + # int32 pair to uint8 VALUES, zero diagonal + wp.launch( + kernel=_inside_finalize_kernel, + dim=(S, N, N), + inputs=[cls._pair_scratch, cls.VALUES_WP], + device="cuda", + ) + + def _get_value(self, other): + if other.prim_type == PrimType.CLOTH: + raise ValueError("Cannot detect if an object is inside a cloth object.") + + return super()._get_value(other) + + def _set_value(self, other, new_value, reset_before_sampling=False, use_trav_map=False): + """ + Set the Inside state for this object with respect to another object (container). + + This samples a random position inside the container's fillable volume, places the object, + lets it settle via physics, and verifies it's still inside. + + The sampling strategy uses a two-phase approach: + 1. First half of attempts: Sample from inset AABB (container bounds minus object extent). + This ensures the sampled position is at the object's centroid, not near the edges, + which makes it more likely to fit inside. + 2. Second half of attempts: Sample from full container AABB. This is a fallback for + cases where the object is too large to fit entirely within the inset bounds. + + Each candidate pose passes through several rejection-sampling stages: + 1. The sampled point must lie inside the container's fillable volume. + 2. After placement and a single physics step, the object must not already be + intersecting anything (catches interpenetration with container walls). + 3. The object must come into contact with something after placement and half a second of + physics steps. + 4. After settling, the container's root pose must not have moved + beyond CONTAINER_POSITION_CHANGE_THRESHOLD / CONTAINER_ORIENTATION_CHANGE_THRESHOLD. + 5. The container's articulated joints must not have moved beyond the per-DOF-type + CONTAINER_JOINT_POSITION_DELTA_THRESHOLD_{TRANSLATION,ROTATION} thresholds + (catches cases where the placed object swings a door/lid or pushes a drawer). + 6. The object must still register as Inside the container after settling, and + reachable via the traversability map if use_trav_map is enabled. + + Args: + other: The container object to place this object inside. + new_value: True to set Inside state (only True is supported). + reset_before_sampling: If True, reset this object before sampling. + use_trav_map: Whether to use traversability-based reachability checks. + Returns: + True if successfully placed inside, False otherwise. + """ + if not new_value: + raise NotImplementedError("Inside does not support set_value(False)") + + if other.prim_type == PrimType.CLOTH: + raise ValueError("Cannot set an object inside a cloth object.") + + # Save the initial position and orientation of the container + container_pos_initial, container_orn_initial = other.get_position_orientation() + container_joint_positions_initial = other.get_joint_positions() if other.n_joints > 0 else None + + # Find the container's fillable meta link (fillable or openfillable) + container_link = None + for link in other.links.values(): + if link.is_meta_link and link.meta_link_type in macros.object_states.contains.CONTAINER_META_LINK_TYPES: + container_link = link + break + + assert container_link is not None, f"Container object {other.name} must have a fillable meta link" + + # Save simulator state for restoration on failed attempts + state = og.sim.dump_state(serialized=False) + + if reset_before_sampling: + self.obj.reset() + + # Get container's fillable volume bounds in world frame + aabb_low, aabb_high = container_link.visual_aabb + # Get the object extent to compute inset bounds + obj_extent = self.obj.aabb_extent + + # Inset the container AABB by half the object extent in each dimension. + # This ensures the sampled position (used as object centroid) won't place + # any part of the object outside the container bounds. + inset_aabb_low = aabb_low + obj_extent / 2.0 + inset_aabb_high = aabb_high - obj_extent / 2.0 + + # Calculate the total attempt count. Here we don't have a sense of high/low-level attempts, + # so to make the same numbr of attempts as the original implementation, we just multiply + # the two sampling parameters. + total_attempts = os_m.DEFAULT_HIGH_LEVEL_SAMPLING_ATTEMPTS * os_m.DEFAULT_LOW_LEVEL_SAMPLING_ATTEMPTS + + if use_trav_map: + reachability_context = get_reachability_sampling_context( + objB=other, + predicate="inside", + use_trav_map=use_trav_map, + warn_on_scene_mismatch=False, + ) + use_trav_map = reachability_context is not None + + for attempt_idx in range(total_attempts): + # Sample orientation if the object supports random orientations, otherwise use default + orientation = ( + self.obj.sample_orientation() + if (hasattr(self.obj, "orientations") and self.obj.orientations is not None) + else th.tensor([0, 0, 0, 1.0]) + ) + + # Also add a random world Z-axis offset to the orientation + random_z_orientation = T.axisangle2quat(th.as_tensor([0, 0, th.rand(1) * 2 * th.pi])) + orientation = T.quat_multiply(orientation, random_z_orientation) + + # First half: use inset bounds (smarter sampling) + # Second half: use full bounds (fallback for large objects) + # Also fallback if inset bounds are invalid (object too large for container) + if attempt_idx < total_attempts // 2 and th.all(inset_aabb_low < inset_aabb_high): + pos = inset_aabb_low + th.rand(3) * (inset_aabb_high - inset_aabb_low) + else: + pos = aabb_low + th.rand(3) * (aabb_high - aabb_low) + + # Rejection sampling #1: Verify the sampled point is actually inside the container volume + if not container_link.check_points_in_volume(pos.unsqueeze(0)).item(): + og.sim.load_state(state, serialized=False) + continue + + # Add small z-offset to avoid spawning inside the container floor + pos[2] += 0.01 + self.obj.set_position_orientation(position=pos, orientation=orientation) + self.obj.keep_still() + # Step physics once so the contact buffer gets populated for the newly-placed object + og.sim.step_physics() + + # Rejection sampling #2: Reject if the object is already intersecting anything + # immediately after placement (e.g. interpenetration with a container wall). + if RigidContactAPI.is_in_contact( + scene_idx=self.obj.scene.idx, + query_set=[self.obj], + with_set=None, + ignore_set=None, + current_only=True, + ): + og.sim.load_state(state, serialized=False) + continue + + # Rejection sampling #3: step until contact is made or max steps reached + # (0.5 seconds of sim time) to let the object settle onto a resting surface. + # If it can't get into contact by then, we reject the placement. + n_steps_max = int(0.5 / og.sim.get_physics_dt()) + for _ in range(n_steps_max): + og.sim.step_physics() + if RigidContactAPI.is_in_contact( + scene_idx=self.obj.scene.idx, + query_set=[self.obj], + with_set=None, + ignore_set=None, + current_only=True, + ): + break + else: + og.sim.load_state(state, serialized=False) + continue + self.obj.keep_still() + other.keep_still() + + # Step a few more times to let velocity stabilize + for _ in range(5): + og.sim.step_physics() + settle_step_idx = 0 + while th.norm(self.obj.get_linear_velocity()) > 1e-3 and settle_step_idx < n_steps_max: + og.sim.step_physics() + settle_step_idx += 1 + + # Rejection sampling #4: Reject if the container's root pose drifted past the + # position/orientation thresholds (i.e. the placed object pushed the container). + container_pos, container_orn = other.get_position_orientation() + position_difference = th.norm(container_pos - container_pos_initial) + orientation_difference = T.get_orientation_diff_in_radian(container_orn, container_orn_initial) + if ( + position_difference > m.CONTAINER_POSITION_CHANGE_THRESHOLD + or orientation_difference > m.CONTAINER_ORIENTATION_CHANGE_THRESHOLD + ): + og.sim.load_state(state, serialized=False) + continue + + # Rejection sampling #5: Reject if any of the container's articulated joints moved + # past the per-DOF-type delta thresholds (e.g. placed object swung a lid or pushed + # a drawer). Thresholds are applied separately for rotational and translational DOFs. + if container_joint_positions_initial is not None: + container_joint_positions_final = other.get_joint_positions() + joint_thresholds = th.where( + other.get_joint_dof_types(), + m.CONTAINER_JOINT_POSITION_DELTA_THRESHOLD_ROTATION, + m.CONTAINER_JOINT_POSITION_DELTA_THRESHOLD_TRANSLATION, + ) + container_joint_positions_delta = th.abs( + container_joint_positions_final - container_joint_positions_initial + ) + if th.any(container_joint_positions_delta > joint_thresholds): + og.sim.load_state(state, serialized=False) + continue + + # Rejection sampling #6: Verify object is still inside after settling and within reach if using trav map. + if self.get_value(other): + if use_trav_map: + settled_pos, _ = self.obj.get_position_orientation() + if not is_pose_reachable_for_predicate( + pos=settled_pos, + objB=other, + predicate="inside", + reachability_context=reachability_context, + ): + og.sim.load_state(state, serialized=False) + continue + return True + + # Reset the simulator state to the initial state + og.sim.load_state(state, serialized=False) + return False diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/joint_break_subscribed_state_mixin.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/joint_break_subscribed_state_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..0fb3e37a9067fa294b65f99ef60c935e099ca9bc --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/joint_break_subscribed_state_mixin.py @@ -0,0 +1,24 @@ +from abc import abstractmethod + +from omnigibson.object_states.object_state_base import BaseObjectState +from omnigibson.utils.python_utils import classproperty + + +class JointBreakSubscribedStateMixin(BaseObjectState): + """ + Handles JOINT_BREAK event. + The subclass should implement its own on_joint_break method + """ + + @abstractmethod + def on_joint_break(self, joint_prim_path): + raise NotImplementedError( + "Subclasses of JointBreakSubscribedStateMixin should implement the on_joint_break method." + ) + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("JointBreakSubscribedStateMixin") + return classes diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/joint_state.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/joint_state.py new file mode 100644 index 0000000000000000000000000000000000000000..dedc62d07eab95ed80acd243784659b4ba3073c8 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/joint_state.py @@ -0,0 +1,22 @@ +import torch as th + +from omnigibson.macros import create_module_macros +from omnigibson.object_states.object_state_base import AbsoluteObjectState + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.POSITIONAL_VALIDATION_EPSILON = 1e-10 + + +class Joint(AbsoluteObjectState): + def _get_value(self): + return self.obj.get_joint_positions() if self.obj.n_joints > 0 else th.tensor([]) + + def _has_changed(self, get_value_args, value, info): + # Only changed if the squared distance between old and current q has changed above some threshold + old_q = value + # Get current joint values + cur_q = self.get_value() + dist_squared = th.sum(th.square(cur_q - old_q)) + return dist_squared > m.POSITIONAL_VALIDATION_EPSILON diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/kinematics_mixin.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/kinematics_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..73c92d8dd78d1b5aab12492af27a4d4f85774b3d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/kinematics_mixin.py @@ -0,0 +1,59 @@ +from omnigibson.object_states.aabb import AABB +from omnigibson.object_states.joint_state import Joint +from omnigibson.object_states.object_state_base import BaseObjectState +from omnigibson.object_states.pose import Pose +from omnigibson.utils.python_utils import classproperty + + +class KinematicsMixin(BaseObjectState): + """ + This class is a subclass of BaseObjectState that adds dependencies + on the default kinematics states. + """ + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.update({Pose, Joint, AABB}) + return deps + + def cache_info(self, get_value_args): + # Import here to avoid circular imports + from omnigibson.objects.usd_object import USDObject + + # Run super first + info = super().cache_info(get_value_args=get_value_args) + + # Store this object as well as any other objects from @get_value_args + info[self.obj] = {"q": self.obj.states[Joint].get_value(), "p": self.obj.states[Pose].get_value()} + for arg in get_value_args: + if isinstance(arg, USDObject): + info[arg] = {"q": arg.states[Joint].get_value(), "p": arg.states[Pose].get_value()} + + return info + + def _cache_is_valid(self, get_value_args): + # Import here to avoid circular imports + from omnigibson.objects.usd_object import USDObject + + # Cache is valid if and only if all of our cached objects have not changed + t = self._cache[get_value_args]["t"] + for obj, info in self._cache[get_value_args]["info"].items(): + # If the object is asleep, assume this object hasn't changed, so continue + if obj.is_asleep: + continue + if isinstance(obj, USDObject): + # If pose has changed, return False + if obj.states[Pose].has_changed(get_value_args=(), value=info["p"], info={}, t=t): + return False + # If obj's joints have changed, return False + if obj.states[Joint].has_changed(get_value_args=(), value=info["q"], info={}, t=t): + return False + return True + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("KinematicsMixin") + return classes diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/link_based_state_mixin.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/link_based_state_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..31054fc4d9620ffa2a5647b664823e330af7a95f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/link_based_state_mixin.py @@ -0,0 +1,137 @@ +import torch as th + +from omnigibson.object_states.object_state_base import BaseObjectState +from omnigibson.prims.cloth_prim import ClothPrim +from omnigibson.utils.python_utils import classproperty +from omnigibson.utils.ui_utils import create_module_logger + +# Create module logger +log = create_module_logger(module_name=__name__) + + +class LinkBasedStateMixin(BaseObjectState): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + self._links = dict() + + @classmethod + def is_compatible(cls, obj, **kwargs): + # Run super first + compatible, reason = super().is_compatible(obj, **kwargs) + if not compatible: + return compatible, reason + + # Check whether this state requires meta link + if not cls.requires_meta_link(**kwargs): + return True, None + meta_link_types = cls.meta_link_types + for link in obj.links.values(): + if link.is_meta_link and link.meta_link_type in meta_link_types: + return True, None + + return ( + False, + f"LinkBasedStateMixin {cls.__name__} requires meta link with type {cls.meta_link_types} " + f"for obj {obj.name} but none was found! To get valid compatible object models, please use " + f"omnigibson.utils.asset_utils.get_all_object_category_models_with_abilities(...)", + ) + + @classmethod + def is_compatible_asset(cls, prim, **kwargs): + # Run super first + compatible, reason = super().is_compatible_asset(prim, **kwargs) + if not compatible: + return compatible, reason + + # Check whether this state requires meta link + if not cls.requires_meta_link(**kwargs): + return True, None + meta_link_types = cls.meta_link_types + for child in prim.GetChildren(): + if child.GetTypeName() == "Xform": + # With the new format, we can know for sure by checking the meta link type + if ( + child.HasAttribute("ig:metaLinkType") + and child.GetAttribute("ig:metaLinkType").Get() in meta_link_types + ): + return True, None + + # Until the next dataset release, also accept the old format + # TODO: Remove this block after the next dataset release + if any(meta_link_type in child.GetName() for meta_link_type in meta_link_types): + return True, None + return ( + False, + f"LinkBasedStateMixin {cls.__name__} requires meta link with prefix {cls.meta_link_types} " + f"for asset prim {prim.GetName()} but none was found! To get valid compatible object models, " + f"please use omnigibson.utils.asset_utils.get_all_object_category_models_with_abilities(...)", + ) + + @classproperty + def meta_link_types(cls): + """ + Returns: + str: Unique keyword that defines the meta link associated with this object state + """ + NotImplementedError() + + @classmethod + def requires_meta_link(cls, **kwargs): + """ + Returns: + bool: Whether an object state instantiated with constructor arguments **kwargs will require a meta link + or not + """ + # True by default + return True + + @property + def link(self): + """ + Returns: + None or RigidPrim: The link associated with this link-based state, if it exists + """ + assert self.links, f"LinkBasedStateMixin link not found for {self.obj.name}" + return next(iter(self.links.values())) + + @property + def links(self): + """ + Returns: + dict: mapping from link names to links that match the meta_link_type + """ + return self._links + + @property + def _default_link(self): + """ + Returns: + None or RigidPrim: If supported, the fallback link associated with this link-based state if + no valid meta link is found + """ + # No default link by default + return None + + def initialize_link_mixin(self): + assert not self._initialized + + # TODO: Extend logic to account for multiple instances of the same meta link? e.g: _0, _1, ... suffixes + for name, link in self.obj.links.items(): + is_appropriate_meta_link = link.is_meta_link and link.meta_link_type in self.meta_link_types + # TODO: Remove support for this default meta link logic after the next dataset release + is_default_link = self._default_link is not None and link.name == self._default_link.name + if is_appropriate_meta_link or is_default_link: + self._links[name] = link + # Make sure the scale is similar if the link is not a cloth prim + if not isinstance(link, ClothPrim): + assert th.allclose( + link.scale, self.obj.scale + ), f"the meta link {name} has a inconsistent scale with the object {self.obj.name}" + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("LinkBasedStateMixin") + return classes diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/max_temperature.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/max_temperature.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb6d3aba64fbb40f0b52b5c48f5415c63465d2d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/max_temperature.py @@ -0,0 +1,80 @@ +import warp as wp + +from omnigibson.object_states.temperature import Temperature +from omnigibson.object_states.tensorized_absolute_state import TensorizedAbsoluteState +from omnigibson.utils.python_utils import classproperty + + +@wp.kernel +def _max_temperature_kernel( + max_values: wp.array2d(dtype=wp.float32), # cls.VALUES (S, O_max) + temperature_values: wp.array2d(dtype=wp.float32), # Temperature.VALUES (S, O_temp) + temperature_idxs: wp.array(dtype=wp.int32), # (O_max,) — O_max → O_temp +): + """ + Element-wise max with index gather: + max_values[s, o] = max(max_values[s, o], temperature_values[s, temperature_idxs[o]]) + One thread per (scene, max_obj_idx). + """ + s, o = wp.tid() + t = temperature_values[s, temperature_idxs[o]] + if t > max_values[s, o]: + max_values[s, o] = t + + +class MaxTemperature(TensorizedAbsoluteState): + """ + This state remembers the highest temperature reached by an object. + """ + + # wp.array(int32) on CUDA: maps each MaxTemperature N index to the matching Temperature N index. + # Built directly as a wp.array (no torch view) — only the kernel reads it. + TEMPERATURE_IDXS_WP = None + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(Temperature) + return deps + + @classmethod + def initialize_view(cls): + # Snapshot which relative paths existed before the rebuild + prev_rel_paths = set(cls.OBJ_IDXS.keys()) if cls.OBJ_IDXS is not None else set() + + # Base class rebuilds OBJ_IDXS, IDX_OBJS, VALUES (with value carry-over for survivors) + super().initialize_view() + + # Rebuild TEMPERATURE_IDXS_WP: for each MaxTemp N index, find matching Temperature N index. + # MaxTemp objects are a subset of Temperature objects with the same relative paths. + # cls.OBJ_IDXS is insertion-ordered (Python 3.7+), so iterating yields keys in N=0,1,2,... order. + # Allocated directly as a Warp array as only the kernel reads it. + idxs = [Temperature.OBJ_IDXS[rel_path] for rel_path in cls.OBJ_IDXS] + cls.TEMPERATURE_IDXS_WP = wp.array(idxs, dtype=wp.int32, device="cuda") if idxs else None + + # Initialize new VALUE slots (not carried over) to -inf + for rel_path, obj_idx in cls.OBJ_IDXS.items(): + if rel_path not in prev_rel_paths: + for s_idx in range(len(cls.IDX_OBJS)): + if cls.IDX_OBJS[s_idx][obj_idx] is not None: + cls.VALUES[s_idx, obj_idx] = -float("inf") + cls.VALUES_CPU[s_idx, obj_idx] = -float("inf") + + @classmethod + def _update_values(cls, values): + # Value is max between stored values and current temperature values. + # Temperature.VALUES is (S, N_temp); cls.TEMPERATURE_IDXS maps MaxTemp N → Temperature N, + # so Temperature.VALUES[:, cls.TEMPERATURE_IDXS] has shape (S, N_max). + if cls.VALUES_WP is None or cls.TEMPERATURE_IDXS_WP is None or Temperature.VALUES_WP is None: + return + S, O = cls.VALUES.shape[:2] + wp.launch( + kernel=_max_temperature_kernel, + dim=(S, O), + inputs=[cls.VALUES_WP, Temperature.VALUES_WP, cls.TEMPERATURE_IDXS_WP], + device="cuda", + ) + + @classproperty + def value_name(cls): + return "max_temperature" diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/next_to.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/next_to.py new file mode 100644 index 0000000000000000000000000000000000000000..a20721dc1a485389771d7daef0fbb184f7d46afe --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/next_to.py @@ -0,0 +1,157 @@ +import torch as th +import warp as wp + +import omnigibson.lazy as lazy +from omnigibson.object_states.aabb import AABB +from omnigibson.object_states.adjacency import Adjacency, _HORIZONTAL_K_END, _HORIZONTAL_K_START +from omnigibson.object_states.kinematics_mixin import KinematicsMixin +from omnigibson.object_states.object_state_base import BooleanStateMixin +from omnigibson.object_states.tensorized_relative_state import TensorizedRelativeState +from omnigibson.utils.python_utils import classproperty + + +# NextTo(self, other) is true when AABBs are close enough AND other lies on any of self's +# horizontal Adjacency axes (or, symmetrically, self lies on any of other's). +# Distance / size threshold ratio: NextTo iff (axis-aligned gap norm) ≤ (sum of dims of both AABBs) / 18. +# That equals avg_aabb_length / 6 where avg_aabb_length = mean over 3 dims of (dim_a + dim_b). +_DISTANCE_RATIO = 1.0 / 6.0 + + +@wp.kernel +def _next_to_kernel( + aabb_values: wp.array3d(dtype=wp.float32), # (S, N_aabb, 6) — [lo_x, lo_y, lo_z, hi_x, hi_y, hi_z] + adjacency_values: wp.array4d(dtype=wp.uint8), # (S, N_adj, N_adj, K) + aabb_idx: wp.array(dtype=wp.int32), # (N,) NextTo idx → AABB idx, -1 if missing + adj_idx: wp.array(dtype=wp.int32), # (N,) NextTo idx → Adjacency idx, -1 if missing + values: wp.array3d(dtype=wp.uint8), # (S, N, N) — NextTo.VALUES uint8 view +): + s, i, j = wp.tid() + + if i == j: + values[s, i, j] = wp.uint8(0) + return + + a_i = aabb_idx[i] + a_j = aabb_idx[j] + adj_i = adj_idx[i] + adj_j = adj_idx[j] + if a_i < 0 or a_j < 0 or adj_i < 0 or adj_j < 0: + values[s, i, j] = wp.uint8(0) + return + + lo_i_x = aabb_values[s, a_i, 0] + lo_i_y = aabb_values[s, a_i, 1] + lo_i_z = aabb_values[s, a_i, 2] + hi_i_x = aabb_values[s, a_i, 3] + hi_i_y = aabb_values[s, a_i, 4] + hi_i_z = aabb_values[s, a_i, 5] + + lo_j_x = aabb_values[s, a_j, 0] + lo_j_y = aabb_values[s, a_j, 1] + lo_j_z = aabb_values[s, a_j, 2] + hi_j_x = aabb_values[s, a_j, 3] + hi_j_y = aabb_values[s, a_j, 4] + hi_j_z = aabb_values[s, a_j, 5] + + # Per-axis gap = max(0, max(lo_i, lo_j) - min(hi_i, hi_j)). Zero when AABBs overlap on this axis. + gap_x = wp.max(wp.float32(0.0), wp.max(lo_i_x, lo_j_x) - wp.min(hi_i_x, hi_j_x)) + gap_y = wp.max(wp.float32(0.0), wp.max(lo_i_y, lo_j_y) - wp.min(hi_i_y, hi_j_y)) + gap_z = wp.max(wp.float32(0.0), wp.max(lo_i_z, lo_j_z) - wp.min(hi_i_z, hi_j_z)) + distance = wp.sqrt(gap_x * gap_x + gap_y * gap_y + gap_z * gap_z) + + # avg_aabb_length = th.mean(objA_dims + objB_dims) = sum(dim_a + dim_b for d in xyz) / 3 + sum_dims = ( + (hi_i_x - lo_i_x) + + (hi_i_y - lo_i_y) + + (hi_i_z - lo_i_z) + + (hi_j_x - lo_j_x) + + (hi_j_y - lo_j_y) + + (hi_j_z - lo_j_z) + ) + threshold = (sum_dims / wp.float32(3.0)) * wp.float32(_DISTANCE_RATIO) + + if distance > threshold: + values[s, i, j] = wp.uint8(0) + return + + # OR over horizontal rays from both objects. Branchless — drops the legacy short-circuit + # between the self and other paths; total work is bounded by twice the horizontal K span. + hit = wp.uint8(0) + for k in range(_HORIZONTAL_K_START, _HORIZONTAL_K_END): + if adjacency_values[s, adj_i, adj_j, k] != wp.uint8(0): + hit = wp.uint8(1) + if adjacency_values[s, adj_j, adj_i, k] != wp.uint8(0): + hit = wp.uint8(1) + + values[s, i, j] = hit + + +class NextTo(TensorizedRelativeState, KinematicsMixin, BooleanStateMixin): + _aabb_idx = None # wp.array (N,) int32 — NextTo idx → AABB idx, -1 if missing + _adj_idx = None # wp.array (N,) int32 — NextTo idx → Adjacency idx, -1 if missing + + @classproperty + def value_shape(cls): + return () + + @classproperty + def value_type(cls): + return th.bool + + @classproperty + def value_name(cls): + return "next_to" + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.update({Adjacency, AABB}) + return deps + + @classmethod + def initialize_view(cls): + super().initialize_view() + N = len(cls.OBJ_IDXS) + if N == 0: + cls._aabb_idx = None + cls._adj_idx = None + return + + aabb_idx_cpu = th.full((N,), -1, dtype=th.int32) + adj_idx_cpu = th.full((N,), -1, dtype=th.int32) + aabb_map = AABB.OBJ_IDXS or {} + adj_map = Adjacency.OBJ_IDXS or {} + for rel_path, idx in cls.OBJ_IDXS.items(): + aabb_idx_cpu[idx] = aabb_map.get(rel_path, -1) + adj_idx_cpu[idx] = adj_map.get(rel_path, -1) + + cls._aabb_idx = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + aabb_idx_cpu, "int32", device="cuda" + ) + cls._adj_idx = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list(adj_idx_cpu, "int32", device="cuda") + + @classmethod + def _update_values(cls, values): + if ( + cls.VALUES_WP is None + or cls._aabb_idx is None + or cls._adj_idx is None + or AABB.VALUES_WP is None + or Adjacency.VALUES_WP is None + ): + return + S, N, _ = values.shape + if S == 0 or N == 0: + return + wp.launch( + kernel=_next_to_kernel, + dim=(S, N, N), + inputs=[ + AABB.VALUES_WP, + Adjacency.VALUES_WP, + cls._aabb_idx, + cls._adj_idx, + cls.VALUES_WP, + ], + device="cuda", + ) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/object_state_base.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/object_state_base.py new file mode 100644 index 0000000000000000000000000000000000000000..f508cd8febdd88aed3378b4b223bcd0324ed0c51 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/object_state_base.py @@ -0,0 +1,448 @@ +import inspect +from abc import ABC + +import omnigibson as og +from omnigibson.utils.python_utils import Recreatable, Registerable, Serializable, classproperty + +# Global dicts that will contain mappings +REGISTERED_OBJECT_STATES = dict() + + +class BaseObjectRequirement: + """ + Base ObjectRequirement class. This allows for sanity checking a given asset / BaseObject to check whether a set + of conditions are met or not. This can be useful for sanity checking dependencies for properties such as requested + abilities or object states. + """ + + @classmethod + def is_compatible(cls, obj, **kwargs): + """ + Determines whether this requirement is compatible with object @obj or not (i.e.: whether this requirement is + satisfied by @obj given other constructor arguments **kwargs). + + NOTE: Must be implemented by subclass. + + Args: + obj (StatefulObject): Object whose compatibility with this state should be checked + + Returns: + 2-tuple: + - bool: Whether the given object is compatible with this requirement or not + - None or str: If not compatible, the reason why it is not compatible. Otherwise, None + """ + raise NotImplementedError + + @classmethod + def is_compatible_asset(cls, prim, **kwargs): + """ + Determines whether this requirement is compatible with prim @prim or not (i.e.: whether this requirement is + satisfied by @prim given other constructor arguments **kwargs). + This is a useful check to evaluate an object's USD that hasn't been explicitly imported into OmniGibson yet. + + NOTE: Must be implemented by subclass + + Args: + prim (Usd.Prim): Object prim whose compatibility with this requirement should be checked + + Returns: + 2-tuple: + - bool: Whether the given prim is compatible with this requirement or not + - None or str: If not compatible, the reason why it is not compatible. Otherwise, None + """ + raise NotImplementedError + + +class BaseObjectState(BaseObjectRequirement, Serializable, Registerable, Recreatable, ABC): + """ + Base ObjectState class. Do NOT inherit from this class directly - use either AbsoluteObjectState or + RelativeObjectState. + """ + + @classmethod + def get_dependencies(cls): + """ + Get the dependency states for this state, e.g. states that need to be explicitly enabled on the current object + before the current state is usable. States listed here will be enabled for all objects that have this current + state, and all dependency states will be processed on *all* objects prior to this state being processed on + *any* object. + + Returns: + set of str: Set of strings corresponding to state keys. + """ + return set() + + @classmethod + def get_optional_dependencies(cls): + """ + Get states that should be processed prior to this state if they are already enabled. These states will not be + enabled because of this state's dependency on them, but if they are already enabled for another reason (e.g. + because of an ability or another state's dependency etc.), they will be processed on *all* objects prior to this + state being processed on *any* object. + + Returns: + set of str: Set of strings corresponding to state keys. + """ + return set() + + def __init__(self, obj): + super().__init__() + self.obj = obj + self._initialized = False + self._cache = None + self._changed = None + self._last_t_updated = -1 # Last timestep when this state was updated + + @classmethod + def is_compatible(cls, obj, **kwargs): + # Make sure all required dependencies are included in this object's state dictionary + for dep in cls.get_dependencies(): + if dep not in obj.states: + return False, f"Missing required dependency state {dep.__name__}" + # Make sure all required kwargs are specified + default_kwargs = inspect.signature(cls.__init__).parameters + for kwarg, val in default_kwargs.items(): + if val.default == inspect._empty and kwarg not in kwargs and kwarg not in {"obj", "self", "args", "kwargs"}: + return False, f"Missing required kwarg '{kwarg}'" + # Default is True if all kwargs are met + return True, None + + @classmethod + def is_compatible_asset(cls, prim, **kwargs): + # Make sure all required kwargs are specified + default_kwargs = inspect.signature(cls.__init__).parameters + for kwarg, val in default_kwargs.items(): + if val.default == inspect._empty and kwarg not in kwargs and kwarg not in {"obj", "self"}: + return False, f"Missing required kwarg '{kwarg}'" + # Default is True if all kwargs are met + return True, None + + @classmethod + def postprocess_ability_params(cls, params, scene): + """ + Post-processes ability parameters if needed. The default implementation is a simple passthrough. + """ + return params + + @property + def stateful(self): + """ + Returns: + bool: True if this object has a state that can be directly dumped / loaded via dump_state() and + load_state(), otherwise, returns False. Note that any sub object states that are NOT stateful do + not need to implement any of _dump_state(), _load_state(), _serialize(), or _deserialize()! + """ + # Default is whether state size > 0 + return self.state_size > 0 + + @property + def state_size(self): + return 0 + + @property + def cache(self): + """ + Returns: + dict: Dictionary mapping specific argument combinations from @self.get_value() to cached values and + information stored for that specific combination + """ + return self._cache + + def _initialize(self): + """ + This function will be called once; should be used for any object state-related objects have been loaded. + """ + pass + + def initialize(self): + """ + Initialize this object state + """ + assert not self._initialized, "State is already initialized." + + # Validate compatibility with the created object + init_args = {k: v for k, v in self.get_init_info()["args"].items() if k != "obj"} + assert self.is_compatible( + obj=self.obj, **init_args + ), f"ObjectState {self.__class__.__name__} is not compatible with object {self.obj.name}." + + # Clear cache + self.clear_cache() + + self._initialize() + + self._initialized = True + + def clear_cache(self): + """ + Clears the internal cache + """ + # Clear all entries + self._cache = dict() + self._changed = dict() + self._last_t_updated = -1 + + def update_cache(self, get_value_args): + """ + Updates the internal cached value based on the evaluation of @self._get_value(*get_value_args) + + Args: + get_value_args (tuple): Specific argument combinations (usually tuple of objects) passed into + @self.get_value / @self._get_value + """ + t = og.sim.current_time_step_index + # Compute value and update cache + val = self._get_value(*get_value_args) + self._cache[get_value_args] = dict(value=val, info=self.cache_info(get_value_args=get_value_args), t=t) + + def cache_info(self, get_value_args): + """ + Helper function to cache relevant information at the current timestep. + Stores it under @self._cache []["info"] + + Args: + get_value_args (tuple): Specific argument combinations (usually tuple of objects) passed into + @self.get_value whose caching information should be computed + + Returns: + dict: Any caching information to include at the current timestep when this state's value is computed + """ + # Default is an empty dictionary + return dict() + + def cache_is_valid(self, get_value_args): + """ + Helper function to check whether the current cached value is valid or not at the current timestep. + Default is False unless we're at the current timestep. + + Args: + get_value_args (tuple): Specific argument combinations (usually tuple of objects) passed into + @self.get_value whose cached values should be validated + + Returns: + bool: True if the cache is valid, else False + """ + # If t == the current timestep, then our cache is obviously valid otherwise we assume it isn't + return ( + True + if self._cache[get_value_args]["t"] == og.sim.current_time_step_index + else self._cache_is_valid(get_value_args=get_value_args) + ) + + def _cache_is_valid(self, get_value_args): + """ + Helper function to check whether the current cached value is valid or not at the current timestep. + Default is False. Subclasses should implement special logic otherwise. + + Args: + get_value_args (tuple): Specific argument combinations (usually tuple of objects) passed into + @self.get_value whose cached values should be validated + + Returns: + bool: True if the cache is valid, else False + """ + return False + + def has_changed(self, get_value_args, value, info, t): + """ + A helper function to query whether this object state has changed between the current timestep and an arbitrary + previous timestep @t with the corresponding cached value @value and cache information @info + + Note that this may require some non-trivial compute, so we leverage @t, in addition to @get_value_args, + as a unique key into an internal dictionary, such that specific @t will result in a computation conducted + exactly once. + This is done for performance reasons; so that multiple states relying on the same state dependency can all + query whether that state has changed between the same timesteps with only a single computation. + + Args: + get_value_args (tuple): Specific argument combinations (usually tuple of objects) passed into + @self.get_value + value (any): Cached value computed at timestep @t for this object state + info (dict): Information calculated at timestep @t when computing this state's value + t (int): Initial timestep to compare against. This should be an index of the steps taken, + i.e. a value queried from og.sim.current_time_step_index at some point in time. It is assumed @value + and @info were computed at this timestep + + Returns: + bool: Whether this object state has changed between @t and the current timestep index for the specific + @get_value_args + """ + # Check current sim step index; if it doesn't match the internal value, we need to clear the changed history + current_t = og.sim.current_time_step_index + if self._last_t_updated != current_t: + self._changed = dict() + self._last_t_updated = current_t + # Compile t, args, and kwargs deterministically + history_key = (t, *get_value_args) + # If t == the current timestep, then we obviously haven't changed so our value is False + if t == current_t: + val = False + # Otherwise, check if it already exists in our has changed dictionary; we return that value if so + elif history_key in self._changed: + val = self._changed[history_key] + # Otherwise, we calculate the value and store it in our changed dictionary + else: + val = self._has_changed(get_value_args=get_value_args, value=value, info=info) + self._changed[history_key] = val + + return val + + def _has_changed(self, get_value_args, value, info): + """ + Checks whether the previous value evaluated at time @t has changed with the current timestep. + By default, it returns True. + + Any custom checks should be overridden by subclass. + + Args: + get_value_args (tuple): Specific argument combinations (usually tuple of objects) passed into + @self.get_value + value (any): Cached value computed at timestep @t for this object state + info (dict): Information calculated at timestep @t when computing this state's value + + Returns: + bool: Whether the value has changed between @value and @info and the coresponding value and info computed + at the current timestep + """ + return True + + def get_value(self, *args, **kwargs): + """ + Get this state's value + + Returns: + any: Object state value given input @args and @kwargs + """ + assert self._initialized + + # Compile args and kwargs deterministically + key = (*args, *tuple(kwargs.values())) + # We need to see if we need to update our cache -- we do so if and only if one of the following conditions are met: + # (a) key is NOT in the cache + # (b) Our cache is not valid + if key not in self._cache or not self.cache_is_valid(get_value_args=key): + # Update the cache + self.update_cache(get_value_args=key) + + # Value is the cached value + val = self._cache[key]["value"] + + return val + + def _get_value(self, *args, **kwargs): + raise NotImplementedError(f"_get_value not implemented for {self.__class__.__name__} state.") + + def set_value(self, *args, **kwargs): + """ + Set this state's value + + Returns: + bool: True if setting the value was successful, otherwise False + """ + assert self._initialized + # Clear cache because the state may be changed + self.clear_cache() + # Set the value + val = self._set_value(*args, **kwargs) + # Add this object to the current state update set in its scene + self.obj.state_updated() + return val + + def _set_value(self, *args, **kwargs): + raise NotImplementedError(f"_set_value not implemented for {self.__class__.__name__} state.") + + def remove(self): + """ + Any cleanup functionality to deploy when @self.obj is removed from the simulator + """ + pass + + def dump_state(self, serialized=False): + assert self._initialized + assert self.stateful + return super().dump_state(serialized=serialized) + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("BaseObjectState") + return classes + + @classproperty + def _cls_registry(cls): + # Global registry + global REGISTERED_OBJECT_STATES + return REGISTERED_OBJECT_STATES + + +class AbsoluteObjectState(BaseObjectState): + """ + This class is used to track object states that are absolute, e.g. do not require a second object to compute + the value. + """ + + def _get_value(self): + raise NotImplementedError(f"_get_value not implemented for {self.__class__.__name__} state.") + + def _set_value(self, new_value): + raise NotImplementedError(f"_set_value not implemented for {self.__class__.__name__} state.") + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("AbsoluteObjectState") + return classes + + +class RelativeObjectState(BaseObjectState): + """ + This class is used to track object states that are relative, e.g. require two objects to compute a value. + Note that subclasses will typically compute values on-the-fly. + """ + + def _get_value(self, other): + raise NotImplementedError(f"_get_value not implemented for {self.__class__.__name__} state.") + + def _set_value(self, other, new_value): + raise NotImplementedError(f"_set_value not implemented for {self.__class__.__name__} state.") + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("RelativeObjectState") + return classes + + +class IntrinsicObjectState(BaseObjectState): + """ + This class is used to track object states that should NOT have getters / setters implemented, since the associated + ability / state is intrinsic to the state + """ + + def _get_value(self): + raise NotImplementedError( + f"_get_value not implemented for IntrinsicObjectState {self.__class__.__name__} state." + ) + + def _set_value(self, new_value): + raise NotImplementedError( + f"_set_value not implemented for IntrinsicObjectState {self.__class__.__name__} state." + ) + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("IntrinsicObjectState") + return classes + + +class BooleanStateMixin(BaseObjectState): + """ + This class is a mixin used to indicate that a state has a boolean value. + """ + + pass diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/on_fire.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/on_fire.py new file mode 100644 index 0000000000000000000000000000000000000000..498d73daee6ced510a6b47938019d510099b9a18 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/on_fire.py @@ -0,0 +1,195 @@ +import torch as th +import warp as wp + +import omnigibson.lazy as lazy +from omnigibson.macros import create_module_macros +from omnigibson.object_states.heat_source_or_sink import HeatSourceOrSink +from omnigibson.object_states.tensorized_absolute_state import TensorizedAbsoluteState +from omnigibson.object_states.temperature import Temperature +from omnigibson.utils.python_utils import classproperty + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# TODO: Delete default values for this and make them required. +m.DEFAULT_IGNITION_TEMPERATURE = 250 + + +@wp.kernel +def _on_fire_kernel( + self_temp_idx: wp.array(dtype=wp.int32), # (N_of,) into Temperature N + ignition_temperatures: wp.array(dtype=wp.float32), # (N_of,) + temperature_values: wp.array2d(dtype=wp.float32), # (S, N_temp) + out_values: wp.array2d(dtype=wp.uint8), # (S, N_of) — uint8 view of bool +): + """ + Per (scene, obj) thread: VALUES[s, h] = Temperature[s, self_temp_idx[h]] >= ignition[h]. + """ + s, h = wp.tid() + n = self_temp_idx[h] + if n < wp.int32(0): + out_values[s, h] = wp.uint8(0) + return + if temperature_values[s, n] >= ignition_temperatures[h]: + out_values[s, h] = wp.uint8(1) + else: + out_values[s, h] = wp.uint8(0) + + +class OnFire(TensorizedAbsoluteState): + """ + Boolean state: True while the object's temperature is at or above its ignition temperature — + a pure threshold detector over Temperature (its dependency), analogous to MaxTemperature. + + Everything the fire *does* lives elsewhere: the flammable ability pairs this state with a + HeatSourceOrSink(requires_on_fire=True) on the same object. That heat source's activation + gate reads this state's previous-step values (a deliberate lag-1 read that breaks the + OnFire → Temperature → HeatSourceOrSink cycle), and Temperature then uses the active source + to heat nearby objects and to hold the burning object itself at its fire temperature. That + self-sustaining clamp is what makes this state sticky: once ignited, temperature stays at + fire temperature (≥ ignition) until the object is deliberately cooled below ignition or + set not-on-fire. + """ + + # Per-object config (N_of,) — uploaded once in initialize_view (single source of truth). + _ignition_temperatures = None # wp.array (N_of,) float32 + + # Index map into Temperature's N dimension. Built directly in initialize_view — safe + # because Temperature is a dependency, so its view is rebuilt before this one. + _self_temp_idx = None # wp.array (N_of,) int32 + + def __init__(self, obj, ignition_temperature=None): + """ + Args: + obj (StatefulObject): The object with the flammable ability. + ignition_temperature (float): The temperature threshold at / above which the object + is on fire. + """ + super().__init__(obj) + self.ignition_temperature = ( + ignition_temperature if ignition_temperature is not None else m.DEFAULT_IGNITION_TEMPERATURE + ) + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(Temperature) + return deps + + @classproperty + def value_type(cls): + return th.bool + + @classproperty + def value_name(cls): + return "on_fire" + + @property + def _companion_heat_source(self): + """ + Returns: + None or HeatSourceOrSink: The requires_on_fire heat source the flammable ability + pairs with this state, if present. + """ + heat_source = self.obj.states.get(HeatSourceOrSink) + return heat_source if heat_source is not None and heat_source.requires_on_fire else None + + @property + def temperature(self): + """ + Returns: + float: The fire temperature the object is held at while on fire. + """ + companion = self._companion_heat_source + return companion.temperature if companion is not None else self.ignition_temperature + + @property + def heating_rate(self): + """ + Returns: + float: Heating rate of the fire towards nearby objects. + """ + companion = self._companion_heat_source + return companion.heating_rate if companion is not None else 0.0 + + @classmethod + def global_initialize(cls): + super().global_initialize() + cls._ignition_temperatures = None + cls._self_temp_idx = None + + @classmethod + def initialize_view(cls): + super().initialize_view() + + N = len(cls.OBJ_IDXS) + if N == 0: + cls._ignition_temperatures = None + cls._self_temp_idx = None + return + + ignition_temperatures = th.zeros(N, dtype=th.float32) + for rel_path, obj_idx in cls.OBJ_IDXS.items(): + for scene_row in cls.IDX_OBJS: + if scene_row[obj_idx] is not None: + ignition_temperatures[obj_idx] = float(scene_row[obj_idx].states[cls].ignition_temperature) + break + + create_tensor_from_list = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list + cls._ignition_temperatures = create_tensor_from_list(ignition_temperatures, "float32", device="cuda") + + # Temperature is a hard dependency, so every OnFire object has a Temperature entry. + idxs = [Temperature.OBJ_IDXS.get(rel_path, -1) for rel_path in cls.OBJ_IDXS] + cls._self_temp_idx = wp.array(idxs, dtype=wp.int32, device="cuda") + + @classmethod + def _update_values(cls, values): + if cls.VALUES_WP is None or cls._self_temp_idx is None or Temperature.VALUES_WP is None: + return + S, N = cls.VALUES.shape[:2] + if S == 0 or N == 0: + return + wp.launch( + kernel=_on_fire_kernel, + dim=(S, N), + inputs=[cls._self_temp_idx, cls._ignition_temperatures, Temperature.VALUES_WP, cls.VALUES_WP], + device="cuda", + ) + + def _get_value(self): + if self.OBJ_IDXS is None or self.obj.relative_prim_path not in self.OBJ_IDXS: + return False + s = self.obj.scene.idx + obj_idx = self.OBJ_IDXS[self.obj.relative_prim_path] + return bool(self.VALUES_CPU[s, obj_idx].item()) + + def _set_value(self, new_value): + """ + Direct setter: write Temperature so the threshold holds (and so the companion heat + source's lag-1 gate picks the change up on the next pass), AND write VALUES immediately + so get_value() reflects the new state without waiting for the next graph pass. + """ + if self.OBJ_IDXS is None or self.obj.relative_prim_path not in self.OBJ_IDXS: + return False + s = self.obj.scene.idx + h = self.OBJ_IDXS[self.obj.relative_prim_path] + + if new_value: + # Push the temperature to the fire temperature (falls back to the ignition + # threshold if no companion heat source exists). + self.obj.states[Temperature].set_value(self.temperature) + else: + # Set temperature just below ignition. + self.obj.states[Temperature].set_value(self.ignition_temperature - 1) + self.VALUES[s, h] = bool(new_value) + self.VALUES_CPU[s, h] = bool(new_value) + return True + + # OnFire is fully derived from Temperature (a pure threshold detector), so loading must be a + # no-op — matching main, where OnFire is not stateful at all. Overriding the inherited + # TensorizedAbsoluteState._load_state is REQUIRED: the generic implementation routes through + # _set_value(stored_value), and _set_value(False) writes Temperature = ignition_temperature - 1 + # (~249 C) — i.e. restoring a saved `on_fire: False` would HEAT a cold flammable object on + # every scene load / reset. + def _load_state(self, state): + return diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/on_top.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/on_top.py new file mode 100644 index 0000000000000000000000000000000000000000..558cc0fd7909ee74c15b8ea0e6334b4639b964fc --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/on_top.py @@ -0,0 +1,155 @@ +import torch as th +import warp as wp + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.object_states.adjacency import Adjacency +from omnigibson.object_states.kinematics_mixin import KinematicsMixin +from omnigibson.object_states.object_state_base import BooleanStateMixin +from omnigibson.object_states.tensorized_relative_state import TensorizedRelativeState +from omnigibson.object_states.touching import Touching +from omnigibson.utils.constants import PrimType +from omnigibson.utils.object_state_utils import get_reachability_sampling_context +from omnigibson.utils.object_state_utils import m as os_m +from omnigibson.utils.object_state_utils import sample_kinematics +from omnigibson.utils.python_utils import classproperty + + +# Adjacency axis layout: k=0 is +Z (other above self), k=1 is -Z (other below self). +# OnTop(self, other) is true when: +# - self is touching other +# - other is directly below self (Adjacency k=1) +# - other is NOT also above self (Adjacency k=0) — disambiguates the rare both-axes case. + + +@wp.kernel +def _on_top_kernel( + touching_values: wp.array3d(dtype=wp.uint8), # (S, N_t, N_t) — Touching.VALUES uint8 view + adjacency_values: wp.array4d(dtype=wp.uint8), # (S, N_a, N_a, K) — Adjacency.VALUES uint8 view + touch_idx: wp.array(dtype=wp.int32), # (N,) — OnTop idx → Touching idx, -1 if missing + adj_idx: wp.array(dtype=wp.int32), # (N,) — OnTop idx → Adjacency idx, -1 if missing + values: wp.array3d(dtype=wp.uint8), # (S, N, N) — OnTop.VALUES uint8 view +): + s, i, j = wp.tid() + + if i == j: + values[s, i, j] = wp.uint8(0) + return + + t_i = touch_idx[i] + t_j = touch_idx[j] + a_i = adj_idx[i] + a_j = adj_idx[j] + if t_i < 0 or t_j < 0 or a_i < 0 or a_j < 0: + values[s, i, j] = wp.uint8(0) + return + + touching = touching_values[s, t_i, t_j] != wp.uint8(0) + above = adjacency_values[s, a_i, a_j, 0] != wp.uint8(0) # k=0 → other above self + below = adjacency_values[s, a_i, a_j, 1] != wp.uint8(0) # k=1 → other below self + + if touching and below and not above: + values[s, i, j] = wp.uint8(1) + else: + values[s, i, j] = wp.uint8(0) + + +class OnTop(TensorizedRelativeState, KinematicsMixin, BooleanStateMixin): + # (N,) int32 mappings from OnTop's N-index to the corresponding state's N-index. + _touch_idx = None # wp.array(N,) int32 — OnTop idx → Touching idx, -1 if missing + _adj_idx = None # wp.array(N,) int32 — OnTop idx → Adjacency idx, -1 if missing + + @classproperty + def value_shape(cls): + return () + + @classproperty + def value_type(cls): + return th.bool + + @classproperty + def value_name(cls): + return "on_top" + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.update({Touching, Adjacency}) + return deps + + @classmethod + def initialize_view(cls): + super().initialize_view() + N = len(cls.OBJ_IDXS) + if N == 0: + cls._touch_idx = None + cls._adj_idx = None + return + + touch_idx_cpu = th.full((N,), -1, dtype=th.int32) + adj_idx_cpu = th.full((N,), -1, dtype=th.int32) + touch_map = Touching.OBJ_IDXS or {} + adj_map = Adjacency.OBJ_IDXS or {} + for rel_path, idx in cls.OBJ_IDXS.items(): + touch_idx_cpu[idx] = touch_map.get(rel_path, -1) + adj_idx_cpu[idx] = adj_map.get(rel_path, -1) + + cls._touch_idx = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + touch_idx_cpu, "int32", device="cuda" + ) + cls._adj_idx = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list(adj_idx_cpu, "int32", device="cuda") + + @classmethod + def _update_values(cls, values): + if cls.VALUES_WP is None or cls._touch_idx is None or cls._adj_idx is None: + return + if Touching.VALUES_WP is None or Adjacency.VALUES_WP is None: + # Upstream not ready — leave VALUES as-is (will be zeros from initial alloc). + return + + S, N, _ = values.shape + if S == 0 or N == 0: + return + + wp.launch( + kernel=_on_top_kernel, + dim=(S, N, N), + inputs=[ + Touching.VALUES_WP, + Adjacency.VALUES_WP, + cls._touch_idx, + cls._adj_idx, + cls.VALUES_WP, + ], + device="cuda", + ) + + def _get_value(self, other): + if other.prim_type == PrimType.CLOTH: + raise ValueError("Cannot detect if an object is on top of a cloth object.") + + return super()._get_value(other) + + def _set_value(self, other, new_value, reset_before_sampling=False, use_trav_map=True): + if not new_value: + raise NotImplementedError("OnTop does not support set_value(False)") + + if other.prim_type == PrimType.CLOTH: + raise ValueError("Cannot set an object on top of a cloth object.") + + state = og.sim.dump_state(serialized=False) + + # Possibly reset this object if requested + if reset_before_sampling: + self.obj.reset() + + reachability_context = get_reachability_sampling_context(other, "onTop", use_trav_map=use_trav_map) + for _ in range(os_m.DEFAULT_HIGH_LEVEL_SAMPLING_ATTEMPTS): + if sample_kinematics( + "onTop", self.obj, other, use_trav_map=use_trav_map, reachability_context=reachability_context + ) and self.get_value(other): + return True + else: + og.sim.load_state(state, serialized=False) + + return False diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/open_state.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/open_state.py new file mode 100644 index 0000000000000000000000000000000000000000..6284bd37ae5d8f7819e4efca541f5fbee93ed103 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/open_state.py @@ -0,0 +1,391 @@ +import random + +import torch as th +import warp as wp + +import omnigibson.lazy as lazy +from omnigibson.macros import create_module_macros +from omnigibson.object_states.object_state_base import BooleanStateMixin +from omnigibson.object_states.tensorized_absolute_state import TensorizedAbsoluteState +from omnigibson.utils.constants import JointType +from omnigibson.utils.python_utils import classproperty +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import ArticulatedObjectViewAPI + +# Create module logger +log = create_module_logger(module_name=__name__) + + +@wp.kernel +def _open_update_kernel( + joint_positions: wp.array2d(dtype=wp.float32), # _JOINT_POSITIONS (N_art, max_dof) + obj_view_rows: wp.array2d(dtype=wp.int32), # OBJ_IDXES_IN_ARTICULATION_VIEW (S, O) + openable_mask: wp.array3d(dtype=wp.uint8), # (S, O, max_dof) bool packed as uint8 + thresholds_s1: wp.array3d(dtype=wp.float32), # (S, O, max_dof) + directions_s1: wp.array3d(dtype=wp.float32), + thresholds_s2: wp.array3d(dtype=wp.float32), + directions_s2: wp.array3d(dtype=wp.float32), + both_sides: wp.array2d(dtype=wp.uint8), # (S, O) + max_dof: wp.int32, + out_values: wp.array2d(dtype=wp.uint8), # (S, O) bool as uint8 +): + """ + Per-(scene, object) thread. A kernel loops over one object's DOF and OR-accumulates + `any_s1` and `any_s2` openness. + """ + s, o = wp.tid() + row = obj_view_rows[s, o] + any_s1 = wp.uint8(0) + any_s2 = wp.uint8(0) + for d in range(max_dof): + if openable_mask[s, o, d] != wp.uint8(0): + p = joint_positions[row, d] + if (p - thresholds_s1[s, o, d]) * directions_s1[s, o, d] > 0.0: + any_s1 = wp.uint8(1) + if (p - thresholds_s2[s, o, d]) * directions_s2[s, o, d] > 0.0: + any_s2 = wp.uint8(1) + if both_sides[s, o] != wp.uint8(0): + out_values[s, o] = any_s1 & any_s2 + else: + out_values[s, o] = any_s1 + + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# Joint position threshold before a joint is considered open. +# Should be a number in the range [0, 1] which will be transformed +# to a position in the joint's min-max range. +m.JOINT_THRESHOLD_BY_TYPE = { + JointType.JOINT_REVOLUTE: 0.05, + JointType.JOINT_PRISMATIC: 0.05, +} +m.OPEN_SAMPLING_ATTEMPTS = 5 + +m.METADATA_FIELD = "openable_joint_ids" +m.BOTH_SIDES_METADATA_FIELD = "openable_both_sides" + + +def _compute_joint_threshold(joint, joint_direction): + """ + Computes the joint threshold for opening and closing + + Args: + joint (JointPrim): Joint to calculate threshold for + joint_direction (int): If 1, assumes opening direction is positive angle change. Otherwise, + assumes opening direction is negative angle change. + + Returns: + 3-tuple: + + - float: Joint value at which closed <--> open + - float: Extreme joint value for being opened + - float: Extreme joint value for being closed + """ + global m + # Convert fractional threshold to actual joint position. + f = m.JOINT_THRESHOLD_BY_TYPE[joint.joint_type] + closed_end = joint.lower_limit if joint_direction == 1 else joint.upper_limit + open_end = joint.upper_limit if joint_direction == 1 else joint.lower_limit + threshold = (1 - f) * closed_end + f * open_end + return threshold, open_end, closed_end + + +def _get_relevant_joints(obj): + """ + Grabs the relevant joints for object @obj + + Args: + obj (StatefulObject): Object to grab relevant joints for + + Returns: + 3-tuple: + - bool: If True, check open/closed state for objects whose joints can switch positions + - list of JointPrim: Relevant joints for determining whether @obj is open or closed + - list of int: Joint directions for each corresponding relevant joint + """ + global m + + default_both_sides = False + default_relevant_joints = list(obj.joints.values()) + # 1 means the open direction corresponds to positive joint angle change and -1 means the opposite + default_joint_directions = [1] * len(default_relevant_joints) + + if not hasattr(obj, "metadata") or obj.metadata is None: + log.debug("No openable joint metadata found for object %s" % obj.name) + return default_both_sides, default_relevant_joints, default_joint_directions + + # Get joint IDs and names from metadata annotation. If not, return default values. + if m.METADATA_FIELD not in obj.metadata or len(obj.metadata[m.METADATA_FIELD]) == 0: + log.debug(f"No openable joint metadata found for object {obj.name}") + return default_both_sides, default_relevant_joints, default_joint_directions + + both_sides = obj.metadata[m.BOTH_SIDES_METADATA_FIELD] if m.BOTH_SIDES_METADATA_FIELD in obj.metadata else False + joint_metadata = obj.metadata[m.METADATA_FIELD].items() + + # The joint metadata is in the format of [(joint_id, joint_name), ...] for legacy annotations and + # [(joint_id, joint_name, joint_direction), ...] for direction-annotated objects. + joint_names = [m[1] for m in joint_metadata] + joint_directions = [m[2] if len(m) > 2 else 1 for m in joint_metadata] + + relevant_joints = [] + for key in joint_names: + assert key in obj.joints, f"Unexpected joint name from Open metadata for object {obj.name}: {key}" + relevant_joints.append(obj.joints[key]) + + assert all(joint.joint_type in m.JOINT_THRESHOLD_BY_TYPE.keys() for joint in relevant_joints) + + return both_sides, relevant_joints, joint_directions + + +class Open(TensorizedAbsoluteState, BooleanStateMixin): + """ + Tensorized Open state. + + VALUES shape: (S, O) — bool True = open, False = closed. + """ + + # wp.array3d (S, O, max_dof) uint8 — 1 for DOF columns corresponding to openable joints. + OPENABLE_MASK = None + + # wp.array3d (S, O, max_dof) float32 — per-DOF threshold/direction for side=+1. + THRESHOLDS_S1 = None + DIRECTIONS_S1 = None + + # wp.array3d (S, O, max_dof) float32 — per-DOF threshold/direction for side=-1 (0 for non-both_sides). + THRESHOLDS_S2 = None + DIRECTIONS_S2 = None + + # wp.array2d (S, O) uint8 — whether each object uses both-sides open logic. + BOTH_SIDES = None + + # wp.array2d (S, O) int32 — row indices into ArticulatedObjectViewAPI._JOINT_POSITIONS. + OBJ_IDXES_IN_ARTICULATION_VIEW = None + + # Cached max_dof int (kernel input). Updated in initialize_view. + _MAX_DOF = 0 + + @classproperty + def value_name(cls): + return "open" + + @classproperty + def value_type(cls): + return th.bool + + @classmethod + def is_compatible(cls, obj, **kwargs): + # Run super first + compatible, reason = super().is_compatible(obj, **kwargs) + if not compatible: + return compatible, reason + + # Check whether this object has any openable joints + return ( + (True, None) + if obj.n_joints > 0 + else (False, f"No relevant joints for Open state found for object {obj.name}") + ) + + @classmethod + def is_compatible_asset(cls, prim, **kwargs): + # Run super first + compatible, reason = super().is_compatible_asset(prim, **kwargs) + if not compatible: + return compatible, reason + + def _find_articulated_joints(prim): + for child in prim.GetChildren(): + child_type = child.GetTypeName().lower() + if "joint" in child_type and "fixed" not in child_type: + return True + for gchild in child.GetChildren(): + gchild_type = gchild.GetTypeName().lower() + if "joint" in gchild_type and "fixed" not in gchild_type: + return True + return False + + # Check whether this object has any openable joints + return ( + (True, None) + if _find_articulated_joints(prim=prim) + else (False, f"No relevant joints for Open state found for asset prim {prim.GetName()}") + ) + + @classmethod + def initialize_view(cls): + super().initialize_view() # builds OBJ_IDXS, IDX_OBJS, VALUES (S, O) + + S = len(cls.IDX_OBJS) + O = len(cls.OBJ_IDXS) + + if O == 0: + cls._MAX_DOF = 0 + cls.OPENABLE_MASK = None + cls.THRESHOLDS_S1 = None + cls.DIRECTIONS_S1 = None + cls.THRESHOLDS_S2 = None + cls.DIRECTIONS_S2 = None + cls.BOTH_SIDES = None + cls.OBJ_IDXES_IN_ARTICULATION_VIEW = None + return + + max_dof = ArticulatedObjectViewAPI.get_max_dof() + cls._MAX_DOF = int(max_dof) + + # Build per-DOF tables on CPU first, then upload once. Per-cell GPU writes via torch + # indexing would round-trip through CUDA per cell — CPU scratch + one bulk upload is faster. + openable_mask_cpu = th.zeros((S, O, max_dof), dtype=th.uint8) + thresholds_s1_cpu = th.zeros((S, O, max_dof), dtype=th.float32) + directions_s1_cpu = th.zeros((S, O, max_dof), dtype=th.float32) + thresholds_s2_cpu = th.zeros((S, O, max_dof), dtype=th.float32) + directions_s2_cpu = th.zeros((S, O, max_dof), dtype=th.float32) + both_sides_cpu = th.zeros((S, O), dtype=th.uint8) + + for scene_idx, scene in enumerate(cls.IDX_OBJS): + for obj_idx in range(O): + obj = scene[obj_idx] + if obj is None or obj.joints is None: + continue # obj not initialized yet + both_sides, relevant_joints, joint_directions = _get_relevant_joints(obj) + both_sides_cpu[scene_idx, obj_idx] = 1 if both_sides else 0 + for joint, direction in zip(relevant_joints, joint_directions): + for dof_col in joint.dof_indices: + openable_mask_cpu[scene_idx, obj_idx, dof_col] = 1 + for side, threshold_attr, direction_attr in [ + (1, thresholds_s1_cpu, directions_s1_cpu), + (-1, thresholds_s2_cpu, directions_s2_cpu), + ]: + threshold, open_end, _ = _compute_joint_threshold(joint, direction * side) + threshold_attr[scene_idx, obj_idx, dof_col] = threshold + direction_attr[scene_idx, obj_idx, dof_col] = 1.0 if open_end > threshold else -1.0 + + # (S, O) row index into ArticulatedObjectViewAPI._JOINT_POSITIONS. + obj_view_rows_cpu = th.zeros((S, O), dtype=th.int32) + for _, obj_idx in cls.OBJ_IDXS.items(): + for scene_idx, scene in enumerate(cls.IDX_OBJS): + obj = scene[obj_idx] + if obj is None: + continue + row = ArticulatedObjectViewAPI.get_view_row(obj.articulation_root_path) + obj_view_rows_cpu[scene_idx, obj_idx] = row + + cls.OPENABLE_MASK = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + openable_mask_cpu, "uint8", device="cuda" + ) + cls.THRESHOLDS_S1 = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + thresholds_s1_cpu, "float32", device="cuda" + ) + cls.DIRECTIONS_S1 = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + directions_s1_cpu, "float32", device="cuda" + ) + cls.THRESHOLDS_S2 = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + thresholds_s2_cpu, "float32", device="cuda" + ) + cls.DIRECTIONS_S2 = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + directions_s2_cpu, "float32", device="cuda" + ) + cls.BOTH_SIDES = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + both_sides_cpu, "uint8", device="cuda" + ) + cls.OBJ_IDXES_IN_ARTICULATION_VIEW = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + obj_view_rows_cpu, "int32", device="cuda" + ) + + @classmethod + def _update_values(cls, values): + if cls.OPENABLE_MASK is None or cls._MAX_DOF == 0: + return + if ArticulatedObjectViewAPI._JOINT_POSITIONS is None: + return + S, O = values.shape[:2] + wp.launch( + kernel=_open_update_kernel, + dim=(S, O), + inputs=[ + ArticulatedObjectViewAPI._JOINT_POSITIONS, + cls.OBJ_IDXES_IN_ARTICULATION_VIEW, + cls.OPENABLE_MASK, + cls.THRESHOLDS_S1, + cls.DIRECTIONS_S1, + cls.THRESHOLDS_S2, + cls.DIRECTIONS_S2, + cls.BOTH_SIDES, + wp.int32(cls._MAX_DOF), + cls.VALUES_WP, + ], + device="cuda", + ) + + def _get_value(self): + return bool(super()._get_value()) + + def _set_value(self, new_value, fully=False): + """ + Set the openness state, either to a random joint position satisfying the new value, or fully open/closed. + + Args: + new_value (bool): The new value for the openness state of the object. + fully (bool): Whether the object should be fully opened/closed (e.g. all relevant joints to 0/1). + + Returns: + bool: A boolean indicating the success of the setter. Failure may happen due to unannotated objects. + """ + both_sides, relevant_joints, joint_directions = _get_relevant_joints(self.obj) + if not relevant_joints: + return False + + # The "sides" variable is used to check open/closed state for objects whose joints can switch + # positions. These objects are annotated with the both_sides annotation and the idea is that switching + # the directions of *all* of the joints results in a similarly valid checkable state. We want our object to be + # open from *both* of the two sides, and I was too lazy to implement the logic for this without rejection + # sampling, so that's what we do. + # TODO: Implement a sampling method that's guaranteed to be correct, ditch the rejection method. + sides = [1, -1] if both_sides else [1] + + for _ in range(m.OPEN_SAMPLING_ATTEMPTS): + side = random.choice(sides) + + joints_to_set = list(zip(relevant_joints, joint_directions)) + + # All joints are relevant if we are closing, but if we are opening let's sample a subset. + if new_value and not fully: + num_to_open = th.randint(1, len(relevant_joints) + 1, (1,)).item() + random_indices = th.randperm(len(relevant_joints))[:num_to_open] + joints_to_set = [joints_to_set[i] for i in random_indices] + + # Go through the relevant joints & set random positions. + for joint, joint_direction in joints_to_set: + threshold, open_end, closed_end = _compute_joint_threshold(joint, joint_direction * side) + + # Get the range + if new_value: + joint_range = (threshold, open_end) + else: + joint_range = (threshold, closed_end) + + if fully: + joint_pos = joint_range[1] + else: + # Convert the range to the format numpy accepts. + low = min(joint_range) + high = max(joint_range) + + # Sample a position. + joint_pos = (th.rand(1) * (high - low) + low).item() + + # Save sampled position. JointPrim.set_pos flips TensorizedState.caches_dirty, + # so the next get_value() below will trigger a refresh and observe the new pose. + joint.set_pos(joint_pos) + + if self.get_value() == new_value: + return True + + # We exhausted our attempts and could not find a working sample. + return False + + # We don't need to load / save anything since the joints are saved elsewhere. + # Overriding the inherited TensorizedAbsoluteState._load_state which would + # call self._set_value(stored_value) + def _load_state(self, state): + return diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/overlaid.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/overlaid.py new file mode 100644 index 0000000000000000000000000000000000000000..3f0a4d40880544edd7ba391d9d5431c7d9a8ca58 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/overlaid.py @@ -0,0 +1,84 @@ +import itertools + +import torch as th +from scipy.spatial import ConvexHull, HalfspaceIntersection, QhullError + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros +from omnigibson.object_states.kinematics_mixin import KinematicsMixin +from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState +from omnigibson.object_states.touching import Touching +from omnigibson.utils.constants import PrimType +from omnigibson.utils.object_state_utils import sample_cloth_on_rigid + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# Percentage of xy-plane of the object's base aligned bbox that needs to covered by the cloth +m.OVERLAP_AREA_PERCENTAGE = 0.5 + +# z-offset for sampling +m.SAMPLING_Z_OFFSET = 0.01 + + +class Overlaid(KinematicsMixin, RelativeObjectState, BooleanStateMixin): + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(Touching) + return deps + + def _set_value(self, other, new_value): + if not new_value: + raise NotImplementedError("Overlaid does not support set_value(False)") + state = og.sim.dump_state(serialized=False) + + if sample_cloth_on_rigid(self.obj, other, randomize_xy=False) and self.get_value(other): + return True + else: + og.sim.load_state(state, serialized=False) + + return False + + def _get_value(self, other): + """ + Check whether the (cloth) object is overlaid on the other (rigid) object. + First, the cloth object needs to be touching the rigid object. + Then, the convex hull of the particles of the cloth object needs to cover a decent percentage of the + base aligned bounding box of the other rigid object. + """ + if not (self.obj.prim_type == PrimType.CLOTH and other.prim_type == PrimType.RIGID): + raise ValueError("Overlaid state requires obj1 is cloth and obj2 is rigid.") + + if not self.obj.states[Touching].get_value(other): + return False + + # Compute the convex hull of the particles of the cloth object. + points = self.obj.root_link.keypoint_particle_positions[:, :2] + cloth_hull = ConvexHull(points) + + # Compute the base aligned bounding box of the rigid object. + bbox_center, bbox_orn, bbox_extent, _ = other.get_base_aligned_bbox(xy_aligned=True) + vertices_local = th.tensor(list(itertools.product((1, -1), repeat=3))) * (bbox_extent / 2) + vertices = T.transform_points(vertices_local, T.pose2mat((bbox_center, bbox_orn))) + rigid_hull = ConvexHull(vertices[:, :2]) + + # The goal is to find the intersection of the convex hull and the bounding box. + # We can do so with HalfspaceIntersection, which takes as input a list of equations that define the half spaces, + # and an interior point. We assume the center of the bounding box is an interior point. + interior_pt = th.mean(vertices, dim=0)[:2] + half_spaces = th.vstack((th.tensor(cloth_hull.equations), th.tensor(rigid_hull.equations))) + try: + half_space_intersection = HalfspaceIntersection(half_spaces, interior_pt) + except QhullError: + # The bbox center of the rigid body does not lie in the intersection, return False. + return False + + # Compute the ratio between the intersection area and the bounding box area in the x-y plane. + # When input points are 2-dimensional, this is the area of the convex hull. + # Ref: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html + intersection_area = ConvexHull(half_space_intersection.intersections).volume + rigid_xy_area = bbox_extent[0] * bbox_extent[1] + + return (intersection_area / rigid_xy_area) > m.OVERLAP_AREA_PERCENTAGE diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/particle.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/particle.py new file mode 100644 index 0000000000000000000000000000000000000000..3bf375504a299e29a145adc4b61a4ac1b13af54e --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/particle.py @@ -0,0 +1,20 @@ +from omnigibson.object_states.object_state_base import BaseObjectRequirement +from omnigibson.macros import gm + + +class ParticleRequirement(BaseObjectRequirement): + """ + Class for sanity checking objects that requires particle systems + """ + + @classmethod + def is_compatible(cls, obj, **kwargs): + if not gm.USE_GPU_DYNAMICS: + return False, "Particle systems are not enabled when GPU dynamics is off." + + return True, None + + @classmethod + def is_compatible_asset(cls, prim, **kwargs): + # No actual requirement on the asset side. + return True, None diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/particle_modifier.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/particle_modifier.py new file mode 100644 index 0000000000000000000000000000000000000000..dc35f886443a89ae3394c8d4b68553dd067f43d7 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/particle_modifier.py @@ -0,0 +1,1588 @@ +import math +from abc import abstractmethod +from collections import defaultdict + +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros, macros, gm +from omnigibson.object_states.aabb import AABB +from omnigibson.object_states.contact_particles import ContactParticles +from omnigibson.object_states.covered import Covered +from omnigibson.object_states.link_based_state_mixin import LinkBasedStateMixin +from omnigibson.object_states.object_state_base import IntrinsicObjectState +from omnigibson.object_states.saturated import ModifiedParticles, Saturated +from omnigibson.object_states.toggle import ToggledOn +from omnigibson.object_states.update_state_mixin import UpdateStateMixin +from omnigibson.prims.geom_prim import GeomPrim +from omnigibson.prims.prim_base import BasePrim +from omnigibson.systems import MicroParticleSystem +from omnigibson.systems.system_base import PhysicalParticleSystem + +# from omnigibson.systems.micro_particle_system import MicroParticleSystem +from omnigibson.utils.constants import ParticleModifyCondition, ParticleModifyMethod, PrimType +from omnigibson.utils.geometry_utils import ( + get_particle_positions_from_frame, + get_particle_positions_in_frame, +) +from omnigibson.utils.numpy_utils import vtarray_to_torch +from omnigibson.utils.python_utils import classproperty +from omnigibson.utils.sampling_utils import sample_cuboid_on_object +from omnigibson.utils.ui_utils import suppress_omni_log +from omnigibson.utils.usd_utils import ( + absolute_prim_path_to_scene_relative, + create_primitive_mesh, + delete_or_deactivate_prim, +) + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.APPLICATION_META_LINK_TYPE = "particleapplier" +m.REMOVAL_META_LINK_TYPE = "particleremover" + +# How many samples within the application area to generate per update step +m.MAX_VISUAL_PARTICLES_APPLIED_PER_STEP = 2 +m.MAX_PHYSICAL_PARTICLES_APPLIED_PER_STEP = 10 + +# How many steps between generating particle samples +m.N_STEPS_PER_APPLICATION = 5 +m.N_STEPS_PER_REMOVAL = 1 + +# Application thresholds -- maximum number of particles that can be applied by a ParticleApplier +m.VISUAL_PARTICLES_APPLICATION_LIMIT = 1000000 +m.PHYSICAL_PARTICLES_APPLICATION_LIMIT = 1000000 + +# Saturation thresholds -- maximum number of particles that can be removed ("absorbed") by a ParticleRemover +m.VISUAL_PARTICLES_REMOVAL_LIMIT = 200 +m.PHYSICAL_PARTICLES_REMOVAL_LIMIT = 400 + +# Fallback particle visualization radius for visualizing projected visual particles +m.VISUAL_PARTICLE_PROJECTION_PARTICLE_RADIUS = 0.01 + +# The margin (> 0) to add to the remover area's AABB when detecting overlaps with other objects +m.PARTICLE_MODIFIER_ADJACENCY_AREA_MARGIN = 0.02 + +# Settings for determining how the projection particles are visualized as they're projected +m.PROJECTION_VISUALIZATION_CONE_TIP_RADIUS = 0.001 +m.PROJECTION_VISUALIZATION_RATE = 200 +m.PROJECTION_VISUALIZATION_SPEED = 2.0 +m.PROJECTION_VISUALIZATION_ORIENTATION_BIAS = 1e6 +m.PROJECTION_VISUALIZATION_SPREAD_FACTOR = 0.8 + +# Whether to visualize direction vector for particle applier +m.USE_PARTICLE_APPLIER_DIRECTION_INDICATOR = True + + +def create_projection_visualization( + scene, + prim_path, + shape, + projection_name, + projection_radius, + projection_height, + particle_radius, + parent_scale, + material=None, +): + """ + Helper function to generate a projection visualization using Omniverse's particle visualization system + + + Args: + scene (Scene): Scene object to generate the projection visualization within + prim_path (str): Stage location for where to generate the projection visualization + shape (str): Shape of the projection to generate. Valid options are: {Sphere, Cone} + projection_name (str): Name associated with this projection visualization. Should be unique! + projection_radius (float): Radius of the generated projection visualization overall volume + (specified in local frame) + projection_height (float): Height of the generated projection visualization overall volume + (specified in local frame) + particle_radius (float): Radius of the particles composing the projection visualization + parent_scale (3-array): If specified, specifies the (x,y,z) scale of the parent Xform prim of the + generated source sphere prim at @prim_path. This will be used to scale the visualization accordingly + material (None or MaterialPrim): If specified, specifies the material to associate with the generated + particles within the projection visualization + + Returns: + 2-tuple: + - UsdPrim: Generated ParticleSystem (ComputeGraph) prim generated + - UsdPrim: Generated Emitter (ComputeGraph) prim generated + """ + # Create the desired shape which will be used as the source input prim into the generated projection visualization + source = lazy.pxr.UsdGeom.Sphere.Define(og.sim.stage, lazy.pxr.Sdf.Path(prim_path)) + + # Modify the radius according to the desired @shape (and also infer the desired spread values) + if shape == "Cylinder": + source_radius = projection_radius + spread = th.zeros(3) + elif shape == "Cone": + # Default to close to singular point otherwise + source_radius = m.PROJECTION_VISUALIZATION_CONE_TIP_RADIUS + spread_ratio = projection_radius * 2.0 / projection_height + spread = th.ones(3) * spread_ratio * m.PROJECTION_VISUALIZATION_SPREAD_FACTOR + else: + raise ValueError( + f"Invalid shape specified for projection visualization! Valid options are: [Cone, Cylinder], got: {shape}" + ) + # Set the radius + source.GetRadiusAttr().Set(source_radius) + # Also make the prim invisible + lazy.pxr.UsdGeom.Imageable(source.GetPrim()).MakeInvisible() + + # Generate the ComputeGraph nodes to render the projection + # Import now to avoid too-eager load of Omni classes due to inheritance + from omnigibson.utils.deprecated_utils import Core + + core = Core(lambda val: None, particle_system_name=projection_name) + + # Scale radius and height by the parent scale -- projection always points in the negative-z direction of the + # parent frame + # We do this AFTER we create the source sphere because the actual projection is scaled in the world frame, whereas + # the source sphere is already scaled by its own parent frame + # NOTE: The generated projection visualization will NOT match the underlying projection mesh if the parent link is + # scaled non-uniformly!! + projection_radius *= th.mean(parent_scale[:2]) + projection_height *= parent_scale[2] + + # Suppress omni warnings here -- we don't have control over this API, but omni likes to complain about this + with suppress_omni_log(channels=["omni.graph.core.plugin", "omni.usd", "rtx.neuraylib.plugin"]): + system_path, _, emitter_path, vis_path, instancer_path, sprite_path, mat_path, output_path = ( + core.create_particle_system(display="point_instancer", paths=[prim_path]) + ) + + # Override the prototype with our own sphere with optional material + prototype_path = "/".join(sprite_path.split("/")[:-1]) + "/prototype" + create_primitive_mesh(prototype_path, primitive_type="Sphere") + relative_prototype_path = absolute_prim_path_to_scene_relative(scene, prototype_path) + prototype = GeomPrim(relative_prim_path=relative_prototype_path, name=f"{projection_name}_prototype") + prototype.load(scene) + prototype.initialize() + # Set the scale (native scaling --> radius 0.5) and possibly update the material + prototype.scale = particle_radius * 2.0 + if material is not None: + prototype.material = material + # Override the prototype used by the instancer + instancer_prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(instancer_path) + instancer_prim.GetProperty("inputs:prototypes").SetTargets([prototype_path]) + + # Destroy the old mat path since we don't use the sprites + delete_or_deactivate_prim(mat_path) + + # Modify the settings of the emitter to match the desired shape from inputs + emitter_prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(emitter_path) + emitter_prim.GetProperty("inputs:active").Set(True) + emitter_prim.GetProperty("inputs:rate").Set(m.PROJECTION_VISUALIZATION_RATE) + emitter_prim.GetProperty("inputs:lifespan").Set(projection_height.item() / m.PROJECTION_VISUALIZATION_SPEED) + emitter_prim.GetProperty("inputs:speed").Set(m.PROJECTION_VISUALIZATION_SPEED) + emitter_prim.GetProperty("inputs:alongAxis").Set(m.PROJECTION_VISUALIZATION_ORIENTATION_BIAS) + emitter_prim.GetProperty("inputs:scale").Set(lazy.pxr.Gf.Vec3f(1.0, 1.0, 1.0)) + emitter_prim.GetProperty("inputs:directionRandom").Set(lazy.pxr.Gf.Vec3f(*spread.tolist())) + emitter_prim.GetProperty("inputs:addSourceVelocity").Set(1.0) + + # Make sure we render 4 times to fully propagate changes (validated empirically) + # Omni likes to complain here again, but we have no control over the low-level information, so we suppress warnings + with suppress_omni_log( + channels=["omni.particle.system.core.plugin", "omni.hydra.scene_delegate.plugin", "omni.usd"] + ): + for i in range(4): + og.sim.render() + + # Return the particle system prim which "owns" everything + return lazy.isaacsim.core.utils.prims.get_prim_at_path(system_path), emitter_prim + + +class ParticleModifier(IntrinsicObjectState, LinkBasedStateMixin, UpdateStateMixin): + """ + Object state representing an object that has the ability to modify visual and / or physical particles within the + active simulation. + + Args: + obj (StatefulObject): Object to which this state will be applied + conditions (dict): Dictionary mapping the names of ParticleSystem (str) to None or list of 2-tuples, where + None represents "never", empty list represents "always", or each 2-tuple is interpreted as a single condition in the form of + (ParticleModifyCondition, value) necessary in order for this particle modifier to be + able to modify particles belonging to @ParticleSystem. Expected types of val are as follows: + + SATURATED: string name of the desired system that this modifier must be saturated by, e.g., "water" + TOGGLEDON: boolean T/F; whether this modifier must be toggled on or not + GRAVITY: boolean T/F; whether this modifier must be pointing downwards (T) or upwards (F) + FUNCTION: a function, whose signature is as follows: + + def condition(obj) --> bool + + Where @obj is the specific object that this ParticleModifier state belongs to. + + For a given ParticleSystem, the list of 2-tuples will be converted into a list of function calls of the + form above -- if all of its conditions evaluate to True and particles are detected within + this particle modifier area, then we potentially modify those particles + method (ParticleModifyMethod): Method to modify particles. Current options supported are ADJACENCY (i.e.: + "touching" particles) or PROJECTION (i.e.: "spraying" particles) + projection_mesh_params (None or dict): If specified and @method is ParticleModifyMethod.PROJECTION, + manually overrides any data inferred directly from this object to infer what projection volume to generate + for this particle modifier. Expected entries are as follows: + + "type": (str), one of {"Cylinder", "Cone", "Cube", "Sphere"} + "extents": (3-array), the (x,y,z) extents of the generated volume (specified in local link frame!) + + If None, information found from @obj.metadata will be used instead. + NOTE: x-direction should align with the projection mesh's height (i.e.: z) parameter in @extents! + """ + + def __init__(self, obj, conditions, method=ParticleModifyMethod.ADJACENCY, projection_mesh_params=None): + # Store internal variables + self.method = method + self.projection_source_sphere = None + self.projection_mesh = None + self._check_overlap = None + self._link_prim_paths = None + self._current_step = None + self._projection_mesh_params = projection_mesh_params + + # Run super method + super().__init__(obj) + + # Parse conditions + self._conditions = self._parse_conditions(conditions=conditions) + + @property + def conditions(self): + """ + dict: Dictionary mapping the names of ParticleSystem (str) to a list of function calls that must evaluate to + True in order for this particle modifier to be able to modify particles belonging to @ParticleSystem. + The list of functions at least contains the limit condition, which is a function that checks whether the + applier has applied or the remover has removed the maximum number of particles allowed. If the systen name is + not in the dictionary, then the modifier cannot modify particles of that system. + """ + return self._conditions + + @classmethod + def is_compatible(cls, obj, **kwargs): + # Run super first + compatible, reason = super().is_compatible(obj, **kwargs) + if not compatible: + return compatible, reason + + # Check whether this state has toggledon if required or saturated if required for any condition + conditions = kwargs.get("conditions", dict()) + cond_types = {cond[0] for _, conds in conditions.items() if conds is not None for cond in conds} + for cond_type, state_type in zip((ParticleModifyCondition.TOGGLEDON,), (ToggledOn,)): + if cond_type in cond_types and state_type not in obj.states: + return False, f"{cls.__name__} requires {state_type.__name__} state!" + + return True, None + + @classmethod + def is_compatible_asset(cls, prim, **kwargs): + # Run super first + compatible, reason = super().is_compatible_asset(prim, **kwargs) + if not compatible: + return compatible, reason + + # Check whether this state has toggledon if required or saturated if required for any condition + conditions = kwargs.get("conditions", dict()) + cond_types = {cond[0] for _, conds in conditions.items() if conds is not None for cond in conds} + for cond_type, state_type in zip((ParticleModifyCondition.TOGGLEDON,), (ToggledOn,)): + if cond_type in cond_types and not state_type.is_compatible_asset(prim=prim, **kwargs): + return False, f"{cls.__name__} requires {state_type.__name__} state!" + + return True, None + + @classmethod + def postprocess_ability_params(cls, params, scene): + """ + Post-processes ability parameters to ensure the system names (rather than synsets) are used for conditions. + """ + # Import here to avoid circular imports + from omnigibson.utils.bddl_utils import get_system_name_by_synset + + for sys in list(params["conditions"].keys()): + # The original key can be either a system name or a system synset. If it's a synset, we need to convert it. + system_name = sys if sys in scene.available_systems.keys() else get_system_name_by_synset(sys) + params["conditions"][system_name] = params["conditions"].pop(sys) + conds = params["conditions"][system_name] + if conds is None: + continue + for cond in conds: + cond_type, cond_sys = cond + if cond_type == ParticleModifyCondition.SATURATED: + cond[1] = ( + cond_sys if cond_sys in scene.available_systems.keys() else get_system_name_by_synset(cond_sys) + ) + return params + + def _initialize(self): + super()._initialize() + + # Run link initialization + self.initialize_link_mixin() + + # Sanity check scale if requested + if self.requires_overlap: + # Run sanity check to make sure compatibility with omniverse physx + if self.method == ParticleModifyMethod.PROJECTION and not th.isclose( + self.obj.scale.max(), self.obj.scale.min(), atol=1e-02 + ): + raise ValueError( + f"{self.__class__.__name__} for obj {self.obj.name} using PROJECTION method cannot be " + f"created with non-uniform scale and requires_overlap! Got scale: {self.obj.scale}" + ) + + # Initialize internal variables + self._current_step = 0 + + # Grab link prim paths and potentially update projection mesh params + self._link_prim_paths = set(self.obj.link_prim_paths) + + # Define callback used during overlap method + # We want to ignore any hits that are with this object itself + valid_hit = False + + def overlap_callback(hit): + nonlocal valid_hit + valid_hit = hit.rigid_body not in self._link_prim_paths + # Continue traversal only if we don't have a valid hit yet + return not valid_hit + + # Possibly create a projection volume if we're using the projection method + if self.method == ParticleModifyMethod.PROJECTION: + # Construct naming prefix to apply to generated prims + name_prefix = f"{self.obj.name}_{self.__class__.__name__}" + shape_defaults = { + "radius": 0.5, + "height": 1.0, + "size": 1.0, + } + + # See if the mesh exists at the latest dataset's target location + mesh_prim_path = f"{self.link.prim_path}/visuals/mesh_0" + pre_existing_mesh = lazy.isaacsim.core.utils.prims.get_prim_at_path(mesh_prim_path) + + # If not, see if it exists in the legacy format's location + # TODO: Remove this after new dataset release + if not pre_existing_mesh: + mesh_prim_path = f"{self.link.prim_path}/mesh_0" + pre_existing_mesh = lazy.isaacsim.core.utils.prims.get_prim_at_path(mesh_prim_path) + + # Create a primitive mesh neither option exists + if not pre_existing_mesh: + mesh_prim_path = f"{self.link.prim_path}/visuals/mesh_0" + + # Projection mesh params must be specified in order to determine scalings + assert self._projection_mesh_params is not None, ( + f"Must specify projection_mesh_params for {self.obj.name}'s {self.__class__.__name__} " + f"since it has no pre-existing projection mesh!" + ) + mesh = ( + getattr(lazy.pxr.UsdGeom, self._projection_mesh_params["type"]) + .Define(og.sim.stage, mesh_prim_path) + .GetPrim() + ) + property_names = set(mesh.GetPropertyNames()) + for shape_attr, default_val in shape_defaults.items(): + if shape_attr in property_names: + mesh.GetAttribute(shape_attr).Set(default_val) + + else: + # Potentially populate projection mesh params if the prim exists + mesh_type = pre_existing_mesh.GetTypeName() + if self._projection_mesh_params is None: + self._projection_mesh_params = { + "type": mesh_type, + "extents": vtarray_to_torch(pre_existing_mesh.GetAttribute("xformOp:scale").Get()), + } + # Otherwise, make sure we don't have a mismatch between the pre-existing shape type and the + # desired type since we can't delete the original mesh + else: + assert self._projection_mesh_params["type"] == mesh_type, ( + f"Got mismatch in requested projection mesh type ({self._projection_mesh_params['type']}) and " + f"pre-existing mesh type ({mesh_type})" + ) + + # Create the visual geom instance referencing the generated mesh prim, and then hide it + self.projection_mesh = GeomPrim( + relative_prim_path=absolute_prim_path_to_scene_relative(self.obj.scene, mesh_prim_path), + name=f"{name_prefix}_projection_mesh", + ) + self.projection_mesh.load(self.obj.scene) + self.projection_mesh.initialize() + self.projection_mesh.visible = False + + # Make sure the shape-based attributes are not set, and only the scaling is set + property_names = set(self.projection_mesh.prim.GetPropertyNames()) + for shape_attr, default_val in shape_defaults.items(): + if shape_attr in property_names: + val = self.projection_mesh.get_attribute(shape_attr) + assert ( + val == default_val + ), f"Projection mesh should have shape-based attribute {shape_attr} == {default_val}! Got: {val}" + + # Set the scale based on projection mesh params + self.projection_mesh.scale = self._projection_mesh_params["extents"] + + # Make sure the object updates its meshes, and assert that there's only a single visual mesh + # TODO: This is a bad idea. It creates orphaned prims when the mesh lists get overwritten. Why do we need this? + self.link.update_meshes() + assert ( + len(self.link.visual_meshes) == 1 + ), f"Expected only a single projection mesh for {self.link}, got: {len(self.link.visual_meshes)}" + + # Make sure the mesh is translated so that its tip lies at the meta link origin, and rotated so the vector + # from tip to tail faces the positive x axis + z_offset = ( + 0.0 + if self._projection_mesh_params["type"] == "Sphere" + else self._projection_mesh_params["extents"][2] / 2 + ) + + self.projection_mesh.set_position_orientation( + position=th.tensor([0, 0, -z_offset]), + orientation=T.euler2quat(th.tensor([0, 0, 0], dtype=th.float32)), + frame="parent", + ) + + # Store the projection mesh's IDs + # projection_mesh_ids = lazy.pxr.PhysicsSchemaTools.encodeSdfPath(self.projection_mesh.prim_path) + + # We also generate the function for checking overlaps at runtime + def check_overlap(): + nonlocal valid_hit + valid_hit = False + # When fabric is on, overlap_shape doesn't work, so we use a more coarse approximation for this broadphase check + aabb = self.link.visual_aabb + og.sim.psqi.overlap_box( + halfExtent=((aabb[1] - aabb[0]) / 2.0).tolist(), + pos=((aabb[1] + aabb[0]) / 2.0).tolist(), + rot=[0, 0, 0, 1.0], + reportFn=overlap_callback, + ) + + # TODO(#2082): Investigate why overlap_shape doesn't work with fabric still. This is a poor approximation. + # og.sim.psqi.overlap_shape(*projection_mesh_ids, reportFn=overlap_callback) + return valid_hit + + # Define direction indicator if requested + if m.USE_PARTICLE_APPLIER_DIRECTION_INDICATOR: + indicator_mesh_path = f"{mesh_prim_path}_direction_indicator" + with og.sim.editing_usd(): + indicator_mesh_prim = ( + getattr(lazy.pxr.UsdGeom, self._projection_mesh_params["type"]) + .Define(og.sim.stage, indicator_mesh_path) + .GetPrim() + ) + property_names = set(indicator_mesh_prim.GetPropertyNames()) + for shape_attr, default_val in shape_defaults.items(): + if shape_attr in property_names: + indicator_mesh_prim.GetAttribute(shape_attr).Set(default_val) + indicator_mesh = GeomPrim( + relative_prim_path=absolute_prim_path_to_scene_relative(self.obj.scene, indicator_mesh_path), + name=f"{name_prefix}_projection_mesh_direction_indicator", + ) + indicator_mesh.load(self.obj.scene) + indicator_mesh.initialize() + indicator_mesh.visible = True + # Scale is 5% of the full scale + indicator_mesh_rel_scale = 0.05 + indicator_mesh.scale = self._projection_mesh_params["extents"] * indicator_mesh_rel_scale + indicator_z_offset = ( + 0.0 + if self._projection_mesh_params["type"] == "Sphere" + else self._projection_mesh_params["extents"][2] * indicator_mesh_rel_scale / 2 + ) + indicator_mesh.set_position_orientation( + position=th.tensor([0, 0, -indicator_z_offset]), + orientation=T.euler2quat(th.tensor([0, 0, 0], dtype=th.float32)), + frame="parent", + ) + + elif self.method == ParticleModifyMethod.ADJACENCY: + # Define the function for checking overlaps at runtime + def check_overlap(): + nonlocal valid_hit + valid_hit = False + aabb = self.link.visual_aabb + og.sim.psqi.overlap_box( + halfExtent=((aabb[1] - aabb[0]) / 2.0 + m.PARTICLE_MODIFIER_ADJACENCY_AREA_MARGIN).tolist(), + pos=((aabb[1] + aabb[0]) / 2.0).tolist(), + rot=[0, 0, 0, 1.0], + reportFn=overlap_callback, + ) + return valid_hit + + else: + raise ValueError(f"Unsupported ParticleModifyMethod: {self.method}!") + + # Store check overlap function + self._check_overlap = check_overlap + + # We abuse the Saturated state to store the limit for particle modifier (including both applier and remover) + self.obj.states[Saturated].set_visual_particle_limit(self.visual_particle_modification_limit) + self.obj.states[Saturated].set_physical_particle_limit(self.physical_particle_modification_limit) + + def _check_in_mesh(self, particle_positions): + if self.method == ParticleModifyMethod.ADJACENCY: + # Define the AABB bounds + lower, upper = self.link.visual_aabb + # Add the margin + lower -= m.PARTICLE_MODIFIER_ADJACENCY_AREA_MARGIN + upper += m.PARTICLE_MODIFIER_ADJACENCY_AREA_MARGIN + return ((lower < particle_positions) & (particle_positions < upper)).all(dim=-1) + else: + return self.link.check_points_in_volume(particle_positions) + + def _generate_condition(self, condition_type, value): + """ + Generates a valid condition function given @condition_type and its corresponding @value + + Args: + condition_type (ParticleModifyCondition): Type of condition to generate + value (any): Corresponding value whose type depends on @condition_type: + + SATURATED: string name of the desired system that this modifier must be saturated by, e.g., "water" + TOGGLEDON: boolean T/F; whether this modifier must be toggled on or not + GRAVITY: boolean T/F; whether this modifier must be pointing downwards (T) or upwards (F) + FUNCTION: a function, whose signature is as follows: + + def condition(obj) --> bool + + Where @obj is the specific object that this ParticleModifier state belongs to. + + Returns: + function: Condition function whose signature is identical to FUNCTION listed above + """ + # Avoid circular imports + from omnigibson.object_states.saturated import Saturated + + if condition_type == ParticleModifyCondition.FUNCTION: + cond = value + elif condition_type == ParticleModifyCondition.SATURATED: + cond = lambda obj: self.obj.scene.is_system_active(value) and obj.states[Saturated].get_value( + self.obj.scene.get_system(value) + ) + elif condition_type == ParticleModifyCondition.TOGGLEDON: + cond = lambda obj: obj.states[ToggledOn].get_value() == value + elif condition_type == ParticleModifyCondition.GRAVITY: + # Particles spawn in negative z-axis direction, so check positive dot product of link frame with global + cond = ( + lambda obj: ( + th.dot( + T.quat2mat(obj.states[self.__class__].link.get_position_orientation()[1]) + @ th.tensor([0, 0, 1], dtype=th.float32), + th.tensor([0, 0, 1], dtype=th.float32), + ) + > 0 + ) + == value + ) + else: + raise ValueError(f"Got invalid ParticleModifyCondition: {condition_type}") + return cond + + def _parse_conditions(self, conditions): + """ + Parse conditions and store them internally + + Args: + conditions (dict): Dictionary mapping the names of ParticleSystem (str) to None or list of 2-tuples, where + None represents "never", empty list represents "always", or each 2-tuple is interpreted as a single condition in the form of + (ParticleModifyCondition, value) necessary in order for this particle modifier to be + able to modify particles belonging to @ParticleSystem. Expected types of val are as follows: + + SATURATED: string name of the desired system that this modifier must be saturated by, e.g., "water" + TOGGLEDON: boolean T/F; whether this modifier must be toggled on or not + GRAVITY: boolean T/F; whether this modifier must be pointing downwards (T) or upwards (F) + FUNCTION: a function, whose signature is as follows: + + def condition(obj) --> bool + + Where @obj is the specific object that this ParticleModifier state belongs to. + + For a given ParticleSystem, the list of 2-tuples will be converted into a list of function calls of the + form above -- if all of its conditions evaluate to True and particles are detected within + this particle modifier area, then we potentially modify those particles + + Returns: + dict: Dictionary mapping the names of ParticleSystem (str) to list of condition functions + """ + parsed_conditions = dict() + # Standardize the conditions (make sure every system has at least one condition, which to make sure + # the particle modifier isn't already limited with the specific number of particles) + for system_name, conds in conditions.items(): + # Make sure the system is supported + assert self.obj.scene.is_visual_particle_system(system_name) or self.obj.scene.is_physical_particle_system( + system_name + ), f"Unsupported system for ParticleModifier: {system_name}" + # Make sure conds isn't empty and is a list + if conds is None: + continue + assert type(conds) is list, f"Expected list of conditions for system {system_name}, got {conds}" + system_conditions = [] + for cond_type, cond_val in conds: + cond = self._generate_condition(condition_type=cond_type, value=cond_val) + system_conditions.append(cond) + # Always add limit condition at the end + system_conditions.append(self._generate_limit_condition(system_name)) + parsed_conditions[system_name] = system_conditions + + return parsed_conditions + + @abstractmethod + def _modify_particles(self, system): + """ + Helper function to modify any particles belonging to @system. + + NOTE: This should handle both cases for @self.method: + + ParticleModifyMethod.ADJACENCY: modify any particles that are overlapping within the relaxed AABB + defining adjacency to this object's modification link. + ParticleModifyMethod.PROJECTION: modify any particles that are overlapping within the projection mesh. + + Must be implemented by subclass. + + Args: + system (BaseSystem): Particle system whose corresponding particles will be checked for modification + """ + raise NotImplementedError() + + def _generate_limit_condition(self, system_name): + """ + Generates a limit function condition for specific system of name @system_name + + Args: + system_name (str): Name of the particle system for which to generate a limit checker function + + Returns: + function: Limit checker function, with signature condition(obj) --> bool, where @obj is the specific object + that this ParticleModifier state belongs to + """ + system = self.obj.scene.get_system(system_name, force_init=False) + + def condition(obj): + return not self.obj.states[Saturated].get_value(system=system) + + return condition + + def supports_system(self, system_name): + """ + Checks whether this particle modifier supports adding/removing a particle from the specified + system, e.g. whether there exists any configuration (toggled on, etc.) in which this modifier + can be used to interact with any particles of this system. + + Args: + system_name (str): Name of the particle system to check + + Returns: + bool: Whether this particle modifier can add or remove a particle from the specified system + """ + return system_name in self.conditions + + def check_conditions_for_system(self, system_name): + """ + Checks whether this particle modifier can add or remove a particle from the specified system + in its current configuration, e.g. all of the conditions for addition/removal other than + physical position are met. + + Args: + system_name (str): Name of the particle system to check + + Returns: + bool: Whether this particle modifier can add or remove a particle from the specified system + """ + if not self.supports_system(system_name): + return False + return all(condition(self.obj) for condition in self.conditions[system_name]) + + def _update(self): + # Check if there's any overlap and if we're at the correct step + if self._current_step == 0: + # Iterate over all systems to check + for system_name in self.systems_to_check: + if system_name in self.conditions: + # Check if all conditions are met + if self.check_conditions_for_system(system_name): + system = self.obj.scene.get_system(system_name) + # Sanity check to see if the modifier has reached its limit for this system + if self.obj.states[Saturated].get_value(system=system): + continue + # Potentially modify particles within the volume + self._modify_particles(system=system) + + # Update the current step + self._current_step = (self._current_step + 1) % self.n_steps_per_modification + + # Add this object to the current state update set in its scene + self.obj.state_updated() + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.update({AABB, Saturated, ModifiedParticles}) + return deps + + @classmethod + def get_optional_dependencies(cls): + deps = super().get_optional_dependencies() + deps.update({Covered, ToggledOn, ContactParticles}) + return deps + + @classproperty + def requires_overlap(self): + """ + Returns: + bool: Whether overlap checks should be executed as a guard condition against modifying particles + """ + raise NotImplementedError() + + @property + def systems_to_check(self): + """ + Returns: + tuple of str: System names that should be actively checked for particle modification at the current timestep + """ + # Default is all supported active systems + # Exclude MicroParticleSystems when GPU dynamics is disabled + if not gm.USE_GPU_DYNAMICS: + return tuple( + name + for name, system in self.obj.scene.active_systems.items() + if not isinstance(system, MicroParticleSystem) + ) + return tuple(self.obj.scene.active_systems.keys()) + + @property + def projection_is_active(self): + """ + Returns: + bool: If using ParticleModifyMethod.PROJECTION, should return whether the projection mesh is currently + active or not (e.g.: whether all conditions are met for a projection modification to potentially occur) + """ + # Return True by default + return True + + @property + def n_steps_per_modification(self): + """ + Returns: + int: How many steps to take in between potentially modifying particles within the simulation + """ + raise NotImplementedError() + + @property + def visual_particle_modification_limit(self): + """ + Returns: + int: Maximum number of visual particles from a specific system that can be modified by this object + """ + raise NotImplementedError() + + @property + def physical_particle_modification_limit(self): + """ + Returns: + int: Maximum number of physical particles from a specific system that can be modified by this object + """ + raise NotImplementedError() + + @property + def state_size(self): + # Only store the current_step + return 1 + + def _dump_state(self): + return dict(current_step=int(self._current_step)) + + def _load_state(self, state): + self._current_step = state["current_step"] + + def serialize(self, state): + return th.tensor([state["current_step"]], dtype=th.float32) + + def deserialize(self, state): + current_step = int(state[0]) + state_dict = dict(current_step=current_step) + + return state_dict, 1 + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("ParticleModifier") + return classes + + +class ParticleRemover(ParticleModifier): + """ + ParticleModifier where the modification results in potentially removing particles from the simulation. + + Args: + obj (StatefulObject): Object to which this state will be applied + conditions (dict): Dictionary mapping the names of ParticleSystem (str) to None or list of 2-tuples, where + None represents "never", empty list represents "always", or each 2-tuple is interpreted as a single condition in the form of + (ParticleModifyCondition, value) necessary in order for this particle modifier to be + able to modify particles belonging to @ParticleSystem. Expected types of val are as follows: + + SATURATED: string name of the desired system that this modifier must be saturated by, e.g., "water" + TOGGLEDON: boolean T/F; whether this modifier must be toggled on or not + GRAVITY: boolean T/F; whether this modifier must be pointing downwards (T) or upwards (F) + FUNCTION: a function, whose signature is as follows: + + def condition(obj) --> bool + + Where @obj is the specific object that this ParticleModifier state belongs to. + + For a given ParticleSystem, the list of 2-tuples will be converted into a list of function calls of the + form above -- if all of its conditions evaluate to True and particles are detected within + this particle modifier area, then we potentially modify those particles + method (ParticleModifyMethod): Method to modify particles. Current options supported are ADJACENCY (i.e.: + "touching" particles) or PROJECTION (i.e.: "spraying" particles) + projection_mesh_params (None or dict): If specified and @method is ParticleModifyMethod.PROJECTION, + manually overrides any data inferred directly from this object to infer what projection volume to generate + for this particle modifier. Expected entries are as follows: + + "type": (str), one of {"Cylinder", "Cone", "Cube", "Sphere"} + "extents": (3-array), the (x,y,z) extents of the generated volume (specified in local link frame!) + + If None, information found from @obj.metadata will be used instead. + NOTE: x-direction should align with the projection mesh's height (i.e.: z) parameter in @extents! + default_fluid_conditions (None or list): Condition(s) needed to remove any fluid particles not explicitly + specified in @conditions. If None, then it is assumed that no other physical particles can be removed. If + not None, should be in same format as an entry in @conditions, i.e.: list of (ParticleModifyCondition, val) + 2-tuples + default_non_fluid_conditions (None or list): Condition(s) needed to remove any physical (excluding fluid) + particles not explicitly specified in @conditions. If None, then it is assumed that no other physical + particles can be removed. If not None, should be in same format as an entry in @conditions, i.e.: list of + (ParticleModifyCondition, val) 2-tuples + default_visual_conditions (None or list): Condition(s) needed to remove any visual particles not explicitly + specified in @conditions. If None, then it is assumed that no other visual particles can be removed. If + not None, should be in same format as an entry in @conditions, i.e.: list of (ParticleModifyCondition, val) + 2-tuples + """ + + def __init__( + self, + obj, + conditions, + method=ParticleModifyMethod.ADJACENCY, + projection_mesh_params=None, + default_fluid_conditions=None, + default_non_fluid_conditions=None, + default_visual_conditions=None, + ): + # Store values + self._default_fluid_conditions = ( + default_fluid_conditions + if default_fluid_conditions is None + else [self._generate_condition(cond_type, cond_val) for cond_type, cond_val in default_fluid_conditions] + ) + self._default_non_fluid_conditions = ( + default_non_fluid_conditions + if default_non_fluid_conditions is None + else [self._generate_condition(cond_type, cond_val) for cond_type, cond_val in default_non_fluid_conditions] + ) + self._default_visual_conditions = ( + default_visual_conditions + if default_visual_conditions is None + else [self._generate_condition(cond_type, cond_val) for cond_type, cond_val in default_visual_conditions] + ) + + # Run super + super().__init__(obj=obj, conditions=conditions, method=method, projection_mesh_params=projection_mesh_params) + + def _parse_conditions(self, conditions): + # Run super first + parsed_conditions = super()._parse_conditions(conditions=conditions) + + # Create set of default system to condition mappings based on settings + all_conditions = dict() + for system_name in self.obj.scene.available_systems.keys(): + # If the system is already explicitly specified in conditions, continue + if system_name in conditions: + continue + # Since fluid system is a subclass of physical system, we need to check for fluid first + elif self.obj.scene.is_fluid_system(system_name): + default_system_conditions = self._default_fluid_conditions + elif self.obj.scene.is_physical_particle_system(system_name): + default_system_conditions = self._default_non_fluid_conditions + elif self.obj.scene.is_visual_particle_system(system_name): + default_system_conditions = self._default_visual_conditions + else: + # Don't process any other systems, continue + continue + if default_system_conditions is not None: + # Always make sure to add on condition for checking count of particles (can't remove any particles if + # there are 0 particles of the given system!) + all_conditions[system_name] = [ + self._generate_nonempty_system_condition(system_name), + self._generate_limit_condition(system_name), + ] + default_system_conditions + + # Overwrite conditions based on manually-specified ones + all_conditions.update(parsed_conditions) + + return all_conditions + + def _modify_particles(self, system): + # If the system has no particles, return + if system.n_particles == 0: + return + + # Check the system + if self.obj.scene.is_visual_particle_system(system_name=system.name): + # Iterate over all particles and remove any that are within the relaxed AABB of the remover volume + particle_positions = system.get_particles_position_orientation()[0] + inbound_idxs = self._check_in_mesh(particle_positions).nonzero() + modification_limit = self.visual_particle_modification_limit + + # Physical system + else: + # If the object is a cloth, we have to use check_in_mesh with the relaxed AABB since we can't detect + # collisions via scene query interface. Alternatively, if we're using the projection method, + # we also need to use check_in_mesh to check for overlap with the projection mesh. + inbound_idxs = ( + self._check_in_mesh(system.get_particles_position_orientation()[0]).nonzero() + if self.obj.prim_type == PrimType.CLOTH or self.method == ParticleModifyMethod.PROJECTION + else th.tensor(list(self.obj.states[ContactParticles].get_value(system, self.link))) + ) + modification_limit = self.physical_particle_modification_limit + + n_modified_particles = self.obj.states[ModifiedParticles].get_value(system) + n_particles_absorbed = min(len(inbound_idxs), modification_limit - n_modified_particles) + system.remove_particles(inbound_idxs[:n_particles_absorbed]) + self.obj.states[ModifiedParticles].set_value(system, n_modified_particles + n_particles_absorbed) + + def _generate_nonempty_system_condition(self, system_name): + """ + Internal helper function to programatically generate a condition checker to make sure that at least one + particle exists in a given system + + Args: + system_name (str): Name of the system + + Returns: + function: Generated condition function with signature fcn(obj) --> bool, returning True if there is at least + one particle in the given system @system_name + """ + system = self.obj.scene.get_system(system_name, force_init=False) + return lambda obj: system.initialized and system.n_particles > 0 + + @property + def requires_overlap(self): + # No overlap check needed for particle removers + return False + + @classproperty + def meta_link_types(cls): + return [m.REMOVAL_META_LINK_TYPE] + + @classmethod + def requires_meta_link(cls, **kwargs): + # No meta link required for adjacency + return kwargs.get("method", ParticleModifyMethod.ADJACENCY) != ParticleModifyMethod.ADJACENCY + + @property + def _default_link(self): + # Only supported for adjacency, NOT projection + return self.obj.root_link if self.method == ParticleModifyMethod.ADJACENCY else None + + @property + def n_steps_per_modification(self): + return m.N_STEPS_PER_REMOVAL + + @property + def visual_particle_modification_limit(self): + return m.VISUAL_PARTICLES_REMOVAL_LIMIT + + @property + def physical_particle_modification_limit(self): + return m.PHYSICAL_PARTICLES_REMOVAL_LIMIT + + +class ParticleApplier(ParticleModifier): + """ + ParticleModifier where the modification results in potentially adding particles into the simulation. + + Args: + obj (StatefulObject): Object to which this state will be applied + conditions (dict): Dictionary mapping the names of ParticleSystem (str) to None or list of 2-tuples, where + None represents "never", empty list represents "always", or each 2-tuple is interpreted as a single condition in the form of + (ParticleModifyCondition, value) necessary in order for this particle modifier to be + able to modify particles belonging to @ParticleSystem. Expected types of val are as follows: + + SATURATED: string name of the desired system that this modifier must be saturated by, e.g., "water" + TOGGLEDON: boolean T/F; whether this modifier must be toggled on or not + GRAVITY: boolean T/F; whether this modifier must be pointing downwards (T) or upwards (F) + FUNCTION: a function, whose signature is as follows: + + def condition(obj) --> bool + + Where @obj is the specific object that this ParticleModifier state belongs to. + + For a given ParticleSystem, the list of 2-tuples will be converted into a list of function calls of the + form above -- if all of its conditions evaluate to True and particles are detected within + this particle modifier area, then we potentially modify those particles + method (ParticleModifyMethod): Method to modify particles. Current options supported are ADJACENCY (i.e.: + "touching" particles) or PROJECTION (i.e.: "spraying" particles) + projection_mesh_params (None or dict): If specified and @method is ParticleModifyMethod.PROJECTION, + manually overrides any data inferred directly from this object to infer what projection volume to generate + for this particle modifier. Expected entries are as follows: + + "type": (str), one of {"Cylinder", "Cone", "Cube", "Sphere"} + "extents": (3-array), the (x,y,z) extents of the generated volume (specified in local link frame!) + + If None, information found from @obj.metadata will be used instead. + sample_with_raycast (bool): If True, will only sample particles at raycast hits. Otherwise, will bypass sampling + and immediately sample particles at the sampled particle locations. Note that this will only work + for PhysicalParticleSystem-based ParticleAppliers that use the Projection method! + initial_speed (float): For physical particles, the initial speed for generated particles. Note that the + direction of the velocity is inferred from the particle sampling process. + """ + + def __init__( + self, + obj, + conditions, + method=ParticleModifyMethod.ADJACENCY, + projection_mesh_params=None, + sample_with_raycast=True, + initial_speed=0.0, + ): + # Store internal value + self._sample_particle_locations = None + self._sample_with_raycast = sample_with_raycast + self._initial_speed = initial_speed + + # Pre-cached values for where particles should be spawned, and in what direction, when this state is + # initialized so we can quickly spawn them at runtime + self._in_mesh_local_particle_positions = None + self._in_mesh_local_particle_directions = None + + self.projection_system = None + self.projection_system_prim = None + self.projection_emitter = None + + # TODO: particle visualization module has been deprecated since Isaac 4.2.0 + # this is a placeholder to replace a part of the visualization code + self._projection_is_active = False + + # Run super + super().__init__(obj=obj, method=method, conditions=conditions, projection_mesh_params=projection_mesh_params) + + def _initialize(self): + # Run super + super()._initialize() + + system_name = list(self.conditions.keys())[0] + + # This will initialize the system if it's not initialized already. + system = self.obj.scene.get_system(system_name, force_init=gm.USE_GPU_DYNAMICS) + + # TODO: particle visualization module has been deprecated since Isaac 4.2.0 + # We need to find a new way for this visualization; keeping this code for now for future reference + if self.visualize and False: + assert self._projection_mesh_params["type"] in { + "Cylinder", + "Cone", + }, f"{self.__class__.__name__} visualization only supports Cylinder and Cone types!" + radius, height = ( + th.mean(self._projection_mesh_params["extents"][:2]) / 2.0, + self._projection_mesh_params["extents"][2], + ) + # Generate the projection visualization + particle_radius = ( + m.VISUAL_PARTICLE_PROJECTION_PARTICLE_RADIUS + if self.obj.scene.is_visual_particle_system(system_name=system.name) + else system.particle_radius + ) + + name_prefix = f"{self.obj.name}_{self.__class__.__name__}" + # Create the projection visualization if it doesn't already exist, otherwise we reference it directly + projection_name = f"{name_prefix}_projection_visualization" + projection_path = f"/OmniGraph/{projection_name}" + projection_visualization_path = f"{self.link.prim_path}/projection_visualization" + if lazy.isaacsim.core.utils.prims.is_prim_path_valid(projection_path): + self.projection_system = lazy.isaacsim.core.utils.prims.get_prim_at_path(projection_path) + self.projection_emitter = lazy.isaacsim.core.utils.prims.get_prim_at_path(f"{projection_path}/emitter") + else: + self.projection_system, self.projection_emitter = create_projection_visualization( + scene=self.obj.scene, + prim_path=projection_visualization_path, + shape=self._projection_mesh_params["type"], + projection_name=projection_name, + projection_radius=radius, + projection_height=height, + particle_radius=particle_radius, + parent_scale=self.link.scale, + material=system.material, + ) + relative_projection_system_path = absolute_prim_path_to_scene_relative( + self.obj.scene, self.projection_system.GetPrimPath().pathString + ) + self.projection_system_prim = BasePrim( + relative_prim_path=relative_projection_system_path, name=projection_name + ) + self.projection_system_prim.load(self.obj.scene) + + # Create the visual geom instance referencing the generated source mesh prim, and then hide it + relative_projection_source_path = absolute_prim_path_to_scene_relative( + self.obj.scene, projection_visualization_path + ) + self.projection_source_sphere = GeomPrim( + relative_prim_path=relative_projection_source_path, name=f"{name_prefix}_projection_source_sphere" + ) + self.projection_source_sphere.load(self.obj.scene) + self.projection_source_sphere.initialize() + self.projection_source_sphere.visible = False + # Rotate by 90 degrees in y-axis so that the projection visualization aligns with the projection mesh + self.projection_source_sphere.set_position_orientation( + orientation=T.euler2quat(th.tensor([0, math.pi / 2, 0], dtype=th.float32)), frame="parent" + ) + + # Make sure the meta mesh is aligned with the meta link if visualizing + # This corresponds to checking (a) position of tip of projection mesh should align with origin of + # metalink, and (b) zero relative orientation between the metalink and the projection mesh + local_pos, local_quat = self.projection_mesh.get_position_orientation(frame="parent") + assert th.all( + th.isclose(local_pos + th.tensor([0, 0, height / 2.0]), th.zeros_like(local_pos)) + ), "Projection mesh tip should align with metalink position!" + local_euler = T.quat2euler(local_quat) + assert th.all( + th.isclose(local_euler, th.zeros_like(local_euler)) + ), "Projection mesh orientation should align with metalink orientation!" + + # Store which method to use for sampling particle locations + if self._sample_with_raycast: + if self.method == ParticleModifyMethod.PROJECTION: + self._sample_particle_locations = self._sample_particle_locations_from_projection_volume + elif self.method == ParticleModifyMethod.ADJACENCY: + self._sample_particle_locations = self._sample_particle_locations_from_adjacency_area + else: + raise ValueError(f"Unsupported ParticleModifyMethod: {self.method}!") + else: + # Make sure we're only using a physical particle system and the projection method + assert isinstance( + system, PhysicalParticleSystem + ), "If not sampling with raycast, ParticleApplier only supports PhysicalParticleSystems!" + assert ( + self.method == ParticleModifyMethod.PROJECTION + ), "If not sampling with raycast, ParticleApplier only supports ParticleModifyMethod.PROJECTION method!" + # Compute particle spawning information once + self._compute_particle_spawn_information(system=system) + + def _parse_conditions(self, conditions): + # Run super first + parsed_conditions = super()._parse_conditions(conditions=conditions) + + # sanity check to make sure only one system is being applied, since unlike a ParticleRemover, which + # can potentially remove multiple types of particles, a ParticleApplier should only apply one type of particle + assert len(parsed_conditions) == 1, ( + f"A ParticleApplier can only have a single ParticleSystem associated " + f"with it! Got: {[system_name for system_name in self.conditions.keys()]}" + ) + + # Append an additional condition for checking overlaps if required + if self.requires_overlap: + system_name = next(iter(parsed_conditions)) + parsed_conditions[system_name].append(lambda obj: self._check_overlap()) + + return parsed_conditions + + def _compute_particle_spawn_information(self, system): + """ + Helper function to compute where particles should be spawned. This is to save computation time at runtime + if @self._sample_with_raycast is False, meaning that we were deterministically sample particles. + + Args: + system (BaseSystem): Particle system whose particles will be spawned from this ParticleApplier + """ + # We now pre-compute local particle positions that are within the projection mesh used to infer spawn pos + # We sample over the entire object AABB, assuming most will be filtered out + sampling_distance = 2 * system.particle_radius + extent = self._projection_mesh_params["extents"] + h = extent[2] + low, high = self.obj.aabb + n_particles_per_axis = ((high - low) / sampling_distance).int() + assert th.all( + n_particles_per_axis + ), f"link {self.link.name} is too small to sample any particle of radius {system.particle_radius}." + # 1e-10 is added because the extent might be an exact multiple of particle radius + arrs = [ + th.arange(l + system.particle_radius, h - system.particle_radius + 1e-10, system.particle_radius * 2) + for l, h, n in zip(low, high, n_particles_per_axis) + ] + # Generate 3D-rectangular grid of points, and only keep the ones inside the mesh + points = th.stack([arr.flatten() for arr in th.meshgrid(*arrs)]).T + pos, quat = self.link.get_position_orientation() + points = points[th.where(self._check_in_mesh(points))[0]] + # Convert the points into local frame + points_in_local_frame = get_particle_positions_in_frame( + pos=pos, + quat=quat, + scale=self.obj.scale, + particle_positions=points, + ) + n_max_particles = self._get_max_particles_limit_per_step(system=system) + # Potentially sub-sample points based on max particle limit per step + self._in_mesh_local_particle_positions = ( + points_in_local_frame + if n_max_particles > len(points) + else points_in_local_frame[th.randperm(len(points_in_local_frame))[:n_max_particles]] + ) + # Also programmatically compute the directions of each particle position -- this is the normalized + # vector pointing from source to the particle + projection_type = self._projection_mesh_params["type"] + if projection_type == "Cone": + # Particles point from source ([0, 0, 0]) to point location + directions = th.clone(self._in_mesh_local_particle_positions) + elif projection_type == "Cylinder": + # All particle points in the same parallel direction towards the -z direction + directions = th.zeros_like(self._in_mesh_local_particle_positions) + directions[:, 2] = -h + else: + raise ValueError( + "If not sampling with raycast, ParticleApplier only supports `Cone` or `Cylinder` projection types!" + ) + self._in_mesh_local_particle_directions = directions / th.norm(directions, dim=-1).reshape(-1, 1) + + def _update(self): + # If we're about to check for modification, update whether it the visualization should be active or not + if self.visualize and self._current_step == 0: + # Only one system in our conditions, so next(iter()) suffices + is_active = all(condition(self.obj) for condition in next(iter(self.conditions.values()))) + # TODO: particle visualization module has been deprecated since Isaac 4.2.0 + # We need to find a new way for this visualization; keeping this code for now for future reference + # self.projection_emitter.GetProperty("inputs:active").Set(is_active) + self._projection_is_active = is_active + + # Run super + super()._update() + + def remove(self): + # We need to remove the projection visualization if it exists + if self.projection_system_prim is not None: + og.sim.remove_prim(self.projection_system_prim) + + def _modify_particles(self, system): + if self._sample_with_raycast: + # Sample potential locations to apply particles, and then apply them + start_points, end_points = self._sample_particle_locations(system=system) + n_samples = len(start_points) + is_visual = self.obj.scene.is_visual_particle_system(system_name=system.name) + + if is_visual: + group = system.get_group_name(obj=self.obj) + # Create an attachment group if necessary + if group not in system.groups: + system.create_attachment_group(obj=self.obj) + avg_scale = th.pow(th.prod(self.obj.scale), 1 / 3) + scales = system.sample_scales_by_group(group=group, n=len(start_points)) + cuboid_dimensions = scales * system.particle_object.aabb_extent.reshape(1, 3) * avg_scale + else: + scales = None + cuboid_dimensions = th.zeros(3) + + # Sample the rays to see where particle can be generated + results = sample_cuboid_on_object( + obj=None, + start_points=start_points.reshape(n_samples, 1, 3), + end_points=end_points.reshape(n_samples, 1, 3), + cuboid_dimensions=cuboid_dimensions, + ignore_objs=[self.obj], + hit_proportion=0.0, # We want all hits + cuboid_bottom_padding=( + macros.utils.sampling_utils.DEFAULT_CUBOID_BOTTOM_PADDING if is_visual else system.particle_radius + ), + undo_cuboid_bottom_padding=is_visual, # micro particles have zero cuboid dimensions so we need to maintain padding + verify_cuboid_empty=False, + ) + + hits = [result for result in results if result[0] is not None] + scales = ( + [scale for scale, result in zip(scales, results) if result[0] is not None] + if scales is not None + else scales + ) + + self._apply_particles_at_raycast_hits(system=system, hits=hits, scales=scales) + else: + self._apply_particles_in_projection_volume(system=system) + + def _apply_particles_at_raycast_hits(self, system, hits, scales=None): + """ + Helper function to apply particles from system @system given raycast hits @hits, + which are the filtered results from omnigibson.utils.sampling_utils.raytest_batch that include only + the results with a valid hit + + Args: + system (BaseSystem): System to apply particles from + hits (list of dict): Valid hit results from a batched raycast representing locations for sampling particles + scales (list of numpy arrays or None): None or scales of the particles that should be sampled, same length as hits + """ + assert system.name in self.conditions, f"System {system.name} is not defined in the conditions." + # Check the system + n_modified_particles = self.obj.states[ModifiedParticles].get_value(system) + if self.obj.scene.is_visual_particle_system(system_name=system.name): + assert scales is not None, "applying visual particles at raycast hits requires scales." + assert len(hits) == len(scales), "length of hits and scales are different when spawning visual particles." + # Sample potential application points + z_up = th.zeros(3) + z_up[-1] = 1.0 + n_particles = min(len(hits), m.VISUAL_PARTICLES_APPLICATION_LIMIT - n_modified_particles) + # Generate particle info -- maps group name to particle info for that group, + # i.e.: positions, orientations, and link_prim_paths + particles_info = defaultdict(lambda: defaultdict(lambda: [])) + modifier_avg_scale = th.pow(th.prod(self.obj.scale), 1 / 3) + for hit, scale in zip(hits[:n_particles], scales[:n_particles]): + # Infer which object was hit + hit_obj = self.obj.scene.object_registry("prim_path", "/".join(hit[3].split("/")[:-1]), None) + if hit_obj is not None: + # Create an attachment group if necessary + group = system.get_group_name(obj=hit_obj) + if group not in system.groups: + system.create_attachment_group(obj=hit_obj) + # Add to info + particles_info[group]["positions"].append(hit[0]) + particles_info[group]["orientations"].append(hit[2]) + # Since particles' scales are sampled with respect to the modifier object, but are being placed + # (in the USD hierarchy) underneath the in_contact object, we need to compensate for the relative + # scale differences between the two objects, so that "moving" the particle to the new object won't + # cause it to unexpectedly shrink / grow based on that parent's (potentially) different scale + particles_info[group]["scales"].append( + scale * modifier_avg_scale / th.pow(th.prod(hit_obj.scale), 1 / 3) + ) + particles_info[group]["link_prim_paths"].append(hit[3]) + # Generate all the particles for each group + for group, particle_info in particles_info.items(): + # Generate particles for this group + system.generate_group_particles( + group=group, + positions=th.stack(particle_info["positions"], dim=0), + orientations=th.stack(particle_info["orientations"], dim=0), + scales=th.stack(particles_info[group]["scales"], dim=0), + link_prim_paths=particle_info["link_prim_paths"], + ) + # Update our particle count + self.obj.states[ModifiedParticles].set_value( + system, n_modified_particles + len(particle_info["link_prim_paths"]) + ) + + # Physical system + else: + # Compile the particle poses to generate and sample the particles + n_particles = min(len(hits), m.PHYSICAL_PARTICLES_APPLICATION_LIMIT - n_modified_particles) + # Generate particles + if n_particles > 0: + velocities = ( + None + if self._initial_speed == 0 + else -self._initial_speed * th.stack([hit[1] for hit in hits[:n_particles]]) + ) + system.generate_particles( + positions=th.stack([hit[0] for hit in hits[:n_particles]]), + velocities=velocities, + ) + # Update our particle count + self.obj.states[ModifiedParticles].set_value(system, n_modified_particles + n_particles) + + def _apply_particles_in_projection_volume(self, system): + """ + Helper function to apply particles form system @system within the projection volume owned by this + ParticleApplier. + + NOTE: This function only supports PhysicalParticleSystems and ParticleModifyMethod.PROJECTION method, which + should have been asserted during this ParticleApplier's initialize() call + + Args: + system (BaseSystem): System to apply particles from + """ + assert ( + self.method == ParticleModifyMethod.PROJECTION + ), "Can only apply particles within projection volume if ParticleModifyMethod.PROJECTION method is used!" + assert self.obj.scene.is_physical_particle_system( + system_name=system.name + ), "Can only apply particles within projection volume if system is PhysicalParticleSystem!" + + # Transform pre-cached particle positions into the world frame + pos, quat = self.link.get_position_orientation() + points = get_particle_positions_from_frame( + pos=pos, + quat=quat, + scale=self.obj.scale, + particle_positions=self._in_mesh_local_particle_positions, + ) + directions = self._in_mesh_local_particle_directions @ T.quat2mat(quat).T + + # Compile the particle poses to generate and sample the particles + n_modified_particles = self.obj.states[ModifiedParticles].get_value(system) + n_particles = min(len(points), m.PHYSICAL_PARTICLES_APPLICATION_LIMIT - n_modified_particles) + # Generate particles + if n_particles > 0: + velocities = None if self._initial_speed == 0 else self._initial_speed * directions[:n_particles] + system.generate_particles( + positions=points[:n_particles], + velocities=velocities, + ) + # Update our particle count + self.obj.states[ModifiedParticles].set_value(system, n_modified_particles + n_particles) + + def _sample_particle_locations_from_projection_volume(self, system): + """ + Helper function for generating potential particle locations from projection volume + + Args: + system (BaseSystem): System to sample potential particle positions for + + Returns: + 2-tuple: + - (n, 3) array: Ray start points to sample + - (n, 3) array: Ray end points to sample + """ + # Randomly sample end points from the base of the cone / cylinder + n_samples = self._get_max_particles_limit_per_step(system=system) + r, h = self._projection_mesh_params["extents"][0] / 2, self._projection_mesh_params["extents"][2] + sampled_r_theta = th.rand(n_samples, 2) + sampled_r_theta = sampled_r_theta * th.tensor([r, math.pi * 2]).reshape(1, 2) + # Get start, end points in local link frame, start points to end points along the -z direction + end_points = th.stack( + [ + sampled_r_theta[:, 0] * th.cos(sampled_r_theta[:, 1]), + sampled_r_theta[:, 0] * th.sin(sampled_r_theta[:, 1]), + -h * th.ones(n_samples), + ], + dim=1, + ) + projection_type = self._projection_mesh_params["type"] + if projection_type == "Cone": + # All start points are the cone tip, which is the local link origin + start_points = th.zeros((n_samples, 3)) + elif projection_type == "Cylinder": + # All start points are the parallel point for their corresponding end point + # i.e.: (x, y, 0) + start_points = end_points + th.tensor([0, 0, h]).reshape(1, 3) + else: + # Other types not supported + raise ValueError(f"Unsupported projection mesh type: {projection_type}!") + + # Convert sampled normalized radius and angle into 3D points + # We convert r, theta --> 3D point in local link frame --> 3D point in global world frame + # We also combine start and end points for efficiency when doing the transform, then split them up again + points = th.cat([start_points, end_points], dim=0) + pos, quat = self.link.get_position_orientation() + points = get_particle_positions_from_frame( + pos=pos, + quat=quat, + scale=self.obj.scale, + particle_positions=points, + ) + + return points[:n_samples, :], points[n_samples:, :] + + def _sample_particle_locations_from_adjacency_area(self, system): + """ + Helper function for generating potential particle locations from adjacency area + + Args: + system (BaseSystem): System to sample potential particle positions for + + Returns: + 2-tuple: + - (n, 3) array: Ray start points to sample + - (n, 3) array: Ray end points to sample + """ + # Randomly sample end points from within the object's AABB + n_samples = self._get_max_particles_limit_per_step(system=system) + lower, upper = self.link.visual_aabb + lower = lower.reshape(1, 3) - m.PARTICLE_MODIFIER_ADJACENCY_AREA_MARGIN + upper = upper.reshape(1, 3) + m.PARTICLE_MODIFIER_ADJACENCY_AREA_MARGIN + lower_upper = th.cat([lower, upper], dim=0) + + # Sample in all directions, shooting from the center of the link / object frame + pos = self.link.get_position_orientation()[0] + start_points = th.ones((n_samples, 3)) * pos.reshape(1, 3) + end_points = th.rand(n_samples, 3) * (upper - lower) + lower + sides, axes = th.randint(2, size=(n_samples,)), th.randint(3, size=(n_samples,)) + end_points[th.arange(n_samples), axes] = lower_upper[sides, axes] + + return start_points, end_points + + def _get_max_particles_limit_per_step(self, system): + """ + Helper function for grabbing the maximum particle limit per step + + Args: + system (BaseSystem): System for which to get max particle limit per step + + Returns: + int: Maximum particles to apply per step for the given system @system + """ + assert system.name in self.conditions, f"System {system.name} is not defined in the conditions." + return ( + m.MAX_VISUAL_PARTICLES_APPLIED_PER_STEP + if self.obj.scene.is_visual_particle_system(system_name=system.name) + else m.MAX_PHYSICAL_PARTICLES_APPLIED_PER_STEP + ) + + @property + def requires_overlap(self): + # Overlap required only if sampling with raycast + return self._sample_with_raycast + + @property + def visualize(self): + """ + Returns: + bool: Whether this Applier should be visualized or not + """ + # Visualize if projection method is used + return self.method == ParticleModifyMethod.PROJECTION + + @property + def systems_to_check(self): + # Only should check active systems in the owned conditions + active_systems = super().systems_to_check + return tuple(name for name in self.conditions.keys() if name in active_systems) + + @property + def projection_is_active(self): + # TODO: particle visualization module has been deprecated since Isaac 4.2.0 + # We need to find a new way for this visualization; keeping this code for now for future reference + # # Only active if the projection mesh is enabled + # return self.projection_emitter.GetProperty("inputs:active").Get() + return self._projection_is_active + + @classproperty + def meta_link_types(cls): + return [m.APPLICATION_META_LINK_TYPE] + + @classmethod + def requires_meta_link(cls, **kwargs): + # No meta link required for adjacency + return kwargs.get("method", ParticleModifyMethod.ADJACENCY) != ParticleModifyMethod.ADJACENCY + + @classmethod + def is_compatible(cls, obj, **kwargs): + # Run super first + compatible, reason = super().is_compatible(obj, **kwargs) + if not compatible: + return compatible, reason + + return True, None + + @property + def _default_link(self): + # Only supported for adjacency, NOT projection + return self.obj.root_link if self.method == ParticleModifyMethod.ADJACENCY else None + + @property + def n_steps_per_modification(self): + return m.N_STEPS_PER_APPLICATION + + @property + def visual_particle_modification_limit(self): + return m.VISUAL_PARTICLES_APPLICATION_LIMIT + + @property + def physical_particle_modification_limit(self): + return m.PHYSICAL_PARTICLES_APPLICATION_LIMIT diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/particle_source_or_sink.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/particle_source_or_sink.py new file mode 100644 index 0000000000000000000000000000000000000000..5cd8e8cb7c5eefb5a1a10d867d09b729640ad395 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/particle_source_or_sink.py @@ -0,0 +1,252 @@ +import math + +import torch as th + +import omnigibson as og +from omnigibson.macros import create_module_macros +from omnigibson.object_states.particle_modifier import ParticleApplier, ParticleRemover +from omnigibson.utils.constants import ParticleModifyMethod +from omnigibson.utils.python_utils import classproperty + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# Meta link naming prefixes +m.SOURCE_META_LINK_TYPE = "particlesource" +m.SINK_META_LINK_TYPE = "particlesink" + +# Default radius and height +m.DEFAULT_SOURCE_RADIUS = 0.0125 +m.DEFAULT_SOURCE_HEIGHT = 0.05 +m.DEFAULT_SINK_RADIUS = 0.05 +m.DEFAULT_SINK_HEIGHT = 0.05 + +# Maximum number of particles that can be sourced / sunk per step +m.MAX_SOURCE_PARTICLES_PER_STEP = 1000 +m.MAX_SINK_PARTICLES_PER_STEP = 1000 + +# How many steps between sinking particles +m.N_STEPS_PER_SINK = 5 + +# Upper limit to number of particles that can be sourced / sunk globally by a single object +m.SOURCE_PARTICLES_LIMIT = 1e6 +m.SINK_PARTICLES_LIMIT = 1e6 + + +class ParticleSource(ParticleApplier): + """ + ParticleApplier where physical particles are spawned continuously in a cylindrical fashion from the + meta link pose. + + Args: + obj (StatefulObject): Object to which this state will be applied + conditions (dict): Dictionary mapping the names of ParticleSystem (str) to None or list of 2-tuples, where + None represents "never", empty list represents "always", or each 2-tuple is interpreted as a single condition in the form of + (ParticleModifyCondition, value) necessary in order for this particle modifier to be + able to modify particles belonging to @ParticleSystem. Expected types of val are as follows: + + SATURATED: string name of the desired system that this modifier must be saturated by, e.g., "water" + TOGGLEDON: boolean T/F; whether this modifier must be toggled on or not + GRAVITY: boolean T/F; whether this modifier must be pointing downwards (T) or upwards (F) + FUNCTION: a function, whose signature is as follows: + + def condition(obj) --> bool + + Where @obj is the specific object that this ParticleModifier state belongs to. + + For a given ParticleSystem, the list of 2-tuples will be converted into a list of function calls of the + form above -- if all of its conditions evaluate to True and particles are detected within + this particle modifier area, then we potentially modify those particles + source_radius (None or float): Radius of the cylinder representing particles' spawning volume, if specified. + If both @source_radius and @source_height are None, values will be inferred directly from the underlying + object asset, otherwise, it will be set to a default value + source_height (None or float): Height of the cylinder representing particles' spawning volume, if specified. + If both @source_radius and @source_height are None, values will be inferred directly from the underlying + object asset, otherwise, it will be set to a default value + initial_speed (float): The initial speed for generated particles. Note that the + direction of the velocity is inferred from the particle sampling process + """ + + def __init__( + self, + obj, + conditions, + source_radius=None, + source_height=None, + initial_speed=0.0, + ): + # Initialize variables that will be filled in at runtime + self._n_steps_per_modification = None + + # Define projection mesh params based on input kwargs + if source_radius is not None or source_height is not None: + source_radius = m.DEFAULT_SOURCE_RADIUS if source_radius is None else source_radius + source_height = m.DEFAULT_SOURCE_HEIGHT if source_height is None else source_height + projection_mesh_params = { + "type": "Cylinder", + "extents": [source_radius * 2, source_radius * 2, source_height], + } + else: + projection_mesh_params = None + + # Convert inputs into arguments to pass to particle applier class + super().__init__( + obj=obj, + conditions=conditions, + method=ParticleModifyMethod.PROJECTION, + projection_mesh_params=projection_mesh_params, + sample_with_raycast=False, + initial_speed=initial_speed, + ) + + def _initialize(self): + # Run super first + super()._initialize() + + # Calculate how many steps we need in between particle cluster spawnings + # This is equivalent to the time it takes for a generated particle to travel @source_height distance + # Note that object state steps are discretized by og.sim.render_step + # Note: t derived from quadratic formula: height = 0.5 g t^2 + v0 t + # Note: height must be considered in the world frame, so we convert the distance from local into world frame + # Extents are in local frame, so we need to convert to world frame using link scale + distance = self.link.scale[2] * self._projection_mesh_params["extents"][2] + t = (-self._initial_speed + th.sqrt(self._initial_speed**2 + 2 * og.sim.gravity * distance)) / og.sim.gravity + self._n_steps_per_modification = math.ceil(1 + t / og.sim.get_sim_step_dt()) + + def _get_max_particles_limit_per_step(self, system): + # Check the system + assert self.obj.scene.is_physical_particle_system( + system_name=system.name + ), "ParticleSource only supports PhysicalParticleSystem" + return m.MAX_SOURCE_PARTICLES_PER_STEP + + @classmethod + def requires_meta_link(cls, **kwargs): + # Always requires meta link since projection is used + return True + + @property + def visualize(self): + # Don't visualize this source + return False + + @classproperty + def meta_link_types(cls): + return [m.SOURCE_META_LINK_TYPE] + + @property + def n_steps_per_modification(self): + return self._n_steps_per_modification + + @property + def physical_particle_modification_limit(self): + return m.SOURCE_PARTICLES_LIMIT + + +class ParticleSink(ParticleRemover): + """ + ParticleRemover where physical particles are removed continuously within a cylindrical volume located + at the meta link pose. + + Args: + obj (StatefulObject): Object to which this state will be applied + conditions (dict): Dictionary mapping the names of ParticleSystem (str) to None or list of 2-tuples, where + None represents "never", empty list represents "always", or each 2-tuple is interpreted as a single condition in the form of + (ParticleModifyCondition, value) necessary in order for this particle modifier to be + able to modify particles belonging to @ParticleSystem. Expected types of val are as follows: + + SATURATED: string name of the desired system that this modifier must be saturated by, e.g., "water" + TOGGLEDON: boolean T/F; whether this modifier must be toggled on or not + GRAVITY: boolean T/F; whether this modifier must be pointing downwards (T) or upwards (F) + FUNCTION: a function, whose signature is as follows: + + def condition(obj) --> bool + + Where @obj is the specific object that this ParticleModifier state belongs to. + + For a given ParticleSystem, the list of 2-tuples will be converted into a list of function calls of the + form above -- if all of its conditions evaluate to True and particles are detected within + this particle modifier area, then we potentially modify those particles + sink_radius (None or float): Radius of the cylinder representing particles' sinking volume, if specified. + If both @sink_radius and @sink_height are None, values will be inferred directly from the underlying + object asset, otherwise, it will be set to a default value + sink_height (None or float): Height of the cylinder representing particles' sinking volume, if specified. + If both @sink_radius and @sink_height are None, values will be inferred directly from the underlying + object asset, otherwise, it will be set to a default value + default_fluid_conditions (None or list): Condition(s) needed to remove any fluid particles not explicitly + specified in @conditions. If None, then it is assumed that no other physical particles can be removed. If + not None, should be in same format as an entry in @conditions, i.e.: list of (ParticleModifyCondition, val) + 2-tuples + default_non_fluid_conditions (None or list): Condition(s) needed to remove any physical (excluding fluid) + particles not explicitly specified in @conditions. If None, then it is assumed that no other physical + particles can be removed. If not None, should be in same format as an entry in @conditions, i.e.: list of + (ParticleModifyCondition, val) 2-tuples + default_visual_conditions (None or list): Condition(s) needed to remove any visual particles not explicitly + specified in @conditions. If None, then it is assumed that no other visual particles can be removed. If + not None, should be in same format as an entry in @conditions, i.e.: list of (ParticleModifyCondition, val) + 2-tuples + """ + + def __init__( + self, + obj, + conditions, + sink_radius=None, + sink_height=None, + default_fluid_conditions=None, + default_non_fluid_conditions=None, + default_visual_conditions=None, + ): + # Initialize variables that will be filled in at runtime + self._n_steps_per_modification = None + + # Define projection mesh params based on input kwargs + if sink_radius is not None or sink_height is not None: + sink_radius = m.DEFAULT_SINK_RADIUS if sink_radius is None else sink_radius + sink_height = m.DEFAULT_SINK_HEIGHT if sink_height is None else sink_height + projection_mesh_params = { + "type": "Cylinder", + "extents": [sink_radius * 2, sink_radius * 2, sink_height], + } + else: + projection_mesh_params = None + + # Convert inputs into arguments to pass to particle remover class + super().__init__( + obj=obj, + conditions=conditions, + method=ParticleModifyMethod.PROJECTION, + projection_mesh_params=projection_mesh_params, + default_fluid_conditions=default_fluid_conditions, + default_non_fluid_conditions=default_non_fluid_conditions, + default_visual_conditions=default_visual_conditions, + ) + + def _get_max_particles_limit_per_step(self, system): + # Check the system + assert self.obj.scene.is_physical_particle_system( + system_name=system.name + ), "ParticleSink only supports PhysicalParticleSystem" + return m.MAX_PHYSICAL_PARTICLES_SOURCED_PER_STEP + + @property + def requires_overlap(self): + # Not required, always sink particles + return False + + @classmethod + def requires_meta_link(cls, **kwargs): + # Always requires meta link since projection is used + return True + + @classproperty + def meta_link_types(cls): + return [m.SINK_META_LINK_TYPE] + + @property + def n_steps_per_modification(self): + return m.N_STEPS_PER_SINK + + @property + def physical_particle_modification_limit(self): + return m.SINK_PARTICLES_LIMIT diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/pose.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/pose.py new file mode 100644 index 0000000000000000000000000000000000000000..0d555526380650a09ac97a4e4d0d3340d4945bb1 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/pose.py @@ -0,0 +1,34 @@ +import torch as th + +from omnigibson.macros import create_module_macros +from omnigibson.object_states.object_state_base import AbsoluteObjectState + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.POSITIONAL_VALIDATION_EPSILON = 1e-10 +m.ORIENTATION_VALIDATION_EPSILON = 0.003 # ~5 degrees error tolerance + + +class Pose(AbsoluteObjectState): + def _get_value(self): + pos, orn = self.obj.get_position_orientation() + return pos, orn + + def _has_changed(self, get_value_args, value, info): + # Only changed if the squared distance between old position and current position has + # changed above some threshold + old_pos, old_quat = value + # Get current pose + current_pos, current_quat = self.get_value() + # Check position and orientation -- either changing means we've changed poses + dist_squared = th.sum(th.square(current_pos - old_pos)) + if dist_squared > m.POSITIONAL_VALIDATION_EPSILON: + return True + # Calculate quat distance simply as the dot product + # A * B = |A||B|cos(theta) + quat_cos_angle = th.abs(th.dot(old_quat, current_quat)) + if (1 - quat_cos_angle) > m.ORIENTATION_VALIDATION_EPSILON: + return True + + return False diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/robot_related_states.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/robot_related_states.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a2100fa096332abd48556b001c1958a507cb40 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/robot_related_states.py @@ -0,0 +1,72 @@ +from omnigibson.object_states.object_state_base import AbsoluteObjectState, BooleanStateMixin, RelativeObjectState +from omnigibson.sensors import VisionSensor + +_IN_REACH_DISTANCE_THRESHOLD = 2.0 + +_IN_FOV_PIXEL_FRACTION_THRESHOLD = 0.05 + + +class RobotStateMixin: + @property + def robot(self): + from omnigibson.robots.robot import Robot + + assert isinstance(self.obj, Robot), "This state only works with robots." + return self.obj + + +class IsGrasping(RelativeObjectState, BooleanStateMixin, RobotStateMixin): + def _get_value(self, obj): + # TODO: Make this work with non-assisted grasping + return any(self.robot._ag_obj_in_hand[arm] == obj for arm in self.robot.arm_names) + + +# class InReachOfRobot(AbsoluteObjectState, BooleanStateMixin): +# def _compute_value(self): +# robot = _get_robot(self.simulator) +# if not robot: +# return False + +# robot_pos = robot.get_position_orientation()[0] +# object_pos = self.obj.get_position_orientation()[0] +# return th.norm(object_pos - th.tensor(robot_pos)) < _IN_REACH_DISTANCE_THRESHOLD + + +# class InFOVOfRobot(AbsoluteObjectState, BooleanStateMixin): +# @staticmethod +# def get_optional_dependencies(): +# return AbsoluteObjectState.get_optional_dependencies() + [ObjectsInFOVOfRobot] + +# def _get_value(self): +# robot = _get_robot(self.simulator) +# if not robot: +# return False + +# body_ids = set(self.obj.get_body_ids()) +# return not body_ids.isdisjoint(robot.states[ObjectsInFOVOfRobot].get_value()) + + +class ObjectsInFOVOfRobot(AbsoluteObjectState, RobotStateMixin): + def _get_value(self): + """ + Gets all objects in the robot's field of view. + + Returns: + set: Set of objects in the robot's field of view + """ + if not any(isinstance(sensor, VisionSensor) for sensor in self.robot.sensors.values()): + raise ValueError("No vision sensors found on robot.") + objs = set() + names_to_exclude = set(["background", "unlabelled"]) + for sensor in self.robot.sensors.values(): + if isinstance(sensor, VisionSensor): + _, info = sensor.get_obs() + objs.update( + set( + self.obj.scene.object_registry("name", name) + for name in info["seg_instance"].values() + if name not in names_to_exclude + ) + ) + # Return all objects, minus any that were mapped to None because they were not found in our object registry + return objs - {None} diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/saturated.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/saturated.py new file mode 100644 index 0000000000000000000000000000000000000000..48656be9a76e71e7279096ec16957e304e13c228 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/saturated.py @@ -0,0 +1,293 @@ +import torch as th + +from omnigibson.macros import create_module_macros +from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState +from omnigibson.systems.system_base import UUID_TO_SYSTEM_NAME + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# Default saturation limit +m.DEFAULT_SATURATION_LIMIT = 1e6 + + +class ModifiedParticles(RelativeObjectState): + """ + Object state tracking number of modified particles for a given object + """ + + def __init__(self, obj): + # Run super first + super().__init__(obj=obj) + + # Set internal values + self.particle_counts = None + + def _initialize(self): + super()._initialize() + + # Set internal variables + self.particle_counts = dict() + + def _get_value(self, system): + # If system isn't stored, return 0, otherwise, return the actual value + return self.particle_counts.get(system.name, 0) + + def _set_value(self, system, new_value): + assert new_value >= 0, "Cannot set ModifiedParticles value to be less than 0!" + # Remove the value from the dictionary if we're setting it to zero (save memory) + if new_value == 0 and system.name in self.particle_counts: + self.particle_counts.pop(system.name) + else: + self.particle_counts[system.name] = new_value + + def _sync_systems(self, system_names): + """ + Helper function for forcing internal systems to be synchronized with external list of @systems. + + NOTE: This may override internal state + + Args: + system_names (list of str): List of system name(s) that should be actively tracked internally + """ + self.particle_counts = {name: -1 for name in system_names} + + @property + def state_size(self): + # Two entries per system (name + count) + number of systems + return len(self.particle_counts) * 2 + 1 + + def _dump_state(self): + state = dict(n_systems=len(self.particle_counts)) + for system_name, val in self.particle_counts.items(): + state[system_name] = val + return state + + def _load_state(self, state): + self.particle_counts = { + system_name: val for system_name, val in state.items() if system_name != "n_systems" and val > 0 + } + + def serialize(self, state): + state_flat = th.tensor([state["n_systems"]], dtype=th.float32) + if state["n_systems"] > 0: + system_names = tuple(state.keys())[1:] + system_uuid = [ + (self.obj.scene.get_system(system_name, force_init=False).uuid, state[system_name]) + for system_name in system_names + ] + system_uuid = th.tensor(system_uuid, dtype=th.float32).view(-1) + state_flat = th.cat([state_flat, system_uuid]) + return state_flat + + def deserialize(self, state): + n_systems = int(state[0]) + state_shaped = state[1 : 1 + n_systems * 2].reshape(-1, 2) + state_dict = dict(n_systems=n_systems) + system_names = [] + for uuid, val in state_shaped: + system_name = UUID_TO_SYSTEM_NAME[int(uuid)] + state_dict[system_name] = int(val) + system_names.append(system_name) + + # Sync systems so that state size sanity check succeeds + self._sync_systems(system_names=system_names) + + return state_dict, n_systems * 2 + 1 + + +class Saturated(RelativeObjectState, BooleanStateMixin): + def __init__(self, obj): + # Run super first + super().__init__(obj=obj) + + # Limits + self._default_visual_particle_limit = m.DEFAULT_SATURATION_LIMIT + self._default_physical_particle_limit = m.DEFAULT_SATURATION_LIMIT + self._limits = None + + def _initialize(self): + super()._initialize() + + # Set internal variables + self._limits = dict() + + def set_visual_particle_limit(self, limit): + """ + Sets the default visual particle limit + + Args: + limit (int): Number of particles representing limit for the visual particle system + """ + self._default_visual_particle_limit = limit + + def set_physical_particle_limit(self, limit): + """ + Sets the default physical particle limit + + Args: + limit (int): Number of particles representing limit for the physical particle system + """ + self._default_physical_particle_limit = limit + + @property + def limits(self): + """ + Returns: + dict: Maps system to limit count for that system, if it exists + """ + return self._limits + + def get_limit(self, system): + """ + Grabs the internal particle limit for @system + + Args: + system (BaseSystem): System to limit + + Returns: + init: Number of particles representing limit for the given @system + """ + # If system is in the (whitelist) limits, return that limit + if system.name in self._limits: + return self._limits[system.name] + # Otherwise, return the default limit + return ( + self._default_visual_particle_limit + if self.obj.scene.is_visual_particle_system(system_name=system.name) + else self._default_physical_particle_limit + ) + + def set_limit(self, system, limit): + """ + Sets internal particle limit @limit for @system + + Args: + system (BaseSystem): System to limit + limit (int): Number of particles representing limit for the given @system + """ + self._limits[system.name] = limit + + # Add this object to the current state update set in its scene + self.obj.state_updated() + + def _get_value(self, system): + limit = self.get_limit(system=system) + + # If requested, run sanity check to make sure we're not over the limit with this system's particles + count = self.obj.states[ModifiedParticles].get_value(system) + assert count <= limit, f"{self.__class__.__name__} should not be over the limit! Max: {limit}, got: {count}" + + return count == limit + + def _set_value(self, system, new_value): + # Only set the value if it's different than what currently exists + if new_value != self.get_value(system): + self.obj.states[ModifiedParticles].set_value(system, self.get_limit(system=system) if new_value else 0) + return True + + def get_texture_change_params(self): + colors = [] + + for system_name in self.obj.states[ModifiedParticles].particle_counts.keys(): + system = self.obj.scene.get_system(system_name, force_init=False) + if self.get_value(system): + colors.append(system.color) + + if len(colors) == 0: + # If no fluid system has Soaked=True, keep the default albedo value + albedo_add = 0.0 + diffuse_tint = th.tensor([1.0, 1.0, 1.0]) + else: + albedo_add = 0.1 + avg_color = th.mean(th.stack(colors), dim=0) + # Add a tint of avg_color + # We want diffuse_tint to sum to 2.5 to result in the final RGB to sum to 1.5 on average + # This is because an average RGB color sum to 1.5 (i.e. [0.5, 0.5, 0.5]) + # (0.5 [original avg RGB per channel] + 0.1 [albedo_add]) * 2.5 = 1.5 + diffuse_tint = th.tensor([0.5, 0.5, 0.5]) + avg_color / th.sum(avg_color) + + return albedo_add, diffuse_tint + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(ModifiedParticles) + return deps + + def _sync_systems(self, system_names): + """ + Helper function for forcing internal systems to be synchronized with external list of @systems. + + NOTE: This may override internal state + + Args: + system_names (list of str): List of system name(s) that should be actively tracked internally + """ + self._limits = {system_name: m.DEFAULT_SATURATION_LIMIT for system_name in system_names} + + @property + def state_size(self): + # n whitelist limits + default visual particle limit + default physical particle limit + # + limit per whitelist entry * 2 (UUID, value) + return 3 + len(self._limits) * 2 + + def _dump_state(self): + state = dict( + n_systems=len(self._limits), + default_visual_particle_limit=self._default_visual_particle_limit, + default_physical_particle_limit=self._default_physical_particle_limit, + ) + for system_name, limit in self._limits.items(): + state[system_name] = limit + return state + + def _load_state(self, state): + self._limits = dict() + for k, v in state.items(): + if k == "n_systems": + continue + elif k == "default_visual_particle_limit": + self._default_visual_particle_limit = v + elif k == "default_physical_particle_limit": + self._default_physical_particle_limit = v + else: + self._limits[k] = v + + def serialize(self, state): + state_flat = th.tensor( + [ + state["n_systems"], + state["default_visual_particle_limit"], + state["default_physical_particle_limit"], + ], + dtype=th.float32, + ) + if state["n_systems"] > 0: + system_names = tuple(state.keys())[3:] + whitelist_limits = [ + (self.obj.scene.get_system(system_name, force_init=False).uuid, state[system_name]) + for system_name in system_names + ] + whitelist_limits = th.tensor(whitelist_limits, dtype=th.float32).view(-1) + state_flat = th.cat([state_flat, whitelist_limits]) + return state_flat + + def deserialize(self, state): + n_systems = int(state[0]) + state_dict = dict( + n_systems=n_systems, + default_visual_particle_limit=int(state[1]), + default_physical_particle_limit=int(state[2]), + ) + state_shaped = state[3 : 3 + n_systems * 2].reshape(-1, 2) + system_names = [] + for uuid, val in state_shaped: + system_name = UUID_TO_SYSTEM_NAME[int(uuid)] + state_dict[system_name] = int(val) + system_names.append(system_name) + + # Sync systems so that state size sanity check succeeds + self._sync_systems(system_names=system_names) + + return state_dict, 3 + n_systems * 2 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/sliceable.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/sliceable.py new file mode 100644 index 0000000000000000000000000000000000000000..3c20898db24b554a9932a26882682b4d63e2d500 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/sliceable.py @@ -0,0 +1,30 @@ +from omnigibson.object_states.object_state_base import BaseObjectRequirement + + +class SliceableRequirement(BaseObjectRequirement): + """ + Class for sanity checking objects that request the "sliceable" ability + """ + + @classmethod + def is_compatible(cls, obj, **kwargs): + # Avoid circular imports + from omnigibson.objects.dataset_object import DatasetObject + + # Make sure object is dataset object + if not isinstance(obj, DatasetObject): + return False, f"Only compatible with DatasetObject, but {obj} is of type {type(obj)}" + # Check to make sure object parts are properly annotated in this object's metadata + if not obj.metadata["object_parts"]: + return False, "Missing required metadata 'object_parts'." + + return True, None + + @classmethod + def is_compatible_asset(cls, prim, **kwargs): + # Check to make sure object parts are properly annotated in this object's metadata + metadata = prim.GetCustomData().get("metadata", dict()) + if not metadata.get("object_parts", None): + return False, "Missing required metadata 'object_parts'." + + return True, None diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/slicer_active.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/slicer_active.py new file mode 100644 index 0000000000000000000000000000000000000000..4461d9c301d04637505cc0daeb76552f5e51fa28 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/slicer_active.py @@ -0,0 +1,343 @@ +import torch as th +import warp as wp + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.macros import create_module_macros +from omnigibson.object_states.object_state_base import BooleanStateMixin +from omnigibson.object_states.tensorized_absolute_state import TensorizedAbsoluteState +from omnigibson.utils.python_utils import classproperty +from omnigibson.utils.usd_utils import RigidContactAPI + +# Create settings for this module +m = create_module_macros(module_path=__file__) +m.REACTIVATION_DELAY = 2.0 # number of seconds to wait before reactivating the slicer + + +@wp.kernel +def _slicer_zero_currently_touching_kernel( + currently_touching: wp.array2d(dtype=wp.int32), # (S, O) +): + """ + Per (scene, obj) thread. Zeroes `currently_touching` so the subsequent per-scene + is_in_contact_batch_warp atomic_max only needs to set-on-hit. + + Lives inside the captured wp.graph so the zero is stream-ordered with the contact + queries that consume it — replaces an out-of-graph torch fill_() that relied on + legacy-default-stream semantics for cross-stream ordering with Warp's capture stream. + """ + s, o = wp.tid() + currently_touching[s, o] = wp.int32(0) + + +@wp.kernel +def _slicer_pre_clear_kernel( + values: wp.array2d(dtype=wp.uint8), # (S, O) — public state, stays uint8 + delay_counter: wp.array2d(dtype=wp.float32), # (S, O) + prev_touching: wp.array2d(dtype=wp.int32), # (S, O) — int32, see SlicerActive class doc +): + """ + Per (scene, obj) thread. Runs at the start of each step. For each cell where prev_touching + is nonzero, set values=0 (deactivated) and delay_counter=0 (cooldown restarted). Cells + where prev_touching is zero are left alone. + """ + s, o = wp.tid() + if prev_touching[s, o] != wp.int32(0): + delay_counter[s, o] = 0.0 + values[s, o] = wp.uint8(0) + + +@wp.kernel +def _slicer_post_update_kernel( + values: wp.array2d(dtype=wp.uint8), # (S, O) — public state, stays uint8 + delay_counter: wp.array2d(dtype=wp.float32), # (S, O) — seconds elapsed since last touch + currently_touching: wp.array2d(dtype=wp.int32), # (S, O) — int32, written by atomic in is_in_contact_batch_warp + prev_touching: wp.array2d(dtype=wp.int32), # (S, O) — int32 to mirror currently_touching + seconds_to_wait: wp.float32, + dt: wp.array(dtype=wp.float32), +): + """ + Per (scene, obj) thread. Per thread does: + - If the slicer is currently active: leave delay_counter alone (it's not in cooldown). + - If the slicer is inactive AND not touching anything: advance delay_counter by dt[0] seconds. + - If the slicer is inactive AND still touching something: reset delay_counter to 0 + (touching restarts the wait — the slicer doesn't reactivate while in contact). + - If delay_counter has hit `seconds_to_wait`, reactivate the slicer. + - Finally, mirror currently_touching into prev_touching for the next step's pre-clear pass. + """ + s, o = wp.tid() + is_active = values[s, o] != wp.uint8(0) + is_touching = currently_touching[s, o] != wp.int32(0) + if not is_active: + if not is_touching: + delay_counter[s, o] = delay_counter[s, o] + dt[0] + else: + delay_counter[s, o] = 0.0 + if delay_counter[s, o] >= seconds_to_wait: + values[s, o] = wp.uint8(1) + prev_touching[s, o] = currently_touching[s, o] + + +class SlicerActive(TensorizedAbsoluteState, BooleanStateMixin): + """ + Slicer-active state. + + Note on dtype: PREVIOUSLY_TOUCHING and _currently_touching are int32, NOT bool/uint8, because + they depend on`RigidContactAPI.is_in_contact_batch_warp` whose output is int32. + """ + + # wp.array2d (S, O) float32 — seconds elapsed since the last touch, per slicer. + DELAY_COUNTER = None + + # wp.array2d (S, O) int32 — whether each slicer touched a sliceable in the previous step. + # int32 (not bool) — see class docstring; mirrors _currently_touching's dtype. + PREVIOUSLY_TOUCHING = None + + # S = number of scenes + # O = number of objects that have SlicerActive state + # R_s = number of contact-matrix rows (links on the "who is touching" side) for scene s + # C_s = number of contact-matrix columns (links on the "what are they touching" side) for scene s + + # list[wp.array(O, R_s) uint8 | None] — row mask per slicer object per scene. + _slicer_contact_query_masks = None + + # list[wp.array(1, C_s) uint8 | None] — col mask for all sliceable links per scene. + _sliceable_contact_col_mask = None + + # wp.array2d (S, O) int32 — filled each step by _currently_touching_sliceables(). + _currently_touching = None + # Per-scene wp row slice views of _currently_touching, used as is_in_contact_batch_warp out=. + _currently_touching_per_scene = None # list[wp.array | None] + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + return deps + + @classmethod + def global_initialize(cls): + # Call super first + super().global_initialize() + + cls._slicer_contact_query_masks = None + cls._sliceable_contact_col_mask = None + cls._currently_touching = None + + @classmethod + def initialize_view(cls): + # Snapshot which relative paths existed before the rebuild + prev_rel_paths = set(cls.OBJ_IDXS.keys()) if cls.OBJ_IDXS is not None else set() + + # Snapshot tracking tensors before rebuild so survivors can be carried over. + # wp.to_torch shares storage; .cpu() forces a single GPU→CPU copy for the carry-over loop. + prev_previously_touching_cpu = ( + wp.to_torch(cls.PREVIOUSLY_TOUCHING).cpu() if cls.PREVIOUSLY_TOUCHING is not None else None + ) + prev_delay_counter_cpu = wp.to_torch(cls.DELAY_COUNTER).cpu() if cls.DELAY_COUNTER is not None else None + prev_obj_idxs = dict(cls.OBJ_IDXS) if cls.OBJ_IDXS is not None else {} + + # Base class rebuilds OBJ_IDXS, IDX_OBJS, VALUES (with value carry-over for survivors) + super().initialize_view() + + S = len(cls.IDX_OBJS) + O = len(cls.OBJ_IDXS) + + # Build fresh tracking tensors via CPU scratch, then ship to GPU wp.arrays. + # Carry over survivors so PREVIOUSLY_TOUCHING set during a slicing step is not lost when + # initialize_view() runs again on the next step (e.g. new objects initialized). + if S == 0 or O == 0: + cls.PREVIOUSLY_TOUCHING = None + cls.DELAY_COUNTER = None + cls._currently_touching = None + else: + new_previously_touching_cpu = th.zeros((S, O), dtype=th.int32) + new_delay_counter_cpu = th.zeros((S, O), dtype=th.float32) + if prev_previously_touching_cpu is not None and prev_previously_touching_cpu.numel() > 0: + for rel_path, obj_idx_new in cls.OBJ_IDXS.items(): + if rel_path not in prev_obj_idxs: + continue + obj_idx_old = prev_obj_idxs[rel_path] + n_scenes = min(prev_previously_touching_cpu.shape[0], S) + new_previously_touching_cpu[:n_scenes, obj_idx_new] = prev_previously_touching_cpu[ + :n_scenes, obj_idx_old + ] + new_delay_counter_cpu[:n_scenes, obj_idx_new] = prev_delay_counter_cpu[:n_scenes, obj_idx_old] + cls.PREVIOUSLY_TOUCHING = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + new_previously_touching_cpu, "int32", device="cuda" + ) + cls.DELAY_COUNTER = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + new_delay_counter_cpu, "float32", device="cuda" + ) + cls._currently_touching = wp.zeros((S, O), dtype=wp.int32, device="cuda") + + # Initialize new VALUE slots (not carried over) to True (slicer starts active) + for rel_path, obj_idx in cls.OBJ_IDXS.items(): + if rel_path not in prev_rel_paths: + cls.VALUES[:, obj_idx] = True + cls.VALUES_CPU[:, obj_idx] = True + + # Build per-scene contact masks (wp.array uint8) and per-scene out-row slices. + cls._slicer_contact_query_masks = [] + cls._sliceable_contact_col_mask = [] + cls._currently_touching_per_scene = [] + + def _append_none_for_scene(): + cls._slicer_contact_query_masks.append(None) + cls._sliceable_contact_col_mask.append(None) + cls._currently_touching_per_scene.append(None) + + for scene_idx, scene in enumerate(og.sim.scenes): + if not RigidContactAPI.has_contact_view(scene_idx): + _append_none_for_scene() + continue + + sliceable_objs = scene.object_registry("abilities", "sliceable", []) + # No sliceable objects in this scene, or no slicers tracked anywhere. + if not sliceable_objs or O == 0: + _append_none_for_scene() + continue + + # Col mask (1, C_s) for all sliceable links — shared across all O slicer queries. + sliceable_paths = [link.prim_path for obj in sliceable_objs for link in obj.links.values()] + sliceable_col = RigidContactAPI.get_contact_col_mask(scene_idx, sliceable_paths) # (C_s,) CPU bool + + # Row masks (O, R_s) — one query per slicer object. If any slicer object isn't + # initialized yet, skip this scene; will be retried on the next initialize_view. + slicer_masks = [] + any_uninitialized = False + for obj_idx in range(O): + if cls.IDX_OBJS[scene_idx][obj_idx] is None: + any_uninitialized = True + break + slicer_masks.append( + RigidContactAPI.get_contact_row_mask( + scene_idx, [link.prim_path for link in cls.IDX_OBJS[scene_idx][obj_idx].links.values()] + ) + ) # (R_s,) CPU bool + if any_uninitialized: + _append_none_for_scene() + continue + + with_mask_data = sliceable_col.unsqueeze(0).to(th.uint8) # (1, C_s) CPU uint8 tensor + query_masks_data = th.stack(slicer_masks).to(th.uint8) # (O, R_s) CPU uint8 tensor + + cls._slicer_contact_query_masks.append( + lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list(query_masks_data, "uint8", device="cuda") + ) + cls._sliceable_contact_col_mask.append( + lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list(with_mask_data, "uint8", device="cuda") + ) + cls._currently_touching_per_scene.append(cls._currently_touching[scene_idx]) + + @classmethod + def _update_values(cls, values): + if cls.PREVIOUSLY_TOUCHING is None: + return + S, O = values.shape[:2] + + wp.launch( + kernel=_slicer_pre_clear_kernel, + dim=(S, O), + inputs=[cls.VALUES_WP, cls.DELAY_COUNTER, cls.PREVIOUSLY_TOUCHING], + device="cuda", + ) + + # Zero _currently_touching inside the graph so it's stream-ordered with the per-scene + # is_in_contact_batch_warp calls below (which atomic_max set-on-hit and require a + # pre-zeroed output). Absent scenes have no kernel launched, so their rows stay 0. + wp.launch( + kernel=_slicer_zero_currently_touching_kernel, + dim=(S, O), + inputs=[cls._currently_touching], + device="cuda", + ) + + cls._currently_touching_sliceables() + + wp.launch( + kernel=_slicer_post_update_kernel, + dim=(S, O), + inputs=[ + cls.VALUES_WP, + cls.DELAY_COUNTER, + cls._currently_touching, + cls.PREVIOUSLY_TOUCHING, + wp.float32(m.REACTIVATION_DELAY), + cls._dt, + ], + device="cuda", + ) + + @classmethod + def _currently_touching_sliceables(cls): + """ + Per-scene Warp contact batch query into the corresponding row of _currently_touching. + Caller must have pre-zeroed _currently_touching (see _slicer_zero_currently_touching_kernel); + empty/missing scenes have no kernel launched and leave their row at 0. + """ + for scene_idx in range(len(og.sim.scenes)): + query_masks = cls._slicer_contact_query_masks[scene_idx] + with_mask = cls._sliceable_contact_col_mask[scene_idx] + out = cls._currently_touching_per_scene[scene_idx] + if query_masks is None or with_mask is None or out is None: + continue + RigidContactAPI.is_in_contact_batch_warp( + scene_idx=scene_idx, + query_masks_wp=query_masks, + with_masks_wp=with_mask, + ignore_masks_wp=None, + current_only=False, + out_wp=out, + ) + + @classproperty + def value_name(cls): + return "value" + + @classproperty + def value_type(cls): + return th.bool + + @property + def state_size(self): + # Call super first + size = super().state_size + + # Add additional 2 to keep track of previously touching and delay counter + return size + 2 + + def _dump_state(self): + if self.OBJ_IDXS is None or self.obj.relative_prim_path not in self.OBJ_IDXS: + return dict(value=True, previously_touching=False, delay_counter=0.0) + state = super()._dump_state() + scene_idx = self.obj.scene.idx + obj_idx = self.OBJ_IDXS[self.obj.relative_prim_path] + # wp.to_torch is a zero-copy view of the wp.array storage. + prev_view = wp.to_torch(type(self).PREVIOUSLY_TOUCHING) + delay_view = wp.to_torch(type(self).DELAY_COUNTER) + state["previously_touching"] = bool(prev_view[scene_idx, obj_idx]) + state["delay_counter"] = float(delay_view[scene_idx, obj_idx]) + return state + + def _load_state(self, state): + super()._load_state(state=state) + s = self.obj.scene.idx + obj_idx = self.OBJ_IDXS[self.obj.relative_prim_path] + wp.to_torch(type(self).PREVIOUSLY_TOUCHING)[s, obj_idx] = int(state["previously_touching"]) + wp.to_torch(type(self).DELAY_COUNTER)[s, obj_idx] = float(state["delay_counter"]) + + def serialize(self, state): + state_flat = super().serialize(state=state) + return th.cat( + [ + state_flat, + th.tensor([state["previously_touching"], state["delay_counter"]]), + ] + ) + + def deserialize(self, state): + state_dict, idx = super().deserialize(state=state) + state_dict[f"{self.value_name}"] = bool(state_dict[f"{self.value_name}"]) + state_dict["previously_touching"] = bool(state[idx]) + state_dict["delay_counter"] = float(state[idx + 1]) + return state_dict, idx + 2 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/temperature.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/temperature.py new file mode 100644 index 0000000000000000000000000000000000000000..0e95fe2b42cc8fd2501ea5becf5df75ef7dadadb --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/temperature.py @@ -0,0 +1,543 @@ +import torch as th +import warp as wp + +import omnigibson.lazy as lazy +from omnigibson.macros import create_module_macros +from omnigibson.object_states.aabb import AABB +from omnigibson.object_states.heat_source_or_sink import HeatSourceOrSink +from omnigibson.object_states.inside import Inside +from omnigibson.object_states.tensorized_absolute_state import TensorizedAbsoluteState +from omnigibson.object_states.tensorized_state import TensorizedState, _wp_from_torch +from omnigibson.utils.constants import PrimType +from omnigibson.utils.python_utils import classproperty +from omnigibson.utils.usd_utils import RigidBodyViewAPI + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# TODO: Consider sourcing default temperature from scene +# Default ambient temperature. +m.DEFAULT_TEMPERATURE = 23.0 # degrees Celsius + +# What fraction of the temperature difference with the default temperature should be decayed every step. +m.TEMPERATURE_DECAY_SPEED = 0.02 # per second. We'll do the conversion to steps later. + + +@wp.kernel +def _incoming_heat_kernel( + source_values: wp.array2d(dtype=wp.uint8), # HeatSourceOrSink.VALUES (S_hss, N_hss) + requires_inside: wp.array(dtype=wp.uint8), # (N_hss,) + source_temperatures: wp.array(dtype=wp.float32), # (N_hss,) + heating_rates: wp.array(dtype=wp.float32), # (N_hss,) + distance_thresholds: wp.array(dtype=wp.float32), # (N_hss,) + hss_self_temp_idx: wp.array(dtype=wp.int32), # (N_hss,) into Temperature N — to skip self + hss_self_inside_idx: wp.array(dtype=wp.int32), # (N_hss,) into Inside N (for requires_inside) + link_flat_idx: wp.array2d(dtype=wp.int32), # (S_hss, N_hss) into POSE_MATRICES — -1 if N/A + link_local_offset: wp.array(dtype=wp.vec3), # (N_hss,) heat element offset in link local frame + temp_to_aabb_idx: wp.array(dtype=wp.int32), # (N_temp,) Temperature N → AABB N + temp_to_inside_idx: wp.array(dtype=wp.int32), # (N_temp,) Temperature N → Inside N + target_link_offsets: wp.array(dtype=wp.int32), # (S_temp*N_temp+1,) CSR offsets into the below + target_link_indices: wp.array(dtype=wp.int32), # (K,) flat link idx of each target's collision links + link_mesh_ids: wp.array(dtype=wp.uint64), # RigidBodyViewAPI.LINK_MESH_IDS — 0 if no mesh + n_temp: wp.int32, # targets per scene, to index the CSR table by (s, n) + pose_matrices: wp.array(dtype=wp.mat44), # RigidBodyViewAPI.POSE_MATRICES + aabb_values: wp.array3d(dtype=wp.float32), # AABB (S, N_aabb, 6) + inside_values: wp.array3d(dtype=wp.uint8), # Inside (S, N_inside, N_inside) — uint8 view of bool + temperature_values: wp.array2d(dtype=wp.float32), # (S_temp, N_temp) + n_inside_scenes: wp.int32, # scene rows in inside_values (0 if the state tracks nothing) + influence_mask: wp.array3d(dtype=wp.uint8), # (S_hss, N_hss, N_temp) — out + incoming_heat_rate: wp.array2d(dtype=wp.float32), # (S_temp, N_temp) — out +): + """ + Per (scene, source, target) thread: if heat source / sink h is active and target n is in + range, write influence_mask[s, h, n] = 1 and atomic_add (T_h - T_n) * rate into + incoming_heat_rate[s, n]. Launched over s < min(S_hss, S_temp). + """ + s, h, n = wp.tid() + if source_values[s, h] == wp.uint8(0): # early return if source not active + return + if hss_self_temp_idx[h] == n: # do not influence self + return + target_aabb_idx = temp_to_aabb_idx[n] + if target_aabb_idx < wp.int32(0): + return + + # containment sources (e.g. ovens): target must be inside the source + if requires_inside[h] != wp.uint8(0): + if s >= n_inside_scenes: + return + src_idx_in_inside = hss_self_inside_idx[h] + target_idx_in_inside = temp_to_inside_idx[n] + if src_idx_in_inside < wp.int32(0) or target_idx_in_inside < wp.int32(0): + return + if inside_values[s, target_idx_in_inside, src_idx_in_inside] == wp.uint8(0): + return + # point sources: the target's AABB must be within the distance threshold of the heat element. + # The element link is a different rigid body in every scene, so its pose index is per (s, h). + else: + li = link_flat_idx[s, h] + if li < wp.int32(0): + return + link_pose = pose_matrices[li] + local_offset = link_local_offset[h] + source_world_position = wp.mul( + link_pose, wp.vec4(local_offset[0], local_offset[1], local_offset[2], wp.float32(1.0)) + ) + # BROAD PHASE: distance from the heat element to the CLOSEST POINT of the target's AABB + # (element position clamped into the box). + # + # Pre-vectorization this test was a PhysX overlap_sphere(threshold) scene query against the + # target's actual COLLISION GEOMETRY (heat_source_or_sink.py on main). That is a CPU-side + # query with a callback, one call per source, so it cannot run inside this kernel. Instead + # we reproduce it in two stages: this cheap AABB test rejects almost everything, and the + # narrow phase below measures to the real meshes for whatever survives. + # + # An AABB always contains its geometry, so distance-to-AABB <= distance-to-geometry and + # this stage never rejects a pair overlap_sphere would have accepted — exactly what a broad + # phase must guarantee. It is only *too permissive* on its own, most visibly for long, thin + # or diagonally-oriented targets (measured 0.69 m of slack for a bar along a box diagonal). + qx = wp.clamp(source_world_position[0], aabb_values[s, target_aabb_idx, 0], aabb_values[s, target_aabb_idx, 3]) + qy = wp.clamp(source_world_position[1], aabb_values[s, target_aabb_idx, 1], aabb_values[s, target_aabb_idx, 4]) + qz = wp.clamp(source_world_position[2], aabb_values[s, target_aabb_idx, 2], aabb_values[s, target_aabb_idx, 5]) + dx = source_world_position[0] - qx + dy = source_world_position[1] - qy + dz = source_world_position[2] - qz + d2 = dx * dx + dy * dy + dz * dz + threshold = distance_thresholds[h] + if d2 > threshold * threshold: + return + + # NARROW PHASE — the AABB test above is only a conservative broad phase (AABB contains the + # geometry, so it can pass for targets whose mesh is far away; measured 0.69 m of slack for + # a bar lying along a box diagonal). Reproduce main's overlap_sphere by measuring to the + # target's actual collision meshes, but only for pairs that survived the broad phase. + base = s * n_temp + n + lo = target_link_offsets[base] + hi = target_link_offsets[base + wp.int32(1)] + if hi > lo: # targets with no collision geometry (e.g. cloth) keep the AABB result + # Search radius. Normally the threshold is enough. But if the element is INSIDE the + # target's AABB (d2 == 0) it may also be inside the mesh, and the nearest surface can + # then be farther away than the threshold — querying only to `threshold` would return + # no result and we would miss a containment that overlap_sphere reports as contact. + # Widen the radius by the AABB diagonal in exactly that case, so the cost is paid only + # for the rare candidate rather than on every pair. + max_d = threshold + if d2 == wp.float32(0.0): + ex = aabb_values[s, target_aabb_idx, 3] - aabb_values[s, target_aabb_idx, 0] + ey = aabb_values[s, target_aabb_idx, 4] - aabb_values[s, target_aabb_idx, 1] + ez = aabb_values[s, target_aabb_idx, 5] - aabb_values[s, target_aabb_idx, 2] + max_d = threshold + wp.sqrt(ex * ex + ey * ey + ez * ez) + hit = wp.int32(0) + for k in range(lo, hi): + body = target_link_indices[k] + mesh_id = link_mesh_ids[body] + if mesh_id == wp.uint64(0): + continue + # Into the link's local frame. collision_mesh_cpu_data bakes world scale into the + # points, so POSE_MATRICES is a pure rotation+translation and its inverse is + # (R^T, -R^T t) — cheaper and stabler than a general 4x4 inverse, and because the + # transform is rigid the distance measured here equals the world-frame distance. + lp = pose_matrices[body] + rot = wp.mat33( + lp[0, 0], + lp[0, 1], + lp[0, 2], + lp[1, 0], + lp[1, 1], + lp[1, 2], + lp[2, 0], + lp[2, 1], + lp[2, 2], + ) + rel = wp.vec3( + source_world_position[0] - lp[0, 3], + source_world_position[1] - lp[1, 3], + source_world_position[2] - lp[2, 3], + ) + local_p = wp.transpose(rot) * rel + # Links farther than max_d return no result, so they cost nothing. + res = wp.mesh_query_point(mesh_id, local_p, max_d) + if res.result: + cp = wp.mesh_eval_position(mesh_id, res.face, res.u, res.v) + dist = wp.length(local_p - cp) + # A negative sign means the element is INSIDE this mesh. overlap_sphere counts + # containment as contact, so accept it regardless of the distance out to the + # surface — otherwise a large pot enclosing a burner would stop cooking. + if res.sign < wp.float32(0.0) or dist <= threshold: + hit = wp.int32(1) + break + if hit == wp.int32(0): + return + + influence_mask[s, h, n] = wp.uint8(1) + delta = (source_temperatures[h] - temperature_values[s, n]) * heating_rates[h] + wp.atomic_add(incoming_heat_rate, s, n, delta) + + +@wp.kernel +def _temperature_decay_kernel( + values: wp.array2d(dtype=wp.float32), + incoming_heat_rate: wp.array2d(dtype=wp.float32), + default_temp: wp.float32, + decay_rate: wp.float32, + dt: wp.array(dtype=wp.float32), +): + """ + Fused exponential decay toward `default_temp` plus consumption of the per-step incoming heat + rate scratch buffer (written by _incoming_heat_kernel earlier in the same update pass). + One thread per (scene, obj). + values += (default_temp - values) * decay_rate * dt[0] + incoming_heat_rate * dt[0] + Then zero the consumed entry so the scratch is fresh for the next step's gather. + + `dt` is a single-element warp array (read as `dt[0]`) rather than a scalar so the + per-frame value written in pre_update is visible inside the captured graph without + re-capturing it (time-dependent-state mechanism). + """ + s, o = wp.tid() + values[s, o] = values[s, o] + (default_temp - values[s, o]) * decay_rate * dt[0] + incoming_heat_rate[s, o] * dt[0] + incoming_heat_rate[s, o] = wp.float32(0.0) + + +@wp.kernel +def _self_heating_clamp_kernel( + source_values: wp.array2d(dtype=wp.uint8), # HeatSourceOrSink.VALUES (S_hss, N_hss) + requires_on_fire: wp.array(dtype=wp.uint8), # (N_hss,) + source_temperatures: wp.array(dtype=wp.float32), # (N_hss,) + ignition_temperatures: wp.array(dtype=wp.float32), # (N_hss,) + hss_self_temp_idx: wp.array(dtype=wp.int32), # (N_hss,) into Temperature N + temperature_values: wp.array2d(dtype=wp.float32), # (S_temp, N_temp) — out +): + """ + Fire sources sustain their own temperature: an active requires_on_fire source holds its + object at the source (fire) temperature. Gated on the temperature still being at or above + ignition, so deliberately cooling the object below ignition (extinguishing) is not + overridden — the fire then dies out on the next OnFire pass instead. Launched over + s < min(S_hss, S_temp). + """ + s, h = wp.tid() + if requires_on_fire[h] == wp.uint8(0): + return + if source_values[s, h] == wp.uint8(0): + return + n = hss_self_temp_idx[h] + if n < wp.int32(0): + return + t = temperature_values[s, n] + if t < ignition_temperatures[h]: + return + if source_temperatures[h] > t: + temperature_values[s, n] = source_temperatures[h] + + +class Temperature(TensorizedAbsoluteState): + """ + Continuous per-object temperature (°C). + + Temperature owns every write into its own tensors. Each step, `_update_values` launches, + in order: + 1. `_incoming_heat_kernel` — gathers heat from active HeatSourceOrSink entries (whose + activation gates were computed earlier this step; HeatSourceOrSink is a dependency) + into the private INCOMING_HEAT_RATE scratch, recording who-heats-whom in + INFLUENCE_MASK (served to HeatSourceOrSink.affects_obj via is_influenced_by()). + 2. `_temperature_decay_kernel` — integrates ambient decay plus the gathered rate, then + zeroes the scratch for the next step. + 3. `_self_heating_clamp_kernel` — objects on fire (heat sources with requires_on_fire) + are held at their fire temperature. + + Note the deliberate one-step lag in the fire feedback loop: OnFire (which depends on + Temperature) flips True the step temperature crosses ignition; the object's + HeatSourceOrSink gate reads OnFire's previous-step values, so the fire starts heating + (including the self-clamp) on the following step. + """ + + # (S, N) float32 — private per-step rate accumulator; written by _incoming_heat_kernel and + # consumed + zeroed by _temperature_decay_kernel within the same _update_values pass. + INCOMING_HEAT_RATE = None # wp.array (S, N) float32 — GPU-only scratch (single source of truth) + + # (S_hss, N_hss, N_temp) — which heat source influenced which object this step. The GPU + # uint8 wp.array is the single source of truth; the CPU mirror keeps a torch bool tensor + # (for .item() reads in is_influenced_by) plus a wp view for the graph-safe wp.copy, + # mirroring how the base class keeps VALUES_CPU + VALUES_CPU_WP. + INFLUENCE_MASK = None # wp.array (S_hss, N_hss, N_temp) uint8 — GPU + INFLUENCE_MASK_CPU = None # torch bool (S_hss, N_hss, N_temp), pinned — CPU mirror + INFLUENCE_MASK_CPU_WP = None # wp.array uint8 view of INFLUENCE_MASK_CPU + + # Index maps into other states' N dimensions. Built in initialize_view — safe because all + # referenced states (HeatSourceOrSink, AABB, Inside) initialize before Temperature in + # dependency order. + _hss_self_temp_idx = None # wp.array (N_hss,) int32 — HeatSourceOrSink N → Temperature N + _hss_self_inside_idx = None # wp.array (N_hss,) int32 — HeatSourceOrSink N → Inside N + _temp_to_aabb_idx = None # wp.array (N_temp,) int32 — Temperature N → AABB N + _temp_to_inside_idx = None # wp.array (N_temp,) int32 — Temperature N → Inside N + + # CSR table giving each (scene, target) its collision-geometry links, so the point-source + # proximity test can measure to the target's actual mesh rather than to its AABB. For scene s + # and Temperature index n the links are + # _target_link_indices[_target_link_offsets[s * N_temp + n] : _target_link_offsets[... + 1]] + # indexing RigidBodyViewAPI.POSE_MATRICES / LINK_MESH_IDS. Targets with no collision geometry + # (e.g. cloth, which is absent from RigidBodyViewAPI) get an empty range. + _target_link_offsets = None # wp.array (S_temp * N_temp + 1,) int32 + _target_link_indices = None # wp.array (K,) int32 + + # Placeholder wp.array to satisfy the kernel signature when Inside tracks no objects. + _placeholder_inside = None # wp.array (1, 1, 1) uint8 + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(AABB) + return deps + + @classmethod + def get_optional_dependencies(cls): + deps = super().get_optional_dependencies() + # Optional because objects without HeatSourceOrSink (e.g. cookable food items) are still + # eligible for a Temperature state — but the topo sort still places HeatSourceOrSink + # before Temperature, so _incoming_heat_kernel reads this step's freshly-computed + # activation gates. + deps.add(HeatSourceOrSink) + return deps + + @classmethod + def global_initialize(cls): + super().global_initialize() + cls.INCOMING_HEAT_RATE = None + cls.INFLUENCE_MASK = None + cls.INFLUENCE_MASK_CPU = None + cls.INFLUENCE_MASK_CPU_WP = None + cls._hss_self_temp_idx = None + cls._hss_self_inside_idx = None + cls._temp_to_aabb_idx = None + cls._temp_to_inside_idx = None + cls._placeholder_inside = wp.zeros((1, 1, 1), dtype=wp.uint8, device="cuda") + + @classmethod + def initialize_view(cls): + # Snapshot which relative paths existed before the rebuild + prev_rel_paths = set(cls.OBJ_IDXS.keys()) if cls.OBJ_IDXS is not None else set() + + # Base class rebuilds OBJ_IDXS, IDX_OBJS, VALUES (with value carry-over for survivors) + super().initialize_view() + + # Initialize new VALUE slots (not carried over) to DEFAULT_TEMPERATURE + for rel_path, obj_idx in cls.OBJ_IDXS.items(): + if rel_path not in prev_rel_paths: + for s_idx in range(len(cls.IDX_OBJS)): + if cls.IDX_OBJS[s_idx][obj_idx] is not None: + cls.VALUES[s_idx, obj_idx] = m.DEFAULT_TEMPERATURE + cls.VALUES_CPU[s_idx, obj_idx] = m.DEFAULT_TEMPERATURE + + # Allocate the per-step heat-rate scratch buffer. No carry-over: a partial step from + # the previous configuration would be applied to the wrong indices. + if cls.VALUES.numel() > 0: + cls.INCOMING_HEAT_RATE = wp.zeros(tuple(cls.VALUES.shape), dtype=wp.float32, device="cuda") + else: + cls.INCOMING_HEAT_RATE = None + + # Rebuild the maps into the states the heat kernels read. + cls._rebuild_heat_source_maps() + + @classmethod + def _rebuild_heat_source_maps(cls): + """ + Rebuild the index maps into HeatSourceOrSink / AABB / Inside plus INFLUENCE_MASK. + Called from initialize_view — safe because those states are (transitive) dependencies + of Temperature, so their views are rebuilt before this one. + """ + N_temp = len(cls.OBJ_IDXS) if cls.OBJ_IDXS is not None else 0 + hss_obj_idxs = HeatSourceOrSink.OBJ_IDXS or {} + N_hss = len(hss_obj_idxs) + S_hss = len(HeatSourceOrSink.IDX_OBJS) if HeatSourceOrSink.IDX_OBJS is not None else 0 + inside_map = Inside.OBJ_IDXS or {} + aabb_map = AABB.OBJ_IDXS or {} + + if N_temp == 0 or N_hss == 0 or S_hss == 0: + cls._hss_self_temp_idx = None + cls._hss_self_inside_idx = None + cls._temp_to_aabb_idx = None + cls._temp_to_inside_idx = None + cls._target_link_offsets = None + cls._target_link_indices = None + cls.INFLUENCE_MASK = None + cls.INFLUENCE_MASK_CPU = None + cls.INFLUENCE_MASK_CPU_WP = None + return + + create_tensor_from_list = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list + + hss_self_temp_idx = th.full((N_hss,), -1, dtype=th.int32) + hss_self_inside_idx = th.full((N_hss,), -1, dtype=th.int32) + for rel_path, h in hss_obj_idxs.items(): + hss_self_temp_idx[h] = cls.OBJ_IDXS.get(rel_path, -1) + hss_self_inside_idx[h] = inside_map.get(rel_path, -1) + cls._hss_self_temp_idx = create_tensor_from_list(hss_self_temp_idx, "int32", device="cuda") + cls._hss_self_inside_idx = create_tensor_from_list(hss_self_inside_idx, "int32", device="cuda") + + temp_to_aabb = th.full((N_temp,), -1, dtype=th.int32) + temp_to_inside = th.full((N_temp,), -1, dtype=th.int32) + for rel_path, n in cls.OBJ_IDXS.items(): + temp_to_aabb[n] = aabb_map.get(rel_path, -1) + temp_to_inside[n] = inside_map.get(rel_path, -1) + cls._temp_to_aabb_idx = create_tensor_from_list(temp_to_aabb, "int32", device="cuda") + cls._temp_to_inside_idx = create_tensor_from_list(temp_to_inside, "int32", device="cuda") + + # CSR table of each (scene, target)'s collision links, for the exact point-source test. + # Walks IDX_OBJS the same way AABB.initialize_view does, and skips links with no collision + # geometry via LINK_VERTEX_COUNTS so the kernel never queries a null mesh id. + S_temp = len(cls.IDX_OBJS) + link_offsets = th.zeros((S_temp * N_temp + 1,), dtype=th.int32) + link_indices = [] + for s_idx, scene_row in enumerate(cls.IDX_OBJS): + for n, obj in enumerate(scene_row): + if obj is not None and obj.prim_type != PrimType.CLOTH: + for link in obj.links.values(): + flat_idx = RigidBodyViewAPI.get_flat_idx(link.prim_path) + if flat_idx is None: + continue + if RigidBodyViewAPI.LINK_VERTEX_COUNTS[flat_idx].item() == 0: + continue # no collision geometry for this link + link_indices.append(flat_idx) + link_offsets[s_idx * N_temp + n + 1] = len(link_indices) + cls._target_link_offsets = create_tensor_from_list(link_offsets, "int32", device="cuda") + # create_tensor_from_list cannot build a zero-length array; the kernel only reads this when + # some (s, n) has a non-empty range, so a 1-element dummy is safe when nothing has geometry. + cls._target_link_indices = create_tensor_from_list( + th.tensor(link_indices or [0], dtype=th.int32), "int32", device="cuda" + ) + + cls.INFLUENCE_MASK = wp.zeros((S_hss, N_hss, N_temp), dtype=wp.uint8, device="cuda") + cls.INFLUENCE_MASK_CPU = th.zeros((S_hss, N_hss, N_temp), dtype=th.bool).pin_memory() + cls.INFLUENCE_MASK_CPU_WP = _wp_from_torch(cls.INFLUENCE_MASK_CPU) + + @classmethod + def pre_update(cls, dt=0.0): + super().pre_update(dt) + # Zero the influence mask every step so _incoming_heat_kernel only OR-writes hits. + if cls.INFLUENCE_MASK is not None: + cls.INFLUENCE_MASK.zero_() + + @classmethod + def _update_values(cls, values): + if cls.VALUES_WP is None or cls.INCOMING_HEAT_RATE is None: + return + S, N = cls.VALUES.shape[:2] + if S == 0 or N == 0: + return + + hss = HeatSourceOrSink + + # 1) Gather incoming heat from active heat sources / sinks into our scratch + mask. + if ( + cls.INFLUENCE_MASK is not None + and cls._hss_self_temp_idx is not None + and hss.VALUES_WP is not None + and AABB.VALUES_WP is not None + ): + S_hss, N_hss = hss.VALUES.shape[:2] + # Scenes beyond either state's row count hold no (source, target) pairs. + S_common = min(S, S_hss) + inside_values_wp = Inside.VALUES_WP + n_inside_scenes = Inside.VALUES.shape[0] if inside_values_wp is not None else 0 + if inside_values_wp is None: + inside_values_wp = cls._placeholder_inside + if S_common > 0 and N_hss > 0: + wp.launch( + kernel=_incoming_heat_kernel, + dim=(S_common, N_hss, N), + inputs=[ + hss.VALUES_WP, + hss._requires_inside, + hss._temperatures, + hss._heating_rates, + hss._distance_thresholds, + cls._hss_self_temp_idx, + cls._hss_self_inside_idx, + hss._link_flat_idx, + hss._link_local_offset, + cls._temp_to_aabb_idx, + cls._temp_to_inside_idx, + cls._target_link_offsets, + cls._target_link_indices, + RigidBodyViewAPI.LINK_MESH_IDS, + wp.int32(N), + RigidBodyViewAPI.POSE_MATRICES, + AABB.VALUES_WP, + inside_values_wp, + cls.VALUES_WP, + wp.int32(n_inside_scenes), + cls.INFLUENCE_MASK, + cls.INCOMING_HEAT_RATE, + ], + device="cuda", + ) + # Mirror the mask for CPU reads (HeatSourceOrSink.affects_obj). + if cls.INFLUENCE_MASK_CPU_WP is not None: + wp.copy(cls.INFLUENCE_MASK_CPU_WP, cls.INFLUENCE_MASK) + + # 2) Decay toward ambient + consume the gathered heat rate (also zeroes the scratch). + # dt is read from cls._dt at kernel-launch time inside the captured graph, so the + # per-frame value written in pre_update is visible without re-capturing the graph. + wp.launch( + kernel=_temperature_decay_kernel, + dim=(S, N), + inputs=[ + cls.VALUES_WP, + cls.INCOMING_HEAT_RATE, + wp.float32(m.DEFAULT_TEMPERATURE), + wp.float32(m.TEMPERATURE_DECAY_SPEED), + cls._dt, + ], + device="cuda", + ) + + # 3) Hold burning objects at their fire temperature (see kernel docstring for the + # ignition-threshold gate that lets deliberate cooling extinguish them). + if cls._hss_self_temp_idx is not None and hss.VALUES_WP is not None: + S_hss, N_hss = hss.VALUES.shape[:2] + S_common = min(S, S_hss) + if S_common > 0 and N_hss > 0: + wp.launch( + kernel=_self_heating_clamp_kernel, + dim=(S_common, N_hss), + inputs=[ + hss.VALUES_WP, + hss._requires_on_fire, + hss._temperatures, + hss._ignition_temperatures, + cls._hss_self_temp_idx, + cls.VALUES_WP, + ], + device="cuda", + ) + + @classmethod + def is_influenced_by(cls, source_obj, target_obj): + """ + Whether @source_obj's heat source / sink contributed heat to @target_obj's temperature + on the most recent update pass. + + Args: + source_obj (StatefulObject): Object with the HeatSourceOrSink state. + target_obj (StatefulObject): Object with the Temperature state. + + Returns: + bool + """ + # Lazy refresh so the read sees this-step's state. + TensorizedState.maybe_refresh_caches() + if cls.INFLUENCE_MASK_CPU is None: + return False + if HeatSourceOrSink.OBJ_IDXS is None or source_obj.relative_prim_path not in HeatSourceOrSink.OBJ_IDXS: + return False + if cls.OBJ_IDXS is None or target_obj.relative_prim_path not in cls.OBJ_IDXS: + return False + s = source_obj.scene.idx + if s >= cls.INFLUENCE_MASK_CPU.shape[0]: + return False + h = HeatSourceOrSink.OBJ_IDXS[source_obj.relative_prim_path] + n = cls.OBJ_IDXS[target_obj.relative_prim_path] + return bool(cls.INFLUENCE_MASK_CPU[s, h, n].item()) + + @classproperty + def value_name(cls): + return "temperature" diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/tensorized_absolute_state.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/tensorized_absolute_state.py new file mode 100644 index 0000000000000000000000000000000000000000..408eb84986a9a124e93c3d9d6458c14ce9f50fc2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/tensorized_absolute_state.py @@ -0,0 +1,185 @@ +import math + +import torch as th + +import omnigibson as og +from omnigibson.object_states.object_state_base import AbsoluteObjectState +from omnigibson.object_states.tensorized_state import TensorizedState, _wp_from_torch +from omnigibson.utils.python_utils import classproperty + + +class TensorizedAbsoluteState(TensorizedState, AbsoluteObjectState): + """ + Tensorized state-mixin for ABSOLUTE (single-object) values. + + All values across all object state instances are updated at once via _update_values(), + rather than per individual instance update() call. + + Multi-scene layout + ------------------ + VALUES (S, N, *value_shape) — S = number of scenes, N = number of unique object types + OBJ_IDXS {relative_prim_path: int} — shared N index; same for the same object type in every scene + IDX_OBJS list[list[obj|None]] — IDX_OBJS[scene_idx][obj_idx] = object instance + + Registration and tensor allocation are handled exclusively by ``initialize_view()``, + which is called from ``simulator.py`` after scene changes. + """ + + @classmethod + def global_initialize(cls): + """Initialize the global class-level tensors and indices.""" + # Shape (0, 0, *value_shape) — zero scenes, zero object types; GPU-resident + cls.VALUES = th.empty(0, dtype=cls.value_type, device="cuda").reshape(0, 0, *cls.value_shape) + cls.VALUES_CPU = th.empty(0, dtype=cls.value_type).pin_memory().reshape(0, 0, *cls.value_shape) + cls.PREV_VALUES = th.empty(0, dtype=cls.value_type).reshape(0, 0, *cls.value_shape) + cls.OBJ_IDXS = {} # {relative_prim_path: int} + cls.IDX_OBJS = [] # list[list[obj|None]] + + # Compute and cache state size + # This is the flattened size of @self.value_shape + cls.STATE_SIZE = math.prod(cls.value_shape) + + @classmethod + def initialize_view(cls): + """ + Rebuild all class-level tensors by scanning current objects across all scenes. + Called from ``simulator.py`` after scene changes. Child classes should call + ``super().initialize_view()`` first, then extend with their own initialization. + + Values for objects whose relative_prim_path still exists are carried over; + new slots are initialized to zero (subclasses override to set correct defaults). + """ + # Snapshot for carry-over (OBJ_IDXS / VALUES are None on the very first call) + prev_obj_idxs = dict(cls.OBJ_IDXS) if cls.OBJ_IDXS is not None else {} + prev_values = cls.VALUES.clone() if cls.VALUES is not None and cls.VALUES.numel() > 0 else None + + # Reset + cls.global_initialize() + + # Scan all scenes and register objects that have this state + for scene_idx, scene in enumerate(og.sim.scenes): + for obj in scene.objects: + if cls not in obj.states: + continue + rel_path = obj.relative_prim_path + + # Extend scene dimension if this is a new scene index + while len(cls.IDX_OBJS) <= scene_idx: + cls.IDX_OBJS.append([None] * len(cls.OBJ_IDXS)) + + # Register new relative path if first seen across all scenes + if rel_path not in cls.OBJ_IDXS: + cls.OBJ_IDXS[rel_path] = len(cls.OBJ_IDXS) + for s_row in cls.IDX_OBJS: + s_row.append(None) + + cls.IDX_OBJS[scene_idx][cls.OBJ_IDXS[rel_path]] = obj + + # Allocate VALUES once then fill carry-over values. + S = len(cls.IDX_OBJS) + N = len(cls.OBJ_IDXS) + if S > 0 and N > 0: + cls.VALUES = th.zeros((S, N, *cls.value_shape), dtype=cls.value_type, device="cuda") + + if prev_values is not None and prev_values.numel() > 0: + # Fast path if we have identical object layout across scenes. + # Used for topology changes that add/remove no objects and preserve ordering — e.g. an + # assisted-grasp/attachment joint. + if prev_obj_idxs == cls.OBJ_IDXS and prev_values.shape == cls.VALUES.shape: + cls.VALUES.copy_(prev_values) + else: + # General carry-over, vectorized: for each scene, gather the surviving objects' + # previous values into their new slots. + # "surviving" = objects present both before and after this re-init, as + # (old_index, new_index) pairs — old_index into prev_values, new_index into VALUES. + surviving = [ + (old_index, cls.OBJ_IDXS[rel_path]) + for rel_path, old_index in prev_obj_idxs.items() + if rel_path in cls.OBJ_IDXS + ] + for scene_idx in range(min(prev_values.shape[0], S)): + # Restrict to survivors that actually exist in THIS scene. + in_scene = [ + (old_i, new_i) for (old_i, new_i) in surviving if cls.IDX_OBJS[scene_idx][new_i] is not None + ] + if in_scene: + old_idx = th.tensor( + [old_i for old_i, _ in in_scene], dtype=th.long, device=cls.VALUES.device + ) + new_idx = th.tensor( + [new_i for _, new_i in in_scene], dtype=th.long, device=cls.VALUES.device + ) + # VALUES[scene, new_i] = prev_values[scene, old_i] for every surviving object. + cls.VALUES[scene_idx][new_idx] = prev_values[scene_idx][old_idx] + + # Rebuild pinned CPU mirror — synchronous copy so _get_value() is valid before first async copy + cls.VALUES_CPU = th.zeros(cls.VALUES.shape, dtype=cls.value_type).pin_memory() + if cls.VALUES.numel() > 0: + cls.VALUES_CPU.copy_(cls.VALUES) + + # PREV_VALUES mirrors VALUES_CPU on CPU; seed so first post_update() fires no spurious state_updated(). + cls.PREV_VALUES = cls.VALUES_CPU.clone() + + # Wrap VALUES as wp.array handles for use inside Warp kernels and graph capture. + # Wrappers cached at the class level; never recreated per call. + if cls.VALUES.numel() > 0: + cls.VALUES_WP = _wp_from_torch(cls.VALUES) + cls.VALUES_CPU_WP = _wp_from_torch(cls.VALUES_CPU) + else: + cls.VALUES_WP = None + cls.VALUES_CPU_WP = None + + # Mark the captured wp.graph as stale — the simulator will re-capture before the next step. + # update_handles() always calls the view APIs' initialize_view BEFORE this, so any + # RigidContactAPI / RigidBodyViewAPI / ArticulatedObjectViewAPI buffer reallocations + # are already covered by the time this fires. + TensorizedState.graph_dirty = True + + super().initialize_view() + + def _get_value(self): + # Read from the pinned CPU mirror — no GPU stall for Python callers + s = self.obj.scene.idx + obj_idx = self.OBJ_IDXS[self.obj.relative_prim_path] + val = self.VALUES_CPU[s, obj_idx].to(self.value_type) + if isinstance(val, th.Tensor) and val.numel() == 1: + val = val.item() + return val + + def _set_value(self, new_value): + # Write to both GPU (VALUES) and CPU mirror (VALUES_CPU) synchronously. + # Safe: setters are never called from within _update_values. + s = self.obj.scene.idx + obj_idx = self.OBJ_IDXS[self.obj.relative_prim_path] + self.VALUES[s, obj_idx] = new_value + self.VALUES_CPU[s, obj_idx] = new_value + return True + + def _dump_state(self): + if self.OBJ_IDXS is None or self.obj.relative_prim_path not in self.OBJ_IDXS: + return {self.value_name: th.zeros(self.value_shape, dtype=self.value_type)} + return {self.value_name: self._get_value()} + + def _load_state(self, state): + self._set_value(state[self.value_name]) + + def serialize(self, state): + # If the state value is not an iterable, wrap it in a numpy array + val = ( + state[self.value_name] + if isinstance(state[self.value_name], th.Tensor) + else th.tensor([state[self.value_name]]) + ).float() + return val.flatten() + + def deserialize(self, state): + value_length = int(math.prod(self.value_shape)) + value = state[:value_length].reshape(self.value_shape) + return {self.value_name: value}, value_length + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("TensorizedAbsoluteState") + return classes diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/tensorized_relative_state.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/tensorized_relative_state.py new file mode 100644 index 0000000000000000000000000000000000000000..406de4dbef174ae0224b7f0c7c39ad0cbf6bf301 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/tensorized_relative_state.py @@ -0,0 +1,202 @@ +import math + +import torch as th + +import omnigibson as og +from omnigibson.object_states.object_state_base import RelativeObjectState +from omnigibson.object_states.tensorized_state import TensorizedState, _wp_from_torch +from omnigibson.utils.python_utils import classproperty + + +class TensorizedRelativeState(TensorizedState, RelativeObjectState): + """ + Tensorized state-mixin for RELATIVE (pairwise) values. + + All pairwise values across all object state instances of this type are updated at once + via _update_values(), rather than per individual instance update() call. + + Multi-scene layout + ------------------ + VALUES (S, N, N, *value_shape) — [scene, self_obj, other_obj, ...] + OBJ_IDXS {relative_prim_path: int} — shared N index across both pairwise dims + IDX_OBJS list[list[obj|None]] — IDX_OBJS[scene_idx][obj_idx] = object instance + + Conventions + ----------- + - Diagonal cells `VALUES[s, i, i, ...]` should be False / zero by convention; subclasses + enforce this in their `_update_values` kernel. + - Cross-scene cells (object `a` exists in scene s but `b` does not) should be False / zero; + subclasses enforce via existence-mask checks in their kernel. + + Subclasses are derived states (computed from simulator state each step). The default + `_dump_state` / `_load_state` / `serialize` / `deserialize` / `state_size` are no-ops + because pairwise values are recomputed and don't need to round-trip through saves. + Subclasses may override if persistence is needed. + + `_set_value(self, other, new_value)` raises NotImplementedError by default. Subclasses + that need a setter should override it (typically by copying the original non-tensorized + setter logic and writing into the (s, idx_self, idx_other) cell). + """ + + @classmethod + def global_initialize(cls): + """Initialize the global class-level tensors and indices for the (S, N, N, ...) shape.""" + cls.VALUES = th.empty(0, dtype=cls.value_type, device="cuda").reshape(0, 0, 0, *cls.value_shape) + cls.VALUES_CPU = th.empty(0, dtype=cls.value_type).pin_memory().reshape(0, 0, 0, *cls.value_shape) + cls.PREV_VALUES = th.empty(0, dtype=cls.value_type).reshape(0, 0, 0, *cls.value_shape) + cls.OBJ_IDXS = {} # {relative_prim_path: int} + cls.IDX_OBJS = [] # list[list[obj|None]] + + # Per-pair state size (flattened size of value_shape). Full per-instance state size + # depends on N; see `state_size` property below. + cls.STATE_SIZE = math.prod(cls.value_shape) + + @classmethod + def initialize_view(cls): + """ + Rebuild all class-level tensors by scanning current objects across all scenes. + Called from ``simulator.py`` after scene changes. + + Two-pass to avoid the O(N^3) grow-by-cat pattern the naive implementation has: + pass 1 only touches Python dicts/lists to settle OBJ_IDXS / IDX_OBJS at their + final size; pass 2 allocates VALUES once at (S, N, N, *value_shape) and fills + carry-over values directly. For a scene with N objects across S scenes this is + O(S*N^2) instead of O(N^3). + + Carry-over: for each (a, b) pair where both relative_prim_paths still exist, the + previous VALUES[s, a, b] is preserved. New rows/columns are zero-initialized. + """ + # Snapshot for carry-over (OBJ_IDXS / VALUES are None on the very first call) + prev_obj_idxs = dict(cls.OBJ_IDXS) if cls.OBJ_IDXS is not None else {} + prev_values = cls.VALUES.clone() if cls.VALUES is not None and cls.VALUES.numel() > 0 else None + + # Reset + cls.global_initialize() + + # Pass 1: scan all scenes, settle OBJ_IDXS / IDX_OBJS at final shape (Python only). + for scene_idx, scene in enumerate(og.sim.scenes): + for obj in scene.objects: + if cls not in obj.states: + continue + rel_path = obj.relative_prim_path + + # Extend scene dimension if this is a new scene index + while len(cls.IDX_OBJS) <= scene_idx: + cls.IDX_OBJS.append([None] * len(cls.OBJ_IDXS)) + + # Register new relative path if first seen across all scenes + if rel_path not in cls.OBJ_IDXS: + cls.OBJ_IDXS[rel_path] = len(cls.OBJ_IDXS) + for s_row in cls.IDX_OBJS: + s_row.append(None) + + cls.IDX_OBJS[scene_idx][cls.OBJ_IDXS[rel_path]] = obj + + # Pass 2: allocate VALUES once at the final shape, then fill carry-over values. + S = len(cls.IDX_OBJS) + N = len(cls.OBJ_IDXS) + if S > 0 and N > 0: + cls.VALUES = th.zeros((S, N, N, *cls.value_shape), dtype=cls.value_type, device="cuda") + + if prev_values is not None and prev_values.numel() > 0: + # Fast path if we have identical object layout across scenes. + # Used for topology changes that adds/removes no objects and preserves ordering — e.g. an assisted-grasp/attachment joint. + if prev_obj_idxs == cls.OBJ_IDXS and prev_values.shape == cls.VALUES.shape: + cls.VALUES.copy_(prev_values) + else: + # General carry-over, vectorized: for each scene, block-copy the surviving pairs' + # previous values. + # "surviving" = objects present both before and after this re-init, as + # (old_index, new_index) pairs — old_index into prev_values, new_index into VALUES. + surviving = [ + (old_index, cls.OBJ_IDXS[rel_path]) + for rel_path, old_index in prev_obj_idxs.items() + if rel_path in cls.OBJ_IDXS + ] + for scene_idx in range(min(prev_values.shape[0], S)): + # Restrict to survivors that actually exist in THIS scene. + in_scene = [ + (old_i, new_i) for (old_i, new_i) in surviving if cls.IDX_OBJS[scene_idx][new_i] is not None + ] + if in_scene: + old_idx = th.tensor( + [old_i for old_i, _ in in_scene], dtype=th.long, device=cls.VALUES.device + ) + new_idx = th.tensor( + [new_i for _, new_i in in_scene], dtype=th.long, device=cls.VALUES.device + ) + # VALUES[scene, new_a, new_b] = prev_values[scene, old_a, old_b] for every (a, b) + # survivor pair, in one indexed assignment. + cls.VALUES[scene_idx][new_idx[:, None], new_idx[None, :]] = prev_values[scene_idx][ + old_idx[:, None], old_idx[None, :] + ] + + # Rebuild pinned CPU mirror — synchronous copy so _get_value() is valid before first async copy + cls.VALUES_CPU = th.zeros(cls.VALUES.shape, dtype=cls.value_type).pin_memory() + if cls.VALUES.numel() > 0: + cls.VALUES_CPU.copy_(cls.VALUES) + + cls.PREV_VALUES = cls.VALUES_CPU.clone() + + # Wrap as wp.array for kernel consumption + if cls.VALUES.numel() > 0: + cls.VALUES_WP = _wp_from_torch(cls.VALUES) + cls.VALUES_CPU_WP = _wp_from_torch(cls.VALUES_CPU) + else: + cls.VALUES_WP = None + cls.VALUES_CPU_WP = None + + # Mark the captured wp.graph as stale — the simulator will re-capture before the next step. + TensorizedState.graph_dirty = True + + super().initialize_view() + + def _get_value(self, other): + # Read from the pinned CPU mirror — no GPU stall for Python callers. + s = self.obj.scene.idx + idx_self = self.OBJ_IDXS[self.obj.relative_prim_path] + idx_other = self.OBJ_IDXS[other.relative_prim_path] + val = self.VALUES_CPU[s, idx_self, idx_other].to(self.value_type) + if isinstance(val, th.Tensor) and val.numel() == 1: + val = val.item() + return val + + def _set_value(self, other, new_value): + """Default: not implemented for tensorized relative states. + + Subclasses may override to support pairwise setters by copying the original + non-tensorized setter logic — typically writing the value into both + ``self.VALUES[s, idx_self, idx_other]`` and ``self.VALUES_CPU[s, idx_self, idx_other]``. + Most tensorized relative states (e.g. Adjacency, Touching) are derived from + simulator state and don't expose setters. + """ + raise NotImplementedError( + f"_set_value not implemented for {self.__class__.__name__}. " + "Override in the subclass if a pairwise setter is needed." + ) + + # Pairwise values are derived state; persistence is a no-op by default. + # Subclasses override if round-tripping through saves is required. + + def _dump_state(self): + return {} + + def _load_state(self, state): + pass + + def serialize(self, state): + return th.empty(0) + + def deserialize(self, state): + return {}, 0 + + @property + def state_size(self): + return 0 + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("TensorizedRelativeState") + return classes diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/tensorized_state.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/tensorized_state.py new file mode 100644 index 0000000000000000000000000000000000000000..ece5c5b1020f7834a03141a4c6d5c0a3aa487b0f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/tensorized_state.py @@ -0,0 +1,226 @@ +import torch as th +import warp as wp + +from omnigibson.utils.python_utils import classproperty +from omnigibson.utils.ui_utils import create_module_logger + +# Create module logger +log = create_module_logger(module_name=__name__) + + +def _wp_from_torch(t): + """ + Wrap a torch tensor as a wp.array. Bool tensors are wrapped as wp.uint8 + (storage is byte-per-bool in torch already). + """ + if t.dtype == th.bool: + return wp.from_torch(t.view(th.uint8), dtype=wp.uint8) + return wp.from_torch(t) + + +class TensorizedState: + """ + Mixin holding the shared lifecycle and class-level tensors for tensorized states. + + Concrete tensorized states should inherit through one of two front-ends: + - ``TensorizedAbsoluteState`` for single-object values, VALUES shape (S, N, *value_shape) + - ``TensorizedRelativeState`` for pairwise values, VALUES shape (S, N, N, *value_shape) + + Both front-ends provide their own ``global_initialize`` / ``initialize_view`` to allocate + their respective VALUES tensor; everything else (pre/post update, change detection, + wp.array wrapping, graph_dirty flag) lives here and is shared. + + Subclasses MUST implement ``_update_values``. + """ + + # Tensor of raw internally tracked values — GPU-resident during computation. + # Shape is (S, N, ...) for absolute or (S, N, N, ...) for relative. + VALUES = None + + # Pinned CPU mirror of VALUES — updated via async DMA after each global_update pass. + # _get_value() always reads from here to avoid GPU stalls for Python callers. + VALUES_CPU = None + + # CPU tensor to store VALUES_CPU from the previous step — used for change detection. + PREV_VALUES = None + + # Dictionary mapping relative prim path to index in the N dimension of VALUES + OBJ_IDXS = None + + # 2-D list: IDX_OBJS[scene_idx][obj_idx] = object instance (or None if absent in that scene) + IDX_OBJS = None + + # Int representing per-object state size (flattened size of value_shape) + STATE_SIZE = None + + # wp.array views over VALUES for use inside Warp kernels and graph capture. + # Wrapped once in initialize_view; never re-created per call. Re-wrapped on every + # initialize_view because torch storage is reallocated there. + VALUES_WP = None + + # wp.array view over the (pinned) VALUES_CPU mirror. Used so that the GPU→CPU mirror + # copy inside the captured wp.graph runs as a wp.copy (graph-safe), not as torch's + # .copy_ which uses the legacy stream and is forbidden during capture. + VALUES_CPU_WP = None + + # Set to True any time any subclass's initialize_view runs, signalling that the + # captured wp.graph holds stale pointers/shapes and must be re-captured. The simulator + # checks-and-resets this before each step. update_handles() always calls the view APIs' + # initialize_view before every TensorizedState's initialize_view, so any viewAPI + # buffer reallocation is automatically covered. + graph_dirty = True + + # Set to True whenever something has happened that could leave VALUES_CPU one frame + # behind the live world: a physics step, a direct pose mutation, a joint mutation, etc. + # Cleared by ``og.sim._refresh_state_caches()``. The lazy-refresh gate in + # ``TensorizedAbsoluteState._get_value`` / ``TensorizedRelativeState._get_value`` checks + # this flag and triggers a refresh on first read so callers always observe fresh state + # without having to know about the cache lifecycle. + caches_dirty = False + + # Re-entrance guard for the lazy refresh: while `_refresh_state_caches` is running, any + # nested `_get_value` should read the (now-being-recomputed) cache directly without + # re-triggering a refresh. Set/cleared inside the simulator helper. + _refresh_in_progress = False + + # Single-element wp.array on cuda holding the seconds elapsed for the current logical step + # (the caller-provided dt, see pre_update). Read by time-dependent subclasses' kernels + # (Temperature, ToggledOn, SlicerActive) inside the captured graph. We use a wp.array (not a + # wp.float32 scalar passed at launch) so per-frame mutation is visible to graph replays without + # re-capture — scalars passed via wp.float32(...) bake the value at capture time. + _dt = None + + @classmethod + def maybe_refresh_caches(cls): + """Helper for `get_value`: if caches are dirty (and we're not already + mid-refresh), run the lazy refresh so the upcoming read sees fresh values. + """ + if cls.caches_dirty and not cls._refresh_in_progress: + import omnigibson as og # local import to avoid module-level cycle + + og.sim._refresh_state_caches() + + @classmethod + def initialize_view(cls): + """ + Δt-tracking setup shared across tensorized states. Subclasses' initialize_view should + call ``super().initialize_view()`` after they finish allocating VALUES. + + Allocates the 1-element wp.array that pre_update fills with the per-step dt each step. + """ + if cls._dt is None: + cls._dt = wp.zeros(shape=(1,), dtype=wp.float32, device="cuda") + + def get_value(self, *args, **kwargs): + self.maybe_refresh_caches() + return super().get_value(*args, **kwargs) + + @classmethod + def pre_update(cls, dt=0.0): + """ + CPU-side prep run BEFORE global_update each step. Snapshots VALUES_CPU into + PREV_VALUES so post_update() can detect changes after the warp work completes, + and stores the caller-provided ``dt`` (seconds elapsed for this logical step) into + cls._dt for time-dependent kernels to read inside the captured graph. + + Lives outside the captured wp.graph. + + Subclasses may override to add per-state CPU prep (e.g. ToggledOn refreshing + marker world poses). + """ + if cls.VALUES_CPU is None or cls.VALUES_CPU.numel() == 0: + return + cls.PREV_VALUES.copy_(cls.VALUES_CPU) + + if cls._dt is not None: + cls._dt.fill_(dt) + + @classmethod + def global_update(cls): + """ + Globally update all values via _update_values() and async-copy to VALUES_CPU. + Change detection and post_update() are called separately by the simulator after synchronize(). + Skips if there are no tracked objects. + + Should be capturable inside wp.graph: only emits CUDA work via Warp + kernel launches and Warp memcpy. + """ + if cls.VALUES is None or cls.VALUES.numel() == 0: + return + + cls._update_values(values=cls.VALUES) + # Mirror VALUES → VALUES_CPU. Use wp.copy when both wp.array handles exist (graph-safe); + # fall back to torch's non-blocking copy otherwise (e.g. partial init). + # TODO(vector): Why would one (torch) exist and not the other (wp)? + if cls.VALUES_WP is not None and cls.VALUES_CPU_WP is not None: + wp.copy(cls.VALUES_CPU_WP, cls.VALUES_WP) + else: + cls.VALUES_CPU.copy_(cls.VALUES, non_blocking=True) + + @classmethod + def post_update(cls): + """ + Called by the simulator after th.cuda.synchronize(). Compares VALUES_CPU with PREV_VALUES + (both CPU) to detect changes, fires state_updated() for affected objects, then updates PREV_VALUES. + + Reduce semantics: + - Absolute (S, N, *value_shape): reduces over value_shape dims to get per-(scene, obj) row mask. + - Relative (S, N, N, *value_shape): reduces over (other-obj, *value_shape) dims to get per-(scene, self-obj) + row mask. A pairwise-cell change fires state_updated() once on the row's self-object. + """ + if cls.VALUES_CPU is None or cls.VALUES_CPU.numel() == 0: + return + S = cls.VALUES_CPU.shape[0] + + diff = cls.VALUES_CPU != cls.PREV_VALUES + changed_mask = th.any(diff, dim=tuple(range(2, diff.ndim))) if diff.ndim > 2 else diff + for s_idx in range(S): + for obj_idx in th.where(changed_mask[s_idx])[0].tolist(): + obj = cls.IDX_OBJS[s_idx][obj_idx] + if obj is None: + # Column vacated in this scene (e.g. mid-play object removal) but kept + # alive by another scene sharing the relative prim path — see IDX_OBJS. + continue + obj.state_updated() + + @classmethod + def _update_values(cls, values): + """ + Updates all internally tracked @values for this object state. Should be implemented by subclass. + Mutates @values in-place. Must not return anything. + + Args: + values (th.tensor): Tensorized value array. Shape depends on the front-end: + (S, N, *value_shape) for TensorizedAbsoluteState, + (S, N, N, *value_shape) for TensorizedRelativeState. + """ + raise NotImplementedError + + @classproperty + def value_shape(cls): + """ + Returns: + tuple: Expected shape of the per-object state instance value. Default is () (scalar). + """ + return () + + @classproperty + def value_type(cls): + """ + Returns: + type: Type of the internal value array, e.g., bool, th.uint, th.float32, etc. Default is th.float32 + """ + return th.float32 + + @classproperty + def value_name(cls): + """ + Returns: + str: Name of the value key to assign when dumping / loading the state. Should be implemented by subclass + """ + raise NotImplementedError + + @property + def state_size(self): + # This is merely the class state size + return self.STATE_SIZE diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/toggle.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/toggle.py new file mode 100644 index 0000000000000000000000000000000000000000..39c183a4948233e1fd68340bf729ef28e95834fc --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/toggle.py @@ -0,0 +1,793 @@ +import torch as th +import warp as wp + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros +from omnigibson.object_states.link_based_state_mixin import LinkBasedStateMixin +from omnigibson.object_states.object_state_base import BooleanStateMixin +from omnigibson.object_states.open_state import Open +from omnigibson.object_states.tensorized_absolute_state import TensorizedAbsoluteState +from omnigibson.prims.geom_prim import GeomPrim +from omnigibson.utils.constants import PrimType +from omnigibson.utils.numpy_utils import vtarray_to_torch +from omnigibson.utils.python_utils import classproperty +from omnigibson.utils.usd_utils import ( + RigidBodyViewAPI, + RigidContactAPI, + absolute_prim_path_to_scene_relative, + create_primitive_mesh, + rigid_inverse_mat44, +) + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.TOGGLE_META_LINK_TYPE = "togglebutton" +m.DEFAULT_SCALE = 0.1 +# Seconds a robot finger must stay in contact with the toggle marker before the state flips. +m.CAN_TOGGLE_SECONDS = 0.15 + + +@wp.kernel +def _check_overlap_kernel( + pose_matrices: wp.array(dtype=wp.mat44), # RigidBodyViewAPI.POSE_MATRICES (N_links,) + mesh_ids: wp.array(dtype=wp.uint64), # RigidBodyViewAPI.LINK_MESH_IDS (N_links,) + marker_parent_link_idx: wp.array(dtype=wp.int32), # (n_markers,) flat link idx of marker's parent rigid body + marker_local_offset: wp.array(dtype=wp.vec3), # (n_markers,) marker center in its parent link's local frame + marker_radii: wp.array(dtype=wp.float32), # (n_markers,) marker radius + marker_finger_pair: wp.array(dtype=wp.vec2i), # (P,) — pair[p] = vec2i(marker_idx, finger_link_flat_idx) + marker_to_obj_idx_flat: wp.array( + dtype=wp.int32 + ), # (n_markers,) flat (scene_idx*num_objects + obj_idx) for each marker + mask_can_toggle_flat: wp.array(dtype=wp.int32), # (S*O,) +): + """ + Each thread checks a (marker, finger_link) pair. + + This kernel does the following things: + - get marker's world center = parent rigid body's pose @ static local offset, then transform into the + finger link's local frame, + - use wp.mesh_query_point_no_sign(finger_mesh, marker_position, marker_radius) to check whether overlap + - On hit, atomic-max the (scene, obj) mask cell up to 2 + + mask needs to be int 32 because Warp's atomic_max doesn't support uint8. + """ + thread_id = wp.tid() + pair = marker_finger_pair[thread_id] + marker_idx = pair[0] + obj_idx = marker_to_obj_idx_flat[marker_idx] + # Skip if this marker not touched by any fingers + if mask_can_toggle_flat[obj_idx] != wp.int32(1): + return + finger_link_idx = pair[1] + finger_mesh_id = mesh_ids[finger_link_idx] + if finger_mesh_id == wp.uint64(0): + return + + # Derive marker world center from its parent link's current pose + static local offset. + parent_pose = pose_matrices[marker_parent_link_idx[marker_idx]] + offset = marker_local_offset[marker_idx] + marker_center_world_frame = wp.mul(parent_pose, wp.vec4(offset[0], offset[1], offset[2], 1.0)) + # Transform marker center from world to finger link local frame. + inv_pose = rigid_inverse_mat44(pose_matrices[finger_link_idx]) + cl4 = wp.mul(inv_pose, marker_center_world_frame) + marker_center_local_frame = wp.vec3(cl4[0], cl4[1], cl4[2]) + + marker_radius = marker_radii[marker_idx] + query = wp.mesh_query_point_no_sign(finger_mesh_id, marker_center_local_frame, marker_radius) + if query.result: + wp.atomic_max(mask_can_toggle_flat, obj_idx, wp.int32(2)) + + +@wp.kernel +def _check_requires_closed_kernel( + requires_closed_idx_in_this: wp.array(dtype=wp.int32), # (R,) flat idx into VALUES (s*O + obj) + requires_closed_idx_in_open: wp.array(dtype=wp.int32), # (R,) flat idx into Open.VALUES + open_values: wp.array(dtype=wp.uint8), # Open.VALUES_WP flattened (S*O_open,) + toggle_values: wp.array(dtype=wp.uint8), # VALUES.view(-1) (S*O_toggle,) + robots_can_toggle_time: wp.array(dtype=wp.float32), # (S*O,) — seconds accumulated + mask_can_toggle: wp.array(dtype=wp.int32), # (S*O,) +): + """ + Each thread checks 1 object in 1 scene. + If Open.VALUES == True, Toggle.VALUES = False, robots_can_toggle_time = 0, mask_can_toggle = False. + """ + thread_id = wp.tid() + if open_values[requires_closed_idx_in_open[thread_id]] != wp.uint8(0): + idx = requires_closed_idx_in_this[thread_id] + toggle_values[idx] = wp.uint8(0) + robots_can_toggle_time[idx] = 0.0 + mask_can_toggle[idx] = wp.int32(0) + + +@wp.kernel +def _set_toggle_value_kernel( + values: wp.array2d(dtype=wp.uint8), # (S, O) + mask_can_toggle_flat: wp.array(dtype=wp.int32), # (S*O,) — single cached 1D view (see _update_values) + robots_can_toggle_time: wp.array2d(dtype=wp.float32), # (S, O) — seconds accumulated this hold + O: wp.int32, # second dim of `values` — to flatten (s, o) → s*O+o for the mask + can_toggle_threshold_seconds: wp.float32, + dt: wp.array(dtype=wp.float32), +): + """ + Each thread works on 1 object in 1 scene. + When mask == 2, all three requirements passed (contact, requires_closed, overlaps). + Accumulate dt seconds and flip values when the counter first crosses the threshold. + Reset mask to 0. + """ + s, o = wp.tid() + idx = s * O + o + eligible = wp.int32(0) + if mask_can_toggle_flat[idx] == wp.int32(2): + eligible = wp.int32(1) + + prev_time = robots_can_toggle_time[s, o] + if eligible != wp.int32(0): + robots_can_toggle_time[s, o] = prev_time + dt[0] + else: + robots_can_toggle_time[s, o] = 0.0 + + new_time = robots_can_toggle_time[s, o] + flip = wp.int32(0) + if prev_time < can_toggle_threshold_seconds and new_time >= can_toggle_threshold_seconds: + flip = eligible + + mask_can_toggle_flat[idx] = wp.int32(0) + + if flip != wp.int32(0): + values[s, o] = wp.uint8(1) - values[s, o] + + +class ToggledOn(TensorizedAbsoluteState, BooleanStateMixin, LinkBasedStateMixin): + """ + Boolean state representing whether an object has been toggled on. + """ + + # S = number of scenes + # O = number of toggleable objects + + # wp.array2d (S, O) float32 — seconds the robot finger has been overlapping the marker for + # the current hold session. Reset to 0 when eligibility breaks. + _robots_can_toggle_time = None + + # (O_requires_closed,) int32 — flat-index lookups into Open.VALUES and ToggledOn.VALUES. + _requires_closed_obj_idxes_in_open_values = None + _requires_closed_obj_idxes_in_this_values = None + + # list[list[GeomPrim]]: visual toggle-button markers, one per tracked object. Shape (S, O). + # Used in _check_overlap and color updates. + visual_markers = None + + # Contact masks + # R_s = number of contact-matrix rows (links on the "who is touching" side) for scene s + # C_s = number of contact-matrix columns (links on the "what are they touching" side) for scene s + _finger_query_mask = None # list[wp.array(1, R_s) uint8 | None] — finger row mask per scene + _toggable_objs_with_mask = None # list[wp.array(O, C_s) uint8 | None] — toggle-object col masks per scene + + # list[list of links of manipulation robots in scene s], len = S + _finger_links = [] + + # Scratch mask buffer. _mask_can_toggle is wp.array2d (S, O) int32; _mask_can_toggle_flat and + # _mask_can_toggle_per_scene[s] are wp views that share storage (reshape + row slice). + _mask_can_toggle = None # wp.array2d (S, O) int32 + _mask_can_toggle_flat = None # wp.array (S*O,) view of _mask_can_toggle + _mask_can_toggle_per_scene = None # list[wp.array(O,) | None] — row slice of _mask_can_toggle + + # Marker info — filled in initialize_view from USD reads. + # Marker is a static visual child of the togglebutton meta link, so its local offset and + # radius never change. Per-step world center is derived inside the overlap kernel from the + # parent link's current pose matrix in RigidBodyViewAPI.POSE_MATRICES. + _marker_parent_link_idx = None # wp.array (n_markers,) int32 — flat link idx in RigidBodyViewAPI + _marker_local_offset = None # wp.array (n_markers,) vec3 — marker center in parent link's local frame + _marker_radii = None # wp.array (n_markers,) float32 — sphere radius + + # === Pair index buffers built once in initialize_view (covers all (marker, finger_link) pairs across scenes). === + # (P,) wp.vec2i — each row is (marker_idx, finger_link_flat_idx) for one (marker, finger) pair. + _marker_finger_pair = None + _marker_to_obj_idx_flat = None # wp.array (n_markers,) int32 — flat (s*O + obj_idx) per marker + + COLOR_ON = th.tensor([0, 1.0, 0]) # green — toggle is on + COLOR_OFF = th.tensor([1.0, 0, 0]) # red — toggle is off + + @classproperty + def value_type(cls): + return th.bool + + @classproperty + def value_name(cls): + return "toggle" + + @classmethod + def global_initialize(cls): + super().global_initialize() + + cls._robots_can_toggle_time = None + cls._requires_closed_obj_idxes_in_open_values = None + cls._requires_closed_obj_idxes_in_this_values = None + cls.visual_markers = [] + + cls._finger_links = [] + cls._finger_query_mask = None + cls._toggable_objs_with_mask = None + + cls._mask_can_toggle = None + cls._mask_can_toggle_flat = None + cls._mask_can_toggle_per_scene = None + + @classmethod + def initialize_view(cls): + """ + Rebuild all class-level tensors after scene changes. + """ + # Snapshot existing states. wp.to_torch shares storage with the wp array; + # .cpu() forces a single GPU→CPU copy so the per-element carry-over reads stay on CPU. + prev_obj_idxs = dict(cls.OBJ_IDXS) if cls.OBJ_IDXS is not None else {} + prev_time_cpu = ( + wp.to_torch(cls._robots_can_toggle_time).cpu() if cls._robots_can_toggle_time is not None else None + ) + + # Base class rebuilds OBJ_IDXS, IDX_OBJS, VALUES (with value carry-over for toggle bool) + super().initialize_view() + + S, O = len(cls.IDX_OBJS), len(cls.OBJ_IDXS) + + cls._init_requires_closed_logic(O) + + if S == 0 or O == 0: + cls._init_empty_states() + return + + # Carry over _robots_can_toggle_time for surviving objects via a CPU scratch tensor, + # then ship to a fresh GPU wp.array. + new_time_cpu = th.zeros((S, O), dtype=th.float32) + if prev_time_cpu is not None: + for relative_prim_path, obj_idx_old in prev_obj_idxs.items(): + if relative_prim_path not in cls.OBJ_IDXS: + continue + obj_idx = cls.OBJ_IDXS[relative_prim_path] + for scene_idx in range(min(prev_time_cpu.shape[0], S)): + new_time_cpu[scene_idx, obj_idx] = prev_time_cpu[scene_idx, obj_idx_old] + cls._robots_can_toggle_time = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + new_time_cpu, "float32", device="cuda" + ) + + marker_finger_pairs = cls._init_finger(S, O) + cls._init_marker(S, O, marker_finger_pairs) + + @classmethod + def _init_requires_closed_logic(cls, O): + """ + Build the (R,) flat-index lookup tables consumed by `_check_requires_closed_kernel`: + for each (scene, toggle_obj) pair where requires_closed=True, store its flat index in + ToggledOn.VALUES (s*O + o_toggle) AND its flat index in Open.VALUES (s*O_open + o_open). + Two different O dims are why we need both. + """ + requires_closed_obj_idxes_in_open_values = [] + requires_closed_obj_idxes_in_this_values = [] + for scene_idx, scene in enumerate(cls.IDX_OBJS): + for obj_idx, toggle_obj in enumerate(scene): + if toggle_obj is None: + continue + if not toggle_obj.states[ToggledOn].requires_closed: + continue + requires_closed_obj_idxes_in_this_values.append(scene_idx * O + obj_idx) + idx_in_open_object_dim = Open.OBJ_IDXS[toggle_obj.relative_prim_path] + open_values_object_dim_size = Open.VALUES.shape[1] + requires_closed_obj_idxes_in_open_values.append( + scene_idx * open_values_object_dim_size + idx_in_open_object_dim + ) + # int32 so the kernel can index with wp.int32. + if requires_closed_obj_idxes_in_open_values: + cls._requires_closed_obj_idxes_in_open_values = ( + lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + requires_closed_obj_idxes_in_open_values, "int32", device="cuda" + ) + ) + cls._requires_closed_obj_idxes_in_this_values = ( + lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + requires_closed_obj_idxes_in_this_values, "int32", device="cuda" + ) + ) + else: + cls._requires_closed_obj_idxes_in_open_values = None + cls._requires_closed_obj_idxes_in_this_values = None + + @classmethod + def _init_empty_states(cls): + """ + Empty-scene (S == 0 or O == 0) early-init: clear every per-scene/per-marker buffer + to a safe default (None or empty list) so `_update_values` short-circuits cleanly. + """ + cls._robots_can_toggle_time = None + cls._finger_query_mask = [] + cls._toggable_objs_with_mask = [] + cls._mask_can_toggle = None + cls._mask_can_toggle_flat = None + cls._mask_can_toggle_per_scene = [] + cls._marker_parent_link_idx = None + cls._marker_local_offset = None + cls._marker_radii = None + cls._marker_finger_pair = None + cls._marker_to_obj_idx_flat = None + + @classmethod + def _init_finger(cls, S, O): + """ + Per-scene init for is_in_contact_batch_wp_kernel + - Collect a scene's manipulation-robot finger links. + - Build finger query_mask + toggle-object with_mask for is_in_contact_batch_warp. + - Allocate the (S, O) int32 mask buffer + per-scene row wp.array slices used as output tensor for kernel + - Collect (marker_idx, finger_link_flat_idx) pairs that the overlap kernel will iterate + over (Stage 4); only valid markers are added so the kernel never sees garbage poses. + + Returns: + list[(int, int)]: marker_finger_pairs, consumed by _init_marker. + """ + marker_finger_pairs = [] # list[(marker_idx, finger_link_flat_idx)] + cls._finger_query_mask = [] + cls._toggable_objs_with_mask = [] + cls._mask_can_toggle_per_scene = [] + + # _mask_can_toggle_flat and _mask_can_toggle_per_scene[s] + # are wp views that share storage with this allocation (reshape + row slice). + cls._mask_can_toggle = wp.zeros((S, O), dtype=wp.int32, device="cuda") + cls._mask_can_toggle_flat = cls._mask_can_toggle.reshape((S * O,)) + + for scene_idx, scene in enumerate(og.sim.scenes): + # Get all finger links and their idx in RigidBodyViewAPI in this scene + finger_links = [] + finger_link_flat_idxs = [] + for robot in scene.robots: + if robot.is_manipulation: + for links in robot.finger_links.values(): + for link in links: + finger_links.append(link) + finger_link_flat_idxs.append(RigidBodyViewAPI.get_flat_idx(link.prim_path)) + + cls._finger_links.append(finger_links) + if not finger_links: + # Keep all 3 per-scene lists in lockstep so the per-step loop can + # index any of them by scene_idx without an IndexError. + cls._finger_query_mask.append(None) + cls._toggable_objs_with_mask.append(None) + cls._mask_can_toggle_per_scene.append(None) + continue + + for obj_idx in range(O): + toggle_obj = cls.IDX_OBJS[scene_idx][obj_idx] + # Skip pair generation for objects whose marker isn't set yet (object not + # fully _initialize'd, or asset has no togglebutton meta link). Their marker + # static info is left at zeros, so we must also skip here so the kernel + # doesn't query BVH with a garbage parent pose. + if toggle_obj is None or toggle_obj.states[ToggledOn].marker is None: + continue + marker_idx_flat = scene_idx * O + obj_idx + for link_flat in finger_link_flat_idxs: + marker_finger_pairs.append((marker_idx_flat, link_flat)) + + # Build toggle-able object with mask — shape (O, C_s) + toggleable_obj_with_mask_rows = [] + any_uninitialized = False + for obj_idx in range(O): + if cls.IDX_OBJS[scene_idx][obj_idx] is None: + any_uninitialized = True + break + toggleable_obj_with_mask_rows.append( + RigidContactAPI.get_contact_col_mask( + scene_idx, list(cls.IDX_OBJS[scene_idx][obj_idx].links.values()) + ) + ) + if any_uninitialized: + cls._finger_query_mask.append(None) + cls._toggable_objs_with_mask.append(None) + cls._mask_can_toggle_per_scene.append(None) + continue + + # Build CPU scratch then ship to wp on GPU. get_contact_row/col_mask return bool; + # cast to uint8 first so wp reads the buffer as uint8 unambiguously. + row_mask = RigidContactAPI.get_contact_row_mask(scene_idx, finger_links) # (R_s,) bool CPU + finger_query_mask_data = row_mask.unsqueeze(0).to(th.uint8) # (1, R_s) CPU uint8 tensor + with_mask_data = th.stack(toggleable_obj_with_mask_rows).to(th.uint8) # (O, C_s) CPU uint8 tensor + + cls._finger_query_mask.append( + lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + finger_query_mask_data, "uint8", device="cuda" + ) + ) + cls._toggable_objs_with_mask.append( + lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list(with_mask_data, "uint8", device="cuda") + ) + cls._mask_can_toggle_per_scene.append(cls._mask_can_toggle[scene_idx]) + + return marker_finger_pairs + + @classmethod + def _init_marker(cls, S, O, marker_finger_pairs): + """ + Init marker info for check_overlap_kernel + - cls.visual_markers[s][o]: GeomPrim handle (for color updates in post_update). + - _marker_to_obj_idx_flat: m → flat (s*O + o) for the atomic_max target. + - _marker_parent_link_idx: m → flat link idx in RigidBodyViewAPI.POSE_MATRICES. + - _marker_local_offset: m → marker center expressed in parent link's local frame. + - _marker_radii: m → BVH query radius (scale * min mesh extent). + - _marker_finger_pair: (P,) wp.vec2i wrapping the (marker, finger) pair list + collected by _init_finger. + + Marker world center is derived inside the kernel each step from the parent link's + current pose @ this static local offset — no per-step USD reads. + """ + n_markers = S * O + cls.visual_markers = [[None] * O for _ in range(S)] + # CPU scratch tensors — convenient for the Python fill loop; dropped after wp conversion. + marker_to_obj_idx_flat_cpu = th.zeros((n_markers,), dtype=th.int32) + marker_parent_link_idx_cpu = th.zeros((n_markers,), dtype=th.int32) + marker_local_offset_cpu = th.zeros((n_markers, 3), dtype=th.float32) + marker_radii_cpu = th.zeros((n_markers,), dtype=th.float32) + + for scene_idx, scene_row in enumerate(cls.IDX_OBJS): + for obj_idx, toggle_obj in enumerate(scene_row): + if toggle_obj is None: + continue + state = toggle_obj.states[ToggledOn] + cls.visual_markers[scene_idx][obj_idx] = state.marker + + marker_idx_flat = scene_idx * O + obj_idx + marker_to_obj_idx_flat_cpu[marker_idx_flat] = marker_idx_flat + # Skip if marker isn't initialized yet — state.link would assert and there's + # nothing meaningful to bake. _init_finger also skips pair generation for these + # markers, so the kernel never reads parent_link_idx / local_offset / radii here. + if state.marker is None: + continue + link = state.link # safe: marker exists ⇒ _initialize completed ⇒ link valid + # Compute marker center in link's local frame from current world poses. This reads + # Fabric world poses, so it must not run mid-step; the simulator defers the + # tensorized-state view rebuild past the physics step (see Simulator.update_handles / + # _on_post_physics_step) so _init_marker() is only ever reached with currently_stepping=False. + marker_pos, _ = state.marker.get_position_orientation() + link_pos, link_ori = link.get_position_orientation() + marker_parent_link_idx_cpu[marker_idx_flat] = RigidBodyViewAPI.get_flat_idx(link.prim_path) + marker_local_offset_cpu[marker_idx_flat] = T.quat2mat(link_ori).T @ (marker_pos - link_pos) + marker_radii_cpu[marker_idx_flat] = th.min(state.marker.extent * state.marker.scale).item() + + # Scalar-typed → create_tensor_from_list; vec3 has no helper, so use wp.array directly + # — it reinterprets the CPU torch (N, 3) float32 buffer as (N,) vec3. + cls._marker_to_obj_idx_flat = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + marker_to_obj_idx_flat_cpu, "int32", device="cuda" + ) + cls._marker_parent_link_idx = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + marker_parent_link_idx_cpu, "int32", device="cuda" + ) + cls._marker_radii = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list( + marker_radii_cpu, "float32", device="cuda" + ) + cls._marker_local_offset = wp.array(marker_local_offset_cpu, dtype=wp.vec3, device="cuda") + + # Wrap (marker, finger) pair list as wp.array of vec2i (each row a 2-element int32 vec). + if marker_finger_pairs: + cls._marker_finger_pair = wp.array(marker_finger_pairs, dtype=wp.vec2i, device="cuda") + else: + cls._marker_finger_pair = None + + def __init__(self, obj, scale=None, requires_closed=False): + self.scale = scale + + if requires_closed: + assert Open in obj.states, f"ToggledOn requires_closed=True but {obj.name} has no Open state." + + # Only used for being written into class tensor by initialize_view() + self._requires_closed_individual = requires_closed + + self.marker = None # init as None, will be filled in initialize() + + super().__init__(obj) + + @property + def requires_closed(self): + return self._requires_closed_individual + + @classmethod + def is_compatible(cls, obj, **kwargs): + # Run super first + compatible, reason = super().is_compatible(obj, **kwargs) + if not compatible: + return compatible, reason + + # Check whether this state has toggledon if required or open if required + if kwargs.get("requires_closed", False) and Open not in obj.states: + return False, f"{cls.__name__} has requires_closed but obj has no Open state!" + + return True, None + + @classmethod + def is_compatible_asset(cls, prim, **kwargs): + # Run super first + compatible, reason = super().is_compatible_asset(prim, **kwargs) + if not compatible: + return compatible, reason + + # Check whether this state has toggledon if required or open if required + if kwargs.get("requires_closed", False) and not Open.is_compatible_asset(prim=prim, **kwargs)[0]: + return False, f"{cls.__name__} has requires_closed but obj has no Open state!" + + return True, None + + @classmethod + def get_optional_dependencies(cls): + deps = super().get_optional_dependencies() + deps.add(Open) + return deps + + @classproperty + def meta_link_types(cls): + return [m.TOGGLE_META_LINK_TYPE] + + @classmethod + def _check_overlap(cls, scene_idx, obj_idx): + """ + Deprecated in warp version. TODO (vector) delete this func + Check whether any robot finger overlaps the toggle-button marker sphere for the object + at class-level index (s_idx, obj_idx). + + Args: + s_idx (int): Scene index. + obj_idx (int): Object type index into cls.IDX_OBJS / cls.visual_markers. + + Returns: + bool: True if a robot finger overlaps the marker sphere. + """ + valid_hit = False + finger_prim_paths = {link.prim_path for link in cls._finger_links[scene_idx]} + + def overlap_callback(hit): + nonlocal valid_hit + valid_hit = hit.rigid_body in finger_prim_paths + # Continue traversal only if we don't have a valid hit yet + return not valid_hit + + marker = cls.visual_markers[scene_idx][obj_idx] + # TODO: This is a temporary fix for flatcache before we properly implement trigger volumes + if marker is None: + return False + og.sim.psqi.overlap_sphere( + radius=th.min(marker.extent * marker.scale).item(), + pos=marker.get_position_orientation()[0].tolist(), + reportFn=overlap_callback, + ) + return valid_hit + + @classmethod + def _update_values(cls, values): + """ + Single-mask tri-state filter chain. The mask carries 3 different meanings across stages: + 0 = shouldn't be toggled + 1 = a finger is in contact with this toggle object + 2 = a finger is in contact AND a finger physically overlaps the marker sphere + + Stages (all run inside wp.graph): + 1. Zero the mask. + 2. use is_in_contact_batch_warp to check whether finger and marker is in contact, + writes mask in {0, 1}. + 3. requires_closed: for objects that are Open yet require closed, force values=0, + robots_can_toggle_time=0, mask=0. + 4. check_overlap kernel: for mask==1, run BVH point-mesh query; on hit, atomic_max + the cell to 2. + 5. Finalize: if mask == 2, accumulate dt seconds; flip values the first step the + counter crosses the seconds threshold; normalize mask back to {0, 1}. + """ + if cls._mask_can_toggle_flat is None: + return + S, O = values.shape[:2] + + mask_flat = cls._mask_can_toggle_flat + values_flat_wp = wp.from_torch(values.view(-1).view(th.uint8), dtype=wp.uint8) + time_flat = cls._robots_can_toggle_time.reshape((S * O,)) + + threshold_seconds = m.CAN_TOGGLE_SECONDS + assert ( + threshold_seconds > og.sim.get_sim_step_dt() + ), f"m.CAN_TOGGLE_SECONDS ({threshold_seconds}s) must exceed one sim step dt ({og.sim.get_sim_step_dt()}s)" + + mask_flat.zero_() + + # check whether finger & marker touching + for scene_idx in range(S): + query_mask = cls._finger_query_mask[scene_idx] + with_mask = cls._toggable_objs_with_mask[scene_idx] + out = cls._mask_can_toggle_per_scene[scene_idx] + if query_mask is None or with_mask is None or out is None: + continue + RigidContactAPI.is_in_contact_batch_warp( + scene_idx=scene_idx, + query_masks_wp=query_mask, # (1, R_s) + with_masks_wp=with_mask, # (O, C_s) + ignore_masks_wp=None, + current_only=False, + out_wp=out, + ) + + # check requires_closed + if cls._requires_closed_obj_idxes_in_open_values is not None and Open.VALUES_WP is not None: + R = cls._requires_closed_obj_idxes_in_open_values.shape[0] + open_flat_wp = wp.from_torch(Open.VALUES.view(-1).view(th.uint8), dtype=wp.uint8) + wp.launch( + kernel=_check_requires_closed_kernel, + dim=R, + inputs=[ + cls._requires_closed_obj_idxes_in_this_values, + cls._requires_closed_obj_idxes_in_open_values, + open_flat_wp, + values_flat_wp, + time_flat, + mask_flat, + ], + device="cuda", + ) + + # check finger & marker overlap + if cls._marker_finger_pair is not None: + wp.launch( + kernel=_check_overlap_kernel, + dim=cls._marker_finger_pair.shape[0], + inputs=[ + RigidBodyViewAPI.POSE_MATRICES, + RigidBodyViewAPI.LINK_MESH_IDS, + cls._marker_parent_link_idx, + cls._marker_local_offset, + cls._marker_radii, + cls._marker_finger_pair, + cls._marker_to_obj_idx_flat, + mask_flat, + ], + device="cuda", + ) + + # accumulate dt seconds onto the per-object counter; flip values on threshold crossing + wp.launch( + kernel=_set_toggle_value_kernel, + dim=(S, O), + inputs=[ + cls.VALUES_WP, + cls._mask_can_toggle_flat, + cls._robots_can_toggle_time, + wp.int32(O), + wp.float32(threshold_seconds), + cls._dt, + ], + device="cuda", + ) + + @classmethod + def post_update(cls): + """Sync visual marker colors for changed objects. + + Overrides (does not extend) TensorizedState.post_update, so it must repeat that + method's guards itself. + """ + if cls.VALUES_CPU is None or cls.VALUES_CPU.numel() == 0: + return + diff = cls.VALUES_CPU != cls.PREV_VALUES + changed_mask = th.any(diff, dim=tuple(range(2, diff.ndim))) if diff.ndim > 2 else diff + for s_idx in range(cls.VALUES_CPU.shape[0]): + for obj_idx in th.where(changed_mask[s_idx])[0].tolist(): + obj = cls.IDX_OBJS[s_idx][obj_idx] + if obj is None: + # Column vacated in this scene (e.g. mid-play object removal) but kept + # alive by another scene sharing the relative prim path — see IDX_OBJS. + continue + obj.state_updated() + marker = cls.visual_markers[s_idx][obj_idx] + # Assets without a togglebutton meta link get no marker (_init_marker leaves + # the entry None and skips them); there is no color to sync. Same guard as + # _check_overlap's. + if marker is None: + continue + marker.color = cls.COLOR_ON if bool(cls.VALUES_CPU[s_idx, obj_idx].item()) else cls.COLOR_OFF + + def _get_value(self): + s = self.obj.scene.idx + obj_idx = self.OBJ_IDXS[self.obj.relative_prim_path] + return bool(self.VALUES[s, obj_idx].item()) + + def _set_value(self, new_value): + """ + Set the toggle state directly (e.g. from BDDL task initialization or external scripts). + Also syncs the visual marker color using the class-level COLOR_ON / COLOR_OFF constants. + + Args: + new_value (bool): Desired toggle on/off state. + + Returns: + bool: True if set successfully; False if blocked by requires_closed + Open state. + """ + if new_value and self.requires_closed and self.obj.states[Open].get_value(): + # If the object is open, we cannot toggle it on + return False + + s = self.obj.scene.idx + obj_idx = self.OBJ_IDXS[self.obj.relative_prim_path] + self.VALUES[s, obj_idx] = 1.0 if new_value else 0.0 + if self.marker is not None: + self.marker.color = type(self).COLOR_ON if new_value else type(self).COLOR_OFF + return True + + def _initialize(self): + super()._initialize() + self.initialize_link_mixin() + + # Make sure this object is not cloth + assert self.obj.prim_type != PrimType.CLOTH, f"Cannot create ToggledOn state for cloth object {self.obj.name}!" + + # See if the mesh exists at the latest dataset's target location + mesh_prim_path = f"{self.link.prim_path}/visuals/mesh_0" + pre_existing_mesh = lazy.isaacsim.core.utils.prims.get_prim_at_path(mesh_prim_path) + + # If not, see if it exists in the legacy format's location + # TODO: Remove this after new dataset release + if not pre_existing_mesh: + mesh_prim_path = f"{self.link.prim_path}/mesh_0" + pre_existing_mesh = lazy.isaacsim.core.utils.prims.get_prim_at_path(mesh_prim_path) + + # Create a primitive mesh if neither option exists + if not pre_existing_mesh: + mesh_prim_path = f"{self.link.prim_path}/visuals/mesh_0" + self.scale = m.DEFAULT_SCALE if self.scale is None else self.scale + # Note: We have to create a mesh (instead of a sphere shape) because physx complains + # about non-uniform scaling for non-meshes + create_primitive_mesh(prim_path=mesh_prim_path, primitive_type="Sphere", extents=1.0) + else: + # Infer radius from mesh if not specified as an input + with og.sim.editing_usd(): + lazy.isaacsim.core.utils.bounds.recompute_extents(prim=pre_existing_mesh) + self.scale = vtarray_to_torch(pre_existing_mesh.GetAttribute("xformOp:scale").Get()) + + # Create the visual geom instance referencing the generated mesh prim + relative_prim_path = absolute_prim_path_to_scene_relative(self.obj.scene, mesh_prim_path) + self.marker = GeomPrim(relative_prim_path=relative_prim_path, name=f"{self.obj.name}_visual_marker") + self.marker.load(self.obj.scene) + self.marker.scale = self.scale + self.marker.initialize() + self.marker.visible = True + self.marker.color = type(self).COLOR_OFF + + @staticmethod + def get_texture_change_params(): + # By default, it keeps the original albedo unchanged. + albedo_add = 0.0 + diffuse_tint = th.tensor([1.0, 1.0, 1.0]) + return albedo_add, diffuse_tint + + @property + def state_size(self): + # Two floats: toggle_state + robot_can_toggle_time (seconds). + return 2 + + def _dump_state(self): + if self.OBJ_IDXS is None or self.obj.relative_prim_path not in self.OBJ_IDXS: + return dict(value=False, hand_in_marker_steps=0.0) + s = self.obj.scene.idx + obj_idx = self.OBJ_IDXS[self.obj.relative_prim_path] + # wp.to_torch is a zero-copy view of the wp.array storage. + time_view = wp.to_torch(type(self)._robots_can_toggle_time) + return dict( + value=bool(self.VALUES[s, obj_idx].item()), + hand_in_marker_steps=float(time_view[s, obj_idx].item()), + ) + + def _load_state(self, state): + # Restore toggle via _set_value so the visual marker color is also updated. + self._set_value(state["value"]) + if self.OBJ_IDXS is None or self.obj.relative_prim_path not in self.OBJ_IDXS: + return + s = self.obj.scene.idx + obj_idx = self.OBJ_IDXS[self.obj.relative_prim_path] + # Restore the seconds counter directly into the wp.array via a zero-copy torch view. + wp.to_torch(type(self)._robots_can_toggle_time)[s, obj_idx] = float(state["hand_in_marker_steps"]) + + def serialize(self, state): + # [toggle_state, can_toggle_time (seconds)] as float32 + return th.tensor([state["value"], state["hand_in_marker_steps"]], dtype=th.float32) + + def deserialize(self, state): + return dict(value=bool(state[0].item()), hand_in_marker_steps=float(state[1].item())), 2 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/touching.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/touching.py new file mode 100644 index 0000000000000000000000000000000000000000..85ea958ce9ddf34599b5ba76480de5410d53fde6 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/touching.py @@ -0,0 +1,244 @@ +import torch as th +import warp as wp + +import omnigibson.lazy as lazy +from omnigibson.object_states.kinematics_mixin import KinematicsMixin +from omnigibson.object_states.object_state_base import BooleanStateMixin +from omnigibson.object_states.tensorized_relative_state import TensorizedRelativeState +from omnigibson.utils.constants import PrimType +from omnigibson.utils.python_utils import classproperty +from omnigibson.utils.usd_utils import RigidContactAPI + + +# Tensorized Touching state. +# +# VALUES shape: (S, N, N) bool — VALUES[s, a, b] is True iff object a is currently in +# rigid contact with object b in scene s. Symmetric (a touches b ⇔ b touches a). +# Diagonal cells and cross-scene cells are always False. +# +# Computation: per-scene two-stage atomic-max contraction over the contact matrix. +# +# Stage 1 obj_to_col[s, i, c] = ∃ r : obj_row_mask[s, i, r] ∧ contact_matrix[s, r, c] +# Stage 2 pair[s, i, j] = ∃ c : obj_to_col[s, i, c] ∧ obj_col_mask[s, j, c] +# Stage 3 VALUES[s, i, j] = (pair[s, i, j] ∨ pair[s, j, i]) ∧ (i ≠ j) +# +# Two stages instead of one collapsed kernel because launch dims would be (S, N, N, R, C); +# the contraction split keeps each launch ≤ 3D and keeps scratch memory at O(N·C + N²) +# instead of O(N² · max(R, C)). +# +# Cloth path: cloth has no rigid contact matrix entries, so the kernel writes 0 for any +# pair touching a cloth obj. `_get_value` overrides the base CPU read to fall back to +# `_check_cloth_contact` for cloth pairs — preserving the pre-tensorized behavior used +# by Overlaid. + + +@wp.kernel +def _touching_obj_to_col_kernel( + obj_row_mask: wp.array2d(dtype=wp.uint8), # (N, R_s) + contact_matrix: wp.array2d(dtype=wp.uint8), # (R_s, C_s) + obj_to_col: wp.array2d(dtype=wp.int32), # (N, C_s) — atomic_max target +): + """Per (i, r, c) thread: set obj_to_col[i, c] = 1 if obj i's row r is in contact with col c.""" + i, r, c = wp.tid() + if obj_row_mask[i, r] == wp.uint8(0): + return + if contact_matrix[r, c] == wp.uint8(0): + return + wp.atomic_max(obj_to_col, i, c, wp.int32(1)) + + +@wp.kernel +def _touching_pair_kernel( + obj_to_col: wp.array2d(dtype=wp.int32), # (N, C_s) + obj_col_mask: wp.array2d(dtype=wp.uint8), # (N, C_s) + pair: wp.array2d(dtype=wp.int32), # (N, N) — per-scene view of pair scratch +): + """Per (i, j, c) thread: set pair[i, j] = 1 if obj i hits col c that belongs to obj j.""" + i, j, c = wp.tid() + if obj_to_col[i, c] == wp.int32(0): + return + if obj_col_mask[j, c] == wp.uint8(0): + return + wp.atomic_max(pair, i, j, wp.int32(1)) + + +@wp.kernel +def _touching_finalize_kernel( + pair: wp.array3d(dtype=wp.int32), # (S, N, N) + values: wp.array3d(dtype=wp.uint8), # (S, N, N) — uint8 view of bool VALUES +): + """Symmetrize, zero diagonal, int32 → uint8.""" + s, i, j = wp.tid() + if i == j: + values[s, i, j] = wp.uint8(0) + return + if pair[s, i, j] > wp.int32(0) or pair[s, j, i] > wp.int32(0): + values[s, i, j] = wp.uint8(1) + else: + values[s, i, j] = wp.uint8(0) + + +class Touching(TensorizedRelativeState, KinematicsMixin, BooleanStateMixin): + """ + Pairwise rigid-body Touching state. + + Cloth-rigid and cloth-cloth pairs go through `_get_value`'s cloth fallback, + not the tensorized pipeline. + """ + + # Per-scene contact mask tables (rebuilt in initialize_view, sized to that scene's R_s / C_s). + # Each entry covers N rows where N = len(OBJ_IDXS); rows for cloth / absent-in-scene objects are zero. + _obj_row_mask = None # list[wp.array2d(N, R_s) uint8 | None] + _obj_col_mask = None # list[wp.array2d(N, C_s) uint8 | None] + + # Stage 1 scratch: per-scene (N, C_s) int32 atomic_max target. + _obj_to_col = None # list[wp.array2d(N, C_s) int32 | None] + + # Stage 2 scratch: single (S, N, N) int32 atomic_max target + per-scene 2D slice views. + _pair_scratch = None # wp.array3d (S, N, N) int32 + _pair_scratch_per_scene = None # list[wp.array2d(int32)] — row slices of _pair_scratch + + @classproperty + def value_shape(cls): + return () + + @classproperty + def value_type(cls): + return th.bool + + @classproperty + def value_name(cls): + return "touching" + + @staticmethod + def _check_cloth_contact(cloth_obj, other_obj): + other_link_paths = set(other_obj.link_prim_paths) + return any(contact_prim_path in other_link_paths for contact_prim_path, _ in cloth_obj.root_link.get_contacts()) + + @classmethod + def global_initialize(cls): + super().global_initialize() + cls._obj_row_mask = None + cls._obj_col_mask = None + cls._obj_to_col = None + cls._pair_scratch = None + cls._pair_scratch_per_scene = None + + @classmethod + def initialize_view(cls): + # Base class rebuilds OBJ_IDXS, IDX_OBJS, VALUES (with value carry-over). + super().initialize_view() + + S = len(cls.IDX_OBJS) + N = len(cls.OBJ_IDXS) + + cls._obj_row_mask = [] + cls._obj_col_mask = [] + cls._obj_to_col = [] + cls._pair_scratch_per_scene = [] + + if S == 0 or N == 0: + cls._pair_scratch = None + return + + # Allocate single (S, N, N) int32 scratch for stage 2 output; per-scene 2D row slices share storage. + cls._pair_scratch = wp.zeros((S, N, N), dtype=wp.int32, device="cuda") + + for scene_idx, scene_row in enumerate(cls.IDX_OBJS): + cls._pair_scratch_per_scene.append(cls._pair_scratch[scene_idx]) + + shape = RigidContactAPI.get_contact_matrix_shape(scene_idx) + if shape is None: + cls._obj_row_mask.append(None) + cls._obj_col_mask.append(None) + cls._obj_to_col.append(None) + continue + + R_s, C_s = shape + + row_mask_cpu = th.zeros((N, R_s), dtype=th.uint8) + col_mask_cpu = th.zeros((N, C_s), dtype=th.uint8) + + for obj_idx, obj in enumerate(scene_row): + if obj is None: + continue + if obj.prim_type == PrimType.CLOTH: + # Cloth gets handled by the _get_value fallback; rigid kernel sees zero masks. + continue + link_paths = [link.prim_path for link in obj.links.values()] + row_mask_cpu[obj_idx] = RigidContactAPI.get_contact_row_mask(scene_idx, link_paths).to(th.uint8) + col_mask_cpu[obj_idx] = RigidContactAPI.get_contact_col_mask(scene_idx, link_paths).to(th.uint8) + + cls._obj_row_mask.append( + lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list(row_mask_cpu, "uint8", device="cuda") + ) + cls._obj_col_mask.append( + lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list(col_mask_cpu, "uint8", device="cuda") + ) + cls._obj_to_col.append(wp.zeros((N, C_s), dtype=wp.int32, device="cuda")) + + @classmethod + def _update_values(cls, values): + if cls._pair_scratch is None or cls.VALUES_WP is None: + return + + S, N, _ = values.shape + if S == 0 or N == 0: + return + + # Zero the (S, N, N) pair scratch in one shot. + cls._pair_scratch.zero_() + + # Per-scene Stage 1 + Stage 2 launches. + for scene_idx in range(S): + obj_to_col = cls._obj_to_col[scene_idx] + if obj_to_col is None: + continue + row_mask = cls._obj_row_mask[scene_idx] + col_mask = cls._obj_col_mask[scene_idx] + contact_matrix_wp = RigidContactAPI.get_contact_matrix_wp(scene_idx, current_only=True) + if contact_matrix_wp is None: + continue + R_s = contact_matrix_wp.shape[0] + C_s = contact_matrix_wp.shape[1] + + # Zero stage-1 scratch. + obj_to_col.zero_() + + # Stage 1: (N, R_s, C_s) — obj_to_col[i, c] |= row_mask[i, r] & contact[r, c] + wp.launch( + kernel=_touching_obj_to_col_kernel, + dim=(N, R_s, C_s), + inputs=[row_mask, contact_matrix_wp, obj_to_col], + device="cuda", + ) + + # Stage 2: (N, N, C_s) — pair[i, j] |= obj_to_col[i, c] & col_mask[j, c] + wp.launch( + kernel=_touching_pair_kernel, + dim=(N, N, C_s), + inputs=[obj_to_col, col_mask, cls._pair_scratch_per_scene[scene_idx]], + device="cuda", + ) + + # Stage 3: symmetrize, zero diagonal, int32 → uint8 into VALUES. + wp.launch( + kernel=_touching_finalize_kernel, + dim=(S, N, N), + inputs=[cls._pair_scratch, cls.VALUES_WP], + device="cuda", + ) + + def _get_value(self, other): + # Cloth path: tensorized pipeline doesn't see cloth contacts (cloth isn't in the + # rigid contact matrix), so fall back to the per-call PhysX get_contacts() check. + self_is_cloth = self.obj.prim_type == PrimType.CLOTH + other_is_cloth = other.prim_type == PrimType.CLOTH + if self_is_cloth and other_is_cloth: + raise ValueError("Cannot detect contact between two cloth objects.") + if self_is_cloth: + return self._check_cloth_contact(self.obj, other) + if other_is_cloth: + return self._check_cloth_contact(other, self.obj) + + return super()._get_value(other) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/under.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/under.py new file mode 100644 index 0000000000000000000000000000000000000000..cd2d8d4caceab742c768e916fa7b0c2e5c7465f2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/under.py @@ -0,0 +1,130 @@ +import torch as th +import warp as wp + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.object_states.adjacency import Adjacency +from omnigibson.object_states.kinematics_mixin import KinematicsMixin +from omnigibson.object_states.object_state_base import BooleanStateMixin +from omnigibson.object_states.tensorized_relative_state import TensorizedRelativeState +from omnigibson.utils.constants import PrimType +from omnigibson.utils.object_state_utils import get_reachability_sampling_context +from omnigibson.utils.object_state_utils import m as os_m +from omnigibson.utils.object_state_utils import sample_kinematics +from omnigibson.utils.python_utils import classproperty + + +# Adjacency axis layout: k=0 is +Z (other above self), k=1 is -Z (other below self). +# Under(self, other) is true when: +# - other is above self (Adjacency[s, i, j, 0]) +# - AND other is NOT below self (Adjacency[s, i, j, 1]) +# - AND self is NOT above other (Adjacency[s, j, i, 0]) — guards against mutual-above ambiguity. + + +@wp.kernel +def _under_kernel( + adjacency_values: wp.array4d(dtype=wp.uint8), # (S, N_a, N_a, K) + adj_idx: wp.array(dtype=wp.int32), # (N,) — Under idx → Adjacency idx, -1 if missing + values: wp.array3d(dtype=wp.uint8), # (S, N, N) — Under.VALUES uint8 view +): + s, i, j = wp.tid() + + if i == j: + values[s, i, j] = wp.uint8(0) + return + + a_i = adj_idx[i] + a_j = adj_idx[j] + if a_i < 0 or a_j < 0: + values[s, i, j] = wp.uint8(0) + return + + other_above = adjacency_values[s, a_i, a_j, 0] != wp.uint8(0) + other_below = adjacency_values[s, a_i, a_j, 1] != wp.uint8(0) + self_above = adjacency_values[s, a_j, a_i, 0] != wp.uint8(0) + + if other_above and not other_below and not self_above: + values[s, i, j] = wp.uint8(1) + else: + values[s, i, j] = wp.uint8(0) + + +class Under(TensorizedRelativeState, KinematicsMixin, BooleanStateMixin): + _adj_idx = None # wp.array (N,) int32 — Under idx → Adjacency idx, -1 if missing + + @classproperty + def value_shape(cls): + return () + + @classproperty + def value_type(cls): + return th.bool + + @classproperty + def value_name(cls): + return "under" + + @classmethod + def get_dependencies(cls): + deps = super().get_dependencies() + deps.add(Adjacency) + return deps + + @classmethod + def initialize_view(cls): + super().initialize_view() + N = len(cls.OBJ_IDXS) + if N == 0: + cls._adj_idx = None + return + + adj_idx_cpu = th.full((N,), -1, dtype=th.int32) + adj_map = Adjacency.OBJ_IDXS or {} + for rel_path, idx in cls.OBJ_IDXS.items(): + adj_idx_cpu[idx] = adj_map.get(rel_path, -1) + + cls._adj_idx = lazy.isaacsim.core.utils.warp.tensor.create_tensor_from_list(adj_idx_cpu, "int32", device="cuda") + + @classmethod + def _update_values(cls, values): + if cls.VALUES_WP is None or cls._adj_idx is None or Adjacency.VALUES_WP is None: + return + S, N, _ = values.shape + if S == 0 or N == 0: + return + wp.launch( + kernel=_under_kernel, + dim=(S, N, N), + inputs=[Adjacency.VALUES_WP, cls._adj_idx, cls.VALUES_WP], + device="cuda", + ) + + def _get_value(self, other): + if other.prim_type == PrimType.CLOTH: + raise ValueError("Cannot detect if an object is under a cloth object.") + + return super()._get_value(other) + + def _set_value(self, other, new_value, reset_before_sampling=False, use_trav_map=False): + if not new_value: + raise NotImplementedError("Under does not support set_value(False)") + + if other.prim_type == PrimType.CLOTH: + raise ValueError("Cannot set an object under a cloth object.") + + state = og.sim.dump_state(serialized=False) + + # Possibly reset this object if requested + if reset_before_sampling: + self.obj.reset() + + reachability_context = get_reachability_sampling_context(other, "under", use_trav_map=use_trav_map) + for _ in range(os_m.DEFAULT_HIGH_LEVEL_SAMPLING_ATTEMPTS): + if sample_kinematics( + "under", self.obj, other, use_trav_map=use_trav_map, reachability_context=reachability_context + ) and self.get_value(other): + return True + else: + og.sim.load_state(state, serialized=False) + + return False diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/update_state_mixin.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/update_state_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..fc5e31f95f126751b4a4b0f8865babbad2eb763d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/object_states/update_state_mixin.py @@ -0,0 +1,29 @@ +from omnigibson.object_states.object_state_base import BaseObjectState +from omnigibson.utils.python_utils import classproperty + + +class UpdateStateMixin(BaseObjectState): + """ + A state-mixin that allows for per-sim-step updates via the update() call + """ + + def update(self): + """ + Updates the object state. This function will be called for every simulator step + """ + assert self._initialized, "Cannot update uninitialized state." + return self._update() + + def _update(self): + """ + This function will be called once for every simulator step. Must be implemented by subclass. + """ + # Explicitly raise not implemented error to avoid silent bugs -- update should never be called otherwise + raise NotImplementedError + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("UpdateStateMixin") + return classes diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bb1af21a1dd6823e6e5777e7ba87b4e87634ae6d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/__init__.py @@ -0,0 +1,12 @@ +from omnigibson.objects.dataset_object import DatasetObject +from omnigibson.objects.light_object import LightObject +from omnigibson.objects.primitive_object import PrimitiveObject +from omnigibson.objects.usd_object import REGISTERED_OBJECTS, USDObject + +__all__ = [ + "DatasetObject", + "LightObject", + "PrimitiveObject", + "REGISTERED_OBJECTS", + "USDObject", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/dataset_object.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/dataset_object.py new file mode 100644 index 0000000000000000000000000000000000000000..02768a5b16bcf99a33aba4eee15c2805623ba184 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/dataset_object.py @@ -0,0 +1,633 @@ +import math +import os +import random + +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros, gm +from omnigibson.prims.rigid_dynamic_prim import RigidDynamicPrim +from omnigibson.objects.usd_object import USDObject +from omnigibson.utils.asset_utils import ( + check_minimum_behavior_1k_assets_version, + get_all_object_category_models, + get_avg_category_specs, + get_dataset_path, +) +from omnigibson.utils.constants import ( + DEFAULT_PRISMATIC_JOINT_FRICTION, + DEFAULT_REVOLUTE_JOINT_FRICTION, + DEFAULT_PRISMATIC_JOINT_DAMPING, + DEFAULT_REVOLUTE_JOINT_DAMPING, + JointType, + PrimType, +) +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import find_joint_prims + +# Create module logger +log = create_module_logger(module_name=__name__) + + +# Create settings for this module +m = create_module_macros(module_path=__file__) + + +def _get_meta_link_prim(default_prim, meta_link_type, meta_link_id, sub_id): + """ + Finds the meta link prim of @default_prim matching the given type / id / sub id. + + Args: + default_prim (Usd.Prim): Default prim of an object's USD stage + meta_link_type (str): Meta link type to match, e.g. "attachment" + meta_link_id (str): Meta link ID to match, e.g. "displaywallM" + sub_id (int): Meta link sub ID to match + + Returns: + None or Usd.Prim: The matching meta link prim, if it exists + """ + for child in default_prim.GetChildren(): + attrs = {attr.GetName(): attr for attr in child.GetAttributes()} + if not attrs.get("ig:isMetaLink", None) or not attrs["ig:isMetaLink"].Get(): + continue + if ( + attrs["ig:metaLinkType"].Get() == meta_link_type + and attrs["ig:metaLinkId"].Get() == meta_link_id + and attrs["ig:metaLinkSubId"].Get() == sub_id + ): + return child + return None + + +def _add_mirrored_attachment_meta_link(stage, default_prim, meta_link_id, src_sub_id=0, new_sub_id=1): + """ + Duplicates the attachment meta link (@meta_link_id, @src_sub_id) of @default_prim onto the opposite face of the + object, mirrored across the midplane of the object's shortest bounding box dimension, and registers it under + @new_sub_id. + + The mirroring is realized as a 180 degree rotation about the object's longest bounding box axis (passing through + the bounding box center) rather than as a true reflection, which would produce a left-handed frame. Since + AttachedTo aligns the child's male meta link frame with the parent's female meta link frame exactly, attaching + through the duplicated link puts the object in the same place as the original link would, but spun around so that + its other face points outwards. The 15 degree orientation tolerance in AttachedTo._find_attachment_links means only + the link matching the object's current facing can trigger, so either face can be attached. + + Args: + stage (Usd.Stage): The object's USD stage + default_prim (Usd.Prim): Default prim of @stage + meta_link_id (str): Attachment meta link ID to mirror, e.g. "displaywallM" + src_sub_id (int): Sub ID of the meta link to mirror + new_sub_id (int): Sub ID to assign to the mirrored meta link + """ + src_link = _get_meta_link_prim(default_prim, "attachment", meta_link_id, src_sub_id) + assert src_link is not None, f"Could not find attachment meta link {meta_link_id}_{src_sub_id} to mirror!" + assert ( + _get_meta_link_prim(default_prim, "attachment", meta_link_id, new_sub_id) is None + ), f"Attachment meta link {meta_link_id}_{new_sub_id} already exists; the mirroring hotfix should be removed!" + + # Find the fixed joint anchoring the source meta link to its parent link + src_joint = None + for joint in find_joint_prims(default_prim): + body1_rel = joint.GetRelationship("physics:body1") + if body1_rel and body1_rel.GetTargets() == [src_link.GetPath()]: + src_joint = joint + break + assert src_joint is not None, f"Could not find the joint anchoring attachment meta link {meta_link_id}!" + + # Mirror across the shortest bbox dimension's midplane by spinning 180 degrees about the longest bbox axis + native_bb = list(default_prim.GetAttribute("ig:nativeBB").Get()) + center = lazy.pxr.Gf.Vec3d(default_prim.GetAttribute("ig:offsetBaseLink").Get()) + long_axis = lazy.pxr.Gf.Vec3d(0.0, 0.0, 0.0) + long_axis[max(range(3), key=lambda i: native_bb[i])] = 1.0 + rot = lazy.pxr.Gf.Rotation(long_axis, 180.0) + + src_pos = lazy.pxr.Gf.Vec3d(src_link.GetAttribute("xformOp:translate").Get()) + src_quat = lazy.pxr.Gf.Quatd(src_link.GetAttribute("xformOp:orient").Get()) + new_pos = center + rot.TransformDir(src_pos - center) + new_quat = (rot.GetQuat() * src_quat).GetNormalized() + + # Copy both the link and its joint verbatim (mass, inertia, break force, etc.), then patch the identifying + # attributes and the pose. The USD is a single flat layer, so a plain CopySpec is sufficient. + def _sub_id_swapped_path(prim, suffix): + name = prim.GetName() + prefix = name[: -len(f"_{src_sub_id}_{suffix}")] + assert name.endswith(f"_{src_sub_id}_{suffix}"), f"Unexpected meta link {suffix} prim name {name}!" + return prim.GetParent().GetPath().AppendChild(f"{prefix}_{new_sub_id}_{suffix}") + + layer = stage.GetRootLayer() + new_link_path = _sub_id_swapped_path(src_link, "link") + new_joint_path = _sub_id_swapped_path(src_joint, "joint") + assert lazy.pxr.Sdf.CopySpec(layer, src_link.GetPath(), layer, new_link_path) + assert lazy.pxr.Sdf.CopySpec(layer, src_joint.GetPath(), layer, new_joint_path) + + new_link = stage.GetPrimAtPath(new_link_path) + new_link.GetAttribute("ig:metaLinkSubId").Set(new_sub_id) + _set_pose_attributes(new_link, "xformOp:translate", "xformOp:orient", new_pos, new_quat) + + new_joint = stage.GetPrimAtPath(new_joint_path) + new_joint.GetRelationship("physics:body1").SetTargets([new_link_path]) + _set_pose_attributes(new_joint, "physics:localPos0", "physics:localRot0", new_pos, new_quat) + + +def _set_pose_attributes(prim, pos_attr_name, quat_attr_name, pos, quat): + """ + Writes @pos / @quat into the given attributes of @prim, preserving each attribute's existing value type (the link + and joint pose attributes differ in float vs. double precision). + + Args: + prim (Usd.Prim): Prim whose attributes should be written + pos_attr_name (str): Name of the (Vec3f or Vec3d) position attribute + quat_attr_name (str): Name of the (Quatf or Quatd) orientation attribute + pos (Gf.Vec3d): Position to write + quat (Gf.Quatd): Orientation to write + """ + for attr_name, value in ((pos_attr_name, pos), (quat_attr_name, quat)): + attr = prim.GetAttribute(attr_name) + current = attr.Get() + assert current is not None, f"Prim {prim.GetPath()} has no authored {attr_name} attribute!" + attr.Set(type(current)(value)) + + +# Per-model USD hotfixes, applied to a copy of the asset at load time. Each entry maps a model ID to a callable taking +# (stage, default_prim) and mutating the stage in place. These patch annotation bugs in the shipped dataset that we +# cannot currently re-export the assets for, and each should be deleted once its asset is fixed upstream. +MODEL_USD_HOTFIXES = { + # This poster is printed on both sides, but only has a single attachment point, on one face. Mirror it onto the + # other face so the poster can be hung either way round (needed by e.g. the hanging_pictures task). + "dsrcyt": lambda stage, default_prim: _add_mirrored_attachment_meta_link(stage, default_prim, "displaywallM"), +} + + +class DatasetObject(USDObject): + """ + DatasetObjects are instantiated from a USD file. It is an object that is assumed to come from an iG-supported + dataset. These objects should contain additional metadata, including aggregate statistics across the + object's category, e.g., avg dims, bounding boxes, masses, etc. + """ + + def __init__( + self, + name, + relative_prim_path=None, + category="object", + model=None, + dataset_name="behavior-1k-assets", + scale=None, + visible=True, + fixed_base=False, + visual_only=False, + kinematic_only=None, + self_collisions=False, + prim_type=PrimType.RIGID, + link_physics_materials=None, + load_config=None, + abilities=None, + include_default_states=True, + bounding_box=None, + in_rooms=None, + expected_file_hash=None, + **kwargs, + ): + """ + Args: + name (str): Name for the object. Names need to be unique per scene + relative_prim_path (None or str): The path relative to its scene prim for this object. If not specified, it defaults to /. + category (str): Category for the object. Defaults to "object". + model (None or str): If specified, this is used in conjunction with + @category to infer the usd filepath to load for this object, which evaluates to the following: + + {gm.DATA_PATH}/{dataset_name}/objects/{category}/{model}/usd/{model}.usd + + Otherwise, will randomly sample a model given @category + dataset_name (str): Dataset to search for this object. Default is behavior-1k-assets, corresponding to the + proprietary (encrypted) BEHAVIOR-1K dataset. Any other dataset names are searched for + under the gm.DATA_PATH directory. + scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale + for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a + 3-array specifies per-axis scaling. + visible (bool): whether to render this object or not in the stage + fixed_base (bool): whether to fix the base of this object or not + visual_only (bool): Whether this object should be visual only (and not collide with any other objects) + kinematic_only (None or bool): Whether this object should be kinematic only (and not get affected by any + collisions). If None, then this value will be set to True if @fixed_base is True and some other criteria + are satisfied (see usd_object.py post_load function), else False. + self_collisions (bool): Whether to enable self collisions for this object + prim_type (PrimType): Which type of prim the object is, Valid options are: {PrimType.RIGID, PrimType.CLOTH} + link_physics_materials (None or dict): If specified, dictionary mapping link name to kwargs used to generate + a specific physical material for that link's collision meshes, where the kwargs are arguments directly + passed into the isaacsim.core.api.materials.physics_material.PhysicsMaterial constructor, e.g.: "static_friction", + "dynamic_friction", and "restitution" + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. + abilities (None or dict): If specified, manually adds specific object states to this object. It should be + a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to + the object state instance constructor. + include_default_states (bool): whether to include the default object states from @get_default_states + bounding_box (None or 3-array): If specified, will scale this object such that it fits in the desired + (x,y,z) object-aligned bounding box. Note that EITHER @bounding_box or @scale may be specified + -- not both! + in_rooms (None or str or list): If specified, sets the room(s) that this object should belong to. Either + a list of room type(s) or a single room type + expected_file_hash (str): The expected hash of the file to load. This is used to check if the file has changed. None to disable check. + kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing + for flexible compositions of various object subclasses (e.g.: Robot is USDObject). + """ + # Store variables + if isinstance(in_rooms, str): + assert "," not in in_rooms + self._in_rooms = [in_rooms] if isinstance(in_rooms, str) else in_rooms + + # Make sure only one of bounding_box and scale are specified + if bounding_box is not None and scale is not None: + raise Exception("You cannot define both scale and bounding box size for an DatasetObject") + + # Add info to load config + load_config = dict() if load_config is None else load_config + load_config["bounding_box"] = bounding_box + load_config["dataset_name"] = dataset_name + # All DatasetObjects should have xform properties pre-loaded + # TODO: enable this after next dataset release + load_config["xform_props_pre_loaded"] = False + + # Infer the correct usd path to use + if model is None: + available_models = get_all_object_category_models(category=category) + assert len(available_models) > 0, f"No available models found for category {category}!" + model = random.choice(available_models) + + self._model = model + usd_path = self.get_usd_path(category=category, model=model, dataset_name=dataset_name) + + # Run super init + super().__init__( + relative_prim_path=relative_prim_path, + usd_path=usd_path, + encrypted=dataset_name == "behavior-1k-assets", + name=name, + category=category, + scale=scale, + visible=visible, + fixed_base=fixed_base, + visual_only=visual_only, + kinematic_only=kinematic_only, + self_collisions=self_collisions, + prim_type=prim_type, + include_default_states=include_default_states, + link_physics_materials=link_physics_materials, + load_config=load_config, + abilities=abilities, + expected_file_hash=expected_file_hash, + **kwargs, + ) + + @classmethod + def get_usd_path(cls, category, model, dataset_name="behavior-1k-assets"): + """ + Grabs the USD path for a DatasetObject corresponding to @category and @model. + + NOTE: This is the unencrypted path, NOT the encrypted path + + Args: + category (str): Category for the object + model (str): Specific model ID of the object + dataset_name (str): Dataset type, used to infer dataset directory to search for @category and @model + + Returns: + str: Absolute filepath to the corresponding USD asset file + """ + dataset_path = get_dataset_path(dataset_name) + + # Here, we assert the minimum version of the BEHAVIOR-1K dataset this is compatible with. + # This requirement was placed by the fact that we switched from USDZ back to USD due to + # speed and caching issues. + if dataset_name == "behavior-1k-assets": + assert check_minimum_behavior_1k_assets_version("3.7.2rc1"), ( + "This version of BEHAVIOR-1K requires at least version 3.7.2rc1 of the behavior-1k-assets dataset! \n" + "Please update your dataset by deleting datasets/behavior-1k-assets and running the below command to reinstall. \n\n" + 'python -c "from omnigibson.utils.asset_utils import download_behavior_1k_assets; download_behavior_1k_assets(accept_license=True)"' + ) + + return os.path.join(dataset_path, "objects", category, model, "usd", f"{model}.usd") + + def sample_orientation(self): + """ + Samples an orientation in quaternion (x,y,z,w) form + + Returns: + 4-array: (x,y,z,w) sampled quaternion orientation for this object, based on self.orientations + """ + if self.orientations is None: + raise ValueError("No orientation probabilities set") + if len(self.orientations) == 0: + # Set default value + chosen_orientation = th.tensor([0, 0, 0, 1.0]) + else: + probabilities = [o["prob"] for o in self.orientations.values()] + probabilities = th.tensor(probabilities, dtype=th.float32) / th.sum(probabilities) + option = th.multinomial(probabilities, 1).item() + chosen_orientation = th.tensor(list(self.orientations.values())[option]["rotation"]) + + # Randomize yaw from -pi to pi + rot_lo, rot_hi = -1, 1 + rot_num = (th.rand(1) * (rot_hi - rot_lo) + rot_lo).item() + rot_matrix = th.tensor( + [ + [math.cos(math.pi * rot_num), -math.sin(math.pi * rot_num), 0.0], + [math.sin(math.pi * rot_num), math.cos(math.pi * rot_num), 0.0], + [0.0, 0.0, 1.0], + ] + ) + rotated_quat = T.mat2quat(rot_matrix @ T.quat2mat(chosen_orientation)) + return rotated_quat + + def _initialize(self): + # Run super method first + super()._initialize() + + # Apply any forced light intensity updates. + if gm.FORCE_LIGHT_INTENSITY is not None: + + def recursive_light_update(child_prim): + if "Light" in child_prim.GetPrimTypeInfo().GetTypeName(): + child_prim.GetAttribute("inputs:intensity").Set(gm.FORCE_LIGHT_INTENSITY) + child_prim.GetAttribute("inputs:normalize").Set(True) + + for child_child_prim in child_prim.GetChildren(): + recursive_light_update(child_child_prim) + + with og.sim.editing_usd(): + recursive_light_update(self._prim) + + # Set the joint frictions based on joint type + for joint in self._joints.values(): + if joint.joint_type == JointType.JOINT_PRISMATIC: + joint.friction = DEFAULT_PRISMATIC_JOINT_FRICTION + elif joint.joint_type == JointType.JOINT_REVOLUTE: + joint.friction = DEFAULT_REVOLUTE_JOINT_FRICTION + + def _apply_usd_hotfixes(self, stage, default_prim): + super()._apply_usd_hotfixes(stage, default_prim) + + # Apply this model's hotfix, if it has one + hotfix = MODEL_USD_HOTFIXES.get(self.model, None) + if hotfix is not None: + log.info(f"Applying USD hotfix for {self.category}/{self.model}") + hotfix(stage, default_prim) + + def _get_preapply_scale(self, default_prim): + # If bounding_box is set, scale hasn't been computed yet (that happens in _post_load). + # Derive it here from ig:nativeBB so kinematic_only is computed correctly and + # PhysxArticulationAPI is pre-applied when needed. + bounding_box = self._load_config.get("bounding_box", None) + if bounding_box is not None and self._load_config.get("scale", None) is None: + native_bb_attr = default_prim.GetAttribute("ig:nativeBB") + if native_bb_attr.IsValid(): + native_bb = th.tensor(list(native_bb_attr.Get())) + bb = th.as_tensor(bounding_box, dtype=th.float32) + scale = th.ones(3) + valid_idxes = native_bb > 1e-4 + scale[valid_idxes] = bb[valid_idxes] / native_bb[valid_idxes] + return scale + return super()._get_preapply_scale(default_prim) + + def _post_load(self): + # Scale was already computed from bounding_box / ig:nativeBB in _preapply_articulation_root. + # If neither was provided, default to ones(3) (no scaling). + if self._load_config.get("scale", None) is None: + self._load_config["scale"] = th.ones(3) + assert th.all( + th.abs(self._load_config["scale"]) > 1e-4 + ), f"Scale of {self.name} is too small: {self._load_config['scale']}" + # Run super last + super()._post_load() + + category_mass = None + category_density = None + if self._load_config["dataset_name"] == "behavior-1k-assets": + # Get the average mass/density for this object category + avg_specs = get_avg_category_specs() + if self.category in avg_specs: + category_mass = avg_specs[self.category]["mass"] + category_density = avg_specs[self.category]["density"] + else: + log.warning( + f"Category {self.category} not found in average object specs! Defaulting to unit mass or density." + ) + category_mass = 1.0 + category_density = 1.0 + + if self._prim_type == PrimType.RIGID: + if category_mass is not None: + total_volume = sum(link.volume for link in self._links.values()) + for link in self._links.values(): + # If not a meta (virtual) link, set the density based on avg_obj_dims and a zero mass (ignored) + if link.has_collision_meshes and isinstance(link, RigidDynamicPrim): + if gm.FORCE_CATEGORY_MASS: + # Each link should get the appropriate fraction of the category mass + # based on the link volume + link.mass = max(category_mass * (link.volume / total_volume), 1e-6) + link.density = 0.0 + else: + link.mass = 0.0 + link.density = category_density + + # If there exists a center of mass annotation, apply it now + if self.prim.HasAttribute("ig:centerOfMass"): + center_of_mass_in_object_frame = th.tensor(self.get_attribute(attr="ig:centerOfMass")) + + # Here we assume that the local frame of the object is the same as the local frame of the root link. We also do NOT need to apply a scale + # since the center of mass is already in the local frame of the object and thus the unscaled local frame of the root link. + self.root_link.center_of_mass = center_of_mass_in_object_frame + + # For all joints under dataset objects, + # 1. we use "acceleration" drive type instead of "force" to properly account for link mass + # 2. we set non-zero damping to simulate dynamic friction: + # the friction coefficient only accounts for static friction + from omnigibson.utils.asset_conversion_utils import find_all_prim_children_with_type + + prismatic_joints = find_all_prim_children_with_type(prim_type="PhysicsPrismaticJoint", root_prim=self._prim) + revolute_joints = find_all_prim_children_with_type(prim_type="PhysicsRevoluteJoint", root_prim=self._prim) + with og.sim.editing_usd(): + for prismatic_joint in prismatic_joints: + prismatic_joint.GetAttribute("drive:linear:physics:type").Set("acceleration") + prismatic_joint.GetAttribute("drive:linear:physics:damping").Set(DEFAULT_PRISMATIC_JOINT_DAMPING) + prismatic_joint.GetAttribute("drive:linear:physics:stiffness").Set(0.0) + prismatic_joint.GetAttribute("drive:linear:physics:targetPosition").Set(0.0) + prismatic_joint.GetAttribute("drive:linear:physics:targetVelocity").Set(0.0) + for revolute_joint in revolute_joints: + revolute_joint.GetAttribute("drive:angular:physics:type").Set("acceleration") + revolute_joint.GetAttribute("drive:angular:physics:damping").Set(DEFAULT_REVOLUTE_JOINT_DAMPING) + revolute_joint.GetAttribute("drive:angular:physics:stiffness").Set(0.0) + revolute_joint.GetAttribute("drive:angular:physics:targetPosition").Set(0.0) + revolute_joint.GetAttribute("drive:angular:physics:targetVelocity").Set(0.0) + + elif self._prim_type == PrimType.CLOTH: + if category_mass is not None: + self.root_link.mass = ( + category_mass if gm.FORCE_CATEGORY_MASS else category_density * self.root_link.volume + ) + + def set_bbox_center_position_orientation(self, position=None, orientation=None): + """ + Sets the center of the object's bounding box with respect to the world's frame. + + Args: + position (None or 3-array): The desired global (x,y,z) position. None means it will not be changed + orientation (None or 4-array): The desired global (x,y,z,w) quaternion orientation. + None means it will not be changed + """ + if orientation is None: + orientation = self.get_position_orientation()[1] + if position is not None: + rotated_offset = T.pose_transform( + th.tensor([0, 0, 0], dtype=th.float32), + orientation, + self.scaled_bbox_center_in_base_frame, + th.tensor([0, 0, 0, 1], dtype=th.float32), + )[0] + position = position + rotated_offset + self.set_position_orientation(position=position, orientation=orientation) + + @property + def model(self): + """ + Returns: + str: Unique model ID for this object + """ + return self._model + + @property + def in_rooms(self): + """ + Returns: + None or list of str: If specified, room(s) that this object should belong to + """ + return self._in_rooms + + @in_rooms.setter + def in_rooms(self, rooms): + """ + Sets which room(s) this object should belong to. If no rooms, then should set to None + + Args: + rooms (None or list of str): If specified, the room(s) this object should belong to + """ + # Store the value to the internal variable and also update the init kwargs accordingly + self._init_info["args"]["in_rooms"] = rooms + self._in_rooms = rooms + + @property + def native_bbox(self): + """ + Get this object's native bounding box + + Returns: + 3-array: (x,y,z) bounding box + """ + assert ( + "ig:nativeBB" in self.property_names + ), f"This dataset object '{self.name}' is expected to have native_bbox specified, but found none!" + return th.tensor(self.get_attribute(attr="ig:nativeBB")) + + @property + def base_link_offset(self): + """ + Get this object's native base link offset + + Returns: + 3-array: (x,y,z) base link offset if it exists + """ + return th.tensor(self.get_attribute(attr="ig:offsetBaseLink")) + + @property + def metadata(self): + """ + Gets this object's metadata, if it exists + + Returns: + None or dict: Nested dictionary of object's metadata if it exists, else None + """ + return self.get_custom_data().get("metadata", None) + + @property + def orientations(self): + """ + Returns: + None or dict: Possible orientation information for this object, if it exists. Otherwise, returns None + """ + metadata = self.metadata + return None if metadata is None else metadata.get("orientations", None) + + @property + def scale(self): + # Just super call + return super().scale + + @scale.setter + def scale(self, scale): + # call super first + # A bit esoteric -- see https://gist.github.com/Susensio/979259559e2bebcd0273f1a95d7c1e79 + super(DatasetObject, type(self)).scale.fset(self, scale) + + # Remove bounding_box from scale if it's in our args + if "bounding_box" in self._init_info["args"]: + self._init_info["args"].pop("bounding_box") + + @property + def scaled_bbox_center_in_base_frame(self): + """ + where the base_link origin is wrt. the bounding box center. This allows us to place the model correctly + since the joint transformations given in the scene USD are wrt. the bounding box center. + We need to scale this offset as well. + + Returns: + 3-array: (x,y,z) location of bounding box, with respet to the base link's coordinate frame + """ + return -self.scale * self.base_link_offset + + @property + def scales_in_link_frame(self): + """ + Returns: + dict: Keyword-mapped relative scales for each link of this object + """ + scales = {self.root_link.body_name: self.scale} + + # Collect every joint prim under this object's prim. We traverse manually this way instead of + # accessing the self._joints dictionary, because the dictionary only includes articulated + # joints and not fixed joints! Joints may live anywhere under the object's prim (recent Isaac + # Sim exports place them in a flat /joints scope rather than under body0). + joint_prims = list(find_joint_prims(self.prim)) + + # Propagate scale outwards from the root link. Fixed-point loop handles arbitrary joint order. + progress = True + while progress: + progress = False + for prim in joint_prims: + body0_targets = prim.GetProperty("physics:body0").GetTargets() + body1_targets = prim.GetProperty("physics:body1").GetTargets() + if not body0_targets or not body1_targets: + continue + parent_name = body0_targets[0].pathString.split("/")[-1] + child_name = body1_targets[0].pathString.split("/")[-1] + if parent_name in scales and child_name not in scales: + scale_in_parent_lf = scales[parent_name] + # The location of the joint frame is scaled using the scale in the parent frame + quat0 = lazy.isaacsim.core.utils.rotations.gf_quat_to_np_array( + prim.GetAttribute("physics:localRot0").Get() + )[[1, 2, 3, 0]] + quat1 = lazy.isaacsim.core.utils.rotations.gf_quat_to_np_array( + prim.GetAttribute("physics:localRot1").Get() + )[[1, 2, 3, 0]] + # Invert the child link relationship, and multiply the two rotations together to get the final rotation + local_ori = T.quat_multiply( + quaternion1=T.quat_inverse(th.from_numpy(quat1)), quaternion0=th.from_numpy(quat0) + ) + jnt_frame_rot = T.quat2mat(local_ori) + scale_in_child_lf = th.abs(jnt_frame_rot.T @ th.tensor(scale_in_parent_lf)) + scales[child_name] = scale_in_child_lf + progress = True + + return scales diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/light_object.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/light_object.py new file mode 100644 index 0000000000000000000000000000000000000000..08d4d4c73e4bc05c3e4552ccd9a1aaf28193b24d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/light_object.py @@ -0,0 +1,245 @@ +import os +import tempfile + +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.objects.usd_object import USDObject +from omnigibson.utils.usd_utils import create_usd_stage, ensure_usd_api +from omnigibson.prims.xform_prim import XFormPrim +from omnigibson.utils.constants import PrimType +from omnigibson.utils.python_utils import assert_valid_key +from omnigibson.utils.ui_utils import create_module_logger + +# Create module logger +log = create_module_logger(module_name=__name__) + + +class LightObject(USDObject): + """ + LightObjects are objects that generate light in the simulation + """ + + LIGHT_TYPES = { + "Cylinder", + "Disk", + "Distant", + "Dome", + "Geometry", + "Rect", + "Sphere", + } + + def __init__( + self, + name, + light_type, + relative_prim_path=None, + category="light", + scale=None, + link_physics_materials=None, + load_config=None, + abilities=None, + include_default_states=True, + radius=1.0, + intensity=50000.0, + **kwargs, + ): + """ + Args: + name (str): Name for the object. Names need to be unique per scene + light_type (str): Type of light to create. Valid options are LIGHT_TYPES + relative_prim_path (None or str): The path relative to its scene prim for this object. If not specified, it defaults to /. + category (str): Category for the object. Defaults to "object". + scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale + for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a + 3-array specifies per-axis scaling. + link_physics_materials (None or dict): If specified, dictionary mapping link name to kwargs used to generate + a specific physical material for that link's collision meshes, where the kwargs are arguments directly + passed into the isaacsim.core.api.materials.physics_material.PhysicsMaterial constructor, e.g.: "static_friction", + "dynamic_friction", and "restitution" + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. + abilities (None or dict): If specified, manually adds specific object states to this object. It should be + a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to + the object state instance constructor. + include_default_states (bool): whether to include the default object states from @get_default_states + radius (float): Radius for this light. + intensity (float): Intensity for this light. + kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing + for flexible compositions of various object subclasses (e.g.: Robot is USDObject). + """ + # Compose load config and add rgba values + load_config = dict() if load_config is None else load_config + load_config["scale"] = scale + load_config["intensity"] = intensity + load_config["radius"] = radius if light_type in {"Cylinder", "Disk", "Sphere"} else None + + # Make sure primitive type is valid + assert_valid_key(key=light_type, valid_keys=self.LIGHT_TYPES, name="light_type") + self.light_type = light_type + + # Other attributes to be filled in at runtime + self._light_link = None + + # Build the USD for this light upfront and pass it to USDObject + usd_path = self._build_usd(name=name, light_type=light_type) + + # Run super method + super().__init__( + usd_path=usd_path, + relative_prim_path=relative_prim_path, + name=name, + category=category, + scale=scale, + visible=True, + fixed_base=True, + visual_only=True, + kinematic_only=True, + self_collisions=False, + prim_type=PrimType.RIGID, + include_default_states=include_default_states, + link_physics_materials=link_physics_materials, + load_config=load_config, + abilities=abilities, + **kwargs, + ) + + @staticmethod + def _build_usd(name, light_type): + """Build a temporary USD containing the light prim structure and return its path.""" + tempdir_path = tempfile.mkdtemp(name, dir=og.tempdir) + usd_path = os.path.join(tempdir_path, f"{name}.usd") + side_stage = create_usd_stage(usd_path) + root = side_stage.DefinePrim("/object", "Xform") + side_stage.SetDefaultPrim(root) + side_stage.DefinePrim("/object/base_link", "Xform") + getattr(lazy.pxr.UsdLux, f"{light_type}Light").Define(side_stage, "/object/base_link/light") + side_stage.Save() + del side_stage + return usd_path + + def _post_load(self): + # run super first + super()._post_load() + + # Grab reference to light link + self._light_link = XFormPrim( + relative_prim_path=f"{self._relative_prim_path}/base_link/light", name=f"{self.name}:light_link" + ) + self._light_link.load(self.scene) + + # Apply Shaping API and set default cone angle attribute + shaping_api = ensure_usd_api(self._light_link.prim, lazy.pxr.UsdLux.ShapingAPI) + with og.sim.editing_usd(): + shaping_api.GetShapingConeAngleAttr().Set(180.0) + + # Optionally set the intensity + if self._load_config.get("intensity", None) is not None: + self.intensity = self._load_config["intensity"] + + # Optionally set the radius + if self._load_config.get("radius", None) is not None: + self.radius = self._load_config["radius"] + + def _initialize(self): + # Run super + super()._initialize() + + # Initialize light link + self._light_link.initialize() + + @property + def aabb(self): + # This is a virtual object (with no associated visual mesh), so omni returns an invalid AABB. + # Therefore we instead return a hardcoded small value + return th.ones(3) * -0.001, th.ones(3) * 0.001 + + @property + def light_link(self): + """ + Returns: + XFormPrim: Link corresponding to the light prim itself + """ + return self._light_link + + @property + def radius(self): + """ + Gets this light's radius + + Returns: + float: radius for this light + """ + return self._light_link.get_attribute("inputs:radius") + + @radius.setter + def radius(self, radius): + """ + Sets this light's radius + + Args: + radius (float): radius to set + """ + self._light_link.set_attribute("inputs:radius", radius) + + @property + def intensity(self): + """ + Gets this light's intensity + + Returns: + float: intensity for this light + """ + return self._light_link.get_attribute("inputs:intensity") + + @intensity.setter + def intensity(self, intensity): + """ + Sets this light's intensity + + Args: + intensity (float): intensity to set + """ + self._light_link.set_attribute("inputs:intensity", intensity) + + @property + def color(self): + """ + Gets this light's color + + Returns: + float: color for this light + """ + return tuple(float(x) for x in self._light_link.get_attribute("inputs:color")) + + @color.setter + def color(self, color): + """ + Sets this light's color + + Args: + color ([float, float, float]): color to set, each value in range [0, 1] + """ + self._light_link.set_attribute("inputs:color", lazy.pxr.Gf.Vec3f(color)) + + @property + def texture_file_path(self): + """ + Gets this light's texture file path. Only valid for dome lights. + + Returns: + str: texture file path for this light + """ + return str(self._light_link.get_attribute("inputs:texture:file")) + + @texture_file_path.setter + def texture_file_path(self, texture_file_path): + """ + Sets this light's texture file path. Only valid for dome lights. + + Args: + texture_file_path (str): path of texture file that should be used for this light + """ + self._light_link.set_attribute("inputs:texture:file", lazy.pxr.Sdf.AssetPath(texture_file_path)) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/primitive_object.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/primitive_object.py new file mode 100644 index 0000000000000000000000000000000000000000..f44f715ede7991494c5cdac57893588ebdfd17ed --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/primitive_object.py @@ -0,0 +1,402 @@ +import os +import tempfile + +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.objects.usd_object import USDObject +from omnigibson.utils.constants import PRIMITIVE_MESH_TYPES, PrimType +from omnigibson.utils.physx_utils import bind_material +from omnigibson.utils.python_utils import assert_valid_key +from omnigibson.utils.render_utils import create_pbr_material +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import create_primitive_mesh, create_usd_stage, ensure_usd_api + +# Create module logger +log = create_module_logger(module_name=__name__) + + +# Define valid objects that can be created +VALID_RADIUS_OBJECTS = {"Cone", "Cylinder", "Disk", "Sphere"} +VALID_HEIGHT_OBJECTS = {"Cone", "Cylinder"} +VALID_SIZE_OBJECTS = {"Cube", "Torus"} + + +class PrimitiveObject(USDObject): + """ + PrimitiveObjects are objects defined by a single geom, e.g: sphere, mesh, cube, etc. + """ + + def __init__( + self, + name, + primitive_type, + relative_prim_path=None, + category="object", + scale=None, + visible=True, + fixed_base=False, + visual_only=False, + kinematic_only=None, + self_collisions=False, + prim_type=PrimType.RIGID, + link_physics_materials=None, + load_config=None, + abilities=None, + include_default_states=True, + rgba=(0.5, 0.5, 0.5, 1.0), + radius=None, + height=None, + size=None, + **kwargs, + ): + """ + Args: + name (str): Name for the object. Names need to be unique per scene + primitive_type (str): type of primitive object to create. Should be one of: + {"Cone", "Cube", "Cylinder", "Disk", "Plane", "Sphere", "Torus"} + relative_prim_path (None or str): The path relative to its scene prim for this object. If not specified, it defaults to /. + category (str): Category for the object. Defaults to "object". + scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale + for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a + 3-array specifies per-axis scaling. + visible (bool): whether to render this object or not in the stage + fixed_base (bool): whether to fix the base of this object or not + visual_only (bool): Whether this object should be visual only (and not collide with any other objects) + kinematic_only (None or bool): Whether this object should be kinematic only (and not get affected by any + collisions). If None, then this value will be set to True if @fixed_base is True and some other criteria + are satisfied (see usd_object.py post_load function), else False. + self_collisions (bool): Whether to enable self collisions for this object + prim_type (PrimType): Which type of prim the object is, Valid options are: {PrimType.RIGID, PrimType.CLOTH} + link_physics_materials (None or dict): If specified, dictionary mapping link name to kwargs used to generate + a specific physical material for that link's collision meshes, where the kwargs are arguments directly + passed into the isaacsim.core.api.materials.physics_material.PhysicsMaterial constructor, e.g.: "static_friction", + "dynamic_friction", and "restitution" + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. + abilities (None or dict): If specified, manually adds specific object states to this object. It should be + a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to + the object state instance constructor.rgba (4-array): (R, G, B, A) values to set for this object + include_default_states (bool): whether to include the default object states from @get_default_states + radius (None or float): If specified, sets the radius for this object. This value is scaled by @scale + Note: Should only be specified if the @primitive_type is one of {"Cone", "Cylinder", "Disk", "Sphere"} + height (None or float): If specified, sets the height for this object. This value is scaled by @scale + Note: Should only be specified if the @primitive_type is one of {"Cone", "Cylinder"} + size (None or float): If specified, sets the size for this object. This value is scaled by @scale + Note: Should only be specified if the @primitive_type is one of {"Cube", "Torus"} + kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing + for flexible compositions of various object subclasses (e.g.: Robot is USDObject). + """ + # Compose load config and add rgba values + load_config = dict() if load_config is None else load_config + load_config["color"] = rgba[:3] + load_config["opacity"] = rgba[3] + load_config["radius"] = radius + load_config["height"] = height + load_config["size"] = size + + # Initialize other internal variables + self._vis_geom = None + self._col_geom = None + self._extents = th.ones(3) # (x,y,z extents) + + # Make sure primitive type is valid + assert_valid_key(key=primitive_type, valid_keys=PRIMITIVE_MESH_TYPES, name="primitive mesh type") + self._primitive_type = primitive_type + + # Build the USD for this primitive upfront and pass it to USDObject + usd_path = self._build_usd(name=name, primitive_type=primitive_type) + + super().__init__( + usd_path=usd_path, + relative_prim_path=relative_prim_path, + name=name, + category=category, + scale=scale, + visible=visible, + fixed_base=fixed_base, + visual_only=visual_only, + kinematic_only=kinematic_only, + self_collisions=self_collisions, + prim_type=prim_type, + include_default_states=include_default_states, + link_physics_materials=link_physics_materials, + load_config=load_config, + abilities=abilities, + **kwargs, + ) + + @staticmethod + def _build_usd(name, primitive_type): + """ + Build a temporary USD containing the primitive mesh structure and return its path. + Material creation is deferred to _post_load(). + """ + tempdir_path = tempfile.mkdtemp(name, dir=og.tempdir) + usd_path = os.path.join(tempdir_path, f"{name}.usd") + side_stage = create_usd_stage(usd_path) + root = side_stage.DefinePrim("/object", "Xform") + side_stage.SetDefaultPrim(root) + side_stage.DefinePrim("/object/base_link", "Xform") + + create_primitive_mesh(prim_path="/object/base_link/visuals", primitive_type=primitive_type, stage=side_stage) + col_geom = create_primitive_mesh( + prim_path="/object/base_link/collisions", primitive_type=primitive_type, stage=side_stage + ) + ensure_usd_api(col_geom.GetPrim(), lazy.pxr.UsdPhysics.CollisionAPI) + ensure_usd_api(col_geom.GetPrim(), lazy.pxr.UsdPhysics.MeshCollisionAPI) + ensure_usd_api(col_geom.GetPrim(), lazy.pxr.PhysxSchema.PhysxCollisionAPI) + + side_stage.Save() + del side_stage + return usd_path + + def _post_load(self): + self._vis_geom = lazy.pxr.UsdGeom.Mesh(og.sim.stage.GetPrimAtPath(f"{self.prim_path}/base_link/visuals")) + self._col_geom = lazy.pxr.UsdGeom.Mesh(og.sim.stage.GetPrimAtPath(f"{self.prim_path}/base_link/collisions")) + + # Create a material and bind it to the visual geom. + # This is done here rather than in _prepare_to_load() because create_pbr_material + # and bind_material both go through omni.kit.commands, which operates on the + # active stage. + with og.sim.editing_usd(): + og.sim.stage.DefinePrim(f"{self.prim_path}/Looks", "Scope") + mat_path = f"{self.prim_path}/Looks/default" + create_pbr_material(prim_path=mat_path) + bind_material(prim_path=self._vis_geom.GetPrim().GetPrimPath().pathString, material_path=mat_path) + + # Possibly set scalings (only if the scale value is not set) + if self._load_config["scale"] is not None: + log.warning("Custom scale specified for primitive object, so ignoring radius, height, and size arguments!") + else: + if self._load_config["radius"] is not None: + self.radius = self._load_config["radius"] + if self._load_config["height"] is not None: + self.height = self._load_config["height"] + if self._load_config["size"] is not None: + self.size = self._load_config["size"] + + # This step might will perform cloth remeshing if self._prim_type == PrimType.CLOTH. + # Therefore, we need to apply size, radius, and height before this to scale the points properly. + super()._post_load() + + # Cloth primitive does not have collision meshes + if self._prim_type != PrimType.CLOTH: + # Set the collision approximation appropriately + if self._primitive_type == "Sphere": + col_approximation = "boundingSphere" + elif self._primitive_type == "Cube": + col_approximation = "boundingCube" + else: + col_approximation = "convexHull" + self.root_link.set_collision_approximation(col_approximation) + + def _initialize(self): + # Run super first + super()._initialize() + + # Set color and opacity + if self._prim_type == PrimType.RIGID: + visual_geom_prim = list(self.root_link.visual_meshes.values())[0] + elif self._prim_type == PrimType.CLOTH: + visual_geom_prim = self.root_link + else: + raise ValueError("Prim type must either be PrimType.RIGID or PrimType.CLOTH for loading a primitive object") + + visual_geom_prim.color = self._load_config["color"] + visual_geom_prim.opacity = ( + self._load_config["opacity"].item() + if isinstance(self._load_config["opacity"], th.Tensor) + else self._load_config["opacity"] + ) + + @property + def radius(self): + """ + Gets this object's radius, if it exists. + + Note: Can only be called if the primitive type is one of {"Cone", "Cylinder", "Disk", "Sphere"} + + Returns: + float: radius for this object + """ + assert_valid_key(key=self._primitive_type, valid_keys=VALID_RADIUS_OBJECTS, name="primitive object with radius") + return self._extents[0] / 2.0 + + @radius.setter + def radius(self, radius): + """ + Sets this object's radius + + Note: Can only be called if the primitive type is one of {"Cone", "Cylinder", "Disk", "Sphere"} + + Args: + radius (float): radius to set + """ + assert_valid_key(key=self._primitive_type, valid_keys=VALID_RADIUS_OBJECTS, name="primitive object with radius") + # Update the extents variable + original_extent = self._extents.clone() + self._extents = ( + th.ones(3) * radius * 2.0 + if self._primitive_type == "Sphere" + else th.tensor([radius * 2.0, radius * 2.0, self._extents[2]]) + ) + attr_pairs = [] + with og.sim.editing_usd(): + for geom in self._vis_geom, self._col_geom: + if geom is not None: + for attr in (geom.GetPointsAttr(), geom.GetNormalsAttr()): + vals = th.tensor(attr.Get()).double() + attr_pairs.append([attr, vals]) + geom.GetExtentAttr().Set( + lazy.pxr.Vt.Vec3fArray( + [ + lazy.pxr.Gf.Vec3f(*(-self._extents / 2.0).tolist()), + lazy.pxr.Gf.Vec3f(*(self._extents / 2.0).tolist()), + ] + ) + ) + + # Calculate how much to scale extents by and then modify the points / normals accordingly + scaling_factor = 2.0 * radius / original_extent[0] + for attr, vals in attr_pairs: + # If this is a sphere, modify all 3 axes + if self._primitive_type == "Sphere": + vals = vals * scaling_factor + # Otherwise, just modify the first two dimensions + else: + vals[:, :2] = vals[:, :2] * scaling_factor + # Set the value + attr.Set(lazy.pxr.Vt.Vec3fArray([lazy.pxr.Gf.Vec3f(*v.tolist()) for v in vals])) + + @property + def height(self): + """ + Gets this object's height, if it exists. + + Note: Can only be called if the primitive type is one of {"Cone", "Cylinder"} + + Returns: + float: height for this object + """ + assert_valid_key(key=self._primitive_type, valid_keys=VALID_HEIGHT_OBJECTS, name="primitive object with height") + return self._extents[2] + + @height.setter + def height(self, height): + """ + Sets this object's height + + Note: Can only be called if the primitive type is one of {"Cone", "Cylinder"} + + Args: + height (float): height to set + """ + assert_valid_key(key=self._primitive_type, valid_keys=VALID_HEIGHT_OBJECTS, name="primitive object with height") + # Update the extents variable + original_extent = self._extents.clone() + self._extents[2] = height + + # Calculate the correct scaling factor and scale the points and normals appropriately + scaling_factor = height / original_extent[2] + with og.sim.editing_usd(): + for geom in self._vis_geom, self._col_geom: + if geom is not None: + for attr in (geom.GetPointsAttr(), geom.GetNormalsAttr()): + vals = th.tensor(attr.Get()).double() + # Scale the z axis by the scaling factor + vals[:, 2] = vals[:, 2] * scaling_factor + attr.Set(lazy.pxr.Vt.Vec3fArray([lazy.pxr.Gf.Vec3f(*v) for v in vals.tolist()])) + geom.GetExtentAttr().Set( + lazy.pxr.Vt.Vec3fArray( + [ + lazy.pxr.Gf.Vec3f(*(-self._extents / 2.0).tolist()), + lazy.pxr.Gf.Vec3f(*(self._extents / 2.0).tolist()), + ] + ) + ) + + @property + def size(self): + """ + Gets this object's size, if it exists. + + Note: Can only be called if the primitive type is one of {"Cube", "Torus"} + + Returns: + float: size for this object + """ + assert_valid_key(key=self._primitive_type, valid_keys=VALID_SIZE_OBJECTS, name="primitive object with size") + return self._extents[0] + + @size.setter + def size(self, size): + """ + Sets this object's size + + Note: Can only be called if the primitive type is one of {"Cube", "Torus"} + + Args: + size (float): size to set + """ + assert_valid_key(key=self._primitive_type, valid_keys=VALID_SIZE_OBJECTS, name="primitive object with size") + + # Update the extents variable + original_extent = self._extents.clone() + self._extents = th.ones(3) * size + + # Calculate the correct scaling factor and scale the points and normals appropriately + scaling_factor = size / original_extent[0] + with og.sim.editing_usd(): + for geom in self._vis_geom, self._col_geom: + if geom is not None: + for attr in (geom.GetPointsAttr(), geom.GetNormalsAttr()): + # Scale all three axes by the scaling factor + vals = th.tensor(attr.Get()).double() * scaling_factor + attr.Set(lazy.pxr.Vt.Vec3fArray([lazy.pxr.Gf.Vec3f(*v.tolist()) for v in vals])) + geom.GetExtentAttr().Set( + lazy.pxr.Vt.Vec3fArray( + [ + lazy.pxr.Gf.Vec3f(*(-self._extents / 2.0).tolist()), + lazy.pxr.Gf.Vec3f(*(self._extents / 2.0).tolist()), + ] + ) + ) + + def _dump_state(self): + state = super()._dump_state() + # state["extents"] = self._extents + state["radius"] = self.radius if self._primitive_type in VALID_RADIUS_OBJECTS else -1 + state["height"] = self.height if self._primitive_type in VALID_HEIGHT_OBJECTS else -1 + state["size"] = self.size if self._primitive_type in VALID_SIZE_OBJECTS else -1 + return state + + def _load_state(self, state): + super()._load_state(state=state) + # self._extents = th.tensor(state["extents"]) + if self._primitive_type in VALID_RADIUS_OBJECTS: + self.radius = state["radius"] + if self._primitive_type in VALID_HEIGHT_OBJECTS: + self.height = state["height"] + if self._primitive_type in VALID_SIZE_OBJECTS: + self.size = state["size"] + + def deserialize(self, state): + state_dict, idx = super().deserialize(state=state) + # state_dict["extents"] = state[idx: idx + 3] + state_dict["radius"] = state[idx] + state_dict["height"] = state[idx + 1] + state_dict["size"] = state[idx + 2] + return state_dict, idx + 3 + + def serialize(self, state): + # Run super first + state_flat = super().serialize(state=state) + + return th.cat( + [ + state_flat, + th.tensor([state["radius"], state["height"], state["size"]]), + ] + ) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/usd_object.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/usd_object.py new file mode 100644 index 0000000000000000000000000000000000000000..a31c0ccf1768fe0463d05b492581cd5bdae360a9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/objects/usd_object.py @@ -0,0 +1,1256 @@ +import hashlib +import os +import tempfile +from abc import ABCMeta +from collections import defaultdict +from collections.abc import Iterable +from functools import cached_property +from typing import Literal + +import torch as th +from omnigibson.utils.bddl_utils import get_knowledge_base + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros, gm +from omnigibson.object_states import Saturated +from omnigibson.object_states.factory import ( + get_default_states, + get_fire_states, + get_requirements_for_ability, + get_state_name, + get_states_and_params_for_ability, + get_states_by_dependency_order, + get_steam_states, + get_texture_change_priority, + get_texture_change_states, + get_visual_states, +) +from omnigibson.object_states.heat_source_or_sink import HeatSourceOrSink +from omnigibson.object_states.object_state_base import REGISTERED_OBJECT_STATES +from omnigibson.object_states.on_fire import OnFire +from omnigibson.prims.entity_prim import EntityPrim +from omnigibson.prims.geom_prim import GeomPrim +from omnigibson.prims.rigid_dynamic_prim import RigidDynamicPrim +from omnigibson.utils.asset_utils import decrypt_file +from omnigibson.utils.constants import EmitterType, PrimType +from omnigibson.utils.python_utils import Registerable, classproperty, extract_class_init_kwargs_from_dict, get_uuid +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import ( + absolute_prim_path_to_scene_relative, + add_asset_to_stage, + compute_kinematic_only, + count_joints, + create_joint, + find_joint_prims, +) +from omnigibson.utils.vision_utils import add_semantic_label + +# Global dicts that will contain mappings +REGISTERED_OBJECTS = dict() + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# Settings for highlighting objects +m.HIGHLIGHT_RGB = [1.0, 0.1, 0.92] # Default highlighting (R,G,B) color when highlighting objects +m.HIGHLIGHT_INTENSITY = 10000.0 # Highlight intensity to apply, range [0, 10000) + +# Physics settings for objects -- see https://nvidia-omniverse.github.io/PhysX/physx/5.3.1/docs/RigidBodyDynamics.html?highlight=velocity%20iteration#solver-iterations +m.DEFAULT_SOLVER_POSITION_ITERATIONS = 32 +m.DEFAULT_SOLVER_VELOCITY_ITERATIONS = 1 + +m.STEAM_EMITTER_SIZE_RATIO = [0.8, 0.8, 0.4] # (x,y,z) scale of generated steam relative to its object, range [0, inf) +m.STEAM_EMITTER_DENSITY_CELL_RATIO = 0.1 # scale of steam density relative to its object, range [0, inf) +m.STEAM_EMITTER_HEIGHT_RATIO = 0.6 # z-height of generated steam relative to its object's native height, range [0, inf) +m.FIRE_EMITTER_HEIGHT_RATIO = 0.4 # z-height of generated fire relative to its object's native height, range [0, inf) + + +# Counter that assigns each flow emitter a unique layer number so emitters don't interfere. +_EMITTER_LAYER_COUNTER = 1 + + +class USDObject(EntityPrim, Registerable, metaclass=ABCMeta): + """ + USDObject is the interface that all OmniGibson objects must implement. + Objects are instantiated from a USD file and can be composed of one or more links and joints. + """ + + def __init__( + self, + name, + usd_path, + encrypted=False, + relative_prim_path=None, + category="object", + scale=None, + visible=True, + fixed_base=False, + visual_only=False, + kinematic_only=None, + self_collisions=False, + prim_type=PrimType.RIGID, + link_physics_materials=None, + load_config=None, + abilities=None, + include_default_states=True, + recorded_non_kin_state_names=None, + expected_file_hash=None, + **kwargs, + ): + """ + Args: + name (str): Name for the object. Names need to be unique per scene + usd_path (str): global path to the USD file to load + encrypted (bool): whether this file is encrypted (and should therefore be decrypted) or not + relative_prim_path (None or str): The path relative to its scene prim for this object. If not specified, it defaults to /. + category (str): Category for the object. Defaults to "object". + scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale + for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a + 3-array specifies per-axis scaling. + visible (bool): whether to render this object or not in the stage + fixed_base (bool): whether to fix the base of this object or not + visual_only (bool): Whether this object should be visual only (and not collide with any other objects) + kinematic_only (None or bool): Whether this object should be kinematic only (and not get affected by any + collisions). If None, then this value will be set to True if @fixed_base is True and some other criteria + are satisfied (see usd_object.py post_load function), else False. + self_collisions (bool): Whether to enable self collisions for this object + prim_type (PrimType): Which type of prim the object is, Valid options are: {PrimType.RIGID, PrimType.CLOTH} + link_physics_materials (None or dict): If specified, dictionary mapping link name to kwargs used to generate + a specific physical material for that link's collision meshes, where the kwargs are arguments directly + passed into the isaacsim.core.api.materials.physics_material.PhysicsMaterial constructor, e.g.: "static_friction", + "dynamic_friction", and "restitution" + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. + abilities (None or dict): If specified, manually adds specific object states to this object. It should be + a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to + the object state instance constructor. + include_default_states (bool): whether to include the default object states from @get_default_states + recorded_non_kin_state_names (None or list[str]): Non-kinematic state classes present in a recording + that this object is being constructed to replay. Missing current states are constructed before + initialization so serialized rows from an older taxonomy retain their recorded layout. None for + ordinary, non-playback construction. + expected_file_hash (str): The expected hash of the file to load. This is used to check if the file has changed. None to disable check. + kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing + for flexible compositions of various object subclasses (e.g.: Robot is USDObject). + Note that this base object does NOT pass kwargs down into the Prim-type super() classes, and we assume + that kwargs are only shared between all SUBclasses (children), not SUPERclasses (parents). + """ + self._usd_path = usd_path + self._encrypted = encrypted + self._expected_file_hash = expected_file_hash + # Generate default prim path if none is specified + relative_prim_path = f"/{name}" if relative_prim_path is None else relative_prim_path + + # Store values + self._uuid = get_uuid(name, deterministic=True) + self.category = category + self.fixed_base = fixed_base + self._link_physics_materials = dict() if link_physics_materials is None else link_physics_materials + + # Values to be created at runtime + self._highlighted = False + self._highlight_color = m.HIGHLIGHT_RGB + self._highlight_intensity = m.HIGHLIGHT_INTENSITY + + # Object state values + self._states = None + self._emitters = dict() + self._visual_states = None + self._current_texture_state = None + self._include_default_states = include_default_states + self._recorded_non_kin_state_build_order = ( + None if recorded_non_kin_state_names is None else tuple(recorded_non_kin_state_names) + ) + self._recorded_non_kin_state_names = ( + None if self._recorded_non_kin_state_build_order is None else set(self._recorded_non_kin_state_build_order) + ) + # Set to the exact per-demo order by the playback wrapper after reset. The constructor + # receives a union because one environment can replay multiple recordings. + self._recorded_non_kin_state_order = None + + # Load abilities from taxonomy if needed & possible + # TODO: Move this to dataset object? Loads B1K abilities for non-B1K objects. + if abilities is None: + abilities = {} + kb_category = get_knowledge_base().get_category(category) + if kb_category is not None and kb_category.synset is not None: + abilities = kb_category.synset.abilities + assert isinstance(abilities, dict), "Object abilities must be in dictionary form." + self._abilities = abilities + + # Create load config from inputs + load_config = dict() if load_config is None else load_config + load_config["scale"] = ( + scale + if isinstance(scale, th.Tensor) + else th.tensor(scale, dtype=th.float32) + if isinstance(scale, Iterable) + else scale + ) + load_config["visible"] = visible + load_config["visual_only"] = visual_only + load_config["kinematic_only"] = kinematic_only + load_config["self_collisions"] = self_collisions + load_config["prim_type"] = prim_type + + # Run super init + super().__init__( + relative_prim_path=relative_prim_path, + name=name, + load_config=load_config, + ) + + # TODO: Super hacky, think of a better way to preserve this info + # Update init info for this + self._init_info["args"]["name"] = self.name + + def _prepare_to_load(self): + """Prepare to load the USD by decrypting, correcting paths, checking hashes, and + pre-applying ArticulationRootAPI at the correct location.""" + usd_path = self._usd_path + + if self._encrypted: + # Create a temporary file to store the decrytped asset, load it, and then delete it + encrypted_filename = self._usd_path.replace(".usd", ".encrypted.usd") + self.check_hash(encrypted_filename) + basename = os.path.basename(self._usd_path) + tempdir_path = tempfile.mkdtemp(basename, dir=og.tempdir) + usd_path = os.path.join(tempdir_path, f"{basename}.usd") + decrypt_file(encrypted_filename, usd_path) + + # Update the paths of all assets to be the absolute path. This is important because the + # relative paths are relative to the encrypted file and not the decrypted file in the + # tempdir. + side_stage = lazy.pxr.Usd.Stage.Open(usd_path) + + def _update_path(asset_path): + if ".mdl" in asset_path: + # MDL paths are searched for in a different search space, so we don't modify them + return asset_path + return os.path.join(os.path.dirname(encrypted_filename), asset_path) + + lazy.pxr.UsdUtils.ModifyAssetPaths(side_stage.GetRootLayer(), _update_path) + side_stage.Save() + del side_stage + else: + self.check_hash(usd_path) + + usd_path = self._preapply_articulation_root(usd_path) + + return usd_path + + def _get_preapply_scale(self, default_prim): + """ + Returns the scale tensor to use when computing kinematic_only inside _preapply_articulation_root. + Subclasses can override to derive scale from USD-side data (e.g. ig:nativeBB for dataset objects). + + Args: + default_prim (Usd.Prim): The default prim of the side stage opened by _preapply_articulation_root. + + Returns: + th.Tensor: 3-element float scale tensor. + """ + raw_scale = self._load_config.get("scale", None) + if raw_scale is not None: + scale = raw_scale if isinstance(raw_scale, th.Tensor) else th.tensor(raw_scale, dtype=th.float32) + if scale.dim() == 0: + scale = scale.expand(3) + return scale.float() + return th.ones(3) + + def _apply_usd_hotfixes(self, stage, default_prim): + """ + Hook for patching the object's USD in place before anything else inspects it. Subclasses can override to + fix up asset-side annotation bugs that we cannot currently re-export the assets for. + + Args: + stage (Usd.Stage): The side stage opened by _preapply_articulation_root. + default_prim (Usd.Prim): The default prim of @stage. + """ + pass + + def _preapply_articulation_root(self, usd_path): + """ + Opens @usd_path with the pxr library, strips any existing ArticulationRootAPI, determines the correct prim to + carry it, applies it there, and returns a path to the modified USD written to a temp file. + """ + stage = lazy.pxr.Usd.Stage.Open(usd_path) + default_prim = stage.GetDefaultPrim() + + # Apply any asset-specific hotfixes first, so that the joint / link counting below sees the final structure + self._apply_usd_hotfixes(stage, default_prim) + + for p in stage.Traverse(): + p.RemoveAPI(lazy.pxr.UsdPhysics.ArticulationRootAPI) + p.RemoveAPI(lazy.pxr.PhysxSchema.PhysxArticulationAPI) + + n_joints, n_fixed_joints, has_attachment = count_joints(default_prim) + + scale = self._get_preapply_scale(default_prim) + # Only persist scale to _load_config if the user already provided one, or if a non-trivial + # scale was derived (e.g. from bounding_box). Avoid overwriting None with the default + # ones(3) so that PrimitiveObjects using radius/height/size are not affected. + if self._load_config.get("scale", None) is not None or not th.allclose(scale, th.ones_like(scale)): + self._load_config["scale"] = scale + + kinematic_only = compute_kinematic_only( + self.fixed_base, + scale, + n_joints, + n_fixed_joints, + self._load_config.get("kinematic_only", None), + has_attachment, + ) + self._load_config["kinematic_only"] = kinematic_only + + # Find root link: the Xform child that is not body1 of any joint that also has a body0. + # Joints can live anywhere under default_prim (recent Isaac Sim exports place them in a flat + # /joints scope rather than under their body0 link), so traverse the full subtree. + link_names = [prim.GetName() for prim in default_prim.GetChildren() if prim.GetTypeName() == "Xform"] + joint_children = set() + for joint in find_joint_prims(default_prim): + rels = {r.GetName(): r for r in joint.GetRelationships()} + body0_rel = rels.get("physics:body0") + body1_rel = rels.get("physics:body1") + if body0_rel is None or body1_rel is None: + continue + if len(body0_rel.GetTargets()) > 0 and len(body1_rel.GetTargets()) > 0: + joint_children.add(body1_rel.GetTargets()[0].pathString.split("/")[-1]) + valid_roots = list(set(link_names) - joint_children) + assert len(valid_roots) == 1, ( + f"Exactly one root link should have been found for {default_prim.GetName()}, " + f"but found none/multiple instead: {valid_roots}" + ) + root_link = default_prim.GetPrimAtPath(valid_roots[0]) + + if self.fixed_base and not kinematic_only: + create_joint( + prim_path=f"{default_prim.GetPath()}/rootJoint", + joint_type="FixedJoint", + body1=f"{root_link.GetPath()}", + stage=stage, + ) + n_fixed_joints += 1 + + # Add articulated_ prefix into prim path so ArticulationView can use a simple pattern match + # Only for non-robot articulated objects + if ( + not kinematic_only + and (n_joints > 0 or n_fixed_joints > 0) + and not self._relative_prim_path.startswith("/controllable") + ): + self._relative_prim_path = f"/articulated__{self.name}" + + # Determine which prim should carry ArticulationRootAPI + articulation_root_prim = None + if not kinematic_only and (n_joints > 0 or n_fixed_joints > 0): + if not self.fixed_base: + articulation_root_prim = root_link + else: + articulation_root_prim = default_prim + + if articulation_root_prim is not None: + lazy.pxr.UsdPhysics.ArticulationRootAPI.Apply(articulation_root_prim) + lazy.pxr.PhysxSchema.PhysxArticulationAPI.Apply(articulation_root_prim) + articulation_root_prim.GetAttribute("physxArticulation:enabledSelfCollisions").Set( + bool(self._load_config.get("self_collisions", False)) + ) + + # Export to a temp file + basename = os.path.basename(usd_path) + tempdir_path = tempfile.mkdtemp(basename, dir=og.tempdir) + temp_usd_path = os.path.join(tempdir_path, basename) + stage.Export(temp_usd_path) + return temp_usd_path + + def prebuild(self, stage): + """ + Pre-build this object on an USD stage that is not loaded into Isaac Sim. + This is useful for pre-compiling scene USDs, speeding up load times especially for parallel envs. + """ + # The /World in the scene USD will be mapped to /World/scene_i in Isaac Sim. + usd_path = self._prepare_to_load() + prim_path = "/World" + self._relative_prim_path + prim = stage.GetPrimAtPath(prim_path) + assert not prim.IsValid(), f"Prim path {prim_path} already exists in the stage!" + prim = stage.DefinePrim(prim_path, "Xform") + assert prim.GetReferences().AddReference(usd_path) + + def _load(self): + return add_asset_to_stage(asset_path=self._prepared_usd_path, prim_path=self.prim_path) + + def load(self, scene): + # Always run _prepare_to_load (which calls _preapply_articulation_root) so that + # _load_config["kinematic_only"] and _load_config["scale"] are set correctly before + # _post_load runs, even when the prim already exists in the stage (e.g. from prebuild). + self._prepared_usd_path = self._prepare_to_load() + prim = super().load(scene) + log.info(f"Loaded {self.name} at {self.prim_path}") + return prim + + def remove(self): + # Run super first + super().remove() + + # Notify user that the object was removed + log.info(f"Removed {self.name} from {self.prim_path}") + + # Iterate over all states and run their remove call + for state_instance in self._states.values(): + state_instance.remove() + + def _post_load(self): + # Run super first + super()._post_load() + + # Set visibility + if "visible" in self._load_config and self._load_config["visible"] is not None: + self.visible = self._load_config["visible"] + + # Set position / velocity solver iterations if we're not cloth and not kinematic only + if self._prim_type != PrimType.CLOTH and not self.kinematic_only: + self.solver_position_iteration_count = m.DEFAULT_SOLVER_POSITION_ITERATIONS + self.solver_velocity_iteration_count = m.DEFAULT_SOLVER_VELOCITY_ITERATIONS + + # Add link materials if specified + if self._link_physics_materials is not None: + for link_name, material_info in self._link_physics_materials.items(): + # We will permute the link materials dict in place to now point to the created material + mat_name = f"{link_name}_physics_mat" + physics_mat = lazy.isaacsim.core.api.materials.physics_material.PhysicsMaterial( + prim_path=f"{self.prim_path}/Looks/{mat_name}", + name=mat_name, + **material_info, + ) + for msh in self.links[link_name].collision_meshes.values(): + msh.apply_physics_material(physics_mat) + self._link_physics_materials[link_name] = physics_mat + + # Add semantics + add_semantic_label(prim=self._prim, label=self.category) + + # Prepare the object states + self._states = {} + self.prepare_object_states() + + def _initialize(self): + # Run super first + super()._initialize() + + # Initialize all states + for state in self._states.values(): + state.initialize() + + # Check whether this object requires any visual updates + states_set = set(self.states) + self._visual_states = states_set & get_visual_states() + + # If we require visual updates, possibly create additional APIs + if len(self._visual_states) > 0: + if len(states_set & get_steam_states()) > 0: + self._create_emitter_apis(EmitterType.STEAM) + + if len(states_set & get_fire_states()) > 0: + self._create_emitter_apis(EmitterType.FIRE) + + def add_state(self, state): + """ + Adds state @state with name @name to self.states. + + Args: + state (ObjectStateBase): Object state instance to add to this object + """ + assert self._states is not None, "Cannot add state since states have not been initialized yet!" + assert ( + state.__class__ not in self._states + ), f"State {state.__class__.__name__} has already been added to this object!" + self._states[state.__class__] = state + + @property + def states(self): + """ + Get the current states of this object. + + Returns: + dict: Keyword-mapped states for this object + """ + return self._states + + @property + def abilities(self): + """ + Returns: + dict: Dictionary mapping ability name to ability arguments for this object + """ + return self._abilities + + @property + def usd_path(self): + """ + Returns: + str: absolute path to this model's USD file + """ + return self._usd_path + + def check_hash(self, usd_path): + """ + Check if the hash of the file matches the expected hash. + + Args: + usd_path (str): The path to the USD file. + """ + # Hash the file to record the loaded asset's version + hash_md5 = hashlib.md5() + with open(usd_path, "rb") as f: + for chunk in iter(lambda: f.read(65536), b""): + hash_md5.update(chunk) + file_hash = hash_md5.hexdigest() + + # If there is a file hash already in the init info, compare against it to see if the file has changed + if self._expected_file_hash is not None: + if file_hash != self._expected_file_hash: + log.debug( + f"Object {self.name} was expected to have USD file hash {self._expected_file_hash} but loaded with {file_hash}. The saved state might be incompatible." + ) + else: + # If there is no expected file hash, set the expected file hash to the loaded one + self._expected_file_hash = file_hash + + # Update the init info too so that the information gets saved with the scene. + # TODO: Super hacky, think of a better way to preserve this info + self._init_info["args"]["expected_file_hash"] = file_hash + + @property + def is_active(self): + """ + Returns: + bool: True if this object is currently considered active -- e.g.: if this object is currently awake + """ + return not self.kinematic_only and not self.is_asleep or self in self.scene.updated_state_objects + + def state_updated(self): + """ + Adds this object to this object's scene's updated_state_objects set -- generally called externally + by owned object state instances when its state is updated. This is useful for tracking when this object + has had its state updated within the last simulation step + """ + self.scene.updated_state_objects.add(self) + + def prepare_object_states(self): + """ + Prepare the state dictionary for an object by generating the appropriate + object state instances. + + This uses the abilities of the object and the state dependency graph to + find & instantiate all relevant states. + """ + states_info = ( + {state_type: {"ability": None, "params": dict()} for state_type in get_default_states()} + if self._include_default_states + else dict() + ) + + # Map the state type (class) to ability name and params + if gm.ENABLE_OBJECT_STATES: + for ability in tuple(self._abilities.keys()): + # First, sanity check all ability requirements + compatible = True + for requirement in get_requirements_for_ability(ability): + compatible, reason = requirement.is_compatible(obj=self) + if not compatible: + # Print out warning and pop ability + log.debug( + f"Ability '{ability}' is incompatible with obj {self.name}, " + f"because requirement {requirement.__name__} was not met. Reason: {reason}" + ) + self._abilities.pop(ability) + break + if compatible: + params = self._abilities[ability] + for state_type, state_params in get_states_and_params_for_ability(ability, params): + # Fail loudly instead of silently letting the last ability's params win — + # a single state instance can't serve two abilities (e.g. an object that + # is both a heatSource and flammable is not supported; the BDDL data + # generation sanity checks enforce this at the synset level). Raised + # unconditionally (not an assert) so python -O cannot skip it. + if state_type in states_info: + raise ValueError( + f"Object {self.name}: state {state_type.__name__} is requested by multiple abilities " + f"({states_info[state_type]['ability']} and {ability}); this is not supported." + ) + states_info[state_type] = { + "ability": ability, + "params": state_type.postprocess_ability_params(state_params, self.scene), + } + + # A recording's flattened object state is not self-describing: if the current taxonomy + # has dropped a state, merely filtering out newly-added current states leaves the reader + # short and every subsequent object is parsed at the wrong offset. Construct only the + # missing recorded states here, after current abilities have supplied their parameters + # but before dependencies and tensor views are initialized. States requiring unavailable + # parameters or incompatible assets are deliberately allowed to fail loudly below. + if self._recorded_non_kin_state_build_order is not None: + for state_name in self._recorded_non_kin_state_build_order: + if state_name not in REGISTERED_OBJECT_STATES: + raise ValueError(f"Object {self.name}: recording references unknown object state {state_name!r}") + state_type = REGISTERED_OBJECT_STATES[state_name] + states_info.setdefault(state_type, {"ability": None, "params": dict()}) + + # Add the dependencies into the list, too, and sort based on the dependency chain + # Must iterate over explicit tuple since dictionary changes size mid-iteration + for state_type in tuple(states_info.keys()): + # Add each state's dependencies, too. Note that only required dependencies are explicitly added, but both + # required AND optional dependencies are checked / sorted + for dependency in state_type.get_dependencies(): + if dependency not in states_info: + states_info[dependency] = {"ability": None, "params": dict()} + + # Iterate over all sorted state types, generating the states in topological order. + self._states = dict() + for state_type in get_states_by_dependency_order(states=states_info): + # Skip over any types that are not in our info dict -- these correspond to optional dependencies + if state_type not in states_info: + continue + + relevant_params = extract_class_init_kwargs_from_dict( + cls=state_type, dic=states_info[state_type]["params"], copy=False + ) + compatible, reason = state_type.is_compatible(obj=self, **relevant_params) + if compatible: + self._states[state_type] = state_type(obj=self, **relevant_params) + else: + log.debug(f"State {state_type.__name__} is incompatible with obj {self.name}. Reason: {reason}") + # Remove the ability if it exists + # Note that the object may still have some of the states related to the desired ability. In this way, + # we guarantee that the existence of a certain ability in self.abilities means at ALL corresponding + # object state dependencies are met by the underlying object asset + ability = states_info[state_type]["ability"] + if ability in self._abilities: + self._abilities.pop(ability) + + def _create_emitter_apis(self, emitter_type): + """ + Create necessary prims and apis for steam effects. + + Args: + emitter_type (EmitterType): Emitter to create + """ + # Specify emitter config. + emitter_config = {} + bbox_extent_local = self.native_bbox if hasattr(self, "native_bbox") else self.aabb_extent / self.scale + if emitter_type == EmitterType.FIRE: + fire_at_meta_link = True + if OnFire in self.states: + # Flammable object: the fire is placed at the companion heat source's link + # (the heatsource meta link when annotated, e.g. a candle wick; the root link + # otherwise). OnFire itself is a pure threshold detector and carries no link. + heat_source = self.states.get(HeatSourceOrSink) + link = heat_source.link if heat_source is not None else self.root_link + fire_at_meta_link = link != self.root_link + elif HeatSourceOrSink in self.states: + # Only apply fire to non-root-link (i.e.: explicitly specified) heat source links + # Otherwise, immediately return + link = self.states[HeatSourceOrSink].link + if link == self.root_link: + return + else: + raise ValueError("Unknown fire state") + + emitter_config["name"] = "flowEmitterSphere" + emitter_config["type"] = "FlowEmitterSphere" + emitter_config["position"] = ( + (0.0, 0.0, 0.0) if fire_at_meta_link else (0.0, 0.0, bbox_extent_local[2] * m.FIRE_EMITTER_HEIGHT_RATIO) + ) + emitter_config["fuel"] = 0.6 + emitter_config["coupleRateFuel"] = 1.2 + emitter_config["buoyancyPerTemp"] = 0.04 + emitter_config["burnPerTemp"] = 4 + emitter_config["gravity"] = (0, 0, -60.0) + emitter_config["constantMask"] = 5.0 + emitter_config["attenuation"] = 0.5 + elif emitter_type == EmitterType.STEAM: + link = self.root_link + emitter_config["name"] = "flowEmitterBox" + emitter_config["type"] = "FlowEmitterBox" + emitter_config["position"] = (0.0, 0.0, bbox_extent_local[2] * m.STEAM_EMITTER_HEIGHT_RATIO) + emitter_config["fuel"] = 1.0 + emitter_config["coupleRateFuel"] = 0.5 + emitter_config["buoyancyPerTemp"] = 0.05 + emitter_config["burnPerTemp"] = 0.5 + emitter_config["gravity"] = (0, 0, -50.0) + emitter_config["constantMask"] = 10.0 + emitter_config["attenuation"] = 1.5 + else: + raise ValueError("Currently, only EmitterTypes FIRE and STEAM are supported!") + + # Define prim paths. + # The flow system is created under the root link (under a dummy mesh) so that it automatically updates its pose + # as the object moves. We put it under a dummy mesh so as not to force write synchronization to the actual + # physx-tracked links (required when using Fabric), which causes physics issues + dummy_mesh_path = f"{link.prim_path}/emitter" + with og.sim.editing_usd(): + lazy.pxr.UsdGeom.Sphere.Define(og.sim.stage, dummy_mesh_path) + relative_dummy_mesh_path = absolute_prim_path_to_scene_relative(self._scene, dummy_mesh_path) + mesh = GeomPrim(relative_prim_path=relative_dummy_mesh_path, name=f"{self.name}_emitter") + mesh.load(self._scene) + mesh.visible = False + + flowEmitter_prim_path = f"{mesh.prim_path}/{emitter_config['name']}" + flowSimulate_prim_path = f"{mesh.prim_path}/flowSimulate" + flowOffscreen_prim_path = f"{mesh.prim_path}/flowOffscreen" + flowRender_prim_path = f"{mesh.prim_path}/flowRender" + + # Define prims and set attributes — all USD edits for this emitter. + with og.sim.editing_usd(): + stage = og.sim.stage + emitter = stage.DefinePrim(flowEmitter_prim_path, emitter_config["type"]) + simulate = stage.DefinePrim(flowSimulate_prim_path, "FlowSimulate") + offscreen = stage.DefinePrim(flowOffscreen_prim_path, "FlowOffscreen") + renderer = stage.DefinePrim(flowRender_prim_path, "FlowRender") + advection = stage.DefinePrim(flowSimulate_prim_path + "/advection", "FlowAdvectionCombustionParams") + smoke = stage.DefinePrim(flowSimulate_prim_path + "/advection/smoke", "FlowAdvectionCombustionParams") + vorticity = stage.DefinePrim(flowSimulate_prim_path + "/vorticity", "FlowVorticityParams") + rayMarch = stage.DefinePrim(flowRender_prim_path + "/rayMarch", "FlowRayMarchParams") + colormap = stage.DefinePrim(flowOffscreen_prim_path + "/colormap", "FlowRayMarchColormapParams") + + self._emitters[emitter_type] = { + "emitter": emitter, + "mesh": mesh, + "link": link, + "canonical_pose": mesh.get_position_orientation(), + } + + global _EMITTER_LAYER_COUNTER + layer_number = _EMITTER_LAYER_COUNTER + _EMITTER_LAYER_COUNTER += 1 + + # Update emitter general settings. + emitter.CreateAttribute("enabled", lazy.pxr.Sdf.ValueTypeNames.Bool, False).Set(False) + emitter.CreateAttribute("position", lazy.pxr.Sdf.ValueTypeNames.Float3, False).Set( + emitter_config["position"] + ) + emitter.CreateAttribute("fuel", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(emitter_config["fuel"]) + emitter.CreateAttribute("coupleRateFuel", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set( + emitter_config["coupleRateFuel"] + ) + emitter.CreateAttribute("coupleRateVelocity", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(2.0) + emitter.CreateAttribute("velocity", lazy.pxr.Sdf.ValueTypeNames.Float3, False).Set((0, 0, 0)) + emitter.CreateAttribute("physicsVelocityScale", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(1.0) + emitter.CreateAttribute("layer", lazy.pxr.Sdf.ValueTypeNames.Int, False).Set(layer_number) + simulate.CreateAttribute("layer", lazy.pxr.Sdf.ValueTypeNames.Int, False).Set(layer_number) + simulate.CreateAttribute("stepsPerSecond", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set( + 1 / og.sim.get_sim_step_dt() + ) + offscreen.CreateAttribute("layer", lazy.pxr.Sdf.ValueTypeNames.Int, False).Set(layer_number) + renderer.CreateAttribute("layer", lazy.pxr.Sdf.ValueTypeNames.Int, False).Set(layer_number) + advection.CreateAttribute("buoyancyPerTemp", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set( + emitter_config["buoyancyPerTemp"] + ) + advection.CreateAttribute("burnPerTemp", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set( + emitter_config["burnPerTemp"] + ) + advection.CreateAttribute("gravity", lazy.pxr.Sdf.ValueTypeNames.Float3, False).Set( + emitter_config["gravity"] + ) + vorticity.CreateAttribute("constantMask", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set( + emitter_config["constantMask"] + ) + rayMarch.CreateAttribute("attenuation", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set( + emitter_config["attenuation"] + ) + + # Update emitter unique settings. + if emitter_type == EmitterType.FIRE: + # Radius is in the absolute world coordinate even though the fire is under the link frame. + # In other words, scaling the object doesn't change the fire radius. + if fire_at_meta_link: + # TODO: get radius of heat_source_link from metadata. + radius = 0.05 + else: + bbox_extent_world = ( + self.native_bbox * self.scale if hasattr(self, "native_bbox") else self.aabb_extent + ) + # Radius is the average x-y half-extent of the object + radius = float(th.mean(bbox_extent_world[:2]) / 2.0) + emitter.CreateAttribute("radius", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(radius) + simulate.CreateAttribute("densityCellSize", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(radius * 0.2) + smoke.CreateAttribute("fade", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(2.0) + # Set fire colormap. + rgbaPoints = [] + rgbaPoints.append(lazy.pxr.Gf.Vec4f(0.0154, 0.0177, 0.0154, 0.004902)) + rgbaPoints.append(lazy.pxr.Gf.Vec4f(0.03575, 0.03575, 0.03575, 0.504902)) + rgbaPoints.append(lazy.pxr.Gf.Vec4f(0.03575, 0.03575, 0.03575, 0.504902)) + rgbaPoints.append(lazy.pxr.Gf.Vec4f(1, 0.1594, 0.0134, 0.8)) + rgbaPoints.append(lazy.pxr.Gf.Vec4f(13.53, 2.99, 0.12599, 0.8)) + rgbaPoints.append(lazy.pxr.Gf.Vec4f(78, 39, 6.1, 0.7)) + colormap.CreateAttribute("rgbaPoints", lazy.pxr.Sdf.ValueTypeNames.Float4Array, False).Set(rgbaPoints) + elif emitter_type == EmitterType.STEAM: + emitter.CreateAttribute("halfSize", lazy.pxr.Sdf.ValueTypeNames.Float3, False).Set( + tuple(bbox_extent_local * th.tensor(m.STEAM_EMITTER_SIZE_RATIO) / 2.0) + ) + simulate.CreateAttribute("densityCellSize", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set( + bbox_extent_local[2].item() * m.STEAM_EMITTER_DENSITY_CELL_RATIO + ) + + def set_emitter_enabled(self, emitter_type, value): + """ + Enable/disable the emitter prim for fire/steam effect. + + Args: + emitter_type (EmitterType): Emitter to set + value (bool): Value to set + """ + if emitter_type not in self._emitters: + return + # If we're running fabric and the value is active, we need to manually update the pose in the USD + # to ensure the rendering is updated properly at the correct pose + # TODO(#2082): Verify if this is still needed. + if value: + self._sync_emitter_mesh_on_usd(emitter_type=emitter_type) + if value != self._emitters[emitter_type]["emitter"].GetAttribute("enabled").Get(): + with og.sim.editing_usd(): + self._emitters[emitter_type]["emitter"].GetAttribute("enabled").Set(value) + + def _sync_emitter_mesh_on_usd(self, emitter_type): + """ + Synchronizes the emitter's pose corresponding to @emitter_type on the USD + + Args: + emitter_type (EmitterType): Emitter to synchronize + """ + emitter_info = self._emitters[emitter_type] + mesh = emitter_info["mesh"] + link_pose = emitter_info["link"].get_position_orientation() + position, orientation = T.relative_pose_transform(*link_pose, *emitter_info["canonical_pose"]) + + # TODO(#2082): Verify if this is still needed. + # Actually set the local pose now. + position = lazy.pxr.Gf.Vec3d(*position.tolist()) + mesh.set_attribute("xformOp:translate", position) + orientation = orientation[[3, 0, 1, 2]].tolist() + xform_op = mesh.prim.GetAttribute("xformOp:orient") + if xform_op.GetTypeName() == "quatf": + rotq = lazy.pxr.Gf.Quatf(*orientation) + else: + rotq = lazy.pxr.Gf.Quatd(*orientation) + with og.sim.editing_usd(): + xform_op.Set(rotq) + + def update_visuals(self): + """ + Update the prim's visuals (texture change, steam/fire effects, etc). + Should be called after all the states are updated. + """ + if len(self._visual_states) > 0: + texture_change_states = [] + emitter_enabled = defaultdict(bool) + for state_type in self._visual_states: + state = self.states[state_type] + if state_type in get_texture_change_states(): + if state_type == Saturated: + for particle_system in self.scene.active_systems.values(): + if state.get_value(particle_system): + texture_change_states.append(state) + # Only need to do this once, since soaked handles all fluid systems + break + elif state.get_value(): + texture_change_states.append(state) + if state_type in get_steam_states(): + emitter_enabled[EmitterType.STEAM] |= state.get_value() + if state_type in get_fire_states(): + emitter_enabled[EmitterType.FIRE] |= state.get_value() + + for emitter_type in emitter_enabled: + self.set_emitter_enabled(emitter_type, emitter_enabled[emitter_type]) + + texture_change_states.sort(key=lambda s: get_texture_change_priority()[s.__class__]) + object_state = texture_change_states[-1] if len(texture_change_states) > 0 else None + + # Only update our texture change if it's a different object state than the one we already have + if object_state != self._current_texture_state: + self._update_texture_change(object_state) + self._current_texture_state = object_state + + def _update_texture_change(self, object_state): + """ + Update the texture based on the given object_state. E.g. if object_state is Frozen, update the diffuse color + to match the frozen state. If object_state is None, update the diffuse color to the default value. It modifies + the current albedo map by adding and scaling the values. The final albedo value is + albedo_value = diffuse_tint * (albedo_value + albedo_add) + + Args: + object_state (BooleanStateMixin or None): the object state that the diffuse color should match to + """ + # Compute the add and tint values + if object_state is None: + # This restore the albedo map to its original value + albedo_add = 0.0 + diffuse_tint = th.tensor([1.0, 1.0, 1.0]) + else: + # Query the object state for the parameters + albedo_add, diffuse_tint = object_state.get_texture_change_params() + + # Apply the add and tint values + for material in self.materials: + if material.albedo_add != albedo_add: + material.albedo_add = albedo_add + + if not th.allclose(material.diffuse_tint, diffuse_tint): + material.diffuse_tint = diffuse_tint + + @cached_property + def articulation_root_path(self): + has_articulated_joints, has_fixed_joints = self.n_joints > 0, self.n_fixed_joints > 0 + if self.kinematic_only or (not has_articulated_joints and not has_fixed_joints): + # Kinematic only, or non-jointed single body objects + return None + elif not self.fixed_base: + # This is all remaining non-fixed objects + # This is a bit hacky because omniverse is buggy + # Articulation roots mess up the joint order if it's on a non-fixed base robot, e.g. a + # mobile manipulator. So if we have to move it to the actual root link of the robot instead. + # See https://forums.developer.nvidia.com/t/inconsistent-values-from-isaacsims-dc-get-joint-parent-child-body/201452/2 + # for more info + return f"{self.prim_path}/{self.root_link_name}" + else: + # Fixed objects that are not kinematic only, or non-fixed objects that have no articulated joints but do + # have fixed joints + return self.prim_path + + @property + def uuid(self): + """ + Returns: + int: 8-digit unique identifier for this object. It is randomly generated from this object's name + but deterministic + """ + return self._uuid + + @property + def mass(self): + """ + Returns: + float: Cumulative mass of this potentially articulated object. + """ + mass = 0.0 + for link in self._links.values(): + if isinstance(link, RigidDynamicPrim): + mass += link.mass + + return mass + + @mass.setter + def mass(self, mass): + raise NotImplementedError("Cannot set mass directly for an object!") + + @property + def volume(self): + """ + Returns: + float: Cumulative volume of this potentially articulated object. + """ + return sum(link.volume for link in self._links.values()) + + @volume.setter + def volume(self, volume): + raise NotImplementedError("Cannot set volume directly for an object!") + + @property + def scale(self): + # Just super call + return super().scale + + @scale.setter + def scale(self, scale): + # call super first + # A bit esoteric -- see https://gist.github.com/Susensio/979259559e2bebcd0273f1a95d7c1e79 + super(USDObject, type(self)).scale.fset(self, scale) + + # Update init info for scale + self._init_info["args"]["scale"] = scale + + @property + def highlighted(self): + """ + Returns: + bool: Whether the object is highlighted or not + """ + return self._highlighted + + @highlighted.setter + def highlighted(self, enabled): + """ + Iterates over all owned links, and modifies their materials with emissive colors so that the object is + highlighted (magenta by default) + + Args: + enabled (bool): whether the object should be highlighted or not + """ + # Return early if the set value matches the internal value + if enabled == self._highlighted: + return + + for material in self.materials: + if enabled: + material.enable_highlight(self._highlight_color, self._highlight_intensity) + else: + material.disable_highlight() + + # Update internal value + self._highlighted = enabled + + def set_highlight_properties(self, color=m.HIGHLIGHT_RGB, intensity=m.HIGHLIGHT_INTENSITY): + """ + Sets the highlight properties for this object + + Args: + color (3-array): RGB color for the highlight + intensity (float): Intensity for the highlight + """ + self._highlight_color = color + self._highlight_intensity = intensity + + # Update the highlight properties if the object is currently highlighted + if self._highlighted: + self.highlighted = False + self.highlighted = True + + def get_base_aligned_bbox(self, link_name=None, visual=False, xy_aligned=False): + """ + Get a bounding box for this object that's axis-aligned in the object's base frame. + + Args: + link_name (None or str): If specified, only get the bbox for the given link + visual (bool): Whether to aggregate the bounding boxes from the visual meshes. Otherwise, will use + collision meshes + xy_aligned (bool): Whether to align the bounding box to the global XY-plane + + Returns: + 4-tuple: + - 3-array: (x,y,z) bbox center position in world frame + - 3-array: (x,y,z,w) bbox quaternion orientation in world frame + - 3-array: (x,y,z) bbox extent in desired frame + - 3-array: (x,y,z) bbox center in desired frame + """ + # Get the base position transform. + pos, orn = self.get_position_orientation() + base_frame_to_world = T.pose2mat((pos, orn)) + + # Prepare the desired frame. + if xy_aligned: + # If the user requested an XY-plane aligned bbox, convert everything to that frame. + # The desired frame is same as the base_com frame with its X/Y rotations removed. + translate = base_frame_to_world[:3, 3] + + # To find the rotation that this transform does around the Z axis, we rotate the [1, 0, 0] vector by it + # and then take the arctangent of its projection onto the XY plane. + rotated_X_axis = base_frame_to_world[:3, 0] + rotation_around_Z_axis = th.arctan2(rotated_X_axis[1], rotated_X_axis[0]) + xy_aligned_base_com_to_world = th.eye(4, dtype=th.float32) + xy_aligned_base_com_to_world[:3, 3] = translate + xy_aligned_base_com_to_world[:3, :3] = T.euler2mat( + th.tensor([0, 0, rotation_around_Z_axis], dtype=th.float32) + ) + + # Finally update our desired frame. + desired_frame_to_world = xy_aligned_base_com_to_world + else: + # Default desired frame is base CoM frame. + desired_frame_to_world = base_frame_to_world + + # Compute the world-to-base frame transform. + world_to_desired_frame = th.linalg.inv_ex(desired_frame_to_world).inverse + + # Grab all the world-frame points corresponding to the object's visual or collision hulls. + points_in_world = [] + if self.prim_type == PrimType.CLOTH: + particle_contact_offset = self.root_link.cloth_system.particle_contact_offset + particle_positions = self.root_link.compute_particle_positions() + particles_in_world_frame = th.cat( + [particle_positions - particle_contact_offset, particle_positions + particle_contact_offset], dim=0 + ) + points_in_world.extend(particles_in_world_frame.tolist()) + else: + links = {link_name: self._links[link_name]} if link_name is not None else self._links + for link_name, link in links.items(): + if visual: + hull_points = link.visual_boundary_points_world + else: + hull_points = link.collision_boundary_points_world + + if hull_points is not None: + points_in_world.extend(hull_points.tolist()) + + # Move the points to the desired frame + points = T.transform_points(th.tensor(points_in_world, dtype=th.float32), world_to_desired_frame) + + # All points are now in the desired frame: either the base CoM or the xy-plane-aligned base CoM. + # Now fit a bounding box to all the points by taking the minimum/maximum in the desired frame. + aabb_min_in_desired_frame = th.amin(points, dim=0) + aabb_max_in_desired_frame = th.amax(points, dim=0) + bbox_center_in_desired_frame = (aabb_min_in_desired_frame + aabb_max_in_desired_frame) / 2 + bbox_extent_in_desired_frame = aabb_max_in_desired_frame - aabb_min_in_desired_frame + + # Transform the center to the world frame. + bbox_center_in_world = T.transform_points( + bbox_center_in_desired_frame.unsqueeze(0), desired_frame_to_world + ).squeeze(0) + bbox_orn_in_world = T.mat2quat(desired_frame_to_world[:3, :3]) + + return bbox_center_in_world, bbox_orn_in_world, bbox_extent_in_desired_frame, bbox_center_in_desired_frame + + def dump_state(self, serialized=False): + """ + Dumps the state of this object in either dictionary of flattened numerical form. + + Args: + serialized (bool): If True, will return the state of this object as a 1D numpy array. Otherewise, will return + a (potentially nested) dictionary of states for this object + + Returns: + dict or n-array: Either: + - Keyword-mapped states of this object, or + - encoded + serialized, 1D numerical th.Tensor capturing this object's state + """ + assert self._initialized, "Object must be initialized before dumping state!" + return super().dump_state(serialized=serialized) + + def _dump_state(self): + # Grab state from super class + state = super()._dump_state() + + # Also add non-kinematic states + non_kin_states = dict() + for state_type, state_instance in self._states.items(): + if state_instance.stateful: + non_kin_states[get_state_name(state_type)] = state_instance.dump_state(serialized=False) + + state["non_kin"] = non_kin_states + + return state + + def _load_state(self, state): + # Call super method first + super()._load_state(state=state) + + # Load non-kinematic states + self.load_non_kin_state(state) + + def load_non_kin_state(self, state): + # Load all states that are stateful + for state_type, state_instance in self._states.items(): + state_name = get_state_name(state_type) + if state_instance.stateful: + if state_name in state["non_kin"]: + state_instance.load_state(state=state["non_kin"][state_name], serialized=False) + else: + log.debug(f"Missing object state [{state_name}] in the state dump for obj {self.name}") + + # Clear cache after loading state + self.clear_states_cache() + + def serialize(self, state): + # Call super method first + state_flat = super().serialize(state=state) + + # Iterate over all states and serialize them individually + non_kin_state_flat = ( + th.cat( + [ + self._states[REGISTERED_OBJECT_STATES[state_name]].serialize(state_dict) + for state_name, state_dict in state["non_kin"].items() + ] + ) + if len(state["non_kin"]) > 0 + else th.empty(0) + ) + + # Combine these two arrays + return th.cat([state_flat, non_kin_state_flat]) + + def _deserialize_non_kin_states(self, state, idx): + # Iterate over all states and deserialize their states if they're stateful. When replaying + # a recording, use its exact order; membership-only filtering is insufficient because + # taxonomy changes can reorder dependencies as well as add or remove states. + non_kin_state_dic = dict() + recorded_order = getattr(self, "_recorded_non_kin_state_order", None) + if recorded_order is None: + recorded_names = getattr(self, "_recorded_non_kin_state_names", None) + state_items = [ + (get_state_name(state_type), state_instance) + for state_type, state_instance in self._states.items() + if state_instance.stateful and (recorded_names is None or get_state_name(state_type) in recorded_names) + ] + else: + current_states = { + get_state_name(state_type): state_instance for state_type, state_instance in self._states.items() + } + missing = [state_name for state_name in recorded_order if state_name not in current_states] + if missing: + raise ValueError( + f"Object {self.name}: recording contains non-kinematic state(s) {missing}, but the replay " + "object could not construct them. Refusing to deserialize the remaining row at wrong offsets." + ) + state_items = [(state_name, current_states[state_name]) for state_name in recorded_order] + + for state_name, state_instance in state_items: + if state_instance.stateful: + non_kin_state_dic[state_name], deserialized_items = state_instance.deserialize(state[idx:]) + idx += deserialized_items + else: + raise ValueError( + f"Object {self.name}: recorded non-kinematic state {state_name!r} is no longer stateful; " + "its serialized width cannot be consumed safely." + ) + + return non_kin_state_dic, idx + + def deserialize(self, state): + # Call super method first + state_dic, idx = super().deserialize(state=state) + + state_dic["non_kin"], idx = self._deserialize_non_kin_states(state=state, idx=idx) + + return state_dic, idx + + def clear_states_cache(self): + """ + Clears the internal cache from all owned states + """ + # Check self._states just in case states have not been initialized yet. + if not self._states: + return + for _, obj_state in self._states.items(): + obj_state.clear_cache() + + def set_position_orientation( + self, position=None, orientation=None, frame: Literal["world", "parent", "scene"] = "world" + ): + """ + Set the position and orientation of the object. + + Args: + position (None or 3-array): The position to set the object to. If None, the position is not changed. + orientation (None or 4-array): The orientation to set the object to. If None, the orientation is not changed. + frame (Literal): The frame in which to set the position and orientation. Defaults to world. + parent frame: set position relative to the object parent. + scene frame: set position relative to the scene. + """ + super().set_position_orientation(position=position, orientation=orientation, frame=frame) + self.clear_states_cache() + + @classproperty + def _do_not_register_classes(cls): + classes = super()._do_not_register_classes + return classes + + @classproperty + def _cls_registry(cls): + # Global robot registry + global REGISTERED_OBJECTS + return REGISTERED_OBJECTS diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/omnigibson_5_1_0.kit b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/omnigibson_5_1_0.kit new file mode 100644 index 0000000000000000000000000000000000000000..2ab394691d12dea7b913f3a84f328fe16c964e48 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/omnigibson_5_1_0.kit @@ -0,0 +1,61 @@ +[package] +description = "A platform for accelerating Embodied AI research" +title = "OmniGibson" +version = "3.9.3" + +keywords = ["experience", "app", "usd", "isaacsim"] # That makes it browsable in UI with "experience" filter + + +[dependencies] +"isaacsim.exp.base" = {} +"omni.flowusd" = {} +#"omni.kit.xr.profile.vr" = {} +"omni.physx.supportui" = {} +#"omni.isaac.physics_inspector" = {} + +[settings.app] +name = "OmniGibson" +version = "3.9.3" +settings.persistent = false # settings reset on each run with this app +window.title = "OmniGibson" +vulkan = true # Explicitly enable Vulkan (on by default on Linux, off by default on Windows) +window.iconPath = "${app}/OmniGibson_logo.png" +enableDeveloperWarnings = false # disable developer warnings to reduce log noise + +[settings.rtx] +# Isaac Sim's own extensions all launch with --/rtx/descriptorSets=360000 (71 occurrences across +# 66 extensions); OmniGibson runs a trimmed custom .kit experience and so inherits Kit's much +# smaller built-in default of 10000. That budget runs out once enough render products exist -- +# e.g. 8 envs x r1pro's 3 cameras -- surfacing as "Unable to allocate descriptor sets" / +# "Failed to allocate ParameterBlock resources" during scene setup. Measured cost of raising it +# on an RTX 5090: 0.06-0.16 GB of VRAM. +descriptorSets = 360000 + +[settings.crashreporter] +enabled = false # disable Kit crash reporter +gatherUserStory = false + +[settings.app.livestream] +proto = "ws" +allowResize = true +outDirectory = "${data}" + +[settings.app.exts.folders] +'++' = [ + "${app}", + "${app}/../exts", + "${app}/../extscache", + "${app}/../extsPhysics", + "${app}/../extsUser", + "${app}/../extsDeprecated", +] + +[settings.exts."omni.kit.registry.nucleus"] +registries = [ + { name = "kit/default", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/107/shared" }, + { name = "kit/sdk", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/sdk/${kit_version_short}/${kit_git_hash}" }, + { name = "kit/community", url = "https://dw290v42wisod.cloudfront.net/exts/kit/community" }, +] + +[settings.app.extensions] +pathStatCacheEnabled = false diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/omnigibson_5_1_0_vr.kit b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/omnigibson_5_1_0_vr.kit new file mode 100644 index 0000000000000000000000000000000000000000..4a9795dc2d4c293f510fa522e5d136e051725025 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/omnigibson_5_1_0_vr.kit @@ -0,0 +1,52 @@ +[package] +description = "A platform for accelerating Embodied AI research" +title = "OmniGibson" +version = "3.9.3" + +keywords = ["experience", "app", "usd", "isaacsim"] # That makes it browsable in UI with "experience" filter + + +[dependencies] +"isaacsim.exp.base" = {} +"omni.flowusd" = {} +"omni.kit.xr.profile.vr" = {} +"omni.physx.supportui" = {} +#"omni.isaac.physics_inspector" = {} + +[settings.app] +name = "OmniGibson" +version = "3.9.3" +settings.persistent = false # settings reset on each run with this app +window.title = "OmniGibson" +vulkan = true # Explicitly enable Vulkan (on by default on Linux, off by default on Windows) +window.iconPath = "${app}/OmniGibson_logo.png" +enableDeveloperWarnings = false # disable developer warnings to reduce log noise + +[settings.crashreporter] +enabled = false # disable Kit crash reporter +gatherUserStory = false + +[settings.app.livestream] +proto = "ws" +allowResize = true +outDirectory = "${data}" + +[settings.app.exts.folders] +'++' = [ + "${app}", + "${app}/../exts", + "${app}/../extscache", + "${app}/../extsPhysics", + "${app}/../extsUser", + "${app}/../extsDeprecated", +] + +[settings.exts."omni.kit.registry.nucleus"] +registries = [ + { name = "kit/default", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/107/shared" }, + { name = "kit/sdk", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/sdk/${kit_version_short}/${kit_git_hash}" }, + { name = "kit/community", url = "https://dw290v42wisod.cloudfront.net/exts/kit/community" }, +] + +[settings.app.extensions] +pathStatCacheEnabled = false diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbd272e18414ab7033aa339ed6d770400deab69b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/__init__.py @@ -0,0 +1,21 @@ +from omnigibson.prims.cloth_prim import ClothPrim +from omnigibson.prims.entity_prim import EntityPrim +from omnigibson.prims.geom_prim import GeomPrim +from omnigibson.prims.joint_prim import JointPrim +from omnigibson.prims.prim_base import BasePrim +from omnigibson.prims.rigid_prim import RigidPrim +from omnigibson.prims.rigid_dynamic_prim import RigidDynamicPrim +from omnigibson.prims.rigid_kinematic_prim import RigidKinematicPrim +from omnigibson.prims.xform_prim import XFormPrim + +__all__ = [ + "BasePrim", + "ClothPrim", + "EntityPrim", + "GeomPrim", + "JointPrim", + "RigidPrim", + "RigidDynamicPrim", + "RigidKinematicPrim", + "XFormPrim", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/cloth_prim.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/cloth_prim.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc4145e8f8d3eeffe135548b1f9100e3b16a65b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/cloth_prim.py @@ -0,0 +1,1045 @@ +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. +# + +import math +from functools import cached_property +import os +from pathlib import Path +import tempfile +from typing import Literal +import uuid + +from omnigibson.prims.xform_prim import XFormPrim +from omnigibson.utils.python_utils import multi_dim_linspace +import torch as th +from omnigibson.utils.ui_utils import create_module_logger +import trimesh + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros +from omnigibson.prims.geom_prim import GeomPrim +from omnigibson.utils.numpy_utils import vtarray_to_torch +from omnigibson.utils.usd_utils import ( + ensure_usd_api, + mesh_prim_to_trimesh_mesh, + sample_mesh_keypoints, + delete_or_deactivate_prim, +) + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +CLOTH_CONFIGURATIONS = ["default", "settled", "folded", "crumpled"] + +# Subsample cloth particle points to boost performance +m.ALLOW_MULTIPLE_CLOTH_MESH_COMPONENTS = True # TODO: Disable after new dataset release +m.N_CLOTH_KEYPOINTS = 1000 +m.FOLDING_INCREMENTS = 100 +m.CRUMPLING_INCREMENTS = 100 +m.KEYPOINT_COVERAGE_THRESHOLD = 0.75 +m.N_CLOTH_KEYFACES = 500 +m.MAX_CLOTH_PARTICLES = 20000 # Comes from a limitation in physx - do not increase +m.CLOTH_PARTICLE_CONTACT_OFFSET = 0.0075 +m.CLOTH_REMESHING_ERROR_THRESHOLD = 0.05 + + +class ClothPrim(GeomPrim): + """ + Provides high level functions to deal with a cloth prim and its attributes/ properties. + If there is an prim present at the path, it will use it. Otherwise, a new XForm prim at + the specified prim path will be created. + + Notes: if the prim does not already have a cloth api applied to it before it is loaded, + it will apply it. + + Args: + relative_prim_path (str): Scene-local prim path of the Prim to encapsulate or create. + name (str): Name for the object. Names need to be unique per scene. + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. Note that this is only needed if the prim does not already exist at + @relative_prim_path -- it will be ignored if it already exists. For this joint prim, the below values can be + specified: + + scale (None or float or 3-array): If specified, sets the scale for this object. A single number corresponds + to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. + mass (None or float): If specified, mass of this body in kg + """ + + def __init__( + self, + relative_prim_path, + name, + load_config=None, + ): + # Internal vars stored + self._centroid_idx = None + self._keypoint_idx = None + self._keyface_idx = None + + # Run super init + super().__init__( + relative_prim_path=relative_prim_path, + name=name, + load_config=load_config, + ) + + def _post_load(self): + # run super first + super()._post_load() + + self._mass_api = ensure_usd_api(self._prim, lazy.pxr.UsdPhysics.MassAPI) + + # Possibly set the mass / density + if "mass" in self._load_config and self._load_config["mass"] is not None: + self.mass = self._load_config["mass"] + + # Save the default point configuration + self.save_configuration("default", self.points) + + # Remesh the object if necessary + force_remesh = self._load_config.get("force_remesh", False) + should_remesh_because_of_scale = self._load_config.get("remesh", True) and not th.allclose( + self.scale, th.ones(3) + ) + # TODO: Remove the legacy check after the next dataset release + should_remesh_because_legacy = self._load_config.get( + "remesh", True + ) and self.get_available_configurations() == ["default"] + if should_remesh_because_of_scale or should_remesh_because_legacy or force_remesh: + # Remesh the object if necessary + log.warning( + f"Remeshing cloth {self.name}. This happens when cloth is loaded with non-unit scale or forced using the forced_remesh argument. It invalidates precached info for settled, folded, and crumpled configurations." + ) + self._remesh() + + # Set the mesh to use the desired configuration + points_configuration = self._load_config.get("default_point_configuration", "default") + self.reset_points_to_configuration(configuration=points_configuration) + + # Clothify this prim, which is assumed to be a mesh + self.cloth_system.clothify_mesh_prim(mesh_prim=self._prim) + + # Track generated particle count + positions = self.compute_particle_positions() + self._n_particles = len(positions) + + # Sample mesh keypoints / keyvalues and sanity check the AABB of these subsampled points vs. the actual points + success = False + for i in range(10): + self._keypoint_idx, self._keyface_idx = sample_mesh_keypoints( + mesh_prim=self._prim, + n_keypoints=m.N_CLOTH_KEYPOINTS, + n_keyfaces=m.N_CLOTH_KEYFACES, + seed=i, + ) + + keypoint_positions = positions[self._keypoint_idx] + keypoint_aabb = keypoint_positions.min(dim=0).values, keypoint_positions.max(dim=0).values + true_aabb = positions.min(dim=0).values, positions.max(dim=0).values + overlap_x = th.max( + th.min(true_aabb[1][0], keypoint_aabb[1][0]) - th.max(true_aabb[0][0], keypoint_aabb[0][0]), + th.tensor(0), + ) + overlap_y = th.max( + th.min(true_aabb[1][1], keypoint_aabb[1][1]) - th.max(true_aabb[0][1], keypoint_aabb[0][1]), + th.tensor(0), + ) + overlap_z = th.max( + th.min(true_aabb[1][2], keypoint_aabb[1][2]) - th.max(true_aabb[0][2], keypoint_aabb[0][2]), + th.tensor(0), + ) + overlap_vol = overlap_x * overlap_y * overlap_z + true_vol = th.prod(true_aabb[1] - true_aabb[0]) + if true_vol == 0.0 or (overlap_vol / true_vol > m.KEYPOINT_COVERAGE_THRESHOLD).item(): + success = True + break + assert success, f"Did not adequately subsample keypoints for cloth {self.name}!" + + # Compute centroid particle idx based on AABB + aabb_min, aabb_max = th.min(positions, dim=0).values, th.max(positions, dim=0).values + aabb_center = (aabb_min + aabb_max) / 2.0 + dists = th.norm(positions - aabb_center.reshape(1, 3), dim=-1) + self._centroid_idx = th.argmin(dists) + + def _remesh(self): + assert self.prim is not None, "Cannot remesh a non-existent prim!" + has_uv_mapping = self.prim.GetAttribute("primvars:st").Get() is not None + + # We will remesh in pymeshlab, but it doesn't allow programmatic construction of a mesh with texcoords so + # we convert our mesh into a trimesh mesh, then export it to a temp file, then load it into pymeshlab + scaled_world_transform = self.scaled_transform + # Convert to trimesh mesh (in world frame) + tm = mesh_prim_to_trimesh_mesh( + mesh_prim=self.prim, include_normals=True, include_texcoord=True, world_frame=True + ) + # Tmp file written to: {tmp_dir}/{tmp_fname}/{tmp_fname}.obj + tmp_name = str(uuid.uuid4()) + tmp_dir = os.path.join(tempfile.gettempdir(), tmp_name) + tmp_fpath = os.path.join(tmp_dir, f"{tmp_name}.obj") + Path(tmp_dir).mkdir(parents=True, exist_ok=True) + tm.export(tmp_fpath) + + # Start with the default particle distance + particle_distance = self.cloth_system.particle_contact_offset * 2 / 1.5 + + # Repetitively re-mesh at lower resolution until we have a mesh that has less than MAX_CLOTH_PARTICLES vertices + import pymeshlab # We import this here because it takes a few seconds to load. + + for _ in range(10): + ms = pymeshlab.MeshSet() + ms.load_new_mesh(tmp_fpath) + + # Re-mesh based on @particle_distance - distance chosen such that at rest particles should be just touching + # each other. The 1.5 magic number comes from the particle cloth demo from omni + # Note that this means that the particles will overlap with each other, since at dist = 2 * contact_offset + # the particles are just touching each other at rest + + avg_edge_percentage_mismatch = 1.0 + # Loop re-meshing until average edge percentage is within error threshold or we reach the max number of tries + for _ in range(5): + if avg_edge_percentage_mismatch <= m.CLOTH_REMESHING_ERROR_THRESHOLD: + break + + ms.meshing_isotropic_explicit_remeshing( + iterations=5, adaptive=True, targetlen=pymeshlab.AbsoluteValue(particle_distance) + ) + + # If the cloth has multiple pieces, only keep the largest one + ms.generate_splitting_by_connected_components(delete_source_mesh=True) + if len(ms) > 1: + assert m.ALLOW_MULTIPLE_CLOTH_MESH_COMPONENTS, "Cloth mesh has multiple components!" + + log.warning( + f"The cloth mesh has {len(ms)} disconnected components. To simplify, we only keep the mesh with largest face number." + ) + biggest_face_num = 0 + for split_mesh in ms: + face_num = split_mesh.face_number() + if face_num > biggest_face_num: + biggest_face_num = face_num + new_ms = pymeshlab.MeshSet() + for split_mesh in ms: + if split_mesh.face_number() == biggest_face_num: + new_ms.add_mesh(split_mesh) + ms = new_ms + + avg_edge_percentage_mismatch = abs( + 1.0 - particle_distance / ms.get_geometric_measures()["avg_edge_length"] + ) + else: + # Terminate anyways, but don't fail + log.warning("The generated cloth may not have evenly distributed particles.") + + # Check if we have too many vertices + cm = ms.current_mesh() + if cm.vertex_number() > m.MAX_CLOTH_PARTICLES: + # We have too many vertices, so we will re-mesh again + particle_distance *= math.sqrt(2) # halve the number of vertices + log.warning( + f"Too many vertices ({cm.vertex_number()})! Re-meshing with particle distance {particle_distance}..." + ) + else: + break + else: + raise ValueError(f"Could not remesh with less than MAX_CLOTH_PARTICLES ({m.MAX_CLOTH_PARTICLES}) vertices!") + + # Re-write data to @mesh_prim + new_faces = cm.face_matrix() + new_vertices = cm.vertex_matrix() + new_normals = cm.vertex_normal_matrix() + texcoord = cm.wedge_tex_coord_matrix() if has_uv_mapping else None + tm = trimesh.Trimesh( + vertices=new_vertices, + faces=new_faces, + vertex_normals=new_normals, + ) + # Apply the inverse of the world transform to get the mesh back into its local frame + tm.apply_transform(th.linalg.inv_ex(scaled_world_transform).inverse) + + # Update the mesh prim to store the new information. First update the non-configuration- + # dependent fields + with og.sim.editing_usd(): + face_vertex_counts = th.tensor([len(face) for face in tm.faces], dtype=int).cpu().numpy() + self.prim.GetAttribute("faceVertexCounts").Set(face_vertex_counts) + self.prim.GetAttribute("faceVertexIndices").Set(tm.faces.flatten()) + self.prim.GetAttribute("normals").Set(lazy.pxr.Vt.Vec3fArray.FromNumpy(tm.vertex_normals)) + if has_uv_mapping: + self.prim.GetAttribute("primvars:st").Set(lazy.pxr.Vt.Vec2fArray.FromNumpy(texcoord)) + + # Remove the properties for all configurations + for config in CLOTH_CONFIGURATIONS: + attr_name = f"points_{config}" + if self.prim.HasAttribute(attr_name): + self.prim.RemoveProperty(attr_name) + + # Then update the configuration-dependent fields + self.save_configuration("default", th.tensor(tm.vertices, dtype=th.float32)) + + # Then update the points to the default configuration + self.reset_points_to_configuration("default") + + def generate_settled_configuration(self): + """ + Generate a settled configuration for the cloth by running a few steps of simulation to let the cloth settle + """ + # Reset position first (moving to a position where the AABB is just on the floor) + self.reset_points_to_configuration("default") + self.set_position_orientation(position=th.zeros(3), orientation=th.tensor([0, 0, 0, 1.0])) + self.set_position_orientation( + position=th.tensor([0, 0, self.aabb_extent[2] / 2.0 - self.aabb_center[2]]), + orientation=th.tensor([0, 0, 0, 1.0]), + ) + + # Run a few steps of simulation to let the cloth settle + for _ in range(300): + og.sim.step() + + # Save the settled configuration + self.save_configuration("settled", self.points) + + def generate_folded_configuration(self): + # Settle and reset position first (moving to a position where the AABB is just on the floor) + self.reset_points_to_configuration("settled") + self.set_position_orientation(position=th.zeros(3), orientation=th.tensor([0, 0, 0, 1.0])) + self.set_position_orientation( + position=th.tensor([0, 0, self.aabb_extent[2] / 2.0 - self.aabb_center[2]]), + orientation=th.tensor([0, 0, 0, 1.0]), + ) + + for _ in range(100): + og.sim.step() + + # Fold - first stage. Take the bottom third of Y positions and fold them over towards + # the middle third. + pos = self.compute_particle_positions() + y_min = th.min(pos[:, 1]) + y_max = th.max(pos[:, 1]) + y_bottom_third = y_min + (y_max - y_min) / 3 + y_top_third = y_min + 2 * (y_max - y_min) / 3 + first_folding_indices = th.where(pos[:, 1] < y_bottom_third)[0] + first_folding_initial_pos = th.clone(pos[first_folding_indices]) + first_staying_pos = pos[pos[:, 1] >= y_bottom_third] + first_staying_z_height = th.max(first_staying_pos[:, 2]) - th.min(first_staying_pos[:, 2]) + first_folding_final_pos = th.clone(first_folding_initial_pos) + first_folding_final_pos[:, 1] = ( + 2 * y_bottom_third - first_folding_final_pos[:, 1] + ) # Mirror bottom to the above of y_mid_bottom + first_folding_final_pos[:, 2] += first_staying_z_height # Add a Z offset to keep particles from overlapping + for ctrl_pts in multi_dim_linspace(first_folding_initial_pos, first_folding_final_pos, m.FOLDING_INCREMENTS): + all_pts = th.clone(pos) + all_pts[first_folding_indices] = ctrl_pts + self.set_particle_positions(all_pts) + og.sim.step() + + # Fold - second stage. Take the top third of original Y positions and fold them over towards the + # middle too. + pos = self.compute_particle_positions() + second_folding_indices = th.where(pos[:, 1] > y_top_third)[0] + second_folding_initial_pos = th.clone(pos[second_folding_indices]) + second_staying_pos = pos[pos[:, 1] <= y_top_third] + second_staying_z_height = th.max(second_staying_pos[:, 2]) - th.min(second_staying_pos[:, 2]) + second_folding_final_pos = th.clone(second_folding_initial_pos) + second_folding_final_pos[:, 1] = ( + 2 * y_top_third - second_folding_final_pos[:, 1] + ) # Mirror top to the below of y_mid + second_folding_final_pos[:, 2] += second_staying_z_height # Add a Z offset to keep particles from overlapping + for ctrl_pts in multi_dim_linspace(second_folding_initial_pos, second_folding_final_pos, m.FOLDING_INCREMENTS): + all_pts = th.clone(pos) + all_pts[second_folding_indices] = ctrl_pts + self.set_particle_positions(all_pts) + og.sim.step() + + # Fold - third stage. Fold along the X axis, in half. + pos = self.compute_particle_positions() + x_min = th.min(pos[:, 0]) + x_max = th.max(pos[:, 0]) + x_mid = (x_min + x_max) / 2 + third_folding_indices = th.where(pos[:, 0] > x_mid)[0] + third_folding_initial_pos = th.clone(pos[third_folding_indices]) + third_staying_pos = pos[pos[:, 0] <= x_mid] + third_staying_z_height = th.max(third_staying_pos[:, 2]) - th.min(third_staying_pos[:, 2]) + third_folding_final_pos = th.clone(third_folding_initial_pos) + third_folding_final_pos[:, 0] = 2 * x_mid - third_folding_final_pos[:, 0] + third_folding_final_pos[:, 2] += third_staying_z_height # Add a Z offset to keep particles from overlapping + for ctrl_pts in multi_dim_linspace(third_folding_initial_pos, third_folding_final_pos, m.FOLDING_INCREMENTS): + all_pts = th.clone(pos) + all_pts[third_folding_indices] = ctrl_pts + self.set_particle_positions(all_pts) + og.sim.step() + + # Let things settle + for _ in range(100): + og.sim.step() + + # Save the folded configuration + self.save_configuration("folded", self.points) + + def generate_crumpled_configuration(self): + # Settle and reset position first (moving to a position where the AABB is just on the floor) + self.reset_points_to_configuration("settled") + self.set_position_orientation(position=th.zeros(3), orientation=th.tensor([0, 0, 0, 1.0])) + self.set_position_orientation( + position=th.tensor([0, 0, self.aabb_extent[2] / 2.0 - self.aabb_center[2]]), + orientation=th.tensor([0, 0, 0, 1.0]), + ) + for _ in range(100): + og.sim.step() + + # We just need to generate the side planes + box_half_extent = self.aabb_extent / 2 + plane_centers = ( + th.tensor( + [ + [1, 0, 1], + [0, 1, 1], + [-1, 0, 1], + [0, -1, 1], + ] + ) + * box_half_extent + ) + plane_prims = [] + plane_motions = [] + for i, pc in enumerate(plane_centers): + plane = lazy.isaacsim.core.api.objects.ground_plane.GroundPlane( + prim_path=f"/World/plane_{i}", + name=f"plane_{i}", + z_position=0, + size=box_half_extent[2].item(), + color=None, + visible=False, + ) + + plane_as_prim = XFormPrim( + relative_prim_path=f"/plane_{i}", + name=plane.name, + ) + plane_as_prim.load(None) + + # Build the plane orientation from the plane normal + horiz_dir = pc - th.tensor([0, 0, box_half_extent[2]]) + plane_z = -1 * horiz_dir / th.norm(horiz_dir) + plane_x = th.tensor([0, 0, 1], dtype=th.float32) + plane_y = th.cross(plane_z, plane_x) + plane_mat = th.stack([plane_x, plane_y, plane_z], dim=1) + plane_quat = T.mat2quat(plane_mat) + plane_as_prim.set_position_orientation(pc, plane_quat) + + plane_prims.append(plane_as_prim) + plane_motions.append(plane_z) + + # Calculate end positions for all walls + end_positions = [] + for i in range(4): + plane_prim = plane_prims[i] + position = plane_prim.get_position_orientation()[0] + end_positions.append(position + plane_motions[i] * box_half_extent) + + for step in range(m.CRUMPLING_INCREMENTS): + # Move all walls a small amount + for i in range(4): + plane_prim = plane_prims[i] + current_pos = multi_dim_linspace( + plane_prim.get_position_orientation()[0], end_positions[i], m.CRUMPLING_INCREMENTS + )[step] + plane_prim.set_position_orientation(position=current_pos) + + og.sim.step() + + # Check cloth height + cloth_positions = self.compute_particle_positions() + max_height = th.max(cloth_positions[:, 2]) + + # Get distance between facing walls (assuming walls 0-2 and 1-3 are facing pairs) + wall_dist_1 = th.linalg.norm( + plane_prims[0].get_position_orientation()[0] - plane_prims[2].get_position_orientation()[0] + ) + wall_dist_2 = th.linalg.norm( + plane_prims[1].get_position_orientation()[0] - plane_prims[3].get_position_orientation()[0] + ) + min_wall_dist = min(wall_dist_1, wall_dist_2) + + # Stop if cloth height exceeds wall distance + if max_height > min_wall_dist: + break + + # Let things settle + for _ in range(100): + og.sim.step() + + # Save the folded configuration + self.save_configuration("crumpled", self.points) + + # Remove the planes + for plane_prim in plane_prims: + delete_or_deactivate_prim(plane_prim.prim_path) + + def get_available_configurations(self): + """ + Returns: + list: List of available configurations for this cloth prim + """ + return [x for x in CLOTH_CONFIGURATIONS if self.prim.HasAttribute(f"points_{x}")] + + def save_configuration(self, configuration: Literal["default", "settled", "folded", "crumpled"], points: th.tensor): + """ + Save the current configuration of the cloth to a specific configuration + + Args: + configuration (Literal["default", "settled", "folded", "crumpled"]): Configuration to save the cloth to + """ + # Get the points arguments stored on the USD prim + assert configuration in CLOTH_CONFIGURATIONS, f"Invalid cloth configuration {configuration}!" + assert self.prim is not None, "Cannot save configuration for a non-existent prim!" + attr_name = f"points_{configuration}" + with og.sim.editing_usd(): + points_default_attrib = ( + self.prim.GetAttribute(attr_name) + if self.prim.HasAttribute(attr_name) + else self.prim.CreateAttribute(attr_name, lazy.pxr.Sdf.ValueTypeNames.Float3Array) + ) + points_default_attrib.Set(lazy.pxr.Vt.Vec3fArray.FromNumpy(points.cpu().numpy())) + + def reset_points_to_configuration(self, configuration: Literal["default", "settled", "folded", "crumpled"]): + """ + Reset the cloth to a specific configuration + + Args: + configuration (Literal["default", "settled", "folded", "crumpled"]): Configuration to reset the cloth to + """ + # Get the points arguments stored on the USD prim + assert ( + configuration in self.get_available_configurations() + ), f"Invalid or unavailable cloth configuration {configuration}!" + attr_name = f"points_{configuration}" + points = self.get_attribute(attr=attr_name) + self.set_attribute(attr="points", val=points) + + # Reset velocities to zero if velocities are present + if self.prim.HasAttribute("velocities"): + self.set_attribute(attr="velocities", val=lazy.pxr.Vt.Vec3fArray(th.zeros((len(points), 3)).tolist())) + + # For cloth, points should NOT be @cached_property because their local poses change over time + @property + def points(self): + """ + Returns: + th.tensor: Local poses of all points + """ + # If the geom is a mesh we can directly return its points. + mesh = self.prim + mesh_type = mesh.GetPrimTypeInfo().GetTypeName() + assert mesh_type == "Mesh", f"Expected a mesh prim, got {mesh_type} instead!" + return vtarray_to_torch(mesh.GetAttribute("points").Get(), dtype=th.float32) + + @property + def visual_aabb(self): + return self.aabb + + @property + def visual_aabb_extent(self): + return self.aabb_extent + + @property + def visual_aabb_center(self): + return self.aabb_center + + @property + def cloth_system(self): + return self.scene.get_system("cloth") + + @property + def n_particles(self): + """ + Returns: + int: Number of particles owned by this cloth prim + """ + return self._n_particles + + @cached_property + def kinematic_only(self): + """ + Returns: + bool: Whether this object is a kinematic-only object. For ClothPrim, always return False. + """ + return False + + def compute_particle_positions(self, idxs=None): + """ + Compute individual particle positions for this cloth prim + + Args: + idxs (n-array or None): If set, will only calculate the requested indexed particle state + + Returns: + th.tensor: (N, 3) numpy array, where each of the N particles' positions are expressed in (x,y,z) + cartesian coordinates relative to the world frame + """ + pos, ori = self.get_position_orientation() + ori = T.quat2mat(ori) + scale = self.scale + + # Don't copy to save compute, since we won't be returning a reference to the underlying object anyways + p_local = vtarray_to_torch(self.get_attribute(attr="points")) + p_local = p_local[idxs] if idxs is not None else p_local + p_world = (ori @ (p_local * scale).T).T + pos + + return p_world + + def set_particle_positions(self, positions, idxs=None): + """ + Sets individual particle positions for this cloth prim + + Args: + positions (n-array): (N, 3) numpy array, where each of the N particles' positions are expressed in (x,y,z) + cartesian coordinates relative to the world frame + idxs (n-array or None): If set, will only set the requested indexed particle state + """ + n_expected = self._n_particles if idxs is None else len(idxs) + assert ( + len(positions) == n_expected + ), f"Got mismatch in particle setting size: {len(positions)}, vs. number of expected particles {n_expected}!" + + translation, rotation = self.get_position_orientation() + rotation = T.quat2mat(rotation) + scale = self.scale + p_local = (rotation.T @ (positions - translation).T).T / scale + + # Fill the idxs if requested + if idxs is not None: + p_local_old = vtarray_to_torch(self.get_attribute(attr="points")) + p_local_old[idxs] = p_local + p_local = p_local_old + + self.set_attribute(attr="points", val=lazy.pxr.Vt.Vec3fArray(p_local.tolist())) + + @property + def keypoint_idx(self): + """ + Returns: + n-array: (N,) array specifying the keypoint particle IDs + """ + return self._keypoint_idx + + @property + def keyface_idx(self): + """ + Returns: + n-array: (N,) array specifying the keyface IDs + """ + return self._keyface_idx + + @property + def faces(self): + """ + Grabs particle indexes defining each of the faces for this cloth prim + + Returns: + th.tensor: (N, 3) numpy array, where each of the N faces are defined by the 3 particle indices + corresponding to that face's vertices + """ + return th.tensor(self.get_attribute("faceVertexIndices")).reshape(-1, 3) + + @property + def keyfaces(self): + """ + Grabs particle indexes defining each of the keyfaces for this cloth prim. + Total number of keyfaces is m.N_CLOTH_KEYFACES + + Returns: + th.tensor: (N, 3) numpy array, where each of the N keyfaces are defined by the 3 particle indices + corresponding to that face's vertices + """ + return self.faces[self._keyface_idx] + + @property + def keypoint_particle_positions(self): + """ + Grabs individual keypoint particle positions for this cloth prim. + Total number of keypoints is m.N_CLOTH_KEYPOINTS + + Returns: + th.tensor: (N, 3) numpy array, where each of the N keypoint particles' positions are expressed in (x,y,z) + cartesian coordinates relative to the world frame + """ + return self.compute_particle_positions(idxs=self._keypoint_idx) + + @property + def centroid_particle_position(self): + """ + Grabs the individual particle that was pre-computed to be the closest to the centroid of this cloth prim. + + Returns: + th.tensor: centroid particle's (x,y,z) cartesian coordinates relative to the world frame + """ + return self.compute_particle_positions(idxs=[self._centroid_idx]) + + @property + def particle_velocities(self): + """ + Grabs individual particle velocities for this cloth prim + + Returns: + th.tensor: (N, 3) numpy array, where each of the N particles' velocities are expressed in (x,y,z) + cartesian coordinates with respect to the world frame. + """ + # the velocities attribute is w.r.t the world frame already + return vtarray_to_torch(self.get_attribute(attr="velocities")) + + @particle_velocities.setter + def particle_velocities(self, vel): + """ + Set the particle velocities of this cloth + + Args: + th.tensor: (N, 3) numpy array, where each of the N particles' velocities are expressed in (x,y,z) + cartesian coordinates with respect to the world frame + """ + assert ( + vel.shape[0] == self._n_particles + ), f"Got mismatch in particle setting size: {vel.shape[0]}, vs. number of particles {self._n_particles}!" + + # the velocities attribute is w.r.t the world frame already + self.set_attribute(attr="velocities", val=lazy.pxr.Vt.Vec3fArray(vel.tolist())) + + def compute_face_normals(self, face_ids=None): + """ + Grabs individual face normals for this cloth prim + + Args: + face_ids (None or n-array): If specified, list of face IDs whose corresponding normals should be computed + If None, all faces will be used + + Returns: + th.tensor: (N, 3) numpy array, where each of the N faces' normals are expressed in (x,y,z) + cartesian coordinates with respect to the world frame. + """ + faces = self.faces if face_ids is None else self.faces[face_ids] + points = self.compute_particle_positions(idxs=faces.flatten()).reshape(-1, 3, 3) + return self.compute_face_normals_from_particle_positions(positions=points) + + def compute_face_normals_from_particle_positions(self, positions): + """ + Grabs individual face normals for this cloth prim + + Args: + positions (n-array): (N, 3, 3) array specifying the per-face particle positions + + Returns: + th.tensor: (N, 3) numpy array, where each of the N faces' normals are expressed in (x,y,z) + cartesian coordinates with respect to the world frame. + """ + # Shape [F, 3] + v1 = positions[:, 2, :] - positions[:, 0, :] + v2 = positions[:, 1, :] - positions[:, 0, :] + normals = th.linalg.cross(v1, v2) + return normals / th.norm(normals, dim=1).reshape(-1, 1) + + def get_contacts(self, keypoints_only=True): + """ + Get list of all current contacts with this cloth body + + Args: + keypoints_only (bool): If True, will only check contact with this cloth's keypoints + + Returns: + list of (contact_prim_path, position) pairs + """ + contacts = [] + + positions = self.keypoint_particle_positions if keypoints_only else self.compute_particle_positions() + for pos in positions: + + def report_hit(hit): + contacts.append((hit.rigid_body, pos)) + return True + + og.sim.psqi.overlap_sphere(self.cloth_system.particle_contact_offset, pos.tolist(), report_hit, False) + + return contacts + + def update_handles(self): + # no handles to update + pass + + @property + def volume(self): + mesh = mesh_prim_to_trimesh_mesh(self.prim, include_normals=False, include_texcoord=False, world_frame=True) + return mesh.volume if mesh.is_volume else mesh.convex_hull.volume + + @volume.setter + def volume(self, volume): + raise NotImplementedError("Cannot set volume directly for a link!") + + @property + def mass(self): + """ + Returns: + float: mass of the rigid body in kg. + """ + # We have to read the mass directly in the cloth prim + return self._mass_api.GetMassAttr().Get() + + @mass.setter + def mass(self, mass): + """ + Args: + mass (float): mass of the rigid body in kg. + """ + with og.sim.editing_usd(): + # We have to set the mass directly in the cloth prim + self._mass_api.GetMassAttr().Set(mass) + + @property + def density(self): + raise NotImplementedError("Cannot get density for ClothPrim") + + @density.setter + def density(self, density): + raise NotImplementedError("Cannot set density for ClothPrim") + + @property + def body_name(self): + """ + Returns: + str: Name of this body + """ + return self.prim_path.split("/")[-1] + + def get_linear_velocity(self): + """ + Returns: + th.tensor: current average linear velocity of the particles of the cloth prim. Shape (3,). + """ + return vtarray_to_torch(self._prim.GetAttribute("velocities").Get()).mean(dim=0) + + def get_angular_velocity(self): + """ + Returns: + th.tensor: zero vector as a placeholder because a cloth prim doesn't have an angular velocity. Shape (3,). + """ + return th.zeros(3) + + def set_linear_velocity(self, velocity): + """ + Sets the linear velocity of all the particles of the cloth prim. + + Args: + velocity (th.tensor): linear velocity to set all the particles of the cloth prim to. Shape (3,). + """ + vel = self.particle_velocities + vel[:] = velocity + self.particle_velocities = vel + + def set_angular_velocity(self, velocity): + """ + Simply returns because a cloth prim doesn't have an angular velocity + + Args: + velocity (th.tensor): linear velocity to set all the particles of the cloth prim to. Shape (3,). + """ + return + + def wake(self): + # TODO (eric): Just a pass through for now. + return + + @property + def bend_stiffness(self): + """ + Returns: + float: spring bend stiffness of the particle system + """ + return self.get_attribute("physxAutoParticleCloth:springBendStiffness") + + @bend_stiffness.setter + def bend_stiffness(self, bend_stiffness): + """ + Args: + bend_stiffness (float): spring bend stiffness of the particle system + """ + self.set_attribute("physxAutoParticleCloth:springBendStiffness", bend_stiffness) + + @property + def damping(self): + """ + Returns: + float: spring damping of the particle system + """ + return self.get_attribute("physxAutoParticleCloth:springDamping") + + @damping.setter + def damping(self, damping): + """ + Args: + damping (float): spring damping of the particle system + """ + self.set_attribute("physxAutoParticleCloth:springDamping", damping) + + @property + def shear_stiffness(self): + """ + Returns: + float: spring shear_stiffness of the particle system + """ + return self.get_attribute("physxAutoParticleCloth:springShearStiffness") + + @shear_stiffness.setter + def shear_stiffness(self, shear_stiffness): + """ + Args: + shear_stiffness (float): spring shear_stiffness of the particle system + """ + self.set_attribute("physxAutoParticleCloth:springShearStiffness", shear_stiffness) + + @property + def stretch_stiffness(self): + """ + Returns: + float: spring stretch_stiffness of the particle system + """ + return self.get_attribute("physxAutoParticleCloth:springStretchStiffness") + + @stretch_stiffness.setter + def stretch_stiffness(self, stretch_stiffness): + """ + Args: + stretch_stiffness (float): spring stretch_stiffness of the particle system + """ + self.set_attribute("physxAutoParticleCloth:springStretchStiffness", stretch_stiffness) + + @property + def particle_group(self): + """ + Returns: + int: Particle group this instancer belongs to + """ + return self.get_attribute(attr="physxParticle:particleGroup") + + @particle_group.setter + def particle_group(self, group): + """ + Args: + group (int): Particle group this instancer belongs to + """ + self.set_attribute(attr="physxParticle:particleGroup", val=group) + + def _dump_state(self): + # Run super first + state = super()._dump_state() + state["particle_group"] = self.particle_group + state["n_particles"] = self.n_particles + state["particle_positions"] = self.compute_particle_positions() + state["particle_velocities"] = self.particle_velocities + return state + + def _load_state(self, state): + # Run super first + super()._load_state(state=state) + # Sanity check the identification number and particle group + assert self.particle_group == state["particle_group"], ( + f"Got mismatch in particle group for this cloth " + f"when loading state! Should be: {self.particle_group}, got: {state['particle_group']}." + ) + + # Set values appropriately + self._n_particles = state["n_particles"] + # Make sure the loaded state is a numpy array, it could have been accidentally casted into a list during + # JSON-serialization + self.particle_velocities = ( + th.tensor(state["particle_velocities"]) + if not isinstance(state["particle_velocities"], th.Tensor) + else state["particle_velocities"] + ) + self.set_particle_positions(positions=state["particle_positions"]) + + def serialize(self, state): + # Run super first + state_flat = super().serialize(state=state) + + return th.cat( + [ + state_flat, + th.tensor([state["particle_group"], state["n_particles"]], dtype=th.float32), + state["particle_positions"].reshape(-1), + state["particle_velocities"].reshape(-1), + ] + ) + + def deserialize(self, state): + # Run super first + state_dict, idx = super().deserialize(state=state) + + particle_group = int(state[idx]) + n_particles = int(state[idx + 1]) + + # Sanity check the identification number + assert self.particle_group == particle_group, ( + f"Got mismatch in particle group for this particle " + f"instancer when deserializing state! Should be: {self.particle_group}, got: {particle_group}." + ) + + # De-compress from 1D array + state_dict["particle_group"] = particle_group + state_dict["n_particles"] = n_particles + + # Process remaining keys and reshape automatically + keys = ("particle_positions", "particle_velocities") + sizes = ((n_particles, 3), (n_particles, 3)) + + idx += 2 + for key, size in zip(keys, sizes): + length = math.prod(size) + state_dict[key] = state[idx : idx + length].reshape(size) + idx += length + + return state_dict, idx + + def reset(self): + """ + Reset the points to their default positions in the local frame, and also zeroes out velocities + """ + if self.initialized: + points_configuration = self._load_config.get("default_point_configuration", "default") + self.reset_points_to_configuration(points_configuration) + + @cached_property + def is_meta_link(self): + return False + + @cached_property + def meta_link_type(self): + raise ValueError(f"{self.name} is not a meta link") + + @cached_property + def meta_link_id(self): + """The meta link id of this link, if the link is a meta link. + + The meta link ID is a semantic identifier for the meta link within the meta link type. It is + used when an object has multiple meta links of the same type. It can be just a numerical index, + or for some objects, it will be a string that can be matched to other meta links. For example, + a stove might have toggle buttons named "left" and "right", and heat sources named "left" and + "right". The meta link ID can be used to match the toggle button to the heat source. + """ + raise ValueError(f"{self.name} is not a meta link") + + @cached_property + def meta_link_sub_id(self): + """The integer meta link sub id of this link, if the link is a meta link. + + The meta link sub ID identifies this link as one of the parts of a meta link. For example, an + attachment meta link's ID will be the attachment pair name, and each attachment point that + works with that pair will show up as a separate link with a unique sub ID. + """ + raise ValueError(f"{self.name} is not a meta link") diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/entity_prim.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/entity_prim.py new file mode 100644 index 0000000000000000000000000000000000000000..58d0134b0bdc87306b4605d6220988b683e7ec01 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/entity_prim.py @@ -0,0 +1,1615 @@ +from functools import cached_property +import math +from typing import Literal + +import networkx as nx +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros, gm +from omnigibson.prims.cloth_prim import ClothPrim +from omnigibson.prims.joint_prim import JointPrim +from omnigibson.prims.rigid_dynamic_prim import RigidDynamicPrim +from omnigibson.prims.rigid_kinematic_prim import RigidKinematicPrim +from omnigibson.prims.xform_prim import XFormPrim +from omnigibson.utils.constants import JointAxis, JointType, PrimType +from omnigibson.utils.usd_utils import ( + RigidBodyViewAPI, + absolute_prim_path_to_scene_relative, + count_joints, + find_joint_prims, +) + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# Default sleep threshold for all objects -- see https://docs.omniverse.nvidia.com/extensions/latest/ext_physics/simulation-control/physics-settings.html?highlight=sleep#sleeping +# Mass-normalized kinetic energy threshold below which an actor may go to sleep +m.DEFAULT_SLEEP_THRESHOLD = 0.00005 + + +class EntityPrim(XFormPrim): + """ + Provides high level functions to deal with an articulation prim and its attributes/ properties. Note that this + type of prim cannot be created from scratch, and assumes there is already a pre-existing prim tree that should + be converted into an articulation! + + Args: + relative_prim_path (str): Scene-local prim path of the Prim to encapsulate or create. + name (str): Name for the object. Names need to be unique per scene. + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. Note that by default, this assumes an articulation already exists (i.e.: + load() will raise NotImplementedError)! Subclasses must implement _load() for this prim to be able to be + dynamically loaded after this class is created. + + visual_only (None or bool): If specified, whether this prim should include collisions or not. + Default is True. + """ + + def __init__( + self, + relative_prim_path, + name, + load_config=None, + ): + # Other values that will be filled in at runtime + self._root_link_name = None # Name of the root link + self._n_dof = None + self._links = None + self._joints = None + self._materials = None + self._visual_only = None + self._articulation_tree = None + self._articulation_view = None + + # This needs to be initialized to be used for _load() of PrimitiveObject + self._prim_type = ( + load_config["prim_type"] if load_config is not None and "prim_type" in load_config else PrimType.RIGID + ) + assert self._prim_type in iter(PrimType), f"Unknown prim type {self._prim_type}!" + + # Run super init + super().__init__( + relative_prim_path=relative_prim_path, + name=name, + load_config=load_config, + ) + + def _initialize(self): + # Run super method + super()._initialize() + + if not self.kinematic_only: + # Set the default sleep threshold + self.sleep_threshold = m.DEFAULT_SLEEP_THRESHOLD + + # Initialize all the links + for link in self._links.values(): + link.initialize() + + # Update joint information + self.update_joints() + + # Re-apply entity scale after physics initialization. Isaac Sim's articulation warmup can reset + # xformOp:scale on physics bodies with no collision geometry (e.g. meta links), so we enforce + # consistency here by writing the scale back from the root link's current state. + self.scale = self.scale + + def _load(self): + # By default, this prim cannot be instantiated from scratch! + raise NotImplementedError("By default, an entity prim cannot be created from scratch.") + + def _post_load(self): + # If this is a cloth, delete the root link and replace it with the single nested mesh + if self._prim_type == PrimType.CLOTH: + # Verify only a single link and a single mesh exists + old_link_prim = None + cloth_mesh_prim = None + for prim in self._prim.GetChildren(): + if prim.GetPrimTypeInfo().GetTypeName() == "Xform": + assert old_link_prim is None, "Found multiple XForm links for a Cloth entity prim! Expected: 1" + old_link_prim = prim + for child in prim.GetChildren(): + if child.GetPrimTypeInfo().GetTypeName() == "Mesh" and not child.HasAPI( + lazy.pxr.UsdPhysics.CollisionAPI + ): + assert cloth_mesh_prim is None, "Found multiple meshes for a Cloth entity prim! Expected: 1" + cloth_mesh_prim = child + + # Move mesh prim one level up via copy, then delete the original link + # NOTE: We copy because we cannot directly move the prim because it is ancestral + # NOTE: We use this specific delete method because alternative methods (eg: "delete_prim") fail beacuse + # the prim is ancestral. Note that because it is non-destructive, the original link prim path is still + # tracked by omni, so we have to utilize a new unique prim path for the copied cloth mesh + # See omni.kit.context_menu module for reference + new_path = f"{self.prim_path}/{old_link_prim.GetName()}_cloth" + with og.sim.editing_usd(): + lazy.omni.kit.commands.execute("CopyPrim", path_from=cloth_mesh_prim.GetPath(), path_to=new_path) + lazy.omni.kit.commands.execute("DeletePrims", paths=[old_link_prim.GetPath()], destructive=False) + + self.update_links() + self._compute_articulation_tree() + + # Prepare the articulation view. + if self.articulated: + # Import now to avoid too-eager load of Omni classes due to inheritance + from omnigibson.utils.deprecated_utils import ArticulationView + + with og.sim.editing_usd(): + self._articulation_view = ArticulationView(f"{self.prim_path}/{self.root_link_name}") + + # Set visual only flag + # This automatically handles setting collisions / gravity appropriately per-link + self.visual_only = ( + self._load_config["visual_only"] + if "visual_only" in self._load_config and self._load_config["visual_only"] is not None + else False + ) or gm.VISUAL_ONLY + + if self._prim_type == PrimType.CLOTH: + assert not self._visual_only, "Cloth cannot be visual-only." + assert len(self._links) == 1, f"Cloth entity prim can only have one link; got: {len(self._links)}" + + # Globally disable any requested collision links + for link_name in self.disabled_collision_link_names: + self._links[link_name].disable_collisions() + + # Disable any requested collision pairs + for a_name, b_name in self.disabled_collision_pairs: + link_a, link_b = self._links[a_name], self._links[b_name] + link_a.add_filtered_collision_pair(prim=link_b) + + # Run super + super()._post_load() + + assert th.all(self.original_scale == 1.0), "scale should be [1, 1, 1] at the EntityPrim (object) level" + + # Cache material information + materials = set() + material_paths = set() + for link in self._links.values(): + xforms = [link] + list(link.visual_meshes.values()) if self.prim_type == PrimType.RIGID else [link] + for xform in xforms: + if xform.has_material(): + mat_path = xform.material.prim_path + if mat_path not in material_paths: + materials.add(xform.material) + material_paths.add(mat_path) + + self._materials = materials + + def remove(self): + # First remove all joints + if self._joints is not None: + for joint in self._joints.values(): + joint.remove() + + # Then links + if self._links is not None: + for link in self._links.values(): + link.remove() + + # Finally, remove this prim + super().remove() + + def update_links(self): + """ + Helper function to refresh owned joints. Useful for synchronizing internal data if + additional bodies are added manually + """ + # We iterate over all children of this object's prim, + # and grab any that are presumed to be rigid bodies (i.e.: other Xforms) + # Keep track of all the links we will create. We can't create that just yet because we need to find + # the base link first. + links_to_create = {} + for prim in self._prim.GetChildren(): + link_name = prim.GetName() + prim_type_name = prim.GetPrimTypeInfo().GetTypeName() + + # Identify links based on prim type + if self._prim_type == PrimType.RIGID and prim_type_name == "Xform": + # For rigid body objects, process Xforms as potential rigid links + # Mark this as a link to create (we'll determine exact class later) + links_to_create[link_name] = (PrimType.RIGID, prim) + + elif self._prim_type == PrimType.CLOTH and prim_type_name == "Mesh": + # For cloth objects, process Meshes as cloth links + links_to_create[link_name] = (PrimType.CLOTH, prim) + + # Find the children of all joints so we can determine which link is the root. + # Joints can live anywhere under self._prim (recent Isaac Sim exports place them in a flat + # /joints scope rather than under their body0 link), so traverse the full subtree. + joint_children = set() + for joint_prim in find_joint_prims(self._prim): + relationships = {r.GetName(): r for r in joint_prim.GetRelationships()} + # Only record if this is NOT a fixed link tying us to the world (i.e.: no target for body0) + if len(relationships["physics:body0"].GetTargets()) > 0: + joint_children.add(relationships["physics:body1"].GetTargets()[0].pathString.split("/")[-1]) + + # Infer the correct root link name -- this corresponds to whatever link does not have any joint existing + # in the children joints + valid_root_links = list(set(links_to_create.keys()) - joint_children) + + assert len(valid_root_links) == 1, ( + f"Exactly one single root link should have been found for {self.name}, " + f"but found none/multiple instead: {valid_root_links}" + ) + self._root_link_name = valid_root_links[0] if len(valid_root_links) == 1 else "base_link" + + # Now actually create the links with appropriate classes + self._links = dict() + for link_name, (link_type, prim) in links_to_create.items(): + # Determine link configuration + is_root_link = link_name == self._root_link_name + # Fixed child links of kinematic-only objects are not kinematic-only, to avoid the USD error: + # PhysicsUSD: CreateJoint - cannot create a joint between static bodies, joint prim: ... + is_kinematic = self._load_config.get("kinematic_only", False) if is_root_link else False + + link_load_config = { + "kinematic_only": is_kinematic, + "belongs_to_articulation": self._articulation_view is not None and not is_root_link, + "remesh": self._load_config.get("remesh", True), + "xform_props_pre_loaded": self._load_config.get("xform_props_pre_loaded", False), + "scale": self._load_config.get("scale", None), + "visual_only": self._load_config.get("visual_only", False), + } + + # Determine the correct class based on link type and kinematic property + if link_type == PrimType.RIGID: + link_cls = RigidKinematicPrim if is_kinematic else RigidDynamicPrim + else: # link_type == PrimType.CLOTH + link_cls = ClothPrim + + # Create and load the link + self._links[link_name] = link_cls( + relative_prim_path=absolute_prim_path_to_scene_relative(self.scene, prim.GetPrimPath().__str__()), + name=f"{self._name}:{link_name}", + load_config=link_load_config, + ) + self._links[link_name].load(self.scene) + + def update_joints(self): + """ + Helper function to refresh owned joints. Useful for synchronizing internal data if + additional bodies are added manually + """ + # Initialize joints dictionary + self._joints = dict() + self.update_handles() + + # Handle case separately based on whether we are actually articulated or not + if self._articulation_view and not self.kinematic_only: + self._n_dof = self._articulation_view.num_dof + + # Additionally grab DOF info if we have non-fixed joints + if self._n_dof > 0: + for i in range(self._articulation_view._metadata.joint_count): + # Only add the joint if it's not fixed (i.e.: it has DOFs > 0) + if self._articulation_view._metadata.joint_dof_counts[i] > 0: + joint_name = self._articulation_view._metadata.joint_names[i] + joint_dof_offset = self._articulation_view._metadata.joint_dof_offsets[i] + joint_path = self._articulation_view._dof_paths[0][joint_dof_offset] + joint = JointPrim( + relative_prim_path=absolute_prim_path_to_scene_relative(self.scene, joint_path), + name=f"{self._name}:joint_{joint_name}", + load_config={"driven": self.is_driven}, + articulation_view=self._articulation_view, + ) + joint.load(self.scene) + joint.initialize() + self._joints[joint_name] = joint + else: + # TODO: May need to extend to clusters of rigid bodies, that aren't exactly joined + # We assume this object contains a single rigid body + self._n_dof = 0 + + assert self.n_joints == len(self._joints), ( + f"Number of joints inferred from prim tree ({self.n_joints}) does not match number of joints " + f"found in the articulation view ({len(self._joints)})!" + ) + + self._update_joint_limits() + + def _update_joint_limits(self): + """ + Helper function to update internal joint limits for prismatic joints based on the object's scale + """ + # If the scale is [1, 1, 1], we can skip this step + if th.allclose(self.scale, th.ones(3)): + return + + prismatic_joints = { + j_name: j for j_name, j in self._joints.items() if j.joint_type == JointType.JOINT_PRISMATIC + } + + # If there are no prismatic joints, we can skip this step + if len(prismatic_joints) == 0: + return + + uniform_scale = th.allclose(self.scale, self.scale[0]) + + for joint_name, joint in prismatic_joints.items(): + if uniform_scale: + scale_along_axis = self.scale[0] + else: + assert ( + not self.initialized + ), "Cannot update joint limits for a non-uniformly scaled object when already initialized." + for link in self.links.values(): + if joint.body0 == link.prim_path: + # Find the parent link frame orientation in the object frame. Note that we + # are OK getting this from XFormPrim since we actually want it relative to + # the object frame, notwithstanding the physics. + _, link_local_orn = XFormPrim.get_position_orientation(link, frame="parent") + + # Find the joint frame orientation in the parent link frame + joint_local_orn = th.tensor( + lazy.isaacsim.core.utils.rotations.gf_quat_to_np_array( + joint.get_attribute("physics:localRot0") + )[[1, 2, 3, 0]], + dtype=th.float32, + ) + + # Compute the joint frame orientation in the object frame + joint_orn = T.quat_multiply(quaternion1=joint_local_orn, quaternion0=link_local_orn) + + # assert T.check_quat_right_angle(joint_orn), \ + # f"Objects that are NOT uniformly scaled requires all joints to have orientations that " \ + # f"are factors of 90 degrees! Got orn: {joint_orn} for object {self.name}" + + # Find the joint axis unit vector (e.g. [1, 0, 0] for "X", [0, 1, 0] for "Y", etc.) + axis_in_joint_frame = th.zeros(3) + axis_in_joint_frame[JointAxis.index(joint.axis)] = 1.0 + + # Compute the joint axis unit vector in the object frame + axis_in_obj_frame = T.quat2mat(joint_orn) @ axis_in_joint_frame + + # Find the correct scale along the joint axis direction + scale_along_axis = self.scale[th.argmax(th.abs(axis_in_obj_frame))] + + joint.lower_limit = joint.lower_limit * scale_along_axis + joint.upper_limit = joint.upper_limit * scale_along_axis + + @property + def is_driven(self) -> bool: + """ + Returns: + bool: Whether this object is actively controlled/driven or not + """ + return False + + @property + def prim_type(self): + """ + Returns: + str: Type of this entity prim, one of omnigibson.utils.constants.PrimType + """ + return self._prim_type + + @property + def articulated(self): + """ + Returns: + bool: Whether this prim is articulated or not + """ + return self.articulation_root_path is not None + + @property + def root_link_name(self): + """ + Returns: + str: Name of this entity's root link + """ + return self._root_link_name + + @property + def root_link(self): + """ + Returns: + RigidPrim or ClothPrim: Root link of this object prim + """ + return self._links[self.root_link_name] + + @property + def root_prim(self): + """ + Returns: + UsdPrim: Root prim object associated with the root link of this object prim + """ + # The root prim belongs to the link with name root_link_name + return self._links[self.root_link_name].prim + + @property + def n_dof(self): + """ + Returns: + int: number of DoFs of the object + """ + return self._n_dof + + @property + def n_joints(self): + """ + Returns: + int: Number of joints owned by this articulation + """ + if self.initialized: + num = len(self._joints) + else: + num, _, _ = count_joints(self.prim) + return num + + @cached_property + def n_fixed_joints(self): + """ + Returns: + int: Number of fixed joints owned by this articulation + """ + # If the articulation view is available, use it. + if self._articulation_view and self._articulation_view._metadata: + return sum(1 for joint_dof in self._articulation_view._metadata.joint_dof_counts if joint_dof == 0) + + _, num, _ = count_joints(self.prim) + return num + + @property + def n_links(self): + """ + Returns: + int: Number of links owned by this articulation + """ + return len(list(self._links.keys())) + + @property + def joints(self): + """ + Returns: + dict: Dictionary mapping joint names (str) to joint prims (JointPrim) owned by this articulation + """ + return self._joints + + @property + def links(self): + """ + Returns: + dict: Dictionary mapping link names (str) to link prims (RigidPrim) owned by this articulation + """ + return self._links + + @cached_property + def link_prim_paths(self): + return [link.prim_path for link in self._links.values()] + + @cached_property + def has_attachment_points(self): + """ + Returns: + bool: Whether this object has any attachment points + """ + _, _, has_attachment = count_joints(self.prim) + return has_attachment + + def _compute_articulation_tree(self): + """ + Get a graph of the articulation tree, where nodes are link names and edges + correspond to joint names, where the joint name is accessible on the `joint_name` + data field of the edge, and the joint type on the `joint_type` field. + """ + G = nx.DiGraph() + rename_later = {} + + # Add the links + for link_name, link in self.links.items(): + prim_path = link.prim_path + G.add_node(prim_path) + rename_later[prim_path] = link_name + + # Add the joints + children = list(self.prim.GetChildren()) + while children: + child_prim = children.pop() + children.extend(child_prim.GetChildren()) + prim_type = child_prim.GetPrimTypeInfo().GetTypeName() + if "Joint" in prim_type: + # Get body 0 + body0_targets = child_prim.GetRelationship("physics:body0").GetTargets() + if not body0_targets: + continue + body0 = str(body0_targets[0]) + + # Get body 1 + body1_targets = child_prim.GetRelationship("physics:body1").GetTargets() + if not body1_targets: + continue + body1 = str(body1_targets[0]) + + # Assert both bodies in links + if body0 not in G.nodes or body1 not in G.nodes: + continue + + # Add the joint + joint_type = JointType.get_type(prim_type.split("Physics")[-1]) + G.add_edge(body0, body1, joint_name=child_prim.GetName(), joint_type=joint_type) + + # Relabel nodes to use link name instead of prim path + nx.relabel_nodes(G, rename_later, copy=False) + + # Assert all nodes have in-degree of 1 except root + in_degrees = {node: G.in_degree(node) for node in G.nodes} + assert in_degrees[self.root_link_name] == 0, "Root link should have in-degree of 0!" + assert all( + [in_degrees[node] == 1 for node in G.nodes if node != self.root_link_name] + ), "All non-root links should have in-degree of 1!" + + self._articulation_tree = G + + @property + def articulation_tree(self): + return self._articulation_tree + + def get_fixed_link_names_in_subtree(self, subtree_root_link_name=None): + """ + Find all the links that are fixed to a given search subtree root link. + + If the subtree root link name is not provided, the object's root link will be used. + """ + if subtree_root_link_name is None: + subtree_root_link_name = self.root_link_name + is_edge_fixed = lambda f, t: self.articulation_tree[f][t]["joint_type"] == JointType.JOINT_FIXED + only_fixed_joints = nx.subgraph_view(self.articulation_tree, filter_edge=is_edge_fixed) + return nx.descendants(only_fixed_joints, subtree_root_link_name) | {subtree_root_link_name} + + @property + def materials(self): + """ + Loop through each link and their visual meshes to gather all the materials that belong to this object + + Returns: + set of MaterialPrim: a set of MaterialPrim that belongs to this object + """ + return self._materials + + @property + def visual_only(self): + """ + Returns: + bool: Whether this link is a visual-only link (i.e.: no gravity or collisions applied) + """ + return self._visual_only + + @visual_only.setter + def visual_only(self, val): + """ + Sets the visual only state of this link + + Args: + val (bool): Whether this link should be a visual-only link (i.e.: no gravity or collisions applied) + """ + # Iterate over all owned links and set their respective visual-only properties accordingly + for link in self._links.values(): + link.visual_only = val + + # Also set the internal value + self._visual_only = val + + def enable_gravity(self) -> None: + """ + Enables gravity for this entity + """ + for link in self._links.values(): + if isinstance(link, RigidDynamicPrim): + link.enable_gravity() + + def disable_gravity(self) -> None: + """ + Disables gravity for this entity + """ + for link in self._links.values(): + if isinstance(link, RigidDynamicPrim): + link.disable_gravity() + + def reset(self): + """ + Resets this entity to some default, pre-defined state + """ + # Make sure simulation is playing, otherwise, we cannot reset because physx requires active running + # simulation in order to set joints + assert og.sim.is_playing(), "Simulator must be playing in order to reset controllable object's joints!" + + # If this is a cloth, reset the particle positions + if self.prim_type == PrimType.CLOTH: + self.root_link.reset() + + # Otherwise, set all joints to have 0 position and 0 velocity if this object has joints + elif self.n_joints > 0: + self.set_joint_positions(positions=th.zeros(self.n_dof), drive=False) + self.set_joint_velocities(velocities=th.zeros(self.n_dof), drive=False) + + def set_joint_positions(self, positions, indices=None, normalized=False, drive=False): + """ + Set the joint positions (both actual value and target values) in simulation. Note: only works if the simulator + is actively running! + + Args: + positions (th.tensor): positions to set. This should be n-DOF length if all joints are being set, + or k-length (k < n) if specific indices are being set. In this case, the length of @positions must + be the same length as @indices! + indices (None or k-array): If specified, should be k (k < n) length array of specific DOF positions to set. + Default is None, which assumes that all joints are being set. + normalized (bool): Whether the inputted joint positions should be interpreted as normalized values. Default + is False + drive (bool): Whether the positions being set are values that should be driven naturally by this entity's + motors or manual values to immediately set. Default is False, corresponding to an instantaneous + setting of the positions + """ + # Run sanity checks -- make sure that we are articulated + assert self.n_joints > 0, "Tried to call method not intended for entity prim with no joints!" + + # Possibly de-normalize the inputs + if normalized: + positions = self._denormalize_positions(positions=positions, indices=indices) + + # Set the DOF states + if drive: + with og.sim.editing_usd(): + self._articulation_view.set_joint_position_targets(positions, joint_indices=indices) + else: + with og.sim.editing_usd(): + self._articulation_view.set_joint_positions(positions, joint_indices=indices) + og.sim.sync_physx_to_fabric() + + # Tensorized state caches (AABB / Touching / Adjacency / ...) read from pose tensors + # that are now one frame behind. Flag them as stale so the next state read forces a + # refresh via the lazy-refresh gate in TensorizedState._get_value. + from omnigibson.object_states.tensorized_state import TensorizedState + + TensorizedState.caches_dirty = True + + def set_joint_velocities(self, velocities, indices=None, normalized=False, drive=False): + """ + Set the joint velocities (both actual value and target values) in simulation. Note: only works if the simulator + is actively running! + + Args: + velocities (th.tensor): velocities to set. This should be n-DOF length if all joints are being set, + or k-length (k < n) if specific indices are being set. In this case, the length of @velocities must + be the same length as @indices! + indices (None or k-array): If specified, should be k (k < n) length array of specific DOF velocities to set. + Default is None, which assumes that all joints are being set. + normalized (bool): Whether the inputted joint velocities should be interpreted as normalized values. Default + is False + drive (bool): Whether the velocities being set are values that should be driven naturally by this entity's + motors or manual values to immediately set. Default is False, corresponding to an instantaneous + setting of the velocities + """ + # Run sanity checks -- make sure we are articulated + assert self.n_joints > 0, "Tried to call method not intended for entity prim with no joints!" + + # Possibly de-normalize the inputs + if normalized: + velocities = self._denormalize_velocities(velocities=velocities, indices=indices) + + # Set the DOF states + if drive: + with og.sim.editing_usd(): + self._articulation_view.set_joint_velocity_targets(velocities, joint_indices=indices) + else: + with og.sim.editing_usd(): + self._articulation_view.set_joint_velocities(velocities, joint_indices=indices) + + def set_joint_efforts(self, efforts, indices=None, normalized=False): + """ + Set the joint efforts (both actual value and target values) in simulation. Note: only works if the simulator + is actively running! + + Args: + efforts (th.tensor): efforts to set. This should be n-DOF length if all joints are being set, + or k-length (k < n) if specific indices are being set. In this case, the length of @efforts must + be the same length as @indices! + indices (None or k-array): If specified, should be k (k < n) length array of specific DOF efforts to set. + Default is None, which assumes that all joints are being set. + normalized (bool): Whether the inputted joint efforts should be interpreted as normalized values. Default + is False + """ + # Run sanity checks -- make sure we are articulated + assert self.n_joints > 0, "Tried to call method not intended for entity prim with no joints!" + + # Possibly de-normalize the inputs + if normalized: + efforts = self._denormalize_efforts(efforts=efforts, indices=indices) + + # Set the DOF states + with og.sim.editing_usd(): + self._articulation_view.set_joint_efforts(efforts, joint_indices=indices) + + def _normalize_positions(self, positions, indices=None): + """ + Normalizes raw joint positions @positions + + Args: + positions (n- or k-array): n-DOF raw positions to normalize, or k (k < n) specific positions to normalize. + In the latter case, @indices should be specified + indices (None or k-array): If specified, should be k (k < n) DOF indices corresponding to the specific + positions to normalize. Default is None, which assumes the positions correspond to all DOF being + normalized. + + Returns: + n- or k-array: normalized positions in range [-1, 1] for the specified DOFs + """ + low, high = self.joint_lower_limits, self.joint_upper_limits + mean = (low + high) / 2.0 + magnitude = (high - low) / 2.0 + return (positions - mean) / magnitude if indices is None else (positions - mean[indices]) / magnitude[indices] + + def _denormalize_positions(self, positions, indices=None): + """ + De-normalizes joint positions @positions + + Args: + positions (n- or k-array): n-DOF normalized positions or k (k < n) specific positions in range [-1, 1] + to de-normalize. In the latter case, @indices should be specified + indices (None or k-array): If specified, should be k (k < n) DOF indices corresponding to the specific + positions to de-normalize. Default is None, which assumes the positions correspond to all DOF being + de-normalized. + + Returns: + n- or k-array: de-normalized positions for the specified DOFs + """ + low, high = self.joint_lower_limits, self.joint_upper_limits + mean = (low + high) / 2.0 + magnitude = (high - low) / 2.0 + return positions * magnitude + mean if indices is None else positions * magnitude[indices] + mean[indices] + + def _normalize_velocities(self, velocities, indices=None): + """ + Normalizes raw joint velocities @velocities + + Args: + velocities (n- or k-array): n-DOF raw velocities to normalize, or k (k < n) specific velocities to normalize. + In the latter case, @indices should be specified + indices (None or k-array): If specified, should be k (k < n) DOF indices corresponding to the specific + velocities to normalize. Default is None, which assumes the velocities correspond to all DOF being + normalized. + + Returns: + n- or k-array: normalized velocities in range [-1, 1] for the specified DOFs + """ + return ( + velocities / self.max_joint_velocities + if indices is None + else velocities / self.max_joint_velocities[indices] + ) + + def _denormalize_velocities(self, velocities, indices=None): + """ + De-normalizes joint velocities @velocities + + Args: + velocities (n- or k-array): n-DOF normalized velocities or k (k < n) specific velocities in range [-1, 1] + to de-normalize. In the latter case, @indices should be specified + indices (None or k-array): If specified, should be k (k < n) DOF indices corresponding to the specific + velocities to de-normalize. Default is None, which assumes the velocities correspond to all DOF being + de-normalized. + + Returns: + n- or k-array: de-normalized velocities for the specified DOFs + """ + return ( + velocities * self.max_joint_velocities + if indices is None + else velocities * self.max_joint_velocities[indices] + ) + + def _normalize_efforts(self, efforts, indices=None): + """ + Normalizes raw joint efforts @efforts + + Args: + efforts (n- or k-array): n-DOF raw efforts to normalize, or k (k < n) specific efforts to normalize. + In the latter case, @indices should be specified + indices (None or k-array): If specified, should be k (k < n) DOF indices corresponding to the specific + efforts to normalize. Default is None, which assumes the efforts correspond to all DOF being + normalized. + + Returns: + n- or k-array: normalized efforts in range [-1, 1] for the specified DOFs + """ + return efforts / self.max_joint_efforts if indices is None else efforts / self.max_joint_efforts[indices] + + def _denormalize_efforts(self, efforts, indices=None): + """ + De-normalizes joint efforts @efforts + + Args: + efforts (n- or k-array): n-DOF normalized efforts or k (k < n) specific efforts in range [-1, 1] + to de-normalize. In the latter case, @indices should be specified + indices (None or k-array): If specified, should be k (k < n) DOF indices corresponding to the specific + efforts to de-normalize. Default is None, which assumes the efforts correspond to all DOF being + de-normalized. + + Returns: + n- or k-array: de-normalized efforts for the specified DOFs + """ + return efforts * self.max_joint_efforts if indices is None else efforts * self.max_joint_efforts[indices] + + def update_handles(self): + """ + Updates all internal handles for this prim, in case they change since initialization + """ + assert og.sim.is_playing(), "Simulator must be playing if updating handles!" + + # Reinitialize the articulation view + if self._articulation_view is not None: + self._articulation_view.initialize(og.sim.physics_sim_view) + + # Update all links and joints as well + for link in self._links.values(): + if not link.initialized: + link.initialize() + link.update_handles() + + for joint in self._joints.values(): + if not joint.initialized: + joint.initialize() + joint.update_handles() + + def get_joint_positions(self, normalized=False): + """ + Grabs this entity's joint positions + + Args: + normalized (bool): Whether returned values should be normalized to range [-1, 1] based on limits or not. + + Returns: + n-array: n-DOF length array of positions + """ + # Run sanity checks -- make sure we are articulated + assert self.n_joints > 0, "Tried to call method not intended for entity prim with no joints!" + + joint_positions = self._articulation_view.get_joint_positions().view(self.n_dof) + + # Possibly normalize values when returning + return self._normalize_positions(positions=joint_positions) if normalized else joint_positions + + def get_joint_dof_types(self): + """ + Per-DOF type mask for this articulation's joints. + + Collapses the underlying ``omni.physics.tensors.DofType`` enum returned by the + articulation view into a boolean tensor, so it can be used directly with ``th.where`` + to pick per-DOF-type values (e.g. degree-vs-meter thresholds). + + Returns: + th.Tensor: (n_dof,) boolean tensor. True for rotational DOFs, False for translational. + """ + return th.as_tensor( + [x == lazy.omni.physics.tensors.DofType.Rotation for x in self._articulation_view.get_dof_types()] + ) + + def get_joint_velocities(self, normalized=False): + """ + Grabs this entity's joint velocities + + Args: + normalized (bool): Whether returned values should be normalized to range [-1, 1] based on limits or not. + + Returns: + n-array: n-DOF length array of velocities + """ + # Run sanity checks -- make sure we are articulated + assert self.n_joints > 0, "Tried to call method not intended for entity prim with no joints!" + + joint_velocities = self._articulation_view.get_joint_velocities().view(self.n_dof) + + # Possibly normalize values when returning + return self._normalize_velocities(velocities=joint_velocities) if normalized else joint_velocities + + def get_joint_efforts(self, normalized=False): + """ + Grabs this entity's "measured" joint efforts + + Args: + normalized (bool): Whether returned values should be normalized to range [-1, 1] based on limits or not. + + Returns: + n-array: n-DOF length array of efforts + """ + # Run sanity checks -- make sure we are articulated + assert self.n_joints > 0, "Tried to call method not intended for entity prim with no joints!" + + joint_efforts = self._articulation_view.get_measured_joint_efforts().view(self.n_dof) + + # Possibly normalize values when returning + return self._normalize_efforts(efforts=joint_efforts) if normalized else joint_efforts + + def get_joint_position_targets(self, normalized=False): + """ + Grabs this entity's joint position targets + + Args: + normalized (bool): Whether returned values should be normalized to range [-1, 1] based on limits or not. + + Returns: + n-array: n-DOF length array of position targets + """ + # Run sanity checks -- make sure we are articulated + assert self.n_joints > 0, "Tried to call method not intended for entity prim with no joints!" + + joint_positions = self._articulation_view.get_joint_position_targets().view(self.n_dof) + + # Possibly normalize values when returning + return self._normalize_positions(positions=joint_positions) if normalized else joint_positions + + def get_joint_velocity_targets(self, normalized=False): + """ + Grabs this entity's joint velocity targets + + Args: + normalized (bool): Whether returned values should be normalized to range [-1, 1] based on limits or not. + + Returns: + n-array: n-DOF length array of velocity targets + """ + # Run sanity checks -- make sure we are articulated + assert self.n_joints > 0, "Tried to call method not intended for entity prim with no joints!" + + joint_velocities = self._articulation_view.get_joint_velocity_targets().view(self.n_dof) + + # Possibly normalize values when returning + return self._normalize_velocities(velocities=joint_velocities) if normalized else joint_velocities + + def set_linear_velocity(self, velocity: th.Tensor): + """ + Sets the linear velocity of the root prim in stage. + + Args: + velocity (th.tensor): linear velocity to set the rigid prim to, in the world frame. Shape (3,). + """ + self.root_link.set_linear_velocity(velocity) + + def get_linear_velocity(self): + """ + Gets the linear velocity of the root prim in stage. + + Returns: + velocity (th.tensor): linear velocity to set the rigid prim to, in the world frame. Shape (3,). + """ + return self.root_link.get_linear_velocity() + + def set_angular_velocity(self, velocity): + """ + Sets the angular velocity of the root prim in stage. + + Args: + velocity (th.tensor): angular velocity to set the rigid prim to, in the world frame. Shape (3,). + """ + self.root_link.set_angular_velocity(velocity) + + def get_angular_velocity(self): + """Gets the angular velocity of the root prim in stage. + + Returns: + velocity (th.tensor): angular velocity to set the rigid prim to, in the world frame. Shape (3,). + """ + return self.root_link.get_angular_velocity() + + def get_relative_linear_velocity(self): + """ + Returns: + 3-array: (x,y,z) Linear velocity of root link in its own frame + """ + return T.quat2mat(self.get_position_orientation()[1]).T @ self.get_linear_velocity() + + def get_relative_angular_velocity(self): + """ + Returns: + 3-array: (ax,ay,az) angular velocity of root link in its own frame + """ + return T.quat2mat(self.get_position_orientation()[1]).T @ self.get_angular_velocity() + + def set_position_orientation(self, position=None, orientation=None, frame: Literal["world", "scene"] = "world"): + """ + Set the position and orientation of entry prim object. + + Args: + position (None or 3-array): The position to set the object to. If None, the position is not changed. + orientation (None or 4-array): The orientation to set the object to. If None, the orientation is not changed. + frame (Literal): The frame in which to set the position and orientation. Defaults to world. + scene frame sets position relative to the scene. + """ + assert frame in ["world", "scene"], f"Invalid frame '{frame}'. Must be 'world', or 'scene'." + + # If the simulation is stopped, we can just move the entity prim directly. This is appropriate because + # it's the only numerically stable way to move the root link and all of the child links together. + # It does create a dual path for places where the transform might end up being set, but is a necessary evil. + # In this case, we also want to make sure that the root link does not have a relative pose to the entity prim. + if og.sim.is_stopped(): + this_position, this_orientation = XFormPrim.get_position_orientation(self, frame=frame) + root_link_position, root_link_orientation = self.root_link.get_position_orientation(frame=frame) + assert th.allclose( + this_position, root_link_position, atol=1e-2 + ), "Position mismatch between entity prim and root link" + assert th.allclose( + this_orientation, root_link_orientation, atol=1e-2 + ), "Orientation mismatch between entity prim and root link" + XFormPrim.set_position_orientation(self, position=position, orientation=orientation, frame=frame) + if self.kinematic_only: + RigidBodyViewAPI.invalidate_kinematic( + [link for link in self._links.values() if isinstance(link, RigidKinematicPrim)] + ) + else: + # Otherwise, we simply move the object in PhysX and force it to update Fabric, too. + if self.articulated: + # If no position or no orientation are given, get the current position and orientation of the object + if position is None or orientation is None: + current_position, current_orientation = self.get_position_orientation(frame=frame) + position = current_position if position is None else position + orientation = current_orientation if orientation is None else orientation + + # Convert to th.Tensor if necessary + position = th.as_tensor(position, dtype=th.float32) + orientation = th.as_tensor(orientation, dtype=th.float32) + + # Assert validity of the orientation + assert math.isclose( + th.norm(orientation).item(), 1, abs_tol=1e-3 + ), f"{self.prim_path} desired orientation {orientation} is not a unit quaternion." + + # Convert to from scene-relative to world if necessary + if frame == "scene": + assert ( + self.scene is not None + ), "cannot set position and orientation relative to scene without a scene" + position, orientation = self.scene.convert_scene_relative_pose_to_world(position, orientation) + + # Check that the articulation view is valid and can write directly to PhysX + assert ( + self._articulation_view.is_physics_handle_valid() + ), "Unexpected: articulation view is not valid while simulation is playing." + self._articulation_view.set_world_poses( + positions=position[None, :], orientations=orientation[None, [3, 0, 1, 2]] + ) + og.sim.sync_physx_to_fabric() + + # Tensorized state caches (AABB / Touching / Adjacency / ...) read from pose tensors + # that are now one frame behind. Flag them as stale so the next state read forces a + # refresh via the lazy-refresh gate in TensorizedState._get_value. + from omnigibson.object_states.tensorized_state import TensorizedState + + TensorizedState.caches_dirty = True + else: + self.root_link.set_position_orientation(position=position, orientation=orientation, frame=frame) + + def get_position_orientation(self, frame: Literal["world", "scene"] = "world", clone=True): + """ + Gets prim's pose with respect to the specified frame. + + Args: + frame (Literal): frame to get the pose with respect to. Default to world. + scene frame get position relative to the scene. + clone (bool): Whether to clone the underlying tensor buffer or not + + Returns: + 2-tuple: + - th.Tensor: (x,y,z) position in the specified frame + - th.Tensor: (x,y,z,w) quaternion orientation in the specified frame + """ + assert frame in ["world", "scene"], f"Invalid frame '{frame}'. Must be 'world' or 'scene'." + + return self.root_link.get_position_orientation(frame=frame, clone=clone) + + # TODO: Is the omni joint damping (used for driving motors) same as dissipative joint damping (what we had in pb)? + @property + def joint_damping(self): + """ + Returns: + n-array: joint damping values for this prim + """ + return th.cat([joint.damping for joint in self._joints.values()]) + + # TODO: These are cached, but they are not updated when the joint limit is changed + @cached_property + def joint_lower_limits(self): + """ + Returns: + n-array: minimum values for this robot's joints. If joint does not have a range, returns -1000 + for that joint + """ + return th.tensor([joint.lower_limit for joint in self._joints.values()]) + + # TODO: These are cached, but they are not updated when the joint limit is changed + @cached_property + def joint_upper_limits(self): + """ + Returns: + n-array: maximum values for this robot's joints. If joint does not have a range, returns 1000 + for that joint + """ + return th.tensor([joint.upper_limit for joint in self._joints.values()]) + + @property + def joint_range(self): + """ + Returns: + n-array: joint range values for this robot's joints + """ + return self.joint_upper_limits - self.joint_lower_limits + + @property + def max_joint_velocities(self): + """ + Returns: + n-array: maximum velocities for this robot's joints + """ + return th.tensor([joint.max_velocity for joint in self._joints.values()]) + + @property + def max_joint_efforts(self): + """ + Returns: + n-array: maximum efforts for this robot's joints + """ + return th.tensor([joint.max_effort for joint in self._joints.values()]) + + @property + def joint_position_limits(self): + """ + Returns: + 2-tuple: + - n-array: min joint position limits, where each is an n-DOF length array + - n-array: max joint position limits, where each is an n-DOF length array + """ + return self.joint_lower_limits, self.joint_upper_limits + + @property + def joint_velocity_limits(self): + """ + Returns: + 2-tuple: + - n-array: min joint velocity limits, where each is an n-DOF length array + - n-array: max joint velocity limits, where each is an n-DOF length array + """ + return -self.max_joint_velocities, self.max_joint_velocities + + @property + def joint_effort_limits(self): + """ + Returns: + 2-tuple: + - n-array: min joint effort limits, where each is an n-DOF length array + - n-array: max joint effort limits, where each is an n-DOF length array + """ + return -self.max_joint_efforts, self.max_joint_efforts + + @property + def joint_at_limits(self): + """ + Returns: + n-array: n-DOF length array specifying whether joint is at its limit, + with 1.0 --> at limit, otherwise 0.0 + """ + return 1.0 * (th.abs(self.get_joint_positions(normalized=True)) > 0.99) + + @property + def joint_has_limits(self): + """ + Returns: + n-array: n-DOF length array specifying whether joint has a limit or not + """ + return th.tensor([j.has_limit for j in self._joints.values()]) + + @property + def disabled_collision_link_names(self): + """ + Returns: + list of str: List of link names for this entity whose collisions should be globally disabled + """ + return [] + + @property + def disabled_collision_pairs(self): + """ + Returns: + list of (str, str): List of rigid body collision pairs to disable within this object prim. + Default is an empty list (no pairs) + """ + return [] + + @property + def scale(self): + # For the EntityPrim (object) level, @self.scale represents the scale with respect to the original scale of + # the link (RigidPrim or ClothPrim), which might not be uniform ([1, 1, 1]) itself. + return self.root_link.scale / self.root_link.original_scale + + @scale.setter + def scale(self, scale): + # For the EntityPrim (object) level, @self.scale represents the scale with respect to the original scale of + # the link (RigidPrim or ClothPrim), which might not be uniform ([1, 1, 1]) itself. + # We iterate over all rigid bodies owned by this object prim and set their individual scales + # We do this because omniverse cannot scale orientation of an articulated prim, so we get mesh mismatches as + # they rotate in the world. + for link in self._links.values(): + link.scale = scale * link.original_scale + + @property + def solver_position_iteration_count(self): + """ + Returns: + int: How many position iterations to take per physics step by the physx solver + """ + return ( + lazy.isaacsim.core.utils.prims.get_prim_property( + self.articulation_root_path, "physxArticulation:solverPositionIterationCount" + ) + if self.articulated + else self.root_link.solver_position_iteration_count + ) + + @solver_position_iteration_count.setter + def solver_position_iteration_count(self, count): + """ + Sets how many position iterations to take per physics step by the physx solver + + Args: + count (int): How many position iterations to take per physics step by the physx solver + """ + if self.articulated: + with og.sim.editing_usd(): + lazy.isaacsim.core.utils.prims.set_prim_property( + self.articulation_root_path, "physxArticulation:solverPositionIterationCount", count + ) + else: + for link in self._links.values(): + link.solver_position_iteration_count = count + + @property + def solver_velocity_iteration_count(self): + """ + Returns: + int: How many velocity iterations to take per physics step by the physx solver + """ + return ( + lazy.isaacsim.core.utils.prims.get_prim_property( + self.articulation_root_path, "physxArticulation:solverVelocityIterationCount" + ) + if self.articulated + else self.root_link.solver_velocity_iteration_count + ) + + @solver_velocity_iteration_count.setter + def solver_velocity_iteration_count(self, count): + """ + Sets how many velocity iterations to take per physics step by the physx solver + + Args: + count (int): How many velocity iterations to take per physics step by the physx solver + """ + if self.articulated: + with og.sim.editing_usd(): + lazy.isaacsim.core.utils.prims.set_prim_property( + self.articulation_root_path, "physxArticulation:solverVelocityIterationCount", count + ) + else: + for link in self._links.values(): + link.solver_velocity_iteration_count = count + + @property + def stabilization_threshold(self): + """ + Returns: + float: threshold for stabilizing this articulation + """ + return ( + lazy.isaacsim.core.utils.prims.get_prim_property( + self.articulation_root_path, "physxArticulation:stabilizationThreshold" + ) + if self.articulated + else self.root_link.stabilization_threshold + ) + + @stabilization_threshold.setter + def stabilization_threshold(self, threshold): + """ + Sets threshold for stabilizing this articulation + + Args: + threshold (float): Stabilization threshold + """ + if self.articulated: + lazy.isaacsim.core.utils.prims.set_prim_property( + self.articulation_root_path, "physxArticulation:stabilizationThreshold", threshold + ) + else: + for link in self._links.values(): + link.stabilization_threshold = threshold + + @property + def is_asleep(self): + """ + Returns: + bool: whether this entity is asleep or not + """ + # If we're kinematic only, immediately return False since it doesn't follow the sleep / wake paradigm + if self.kinematic_only or self.prim_type != PrimType.RIGID: + return False + else: + return ( + og.sim.psi.is_sleeping( + og.sim.stage_id, lazy.pxr.PhysicsSchemaTools.sdfPathToInt(self.articulation_root_path) + ) + if self.articulated + else self.root_link.is_asleep + ) + + @property + def sleep_threshold(self): + """ + Returns: + float: threshold for sleeping this articulation + """ + return ( + lazy.isaacsim.core.utils.prims.get_prim_property( + self.articulation_root_path, "physxArticulation:sleepThreshold" + ) + if self.articulated + else self.root_link.sleep_threshold + ) + + @sleep_threshold.setter + def sleep_threshold(self, threshold): + """ + Sets threshold for sleeping this articulation + + Args: + threshold (float): Sleeping threshold + """ + if self.articulated: + with og.sim.editing_usd(): + lazy.isaacsim.core.utils.prims.set_prim_property( + self.articulation_root_path, "physxArticulation:sleepThreshold", threshold + ) + else: + for link in self._links.values(): + link.sleep_threshold = threshold + + @property + def self_collisions(self): + """ + Returns: + bool: Whether self-collisions are enabled for this prim or not + """ + return lazy.isaacsim.core.utils.prims.get_prim_property( + self.articulation_root_path, "physxArticulation:enabledSelfCollisions" + ) + + @cached_property + def kinematic_only(self): + """ + Returns: + bool: Whether this object is a kinematic-only object (otherwise, it is a rigid body). A kinematic-only + object is not subject to simulator dynamics, and remains fixed unless the user explicitly sets the + body's pose / velocities. See https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_physics/rigid-bodies.html?highlight=rigid%20body%20enabled#kinematic-rigid-bodies + for more information + """ + return isinstance(self.root_link, RigidKinematicPrim) + + @property + def collision_points_world(self): + """Get all collision points in world coordinates. + + For cloth objects, returns particle positions. + For rigid objects, returns collision boundary points from all links. + """ + if self._prim_type == PrimType.CLOTH: + return self.root_link.compute_particle_positions() + else: + points_world = [link.collision_boundary_points_world for link in self._links.values()] + return th.cat([p for p in points_world if p is not None], dim=0) + + @property + def aabb(self): + """Compute axis-aligned bounding box from collision mesh points.""" + points = self.collision_points_world + if self._prim_type == PrimType.CLOTH: + particle_contact_offset = self.root_link.cloth_system.particle_contact_offset + aabb_lo = th.min(points, dim=0).values - particle_contact_offset + aabb_hi = th.max(points, dim=0).values + particle_contact_offset + else: + aabb_lo = th.min(points, dim=0).values + aabb_hi = th.max(points, dim=0).values + return aabb_lo, aabb_hi + + @property + def aabb_extent(self): + """ + Get this xform's actual bounding box extent + + Returns: + 3-array: (x,y,z) bounding box + """ + min_corner, max_corner = self.aabb + return max_corner - min_corner + + @property + def aabb_center(self): + """ + Get this xform's actual bounding box center + + Returns: + 3-array: (x,y,z) bounding box center + """ + min_corner, max_corner = self.aabb + return (max_corner + min_corner) / 2.0 + + def get_coriolis_and_centrifugal_forces(self, clone=True): + """ + Args: + clone (bool): Whether to clone the underlying tensor buffer or not + + Returns: + n-array: (N,) shaped per-DOF coriolis and centrifugal forces experienced by the entity, if articulated + """ + assert self.articulated, "Cannot get coriolis and centrifugal forces for non-articulated entity!" + return self._articulation_view.get_coriolis_and_centrifugal_forces(clone=clone).view(self.n_dof) + + def get_generalized_gravity_forces(self, clone=True): + """ + Args: + clone (bool): Whether to clone the underlying tensor buffer or not + + Returns: + n-array: (N, N) shaped per-DOF gravity forces, if articulated + """ + assert self.articulated, "Cannot get generalized gravity forces for non-articulated entity!" + return self._articulation_view.get_generalized_gravity_forces(clone=clone).view(self.n_dof) + + def get_mass_matrix(self, clone=True): + """ + Args: + clone (bool): Whether to clone the underlying tensor buffer or not + + Returns: + n-array: (N, N) shaped per-DOF mass matrix, if articulated + """ + assert self.articulated, "Cannot get mass matrix for non-articulated entity!" + return self._articulation_view.get_mass_matrices(clone=clone).view(self.n_dof, self.n_dof) + + def get_jacobian(self, clone=True): + """ + Args: + clone (bool): Whether to clone the underlying tensor buffer or not + + Returns: + n-array: (N_links - 1 [+ 1], 6, N_dof [+ 6]) shaped per-link jacobian, if articulated. Note that the first + dimension is +1 and the final dimension is +6 if the entity does not have a fixed base + (i.e.: there is an additional "floating" joint tying the robot to the world frame) + """ + assert self.articulated, "Cannot get jacobian for non-articulated entity!" + return self._articulation_view.get_jacobians(clone=clone).squeeze(dim=0) + + def get_relative_jacobian(self, clone=True): + """ + Args: + clone (bool): Whether to clone the underlying tensor buffer or not + + Returns: + n-array: (N_links - 1 [+ 1], 6, N_dof [+ 6]) shaped per-link relative jacobian, if articulated (expressed in + this entity's base frame). Note that the first dimension is +1 and the final dimension is +6 if the + entity does not have a fixed base (i.e.: there is an additional "floating" joint tying the robot to + the world frame) + """ + jac = self.get_jacobian(clone=clone) + ori_t = T.quat2mat(self.get_position_orientation()[1]).T + tf = th.zeros((1, 6, 6), dtype=th.float32) + tf[:, :3, :3] = ori_t + tf[:, 3:, 3:] = ori_t + return tf @ jac + + def wake(self): + """ + Enable physics for this articulation + """ + if self.articulated: + prim_id = lazy.pxr.PhysicsSchemaTools.sdfPathToInt(self.articulation_root_path) + og.sim.psi.wake_up(og.sim.stage_id, prim_id) + else: + for link in self._links.values(): + if isinstance(link, RigidDynamicPrim): + link.wake() + + def sleep(self): + """ + Disable physics for this articulation + """ + if self.articulated: + prim_id = lazy.pxr.PhysicsSchemaTools.sdfPathToInt(self.articulation_root_path) + og.sim.psi.put_to_sleep(og.sim.stage_id, prim_id) + else: + for link in self._links.values(): + if isinstance(link, RigidDynamicPrim): + link.sleep() + + def keep_still(self): + """ + Zero out all velocities for this prim + """ + if self.kinematic_only: + return + self.set_linear_velocity(velocity=th.zeros(3)) + self.set_angular_velocity(velocity=th.zeros(3)) + if self.initialized: + for joint in self._joints.values(): + joint.keep_still() + # Make sure object is awake + self.wake() + + def _dump_state(self): + # We don't call super, instead, this state is simply the root link state and all joint states + state = dict(is_asleep=self.is_asleep, root_link=self.root_link._dump_state()) + if self.n_joints > 0: + state["joint_pos"] = self.get_joint_positions() + state["joint_vel"] = self.get_joint_velocities() + + # We do NOT save joint pos / vel targets because this is only relevant for motorized joints (e.g.: robots). + # Such control (a) only relies on the joint state, and not joint targets, when computing control, and + # (b) these targets will be immediately overwritten as soon as the next physics step occurs. + # In other words, when loading the sim state, we will load the joint pos / vel and the controller state (e.g. goal) + # and then when we take a physics step, right before the physics step actually occurs, @og.sim._on_physics_step() + # will be called, which computes the control based on the just-loaded joint state and overwrites the joint targets with the new control. + # So because these values are not used and require additional memory / compute, we do not save targets + + return state + + def _load_state(self, state): + recorded_sleep = state.get("is_asleep", False) + if recorded_sleep: + pos, orn = state["root_link"]["pos"], state["root_link"]["ori"] + cur_pos, cur_orn = self.get_position_orientation() + same_pos = bool(th.allclose(cur_pos, pos, rtol=0.0, atol=1e-7)) + same_orn = bool((1.0 - th.abs(th.dot(cur_orn, orn))) < 1e-7) + + # Load base link state and joint states + self.root_link._load_state(state=state["root_link"]) + + # TODO: Remove this backwards-compatible part once we re-sample scenes + if "joints" in state: + for joint_name, joint_state in state["joints"].items(): + self._joints[joint_name]._load_state(state=joint_state) + + elif self.n_joints > 0: + self.set_joint_positions(state["joint_pos"]) + self.set_joint_velocities(state["joint_vel"]) + + if recorded_sleep and same_pos and same_orn: + self.sleep() + else: + self.wake() + + def serialize(self, state): + # We serialize by first flattening the root link state and then iterating over all joints and + # adding them to the a flattened array + state_flat = [th.tensor([state["is_asleep"]], dtype=th.int), self.root_link.serialize(state=state["root_link"])] + if self.n_joints > 0: + state_flat += [ + state["joint_pos"], + state["joint_vel"], + ] + + return th.cat(state_flat) + + def deserialize(self, state): + # Get sleep state first + is_asleep = bool(state[0].item()) + # We deserialize by first de-flattening the root link state and then iterating over all joints and + # sequentially grabbing from the flattened state array, incrementing along the way + root_link_state, idx = self.root_link.deserialize(state=state[1:]) + idx += 1 # Incremented 1 from is_asleep value + state_dict = dict(is_asleep=is_asleep, root_link=root_link_state) + if self.n_joints > 0: + for jnt_state in ("pos", "vel"): + state_dict[f"joint_{jnt_state}"] = state[idx : idx + self.n_joints] + idx += self.n_joints + + return state_dict, idx diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/geom_prim.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/geom_prim.py new file mode 100644 index 0000000000000000000000000000000000000000..271a3f6212af6551d8df1fa8978c705056206bfb --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/geom_prim.py @@ -0,0 +1,336 @@ +from functools import cached_property + +from scipy.spatial import Delaunay +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.utils.geometry_utils import ( + check_points_in_cone, + check_points_in_cube, + check_points_in_cylinder, + check_points_in_sphere, +) +import omnigibson.utils.transform_utils as T +from omnigibson.prims.xform_prim import XFormPrim +from omnigibson.utils.numpy_utils import vtarray_to_torch +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import mesh_prim_shape_to_trimesh_mesh + +# Create module logger +log = create_module_logger(module_name=__name__) + + +class GeomPrim(XFormPrim): + """ + Provides high level functions to deal with a geom prim and its attributes / properties. + If there is an geom prim present at the path, it will use it. By default, a geom prim cannot be directly + created from scratch. + + Geom prims are not inherently distinguished as collision or visual. Instead, at the link level + (RigidPrim), they are tracked separately based on whether they appear with a CollisionAPI or as a child of one. + Collision-related APIs and methods live on RigidPrim and operate on all collision meshes of a link. + + Args: + relative_prim_path (str): Scene-local prim path of the Prim to encapsulate or create. + name (str): Name for the object. Names need to be unique per scene. + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. For this mesh prim, the below values can be specified: + """ + + def __init__( + self, + relative_prim_path, + name, + load_config=None, + ): + self._mesh_type = None + self._applied_physics_material = None + + # Run super method + super().__init__( + relative_prim_path=relative_prim_path, + name=name, + load_config=load_config, + ) + + def _load(self): + # This should not be called, because this prim cannot be instantiated from scratch! + raise NotImplementedError("By default, a geom prim cannot be created from scratch.") + + def _post_load(self): + super()._post_load() + self._mesh_type = self.prim.GetTypeName() + + @property + def purpose(self): + """ + Returns: + str: the purpose used for this geom, one of {"default", "render", "proxy", "guide"} + """ + return self.get_attribute("purpose") + + @purpose.setter + def purpose(self, purpose): + """ + Sets the purpose of this geom + + Args: + purpose (str): the purpose used for this geom, one of {"default", "render", "proxy", "guide"} + """ + self.set_attribute("purpose", purpose) + + @property + def color(self): + """ + Returns: + None or 3-array: If set, the default RGB color used for this visual geom + """ + if self.has_material(): + return self.material.diffuse_color_constant + else: + color = self.get_attribute("primvars:displayColor") + return None if color is None else th.tensor(color)[0] + + @color.setter + def color(self, rgb): + """ + Sets the RGB color of this visual mesh + + Args: + 3-array: The default RGB color used for this visual geom + """ + rgb = th.as_tensor(rgb) + if self.has_material(): + self.material.diffuse_color_constant = rgb + else: + self.set_attribute("primvars:displayColor", rgb.cpu().numpy()) + + @property + def opacity(self): + """ + Returns: + None or float: If set, the default opacity used for this visual geom + """ + if self.has_material(): + return self.material.opacity_constant + else: + opacity = self.get_attribute("primvars:displayOpacity") + return None if opacity is None else th.tensor(opacity)[0] + + @opacity.setter + def opacity(self, opacity): + """ + Sets the opacity of this visual mesh + + Args: + opacity: The default opacity used for this visual geom + """ + if self.has_material(): + self.material.opacity_constant = opacity + else: + self.set_attribute("primvars:displayOpacity", [opacity]) + + @cached_property + def points_and_faces(self): + mesh = self.prim + mesh_type = mesh.GetPrimTypeInfo().GetTypeName() + if mesh_type == "Mesh": + points = vtarray_to_torch(mesh.GetAttribute("points").Get(), dtype=th.float32) + face_vertex_counts = vtarray_to_torch(mesh.GetAttribute("faceVertexCounts").Get(), dtype=th.int) + face_indices = vtarray_to_torch(mesh.GetAttribute("faceVertexIndices").Get(), dtype=th.int) + + faces = [] + i = 0 + for count in face_vertex_counts: + for j in range(count - 2): + faces.append([face_indices[i], face_indices[i + j + 1], face_indices[i + j + 2]]) + i += count + faces = th.tensor(faces, dtype=th.int) + else: + tm = mesh_prim_shape_to_trimesh_mesh(mesh) + points = th.tensor(tm.vertices, dtype=th.float32) + faces = th.tensor(tm.faces, dtype=th.int) + return points, faces + + @property + def points(self): + return self.points_and_faces[0] + + @property + def faces(self): + return self.points_and_faces[1] + + @cached_property + def delaunay_triangulation(self): + return Delaunay(self.points.numpy()) + + @property + def geom_type(self): + """ + Returns: + str: the type of the geom prim, one of {"Sphere", "Cube", "Cone", "Cylinder", "Mesh"} + """ + return self._prim.GetPrimTypeInfo().GetTypeName() + + @cached_property + def mesh_face_centroids(self): + return self.points[self.faces].mean(dim=1) + + @cached_property + def mesh_face_normals(self): + # Get the vertices for each triangle + vertices = self.points[self.faces] # Shape: (N_triangles, 3, 3) + + # Compute two edges of each triangle + edge1 = vertices[:, 1] - vertices[:, 0] # Shape: (N_triangles, 3) + edge2 = vertices[:, 2] - vertices[:, 0] # Shape: (N_triangles, 3) + + # Compute the cross product of the two edges to get the normal vector + face_normals = th.cross(edge1, edge2, dim=1) # Shape: (N_triangles, 3) + + # Normalize the normal vectors + face_normals_norm = th.norm(face_normals, dim=1, keepdim=True) + + # Handle potential division by zero for degenerate faces + epsilon = 1e-8 + face_normals_norm = th.clamp(face_normals_norm, min=epsilon) + + face_normals = face_normals / face_normals_norm + + return face_normals + + def check_local_points_in_volume(self, particle_positions_in_mesh_frame): + if self._mesh_type == "Mesh": + return th.as_tensor(self.delaunay_triangulation.find_simplex(particle_positions_in_mesh_frame.numpy())) >= 0 + elif self._mesh_type == "Sphere": + return check_points_in_sphere( + size=self.get_attribute("radius"), + particle_positions=particle_positions_in_mesh_frame, + ) + elif self._mesh_type == "Cylinder": + return check_points_in_cylinder( + size=[self.get_attribute("radius"), self.get_attribute("height")], + particle_positions=particle_positions_in_mesh_frame, + ) + elif self._mesh_type == "Cone": + return check_points_in_cone( + size=[self.get_attribute("radius"), self.get_attribute("height")], + particle_positions=particle_positions_in_mesh_frame, + ) + elif self._mesh_type == "Cube": + return check_points_in_cube( + size=self.get_attribute("size"), + particle_positions=particle_positions_in_mesh_frame, + ) + else: + raise ValueError(f"Cannot check in volume for mesh of type: {self._mesh_type}") + + def check_points_in_volume(self, particle_positions_world): + # Move particles into local frame + world_pose_w_scale = self.scaled_transform + particle_positions_world_homogeneous = th.cat( + (particle_positions_world, th.ones((particle_positions_world.shape[0], 1))), dim=1 + ) + particle_positions_local = (particle_positions_world_homogeneous @ th.linalg.inv(world_pose_w_scale).T)[:, :3] + return self.check_local_points_in_volume(particle_positions_local) + + @property + def points_in_parent_frame(self): + points = self.points + if points is None: + return None + position, orientation = self.get_position_orientation(frame="parent") + scale = self.scale + points_scaled = points * scale + points_rotated = (T.quat2mat(orientation) @ points_scaled.T).T + points_transformed = points_rotated + position + return points_transformed + + @property + def points_in_world_frame(self): + return self.transform_local_points_to_world(self.points) + + @property + def aabb(self): + points_transformed = self.points_in_world_frame + + aabb_lo = th.min(points_transformed, dim=0).values + aabb_hi = th.max(points_transformed, dim=0).values + return aabb_lo, aabb_hi + + @property + def aabb_extent(self): + """ + Bounding box extent of this geom prim + + Returns: + 3-array: (x,y,z) bounding box + """ + min_corner, max_corner = self.aabb + return max_corner - min_corner + + @property + def aabb_center(self): + """ + Bounding box center of this geom prim + + Returns: + 3-array: (x,y,z) bounding box center + """ + min_corner, max_corner = self.aabb + return (max_corner + min_corner) / 2.0 + + @cached_property + def extent(self): + """ + Returns: + th.tensor: The unscaled 3d extent of the mesh in its local frame. + """ + points = self.points + return th.max(points, dim=0).values - th.min(points, dim=0).values + + def apply_physics_material(self, physics_material, weaker_than_descendants=False): + """ + Used to apply physics material to the held prim and optionally its descendants. + + Args: + physics_material (PhysicsMaterial): physics material to be applied to the held prim. This where you want to + define friction, restitution..etc. Note: if a physics material is not + defined, the defaults will be used from PhysX. + weaker_than_descendants (bool, optional): True if the material shouldn't override the descendants + materials, otherwise False. Defaults to False. + """ + binding_api = self._binding_api + with og.sim.editing_usd(): + if weaker_than_descendants: + binding_api.Bind( + physics_material.material, + bindingStrength=lazy.pxr.UsdShade.Tokens.weakerThanDescendants, + materialPurpose="physics", + ) + else: + binding_api.Bind( + physics_material.material, + bindingStrength=lazy.pxr.UsdShade.Tokens.strongerThanDescendants, + materialPurpose="physics", + ) + self._applied_physics_material = physics_material + + def get_applied_physics_material(self): + """ + Returns the current applied physics material in case it was applied using apply_physics_material or not. + + Returns: + PhysicsMaterial: the current applied physics material. + """ + if self._applied_physics_material is not None: + return self._applied_physics_material + else: + physics_binding = self._binding_api.GetDirectBinding(materialPurpose="physics") + path = physics_binding.GetMaterialPath() + if path == "": + return None + else: + self._applied_physics_material = lazy.isaacsim.core.api.materials.PhysicsMaterial(prim_path=path) + return self._applied_physics_material diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/joint_prim.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/joint_prim.py new file mode 100644 index 0000000000000000000000000000000000000000..0f8b558285c69684f16bf3017c63084a4596c1f9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/joint_prim.py @@ -0,0 +1,939 @@ +from collections.abc import Iterable + +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.controllers.controller_base import ControlType +from omnigibson.macros import create_module_macros +from omnigibson.prims.prim_base import BasePrim +from omnigibson.utils.constants import JointAxis, JointType +from omnigibson.utils.python_utils import assert_valid_key +from omnigibson.utils.usd_utils import create_joint +from omnigibson.utils.numpy_utils import gf_quat_to_torch, vtarray_to_torch + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.DEFAULT_MAX_POS = 1000.0 +m.DEFAULT_MAX_PRISMATIC_VEL = 1.0 +m.DEFAULT_MAX_REVOLUTE_VEL = 15.0 +m.DEFAULT_MAX_EFFORT = 100.0 +m.INF_POS_THRESHOLD = 1e5 +m.INF_VEL_THRESHOLD = 1e5 +m.INF_EFFORT_THRESHOLD = 1e10 +m.COMPONENT_SUFFIXES = ["x", "y", "z", "rx", "ry", "rz"] + +# TODO: Split into non-articulated / articulated Joint Prim classes? + + +# TODO: Add logic for non Prismatic / Revolute joints (D6, spherical) + + +class JointPrim(BasePrim): + """ + Provides high level functions to deal with a joint prim and its attributes/ properties. + If there is an joint prim present at the path, it will use it. Otherwise, a new joint prim at + the specified prim path will be created when self.load(...) is called. + + Note: the prim will have "xformOp:orient", "xformOp:translate" and "xformOp:scale" only post init, + unless it is a non-root articulation link. + + Args: + relative_prim_path (str): Scene-local prim path of the Prim to encapsulate or create. + name (str): Name for the object. Names need to be unique per scene. + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. For this joint prim, the below values can be specified: + + joint_type (str): If specified, should be the joint type to create. Valid options are: + {"Joint", "FixedJoint", "PrismaticJoint", "RevoluteJoint", "SphericalJoint"} + (equivalently, one of JointType) + body0 (None or str): If specified, should be the absolute prim path to the parent body that this joint + is connected to. None can also be valid, which corresponds to cases where only a single body may be + specified (e.g.: fixed joints) + body1 (None or str): If specified, should be the absolute prim path to the child body that this joint + is connected to. None can also be valid, which corresponds to cases where only a single body may be + specified (e.g.: fixed joints) + """ + + def __init__( + self, + relative_prim_path, + name, + load_config=None, + articulation_view=None, + ): + # Grab dynamic control reference and set properties + self._articulation_view = articulation_view + + # Other values that will be filled in at runtime + self._joint_type = None + self._control_type = None + self._driven = None + self._body0 = None + self._body1 = None + + # The following values will only be valid if this joint is part of an articulation + self._n_dof = None # The number of degrees of freedom this joint provides + self._joint_idx = None # The index of this joint in the parent articulation's joint array + self._joint_dof_offset = ( + None # The starting index of the DOFs for this joint in the parent articulation's DOF array + ) + self._joint_name = None # The name of this joint in the parent's articulation tree + + # Run super method + super().__init__( + relative_prim_path=relative_prim_path, + name=name, + load_config=load_config, + ) + + def _load(self): + # Make sure this joint isn't articulated + assert not self.articulated, ( + "Joint cannot be created, since this is an articulated joint! We are assuming" + "the joint already exists in the stage." + ) + + # Define a joint prim at the current stage + prim = create_joint( + prim_path=self.prim_path, + joint_type=self._load_config.get("joint_type", JointType.JOINT), + ) + + return prim + + def _post_load(self): + # run super first + super()._post_load() + + # Check whether this joint is driven or not + self._driven = self._prim.HasAPI(lazy.pxr.UsdPhysics.DriveAPI) and self._load_config.get("driven", False) + + # Add joint state API if this is a revolute or prismatic joint + self._joint_type = JointType.get_type(self._prim.GetTypeName().split("Physics")[-1]) + + # Possibly set the bodies + if "body0" in self._load_config and self._load_config["body0"] is not None: + self.body0 = self._load_config["body0"] + if "body1" in self._load_config and self._load_config["body1"] is not None: + self.body1 = self._load_config["body1"] + + def _initialize(self): + # Always run super first + super()._initialize() + + # Update the joint indices etc. + self.update_handles() + + # Get control type + if self.articulated: + control_types = [] + stiffnesses, dampings = self._articulation_view.get_gains(joint_indices=self.dof_indices) + for i, (kp, kd) in enumerate(zip(stiffnesses[0], dampings[0])): + # Infer control type based on whether kp and kd are 0 or not, as well as whether this joint is driven or not + # TODO: Maybe assert mutual exclusiveness here? + if not self._driven: + control_type = ControlType.NONE + elif kp == 0.0: + control_type = ControlType.EFFORT if kd == 0.0 else ControlType.VELOCITY + else: + control_type = ControlType.POSITION + control_types.append(control_type) + + # Make sure all the control types are the same -- if not, we had something go wrong! + assert len(set(control_types)) == 1, f"Got multiple control types for this single joint: {control_types}" + self._control_type = control_types[0] + + def update_handles(self): + """ + Updates all internal handles for this prim, in case they change since initialization + """ + # It's a bit tricky to get the joint index here. We need to find the first dof at this prim path + # first, then get the corresponding joint index from that dof offset. + self._joint_dof_offset = list(self._articulation_view._dof_paths[0]).index(self.prim_path) + joint_dof_offsets = self._articulation_view._metadata.joint_dof_offsets + # Note that we are finding the last occurrence of the dof offset, since that corresponds to the joint index + # The first occurrence can be a fixed link that is 0-dof, meaning the offset will be repeated. + self._joint_idx = next( + i for i in reversed(range(len(joint_dof_offsets))) if joint_dof_offsets[i] == self._joint_dof_offset + ) + self._joint_name = self._articulation_view._metadata.joint_names[self._joint_idx] + self._n_dof = self._articulation_view._metadata.joint_dof_counts[self._joint_idx] + + def set_control_type(self, control_type, kp=None, kd=None): + """ + Sets the control type for this joint. Note that ControlType.NONE is equivalent to + ControlType.EFFORT with 0 kp / kd + + Args: + control_type (ControlType): What type of control to use for this joint. + Valid options are: {ControlType.POSITION, ControlType.VELOCITY, ControlType.EFFORT, ControlType.NONE} + kp (None or float): If specified, sets the kp gain value for this joint. Should only be set if + setting ControlType.POSITION + kd (None or float): If specified, sets the kd gain value for this joint. Should only be set if + setting ControlType.VELOCITY + """ + # Sanity check inputs + assert_valid_key(key=control_type, valid_keys=ControlType.VALID_TYPES, name="control type") + if self.is_mimic_joint: + assert kp is None, "kp gain must not be specified for setting mimic joint control!" + assert kd is None, "kd gain must not be specified for setting mimic joint control!" + kp, kd = 0.0, 0.0 + else: + if control_type == ControlType.POSITION: + assert kp is not None, "kp gain must be specified for setting POSITION control!" + if kd is None: + # kd could have been optionally set, if not, then set 0 as default + kd = 0.0 + elif control_type == ControlType.VELOCITY: + assert kp is None, "kp gain must not be specified for setting VELOCITY control!" + assert kd is not None, "kd gain must be specified for setting VELOCITY control!" + kp = 0.0 + else: # Efforts (or NONE -- equivalent) + assert kp is None, "kp gain must not be specified for setting EFFORT control!" + assert kd is None, "kd gain must not be specified for setting EFFORT control!" + kp, kd = 0.0, 0.0 + + # Set values + kps = th.full((1, self._n_dof), kp) + kds = th.full((1, self._n_dof), kd) + self._articulation_view.set_gains(kps=kps, kds=kds, joint_indices=self.dof_indices) + + # Update control type + self._control_type = control_type + + @property + def body0(self): + """ + Gets this joint's body0 relationship. + + Returns: + None or str: Absolute prim path to the body prim to set as this joint's parent link, or None if there is + no body0 specified. + """ + if self._body0 is None: + targets = self._prim.GetRelationship("physics:body0").GetTargets() + self._body0 = targets[0].__str__() + return self._body0 + + @body0.setter + def body0(self, body0): + """ + Sets this joint's body0 relationship. + + Args: + body0 (str): Absolute prim path to the body prim to set as this joint's parent link. + """ + # Make sure prim path is valid + assert lazy.isaacsim.core.utils.prims.is_prim_path_valid(body0), f"Invalid body0 path specified: {body0}" + self._prim.GetRelationship("physics:body0").SetTargets([lazy.pxr.Sdf.Path(body0)]) + self._body0 = None + + @property + def body1(self): + """ + Gets this joint's body1 relationship. + + Returns: + None or str: Absolute prim path to the body prim to set as this joint's child link, or None if there is + no body1 specified. + """ + if self._body1 is None: + targets = self._prim.GetRelationship("physics:body1").GetTargets() + self._body1 = targets[0].__str__() + return self._body1 + + @body1.setter + def body1(self, body1): + """ + Sets this joint's body1 relationship. + + Args: + body1 (str): Absolute prim path to the body prim to set as this joint's child link. + """ + # Make sure prim path is valid + assert lazy.isaacsim.core.utils.prims.is_prim_path_valid(body1), f"Invalid body1 path specified: {body1}" + self._prim.GetRelationship("physics:body1").SetTargets([lazy.pxr.Sdf.Path(body1)]) + self._body1 = None + + @property + def local_orientation_0(self): + """ + Returns: + 4-array: (x,y,z,w) local quaternion orientation of this joint, relative to the parent link + """ + return gf_quat_to_torch(self.get_attribute("physics:localRot0")) + + @property + def local_orientation_1(self): + """ + Returns: + 4-array: (x,y,z,w) local quaternion orientation of this joint, relative to the child link + """ + return gf_quat_to_torch(self.get_attribute("physics:localRot1")) + + @property + def local_position_0(self): + """ + Returns: + 3-array: (x,y,z) local position of this joint, relative to the parent link + """ + return vtarray_to_torch(self.get_attribute("physics:localPos0")) + + @property + def local_position_1(self): + """ + Returns: + 3-array: (x,y,z) local position of this joint, relative to the child link + """ + return vtarray_to_torch(self.get_attribute("physics:localPos1")) + + @property + def joint_name(self): + """ + Returns: + str: Name of this joint + """ + return self._joint_name + + @property + def joint_type(self): + """ + Gets this joint's type (ignoring the "Physics" prefix) + + Returns: + JointType: Joint's type. Should be one corresponding to: + {JOINT_PRISMATIC, JOINT_REVOLUTE, JOINT_FIXED, JOINT_SPHERICAL} + """ + return self._joint_type + + @property + def driven(self): + """ + Returns: + bool: Whether this joint can be driven by a motor or not + """ + return self._driven + + @property + def control_type(self): + """ + Gets the control types for this joint + + Returns: + ControlType: control type for this joint + """ + return self._control_type + + @property + def max_velocity(self): + """ + Gets this joint's maximum velocity + + Returns: + float: maximum velocity for this joint + """ + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + # We either return the raw value or a default value if there is no max specified + raw_vel = self._articulation_view.get_max_velocities(joint_indices=self.dof_indices)[0][0] + default_max_vel = ( + m.DEFAULT_MAX_REVOLUTE_VEL if self.joint_type == JointType.JOINT_REVOLUTE else m.DEFAULT_MAX_PRISMATIC_VEL + ) + return default_max_vel if raw_vel is None or th.abs(raw_vel) > m.INF_VEL_THRESHOLD else raw_vel + + @max_velocity.setter + def max_velocity(self, vel): + """ + Sets this joint's maximum velocity + + Args: + vel (float): Velocity to set + """ + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + self._articulation_view.set_max_velocities(th.tensor([[vel]]), joint_indices=self.dof_indices) + + @property + def max_effort(self): + """ + Gets this joint's maximum effort + + Returns: + float: maximum effort for this joint + """ + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + # We either return the raw value or a default value if there is no max specified + raw_effort = self._articulation_view.get_max_efforts(joint_indices=self.dof_indices)[0][0] + return m.DEFAULT_MAX_EFFORT if raw_effort is None or th.abs(raw_effort) > m.INF_EFFORT_THRESHOLD else raw_effort + + @max_effort.setter + def max_effort(self, effort): + """ + Sets this joint's maximum effort + + Args: + effort (float): effort to set + """ + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + self._articulation_view.set_max_efforts(th.tensor([[effort]], dtype=th.float32), joint_indices=self.dof_indices) + + @property + def stiffness(self): + """ + Gets this joint's stiffness + + Returns: + float: stiffness for this joint + """ + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + stiffnesses = self._articulation_view.get_gains(joint_indices=self.dof_indices)[0] + return stiffnesses[0][0] + + @stiffness.setter + def stiffness(self, stiffness): + """ + Sets this joint's stiffness + + Args: + stiffness (float): stiffness to set + """ + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + self._articulation_view.set_gains(kps=th.tensor([[stiffness]]), joint_indices=self.dof_indices) + + @property + def damping(self): + """ + Gets this joint's damping + + Returns: + float: damping for this joint + """ + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + dampings = self._articulation_view.get_gains(joint_indices=self.dof_indices)[1] + return dampings[0][0] + + @damping.setter + def damping(self, damping): + """ + Sets this joint's damping + + Args: + damping (float): damping to set + """ + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + self._articulation_view.set_gains(kds=th.tensor([[damping]]), joint_indices=self.dof_indices) + + @property + def friction(self): + """ + Gets this joint's friction + + Returns: + float: friction for this joint + """ + return ( + self._articulation_view.get_friction_coefficients(joint_indices=self.dof_indices)[0][0] + if og.sim.is_playing() + else self.get_attribute("physxJoint:jointFriction") + ) + + @friction.setter + def friction(self, friction): + """ + Sets this joint's friction + + Args: + friction (float): friction to set + """ + self.set_attribute("physxJoint:jointFriction", friction) + if og.sim.is_playing(): + self._articulation_view.set_friction_coefficients(th.tensor([[friction]]), joint_indices=self.dof_indices) + + @property + def lower_limit(self): + """ + Gets this joint's lower_limit + + Returns: + float: lower_limit for this joint + """ + # TODO: Add logic for non Prismatic / Revolute joints (D6, spherical) + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + # We either return the raw value or a default value if there is no max specified + raw_pos_lower, raw_pos_upper = self._articulation_view.get_joint_limits( + joint_indices=self.dof_indices + ).flatten() + return ( + -m.DEFAULT_MAX_POS + if raw_pos_lower is None or raw_pos_lower == raw_pos_upper or th.abs(raw_pos_lower) > m.INF_POS_THRESHOLD + else raw_pos_lower + ) + + @lower_limit.setter + def lower_limit(self, lower_limit): + """ + Sets this joint's lower_limit + + Args: + lower_limit (float): lower_limit to set + """ + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + self._articulation_view.set_joint_limits( + th.tensor([[lower_limit, self.upper_limit]]), joint_indices=self.dof_indices + ) + + @property + def upper_limit(self): + """ + Gets this joint's upper_limit + + Returns: + float: upper_limit for this joint + """ + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + # We either return the raw value or a default value if there is no max specified + raw_pos_lower, raw_pos_upper = self._articulation_view.get_joint_limits( + joint_indices=self.dof_indices + ).flatten() + return ( + m.DEFAULT_MAX_POS + if raw_pos_upper is None or raw_pos_lower == raw_pos_upper or th.abs(raw_pos_upper) > m.INF_POS_THRESHOLD + else raw_pos_upper + ) + + @upper_limit.setter + def upper_limit(self, upper_limit): + """ + Sets this joint's upper_limit + + Args: + upper_limit (float): upper_limit to set + """ + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + self._articulation_view.set_joint_limits( + th.tensor([[self.lower_limit, upper_limit]]), joint_indices=self.dof_indices + ) + + @property + def has_limit(self): + """ + Returns: + bool: True if this joint has a limit, else False + """ + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + return th.all( + th.abs(self._articulation_view.get_joint_limits(joint_indices=self.dof_indices)) < m.INF_POS_THRESHOLD + ) + + @property + def axis(self): + """ + Gets this joint's axis + + Returns: + str: axis for this joint, one of "X", "Y, "Z" + """ + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + axis = self.get_attribute("physics:axis") + if axis == "": + return "X" + return axis + + @axis.setter + def axis(self, axis): + """ + Sets this joint's axis + + Args: + str: axis for this joint, one of "X", "Y, "Z" + """ + # Only support revolute and prismatic joints for now + assert self.is_single_dof, "Joint properties only supported for a single DOF currently!" + assert axis in JointAxis, f"Invalid joint axis specified: {axis}!" + self.set_attribute("physics:axis", axis) + + @property + def n_dof(self): + """ + Returns: + int: Number of degrees of freedom this joint has + """ + return self._n_dof + + @property + def dof_indices(self): + """ + Returns: + list of int: Indices of this joint's DOFs in the parent articulation's DOF array + """ + assert self.articulated, "Can only get DOF indices for articulated joints!" + return list(range(self._joint_dof_offset, self._joint_dof_offset + self._n_dof)) + + @property + def articulated(self): + """ + Returns: + bool: Whether this joint is articulated or not + """ + return self._articulation_view is not None + + @property + def is_revolute(self): + """ + Returns: + bool: Whether this joint is revolute or not + """ + return self._joint_type == JointType.JOINT_REVOLUTE + + @property + def is_single_dof(self): + """ + Returns: + bool: Whether this joint has a single DOF or not + """ + return self._joint_type in {JointType.JOINT_REVOLUTE, JointType.JOINT_PRISMATIC} + + def get_state(self, normalized=False): + """ + (pos, vel, effort) state of this joint + + Args: + normalized (bool): If True, will return normalized state of this joint, where pos, vel, and effort values + are in range [-1, 1]. + + Returns: + 3-tuple: + - n-array: position of this joint, where n = number of DOF for this joint + - n-array: velocity of this joint, where n = number of DOF for this joint + - n-array: effort of this joint, where n = number of DOF for this joint + """ + # Make sure we only call this if we're an articulated joint + assert self.articulated, "Can only get state for articulated joints!" + + # Grab raw states + pos = self._articulation_view.get_joint_positions(joint_indices=self.dof_indices)[0] + vel = self._articulation_view.get_joint_velocities(joint_indices=self.dof_indices)[0] + effort = self._articulation_view.get_measured_joint_efforts(joint_indices=self.dof_indices)[0] + + # Potentially normalize if requested + if normalized: + pos, vel, effort = self._normalize_pos(pos), self._normalize_vel(vel), self._normalize_effort(effort) + + return pos, vel, effort + + def get_target(self, normalized=False): + """ + (pos, vel) target of this joint + + Args: + normalized (bool): If True, will return normalized target of this joint + + Returns: + 2-tuple: + - n-array: target position of this joint, where n = number of DOF for this joint + - n-array: target velocity of this joint, where n = number of DOF for this joint + """ + # Make sure we only call this if we're an articulated joint + assert self.articulated, "Can only get targets for articulated joints!" + + # Grab raw states + targets = self._articulation_view.get_applied_actions() + pos = targets.joint_positions[0][self.dof_indices] + vel = targets.joint_velocities[0][self.dof_indices] + + # Potentially normalize if requested + if normalized: + pos, vel = self._normalize_pos(pos), self._normalize_vel(vel) + + return pos, vel + + def _normalize_pos(self, pos): + """ + Normalizes raw joint positions @pos + + Args: + pos (n-array): n-DOF raw positions to normalize + + Returns: + n-array: n-DOF normalized positions in range [-1, 1] + """ + low, high = self.lower_limit, self.upper_limit + mean = (low + high) / 2.0 + magnitude = (high - low) / 2.0 + pos = (pos - mean) / magnitude + + return pos + + def _denormalize_pos(self, pos): + """ + De-normalizes joint positions @pos + + Args: + pos (n-array): n-DOF normalized positions in range [-1, 1] + + Returns: + n-array: n-DOF de-normalized positions + """ + low, high = self.lower_limit, self.upper_limit + mean = (low + high) / 2.0 + magnitude = (high - low) / 2.0 + pos = pos * magnitude + mean + + return pos + + def _normalize_vel(self, vel): + """ + Normalizes raw joint velocities @vel + + Args: + vel (n-array): n-DOF raw velocities to normalize + + Returns: + n-array: n-DOF normalized velocities in range [-1, 1] + """ + return vel / self.max_velocity + + def _denormalize_vel(self, vel): + """ + De-normalizes joint velocities @vel + + Args: + vel (n-array): n-DOF normalized velocities in range [-1, 1] + + Returns: + n-array: n-DOF de-normalized velocities + """ + return vel * self.max_velocity + + def _normalize_effort(self, effort): + """ + Normalizes raw joint effort @effort + + Args: + effort (n-array): n-DOF raw effort to normalize + + Returns: + n-array: n-DOF normalized effort in range [-1, 1] + """ + return effort / self.max_effort + + def _denormalize_effort(self, effort): + """ + De-normalizes joint effort @effort + + Args: + effort (n-array): n-DOF normalized effort in range [-1, 1] + + Returns: + n-array: n-DOF de-normalized effort + """ + return effort * self.max_effort + + def set_pos(self, pos, normalized=False, drive=False): + """ + Set the position of this joint in metric space + + Args: + pos (float or n-array of float): Set the position(s) for this joint. Can be a single float or 1-array of + float if the joint only has a single DOF, otherwise it should be an n-array of floats. + normalized (bool): Whether the input is normalized to [-1, 1] (in this case, the values will be + de-normalized first before being executed). Default is False + drive (bool): Whether the joint should be driven naturally via its motor to the position being set or + whether it should be instantaneously set. Default is False, corresponding to an + instantaneous setting of the position + """ + # Sanity checks -- make sure we're the correct control type if we're setting a target and that we're articulated + assert self.articulated, "Can only set position for articulated joints!" + if drive: + assert self.driven, "Can only use set_pos with drive=True if this joint is driven!" + assert ( + self._control_type == ControlType.POSITION + ), "Trying to set joint position target, but control type is not position!" + + # Standardize input + pos = ( + pos + if isinstance(pos, th.Tensor) + else ( + th.tensor([pos], dtype=th.float32) + if self._n_dof == 1 and not isinstance(pos, Iterable) + else th.tensor(pos, dtype=th.float32) + ) + ) + + # Potentially de-normalize if the input is normalized + if normalized: + pos = self._denormalize_pos(pos) + + # Set the DOF(s) in this joint + if self.driven: + # Any controllable objects, e.g. a robot + if drive: + self._articulation_view.set_joint_position_targets(positions=pos, joint_indices=self.dof_indices) + else: + self._articulation_view.set_joint_positions(positions=pos, joint_indices=self.dof_indices) + self._articulation_view.set_joint_position_targets(positions=pos, joint_indices=self.dof_indices) + og.sim.sync_physx_to_fabric() + else: + # Any other objects, e.g. furniture with passive joints + # In this case, since we're not actively driven, just set instantaneous position + self._articulation_view.set_joint_positions(positions=pos, joint_indices=self.dof_indices) + og.sim.sync_physx_to_fabric() + + # OpenState (and any future joint-derived state) reads from a cached + # ArticulatedObjectViewAPI._JOINT_POSITIONS that we've just bypassed; mark all + # tensorized caches dirty so the next read forces a refresh. + from omnigibson.object_states.tensorized_state import TensorizedState + + TensorizedState.caches_dirty = True + + def set_vel(self, vel, normalized=False, drive=False): + """ + Set the velocity of this joint in metric space + + Args: + vel (float or n-array of float): Set the velocity(s) for this joint. Can be a single float or 1-array of + float if the joint only has a single DOF, otherwise it should be an n-array of floats. + normalized (bool): Whether the input is normalized to [-1, 1] (in this case, the values will be + de-normalized first before being executed). Default is False + drive (bool): Whether the joint should be driven naturally via its motor to the velocity being set or + whether it should be instantaneously set. Default is False, corresponding to an + instantaneous setting of the velocity + """ + # Sanity checks -- make sure we're the correct control type if we're setting a target and that we're articulated + assert self.articulated, "Can only set velocity for articulated joints!" + if drive: + assert self.driven, "Can only use set_vel with drive=True if this joint is driven!" + assert ( + self._control_type == ControlType.VELOCITY + ), f"Trying to set joint velocity target for joint {self.name}, but control type is not velocity!" + + # Standardize input + vel = ( + vel + if isinstance(vel, th.Tensor) + else ( + th.tensor([vel], dtype=th.float32) + if self._n_dof == 1 and not isinstance(vel, Iterable) + else th.tensor(vel, dtype=th.float32) + ) + ) + + # Potentially de-normalize if the input is normalized + if normalized: + vel = self._denormalize_vel(vel) + + # Set the DOF(s) in this joint + if self.driven: + # Any controllable objects, e.g. a robot + if drive: + self._articulation_view.set_joint_velocity_targets(velocities=vel, joint_indices=self.dof_indices) + else: + self._articulation_view.set_joint_velocities(velocities=vel, joint_indices=self.dof_indices) + self._articulation_view.set_joint_velocity_targets(velocities=vel, joint_indices=self.dof_indices) + else: + # Any other objects, e.g. furniture with passive joints + # In this case, since we're not actively driven, just set instantaneous velocity + self._articulation_view.set_joint_velocities(velocities=vel, joint_indices=self.dof_indices) + + def set_effort(self, effort, normalized=False): + """ + Set the effort of this joint in metric space + + Args: + effort (float or n-array of float): Set the effort(s) for this joint. Can be a single float or 1-array of + float if the joint only has a single DOF, otherwise it should be an n-array of floats. + normalized (bool): Whether the input is normalized to [-1, 1] (in this case, the values will be + de-normalized first before being executed). Default is False + """ + # Sanity checks -- make sure that we're articulated (no control type check like position and velocity + # because we can't set effort targets) and that we're driven + assert self.articulated, "Can only set effort for articulated joints!" + + # Standardize input + effort = ( + effort + if isinstance(effort, th.Tensor) + else ( + th.tensor([effort], dtype=th.float32) + if self._n_dof == 1 and not isinstance(effort, Iterable) + else th.tensor(effort, dtype=th.float32) + ) + ) + + # Potentially de-normalize if the input is normalized + if normalized: + effort = self._denormalize_effort(effort) + + # Set the DOF(s) in this joint + self._articulation_view.set_joint_efforts(efforts=effort, joint_indices=self.dof_indices) + + def keep_still(self): + """ + Zero out all velocities for this prim + """ + self.set_vel(th.zeros(self.n_dof)) + self.set_effort(th.zeros(self.n_dof)) + + def _dump_state(self): + pos, vel, _ = self.get_state() if self.articulated else (th.empty(0), th.empty(0), th.empty(0)) + target_pos, target_vel = self.get_target() if self.articulated else (th.empty(0), th.empty(0)) + return dict( + pos=pos, + vel=vel, + target_pos=target_pos, + target_vel=target_vel, + ) + + def _load_state(self, state): + if self.articulated: + self.set_pos(state["pos"], drive=False) + self.set_vel(state["vel"], drive=False) + if self._control_type == ControlType.POSITION: + self.set_pos(state["target_pos"], drive=True) + elif self._control_type == ControlType.VELOCITY: + self.set_vel(state["target_vel"], drive=True) + + def serialize(self, state): + return th.cat( + [ + state["pos"], + state["vel"], + state["target_pos"], + state["target_vel"], + ] + ) + + def deserialize(self, state): + # We deserialize deterministically by knowing the order of values -- pos, vel, effort + return ( + dict( + pos=state[0 : self.n_dof], + vel=state[self.n_dof : 2 * self.n_dof], + target_pos=state[2 * self.n_dof : 3 * self.n_dof], + target_vel=state[3 * self.n_dof : 4 * self.n_dof], + ), + 4 * self.n_dof, + ) + + @property + def is_mimic_joint(self): + """ + Returns: + bool: True if this joint is a mimic joint, else False + """ + return self.prim.HasAPI(lazy.pxr.PhysxSchema.PhysxMimicJointAPI) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/material_prim.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/material_prim.py new file mode 100644 index 0000000000000000000000000000000000000000..50e08c48a5be1f63eaa317c3c1599565bc25a685 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/material_prim.py @@ -0,0 +1,779 @@ +import cv2 +from omnigibson.utils.ui_utils import create_module_logger +import torch as th + +import omnigibson as og +from omnigibson.macros import gm +import omnigibson.lazy as lazy +from omnigibson.prims.prim_base import BasePrim +from omnigibson.utils.physx_utils import bind_material +from omnigibson.utils.usd_utils import absolute_prim_path_to_scene_relative, get_sdf_value_type_name + + +log = create_module_logger(module_name=__name__) + + +class MaterialPrim(BasePrim): + """ + Provides high level functions to deal with a material prim and its attributes/ properties. + + If there is a material prim present at the path, it will use it. Otherwise, a new material prim at + the specified prim path will be created. + + Args: + relative_prim_path (str): Scene-local prim path of the Prim to encapsulate or create. + name (str): Name for the object. Names need to be unique per scene. + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. Note that this is only needed if the prim does not already exist at + @relative_prim_path -- it will be ignored if it already exists. Subclasses should define the exact keys expected + for their class. For this material prim, the below values can be specified: + + mdl_name (None or str): If specified, should be the name of the mdl preset to load (including .mdl). + None results in default, "OmniPBR.mdl" + mtl_name (None or str): If specified, should be the name of the mtl preset to load. + None results in default, "OmniPBR" + """ + + # Persistent dictionary of materials, mapped from prim_path to MaterialPrim + MATERIALS = dict() + + @classmethod + def get_material(cls, scene, name, prim_path, **kwargs): + """ + Get a material prim from the persistent dictionary of materials, or create a new one if it doesn't exist. + + Args: + scene (Scene): Scene to which this material belongs. + name (str): Name for the object. + prim_path (str): prim path of the MaterialPrim. + **kwargs (dict): Additional keyword arguments to pass to the MaterialPrim or subclass constructor. + + Returns: + MaterialPrim: Material prim at the specified path + """ + # If the material already exists, return it + if prim_path in MaterialPrim.MATERIALS: + return MaterialPrim.MATERIALS[prim_path] + + # Otherwise, create a new one and return it + material_class = cls + if lazy.isaacsim.core.utils.prims.is_prim_path_valid(prim_path): + # If the prim already exists, infer its type. + material_prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(prim_path) + shader_prim = lazy.omni.usd.get_shader_from_material(material_prim) + assert shader_prim is not None, ( + f"Material prim at {prim_path} exists, but does not have a shader associated with it! " + f"Please make sure the material is created correctly." + ) + + # If we are able to obtain the asset path and sub-identifier, we can determine the material class. + mdl_asset = shader_prim.GetSourceAsset("mdl") + if mdl_asset is not None: + asset_path = mdl_asset.path + asset_sub_identifier = shader_prim.GetSourceAssetSubIdentifier("mdl") + + if cls == MaterialPrim: + # If this function is getting called on MaterialPrim, then we try to pick a compatible subclass. + compatible_classes = [ + subclass + for subclass in MaterialPrim.__subclasses__() + if subclass.supports_material(asset_path, asset_sub_identifier) + ] + assert len(compatible_classes) <= 1, ( + "Found multiple compatible material prim classes for " + f"material at {prim_path} with asset path {asset_path} and sub-identifier {asset_sub_identifier}: " + f"{compatible_classes}" + ) + if len(compatible_classes) == 1: + # Use the only found compatible class + material_class = compatible_classes[0] + else: + # Fall back to MaterialPrim + log.warning( + f"No compatible material prim class found for material at {prim_path} with " + f"asset path {asset_path} and sub-identifier {asset_sub_identifier}. " + f"Using MaterialPrim as a fallback." + ) + else: + # If this function is called on a subclass of MaterialPrim, then we check if the subclass supports the material. + assert material_class.supports_material(asset_path, asset_sub_identifier), ( + f"MaterialPrim subclass {material_class.__name__} does not support material at {prim_path} " + f"with asset path {asset_path} and sub-identifier {asset_sub_identifier}!" + ) + else: + # If the material prim exists, but does not have a shader file we can recognize. + log.warning( + f"Material prim at {prim_path} exists, but does not have a known shader file associated with it! " + f"Using MaterialPrim as a fallback. If this is not intended, please make sure the material is created correctly." + ) + + relative_prim_path = absolute_prim_path_to_scene_relative(scene, prim_path) + new_material = material_class(relative_prim_path=relative_prim_path, name=name, **kwargs) + new_material.load(scene) + assert ( + new_material.prim_path == prim_path + ), f"Material prim path {new_material.prim_path} does not match {prim_path}" + MaterialPrim.MATERIALS[prim_path] = new_material + return new_material + + def __init__( + self, + relative_prim_path, + name, + load_config=None, + ): + # Other values that will be filled in at runtime + self._shader = None + self._shader_node = None + + # Users of this material: should be a set of USDObject and BaseSystem + self._users = set() + + # Run super init + super().__init__( + relative_prim_path=relative_prim_path, + name=name, + load_config=load_config, + ) + + @classmethod + def supports_material(cls, asset_path, asset_sub_identifier): + """ + Checks if this material prim supports the given asset path and sub-identifier. + + Args: + asset_path (str): The asset path of the MDL file. + asset_sub_identifier (str): The sub-identifier of the MDL file. + + Returns: + bool: True if this material prim supports the given asset path and sub-identifier, False otherwise. + """ + raise NotImplementedError(f"MaterialPrim subclass {cls.__name__} does not implement supports_material method!") + + @property + def mdl_name(self): + """ + The name of the MDL file to load for this material. + This is expected to be defined in the load_config dictionary for this base class which is used + for generic material prims. The PBR and V-Ray material prims will override this method + to return their own MDL names. + """ + assert "mdl_name" in self._load_config, ( + f"MaterialPrim at {self.prim_path} does not have a 'mdl_name' in its load_config! " + f"Please specify it in the load_config dictionary or use one of the subclasses that " + f"already define it (e.g. OmniPBRMaterialPrim, VRayMaterialPrim, OmniGlassMaterialPrim, OmniSurfaceMaterialPrim)" + ) + return self._load_config["mdl_name"] + + @property + def mtl_name(self): + """ + The name of the material from the MDL file to load for this material. + This is expected to be defined in the load_config dictionary for this base class which is used + for generic material prims. The PBR and V-Ray material prims will override this method + to return their own MDL names. + """ + assert "mtl_name" in self._load_config, ( + f"MaterialPrim at {self.prim_path} does not have a 'mtl_name' in its load_config! " + f"Please specify it in the load_config dictionary or use one of the subclasses that " + f"already define it (e.g. OmniPBRMaterialPrim, VRayMaterialPrim, OmniGlassMaterialPrim)" + ) + return self._load_config["mtl_name"] + + def _load(self): + # We create a new material at the specified path + mtl_created = [] + with og.sim.editing_usd(): + lazy.omni.kit.commands.execute( + "CreateAndBindMdlMaterialFromLibrary", + mdl_name=self.mdl_name, + mtl_name=self.mtl_name, + mtl_created_list=mtl_created, + ) + material_path = mtl_created[0] + + # Move prim to desired location + lazy.omni.kit.commands.execute("MovePrim", path_from=material_path, path_to=self.prim_path) + og.sim.update_handles() + + # Return generated material + return lazy.isaacsim.core.utils.prims.get_prim_at_path(self.prim_path) + + @classmethod + def clear(cls): + cls.MATERIALS = dict() + + @property + def users(self): + """ + Users of this material: should be a list of USDObject and BaseSystem + """ + return self._users + + def add_user(self, user): + """ + Adds a user to the material. This can be a USDObject or BaseSystem. + + Args: + user (USDObject or BaseSystem): User to add to the material + """ + self._users.add(user) + + def remove_user(self, user): + """ + Removes a user from the material. This can be a USDObject or BaseSystem. + If there are no users left, the material will be removed. + + Args: + user (USDObject or BaseSystem): User to remove from the material + """ + self._users.remove(user) + if len(self._users) == 0: + self.remove() + + def remove(self): + # Remove from global sensors dictionary + self.MATERIALS.pop(self.prim_path) + + # Run super + super().remove() + + def _post_load(self): + # run super first + super()._post_load() + + # Add this material to the list of global materials + self.MATERIALS[self.prim_path] = self + + # Generate shader reference + self._shader = lazy.omni.usd.get_shader_from_material(self._prim) + self._shader_node = lazy.omni.UsdMdl.RegistryUtils.GetShaderNodeForPrim(self._shader.GetPrim()) + + def bind(self, target_prim_path): + """ + Bind this material to an arbitrary prim (usually a visual mesh prim) + + Args: + target_prim_path (str): prim path of the Prim to bind to + """ + bind_material(prim_path=target_prim_path, material_path=self.prim_path) + + def get_input(self, inp): + """ + Grabs the input with corresponding name @inp associated with this material and shader + + Args: + inp (str): Name of the shader input whose value will be grabbed + + Returns: + any: value of the requested @inp + """ + non_default_inp = self._shader.GetInput(inp).Get() + if non_default_inp is not None: + return non_default_inp + + return self._shader_node.GetInput(inp).GetDefaultValue() + + def set_input(self, inp, val): + """ + Sets the input with corresponding name @inp associated with this material and shader + + Args: + inp (str): Name of the shader input whose value will be set + val (any): Value to set for the input. This should be the valid type for that attribute. + """ + with og.sim.editing_usd(): + # Make sure the input exists first, so we avoid segfaults with "invalid null prim" + if inp in self.shader_input_names: + self._shader.GetInput(inp).Set(val) + elif inp in self.shader_default_input_names: + input_type = get_sdf_value_type_name(val) + self._shader.CreateInput(inp, input_type).Set(val) + else: + raise ValueError(f"Got invalid shader input to set! Got: {inp}") + + @property + def shader(self): + """ + Returns: + Usd.Shade: Shader associated with this material + """ + return self._shader + + @property + def shader_input_names(self): + """ + Returns: + set: All the shader input names associated with this material + """ + return {inp.GetBaseName() for inp in self._shader.GetInputs()} + + @property + def shader_default_input_names(self): + """ + Returns: + set: All the shader input names associated with this material that have default values + """ + return set(self._shader_node.GetInputNames()) + + def get_shader_input_names_by_type(self, input_type, include_default=False): + """ + Args: + input_type (str): input type + include_default (bool): whether to include default inputs + Returns: + set: All the shader input names associated with this material that match the given input type + """ + shader_input_names = { + inp.GetBaseName() for inp in self._shader.GetInputs() if inp.GetTypeName().cppTypeName == input_type + } + if not include_default: + return shader_input_names + shader_default_input_names = { + inp_name + for inp_name in self.shader_default_input_names + if self._shader_node.GetInput(inp_name).GetType() == input_type + } + return shader_input_names | shader_default_input_names + + @property + def average_diffuse_color(self): + return th.zeros(3) + + @property + def albedo_add(self): + """ + Returns: + float: this material's applied albedo_add + """ + return 0.0 + + @albedo_add.setter + def albedo_add(self, add): + """ + Args: + add (float): this material's applied albedo_add + """ + return + + @property + def diffuse_tint(self): + """ + Returns: + 3-array: this material's applied (R,G,B) diffuse_tint + """ + return th.zeros(3) + + @diffuse_tint.setter + def diffuse_tint(self, color): + """ + Args: + color (3-array): this material's applied (R,G,B) diffuse_tint + """ + return + + def enable_highlight(self, highlight_color, highlight_intensity): + """ + Enables highlight for this material with the specified color and intensity. + + Args: + highlight_color (3-array): Color of the highlight in (R,G,B) + highlight_intensity (float): Intensity of the highlight + """ + pass + + def disable_highlight(self): + """ + Disables highlight for this material. + """ + pass + + +class OmniPBRMaterialPrim(MaterialPrim): + """ + A MaterialPrim that uses the OmniPBR material preset. + """ + + @classmethod + def supports_material(cls, asset_path, asset_sub_identifier): + return asset_path.endswith("OmniPBR.mdl") and asset_sub_identifier == "OmniPBR" + + @property + def mdl_name(self): + return "OmniPBR.mdl" + + @property + def mtl_name(self): + return "OmniPBR" + + def _post_load(self): + # Run super first + super()._post_load() + + # Apply any forced roughness updates + self.set_input(inp="reflection_roughness_texture_influence", val=0.0) + self.set_input(inp="reflection_roughness_constant", val=gm.FORCE_ROUGHNESS) + + # TODO: Check that it does not use emission by default. + + @property + def diffuse_color_constant(self): + """ + Returns: + 3-array: this material's applied (R,G,B) color + """ + diffuse_color_constant = self.get_input(inp="diffuse_color_constant") + return th.tensor(diffuse_color_constant, dtype=th.float32) if diffuse_color_constant is not None else None + + @diffuse_color_constant.setter + def diffuse_color_constant(self, color): + """ + Args: + color (3-array): this material's applied (R,G,B) color + """ + self.set_input(inp="diffuse_color_constant", val=lazy.pxr.Gf.Vec3f(*color.tolist())) + + @property + def diffuse_texture(self): + """ + Returns: + str: this material's applied diffuse_texture filepath + """ + return self.get_input(inp="diffuse_texture").resolvedPath + + @diffuse_texture.setter + def diffuse_texture(self, fpath): + """ + Args: + str: this material's applied diffuse_texture filepath + """ + self.set_input(inp="diffuse_texture", val=lazy.pxr.Sdf.AssetPath(fpath)) + + @property + def albedo_add(self): + """ + Returns: + float: this material's applied albedo_add + """ + return self.get_input(inp="albedo_add") + + @albedo_add.setter + def albedo_add(self, add): + """ + Args: + add (float): this material's applied albedo_add + """ + self.set_input(inp="albedo_add", val=add) + + @property + def diffuse_tint(self): + """ + Returns: + 3-array: this material's applied (R,G,B) diffuse_tint + """ + diffuse_tint = self.get_input(inp="diffuse_tint") + return th.tensor(diffuse_tint, dtype=th.float32) if diffuse_tint is not None else None + + @diffuse_tint.setter + def diffuse_tint(self, color): + """ + Args: + color (3-array): this material's applied (R,G,B) diffuse_tint + """ + self.set_input(inp="diffuse_tint", val=lazy.pxr.Gf.Vec3f(*color.tolist())) + + @property + def average_diffuse_color(self): + diffuse_texture = self.diffuse_texture + return cv2.imread(diffuse_texture).mean(axis=(0, 1)) if diffuse_texture else self.diffuse_color_constant + + def enable_highlight(self, highlight_color, highlight_intensity): + """ + Enables highlight for this material with the specified color and intensity. + + Args: + highlight_color (3-array): Color of the highlight in (R,G,B) + highlight_intensity (float): Intensity of the highlight + """ + # Set emissive properties to enable highlight + self.set_input(inp="enable_emission", val=True) + self.set_input(inp="emissive_color", val=lazy.pxr.Gf.Vec3f(*highlight_color)) + self.set_input(inp="emissive_intensity", val=highlight_intensity) + + def disable_highlight(self): + self.set_input(inp="enable_emission", val=False) + + +class VRayMaterialPrim(MaterialPrim): + """ + A MaterialPrim that uses the V-Ray material preset. + """ + + @classmethod + def supports_material(cls, asset_path, asset_sub_identifier): + return asset_path.endswith("omnigibson_vray_mtl.mdl") and asset_sub_identifier == "OmniGibsonVRayMtl" + + @property + def mdl_name(self): + return "omnigibson_vray_mtl.mdl" + + @property + def mtl_name(self): + return "OmniGibsonVRayMtl" + + @property + def diffuse_texture(self): + """ + Returns: + str: this material's applied diffuse_texture filepath + """ + return self.get_input(inp="diffuse_texture").resolvedPath + + @property + def albedo_add(self): + """ + Returns: + float: this material's applied albedo_add + """ + return self.get_input(inp="albedo_add") + + @albedo_add.setter + def albedo_add(self, add): + """ + Args: + add (float): this material's applied albedo_add + """ + self.set_input(inp="albedo_add", val=add) + + @property + def diffuse_tint(self): + """ + Returns: + 3-array: this material's applied (R,G,B) diffuse_tint + """ + diffuse_tint = self.get_input(inp="diffuse_tint") + return th.tensor(diffuse_tint, dtype=th.float32) if diffuse_tint is not None else None + + @diffuse_tint.setter + def diffuse_tint(self, color): + """ + Args: + color (3-array): this material's applied (R,G,B) diffuse_tint + """ + self.set_input(inp="diffuse_tint", val=lazy.pxr.Gf.Vec3f(*color.tolist())) + + @property + def average_diffuse_color(self): + """ + Returns: + 3-array: this material's average diffuse color. + """ + return cv2.imread(self.diffuse_texture).mean(axis=(0, 1)) + + def enable_highlight(self, highlight_color, highlight_intensity): + """ + Enables highlight for this material with the specified color and intensity. + + Args: + highlight_color (3-array): Color of the highlight in (R,G,B) + highlight_intensity (float): Intensity of the highlight + """ + # Set emissive properties to enable highlight + self.set_input(inp="emission_color", val=lazy.pxr.Gf.Vec3f(*highlight_color)) + self.set_input(inp="emission_intensity", val=highlight_intensity) + + def disable_highlight(self): + self.set_input(inp="emission_color", val=lazy.pxr.Gf.Vec3f(0, 0, 0)) + self.set_input(inp="emission_intensity", val=0.0) + + +class OmniGlassMaterialPrim(MaterialPrim): + """ + A MaterialPrim that uses the OmniGlass material preset. + """ + + @classmethod + def supports_material(cls, asset_path, asset_sub_identifier): + return asset_path.endswith("OmniGlass.mdl") and asset_sub_identifier == "OmniGlass" + + @property + def mdl_name(self): + return "OmniGlass.mdl" + + @property + def mtl_name(self): + return "OmniGlass" + + @property + def color(self): + """ + Returns: + 3-array: this material's applied (R,G,B) glass color (only applicable to OmniGlass materials) + """ + glass_color = self.get_input(inp="glass_color") + return th.tensor(glass_color, dtype=th.float32) if glass_color is not None else None + + @color.setter + def color(self, color): + """ + Args: + color (3-array): this material's applied (R,G,B) glass color (only applicable to OmniGlass materials) + """ + self.set_input(inp="glass_color", val=lazy.pxr.Gf.Vec3f(*color)) + + @property + def average_diffuse_color(self): + """ + Returns: + 3-array: this material's average diffuse color - we pretend this is the same as the glass color. + """ + return self.color + + +class OmniSurfaceMaterialPrim(MaterialPrim): + """ + A MaterialPrim that uses the OmniSurface material preset. + """ + + def __init__(self, relative_prim_path, name, preset_name, load_config=None): + """ + Args: + relative_prim_path (str): Scene-local prim path of the Prim to encapsulate or create. + name (str): Name for the object. Names need to be unique per scene. + preset_name (str): Name of the preset to use for this material. If None, defaults to "OmniSurface". + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. Note that this is only needed if the prim does not already exist at + @relative_prim_path -- it will be ignored if it already exists. + """ + self.preset_name = preset_name + super().__init__(relative_prim_path=relative_prim_path, name=name, load_config=load_config) + + @classmethod + def supports_material(cls, asset_path, asset_sub_identifier): + return (asset_path.endswith("OmniSurface.mdl") and asset_sub_identifier == "OmniSurface") or ( + asset_path.endswith("OmniSurfacePresets.mdl") and asset_sub_identifier.startswith("OmniSurface_") + ) + + @property + def mdl_name(self): + return "OmniSurfacePresets.mdl" if self.preset_name else "OmniSurface.mdl" + + @property + def mtl_name(self): + return f"OmniSurface_{self.preset_name}" if self.preset_name else "OmniSurface" + + @property + def diffuse_reflection_weight(self): + """ + Returns: + float: this material's applied diffuse_reflection_weight + """ + return self.get_input(inp="diffuse_reflection_weight") + + @diffuse_reflection_weight.setter + def diffuse_reflection_weight(self, weight): + """ + Args: + weight (float): this material's applied diffuse_reflection_weight + """ + self.set_input(inp="diffuse_reflection_weight", val=weight) + + @property + def enable_specular_transmission(self): + """ + Returns: + bool: this material's applied enable_specular_transmission + """ + return self.get_input(inp="enable_specular_transmission") + + @enable_specular_transmission.setter + def enable_specular_transmission(self, enabled): + """ + Args: + enabled (bool): this material's applied enable_specular_transmission + """ + self.set_input(inp="enable_specular_transmission", val=enabled) + + @property + def specular_transmission_weight(self): + """ + Returns: + float: this material's applied specular_transmission_weight + """ + return self.get_input(inp="specular_transmission_weight") + + @specular_transmission_weight.setter + def specular_transmission_weight(self, weight): + """ + Args: + weight (float): this material's applied specular_transmission_weight + """ + self.set_input(inp="specular_transmission_weight", val=weight) + + @property + def diffuse_reflection_color(self): + """ + Returns: + 3-array: this material's diffuse_reflection_color in (R,G,B) + """ + diffuse_reflection_color = self.get_input(inp="diffuse_reflection_color") + return th.tensor(diffuse_reflection_color, dtype=th.float32) if diffuse_reflection_color is not None else None + + @diffuse_reflection_color.setter + def diffuse_reflection_color(self, color): + """ + Args: + color (3-array): this material's diffuse_reflection_color in (R,G,B) + """ + self.set_input(inp="diffuse_reflection_color", val=lazy.pxr.Gf.Vec3f(*color)) + + @property + def specular_transmission_color(self): + """ + Returns: + 3-array: this material's specular_transmission_color in (R,G,B) + """ + specular_transmission_color = self.get_input(inp="specular_transmission_color") + return th.tensor(specular_transmission_color, dtype=th.float32) + + @specular_transmission_color.setter + def specular_transmission_color(self, color): + """ + Args: + color (3-array): this material's specular_transmission_color in (R,G,B) + """ + self.set_input(inp="specular_transmission_color", val=lazy.pxr.Gf.Vec3f(*color)) + + @property + def specular_transmission_scattering_color(self): + """ + Returns: + 3-array: this material's specular_transmission_scattering_color in (R,G,B) + """ + specular_transmission_scattering_color = self.get_input(inp="specular_transmission_scattering_color") + return th.tensor(specular_transmission_scattering_color, dtype=th.float32) + + @specular_transmission_scattering_color.setter + def specular_transmission_scattering_color(self, color): + """ + Args: + color (3-array): this material's specular_transmission_scattering_color in (R,G,B) + """ + self.set_input(inp="specular_transmission_scattering_color", val=lazy.pxr.Gf.Vec3f(*color)) + + @property + def average_diffuse_color(self): + base_color_weight = self.diffuse_reflection_weight + transmission_weight = self.enable_specular_transmission * self.specular_transmission_weight + total_weight = base_color_weight + transmission_weight + + # If the fluid doesn't have any color, we add a "blue" tint by default + if total_weight == 0.0: + return th.tensor([0.0, 0.0, 1.0]) + + base_color_weight /= total_weight + transmission_weight /= total_weight + # Weighted sum of base color and transmission color + return base_color_weight * self.diffuse_reflection_color + transmission_weight * ( + 0.5 * self.specular_transmission_color + 0.5 * self.specular_transmission_scattering_color + ) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/prim_base.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/prim_base.py new file mode 100644 index 0000000000000000000000000000000000000000..fdceaff157be7b6edbda55ff0c4a501dff814875 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/prim_base.py @@ -0,0 +1,327 @@ +import string +from abc import ABC + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.utils.python_utils import Recreatable, Serializable +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import ( + delete_or_deactivate_prim, + scene_relative_prim_path_to_absolute, + get_sdf_value_type_name, + activate_prim_and_children, +) + +# Create module logger +log = create_module_logger(module_name=__name__) + + +class BasePrim(Serializable, Recreatable, ABC): + """ + Provides high level functions to deal with a basic prim and its attributes/ properties. + If there is an Xform prim present at the path, it will use it. Otherwise, a new XForm prim at + the specified prim path will be created. + + Note: the prim will have "xformOp:orient", "xformOp:translate" and "xformOp:scale" only post init, + unless it is a non-root articulation link. + + Args: + relative_prim_path (str): Scene-local prim path of the Prim to encapsulate or create. + name (str): Name for the object. Names need to be unique per scene. + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. Note that this is only needed if the prim does not already exist at + @relative_prim_path -- it will be ignored if it already exists. Subclasses should define the exact keys expected + for their class. + """ + + def __init__( + self, + relative_prim_path, + name, + load_config=None, + ): + self._relative_prim_path = relative_prim_path + assert relative_prim_path.startswith("/"), f"Relative prim path {relative_prim_path} must start with a '/'!" + assert all( + component[0] in string.ascii_letters for component in relative_prim_path[1:].split("/") + ), f"Each component of relative prim path {relative_prim_path} must start with a letter!" + + self._name = name + self._load_config = dict() if load_config is None else load_config + + # Other values that will be filled in at runtime + self._scene = None + self._scene_assigned = False + self._applied_visual_material = None + self._loaded = False # Whether this prim exists in the stage or not + self._initialized = False # Whether this prim has its internal handles / info initialized or not (occurs AFTER and INDEPENDENTLY from loading!) + self._prim = None + self._n_duplicates = 0 # Simple counter for keeping track of duplicates for unique name indexing + + # Check if this prim was created manually. This member will be automatically set for prims + # that get created during the _load phase of this class, but sometimes we create prims using + # alternative methods and then create this class - in that case too we need to make sure we + # add the right xform properties, so callers will just pass in the created manually flag. + self._xform_props_pre_loaded = self._load_config.get("xform_props_pre_loaded", False) + # Run super init + super().__init__() + + def _initialize(self): + """ + Initializes state of this object and sets up any references necessary post-loading. Should be implemented by + sub-class for extended utility + """ + pass + + def initialize(self): + """ + Initializes state of this object and sets up any references necessary post-loading. Subclasses should + implement / extend the _initialize() method. + """ + assert ( + not self._initialized + ), f"Prim {self.name} at prim_path {self.prim_path} can only be initialized once! (It is already initialized)" + self._initialize() + + self._initialized = True + + # Cache state size (note that we are doing this after initialized is set to True because + # dump_state asserts that the prim is initialized for some prims). + self._state_size = len(self.dump_state(serialized=True)) + + def load(self, scene): + """ + Load this prim into omniverse, and return loaded prim reference. + + Returns: + Usd.Prim: Prim object loaded into the simulator + """ + # Load the prim if it doesn't exist yet. + assert ( + not self._loaded + ), f"Prim {self.name} at prim_path {self.prim_path} can only be loaded once! (It is already loaded)" + + # Assign the scene first. + self._scene = scene + self._scene_assigned = True + + # Check if the prim path exists in the stage + if lazy.isaacsim.core.utils.prims.is_prim_path_valid(prim_path=self.prim_path): + existing_prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(prim_path=self.prim_path) + + # Note: A prim path can be valid but the prim itself may be inactive. + # This commonly occurs after transition rules when scene prims get deleted - + # the prim paths remain valid but the prims become inactive. + # In such cases, we need to activate the prim to make it usable again. + if not existing_prim.IsActive(): + log.debug(f"Prim '{self.name}' exists but is inactive/invalid, activating it") + # Recursively find all prims under it, even those that are deactivated + activate_prim_and_children(self.prim_path) + self._prim = existing_prim + else: + # Prim path doesn't exist - load it for the first time + log.debug(f"Prim '{self.name}' doesn't exist, loading") + self._prim = self._load() + + # Mark the prim as loaded. + self._loaded = True + + # Run any post-loading logic + self._post_load() + + return self._prim + + def _post_load(self): + """ + Any actions that should be taken (e.g.: modifying the object's properties such as scale, visibility, additional + joints, etc.) that should be taken after loading the raw object into omniverse but BEFORE we initialize the + object and grab its handles and internal references. By default, this is a no-op. + """ + pass + + def remove(self): + """ + Removes this prim from omniverse stage. + """ + if not self._loaded: + raise ValueError("Cannot remove a prim that was never loaded.") + + # Remove or deactivate prim if it's possible + if not delete_or_deactivate_prim(self.prim_path): + log.warning(f"Prim {self.name} at prim_path {self.prim_path} could not be deleted or deactivated.") + + def _load(self): + """ + Loads the raw prim into the simulator. Any post-processing should be done in @self._post_load() + """ + raise NotImplementedError() + + @property + def loaded(self): + return self._loaded + + @property + def initialized(self): + return self._initialized + + @property + def scene(self): + """ + Returns: + Scene or None: Scene object that this prim is loaded into + """ + assert self._scene_assigned, "Scene has not been assigned to this prim yet!" + return self._scene + + @property + def state_size(self): + # This is the cached value + return self._state_size + + @property + def relative_prim_path(self): + """ + Returns: + str: scene-relative prim path (e.g. /robot_0/base_link), identical across all scenes + in a VectorEnvironment. + """ + return self._relative_prim_path + + @property + def prim_path(self): + """ + Returns: + str: prim path in the stage. + """ + return scene_relative_prim_path_to_absolute(self.scene, self._relative_prim_path) + + @property + def name(self): + """ + Returns: + str: unique name assigned to this prim + """ + return self._name + + @property + def prim(self): + """ + Returns: + Usd.Prim: USD Prim object that this object holds. + """ + return self._prim + + @property + def property_names(self): + """ + Returns: + set of str: Set of property names that this prim has (e.g.: visibility, proxyPrim, etc.) + """ + return set(self._prim.GetPropertyNames()) + + @property + def visible(self): + """ + Returns: + bool: true if the prim is visible in stage. false otherwise. + """ + return ( + lazy.pxr.UsdGeom.Imageable(self.prim).ComputeVisibility(lazy.pxr.Usd.TimeCode.Default()) + != lazy.pxr.UsdGeom.Tokens.invisible + ) + + @visible.setter + def visible(self, visible): + """ + Sets the visibility of the prim in stage. + + Args: + visible (bool): flag to set the visibility of the usd prim in stage. + """ + with og.sim.editing_usd(): + imageable = lazy.pxr.UsdGeom.Imageable(self.prim) + if visible: + imageable.MakeVisible() + else: + imageable.MakeInvisible() + + def is_valid(self): + """ + Returns: + bool: True is the current prim path corresponds to a valid prim in stage. False otherwise. + """ + return lazy.isaacsim.core.utils.prims.is_prim_path_valid(self.prim_path) + + def is_attribute_valid(self, attr): + """ + Check if the attribute is valid for this prim. + + Args: + attr (str): Attribute to check + + Returns: + bool: True if the attribute is valid for this prim. False otherwise. + """ + return self._prim.GetAttribute(attr).IsValid() + + def get_attribute(self, attr): + """ + Get this prim's attribute. Should be a valid attribute under self._prim.GetAttributes() + + Returns: + any: value of the requested @attribute + """ + return self._prim.GetAttribute(attr).Get() + + def set_attribute(self, attr, val): + """ + Set this prim's attribute. Should be a valid attribute under self._prim.GetAttributes() + + Args: + attr (str): Attribute to set + val (any): Value to set for the attribute. This should be the valid type for that attribute. + """ + with og.sim.editing_usd(): + self._prim.GetAttribute(attr).Set(val) + + def create_attribute(self, attr, val): + """ + Create a new attribute for this prim. Should be a valid attribute under self._prim.GetAttributes() + + Args: + attr (str): Attribute to create + val (any): Value to set for the attribute. This should be the valid type for that attribute. + """ + with og.sim.editing_usd(): + self._prim.CreateAttribute(attr, get_sdf_value_type_name(val)) + + def get_property(self, prop): + """ + Sets property @prop with value @val + + Args: + prop (str): Name of the property to get. See Raw USD Properties in the GUI for examples of property names + + Returns: + any: Property value + """ + self._prim.GetProperty(prop).Get() + + def set_property(self, prop, val): + """ + Sets property @prop with value @val + + Args: + prop (str): Name of the property to set. See Raw USD Properties in the GUI for examples of property names + val (any): Value to set for the property. Should be valid for that property + """ + self._prim.GetProperty(prop).Set(val) + + def get_custom_data(self): + """ + Get custom data associated with this prim + + Returns: + dict: Dictionary of any custom information + """ + return self._prim.GetCustomData() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/rigid_dynamic_prim.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/rigid_dynamic_prim.py new file mode 100644 index 0000000000000000000000000000000000000000..ab0b6dfee5c36ef49ab589576c99b44770c39345 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/rigid_dynamic_prim.py @@ -0,0 +1,423 @@ +import math +from typing import Literal + +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy + +from .rigid_prim import RigidPrim + + +class RigidDynamicPrim(RigidPrim): + """ + Provides high level functions to deal with a dynamic rigid body prim and its attributes/properties. + This class is used for rigid bodies that are not kinematic-only, meaning they are subject to physics simulation + dynamics like gravity, forces, and collisions. + + Args: + relative_prim_path (str): Scene-local prim path of the Prim to encapsulate or create. + name (str): Name for the object. Names need to be unique per scene. + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. + """ + + def __init__( + self, + relative_prim_path, + name, + load_config=None, + ): + # Set up rigid body view which will be filled in later + self._rigid_prim_view = None + + # Run super init + super().__init__( + relative_prim_path=relative_prim_path, + name=name, + load_config=load_config, + ) + + def _post_load(self): + # Make sure it's set to be a rigid body (not kinematic) + if not self.is_attribute_valid("physics:kinematicEnabled"): + self.create_attribute("physics:kinematicEnabled", False) + if not self.is_attribute_valid("physics:rigidBodyEnabled"): + self.create_attribute("physics:rigidBodyEnabled", True) + self.set_attribute("physics:kinematicEnabled", False) + self.set_attribute("physics:rigidBodyEnabled", True) + + # Create the rigid prim view + # Import now to avoid too-eager load of Omni classes due to inheritance + from omnigibson.utils.deprecated_utils import RigidPrimView + + # set reset_xform_properties to False for load time + with og.sim.editing_usd(): + self._rigid_prim_view = RigidPrimView(self.prim_path, reset_xform_properties=False) + + # Run super method to handle common functionality + super()._post_load() + + def update_handles(self): + """ + Updates all internal handles for this prim, in case they change since initialization + """ + # Validate that the view is valid if physics is running + if og.sim.is_playing() and self.initialized: + assert ( + self._rigid_prim_view.is_physics_handle_valid() and self._rigid_prim_view._physics_view.check() + ), "Rigid prim view must be valid if physics is running!" + + assert not ( + og.sim.is_playing() and not self._rigid_prim_view.is_valid + ), "Rigid prim view must be valid if physics is running!" + + self._rigid_prim_view.initialize(og.sim.physics_sim_view) + + def set_linear_velocity(self, velocity): + """ + Sets the linear velocity of the prim in stage. + + Args: + velocity (th.tensor): linear velocity to set the rigid prim to. Shape (3,). + """ + with og.sim.editing_usd(): + self._rigid_prim_view.set_linear_velocities(velocity[None, :]) + + def get_linear_velocity(self, clone=True): + """ + Args: + clone (bool): Whether to clone the internal buffer or not when grabbing data + + Returns: + th.tensor: current linear velocity of the the rigid prim. Shape (3,). + """ + return self._rigid_prim_view.get_linear_velocities(clone=clone)[0] + + def set_angular_velocity(self, velocity): + """ + Sets the angular velocity of the prim in stage. + + Args: + velocity (th.tensor): angular velocity to set the rigid prim to. Shape (3,). + """ + with og.sim.editing_usd(): + self._rigid_prim_view.set_angular_velocities(velocity[None, :]) + + def get_angular_velocity(self, clone=True): + """ + Args: + clone (bool): Whether to clone the internal buffer or not when grabbing data + + Returns: + th.tensor: current angular velocity of the the rigid prim. Shape (3,). + """ + return self._rigid_prim_view.get_angular_velocities(clone=clone)[0] + + def set_position_orientation(self, position=None, orientation=None, frame: Literal["world", "scene"] = "world"): + """ + Set the position and orientation of the dynamic rigid body. + + Args: + position (None or 3-array): The position to set the object to. If None, the position is not changed. + orientation (None or 4-array): The orientation to set the object to. If None, the orientation is not changed. + frame (Literal): The frame in which to set the position and orientation. Defaults to world. + Scene frame sets position relative to the scene. + """ + assert frame in ["world", "scene"], f"Invalid frame '{frame}'. Must be 'world' or 'scene'." + + # If the simulation is stopped, we can just use the XFormPrim implementation directly. This is slower than + # the PhysX-based implementation, but the PhysX implementation is not available when the simulation is stopped. + if og.sim.is_stopped(): + return super().set_position_orientation(position=position, orientation=orientation, frame=frame) + + # If no position or no orientation are given, get the current position and orientation of the object + if position is None or orientation is None: + current_position, current_orientation = self.get_position_orientation(frame=frame) + position = current_position if position is None else position + orientation = current_orientation if orientation is None else orientation + + # Convert to th.Tensor if necessary + position = th.as_tensor(position, dtype=th.float32) + orientation = th.as_tensor(orientation, dtype=th.float32) + + # Assert validity of the orientation + assert math.isclose( + th.norm(orientation).item(), 1, abs_tol=1e-3 + ), f"{self.prim_path} desired orientation {orientation} is not a unit quaternion." + + # Convert to from scene-relative to world if necessary + if frame == "scene": + assert self.scene is not None, "cannot set position and orientation relative to scene without a scene" + position, orientation = self.scene.convert_scene_relative_pose_to_world(position, orientation) + + assert ( + self._rigid_prim_view.is_physics_handle_valid() + ), "Unexpected: rigid prim view is not valid while simulation is playing." + self._rigid_prim_view.set_world_poses(positions=position[None, :], orientations=orientation[None, [3, 0, 1, 2]]) + og.sim.sync_physx_to_fabric() + + # Tensorized state caches (AABB / Touching / Adjacency / ...) read from pose tensors + # that are now one frame behind. Flag them as stale so the next state read forces a + # refresh via the lazy-refresh gate in TensorizedState._get_value. + from omnigibson.object_states.tensorized_state import TensorizedState + + TensorizedState.caches_dirty = True + + def get_position_orientation(self, frame: Literal["world", "scene"] = "world", clone=True): + """ + Gets prim's pose with respect to the specified frame. + + Args: + frame (Literal): frame to get the pose with respect to. Default to world. + scene frame gets position relative to the scene. + clone (bool): Whether to clone the internal buffer or not when grabbing data + + Returns: + 2-tuple: + - th.Tensor: (x,y,z) position in the specified frame + - th.Tensor: (x,y,z,w) quaternion orientation in the specified frame + """ + assert frame in ["world", "scene"], f"Invalid frame '{frame}'. Must be 'world', or 'scene'." + + # Get the pose from the rigid prim view and convert to our format + positions, orientations = self._rigid_prim_view.get_world_poses(clone=clone) + position = positions[0] + orientation = orientations[0][[1, 2, 3, 0]] # Convert from (w,x,y,z) to (x,y,z,w) + + # Assert that the orientation is a unit quaternion + assert math.isclose( + th.norm(orientation).item(), 1, abs_tol=1e-3 + ), f"{self.prim_path} orientation {orientation} is not a unit quaternion." + + # If requested, compute the scene-local transform + if frame == "scene": + assert self.scene is not None, "Cannot get position and orientation relative to scene without a scene" + position, orientation = self.scene.convert_world_pose_to_scene_relative(position, orientation) + + return position, orientation + + @property + def center_of_mass(self): + """ + Returns: + th.Tensor: (x,y,z) position of link CoM in the link frame + """ + positions, orientations = self._rigid_prim_view.get_coms(clone=True) + position = positions[0][0] + return position + + @center_of_mass.setter + def center_of_mass(self, com): + """ + Args: + com (th.Tensor): (x,y,z) position of link CoM in the link frame + """ + with og.sim.editing_usd(): + self._rigid_prim_view.set_coms(positions=com.reshape(1, 1, 3)) + + @property + def mass(self): + """ + Returns: + float: mass of the rigid body in kg. + """ + mass = self._rigid_prim_view.get_masses()[0] + + # Fallback to analytical computation of volume * density + if mass == 0: + return self.volume * self.density + + return mass + + @mass.setter + def mass(self, mass): + """ + Args: + mass (float): mass of the rigid body in kg. + """ + with og.sim.editing_usd(): + self._rigid_prim_view.set_masses(th.tensor([mass])) + + @property + def density(self): + """ + Returns: + float: density of the rigid body in kg / m^3. + """ + mass = self._rigid_prim_view.get_masses()[0] + # We first check if the mass is specified, since mass overrides density. If so, density = mass / volume. + # Otherwise, we try to directly grab the raw usd density value, and if that value does not exist, + # we return 1000 since that is the canonical density assigned by omniverse + if mass != 0.0: + density = mass / self.volume + else: + density = self._rigid_prim_view.get_densities()[0] + if density == 0.0: + density = 1000.0 + + return density + + @density.setter + def density(self, density): + """ + Args: + density (float): density of the rigid body in kg / m^3. + """ + with og.sim.editing_usd(): + self._rigid_prim_view.set_densities(th.tensor([density])) + + @property + def is_asleep(self): + """ + Returns: + bool: whether this rigid prim is asleep or not + """ + return og.sim.psi.is_sleeping(og.sim.stage_id, lazy.pxr.PhysicsSchemaTools.sdfPathToInt(self.prim_path)) + + def enable_gravity(self): + """ + Enables gravity for this rigid body + """ + with og.sim.editing_usd(): + self._rigid_prim_view.enable_gravities() + + def disable_gravity(self): + """ + Disables gravity for this rigid body + """ + with og.sim.editing_usd(): + self._rigid_prim_view.disable_gravities() + + def wake(self): + """ + Enable physics for this rigid body + """ + prim_id = lazy.pxr.PhysicsSchemaTools.sdfPathToInt(self.prim_path) + og.sim.psi.wake_up(og.sim.stage_id, prim_id) + + def sleep(self): + """ + Disable physics for this rigid body + """ + prim_id = lazy.pxr.PhysicsSchemaTools.sdfPathToInt(self.prim_path) + og.sim.psi.put_to_sleep(og.sim.stage_id, prim_id) + + @property + def stabilization_threshold(self): + """ + Returns: + float: threshold for stabilizing this rigid body + """ + return self.get_attribute("physxRigidBody:stabilizationThreshold") + + @stabilization_threshold.setter + def stabilization_threshold(self, threshold): + """ + Sets threshold for stabilizing this rigid body + + Args: + threshold (float): stabilizing threshold + """ + self.set_attribute("physxRigidBody:stabilizationThreshold", threshold) + + @property + def sleep_threshold(self): + """ + Returns: + float: threshold for sleeping this rigid body + """ + return self.get_attribute("physxRigidBody:sleepThreshold") + + @sleep_threshold.setter + def sleep_threshold(self, threshold): + """ + Sets threshold for sleeping this rigid body + + Args: + threshold (float): Sleeping threshold + """ + self.set_attribute("physxRigidBody:sleepThreshold", threshold) + + @property + def solver_position_iteration_count(self): + """ + Returns: + int: How many position iterations to take per physics step by the physx solver + """ + return self.get_attribute("physxRigidBody:solverPositionIterationCount") + + @solver_position_iteration_count.setter + def solver_position_iteration_count(self, count): + """ + Sets how many position iterations to take per physics step by the physx solver + + Args: + count (int): How many position iterations to take per physics step by the physx solver + """ + self.set_attribute("physxRigidBody:solverPositionIterationCount", count) + + @property + def solver_velocity_iteration_count(self): + """ + Returns: + int: How many velocity iterations to take per physics step by the physx solver + """ + return self.get_attribute("physxRigidBody:solverVelocityIterationCount") + + @solver_velocity_iteration_count.setter + def solver_velocity_iteration_count(self, count): + """ + Sets how many velocity iterations to take per physics step by the physx solver + + Args: + count (int): How many velocity iterations to take per physics step by the physx solver + """ + self.set_attribute("physxRigidBody:solverVelocityIterationCount", count) + + def _dump_state(self): + # Grab pose from super class + state = super()._dump_state() + + state["lin_vel"] = self.get_linear_velocity(clone=False) + state["ang_vel"] = self.get_angular_velocity(clone=False) + + return state + + def _load_state(self, state): + # If we are part of an articulation, there's nothing to do, the entityprim will take care + # of setting everything for us. + if self._belongs_to_articulation: + return + + # Call super first + super()._load_state(state=state) + + # Set velocities + self.set_linear_velocity( + state["lin_vel"] if isinstance(state["lin_vel"], th.Tensor) else th.tensor(state["lin_vel"]) + ) + self.set_angular_velocity( + state["ang_vel"] if isinstance(state["ang_vel"], th.Tensor) else th.tensor(state["ang_vel"]) + ) + + def serialize(self, state): + # Run super first + state_flat = super().serialize(state=state) + + return th.cat( + [ + state_flat, + state["lin_vel"], + state["ang_vel"], + ] + ) + + def deserialize(self, state): + # Call supermethod first + state_dic, idx = super().deserialize(state=state) + # We deserialize deterministically by knowing the order of values -- lin_vel, ang_vel + state_dic["lin_vel"] = state[idx : idx + 3] + state_dic["ang_vel"] = state[idx + 3 : idx + 6] + + return state_dic, idx + 6 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/rigid_kinematic_prim.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/rigid_kinematic_prim.py new file mode 100644 index 0000000000000000000000000000000000000000..bdf38ad1744c16b60ecde4fd1be89d8b4be84639 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/rigid_kinematic_prim.py @@ -0,0 +1,124 @@ +from typing import Literal + +import torch as th + +from omnigibson.utils.usd_utils import RigidBodyViewAPI + +from .rigid_prim import RigidPrim + + +class RigidKinematicPrim(RigidPrim): + """ + Provides high level functions to deal with a kinematic-only rigid prim and its attributes/properties. + A kinematic-only object is not subject to simulator dynamics, and remains fixed unless the user + explicitly sets the body's pose / velocities. + + Args: + relative_prim_path (str): Scene-local prim path of the Prim to encapsulate or create. + name (str): Name for the object. Names need to be unique per scene. + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. + """ + + def __init__( + self, + relative_prim_path, + name, + load_config=None, + ): + super().__init__( + relative_prim_path=relative_prim_path, + name=name, + load_config=load_config, + ) + + def _post_load(self): + # Make sure it's set to be kinematic + if not self.is_attribute_valid("physics:kinematicEnabled"): + self.create_attribute("physics:kinematicEnabled", True) + if not self.is_attribute_valid("physics:rigidBodyEnabled"): + self.create_attribute("physics:rigidBodyEnabled", False) + self.set_attribute("physics:kinematicEnabled", True) + self.set_attribute("physics:rigidBodyEnabled", False) + + # Run super method to handle common functionality + super()._post_load() + + def set_position_orientation(self, position=None, orientation=None, frame: Literal["world", "scene"] = "world"): + """ + Set the position and orientation of the kinematic rigid body. + + Args: + position (None or 3-array): The position to set the object to. If None, the position is not changed. + orientation (None or 4-array): The orientation to set the object to. If None, the orientation is not changed. + frame (Literal): The frame in which to set the position and orientation. Defaults to world. + Scene frame sets position relative to the scene. + """ + super().set_position_orientation(position=position, orientation=orientation, frame=frame) + + RigidBodyViewAPI.invalidate_kinematic([self]) + + # The following methods implement the same interface as RigidDynamicPrim, but as no-op + # versions for kinematic-only prims. This allows code to call these methods on any RigidPrim + # without type checking, while maintaining proper physics behavior based on the actual + # runtime type (dynamic vs. kinematic). + + @property + def center_of_mass(self): + """ + Returns: + th.Tensor: (x,y,z) position of link CoM in the link frame + """ + return th.zeros(3) + + @center_of_mass.setter + def center_of_mass(self, com): + """ + Args: + com (th.Tensor): (x,y,z) position of link CoM in the link frame + """ + pass + + @property + def mass(self): + """ + Returns: + float: mass of the rigid body in kg. + """ + return 0.0 + + @mass.setter + def mass(self, _): + """ + Args: + mass (float): mass of the rigid body in kg. + """ + pass + + @property + def density(self): + """ + Returns: + float: density of the rigid body in kg / m^3. + """ + return 0.0 + + @density.setter + def density(self, _): + """ + Args: + density (float): density of the rigid body in kg / m^3. + """ + pass + + def enable_gravity(self): + """ + Enables gravity for this rigid body + """ + pass + + def disable_gravity(self): + """ + Disables gravity for this rigid body + """ + pass diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/rigid_prim.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/rigid_prim.py new file mode 100644 index 0000000000000000000000000000000000000000..7cdc0ac569f99dfd91c3f724e1a727688046e515 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/rigid_prim.py @@ -0,0 +1,702 @@ +from functools import cached_property +import re +import math + +import torch as th +from scipy.spatial import ConvexHull + +import omnigibson as og +from omnigibson.macros import gm +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros +from omnigibson.prims.geom_prim import GeomPrim +from omnigibson.prims.xform_prim import XFormPrim +from omnigibson.utils.constants import GEOM_TYPES +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import ( + absolute_prim_path_to_scene_relative, + apply_collision_approximation, + check_extent_radius_ratio, + ensure_usd_api, + get_mesh_volume_and_com, +) + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.DEFAULT_CONTACT_OFFSET = 0.001 +m.DEFAULT_REST_OFFSET = 0.0 +m.LEGACY_META_LINK_PATTERN = re.compile(r".*:(\w+)_([A-Za-z0-9]+)_(\d+)_link") + + +class RigidPrim(XFormPrim): + """ + Base class that provides common functionality for all rigid prim types. + This serves as the parent class for RigidDynamicPrim and RigidKinematicPrim. + + Provides high level functions to deal with a rigid body prim and its attributes/properties. + If there is a prim present at the path, it will use it. Otherwise, a new XForm prim at + the specified prim path will be created. + + Args: + relative_prim_path (str): Scene-local prim path of the Prim to encapsulate or create. + name (str): Name for the object. Names need to be unique per scene. + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. Note that this is only needed if the prim does not already exist at + @relative_prim_path -- it will be ignored if it already exists. For this joint prim, the below values can be + specified: + + scale (None or float or 3-array): If specified, sets the scale for this object. A single number corresponds + to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. + mass (None or float): If specified, mass of this body in kg + density (None or float): If specified, density of this body in kg / m^3 + visual_only (None or bool): If specified, whether this prim should include collisions or not. + Default is True. + """ + + def __init__( + self, + relative_prim_path, + name, + load_config=None, + ): + # Common values that will be used by both kinematic and dynamic rigid prims + self._body_name = None + self._visual_only = None + self._collision_meshes = None + self._visual_meshes = None + self._belongs_to_articulation = None + + # Collision API references collected from the prim hierarchy (not 1:1 with meshes). + # A single CollisionAPI on a scope prim may cover multiple geom prims. + self._collision_apis = None # list of UsdPhysics.CollisionAPI + self._physx_collision_apis = None # list of PhysxSchema.PhysxCollisionAPI + self._mesh_collision_apis = None # list of (USD prim, UsdPhysics.MeshCollisionAPI) + + # Run super init + super().__init__( + relative_prim_path=relative_prim_path, + name=name, + load_config=load_config, + ) + + def _post_load(self): + # Run super first + super()._post_load() + + # Apply rigid body and mass APIs + ensure_usd_api(self._prim, lazy.pxr.UsdPhysics.RigidBodyAPI) + ensure_usd_api(self._prim, lazy.pxr.PhysxSchema.PhysxRigidBodyAPI) + ensure_usd_api(self._prim, lazy.pxr.UsdPhysics.MassAPI) + + # Check if it's part of an articulation view + self._belongs_to_articulation = ( + "belongs_to_articulation" in self._load_config and self._load_config["belongs_to_articulation"] + ) + + # Only create contact report api if we're not visual only + self._visual_only = ( + self._load_config["visual_only"] + if "visual_only" in self._load_config and self._load_config["visual_only"] is not None + else False + ) + + if not self._visual_only: + contact_api = ensure_usd_api(self._prim, lazy.pxr.PhysxSchema.PhysxContactReportAPI) + with og.sim.editing_usd(): + contact_api.GetThresholdAttr().Set(0.0) + + # Store references to owned visual / collision meshes + # We iterate over all children of this object's prim, + # and grab any that are presumed to be meshes + self.update_meshes() + + # Possibly set the mass / density + if not self.has_collision_meshes: + # A meta (virtual) link has no collision meshes; set a negligible mass and a zero density (ignored) + self.mass = 1e-6 + self.density = 0.0 + elif "mass" in self._load_config and self._load_config["mass"] is not None: + self.mass = self._load_config["mass"] + if "density" in self._load_config and self._load_config["density"] is not None: + self.density = self._load_config["density"] + + # Set the visual-only attribute + # This automatically handles setting collisions / gravity appropriately + self.visual_only = self._visual_only or gm.VISUAL_ONLY + + def _initialize(self): + # Run super method first + super()._initialize() + + # Initialize all owned meshes + for mesh_group in (self._collision_meshes, self._visual_meshes): + for mesh in mesh_group.values(): + mesh.initialize() + + # Grab handle to this rigid body and get name + self.update_handles() + self._body_name = self.prim_path.split("/")[-1] + + def remove(self): + # First remove the meshes + if self._collision_meshes is not None: + for collision_mesh in self._collision_meshes.values(): + collision_mesh.remove() + + # Make sure to clean up all pre-existing names for all visual_meshes + if self._visual_meshes is not None: + for visual_mesh in self._visual_meshes.values(): + visual_mesh.remove() + + # Then self + super().remove() + + def update_meshes(self): + """ + Helper function to refresh owned visual and collision meshes. Useful for synchronizing internal data if + additional bodies are added manually. + + Collision vs. visual meshes are distinguished at the link level based on whether the geom prim + appears as or under a prim that already has a UsdPhysics.CollisionAPI or PhysxSchema.PhysxCollisionAPI. + The existing API references are collected into flat lists during traversal -- a single CollisionAPI + on a scope prim may cover multiple geom prims underneath it, so the API lists are not 1:1 with meshes. + """ + self._collision_meshes, self._visual_meshes = dict(), dict() + self._collision_apis = [] + self._physx_collision_apis = [] + self._mesh_collision_apis = [] + + # Recursively find all geom prims, collecting collision API references into + # the link-level lists as they are encountered during descent. + geom_prims = [] + + def _find_geom_prims(prim, is_collision=False): + # If this prim has collision APIs, add them to the link-level lists + if prim.HasAPI(lazy.pxr.UsdPhysics.CollisionAPI): + self._collision_apis.append(lazy.pxr.UsdPhysics.CollisionAPI(prim)) + is_collision = True + if prim.HasAPI(lazy.pxr.PhysxSchema.PhysxCollisionAPI): + self._physx_collision_apis.append(lazy.pxr.PhysxSchema.PhysxCollisionAPI(prim)) + is_collision = True + + if prim.GetPrimTypeInfo().GetTypeName() in GEOM_TYPES: + # MeshCollisionAPI is inherently per-geom-prim; store alongside prim reference + if prim.HasAPI(lazy.pxr.UsdPhysics.MeshCollisionAPI): + self._mesh_collision_apis.append((prim, lazy.pxr.UsdPhysics.MeshCollisionAPI(prim))) + geom_prims.append((prim, is_collision)) + + for child in prim.GetChildren(): + _find_geom_prims(child, is_collision) + + _find_geom_prims(self._prim) + + # Set default contact/rest offsets on all PhysxCollisionAPIs + with og.sim.editing_usd(): + for api in self._physx_collision_apis: + api.GetContactOffsetAttr().Set(m.DEFAULT_CONTACT_OFFSET) + api.GetRestOffsetAttr().Set(m.DEFAULT_REST_OFFSET) + + coms, vols = [], [] + for prim, is_collision in geom_prims: + mesh_name, mesh_path = prim.GetName(), prim.GetPrimPath().__str__() + mesh_kwargs = { + "relative_prim_path": absolute_prim_path_to_scene_relative(self.scene, mesh_path), + "name": f"{self._name}:{'collision' if is_collision else 'visual'}_{mesh_name}", + "load_config": {"xform_props_pre_loaded": self._load_config["xform_props_pre_loaded"]}, + } + mesh = GeomPrim(**mesh_kwargs) + mesh.load(self.scene) + if is_collision: + # Collision meshes should not show up in rendering by default + mesh.purpose = "guide" + self._collision_meshes[mesh_name] = mesh + + volume, com = get_mesh_volume_and_com(mesh.prim) + # We need to transform the volume and CoM from the mesh's local frame to the link's local frame + local_pos, local_orn = mesh.get_position_orientation(frame="parent") + vols.append(volume * th.prod(mesh.scale)) + coms.append(T.quat2mat(local_orn) @ (com * mesh.scale) + local_pos) + # If the ratio between the max extent and min radius is too large (i.e. shape too oblong), use + # boundingCube approximation for the underlying collision approximation for GPU compatibility + if prim.HasAPI(lazy.pxr.UsdPhysics.MeshCollisionAPI) and not check_extent_radius_ratio(mesh, com): + log.warning(f"Got overly oblong collision mesh: {mesh.name}; use boundingCube approximation") + apply_collision_approximation(prim, lazy.pxr.UsdPhysics.MeshCollisionAPI(prim), "boundingCube") + else: + self._visual_meshes[mesh_name] = mesh + # TODO: tmp fix for visible metalinks + if "meta" in mesh.name: + if "togglebutton" in mesh.name: + # Make sure togglebutton mesh is visible + mesh.purpose = "default" + elif any( + metalink in mesh.name + for metalink in [ + "particlesource", + "particlesink", + "fillable", + "particleremover", + "particleapplier", + "slicer", + ] + ): + # Make sure particlesource, particlesink and fillable meshes are not visible + mesh.purpose = "guide" + + # If we have any collision meshes, compute the center of mass from collision geometry + if len(coms) > 0: + coms_tensor = th.stack(coms) + vols_tensor = th.tensor(vols).unsqueeze(1) + com = th.sum(coms_tensor * vols_tensor, dim=0) / th.sum(vols_tensor) + self.center_of_mass = com + + def enable_collisions(self): + """ + Enable collisions for all collision meshes owned by this RigidPrim + """ + with og.sim.editing_usd(): + for collision_api in self._collision_apis: + collision_api.GetCollisionEnabledAttr().Set(True) + + def disable_collisions(self): + """ + Disable collisions for all collision meshes owned by this RigidPrim + """ + with og.sim.editing_usd(): + for collision_api in self._collision_apis: + collision_api.GetCollisionEnabledAttr().Set(False) + + def set_contact_offset(self, offset): + """ + Set contact offset for all collision APIs in this link. + + Args: + offset (float): Contact offset of a collision shape. Allowed range [maximum(0, rest_offset), 0]. + Default value is -inf, means default is picked by simulation based on the shape extent. + """ + with og.sim.editing_usd(): + for api in self._physx_collision_apis: + api.GetContactOffsetAttr().Set(offset) + + def set_rest_offset(self, offset): + """ + Set rest offset for all collision APIs in this link. + + Args: + offset (float): Rest offset of a collision shape. Allowed range [-max_float, contact_offset. + Default value is -inf, means default is picked by simulation. For rigid bodies its zero. + """ + with og.sim.editing_usd(): + for api in self._physx_collision_apis: + api.GetRestOffsetAttr().Set(offset) + + def set_torsional_patch_radius(self, radius): + """ + Set torsional patch radius for all collision APIs in this link. + + Args: + radius (float): radius of the contact patch used to apply torsional friction. Allowed range [0, max_float]. + """ + with og.sim.editing_usd(): + for api in self._physx_collision_apis: + api.GetTorsionalPatchRadiusAttr().Set(radius) + + def set_min_torsional_patch_radius(self, radius): + """ + Set minimum torsional patch radius for all collision APIs in this link. + + Args: + radius (float): minimum radius of the contact patch used to apply torsional friction. + Allowed range [0, max_float]. + """ + with og.sim.editing_usd(): + for api in self._physx_collision_apis: + api.GetMinTorsionalPatchRadiusAttr().Set(radius) + + def set_collision_approximation(self, approximation_type): + """ + Set collision approximation for all mesh collision APIs in this link. + + Args: + approximation_type (str): approximation used for collision. + Can be one of: {"none", "convexHull", "convexDecomposition", "meshSimplification", "sdf", + "boundingSphere", "boundingCube"} + """ + for prim, mesh_collision_api in self._mesh_collision_apis: + apply_collision_approximation(prim, mesh_collision_api, approximation_type) + + def update_handles(self): + """ + Updates all internal handles for this prim, in case they change since initialization. + To be implemented by subclasses as needed. + """ + pass + + @property + def body_name(self): + """ + Returns: + str: Name of this body + """ + return self._body_name + + @property + def collision_meshes(self): + """ + Returns: + dict: Dictionary mapping collision mesh names (str) to mesh prims (GeomPrim) owned by + this rigid body + """ + return self._collision_meshes + + @property + def visual_meshes(self): + """ + Returns: + dict: Dictionary mapping visual mesh names (str) to mesh prims (GeomPrim) owned by + this rigid body + """ + return self._visual_meshes + + @property + def visual_only(self): + """ + Returns: + bool: Whether this link is a visual-only link (i.e.: no gravity or collisions applied) + """ + return self._visual_only + + @property + def has_collision_meshes(self): + """ + Returns: + bool: Whether this link has any collision mesh + """ + return len(self._collision_meshes) > 0 + + @visual_only.setter + def visual_only(self, val): + """ + Sets the visual only state of this link + + Args: + val (bool): Whether this link should be a visual-only link (i.e.: no gravity or collisions applied) + """ + # Set gravity and collisions based on value + if val: + self.disable_collisions() + self.disable_gravity() + else: + self.enable_collisions() + self.enable_gravity() + + # Also set the internal value + self._visual_only = val + + @cached_property + def volume(self): + """ + Note: Currently it doesn't support Capsule type yet + + Returns: + float: total volume of all the collision meshes of the rigid body in m^3. + """ + # TODO (eric): revise this once omni exposes API to query volume of GeomPrims + meshes = self._visual_meshes.values() if self.is_meta_link else self._collision_meshes.values() + return sum(get_mesh_volume_and_com(mesh.prim, world_frame=True)[0] for mesh in meshes) + + @property + def ccd_enabled(self): + """ + Returns: + bool: whether CCD is enabled or not for this link + """ + return self.get_attribute("physxRigidBody:enableCCD") + + @ccd_enabled.setter + def ccd_enabled(self, enabled): + """ + Args: + enabled (bool): whether CCD should be enabled or not for this link + """ + self.set_attribute("physxRigidBody:enableCCD", enabled) + + @property + def contact_reporting_enabled(self): + """ + Returns: + bool: Whether contact reporting is enabled for this rigid prim or not + """ + return self._prim.HasAPI(lazy.pxr.PhysxSchema.PhysxContactReportAPI) + + def _compute_points_on_convex_hull(self, visual): + """ + Returns: + th.tensor or None: points on the convex hull of all points from child geom prims + """ + meshes = self._visual_meshes if visual else self._collision_meshes + points = [] + + for mesh in meshes.values(): + mesh_points = mesh.points_in_parent_frame + if mesh_points is not None and len(mesh_points) > 0: + points.append(mesh_points) + + if not points: + return None + + points = th.cat(points, dim=0) + + try: + hull = ConvexHull(points) + return points[hull.vertices, :] + except: + # Handle the case where a convex hull cannot be formed (e.g., collinear points) + # return all the points in this case + return points + + @cached_property + def visual_boundary_points_local(self): + """ + Returns: + th.tensor: local coords of points on the convex hull of all points from child geom prims + """ + return self._compute_points_on_convex_hull(visual=True) + + @property + def visual_boundary_points_world(self): + """ + Returns: + th.tensor: world coords of points on the convex hull of all points from child geom prims + """ + local_points = self.visual_boundary_points_local + if local_points is None: + return None + return self.transform_local_points_to_world(local_points) + + @cached_property + def collision_boundary_points_local(self): + """ + Returns: + th.tensor: local coords of points on the convex hull of all points from child geom prims + """ + return self._compute_points_on_convex_hull(visual=False) + + @property + def collision_boundary_points_world(self): + """ + Returns: + th.tensor: world coords of points on the convex hull of all points from child geom prims + """ + local_points = self.collision_boundary_points_local + if local_points is None: + return None + return self.transform_local_points_to_world(local_points) + + @cached_property + def collision_mesh_cpu_data(self): + """ + Returns: + (pts_cpu, faces_cpu) tuple of CPU torch tensors, or None if the link has no collision + geometry. Used by RigidBodyViewAPI.initialize_view() to batch H2D copies and + wp.Mesh construction across all links. + + - pts_cpu: (N, 3) float32 — vertices of all collision geoms of this link, expressed + in the link's local frame, with the link's world scale baked in. + - faces_cpu: (M*3,) int32 — flat triangle vertex indices into pts_cpu (link-local; + offsets across geoms within the link are already applied). + + The world scale is baked into the stored points so that downstream kernels can + transform back to world frame using just the link's pose-matrix (rotation + translation, + no scale) — matching what RigidBodyViewAPI.POSE_MATRICES provides. + """ + world_to_scaled_link = T.pose_inv(T.pose2mat(self.get_position_orientation())) + pts_concat, idx_concat, point_offset = [], [], 0 + for geom in self._collision_meshes.values(): + pts = geom.points_in_world_frame + if pts is None or pts.shape[0] == 0: + continue + points_wrt_link = T.transform_points(pts, world_to_scaled_link) + faces = geom.faces + pts_concat.append(points_wrt_link) + idx_concat.append((faces + point_offset).flatten()) + point_offset += points_wrt_link.shape[0] + + if not pts_concat: + return None + + pts_cpu = th.cat(pts_concat, dim=0).to(th.float32) + faces_cpu = th.cat(idx_concat, dim=0).to(th.int32) + return pts_cpu, faces_cpu + + @property + def aabb(self): + position, _ = self.get_position_orientation() + hull_points = self.collision_boundary_points_world + + if hull_points is None: + # When there's no points on the collision meshes + return position, position + + aabb_lo = th.min(hull_points, dim=0).values + aabb_hi = th.max(hull_points, dim=0).values + return aabb_lo, aabb_hi + + @property + def aabb_extent(self): + """ + Get this xform's actual bounding box extent + + Returns: + 3-array: (x,y,z) bounding box + """ + min_corner, max_corner = self.aabb + return max_corner - min_corner + + @property + def aabb_center(self): + """ + Get this xform's actual bounding box center + + Returns: + 3-array: (x,y,z) bounding box center + """ + min_corner, max_corner = self.aabb + return (max_corner + min_corner) / 2.0 + + @property + def visual_aabb(self): + hull_points = self.visual_boundary_points_world + assert hull_points is not None, "No visual boundary points found for this rigid prim" + + # Calculate and return the AABB + aabb_lo = th.min(hull_points, dim=0).values + aabb_hi = th.max(hull_points, dim=0).values + + return aabb_lo, aabb_hi + + @property + def visual_aabb_extent(self): + """ + Get this xform's actual bounding box extent + + Returns: + 3-array: (x,y,z) bounding box + """ + min_corner, max_corner = self.visual_aabb + return max_corner - min_corner + + @property + def visual_aabb_center(self): + """ + Get this xform's actual bounding box center + + Returns: + 3-array: (x,y,z) bounding box center + """ + min_corner, max_corner = self.visual_aabb + return (max_corner + min_corner) / 2.0 + + @cached_property + def is_meta_link(self): + # Check using the new format first + new_format = self.prim.HasAttribute("ig:isMetaLink") and self.get_attribute("ig:isMetaLink") + if new_format: + return True + + # Check using the old format. + # TODO: Remove this after the next dataset release + old_format = m.LEGACY_META_LINK_PATTERN.fullmatch(self.name) is not None + if old_format: + return True + + return False + + @cached_property + def meta_link_type(self): + assert self.is_meta_link, f"{self.name} is not a meta link" + if self.prim.HasAttribute("ig:metaLinkType"): + return self.get_attribute("ig:metaLinkType") + + # Check using the old format. + # TODO: Remove this after the next dataset release + return m.LEGACY_META_LINK_PATTERN.fullmatch(self.name).group(1) + + @cached_property + def meta_link_id(self): + """The meta link id of this link, if the link is a meta link. + + The meta link ID is a semantic identifier for the meta link within the meta link type. It is + used when an object has multiple meta links of the same type. It can be just a numerical index, + or for some objects, it will be a string that can be matched to other meta links. For example, + a stove might have toggle buttons named "left" and "right", and heat sources named "left" and + "right". The meta link ID can be used to match the toggle button to the heat source. + """ + assert self.is_meta_link, f"{self.name} is not a meta link" + if self.prim.HasAttribute("ig:metaLinkId"): + return self.get_attribute("ig:metaLinkId") + + # Check using the old format. + # TODO: Remove this after the next dataset release + return m.LEGACY_META_LINK_PATTERN.fullmatch(self.name).group(2) + + @cached_property + def meta_link_sub_id(self): + """The integer meta link sub id of this link, if the link is a meta link. + + The meta link sub ID identifies this link as one of the parts of a meta link. For example, an + attachment meta link's ID will be the attachment pair name, and each attachment point that + works with that pair will show up as a separate link with a unique sub ID. + """ + assert self.is_meta_link, f"{self.name} is not a meta link" + if self.prim.HasAttribute("ig:metaLinkSubId"): + return int(self.get_attribute("ig:metaLinkSubId")) + + # Check using the old format. + # TODO: Remove this after the next dataset release + return int(m.LEGACY_META_LINK_PATTERN.fullmatch(self.name).group(3)) + + def check_points_in_volume( + self, + particle_positions_world, + use_visual_meshes=True, + ): + """ + Args: + particle_positions_world (th.tensor): (N, 3) array of particle positions to check + use_visual_meshes (bool): Whether to use @volume_link's visual or collision meshes to generate points fcn. + In either case, this assumes the given meshes are convex hulls. For visual meshes, we enforce this + constraint by explicitly converting them into convex hulls + """ + in_volume = th.zeros(particle_positions_world.shape[0], dtype=th.bool) + meshes_to_check = self.visual_meshes if use_visual_meshes else self.collision_meshes + for mesh in meshes_to_check.values(): + in_volume |= mesh.check_points_in_volume(particle_positions_world) + return in_volume + + @cached_property + def world_volume(self, precision=1e-5): + # We use monte-carlo sampling to approximate the voluem up to @precision + # NOTE: precision defines the RELATIVE precision of the volume computation -- i.e.: the relative error with + # respect to the volume link's global AABB + + # Convert precision to minimum number of particles to sample + min_n_particles = int(math.ceil(1.0 / precision)) + + # Determine equally-spaced sampling distance to achieve this minimum particle count + aabb_volume = th.prod(self.visual_aabb_extent) + sampling_distance = th.pow(aabb_volume / min_n_particles, 1 / 3.0) + low, high = self.aabb + n_particles_per_axis = ((high - low) / sampling_distance).int() + 1 + assert th.all(n_particles_per_axis), "Must increase precision for calculate_volume -- too coarse for sampling!" + # 1e-10 is added because the extent might be an exact multiple of particle radius + arrs = [th.arange(l, h, sampling_distance) for l, h, n in zip(low, high, n_particles_per_axis)] + # Generate 3D-rectangular grid of points, and only keep the ones inside the mesh + points = th.stack([arr.flatten() for arr in th.meshgrid(*arrs)]).T + + # Return the fraction of the link AABB's volume based on fraction of points enclosed within it + return aabb_volume * th.mean(self.check_points_in_volume(points).float()) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/xform_prim.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/xform_prim.py new file mode 100644 index 0000000000000000000000000000000000000000..5f133491d7b8b754632a32c13dac8f7b6974da56 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/prims/xform_prim.py @@ -0,0 +1,504 @@ +import math +from collections.abc import Iterable +from typing import Literal + +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.prims.material_prim import MaterialPrim +from omnigibson.prims.prim_base import BasePrim +from omnigibson.utils.transform_utils import quat2euler +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import get_world_pose_with_scale, get_world_pose, get_local_pose, ensure_usd_api + +# Create module logger +logger = create_module_logger(module_name=__name__) + + +class XFormPrim(BasePrim): + """ + Provides high level functions to deal with an Xform prim and its attributes/ properties. + If there is an Xform prim present at the path, it will use it. Otherwise, a new XForm prim at + the specified prim path will be created when self.load(...) is called. + + Note: the prim will have "xformOp:orient", "xformOp:translate" and "xformOp:scale" only post init, + unless it is a non-root articulation link. + + Args: + relative_prim_path (str): Scene-local prim path of the Prim to encapsulate or create. + name (str): Name for the object. Names need to be unique per scene. + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. For this xform prim, the below values can be specified: + + scale (None or float or 3-array): If specified, sets the scale for this object. A single number corresponds + to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. + """ + + def __init__( + self, + relative_prim_path, + name, + load_config=None, + ): + # Other values that will be filled in at runtime + self._material = None + self.original_scale = None + self._cached_scale = None + + # Run super method + super().__init__( + relative_prim_path=relative_prim_path, + name=name, + load_config=load_config, + ) + + def _load(self): + with og.sim.editing_usd(): + return og.sim.stage.DefinePrim(self.prim_path, "Xform") + + def _post_load(self): + # run super first + super()._post_load() + + # Make sure all xforms have pose and scaling info + # These only need to be done if we are creating this prim from scratch AND it is not an instanceable / proxy prim. + # Pre-created OG objects' prims always have these things set up ahead of time. + # Note that if this is an instanceable prim, we also don't need write these properties + # TODO: This still breaks things downstream so we assert here to make sure we have backwards-compatibility with the expected prim types + assert ( + not self._prim.IsInstanceable() and not self._prim.IsInstanceProxy() + ), "Support for instanceable prims has not been implemented yet!" + if not self._xform_props_pre_loaded and not self._prim.IsInstanceable() and not self._prim.IsInstanceProxy(): + self._set_xform_properties() + + # Cache the original scale from the USD so that when EntityPrim sets the scale for each link (Rigid/ClothPrim), + # the new scale is with respect to the original scale. XFormPrim's scale always matches the scale in the USD. + self.original_scale = th.tensor(self.get_attribute("xformOp:scale")) + + # Grab the attached material if it exists + if self.has_material(): + material_prim_path = self._binding_api.GetDirectBinding().GetMaterialPath().pathString + material_name = f"{self.name}:material" + material = MaterialPrim.get_material(scene=self.scene, prim_path=material_prim_path, name=material_name) + assert material.loaded, f"Material prim path {material_prim_path} doesn't exist on stage." + material.add_user(self) + self._material = material + + # Optionally set the scale, which is specified with respect to the original scale + if "scale" in self._load_config and self._load_config["scale"] is not None: + self.scale = self._load_config["scale"] * self.original_scale + + def remove(self): + # Remove the material prim if one exists + if self._material is not None: + self._material.remove_user(self) + + # Remove the prim + super().remove() + + def _set_xform_properties(self): + current_position, current_orientation = self.get_position_orientation() + properties_to_remove = [ + "xformOp:rotateX", + "xformOp:rotateXZY", + "xformOp:rotateY", + "xformOp:rotateYXZ", + "xformOp:rotateYZX", + "xformOp:rotateZ", + "xformOp:rotateZYX", + "xformOp:rotateZXY", + "xformOp:rotateXYZ", + "xformOp:transform", + ] + prop_names = self.prim.GetPropertyNames() + xformable = lazy.pxr.UsdGeom.Xformable(self.prim) + + with og.sim.editing_usd(): + xformable.ClearXformOpOrder() + # TODO: wont be able to delete props for non root links on articulated objects + for prop_name in prop_names: + if prop_name in properties_to_remove: + self.prim.RemoveProperty(prop_name) + if "xformOp:scale" not in prop_names: + xform_op_scale = xformable.AddXformOp( + lazy.pxr.UsdGeom.XformOp.TypeScale, lazy.pxr.UsdGeom.XformOp.PrecisionDouble, "" + ) + xform_op_scale.Set(lazy.pxr.Gf.Vec3d([1.0, 1.0, 1.0])) + else: + xform_op_scale = lazy.pxr.UsdGeom.XformOp(self._prim.GetAttribute("xformOp:scale")) + + if "xformOp:translate" not in prop_names: + xform_op_translate = xformable.AddXformOp( + lazy.pxr.UsdGeom.XformOp.TypeTranslate, lazy.pxr.UsdGeom.XformOp.PrecisionDouble, "" + ) + else: + xform_op_translate = lazy.pxr.UsdGeom.XformOp(self._prim.GetAttribute("xformOp:translate")) + + if "xformOp:orient" not in prop_names: + xform_op_rot = xformable.AddXformOp( + lazy.pxr.UsdGeom.XformOp.TypeOrient, lazy.pxr.UsdGeom.XformOp.PrecisionDouble, "" + ) + else: + xform_op_rot = lazy.pxr.UsdGeom.XformOp(self._prim.GetAttribute("xformOp:orient")) + xformable.SetXformOpOrder([xform_op_translate, xform_op_rot, xform_op_scale]) + + # This creates its own editing_usd context. + XFormPrim.set_position_orientation(self, position=current_position, orientation=current_orientation) + new_position, new_orientation = self.get_position_orientation() + r1 = T.quat2mat(current_orientation) + r2 = T.quat2mat(new_orientation) + # Make sure setting is done correctly + assert th.allclose(new_position, current_position, atol=1e-4) and th.allclose(r1, r2, atol=1e-3), ( + f"{self.prim_path}: old_pos: {current_position}, new_pos: {new_position}, " + f"old_orn: {current_orientation}, new_orn: {new_orientation}" + ) + + @property + def _collision_filter_api(self): + return ensure_usd_api(self._prim, lazy.pxr.UsdPhysics.FilteredPairsAPI) + + @property + def _binding_api(self): + return ensure_usd_api(self.prim, lazy.pxr.UsdShade.MaterialBindingAPI) + + def has_material(self): + """ + Returns: + bool: True if there is a visual material bound to this prim. False otherwise + """ + material_path = self._binding_api.GetDirectBinding().GetMaterialPath().pathString + return material_path != "" and lazy.isaacsim.core.utils.prims.is_prim_path_valid(material_path) + + def set_position_orientation( + self, position=None, orientation=None, frame: Literal["world", "parent", "scene"] = "world" + ): + """ + Sets prim's pose with respect to the specified frame + + Args: + position (None or 3-array): if specified, (x,y,z) position in the world frame + Default is None, which means left unchanged. + orientation (None or 4-array): if specified, (x,y,z,w) quaternion orientation in the world frame. + Default is None, which means left unchanged. + frame (Literal): frame to set the pose with respect to, defaults to "world". parent frame + set position relative to the object parent. scene frame set position relative to the scene. + """ + assert frame in ["world", "parent", "scene"], f"Invalid frame '{frame}'. Must be 'world', 'parent', or 'scene'." + + # If no position or no orientation are given, get the current position and orientation of the object + if position is None or orientation is None: + current_position, current_orientation = self.get_position_orientation(frame=frame) + position = current_position if position is None else position + orientation = current_orientation if orientation is None else orientation + + # Convert to th.Tensor if necessary + position = th.as_tensor(position, dtype=th.float32) + orientation = th.as_tensor(orientation, dtype=th.float32) + + # Convert to from scene-relative to world if necessary + if frame == "scene": + assert self.scene is not None, "cannot set position and orientation relative to scene without a scene" + position, orientation = self.scene.convert_scene_relative_pose_to_world(position, orientation) + + # If the current pose is not in parent frame, convert to parent frame since that's what we can set. + if frame != "parent": + world_transform = T.pose2mat((position, orientation)) + parent_path = str(lazy.isaacsim.core.utils.prims.get_prim_parent(self._prim).GetPath()) + parent_world_transform = get_world_pose_with_scale(parent_path) + + local_transform = th.linalg.inv_ex(parent_world_transform).inverse @ world_transform + local_transform[:3, :3] /= th.linalg.norm( + local_transform[:3, :3], dim=0 + ) # unscale local transform's rotation + + # Check that the local transform consists only of a position, scale and rotation + product = local_transform[:3, :3] @ local_transform[:3, :3].T + assert th.allclose( + product, th.diag(th.diag(product)), atol=1e-3 + ), f"{self._prim.GetPath()} local transform is not orthogonal." + + # Return the local pose + position, orientation = T.mat2pose(local_transform) + + # Assert validity of the orientation + assert math.isclose( + th.norm(orientation).item(), 1, abs_tol=1e-3 + ), f"{self.prim_path} desired orientation {orientation} is not a unit quaternion." + + # Actually set the local pose now. + properties = self.prim.GetPropertyNames() + position = lazy.pxr.Gf.Vec3d(*position.tolist()) + if "xformOp:translate" not in properties: + logger.error("Translate property needs to be set for {} before setting its position".format(self.name)) + self.set_attribute("xformOp:translate", position) + orientation = orientation[[3, 0, 1, 2]].tolist() + if "xformOp:orient" not in properties: + logger.error("Orient property needs to be set for {} before setting its orientation".format(self.name)) + xform_op = self._prim.GetAttribute("xformOp:orient") + if xform_op.GetTypeName() == "quatf": + rotq = lazy.pxr.Gf.Quatf(*orientation) + else: + rotq = lazy.pxr.Gf.Quatd(*orientation) + with og.sim.editing_usd(): + xform_op.Set(rotq) + + og.sim.fabric_hierarchy.update_world_xforms() + + # Tensorized state caches (AABB / Touching / Adjacency / ...) read from pose tensors + # that are now one frame behind. Flag them as stale so the next state read forces a + # refresh via the lazy-refresh gate in TensorizedState._get_value. + from omnigibson.object_states.tensorized_state import TensorizedState + + TensorizedState.caches_dirty = True + + def get_position_orientation(self, frame: Literal["world", "scene", "parent"] = "world", clone=True): + """ + Gets prim's pose with respect to the specified frame. + + Args: + frame (Literal): frame to get the pose with respect to. Default to world. + parent frame: get position relative to the object parent. + scene frame: get position relative to the scene. + clone (bool): Whether to clone the internal buffer or not when grabbing data + + Returns: + 2-tuple: + - th.Tensor: (x,y,z) position in the specified frame + - th.Tensor: (x,y,z,w) quaternion orientation in the specified frame + """ + assert frame in ["world", "parent", "scene"], f"Invalid frame '{frame}'. Must be 'world', 'parent', or 'scene'." + if frame == "world": + return get_world_pose(self.prim_path) + elif frame == "scene": + assert self.scene is not None, "Cannot get position and orientation relative to scene without a scene" + return self.scene.convert_world_pose_to_scene_relative(*get_world_pose(self.prim_path)) + else: + return get_local_pose(self.prim_path) + + def set_position(self, position): + """ + Set this prim's position with respect to the world frame + + Args: + position (3-array): (x,y,z) global cartesian position to set + """ + logger.warning( + "set_position is deprecated and will be removed in a future release. Use set_position_orientation(position=position) instead" + ) + return self.set_position_orientation(position=position) + + def get_position(self): + """ + Get this prim's position with respect to the world frame + + Returns: + 3-array: (x,y,z) global cartesian position of this prim + """ + logger.warning( + "get_position is deprecated and will be removed in a future release. Use get_position_orientation()[0] instead." + ) + return self.get_position_orientation()[0] + + def set_orientation(self, orientation): + """ + Set this prim's orientation with respect to the world frame + + Args: + orientation (4-array): (x,y,z,w) global quaternion orientation to set + """ + logger.warning( + "set_orientation is deprecated and will be removed in a future release. Use set_position_orientation(orientation=orientation) instead" + ) + self.set_position_orientation(orientation=orientation) + + def get_orientation(self): + """ + Get this prim's orientation with respect to the world frame + + Returns: + 4-array: (x,y,z,w) global quaternion orientation of this prim + """ + logger.warning( + "get_orientation is deprecated and will be removed in a future release. Use get_position_orientation()[1] instead" + ) + return self.get_position_orientation()[1] + + def get_rpy(self): + """ + Get this prim's orientation with respect to the world frame + + Returns: + 3-array: (roll, pitch, yaw) global euler orientation of this prim + """ + return quat2euler(self.get_position_orientation()[1]) + + def get_xy_orientation(self): + """ + Get this prim's orientation on the XY plane of the world frame. This is obtained by + projecting the forward vector onto the XY plane and then computing the angle. + """ + return T.calculate_xy_plane_angle(self.get_position_orientation()[1]) + + def get_local_pose(self): + """ + Gets prim's pose with respect to the prim's local frame (its parent frame) + + Returns: + 2-tuple: + - 3-array: (x,y,z) position in the local frame + - 4-array: (x,y,z,w) quaternion orientation in the local frame + """ + logger.warning( + 'get_local_pose is deprecated and will be removed in a future release. Use get_position_orientation(frame="parent") instead' + ) + return self.get_position_orientation(frame="parent") + + def set_local_pose(self, position=None, orientation=None): + """ + Sets prim's pose with respect to the local frame (the prim's parent frame). + + Args: + position (None or 3-array): if specified, (x,y,z) position in the local frame of the prim + (with respect to its parent prim). Default is None, which means left unchanged. + orientation (None or 4-array): if specified, (x,y,z,w) quaternion orientation in the local frame of the prim + (with respect to its parent prim). Default is None, which means left unchanged. + """ + logger.warning( + 'set_local_pose is deprecated and will be removed in a future release. Use set_position_orientation(position=position, orientation=orientation, frame="parent") instead' + ) + return self.set_position_orientation(position, orientation, frame="parent") + + @property + def aabb(self): + aabb_min, aabb_max = lazy.omni.usd.get_context().compute_path_world_bounding_box(self.prim_path) + logger.warning( + "Computing AABB of an XFormPrim using the USD context is slow and unreliable, especially when fabric is enabled. " + "This is provided as a convenience for USD editing use cases and should generally not be used for physical objects." + ) + return th.tensor(aabb_min), th.tensor(aabb_max) + + @property + def aabb_center(self): + min_corner, max_corner = self.aabb + return (min_corner + max_corner) / 2 + + @property + def aabb_extent(self): + min_corner, max_corner = self.aabb + return max_corner - min_corner + + @property + def scaled_transform(self): + """ + Returns the scaled transform of this prim. + """ + return get_world_pose_with_scale(self.prim_path) + + def transform_local_points_to_world(self, points): + return T.transform_points(points, self.scaled_transform) + + @property + def scale(self): + """ + Gets prim's scale with respect to the local frame (the parent's frame). + + Returns: + th.tensor: scale applied to the prim's dimensions in the local frame. shape is (3, ). + """ + if self._cached_scale is not None: + return self._cached_scale + scale = self.get_attribute("xformOp:scale") + assert scale is not None, "Attribute 'xformOp:scale' is None for prim {}".format(self.name) + return th.tensor(scale) + + @scale.setter + def scale(self, scale): + """ + Sets prim's scale with respect to the local frame (the prim's parent frame). + + Args: + scale (float or th.tensor): scale to be applied to the prim's dimensions. shape is (3, ). + Defaults to None, which means left unchanged. + """ + if isinstance(scale, th.Tensor): + scale = scale + elif isinstance(scale, Iterable): + scale = th.tensor(scale, dtype=th.float32) + else: + scale = th.ones(3, dtype=th.float32) * scale + assert th.all(scale > 0), f"Scale {scale} must consist of positive numbers." + # Invalidate the cached scale + self._cached_scale = None + scale = lazy.pxr.Gf.Vec3d(*scale.tolist()) + properties = self.prim.GetPropertyNames() + if "xformOp:scale" not in properties: + logger.error("Scale property needs to be set for {} before setting its scale".format(self.name)) + self.set_attribute("xformOp:scale", scale) + + @property + def material(self): + """ + Returns: + None or MaterialPrim: The bound material to this prim, if there is one + """ + return self._material + + @material.setter + def material(self, material): + """ + Set the material @material for this prim. This will also bind the material to this prim + + Args: + material (MaterialPrim): Material to bind to this prim + """ + binding_api = self._binding_api + with og.sim.editing_usd(): + binding_api.Bind( + lazy.pxr.UsdShade.Material(material.prim), + bindingStrength=lazy.pxr.UsdShade.Tokens.weakerThanDescendants, + ) + self._material = material + + def add_filtered_collision_pair(self, prim): + """ + Adds a collision filter pair with another prim + + Args: + prim (XFormPrim): Another prim to filter collisions with + """ + self_api = self._collision_filter_api + other_api = prim._collision_filter_api + with og.sim.editing_usd(): + # Add to both this prim's and the other prim's filtered pair + self_api.GetFilteredPairsRel().AddTarget(prim.prim_path) + other_api.GetFilteredPairsRel().AddTarget(self.prim_path) + + def remove_filtered_collision_pair(self, prim): + """ + Removes a collision filter pair with another prim + + Args: + prim (XFormPrim): Another prim to remove filter collisions with + """ + self_api = self._collision_filter_api + other_api = prim._collision_filter_api + with og.sim.editing_usd(): + self_api.GetFilteredPairsRel().RemoveTarget(prim.prim_path) + other_api.GetFilteredPairsRel().RemoveTarget(self.prim_path) + + def _dump_state(self): + pos, ori = self.get_position_orientation() + return dict(pos=pos, ori=ori) + + def _load_state(self, state): + pos, orn = state["pos"], state["ori"] + self.set_position_orientation(pos, orn) + + def serialize(self, state): + return th.cat([state["pos"], state["ori"]]) + + def deserialize(self, state): + # We deserialize deterministically by knowing the order of values -- pos, ori + return dict(pos=state[0:3], ori=state[3:7]), 7 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ac9e61a5de8ce47eef2949c3f622c743a6c58f28 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/__init__.py @@ -0,0 +1,16 @@ +from omnigibson.reward_functions.collision_reward import CollisionReward +from omnigibson.reward_functions.grasp_reward import GraspReward +from omnigibson.reward_functions.point_goal_reward import PointGoalReward +from omnigibson.reward_functions.potential_reward import PotentialReward +from omnigibson.reward_functions.reaching_goal_reward import ReachingGoalReward +from omnigibson.reward_functions.reward_function_base import REGISTERED_REWARD_FUNCTIONS, BaseRewardFunction + +__all__ = [ + "BaseRewardFunction", + "CollisionReward", + "GraspReward", + "PointGoalReward", + "PotentialReward", + "ReachingGoalReward", + "REGISTERED_REWARD_FUNCTIONS", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/collision_reward.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/collision_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..578902fde4fa05bdc0e577f5eb82fb3f6bb11d8d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/collision_reward.py @@ -0,0 +1,43 @@ +import torch as th + +from omnigibson.utils.usd_utils import RigidContactAPI +from omnigibson.reward_functions.reward_function_base import BaseRewardFunction + + +class CollisionReward(BaseRewardFunction): + """ + Collision reward + Penalize robot collision. Typically collision_reward_weight is negative. Note that we ignore collisions with any + floor objects. + + Args: + robot_idn (int): robot identifier to evaluate collision penalty with. Default is 0, corresponding to the first + robot added to the scene + ignore_self_collisions (bool): Whether to ignore robot self-collisions or not + r_collision (float): Penalty value (>0) to penalize collisions + """ + + def __init__(self, robot_idn=0, ignore_self_collisions=True, r_collision=0.1): + # Store internal vars + assert r_collision > 0, f"r_collision must be positive, got: {r_collision}!" + self._robot_idn = robot_idn + self._ignore_self_collisions = ignore_self_collisions + self._r_collision = r_collision + + # Run super + super().__init__() + + def _step(self, task, env, action): + # Penalty is Reward is -self._r_collision if there were any collisions in the last timestep + rewards = th.zeros(env.num_envs, dtype=th.float32) + infos = [dict() for _ in range(env.num_envs)] + for env_idx in range(env.num_envs): + robot = env.scenes[env_idx].robots[self._robot_idn] + # Ignore floors and potentially robot's own prims as well + floors = list(env.scenes[env_idx].object_registry("category", "floors", [])) + ignore_objs = floors + [robot] if self._ignore_self_collisions else floors + in_contact = RigidContactAPI.is_in_contact( + scene_idx=robot.scene.idx, query_set=[robot], with_set=None, ignore_set=ignore_objs, current_only=False + ) + rewards[env_idx] = float(in_contact) * -self._r_collision + return rewards, infos diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/grasp_reward.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/grasp_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..f49ecabdddbcfcf2cecfec04d652fd8b384a5afd --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/grasp_reward.py @@ -0,0 +1,184 @@ +import math + +import torch as th + +import omnigibson.utils.transform_utils as T +from omnigibson.reward_functions.reward_function_base import BaseRewardFunction +from omnigibson.utils.motion_planning_utils import detect_robot_collision_in_sim + + +class GraspReward(BaseRewardFunction): + """ + A composite reward function for grasping tasks. This reward function not only evaluates the success of object grasping + but also considers various penalties and efficiencies. + + The reward is calculated based on several factors: + - Grasping reward: A positive reward is given if the robot is currently grasping the specified object. + - Distance reward: A reward based on the inverse exponential distance between the end-effector and the object. + - Regularization penalty: Penalizes large magnitude actions to encourage smoother and more energy-efficient movements. + - Position and orientation penalties: Discourages excessive movement of the end-effector. + - Collision penalty: Penalizes collisions with the environment or other objects. + + Attributes: + obj_name (str): Name of the object to grasp. + dist_coeff (float): Coefficient for the distance reward calculation. + grasp_reward (float): Reward given for successfully grasping the object. + collision_penalty (float): Penalty incurred for any collision. + eef_position_penalty_coef (float): Coefficient for the penalty based on end-effector's position change. + eef_orientation_penalty_coef (float): Coefficient for the penalty based on end-effector's orientation change. + regularization_coef (float): Coefficient for penalizing large actions. + """ + + def __init__( + self, + obj_name, + dist_coeff, + grasp_reward, + collision_penalty, + eef_position_penalty_coef, + eef_orientation_penalty_coef, + regularization_coef, + ): + # Store internal vars + self.prev_grasping = None + self.prev_eef_pos = None + self.prev_eef_quat = None + self.obj_name = obj_name + self._objs = None # list of objects per scene, populated lazily + self.dist_coeff = dist_coeff + self.grasp_reward = grasp_reward + self.collision_penalty = collision_penalty + self.eef_position_penalty_coef = eef_position_penalty_coef + self.eef_orientation_penalty_coef = eef_orientation_penalty_coef + self.regularization_coef = regularization_coef + + # Run super + super().__init__() + + def _step(self, task, env, action): + # Lazily populate per-scene object references + if self._objs is None: + self._objs = [env.scenes[i].object_registry("name", self.obj_name) for i in range(env.num_envs)] + + rewards = th.zeros(env.num_envs, dtype=th.float32) + infos = [dict() for _ in range(env.num_envs)] + + for env_idx in range(env.num_envs): + obj = self._objs[env_idx] + scene = env.scenes[env_idx] + robot_idx = 0 + robot = scene.robots[robot_idx] + obj_in_hand = robot._ag_obj_in_hand[robot.default_arm] + current_grasping = obj_in_hand == obj + + info = {"grasp_success": current_grasping} + + # Reward varying based on combination of whether the robot was previously grasping the desired object + # and is currently grasping the desired object + reward = 0.0 + + # Penalize large actions. action is shaped (num_envs, action_dim), so we must select + # this env's row and, within it, only the slice belonging to this robot (keyed by + # scene + robot, matching the action layout in Environment.step). + robot_action_start = sum(r.action_dim for r in scene.robots[:robot_idx]) + robot_action = action[env_idx][robot_action_start : robot_action_start + robot.action_dim] + action_mag = th.sum(th.abs(robot_action)) + regularization_penalty = -(action_mag * self.regularization_coef) + reward += regularization_penalty + info["regularization_penalty_factor"] = action_mag + info["regularization_penalty"] = regularization_penalty + + # Penalize based on the magnitude of the action + eef_pos = robot.get_eef_position(robot.default_arm) + info["position_penalty_factor"] = 0.0 + info["position_penalty"] = 0.0 + if self.prev_eef_pos is not None and self.prev_eef_pos[env_idx] is not None: + eef_pos_delta = T.l2_distance(self.prev_eef_pos[env_idx], eef_pos) + position_penalty = -eef_pos_delta * self.eef_position_penalty_coef + reward += position_penalty + info["position_penalty_factor"] = eef_pos_delta + info["position_penalty"] = position_penalty + + eef_quat = robot.get_eef_orientation(robot.default_arm) + info["rotation_penalty_factor"] = 0.0 + info["rotation_penalty"] = 0.0 + if self.prev_eef_quat is not None and self.prev_eef_quat[env_idx] is not None: + delta_rot = T.get_orientation_diff_in_radian(self.prev_eef_quat[env_idx], eef_quat) + rotation_penalty = -delta_rot * self.eef_orientation_penalty_coef + reward += rotation_penalty + info["rotation_penalty_factor"] = delta_rot.item() + info["rotation_penalty"] = rotation_penalty.item() + + # Penalize robot for colliding with an object + info["collision_penalty_factor"] = 0.0 + info["collision_penalty"] = 0.0 + if detect_robot_collision_in_sim(robot, filter_objs=[obj]): + reward += -self.collision_penalty + info["collision_penalty_factor"] = 1.0 + info["collision_penalty"] = -self.collision_penalty + + # If we're not currently grasping + info["grasp_reward_factor"] = 0.0 + info["grasp_reward"] = 0.0 + info["pregrasp_dist"] = 0.0 + info["pregrasp_dist_reward_factor"] = 0.0 + info["pregrasp_dist_reward"] = 0.0 + info["postgrasp_dist"] = 0.0 + info["postgrasp_dist_reward_factor"] = 0.0 + info["postgrasp_dist_reward"] = 0.0 + if not current_grasping: + # TODO: If we dropped the object recently, penalize for that + obj_center = obj.get_position_orientation()[0] + dist = T.l2_distance(eef_pos, obj_center) + dist_reward = math.exp(-dist) * self.dist_coeff + reward += dist_reward + info["pregrasp_dist"] = dist + info["pregrasp_dist_reward_factor"] = math.exp(-dist) + info["pregrasp_dist_reward"] = dist_reward + else: + # We are currently grasping - first apply a grasp reward + reward += self.grasp_reward + info["grasp_reward_factor"] = 1.0 + info["grasp_reward"] = self.grasp_reward + + # Then apply a distance reward to take us to a tucked position + robot_center = robot.links["torso_lift_link"].get_position_orientation()[0] + obj_center = obj.get_position_orientation()[0] + dist = T.l2_distance(robot_center, obj_center) + dist_reward = math.exp(-dist) * self.dist_coeff + reward += dist_reward + info["postgrasp_dist"] = dist + info["postgrasp_dist_reward_factor"] = math.exp(-dist) + info["postgrasp_dist_reward"] = dist_reward + + rewards[env_idx] = reward + infos[env_idx] = info + + # Update per-env tracking + if self.prev_eef_pos is not None: + self.prev_eef_pos[env_idx] = eef_pos + if self.prev_eef_quat is not None: + self.prev_eef_quat[env_idx] = eef_quat + if self.prev_grasping is not None: + self.prev_grasping[env_idx] = current_grasping + + return rewards, infos + + def reset(self, task, env, env_indices): + """ + Reward function-specific reset + + Args: + task (BaseTask): Task instance + env (Environment): Environment instance + env_indices (list): List of environment indices to reset + """ + super().reset(task, env, env_indices) + if self.prev_grasping is None: + self.prev_grasping = [False] * env.num_envs + self.prev_eef_pos = [None] * env.num_envs + self.prev_eef_quat = [None] * env.num_envs + for idx in env_indices: + self.prev_grasping[idx] = False + self.prev_eef_pos[idx] = None + self.prev_eef_quat[idx] = None diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/point_goal_reward.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/point_goal_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..c0b3d7ce54bcdc2061875892cacd55ce91a59b1f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/point_goal_reward.py @@ -0,0 +1,29 @@ +import torch as th + +from omnigibson.reward_functions.reward_function_base import BaseRewardFunction + + +class PointGoalReward(BaseRewardFunction): + """ + Point goal reward + Success reward for reaching the goal with the robot's base + + Args: + pointgoal (PointGoal): Termination condition for checking whether a point goal is reached + r_pointgoal (float): Reward for reaching the point goal + """ + + def __init__(self, pointgoal, r_pointgoal=10.0): + # Store internal vars + self._pointgoal = pointgoal + self._r_pointgoal = r_pointgoal + + # Run super + super().__init__() + + def _step(self, task, env, action): + # Reward received when the pointgoal success condition is met + # self._pointgoal.success is (num_envs,) bool tensor + rewards = th.where(self._pointgoal.success, self._r_pointgoal, 0.0) + infos = [dict() for _ in range(env.num_envs)] + return rewards, infos diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/potential_reward.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/potential_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..fab45171492f22b90787c830e290412bd8efe76d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/potential_reward.py @@ -0,0 +1,59 @@ +import torch as th + +from omnigibson.reward_functions.reward_function_base import BaseRewardFunction + + +class PotentialReward(BaseRewardFunction): + """ + Potential reward + Assume task has get_potential implemented; Low potential is preferred + (e.g. a common potential for goal-directed task is the distance to goal) + + Args: + potential_fcn (method): function for calculating potential. Function signature should be: + + potential = potential_fcn(env, env_idx) + + where @env is an Environment instance, @env_idx is the environment index, + and @potential is a float value representing the calculated potential + + r_potential (float): Reward weighting to give proportional to the potential difference calculated + in between env timesteps + """ + + def __init__(self, potential_fcn, r_potential=1.0): + # Store internal vars + self._potential_fcn = potential_fcn + self._r_potential = r_potential + + # Store internal vars that will be filled in at runtime + self._potential = None + + # Run super + super().__init__() + + def reset(self, task, env, env_indices): + """ + Compute the initial potential after episode reset + + :param task: task instance + :param env: environment instance + :param env_indices: indices of environments to reset + """ + super().reset(task, env, env_indices) + # Reset potential + if self._potential is None: + self._potential = th.zeros(env.num_envs, dtype=th.float32) + for idx in env_indices: + self._potential[idx] = self._potential_fcn(env, idx) + + def _step(self, task, env, action): + # Reward is proportional to the potential difference between the current and previous timestep + rewards = th.zeros(env.num_envs, dtype=th.float32) + infos = [dict() for _ in range(env.num_envs)] + for env_idx in range(env.num_envs): + new_potential = self._potential_fcn(env, env_idx) + rewards[env_idx] = (self._potential[env_idx] - new_potential) * self._r_potential + # Update internal potential + self._potential[env_idx] = new_potential + return rewards, infos diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/reaching_goal_reward.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/reaching_goal_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..230bb8285444632ab8eeaffcc43c9e627a8a97f7 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/reaching_goal_reward.py @@ -0,0 +1,39 @@ +import torch as th + +import omnigibson.utils.transform_utils as T +from omnigibson.reward_functions.reward_function_base import BaseRewardFunction + + +class ReachingGoalReward(BaseRewardFunction): + """ + Reaching goal reward + Success reward for reaching the goal with the robot's end-effector + + Args: + robot_idn (int): robot identifier to evaluate point goal with. Default is 0, corresponding to the first + robot added to the scene + r_reach (float): reward for succeeding to reach the goal + distance_tol (float): Distance (m) tolerance between goal position and @robot_idn's robot eef position + that is accepted as a success + """ + + def __init__(self, robot_idn=0, r_reach=10.0, distance_tol=0.1): + # Store internal vars + self._robot_idn = robot_idn + self._r_reach = r_reach + self._distance_tol = distance_tol + + # Run super + super().__init__() + + def _step(self, task, env, action): + # Sparse reward is received if distance between robot_idn robot's eef and goal is below the distance threshold + rewards = th.zeros(env.num_envs, dtype=th.float32) + infos = [dict() for _ in range(env.num_envs)] + for env_idx in range(env.num_envs): + robot = env.scenes[env_idx].robots[self._robot_idn] + eef_pos = robot.get_eef_position() + dist = T.l2_distance(eef_pos, task.get_goal_pos(env_idx)) + if dist < self._distance_tol: + rewards[env_idx] = self._r_reach + return rewards, infos diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/reward_function_base.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/reward_function_base.py new file mode 100644 index 0000000000000000000000000000000000000000..3ec9bd2f6bcb682f6e843784682acae991586b57 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/reward_functions/reward_function_base.py @@ -0,0 +1,106 @@ +from abc import ABCMeta, abstractmethod +from copy import deepcopy + +import torch as th + +from omnigibson.utils.python_utils import Registerable, classproperty + +REGISTERED_REWARD_FUNCTIONS = dict() + + +class BaseRewardFunction(Registerable, metaclass=ABCMeta): + """ + Base RewardFunction class + Reward-specific reset and get_reward methods are implemented in subclasses + """ + + def __init__(self): + # Store internal vars that will be filled in at runtime + self._num_envs = None + self._reward = None + self._info = None + + @abstractmethod + def _step(self, task, env, action): + """ + Step the reward function and compute the reward at the current timestep. Overwritten by subclasses. + + Args: + task (BaseTask): Task instance + env (Environment): Environment instance + action (n-array): 1D flattened array of actions executed by all agents in the environment + + Returns: + 2-tuple: + - th.Tensor: (num_envs,) computed reward per env + - list[dict]: reward-related information per env + """ + raise NotImplementedError() + + def step(self, task, env, action): + """ + Step the reward function and compute the reward at the current timestep. + + Args: + task (BaseTask): Task instance + env (Environment): Environment instance + action (n-array): 1D flattened array of actions executed by all agents in the environment + + Returns: + 2-tuple: + - th.Tensor: (num_envs,) computed reward per env + - list[dict]: any reward-related information for this specific reward per env + """ + # Step internally and store output + self._reward, self._info = self._step(task=task, env=env, action=action) + + # Return reward and a copy of the info + return self._reward, deepcopy(self._info) + + def reset(self, task, env, env_indices): + """ + Reward function-specific reset + + Args: + task (BaseTask): Task instance + env (Environment): Environment instance + env_indices (th.Tensor): Indices of environments to reset + """ + if self._num_envs is None: + self._num_envs = env.num_envs + self._reward = th.zeros(self._num_envs, dtype=th.float32) + self._info = [dict() for _ in range(self._num_envs)] + self._reward[env_indices] = 0.0 + for idx in env_indices: + self._info[idx] = dict() + + @property + def reward(self): + """ + Returns: + th.Tensor: (num_envs,) current reward for this reward function + """ + assert self._reward is not None, "At least one step() must occur before reward can be calculated!" + return self._reward + + @property + def info(self): + """ + Returns: + list[dict]: Current info for this reward function per env + """ + assert self._info is not None, "At least one step() must occur before info can be calculated!" + return self._info + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("BaseRewardFunction") + return classes + + @classproperty + def _cls_registry(cls): + # Global registry + global REGISTERED_REWARD_FUNCTIONS + return REGISTERED_REWARD_FUNCTIONS diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/robots/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/robots/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3d1a5eb2aa5c7d157a9006728e8aab20748149b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/robots/__init__.py @@ -0,0 +1,14 @@ +from pathlib import Path +from omnigibson.robots.robot import Robot +from omnigibson.macros import gm + + +REGISTERED_ROBOTS = [] +for yaml_file in sorted(Path(gm.DATA_PATH).glob("*/models/*/*.yaml")): + if yaml_file.stem == yaml_file.parent.name: + REGISTERED_ROBOTS.append(yaml_file.stem) + +__all__ = [ + "Robot", + "REGISTERED_ROBOTS", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/robots/definition_schema.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/robots/definition_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..136c5bf21b635c131b175e35a1dfa5bd730817f6 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/robots/definition_schema.py @@ -0,0 +1,126 @@ +from dataclasses import dataclass +from typing import Any, Dict, List, Optional + + +# === Capability-specific definitions === +@dataclass +class EndEffectorDefinition: + """Definition for a specific end effector (gripper, robotiq, allegro, etc.)""" + + model: str + eef_link_names: Dict[str, str] + finger_link_names: Dict[str, List[str]] + finger_joint_names: Dict[str, List[str]] + default_joint_pos: List[Any] + teleop_rotation_offset: Optional[Dict[str, List[Any]]] = None + usd_path: Optional[str] = None + urdf_path: Optional[str] = None + curobo_path: Optional[str] = None + disabled_collision_pairs: Optional[List[List[str]]] = None + ag_start_points: Optional[List[List[Any]]] = None + ag_end_points: Optional[List[List[Any]]] = None + gripper_control_idx: Optional[List[int]] = None + not_support_urdf: bool = False + + +@dataclass +class ManipulationDefinition: + """Fields for manipulation robots""" + + n_arms: int = 1 + arm_names: Optional[List[str]] = None + arm_link_names: Optional[Dict[str, List[str]]] = None + arm_joint_names: Optional[Dict[str, List[str]]] = None + eef_link_names: Optional[Dict[str, str]] = None + finger_link_names: Optional[Dict[str, List[str]]] = None + finger_joint_names: Optional[Dict[str, List[str]]] = None + gripper_link_names: Optional[Dict[str, List[str]]] = None + arm_workspace_range: Optional[Dict[str, List[Any]]] = None + teleop_rotation_offset: Optional[Dict[str, List[Any]]] = None + supported_end_effector: Optional[List[str]] = None + eef_support_curobo_attached_object_link_names: Optional[List[str]] = None + end_effectors: Optional[Dict[str, EndEffectorDefinition]] = None + assisted_grasp_start_points: Optional[Dict[str, List[List[Any]]]] = None + assisted_grasp_end_points: Optional[Dict[str, List[List[Any]]]] = None + add_combined_arm_control_idx: bool = False + manipulation_link_names: Optional[List[str]] = None + + +@dataclass +class TwoWheelDefinition: + """Fields for two-wheel differential drive robots (wheel-specific params only)""" + + wheel_radius: float = 0.0 + wheel_axle_length: float = 0.0 + + +@dataclass +class HolonomicBaseDefinition: + """Fields for holonomic base robots""" + + force_sphere_wheel_approximation: bool = False + + +@dataclass +class ArticulatedTrunkDefinition: + """Fields for robots with articulated trunk""" + + trunk_joint_names: List[str] + trunk_link_names: Optional[List[str]] = None + + +@dataclass +class ActiveCameraDefinition: + """Fields for robots with controllable camera""" + + camera_joint_names: List[str] + + +@dataclass +class LocomotionDefinition: + """Fields for locomotion robots""" + + base_joint_names: Optional[List[str]] = None + floor_touching_base_link_names: Optional[List[str]] = None + + +@dataclass +class MobileManipulationDefinition: + """Fields for mobile manipulation robots (tuck/untuck and multiple arm poses)""" + + untucked_default_joint_pos: List[Any] + tucked_default_joint_pos: List[Any] + # Multiple arm pose support (optional) + default_arm_pose_key: Optional[str] = None + default_arm_poses: Optional[Dict[str, List[Any]]] = None + + +# === Main Robot Definition === +@dataclass +class RobotDefinition: + """ + Root configuration for a robot, with optional capability sub-configs. + """ + + raw_controller_order: List[str] + default_controllers: Dict[str, str] + default_joint_pos: Optional[List[Any]] = None + disabled_collision_pairs: Optional[List[List[str]]] = None + disabled_collision_link_names: Optional[List[Any]] = None + usd_path: Optional[str] = None + urdf_path: Optional[str] = None + curobo_path: Optional[str] = None + base_footprint_link_name: Optional[str] = None + visual_only_eef_links: bool = False + + self_collisions: Optional[bool] = None + linear_velocity_gain_for_primitives: Optional[float] = None + angular_velocity_gain_for_primitives: Optional[float] = None + + manipulation: Optional[ManipulationDefinition] = None + two_wheel: Optional[TwoWheelDefinition] = None + holonomic_base: Optional[HolonomicBaseDefinition] = None + locomotion: Optional[LocomotionDefinition] = None + articulated_trunk: Optional[ArticulatedTrunkDefinition] = None + active_camera: Optional[ActiveCameraDefinition] = None + mobile_manipulation: Optional[MobileManipulationDefinition] = None diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/robots/robot.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/robots/robot.py new file mode 100644 index 0000000000000000000000000000000000000000..ef2a0e1f6f020cc96e66c6da50a8fef2044c42d8 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/robots/robot.py @@ -0,0 +1,4276 @@ +import os +from copy import deepcopy +import math +import torch as th +from functools import cached_property +from omegaconf import OmegaConf + +from omnigibson.robots.definition_schema import ( + RobotDefinition, + EndEffectorDefinition, +) +from typing import Literal +from collections import namedtuple +import networkx as nx +import gymnasium as gym +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros, gm +from omnigibson.objects.usd_object import USDObject +from omnigibson.prims.rigid_dynamic_prim import RigidDynamicPrim +from omnigibson.sensors import ( + ALL_SENSOR_MODALITIES, + SENSOR_PRIMS_TO_SENSOR_CLS, + ScanSensor, + VisionSensor, + create_sensor, +) +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.utils.asset_utils import get_dataset_path +from omnigibson.utils.gym_utils import GymObservable +from omnigibson.utils.numpy_utils import NumpyTypes +from omnigibson.utils.python_utils import merge_nested_dicts, assert_valid_key +from omnigibson.utils.vision_utils import segmentation_to_rgb, change_pcd_frame +from omnigibson.utils.geometry_utils import wrap_angle +from omnigibson.controllers import ( + ControlType, + GripperController, + InverseKinematicsController, + IsGraspingState, + ManipulationController, + MultiFingerGripperController, + OperationalSpaceController, + LocomotionController, + JointController, + HolonomicBaseJointController, + DifferentialDriveController, + ControllerView, +) +from omnigibson.utils.ui_utils import create_module_logger, suppress_omni_log +from omnigibson.prims.geom_prim import GeomPrim +from omnigibson.utils.constants import JointType, PrimType, ROBOT_CATEGORY +from omnigibson.utils.sampling_utils import raytest_batch +from omnigibson.utils.usd_utils import ( + ControllableObjectViewAPI, + RigidContactAPI, + create_joint, + create_primitive_mesh, + absolute_prim_path_to_scene_relative, + delete_or_deactivate_prim, +) + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Add proprio sensor modality to ALL_SENSOR_MODALITIES +ALL_SENSOR_MODALITIES.add("proprio") + +RESET_JOINT_OPTIONS = { + "tuck", + "untuck", +} + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.ASSIST_GRASP_MASS_THRESHOLD = 10.0 +m.MIN_AG_DEFAULT_GRASP_POINT_PROP = 0.2 +m.MAX_AG_DEFAULT_GRASP_POINT_PROP = 0.95 +m.AG_DEFAULT_GRASP_POINT_Z_PROP = 0.4 +m.CONSTRAINT_VIOLATION_THRESHOLD = 0.1 +m.GRASP_WINDOW = 0.3 +m.RELEASE_WINDOW = 1 / 30.0 +m.MAX_LINEAR_VELOCITY = 1.5 +m.MAX_ANGULAR_VELOCITY = th.pi +m.MAX_EFFORT = 1000.0 +m.BASE_JOINT_CONTROLLER_POSITION_KP = 100.0 + + +AG_MODES = { + "physical", + "assisted", + "sticky", +} +GraspingPoint = namedtuple("GraspingPoint", ["link_name", "position"]) # link_name (str), position (x,y,z tuple) + +# Sentinel written before each grasping-arm block in the serialized state tensor. Should be: +# - Larger than the max UUID (10^8 - 1 = 99,999,999) to avoid false positives on UUID values +# - Exactly representable in float32 +# Old recordings that predate AG serialization will not contain this value, so the block is skipped. +_AG_MAGIC = 1e8 + 123456 +# Floats of payload per grasping arm (after the magic + arm_idx): [obj_uuid, link_idx, parent_pos(3), parent_orn(4), child_pos(3), child_orn(4), joint_type] +_AG_STATE_SIZE = 17 + + +class Robot(USDObject, GymObservable): + def __init__( + self, + # Shared kwargs in hierarchy + name, + model, + scale=None, + visible=True, + fixed_base=False, + visual_only=False, + self_collisions=True, + link_physics_materials=None, + load_config=None, + # Unique to USDObject hierarchy + abilities=None, + # Unique to Robot + control_freq=None, + controller_config=None, + action_type="continuous", + action_normalize=True, + reset_joint_pos=None, + obs_modalities=("rgb", "proprio"), + include_sensor_names=None, + exclude_sensor_names=None, + proprio_obs="default", + sensor_config=None, + # Unique to ManipulationRobot + grasping_mode="physical", + grasping_direction="lower", + disable_grasp_handling=False, + finger_static_friction=None, + finger_dynamic_friction=None, + # Unique to MobileManipulationRobot + default_reset_mode="untuck", + # Unique to robots with multiple arm poses + default_arm_pose=None, + # Unique to Tiago + variant="default", + # Unique to A1, Franka + end_effector="gripper", + **kwargs, + ): + """ + Args: + name (str): Name for the object. Names need to be unique per scene + model (str): Model of Robot. + scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale + for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a + 3-array specifies per-axis scaling. + visible (bool): whether to render this object or not in the stage + fixed_base (bool): whether to fix the base of this object or not + visual_only (bool): Whether this object should be visual only (and not collide with any other objects) + self_collisions (bool): Whether to enable self collisions for this object + link_physics_materials (None or dict): If specified, dictionary mapping link name to kwargs used to generate + a specific physical material for that link's collision meshes, where the kwargs are arguments directly + passed into the isaacsim.core.api.materials.physics_material.PhysicsMaterial constructor, e.g.: "static_friction", + "dynamic_friction", and "restitution" + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this prim at runtime. + abilities (None or dict): If specified, manually adds specific object states to this object. It should be + a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to + the object state instance constructor. + control_freq (float): control frequency (in Hz) at which to control the object. If set to be None, + we will automatically set the control frequency to be at the render frequency by default. + controller_config (None or dict): nested dictionary mapping controller name(s) to specific controller + configurations for this object. This will override any default values specified by this class. + action_type (str): one of {discrete, continuous} - what type of action space to use + action_normalize (bool): whether to normalize inputted actions. This will override any default values + specified by this class. + reset_joint_pos (None or n-array): if specified, should be the joint positions that the object should + be set to during a reset. If None (default), self._default_joint_pos will be used instead. + Note that _default_joint_pos are hardcoded & precomputed, and thus should not be modified by the user. + Set this value instead if you want to initialize the object with a different reset joint position. + obs_modalities (str or list of str): Observation modalities to use for this robot. Default is ["rgb", "proprio"]. + Valid options are "all", or a list containing any subset of omnigibson.sensors.ALL_SENSOR_MODALITIES. + Note: If @sensor_config explicitly specifies `modalities` for a given sensor class, it will + override any values specified from @obs_modalities! + include_sensor_names (None or list of str): If specified, substring(s) to check for in all raw sensor prim + paths found on the robot. A sensor must include one of the specified substrings in order to be included + in this robot's set of sensors + exclude_sensor_names (None or list of str): If specified, substring(s) to check against in all raw sensor + prim paths found on the robot. A sensor must not include any of the specified substrings in order to + be included in this robot's set of sensors + proprio_obs (str or list of str): proprioception observation key(s) to use for generating proprioceptive + observations. If str, should be exactly "default" -- this results in the default proprioception + observations being used, as defined by self.default_proprio_obs. See self._get_proprioception_dict + for valid key choices + sensor_config (None or dict): nested dictionary mapping sensor class name(s) to specific sensor + configurations for this object. This will override any default values specified by this class. + grasping_mode (str): One of {"physical", "assisted", "sticky"}. + If "physical", no assistive grasping will be applied (relies on contact friction + finger force). + If "assisted", will magnetize any object touching and within the gripper's fingers. In this mode, + at least two "fingers" need to touch the object. + If "sticky", will magnetize any object touching the gripper's fingers. In this mode, only one finger + needs to touch the object. + grasping_direction (str): One of {"lower", "upper"}. If "lower", lower limit represents a closed grasp, + otherwise upper limit represents a closed grasp. + disable_grasp_handling (bool): If True, the robot will not automatically handle assisted or sticky grasps. + Instead, you will need to call the grasp handling methods yourself. + finger_static_friction (None or float): If specified, specific static friction to use for robot's fingers + finger_dynamic_friction (None or float): If specified, specific dynamic friction to use for robot's fingers. + Note: If specified, this will override any ways that are found within @link_physics_materials for any + robot finger gripper links + default_reset_mode (str): Default reset mode for the robot. Should be one of: {"tuck", "untuck"} + If reset_joint_pos is not None, this will be ignored (since _default_joint_pos won't be used during initialization). + end_effector (str): The end effector type to use. + kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing + for flexible compositions of various object subclasses (e.g.: Robot is USDObject). + """ + self.model = model + # Read and validate robot definition YAML file using OmegaConf + definition_path = os.path.join( + get_dataset_path("omnigibson-robot-assets"), "models", self.model, self.model + ".yaml" + ) + yaml_definition = OmegaConf.load(definition_path) + schema = OmegaConf.structured(RobotDefinition) + merged_definition = OmegaConf.merge(schema, yaml_definition) + self._definition: RobotDefinition = OmegaConf.to_object(merged_definition) + + if self._definition.self_collisions is not None: + self_collisions = self._definition.self_collisions + + if self.has_end_effector_variants: + self.end_effector = end_effector + grasping_direction = "lower" if end_effector == "gripper" else "upper" + + if self.is_manipulation: + # Store relevant internal vars + assert_valid_key(key=grasping_mode, valid_keys=AG_MODES, name="grasping_mode") + assert_valid_key(key=grasping_direction, valid_keys=["lower", "upper"], name="grasping direction") + self._grasping_mode = grasping_mode + self._grasping_direction = grasping_direction + self._disable_grasp_handling = disable_grasp_handling + + # Other variables filled in at runtime + self._eef_to_fingertip_lengths = None # dict mapping arm name to finger name to offset + + # Initialize other variables used for assistive grasping + self._ag_obj_in_hand = {arm: None for arm in self.arm_names} + self._ag_obj_constraints = {arm: None for arm in self.arm_names} + self._ag_obj_constraint_params = { + arm: None for arm in self.arm_names + } # Opaque args for create_joint. Don't inspect. + self._ag_release_counter = {arm: None for arm in self.arm_names} + self._ag_grasp_counter = {arm: None for arm in self.arm_names} + + can_be_floating = self.is_locomotion and not self.is_holonomic_base + if not fixed_base and not can_be_floating: + log.warning(f"{self.model} is set to floating base but is not a non-holonomic locomotion robot") + fixed_base = fixed_base or not can_be_floating + + if self.is_holonomic_base: + self._world_base_fixed_joint_prim = None + + # Sanity check that the base controller is a HolonomicBaseJointController + if controller_config is not None and "base" in controller_config: + assert ( + controller_config["base"]["name"] == "HolonomicBaseJointController" + ), "Base controller must be a HolonomicBaseJointController!" + + if self.is_mobile_manipulation: + assert_valid_key(key=default_reset_mode, valid_keys=RESET_JOINT_OPTIONS, name="default_reset_mode") + self.default_reset_mode = default_reset_mode + + if self.has_multiple_arm_poses: + if default_arm_pose is not None: + assert_valid_key(key=default_arm_pose, valid_keys=self.default_arm_poses, name="default_arm_pose") + else: + default_arm_pose = self._definition.mobile_manipulation.default_arm_pose_key + self.default_arm_pose = default_arm_pose + + # Store robot-specific inputs + self._obs_modalities = ( + obs_modalities + if obs_modalities == "all" + else {obs_modalities} + if isinstance(obs_modalities, str) + else set(obs_modalities) + ) # this will get updated later when we fill in our sensors + self._proprio_obs = self.default_proprio_obs if proprio_obs == "default" else list(proprio_obs) + self._sensor_config = sensor_config + + # Process abilities + robot_abilities = {"robot": {}} + abilities = robot_abilities if abilities is None else robot_abilities.update(abilities) + + # Initialize internal attributes that will be loaded later + self._include_sensor_names = None if include_sensor_names is None else set(include_sensor_names) + self._exclude_sensor_names = None if exclude_sensor_names is None else set(exclude_sensor_names) + self._sensors = None # e.g.: scan sensor, vision sensor + + # Per-robot rigid contact view, used for reading contact positions between the robot's finger + # links and any other rigid body in the scene for assisted grasping. The view is rebuilt every + # time update_handles runs so new/removed bodies are picked up. + self._rigid_contact_view = None + self._rigid_contact_view_row_path_to_idx = {} + self._rigid_contact_view_col_path_to_idx = {} + + # All BaseRobots should have xform properties pre-loaded + load_config = {} if load_config is None else load_config + load_config["xform_props_pre_loaded"] = True + + # Store control-related inputs + self._control_freq = control_freq + self._controller_config = controller_config + if reset_joint_pos is None: + self._reset_joint_pos = None + elif isinstance(reset_joint_pos, th.Tensor): + self._reset_joint_pos = reset_joint_pos + else: + self._reset_joint_pos = th.tensor(reset_joint_pos, dtype=th.float) + + # Make sure action type is valid, and also save + assert_valid_key(key=action_type, valid_keys={"discrete", "continuous"}, name="action type") + self._action_type = action_type + self._action_normalize = action_normalize + + # Store internal placeholders that will be filled in later + self._dof_to_joints = None # dict that will map DOF indices to JointPrims + self._last_action = None + self._controllers = None + self.dof_names_ordered = None + self._control_enabled = True + + relative_prim_path = f"/controllable__{self.robot_type.lower()}__{name}" + + # Run super init + super().__init__( + relative_prim_path=relative_prim_path, + usd_path=self.usd_path, + name=name, + category=ROBOT_CATEGORY, + scale=scale, + visible=visible, + fixed_base=fixed_base, + visual_only=visual_only, + self_collisions=self_collisions, + prim_type=PrimType.RIGID, + include_default_states=True, + link_physics_materials=link_physics_materials, + load_config=load_config, + abilities=abilities, + **kwargs, + ) + + assert not isinstance(self._load_config["scale"], th.Tensor) or th.all( + self._load_config["scale"] == self._load_config["scale"][0] + ), f"Robot scale must be uniform! Got: {self._load_config['scale']}" + + if self.is_manipulation: + # Update finger link material dictionary based on desired values + if finger_static_friction is not None or finger_dynamic_friction is not None: + for arm, finger_link_names in self.finger_link_names.items(): + for finger_link_name in finger_link_names: + if finger_link_name not in self._link_physics_materials: + self._link_physics_materials[finger_link_name] = dict() + if finger_static_friction is not None: + self._link_physics_materials[finger_link_name]["static_friction"] = finger_static_friction + if finger_dynamic_friction is not None: + self._link_physics_materials[finger_link_name]["dynamic_friction"] = finger_dynamic_friction + + @property + def is_two_wheel(self) -> bool: + """Returns True if this robot has a two-wheel differential drive base.""" + return self._definition.two_wheel is not None + + @property + def is_holonomic_base(self) -> bool: + """Returns True if this robot has a holonomic base.""" + return self._definition.holonomic_base is not None + + @property + def is_articulated_trunk(self) -> bool: + """Returns True if this robot has an articulated trunk.""" + return self._definition.articulated_trunk is not None + + @property + def is_active_camera(self) -> bool: + """Returns True if this robot has an active (controllable) camera.""" + return self._definition.active_camera is not None + + @property + def has_multiple_arm_poses(self) -> bool: + """Returns True if this robot has multiple arm pose configurations.""" + return ( + self._definition.mobile_manipulation is not None + and self._definition.mobile_manipulation.default_arm_poses is not None + ) + + @property + def is_mobile_manipulation(self) -> bool: + """Returns True if this robot is a mobile manipulation robot.""" + return self._definition.mobile_manipulation is not None + + @property + def is_manipulation(self) -> bool: + """Returns True if this robot has manipulation capabilities.""" + return self._definition.manipulation is not None or self.is_mobile_manipulation or self.is_articulated_trunk + + @property + def is_locomotion(self) -> bool: + """Returns True if this robot has locomotion capabilities.""" + return self.is_holonomic_base or self.is_two_wheel or self._definition.locomotion is not None + + @property + def linear_velocity_gain_for_primitives(self) -> float: + """Returns the linear velocity proportional gain for action primitives.""" + assert ( + self._definition.linear_velocity_gain_for_primitives is not None + ), f"linear_velocity_gain_for_primitives not defined for robot {self.model}" + return self._definition.linear_velocity_gain_for_primitives + + @property + def angular_velocity_gain_for_primitives(self) -> float: + """Returns the angular velocity proportional gain for action primitives.""" + assert ( + self._definition.angular_velocity_gain_for_primitives is not None + ), f"angular_velocity_gain_for_primitives not defined for robot {self.model}" + return self._definition.angular_velocity_gain_for_primitives + + @property + def has_end_effector_variants(self) -> bool: + """Returns True if this robot supports multiple end effector types.""" + return ( + self._definition.manipulation is not None + and self._definition.manipulation.supported_end_effector is not None + ) + + def _convert_to_grasping_points(self, points): + """Converts raw assisted grasp point definitions into an arm-keyed dict of GraspingPoint entries.""" + + def _convert_point_list(point_list): + if point_list is None: + return None + result = [] + for link_name, position in point_list: + result.append(GraspingPoint(link_name=link_name, position=th.tensor(position))) + return result + + if points is None: + return None + + return {arm: _convert_point_list(points.get(arm)) for arm in self.arm_names} + + def _get_end_effector_definition(self) -> "EndEffectorDefinition | None": + """Get the current end effector configuration if this robot has end effector variants.""" + if not self.has_end_effector_variants: + return None + return self._definition.manipulation.end_effectors.get(self.end_effector) + + @property + def robot_type(self): + """ + A string identifying this robot's physical configuration type, embedded in its USD + prim path as ``controllable__{robot_type}__``. + + Unlike :attr:`model` (always this robot's own model name), this returns the active + end-effector's model name when an EEF variant is configured — because EEF swaps + change the joint structure and must be grouped separately in batched articulation views. + + Used by `omnigibson.utils.usd_utils.get_robot_kinematic_tree_pattern` to generate + glob patterns for batched view grouping. + """ + if self._definition.manipulation and self._definition.manipulation.supported_end_effector: + eef_def = self._get_end_effector_definition() + if eef_def and eef_def.model: + return eef_def.model + return self.model + + def load(self, scene): + # Run super first + prim = super().load(scene) + + # Set the control frequency if one was not provided. + expected_control_freq = 1.0 / og.sim.get_sim_step_dt() + if self._control_freq is None: + log.info( + "Control frequency is None - being set to default of render_frequency: %.4f", expected_control_freq + ) + self._control_freq = expected_control_freq + else: + assert math.isclose( + expected_control_freq, self._control_freq + ), "Stored control frequency does not match environment's render timestep." + + return prim + + def _post_load(self): + # Run super post load first + super()._post_load() + + # For controllable objects, we disable gravity of all links that are not fixed to the base link. + # This is because we cannot accurately apply gravity compensation in the absence of a working + # generalized gravity force computation. This may have some side effects on the measured + # torque on each of these links, but it provides a greatly improved joint control behavior. + # Note that we do NOT disable gravity for links that are fixed to the base link, as these links + # are typically where most of the downward force on the robot is applied. Disabling gravity + # for these links would result in the robot floating in the air easily. Also note that here + # we use the base link footprint which takes into account the presence of virtual joints. + fixed_link_names = self.get_fixed_link_names_in_subtree(self.base_footprint_link_name) + + # Find the links that are NOT fixed. + other_link_names = set(self.links.keys()) - fixed_link_names + + # Disable gravity for those links. + for link_name in other_link_names: + self.links[link_name].disable_gravity() + + # Load the sensors + self._load_sensors() + + if self.is_holonomic_base: + self._world_base_fixed_joint_prim = lazy.isaacsim.core.utils.prims.get_prim_at_path( + f"{self.prim_path}/rootJoint" + ) + position, orientation = self.get_position_orientation() + # Set the world-to-base fixed joint to be at the robot's current pose + with og.sim.editing_usd(): + self._world_base_fixed_joint_prim.GetAttribute("physics:localPos0").Set(tuple(position)) + self._world_base_fixed_joint_prim.GetAttribute("physics:localRot0").Set( + lazy.pxr.Gf.Quatf(*orientation[[3, 0, 1, 2]].tolist()) + ) + + force_sphere = ( + self.is_holonomic_base + and self._definition.holonomic_base + and self._definition.holonomic_base.force_sphere_wheel_approximation + ) + if force_sphere: + # R1 and R1Pro's URDFs still use the mesh type for the collision meshes of the wheels + # We need to manually set it back to sphere approximation + for wheel_name in self.floor_touching_base_link_names: + wheel_link = self.links[wheel_name] + assert len(wheel_link.collision_meshes) == 1, "Wheel link should only have 1 collision!" + wheel_link.set_collision_approximation("boundingSphere") + if self._definition.visual_only_eef_links: + # The eef gripper links should be visual-only. They only contain a "ghost" box volume + # for detecting objects inside the gripper, in order to activate attachments (AG for Cloths). + for arm in self.arm_names: + self.eef_links[arm].visual_only = True + self.eef_links[arm].visible = False + + def _load_controllers(self): + """ + Loads controller(s) to map inputted actions into executable (pos, vel, and / or effort) signals on this object. + Stores created controllers as dictionary mapping controller names to specific controller + instances used by this object. + """ + # Generate the controller config + self._controller_config = self._generate_controller_config(custom_config=self._controller_config) + + # We copy the controller config here because we add/remove some keys in-place that shouldn't persist + _controller_config = deepcopy(self._controller_config) + + # Store dof idx mapping to dof name + self.dof_names_ordered = list(self._joints.keys()) + + # Initialize controllers to create + self._controllers = dict() + # Keep track of any controllers that are subsumed by other controllers + # We will not instantiate subsumed controllers + controller_subsumes = dict() # Maps independent controller name to list of subsumed controllers + subsume_names = set() + for name in self._raw_controller_order: + # Make sure we have the valid controller name specified + assert_valid_key(key=name, valid_keys=_controller_config, name="controller name") + cfg = _controller_config[name] + subsume_controllers = cfg.pop("subsume_controllers", []) + # If this controller subsumes other controllers, it cannot be subsumed by another controller + # (i.e.: we don't allow nested / cyclical subsuming) + if len(subsume_controllers) > 0: + assert ( + name not in subsume_names + ), f"Controller {name} subsumes other controllers, and therefore cannot be subsumed by another controller!" + controller_subsumes[name] = subsume_controllers + for subsume_name in subsume_controllers: + # Make sure it doesn't already exist -- a controller should only be subsumed by up to one other + assert ( + subsume_name not in subsume_names + ), f"Controller {subsume_name} cannot be subsumed by more than one other controller!" + assert ( + subsume_name not in controller_subsumes + ), f"Controller {name} subsumes other controllers, and therefore cannot be subsumed by another controller!" + subsume_names.add(subsume_name) + + # Loop over all controllers, in the order corresponding to @action dim + for name in self._raw_controller_order: + # If this controller is subsumed by another controller, simply skip it + if name in subsume_names: + continue + cfg = _controller_config[name] + # If we subsume other controllers, prepend the subsumed' dof idxs to this controller's idxs + if name in controller_subsumes: + for subsumed_name in controller_subsumes[name]: + subsumed_cfg = _controller_config[subsumed_name] + cfg["dof_idx"] = th.concatenate([subsumed_cfg["dof_idx"], cfg["dof_idx"]]) + # If we're using normalized action space, override the inputs for all controllers + if self._action_normalize: + cfg["command_input_limits"] = "default" # default is normalized (-1, 1) + + # Determine link_name for arm or trunk controllers (used by IK/OSC) + link_name = None + if self.is_manipulation: + for arm in self.arm_names: + if name == f"arm_{arm}": + link_name = self.eef_link_names[arm] + if self.is_articulated_trunk: + if name == "trunk": + link_name = self.joints[self.trunk_joint_names[-1]].body1.split("/")[-1] + + # Register with ControllerView — creates the shared controller if it doesn't exist yet, + # then adds this robot as a member and returns its per-member index. + group_key, controller_idx = ControllerView.register( + body_part=name, + controller_cfg=cfg, + articulation_root_path=self.articulation_root_path, + link_name=link_name, + control_enabled=self.control_enabled, + ) + # Verify the controller's DOFs can all be driven + for idx in ControllerView.get_dof_idx(group_key).tolist(): + assert self._joints[ + self.dof_names_ordered[idx] + ].driven, "Controllers should only control driveable joints!" + self._controllers[name] = (group_key, controller_idx) + self.update_controller_mode() + + def update_controller_mode(self): + """ + Helper function to force the joints to use the internal specified control mode and gains + """ + # Update the control modes of each joint based on the outputted control from the controllers + unused_dofs = {i for i in range(self.n_dof)} + for group_key, _ in self._controllers.values(): + isaac_kp = ControllerView.get_isaac_kp(group_key) + isaac_kd = ControllerView.get_isaac_kd(group_key) + control_type = ControllerView.get_control_type(group_key) + for i, dof in enumerate(ControllerView.get_dof_idx(group_key).tolist()): + # Make sure the DOF has not already been set yet, and remove it afterwards + assert dof in unused_dofs + unused_dofs.remove(dof) + dof_joint = self._joints[self.dof_names_ordered[dof]] + dof_joint.set_control_type( + control_type=control_type, + kp=None if isaac_kp is None or dof_joint.is_mimic_joint else isaac_kp[i], + kd=None if isaac_kd is None or dof_joint.is_mimic_joint else isaac_kd[i], + ) + + # For all remaining DOFs not controlled, we assume these are free DOFs (e.g.: virtual joints representing free + # motion wrt a specific axis), so explicitly set kp / kd to 0 to avoid silent bugs when + # joint positions / velocities are set + for unused_dof in unused_dofs: + unused_joint = self._joints[self.dof_names_ordered[unused_dof]] + assert not unused_joint.driven, ( + f"All unused joints not mapped to any controller should not have DriveAPI attached to it! " + f"However, joint {unused_joint.name} is driven!" + ) + unused_joint.set_control_type( + control_type=ControlType.NONE, + kp=None, + kd=None, + ) + + def _generate_controller_config(self, custom_config=None): + """ + Generates a fully-populated controller config, overriding any default values with the corresponding values + specified in @custom_config + + Args: + custom_config (None or Dict[str, ...]): nested dictionary mapping controller name(s) to specific custom + controller configurations for this object. This will override any default values specified by this class + + Returns: + dict: Fully-populated nested dictionary mapping controller name(s) to specific controller configurations for + this object + """ + controller_config = {} if custom_config is None else deepcopy(custom_config) + + # Update the configs + for group in self._raw_controller_order: + group_controller_name = ( + controller_config[group]["name"] + if group in controller_config and "name" in controller_config[group] + else self._default_controllers[group] + ) + controller_config[group] = merge_nested_dicts( + base_dict=self._default_controller_config[group][group_controller_name], + extra_dict=controller_config.get(group, {}), + ) + + return controller_config + + def reload_controllers(self, controller_config=None): + """ + Reloads controllers based on the specified new @controller_config + + Args: + controller_config (None or Dict[str, ...]): nested dictionary mapping controller name(s) to specific + controller configurations for this object. This will override any default values specified by this class. + """ + self._controller_config = {} if controller_config is None else controller_config + + # Remove only this robot's controller groups from ControllerView so it re-registers fresh. + # Other robots' groups are preserved. + ControllerView.unregister_robot(self._controllers) + + # (Re-)load controllers + self._load_controllers() + + # (Re-)create the action space + self._action_space = ( + self._create_discrete_action_space() + if self._action_type == "discrete" + else self._create_continuous_action_space() + ) + + def reset(self): + if self.is_holonomic_base: + base_joint_positions = self.get_joint_positions()[self.base_idx] + # Call super first + super().reset() + + # Override the reset joint state based on reset values + self.set_joint_positions(positions=self._reset_joint_pos, drive=False) + + if self.is_holonomic_base: + self.set_joint_positions(base_joint_positions, indices=self.base_idx) + + def _create_continuous_action_space(self): + """ + Create a continuous action space for this object. By default, this loops over all controllers and + appends their respective input command limits to set the action space. + Any custom behavior should be implemented by the subclass (e.g.: if a subclass does not + support this type of action space, it should raise an error). + + Returns: + gym.space.Box: Object-specific continuous action space + """ + # Action space is ordered according to the order in _default_controller_config control + low, high = [], [] + for group_key, _ in self._controllers.values(): + limits = ControllerView.get_command_input_limits(group_key) + cmd_dim = ControllerView.get_command_dim(group_key) + low.append(th.tensor([-float("inf")] * cmd_dim) if limits is None else limits[0]) + high.append(th.tensor([float("inf")] * cmd_dim) if limits is None else limits[1]) + + return gym.spaces.Box( + shape=(self.action_dim,), + low=th.cat(low).numpy(), + high=th.cat(high).numpy(), + dtype=NumpyTypes.FLOAT32, + ) + + def apply_action(self, action): + """ + Converts inputted actions into low-level control signals + + NOTE: This does NOT deploy control on the object. Use self.step() instead. + + Args: + action (n-array): n-DOF length array of actions to apply to this object's internal controllers + """ + if self.is_holonomic_base: + rz_joint_dof_indices = self.joints["base_footprint_rz_joint"].dof_indices + j_pos = self.get_joint_positions()[rz_joint_dof_indices] + # In preparation for the base controller's @update_goal, we need to wrap the current joint pos + # to be in range [-pi, pi], so that once the command (a delta joint pos in range [-pi, pi]) + # is applied, the final target joint pos is in range [-pi * 2, pi * 2], which is required by Isaac. + if j_pos < -math.pi or j_pos > math.pi: + j_pos = wrap_angle(j_pos) + self.set_joint_positions(j_pos, indices=rz_joint_dof_indices, drive=False) + + # Store last action as the current action being applied + self._last_action = action + + # If we're using discrete action space, we grab the specific action and use that to convert to control + if self._action_type == "discrete": + action = th.tensor(self.discrete_action_list[action], dtype=th.float32) + + # Sanity check that action is 1D array + assert len(action.shape) == 1, f"Action must be 1D array, got {len(action.shape)}D array!" + + # Sanity check that action is 1D array + assert len(action.shape) == 1, f"Action must be 1D array, got {len(action.shape)}D array!" + + # Check if the input action's length matches the action dimension + assert len(action) == self.action_dim, "Action must be dimension {}, got dim {} instead.".format( + self.action_dim, len(action) + ) + + # First, loop over all controllers, and update the desired command + idx = 0 + for group_key, controller_idx in self._controllers.values(): + command_dim = ControllerView.get_command_dim(group_key) + # Set command for this robot's slot in the shared batch controller + ControllerView.update_goal(group_key, controller_idx, action[idx : idx + command_dim]) + # Update idx + idx += command_dim + + @property + def is_driven(self) -> bool: + """ + Returns: + bool: Whether this object is actively controlled/driven or not + """ + return True + + @property + def control_enabled(self): + return self._control_enabled + + @control_enabled.setter + def control_enabled(self, value): + self._control_enabled = value + for group_key, controller_idx in self._controllers.values(): + ControllerView.set_control_enabled(group_key, controller_idx, value) + + def post_step(self): + """ + Run per-robot assisted grasping logic after ControllerView.step_all() writes controls to the Isaac buffer + but before the ControllableObjectViewAPI flushes buffered articulation commands for the step. + """ + if not self.control_enabled: + return + if self._articulation_view is None: + return + if self.is_manipulation: + if self.grasping_mode != "physical" and not self._disable_grasp_handling: + self._handle_assisted_grasping() + + def _handle_assisted_grasping(self): + """ + Handles assisted grasping by creating or removing constraints. + """ + assert self.is_manipulation + # Loop over all arms + for arm in self.arm_names: + # We apply a threshold based on the control rather than the command here so that the behavior + # stays the same across different controllers and control modes (absolute / delta). This way, + # a zero action will actually keep the AG setting where it already is. + group_key, controller_idx = self._controllers[f"gripper_{arm}"] + controlled_joints = ControllerView.get_dof_idx(group_key) + control = ControllerView.get_control(group_key, controller_idx) + if control is None: + applying_grasp = False + else: + if self._grasping_direction == "lower": + applying_grasp = ( + th.any(control < self.joint_upper_limits[controlled_joints]) + if ControllerView.get_control_type(group_key) == ControlType.POSITION + else th.any(control < 0) + ) + else: + applying_grasp = ( + th.any(control > self.joint_lower_limits[controlled_joints]) + if ControllerView.get_control_type(group_key) == ControlType.POSITION + else th.any(control > 0) + ) + # Execute gradual release of object + if self._ag_obj_in_hand[arm]: + if self._ag_release_counter[arm] is not None: + self._handle_release_window(arm=arm) + else: + if not applying_grasp: + self._release_grasp(arm=arm) + elif applying_grasp: + ag_target_object_and_link_name = self._calculate_in_hand_object(arm=arm) + if self._ag_grasp_counter[arm] is not None: + # We're in a grasp window already + if ag_target_object_and_link_name is None: + # Lost contact with object, reset window + self._ag_grasp_counter[arm] = None + else: + self._ag_grasp_counter[arm] += 1 + + # Check if window is complete + time_in_grasp = self._ag_grasp_counter[arm] * og.sim.get_physics_dt() + if time_in_grasp >= m.GRASP_WINDOW: + # Consider establishing a grasp + target_obj, target_link_name = ag_target_object_and_link_name + self._maybe_establish_grasp( + target_obj=target_obj, target_link_name=target_link_name, arm=arm + ) + + # Reset the grasp window tracking + self._ag_grasp_counter[arm] = None + + elif ag_target_object_and_link_name is not None: + # Start tracking a new potential grasp + self._ag_grasp_counter[arm] = 0 + else: + # Not trying to grasp, reset any pending grasp window + self._ag_grasp_counter[arm] = None + + def dump_action(self): + """ + Dump the last action applied to this object. For use in demo collection. + """ + return self._last_action + + def set_position_orientation( + self, position=None, orientation=None, frame: Literal["world", "parent", "scene"] = "world" + ): + """ + Sets robot's pose with respect to the specified frame + ... + """ + assert frame in ["world", "scene"], f"Invalid frame '{frame}'. Must be 'world' or 'scene'." + + # Store the original EEF poses for restoring AG later. + if self.is_manipulation: + original_poses = {} + for arm in self.arm_names: + original_poses[arm] = (self.get_eef_position(arm), self.get_eef_orientation(arm)) + + # Move the robot. We need to do different stuff if it's a holonomic base. + if self.is_holonomic_base: + # If no position or no orientation are given, get the current position and orientation of the object + if position is None or orientation is None: + current_position, current_orientation = self.get_position_orientation(frame=frame) + position = current_position if position is None else position + orientation = current_orientation if orientation is None else orientation + + # Convert to th.Tensor if necessary + position = th.as_tensor(position, dtype=th.float32) + orientation = th.as_tensor(orientation, dtype=th.float32) + + # Convert to from scene-relative to world if necessary + if frame == "scene": + assert self.scene is not None, "cannot set position and orientation relative to scene without a scene" + position, orientation = self.scene.convert_scene_relative_pose_to_world(position, orientation) + + # If the simulator is playing, set the 6 base joints to achieve the desired pose of base_footprint link frame + if og.sim.is_playing() and self.initialized: + # Find the relative transformation from base_footprint_link ("base_footprint") frame to root_link + # ("base_footprint_x") frame. Assign it to the 6 1DoF joints that control the base. + # Note that the 6 1DoF joints are originated from the root_link ("base_footprint_x") frame. + joint_pos, joint_orn = self.root_link.get_position_orientation() + inv_joint_pos, inv_joint_orn = T.invert_pose_transform(joint_pos, joint_orn) + relative_pos, relative_orn = T.pose_transform(inv_joint_pos, inv_joint_orn, position, orientation) + intrinsic_eulers = T.mat2euler_intrinsic(T.quat2mat(relative_orn)) + joint_positions = th.concatenate((relative_pos, intrinsic_eulers)) + self.set_joint_positions(positions=joint_positions, indices=self.base_idx, drive=False) + + # Else, set the pose of the robot frame, and then move the joint frame of the world_base_joint to match it + else: + # Call the super() method to move the robot frame first. Note that we use world frame since we have done + # the conversion to world frame already in the code block before this conditional. + super().set_position_orientation(position, orientation, frame="world") + # Move the joint frame for the world_base_joint + if self._world_base_fixed_joint_prim is not None: + with og.sim.editing_usd(): + self._world_base_fixed_joint_prim.GetAttribute("physics:localPos0").Set(tuple(position)) + self._world_base_fixed_joint_prim.GetAttribute("physics:localRot0").Set( + lazy.pxr.Gf.Quatf(*orientation[[3, 0, 1, 2]].tolist()) + ) + else: + super().set_position_orientation(position, orientation, frame) + + # Clear the controllable view's backend since state has changed + ControllableObjectViewAPI.clear_object(prim_path=self.articulation_root_path) + + # Now for each hand, if it was holding an AG object, teleport it. + if self.is_manipulation: + for arm in self.arm_names: + if self._ag_obj_in_hand[arm] is not None: + original_eef_pose = T.pose2mat(original_poses[arm]) + inv_original_eef_pose = T.pose_inv(pose_mat=original_eef_pose) + original_obj_pose = T.pose2mat(self._ag_obj_in_hand[arm].get_position_orientation()) + new_eef_pose = T.pose2mat((self.get_eef_position(arm), self.get_eef_orientation(arm))) + # New object pose is transform: + # original --> "De"transform the original EEF pose --> "Re"transform the new EEF pose + new_obj_pose = new_eef_pose @ inv_original_eef_pose @ original_obj_pose + self._ag_obj_in_hand[arm].set_position_orientation(*T.mat2pose(hmat=new_obj_pose)) + + def set_joint_positions(self, positions, indices=None, normalized=False, drive=False): + # Call super first + super().set_joint_positions(positions=positions, indices=indices, normalized=normalized, drive=drive) + + # If we're not driving the joints, reset the controllers so that the goals are updated wrt to the new state + # Also clear the controllable view's backend since state has changed + if not drive and self._controllers is not None: + ControllableObjectViewAPI.clear_object(prim_path=self.articulation_root_path) + for group_key, controller_idx in self._controllers.values(): + ControllerView.reset(group_key, controller_idx) + + def _dump_state(self): + # Grab super state + state = super()._dump_state() + + # Dump controllers + controller_states = {} + for controller_name, (group_key, controller_idx) in self._controllers.items(): + controller_states[controller_name] = ControllerView.dump_state(group_key, controller_idx) + state["controller_groups"] = controller_states + + # If we're using actual physical grasping, no extra state needed to save + if self.is_manipulation and self.grasping_mode != "physical": + # Include AG state + state["ag_obj_constraint_params"] = {} + for arm, ag_params_for_arm in self._ag_obj_constraint_params.items(): + if ag_params_for_arm is not None: + # Make a copy so that the original is not mutated + state["ag_obj_constraint_params"][arm] = ag_params_for_arm.copy() + + # Change the object reference to be the object name instead of the object itself + state["ag_obj_constraint_params"][arm]["target_obj"] = state["ag_obj_constraint_params"][arm][ + "target_obj" + ].name + + return state + + def _load_state(self, state): + # Run super first + super()._load_state(state=state) + + # Load controllers + for controller_name, (group_key, controller_idx) in self._controllers.items(): + controller_state = state["controller_groups"].get(controller_name) + if controller_state is not None: + ControllerView.load_state(group_key, controller_idx, controller_state) + + if self.is_manipulation: + # No additional loading needed if we're using physical grasping + if self.grasping_mode == "physical": + return + + # Load AG state + # TODO: add unit tests + for arm in self.arm_names: + current_ag_constraint = self._ag_obj_constraint_params[arm] + + loaded_ag_constraint = None + if ( + "ag_obj_constraint_params" in state + and arm in state["ag_obj_constraint_params"] + and state["ag_obj_constraint_params"][arm] + ): + # Get this arm's constraint + loaded_ag_constraint = state["ag_obj_constraint_params"][arm].copy() + + # If it's the legacy format, convert it to the new format + if "contact_pos" in loaded_ag_constraint: + # Find the object and the appropriate joint type + target_obj = self.scene.object_registry("prim_path", loaded_ag_constraint["ag_obj_prim_path"]) + target_link_name = loaded_ag_constraint["ag_link_prim_path"].split("/")[-1] + joint_type = self._get_assisted_grasp_joint_type(target_obj, target_link_name) + assert joint_type in ["FixedJoint", "SphericalJoint"], "Failed to get assisted grasp joint type" + + # Here we address a major bug: the original "contact_pos" was the position of the contact point at the start + # of the grasp, but it is possible that the objects have moved since then. We thus do not know where the joint + # is supposed to go. We make a best-effort guess by taking the current position of the EEF. + # For a FixedJoint, this is perfectly fine, since the joint position and orientation don't actually matter. + # But for a SphericalJoint, it is quite problematic, because the relative rotation pivot of the two objects + # will now have changed. So we need to warn the user. + contact_pos_world = self.get_eef_position(arm) + if joint_type == "SphericalJoint": + log.warning( + "You are restoring a robot state that was saved with a previous version of OmniGibson that had a bug " + "in the assisted grasp functionality. The saved state contains an assisted grasp of a moving link, which " + "uses a spherical joint. However, in that version of OmniGibson, the spherical joint position was not stored " + "correctly in the saved state. As a result, we are making a best-effort guess for the relative pivot point " + "of the two objects, which is guaranteed to be inaccurate and different from the original position. We recommend " + "that you re-record the state with the current version of OmniGibson." + f"The target object is {target_obj.name} and the link is {target_link_name}, being grasped by the {arm} arm of robot {self.name}." + ) + + # Need to find distance between robot and contact point in robot link's local frame and + # ag link and contact point in ag link's local frame + joint_frame_orn = th.tensor([0, 0, 0, 1.0]) + eef_link_pos, eef_link_orn = self.eef_links[arm].get_position_orientation() + parent_frame_pos, parent_frame_orn = T.relative_pose_transform( + contact_pos_world, joint_frame_orn, eef_link_pos, eef_link_orn + ) + parent_frame_pos = parent_frame_pos / self.scale + obj_link_pos, obj_link_orn = target_obj.links[target_link_name].get_position_orientation() + child_frame_pos, child_frame_orn = T.relative_pose_transform( + contact_pos_world, joint_frame_orn, obj_link_pos, obj_link_orn + ) + child_frame_pos = child_frame_pos / target_obj.scale + + # Compile the constraint params dict + loaded_ag_constraint = { + "target_obj": target_obj.name, # Here we use the name since this is what we saved in the state - it's converted to the object itself later + "target_link_name": target_link_name, + "parent_frame_pos": parent_frame_pos, + "parent_frame_orn": parent_frame_orn, + "child_frame_pos": child_frame_pos, + "child_frame_orn": child_frame_orn, + "joint_type": joint_type, + } + + # Convert the target object name back to the object itself. + loaded_ag_constraint["target_obj"] = self.scene.object_registry( + "name", loaded_ag_constraint["target_obj"] + ) + assert loaded_ag_constraint["target_obj"] is not None, "Target object not found in scene" + + # Release existing grasp if needed + should_release = False + if current_ag_constraint: + if loaded_ag_constraint is None: + should_release = True + else: + # Check if constraints are different + are_equal = current_ag_constraint.keys() == loaded_ag_constraint.keys() and all( + th.equal(v1, v2) if isinstance(v1, th.Tensor) and isinstance(v2, th.Tensor) else v1 == v2 + for v1, v2 in zip(current_ag_constraint.values(), loaded_ag_constraint.values()) + ) + should_release = not are_equal + + if should_release: + self.release_grasp_immediately(arm=arm) + + # Create new assisted grasp joint if needed + if loaded_ag_constraint is not None and (current_ag_constraint is None or should_release): + self._create_assisted_grasp_joint(arm, loaded_ag_constraint) + + def serialize(self, state): + # Run super first + state_flat = super().serialize(state=state) + + # Serialize each controller entry separately + group_parts = [] + for controller_name, (group_key, controller_idx) in self._controllers.items(): + controller_state = state["controller_groups"].get(controller_name) + if controller_state is None and group_key in state["controller_groups"]: + controller_state = state["controller_groups"][group_key] + if controller_state is not None: + group_parts.append(ControllerView.serialize(group_key, controller_idx, controller_state)) + if group_parts: + state_flat = th.cat([state_flat] + group_parts) + + if self.is_manipulation and self.grasping_mode != "physical": + ag_params = state.get("ag_obj_constraint_params", {}) + # One block per grasping arm, each prefixed with the magic sentinel and arm_idx. + # Non-grasping arms are omitted entirely, and old recordings that predate AG + # serialization simply have no trailing magic — deserialize() skips cleanly. + ag_parts = [] + for arm_idx, arm in enumerate(self.arm_names): + arm_params = ag_params.get(arm) + if arm_params is None: + continue + target_obj = self.scene.object_registry("name", arm_params["target_obj"]) + link_names = sorted(target_obj.links.keys()) + link_idx = link_names.index(arm_params["target_link_name"]) + ag_parts.append( + th.tensor( + [ + _AG_MAGIC, + float(arm_idx), + float(target_obj.uuid), + float(link_idx), + *arm_params["parent_frame_pos"].tolist(), + *arm_params["parent_frame_orn"].tolist(), + *arm_params["child_frame_pos"].tolist(), + *arm_params["child_frame_orn"].tolist(), + float(arm_params["joint_type"] == "SphericalJoint"), + ] + ) + ) + if ag_parts: + state_flat = th.cat([state_flat] + ag_parts) + + return state_flat + + def deserialize(self, state): + # Run super first + state_dict, idx = super().deserialize(state=state) + + # Deserialize each controller entry separately + group_states = {} + for controller_name, (group_key, controller_idx) in self._controllers.items(): + group_states[controller_name], n = ControllerView.deserialize(group_key, controller_idx, state[idx:]) + idx += n + state_dict["controller_groups"] = group_states + + if self.is_manipulation and self.grasping_mode != "physical": + state_dict["ag_obj_constraint_params"] = {} + # One block per grasping arm, each starting with the magic sentinel followed by + # arm_idx and the constraint payload. Old recordings that predate AG serialization + # lack the sentinel entirely, so this loop is safely skipped for them. + while idx < len(state) and state[idx].item() == _AG_MAGIC: + idx += 1 + arm_idx = int(state[idx].item()) + idx += 1 + arm = self.arm_names[arm_idx] + arm_data = state[idx : idx + _AG_STATE_SIZE] + idx += _AG_STATE_SIZE + obj_uuid = int(arm_data[0].item()) + link_idx = int(arm_data[1].item()) + target_obj = self.scene.object_registry("uuid", obj_uuid) + assert target_obj is not None, f"Object with UUID {obj_uuid} not found in scene registry" + link_name = sorted(target_obj.links.keys())[link_idx] + state_dict["ag_obj_constraint_params"][arm] = { + "target_obj": target_obj.name, + "target_link_name": link_name, + "parent_frame_pos": arm_data[2:5].clone(), + "parent_frame_orn": arm_data[5:9].clone(), + "child_frame_pos": arm_data[9:12].clone(), + "child_frame_orn": arm_data[12:16].clone(), + "joint_type": "SphericalJoint" if bool(arm_data[16].item()) else "FixedJoint", + } + + return state_dict, idx + + def _initialize(self): + # Run super + super()._initialize() + # Fill in the DOF to joint mapping + self._dof_to_joints = dict() + idx = 0 + for joint in self._joints.values(): + for _ in range(joint.n_dof): + self._dof_to_joints[idx] = joint + idx += 1 + + # Update the reset joint pos + if self._reset_joint_pos is None: + self._reset_joint_pos = self._default_joint_pos + + # Load controllers + self._load_controllers() + + # Setup action space + self._action_space = ( + self._create_discrete_action_space() + if self._action_type == "discrete" + else self._create_continuous_action_space() + ) + + # Reset the object and keep all joints still after loading + self.reset() + self.keep_still() + + # Initialize all sensors + for sensor in self._sensors.values(): + sensor.initialize() + + # Load the observation space for this robot + self.load_observation_space() + + # Validate this robot configuration + self._validate_configuration() + + self._reset_joint_pos_aabb_extent = self.aabb_extent + + if self.is_manipulation: + # make eef link not visible + for arm in self.arm_names: + self._links[self.eef_link_names[arm]].visible = False + + # Infer relevant link properties, e.g.: fingertip location, AG grasping points + # We use a try / except to maintain backwards-compatibility with robots that do not follow our + # OG-specified convention + try: + self._infer_finger_properties() + except AssertionError as e: + log.warning(f"Could not infer relevant finger link properties because:\n\n{e}") + + if self.is_holonomic_base: + for i, component in enumerate(["x", "y", "z", "rx", "ry", "rz"]): + joint_name = f"base_footprint_{component}_joint" + assert joint_name in self.joints, f"Missing base joint: {joint_name}" + + # Set the linear and angular velocity limits for the base joints (the default value is too large) + if i < 3: + self.joints[joint_name].max_velocity = m.MAX_LINEAR_VELOCITY + else: + self.joints[joint_name].max_velocity = m.MAX_ANGULAR_VELOCITY + + # Set the effort limits for the base joints (the default value is too small) + self.joints[joint_name].max_effort = m.MAX_EFFORT + + # Force the recomputation of this cached property + del self.control_limits + + # Overwrite with the new control limits + self._controller_config["base"]["control_limits"]["velocity"] = self.control_limits["velocity"] + self._controller_config["base"]["control_limits"]["effort"] = self.control_limits["effort"] + + # Reload the controllers to update their command_output_limits and control_limits + self.reload_controllers(self._controller_config) + + def update_handles(self): + # Run super first so the articulation / link / joint views are re-created. + super().update_handles() + # Rebuild the per-robot rigid contact view so it picks up any new/removed rigid bodies. + # This intentionally runs after the physics sim view has been refreshed by the simulator. + self._refresh_rigid_contact_view() + + def _refresh_rigid_contact_view(self): + """ + (Re)creates this robot's rigid contact view, which provides per-contact force/position data + between dynamic rigid bodies in the scene (rows) and this robot's finger links (columns). + Kinematic and static bodies are not included as rows by Isaac's RigidContactView. + + Only manipulation robots own a view — any other robot simply clears its state. + """ + # Non-manipulation robots don't need contact positions from fingers; just clear and exit. + if not self.is_manipulation: + self._rigid_contact_view = None + self._rigid_contact_view_row_path_to_idx = {} + self._rigid_contact_view_col_path_to_idx = {} + return + + # Collect finger prim paths across all arms — these become the columns of the contact view. + finger_paths = sorted({link.prim_path for links in self.finger_links.values() for link in links}) + if len(finger_paths) == 0: + self._rigid_contact_view = None + self._rigid_contact_view_row_path_to_idx = {} + self._rigid_contact_view_col_path_to_idx = {} + return + + # Rows are dynamic rigid bodies in the robot's scene; columns are the robot's fingers. + with suppress_omni_log(channels=["omni.physx.tensors.plugin"]): + self._rigid_contact_view = og.sim.physics_sim_view.create_rigid_contact_view( + pattern=f"/World/scene_{self.scene.idx}/*/*", + filter_patterns=finger_paths, + max_contact_data_count=len(finger_paths) * 8, + ) + + row_paths = list(self._rigid_contact_view.sensor_paths) + col_paths = list(getattr(self._rigid_contact_view, "filter_patterns", finger_paths)) + self._rigid_contact_view_row_path_to_idx = {path: i for i, path in enumerate(row_paths)} + self._rigid_contact_view_col_path_to_idx = {path: i for i, path in enumerate(col_paths)} + + def _find_finger_contact_position(self, arm, target_link_prim_path): + """ + Looks up the world-frame (x,y,z) position of a contact between one of this robot's finger links + for @arm and the rigid body at @target_link_prim_path, using this robot's rigid contact view. + + Args: + arm (str): Arm name whose fingers should be queried. + target_link_prim_path (str): Prim path of the target rigid body to find contact against. + + Returns: + None or th.Tensor: (3,) float tensor world-frame contact position, or None if no contact + exists between any finger and the target link. + """ + if self._rigid_contact_view is None: + return None + + row_idx = self._rigid_contact_view_row_path_to_idx.get(target_link_prim_path) + if row_idx is None: + return None + + forces, points, normals, separations, contact_counts, start_indices = self._rigid_contact_view.get_contact_data( + dt=og.sim.get_physics_dt() + ) + + for finger_link in self.finger_links[arm]: + col_idx = self._rigid_contact_view_col_path_to_idx.get(finger_link.prim_path) + if col_idx is None: + continue + count = int(contact_counts[row_idx, col_idx]) + if count == 0: + continue + start = int(start_indices[row_idx, col_idx]) + if start >= len(points): + continue + return th.as_tensor(points[start], dtype=th.float32) + return None + + def _load_sensors(self): + """ + Loads sensor(s) to retrieve observations from this object. + Stores created sensors as dictionary mapping sensor names to specific sensor + instances used by this object. + """ + # Populate sensor config + self._sensor_config = self._generate_sensor_config(custom_config=self._sensor_config) + + # Search for any sensors this robot might have attached to any of its links + self._sensors = dict() + obs_modalities = set() + for link_name, link in self._links.items(): + # Search through all children prims and see if we find any sensor + sensor_counts = {p: 0 for p in SENSOR_PRIMS_TO_SENSOR_CLS.keys()} + for prim in link.prim.GetChildren(): + prim_type = prim.GetPrimTypeInfo().GetTypeName() + if prim_type in SENSOR_PRIMS_TO_SENSOR_CLS: + # Possibly filter out the sensor based on name + prim_path = str(prim.GetPrimPath()) + not_blacklisted = self._exclude_sensor_names is None or not any( + name in prim_path for name in self._exclude_sensor_names + ) + whitelisted = self._include_sensor_names is None or any( + name in prim_path for name in self._include_sensor_names + ) + # Also make sure that the include / exclude sensor names are mutually exclusive + if self._exclude_sensor_names is not None and self._include_sensor_names is not None: + assert ( + len(set(self._exclude_sensor_names).intersection(set(self._include_sensor_names))) == 0 + ), ( + f"include_sensor_names and exclude_sensor_names must be mutually exclusive! " + f"Got: {self._include_sensor_names} and {self._exclude_sensor_names}" + ) + if not (not_blacklisted and whitelisted): + continue + + # Infer what obs modalities to use for this sensor + sensor_cls = SENSOR_PRIMS_TO_SENSOR_CLS[prim_type] + link_key = f"{link_name}:{prim_type}:{sensor_counts[prim_type]}" + class_key = sensor_cls.__name__ + if link_key in self._sensor_config: + sensor_kwargs = self._sensor_config[link_key] + elif class_key in self._sensor_config: + sensor_kwargs = self._sensor_config[class_key] + else: + sensor_kwargs = {} + if "modalities" not in sensor_kwargs: + sensor_kwargs["modalities"] = ( + sensor_cls.all_modalities + if self._obs_modalities == "all" + else sensor_cls.all_modalities.intersection(self._obs_modalities) + ) + # If the modalities list is empty, don't import the sensor. + if not sensor_kwargs["modalities"]: + continue + + obs_modalities = obs_modalities.union(sensor_kwargs["modalities"]) + # Create the sensor and store it internally + sensor = create_sensor( + sensor_type=prim_type, + relative_prim_path=absolute_prim_path_to_scene_relative(self.scene, prim_path), + name=f"{self.name}:{link_name}:{prim_type}:{sensor_counts[prim_type]}", + **sensor_kwargs, + ) + sensor.load(self.scene) + self._sensors[sensor.name] = sensor + sensor_counts[prim_type] += 1 + + # Since proprioception isn't an actual sensor, we need to possibly manually add it here as well + if self._obs_modalities == "all" or "proprio" in self._obs_modalities: + obs_modalities.add("proprio") + + # Update our overall obs modalities + self._obs_modalities = obs_modalities + + def _generate_sensor_config(self, custom_config=None): + """ + Generates a fully-populated sensor config, overriding any default values with the corresponding values + specified in @custom_config + + Args: + custom_config (None or Dict[str, ...]): nested dictionary mapping sensor class name(s) to specific custom + sensor configurations for this object. This will override any default values specified by this class + + Returns: + dict: Fully-populated nested dictionary mapping sensor class name(s) to specific sensor configurations + for this object + """ + sensor_config = {} if custom_config is None else deepcopy(custom_config) + + # Merge the sensor dictionaries + sensor_config = merge_nested_dicts( + base_dict=self._default_sensor_config, + extra_dict=sensor_config, + ) + + return sensor_config + + def _validate_configuration(self): + """ + Run any needed sanity checks to make sure this robot was created correctly. + """ + if self.is_manipulation: + # Iterate over all arms + for arm in self.arm_names: + # If we have an arm controller, make sure it is a manipulation controller + if f"arm_{arm}" in self._controllers: + assert ControllerView.is_controller_type( + self._controllers[f"arm_{arm}"][0], ManipulationController + ), "Arm {} controller must be a member of ManipulationController!".format(arm) + + # If we have a gripper controller, make sure it is a manipulation controller + if f"gripper_{arm}" in self._controllers: + assert ControllerView.is_controller_type( + self._controllers[f"gripper_{arm}"][0], GripperController + ), "Gripper {} controller must be a member of GripperController!".format(arm) + + if self.is_locomotion: + # If we have a base controller, make sure it is a locomotion controller + if "base" in self._controllers: + assert ControllerView.is_controller_type( + self._controllers["base"][0], LocomotionController + ), "Base controller must be a member of LocomotionController!" + if self.is_two_wheel: + assert ( + len(self.base_control_idx) == 2 + ), "Differential drive can only be used with robot with two base joints!" + + def get_obs(self): + """ + Grabs all observations from the robot. This is keyword-mapped based on each observation modality + (e.g.: proprio, rgb, etc.) + + Returns: + 2-tuple: + dict: Keyword-mapped dictionary mapping observation modality names to + observations (usually np arrays) + dict: Keyword-mapped dictionary mapping observation modality names to + additional info + """ + # Our sensors already know what observation modalities it has, so we simply iterate over all of them + # and grab their observations, processing them into a flat dict + obs_dict = dict() + info_dict = dict() + for sensor_name, sensor in self._sensors.items(): + obs_dict[sensor_name], info_dict[sensor_name] = sensor.get_obs() + for key in obs_dict[sensor_name]: + if "pointcloud" in key: + # convert point cloud from world frame to robot base frame + obs_dict[sensor_name][key] = change_pcd_frame( + pcd=obs_dict[sensor_name][key], + rel_pose=th.cat(self.get_position_orientation()), + ) + + # Have to handle proprio separately since it's not an actual sensor + if "proprio" in self._obs_modalities: + obs_dict["proprio"], info_dict["proprio"] = self.get_proprioception() + + return obs_dict, info_dict + + def get_proprioception(self): + """ + Returns: + n-array: numpy array of all robot-specific proprioceptive observations. + dict: empty dictionary, a placeholder for additional info + """ + proprio_dict = self._get_proprioception_dict() + dic = th.cat([proprio_dict[obs] for obs in self._proprio_obs]), {} + + return dic + + def _get_proprioception_dict(self): + """ + Returns: + dict: keyword-mapped proprioception observations available for this robot. + """ + joint_positions = self.get_joint_positions() + joint_velocities = self.get_joint_velocities() + joint_efforts = self.get_joint_efforts() + pos, quat = self.get_position_orientation() + ori = T.quat2euler(quat) + + ori_2d = T.z_angle_from_quat(quat).unsqueeze(0) # Convert to 1D tensor + + # Pack everything together + dic = dict( + joint_qpos=joint_positions, + joint_qpos_sin=th.sin(joint_positions), + joint_qpos_cos=th.cos(joint_positions), + joint_qvel=joint_velocities, + joint_qeffort=joint_efforts, + robot_pos=pos, + robot_ori_cos=th.cos(ori), + robot_ori_sin=th.sin(ori), + robot_2d_ori=ori_2d, + robot_2d_ori_cos=th.cos(ori_2d), + robot_2d_ori_sin=th.sin(ori_2d), + robot_lin_vel=self.get_linear_velocity(), + robot_ang_vel=self.get_angular_velocity(), + ) + + if self.is_manipulation: + # Loop over all arms to grab proprio info + joint_positions = dic["joint_qpos"] + joint_velocities = dic["joint_qvel"] + for arm in self.arm_names: + # Add arm info + dic["arm_{}_qpos".format(arm)] = joint_positions[self.arm_control_idx[arm]] + dic["arm_{}_qpos_sin".format(arm)] = th.sin(joint_positions[self.arm_control_idx[arm]]) + dic["arm_{}_qpos_cos".format(arm)] = th.cos(joint_positions[self.arm_control_idx[arm]]) + dic["arm_{}_qvel".format(arm)] = joint_velocities[self.arm_control_idx[arm]] + + # Add eef and grasping info (relative to articulation root / robot base frame) + eef_pos, eef_quat = self.get_relative_eef_pose(arm=arm) + dic["eef_{}_pos".format(arm)], dic["eef_{}_quat".format(arm)] = eef_pos, eef_quat + dic["grasp_{}".format(arm)] = th.tensor([self.is_grasping(arm)]) + dic["gripper_{}_qpos".format(arm)] = joint_positions[self.gripper_control_idx[arm]] + dic["gripper_{}_qvel".format(arm)] = joint_velocities[self.gripper_control_idx[arm]] + if self.is_articulated_trunk: + joint_positions = dic["joint_qpos"] + joint_velocities = dic["joint_qvel"] + dic["trunk_qpos"] = joint_positions[self.trunk_control_idx] + dic["trunk_qvel"] = joint_velocities[self.trunk_control_idx] + if self.is_locomotion: + joint_positions = dic["joint_qpos"] + joint_velocities = dic["joint_qvel"] + + # Add base info + dic["base_qpos"] = joint_positions[self.base_control_idx] + dic["base_qpos_sin"] = th.sin(joint_positions[self.base_control_idx]) + dic["base_qpos_cos"] = th.cos(joint_positions[self.base_control_idx]) + dic["base_qvel"] = self._get_base_qvel_for_proprioception(joint_positions, joint_velocities) + if self.is_two_wheel: + # Grab wheel joint velocity info + l_vel, r_vel = joint_velocities[self.base_control_idx].tolist() + + # Compute linear and angular velocities + lin_vel = (l_vel + r_vel) / 2.0 * self.wheel_radius + ang_vel = (r_vel - l_vel) / self.wheel_axle_length + + # Add info + dic["dd_base_lin_vel"] = th.tensor([lin_vel]) + dic["dd_base_ang_vel"] = th.tensor([ang_vel]) + if self.is_active_camera: + joint_positions = dic["joint_qpos"] + joint_velocities = dic["joint_qvel"] + dic["camera_qpos"] = joint_positions[self.camera_control_idx] + dic["camera_qpos_sin"] = th.sin(joint_positions[self.camera_control_idx]) + dic["camera_qpos_cos"] = th.cos(joint_positions[self.camera_control_idx]) + dic["camera_qvel"] = joint_velocities[self.camera_control_idx] + + return dic + + def _get_base_qvel_for_proprioception(self, joint_positions, joint_velocities): + """ + Returns: + th.Tensor: base velocity exposed through proprioception. + """ + base_qvel = joint_velocities[self.base_control_idx] + if not self.is_holonomic_base: + return base_qvel + + base_qpos_6dof = joint_positions[self.base_idx] + yaw = base_qpos_6dof[5] + c = th.cos(yaw) + s = th.sin(yaw) + return th.stack( + [ + c * base_qvel[0] + s * base_qvel[1], + -s * base_qvel[0] + c * base_qvel[1], + base_qvel[2], + ] + ) + + def _load_observation_space(self): + # We compile observation spaces from our sensors + obs_space = dict() + + for sensor_name, sensor in self._sensors.items(): + # Load the sensor observation space + obs_space[sensor_name] = sensor.load_observation_space() + + # Have to handle proprio separately since it's not an actual sensor + if "proprio" in self._obs_modalities: + obs_space["proprio"] = self._build_obs_box_space( + shape=(self.proprioception_dim,), low=-float("inf"), high=float("inf"), dtype=NumpyTypes.FLOAT32 + ) + + return obs_space + + def add_obs_modality(self, modality): + """ + Adds observation modality @modality to this robot. Note: Should be one of omnigibson.sensors.ALL_SENSOR_MODALITIES + + Args: + modality (str): Observation modality to add to this robot + """ + # Iterate over all sensors we own, and if the requested modality is a part of its possible valid modalities, + # then we add it + for sensor in self._sensors.values(): + if modality in sensor.all_modalities: + sensor.add_modality(modality=modality) + + def remove_obs_modality(self, modality): + """ + Remove observation modality @modality from this robot. Note: Should be one of + omnigibson.sensors.ALL_SENSOR_MODALITIES + + Args: + modality (str): Observation modality to remove from this robot + """ + # Iterate over all sensors we own, and if the requested modality is a part of its possible valid modalities, + # then we remove it + for sensor in self._sensors.values(): + if modality in sensor.all_modalities: + sensor.remove_modality(modality=modality) + + def visualize_sensors(self): + """ + Renders this robot's key sensors, visualizing them via matplotlib plots + """ + frames = dict() + remaining_obs_modalities = deepcopy(self.obs_modalities) + for sensor in self.sensors.values(): + obs, _ = sensor.get_obs() + sensor_frames = [] + if isinstance(sensor, VisionSensor): + # We check for rgb, depth, normal, seg_instance + for modality in ["rgb", "depth", "normal", "seg_instance"]: + if modality in sensor.modalities: + ob = obs[modality] + if modality == "rgb": + # Ignore alpha channel, map to floats + ob = ob[:, :, :3] / 255.0 + elif modality == "seg_instance": + # Map IDs to rgb + ob = segmentation_to_rgb(ob, N=256) / 255.0 + elif modality == "normal": + # Re-map to 0 - 1 range + ob = (ob + 1.0) / 2.0 + else: + # Depth, nothing to do here + pass + # Add this observation to our frames and remove the modality + sensor_frames.append((modality, ob)) + remaining_obs_modalities -= {modality} + else: + # Warn user that we didn't find this modality + print(f"Modality {modality} is not active in sensor {sensor.name}, skipping...") + elif isinstance(sensor, ScanSensor): + # We check for occupancy_grid + occupancy_grid = obs.get("occupancy_grid", None) + if occupancy_grid is not None: + sensor_frames.append(("occupancy_grid", occupancy_grid)) + remaining_obs_modalities -= {"occupancy_grid"} + + # Map the sensor name to the frames for that sensor + frames[sensor.name] = sensor_frames + + # Warn user that any remaining modalities are not able to be visualized + if len(remaining_obs_modalities) > 0: + print(f"Modalities: {remaining_obs_modalities} cannot be visualized, skipping...") + + # Write all the frames to a plot + import matplotlib.pyplot as plt + + for sensor_name, sensor_frames in frames.items(): + n_sensor_frames = len(sensor_frames) + if n_sensor_frames > 0: + fig, axes = plt.subplots(nrows=1, ncols=n_sensor_frames) + if n_sensor_frames == 1: + axes = [axes] + # Dump frames and set each subtitle + for i, (modality, frame) in enumerate(sensor_frames): + axes[i].imshow(frame) + axes[i].set_title(modality) + axes[i].set_axis_off() + # Set title + fig.suptitle(sensor_name) + plt.show(block=False) + + # One final plot show so all the figures get rendered + plt.show() + + def remove(self): + """ + Do NOT call this function directly to remove a prim - call og.sim.remove_prim(prim) for proper cleanup + """ + # Remove all controllers + ControllerView.unregister_robot(self._controllers) + + # Remove all sensors + for sensor in self._sensors.values(): + sensor.remove() + + # Run super + super().remove() + + def _infer_finger_properties(self): + """ + Infers relevant finger properties based on the given finger meshes of the robot + + NOTE: This assumes the given EEF convention for parallel jaw grippers -- i.e.: + z points in the direction of the fingers, y points in the direction of grasp articulation, and x + is then inferred automatically + """ + assert self.is_manipulation + # Calculate and cache fingertip to eef frame offsets, as well as AG grasping points + self._eef_to_fingertip_lengths = dict() + self._default_ag_start_points = dict() + self._default_ag_end_points = dict() + for arm, finger_links in self.finger_links.items(): + self._eef_to_fingertip_lengths[arm] = dict() + eef_link = self.eef_links[arm] + world_to_eef_tf = T.pose2mat(eef_link.get_position_orientation()) + eef_to_world_tf = T.pose_inv(world_to_eef_tf) + + # Infer parent link for this finger + finger_parent_link, finger_parent_max_z = None, None + is_parallel_jaw = len(finger_links) == 2 + assert ( + is_parallel_jaw + ), "Inferring finger link information can only be done for parallel jaw gripper robots!" + finger_pts_in_eef_frame = [] + for i, finger_link in enumerate(finger_links): + # Find parent, and make sure one exists + parent_prim_path, parent_link = None, None + for joint in self.joints.values(): + if finger_link.prim_path == joint.body1: + parent_prim_path = joint.body0 + break + assert ( + parent_prim_path is not None + ), f"Expected articulated parent joint for finger link {finger_link.name} but found none!" + for link in self.links.values(): + if parent_prim_path == link.prim_path: + parent_link = link + break + assert parent_link is not None, f"Expected parent link located at {parent_prim_path} but found none!" + # Make sure all fingers share the same parent + if finger_parent_link is None: + finger_parent_link = parent_link + finger_parent_pts = finger_parent_link.collision_boundary_points_world + assert ( + finger_parent_pts is not None + ), f"Expected finger parent points to be defined for parent link {finger_parent_link.name}, but got None!" + # Convert from world frame -> eef frame + finger_parent_pts = th.concatenate([finger_parent_pts, th.ones(len(finger_parent_pts), 1)], dim=-1) + finger_parent_pts = (finger_parent_pts @ eef_to_world_tf.T)[:, :3] + finger_parent_max_z = finger_parent_pts[:, 2].max().item() + else: + assert ( + finger_parent_link == parent_link + ), f"Expected all fingers to have same parent link, but found multiple parents at {finger_parent_link.prim_path} and {parent_link.prim_path}" + + # Calculate this finger's collision boundary points in the world frame + finger_pts = finger_link.collision_boundary_points_world + assert ( + finger_pts is not None + ), f"Expected finger points to be defined for link {finger_link.name}, but got None!" + # Convert from world frame -> eef frame + finger_pts = th.concatenate([finger_pts, th.ones(len(finger_pts), 1)], dim=-1) + finger_pts = (finger_pts @ eef_to_world_tf.T)[:, :3] + finger_pts_in_eef_frame.append(finger_pts) + + # Determine how each finger is located relative to the other in the EEF frame along the y-axis + # This is used to infer which side of each finger's set of points correspond to the "inner" surface + finger_pts_mean = [finger_pts[:, 1].mean().item() for finger_pts in finger_pts_in_eef_frame] + first_finger_is_lower_y_finger = finger_pts_mean[0] < finger_pts_mean[1] + is_lower_y_fingers = [first_finger_is_lower_y_finger, not first_finger_is_lower_y_finger] + + for i, (finger_link, finger_pts, is_lower_y_finger) in enumerate( + zip(finger_links, finger_pts_in_eef_frame, is_lower_y_fingers) + ): + # Since we know the EEF frame always points with z outwards towards the fingers, the outer-most point / + # fingertip is the maximum z value + finger_max_z = finger_pts[:, 2].max().item() + assert ( + finger_max_z > 0 + ), f"Expected positive fingertip to eef frame offset for link {finger_link.name}, but got: {finger_max_z}. Does the EEF frame z-axis point in the direction of the fingers?" + self._eef_to_fingertip_lengths[arm][finger_link.name] = finger_max_z + + # Now, only keep points that are above the parent max z by 20% for inferring y values + finger_range = finger_max_z - finger_parent_max_z + valid_idxs = th.where( + finger_pts[:, 2] > (finger_parent_max_z + finger_range * m.MIN_AG_DEFAULT_GRASP_POINT_PROP) + )[0] + finger_pts = finger_pts[valid_idxs] + # Infer which side of the gripper corresponds to the inner side (i.e.: the side that touches between the + # two fingers + # We use the heuristic that given a set of points defining a gripper finger, we assume that it's one + # of (y_min, y_max) over all points, with the selection being chosen by inferring which of the limits + # corresponds to the inner side of the finger. + # This is the upper side of the y values if this finger is the lower finger, else the lower side + # of the y values + y_min, y_max = finger_pts[:, 1].min(), finger_pts[:, 1].max() + y_offset = y_max if is_lower_y_finger else y_min + y_sign = 1.0 if is_lower_y_finger else -1.0 + + # Compute the default grasping points for this finger + # For now, we only have a strong heuristic defined for parallel jaw grippers, which assumes that + # there are exactly 2 fingers + # In this case, this is defined as the x2 (x,y,z) tuples where: + # z - the +/-40% from the EEF frame, bounded by the 20% and 100% length between the range from + # [finger_parent_max_z, finger_max_z] + # This is synonymous to inferring the length of the finger (lower bounded by the gripper base, + # assumed to be the parent link), and then taking the values +/-%, bounded by the MIN% and MAX% + # along its length + # y - the value closest to the edge of the finger surface in the direction of +/- EEF y-axis. + # This assumes that each individual finger lies completely on one side of the EEF y-axis + # x - 0. This assumes that the EEF axis evenly splits each finger symmetrically on each side + # (x,y,z,1) -- homogenous form for efficient transforming into finger link frame + z_lower = max( + finger_parent_max_z + finger_range * m.MIN_AG_DEFAULT_GRASP_POINT_PROP, + -finger_range * m.AG_DEFAULT_GRASP_POINT_Z_PROP, + ) + z_upper = min( + finger_parent_max_z + finger_range * m.MAX_AG_DEFAULT_GRASP_POINT_PROP, + finger_range * m.AG_DEFAULT_GRASP_POINT_Z_PROP, + ) + # We want to ensure the z value is symmetric about the EEF z frame, so make sure z_lower is negative + # and z_upper is positive, and use +/- the absolute minimum value between the two + assert ( + z_lower < 0 and z_upper > 0 + ), f"Expected computed z_lower / z_upper bounds for finger grasping points to be negative / positive, but instead got: {z_lower}, {z_upper}" + z_offset = min(abs(z_lower), abs(z_upper)) + + grasp_pts = th.tensor( + [ + [ + 0, + y_offset + 0.002 * y_sign, + -z_offset, + 1, + ], + [ + 0, + y_offset + 0.002 * y_sign, + z_offset, + 1, + ], + ] + ) + # Convert the grasping points from the EEF frame -> finger frame + finger_to_world_tf = T.pose_inv(T.pose2mat(finger_link.get_position_orientation())) + finger_to_eef_tf = finger_to_world_tf @ world_to_eef_tf + grasp_pts = (grasp_pts @ finger_to_eef_tf.T)[:, :3] + grasping_points = [ + GraspingPoint(link_name=finger_link.body_name, position=grasp_pt) for grasp_pt in grasp_pts + ] + if i == 0: + # Start point + self._default_ag_start_points[arm] = grasping_points + else: + # End point + self._default_ag_end_points[arm] = grasping_points + + # For each grasping point, if we're in DEBUG mode, visualize with spheres + if gm.DEBUG: + for ag_points in (self.assisted_grasp_start_points, self.assisted_grasp_end_points): + for arm_ag_points in ag_points.values(): + # Skip if None exist + if arm_ag_points is None: + continue + # For each ag point, generate a small sphere at that point + for i, arm_ag_point in enumerate(arm_ag_points): + link = self.links[arm_ag_point.link_name] + local_pos = arm_ag_point.position + vis_mesh_prim_path = f"{link.prim_path}/ag_point_{i}" + create_primitive_mesh( + prim_path=vis_mesh_prim_path, + extents=0.005, + primitive_type="Sphere", + ) + vis_geom = GeomPrim( + relative_prim_path=absolute_prim_path_to_scene_relative( + scene=self.scene, + absolute_prim_path=vis_mesh_prim_path, + ), + name=f"ag_point_{i}", + ) + vis_geom.load(self.scene) + vis_geom.set_position_orientation( + position=local_pos, + frame="parent", + ) + + def is_grasping(self, arm="default", candidate_obj=None): + """ + Returns True if the robot is grasping the target option @candidate_obj or any object if @candidate_obj is None. + + Args: + arm (str): specific arm to check for grasping. Default is "default" which corresponds to the first entry + in self.arm_names + candidate_obj (StatefulObject or None): object to check if this robot is currently grasping. If None, then + will be a general (object-agnostic) check for grasping. + Note: if self.grasping_mode is "physical", then @candidate_obj will be ignored completely + + Returns: + IsGraspingState: For the specific manipulator appendage, returns IsGraspingState.TRUE if it is grasping + (potentially @candidate_obj if specified), IsGraspingState.FALSE if it is not grasping, + and IsGraspingState.UNKNOWN if unknown. + """ + assert self.is_manipulation + arm = self.default_arm if arm == "default" else arm + if self.grasping_mode != "physical": + is_grasping_obj = ( + self._ag_obj_in_hand[arm] is not None + if candidate_obj is None + else self._ag_obj_in_hand[arm] == candidate_obj + ) + is_grasping = ( + IsGraspingState.TRUE + if is_grasping_obj and self._ag_release_counter[arm] is None + else IsGraspingState.FALSE + ) + else: + # Infer from the gripper controller the state + group_key, controller_idx = self._controllers[f"gripper_{arm}"] + is_grasping = ControllerView.is_grasping(group_key, controller_idx) + # If candidate obj is not None, we also check to see if our fingers are in contact with the object + if is_grasping == IsGraspingState.TRUE and candidate_obj is not None: + finger_links = {link for link in self.finger_links[arm]} + if not RigidContactAPI.is_in_contact( + scene_idx=self.scene.idx, + query_set=finger_links, + with_set=[candidate_obj], + ignore_set=None, + current_only=False, + ): + is_grasping = IsGraspingState.FALSE + return is_grasping + + def _find_gripper_contacts(self, arm="default"): + """ + Specific for Manipulation Robot + For arm @arm, calculate any body IDs and corresponding link IDs that are not part of the robot + itself that are in contact with any of this arm's gripper's fingers + Args: + arm (str): specific arm whose gripper will be checked for contact. Default is "default" which + corresponds to the first entry in self.arm_names + Returns: + 2-tuple: + - set: set of unique contact prim_paths that are not the robot self-collisions. + Note: if no objects that are not the robot itself are intersecting, the set will be empty. + - dict: dictionary mapping unique contact objects defined by the contact prim_path to + set of unique robot link prim_paths that it is in contact with + """ + assert self.is_manipulation + arm = self.default_arm if arm == "default" else arm + + # Get robot finger links + finger_paths = set([link.prim_path for link in self.finger_links[arm]]) + + # Get robot links + link_paths = set(self.link_prim_paths) + + raw_contact_data = { + (link_contact, other_contact) + for link_contact, other_contact in RigidContactAPI.get_contact_pairs( + scene_idx=self.scene.idx, query_set=finger_paths, with_set=None, current_only=False + ) + if other_contact not in link_paths + } + + # Translate to robot contact data + robot_contact_links = dict() + contact_data = set() + for con_data in raw_contact_data: + link_contact, other_contact = con_data + contact_data.add(other_contact) + if other_contact not in robot_contact_links: + robot_contact_links[other_contact] = set() + robot_contact_links[other_contact].add(link_contact) + + return contact_data, robot_contact_links + + def _release_grasp(self, arm="default"): + """ + Magic action to release this robot's grasp on an object + + Args: + arm (str): specific arm whose grasp will be released. + Default is "default" which corresponds to the first entry in self.arm_names + """ + assert self.is_manipulation + arm = self.default_arm if arm == "default" else arm + + # Remove joint and filtered collision restraints + delete_or_deactivate_prim(self._ag_obj_constraints[arm].GetPath().pathString) + og.sim.update_handles() + self._ag_obj_constraints[arm] = None + self._ag_obj_constraint_params[arm] = None + self._ag_release_counter[arm] = 0 + + def release_grasp_immediately(self, arm="default"): + """ + Magic action to release this robot's grasp for one arm. + As opposed to @_release_grasp, this method would bypass the release window mechanism and immediately release. + """ + assert self.is_manipulation + if self._ag_obj_constraints[arm] is not None: + self._release_grasp(arm=arm) + self._ag_release_counter[arm] = int(math.ceil(m.RELEASE_WINDOW / og.sim.get_physics_dt())) + self._handle_release_window(arm=arm) + assert not self._ag_obj_in_hand[arm], "Object still in ag list after release!" + + @property + def reset_joint_pos_aabb_extent(self): + """ + This is the aabb extent of the robot in the robot frame after resetting the joints. + Returns: + 3-array: Axis-aligned bounding box extent of the robot base + """ + return self._reset_joint_pos_aabb_extent + + def teleop_data_to_action(self, teleop_action) -> th.Tensor: + """ + Generate action data from teleoperation action data + Args: + teleop_action (TeleopAction): teleoperation action data + Returns: + th.tensor: array of action data filled with update value + """ + if self.is_two_wheel: + action = th.zeros(self.action_dim) + assert ControllerView.is_controller_type( + self._controllers["base"][0], DifferentialDriveController + ), "Only DifferentialDriveController is supported!" + action[self.base_action_idx] = th.tensor([teleop_action.base[0], teleop_action.base[2]]).float() * 0.3 + return action + + if self.is_holonomic_base: + action = th.zeros(self.action_dim) + hands = ["left", "right"] if self.n_arms == 2 else ["right"] + for i, hand in enumerate(hands): + arm_name = self.arm_names[i] + arm_action = th.tensor(teleop_action[hand]).float() + # arm action + assert ControllerView.is_controller_type( + self._controllers[f"arm_{arm_name}"][0], InverseKinematicsController + ) or ControllerView.is_controller_type( + self._controllers[f"arm_{arm_name}"][0], OperationalSpaceController + ), f"Only IK and OSC controllers are supported for arm {arm_name}!" + target_pos, target_orn = arm_action[:3], T.quat2axisangle(T.euler2quat(arm_action[3:6])) + action[self.arm_action_idx[arm_name]] = th.cat((target_pos, target_orn)) + # gripper action + assert ControllerView.is_controller_type( + self._controllers[f"gripper_{arm_name}"][0], MultiFingerGripperController + ), f"Only MultiFingerGripperController is supported for gripper {arm_name}!" + action[self.gripper_action_idx[arm_name]] = arm_action[6] + action[self.base_action_idx] = th.tensor(teleop_action.base).float() + return action + + if self.is_manipulation: + action = th.zeros(self.action_dim) + hands = ["left", "right"] if self.n_arms == 2 else ["right"] + for i, hand in enumerate(hands): + arm_name = self.arm_names[i] + arm_action = th.tensor(teleop_action[hand]).float() + # arm action + assert ControllerView.is_controller_type( + self._controllers[f"arm_{arm_name}"][0], InverseKinematicsController + ) or ControllerView.is_controller_type( + self._controllers[f"arm_{arm_name}"][0], OperationalSpaceController + ), f"Only IK and OSC controllers are supported for arm {arm_name}!" + target_pos, target_orn = arm_action[:3], T.quat2axisangle(T.euler2quat(arm_action[3:6])) + action[self.arm_action_idx[arm_name]] = th.cat((target_pos, target_orn)) + # gripper action + assert ControllerView.is_controller_type( + self._controllers[f"gripper_{arm_name}"][0], MultiFingerGripperController + ), f"Only MultiFingerGripperController is supported for gripper {arm_name}!" + action[self.gripper_action_idx[arm_name]] = arm_action[6] + return action + + @property + def sensors(self): + """ + Returns: + dict: Keyword-mapped dictionary mapping sensor names to BaseSensor instances owned by this robot + """ + return self._sensors + + @property + def obs_modalities(self): + """ + Returns: + set of str: Observation modalities used for this robot (e.g.: proprio, rgb, etc.) + """ + assert self._loaded, "Cannot check observation modalities until we load this robot!" + return self._obs_modalities + + @property + def proprioception_dim(self): + """ + Returns: + int: Size of self.get_proprioception() vector + """ + return len(self.get_proprioception()[0]) + + @property + def _default_sensor_config(self): + """ + Returns: + dict: default nested dictionary mapping sensor class name(s) to specific sensor + configurations for this object. See kwargs from omnigibson/sensors/__init__/create_sensor for more + details + + Expected structure is as follows: + SensorClassName1: + modalities: ... + enabled: ... + noise_type: ... + noise_kwargs: + ... + sensor_kwargs: + ... + SensorClassName2: + modalities: ... + enabled: ... + noise_type: ... + noise_kwargs: + ... + sensor_kwargs: + ... + ... + """ + return { + "VisionSensor": { + "enabled": True, + "noise_type": None, + "noise_kwargs": None, + "sensor_kwargs": { + "image_height": 128, + "image_width": 128, + }, + }, + "ScanSensor": { + "enabled": True, + "noise_type": None, + "noise_kwargs": None, + "sensor_kwargs": { + # Basic LIDAR kwargs + "min_range": 0.05, + "max_range": 10.0, + "horizontal_fov": 360.0, + "vertical_fov": 1.0, + "yaw_offset": 0.0, + "horizontal_resolution": 1.0, + "vertical_resolution": 1.0, + "rotation_rate": 0.0, + "draw_points": False, + "draw_lines": False, + # Occupancy Grid kwargs + "occupancy_grid_resolution": 128, + "occupancy_grid_range": 5.0, + "occupancy_grid_inner_radius": 0.5, + "occupancy_grid_local_link": None, + }, + }, + } + + @property + def default_proprio_obs(self): + """ + Returns: + list of str: Default proprioception observations to use + """ + obs_keys = [] + if self.is_manipulation: + for arm in self.arm_names: + obs_keys += [ + "arm_{}_qpos_sin".format(arm), + "arm_{}_qpos_cos".format(arm), + "eef_{}_pos".format(arm), + "eef_{}_quat".format(arm), + "gripper_{}_qpos".format(arm), + "grasp_{}".format(arm), + ] + return obs_keys + if self.is_locomotion: + obs_keys += ["base_qpos_sin", "base_qpos_cos", "robot_lin_vel", "robot_ang_vel"] + if self.is_articulated_trunk: + obs_keys += ["trunk_qpos", "trunk_qvel"] + if self.is_two_wheel: + obs_keys += ["dd_base_lin_vel", "dd_base_ang_vel"] + if self.is_active_camera: + obs_keys += ["camera_qpos_sin", "camera_qpos_cos"] + return obs_keys + + @property + def usd_path(self): + # Check top-level usd_path + if self._definition.usd_path: + return os.path.join(get_dataset_path("omnigibson-robot-assets"), self._definition.usd_path) + # Check end-effector specific usd_path + if self.has_end_effector_variants: + eef_def = self._get_end_effector_definition() + if eef_def and eef_def.usd_path: + return os.path.join(get_dataset_path("omnigibson-robot-assets"), eef_def.usd_path) + + # By default, sets the standardized path + model = self.model.lower() + return os.path.join(get_dataset_path("omnigibson-robot-assets"), f"models/{model}/usd/{model}.usda") + + @property + def urdf_path(self): + """ + Returns: + str: file path to the robot urdf file. + """ + # Check top-level urdf_path + if self._definition.urdf_path: + return os.path.join(get_dataset_path("omnigibson-robot-assets"), self._definition.urdf_path) + # Check end-effector specific urdf_path + if self.has_end_effector_variants: + eef_def = self._get_end_effector_definition() + if eef_def: + assert not eef_def.not_support_urdf, "Robot doesn't support URDF." + if eef_def.urdf_path: + return os.path.join(get_dataset_path("omnigibson-robot-assets"), eef_def.urdf_path) + + # By default, sets the standardized path + model = self.model.lower() + return os.path.join(get_dataset_path("omnigibson-robot-assets"), f"models/{model}/urdf/{model}.urdf") + + @property + def base_footprint_link_name(self): + """ + Get the base footprint link name for the controllable object. + + The base footprint link is the link that should be considered the base link for the object + even in the presence of virtual joints that may be present in the object's articulation. For + robots without virtual joints, this is the same as the root link. For robots with virtual joints, + this is the link that is the child of the last virtual joint in the robot's articulation. + + Returns: + str: Name of the base footprint link for this object + """ + if self._definition.base_footprint_link_name: + return self._definition.base_footprint_link_name + if self.is_holonomic_base: + raise NotImplementedError("base_footprint_link_name is not implemented for HolonomicBaseRobot") + return self.root_link_name + + @property + def base_footprint_link(self): + """ + Get the base footprint link for the controllable object. + + The base footprint link is the link that should be considered the base link for the object + even in the presence of virtual joints that may be present in the object's articulation. For + robots without virtual joints, this is the same as the root link. For robots with virtual joints, + this is the link that is the child of the last virtual joint in the robot's articulation. + + Returns: + RigidDynamicPrim: Base footprint link for this object + """ + return self.links[self.base_footprint_link_name] + + @property + def action_dim(self): + """ + Returns: + int: Dimension of action space for this object. By default, + is the sum over all controller action dimensions + """ + return sum(ControllerView.get_command_dim(group_key) for group_key, _ in self._controllers.values()) + + @property + def action_space(self): + """ + Action space for this object. + + Returns: + gym.space: Action space, either discrete (Discrete) or continuous (Box) + """ + return deepcopy(self._action_space) + + @property + def discrete_action_list(self): + """ + Discrete choices for actions for this object. Only needs to be implemented if the object supports discrete + actions. + + Returns: + dict: Mapping from single action identifier (e.g.: a string, or a number) to array of continuous + actions to deploy via this object's controllers. + """ + raise NotImplementedError() + + @property + def controllers(self): + """ + Returns: + dict: Mapping from controller name to (group_key, controller_idx) tuples + """ + return self._controllers + + @property + def controller_order(self): + """ + Returns: + list: Ordering of the actions, corresponding to the controllers. e.g., ["base", "arm", "gripper"], + to denote that the action vector should be interpreted as first the base action, then arm command, then + gripper command. Note that this may be a subset of all possible controllers due to some controllers + subsuming others (e.g.: arm controller subsuming the trunk controller if using IK) + """ + assert self._controllers is not None, "Can only view controller_order after controllers are loaded!" + return list(self._controllers.keys()) + + @property + def _raw_controller_order(self): + """ + Returns: + list: Raw ordering of the actions, corresponding to the controllers. e.g., ["base", "arm", "gripper"], + to denote that the action vector should be interpreted as first the base action, then arm command, then + gripper command. Note that external users should query @controller_order, which is the post-processed + ordering of actions, which may be a subset of the controllers due to some controllers subsuming others + (e.g.: arm controller subsuming the trunk controller if using IK) + """ + return self._definition.raw_controller_order + + @property + def controller_action_idx(self): + """ + Returns: + dict: Mapping from controller names (e.g.: head, base, arm, etc.) to corresponding + indices (list) in the action vector + """ + dic = {} + idx = 0 + for controller in self.controller_order: + cmd_dim = ControllerView.get_command_dim(self._controllers[controller][0]) + dic[controller] = th.arange(idx, idx + cmd_dim) + idx += cmd_dim + + return dic + + @property + def controller_joint_idx(self): + """ + Returns: + dict: Mapping from controller names (e.g.: head, base, arm, etc.) to corresponding + 1-D ``torch.long`` indices of the joint state vector controlled by each controller + """ + dic = {} + for controller in self.controller_order: + dic[controller] = ControllerView.get_dof_idx(self._controllers[controller][0]) + + return dic + + # TODO: These are cached, but they are not updated when the joint limit is changed + @cached_property + def control_limits(self): + """ + Returns: + dict: Keyword-mapped limits for this object. Dict contains: + position: (min, max) joint limits, where min and max are N-DOF arrays + velocity: (min, max) joint velocity limits, where min and max are N-DOF arrays + effort: (min, max) joint effort limits, where min and max are N-DOF arrays + has_limit: (n_dof,) array where each element is True if that corresponding joint has a position limit + (otherwise, joint is assumed to be limitless) + """ + return { + "position": (self.joint_lower_limits, self.joint_upper_limits), + "velocity": (-self.max_joint_velocities, self.max_joint_velocities), + "effort": (-self.max_joint_efforts, self.max_joint_efforts), + "has_limit": self.joint_has_limits, + } + + @property + def reset_joint_pos(self): + """ + Returns: + n-array: reset joint positions for this robot + """ + return self._reset_joint_pos + + @reset_joint_pos.setter + def reset_joint_pos(self, value): + """ + Args: + value: the new reset joint positions for this robot + """ + self._reset_joint_pos = value + + @property + def _default_joint_pos(self): + """ + Returns: + n-array: Default joint positions for this robot + """ + # Check top-level default_joint_pos + if self._definition.default_joint_pos: + return self._convert_yaml_list_to_tensor(self._definition.default_joint_pos) + # Check end-effector specific default_joint_pos + if self.has_end_effector_variants: + eef_def = self._get_end_effector_definition() + if eef_def and eef_def.default_joint_pos: + return self._convert_yaml_list_to_tensor(eef_def.default_joint_pos) + + if self.is_mobile_manipulation: + return ( + self.tucked_default_joint_pos if self.default_reset_mode == "tuck" else self.untucked_default_joint_pos + ) + + @property + def _default_controller_config(self): + """ + Returns: + dict: default nested dictionary mapping controller name(s) to specific controller + configurations for this object. Note that the order specifies the sequence of actions to be received + from the environment. + + Expected structure is as follows: + group1: + controller_name1: + controller_name1_params + ... + controller_name2: + ... + group2: + ... + + The @group keys specify the control type for various aspects of the object, + e.g.: "head", "arm", "base", etc. @controller_name keys specify the supported controllers for + that group. A default specification MUST be specified for each controller_name. + e.g.: IKController, DifferentialDriveController, JointController, etc. + """ + cfg = {} + if self.is_manipulation: + arm_ik_configs = self._default_arm_ik_controller_configs + arm_osc_configs = self._default_arm_osc_controller_configs + arm_joint_configs = self._default_arm_joint_controller_configs + arm_null_joint_configs = self._default_arm_null_joint_controller_configs + gripper_pj_configs = self._default_gripper_multi_finger_controller_configs + gripper_joint_configs = self._default_gripper_joint_controller_configs + gripper_null_configs = self._default_gripper_null_controller_configs + + # Add arm and gripper defaults, per arm + for arm in self.arm_names: + cfg["arm_{}".format(arm)] = { + arm_ik_configs[arm]["name"]: arm_ik_configs[arm], + arm_osc_configs[arm]["name"]: arm_osc_configs[arm], + arm_joint_configs[arm]["name"]: arm_joint_configs[arm], + arm_null_joint_configs[arm]["name"]: arm_null_joint_configs[arm], + } + cfg["gripper_{}".format(arm)] = { + gripper_pj_configs[arm]["name"]: gripper_pj_configs[arm], + gripper_joint_configs[arm]["name"]: gripper_joint_configs[arm], + gripper_null_configs[arm]["name"]: gripper_null_configs[arm], + } + if self.is_locomotion: + # Add supported base controllers + cfg["base"] = { + self._default_base_joint_controller_config["name"]: self._default_base_joint_controller_config, + self._default_base_null_joint_controller_config[ + "name" + ]: self._default_base_null_joint_controller_config, + } + if self.is_holonomic_base: + # Add supported base controllers + cfg["base"] = { + self._default_holonomic_base_joint_controller_config[ + "name" + ]: self._default_holonomic_base_joint_controller_config, + self._default_base_null_joint_controller_config[ + "name" + ]: self._default_base_null_joint_controller_config, + } + if self.is_articulated_trunk: + cfg["trunk"] = { + self._default_trunk_joint_controller_config["name"]: self._default_trunk_joint_controller_config, + self._default_trunk_null_joint_controller_config[ + "name" + ]: self._default_trunk_null_joint_controller_config, + self._default_trunk_ik_controller_config["name"]: self._default_trunk_ik_controller_config, + self._default_trunk_osc_controller_config["name"]: self._default_trunk_osc_controller_config, + } + if self.is_two_wheel: + cfg["base"][self._default_base_differential_drive_controller_config["name"]] = ( + self._default_base_differential_drive_controller_config + ) + if self.is_active_camera: + cfg["camera"] = { + self._default_camera_joint_controller_config["name"]: self._default_camera_joint_controller_config, + self._default_camera_null_joint_controller_config[ + "name" + ]: self._default_camera_null_joint_controller_config, + } + + return cfg + + def _get_assisted_grasp_joint_type(self, target_obj, target_link_name): + """ + Check whether an object @obj can be grasped. If so, return the joint type to use for assisted grasping. + Otherwise, return None. + + Args: + target_obj (USDObject): Object targeted for an assisted grasp + target_link_name (str): Name of the link of the object to be grasped + + Returns: + (None or str): If obj can be grasped, returns the joint type to use for assisted grasping. + """ + assert self.is_manipulation + # Deny objects that are too heavy and are not a non-base link of a fixed-base object) + mass = target_obj.links[target_link_name].mass + if mass > m.ASSIST_GRASP_MASS_THRESHOLD and not ( + target_obj.fixed_base and target_link_name != target_obj.root_link_name + ): + return None + + # Otherwise, compute the joint type. We use a fixed joint unless the link is a non-fixed link. + # A link is non-fixed if it has any non-fixed parent joints. + joint_type = "FixedJoint" + for edge in nx.edge_dfs(target_obj.articulation_tree, target_link_name, orientation="reverse"): + joint = target_obj.articulation_tree.edges[edge[:2]] + if joint["joint_type"] != JointType.JOINT_FIXED: + joint_type = "SphericalJoint" + break + + return joint_type + + @property + def _default_controllers(self): + """ + Returns: + dict: Maps object group (e.g. base, arm, etc.) to default controller class name to use + (e.g. IKController, JointController, etc.) + """ + controllers = {} + + if self.is_manipulation: + for arm in self.arm_names: + controllers["arm_{}".format(arm)] = "JointController" + controllers["gripper_{}".format(arm)] = "JointController" + if self.is_locomotion: + controllers["base"] = "JointController" + if self.is_holonomic_base: + controllers["base"] = "HolonomicBaseJointController" + if self.is_articulated_trunk: + controllers["trunk"] = "JointController" + if self.is_two_wheel: + controllers["base"] = "DifferentialDriveController" + if self.is_active_camera: + controllers["camera"] = "JointController" + + # Override with config-specified defaults + if self._definition.default_controllers: + for key, value in self._definition.default_controllers.items(): + controllers[key] = value + + return controllers + + @property + def grasping_mode(self): + """ + Grasping mode of this robot. Is one of AG_MODES + + Returns: + str: Grasping mode for this robot + """ + assert self.is_manipulation + return self._grasping_mode + + @property + def n_arms(self): + """ + Specific for Manipulation Robot. + Returns: + int: Number of arms this robot has. Returns 1 by default + """ + if self._definition.manipulation: + return self._definition.manipulation.n_arms + return 1 + + @property + def arm_names(self): + """ + Specific for Manipulation Robot. + Returns: + list of str: List of arm names for this robot. Should correspond to the keys used to index into + arm- and gripper-related dictionaries, e.g.: eef_link_names, finger_link_names, etc. + Default is string enumeration based on @self.n_arms. + """ + if self._definition.manipulation and self._definition.manipulation.arm_names: + return self._definition.manipulation.arm_names + return [str(i) for i in range(self.n_arms)] + + @property + def default_arm(self): + """ + Returns: + str: Default arm name for this robot, corresponds to the first entry in @arm_names by default + """ + assert self.is_manipulation + return self.arm_names[0] + + @property + def arm_action_idx(self): + assert self.is_manipulation + arm_action_idx = {} + for arm_name in self.arm_names: + c_order_idx = self.controller_order.index(f"arm_{arm_name}") + action_start_idx = sum( + ControllerView.get_command_dim(self._controllers[self.controller_order[i]][0]) + for i in range(c_order_idx) + ) + arm_group_key = self._controllers[f"arm_{arm_name}"][0] + arm_action_idx[arm_name] = th.arange( + action_start_idx, action_start_idx + ControllerView.get_command_dim(arm_group_key) + ) + return arm_action_idx + + @property + def gripper_action_idx(self): + assert self.is_manipulation + gripper_action_idx = {} + for arm_name in self.arm_names: + c_order_idx = self.controller_order.index(f"gripper_{arm_name}") + action_start_idx = sum( + ControllerView.get_command_dim(self._controllers[self.controller_order[i]][0]) + for i in range(c_order_idx) + ) + gripper_group_key = self._controllers[f"gripper_{arm_name}"][0] + gripper_action_idx[arm_name] = th.arange( + action_start_idx, action_start_idx + ControllerView.get_command_dim(gripper_group_key) + ) + return gripper_action_idx + + @cached_property + def arm_link_names(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to corresponding arm link names, + should correspond to specific link names in this robot's underlying model file + + Note: the ordering within the dictionary is assumed to be intentional, and is + directly used to define the set of corresponding idxs. + """ + assert self.is_manipulation + if self._definition.manipulation and self._definition.manipulation.arm_link_names: + return self._definition.manipulation.arm_link_names + return {} + + @cached_property + def arm_joint_names(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to corresponding arm joint names, + should correspond to specific joint names in this robot's underlying model file + + Note: the ordering within the dictionary is assumed to be intentional, and is + directly used to define the set of corresponding control idxs. + """ + assert self.is_manipulation + if self._definition.manipulation and self._definition.manipulation.arm_joint_names: + return self._definition.manipulation.arm_joint_names + return {} + + @cached_property + def eef_link_names(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to corresponding name of the EEF link, + should correspond to specific link name in this robot's underlying model file + """ + assert self.is_manipulation + # Check manipulation definition + if self._definition.manipulation and self._definition.manipulation.eef_link_names: + return self._definition.manipulation.eef_link_names + # Check end-effector specific + if self.has_end_effector_variants: + eef_def = self._get_end_effector_definition() + if eef_def and eef_def.eef_link_names: + return eef_def.eef_link_names + raise ValueError(f"eef_link_names not found in model definition for model={self.model}") + + @cached_property + def gripper_link_names(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to array of link names corresponding to + this robot's gripper. Should be mutual exclusive from self.arm_link_names and self.finger_link_names! + + Note: the ordering within the dictionary is assumed to be intentional, and is + directly used to define the set of corresponding idxs. + """ + assert self.is_manipulation + if self._definition.manipulation and self._definition.manipulation.gripper_link_names: + return self._definition.manipulation.gripper_link_names + raise NotImplementedError + + @cached_property + def finger_link_names(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to array of link names corresponding to + this robot's fingers + + Note: the ordering within the dictionary is assumed to be intentional, and is + directly used to define the set of corresponding idxs. + """ + assert self.is_manipulation + # Check manipulation definition + if self._definition.manipulation and self._definition.manipulation.finger_link_names: + return self._definition.manipulation.finger_link_names + # Check end-effector specific + if self.has_end_effector_variants: + eef_def = self._get_end_effector_definition() + if eef_def and eef_def.finger_link_names: + return eef_def.finger_link_names + return {} + + @cached_property + def finger_joint_names(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to array of joint names corresponding to + this robot's fingers. + + Note: the ordering within the dictionary is assumed to be intentional, and is + directly used to define the set of corresponding control idxs. + """ + assert self.is_manipulation + # Check manipulation definition + if self._definition.manipulation and self._definition.manipulation.finger_joint_names: + return self._definition.manipulation.finger_joint_names + # Check end-effector specific + if self.has_end_effector_variants: + eef_def = self._get_end_effector_definition() + if eef_def and eef_def.finger_joint_names: + return eef_def.finger_joint_names + return {} + + @cached_property + def arm_control_idx(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to indices in low-level control + vector corresponding to arm joints. + """ + assert self.is_manipulation + idxs = { + arm: th.tensor([list(self.joints.keys()).index(name) for name in self.arm_joint_names[arm]]) + for arm in self.arm_names + } + if self._definition.manipulation and self._definition.manipulation.add_combined_arm_control_idx: + idxs["combined"] = th.sort(th.cat([val for val in idxs.values()]))[0] + return idxs + + @cached_property + def gripper_control_idx(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to indices in low-level control + vector corresponding to gripper joints. + """ + assert self.is_manipulation + return { + arm: th.tensor([list(self.joints.keys()).index(name) for name in self.finger_joint_names[arm]]) + for arm in self.arm_names + } + + @cached_property + def arm_links(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to robot links corresponding to + that arm's links + """ + assert self.is_manipulation + return {arm: [self._links[link] for link in self.arm_link_names[arm]] for arm in self.arm_names} + + @cached_property + def eef_links(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to robot link corresponding to that arm's + eef link. NOTE: These links always have a canonical local orientation frame -- assuming a parallel jaw + eef morphology, it is assumed that the eef z-axis points out from the tips of the fingers, the y-axis + points from the left finger to the right finger, and the x-axis inferred programmatically + """ + assert self.is_manipulation + return {arm: self._links[self.eef_link_names[arm]] for arm in self.arm_names} + + @cached_property + def gripper_links(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to robot links corresponding to + that arm's gripper links + """ + assert self.is_manipulation + return {arm: [self._links[link] for link in self.gripper_link_names[arm]] for arm in self.arm_names} + + @cached_property + def finger_links(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to robot links corresponding to + that arm's finger links + """ + assert self.is_manipulation + return {arm: [self._links[link] for link in self.finger_link_names[arm]] for arm in self.arm_names} + + @cached_property + def finger_joints(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to robot joints corresponding to + that arm's finger joints + """ + assert self.is_manipulation + return {arm: [self._joints[joint] for joint in self.finger_joint_names[arm]] for arm in self.arm_names} + + @property + def _assisted_grasp_start_points(self): + """ + Returns: + dict: Dictionary mapping individual arm appendage names to array of GraspingPoint tuples, + composed of (link_name, position) values specifying valid grasping start points located at + cartesian (x,y,z) coordinates specified in link_name's local coordinate frame. + These values will be used in conjunction with + @self.assisted_grasp_end_points to trigger assisted grasps, where objects that intersect + with any ray starting at any point in @self.assisted_grasp_start_points and terminating at any point in + @self.assisted_grasp_end_points will trigger an assisted grasp (calculated individually for each gripper + appendage). By default, each entry returns None, and must be implemented by any robot subclass that + wishes to use assisted grasping. + """ + if not self.is_manipulation: + return None + + # Use EEF definition if available + eef_def = self._get_end_effector_definition() + if eef_def is not None and eef_def.ag_start_points is not None: + return self._convert_to_grasping_points({self.default_arm: eef_def.ag_start_points}) + + # Use manipulation definition if available + if self._definition.manipulation.assisted_grasp_start_points: + return self._convert_to_grasping_points(self._definition.manipulation.assisted_grasp_start_points) + + # No assisted grasp start points found + return None + + @property + def assisted_grasp_start_points(self): + """ + Returns: + dict: Dictionary mapping individual arm appendage names to array of GraspingPoint tuples, + composed of (link_name, position) values specifying valid grasping start points located at + cartesian (x,y,z) coordinates specified in link_name's local coordinate frame. + These values will be used in conjunction with + @self.assisted_grasp_end_points to trigger assisted grasps, where objects that intersect + with any ray starting at any point in @self.assisted_grasp_start_points and terminating at any point in + @self.assisted_grasp_end_points will trigger an assisted grasp (calculated individually for each gripper + appendage). By default, each entry returns None, and must be implemented by any robot subclass that + wishes to use assisted grasping. + """ + assert self.is_manipulation + return ( + self._assisted_grasp_start_points + if self._assisted_grasp_start_points is not None + else self._default_ag_start_points + ) + + @property + def _assisted_grasp_end_points(self): + """ + Returns: + dict: Dictionary mapping individual arm appendage names to array of GraspingPoint tuples, + composed of (link_name, position) values specifying valid grasping end points located at + cartesian (x,y,z) coordinates specified in link_name's local coordinate frame. + These values will be used in conjunction with + @self.assisted_grasp_start_points to trigger assisted grasps, where objects that intersect + with any ray starting at any point in @self.assisted_grasp_start_points and terminating at any point in + @self.assisted_grasp_end_points will trigger an assisted grasp (calculated individually for each gripper + appendage). By default, each entry returns None, and must be implemented by any robot subclass that + wishes to use assisted grasping. + """ + if not self.is_manipulation: + return None + + # Use EEF definition if available + eef_def = self._get_end_effector_definition() + if eef_def is not None and eef_def.ag_end_points is not None: + return self._convert_to_grasping_points({self.default_arm: eef_def.ag_end_points}) + + # Use manipulation definition if available + if self._definition.manipulation.assisted_grasp_end_points: + return self._convert_to_grasping_points(self._definition.manipulation.assisted_grasp_end_points) + + # No assisted grasp end points found + return None + + @property + def assisted_grasp_end_points(self): + """ + Returns: + dict: Dictionary mapping individual arm appendage names to array of GraspingPoint tuples, + composed of (link_name, position) values specifying valid grasping end points located at + cartesian (x,y,z) coordinates specified in link_name's local coordinate frame. + These values will be used in conjunction with + @self.assisted_grasp_start_points to trigger assisted grasps, where objects that intersect + with any ray starting at any point in @self.assisted_grasp_start_points and terminating at any point in + @self.assisted_grasp_end_points will trigger an assisted grasp (calculated individually for each gripper + appendage). By default, each entry returns None, and must be implemented by any robot subclass that + wishes to use assisted grasping. + """ + assert self.is_manipulation + return ( + self._assisted_grasp_end_points + if self._assisted_grasp_end_points is not None + else self._default_ag_end_points + ) + + @property + def eef_to_fingertip_lengths(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to per-finger corresponding z-distance between EEF and each + respective fingertip + """ + assert self.is_manipulation + return self._eef_to_fingertip_lengths + + @property + def arm_workspace_range(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to a tuple indicating the start and end of the + angular range of the arm workspace around the Z axis of the robot, where 0 is facing + forward. + """ + assert self.is_manipulation + dic = dict() + workspace_range = {} + if self._definition.manipulation and self._definition.manipulation.arm_workspace_range: + workspace_range = self._definition.manipulation.arm_workspace_range + for k, v in workspace_range.items(): + dic[k] = th.deg2rad(th.tensor(v, dtype=th.float32)) + return dic + + def get_eef_pose(self, arm="default"): + """ + Args: + arm (str): specific arm to grab eef pose. Default is "default" which corresponds to the first entry + in self.arm_names + + Returns: + 2-tuple: End-effector pose, in (pos, quat) format, corresponding to arm @arm + """ + assert self.is_manipulation + arm = self.default_arm if arm == "default" else arm + return self._links[self.eef_link_names[arm]].get_position_orientation() + + def get_eef_position(self, arm="default"): + """ + Args: + arm (str): specific arm to grab eef position. Default is "default" which corresponds to the first entry + in self.arm_names + + Returns: + 3-array: (x,y,z) global end-effector Cartesian position for this robot's end-effector corresponding + to arm @arm + """ + assert self.is_manipulation + arm = self.default_arm if arm == "default" else arm + return self.get_eef_pose(arm=arm)[0] + + def get_eef_orientation(self, arm="default"): + """ + Args: + arm (str): specific arm to grab eef orientation. Default is "default" which corresponds to the first entry + in self.arm_names + + Returns: + 3-array: (x,y,z,w) global quaternion orientation for this robot's end-effector corresponding + to arm @arm + """ + assert self.is_manipulation + arm = self.default_arm if arm == "default" else arm + return self.get_eef_pose(arm=arm)[1] + + def get_relative_eef_pose(self, arm="default", mat=False): + """ + Args: + arm (str): specific arm to grab eef pose. Default is "default" which corresponds to the first entry + in self.arm_names + mat (bool): whether to return pose in matrix form (mat=True) or (pos, quat) tuple (mat=False) + + Returns: + 2-tuple or (4, 4)-array: End-effector pose, either in 4x4 homogeneous + matrix form (if @mat=True) or (pos, quat) tuple (if @mat=False), corresponding to arm @arm + """ + assert self.is_manipulation + arm = self.default_arm if arm == "default" else arm + eef_link_pose = self.eef_links[arm].get_position_orientation() + base_link_pose = self.get_position_orientation() + pose = T.relative_pose_transform(*eef_link_pose, *base_link_pose) + return T.pose2mat(pose) if mat else pose + + def get_relative_eef_position(self, arm="default"): + """ + Args: + arm (str): specific arm to grab relative eef pos. + Default is "default" which corresponds to the first entry in self.arm_names + + + Returns: + 3-array: (x,y,z) Cartesian position of end-effector relative to robot base frame + """ + assert self.is_manipulation + arm = self.default_arm if arm == "default" else arm + return self.get_relative_eef_pose(arm=arm)[0] + + def get_relative_eef_orientation(self, arm="default"): + """ + Args: + arm (str): specific arm to grab relative eef orientation. + Default is "default" which corresponds to the first entry in self.arm_names + + Returns: + 4-array: (x,y,z,w) quaternion orientation of end-effector relative to robot base frame + """ + assert self.is_manipulation + arm = self.default_arm if arm == "default" else arm + return self.get_relative_eef_pose(arm=arm)[1] + + def get_relative_eef_lin_vel(self, arm="default"): + """ + Args: + arm (str): specific arm to grab relative eef linear velocity. + Default is "default" which corresponds to the first entry in self.arm_names + + + Returns: + 3-array: (x,y,z) Linear velocity of end-effector relative to robot base frame + """ + assert self.is_manipulation + arm = self.default_arm if arm == "default" else arm + base_link_quat = self.get_position_orientation()[1] + return T.quat2mat(base_link_quat).T @ self.eef_links[arm].get_linear_velocity() + + def get_relative_eef_ang_vel(self, arm="default"): + """ + Args: + arm (str): specific arm to grab relative eef angular velocity. + Default is "default" which corresponds to the first entry in self.arm_names + + Returns: + 3-array: (ax,ay,az) angular velocity of end-effector relative to robot base frame + """ + assert self.is_manipulation + arm = self.default_arm if arm == "default" else arm + base_link_quat = self.get_position_orientation()[1] + return T.quat2mat(base_link_quat).T @ self.eef_links[arm].get_angular_velocity() + + def _calculate_in_hand_object(self, arm="default"): + """ + Calculates which object to assisted-grasp for arm @arm. Returns an (object_id, link_id) tuple or None + if no valid AG-enabled object can be found. + + Args: + arm (str): specific arm to calculate in-hand object for. + Default is "default" which corresponds to the first entry in self.arm_names + + Returns: + + """ + assert self.is_manipulation + assert self.grasping_mode in ["assisted", "sticky"] + + arm = self.default_arm if arm == "default" else arm + + candidates_set, robot_contact_links = self._find_gripper_contacts(arm=arm) + # If we're using assisted grasping, we further filter candidates via ray-casting + if self.grasping_mode == "assisted": + candidates_set_raycast = self._find_gripper_raycast_collisions(arm=arm) + candidates_set = candidates_set.intersection(candidates_set_raycast) + + # Immediately return if there are no valid candidates + if len(candidates_set) == 0: + return None + + # Find the closest object to the gripper center + gripper_center_pos = self.eef_links[arm].get_position_orientation()[0] + + candidate_data = [] + for prim_path in candidates_set: + # Calculate position of the object link. Only allow this for objects currently. + obj_prim_path, link_name = prim_path.rsplit("/", 1) + candidate_obj = self.scene.object_registry("prim_path", obj_prim_path, None) + if ( + candidate_obj is None + or link_name not in candidate_obj.links + or not isinstance(candidate_obj.links[link_name], RigidDynamicPrim) + ): + continue + candidate_link = candidate_obj.links[link_name] + dist = th.norm(candidate_link.get_position_orientation()[0] - gripper_center_pos) + candidate_data.append((prim_path, dist)) + + if not candidate_data: + return None + + candidate_data = sorted(candidate_data, key=lambda x: x[-1]) + ag_prim_path, _ = candidate_data[0] + + # Make sure the ag_prim_path is not a self collision + assert ag_prim_path not in self.link_prim_paths, "assisted grasp object cannot be the robot itself!" + + # Make sure at least two fingers are in contact with this object + robot_contacts = robot_contact_links[ag_prim_path] + touching_at_least_two_fingers = ( + True + if self.grasping_mode == "sticky" + else len({link.prim_path for link in self.finger_links[arm]}.intersection(robot_contacts)) >= 2 + ) + if not touching_at_least_two_fingers: + return None + + # TODO: Better heuristic, hacky, we assume the parent object prim path is the prim_path minus the last "/" item + ag_obj_prim_path = "/".join(ag_prim_path.split("/")[:-1]) + ag_obj_link_name = ag_prim_path.split("/")[-1] + ag_obj = self.scene.object_registry("prim_path", ag_obj_prim_path) + + # Return None if object cannot be assisted grasped + if ag_obj is None: + return None + + # Get object and its contacted link + return ag_obj, ag_obj_link_name + + def _find_gripper_raycast_collisions(self, arm="default"): + """ + For arm @arm, calculate any prims that are not part of the robot + itself that intersect with rays cast between any of the gripper's start and end points + + Args: + arm (str): specific arm whose gripper will be checked for raycast collisions. Default is "default" + which corresponds to the first entry in self.arm_names + + Returns: + set[str]: set of prim path of detected raycast intersections that + are not the robot itself. Note: if no objects that are not the robot itself are intersecting, + the set will be empty. + """ + assert self.is_manipulation + arm = self.default_arm if arm == "default" else arm + # First, make sure start and end grasp points exist (i.e.: aren't None) + assert ( + self.assisted_grasp_start_points[arm] is not None + ), "In order to use assisted grasping, assisted_grasp_start_points must not be None!" + assert ( + self.assisted_grasp_end_points[arm] is not None + ), "In order to use assisted grasping, assisted_grasp_end_points must not be None!" + + # Iterate over all start and end grasp points and calculate their x,y,z positions in the world frame + # (per arm appendage) + # Since we'll be calculating the cartesian cross product between start and end points, we stack the start points + # by the number of end points and repeat the individual elements of the end points by the number of start points + n_start_points = len(self.assisted_grasp_start_points[arm]) + n_end_points = len(self.assisted_grasp_end_points[arm]) + start_and_end_points = th.zeros(n_start_points + n_end_points, 3) + link_positions = th.zeros(n_start_points + n_end_points, 3) + link_quats = th.zeros(n_start_points + n_end_points, 4) + idx = 0 + for grasp_start_point in self.assisted_grasp_start_points[arm]: + # Get world coordinates of link base frame + link_pos, link_orn = self.links[grasp_start_point.link_name].get_position_orientation() + link_positions[idx] = link_pos + link_quats[idx] = link_orn + start_and_end_points[idx] = grasp_start_point.position + idx += 1 + + for grasp_end_point in self.assisted_grasp_end_points[arm]: + # Get world coordinates of link base frame + link_pos, link_orn = self.links[grasp_end_point.link_name].get_position_orientation() + link_positions[idx] = link_pos + link_quats[idx] = link_orn + start_and_end_points[idx] = grasp_end_point.position + idx += 1 + + # Transform start / end points into world frame (batched call for efficiency sake) + start_and_end_points = link_positions + (T.quat2mat(link_quats) @ start_and_end_points.unsqueeze(-1)).squeeze( + -1 + ) + # Stack the start points and repeat the end points, and add these values to the raycast dicts + raycast_startpoints = th.tile(start_and_end_points[:n_start_points], (n_end_points, 1)) + raycast_endpoints = th.repeat_interleave(start_and_end_points[n_start_points:], n_start_points, dim=0) + 1e-8 + ray_data = set() + # Calculate raycasts from each start point to end point -- this is n_startpoints * n_endpoints total rays + for result in raytest_batch(raycast_startpoints, raycast_endpoints, only_closest=True): + if result["hit"]: + # filter out self body parts (we currently assume that the robot cannot grasp itself) + if self.prim_path not in result["rigidBody"]: + ray_data.add(result["rigidBody"]) + return ray_data + + def _handle_release_window(self, arm="default"): + """ + Handles releasing an object from arm @arm + + Args: + arm (str): specific arm to handle release window. + Default is "default" which corresponds to the first entry in self.arm_names + """ + assert self.is_manipulation + arm = self.default_arm if arm == "default" else arm + self._ag_release_counter[arm] += 1 + time_since_release = self._ag_release_counter[arm] * og.sim.get_physics_dt() + if time_since_release >= m.RELEASE_WINDOW: + self._ag_obj_in_hand[arm] = None + self._ag_release_counter[arm] = None + + @property + def curobo_path(self): + """ + Returns: + str or Dict[CuRoboEmbodimentSelection, str]: file path to the robot curobo file or a mapping from + CuRoboEmbodimentSelection to the file path + """ + # Check top-level curobo_path + if self._definition.curobo_path: + return os.path.join(get_dataset_path("omnigibson-robot-assets"), self._definition.curobo_path) + # Check end-effector specific curobo_path + if self.has_end_effector_variants: + eef_def = self._get_end_effector_definition() + if eef_def and eef_def.curobo_path: + return os.path.join(get_dataset_path("omnigibson-robot-assets"), eef_def.curobo_path) + else: + assert False, "Robot not supported for curobo." + + # Import here to avoid circular imports + from omnigibson.action_primitives.curobo import CuRoboEmbodimentSelection + + # By default, sets the standardized path + model = self.model.lower() + return { + emb_sel: os.path.join( + get_dataset_path("omnigibson-robot-assets"), + f"models/{model}/curobo/{model}_description_curobo_{emb_sel.value}.yaml", + ) + for emb_sel in CuRoboEmbodimentSelection + } + + @property + def curobo_attached_object_link_names(self): + """ + Returns: + Dict[str, str]: mapping from robot eef link names to the link names of the attached objects + """ + if ( + self._definition.manipulation + and self._definition.manipulation.eef_support_curobo_attached_object_link_names + ): + assert ( + self.end_effector in self._definition.manipulation.eef_support_curobo_attached_object_link_names + ), "Robot not supported for curobo." + + assert self.is_manipulation + # By default, sets the standardized path + return {eef_link_name: f"attached_object_{eef_link_name}" for eef_link_name in self.eef_link_names.values()} + + @property + def _default_arm_joint_controller_configs(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to default controller config to control that + robot's arm. Uses velocity control by default. + """ + assert self.is_manipulation + dic = {} + for arm in self.arm_names: + dic[arm] = { + "name": "JointController", + "control_freq": self._control_freq, + "control_limits": self.control_limits, + "dof_idx": self.arm_control_idx[arm], + "command_output_limits": None, + "motor_type": "position", + "use_delta_commands": True, + "use_impedances": False, + } + return dic + + @property + def _default_arm_ik_controller_configs(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to default controller config for an + Inverse kinematics controller to control this robot's arm + """ + assert self.is_manipulation + dic = {} + for arm in self.arm_names: + dic[arm] = { + "name": "InverseKinematicsController", + "control_freq": self._control_freq, + "reset_joint_pos": self.reset_joint_pos, + "control_limits": self.control_limits, + "dof_idx": self.arm_control_idx[arm], + "command_output_limits": ( + th.tensor([-0.2, -0.2, -0.2, -0.5, -0.5, -0.5]), + th.tensor([0.2, 0.2, 0.2, 0.5, 0.5, 0.5]), + ), + "mode": "pose_delta_ori", + "smoothing_filter_size": 2, + "workspace_pose_limiter": None, + } + return dic + + @property + def _default_arm_osc_controller_configs(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to default controller config for an + operational space controller to control this robot's arm + """ + assert self.is_manipulation + dic = {} + for arm in self.arm_names: + dic[arm] = { + "name": "OperationalSpaceController", + "control_freq": self._control_freq, + "reset_joint_pos": self.reset_joint_pos, + "control_limits": self.control_limits, + "dof_idx": self.arm_control_idx[arm], + "command_output_limits": ( + th.tensor([-0.2, -0.2, -0.2, -0.5, -0.5, -0.5]), + th.tensor([0.2, 0.2, 0.2, 0.5, 0.5, 0.5]), + ), + "mode": "pose_delta_ori", + "workspace_pose_limiter": None, + } + return dic + + @property + def _default_arm_null_joint_controller_configs(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to default arm null controller config + to control this robot's arm i.e. dummy controller + """ + assert self.is_manipulation + dic = {} + for arm in self.arm_names: + dic[arm] = { + "name": "NullJointController", + "control_freq": self._control_freq, + "motor_type": "position", + "control_limits": self.control_limits, + "dof_idx": self.arm_control_idx[arm], + "default_goal": self.reset_joint_pos[self.arm_control_idx[arm]], + "use_impedances": False, + } + return dic + + @property + def _default_gripper_multi_finger_controller_configs(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to default controller config to control + this robot's multi finger gripper. Assumes robot gripper idx has exactly two elements + """ + assert self.is_manipulation + dic = {} + for arm in self.arm_names: + dic[arm] = { + "name": "MultiFingerGripperController", + "control_freq": self._control_freq, + "motor_type": "position", + "control_limits": self.control_limits, + "dof_idx": self.gripper_control_idx[arm], + "command_output_limits": "default", + "mode": "binary", + "limit_tolerance": 0.001, + "inverted": self._grasping_direction == "upper", + } + return dic + + @property + def _default_gripper_joint_controller_configs(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to default gripper joint controller config + to control this robot's gripper + """ + assert self.is_manipulation + dic = {} + for arm in self.arm_names: + dic[arm] = { + "name": "JointController", + "control_freq": self._control_freq, + "motor_type": "velocity", + "control_limits": self.control_limits, + "dof_idx": self.gripper_control_idx[arm], + "command_output_limits": "default", + "use_delta_commands": False, + "use_impedances": False, + } + return dic + + @property + def _default_gripper_null_controller_configs(self): + """ + Returns: + dict: Dictionary mapping arm appendage name to default gripper null controller config + to control this robot's (non-prehensile) gripper i.e. dummy controller + """ + assert self.is_manipulation + dic = {} + for arm in self.arm_names: + dic[arm] = { + "name": "NullJointController", + "control_freq": self._control_freq, + "motor_type": "velocity", + "control_limits": self.control_limits, + "dof_idx": self.gripper_control_idx[arm], + "default_goal": th.zeros(len(self.gripper_control_idx[arm])), + "use_impedances": False, + } + return dic + + def _maybe_establish_grasp(self, target_obj, target_link_name, arm): + """ + Establishes an assisted grasp joint between the robot and the target object if the object + is assisted-graspable and the robot is in contact with the object. + + This is called internally when all of the temporal requirements of the grasp window are met. + (Rays have been hitting object for N frames, fingers have been in contact with object, etc.) + so we only perform some final checks. + + Args: + target_obj (USDObject): Object targeted for an assisted grasp + target_link_name (str): Name of the link of the object to be grasped + arm (str): Name of the arm to create the joint for + """ + # Decide what type of joint is needed + joint_type = self._get_assisted_grasp_joint_type(target_obj, target_link_name) + if joint_type is None: + return + + # Compute the contact position in world frame using this robot's own rigid contact view. + target_link_prim_path = target_obj.links[target_link_name].prim_path + contact_pos_world = self._find_finger_contact_position(arm, target_link_prim_path) + if contact_pos_world is None: + return + + # Establish the grasp + self._establish_grasp(target_obj, target_link_name, arm, contact_pos_world, joint_type) + + def _establish_grasp(self, target_obj, target_link_name, arm, contact_pos_world, joint_type): + """ + Establishes an assisted grasp joint between the robot and the target object at the given contact position. + + This function guarantees that the joint is created, computing the joint's relative position to both + the robot and the target object using both sides' current poses, and storing the joint's parameters + in the robot's state. + + It can be called externally if desired, e.g. if you want to establish a grasp at a specific contact position + for use in symbolic primitive actions. It is also called internally when the robot has decided the physical + state of the world is such that it should establish a grasp. + + Args: + target_obj (USDObject): Object targeted for an assisted grasp + target_link_name (str): Name of the link of the object to be grasped + arm (str): Name of the arm to create the joint for + contact_pos_world (th.tensor): Position of the contact point in world frame + joint_type (str): Type of joint to create + """ + + # Find out where the joint should go in the local frame of both the robot and the target object + # Note that we can't use scaled transforms here because those are only available through Fabric getters + # which cannot be refreshed during a physics step. We instead use the unscaled position and orientation + # and divide by the scale of the robot and target object to get the local frame position and orientation. + joint_frame_orn = th.tensor([0, 0, 0, 1.0]) + eef_link_pos, eef_link_orn = self.eef_links[arm].get_position_orientation() + parent_frame_pos, parent_frame_orn = T.relative_pose_transform( + contact_pos_world, joint_frame_orn, eef_link_pos, eef_link_orn + ) + parent_frame_pos = parent_frame_pos / self.scale + obj_link_pos, obj_link_orn = target_obj.links[target_link_name].get_position_orientation() + child_frame_pos, child_frame_orn = T.relative_pose_transform( + contact_pos_world, joint_frame_orn, obj_link_pos, obj_link_orn + ) + child_frame_pos = child_frame_pos / target_obj.scale + + # Create the constraint params dict + constraint_params = { + "target_obj": target_obj, + "target_link_name": target_link_name, + "parent_frame_pos": parent_frame_pos, + "parent_frame_orn": parent_frame_orn, + "child_frame_pos": child_frame_pos, + "child_frame_orn": child_frame_orn, + "joint_type": joint_type, + } + + # Create the joint. This reads the + self._create_assisted_grasp_joint(arm, constraint_params) + + def _create_assisted_grasp_joint(self, arm, constraint_params): + """ + Creates an assisted grasp joint between the robot and the target object at the given contact position. + + This function acts on the relative position and orientation of the joint frame in the local frame of both the robot and the target object. + It does not take into account any world frame position or orientation. As a result, its inputs can be safely stored and restored from a saved state. + + The constraint params dictionary is expected to have the following keys: + - target_obj: USDObject: Object targeted for an assisted grasp + - target_link_name: str: Name of the link of the object to be grasped + - parent_frame_pos: th.tensor: Position of the parent frame + - parent_frame_orn: th.tensor: Orientation of the parent frame + - child_frame_pos: th.tensor: Position of the child frame + - child_frame_orn: th.tensor: Orientation of the child frame + - joint_type: str: Type of joint to create + + Args: + arm (str): Name of the arm to create the joint for + constraint_params (dict): Dictionary containing the constraint parameters + """ + # Create the joint + joint_prim_path = f"{self.eef_links[arm].prim_path}/ag_constraint" + joint_prim = create_joint( + prim_path=joint_prim_path, + joint_type=constraint_params["joint_type"], + body0=self.eef_links[arm].prim_path, + body1=constraint_params["target_obj"].links[constraint_params["target_link_name"]].prim_path, + enabled=True, + exclude_from_articulation=True, + joint_frame_in_parent_frame_pos=constraint_params["parent_frame_pos"], + joint_frame_in_parent_frame_quat=constraint_params["parent_frame_orn"], + joint_frame_in_child_frame_pos=constraint_params["child_frame_pos"], + joint_frame_in_child_frame_quat=constraint_params["child_frame_orn"], + ) + + # Save a reference to this joint prim + self._ag_obj_constraints[arm] = joint_prim + self._ag_obj_in_hand[arm] = constraint_params["target_obj"] + self._ag_obj_constraint_params[arm] = constraint_params + + def _convert_to_math_pi(self, ele): + """ + Convert string expressions involving pi (e.g., "pi/8", "0.5*pi", "-pi/2") + to their numeric values. + """ + if not isinstance(ele, str) or "pi" not in ele: + return float(ele) + + expression = ele.replace("-pi", f"(-{math.pi})") + expression = expression.replace("pi", str(math.pi)) + safe_dict = { + "__builtins__": {}, + "math": math, + "abs": abs, + "round": round, + } + result = eval(expression, safe_dict) + return float(result) + + def _convert_yaml_list_to_tensor(self, li): + ret = [] + for element in li: + ret.append(self._convert_to_math_pi(element)) + return th.tensor(ret) + + def _get_teleop_rotation_offset(self, prop): + dic = dict() + for key, value in prop.items(): + tensor_val = self._convert_yaml_list_to_tensor(value) + # Check if it's quaternion (4 values) or euler angles (3 values) + if len(value) == 4: + # Already a quaternion, return as-is + dic[key] = tensor_val + elif len(value) == 3: + # Euler angles, convert to quaternion + dic[key] = T.euler2quat(tensor_val) + else: + raise ValueError( + f"teleop_rotation_offset must have 3 (euler) or 4 (quaternion) values, got {len(tensor_val)}" + ) + return dic + + @property + def teleop_rotation_offset(self): + """ + Rotational offset that will be applied for teleoperation + such that [0, 0, 0, 1] as action will keep the robot eef pointing at +x axis + """ + assert self.is_manipulation + # Check end-effector specific + if self.has_end_effector_variants: + eef_def = self._get_end_effector_definition() + if eef_def and eef_def.teleop_rotation_offset: + return self._get_teleop_rotation_offset(eef_def.teleop_rotation_offset) + # Check manipulation definition + if self._definition.manipulation and self._definition.manipulation.teleop_rotation_offset: + return self._get_teleop_rotation_offset(self._definition.manipulation.teleop_rotation_offset) + return {arm: th.tensor([0, 0, 0, 1]) for arm in self.arm_names} + + @property + def _default_base_joint_controller_config(self): + """ + Returns: + dict: Default base joint controller config to control this robot's base. Uses velocity + control by default. + """ + assert self.is_locomotion + return { + "name": "JointController", + "control_freq": self._control_freq, + "motor_type": "velocity", + "control_limits": self.control_limits, + "dof_idx": self.base_control_idx, + "command_output_limits": "default", + "use_delta_commands": False, + } + + @property + def _default_base_null_joint_controller_config(self): + """ + Returns: + dict: Default null joint controller config to control this robot's base i.e. dummy controller + """ + assert self.is_locomotion + return { + "name": "NullJointController", + "control_freq": self._control_freq, + "motor_type": "velocity", + "control_limits": self.control_limits, + "dof_idx": self.base_control_idx, + "default_goal": th.zeros(len(self.base_control_idx)), + "use_impedances": False, + } + + def move_by(self, delta): + """ + Move robot base without physics simulation + + Args: + delta (float):float], (x,y,z) cartesian delta base position + """ + assert self.is_locomotion + new_pos = th.tensor(delta) + self.get_position_orientation()[0] + self.set_position_orientation(position=new_pos) + + def move_forward(self, delta=0.05): + """ + Move robot base forward without physics simulation + + Args: + delta (float): delta base position forward + """ + assert self.is_locomotion + self.move_by(T.quat2mat(self.get_position_orientation()[1]).dot(th.tensor([delta, 0, 0]))) + + def move_backward(self, delta=0.05): + """ + Move robot base backward without physics simulation + + Args: + delta (float): delta base position backward + """ + assert self.is_locomotion + self.move_by(T.quat2mat(self.get_position_orientation()[1]).dot(th.tensor([-delta, 0, 0]))) + + def move_left(self, delta=0.05): + """ + Move robot base left without physics simulation + + Args: + delta (float): delta base position left + """ + assert self.is_locomotion + self.move_by(T.quat2mat(self.get_position_orientation()[1]).dot(th.tensor([0, -delta, 0]))) + + def move_right(self, delta=0.05): + """ + Move robot base right without physics simulation + + Args: + delta (float): delta base position right + """ + assert self.is_locomotion + self.move_by(T.quat2mat(self.get_position_orientation()[1]).dot(th.tensor([0, delta, 0]))) + + def turn_left(self, delta=0.03): + """ + Rotate robot base left without physics simulation + + Args: + delta (float): delta angle to rotate the base left + """ + assert self.is_locomotion + quat = self.get_position_orientation()[1] + quat = T.quat_multiply((T.euler2quat(-delta, 0, 0)), quat) + self.set_position_orientation(orientation=quat) + + def turn_right(self, delta=0.03): + """ + Rotate robot base right without physics simulation + + Args: + delta (float): angle to rotate the base right + """ + assert self.is_locomotion + quat = self.get_position_orientation()[1] + quat = T.quat_multiply((T.euler2quat(delta, 0, 0)), quat) + self.set_position_orientation(orientation=quat) + + @cached_property + def non_floor_touching_base_links(self): + assert self.is_locomotion + return [self.links[name] for name in self.non_floor_touching_base_link_names] + + @cached_property + def non_floor_touching_base_link_names(self): + assert self.is_locomotion + return [self.base_footprint_link_name] + + @cached_property + def floor_touching_base_links(self): + assert self.is_locomotion + return [self.links[name] for name in self.floor_touching_base_link_names] + + @cached_property + def floor_touching_base_link_names(self): + assert self.is_locomotion + return self._definition.locomotion.floor_touching_base_link_names or [] + + @property + def base_action_idx(self): + assert self.is_locomotion + c_order_idx = self.controller_order.index("base") + action_start_idx = sum( + ControllerView.get_command_dim(self._controllers[self.controller_order[i]][0]) for i in range(c_order_idx) + ) + base_group_key = self._controllers["base"][0] + return th.arange(action_start_idx, action_start_idx + ControllerView.get_command_dim(base_group_key)) + + @property + def base_joint_names(self): + """ + Returns: + list: Array of joint names corresponding to this robot's base joints (e.g.: wheels). + + Note: the ordering within the list is assumed to be intentional, and is + directly used to define the set of corresponding control idxs. + """ + assert self.is_locomotion + return self._definition.locomotion.base_joint_names + + @cached_property + def base_control_idx(self): + """ + Returns: + n-array: Indices in low-level control vector corresponding to base joints. + """ + assert self.is_locomotion + return th.tensor([list(self.joints.keys()).index(name) for name in self.base_joint_names]) + + @property + def _default_holonomic_base_joint_controller_config(self): + """ + Returns: + dict: Default base joint controller config to control this robot's base. Uses velocity + control by default. + """ + assert self.is_holonomic_base + return { + "name": "HolonomicBaseJointController", + "control_freq": self._control_freq, + "motor_type": "velocity", + "control_limits": self.control_limits, + "dof_idx": self.base_control_idx, + "command_output_limits": "default", + } + + @cached_property + def base_idx(self): + """ + Returns: + n-array: Indices in low-level control vector corresponding to the six 1DoF base joints + """ + assert self.is_holonomic_base + joints = list(self.joints.keys()) + return th.tensor( + [joints.index(f"base_footprint_{component}_joint") for component in ["x", "y", "z", "rx", "ry", "rz"]] + ) + + def get_position_orientation(self, frame: Literal["world", "scene"] = "world", clone=True): + """ + Gets the robot's pose with respect to the specified frame. + + Args: + frame (Literal): frame to get the pose with respect to. Default to world. + scene frame gets position relative to the scene. + clone (bool): Whether to clone the internal buffer or not when grabbing data + + Returns: + 2-tuple: + - th.Tensor: (x,y,z) position in the specified frame + - th.Tensor: (x,y,z,w) quaternion orientation in the specified frame + """ + if self.is_holonomic_base: + return self.base_footprint_link.get_position_orientation(frame=frame, clone=clone) + return super().get_position_orientation(frame=frame, clone=clone) + + def set_linear_velocity(self, velocity: th.Tensor): + if self.is_holonomic_base: + # Transform the desired linear velocity from the world frame to the root_link ("base_footprint_x") frame + # Note that this will also set the target to be the desired linear velocity (i.e. the robot will try to maintain + # such velocity), which is different from the default behavior of set_linear_velocity for all other objects. + orn = self.root_link.get_position_orientation()[1] + velocity_in_root_link = T.quat2mat(orn).T @ velocity + self.set_joint_velocities(velocity_in_root_link, indices=self.base_idx[:3], drive=False) + else: + super().set_linear_velocity(velocity) + + def get_linear_velocity(self) -> th.Tensor: + if self.is_holonomic_base: + # Note that the link we are interested in is self.base_footprint_link, not self.root_link + return self.base_footprint_link.get_linear_velocity() + else: + return super().get_linear_velocity() + + def set_angular_velocity(self, velocity: th.Tensor) -> None: + if self.is_holonomic_base: + # 1e-3 is emperically tuned to be a good value for the time step + delta_t = 1e-3 / (velocity.norm() + 1e-6) + delta_mat = T.delta_rotation_matrix(velocity, delta_t) + base_link_orn = self.get_position_orientation()[1] + rot_mat = T.quat2mat(base_link_orn) + desired_mat = delta_mat @ rot_mat + root_link_orn = self.root_link.get_position_orientation()[1] + desired_mat_in_root_link = T.quat2mat(root_link_orn).T @ desired_mat + desired_intrinsic_eulers = T.mat2euler_intrinsic(desired_mat_in_root_link) + + cur_joint_pos = self.get_joint_positions()[self.base_idx[3:]] + delta_intrinsic_eulers = desired_intrinsic_eulers - cur_joint_pos + velocity_intrinsic = delta_intrinsic_eulers / delta_t + + self.set_joint_velocities(velocity_intrinsic, indices=self.base_idx[3:], drive=False) + else: + super().set_angular_velocity(velocity) + + def get_angular_velocity(self) -> th.Tensor: + if self.is_holonomic_base: + # Note that the link we are interested in is self.base_footprint_link, not self.root_link + return self.base_footprint_link.get_angular_velocity() + else: + return super().get_angular_velocity() + + def q_to_action(self, q): + """ + Converts a target joint configuration to an action that can be applied to this object. + All controllers should be JointController with use_delta_commands=False + """ + if not self.is_holonomic_base: + action = [] + for name, (group_key, _) in self.controllers.items(): + assert ControllerView.is_controller_type( + group_key, JointController + ) and not ControllerView.get_use_delta_commands( + group_key + ), f"Controller [{name}] should be a JointController with use_delta_commands=False!" + command = q[ControllerView.get_dof_idx(group_key)] + action.append(ControllerView.reverse_preprocess_command(group_key, command)) + action = th.cat(action, dim=0) + assert ( + action.shape[0] == self.action_dim + ), f"Action should have dimension {self.action_dim}, got {action.shape[0]}" + return action + + action = [] + for name, (group_key, _) in self.controllers.items(): + assert ( + ControllerView.is_controller_type(group_key, JointController) + and not ControllerView.get_use_delta_commands(group_key) + ), f"Controller [{name}] should be a JointController/HolonomicBaseJointController with use_delta_commands=False!" + command = q[ControllerView.get_dof_idx(group_key)] + if ControllerView.is_controller_type(group_key, HolonomicBaseJointController): + # Holonomnic base controller expects delta (x, y, rz) in robot base footprint link frame + # However, q actions are in absolute (x, y, rz) in robot root frame, so we need to convert them before feeding to the controller + base_joint_pos = self.get_joint_positions()[self.base_idx] + cur_rz_joint_pos = base_joint_pos[5] + delta_q = wrap_angle(command[2] - cur_rz_joint_pos) + + # For translation, we need to convert the command to the robot local frame + body_pos = base_joint_pos[:3] + body_quat = T.mat2quat(T.euler_intrinsic2mat(base_joint_pos[3:6])) + canonical_pos = th.tensor([command[0], command[1], body_pos[2]], dtype=th.float32) + local_pos = T.relative_pose_transform( + canonical_pos, th.tensor([0.0, 0.0, 0.0, 1.0]), body_pos, body_quat + )[0] + command = th.tensor([local_pos[0], local_pos[1], delta_q]) + action.append(ControllerView.reverse_preprocess_command(group_key, command)) + action = th.cat(action, dim=0) + assert ( + action.shape[0] == self.action_dim + ), f"Action should have dimension {self.action_dim}, got {action.shape[0]}" + return action + + @property + def tucked_default_joint_pos(self): + assert self.is_mobile_manipulation + return self._convert_yaml_list_to_tensor(self._definition.mobile_manipulation.tucked_default_joint_pos) + + @property + def untucked_default_joint_pos(self): + assert self.is_mobile_manipulation + return self._convert_yaml_list_to_tensor(self._definition.mobile_manipulation.untucked_default_joint_pos) + + def tuck(self): + """ + Immediately set this robot's configuration to be in tucked mode + """ + assert self.is_mobile_manipulation + pos = self.tucked_default_joint_pos + if self.is_holonomic_base: + pos[self.base_idx] = self.get_joint_positions()[self.base_idx] + self.set_joint_positions(pos) + + def untuck(self): + """ + Immediately set this robot's configuration to be in untucked mode + """ + assert self.is_mobile_manipulation + pos = self.untucked_default_joint_pos + if self.is_holonomic_base: + pos[self.base_idx] = self.get_joint_positions()[self.base_idx] + self.set_joint_positions(pos) + + @cached_property + def trunk_links(self): + assert self.is_articulated_trunk + return [self.links[name] for name in self.trunk_link_names] + + @cached_property + def trunk_link_names(self): + assert self.is_articulated_trunk + if self._definition.articulated_trunk: + return self._definition.articulated_trunk.trunk_link_names + return [] + + @cached_property + def trunk_joint_names(self): + assert self.is_articulated_trunk + if self._definition.articulated_trunk: + return self._definition.articulated_trunk.trunk_joint_names + return [] + + @cached_property + def trunk_control_idx(self): + """ + Returns: + n-array: Indices in low-level control vector corresponding to trunk joints. + """ + assert self.is_articulated_trunk + return th.tensor([list(self.joints.keys()).index(name) for name in self.trunk_joint_names]) + + @property + def trunk_action_idx(self): + assert self.is_articulated_trunk + c_order_idx = self.controller_order.index("trunk") + action_start_idx = sum( + ControllerView.get_command_dim(self._controllers[self.controller_order[i]][0]) for i in range(c_order_idx) + ) + trunk_group_key = self._controllers["trunk"][0] + return th.arange(action_start_idx, action_start_idx + ControllerView.get_command_dim(trunk_group_key)) + + @property + def _default_trunk_ik_controller_config(self): + """ + Returns: + dict: Default controller config for an Inverse kinematics controller to control this robot's trunk + """ + assert self.is_articulated_trunk + return { + "name": "InverseKinematicsController", + "control_freq": self._control_freq, + "reset_joint_pos": self.reset_joint_pos, + "control_limits": self.control_limits, + "dof_idx": self.trunk_control_idx, + "command_output_limits": ( + th.tensor([-0.2, -0.2, -0.2, -0.5, -0.5, -0.5]), + th.tensor([0.2, 0.2, 0.2, 0.5, 0.5, 0.5]), + ), + "mode": "pose_delta_ori", + "smoothing_filter_size": 2, + "workspace_pose_limiter": None, + } + + @property + def _default_trunk_osc_controller_config(self): + """ + Returns: + dict: Default controller config for an Operational Space controller to control this robot's trunk + """ + assert self.is_articulated_trunk + return { + "name": "OperationalSpaceController", + "control_freq": self._control_freq, + "reset_joint_pos": self.reset_joint_pos, + "control_limits": self.control_limits, + "dof_idx": self.trunk_control_idx, + "command_output_limits": ( + th.tensor([-0.2, -0.2, -0.2, -0.5, -0.5, -0.5]), + th.tensor([0.2, 0.2, 0.2, 0.5, 0.5, 0.5]), + ), + "mode": "pose_delta_ori", + "workspace_pose_limiter": None, + } + + @property + def _default_trunk_joint_controller_config(self): + """ + Returns: + dict: Default base joint controller config to control this robot's base. Uses position + control by default. + """ + assert self.is_articulated_trunk + return { + "name": "JointController", + "control_freq": self._control_freq, + "motor_type": "position", + "control_limits": self.control_limits, + "dof_idx": self.trunk_control_idx, + "command_output_limits": None, + "use_delta_commands": True, + } + + @property + def _default_trunk_null_joint_controller_config(self): + """ + Returns: + dict: Default null joint controller config to control this robot's base i.e. dummy controller + """ + assert self.is_articulated_trunk + return { + "name": "NullJointController", + "control_freq": self._control_freq, + "motor_type": "position", + "control_limits": self.control_limits, + "dof_idx": self.trunk_control_idx, + "default_goal": self.reset_joint_pos[self.trunk_control_idx], + "use_impedances": False, + } + + @property + def default_arm_poses(self): + assert self.has_multiple_arm_poses + dic = dict() + if self._definition.mobile_manipulation and self._definition.mobile_manipulation.default_arm_poses: + for key, value in self._definition.mobile_manipulation.default_arm_poses.items(): + dic[key] = self._convert_yaml_list_to_tensor(value) + return dic + + def _create_discrete_action_space(self): + if not self.is_two_wheel: + raise ValueError(f"{self.model} does not support discrete actions!") + + # Set action list based on controller (joint or DD) used + + # We set straight velocity to be 50% of max velocity for the wheels + max_wheel_joint_vels = self.control_limits["velocity"][1][self.base_control_idx] + assert len(max_wheel_joint_vels) == 2, "TwoWheelRobot must only have two base (wheel) joints!" + assert max_wheel_joint_vels[0] == max_wheel_joint_vels[1], "Both wheels must have the same max speed!" + wheel_straight_vel = 0.5 * max_wheel_joint_vels[0] + wheel_rotate_vel = 0.5 + if self._controller_config["base"]["name"] == "JointController": + action_list = [ + [wheel_straight_vel, wheel_straight_vel], + [-wheel_straight_vel, -wheel_straight_vel], + [wheel_rotate_vel, -wheel_rotate_vel], + [-wheel_rotate_vel, wheel_rotate_vel], + [0, 0], + ] + else: + # DifferentialDriveController + lin_vel = wheel_straight_vel * self.wheel_radius + ang_vel = wheel_rotate_vel * self.wheel_radius * 2.0 / self.wheel_axle_length + action_list = [ + [lin_vel, 0], + [-lin_vel, 0], + [0, ang_vel], + [0, -ang_vel], + [0, 0], + ] + + self.action_list = action_list + + # Return this action space + return gym.spaces.Discrete(n=len(self.action_list)) + + @property + def _default_base_differential_drive_controller_config(self): + """ + Returns: + dict: Default differential drive controller config to + control this robot's base. + """ + assert self.is_two_wheel + return { + "name": "DifferentialDriveController", + "control_freq": self._control_freq, + "wheel_radius": self.wheel_radius, + "wheel_axle_length": self.wheel_axle_length, + "control_limits": self.control_limits, + "dof_idx": self.base_control_idx, + } + + @property + def wheel_radius(self): + """ + Returns: + float: radius of each wheel at the base, in metric units + """ + assert self.is_two_wheel + return self._definition.two_wheel.wheel_radius + + @property + def wheel_axle_length(self): + """ + Returns: + float: perpendicular distance between the robot's two wheels, in metric units + """ + assert self.is_two_wheel + return self._definition.two_wheel.wheel_axle_length + + @property + def _default_camera_joint_controller_config(self): + """ + Returns: + dict: Default camera joint controller config to control this robot's camera + """ + assert self.is_active_camera + return { + "name": "JointController", + "control_freq": self._control_freq, + "control_limits": self.control_limits, + "dof_idx": self.camera_control_idx, + "command_output_limits": None, + "motor_type": "position", + "use_delta_commands": True, + "use_impedances": False, + } + + @property + def _default_camera_null_joint_controller_config(self): + """ + Returns: + dict: Default null joint controller config to control this robot's camera i.e. dummy controller + """ + assert self.is_active_camera + return { + "name": "NullJointController", + "control_freq": self._control_freq, + "motor_type": "position", + "control_limits": self.control_limits, + "dof_idx": self.camera_control_idx, + "default_goal": self.reset_joint_pos[self.camera_control_idx], + "use_impedances": False, + } + + @cached_property + def camera_joint_names(self): + """ + Returns: + list: Array of joint names corresponding to this robot's camera joints. + + Note: the ordering within the list is assumed to be intentional, and is + directly used to define the set of corresponding control idxs. + """ + assert self.is_active_camera + if self._definition.active_camera: + return self._definition.active_camera.camera_joint_names + return [] + + @cached_property + def camera_control_idx(self): + """ + Returns: + n-array: Indices in low-level control vector corresponding to camera joints. + """ + assert self.is_active_camera + return th.tensor([list(self.joints.keys()).index(name) for name in self.camera_joint_names]) + + @property + def disabled_collision_link_names(self): + return self._definition.disabled_collision_link_names or [] + + @property + def disabled_collision_pairs(self): + if self.has_end_effector_variants: + eef_def = self._get_end_effector_definition() + if eef_def and eef_def.disabled_collision_pairs: + return eef_def.disabled_collision_pairs + return self._definition.disabled_collision_pairs or [] + + @cached_property + def manipulation_link_names(self): + return self._definition.manipulation.manipulation_link_names or [] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scene_graphs/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scene_graphs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scene_graphs/graph_builder.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scene_graphs/graph_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..b78be325014acf4a801239a9c4a11277fc554631 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scene_graphs/graph_builder.py @@ -0,0 +1,326 @@ +import itertools + +import networkx as nx +import numpy as np +import torch as th +from PIL import Image + +from omnigibson import object_states +from omnigibson.object_states.factory import get_state_name +from omnigibson.object_states.object_state_base import AbsoluteObjectState, BooleanStateMixin, RelativeObjectState +from omnigibson.robots import Robot +from omnigibson.sensors import VisionSensor +from omnigibson.utils import transform_utils as T +from omnigibson.utils.numpy_utils import pil_to_tensor + + +def _formatted_aabb(obj): + return T.pose2mat((obj.aabb_center, th.tensor([0, 0, 0, 1], dtype=th.float32))), obj.aabb_extent + + +class SceneGraphBuilder(object): + def __init__( + self, + robot_names=None, + egocentric=False, + full_obs=False, + only_true=True, + merge_parallel_edges=False, + exclude_states=( + object_states.Touching, + object_states.NextTo, + ), + ): + """ + A utility that builds a scene graph with objects as nodes and relative states as edges, + alongside additional metadata. + + Args: + robot_names (list of str): Names of the robots whose POV the scene graph will be from. If None, we assert that there + is exactly one robot in the scene and use that robot. + egocentric (bool): Whether the objects should have poses in the world frame or robot frame. + full_obs (bool): Whether all objects should be updated or only those in FOV of the robot. + only_true (bool): Whether edges should be created only for relative states that have a value True, or for all + relative states (with the appropriate value attached as an attribute). + merge_parallel_edges (bool): Whether parallel edges (e.g. different states of the same pair of objects) should + exist (making the graph a MultiDiGraph) or should be merged into a single edge instead. + exclude_states (Iterable): Object state classes that should be ignored when building the graph. + """ + self._G = None + self._robots = None + if robot_names is not None and len(robot_names) > 1: + assert not egocentric, "Cannot have multiple robots in egocentric mode." + self._robot_names = robot_names + self._egocentric = egocentric + self._full_obs = full_obs + self._only_true = only_true + self._merge_parallel_edges = merge_parallel_edges + self._last_desired_frame_to_world = None + self._exclude_states = set(exclude_states) + + def get_scene_graph(self): + return self._G.copy() + + def _get_desired_frame(self): + desired_frame_to_world = th.eye(4) + world_to_desired_frame = th.eye(4) + if self._egocentric: + desired_frame_to_world = self._get_robot_to_world_transform(self._robots[0]) + world_to_desired_frame = T.pose_inv(desired_frame_to_world) + + return desired_frame_to_world, world_to_desired_frame + + def _get_robot_to_world_transform(self, robot): + robot_to_world = robot.get_position_orientation() + + # Get rid of any rotation outside xy plane + z_angle = T.z_angle_from_quat(robot_to_world[1]) + robot_to_world = T.pose2mat((robot_to_world[0], T.euler2quat(th.tensor([0, 0, z_angle], dtype=th.float32)))) + + return robot_to_world + + def _get_boolean_unary_states(self, obj): + states = {} + for state_type, state_inst in obj.states.items(): + if not issubclass(state_type, BooleanStateMixin) or not issubclass(state_type, AbsoluteObjectState): + continue + + if state_type in self._exclude_states: + continue + + value = state_inst.get_value() + if self._only_true and not value: + continue + + states[get_state_name(state_type)] = value + + return states + + def _get_boolean_binary_states(self, objs): + states = [] + for obj1 in objs: + for obj2 in objs: + if obj1 == obj2: + continue + + for state_type, state_inst in obj1.states.items(): + if not issubclass(state_type, BooleanStateMixin) or not issubclass(state_type, RelativeObjectState): + continue + + if state_type in self._exclude_states: + continue + + try: + value = state_inst.get_value(obj2) + if self._only_true and not value: + continue + + states.append((obj1, obj2, get_state_name(state_type), {"value": value})) + except: + pass + + return states + + def start(self, scene): + assert self._G is None, "Cannot start graph builder multiple times." + + if self._robot_names is None: + assert ( + len(scene.robots) == 1 + ), "Cannot build scene graph without specifying robot name if there are multiple robots." + self._robots = [scene.robots[0]] + else: + self._robots = [scene.object_registry("name", name) for name in self._robot_names] + assert len(self._robots) > 0, f"Robots with names {self._robot_names} not found in scene." + self._G = nx.DiGraph() if self._merge_parallel_edges else nx.MultiDiGraph() + + desired_frame_to_world, world_to_desired_frame = self._get_desired_frame() + + for robot in self._robots: + robot_pose = world_to_desired_frame @ self._get_robot_to_world_transform(robot) + robot_bbox_pose, robot_bbox_extent = _formatted_aabb(robot) + robot_bbox_pose = world_to_desired_frame @ robot_bbox_pose + self._G.add_node( + robot, pose=robot_pose, bbox_pose=robot_bbox_pose, bbox_extent=robot_bbox_extent, states={} + ) + + self._last_desired_frame_to_world = desired_frame_to_world + + # Let's also take the first step. + self.step(scene) + + def step(self, scene): + assert self._G is not None, "Cannot step graph builder before starting it." + + # Prepare the necessary transformations. + desired_frame_to_world, world_to_desired_frame = self._get_desired_frame() + + # Update the position of everything that's already in the scene by using our relative position to last frame. + old_desired_to_new_desired = world_to_desired_frame @ self._last_desired_frame_to_world + nodes = list(self._G.nodes) + poses = th.stack([self._G.nodes[obj]["pose"] for obj in nodes]) + bbox_poses = th.stack([self._G.nodes[obj]["bbox_pose"] for obj in nodes]) + updated_poses = old_desired_to_new_desired @ poses + updated_bbox_poses = old_desired_to_new_desired @ bbox_poses + for i, obj in enumerate(nodes): + self._G.nodes[obj]["pose"] = updated_poses[i] + self._G.nodes[obj]["bbox_pose"] = updated_bbox_poses[i] + + # Update the robots' poses. We don't want to accumulate errors because of the repeated transforms. + for robot in self._robots: + self._G.nodes[robot]["pose"] = world_to_desired_frame @ self._get_robot_to_world_transform(robot) + robot_bbox_pose, robot_bbox_extent = _formatted_aabb(robot) + robot_bbox_pose = world_to_desired_frame @ robot_bbox_pose + self._G.nodes[robot]["bbox_pose"] = robot_bbox_pose + self._G.nodes[robot]["bbox_extent"] = robot_bbox_extent + + # Go through the objects in FOV of the robot. + objs_to_add = set(scene.objects) + if not self._full_obs: + # If we're not in full observability mode, only pick the objects in FOV of robots. + for robot in self._robots: + objs_in_fov = robot.states[object_states.ObjectsInFOVOfRobot].get_value() + objs_to_add &= objs_in_fov + + # Remove all Robot objects from the set of objects to add. + base_robots = [obj for obj in objs_to_add if isinstance(obj, Robot)] + objs_to_add -= set(base_robots) + + for obj in objs_to_add: + # Add the object if not already in the graph + if obj not in self._G.nodes: + self._G.add_node(obj) + + # Get the relative position of the object & update it (reducing accumulated errors) + self._G.nodes[obj]["pose"] = world_to_desired_frame @ T.pose2mat(obj.get_position_orientation()) + + # Get the bounding box. + if hasattr(obj, "get_base_aligned_bbox"): + bbox_center, bbox_orn, bbox_extent, _ = obj.get_base_aligned_bbox(visual=True) + bbox_pose = T.pose2mat((bbox_center, bbox_orn)) + else: + bbox_pose, bbox_extent = _formatted_aabb(obj) + self._G.nodes[obj]["bbox_pose"] = world_to_desired_frame @ bbox_pose + self._G.nodes[obj]["bbox_extent"] = bbox_extent + + # Update the states of the object + self._G.nodes[obj]["states"] = self._get_boolean_unary_states(obj) + + # Update the binary states for seen objects. + self._G.remove_edges_from(list(itertools.product(objs_to_add, objs_to_add))) + edges = self._get_boolean_binary_states(objs_to_add) + if self._merge_parallel_edges: + new_edges = {} + for edge in edges: + edge_pair = (edge[0], edge[1]) + if edge_pair not in new_edges: + new_edges[edge_pair] = [] + + new_edges[edge_pair].append((edge[2], edge[3]["value"])) + + edges = [(k[0], k[1], {"states": v}) for k, v in new_edges.items()] + + self._G.add_edges_from(edges) + + # Save the robot's transform in this frame. + self._last_desired_frame_to_world = desired_frame_to_world + + +def visualize_scene_graph(scene, G, show_window=True, cartesian_positioning=False): + """ + Converts the graph into an image and shows it in a cv2 window if preferred. + Note: Currently, this function only works when we merge parallel edges, i.e. the graph is a DiGraph. + + Args: + scene (Scene): The scene object containing the scene graph. + G (Graph): The graph object to visualize. + show_window (bool): Whether a cv2 GUI window containing the visualization should be shown. + cartesian_positioning (bool): Whether nodes should be positioned based on their position in the scene (if True) + or placed using a graphviz layout (neato) that makes it easier to read edges & find clusters. + """ + + nodes = list(G.nodes) + all_robots = [robot for robot in nodes if isinstance(robot, Robot)] + + def _draw_graph(): + node_labels = {obj: obj.category for obj in nodes} + + # get all objects in fov of robots + objects_in_fov = set() + for robot in all_robots: + objects_in_fov.update(robot.states[object_states.ObjectsInFOVOfRobot].get_value()) + colors = [ + ("yellow" if obj.category == "agent" else ("green" if obj in objects_in_fov else "red")) for obj in nodes + ] + positions = ( + {obj: (-pose[1][-1], pose[0][-1]) for obj, pose in G.nodes.data("pose")} + if cartesian_positioning + else nx.nx_pydot.pydot_layout(G, prog="neato") + ) + nx.drawing.draw_networkx( + G, + pos=positions, + labels=node_labels, + nodelist=nodes, + node_color=colors, + font_size=5, + arrowsize=5, + node_size=200, + ) + + edge_labels = {} + for edge in G.edges: + state_value_pairs = [] + if len(edge) == 3: + # When we don't merge parallel edges + raise ValueError("Visualization does not support parallel edges.") + else: + # When we merge parallel edges + assert len(edge) == 2, "Invalid graph format for scene graph visualization." + for state, value in G.edges[edge]["states"]: + state_value_pairs.append(state + "=" + str(value)) + edge_labels[edge] = ", ".join(state_value_pairs) + + nx.drawing.draw_networkx_edge_labels(G, pos=positions, edge_labels=edge_labels, font_size=4) + + # Prepare pyplot figure that's sized to match the robot video. + robot = all_robots[0] # If there are multiple robots, we only include the first one + (robot_camera_sensor,) = [ + s for s in robot.sensors.values() if isinstance(s, VisionSensor) and "eyes" in s.name and "rgb" in s.modalities + ] + robot_view = (robot_camera_sensor.get_obs()[0]["rgb"][..., :3]).to(th.uint8) + imgheight, imgwidth, _ = robot_view.shape + + # check imgheight and imgwidth; if they are too small, we need to upsample the image to 640x640 + if imgheight < 640 or imgwidth < 640: + # Convert to PIL Image to upsample, then write back to tensor + robot_view = pil_to_tensor(Image.fromarray(robot_view.cpu().numpy()).resize((640, 640), Image.BILINEAR)) + imgheight, imgwidth, _ = robot_view.shape + + figheight = 4.8 + figdpi = imgheight / figheight + figwidth = imgwidth / figdpi + + # Draw the graph onto the figure. + import matplotlib.pyplot as plt + + fig = plt.figure(figsize=(figwidth, figheight), dpi=figdpi) + _draw_graph() + fig.canvas.draw() + + # Convert the canvas to image + graph_view = th.from_numpy(np.asarray(fig.canvas.renderer.buffer_rgba())[:, :, :3]) + assert graph_view.shape == robot_view.shape + plt.close(fig) + + # Combine the two images side-by-side + img = th.cat((robot_view, graph_view), dim=1) + + # # Convert to BGR for cv2-based viewing. + if show_window: + plt.imshow(img) + plt.title("SceneGraph") + plt.axis("off") + plt.show() + + return img diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ecf9a802f94d78f0e0758d8521be76b48a62616d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/__init__.py @@ -0,0 +1,12 @@ +from omnigibson.scenes.interactive_traversable_scene import InteractiveTraversableScene +from omnigibson.scenes.scene_base import REGISTERED_SCENES, Scene +from omnigibson.scenes.static_traversable_scene import StaticTraversableScene +from omnigibson.scenes.traversable_scene import TraversableScene + +__all__ = [ + "InteractiveTraversableScene", + "REGISTERED_SCENES", + "Scene", + "StaticTraversableScene", + "TraversableScene", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/interactive_traversable_scene.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/interactive_traversable_scene.py new file mode 100644 index 0000000000000000000000000000000000000000..52c3a796d3e8024d34178e4a611228e7b00832f5 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/interactive_traversable_scene.py @@ -0,0 +1,231 @@ +import os + +import omnigibson as og +from omnigibson.maps.segmentation_map import SegmentationMap +from omnigibson.scenes.traversable_scene import TraversableScene +from omnigibson.utils.asset_utils import get_scene_path, get_task_instance_path +from omnigibson.utils.constants import STRUCTURE_CATEGORIES, GROUND_CATEGORIES +from omnigibson.utils.ui_utils import create_module_logger + +# Create module logger +log = create_module_logger(module_name=__name__) + + +class InteractiveTraversableScene(TraversableScene): + """ + Create an interactive scene defined from a scene json file. + In general, this supports curated, pre-defined scene layouts with annotated objects. + This adds semantic support via a segmentation map generated for this specific scene. + """ + + def __init__( + self, + scene_model, + scene_instance=None, + scene_file=None, + dataset_name="behavior-1k-assets", + trav_map_resolution=0.1, + default_erosion_radius=0.0, + trav_map_with_objects=True, + num_waypoints=10, + waypoint_resolution=0.2, + load_object_categories=None, + not_load_object_categories=None, + load_room_types=None, + load_room_instances=None, + load_task_relevant_only=False, + seg_map_resolution=0.1, + include_robots=True, + ): + """ + Args: + scene_model (str): Scene model name, e.g.: Rs_int + scene_instance (None or str): name of json file to load (without .json); if None, + defaults to //scenes//json/.urdf + scene_file (None or str): If specified, full path of JSON file to load (with .json). + This will override scene_instance and scene_model! + dataset_name (str): Type of dataset to load the scene from, e.g.: "behavior-1k-assets" + trav_map_resolution (float): traversability map resolution + default_erosion_radius (float): default map erosion radius in meters + trav_map_with_objects (bool): whether to use objects or not when constructing graph + num_waypoints (int): number of way points returned + waypoint_resolution (float): resolution of adjacent way points + load_object_categories (None or list): if specified, only load these object categories into the scene + not_load_object_categories (None or list): if specified, do not load these object categories into the scene + load_room_types (None or list): only load objects in these room types into the scene + load_room_instances (None or list): if specified, only load objects in these room instances into the scene + load_task_relevant_only (bool): Whether only task relevant objects (and building structure) should be loaded + seg_map_resolution (float): room segmentation map resolution (m) + include_robots (bool): whether to also include the robot(s) defined in the scene + """ + + self.scene_model = scene_model + # Infer scene directory + self.scene_dir = get_scene_path(scene_model, dataset_name=dataset_name) + + # Other values that will be loaded at runtime + self.load_object_categories = None + self.not_load_object_categories = None + self.load_room_instances = None + self.load_task_relevant_only = load_task_relevant_only + + # Get scene information + if scene_file is None: + scene_file = self.get_scene_loading_info( + scene_model=scene_model, + scene_instance=scene_instance, + ) + + # Load room semantic and instance segmentation map (must occur AFTER inferring scene directory) + self._seg_map = SegmentationMap(scene_dir=self.scene_dir, map_resolution=seg_map_resolution) + + # Decide which room(s) and object categories to load + self.filter_rooms_and_object_categories( + load_object_categories, not_load_object_categories, load_room_types, load_room_instances + ) + + # Assert that the floor plane is not enabled + assert not og.sim.floor_plane, "Floor plane should not be enabled for interactive scenes!" + + # Run super init first + super().__init__( + scene_model=scene_model, + scene_file=scene_file, + trav_map_resolution=trav_map_resolution, + default_erosion_radius=default_erosion_radius, + trav_map_with_objects=trav_map_with_objects, + num_waypoints=num_waypoints, + waypoint_resolution=waypoint_resolution, + use_floor_plane=False, + include_robots=include_robots, + ) + + def get_scene_loading_info(self, scene_model, scene_instance=None): + """ + Gets scene loading info to know what single USD file to load, specified indirectly via @scene_instance if it + is specified, otherwise, will grab the "best" scene file to load. + + Args: + scene_model (str): Name of the scene to load, e.g, Rs_int, etc. + scene_instance (None or str): If specified, should be name of json file to load. (without .json), default to + behavior-1k-assets/scenes//json/.json + + Returns: + str: Absolute path to the desired scene file (.json) to load + """ + if scene_instance is None: + # Load default "best" scene from scene directory + fname = f"{scene_model}_best" + return os.path.join(self.scene_dir, "json", f"{fname}.json") + else: + # Load specific instance from task instance directory + return os.path.join(get_task_instance_path(scene_model, scene_instance)) + + def filter_rooms_and_object_categories( + self, load_object_categories, not_load_object_categories, load_room_types, load_room_instances + ): + """ + Handle partial scene loading based on object categories, room types or room instances + + Args: + load_object_categories (None or list): if specified, only load these object categories into the scene + not_load_object_categories (None or list): if specified, do not load these object categories into the scene + load_room_types (None or list): only load objects in these room types into the scene + load_room_instances (None or list): if specified, only load objects in these room instances into the scene + """ + self.load_object_categories = ( + [load_object_categories] if isinstance(load_object_categories, str) else load_object_categories + ) + + self.not_load_object_categories = ( + [not_load_object_categories] if isinstance(not_load_object_categories, str) else not_load_object_categories + ) + + if load_room_instances is not None: + if isinstance(load_room_instances, str): + load_room_instances = [load_room_instances] + load_room_instances_filtered = [] + for room_instance in load_room_instances: + if room_instance not in self._seg_map.room_ins_name_to_ins_id: + log.warning("room_instance [{}] does not exist.".format(room_instance)) + load_room_instances_filtered.append(room_instance) + self.load_room_instances = load_room_instances_filtered + elif load_room_types is not None: + if isinstance(load_room_types, str): + load_room_types = [load_room_types] + load_room_instances_filtered = [] + for room_type in load_room_types: + if room_type in self._seg_map.room_sem_name_to_ins_name: + load_room_instances_filtered.extend(self._seg_map.room_sem_name_to_ins_name[room_type]) + else: + log.warning("room_type [{}] does not exist.".format(room_type)) + self.load_room_instances = load_room_instances_filtered + else: + self.load_room_instances = None + + def _load(self): + # Load the traversability map if we have the connectivity graph + maps_path = os.path.join(self.scene_dir, "layout") + self._trav_map.load_map(maps_path) + + def _should_load_object(self, obj_info, task_metadata): + agent_ok = super()._should_load_object(obj_info, task_metadata) + + name = obj_info["args"]["name"] + category = obj_info["args"].get("category", "object") + in_rooms = obj_info["args"].get("in_rooms", []) + + if isinstance(in_rooms, str): + assert "," not in in_rooms + in_rooms = [in_rooms] if isinstance(in_rooms, str) else in_rooms + + # Do not load these object categories (can blacklist building structures as well) + not_blacklisted = self.not_load_object_categories is None or category not in self.not_load_object_categories + + # Only load these object categories (no need to white list building structures) + task_relevant_names = set(task_metadata["inst_to_name"].values()) if "inst_to_name" in task_metadata else set() + is_task_relevant = name in task_relevant_names or category in STRUCTURE_CATEGORIES + whitelisted = ( + # Either no whitelisting-only mode is on + (self.load_object_categories is None and not self.load_task_relevant_only) + or + # Or the object is in the whitelist + (self.load_object_categories is not None and category in self.load_object_categories) + or + # Or it's in the task relevant list + (self.load_task_relevant_only and is_task_relevant) + ) + + # This object is not located in one of the selected rooms, skip + valid_room = self.load_room_instances is None or len(set(self.load_room_instances) & set(in_rooms)) > 0 + + # Always load building structures for now because walls are missing room assignments + # TODO (Wensi): below is changed to include doors to allow partial scene demo replay. + # We need to think of a better way to handle this. + is_building_structure = category in (STRUCTURE_CATEGORIES - GROUND_CATEGORIES) or category in [ + "door", + "sliding_door", + ] + + # We only load this model if all the above conditions are met + return (not_blacklisted and whitelisted and valid_room and agent_ok) or is_building_structure + + @property + def seg_map(self): + """ + Returns: + SegmentationMap: Map for segmenting this scene + """ + return self._seg_map + + @classmethod + def modify_init_info_for_restoring(cls, init_info): + # Run super first + super().modify_init_info_for_restoring(init_info=init_info) + + # We also make sure we load in any robots, and also pop any filters that were stored + init_info["args"]["include_robots"] = True + init_info["args"]["load_object_categories"] = None + init_info["args"]["not_load_object_categories"] = None + init_info["args"]["load_room_types"] = None + init_info["args"]["load_room_instances"] = None diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/scene_base.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/scene_base.py new file mode 100644 index 0000000000000000000000000000000000000000..445c74a24e340894e719cc5b21892efcff2800c9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/scene_base.py @@ -0,0 +1,1410 @@ +import contextlib +import json +import os +import shutil +import tempfile +from abc import ABC +from pathlib import Path + +import torch as th +from packaging.version import InvalidVersion, Version + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.sensors.vision_sensor import VisionSensor +import omnigibson.utils.asset_utils +import omnigibson.utils.transform_utils as T +from omnigibson.macros import gm +from omnigibson.objects.usd_object import USDObject +from omnigibson.prims.xform_prim import XFormPrim +from omnigibson.robots import REGISTERED_ROBOTS +from omnigibson.systems import Cloth +from omnigibson.systems.micro_particle_system import FluidSystem +from omnigibson.systems.macro_particle_system import MacroParticleSystem +from omnigibson.systems.system_base import ( + BaseSystem, + PhysicalParticleSystem, + VisualParticleSystem, + create_system_from_metadata, + get_all_system_names, +) +from omnigibson.transition_rules import TransitionRuleAPI +from omnigibson.utils.asset_utils import get_dataset_path +from omnigibson.utils.config_utils import TorchEncoder +from omnigibson.utils.constants import ROBOT_CATEGORY, STRUCTURAL_DOOR_CATEGORIES +from omnigibson.utils.python_utils import ( + Recreatable, + Registerable, + Serializable, + classproperty, + create_object_from_init_info, + get_uuid, + recursively_convert_to_torch, +) +from omnigibson.utils.registry_utils import SerializableRegistry +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import CollisionAPI, add_asset_to_stage, create_usd_stage + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Global dicts that will contain mappings +REGISTERED_SCENES = dict() + +# Prebuilt USDs that are cached per scene file to speed things up. +PREBUILT_USDS = dict() + + +class Scene(Serializable, Registerable, Recreatable, ABC): + """ + Base class for all Scene objects. + Contains the base functionalities for an arbitrary scene with an arbitrary set of added objects + """ + + def __init__( + self, + scene_file=None, + use_floor_plane=True, + floor_plane_visible=True, + floor_plane_color=(1.0, 1.0, 1.0), + use_skybox=True, + include_robots=True, + ): + """ + Args: + scene_file (None or str or dict): If specified, full path of JSON file to load (with .json) or the + pre-loaded scene state from that json. + None results in no additional objects being loaded into the scene + use_floor_plane (bool): whether to load a flat floor plane into the simulator + floor_plane_visible (bool): whether to render the additionally added floor plane + floor_plane_color (3-array): if @floor_plane_visible is True, this determines the (R,G,B) color assigned + to the generated floor plane + use_skybox (bool): whether to load a skybox into the simulator + include_robots (bool): whether to also include the robot(s) defined in the scene + """ + # Store internal variables + self.scene_file = scene_file + self._loaded = False # Whether this scene exists in the stage or not + self._initialized = False # Whether this scene has its internal handles / info initialized or not (occurs AFTER and INDEPENDENTLY from loading!) + self._registry = None + self._scene_prim = None + self._initial_file = None + self._objects_info = None # Information associated with this scene + self._idx = None + self._use_floor_plane = use_floor_plane + self._floor_plane_visible = floor_plane_visible + self._floor_plane_color = floor_plane_color + self._use_skybox = use_skybox + self._transition_rule_api = None + self._available_systems = None + self._pose_info = None + self._updated_state_objects = None + self._include_robots = include_robots + self._task_metadata = {} + + # Call super init + super().__init__() + + # Prepare the initialization dicts + self._init_objs = {} + self._init_state = {} + self._init_systems = [] + + # If we have any scene file specified, use it to create the objects within it + if self.scene_file is not None: + # Grab objects info from the scene file + if isinstance(self.scene_file, str): + with open(self.scene_file, "r") as f: + scene_info = json.load(f) + else: + scene_info = self.scene_file + + # Verify the saved component versions are compatible with the currently-installed versions. + # We require each saved version to be <= the currently-installed version. + self._check_versions_compatible(scene_info.get("versions", {})) + + init_info = scene_info["objects_info"]["init_info"] + # TODO: Remove this backwards-compatibility once newer RC is released + self._init_state = ( + scene_info["state"]["registry"]["object_registry"] + if "registry" in scene_info["state"] + else scene_info["state"]["object_registry"] + ) + self._init_systems = ( + list(scene_info["state"]["registry"]["system_registry"].keys()) + if "registry" in scene_info["state"] + else list(scene_info["state"]["system_registry"].keys()) + ) + task_metadata = ( + scene_info["metadata"]["task"] if "metadata" in scene_info and "task" in scene_info["metadata"] else {} + ) + + # Iterate over all scene info, and instantiate object classes linked to the objects found on the stage accordingly + for obj_name, obj_info in init_info.items(): + # Check whether we should load the object or not + if not self._should_load_object(obj_info=obj_info, task_metadata=task_metadata): + continue + # Create object class instance + obj = create_object_from_init_info(obj_info) + self._init_objs[obj_name] = obj + + # Store presampled robot poses from metadata + for key, data in task_metadata.items(): + self.write_task_metadata(key=key, data=data) + + @property + def registry(self): + """ + Returns: + SerializableRegistry: Master registry containing sub-registries of objects, robots, systems, etc. + """ + return self._registry + + @property + def object_registry(self): + """ + Returns: + SerializableRegistry: Object registry containing all active standalone objects in the scene + """ + return self._registry(key="name", value="object_registry") + + @property + def system_registry(self): + """ + Returns: + SerializableRegistry: System registry containing all systems in the scene (e.g.: water, dust, etc.) + """ + return self._registry(key="name", value="system_registry") + + @property + def objects(self): + """ + Get the objects in the scene. + + Returns: + list of USDObject: Standalone object(s) that are currently in this scene + """ + return self.object_registry.objects + + @property + def updated_state_objects(self): + """ + Returns: + set of StatefulObject: set of stateful objects in the scene that have had at least a single object state + updated since the last simulator's non_physics_step() + """ + return self._updated_state_objects + + @property + def robots(self): + """ + Robots in the scene + + Returns: + list of BaseRobot: Robot(s) that are currently in this scene + """ + return list(sorted(self.object_registry("category", ROBOT_CATEGORY, []), key=lambda x: x.name)) + + @property + def systems(self): + """ + Active systems in the scene + + Returns: + list of BaseSystem: Active system(s) in this scene + """ + return self.system_registry.objects + + @property + def available_systems(self): + """ + Available systems in the scene + + Returns: + dict: Maps all system names to corresponding systems that are available to use in this scene + """ + return self._available_systems + + @property + def object_registry_unique_keys(self): + """ + Returns: + list of str: Keys with which to index into the object registry. These should be valid public attributes of + prims that we can use as unique IDs to reference prims, e.g., prim.prim_path, prim.name, etc. + """ + return ["name", "prim_path", "uuid"] + + @property + def object_registry_group_keys(self): + """ + Returns: + list of str: Keys with which to index into the object registry. These should be valid public attributes of + prims that we can use as grouping IDs to reference prims, e.g., prim.in_rooms + """ + return ["prim_type", "states", "category", "fixed_base", "in_rooms", "abilities"] + + @property + def loaded(self): + return self._loaded + + @property + def idx(self): + """Index of this scene in the simulator. Should not change.""" + assert self._idx is not None, "This scene is not loaded yet!" + return self._idx + + @property + def initialized(self): + return self._initialized + + @property + def use_floor_plane(self): + return self._use_floor_plane + + @property + def transition_rule_api(self): + return self._transition_rule_api + + def clear_updated_objects(self): + self._updated_state_objects = set() + + def prebuild(self): + """ + Prebuild the scene USD before loading it into the simulator. This is useful for caching the scene USD for faster + loading times. + + Returns: + str: Path to the prebuilt USD file + """ + # Prebuild and cache the scene USD using the objects + if isinstance(self.scene_file, str): + scene_file_path = self.scene_file + else: + # The scene file is a dict, so write it to disk directly + scene_file_str = json.dumps(self.scene_file, cls=TorchEncoder, indent=4) + scene_file_hash = get_uuid(scene_file_str, deterministic=True) + scene_file_path = os.path.join(og.tempdir, f"scene_file_{scene_file_hash}.json") + with open(scene_file_path, "w+") as f: + json.dump(self.scene_file, f, cls=TorchEncoder, indent=4) + + if scene_file_path not in PREBUILT_USDS: + # Prebuild the scene USD + log.info(f"Prebuilding scene file {scene_file_path}...") + + # Create a new stage inside the tempdir, named after this scene's file. + decrypted_fd, usd_path = tempfile.mkstemp(os.path.basename(scene_file_path) + ".usd", dir=og.tempdir) + os.close(decrypted_fd) + stage = create_usd_stage(usd_path) + + # Create the world prim and make it the default + world_prim = stage.DefinePrim("/World", "Xform") + stage.SetDefaultPrim(world_prim) + + # Iterate through all objects and add them to the stage + for obj_name, obj in self._init_objs.items(): + obj.prebuild(stage) + + stage.Save() + del stage + + PREBUILT_USDS[scene_file_path] = usd_path + + # Copy the prebuilt USD to a new path + decrypted_fd, instance_usd_path = tempfile.mkstemp(os.path.basename(scene_file_path) + ".usd", dir=og.tempdir) + os.close(decrypted_fd) + shutil.copyfile(PREBUILT_USDS[scene_file_path], instance_usd_path) + return instance_usd_path + + def _load(self): + """ + Load the scene into simulator + The elements to load may include: floor, building, objects, etc. + """ + # There's nothing to load for the base scene. Subclasses can implement this method. + # Do nothing here + pass + + def _load_systems(self): + system_dir = os.path.join(get_dataset_path("behavior-1k-assets"), "systems") + + available_systems = ( + { + system_name: create_system_from_metadata(system_name=system_name) + for system_name in get_all_system_names() + } + if os.path.exists(system_dir) + else dict() + ) + + # Manually add cloth system since it is a special system that doesn't have any corresponding directory in + # the B1K database + cloth_system = Cloth(name="cloth") + available_systems["cloth"] = cloth_system + self._available_systems = available_systems + + def _load_scene_prim_with_objects(self, last_scene_edge, initial_scene_prim_z_offset, scene_margin): + """ + Loads scene objects based on metadata information found in the current USD stage's scene info + (information stored in the world prim's CustomData) + """ + # Add the prebuilt scene USD to the stage + scene_relative_path = f"/scene_{self.idx}" + scene_absolute_path = f"/World{scene_relative_path}" + + # If there is already a prim at the absolute path, the scene has been loaded. If not, load the prebuilt scene USD now. + if self.scene_file is not None: + scene_prim_obj = og.sim.stage.GetPrimAtPath(scene_absolute_path) + if not scene_prim_obj: + scene_prim_obj = add_asset_to_stage(asset_path=self.prebuild(), prim_path=scene_absolute_path) + + # Store world prim and load the scene into the simulator + self._scene_prim = XFormPrim( + relative_prim_path=scene_relative_path, + name=f"scene_{self.idx}", + ) + self._scene_prim.load(None) + if self.scene_file is not None: + assert self._scene_prim.prim_path == scene_prim_obj.GetPath().pathString, "Scene prim path mismatch!" + + # Go through and load all systems. + self._load_systems() + + # Create desired systems + for system_name in self._init_systems: + system = self.get_system(system_name, force_init=False) + if gm.USE_GPU_DYNAMICS or isinstance(system, MacroParticleSystem): + self.get_system(system_name, force_init=True) + else: + log.warning(f"System {system_name} is not supported without GPU dynamics! Skipping...") + + # Position the scene prim initially at a z offset to avoid collision + initial_scene_prim_pos = th.tensor([0.0, 0.0, initial_scene_prim_z_offset if self.idx != 0 else 0.0]) + self._scene_prim.set_position_orientation(position=initial_scene_prim_pos) + + # Now load the objects with their own logic + with og.sim.adding_objects(objs=self._init_objs.values()): + for obj_name, obj in self._init_objs.items(): + # Import into the simulator + self.add_object(obj, _batched_call=True) + # Set the init pose accordingly. The init pose is authored in the scene frame, and the + # scene prim currently sits at the temporary z offset above, so include that offset in + # this world-frame write. Otherwise the offset gets baked into the object's USD local + # transform (local = scene_z - (-offset) = scene_z + |offset|), and once the scene prim + # moves to its final tile position every object inherits a +|offset| world-z error. + # Later scene-relative load_state writes hide this for most objects, but any object + # that never receives one (e.g. scene furniture under the eval's partial-scene-load + # path, such as the stove burner in cook_hot_dogs) physically stays ~100 m above its + # scene in every env other than env 0. + obj.set_position_orientation( + position=th.as_tensor(self._init_state[obj_name]["root_link"]["pos"]) + initial_scene_prim_pos, + orientation=self._init_state[obj_name]["root_link"]["ori"], + ) + + # Position the scene prim based on the last scene's right edge + # NOTE: for empty scenes (no objects), the computed AABB is degenerate, so we manually use a zero extent + if self.idx != 0: + aabb_min, aabb_max = lazy.omni.usd.get_context().compute_path_world_bounding_box(scene_absolute_path) + left_edge_to_center = 0.0 if len(self._init_objs) == 0 else -aabb_min[0] + scene_position = th.tensor([last_scene_edge + scene_margin + left_edge_to_center, 0, 0]) + identity_quat = th.tensor([0.0, 0.0, 0.0, 1.0]) + self._scene_prim.set_position_orientation(position=scene_position, orientation=identity_quat) + if len(self._init_objs) == 0: + new_scene_edge = last_scene_edge + scene_margin + else: + new_scene_edge = last_scene_edge + scene_margin + (aabb_max[0] - aabb_min[0]) + else: + scene_position = th.zeros(3) + aabb_min, aabb_max = lazy.omni.usd.get_context().compute_path_world_bounding_box(scene_absolute_path) + new_scene_edge = 0.0 if len(self._init_objs) == 0 else aabb_max[0] + + return new_scene_edge, scene_position + + def _load_metadata_from_scene_file(self): + """ + Loads metadata from self.scene_file and stores it within the world prim's CustomData + """ + if isinstance(self.scene_file, str): + with open(self.scene_file, "r") as f: + scene_info = json.load(f) + else: + scene_info = self.scene_file + + # Write the metadata + for key, data in scene_info.get("metadata", dict()).items(): + self.write_task_metadata(key=key, data=data) + + def _should_load_object(self, obj_info, task_metadata): + """ + Helper function to check whether we should load an object given its init_info. Useful for potentially filtering + objects based on, e.g., their category, size, etc. + + By default, this checks whether robot should be loaded. + Subclasses should call super and implement additional logic. + + Args: + obj_info (dict): Dictionary of object kwargs that will be used to load the object + + Returns: + bool: Whether this object should be loaded or not + """ + # Check whether this is an agent and we allow agents + return self._include_robots or obj_info["class_name"] not in REGISTERED_ROBOTS + + def load(self, idx, **kwargs): + """ + Load the scene into simulator + The elements to load may include: floor, building, objects, etc. + Do not override this function. Override _load instead. + """ + # Make sure simulator is stopped + assert og.sim.is_stopped(), "Simulator should be stopped when loading this scene!" + + # Check if scene is already loaded + if self._loaded: + raise ValueError("This scene is already loaded.") + + self._idx = idx + self.clear_updated_objects() + + # Create the registry for tracking all objects in the scene + self._registry = self._create_registry() + + # Load floor plane and skybox + if self.use_floor_plane: + og.sim.add_ground_plane( + floor_plane_visible=self._floor_plane_visible, floor_plane_color=self._floor_plane_color + ) + if self._use_skybox: + og.sim.add_skybox() + + # Go through whatever else loading the scene needs to do. + self._load() + + # We're now loaded + self._loaded = True + + # If we have any scene file specified, use it to load the objects within it and also update the initial state + # and metadata + new_scene_edge, scene_position = self._load_scene_prim_with_objects(**kwargs) + if self.scene_file is not None: + self._load_metadata_from_scene_file() + + # Cache this scene's pose using the position we just set, rather than reading + # it back from the prim, since the physics engine may not have processed the + # update yet (sim is stopped during load). + identity_quat = th.tensor([0.0, 0.0, 0.0, 1.0]) + pos_ori = (scene_position, identity_quat) + pose = T.pose2mat(pos_ori) + self._pose_info = { + "pos_ori": pos_ori, + "pose": pose, + "pose_inv": th.linalg.inv_ex(pose).inverse, + } + + if gm.ENABLE_TRANSITION_RULES: + assert gm.ENABLE_OBJECT_STATES, "Transition rules require object states to be enabled!" + self._transition_rule_api = TransitionRuleAPI(scene=self) + + # Always stop the sim if we started it internally + if not og.sim.is_stopped(): + og.sim.stop() + + return new_scene_edge + + def clear(self): + """ + Clears any internal state before the scene is destroyed + """ + # Clears systems so they can be re-initialized. + for system in self.active_systems.values(): + self.clear_system(system_name=system.name) + + # Remove any vision sensors attached to this scene + # This needs to happen BEFORE the scene prim is removed or else the path to the sensor will become stale + # which will cause segfault during og.clear() + scene_prim_path = self.prim_path + scene_prim_prefix = f"{scene_prim_path}/" + for sensor in tuple(VisionSensor.SENSORS.values()): + if sensor.prim_path == scene_prim_path or sensor.prim_path.startswith(scene_prim_prefix): + sensor.remove() + + # Remove all of the scene's objects. + og.sim.batch_remove_objects(list(self.objects)) + + # Remove the scene prim. + self._scene_prim.remove() + + if gm.ENABLE_TRANSITION_RULES: + # Clear the transition rule API + self._transition_rule_api.clear() + + def _initialize(self): + """ + Initializes state of this scene and sets up any references necessary post-loading. Should be implemented by + sub-class for extended utility + """ + pass + + def initialize(self): + """ + Initializes state of this scene and sets up any references necessary post-loading. Subclasses should + implement / extend the _initialize() method. + """ + assert not self._initialized, "Scene can only be initialized once! (It is already initialized)" + assert og.sim.is_playing(), "Simulator must be playing in order to initialize the scene!" + self._initialize() + + # Grab relevant objects info + self.update_objects_info() + self.wake_scene_objects() + + self._initialized = True + + # Store initial state, which may be loaded from a scene file if specified + if self.scene_file is not None: + if isinstance(self.scene_file, str): + with open(self.scene_file, "r") as f: + scene_info = json.load(f) + else: + scene_info = self.scene_file + init_state = scene_info["state"] + init_state = recursively_convert_to_torch(init_state) + # In VectorEnvironment, the scene pose loaded from the file should be updated + init_state["pos"], init_state["ori"] = self._pose_info["pos_ori"] + for obj_name, obj_info in init_state["registry"]["object_registry"].items(): + # Convert the pose to be in the scene's coordinate frame + pos, ori = obj_info["root_link"]["pos"], obj_info["root_link"]["ori"] + # apply scene pose to all objects in this scene + obj_info["root_link"]["pos"], obj_info["root_link"]["ori"] = T.pose_transform( + *T.mat2pose(self.pose), pos, ori + ) + # NOTE: system registry states need no such conversion -- particle systems dump/load + # their particle poses in the SCENE frame (see BaseSystem._dump_state and + # PhysxParticleInstancer._dump_state), so load_state below places each scene's particles + # at that scene's own world offset. + self.load_state(init_state, serialized=False) + self._initial_file = self.save(as_dict=True) + + def _create_registry(self): + """ + Creates the internal registry used for tracking all objects + + Returns: + SerializableRegistry: registry for tracking all objects + """ + + # Create meta registry and populate with internal registries for robots, objects, and systems + registry = SerializableRegistry( + name=f"scene_registry_{self.idx}", + class_types=SerializableRegistry, + ) + + # Add registry for systems -- this is already created externally, so we just update it and pull it directly + registry.add( + obj=SerializableRegistry( + name="system_registry", + class_types=BaseSystem, + default_key="name", + hash_key="uuid", + unique_keys=["name", "prim_path", "uuid"], + ) + ) + + # Add registry for objects + registry.add( + obj=SerializableRegistry( + name="object_registry", + class_types=USDObject, + default_key="name", + hash_key="uuid", + unique_keys=self.object_registry_unique_keys, + group_keys=self.object_registry_group_keys, + ) + ) + + return registry + + def wake_scene_objects(self): + """ + Force wakeup sleeping objects + """ + for obj in self.objects: + obj.wake() + + def get_objects_with_state(self, state): + """ + Get the objects with a given state in the scene. + + Args: + state (BaseObjectState): state of the objects to get + + Returns: + set: all objects with the given state + """ + return self.object_registry("states", state, set()) + + def get_objects_with_state_recursive(self, state): + """ + Get the objects with a given state and its subclasses in the scene. + + Args: + state (BaseObjectState): state of the objects to get + + Returns: + set: all objects with the given state and its subclasses + """ + objs = set() + states = {state} + while states: + next_states = set() + for state in states: + objs |= self.object_registry("states", state, set()) + next_states |= set(state.__subclasses__()) + states = next_states + return objs + + def _add_object(self, obj): + """ + Add an object to the scene's internal object tracking mechanisms. + + Note that if the scene is not loaded, it should load this added object alongside its other objects when + scene.load() is called. The object should also be accessible through scene.objects. + + Args: + obj (USDObject): the object to load into the simulator + """ + pass + + def add_object(self, obj, register=True, _batched_call=False): + """ + Add an object to the scene. The scene should already be loaded. + + Args: + obj (USDObject): the object to load + register (bool): Whether to register @obj internally in the scene object registry or not, as well as run + additional scene-specific logic in addition to the obj being loaded + _batched_call (bool): Whether this is from a batched call or not. If True, will avoid running + a context externally. In general, this should NOT be explicitly set by the user + """ + cxt = contextlib.nullcontext() if _batched_call else og.sim.adding_objects(objs=[obj]) + with cxt: + # Make sure all objects in this scene are uniquely named + assert ( + obj.name not in self.object_registry.object_names + ), f"Object with name {obj.name} already exists in scene!" + + # Load the object. + obj.load(self) + + if register: + # If this object is fixed and is NOT an agent, disable collisions between the fixed links of the fixed objects + # This is to account for cases such as Tiago, which has a fixed base which is needed for its global base joints + # We do this by adding the object to our tracked collision groups + if obj.fixed_base and obj.category != ROBOT_CATEGORY and not obj.visual_only: + obj_fixed_links = obj.get_fixed_link_names_in_subtree() + for link_name, link in obj.links.items(): + if link_name in obj_fixed_links: + CollisionAPI.add_to_collision_group( + col_group=("fixed_base_fixed_links"), + prim_path=link.prim_path, + ) + elif obj.category in STRUCTURAL_DOOR_CATEGORIES: + CollisionAPI.add_to_collision_group( + col_group=("structural_doors"), + prim_path=link.prim_path, + ) + + # Add this object to our registry based on its type, if we want to register it + self.object_registry.add(obj) + + # Run any additional scene-specific logic with the created object + self._add_object(obj) + + def remove_object(self, obj, _batched_call=False): + """ + Method to remove an object from the simulator + + Args: + obj (USDObject): Object to remove + _batched_call (bool): Whether this is from a batched call or not. If True, will avoid running + a context externally. In general, this should NOT be explicitly set by the user + """ + cxt = contextlib.nullcontext() if _batched_call else og.sim.removing_objects(objs=[obj]) + with cxt: + # Remove from the appropriate registry if registered. + # Sometimes we don't register objects to the object registry during add_object (e.g. particle templates) + if self.object_registry.object_is_registered(obj): + self.object_registry.remove(obj) + + # Remove from omni stage + obj.remove() + + def reset(self, hard=True): + """ + Resets this scene + + Args: + hard (bool): If set, will force the set of active objects currently in the sim to match + the specified objects stored in self._initial_file. Otherwise, will only load the kinematic and semantic + state for any objects that are currently in the sim, ignoring any additional / missing objects + """ + # Make sure the simulator is playing + assert og.sim.is_playing(), "Simulator must be playing in order to reset the scene!" + + # Reset the states of all objects (including robots), including (non-)kinematic states and internal variables. + # This also forces the scene to align with the correct set of initial objects / systems, in case any + # were removed / added during runtime + assert self._initial_file is not None + if hard: + self.restore(scene_file=self._initial_file) + else: + self.load_state(self._initial_file["state"], serialized=False) + + og.sim.step_physics() + + def save(self, json_path=None, as_dict=False): + """ + Saves the current scene environment to @json_path. + + Args: + json_path (None or str): Full path of JSON file to save (should end with .json), which will + contain information to recreate the current scene, if specified. If None, will return the raw JSON + string instead. + as_dict (bool): If set and @json_path is None, will return the saved environment as a dictionary instead + of encoded json strings + + Returns: + None or str or dict: If @json_path is None, returns dumped json string (or dict if @as_dict is set). + Else, None + """ + # Make sure the sim is not stopped, since we need to grab joint states + assert not og.sim.is_stopped(), "Simulator cannot be stopped when saving scene!" + + if json_path is not None: + if not json_path.endswith(".json"): + log.error(f"You have to define the full json_path to save the scene to. Got: {json_path}") + return + + # Update scene info + self.update_objects_info() + + # Dump saved current state and also scene init info + scene_info = { + "versions": self._get_current_versions(), + "metadata": {"task": self._task_metadata}, + "state": self.dump_state(serialized=False), + "init_info": self.get_init_info(), + "objects_info": self.get_objects_info(), + } + + # Write this to the json file + if json_path is None: + return scene_info if as_dict else json.dumps(scene_info, cls=TorchEncoder, indent=4) + + else: + Path(os.path.dirname(json_path)).mkdir(parents=True, exist_ok=True) + with open(json_path, "w+") as f: + json.dump(scene_info, f, cls=TorchEncoder, indent=4) + + log.info(f"Scene {self.idx} saved to {json_path}.") + + @staticmethod + def _get_current_versions(): + """ + Returns: + dict: Dictionary of currently-installed component versions, in the same shape that is stored + under the "versions" key of a saved scene file. + """ + return { + "omnigibson": { + "version": omnigibson.utils.asset_utils.get_omnigibson_version(), + "git_hash": omnigibson.utils.asset_utils.get_omnigibson_git_hash(), + }, + "bddl": { + "version": omnigibson.utils.asset_utils.get_bddl_version(), + }, + "behavior-1k-assets": { + "version": omnigibson.utils.asset_utils.get_behavior_1k_assets_version(), + }, + "omnigibson-robot-assets": { + "version": omnigibson.utils.asset_utils.get_omnigibson_robot_asset_version(), + }, + } + + @staticmethod + def _check_versions_compatible(saved_versions): + """ + Validates that each component version saved in @saved_versions is less than or equal to the + currently-installed version. This prevents loading a scene that was saved against newer + components than what is currently available. + + Args: + saved_versions (dict): The "versions" sub-dictionary from a saved scene file. + + Raises: + ValueError: If any saved version is strictly newer than the currently-installed version. + """ + if not saved_versions: + log.warning("Scene file does not contain version information; skipping version compatibility check.") + return + + current_versions = Scene._get_current_versions() + for component, current_info in current_versions.items(): + saved_info = saved_versions.get(component) + if not saved_info: + continue + saved_version_str = saved_info.get("version") + current_version_str = current_info.get("version") + if saved_version_str is None or current_version_str is None: + continue + try: + saved_version = Version(saved_version_str) + current_version = Version(current_version_str) + except InvalidVersion: + log.warning( + f"Could not parse version for {component} (saved={saved_version_str}, " + f"current={current_version_str}); skipping comparison for this component." + ) + continue + if saved_version > current_version: + raise ValueError( + f"Scene file was saved with {component} version {saved_version_str}, which is newer than " + f"the currently-installed version {current_version_str}. Please update {component} before " + f"loading this scene." + ) + + def restore(self, scene_file, update_initial_file=False): + """ + Restores this scene given @scene_file + + This does NOT move the scene prim to the pose recorded in @scene_file: that + pose identifies the frame the file was captured in, and object poses are + re-based from it into this scene's current frame. See ``_dump_state``. + + Args: + scene_file (str or dict): Full path of either JSON file or loaded scene file to load, which contains + information to recreate a scene. Should be the output of self.save() + update_initial_file (bool): Whether to update this scene's initial file or not + """ + # Make sure the sim is not stopped, since we need to grab joint states + assert not og.sim.is_stopped(), "Simulator cannot be stopped when restoring scene!" + + if isinstance(scene_file, str): + if not scene_file.endswith(".json"): + log.error(f"You have to define the full json_path to load from. Got: {scene_file}") + return + + # Load the info from the json + with open(scene_file, "r") as f: + scene_info = json.load(f) + else: + scene_info = scene_file + + # Verify the saved component versions are compatible with the currently-installed versions. + # We require each saved version to be <= the currently-installed version. + self._check_versions_compatible(scene_info.get("versions", {})) + + init_info = scene_info["init_info"] + # The saved state are lists, convert them to torch tensors + state = recursively_convert_to_torch(scene_info["state"]) + + # Recover metadata + if "metadata" in scene_info: + metadata = scene_info["metadata"] + task_metadata = metadata["task"] if "task" in metadata else metadata + for key, data in task_metadata.items(): + self.write_task_metadata(key=key, data=data) + + # Make sure the class type is the same + if self.__class__.__name__ != init_info["class_name"]: + log.error( + f"Got mismatch in scene type: current is type {self.__class__.__name__}, trying to load type {init_info['class_name']}" + ) + + # Work out every topology change before touching either systems or objects. System + # clear/init can remove/add particle template objects, so it must participate in the + # same stop -> mutate topology -> play lifecycle as ordinary object changes. + current_systems = set(self.active_systems.keys()) + load_systems = set(scene_info["state"]["registry"]["system_registry"].keys()) + systems_to_remove = current_systems - load_systems + systems_to_add = load_systems - current_systems + load_obj_names = set(scene_info["objects_info"]["init_info"].keys()) + current_obj_names = set(self.object_registry.get_dict("name").keys()) + object_topology_changed = current_obj_names != load_obj_names + + restart_sim = bool(systems_to_remove or systems_to_add or object_topology_changed) and og.sim.is_playing() + + if restart_sim: + og.sim.stop() + + # Synchronize systems -- we need to check for pruning currently-existing systems, + # as well as creating any non-existing systems. This is deliberately after stop(): + # MacroParticleSystem.clear() removes its particle template object, and doing that + # while playing enters Simulator.removing_objects(), which first dumps the entire + # simulation through tensor views that a prior transition may already have invalidated. + for name in systems_to_remove: + self.clear_system(name) + for name in systems_to_add: + self.get_system(name, force_init=True) + + # System init / clear can itself add or remove particle-template objects. Recompute the + # object delta afterwards so those objects are not removed twice or recreated manually. + current_obj_names = set(self.object_registry.get_dict("name").keys()) + objs_to_remove = current_obj_names - load_obj_names + objs_to_add = load_obj_names - current_obj_names + + # Delete any extra objects that currently exist in the scene stage + objects_to_remove = [self.object_registry("name", obj_to_remove) for obj_to_remove in objs_to_remove] + og.sim.batch_remove_objects(objects_to_remove) + + # Add any extra objects that do not currently exist in the scene stage + objects_to_add = [ + create_object_from_init_info(scene_info["objects_info"]["init_info"][obj_to_add]) + for obj_to_add in objs_to_add + ] + # Add new physics prims while stopped, then reuse play() to rebuild handles before loading poses. + + og.sim.batch_add_objects(objects_to_add, scenes=[self] * len(objects_to_add)) + + if restart_sim: + og.sim.play() + + # Load state + self.load_state(state, serialized=False) + + if update_initial_file: + self.update_initial_file(scene_file=scene_file) + + def get_task_metadata(self, key): + return self._task_metadata.get(key, None) + + def write_task_metadata(self, key, data): + self._task_metadata[key] = data + + def get_position_orientation(self): + """ + Get the position and orientation of the scene + + Returns: + 2-tuple: + - th.Tensor: (3,) position of the scene + - th.Tensor: (4,) orientation of the scene + """ + return self._pose_info["pos_ori"] + + def set_position_orientation(self, position=None, orientation=None): + """ + Set the position and orientation of the scene + + Args: + position (th.Tensor): (3,) position of the scene + orientation (th.Tensor): (4,) orientation of the scene + """ + self._scene_prim.set_position_orientation(position=position, orientation=orientation) + + # Update the cached pose and inverse pose + pos_ori = self._scene_prim.get_position_orientation() + pose = T.pose2mat(pos_ori) + self._pose_info = { + "pos_ori": pos_ori, + "pose": T.pose2mat(pos_ori), + "pose_inv": th.linalg.inv_ex(pose).inverse, + } + + @property + def prim_path(self): + """ + Returns: + str: the prim path of the scene + """ + assert self._scene_prim is not None, "Scene prim is not loaded yet!" + return self._scene_prim.prim_path + + @property + def n_floors(self): + """ + Returns: + int: Number of floors in this scene + """ + # Default is a single floor + return 1 + + @property + def n_objects(self): + """ + Returns: + int: number of objects + """ + return len(self.objects) + + @property + def fixed_objects(self): + """ + Returns: + dict: Keyword-mapped objects that are fixed in the scene, IGNORING any robots. + Maps object name to their object class instances (DatasetObject) + """ + return { + obj.name: obj + for obj in self.object_registry("fixed_base", True, default_val=[]) + if obj.category != ROBOT_CATEGORY + } + + @property + def pose(self): + """ + Returns: + th.Tensor: (4,4) homogeneous transformation matrix representing this scene's global pose + """ + return self._pose_info["pose"] + + @property + def pose_inv(self): + """ + Returns: + th.Tensor: (4,4) homogeneous transformation matrix representing this scene's global inverse pose + """ + return self._pose_info["pose_inv"] + + def convert_world_pose_to_scene_relative(self, position, orientation): + """ + Convert a world pose to a scene-relative pose. + + Args: + position (th.Tensor): (3,) position in world frame + orientation (th.Tensor): (4,) orientation in world frame + + Returns: + 2-tuple: + - th.Tensor: (3,) position in scene frame + - th.Tensor: (4,) orientation in scene frame + """ + return T.mat2pose(self.pose_inv @ T.pose2mat((position, orientation))) + + def convert_scene_relative_pose_to_world(self, position, orientation): + """ + Convert a scene-relative pose to a world pose. + + Args: + position (th.Tensor): (3,) position in scene frame + orientation (th.Tensor): (4,) orientation in scene frame + + Returns: + 2-tuple: + - th.Tensor: (3,) position in world frame + - th.Tensor: (4,) orientation in world frame + """ + return T.mat2pose(self.pose @ T.pose2mat((position, orientation))) + + def is_system_active(self, system_name): + return self.get_system(system_name, force_init=False).initialized + + def is_visual_particle_system(self, system_name): + return isinstance(self.get_system(system_name, force_init=False), VisualParticleSystem) + + def is_physical_particle_system(self, system_name): + return isinstance(self.get_system(system_name, force_init=False), PhysicalParticleSystem) + + def is_fluid_system(self, system_name): + return isinstance(self.get_system(system_name, force_init=False), FluidSystem) + + def get_system(self, system_name, force_init=True): + """ + Grab the system @system_name, and optionally initialize it if @force_init is set + + Args: + system_name (str): Name of the system to grab + force_init (bool): Whether to force the system to be initialized and added to set of active_systems + if not already + + Returns: + BaseSystem: Requested system + """ + # Make sure scene exists + assert self.loaded, "Cannot get systems until scene is imported!" + assert system_name in self._available_systems, f"System {system_name} is not a valid system name" + # If system is not initialized, initialize and add it to our registry + system = self._available_systems[system_name] + if not system.initialized and force_init: + system.initialize(scene=self) + self.system_registry.add(system) + return system + + def clear_system(self, system_name): + """ + Clear the system @system_name and remove it from our set of active systems + + Args: + system_name (str): Name of the system to remove + """ + system = self.system_registry("name", system_name) + if system is not None: + # Remove from system registry and clear + self.system_registry.remove(system) + system.clear() + + # Clearing a system deletes prims, which invalidates the PhysX tensor views of + # unrelated objects. Update handles accordingly. + og.sim.update_handles() + + @property + def active_systems(self): + return {system.name: system for system in self.systems if not isinstance(system, Cloth)} + + def get_random_floor(self): + """ + Sample a random floor among all existing floor_heights in the scene. + Most scenes in OmniGibson only have a single floor. + + Returns: + int: an integer between 0 and self.n_floors-1 + """ + return th.randint(0, self.n_floors) + + def get_random_point(self, floor=None, reference_point=None, robot=None): + """ + Sample a random point on the given floor number. If not given, sample a random floor number. + If @reference_point is given, sample a point in the same connected component as the previous point. + + Args: + floor (None or int): floor number. None means the floor is randomly sampled + Warning: if @reference_point is given, @floor must be given; + otherwise, this would lead to undefined behavior + reference_point (3-array): (x,y,z) if given, sample a point in the same connected component as this point + + Returns: + 2-tuple: + - int: floor number. This is the sampled floor number if @floor is None + - 3-array: (x,y,z) randomly sampled point + """ + raise NotImplementedError() + + def get_shortest_path(self, floor, source_world, target_world, entire_path=False, robot=None): + """ + Get the shortest path from one point to another point. + + Args: + floor (int): floor number + source_world (2-array): (x,y) 2D source location in world reference frame (metric) + target_world (2-array): (x,y) 2D target location in world reference frame (metric) + entire_path (bool): whether to return the entire path + robot (None or BaseRobot): if given, erode the traversability map to account for the robot's size + + Returns: + 2-tuple: + - (N, 2) array: array of path waypoints, where N is the number of generated waypoints + - float: geodesic distance of the path + """ + raise NotImplementedError() + + def get_floor_height(self, floor=0): + """ + Get the height of the given floor. Default is 0.0, since we only have a single floor + + Args: + floor (int): an integer identifying the floor + + Returns: + int: height of the given floor + """ + return 0.0 + + def update_initial_file(self, scene_file=None): + """ + Updates the initial scene file for this scene (which the scene will get reset to upon calling reset()) + + Args: + scene_file (None or str or dict): If specified, the state to set internally. Can be a full path to the scene + file or the already-loaded dictionary equivalent. This should be the output of self.save(). Otherwise, + will set the initial file to be the current scene file that will be cached immediately + """ + if scene_file is None: + scene_file = self.save(as_dict=True) + else: + if isinstance(scene_file, str): + with open(scene_file, "r") as f: + scene_file = json.load(f) + else: + assert isinstance( + scene_file, dict + ), f"Expected scene_file to be a dictionary, but got: {type(scene_file)}" + + scene_file["state"] = recursively_convert_to_torch(scene_file["state"]) + self._initial_file = scene_file + + def update_objects_info(self): + """ + Updates the scene-relevant information and saves it to the active USD. Useful for reloading a scene directly + from a saved USD in this format. + """ + # Save relevant information + + # Iterate over all objects and save their init info + init_info = {obj.name: obj.get_init_info() for obj in self.object_registry.objects} + + # Compose as single dictionary and store internally + self._objects_info = dict(init_info=init_info) + + def get_objects_info(self): + """ + Stored information, if any, for this scene. Structure is: + + "init_info": + "": init kw/args + ... + "": init kw/args + ... + + Returns: + None or dict: If it exists, nested dictionary of relevant objects' information + """ + return self._objects_info + + def _dump_state(self): + """Dumps this scene's state. + + ``pos``/``ori`` record where the scene sat when the state was taken; loading uses them to + shift object poses over to wherever the scene sits now, and never moves the scene itself. + Moving it would stack every scene on the same spot when running several at once, so their + objects would collide. + """ + # Default state for the scene is from the registry alone + pos, ori = self.get_position_orientation() + return { + "pos": pos, + "ori": ori, + "registry": self._registry.dump_state(serialized=False), + } + + def _load_state(self, state): + # Load scene state, then registry + # TODO: Remove backwards compatible check once new scene RC is updated + if "pos" in state: + # ("pos", "ori") say where the scene sat when the state was taken. Leave this scene + # where it is and shift the object poses over instead, so that running several + # scenes at once does not pile them all onto the recorded spot and let their + # objects collide. + rec_pos = th.as_tensor(state["pos"], dtype=th.float32).reshape(3) + rec_ori = th.as_tensor(state["ori"], dtype=th.float32).reshape(4) + cur_pos, cur_ori = self.get_position_orientation() + registry_state = state["registry"] + if not (th.equal(rec_pos, cur_pos) and th.equal(rec_ori, cur_ori)): + # rel = cur ∘ rec⁻¹ moves a recorded pose over to this scene. When the two + # match, this branch is skipped and the poses load unchanged. + inv_rec_pos, inv_rec_ori = T.invert_pose_transform(rec_pos, rec_ori) + rel_pos, rel_ori = T.pose_transform(cur_pos, cur_ori, inv_rec_pos, inv_rec_ori) + registry_state = self._rebase_registry_state_poses(registry_state, rel_pos, rel_ori) + self._registry.load_state(state=registry_state, serialized=False) + else: + self._registry.load_state(state=state, serialized=False) + + @staticmethod + def _rebase_registry_state_poses(registry_state, rel_pos, rel_ori): + """Returns a copy of @registry_state with object poses moved over by (rel_pos, rel_ori). + + Objects have their positions moved and their velocities rotated. Particle systems are + different: their positions are already stored relative to the scene, so only their + velocities need rotating. Velocities are only ever rotated, never moved. + + The input dicts are left untouched, since callers reuse them across calls. + """ + rebased = dict(registry_state) + object_registry = registry_state.get("object_registry") + if object_registry is None: + return rebased + new_object_registry = {} + for name, obj_state in object_registry.items(): + root = obj_state.get("root_link") if isinstance(obj_state, dict) else None + if not isinstance(root, dict) or "pos" not in root: + new_object_registry[name] = obj_state + continue + new_root = dict(root) + new_root["pos"], new_root["ori"] = T.pose_transform( + rel_pos, + rel_ori, + th.as_tensor(root["pos"], dtype=th.float32).reshape(3), + th.as_tensor(root["ori"], dtype=th.float32).reshape(4), + ) + for vec_key in ("lin_vel", "ang_vel", "particle_velocities"): + if vec_key in root: + vec = th.as_tensor(root[vec_key], dtype=th.float32) + new_root[vec_key] = T.quat_apply(rel_ori, vec).reshape(vec.shape) + if "particle_positions" in root: + pts = th.as_tensor(root["particle_positions"], dtype=th.float32) + new_root["particle_positions"] = (T.quat_apply(rel_ori, pts) + rel_pos).reshape(pts.shape) + new_obj_state = dict(obj_state) + new_obj_state["root_link"] = new_root + new_object_registry[name] = new_obj_state + rebased["object_registry"] = new_object_registry + + system_registry = registry_state.get("system_registry") + if isinstance(system_registry, dict): + new_system_registry = {} + for name, sys_state in system_registry.items(): + if not isinstance(sys_state, dict): + new_system_registry[name] = sys_state + continue + new_sys_state = Scene._rebase_system_velocities(sys_state, rel_ori) + new_system_registry[name] = new_sys_state + rebased["system_registry"] = new_system_registry + return rebased + + @staticmethod + def _rebase_system_velocities(sys_state, rel_ori): + """Returns a copy of a system state with its world-frame velocity fields rotated. + + Recurses one level into nested per-instancer dicts (micro systems keep a dict of + instancer states), and leaves every other field -- including scene-relative + particle positions and orientations -- untouched. + """ + rotated = dict(sys_state) + changed = False + for key in ("particle_velocities", "lin_velocities", "ang_velocities"): + value = sys_state.get(key) + if value is None: + continue + vec = th.as_tensor(value, dtype=th.float32) + if vec.numel() == 0: + continue + rotated[key] = T.quat_apply(rel_ori, vec.reshape(-1, 3)).reshape(vec.shape) + changed = True + for key, value in sys_state.items(): + if key in ("particle_velocities", "lin_velocities", "ang_velocities"): + continue + if isinstance(value, dict): + nested = Scene._rebase_system_velocities(value, rel_ori) + if nested is not value: + rotated[key] = nested + changed = True + return rotated if changed else sys_state + + def serialize(self, state): + return th.cat([state["pos"], state["ori"], self._registry.serialize(state=state["registry"])]) + + def deserialize(self, state): + state_dict = { + "pos": state[:3], + "ori": state[3:7], + } + idx = 7 + registry_dict, registry_idx = self._registry.deserialize(state=state[idx:]) + state_dict["registry"] = registry_dict + return state_dict, idx + registry_idx + + @classproperty + def _cls_registry(cls): + # Global registry + global REGISTERED_SCENES + return REGISTERED_SCENES + + @classmethod + def modify_init_info_for_restoring(cls, init_info): + """ + Helper function to modify a given init info for restoring a scene from corresponding scene info. + Note that this function modifies IN-PLACE! + + Args: + init_info (dict): Information for this scene from @self.get_init_info() + """ + # Default is pass + pass diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/static_traversable_scene.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/static_traversable_scene.py new file mode 100644 index 0000000000000000000000000000000000000000..be86cf35184c18c3d5720c4247049a25e1093fe7 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/static_traversable_scene.py @@ -0,0 +1,142 @@ +import os + +import torch as th + +import omnigibson as og +from omnigibson.macros import create_module_macros +from omnigibson.prims.geom_prim import GeomPrim +from omnigibson.scenes.traversable_scene import TraversableScene +from omnigibson.utils.asset_utils import get_scene_path +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import add_asset_to_stage, scene_relative_prim_path_to_absolute, setup_collision_apis + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Create macros +m = create_module_macros(module_path=__file__) + +# Additional elevation for the floor plane +m.FLOOR_Z_OFFSET = 0.02 + + +class StaticTraversableScene(TraversableScene): + """ + Static traversable scene class for OmniGibson, where scene is defined by a singular mesh (no intereactable objects) + """ + + def __init__( + self, + scene_model, + scene_file=None, + trav_map_resolution=0.1, + default_erosion_radius=0.0, + trav_map_with_objects=True, + num_waypoints=10, + waypoint_resolution=0.2, + include_robots=True, + ): + """ + Args: + scene_model (str): Scene model name, e.g.: Adrian + scene_file (None or str): If specified, full path of JSON file to load (with .json). + None results in no additional objects being loaded into the scene + trav_map_resolution (float): traversability map resolution + default_erosion_radius (float): default map erosion radius in meters + trav_map_with_objects (bool): whether to use objects or not when constructing graph + num_waypoints (int): number of way points returned + waypoint_resolution (float): resolution of adjacent way points + include_robots (bool): whether to also include the robot(s) defined in the scene + """ + # Store and initialize additional variables + self._floor_heights = None + self._scene_mesh = None + + # Run super init + assert og.sim.floor_plane, "Floor plane must be enabled for StaticTraversableScene" + super().__init__( + scene_model=scene_model, + scene_file=scene_file, + trav_map_resolution=trav_map_resolution, + default_erosion_radius=default_erosion_radius, + trav_map_with_objects=trav_map_with_objects, + num_waypoints=num_waypoints, + waypoint_resolution=waypoint_resolution, + use_floor_plane=True, + include_robots=include_robots, + ) + + def _load(self): + # Run super first + super()._load() + + # Load the scene mesh (use downsampled one if available) + filename = os.path.join(get_scene_path(self.scene_model), "mesh_z_up_downsampled.obj") + if not os.path.isfile(filename): + filename = os.path.join(get_scene_path(self.scene_model), "mesh_z_up.obj") + + scene_mesh_relative_path = "/scene" + scene_mesh_absolute_path = scene_relative_prim_path_to_absolute(self, scene_mesh_relative_path) + add_asset_to_stage( + asset_path=filename, + prim_path=scene_mesh_absolute_path, + ) + + # Grab the actual mesh prim + self._scene_mesh = GeomPrim( + relative_prim_path=f"/scene/mesh_z_up/{self.scene_model}_mesh_texture", + name=f"{self.scene_model}_mesh", + ) + self._scene_mesh.load(self) + setup_collision_apis(self._scene_mesh.prim) + + # Load floor metadata + floor_height_path = os.path.join(get_scene_path(self.scene_model), "floors.txt") + assert os.path.isfile(floor_height_path), f"floor_heights.txt cannot be found in model: {self.scene_model}" + with open(floor_height_path, "r") as f: + self.floor_heights = sorted(list(map(float, f.readlines()))) + log.debug("Floors {}".format(self.floor_heights)) + + # Move the first floor to be at the floor level by default. + default_floor = 0 + floor_height = self.floor_heights[default_floor] + m.FLOOR_Z_OFFSET + scene_position = self._scene_prim.get_position_orientation()[0] + scene_position[2] = floor_height + self._scene_prim.set_position_orientation(position=scene_position) + + # Filter the collision between the scene mesh and the floor plane + self._scene_mesh.add_filtered_collision_pair(prim=og.sim.floor_plane) + + # Load the traversability map + self._trav_map.load_map(get_scene_path(self.scene_model)) + + def move_floor_plane(self, floor=0, additional_elevation=0.02, height=None): + """ + Resets the floor plane to a new floor + + Args: + floor (int): Integer identifying the floor to move the floor plane to + additional_elevation (float): Additional elevation with respect to the height of the floor + height (None or float): If specified, alternative parameter to directly control the height of the ground + plane. Note that this will override @additional_elevation and @floor! + """ + if height is not None: + height_adjustment = height - self.floor_heights[floor] + else: + height_adjustment = ( + self.floor_heights[floor] - self._scene_prim.get_position_orientation()[0][2] + additional_elevation + ) + self._scene_prim.set_position_orientation(position=th.tensor([0, 0, height_adjustment])) + + def get_floor_height(self, floor=0): + """ + Return the current floor height (in meter) + + Returns: + int: current floor height + """ + return self.floor_heights[floor] + + @property + def n_floors(self): + return len(self._floor_heights) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/traversable_scene.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/traversable_scene.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1773d7789956bf08bda550925b193761b32667 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/scenes/traversable_scene.py @@ -0,0 +1,76 @@ +from omnigibson.maps.traversable_map import TraversableMap +from omnigibson.scenes.scene_base import Scene +from omnigibson.utils.ui_utils import create_module_logger + +# Create module logger +log = create_module_logger(module_name=__name__) + + +class TraversableScene(Scene): + """ + Traversable scene class. + Contains the functionalities for navigation such as shortest path computation + """ + + def __init__( + self, + scene_model, + scene_file=None, + trav_map_resolution=0.1, + default_erosion_radius=0.0, + trav_map_with_objects=True, + num_waypoints=10, + waypoint_resolution=0.2, + use_floor_plane=True, + include_robots=True, + ): + """ + Args: + scene_model (str): Scene model name, e.g.: Adrian or Rs_int + scene_file (None or str): If specified, full path of JSON file to load (with .json). + None results in no additional objects being loaded into the scene + trav_map_resolution (float): traversability map resolution + default_erosion_radius (float): default map erosion radius in meters + trav_map_with_objects (bool): whether to use objects or not when constructing graph + num_waypoints (int): number of way points returned + waypoint_resolution (float): resolution of adjacent way points + use_floor_plane (bool): whether to load a flat floor plane into the simulator + include_robots (bool): whether to also include the robot(s) defined in the scene + """ + log.info("TraversableScene model: {}".format(scene_model)) + self.scene_model = scene_model + + # Create traversable map + self._trav_map = TraversableMap( + map_resolution=trav_map_resolution, + default_erosion_radius=default_erosion_radius, + trav_map_with_objects=trav_map_with_objects, + num_waypoints=num_waypoints, + waypoint_resolution=waypoint_resolution, + ) + # Run super init + super().__init__( + scene_file=scene_file, + use_floor_plane=use_floor_plane, + include_robots=include_robots, + ) + + @property + def trav_map(self): + """ + Returns: + TraversableMap: Map for computing connectivity between nodes for this scene + """ + return self._trav_map + + def get_random_point(self, floor=None, reference_point=None, robot=None): + return self._trav_map.get_random_point(floor=floor, reference_point=reference_point, robot=robot) + + def get_shortest_path(self, floor, source_world, target_world, entire_path=False, robot=None): + return self._trav_map.get_shortest_path( + floor=floor, + source_world=source_world, + target_world=target_world, + entire_path=entire_path, + robot=robot, + ) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9fe98ac38d624f43f31f3d49dd1c3fb5a2e48795 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/__init__.py @@ -0,0 +1,91 @@ +from omnigibson.sensors.dropout_sensor_noise import DropoutSensorNoise +from omnigibson.sensors.scan_sensor import ScanSensor +from omnigibson.sensors.sensor_base import ALL_SENSOR_MODALITIES, REGISTERED_SENSORS, BaseSensor +from omnigibson.sensors.sensor_noise_base import REGISTERED_SENSOR_NOISES, BaseSensorNoise +from omnigibson.sensors.tiled_sensor import TiledVisionSensor +from omnigibson.sensors.vision_sensor import VisionSensor +from omnigibson.utils.python_utils import assert_valid_key + +# Map sensor prim names to corresponding sensor classes +SENSOR_PRIMS_TO_SENSOR_CLS = { + "Lidar": ScanSensor, + "Camera": VisionSensor, +} + + +def create_sensor( + sensor_type, + relative_prim_path, + name, + modalities="all", + enabled=True, + sensor_kwargs=None, + noise_type=None, + noise_kwargs=None, +): + """ + Create a sensor of type @sensor_type with optional keyword args @sensor_kwargs that should be passed to the + constructor. Also, additionally send noise of type @noise_type with corresponding keyword args @noise_kwargs + that should be passed to the noise constructor. + + Args: + sensor_type (str): Type of sensor to create. Should be either one of SENSOR_PRIM_TO_SENSOR.keys() or + one of REGISTERED_SENSORS (i.e.: the string name of the desired class to create) + relative_prim_path (str): Scene-local prim path of the Sensor to encapsulate or create. + name (str): Name for the sensor. Names need to be unique per scene. + modalities (str or list of str): Modality(s) supported by this sensor. Valid options are part of + sensor.all_modalities. Default is "all", which corresponds to all modalities being used + enabled (bool): Whether this sensor should be enabled or not + sensor_kwargs (dict): Any keyword kwargs to pass to the constructor + noise_type (str): Type of sensor to create. Should be one of REGISTERED_SENSOR_NOISES + (i.e.: the string name of the desired class to create) + noise_kwargs (dict): Any keyword kwargs to pass to the constructor + + Returns: + BaseSensor: Created sensor with specified params + """ + # Run basic sanity check + assert isinstance(sensor_type, str), "Inputted sensor_type must be a string!" + + # Grab the requested sensor class + if sensor_type in SENSOR_PRIMS_TO_SENSOR_CLS: + sensor_cls = SENSOR_PRIMS_TO_SENSOR_CLS[sensor_type] + elif sensor_type in REGISTERED_SENSORS: + sensor_cls = REGISTERED_SENSORS[sensor_type] + else: + # This is an error, we didn't find the requested sensor ): + raise ValueError(f"No sensor found with corresponding sensor_type: {sensor_type}") + + # Create the noise, and sanity check to make sure it's a valid type + noise = None + if noise_type is not None: + assert_valid_key(key=noise_type, valid_keys=REGISTERED_SENSOR_NOISES, name="sensor noise type") + noise_kwargs = dict() if noise_kwargs is None else noise_kwargs + noise = REGISTERED_SENSOR_NOISES[noise_type](**noise_kwargs) + + # Create the sensor + sensor_kwargs = dict() if sensor_kwargs is None else sensor_kwargs + sensor = sensor_cls( + relative_prim_path=relative_prim_path, + name=name, + modalities=modalities, + enabled=enabled, + noise=noise, + **sensor_kwargs, + ) + + return sensor + + +__all__ = [ + "ALL_SENSOR_MODALITIES", + "BaseSensor", + "BaseSensorNoise", + "create_sensor", + "DropoutSensorNoise", + "REGISTERED_SENSOR_NOISES", + "REGISTERED_SENSORS", + "ScanSensor", + "TiledVisionSensor", + "VisionSensor", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/dropout_sensor_noise.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/dropout_sensor_noise.py new file mode 100644 index 0000000000000000000000000000000000000000..d64d297e550fe7b6169076095768ff872e69bba0 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/dropout_sensor_noise.py @@ -0,0 +1,80 @@ +import torch as th + +from omnigibson.sensors.sensor_noise_base import BaseSensorNoise + + +class DropoutSensorNoise(BaseSensorNoise): + """ + Naive dropout sensor noise model + + Args: + dropout_prob (float): Value in [0.0, 1.0] representing fraction of a single observation to be replaced + with @dropout_value + dropout_value (float): Value in [0.0, 1.0] to replace observations selected to be dropped out + enabled (bool): Whether this sensor should be enabled by default + """ + + def __init__( + self, + dropout_prob=0.05, + dropout_value=1.0, + enabled=True, + ): + # Store args, and make sure values are in acceptable range + for name, val in zip(("dropout_prob", "dropout_value"), (dropout_prob, dropout_value)): + assert 0.0 <= val <= 1.0, f"{name} should be in range [0.0, 1.0], got: {val}" + self._dropout_prob = dropout_prob + self._dropout_value = dropout_value + + # Run super method + super().__init__(enabled=enabled) + + def _corrupt(self, obs): + # If our noise rate is 0, we just return the obs + if self._dropout_prob == 0.0: + return obs + + # Corrupt with randomized dropout + valid_mask = th.bernoulli(th.full(obs.shape, 1.0 - self._dropout_prob)).to(th.int64) + obs[valid_mask == 0] = self._dropout_value + return obs + + @property + def dropout_prob(self): + """ + Returns: + float: Value in [0.0, 1.0] representing fraction of a single observation to be replaced + with self.dropout_value + """ + return self._dropout_prob + + @dropout_prob.setter + def dropout_prob(self, p): + """ + Set the dropout probability for this noise model. + + Args: + p (float): Value in [0.0, 1.0] representing fraction of a single observation to be replaced + with self.dropout_value + """ + assert 0.0 <= p <= 1.0, f"dropout_prob should be in range [0.0, 1.0], got: {p}" + self._dropout_prob = p + + @property + def dropout_value(self): + """ + Returns: + float: Value in [0.0, 1.0] to replace observations selected to be dropped out + """ + return self._dropout_value + + @dropout_value.setter + def dropout_value(self, val): + """ + Set the dropout value for this noise model. + + Args: + val (float): Value in [0.0, 1.0] to replace observations selected to be dropped out + """ + assert 0.0 <= val <= 1.0, f"dropout_value should be in range [0.0, 1.0], got: {val}" + self._dropout_value = val diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/scan_sensor.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/scan_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..954ad1366b2c25b39fe57bff3ea7e89e8cda61d7 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/scan_sensor.py @@ -0,0 +1,498 @@ +import math +from collections.abc import Iterable + +import cv2 +import torch as th + +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.sensors.sensor_base import BaseSensor +from omnigibson.utils.constants import OccupancyGridState +from omnigibson.utils.numpy_utils import NumpyTypes +from omnigibson.utils.python_utils import classproperty + + +class ScanSensor(BaseSensor): + """ + General 2D LiDAR range sensor and occupancy grid sensor. + + Args: + relative_prim_path (str): Scene-local prim path of the Sensor to encapsulate or create. + name (str): Name for the object. Names need to be unique per scene. + modalities (str or list of str): Modality(s) supported by this sensor. Default is "all", which corresponds + to all modalities being used. Otherwise, valid options should be part of cls.all_modalities. + For this scan sensor, this includes any of: + {scan, occupancy_grid} + Note that in order for "occupancy_grid" to be used, "scan" must also be included. + enabled (bool): Whether this sensor should be enabled by default + noise (None or BaseSensorNoise): If specified, sensor noise model to apply to this sensor. + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this sensor's prim at runtime. + min_range (float): Minimum range to sense in meters + max_range (float): Maximum range to sense in meters + horizontal_fov (float): Field of view of sensor, in degrees + vertical_fov (float): Field of view of sensor, in degrees + yaw_offset (float): Degrees for offsetting this sensors horizontal FOV. + Useful in cases where this sensor's forward direction is different than expected + horizontal_resolution (float): Degrees in between each horizontal scan hit + vertical_resolution (float): Degrees in between each vertical scan hit + rotation_rate (float): How fast the range sensor is rotating, in rotations per sec. Set to 0 for all scans + be to hit at once + draw_points (bool): Whether to draw the points hit by this sensor + draw_lines (bool): Whether to draw the lines representing the scans from this sensor + occupancy_grid_resolution (int): How many discretized nodes in the occupancy grid. This will specify the + height == width of the map + occupancy_grid_range (float): Range of the occupancy grid, in meters + occupancy_grid_inner_radius (float): Inner range of the occupancy grid that will assumed to be empty, in meters + occupancy_grid_local_link (None or XFormPrim): XForm prim that represents the "origin" of any generated + occupancy grid, e.g.: if this scan sensor is attached to a robot, then this should possibly be the base link + for that robot. If None is specified, then this will default to this own sensor's frame as the origin. + """ + + def __init__( + self, + relative_prim_path, + name, + modalities="all", + enabled=True, + noise=None, + load_config=None, + # Basic LIDAR kwargs + min_range=0.05, + max_range=10.0, + horizontal_fov=360.0, + vertical_fov=1.0, + yaw_offset=0.0, + horizontal_resolution=1.0, + vertical_resolution=1.0, + rotation_rate=0.0, + draw_points=False, + draw_lines=False, + # Occupancy Grid kwargs + occupancy_grid_resolution=128, + occupancy_grid_range=5.0, + occupancy_grid_inner_radius=0.5, + occupancy_grid_local_link=None, + ): + # Store settings + self.occupancy_grid_resolution = occupancy_grid_resolution + self.occupancy_grid_range = occupancy_grid_range + self.occupancy_grid_inner_radius = int( + occupancy_grid_inner_radius * occupancy_grid_resolution / occupancy_grid_range + ) + self.occupancy_grid_local_link = self if occupancy_grid_local_link is None else occupancy_grid_local_link + + # Create variables that will be filled in at runtime + self._rs = None # Range sensor interface, analagous to others, e.g.: dynamic control interface + + # Create load config from inputs + load_config = dict() if load_config is None else load_config + load_config["min_range"] = min_range + load_config["max_range"] = max_range + load_config["horizontal_fov"] = horizontal_fov + load_config["vertical_fov"] = vertical_fov + load_config["yaw_offset"] = yaw_offset + load_config["horizontal_resolution"] = horizontal_resolution + load_config["vertical_resolution"] = vertical_resolution + load_config["rotation_rate"] = rotation_rate + load_config["draw_points"] = draw_points + load_config["draw_lines"] = draw_lines + + # Sanity check modalities -- if we're using occupancy_grid without scan modality, raise an error + if isinstance(modalities, Iterable) and not isinstance(modalities, str) and "occupancy_grid" in modalities: + assert "scan" in modalities, "'scan' modality must be included in order to get occupancy_grid modality!" + + # Run super method + super().__init__( + relative_prim_path=relative_prim_path, + name=name, + modalities=modalities, + enabled=enabled, + noise=noise, + load_config=load_config, + ) + + def _load(self): + # Define a LIDAR prim at the current stage + result, lidar = lazy.omni.kit.commands.execute("RangeSensorCreateLidar", path=self.prim_path) + + return lidar.GetPrim() + + def _post_load(self): + # run super first + super()._post_load() + + # Set all the lidar kwargs + self.min_range = self._load_config["min_range"] + self.max_range = self._load_config["max_range"] + self.horizontal_fov = self._load_config["horizontal_fov"] + self.vertical_fov = self._load_config["vertical_fov"] + self.yaw_offset = self._load_config["yaw_offset"] + self.horizontal_resolution = self._load_config["horizontal_resolution"] + self.vertical_resolution = self._load_config["vertical_resolution"] + self.rotation_rate = self._load_config["rotation_rate"] + self.draw_points = self._load_config["draw_points"] + self.draw_lines = self._load_config["draw_lines"] + + def _initialize(self): + # run super first + super()._initialize() + + # Initialize lidar sensor interface + self._rs = lazy.isaacsim.sensors.physx._range_sensor.acquire_lidar_sensor_interface() + + @property + def _obs_space_mapping(self): + # Set the remaining modalities' values + # (obs modality, shape, low, high) + obs_space_mapping = dict( + scan=((self.n_horizontal_rays, self.n_vertical_rays), 0.0, 1.0, NumpyTypes.FLOAT32), + occupancy_grid=( + (self.occupancy_grid_resolution, self.occupancy_grid_resolution, 1), + 0.0, + 1.0, + NumpyTypes.FLOAT32, + ), + ) + + return obs_space_mapping + + def get_local_occupancy_grid(self, scan): + """ + Get local occupancy grid based on current 1D scan + + Args: + scan (array): 1D LiDAR scan + + Returns: + 2D-array: (occupancy_grid_resolution, occupancy_grid_resolution)-sized numpy array of the local occupancy grid + """ + # Run sanity checks first + assert "occupancy_grid" in self._modalities, "Occupancy grid is not enabled for this range sensor!" + assert self.n_vertical_rays == 1, "Occupancy grid is only valid for a 1D range sensor (n_vertical_rays = 1)!" + + # Calculate the number of points + num_points = math.ceil(self.horizontal_fov / self.horizontal_resolution) + + # Generate angles using linspace + angles = th.linspace( + -th.deg2rad(th.tensor([self.horizontal_fov / 2])).item(), + th.deg2rad(th.tensor([self.horizontal_fov / 2])).item(), + num_points, + ) + + # Convert into 3D unit vectors for each angle + unit_vector_laser = th.stack([th.cos(angles), th.sin(angles), th.zeros_like(angles)], dim=1) + + # Scale unit vectors by corresponding laser scan distnaces + assert ((scan >= 0.0) & (scan <= 1.0)).all(), "scan out of valid range [0, 1]" + scan_laser = unit_vector_laser * (scan * (self.max_range - self.min_range) + self.min_range) + + # Convert scans from laser frame to world frame + pos, ori = self.get_position_orientation() + scan_world = (T.quat2mat(ori) @ scan_laser.T).T + pos + + # Convert scans from world frame to local base frame + base_pos, base_ori = self.occupancy_grid_local_link.get_position_orientation() + scan_local = (T.quat2mat(base_ori).T @ (scan_world - base_pos).T).T + scan_local = scan_local[:, :2] + scan_local = th.cat([th.tensor([[0, 0]]), scan_local, th.tensor([[0, 0]])], dim=0) + + # flip y axis + scan_local[:, 1] *= -1 + + # Initialize occupancy grid -- default is unknown values + occupancy_grid = th.full( + (self.occupancy_grid_resolution, self.occupancy_grid_resolution), + fill_value=int(OccupancyGridState.UNKNOWN * 2.0), + dtype=th.uint8, + ) + + # Convert local scans into the corresponding OG square it should belong to (note now all values are > 0, since + # OG ranges from [0, resolution] x [0, resolution]) + scan_local_in_map = scan_local / self.occupancy_grid_range * self.occupancy_grid_resolution + ( + self.occupancy_grid_resolution / 2 + ) + scan_local_in_map = scan_local_in_map.reshape((1, -1, 1, 2)).int() + + occupancy_grid = occupancy_grid.cpu().numpy() + scan_local_in_map = scan_local_in_map.cpu().numpy() + + # For each scan hit, + for i in range(scan_local_in_map.shape[1]): + cv2.circle( + img=occupancy_grid, + center=(scan_local_in_map[0, i, 0, 0], scan_local_in_map[0, i, 0, 1]), + radius=2, + color=int(OccupancyGridState.OBSTACLES * 2.0), + thickness=-1, + ) + cv2.fillPoly( + img=occupancy_grid, pts=scan_local_in_map, color=int(OccupancyGridState.FREESPACE * 2.0), lineType=1 + ) + cv2.circle( + img=occupancy_grid, + center=(self.occupancy_grid_resolution // 2, self.occupancy_grid_resolution // 2), + radius=self.occupancy_grid_inner_radius, + color=int(OccupancyGridState.FREESPACE * 2.0), + thickness=-1, + ) + + return th.tensor(occupancy_grid[:, :, None]) / 2.0 + + def _get_obs(self): + # Run super first to grab any upstream obs + obs, info = super()._get_obs() + + # Add scan info (normalized to [0.0, 1.0]) + if "scan" in self._modalities: + raw_scan = th.tensor(self._rs.get_linear_depth_data(self.prim_path), dtype=th.float32) + # Sometimes get_linear_depth_data will return values that are slightly out of range, needs clipping + raw_scan = th.clip(raw_scan, self.min_range, self.max_range) + obs["scan"] = (raw_scan - self.min_range) / (self.max_range - self.min_range) + + # Optionally add occupancy grid info + if "occupancy_grid" in self._modalities: + obs["occupancy_grid"] = self.get_local_occupancy_grid(scan=obs["scan"]) + + return obs, info + + @property + def n_horizontal_rays(self): + """ + Returns: + int: Number of horizontal rays for this range sensor + """ + return int(self.horizontal_fov // self.horizontal_resolution) + + @property + def n_vertical_rays(self): + """ + Returns: + int: Number of vertical rays for this range sensor + """ + return int(self.vertical_fov // self.vertical_resolution) + + @property + def min_range(self): + """ + Gets this range sensor's min_range (minimum distance in meters which will register a hit) + + Returns: + float: minimum range for this range sensor, in meters + """ + return self.get_attribute("minRange") + + @min_range.setter + def min_range(self, val): + """ + Sets this range sensor's min_range (minimum distance in meters which will register a hit) + + Args: + val (float): minimum range for this range sensor, in meters + """ + self.set_attribute("minRange", val) + + @property + def max_range(self): + """ + Gets this range sensor's max_range (maximum distance in meters which will register a hit) + + Returns: + float: maximum range for this range sensor, in meters + """ + return self.get_attribute("maxRange") + + @max_range.setter + def max_range(self, val): + """ + Sets this range sensor's max_range (maximum distance in meters which will register a hit) + + Args: + val (float): maximum range for this range sensor, in meters + """ + self.set_attribute("maxRange", val) + + @property + def draw_lines(self): + """ + Gets whether range lines are drawn for this sensor + + Returns: + bool: Whether range lines are drawn for this sensor + """ + return self.get_attribute("drawLines") + + @draw_lines.setter + def draw_lines(self, draw): + """ + Sets whether range lines are drawn for this sensor + + Args: + draw (float): Whether range lines are drawn for this sensor + """ + self.set_attribute("drawLines", draw) + + @property + def draw_points(self): + """ + Gets whether range points are drawn for this sensor + + Returns: + bool: Whether range points are drawn for this sensor + """ + return self.get_attribute("drawPoints") + + @draw_points.setter + def draw_points(self, draw): + """ + Sets whether range points are drawn for this sensor + + Args: + draw (float): Whether range points are drawn for this sensor + """ + self.set_attribute("drawPoints", draw) + + @property + def horizontal_fov(self): + """ + Gets this range sensor's horizontal_fov + + Returns: + float: horizontal field of view for this range sensor + """ + return self.get_attribute("horizontalFov") + + @horizontal_fov.setter + def horizontal_fov(self, fov): + """ + Sets this range sensor's horizontal_fov + + Args: + fov (float): horizontal field of view to set + """ + self.set_attribute("horizontalFov", fov) + + @property + def horizontal_resolution(self): + """ + Gets this range sensor's horizontal_resolution (degrees in between each horizontal hit) + + Returns: + float: horizontal resolution for this range sensor, in degrees + """ + return self.get_attribute("horizontalResolution") + + @horizontal_resolution.setter + def horizontal_resolution(self, resolution): + """ + Sets this range sensor's horizontal_resolution (degrees in between each horizontal hit) + + Args: + resolution (float): horizontal resolution to set, in degrees + """ + self.set_attribute("horizontalResolution", resolution) + + @property + def vertical_fov(self): + """ + Gets this range sensor's vertical_fov + + Returns: + float: vertical field of view for this range sensor + """ + return self.get_attribute("verticalFov") + + @vertical_fov.setter + def vertical_fov(self, fov): + """ + Sets this range sensor's vertical_fov + + Args: + fov (float): vertical field of view to set + """ + self.set_attribute("verticalFov", fov) + + @property + def vertical_resolution(self): + """ + Gets this range sensor's vertical_resolution (degrees in between each vertical hit) + + Returns: + float: vertical resolution for this range sensor, in degrees + """ + return self.get_attribute("verticalResolution") + + @vertical_resolution.setter + def vertical_resolution(self, resolution): + """ + Sets this range sensor's vertical_resolution (degrees in between each vertical hit) + + Args: + resolution (float): vertical resolution to set, in degrees + """ + self.set_attribute("verticalResolution", resolution) + + @property + def yaw_offset(self): + """ + Gets this range sensor's yaw_offset (used in cases where this sensor's forward direction is different than expected) + + Returns: + float: yaw offset for this range sensor in degrees + """ + return self.get_attribute("yawOffset") + + @yaw_offset.setter + def yaw_offset(self, offset): + """ + Sets this range sensor's yaw_offset (used in cases where this sensor's forward direction is different than expected) + + Args: + offset (float): yaw offset to set in degrees. + """ + self.set_attribute("yawOffset", offset) + + @property + def rotation_rate(self): + """ + Gets this range sensor's rotation_rate, in degrees per second. Note that a 0 value corresponds to no rotation, + and all range hits are assumed to be received at the exact same time. + + Returns: + float: rotation rate for this range sensor in degrees per second + """ + return self.get_attribute("rotationRate") + + @rotation_rate.setter + def rotation_rate(self, rate): + """ + Sets this range sensor's rotation_rate, in degrees per second. Note that a 0 value corresponds to no rotation, + and all range hits are assumed to be received at the exact same time. + + Args: + rate (float): rotation rate for this range sensor in degrees per second + """ + self.set_attribute("rotationRate", rate) + + @classproperty + def all_modalities(cls): + return {"scan", "occupancy_grid"} + + @classproperty + def no_noise_modalities(cls): + # Occupancy grid should have no noise + return {"occupancy_grid"} + + @property + def enabled(self): + # Just use super + return super().enabled + + @enabled.setter + def enabled(self, enabled): + # We must use super and additionally directly en/disable the sensor in the simulation + # Note: weird syntax below required to "extend" super class's implementation, see: + # https://stackoverflow.com/a/37663266 + super(ScanSensor, self.__class__).enabled.fset(self, enabled) + self.set_attribute("enabled", enabled) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/sensor_base.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/sensor_base.py new file mode 100644 index 0000000000000000000000000000000000000000..c3846fc32abee6f9d4a1e16c2277c1218bf5cd9b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/sensor_base.py @@ -0,0 +1,235 @@ +from abc import ABCMeta + +import gymnasium as gym + +from omnigibson.prims.xform_prim import XFormPrim +from omnigibson.utils.gym_utils import GymObservable +from omnigibson.utils.python_utils import Registerable, assert_valid_key, classproperty + +# Registered sensors +REGISTERED_SENSORS = dict() + +# All possible modalities across all sensors +ALL_SENSOR_MODALITIES = set() + + +class BaseSensor(XFormPrim, GymObservable, Registerable, metaclass=ABCMeta): + """ + Base Sensor class. + Sensor-specific get_obs method is implemented in subclasses + + Args: + relative_prim_path (str): Scene-local prim path of the Sensor to encapsulate or create. + name (str): Name for the sensor. Names need to be unique per scene. + modalities (str or list of str): Modality(s) supported by this sensor. Default is "all", which corresponds + to all modalities being used. Otherwise, valid options should be part of cls.all_modalities. + enabled (bool): Whether this sensor should be enabled by default + noise (None or BaseSensorNoise): If specified, sensor noise model to apply to this sensor. + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this sensor's prim at runtime. + """ + + def __init__( + self, + relative_prim_path, + name, + modalities="all", + enabled=True, + noise=None, + load_config=None, + ): + # Store inputs (and sanity check modalities along the way) + if modalities == "all": + modalities = self.all_modalities + else: + modalities = [modalities] if isinstance(modalities, str) else modalities + for modality in modalities: + assert_valid_key(key=modality, valid_keys=self.all_modalities, name="modality") + self._modalities = set(modalities) + self._enabled = enabled + self._noise = noise + + # Run super method + super().__init__( + relative_prim_path=relative_prim_path, + name=name, + load_config=load_config, + ) + + def _load(self): + # Sub-sensors must implement this class directly! Cannot use parent XForm class by default + raise NotImplementedError("Sensor class must implement _load!") + + def _post_load(self): + # Run super first + super()._post_load() + + # Set the enabled property based on the internal value + # This is done so that any subclassed sensors which require simulator specific enabling can handle this now + self.enabled = self._enabled + + def get_obs(self): + # Get sensor reading, and optionally corrupt the readings with noise using self.noise if + # self.noise.enabled is True. + # Note that the returned dictionary will only be filled in if this sensor is enabled! + if not self._enabled: + return dict() + + obs, info = self._get_obs() + + if self._noise is not None: + for k, v in obs.items(): + if k not in self.no_noise_modalities: + obs[k] = self._noise(v) + + return obs, info + + def _get_obs(self): + """ + Get sensor reading. Should generally be extended by subclass. + + Returns: + 2-tuple: + dict: Keyword-mapped observations mapping modality names to numpy arrays of arbitrary dimension + dict: Additional information about the observations. + """ + # Default is returning an empty dict + return dict(), dict() + + def _load_observation_space(self): + # Fill in observation space based on mapping and active modalities + obs_space = dict() + for modality, space in self._obs_space_mapping.items(): + if modality in self._modalities: + if isinstance(space, gym.Space): + # Directly add this space + obs_space[modality] = space + else: + # Assume we are procedurally generating a box space + shape, low, high, dtype = space + obs_space[modality] = self._build_obs_box_space(shape=shape, low=low, high=high, dtype=dtype) + + return obs_space + + def add_modality(self, modality): + """ + Add a modality to this sensor. Must be a valid modality (one of self.all_modalities) + + Args: + modality (str): Name of the modality to add to this sensor + """ + assert_valid_key(key=modality, valid_keys=self.all_modalities, name="modality") + if modality not in self._modalities: + self._modalities.add(modality) + # Update observation space + self.load_observation_space() + + def remove_modality(self, modality): + """ + Remove a modality from this sensor. Must be a valid modality that is active (one of self.modalities) + + Args: + modality (str): Name of the modality to remove from this sensor + """ + assert_valid_key(key=modality, valid_keys=self._modalities, name="modality") + if modality in self._modalities: + self._modalities.remove(modality) + # Update observation space + self.load_observation_space() + + @property + def modalities(self): + """ + Returns: + set: Name of modalities provided by this sensor. This should correspond to all the keys provided + in self.get_obs() + """ + return self._modalities + + @property + def _obs_space_mapping(self): + """ + Returns: + dict: Keyword-mapped observation space settings for each modality. For each modality in + cls.all_modalities, its name should map directly to the corresponding gym space Space for that modality + or a 4-tuple entry (shape, low, high, dtype) for procedurally generating the appropriate Box Space + for that modality + """ + raise NotImplementedError() + + @classproperty + def all_modalities(cls): + """ + Returns: + set: All possible valid modalities for this sensor. Should be implemented by subclass. + """ + raise NotImplementedError() + + @property + def noise(self): + """ + Returns: + None or BaseSensorNoise: Noise model to use for this sensor + """ + return self._noise + + @classproperty + def no_noise_modalities(cls): + """ + Returns: + set: Modalities that should NOT be passed through noise, irregardless of whether noise is enabled or not. + This is useful for some modalities which are not exclusively numerical arrays. + """ + raise NotImplementedError() + + @property + def enabled(self): + """ + Returns: + bool: Whether this sensor is enabled or not + """ + # By default, we simply return the internal value. Subclasses may need to extend this functionality, + # e.g. by disabling actual sim functionality for better computational efficiency + return self._enabled + + @enabled.setter + def enabled(self, enabled): + """ + Args: + enabled (bool): Whether this sensor should be enabled or not + """ + # By default, we simply store the value internally. Subclasses may need to extend this functionality, + # e.g. by disabling actual sim functionality for better computational efficiency + self._enabled = enabled + + @classproperty + def sensor_type(cls): + """ + Returns: + str: Type of this sensor. By default, this is the sensor class name + """ + return cls.__name__ + + @classmethod + def _register_cls(cls): + global ALL_SENSOR_MODALITIES + + # Run super first + super()._register_cls() + + # Also store modalities from this sensor class if we're registering it + if cls.__name__ not in cls._do_not_register_classes: + ALL_SENSOR_MODALITIES.union(cls.all_modalities) + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("BaseSensor") + return classes + + @classproperty + def _cls_registry(cls): + # Global registry + global REGISTERED_SENSORS + return REGISTERED_SENSORS diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/sensor_noise_base.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/sensor_noise_base.py new file mode 100644 index 0000000000000000000000000000000000000000..57a74296674812e6668bf4b65b30ca0bc85006a1 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/sensor_noise_base.py @@ -0,0 +1,92 @@ +from abc import ABCMeta, abstractmethod + +from omnigibson.utils.python_utils import Registerable, classproperty + +# Registered sensor noises +REGISTERED_SENSOR_NOISES = dict() + + +class BaseSensorNoise(Registerable, metaclass=ABCMeta): + """ + Base SensorNoise class. + Sensor noise-specific add_noise method is implemented in subclasses + + Args: + enabled (bool): Whether this sensor should be enabled by default + """ + + def __init__(self, enabled=True): + # Store whether this noise model is enabled or not + self._enabled = enabled + + def __call__(self, obs): + """ + If this noise is enabled, corrupts observation @obs by adding sensor noise to sensor reading. This is an + identical call to self.corrupt(...) + + Args: + obs (th.tensor): observation numpy array of values of arbitrary dimension normalized to range [0.0, 1.0] + + Returns: + th.tensor: Corrupted observation numpy array if self.enabled is True, otherwise this is a pass-through + """ + return self.corrupt(obs=obs) + + def corrupt(self, obs): + """ + If this noise is enabled, corrupts observation @obs by adding sensor noise to sensor reading. + + Args: + obs (th.tensor): observation numpy array of values of arbitrary dimension normalized to range [0.0, 1.0] + + Returns: + th.tensor: Corrupted observation numpy array if self.enabled is True, otherwise this is a pass-through + """ + # Run sanity check to make sure obs is in acceptable range + assert len(obs[(obs < 0.0) | (obs > 1.0)]) == 0, "sensor reading has to be between [0.0, 1.0]" + + return self._corrupt(obs=obs) if self._enabled else obs + + @abstractmethod + def _corrupt(self, obs): + """ + Corrupts observation @obs by adding sensor noise to sensor reading + + Args: + obs (th.tensor): observation numpy array of values of arbitrary dimension normalized to range [0.0, 1.0] + + Returns: + th.tensor: Corrupted observation numpy array + """ + raise NotImplementedError() + + @property + def enabled(self): + """ + Returns: + bool: Whether this noise model is enabled or not + """ + return self._enabled + + @enabled.setter + def enabled(self, enabled): + """ + En/disables this noise model + + Args: + enabled (bool): Whether this noise model should be enabled or not + """ + self._enabled = enabled + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("BaseSensorNoise") + return classes + + @classproperty + def _cls_registry(cls): + # Global registry + global REGISTERED_SENSOR_NOISES + return REGISTERED_SENSOR_NOISES diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/tiled_sensor.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/tiled_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..4458f58327148254801aae4e79ae1af5949354d6 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/tiled_sensor.py @@ -0,0 +1,289 @@ +import math +import omnigibson as og +import omnigibson.lazy as lazy +import torch as th +import warp as wp +from omnigibson.sensors.vision_sensor import VisionSensor +from omnigibson.utils.ui_utils import create_module_logger +from typing import Any, Tuple, List + +# Create module logger +log = create_module_logger(module_name=__name__) + + +# Vendored from isaacsim.sensors.camera.camera_view.reshape_tiled_image, with the unused offset / +# num_output_channels arguments dropped and a uint32 overload added -- upstream only registers uint8 +# and float32, but non-colored segmentation annotators hand back raw uint32 IDs. +@wp.kernel(enable_backward=False) +def reshape_tiled_image( + tiled_image_buffer: Any, + batched_image: Any, + image_height: int, + image_width: int, + num_channels: int, + num_tiles_x: int, +): + """Reshapes a tiled image into a batch of images. + This function reshapes the input tiled image buffer into a batch of images. The input image buffer + is assumed to be tiled in the x and y directions. The output image is a batch of images with the + specified height, width, and number of channels. + Args: + tiled_image_buffer: The input image buffer. Shape is (height * width * num_channels * num_cameras,). + batched_image: The output image. Shape is (num_cameras, height, width, num_channels). + image_width: The width of the image. + image_height: The height of the image. + num_channels: The number of channels in the image. + num_tiles_x: The number of tiles in x-direction. + """ + # get the thread id + camera_id, height_id, width_id = wp.tid() + + # resolve the tile indices + tile_x_id = camera_id % num_tiles_x + tile_y_id = camera_id // num_tiles_x + # compute the start index of the pixel in the tiled image buffer + pixel_start = ( + num_channels * num_tiles_x * image_width * (image_height * tile_y_id + height_id) + + num_channels * tile_x_id * image_width + + num_channels * width_id + ) + + # copy the pixel values into the batched image + for i in range(num_channels): + batched_image[camera_id, height_id, width_id, i] = tiled_image_buffer[pixel_start + i] + + +# uint32 is used for non-colored segmentation annotators (raw IDs, no dtype conversion is performed) +wp.overload( + reshape_tiled_image, + {"tiled_image_buffer": wp.array(dtype=wp.uint32), "batched_image": wp.array(dtype=wp.uint32, ndim=4)}, +) +# uint8 is used for 4 channel annotators +wp.overload( + reshape_tiled_image, + {"tiled_image_buffer": wp.array(dtype=wp.uint8), "batched_image": wp.array(dtype=wp.uint8, ndim=4)}, +) +# float32 is used for single channel annotators +wp.overload( + reshape_tiled_image, + {"tiled_image_buffer": wp.array(dtype=wp.float32), "batched_image": wp.array(dtype=wp.float32, ndim=4)}, +) + + +class TiledVisionSensor: + """ + Tiled vision sensor that leverages Omniverse Replicator to render tiled images from multiple cameras + Args: + envs (Iterable): Robot containers to create tiled sensors for -- any objects exposing a .robots list + (e.g. the per-env Scene instances of a multi-env Environment), one per environment, in env order. + tile_all_sensors (bool): Whether to tile all cameras in the envs or only those with matching names. Defaults to False. + NOTE: If True, all cameras must have the same modalities and resolution. + """ + + # Registry of all created tiled sensors, used for cleanup on og.clear() + TILED_SENSORS = [] + + def __init__(self, envs: List[Any], tile_all_sensors: bool = False) -> None: + camera_prim_paths = dict() + self.modalities = dict() + self._camera_resolution = dict() + self._camera_prims = dict() + self._annotators = dict() + + stage = lazy.omni.usd.get_context().get_stage() + for env in envs: + for robot in env.robots: + for sensor_name, sensor in robot.sensors.items(): + if tile_all_sensors: + sensor_name = "sensor" + if isinstance(sensor, VisionSensor): + if sensor_name not in camera_prim_paths: + camera_prim_paths[sensor_name] = [] + self.modalities[sensor_name] = sensor.modalities + self._camera_resolution[sensor_name] = (sensor.image_width, sensor.image_height) + self._camera_prims[sensor_name] = [] + assert ( + sensor.modalities == self.modalities[sensor_name] + ), f"All sensors named {sensor_name} must have the same modalities!" + assert self._camera_resolution[sensor_name] == ( + sensor.image_width, + sensor.image_height, + ), f"All sensors named {sensor_name} must have the same resolution!" + camera_prim_paths[sensor_name].append(sensor.prim_path) + camera_prim = stage.GetPrimAtPath(sensor.prim_path) + self._camera_prims[sensor_name].append(lazy.pxr.UsdGeom.Camera(camera_prim)) + self._render_product_paths = { + sensor_name: lazy.omni.replicator.core.create.render_product_tiled( + cameras=camera_prim_paths[sensor_name], tile_resolution=self._camera_resolution[sensor_name] + ) + for sensor_name in camera_prim_paths + } + self._create_annotators() + # Attach the annotator to the render product + for sensor_name in self._annotators: + for modality in self._annotators[sensor_name]: + self._annotators[sensor_name][modality].attach([self._render_product_paths[sensor_name]]) + + # Create internal buffers + self._create_buffers() + + # Register for cleanup on og.clear() + TiledVisionSensor.TILED_SENSORS.append(self) + + def remove(self) -> None: + """Detach all annotators and destroy the tiled render products. Idempotent.""" + if self not in TiledVisionSensor.TILED_SENSORS: + return + TiledVisionSensor.TILED_SENSORS.remove(self) + with og.sim.editing_usd(): + for sensor_name in self._annotators: + for annotator in self._annotators[sensor_name].values(): + # Passing an explicit list is bugged -- see VisionSensor._remove_modality_from_backend + try: + annotator.detach(self._render_product_paths[sensor_name]) + except TypeError: + log.warning(f"Failed to cleanly detach tiled annotator for {sensor_name}; skipping") + # Render so the syntheticdata graph settles before the render product is destroyed -- destroying + # with pending graph edits leaves invalid nodes that break subsequent annotator detach calls + og.sim.render() + with og.sim.editing_usd(): + for render_product in self._render_product_paths.values(): + render_product.destroy() + og.sim.render() + self._annotators = dict() + self._render_product_paths = dict() + + @classmethod + def clear(cls) -> None: + """Remove all tiled vision sensors. Called on og.clear() before scenes (and their cameras) are removed.""" + for sensor in tuple(cls.TILED_SENSORS): + sensor.remove() + + def _create_annotators(self) -> None: + self._annotators = dict() + for sensor_name in self.modalities: + self._annotators[sensor_name] = dict() + for modality in self.modalities[sensor_name]: + annotator_type = VisionSensor.RAW_SENSOR_TYPES[modality] + annotator = lazy.omni.replicator.core.AnnotatorRegistry.get_annotator( + annotator_type, device="cuda:0", do_array_copy=False + ) + self._annotators[sensor_name][modality] = annotator + + def _create_buffers(self, device: str = "cuda:0") -> None: + self._output_buffer = dict() + self._output_warp_buffer = dict() + self._reshape_dims = dict() + self._num_tiles_x = dict() + for sensor_name in self._camera_prims: + self._output_buffer[sensor_name] = dict() + self._output_warp_buffer[sensor_name] = dict() + self._reshape_dims[sensor_name] = ( + self._camera_count(sensor_name=sensor_name), + self._camera_resolution[sensor_name][1], + self._camera_resolution[sensor_name][0], + ) + self._num_tiles_x[sensor_name] = self._tiled_grid_shape(sensor_name=sensor_name)[0] + for modality in self.modalities[sensor_name]: + if modality == "rgb": + self._output_buffer[sensor_name][modality] = th.zeros( + ( + self._camera_count(sensor_name=sensor_name), + self._camera_resolution[sensor_name][1], + self._camera_resolution[sensor_name][0], + 4, + ), + device=device, + dtype=th.uint8, + ).contiguous() + elif modality == "depth" or modality == "depth_linear": + self._output_buffer[sensor_name][modality] = th.zeros( + ( + self._camera_count(sensor_name=sensor_name), + self._camera_resolution[sensor_name][1], + self._camera_resolution[sensor_name][0], + 1, + ), + device=device, + dtype=th.float32, + ).contiguous() + elif modality == "seg_semantic" or modality == "seg_instance" or modality == "seg_instance_id": + # unlike VisionSensor.get_obs(), the tiled path returns RAW Replicator segmentation + # IDs -- they are arbitrary, change between sessions, and are NOT remapped to OmniGibson's + # stable semantic/instance IDs (see VisionSensor._remap_semantic_segmentation). No id->name + # mapping info dict is available either. Do NOT train on these values until a batched remap + # is implemented; use the single-env per-sensor path for correct segmentation labels. + self._output_buffer[sensor_name][modality] = th.zeros( + ( + self._camera_count(sensor_name=sensor_name), + self._camera_resolution[sensor_name][1], + self._camera_resolution[sensor_name][0], + 1, + ), + device=device, + dtype=th.uint32, + ).contiguous() + elif modality == "flow": + self._output_buffer[sensor_name][modality] = th.zeros( + ( + self._camera_count(sensor_name=sensor_name), + self._camera_resolution[sensor_name][1], + self._camera_resolution[sensor_name][0], + 2, + ), + device=device, + dtype=th.float32, + ).contiguous() + elif modality == "normal": + self._output_buffer[sensor_name][modality] = th.zeros( + ( + self._camera_count(sensor_name=sensor_name), + self._camera_resolution[sensor_name][1], + self._camera_resolution[sensor_name][0], + 3, + ), + device=device, + dtype=th.uint8, + ).contiguous() + else: + raise ValueError(f"Unsupported modality {modality} for tiled vision sensor!") + # The output tensors are persistent. Cache their zero-copy Warp aliases instead of + # recreating Python/Warp wrappers on every rendered frame. + self._output_warp_buffer[sensor_name][modality] = lazy.warp.from_torch( + self._output_buffer[sensor_name][modality] + ) + + def _camera_count(self, sensor_name: str) -> int: + return len(self._camera_prims[sensor_name]) + + def _tiled_grid_shape(self, sensor_name: str) -> Tuple[int, int]: + cols = math.ceil(math.sqrt(self._camera_count(sensor_name=sensor_name))) + rows = math.ceil(self._camera_count(sensor_name=sensor_name) / cols) + return (cols, rows) + + def _tiled_img_shape(self, sensor_name: str) -> Tuple[int, int]: + cols, rows = self._tiled_grid_shape(sensor_name=sensor_name) + width, height = self._camera_resolution[sensor_name] + return (width * cols, height * rows) + + def get_obs(self): + for sensor_name in self._annotators: + for modality in self.modalities[sensor_name]: + tiled_data_buffer = self._annotators[sensor_name][modality].get_data().to("cuda:0") + # For flow, we only require the first two channels of the tiled buffer + # Note: Not doing this breaks the alignment of the data (check: https://github.com/isaac-sim/IsaacLab/issues/2003) + if modality == "flow": + tiled_data_buffer = tiled_data_buffer[:, :, :2].contiguous() + lazy.warp.launch( + kernel=reshape_tiled_image, + dim=self._reshape_dims[sensor_name], + inputs=[ + tiled_data_buffer.flatten(), + self._output_warp_buffer[sensor_name][modality], + *list(self._output_buffer[sensor_name][modality].shape[1:]), # height, width, num_channels + self._num_tiles_x[sensor_name], + ], + device="cuda:0", + ) + + return self._output_buffer diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/vision_sensor.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/vision_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..4a104086a158ae9af25f812d10a86b709d2e20f2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/sensors/vision_sensor.py @@ -0,0 +1,1014 @@ +import gymnasium as gym +import numpy as np +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.macros import gm +from omnigibson.sensors.sensor_base import BaseSensor +from omnigibson.systems.system_base import get_all_system_names +from omnigibson.utils.constants import ( + MAX_CLASS_COUNT, + MAX_INSTANCE_COUNT, + MAX_VIEWER_SIZE, + semantic_class_id_to_name, + semantic_class_name_to_id, +) +from omnigibson.utils.numpy_utils import NumpyTypes +from omnigibson.utils.python_utils import assert_valid_key, classproperty +from omnigibson.utils.ui_utils import create_module_logger, dock_window +from omnigibson.utils.vision_utils import Remapper + +# Create module logger +log = create_module_logger(module_name=__name__) + + +class VisionSensor(BaseSensor): + """ + Vision sensor that handles a variety of modalities, including: + + - RGB (normal) + - Depth (normal, linear) + - Normals + - Segmentation (semantic, instance) + - Optical flow + - 2D Bounding boxes (tight, loose) + - 3D Bounding boxes + - Camera state + + Args: + relative_prim_path (str): Scene-local prim path of the Sensor to encapsulate or create. + name (str): Name for the object. Names need to be unique per scene. + modalities (str or list of str): Modality(s) supported by this sensor. Default is "rgb". "all" will enable all + Otherwise, valid options should be part of cls.all_modalities. + For this vision sensor, this includes any of: + {rgb, depth, depth_linear, normal, seg_semantic, seg_instance, flow, bbox_2d_tight, + bbox_2d_loose, bbox_3d, camera_params} + enabled (bool): Whether this sensor should be enabled by default + noise (None or BaseSensorNoise): If specified, sensor noise model to apply to this sensor. + load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for + loading this sensor's prim at runtime. + image_height (int): Height of generated images, in pixels + image_width (int): Width of generated images, in pixels + focal_length (float): Focal length to set + focus_distance (float): Focus distance to set + fstop (float): fStop value to set + horizontal_aperture (float): Horizontal aperture to set + clipping_range (2-tuple): (min, max) viewing range of this vision sensor + viewport_name (None or str): If specified, will link this camera to the specified viewport, overriding its + current camera. Otherwise, creates a new viewport if not in headless mode and links this camera to it. + """ + + ALL_MODALITIES = ( + "rgb", + "depth", + "depth_linear", + "normal", + "seg_semantic", # Semantic segmentation shows the category each pixel belongs to + "seg_instance", # Instance segmentation shows the name of the object each pixel belongs to + "seg_instance_id", # Instance ID segmentation shows the prim path of the visual mesh each pixel belongs to + "flow", + "bbox_2d_tight", + "bbox_2d_loose", + "bbox_3d", + "camera_params", + "pointcloud", + ) + + RAW_SENSOR_TYPES = dict( + rgb="rgb", + depth="distance_to_camera", + depth_linear="distance_to_image_plane", + normal="normals", + # Semantic segmentation shows the category each pixel belongs to + seg_semantic="semantic_segmentation", + # Instance segmentation shows the name of the object each pixel belongs to + seg_instance="instance_segmentation", + # Instance ID segmentation shows the prim path of the visual mesh each pixel belongs to + seg_instance_id="instance_id_segmentation", + flow="motion_vectors", + bbox_2d_tight="bounding_box_2d_tight", + bbox_2d_loose="bounding_box_2d_loose", + bbox_3d="bounding_box_3d", + camera_params="camera_params", + pointcloud="pointcloud", + ) + + # Documentation for the different types of segmentation for particle systems: + # - Cloth (e.g. `dishtowel`): + # - semantic: all shows up under one semantic label (e.g. `"4207839377": "dishtowel"`) + # - instance: entire cloth shows up under one label (e.g. `"87": "dishtowel_0"`) + # - instance id: entire cloth shows up under one label (e.g. `"31": "/World/dishtowel_0/base_link_cloth"`) + # - MicroPhysicalParticleSystem - FluidSystem (e.g. `water`): + # - semantic: all shows up under one semantic label (e.g. `"3330677804": "water"`) + # - instance: all shows up under one instance label (e.g. `"21": "water"`) + # - instance id: all shows up under one instance ID label (e.g. `"36": "water"`) + # - MicroPhysicalParticleSystem - GranularSystem (e.g. `sesame seed`): + # - semantic: all shows up under one semantic label (e.g. `"2975304485": "sesame_seed"`) + # - instance: all shows up under one instance label (e.g. `"21": "sesame_seed"`) + # - instance id: all shows up under one instance ID label (e.g. `"36": "sesame_seed"`) + # - MacroPhysicalParticleSystem (e.g. `diced__carrot`): + # - semantic: all shows up under one semantic label (e.g. `"2419487146": "diced__carrot"`) + # - instance: all shows up under one instance label (e.g. `"21": "diced__carrot"`) + # - instance id: all shows up under one instance ID label (e.g. `"36": "diced__carrot"`) + # - MacroVisualParticleSystem (e.g. `stain`): + # - semantic: all shows up under one semantic label (e.g. `"884110082": "stain"`) + # - instance: all shows up under one instance label (e.g. `"21": "stain"`) + # - instance id: all shows up under one instance ID label (e.g. `"36": "stain"`) + + # Persistent dictionary of sensors, mapped from prim_path to sensor + SENSORS = dict() + + SEMANTIC_REMAPPER = Remapper() + INSTANCE_REMAPPER = Remapper() + INSTANCE_ID_REMAPPER = Remapper() + INSTANCE_REGISTRY = {0: "background", 1: "unlabelled"} + INSTANCE_ID_REGISTRY = {0: "background"} + + def __init__( + self, + relative_prim_path, + name, + modalities=["rgb"], + enabled=True, + noise=None, + load_config=None, + image_height=128, + image_width=128, + focal_length=17.0, # Default 17.0 since this is roughly the human eye focal length + focus_distance=0.0, + fstop=0.0, + horizontal_aperture=20.995, + clipping_range=(0.001, 10000000.0), + viewport_name=None, + ): + # Create load config from inputs + load_config = dict() if load_config is None else load_config + load_config["image_height"] = image_height + load_config["image_width"] = image_width + load_config["focal_length"] = focal_length + load_config["focus_distance"] = focus_distance + load_config["fstop"] = fstop + load_config["horizontal_aperture"] = horizontal_aperture + load_config["clipping_range"] = clipping_range + load_config["viewport_name"] = viewport_name + + # Create variables that will be filled in later at runtime + self._viewport = None # Viewport from which to grab data + self._annotators = None + self._render_product = None + self._image_height = image_height # used when viewport is not created + self._image_width = image_width # used when viewport is not created + + assert {key for key in self.raw_sensor_types.keys() if key != "camera_params"} == set( + self.all_modalities + ), "VisionSensor.RAW_SENSOR_TYPES must have the same keys as VisionSensor.ALL_MODALITIES!" + + if modalities == "all": + modalities = self.all_modalities + else: + modalities = set([modalities]) if isinstance(modalities, str) else set(modalities) + + # 1) seg_instance and seg_instance_id require seg_semantic to be enabled (for rendering particle systems) + # 2) bounding box observations require seg_semantic to be enabled (for remapping bounding box semantic IDs) + semantic_dependent_modalities = {"seg_instance", "seg_instance_id", "bbox_2d_loose", "bbox_2d_tight", "bbox_3d"} + # if any of the semantic dependent modalities are enabled, then seg_semantic must be enabled + if semantic_dependent_modalities.intersection(modalities) and "seg_semantic" not in modalities: + modalities.add("seg_semantic") + + # Run super method + super().__init__( + relative_prim_path=relative_prim_path, + name=name, + modalities=modalities, + enabled=enabled, + noise=noise, + load_config=load_config, + ) + + def _load(self): + # Define a new camera prim at the current stage + # Note that we can't use og.sim.stage here because the vision sensors get loaded first + with og.sim.editing_usd(): + return lazy.pxr.UsdGeom.Camera.Define( + lazy.isaacsim.core.utils.stage.get_current_stage(), self.prim_path + ).GetPrim() + + def _post_load(self): + # run super first + super()._post_load() + + # Add this sensor to the list of global sensors + self.SENSORS[self.prim_path] = self + + resolution = (self._load_config["image_width"], self._load_config["image_height"]) + self._image_width, self._image_height = resolution + with og.sim.editing_usd(): + self._render_product = lazy.omni.replicator.core.create.render_product(self.prim_path, resolution) + + # Create a new viewport to link to this camera or link to a pre-existing one + viewport_name = self._load_config["viewport_name"] + should_create_viewport = viewport_name is not None or not gm.HEADLESS + viewport = None + if should_create_viewport and viewport_name is not None: + vp_names_to_handles = {vp.name: vp for vp in lazy.omni.kit.viewport.window.get_viewport_window_instances()} + assert_valid_key(key=viewport_name, valid_keys=vp_names_to_handles, name="viewport name") + viewport = vp_names_to_handles[viewport_name] + elif should_create_viewport: + with og.sim.editing_usd(): + viewport = lazy.omni.kit.viewport.utility.create_viewport_window() + # Take a render step to make sure the viewport is generated before docking it + og.sim.render() + # Grab the newly created viewport and dock it to the GUI + # The first viewport is always the "main" global camera, and any additional cameras are auxiliary views + # These auxiliary views will be stacked in a single column + # Thus, the first auxiliary viewport should be generated to the left of the main dockspace, and any + # subsequent viewports should be equally spaced according to the number of pre-existing auxiliary views + n_auxiliary_sensors = len(self.SENSORS) - 1 + if n_auxiliary_sensors == 1: + # This is the first auxiliary viewport, dock to the left of the main dockspace + dock_window( + space=lazy.omni.ui.Workspace.get_window("DockSpace"), + name=viewport.name, + location=lazy.omni.ui.DockPosition.LEFT, + ratio=0.25, + ) + elif n_auxiliary_sensors > 1: + # This is any additional auxiliary viewports, dock equally-spaced in the auxiliary column + # We also need to re-dock any prior viewports! + for i in range(2, n_auxiliary_sensors + 1): + dock_window( + space=lazy.omni.ui.Workspace.get_window(f"Viewport {i - 1}"), + name=f"Viewport {i}", + location=lazy.omni.ui.DockPosition.BOTTOM, + ratio=(1 + n_auxiliary_sensors - i) / (2 + n_auxiliary_sensors - i), + ) + + self._viewport = viewport + if self._viewport is not None: + # Link the camera and viewport together + self._viewport.viewport_api.set_active_camera(self.prim_path) + + # Requires 4 render updates to propagate changes + for i in range(4): + og.sim.render() + + # Set the viewer size (requires taking one render step afterwards) + self._viewport.viewport_api.set_texture_resolution(resolution) + + # Also update relevant camera params from load config + self.focal_length = self._load_config["focal_length"] + self.focus_distance = self._load_config["focus_distance"] + self.fstop = self._load_config["fstop"] + self.horizontal_aperture = self._load_config["horizontal_aperture"] + self.clipping_range = self._load_config["clipping_range"] + + # Requires 4 render updates to propagate changes + for i in range(4): + og.sim.render() + + def _initialize(self): + # Run super first + super()._initialize() + + self._annotators = {modality: None for modality in self._modalities} + + # Initialize sensors + self.initialize_sensors(names=self._modalities) + for _ in range(4): + og.sim.render() + + def initialize_sensors(self, names): + """Initializes a raw sensor in the simulation. + + Args: + names (str or list of str): Name of the raw sensor(s) to initialize. + If they are not part of self.raw_sensor_types' keys, we will simply pass over them + """ + names = {names} if isinstance(names, str) else set(names) + for name in names: + self._add_modality_to_backend(modality=name) + + def _get_obs(self): + # Make sure we're initialized + assert self.initialized, "Cannot grab vision observations without first initializing this VisionSensor!" + + # Run super first to grab any upstream obs + obs, info = super()._get_obs() + + # Reorder modalities to ensure that seg_semantic is always ran before seg_instance or seg_instance_id + if "seg_semantic" in self._modalities: + reordered_modalities = ["seg_semantic"] + [ + modality for modality in self._modalities if modality != "seg_semantic" + ] + else: + reordered_modalities = self._modalities + + for modality in reordered_modalities: + raw_obs = self._annotators[modality].get_data(device=og.sim.device) + + if modality == "pointcloud": + # Pointcloud is a special case where we need to concatenate the point xyz coordinates with the rgb values + # Note: rgb values are in the range of [0, 255], xyz is in world frame + concatenated = np.concatenate([raw_obs["pointRgb"][:, :3], raw_obs["data"]], axis=1) + # Pad to match gym space dimensions (self.image_height * self.image_width) + target_rows = self.image_height * self.image_width + if concatenated.shape[0] < target_rows: + pad_width = ((0, target_rows - concatenated.shape[0]), (0, 0)) + obs[modality] = np.pad(concatenated, pad_width, mode="constant", constant_values=0) + else: + obs[modality] = concatenated + else: + # Obs is either a dictionary of {"data":, ..., "info": ...} or a direct array + obs[modality] = raw_obs["data"] if isinstance(raw_obs, dict) else raw_obs + + if og.sim.device == "cpu": + obs[modality] = self._preprocess_cpu_obs(obs[modality], modality) + elif "cuda" in og.sim.device: + obs[modality] = self._preprocess_gpu_obs(obs[modality], modality) + else: + raise ValueError(f"Unsupported device {og.sim.device}") + + if "seg_" in modality or "bbox_" in modality: + self._remap_modality(modality, obs, info, raw_obs) + return obs, info + + def _preprocess_cpu_obs(self, obs, modality): + # All segmentation modalities return uint32 numpy arrays on cpu, but PyTorch doesn't support it + if "seg_" in modality: + obs = obs.astype(NumpyTypes.INT64) # Convert to int64 first to avoid overflow + return th.from_numpy(obs) if "bbox_" not in modality else obs + + def _preprocess_gpu_obs(self, obs, modality): + # All segmentation modalities return uint32 warp arrays on gpu, but PyTorch doesn't support it + if "seg_" in modality: + obs = obs.view(lazy.warp.int32) + return lazy.warp.to_torch(obs) if "bbox_" not in modality else obs + + def _remap_modality(self, modality, obs, info, raw_obs): + id_to_labels = raw_obs["info"]["idToLabels"] + + if modality == "seg_semantic": + obs[modality], info[modality] = self._remap_semantic_segmentation(obs[modality], id_to_labels) + elif modality in ["seg_instance", "seg_instance_id"]: + obs[modality], info[modality] = self._remap_instance_segmentation( + obs[modality], + id_to_labels, + id=(modality == "seg_instance_id"), + ) + elif "bbox" in modality: + obs[modality], info[modality] = self._remap_bounding_box_semantic_ids(obs[modality], id_to_labels) + else: + raise ValueError(f"Unsupported modality {modality}") + + def _preprocess_semantic_labels(self, id_to_labels): + """ + Preprocess the semantic labels to feed into the remapper. + + Args: + id_to_labels (dict): Dictionary of semantic IDs to class labels + Returns: + dict: Preprocessed dictionary of semantic IDs to class labels + """ + replicator_mapping = {} + for key, val in id_to_labels.items(): + key = int(key) + replicator_mapping[key] = val["class"].lower() + if "," in replicator_mapping[key]: + # If there are multiple class names, grab the one that is a registered system + # This happens with MacroVisual particles, e.g. {"11": {"class": "breakfast_table,stain"}} + categories = [cat for cat in replicator_mapping[key].split(",") if cat in get_all_system_names()] + assert ( + len(categories) == 1 + ), "There should be exactly one category that belongs to scene.system_registry" + replicator_mapping[key] = categories[0] + + assert ( + replicator_mapping[key] in semantic_class_id_to_name().values() + ), f"Class {val['class']} does not exist in the semantic class name to id mapping!" + return replicator_mapping + + def _remap_semantic_segmentation(self, img, id_to_labels): + """ + Remap the semantic segmentation image to the class IDs defined in semantic_class_name_to_id(). + Also, correct the id_to_labels input with the labels from semantic_class_name_to_id() and return it. + + Args: + img (th.Tensor): Semantic segmentation image to remap + id_to_labels (dict): Dictionary of semantic IDs to class labels + Returns: + th.Tensor: Remapped semantic segmentation image + dict: Corrected id_to_labels dictionary + """ + replicator_mapping = self._preprocess_semantic_labels(id_to_labels) + + image_keys = th.unique(img) + if not set(image_keys.tolist()).issubset(set(replicator_mapping.keys())): + log.debug( + "Some semantic IDs in the image are not in the id_to_labels mapping. This is a known issue with the replicator and should only affect a few pixels. These pixels will be marked as unlabelled." + ) + + return VisionSensor.SEMANTIC_REMAPPER.remap(replicator_mapping, semantic_class_id_to_name(), img, image_keys) + + def _remap_instance_segmentation(self, img, id_to_labels, id=False): + """ + Remap the instance segmentation image to our own instance IDs. + Also, correct the id_to_labels input with our new labels and return it. + + Args: + img (th.tensor): Instance segmentation image to remap + id_to_labels (dict): Dictionary of instance IDs to class labels + id (bool): Whether to remap for instance ID segmentation + Returns: + th.tensor: Remapped instance segmentation image + dict: Corrected id_to_labels dictionary + """ + # Sometimes 0 and 1 show up in the image, but they are not in the id_to_labels mapping + id_to_labels.update({"0": "BACKGROUND"}) + if not id: + id_to_labels.update({"1": "UNLABELLED"}) + + # Preprocess id_to_labels and update instance registry + replicator_mapping = {} + for key, value in id_to_labels.items(): + key = int(key) + if value in ["BACKGROUND", "UNLABELLED"]: + value = value.lower() + elif "/" in value: + # Instance Segmentation + if not id: + # Case 1: This is the ground plane + if og.sim.floor_plane is not None and value == og.sim.floor_plane.prim_path: + value = "groundPlane" + else: + # Case 2: Check if this is an object, e.g. '/World/scene_0/breakfast_table', '/World/scene_0/dishtowel' + obj = None + if self.scene is not None: + # If this is a camera within a scene, we check the object registry of the scene + obj = self.scene.object_registry("prim_path", value) + else: + # If this is the viewer camera, we check each object registry + for scene in og.sim.scenes: + obj = scene.object_registry("prim_path", value) + if obj: + break + if obj is not None: + # This is an object, so we remap the instance segmentation label to the object name + value = obj.name + # Case 3: Check if this is a particle system + else: + # This is a particle system + path_split = value.split("/") + prim_name = path_split[-1] + system_matched = False + # Case 3.1: Filter out macro particle systems + # e.g. '/World/scene_0/diced__apple/particles/diced__appleParticle0', '/World/scene_0/breakfast_table/base_link/stainParticle0' + if "Particle" in prim_name: + macro_system_name = prim_name.split("Particle")[0] + if macro_system_name in get_all_system_names(): + system_matched = True + value = macro_system_name + # Case 3.2: Filter out micro particle systems + # e.g. '/World/scene_0/water/waterInstancer0/prototype0_1', '/World/scene_0/white_rice/white_riceInstancer0/prototype0' + else: + # If anything in path_split has "Instancer" in it, we know it's a micro particle system + for path in path_split: + if "Instancer" in path: + # This is a micro particle system + system_matched = True + value = path.split("Instancer")[0] + break + # Case 4: If nothing matched, we label it as unlabelled + if not system_matched: + value = "unlabelled" + # Instance ID Segmentation + else: + # The only thing we do here is for micro particle system, we clean its name + # e.g. a raw path looks like '/World/scene_0/water/waterInstancer0/prototype0.proto0_prototype0_id0' + # we clean it to '/World/scene_0/water/waterInstancer0/prototype0' + # Case 1: This is a micro particle system + # e.g. '/World/scene_0/water/waterInstancer0/prototype0.proto0_prototype0_id0', '/World/scene_0/white_rice/white_riceInstancer0/prototype0.proto0_prototype0_id0' + if "Instancer" in value and "." in value: + # This is a micro particle system + value = value[: value.rfind(".")] + # Case 2: For everything else, we keep the name as is + """ + e.g. + { + '54': '/World/scene_0/water/waterInstancer0/prototype0.proto0_prototype0_id0', + '60': '/World/scene_0/water/waterInstancer0/prototype0.proto0_prototype0_id0', + '30': '/World/scene_0/breakfast_table/base_link/stainParticle1', + '27': '/World/scene_0/diced__apple/particles/diced__appleParticle0', + '58': '/World/scene_0/white_rice/white_riceInstancer0/prototype0.proto0_prototype0_id0', + '64': '/World/scene_0/white_rice/white_riceInstancer0/prototype0.proto0_prototype0_id0', + '40': '/World/scene_0/diced__apple/particles/diced__appleParticle1', + '48': '/World/scene_0/breakfast_table/base_link/stainParticle0', + '1': '/World/ground_plane/geom', + '19': '/World/scene_0/dishtowel/base_link_cloth', + '6': '/World/scene_0/breakfast_table/base_link/visuals' + } + """ + else: + # TODO: This is a temporary fix unexpected labels e.g. INVALID introduced in new Isaac Sim versions + value = "unlabelled" + + self._register_instance(value, id=id) + replicator_mapping[key] = value + + # This is a temporary fix for the problem where some small number of pixels show up in the image, but not in the info (id_to_labels). + # We identify these values and mark them as unlabelled. + image_keys = th.unique(img) + for key in image_keys: + if str(key.item()) not in id_to_labels: + value = "unlabelled" + self._register_instance(value, id=id) + replicator_mapping[key.item()] = value + + registry = VisionSensor.INSTANCE_ID_REGISTRY if id else VisionSensor.INSTANCE_REGISTRY + remapper = VisionSensor.INSTANCE_ID_REMAPPER if id else VisionSensor.INSTANCE_REMAPPER + + if not set(image_keys.tolist()).issubset(set(replicator_mapping.keys())): + log.warning( + "Some instance IDs in the image are not in the id_to_labels mapping. This is a known issue with the replicator and should only affect a few pixels. These pixels will be marked as unlabelled." + ) + + return remapper.remap(replicator_mapping, registry, img, image_keys) + + def _register_instance(self, instance_name, id=False): + registry = VisionSensor.INSTANCE_ID_REGISTRY if id else VisionSensor.INSTANCE_REGISTRY + if instance_name not in registry.values(): + registry[len(registry)] = instance_name + + def _remap_bounding_box_semantic_ids(self, bboxes, id_to_labels): + """ + Remap the semantic IDs of the bounding boxes to our own semantic IDs. + + Args: + bboxes (list of dict): List of bounding boxes to remap + id_to_labels (dict): Dictionary of semantic IDs to class labels + Returns: + list of dict: Remapped list of bounding boxes + dict: Remapped id_to_labels dictionary + """ + replicator_mapping = self._preprocess_semantic_labels(id_to_labels) + for bbox in bboxes: + bbox["semanticId"] = semantic_class_name_to_id()[replicator_mapping[bbox["semanticId"]]] + # Replicator returns each box as a numpy.void; we convert them to tuples here + bboxes = [box.tolist() for box in bboxes] + info = {semantic_class_name_to_id()[val]: val for val in replicator_mapping.values()} + return bboxes, info + + def add_modality(self, modality): + # Check if we already have this modality (if so, no need to initialize it explicitly) + should_initialize = modality not in self._modalities + + # Run super + super().add_modality(modality=modality) + + # We also need to initialize this new modality + if should_initialize: + self.initialize_sensors(names=modality) + + def remove_modality(self, modality): + # Check if we don't have this modality (if not, no need to remove it explicitly) + should_remove = modality in self._modalities + + # Run super + super().remove_modality(modality=modality) + + if should_remove: + self._remove_modality_from_backend(modality=modality) + + def _add_modality_to_backend(self, modality): + """ + Helper function to add specified modality @modality to the omniverse Replicator backend so that its data is + generated during get_obs() + Args: + modality (str): Name of the modality to add to the Replicator backend + """ + if self._annotators.get(modality, None) is None: + with og.sim.editing_usd(): + self._annotators[modality] = lazy.omni.replicator.core.AnnotatorRegistry.get_annotator( + self.raw_sensor_types[modality] + ) + self._annotators[modality].attach([self._render_product]) + + def _remove_modality_from_backend(self, modality): + """ + Helper function to remove specified modality @modality from the omniverse Replicator backend so that its data is + no longer generated during get_obs() + Args: + modality (str): Name of the modality to remove from the Replicator backend + """ + if self._annotators.get(modality, None) is not None: + # Passing an explicit list is bugged -- see omni source code + # So we only pass in the product directly, which gets post-processed correctly + with og.sim.editing_usd(): + try: + self._annotators[modality].detach(self._render_product) + except TypeError: + # omni.syntheticdata's node deactivation walk is fragile once a tiled render product + # has existed in the session: cached graph node handles become invalid and detach raises + # "Invalid NodeObj object". The annotator's nodes are already gone at that point, so we + # just drop our reference (teardown-only; nothing further to clean up) + log.warning(f"Failed to cleanly detach annotator for modality {modality}; skipping") + self._annotators[modality] = None + + def remove(self): + # Remove from global sensors dictionary + self.SENSORS.pop(self.prim_path, None) + + # Remove all modalities + for modality in tuple(self.modalities): + self.remove_modality(modality) + + # Destroy the render product + with og.sim.editing_usd(): + self._render_product.destroy() + + # Remove the viewport if it exists. + if self._viewport is not None: + # Remove the viewport if it's not the main viewport + if self._viewport.name != "Viewport": + with og.sim.editing_usd(): + self._viewport.destroy() + else: + # We're deleting our camera, so set the normal viewport camera to the default /Perspective camera + self.active_camera_path = "/OmniverseKit_Persp" + + # Run super + super().remove() + + @property + def render_product(self): + """ + Returns: + HydraTexture: Render product associated with this viewport and camera + """ + return self._render_product + + @property + def camera_parameters(self): + """ + Returns a dictionary of keyword-mapped relevant intrinsic and extrinsic camera parameters for this vision sensor. + The returned dictionary includes the following keys and their corresponding data types: + + - "cameraAperture": th.tensor (float32) - Camera aperture dimensions. + - "cameraApertureOffset": th.tensor (float32) - Offset of the camera aperture. + - "cameraFisheyeLensP": th.tensor (float32) - Fisheye lens P parameter. + - "cameraFisheyeLensS": th.tensor (float32) - Fisheye lens S parameter. + - "cameraFisheyeMaxFOV": float - Maximum field of view for fisheye lens. + - "cameraFisheyeNominalHeight": int - Nominal height for fisheye lens. + - "cameraFisheyeNominalWidth": int - Nominal width for fisheye lens. + - "cameraFisheyeOpticalCentre": th.tensor (float32) - Optical center for fisheye lens. + - "cameraFisheyePolynomial": th.tensor (float32) - Polynomial parameters for fisheye lens distortion. + - "cameraFocalLength": float - Focal length of the camera. + - "cameraFocusDistance": float - Focus distance of the camera. + - "cameraFStop": float - F-stop value of the camera. + - "cameraModel": str - Camera model identifier. + - "cameraNearFar": th.tensor (float32) - Near and far plane distances. + - "cameraProjection": th.tensor (float32) - Camera projection matrix. + - "cameraViewTransform": th.tensor (float32) - Camera view transformation matrix. + - "metersPerSceneUnit": float - Scale factor from scene units to meters. + - "renderProductResolution": th.tensor (int32) - Resolution of the rendered product. + + Returns: + dict: Keyword-mapped relevant intrinsic and extrinsic camera parameters for this vision sensor. + """ + # Add the camera params modality if it doesn't already exist + if "camera_params" not in self._annotators: + self.initialize_sensors(names="camera_params") + # Requires 4 render updates for camera params annotator to become active + for _ in range(4): + og.sim.render() + # Grab and return the parameters + return self._annotators["camera_params"].get_data() + + @property + def viewer_visibility(self): + """ + Returns: + bool: Whether the viewer is visible or not + """ + return False if self._viewport is None else self._viewport.visible + + @viewer_visibility.setter + def viewer_visibility(self, visible): + """ + Sets whether the viewer should be visible or not in the Omni UI + + Args: + visible (bool): Whether the viewer should be visible or not + """ + if self._viewport is None: + return + self._viewport.visible = visible + # Requires 1 render update to propagate changes + og.sim.render() + + @property + def image_height(self): + """ + Returns: + int: Image height of this sensor, in pixels + """ + return self._image_height if self._viewport is None else self._viewport.viewport_api.get_texture_resolution()[1] + + @image_height.setter + def image_height(self, height): + """ + Sets the image height @height for this sensor + + Args: + height (int): Image height of this sensor, in pixels + """ + self._image_height = height + width = self._image_width + if self._viewport is not None: + width, _ = self._viewport.viewport_api.get_texture_resolution() + self._viewport.viewport_api.set_texture_resolution((width, height)) + + # Also update render product and update all annotators + with og.sim.editing_usd(): + for annotator in self._annotators.values(): + annotator.detach([self._render_product.path]) + + self._render_product.destroy() + self._render_product = lazy.omni.replicator.core.create.render_product( + self.prim_path, (width, height), force_new=True + ) + + for annotator in self._annotators.values(): + annotator.attach([self._render_product]) + + # Requires 4 updates to propagate changes + for i in range(4): + og.sim.render() + + @property + def image_width(self): + """ + Returns: + int: Image width of this sensor, in pixels + """ + return self._image_width if self._viewport is None else self._viewport.viewport_api.get_texture_resolution()[0] + + @image_width.setter + def image_width(self, width): + """ + Sets the image width @width for this sensor + + Args: + width (int): Image width of this sensor, in pixels + """ + self._image_width = width + height = self._image_height + if self._viewport is not None: + _, height = self._viewport.viewport_api.get_texture_resolution() + self._viewport.viewport_api.set_texture_resolution((width, height)) + + # Also update render product and update all annotators + with og.sim.editing_usd(): + for annotator in self._annotators.values(): + annotator.detach([self._render_product.path]) + + self._render_product.destroy() + self._render_product = lazy.omni.replicator.core.create.render_product( + self.prim_path, (width, height), force_new=True + ) + + for annotator in self._annotators.values(): + annotator.attach([self._render_product]) + + # Requires 4 updates to propagate changes + for i in range(4): + og.sim.render() + + @property + def clipping_range(self): + """ + Returns: + 2-tuple: [min, max] value of the sensor's clipping range, in meters + """ + return th.tensor(self.get_attribute("clippingRange")) + + @clipping_range.setter + def clipping_range(self, limits): + """ + Sets the clipping range @limits for this sensor + + Args: + limits (2-tuple): [min, max] value of the sensor's clipping range, in meters + """ + self.set_attribute(attr="clippingRange", val=lazy.pxr.Gf.Vec2f(*limits)) + # In order for sensor changes to propagate, we must toggle its visibility + self.visible = False + # A single update step has to happen here before we toggle visibility for changes to propagate + og.sim.render() + self.visible = True + + @property + def horizontal_aperture(self): + """ + Returns: + float: horizontal aperture of this sensor, in mm + """ + return self.get_attribute("horizontalAperture") + + @horizontal_aperture.setter + def horizontal_aperture(self, length): + """ + Sets the focal length @length for this sensor + + Args: + length (float): horizontal aperture of this sensor, in meters + """ + self.set_attribute("horizontalAperture", length) + + @property + def focal_length(self): + """ + Returns: + float: focal length of this sensor, in mm + """ + return self.get_attribute("focalLength") + + @focal_length.setter + def focal_length(self, length): + """ + Sets the focal length @length for this sensor + + Args: + length (float): focal length of this sensor, in mm + """ + self.set_attribute("focalLength", length) + + @property + def focus_distance(self): + """ + Returns: + float: focus distance of this sensor, in mm + """ + return self.get_attribute("focusDistance") + + @focus_distance.setter + def focus_distance(self, distance): + """ + Sets the focus distance @distance for this sensor + + Args: + distance (float): focus distance of this sensor, in mm + """ + self.set_attribute("focusDistance", distance) + + @property + def fstop(self): + """ + Returns: + float: fstop of this sensor + """ + return self.get_attribute("fStop") + + @fstop.setter + def fstop(self, val): + """ + Sets the fstop for this sensor + + Args: + val (float): fstop of this sensor + """ + self.set_attribute("fStop", val) + + @property + def active_camera_path(self): + """ + Returns: + str: prim path of the active camera attached to this vision sensor + """ + return None if self._viewport is None else self._viewport.viewport_api.get_active_camera().pathString + + @active_camera_path.setter + def active_camera_path(self, path): + """ + Sets the active camera prim path @path for this vision sensor. Note: Must be a valid Camera prim path + + Args: + path (str): Prim path to the camera that will be attached to this vision sensor + """ + if self._viewport is None: + raise RuntimeError( + "Cannot set active_camera_path because this sensor has no viewport. " + "Set gm.HEADLESS=False to enable viewport textures." + ) + self._viewport.viewport_api.set_active_camera(path) + # Requires 6 updates to propagate changes + for i in range(6): + og.sim.render() + + @property + def intrinsic_matrix(self): + """ + Returns: + n-array: (3, 3) camera intrinsic matrix. Transforming point p (x,y,z) in the camera frame via K * p will + produce p' (x', y', w) - the point in the image plane. To get pixel coordiantes, divide x' and y' by w + """ + P = self.camera_parameters["cameraProjection"].reshape(4, 4) + width, height = self.camera_parameters["renderProductResolution"] + fx = P[0, 0] * width / 2.0 + fy = P[1, 1] * height / 2.0 + cx = (1.0 - P[0, 2]) * width / 2.0 + cy = (1.0 - P[1, 2]) * height / 2.0 + K = th.tensor([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) + + # Explicitly sanity check for null values here + degen_mat = th.zeros(3, 3) + degen_mat[2, 2] = 1.0 + assert not th.all(K == degen_mat).item(), f"intrinsic matrix for sensor: {self.name} is degenerate!" + + return K + + @property + def _obs_space_mapping(self): + # Generate the complex space types for special modalities: + # {"bbox_2d_tight", "bbox_2d_loose", "bbox_3d"} + bbox_3d_space = gym.spaces.Sequence( + space=gym.spaces.Tuple( + ( + gym.spaces.Box(low=0, high=MAX_CLASS_COUNT, shape=(), dtype=NumpyTypes.UINT32), # semanticId + gym.spaces.Box(low=-float("inf"), high=float("inf"), shape=(), dtype=NumpyTypes.FLOAT32), # x_min + gym.spaces.Box(low=-float("inf"), high=float("inf"), shape=(), dtype=NumpyTypes.FLOAT32), # y_min + gym.spaces.Box(low=-float("inf"), high=float("inf"), shape=(), dtype=NumpyTypes.FLOAT32), # z_min + gym.spaces.Box(low=-float("inf"), high=float("inf"), shape=(), dtype=NumpyTypes.FLOAT32), # x_max + gym.spaces.Box(low=-float("inf"), high=float("inf"), shape=(), dtype=NumpyTypes.FLOAT32), # y_max + gym.spaces.Box(low=-float("inf"), high=float("inf"), shape=(), dtype=NumpyTypes.FLOAT32), # z_max + gym.spaces.Box( + low=-float("inf"), high=float("inf"), shape=(4, 4), dtype=NumpyTypes.FLOAT32 + ), # transform + gym.spaces.Box(low=-1.0, high=1.0, shape=(), dtype=NumpyTypes.FLOAT32), # occlusion ratio + ) + ) + ) + + bbox_2d_space = gym.spaces.Sequence( + space=gym.spaces.Tuple( + ( + gym.spaces.Box(low=0, high=MAX_CLASS_COUNT, shape=(), dtype=NumpyTypes.UINT32), # semanticId + gym.spaces.Box(low=0, high=MAX_VIEWER_SIZE, shape=(), dtype=NumpyTypes.INT32), # x_min + gym.spaces.Box(low=0, high=MAX_VIEWER_SIZE, shape=(), dtype=NumpyTypes.INT32), # y_min + gym.spaces.Box(low=0, high=MAX_VIEWER_SIZE, shape=(), dtype=NumpyTypes.INT32), # x_max + gym.spaces.Box(low=0, high=MAX_VIEWER_SIZE, shape=(), dtype=NumpyTypes.INT32), # y_max + gym.spaces.Box(low=-1.0, high=1.0, shape=(), dtype=NumpyTypes.FLOAT32), # occlusion ratio + ) + ) + ) + + obs_space_mapping = dict( + rgb=((self.image_height, self.image_width, 4), 0, 255, NumpyTypes.UINT8), + depth=((self.image_height, self.image_width), 0.0, float("inf"), NumpyTypes.FLOAT32), + depth_linear=((self.image_height, self.image_width), 0.0, float("inf"), NumpyTypes.FLOAT32), + normal=((self.image_height, self.image_width, 4), -1.0, 1.0, NumpyTypes.FLOAT32), + seg_semantic=((self.image_height, self.image_width), 0, MAX_CLASS_COUNT, NumpyTypes.UINT32), + seg_instance=((self.image_height, self.image_width), 0, MAX_INSTANCE_COUNT, NumpyTypes.UINT32), + seg_instance_id=((self.image_height, self.image_width), 0, MAX_INSTANCE_COUNT, NumpyTypes.UINT32), + flow=((self.image_height, self.image_width, 4), -float("inf"), float("inf"), NumpyTypes.FLOAT32), + bbox_2d_tight=bbox_2d_space, + bbox_2d_loose=bbox_2d_space, + bbox_3d=bbox_3d_space, + pointcloud=((self.image_height * self.image_width, 6), -float("inf"), float("inf"), NumpyTypes.FLOAT32), + ) + + return obs_space_mapping + + @classmethod + def clear(cls): + """ + Clear all the class-wide variables. + """ + # Remove all sensors + for sensor in tuple(cls.SENSORS.values()): + sensor.remove() + + # Render to update + og.sim.render() + + cls.SEMANTIC_REMAPPER = Remapper() + cls.INSTANCE_REMAPPER = Remapper() + cls.INSTANCE_ID_REMAPPER = Remapper() + cls.SENSORS = dict() + cls.KNOWN_SEMANTIC_IDS = set() + cls.KEY_ARRAY = None + cls.INSTANCE_REGISTRY = {0: "background", 1: "unlabelled"} + cls.INSTANCE_ID_REGISTRY = {0: "background"} + + @classproperty + def all_modalities(cls): + return {modality for modality in cls.ALL_MODALITIES if modality != "camera_params"} + + @classproperty + def raw_sensor_types(cls): + return cls.RAW_SENSOR_TYPES.copy() + + @classproperty + def no_noise_modalities(cls): + # bounding boxes and camera state should not have noise + return {"bbox_2d_tight", "bbox_2d_loose", "bbox_3d"} diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/simulator.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a5c4cce56f1972b90def354d6ec647f49177a69d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/simulator.py @@ -0,0 +1,2258 @@ +import contextlib +import functools +import json +import logging +import math +import os +import shutil +import signal +import socket +import sys +import tempfile +import traceback +from contextlib import nullcontext +from pathlib import Path +from omnigibson.utils.profiling_utils import Profiler + +import torch as th +import warp as wp + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.macros import create_module_macros, gm +from omnigibson.object_states.factory import get_states_by_dependency_order +from omnigibson.object_states.joint_break_subscribed_state_mixin import JointBreakSubscribedStateMixin +from omnigibson.object_states.tensorized_state import TensorizedState +from omnigibson.object_states.update_state_mixin import UpdateStateMixin +from omnigibson.objects.light_object import LightObject +from omnigibson.objects.usd_object import USDObject +from omnigibson.prims import XFormPrim +from omnigibson.prims.material_prim import MaterialPrim +from omnigibson.scenes import Scene +from omnigibson.sensors.tiled_sensor import TiledVisionSensor +from omnigibson.sensors.vision_sensor import VisionSensor +from omnigibson.systems.macro_particle_system import MacroPhysicalParticleSystem +from omnigibson.utils.asset_utils import ensure_omnigibson_robot_assets_version, get_dataset_path +from omnigibson.utils.constants import LightingMode +from omnigibson.utils.python_utils import Serializable +from omnigibson.utils.python_utils import clear as clear_python_utils +from omnigibson.utils.python_utils import create_object_from_init_info, recursively_convert_to_torch +from omnigibson.utils.ui_utils import ( + CameraMover, + create_module_logger, + disclaimer, + logo_small, + print_icon, + print_logo, + suppress_omni_log, +) +from omnigibson.utils.vision_utils import add_semantic_label +from omnigibson.utils.usd_utils import ( + ArticulatedObjectViewAPI, + CollisionAPI, + ControllableObjectViewAPI, + RigidBodyViewAPI, + RigidContactAPI, + clear as clear_usd_utils, + triangularize_mesh, +) +from omnigibson.controllers import ControllerView + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.DEFAULT_VIEWER_CAMERA_POS = (-0.201028, -2.72566, 1.0654) +m.DEFAULT_VIEWER_CAMERA_QUAT = (0.68196617, -0.00155408, -0.00166678, 0.73138017) + +m.OBJECT_GRAVEYARD_POS = (100.0, 100.0, 100.0) + +m.SCENE_MARGIN = 10.0 +m.INITIAL_SCENE_PRIM_Z_OFFSET = -100.0 + +m.KIT_FILES = { + (5, 1, 0): "omnigibson_5_1_0.kit", +} + + +def with_profiler(name): + def decorator(fn): + @functools.wraps(fn) + def wrapper(self, *args, **kwargs): + profiler = getattr(self, name) + profiler.enable() + try: + return fn(self, *args, **kwargs) + finally: + profiler.disable() + + return wrapper + + return decorator + + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.DEFAULT_VIEWER_CAMERA_POS = (-0.201028, -2.72566, 1.0654) +m.DEFAULT_VIEWER_CAMERA_QUAT = (0.68196617, -0.00155408, -0.00166678, 0.73138017) + +m.OBJECT_GRAVEYARD_POS = (100.0, 100.0, 100.0) + +m.SCENE_MARGIN = 10.0 +m.INITIAL_SCENE_PRIM_Z_OFFSET = -100.0 + +m.KIT_FILES = { + (5, 1, 0): "omnigibson_5_1_0.kit", +} + + +# Helper functions for starting omnigibson +def print_save_usd_warning(_): + log.warning("Exporting individual USDs has been disabled in OG due to copyrights.") + + +class SuppressLogsUntilError: + """ + Suppress stdout/stderr logs until an error occurs, at which point dump everything. + """ + + def __init__(self, _): + self._old_stdout = None + self._old_stderr = None + self._tmpfile = None + self._tmppath = None + self._running = False + + def __enter__(self): + # Temp file to buffer logs + self._tmpfile = tempfile.NamedTemporaryFile(delete=False, mode="w+") + self._tmppath = self._tmpfile.name + self._tmpfile.close() + + # Save original fds + sys.stdout.flush() + sys.stderr.flush() + self._old_stdout = os.dup(1) + self._old_stderr = os.dup(2) + + # Redirect stdout/stderr → temp file + fd = os.open(self._tmppath, os.O_WRONLY | os.O_APPEND) + os.dup2(fd, 1) + os.dup2(fd, 2) + os.close(fd) + + # Start background reader + self._running = True + + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + # Stop background reader + self._running = False + + # Restore stdout/stderr + sys.stdout.flush() + sys.stderr.flush() + os.dup2(self._old_stdout, 1) + os.dup2(self._old_stderr, 2) + os.close(self._old_stdout) + os.close(self._old_stderr) + + # On error → dump everything + traceback + if exc_type is not None: + print("\n=== Isaac Sim logs (dump on error) ===\n") + with open(self._tmppath, "r") as f: + print(f.read()) + print("=== End of Isaac Sim logs ===\n") + + print("Python traceback:\n") + traceback.print_exception(exc_type, exc_val, exc_tb) + + # Cleanup + try: + os.remove(self._tmppath) + except OSError: + pass + + return False # let exception propagate + + +def _launch_app(): + log.setLevel(logging.DEBUG if gm.DEBUG else logging.INFO) + + # ensure that the omnigibson robot assets are up to date + ensure_omnigibson_robot_assets_version() + + log.info(f"{'-' * 5} Starting {logo_small()}. This will take 10-30 seconds... {'-' * 5}") + + # If multi_gpu is used, og.sim.render() will cause a segfault when called during on_contact callbacks, + # e.g. when an attachment joint is being created due to contacts (create_joint calls og.sim.render() internally). + gpu_id = None if gm.GPU_ID is None else int(gm.GPU_ID) + config_kwargs = {"headless": gm.HEADLESS or bool(gm.REMOTE_STREAMING), "multi_gpu": False} + if gpu_id is not None: + config_kwargs["active_gpu"] = gpu_id + config_kwargs["physics_gpu"] = gpu_id + + # Clear the argv - Isaac Sim unfortunately reads from it directly, so we need to clear it to avoid issues. + # Otherwise it will inherit the arguments of the entrypoint script. + _saved_argv = sys.argv[:] + try: + sys.argv = [ + _saved_argv[0] + ] # The script filename needs to be included - otherwise the first arg will get skipped. + + # Omni's logging is super annoying and overly verbose, so suppress it by modifying the logging levels + if not gm.DEBUG: + import warnings + + try: + from numba.core.errors import NumbaPerformanceWarning + + warnings.simplefilter("ignore", category=NumbaPerformanceWarning) + except ImportError: + pass + + # Find a more elegant way to prune omni logging + if gm.NO_OMNI_LOGS: + sys.argv.append("--/log/level=error") + sys.argv.append("--/log/fileLogLevel=error") + sys.argv.append("--/log/outputStreamLevel=error") + + # Try to import the isaacsim module that only shows up in Isaac Sim 4.0.0. This ensures that + # if we are using the pip installed version, all the ISAAC_PATH etc. env vars are set correctly. + # On the regular omniverse launcher version this should not have any impact. + try: + os.environ["OMNI_KIT_ACCEPT_EULA"] = "YES" + import isaacsim # noqa: F401 + except ImportError: + pass + + # First obtain the Isaac Sim version + isaac_path = os.environ["ISAAC_PATH"] + version_file_path = os.path.join(isaac_path, "VERSION") + assert os.path.exists(version_file_path), f"Isaac Sim version file not found at {version_file_path}" + with open(version_file_path, "r") as file: + version_content = file.read().strip() + isaac_version_str = version_content.split("-")[0] + isaac_version_tuple = tuple(map(int, isaac_version_str.split(".")[:3])) + assert isaac_version_tuple in m.KIT_FILES, f"Isaac Sim version must be one of {list(m.KIT_FILES.keys())}" + kit_file_name = m.KIT_FILES[isaac_version_tuple] + if gm.ENABLE_VR: + kit_file_name = kit_file_name.replace(".kit", "_vr.kit") + + # Copy the OmniGibson kit file and icon file to the Isaac Sim apps directory. This is necessary because the Isaac Sim app + # expects the extensions to be reachable in the parent directory of the kit file. We copy on every launch to + # ensure that the kit file is always up to date. + assert ( + "EXP_PATH" in os.environ + ), "The EXP_PATH variable is not set. Are you in an Isaac Sim installed environment?" + exp_path = os.environ["EXP_PATH"] + kit_file = Path(__file__).parent / kit_file_name + kit_file_target = Path(exp_path) / kit_file_name + icon_file = Path(__file__).parents[2] / "docs" / "assets" / "OmniGibson_logo.png" + icon_file_target = Path(exp_path) / "OmniGibson_logo.png" + + try: + shutil.copyfile(kit_file, kit_file_target) + shutil.copyfile(icon_file, icon_file_target) + except Exception as e: + raise e from ValueError(f"Failed to copy {kit_file_name} or {icon_file.name} to Isaac Sim apps directory.") + + # Set the MDL search path so that our OmniGibsonVrayMtl can be found. + os.environ["MDL_USER_PATH"] = str((Path(__file__).parent / "materials").resolve()) + + launch_context = nullcontext if gm.DEBUG else SuppressLogsUntilError if gm.NO_OMNI_LOGS else suppress_omni_log + + # Prepare the directories where Omniverse will store its appdata (logs, caches, etc.) + local_appdata = Path(gm.APPDATA_PATH) / "local" + local_appdata.mkdir(parents=True, exist_ok=True) + sys.argv.extend(["--portable-root", str(local_appdata)]) + + global_cache_dir = Path(gm.APPDATA_PATH) / "global" / "cache" + global_cache_dir.mkdir(parents=True, exist_ok=True) + sys.argv.append(f"--/app/tokens/omni_global_cache={global_cache_dir}") + + global_data_dir = Path(gm.APPDATA_PATH) / "global" / "data" + global_data_dir.mkdir(parents=True, exist_ok=True) + sys.argv.append(f"--/app/tokens/omni_global_data={str(global_data_dir)}") + + # Persist warp's JIT-compiled kernel cache under gm.APPDATA_PATH so it survives + # across runs (warp's default ~/.cache/warp is per-user/ephemeral on some + # self-hosted CI runners, which means every run pays the full NVRTC JIT cost). + global_warp_cache_dir = Path(gm.APPDATA_PATH) / "global" / "warp_cache" + global_warp_cache_dir.mkdir(parents=True, exist_ok=True) + wp.config.kernel_cache_dir = str(global_warp_cache_dir) + + with launch_context(None): + app = lazy.isaacsim.SimulationApp(config_kwargs, experience=str(kit_file_target.resolve(strict=True))) + finally: + # Always restore the caller's argv, even if Isaac Sim startup raises. + sys.argv = _saved_argv + + # Close the stage so that we can create a new one when a Simulator Instance is created + assert lazy.isaacsim.core.utils.stage.close_stage() + + # Omni overrides the global logger to be DEBUG, which is very annoying, so we re-override it to the default WARN + # TODO: Remove this once omniverse fixes it + logging.getLogger().setLevel(logging.WARNING) + + # Default Livestream settings + if gm.REMOTE_STREAMING: + app.set_setting("/app/window/drawMouse", True) + app.set_setting("/app/livestream/proto", "ws") + app.set_setting("/app/livestream/websocket/framerate_limit", 120) + app.set_setting("/ngx/enabled", False) + + # Find our IP address + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.connect(("8.8.8.8", 80)) + ip = s.getsockname()[0] + s.close() + + # Note: Only one livestream extension can be enabled at a time + if gm.REMOTE_STREAMING == "native": + # Enable Native Livestream extension + # Default App: Streaming Client from the Omniverse Launcher + lazy.isaacsim.core.utils.extensions.enable_extension("omni.kit.livestream.native") + print(f"Now streaming on {ip} via Omniverse Streaming Client") + elif gm.REMOTE_STREAMING == "webrtc": + # Enable WebRTC Livestream extension + app.set_setting("/exts/omni.services.transport.server.http/port", gm.HTTP_PORT) + app.set_setting("/app/livestream/port", gm.WEBRTC_PORT) + lazy.isaacsim.core.utils.extensions.enable_extension("omni.services.streamclient.webrtc") + print(f"Now streaming on: http://{ip}:{gm.HTTP_PORT}/streaming/webrtc-client?server={ip}") + else: + raise ValueError( + f"Invalid REMOTE_STREAMING option {gm.REMOTE_STREAMING}. Must be one of None, native, webrtc." + ) + + # If we're headless, suppress all warnings about GLFW + if gm.HEADLESS: + og_log = lazy.omni.log.get_log() + og_log.set_channel_enabled("carb.windowing-glfw.plugin", False, lazy.omni.log.SettingBehavior.OVERRIDE) + + # Globally suppress certain logging modules (unless we're in debug mode) since they produce spurious warnings + if not gm.DEBUG: + og_log = lazy.omni.log.get_log() + for channel in ["omni.hydra.scene_delegate.plugin", "omni.kit.manipulator.prim.model"]: + og_log.set_channel_enabled(channel, False, lazy.omni.log.SettingBehavior.OVERRIDE) + + # Possibly hide windows if in debug mode + hide_window_names = [] + if not gm.RENDER_VIEWER_CAMERA: + hide_window_names.append("Viewport") + if gm.GUI_VIEWPORT_ONLY: + hide_window_names.extend( + [ + "Console", + "Main ToolBar", + "Stage", + "Layer", + "Property", + "Render Settings", + "Content", + "Flow", + "Semantics Schema Editor", + "VR", + "Isaac Sim Assets [Beta]", + ] + ) + + for name in hide_window_names: + window = lazy.omni.ui.Workspace.get_window(name) + if window is not None: + window.visible = False + app.update() + + lazy.omni.kit.widget.stage.context_menu.ContextMenu.save_prim = print_save_usd_warning + + # Let the hotkeys propagate. + app.update() + + # Disable all hotkeys for now. These are not exactly helpful and they cause collisions with + # the OmniGibson-provided hotkeys. + hotkey_registry = lazy.omni.kit.hotkeys.core.get_hotkey_registry() + for hotkey in list(hotkey_registry.get_all_hotkeys()): + hotkey_registry.deregister_hotkey(hotkey) + + # TODO: Automated cleanup in callback doesn't work for some reason. Need to investigate. + shutdown_stream = lazy.omni.kit.app.get_app().get_shutdown_event_stream() + shutdown_stream.create_subscription_to_pop(og.cleanup, name="og_cleanup", order=0) + + # Loading Isaac Sim disables Ctrl+C, so we need to re-enable it + signal.signal(signal.SIGINT, og.shutdown_handler) + + # Set compute backend + import omnigibson.utils.backend_utils as _backend_utils + + _backend_utils._compute_backend.set_methods_from_backend( + _backend_utils._ComputeNumpyBackend if gm.USE_NUMPY_CONTROLLER_BACKEND else _backend_utils._ComputeTorchBackend + ) + + return app + + +def _launch_simulator(*args, **kwargs): + if not og.app: + og.app = _launch_app() + + class Simulator(Serializable): + """ + Simulator class for directly interfacing with the physx physics engine. + + NOTE: This is a monolithic class. + All created Simulator() instances will reference the same underlying Simulator object + + Args: + gravity (float): gravity on z direction. + physics_dt (None or float): dt between physics steps. If None, will use default value + 1 / gm.DEFAULT_PHYSICS_FREQ + rendering_dt (None or float): dt between rendering steps. Note: rendering means rendering a frame of the + current application and not only rendering a frame to the viewports/ cameras. So UI elements of + Isaac Sim will be refreshed with this dt as well if running non-headless. If None, will use default + value 1 / gm.DEFAULT_RENDERING_FREQ + sim_step_dt (None or float): dt between self.step() calls. This is the amount of simulation time that + passes every time step() is called. Note: This must be a multiple of @rendering_dt. If None, will + use default value 1 / gm.DEFAULT_SIM_STEP_FREQ + viewer_width (int): width of the camera image, in pixels + viewer_height (int): height of the camera image, in pixels + device (None or str): specifies the device to be used if running on the gpu with torch backend + """ + + def __init__( + self, + gravity=9.81 if not gm.VISUAL_ONLY else 0.0, + physics_dt=None, + rendering_dt=None, + sim_step_dt=None, + viewer_width=gm.DEFAULT_VIEWER_WIDTH, + viewer_height=gm.DEFAULT_VIEWER_HEIGHT, + device=None, + ): + assert ( + lazy.isaacsim.core.utils.stage.get_current_stage() is None + ), "Stage should not exist when creating a new Simulator instance" + + # Here we assign self as the Simulator instance and as og.sim, because certain functions + # called downstream during the initialization of this object will try to access og.sim. + # This makes that possible (and also introduces possible issues around circular dependencies) + assert og.sim is None, "Only one Simulator instance can be created at a time!" + og.sim = self + + # Sanity check physics vs. rendering vs. sim step dt + physics_dt = 1.0 / gm.DEFAULT_PHYSICS_FREQ if physics_dt is None else physics_dt + rendering_dt = 1.0 / gm.DEFAULT_RENDERING_FREQ if rendering_dt is None else rendering_dt + sim_step_dt = 1.0 / gm.DEFAULT_SIM_STEP_FREQ if sim_step_dt is None else sim_step_dt + self._validate_dts(physics_dt, rendering_dt, sim_step_dt) + + # Store vars needed for initialization + self.gravity = gravity + self._sim_step_dt = sim_step_dt + self._n_steps_per_loop = int(sim_step_dt // rendering_dt) + self._viewer_camera = None + self._camera_mover = None + self._render_on_step = True + self.currently_stepping = ( + False # Whether we are currently in a physics step lifecycle, including pre-and-post-step callbacks. + ) + self.currently_in_isaac_step = False # Whether we are currently in the Isaac Sim-owned part of the step context (e.g. NOT the callbacks) + self.pre_step_exception = None + self.post_step_exception = None + + self._step_profiler = Profiler(deep=gm.ENABLE_DEEP_PROFILING) + self._pre_physics_step_profiler = Profiler(deep=gm.ENABLE_DEEP_PROFILING) + self._post_physics_step_profiler = Profiler(deep=gm.ENABLE_DEEP_PROFILING) + self._non_physics_step_profiler = Profiler(deep=gm.ENABLE_DEEP_PROFILING) + + self._floor_plane = None + self._skybox = None + self._last_scene_edge = None + self._stage_id = None + + # USD edit guard: detects edits outside editing_usd() context + self._editing_usd = False + self._editing_usd_caller = None + self._in_sim_lifecycle = 0 + self._deferred_usd_guard_error = None + self._usd_guard_enabled = False + self._usd_guard_listener = None + + # Create the SimulationContext instance (composition instead of inheritance) + self._sim_context = lazy.isaacsim.core.api.SimulationContext( + physics_dt=physics_dt, + rendering_dt=rendering_dt, + backend="torch", + device=device, + ) + + # Store other references to variables that will be initialized later + self._scenes = [] + # The callback will be called right *before* the physics step + self._pre_physics_step_callback = self._physics_context._physx_interface.subscribe_physics_on_step_events( + lambda _: self._on_pre_physics_step(), + pre_step=True, + order=0, + ) + # The callback will be called right *after* the physics step + self._post_physics_step_callback = self._physics_context._physx_interface.subscribe_physics_on_step_events( + lambda _: self._on_post_physics_step(), + pre_step=False, + order=0, + ) + self._simulation_event_callback = ( + self._physics_context._physx_interface.get_simulation_event_stream_v2().create_subscription_to_pop( + self._on_simulation_event + ) + ) + + # List of objects that need to be initialized during whenever the next sim step occurs + self._objects_to_initialize = [] + self._objects_require_joint_break_callback = False + self._deferred_joint_breaks = [] + # Set when update_handles() is called mid-step (currently_stepping): the tensorized + # object-state views read world poses from Fabric in their initialize_view(), which is + # forbidden during a physics step, so the rebuild is deferred to _on_post_physics_step. + self._deferred_tensorized_view_init = False + + # Maps callback name to callback + self._callbacks_on_play = dict() + self._callbacks_on_stop = dict() + self._callbacks_on_add_obj = dict() + self._callbacks_on_remove_obj = dict() + self._callbacks_on_system_init = dict() + self._callbacks_on_system_clear = dict() + + # Update internal settings + self._set_physics_engine_settings() + self._set_renderer_settings() + + # Set the lighting mode to be stage by default + self.set_lighting_mode(mode=LightingMode.STAGE) + + # Set of categories that can be grasped by assisted grasping + self.object_state_types = get_states_by_dependency_order() + self.object_state_types_requiring_update = [ + state + for state in self.object_state_types + if (issubclass(state, UpdateStateMixin) or issubclass(state, TensorizedState)) + ] + self.object_state_types_on_joint_break = { + state for state in self.object_state_types if issubclass(state, JointBreakSubscribedStateMixin) + } + + # Create the Fabric Hierarchy + self.usdrt_stage = lazy.isaacsim.core.utils.stage.get_current_stage(fabric=True) + self.fabric_hierarchy = lazy.usdrt.hierarchy.IFabricHierarchy().get_fabric_hierarchy( + self.usdrt_stage.GetFabricId(), self.usdrt_stage.GetStageIdAsStageId() + ) + + # Create world prim and set up initial USD state + with self.editing_usd(): + self.stage.DefinePrim("/World", "Xform") + + # Cycle play / stop to validate sim.psi object to avoid getPhysXSceneStatistics errors + self.play() + self.stop() + + for state in self.object_state_types_requiring_update: + if issubclass(state, TensorizedState): + state.global_initialize() + + # Captured wp.Graph wrapping every TensorizedState's global_update(). + self._state_graph = None + + # Now start rebuilding everything + # Disable collision between root links of fixed base objects + CollisionAPI.create_collision_group(col_group="fixed_base_fixed_links", filter_self_collisions=True) + # Create collision group for sliding/pocket_doors to allow them to slide into walls + CollisionAPI.create_collision_group(col_group="structural_doors", filter_self_collisions=True) + CollisionAPI.add_group_filter(col_group="structural_doors", filter_group="fixed_base_fixed_links") + + # Store stage ID + self._stage_id = lazy.pxr.UsdUtils.StageCache.Get().GetId(self.stage).ToLongInt() + + # Set the viewer camera, and then set its default pose + if gm.RENDER_VIEWER_CAMERA: + self._set_viewer_camera( + viewer_width=viewer_width, + viewer_height=viewer_height, + ) + self.viewer_camera.set_position_orientation( + position=th.tensor(m.DEFAULT_VIEWER_CAMERA_POS), + orientation=th.tensor(m.DEFAULT_VIEWER_CAMERA_QUAT), + ) + + # Enable the USD edit guard - from now on, any USD edits outside editing_usd() will crash + self._enable_usd_guard() + + def _set_viewer_camera( + self, + relative_prim_path="/viewer_camera", + viewport_name="Viewport", + viewer_height=gm.DEFAULT_VIEWER_HEIGHT, + viewer_width=gm.DEFAULT_VIEWER_WIDTH, + ): + """ + Creates a camera prim dedicated for this viewer at @prim_path if it doesn't exist, + and sets this camera as the active camera for the viewer + + Args: + prim_path (str): Path to check for / create the viewer camera + viewport_name (str): Name of the viewport this camera should attach to. Default is "Viewport", which is + the default viewport's name in Isaac Sim + """ + self._viewer_camera = VisionSensor( + relative_prim_path=relative_prim_path, + name=relative_prim_path.split("/")[-1], # Assume name is the lowest-level name in the prim_path + modalities="rgb", + image_height=viewer_height, + image_width=viewer_width, + viewport_name=viewport_name, + ) + self._viewer_camera.load(None) + + # We update its clipping range and focal length so we get a good FOV and so that it doesn't clip + # nearby objects (default min is 1 m) + self._viewer_camera.clipping_range = [0.001, 10000000.0] + self._viewer_camera.focal_length = 17.0 + + # Initialize the sensor + self._viewer_camera.initialize() + + # Also need to potentially update our camera mover if it already exists + if self._camera_mover is not None: + self._camera_mover.set_cam(cam=self._viewer_camera) + + def _set_physics_engine_settings(self): + """ + Set the physics engine with specified settings + """ + assert self.is_stopped(), "Cannot set simulator physics settings while simulation is playing!" + self._physics_context.set_gravity(value=-self.gravity) + # Also make sure we don't invert the collision group filter settings so that different collision groups by + # default collide with each other, and modify settings for speed optimization + self._physics_context.set_invert_collision_group_filter(False) + self._physics_context.enable_ccd(gm.ENABLE_CCD) + self._physics_context.enable_fabric(True) + + # Enable GPU dynamics based on whether we need omni particles feature + if gm.USE_GPU_DYNAMICS: + self._physics_context.enable_gpu_dynamics(True) + self._physics_context.set_broadphase_type("GPU") + else: + self._physics_context.enable_gpu_dynamics(False) + self._physics_context.set_broadphase_type("MBP") + + # Set GPU Pairs capacity and other GPU settings + self._physics_context.set_gpu_found_lost_pairs_capacity(gm.GPU_PAIRS_CAPACITY) + self._physics_context.set_gpu_found_lost_aggregate_pairs_capacity(gm.GPU_AGGR_PAIRS_CAPACITY) + self._physics_context.set_gpu_total_aggregate_pairs_capacity(gm.GPU_AGGR_PAIRS_CAPACITY) + self._physics_context.set_gpu_max_particle_contacts(gm.GPU_MAX_PARTICLE_CONTACTS) + self._physics_context.set_gpu_max_rigid_contact_count(gm.GPU_MAX_RIGID_CONTACT_COUNT) + self._physics_context.set_gpu_max_rigid_patch_count(gm.GPU_MAX_RIGID_PATCH_COUNT) + + def _set_renderer_settings(self): + settings = lazy.carb.settings.get_settings() + settings.set_bool("/rtx/rtx/modes/rt/enabled", True) # real-time 2.0 requires rt to be enabled as well + settings.set_bool("/rtx/rtx/modes/rt2/enabled", True) + settings.set("/rtx/rendermode", "RealTimePathTracing") + settings.set_bool("/rtx/raytracing/fractionalCutoutOpacity", True) + + settings.set_bool("/rtx/reflections/enabled", True) + settings.set_bool("/rtx/indirectDiffuse/enabled", True) + settings.set_int( + "/rtx/post/dlss/execMode", 0 if not gm.ENABLE_HQ_RENDERING else 1 + ) # "Performance" vs "Realism" + settings.set_bool("/rtx/ambientOcclusion/enabled", True) + settings.set_bool("/rtx/directLighting/sampledLighting/enabled", True) + settings.set_int("/rtx/raytracing/showLights", 1) + settings.set_float("/rtx/sceneDb/ambientLightIntensity", 1.0) + settings.set_bool("/app/renderer/skipMaterialLoading", False) + settings.set_bool("/rtx/flow/enabled", True) + + # Below settings are for improving performance: we use the USD / Fabric only for poses. + settings.set_bool("/physics/updateToUsd", False) + settings.set_bool("/physics/updateParticlesToUsd", True) + settings.set_bool( + "/physics/updateVelocitiesToUsd", gm.ENABLE_HQ_RENDERING + ) # Needed for isosurface HQ rendering + settings.set_bool("/physics/updateForceSensorsToUsd", False) + settings.set_bool("/physics/updateResidualsToUsd", False) + settings.set_bool("/physics/outputVelocitiesLocalSpace", False) + settings.set_bool("/physics/fabricUpdateTransformations", True) + settings.set_bool("/physics/fabricUpdateVelocities", False) + settings.set_bool("/physics/fabricUpdateForceSensors", False) + settings.set_bool("/physics/fabricUpdateJointStates", False) + settings.set_bool("/physics/fabricUpdateResiduals", False) + settings.set_bool("/physics/fabricUseGPUInterop", True) + + if gm.ENABLE_HQ_RENDERING: + min_frame_rate = 60 + # Make sure we have at least 60 FPS before setting "persistent/simulation/minFrameRate" to 60 + assert (1 / self.get_rendering_dt()) >= min_frame_rate, ( + f"isosurface HQ rendering requires at least {min_frame_rate} FPS; consider increasing " + f"rendering_frequency of env_config to {min_frame_rate}." + ) + + # Settings for Isosurface + # disable grid and lights + dOptions = settings.get_as_int("/persistent/app/viewport/displayOptions") + dOptions &= ~(1 << 6 | 1 << 8) + settings.set_int("/persistent/app/viewport/displayOptions", dOptions) + settings.set_int("/persistent/simulation/minFrameRate", min_frame_rate) + settings.set_bool("/rtx-defaults/pathtracing/lightcache/cached/enabled", False) + settings.set_bool("/rtx-defaults/pathtracing/cached/enabled", False) + settings.set_int("/rtx-defaults/pathtracing/fireflyFilter/maxIntensityPerSample", 10000) + settings.set_int("/rtx-defaults/pathtracing/fireflyFilter/maxIntensityPerSampleDiffuse", 50000) + settings.set_float("/rtx-defaults/pathtracing/optixDenoiser/blendFactor", 0.09) + settings.set_int("/rtx-defaults/pathtracing/aa/op", 2) + settings.set_int("/rtx-defaults/pathtracing/maxBounces", 32) + settings.set_int("/rtx-defaults/pathtracing/maxSpecularAndTransmissionBounces", 16) + settings.set_int("/rtx-defaults/translucency/maxRefractionBounces", 12) + + def _validate_dts(self, physics_dt, rendering_dt, sim_step_dt): + """ + Validates that @physics_dt, @rendering_dt, and @sim_step_dt are all valid with respect to each other + + Args: + physics_dt (float): Physics timestep + rendering_dt (float): Rendering timestep + sim_step_dt (float): Simulation step timestep + """ + render_physics_ratio = rendering_dt / physics_dt + sim_render_ratio = sim_step_dt / rendering_dt + assert math.isclose( + render_physics_ratio, round(render_physics_ratio) + ), f"Rendering dt ({rendering_dt}) must be a multiple of physics dt ({physics_dt})" + assert ( + rendering_dt >= physics_dt + ), f"Rendering dt ({rendering_dt}) cannot be smaller than physics dt ({rendering_dt})" + assert math.isclose( + sim_render_ratio, round(sim_render_ratio) + ), f"Simulation step dt ({sim_step_dt}) must be a multiple of rendering dt ({rendering_dt})" + assert ( + sim_step_dt >= rendering_dt + ), f"Simulation step dt ({sim_step_dt}) cannot be smaller than rendering dt ({rendering_dt})" + + # If we're headless, we also enforce that sim_step_dt == rendering_dt because it doesn't make sense + # to waste rendering that is not observed by the user + if gm.HEADLESS: + assert sim_step_dt == rendering_dt, ( + f"Simulation step dt ({sim_step_dt}) must be equal to rendering dt ({rendering_dt}) when " + f"gm.HEADLESS is set!" + ) + + @property + def viewer_visibility(self): + """ + Returns: + bool: Whether the viewer is visible or not + """ + return self._viewer_camera.viewer_visibility + + @viewer_visibility.setter + def viewer_visibility(self, visible): + """ + Sets whether the viewer should be visible or not in the Omni UI + + Args: + visible (bool): Whether the viewer should be visible or not + """ + self._viewer_camera.viewer_visibility = visible + + @property + def viewer_height(self): + """ + Returns: + int: viewer height of this sensor, in pixels + """ + # If the viewer camera hasn't been created yet, utilize the default width + return gm.DEFAULT_VIEWER_HEIGHT if self._viewer_camera is None else self._viewer_camera.image_height + + @viewer_height.setter + def viewer_height(self, height): + """ + Sets the viewer height @height for this sensor + + Args: + height (int): viewer height, in pixels + """ + self._viewer_camera.image_height = height + + @property + def viewer_width(self): + """ + Returns: + int: viewer width of this sensor, in pixels + """ + # If the viewer camera hasn't been created yet, utilize the default height + return gm.DEFAULT_VIEWER_WIDTH if self._viewer_camera is None else self._viewer_camera.image_width + + @viewer_width.setter + def viewer_width(self, width): + """ + Sets the viewer width @width for this sensor + + Args: + width (int): viewer width, in pixels + """ + self._viewer_camera.image_width = width + + def add_ground_plane(self, floor_plane_visible=True, floor_plane_color=None): + """ + Generate a ground plane into the simulator. + """ + if self._floor_plane is not None: + return + + ground_plane_relative_path = "/ground_plane" + + with self.editing_usd(): + plane = lazy.isaacsim.core.api.objects.ground_plane.GroundPlane( + prim_path="/World" + ground_plane_relative_path, + name="ground_plane", + z_position=0, + size=None, + color=None if floor_plane_color is None else th.tensor(floor_plane_color), + visible=floor_plane_visible, + # TODO: update with new PhysicsMaterial API + # static_friction=static_friction, + # dynamic_friction=dynamic_friction, + # restitution=restitution, + ) + + triangularize_mesh(lazy.pxr.UsdGeom.Mesh.Define(self.stage, plane.prim.GetChildren()[0].GetPath())) + + self._floor_plane = XFormPrim( + relative_prim_path=ground_plane_relative_path, + name=plane.name, + ) + self._floor_plane.load(None) + + # Assign floors category to the floor plane + add_semantic_label(prim=self._floor_plane.prim, label="floors") + + def add_skybox(self): + """ + Generate a skybox into the simulator. + """ + if self._skybox is not None: + return + self._skybox = LightObject( + relative_prim_path="/skybox", + name="skybox", + category="background", + light_type="Dome", + intensity=2500, + ) + self._skybox.load(None) + self._skybox.color = (1.07, 0.85, 0.61) + self._skybox.texture_file_path = os.path.join( + get_dataset_path("omnigibson-robot-assets"), "models/background/sky.jpg" + ) + + def get_sim_step_dt(self): + """ + Gets the internal simulation step timestep size + + Returns: + float: Simulation timestep size + """ + return self._sim_step_dt + + def set_simulation_dt(self, physics_dt=None, rendering_dt=None, sim_step_dt=None): + """ + Unified method to set simulation timestep parameters. Any of the parameters can be None to keep the current + + Args: + physics_dt (float, optional): Physics simulation timestep + rendering_dt (float, optional): Rendering timestep + sim_step_dt (float, optional): Internal simulation step timestep + If None, will default to the current value + """ + with self.editing_usd(): + self._sim_context.set_simulation_dt(physics_dt=physics_dt, rendering_dt=rendering_dt) + current_physics_dt = self.get_physics_dt() + current_rendering_dt = self.get_rendering_dt() + + if sim_step_dt is not None: + self._validate_dts(current_physics_dt, current_rendering_dt, sim_step_dt) + + # Update sim_step_dt and recalculate steps per loop + self._sim_step_dt = sim_step_dt + self._n_steps_per_loop = int(sim_step_dt // current_rendering_dt) + else: + self._validate_dts(current_physics_dt, current_rendering_dt, self._sim_step_dt) + + def set_lighting_mode(self, mode): + """ + Sets the active lighting mode in the current simulator. Valid options are one of LightingMode + + Args: + mode (LightingMode): Lighting mode to set + """ + lazy.omni.kit.commands.execute("SetLightingMenuModeCommand", lighting_mode=mode) + + def enable_viewer_camera_teleoperation(self): + """ + Enables keyboard control of the active viewer camera for this simulation + """ + assert gm.RENDER_VIEWER_CAMERA, "Viewer camera must be enabled to enable teleoperation!" + self._camera_mover = CameraMover(cam=self._viewer_camera) + self._camera_mover.print_info() + return self._camera_mover + + def import_scene(self, scenes): + """ + Import one or more scenes into the simulator. A scene could be a synthetic one or a realistic Gibson + Environment. + + Args: + scenes (Scene or list of Scenes): scene(s) to load + """ + assert self.is_stopped(), "Simulator must be stopped while importing a scene!" + if isinstance(scenes, Scene): + scenes = [scenes] + assert all( + isinstance(scene, Scene) for scene in scenes + ), "import_scene can only be called with Scene instances" + assert len(scenes) > 0, "import_scene requires at least one scene" + + # Check that the scene is not already imported + for scene in scenes: + if scene.loaded: + raise ValueError("Scene is already loaded!") + self._last_scene_edge = scene.load( + idx=len(self.scenes), + last_scene_edge=self._last_scene_edge, + initial_scene_prim_z_offset=m.INITIAL_SCENE_PRIM_Z_OFFSET, + scene_margin=m.SCENE_MARGIN, + ) + # Load the scene. + self._scenes.append(scene) + + self.play() + for scene in scenes: + scene.initialize() + # One step is needed for particle systems to work. + self.step() + self.stop() + + for scene in scenes: + log.info(f"Imported scene {scene.idx}.") + + # TODO: Remove this context manager and call _post_import_object directly since the objects + # are already known when this is called. + @contextlib.contextmanager + def adding_objects(self, objs): + """ + Adds a set of objects from the simulator. This is a context manager that handles low-level simulator state + and should be called externally. Note that this method does not explicitly add the object from + the simulator; it is assumed that this is handled externally + + Args: + objs (Iterable[USDObject]): list of objects to add + """ + SimulationManager = lazy.isaacsim.core.simulation_manager.SimulationManager + if self.is_playing() and SimulationManager._physics_sim_view: + # Certain operations during object loading invalidate the physics simulation view. + # Since this view is required later if initialized, we preemptively invalidate + # and de-initialize it to avoid conflicts. + SimulationManager._physics_sim_view.invalidate() + SimulationManager._physics_sim_view = None + + try: + yield + finally: + # We want to make sure we revalidate the views here even if the object addition + # fails, because the pre-yield invalidation above leaves things in a broken state. + if self.is_playing(): + self.update_handles() + + # Run all post-processing on all newly added objects + for obj in objs: + self._post_import_object(obj=obj) + + def _post_import_object(self, obj): + """ + Post import an object into the simulator, handling any additional setup that needs to be done. + + Args: + obj (USDObject): an object to load + """ + assert isinstance(obj, USDObject), "_post_import_object can only be called with USDObject" + + # Run any callbacks + for callback in self._callbacks_on_add_obj.values(): + callback(obj) + + # Lastly, additionally add this object automatically to be initialized as soon as another simulator step occurs + self._objects_to_initialize.append(obj) + + def batch_add_objects(self, objs, scenes): + """ + Add a set of objects from the simulator. + + Args: + objs (Iterable[USDObject]): list of objects to add + scenes (Iterable[BaseScene]): list of scenes corresponding to each object to load + """ + with self.adding_objects(objs=objs): + for obj, scene in zip(objs, scenes): + scene.add_object(obj, _batched_call=True) + + @contextlib.contextmanager + def removing_objects(self, objs): + """ + Remove a set of objects from the simulator. This is a context manager that handles low-level simulator state + and should be called externally. Note that this method does not explicitly remove the object from + the simulator; it is assumed that this is handled externally + + Args: + objs (Iterable[USDObject]): list of objects to remove + """ + playing = self.is_playing() + if playing: + state = self.dump_state() + + # Omniverse has a strange bug where if GPU dynamics is on and the object to remove is in contact with + # with another object (in some specific configuration only, not always), the simulator crashes. Therefore, + # we first move the object to a safe location, then remove it. + pos = list(m.OBJECT_GRAVEYARD_POS) + for ob in objs: + ob.set_position_orientation(pos, th.tensor([0, 0, 0, 1], dtype=th.float32)) + pos[0] += max(ob.aabb_extent) + + # One physics timestep will elapse + self.step_physics() + + # Run all pre-processing for all objects and record which scenes have been modified + scenes_modified = set() + for obj in objs: + scenes_modified.add(obj.scene) + self._pre_remove_object(obj) + # Prune from the state if recorded + if playing: + obj_registry = state[obj.scene.idx]["registry"]["object_registry"] + if ( + obj.name in obj_registry + ): # a particle system template object might not exist in the registry when it's empty + obj_registry.pop(obj.name) + # Remove stale articulated-grasp constraints for any robot arm targeting this object. + for robot in obj.scene.robots: + robot_state = obj_registry.get(robot.name) + ag_params = None if robot_state is None else robot_state.get("ag_obj_constraint_params") + if ag_params is None: + continue + for arm, arm_params in ag_params.items(): + if not arm_params: + continue + target_obj = arm_params.get("target_obj") + target_obj_name = target_obj.name if hasattr(target_obj, "name") else target_obj + if target_obj_name == obj.name or arm_params.get("ag_obj_prim_path") == obj.prim_path: + ag_params[arm] = None + + # Run the main method + try: + yield + finally: + # Update all handles that are now broken because objects have changed + if playing: + self.update_handles() + + # Run post-processing required if we were playing + if playing: + if gm.ENABLE_TRANSITION_RULES: + # Prune the transition rules that are currently active + for scene in scenes_modified: + scene.transition_rule_api.prune_active_rules() + + # Load the state back + self.load_state(state) + + def _pre_remove_object(self, obj): + """ + Remove a non-robot object from the simulator. Should not be called directly by the user. + + Args: + obj (USDObject): a non-robot object to remove + """ + # Run any callbacks + for callback in self._callbacks_on_remove_obj.values(): + callback(obj) + + # If it was queued up to be initialized, remove it from the queue as well + for i, initialize_obj in enumerate(self._objects_to_initialize): + if obj.name == initialize_obj.name: + self._objects_to_initialize.pop(i) + break + + def batch_remove_objects(self, objs): + """ + Remove a set of objects from the simulator. + + Args: + objs (Iterable[USDObject]): list of objects to remove + """ + objs = list(objs) + if len(objs) > 0: + with self.removing_objects(objs=objs): + for obj in objs: + obj.scene.remove_object(obj, _batched_call=True) + + def remove_prim(self, prim): + """ + Remove a prim from the simulator. + + Args: + prim (BasePrim): a prim to remove + """ + # [omni.physx.tensors.plugin] prim '[prim_path]' was deleted while being used by a shape in a tensor view + # class. The physics.tensors simulationView was invalidated. + with suppress_omni_log(channels=["omni.physx.tensors.plugin"]): + # Remove prim + prim.remove() + + # Update all handles that are now broken because prims have changed + self.update_handles() + + # ---- Proxy properties/methods delegating to the SimulationContext instance ---- + def get_physics_context(self): + return self._sim_context.get_physics_context() + + @property + def _physics_context(self): + return self._sim_context._physics_context + + @property + def stage(self): + return self._sim_context.stage + + @property + def current_time(self): + return self._sim_context.current_time + + @property + def _initial_physics_dt(self): + return self._sim_context._initial_physics_dt + + @property + def _initial_rendering_dt(self): + return self._sim_context._initial_rendering_dt + + def is_playing(self): + return self._sim_context.is_playing() + + def is_stopped(self): + return self._sim_context.is_stopped() + + def get_physics_dt(self): + return self._sim_context.get_physics_dt() + + def get_rendering_dt(self): + return self._sim_context.get_rendering_dt() + + @property + def physics_sim_view(self): + return self._sim_context.physics_sim_view + + @property + def pi(self): + return self._physics_context._physx_interface + + @property + def psi(self): + return self._physics_context._physx_sim_interface + + @property + def psqi(self): + return lazy.omni.physx.get_physx_scene_query_interface() + + @property + def current_time_step_index(self): + return self._sim_context.current_time_step_index + + # ---- End proxy properties/methods ---- + + def render(self): + self._check_usd_guard() + self._in_sim_lifecycle += 1 + try: + self._sim_context.render() + finally: + self._in_sim_lifecycle -= 1 + + def _refresh_physics_sim_view(self): + self._in_sim_lifecycle += 1 + try: + SimulationManager = lazy.isaacsim.core.simulation_manager.SimulationManager + IsaacEvents = lazy.isaacsim.core.simulation_manager.IsaacEvents + + stage_id = lazy.isaacsim.core.utils.stage.get_current_stage_id() + SimulationManager._physics_sim_view = lazy.omni.physics.tensors.create_simulation_view( + SimulationManager._backend, stage_id=stage_id + ) + SimulationManager._physics_sim_view.set_subspace_roots("/") + SimulationManager._physics_sim_view__warp = lazy.omni.physics.tensors.create_simulation_view( + "warp", stage_id=stage_id + ) + SimulationManager._simulation_view_created = True + SimulationManager._message_bus.dispatch_event(IsaacEvents.SIMULATION_VIEW_CREATED.value, payload={}) + SimulationManager._message_bus.dispatch_event(IsaacEvents.PHYSICS_READY.value, payload={}) + finally: + self._in_sim_lifecycle -= 1 + + def sync_physx_to_fabric(self): + # We don't want to sync PhysX to Fabric during a physics step, as it is quite slow! + assert not self.currently_stepping, "Cannot refresh poses during a physics step!" + + self._sim_context._physx_fabric_interface.update(self.current_time, self.get_physics_dt()) + + def update_handles(self): + # Handles are only relevant when physx is running + if not self.is_playing(): + return + + # Flush any USD changes to PhysX + with self.editing_usd(): + self.psi.flush_changes() + + # Refresh the sim view + self._refresh_physics_sim_view() + + # Then update the handles for all objects + for scene in self.scenes: + if scene is not None: + for obj in scene.objects: + # Only need to update if object is already initialized as well + if obj.initialized: + obj.update_handles() + for system in scene.active_systems.values(): + if isinstance(system, MacroPhysicalParticleSystem): + system.update_handles() + + # Finally update any unified views + RigidContactAPI.initialize_view() + RigidBodyViewAPI.initialize_view() + ArticulatedObjectViewAPI.initialize_view() + ControllableObjectViewAPI.initialize_view() + + if gm.ENABLE_OBJECT_STATES: + if self.currently_stepping: + # update_handles() is reached mid-step when a joint is created during a physics + # callback (e.g. assisted grasping or on-contact attachment). Tensorized state + # views bake static geometry from Fabric world poses in initialize_view(), which + # is forbidden while currently_stepping=True. These views are only consumed by the + # post-physics state update, so defer the rebuild until currently_stepping clears + # (mirrors the deferred joint-break handling in _on_post_physics_step). The physics + # views above are refreshed immediately so the new joint is registered. + self._deferred_tensorized_view_init = True + else: + for state_type in og.sim.object_state_types_requiring_update: + if issubclass(state_type, TensorizedState): + state_type.initialize_view() + + def _refresh_state_caches(self, dt=0.0): + """ + Run a full update for tensorized object state and view API. + + This function will be called in the following cases: + - in usual step, in ``_non_physics_step`` (passes the sim-step dt) + - in ``step_physics`` (passes dt=0) + - anywhere that poses/joints are set between sim steps (sample_kinematics, + Inside._set_value, set_position_orientation / JointPrim.set_pos) and + any TensorizedAbsoluteState need to get_value (default dt=0) + + ``dt`` is the seconds elapsed for this logical step; it is forwarded to each + tensorized state's ``pre_update`` so time-dependent states advance by exactly the + sim-step dt on a real step and by 0 on physics-only / out-of-step refreshes. + + Always clears ``TensorizedState.caches_dirty`` on completion. + """ + if len(self.scenes) == 0 or not self.is_playing(): + TensorizedState.caches_dirty = False + return + + RigidBodyViewAPI.read_from_physx() + ArticulatedObjectViewAPI.read_from_physx() + wp.synchronize_stream(wp.get_stream()) + + self._capture_warp_graph(dt) + + RigidContactAPI._PENDING_STEPS = 0 + + def _capture_warp_graph(self, dt=0.0): + """ + Manage the per-step warp graph end-to-end (gating, pre/post bookkeeping, capture, + and launch all live here so ``_refresh_state_caches`` stays thin). + + Steps: + 1. Compute the list of tensorized states, gated on ``gm.ENABLE_OBJECT_STATES``. + If the list is empty (object states disabled or none registered), run the + view-API ``update()``s directly and return — there is no pre/global/post + pipeline to drive. + 2. Otherwise, run ``pre_update(dt)`` for each state, then either (re-)capture or + replay the per-step graph (view-API H2D + tensorized state global_updates). + ``wp.ScopedCapture`` only RECORDS ops — the captured graph must be launched + explicitly via ``wp.capture_launch`` for its kernels to run this frame. + 3. After ``wp.synchronize()``, run ``post_update`` for each state for change + detection. + + Always clears ``TensorizedState.caches_dirty`` on completion. + """ + tensorized_states = ( + [state for state in self.object_state_types_requiring_update if issubclass(state, TensorizedState)] + if gm.ENABLE_OBJECT_STATES + else [] + ) + + if not tensorized_states: + # No tensorized-state pipeline → still refresh GPU view-API mirrors so + # downstream consumers (rendering, ad-hoc queries) see fresh poses / contacts. + RigidBodyViewAPI.update() + RigidContactAPI.update() + wp.synchronize_stream(wp.get_stream()) + TensorizedState.caches_dirty = False + return + + # Nested _get_value during this refresh should read the cache directly rather + # than recursively triggering another refresh. + TensorizedState._refresh_in_progress = True + try: + TensorizedState.caches_dirty = True + + for state_type in tensorized_states: + state_type.pre_update(dt) + + if TensorizedState.graph_dirty: + if all(s.VALUES is None or s.VALUES.numel() == 0 for s in tensorized_states): + # Nothing to capture; leave _state_graph as None. + self._state_graph = None + else: + # ScopedCapture creates + owns its capture stream. Inside the with-block, + # wp.get_stream() returns that stream and any wp.launch / wp.copy defaults + # to it. Tensorized-state kernels read POSE_MATRICES / joint positions + # written by the view-API kernels above — stream ordering on the capture + # stream guarantees they see fresh values. + with wp.ScopedCapture(device="cuda") as capture: + RigidBodyViewAPI.update() + RigidContactAPI.update() + for state_type in tensorized_states: + state_type.global_update() + self._state_graph = capture.graph + TensorizedState.graph_dirty = False + if self._state_graph is not None: + wp.capture_launch(self._state_graph) + + wp.synchronize_stream(wp.get_stream()) + + for state_type in tensorized_states: + state_type.post_update() + finally: + TensorizedState._refresh_in_progress = False + TensorizedState.caches_dirty = False + + @with_profiler(name="_non_physics_step_profiler") + def _non_physics_step(self): + """ + Complete any non-physics steps such as state updates. + """ + # If we don't have a valid scene, immediately return + if len(self.scenes) == 0: + return + + # If we're playing we, also run additional logic + if self.is_playing(): + # Check to see if any objects should be initialized (only done IF we're playing) + n_objects_to_initialize = len(self._objects_to_initialize) + if n_objects_to_initialize > 0 and self.is_playing(): + # We iterate through the objects to initialize + # Note that we don't explicitly do for obj in self._objects_to_initialize because additional objects + # may be added mid-iteration!! + # For this same reason, after we finish the loop, we keep any objects that are yet to be initialized + # First call zero-physics step update, so that handles are properly propagated + scenes_modified = set() + for i in range(n_objects_to_initialize): + obj = self._objects_to_initialize[i] + obj.initialize() + scenes_modified.add(obj.scene) + if len(obj.states.keys() & self.object_state_types_on_joint_break) > 0: + self._objects_require_joint_break_callback = True + obj.keep_still() + + self._objects_to_initialize = self._objects_to_initialize[n_objects_to_initialize:] + + # Re-initialize the physics view because the number of objects has changed + self.update_handles() + + if gm.ENABLE_TRANSITION_RULES: + # Refresh the transition rules + for scene in scenes_modified: + scene.transition_rule_api.refresh_all_rules() + + # Update any system-related state + for scene in self.scenes: + for system in scene.active_systems.values(): + system.update() + + # Update view API data and tensorized states. One _non_physics_step runs per + # og.sim.step(), which spans get_sim_step_dt() seconds — advance time-dependent + # states by exactly that. + self._refresh_state_caches(dt=self.get_sim_step_dt()) + + # Propagate states if the feature is enabled + if gm.ENABLE_OBJECT_STATES: + # UpdateStateMixin per-object updates (reads VALUES_CPU after sync) + for state_type in self.object_state_types_requiring_update: + if issubclass(state_type, UpdateStateMixin): + for scene in self.scenes: + for obj in scene.get_objects_with_state(state_type): + # Update the state (object should already be initialized since + # this step will only occur after objects are initialized and sim + # is playing + obj.states[state_type].update() + + for scene in self.scenes: + for obj in scene.objects: + # Only update visuals for objects that have been initialized so far + if obj.initialized: + obj.update_visuals() + + # Possibly run transition rule step + if gm.ENABLE_TRANSITION_RULES: + for scene in self.scenes: + scene.transition_rule_api.step() + + def play(self): + if not self.is_playing(): + # Track whether we're starting the simulator fresh -- i.e.: whether we were stopped previously + was_stopped = self.is_stopped() + + # We suppress warnings from omni.usd because it complains about values set in the native USD + # These warnings occur because the native USD file has some type mismatch in the `scale` property, + # where the property expects a double but for whatever reason the USD interprets its values as floats + # We suppress omni.physicsschema.plugin when kinematic_only objects are placed with scale ~1.0, to suppress + # the following error: + # [omni.physicsschema.plugin] ScaleOrientation is not supported for rigid bodies, prim path: [...] You may + # ignore this if the scale is close to uniform. + # We also need to suppress the following error when flat cache is used: + # [omni.physx.plugin] Transformation change on non-root links is not supported. + channels = ["omni.usd", "omni.physicsschema.plugin", "omni.physx.plugin"] + + with suppress_omni_log(channels=channels): + self._in_sim_lifecycle += 1 + try: + self._sim_context.play() + finally: + self._in_sim_lifecycle -= 1 + + # Take a render step -- this is needed so that certain (unknown, maybe omni internal state?) is populated + # correctly. + self.render() + + # Update all object handles, unless this is a play during initialization + if og.sim is not None: + self.update_handles() + + if was_stopped: + # We need to update controller mode because kp and kd were set to the original (incorrect) values when + # sim was stopped. We need to reset them to default_kp and default_kd defined defined in Robot. + for scene in self.scenes: + for robot in scene.robots: + if robot.initialized: + robot.update_controller_mode() + + # Also refresh any transition rules that became stale while sim was stopped + if gm.ENABLE_TRANSITION_RULES: + scene.transition_rule_api.refresh_all_rules() + + # Additionally run non physics things + self._non_physics_step() + + # Run all callbacks + for callback in self._callbacks_on_play.values(): + callback() + + def pause(self): + if not self.is_paused(): + self._sim_context.pause() + + def stop(self): + if not self.is_stopped(): + self._in_sim_lifecycle += 1 + try: + self._sim_context.stop() + finally: + self._in_sim_lifecycle -= 1 + + # Run all callbacks + for callback in self._callbacks_on_stop.values(): + callback() + + @property + def n_physics_timesteps_per_render(self): + """ + Number of physics timesteps per rendering timestep. rendering_dt has to be a multiple of physics_dt. + + Returns: + int: Discrete number of physics timesteps to take per step + """ + n_physics_timesteps_per_render = self.get_rendering_dt() / self.get_physics_dt() + assert n_physics_timesteps_per_render.is_integer(), "render_timestep must be a multiple of physics_timestep" + return int(n_physics_timesteps_per_render) + + @with_profiler(name="_step_profiler") + def step(self): + """ + Step the simulation at self.get_sim_step_dt() rate + """ + self._check_usd_guard() + assert self.is_playing(), "Simulator must be playing to step" + + render = self._render_on_step + if self.stage is None: + raise Exception("There is no stage currently opened, init_stage needed before calling this func") + + # If we have imported any objects within the last timestep, we render the app once, since otherwise calling + # step() may not step physics + if len(self._objects_to_initialize) > 0: + self.render() + + # Clear all scenes' updated objects + for scene in self.scenes: + scene.clear_updated_objects() + + self._in_sim_lifecycle += 1 + try: + for _ in range(self._n_steps_per_loop): + if render: + self._sim_context.step(render=True) + self._report_step_exceptions() + else: + for i in range(self.n_physics_timesteps_per_render): + self._sim_context.step(render=False) + self._report_step_exceptions() + finally: + self._in_sim_lifecycle -= 1 + + # Additionally run non physics things + self._non_physics_step() + + # TODO (eric): After stage changes (e.g. pose, texture change), it will take two _sim_context.step(render=True) for + # the result to propagate to the rendering. We could have called _sim_context.render() here but it will introduce + # a big performance regression. + + def step_physics(self): + """ + Step the physics a single step. + """ + assert self.is_playing(), "Simulator must be playing to step" + + self._in_sim_lifecycle += 1 + try: + self._physics_context._step(current_time=self.current_time) + finally: + self._in_sim_lifecycle -= 1 + + self._report_step_exceptions() + + # Accumulate contact data from this physics step and then flush to cache. + # We normally do this in _non_physics_step, but step_physics bypasses that so we do it here. + # dt=0: a bare physics step must not advance time-dependent states (matches legacy behavior). + self._refresh_state_caches(dt=0.0) + + @with_profiler(name="_pre_physics_step_profiler") + def _on_pre_physics_step(self): + try: + # Make it possible to identify that we are currently within a step + self.currently_stepping = True + + # Only do this if we're not in the warmup phase + if not lazy.isaacsim.core.simulation_manager.SimulationManager._warmup_needed: + # Batch-step all controller groups (computes control and writes to Isaac buffer) + ControllerView.step_all() + + # Per-robot post-step: override frozen gripper positions, handle assisted grasping + for scene in self.scenes: + for robot in scene.robots: + robot.post_step() + + # Flush the controls from the ControllableObjectViewAPI + ControllableObjectViewAPI.flush_control() + + self.currently_in_isaac_step = True + except Exception as e: + self.currently_stepping = False + self.currently_in_isaac_step = False + self.pre_step_exception = e + raise + + @with_profiler(name="_post_physics_step_profiler") + def _on_post_physics_step(self): + try: + self.currently_in_isaac_step = False + + # Only do this if we're not in the warmup phase + if not lazy.isaacsim.core.simulation_manager.SimulationManager._warmup_needed: + # Run the post physics update for backend view + ControllableObjectViewAPI.post_physics_step() + + # Pull the contact sensor data — must run while currently_stepping is True, + # since RigidContactAPI.read_from_physx asserts on it. Unlike the pose/DOF + # view APIs (snapshot-only, drained once per render-step in + # _refresh_state_caches), contacts accumulate per sub-step into pending + # buffers that update() later walks, so they must be drained here. + # Warmup-gated like the view-API calls above: play()'s two back-to-back + # internal warmup physics steps have no cache drain between them, so they + # overflow the pending buffers whenever n_physics_timesteps_per_render is + # 1, and play()'s update_handles() rebuilds the contact views right after, + # discarding any warmup capture regardless. + if not lazy.isaacsim.core.simulation_manager.SimulationManager._warmup_needed: + RigidContactAPI.read_from_physx() + wp.synchronize_stream(wp.get_stream()) + + # Record that we are done with the step context. Joint-break callbacks below + # are post-step user code: they may call update_handles() / read Fabric, which + # is forbidden while currently_stepping=True. + self.currently_stepping = False + + # Run any tensorized-state view rebuild that was deferred from a mid-step + # update_handles() (e.g. a joint created during grasping). Now that + # currently_stepping is False, the Fabric world-pose reads in initialize_view() + # are allowed. Do this before joint-break callbacks so they observe fresh views. + if self._deferred_tensorized_view_init: + self._deferred_tensorized_view_init = False + if gm.ENABLE_OBJECT_STATES: + for state_type in og.sim.object_state_types_requiring_update: + if issubclass(state_type, TensorizedState): + state_type.initialize_view() + TensorizedState.caches_dirty = True + + if self._deferred_joint_breaks: + # Copy the current deferred joint breaks and clear the shared list + # before invoking callbacks, so we don't retain stale entries if a + # callback raises an exception. + deferred_breaks = list(self._deferred_joint_breaks) + self._deferred_joint_breaks.clear() + for obj, state_type, joint_path in deferred_breaks: + obj.states[state_type].on_joint_break(joint_path) + except Exception as e: + self.currently_in_isaac_step = False + self.currently_stepping = False + self.post_step_exception = e + raise + + def _report_step_exceptions(self): + if self.pre_step_exception is not None: + pre_step_exception = self.pre_step_exception + self.pre_step_exception = None + raise RuntimeError("Exception occurred during pre-physics step") from pre_step_exception + if self.post_step_exception is not None: + post_step_exception = self.post_step_exception + self.post_step_exception = None + raise RuntimeError("Exception occurred during post-physics step") from post_step_exception + + def get_obj_at_prim_path(self, prim_path): + for scene in self.scenes: + obj = scene.object_registry("prim_path", prim_path) + if obj is not None: + return obj + return None + + def _on_simulation_event(self, event): + """ + This callback will be invoked if there is any simulation event. Currently it only processes JOINT_BREAK event. + """ + if gm.ENABLE_OBJECT_STATES: + if ( + event.type == int(lazy.omni.physx.bindings._physx.SimulationEvent.JOINT_BREAK) + and self._objects_require_joint_break_callback + ): + joint_path = str( + lazy.pxr.PhysicsSchemaTools.decodeSdfPath( + event.payload["jointPath"][0], event.payload["jointPath"][1] + ) + ) + obj = None + + tokens = joint_path.split("/") + for i in range(2, len(tokens) + 1): + obj = self.get_obj_at_prim_path("/".join(tokens[:i])) + if obj is not None: + break + + if obj is None or not obj.initialized: + return + if len(obj.states.keys() & self.object_state_types_on_joint_break) == 0: + return + for state_type in self.object_state_types_on_joint_break: + if state_type in obj.states: + self._deferred_joint_breaks.append((obj, state_type, joint_path)) + + def is_paused(self): + """ + Returns: + bool: True if the simulator is paused, otherwise False + """ + return not (self.is_stopped() or self.is_playing()) + + @contextlib.contextmanager + def render_on_step(self, value): + """ + A context scope for setting whether rendering should occur on each simulator step. + """ + # Store the original value, set the new value, yield, and then reset the original value + original_value = self._render_on_step + self._render_on_step = value + yield + self._render_on_step = original_value + + @contextlib.contextmanager + def slowed(self, slow_dt=1e-6): + """ + A context scope for making the simulator simulation dt slowed, e.g.: for taking micro-steps for propagating + instantaneous kinematics with minimal impact on physics propagation. + + Upon leaving the scope, the prior simulator state is restored. + """ + # Set dt, yield, then restore the original dt + physics_dt, rendering_dt, sim_step_dt = self.get_physics_dt(), self.get_rendering_dt(), self._sim_step_dt + self.set_simulation_dt(physics_dt=slow_dt, rendering_dt=slow_dt, sim_step_dt=slow_dt) + yield + self.set_simulation_dt(physics_dt=physics_dt, rendering_dt=rendering_dt, sim_step_dt=sim_step_dt) + + @contextlib.contextmanager + def editing_usd(self, stage=None): + """ + Context manager for USD edits with proper Fabric synchronization. + + Under Fabric Scene Delegate (lazy USD-Fabric sync), USD edits are NOT automatically + propagated to Fabric. This context manager ensures that USD changes are synchronized + to Fabric (via SynchronizeToFabric) when the block exits, so that code immediately + after the block can rely on Fabric being up to date. + + This context MUST NOT be nested — opening an editing_usd() context while another is + already open will raise an error. All USD edits within a single logical operation + should be in one context. + + A guard (enabled after simulator init) detects any USD edits that occur outside this + context and raises a RuntimeError with a full backtrace. + + Usage:: + + with og.sim.editing_usd(): + prim.set_attribute("someAttr", value) + other_prim.visible = False + # USD is now synchronized to Fabric + """ + # If the stage is a non-None value that's also not the simulator stage, we don't need to synchronize to Fabric. + if stage is not None and stage != self.stage: + yield + return + + caller = traceback.extract_stack(limit=3)[0] + assert not self._editing_usd, ( + f"Cannot nest editing_usd() contexts. All USD edits for a logical operation " + f"should be in a single editing_usd() block.\n" + f" Existing context opened at: {self._editing_usd_caller}" + ) + self._check_usd_guard() + assert not self.currently_in_isaac_step, "Cannot edit USD while simulation is stepping!" + self._editing_usd = True + self._editing_usd_caller = f"{caller.filename}:{caller.lineno} in {caller.name}" + try: + yield + finally: + self._editing_usd = False + self._editing_usd_caller = None + self.usdrt_stage.SynchronizeToFabric() + + def _enable_usd_guard(self): + """Enable the guard that detects USD edits outside editing_usd() context.""" + if self._usd_guard_enabled: + return + self._usd_guard_listener = lazy.pxr.Tf.Notice.Register( + lazy.pxr.Usd.Notice.ObjectsChanged, self._on_usd_objects_changed, self.stage + ) + self._usd_guard_enabled = True + + def _disable_usd_guard(self): + """Disable the USD edit guard.""" + if self._usd_guard_listener is not None: + try: + self._usd_guard_listener.Revoke() + except Exception: + pass + self._usd_guard_listener = None + self._usd_guard_enabled = False + + def _on_usd_objects_changed(self, notice, stage): + """Callback fired by Tf.Notice when USD objects change. Crashes if outside editing_usd().""" + if not self._usd_guard_enabled or self._editing_usd or self._in_sim_lifecycle > 0: + return + + resynced = [str(p) for p in notice.GetResyncedPaths()] + info_only = [str(p) for p in notice.GetChangedInfoOnlyPaths()] + all_paths = resynced + info_only + if not all_paths: + return + + # We can't raise here — Tf.Notice callbacks run inside C++ dispatch, which catches + # Python exceptions and converts them to TF errors without propagating. Instead, store + # the violation and raise it later at a point where exceptions propagate normally. + if self._deferred_usd_guard_error is None: + stack = "".join(traceback.format_stack()[:-1]) + paths_str = "\n ".join(all_paths[:20]) + if len(all_paths) > 20: + paths_str += f"\n ... and {len(all_paths) - 20} more" + self._deferred_usd_guard_error = RuntimeError( + f"USD edit detected outside of og.sim.editing_usd() context!\n" + f"Changed paths:\n {paths_str}\n" + f"Stack trace:\n{stack}\n" + f"All USD edits must be wrapped in a `with og.sim.editing_usd():` block " + f"to ensure proper USD-Fabric synchronization." + ) + print(self._deferred_usd_guard_error) + + def _check_usd_guard(self): + """Raise any deferred USD guard error. Called at points where Python exceptions propagate.""" + if self._deferred_usd_guard_error is not None: + error = self._deferred_usd_guard_error + self._deferred_usd_guard_error = None + raise error + + def add_callback_on_play(self, name, callback): + """ + Adds a function @callback, referenced by @name, to be executed every time sim.play() is called + + Args: + name (str): Name of the callback + callback (function): Callback function. Function signature is expected to be: + + def callback() --> None + """ + self._callbacks_on_play[name] = callback + + def add_callback_on_stop(self, name, callback): + """ + Adds a function @callback, referenced by @name, to be executed every time sim.stop() is called + + Args: + name (str): Name of the callback + callback (function): Callback function. Function signature is expected to be: + + def callback() --> None + """ + self._callbacks_on_stop[name] = callback + + def add_callback_on_add_obj(self, name, callback): + """ + Adds a function @callback, referenced by @name, to be executed every time + sim._post_import_object() is called + + Args: + name (str): Name of the callback + callback (function): Callback function. Function signature is expected to be: + + def callback(obj: USDObject) --> None + """ + self._callbacks_on_add_obj[name] = callback + + def add_callback_on_remove_obj(self, name, callback): + """ + Adds a function @callback, referenced by @name, to be executed every time + sim._pre_remove_object() is called + + Args: + name (str): Name of the callback + callback (function): Callback function. Function signature is expected to be: + + def callback(obj: USDObject) --> None + """ + self._callbacks_on_remove_obj[name] = callback + + def add_callback_on_system_init(self, name, callback): + """ + Adds a function @callback, referenced by @name, to be executed every time a system is initialized + + Args: + name (str): Name of the callback + callback (function): Callback function. Function signature is expected to be: + + def callback(system: System) --> None + """ + self._callbacks_on_system_init[name] = callback + + def add_callback_on_system_clear(self, name, callback): + """ + Adds a function @callback, referenced by @name, to be executed every time a system is cleared + + Args: + name (str): Name of the callback + callback (function): Callback function. Function signature is expected to be: + + def callback(system: System) --> None + """ + self._callbacks_on_system_clear[name] = callback + + def remove_callback_on_play(self, name): + """ + Remove play callback whose reference is @name + + Args: + name (str): Name of the callback + """ + self._callbacks_on_play.pop(name, None) + + def remove_callback_on_stop(self, name): + """ + Remove stop callback whose reference is @name + + Args: + name (str): Name of the callback + """ + self._callbacks_on_stop.pop(name, None) + + def remove_callback_on_add_obj(self, name): + """ + Remove add obj callback whose reference is @name + + Args: + name (str): Name of the callback + """ + self._callbacks_on_add_obj.pop(name, None) + + def remove_callback_on_remove_obj(self, name): + """ + Remove remove obj callback whose reference is @name + + Args: + name (str): Name of the callback + """ + self._callbacks_on_remove_obj.pop(name, None) + + def remove_callback_on_system_init(self, name): + """ + Remove system init callback whose reference is @name + + Args: + name (str): Name of the callback + """ + self._callbacks_on_system_init.pop(name, None) + + def remove_callback_on_system_clear(self, name): + """ + Remove system clear callback whose reference is @name + + Args: + name (str): Name of the callback + """ + self._callbacks_on_system_clear.pop(name, None) + + @property + def scenes(self): + """ + Returns: + Empty list or [Scene]: Scenes currently loaded in this simulator. If no scenes are loaded, returns empty list + """ + return self._scenes + + @property + def viewer_camera(self): + """ + Returns: + VisionSensor: Active camera sensor corresponding to the active viewport window instance shown in the omni UI + """ + return self._viewer_camera + + @property + def camera_mover(self): + """ + Returns: + None or CameraMover: If enabled, the teleoperation interface for controlling the active viewer camera + """ + return self._camera_mover + + @property + def world_prim(self): + """ + Returns: + Usd.Prim: Prim at /World + """ + return lazy.isaacsim.core.utils.prims.get_prim_at_path(prim_path="/World") + + @property + def floor_plane(self): + return self._floor_plane + + @property + def skybox(self): + return self._skybox + + def get_callbacks_on_system_init(self): + return self._callbacks_on_system_init + + def get_callbacks_on_system_clear(self): + return self._callbacks_on_system_clear + + def restore(self, scene_files): + """ + Restore simulation environments from @json_paths. + + Args: + scene_files (List[str] or List[dict]): Full paths of either JSON files or loaded scene files to load, + which contains information to recreate a scene. + """ + # Note whether we're loading from scratch or not + load_from_scratch = len(self.scenes) == 0 + + # We don't support smart diff'ing if there's a mismatch in number of scenes + if not load_from_scratch and len(self.scenes) != len(scene_files): + log.error( + "There is a mismatch between the number of active scenes and number of json_paths to be " + "loaded. Please call og.clear() to relaunch the simulator first." + ) + return + + # Handle loading scenes differently depending on whether we're loading from scratch or not + if load_from_scratch: + states = [] + recreated_scenes = [] + self.stop() + for i, scene_file in enumerate(scene_files): + # Directly create and load the scene object + if isinstance(scene_file, str): + if not scene_file.endswith(".json"): + log.error(f"You have to define the full json_path to load from. Got: {scene_file}") + return + + # Load the info from the json + with open(scene_file, "r") as f: + scene_info = json.load(f) + else: + scene_info = scene_file + init_info = scene_info["init_info"] + # The saved state are lists, convert them to torch tensors + state = recursively_convert_to_torch(scene_info["state"]) + states.append(state) + # Override the init info with our json path + init_info["args"]["scene_file"] = scene_file + + # Also make sure we have any additional modifications necessary from the specific scene + og.REGISTERED_SCENES[init_info["class_name"]].modify_init_info_for_restoring(init_info=init_info) + + # Recreate the saved scene + recreated_scenes.append(create_object_from_init_info(init_info)) + + self.import_scene(recreated_scenes) + self.play() + for i, state in enumerate(states): + self.scenes[i].load_state(state, serialized=False) + + else: + for scene, scene_file in zip(self.scenes, scene_files): + scene.restore(scene_file=scene_file) + + log.info("The saved simulation environment loaded.") + + def save(self, json_paths=None, as_dict=False): + """ + Saves the current simulation environment to @json_path. + + Args: + json_paths (None or List[str]): Full path of JSON files to save (should end with .json), each of which + contain information to recreate the current scenes, if specified. List should have one element per + currently loaded scene. If None, will return a list of JSON strings instead. + as_dict (bool): If set and @json_paths is None, will return the saved environment state as a list + of dictionaries instead of encoded json strings + + Returns: + None or list of str or list of dict: If @json_paths is None, returns list of dumped json strings (or + list of dict if @as_dict is set). Else, None + """ + # Make sure there are no objects in the initialization queue, if not, terminate early and notify user + # Also run other sanity checks before saving + if len(self._objects_to_initialize) > 0: + log.error("There are still objects to initialize! Please take one additional sim step and then save.") + return + if not self.scenes: + log.warning("Scene has not been loaded. Nothing to save.") + return + if json_paths is not None: + if isinstance(json_paths, str): + log.error( + f"You must define a list of .json paths, one for each scene. Number of scenes: {len(self.scenes)}" + ) + return + + if not json_paths: + json_paths = [None] * len(self.scenes) + + assert len(json_paths) == len(self.scenes), "Number of json paths should match the number of scenes" + + # Update scene info + jsons = [] + for scene, json_path in zip(self.scenes, json_paths): + jsons.append(scene.save(json_path=json_path, as_dict=as_dict)) + + return None if jsons[0] is None else jsons + + def _partial_clear(self): + """Partial clear clearing all components owned by the Simulator. Rest is completed in og.clear.""" + # Stop the physics + self.stop() + + # Clean subscribed callbacks + self._pre_physics_step_callback.unsubscribe() + self._post_physics_step_callback.unsubscribe() + self._simulation_event_callback.unsubscribe() + + # Clear all tiled vision sensors first -- their render products reference per-scene cameras, + # so they must be destroyed before the scenes (and the cameras) are removed + TiledVisionSensor.clear() + + # Clear all scenes + for scene in self.scenes: + scene.clear() + + # Remove the skybox, floor plane and viewer camera + if self._skybox is not None: + self._skybox.remove() + + if self._floor_plane is not None: + self._floor_plane.remove() + + if self._viewer_camera is not None: + self._viewer_camera.remove() + + if self._camera_mover is not None: + self._camera_mover.clear() + + # Clear the vision sensor cache + VisionSensor.clear() + + # Clear all global update states + for state in self.object_state_types_requiring_update: + if issubclass(state, TensorizedState): + state.global_initialize() + + # Clear all materials + MaterialPrim.clear() + + # Clear uniquely named items and other internal states + clear_python_utils() + clear_usd_utils() + + # Clear all controller groups so robots re-register on next load + ControllerView.clear() + + # Disable the USD guard - we don't care anymore + self._disable_usd_guard() + + def close(self): + """ + Shuts down the OmniGibson application + """ + og.app.shutdown() + + @property + def stage_id(self): + """ + Returns: + int: ID of the current active stage + """ + return self._stage_id + + @property + def device(self): + """ + Returns: + str: Device used in simulation backend + """ + return lazy.isaacsim.core.simulation_manager.SimulationManager.get_physics_sim_device() + + @device.setter + def device(self, device): + """ + Sets the device used for sim backend + + Args: + str: Device to set for the simulation backend + """ + lazy.isaacsim.core.simulation_manager.SimulationManager.set_physics_sim_device(device) + + @property + def initial_physics_dt(self): + """ + Returns: + float: Physics timestep + """ + return self._initial_physics_dt + + @property + def initial_rendering_dt(self): + """ + Returns: + float: Rendering timestep + """ + return self._initial_rendering_dt + + def _dump_state(self): + # Default state is from the scene + return {i: scene.dump_state(serialized=False) for i, scene in enumerate(self.scenes)} + + def _load_state(self, state): + # Default state is from the scene + for i, scene in enumerate(self.scenes): + scene.load_state(state=state[i], serialized=False) + + def load_state(self, state, serialized=False): + # We need to make sure the simulator is playing since joint states only get updated when playing + assert self.is_playing() + + # Run Serializable.load_state (which calls _load_state) + super().load_state(state=state, serialized=serialized) + + # Highlight that at the current step, the non-kinematic states are potentially inaccurate because a sim + # step is needed to propagate specific states in physics backend + # TODO: This should be resolved in a future omniverse release! + disclaimer( + "Attempting to load simulator state.\n" + "Currently, omniverse does not support exclusively stepping kinematics, so we cannot update some " + "of our object states relying on updated kinematics until a simulator step is taken!\n" + "Object states such as OnTop, Inside, etc. relying on relative spatial information will inaccurate" + "until a single sim step is taken.\n" + "This should be resolved by the next NVIDIA Isaac Sim release." + ) + + def serialize(self, state): + # Default state is from the scene + return th.cat([scene.serialize(state=state[i]) for i, scene in enumerate(self.scenes)], dim=0) + + def deserialize(self, state): + # Default state is from the scene + dicts = {} + total_state_size = 0 + for i, scene in enumerate(self.scenes): + scene_dict, deserialized_items = scene.deserialize(state=state[total_state_size:]) + dicts[i] = scene_dict + total_state_size += deserialized_items + return dicts, total_state_size + + if not og.sim: + # The simulator init function saves itself as og.sim. + Simulator(*args, **kwargs) + + print() + print_icon() + print_logo() + print() + log.info(f"{'-' * 10} Welcome to {logo_small()}! {'-' * 10}") + + return og.sim diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/systems/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/systems/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe8f42afc4ef8081a604d2cbb16f85f39d11376b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/systems/__init__.py @@ -0,0 +1,27 @@ +from omnigibson.systems.system_base import BaseSystem, PhysicalParticleSystem, VisualParticleSystem +from omnigibson.systems.macro_particle_system import ( + MacroParticleSystem, + MacroPhysicalParticleSystem, + MacroVisualParticleSystem, +) +from omnigibson.systems.micro_particle_system import ( + Cloth, + FluidSystem, + GranularSystem, + MicroParticleSystem, + MicroPhysicalParticleSystem, +) + +__all__ = [ + "BaseSystem", + "Cloth", + "FluidSystem", + "GranularSystem", + "MacroParticleSystem", + "MacroPhysicalParticleSystem", + "MacroVisualParticleSystem", + "MicroParticleSystem", + "MicroPhysicalParticleSystem", + "PhysicalParticleSystem", + "VisualParticleSystem", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/systems/macro_particle_system.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/systems/macro_particle_system.py new file mode 100644 index 0000000000000000000000000000000000000000..b2ed75030ccd4f320278b0a6b2f80f63a9b10bf2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/systems/macro_particle_system.py @@ -0,0 +1,1535 @@ +import torch as th +import trimesh + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros +from omnigibson.prims.geom_prim import GeomPrim +from omnigibson.systems.system_base import BaseSystem, PhysicalParticleSystem, VisualParticleSystem +from omnigibson.utils.constants import PrimType +from omnigibson.utils.python_utils import torch_delete +from omnigibson.utils.constants import GROUND_CATEGORIES +from omnigibson.utils.object_state_utils import get_reachability_sampling_context, is_pose_reachable_for_predicate +from omnigibson.utils.sampling_utils import sample_cuboid_on_object_symmetric_bimodal_distribution +from omnigibson.utils.ui_utils import create_module_logger, suppress_omni_log +from omnigibson.utils.usd_utils import ( + absolute_prim_path_to_scene_relative, + ensure_usd_api, + scene_relative_prim_path_to_absolute, + setup_collision_apis, +) +from omnigibson.utils.vision_utils import add_semantic_label + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.MIN_PARTICLE_RADIUS = ( + 0.01 # Minimum particle radius for physical macro particles -- this reduces the chance of omni physx crashing +) +m.MACRO_PARTICLE_SYSTEM_MAX_DENSITY = None # If set, the maximum density for macro particle systems + +m.MACRO_PHYSICAL_STATIC_FRICTION = 1.0 +m.MACRO_PHYSICAL_DYNAMIC_FRICTION = 0.8 +m.MACRO_PHYSICAL_RESTITUTION = 0.0 + + +class MacroParticleSystem(BaseSystem): + """ + Global system for modeling "macro" level particles, e.g.: dirt, dust, etc. + """ + + def __init__(self, name, **kwargs): + # Template object to use -- class particle objet is assumed to be the first and only visual mesh belonging to the + # root link of this template object, which symbolizes a single particle, and will be duplicated to generate the + # particle system. Note that this object is NOT part of the actual particle system itself! + self._particle_template = None + + # dict, array of particle objects, mapped by their prim names + self.particles = None + + # Counter to increment monotonically as we add more particles + self._particle_counter = 0 + + # Color associated with this system (NOTE: external queries should call self.color) + self._color = None + return super().__init__(name=name, **kwargs) + + def initialize(self, scene): + # Run super method first + super().initialize(scene) + + # Initialize mutable class variables so they don't automatically get overridden by children classes + self._particle_counter = 0 + + # Create the system prim -- this is merely a scope prim + with og.sim.editing_usd(): + og.sim.stage.DefinePrim(f"/World/scene_{scene.idx}/{self.name}", "Scope") + + # Load the particle template, and make it kinematic only because it's not interacting with anything + particle_template = self._create_particle_template() + scene.add_object(particle_template, register=False) + + # Make sure template scaling is [1, 1, 1] -- any particle scaling should be done via self.min/max_scale + assert th.all(particle_template.scale == 1.0) + + # Make sure there is no ambiguity about which mesh to use as the particle from this template + assert len(particle_template.links) == 1, "MacroParticleSystem particle template has more than one link" + assert ( + len(particle_template.root_link.visual_meshes) == 1 + ), "MacroParticleSystem particle template has more than one visual mesh" + + self._particle_template = particle_template + + # Class particle objet is assumed to be the first and only visual mesh belonging to the root link + self.process_particle_object() + + @property + def particle_object(self): + return list(self._particle_template.root_link.visual_meshes.values())[0] + + @property + def particle_idns(self): + """ + Returns: + set: idn of all the particles across all groups. + """ + return {self.particle_name2idn(particle_name) for particle_name in self.particles} if self.particles else set() + + @property + def next_available_particle_idn(self): + """ + Returns: + int: the next available particle idn across all groups. + """ + return self._particle_counter + + def _create_particle_template(self): + """ + Creates the particle template to be used for this system. + + NOTE: The loaded particle template is expected to be a non-articulated, single-link object with a single + visual mesh attached to its root link, since this will be the actual visual mesh used + + Returns: + EntityPrim: Particle template that will be duplicated when generating future particle groups + """ + raise NotImplementedError() + + def remove_all_particles(self): + # Use list explicitly to prevent mid-loop mutation of dict + if self.particles is not None: + for particle_name in tuple(self.particles.keys()): + self.remove_particle_by_name(name=particle_name) + + def reset(self): + # Call super first + super().reset() + + # Reset the particle counter + self._particle_counter = 0 + + def _clear(self): + # Clear all internal state + self.scene.remove_object(self._particle_template) + + super()._clear() + + self._particle_template = None + self.particles = None + self._color = None + + @property + def n_particles(self): + return len(self.particles) if self.particles is not None else 0 + + @property + def material(self): + return self.particle_object.material + + @property + def particle_name_prefix(self): + """ + Returns: + str: Naming prefix used for all generated particles. This is coupled with the unique particle ID to generate + the full particle name + """ + return f"{self.name}Particle" + + def _dump_state(self): + state = super()._dump_state() + state["scales"] = ( + th.stack([particle.scale for particle in self.particles.values()]) + if self.particles is not None and self.particles != {} + else th.empty(0) + ) + state["particle_counter"] = self._particle_counter + return state + + def _load_state(self, state): + # Run super first + super()._load_state(state=state) + + # Set particle scales + if self.particles is not None: + for particle, scale in zip(self.particles.values(), state["scales"]): + particle.scale = scale + + # Set counter to next available ID, or 0 if no particles exist + # TODO: remove particle counter from dump and load state after data collection + self._particle_counter = max(self.particle_idns) + 1 if self.particle_idns else 0 + + def serialize(self, state): + # Run super first + states_flat = super().serialize(state=state) + + # Add particle scales, then the template info + return th.cat( + [ + states_flat, + state["scales"].flatten(), + th.tensor([state["particle_counter"]], dtype=th.float32), + ] + ) + + def deserialize(self, state): + # Run super first + state_dict, idx = super().deserialize(state=state) + + # Infer how many scales we have, then deserialize + n_particles = state_dict["n_particles"] + len_scales = n_particles * 3 + state_dict["scales"] = state[idx : idx + len_scales].reshape(-1, 3) + state_dict["particle_counter"] = int(state[idx + len_scales]) + + return state_dict, idx + len_scales + 1 + + def process_particle_object(self): + """ + Perform any necessary processing on the particle object to extract further information. + """ + # Update color if the particle object has any material + color = th.ones(3) + if self.particle_object.has_material(): + color = self.particle_object.material.average_diffuse_color + self._color = color + + def add_particle(self, relative_prim_path, scale, idn=None): + """ + Adds a particle to this system. + + Args: + relative_prim_path (str): scene-local prim path to the newly created particle, minus the name for this particle + scale (3-array): (x,y,z) scale to set for the added particle + idn (None or int): If specified, should be unique identifier to assign to this particle. If not, will + automatically generate a new unique one + + Returns: + XFormPrim: Newly created particle instance, which is added internally as well + """ + # Generate the new particle + name = self.particle_idn2name(idn=self.next_available_particle_idn if idn is None else idn) + # Make sure name doesn't already exist + assert ( + self.particles is None or name not in self.particles.keys() + ), f"Cannot create particle with name {name} because it already exists!" + new_particle = self._load_new_particle(relative_prim_path=f"{relative_prim_path}/{name}", name=name) + + # Set the scale and make sure the particle is visible + new_particle.scale *= scale + new_particle.visible = True + + # Track this particle as well + if self.particles is None: + self.particles = dict() + self.particles[new_particle.name] = new_particle + + # Increment counter + self._particle_counter += 1 + + return new_particle + + def remove_particle_by_name(self, name): + assert name in self.particles, f"Got invalid name for particle to remove {name}" + particle = self.particles.pop(name) + og.sim.remove_prim(particle) + + def remove_particles( + self, + idxs, + **kwargs, + ): + particle_names = tuple(self.particles.keys()) if self.particles else [] + for idx in idxs: + self.remove_particle_by_name(particle_names[idx]) + + def generate_particles( + self, + positions, + orientations=None, + scales=None, + **kwargs, + ): + # Grab pre-existing tfs + current_positions, current_orientations = self.get_particles_position_orientation() + + # Update the tensors + n_particles = len(positions) + orientations = T.random_quaternion(n_particles) if orientations is None else orientations + scales = self.sample_scales(n=n_particles) if scales is None else scales + + positions = th.cat([current_positions, positions], dim=0) + orientations = th.cat([current_orientations, orientations], dim=0) + + # Add particles + for scale in scales: + self.add_particle(relative_prim_path=f"{self.relative_prim_path}/particles", scale=scale) + + # Set the tfs + self.set_particles_position_orientation(positions=positions, orientations=orientations) + + def _load_new_particle(self, relative_prim_path, name): + """ + Loads a new particle into the current stage, leveraging @self.particle_object as a template for the new particle + to load. This function should be implemented by any subclasses. + + Args: + relative_prim_path (str): scene-local prim path at which to create the new particle + name (str): The name to assign to this new particle at the path + + Returns: + XFormPrim: Loaded particle + """ + raise NotImplementedError() + + def particle_name2idn(self, name): + """ + Args: + name (str): Particle name to grab its corresponding unique id number for + + Returns: + int: Unique ID assigned to the particle based on its name + """ + assert ( + self.particle_name_prefix in name + ), f"Particle name should have '{self.particle_name_prefix}' in it when checking ID! Got: {name}" + return int(name.split(self.particle_name_prefix)[-1]) + + def particle_idn2name(self, idn): + """ + Args: + idn (int): Unique ID number assigned to the particle to grab the name for + + Returns: + str: Particle name corresponding to its unique id number + """ + assert isinstance( + idn, int + ), f"Particle idn must be an integer when checking name! Got: {idn}. Type: {type(idn)}" + return f"{self.particle_name_prefix}{idn}" + + @property + def color(self): + return th.tensor(self._color) + + +class MacroVisualParticleSystem(MacroParticleSystem, VisualParticleSystem): + """ + Particle system class that procedurally generates individual particles that are not subject to physics + """ + + def __init__( + self, + name, + create_particle_template, + min_scale=None, + max_scale=None, + scale_relative_to_parent=False, + sampling_axis_probabilities=(0.0, 0.0, 0.1), + sampling_aabb_offset=0.01, + sampling_bimodal_mean_fraction=1.0, + sampling_bimodal_stdev_fraction=1e-5, + sampling_max_attempts=20, + sampling_hit_proportion=0.4, + **kwargs, + ): + """ + Args: + name (str): Name of the visual particles, in snake case. + create_particle_template (function): Method for generating the visual particle template that will be duplicated + when generating groups of particles. + Expected signature: + + create_particle_template(prim_path: str, name: str) --> EntityPrim + + where @prim_path and @name are the parameters to assign to the generated EntityPrim. + NOTE: The loaded particle template is expected to be a non-articulated, single-link object with a single + visual mesh attached to its root link, since this will be the actual visual mesh used + min_scale (None or 3-array): If specified, sets the minumum bound for the visual particles' relative scale. + Else, defaults to 1 + max_scale (None or 3-array): If specified, sets the maximum bound for the visual particles' relative scale. + Else, defaults to 1 + scale_relative_to_parent (bool): If True, will scale generated particles relative to the corresponding + group's object + **kwargs (any): keyword-mapped parameters to override / set in the child class, where the keys represent + the class attribute to modify and the values represent the functions / value to set + (Note: These values should have either @classproperty or @classmethod decorators!) + """ + self._scale_relative_to_parent = scale_relative_to_parent + self._create_particle_template_fcn = create_particle_template + + # Maps particle name to dict of {obj, link, face_id} + # NOTE: link will only exist for particles on rigid bodies + # NOTE: face_id will only exist for particles on cloths + self._particles_info = None + + # Pre-cached information about visual particles so that we have efficient runtime computations + # Maps particle name to local pose matrix for computing global poses for the particle + self._particles_local_mat = None + + # Maps group name to array of face_ids where particles are located if the group object is a cloth type + # Maps group name to th.tensor of face IDs (int) that particles are attached to + self._cloth_face_ids = None + + # Default behavior for this class -- whether to clip generated particles halfway into objects when sampling + # their locations on the surface of the given object + self._CLIP_INTO_OBJECTS = False + + # Default parameters for sampling particle locations + # See omnigibson/utils/sampling_utils.py for how they are used. + self._SAMPLING_AXIS_PROBABILITIES = sampling_axis_probabilities + self._SAMPLING_AABB_OFFSET = sampling_aabb_offset + self._SAMPLING_BIMODAL_MEAN_FRACTION = sampling_bimodal_mean_fraction + self._SAMPLING_BIMODAL_STDEV_FRACTION = sampling_bimodal_stdev_fraction + self._SAMPLING_MAX_ATTEMPTS = sampling_max_attempts + self._SAMPLING_HIT_PROPORTION = sampling_hit_proportion + return super().__init__(name=name, min_scale=min_scale, max_scale=max_scale, **kwargs) + + def initialize(self, scene): + # Run super method first + super().initialize(scene) + + # Initialize mutable class variables so they don't automatically get overridden by children classes + self._particles_info = dict() + self._particles_local_mat = dict() + self._cloth_face_ids = dict() + + def update(self): + # Run super first + super().update() + + z_extent = self.particle_object.aabb_extent[2] + # Iterate over all objects, and update all particles belonging to any cloth objects + for name, obj in self._group_objects.items(): + group = self.get_group_name(obj=obj) + if obj.prim_type == PrimType.CLOTH and self.num_group_particles(group=group) > 0: + # Update the transforms + cloth = obj.root_link + face_ids = self._cloth_face_ids[group] + idxs = cloth.faces[face_ids].flatten() + positions = cloth.compute_particle_positions(idxs=idxs).reshape(-1, 3, 3) + normals = cloth.compute_face_normals_from_particle_positions(positions=positions) + + # The actual positions we want are the face centroids, or the mean of all the positions + positions = positions.mean(dim=1) + # Orientations are the normals + z_up = th.zeros_like(normals) + z_up[:, 2] = 1.0 + orientations = T.axisangle2quat(T.vecs2axisangle(z_up, normals)) + if not self._CLIP_INTO_OBJECTS and z_extent > 0: + z_offsets = ( + th.tensor([z_extent * particle.scale[2] for particle in self._group_particles[group].values()]) + / 2.0 + ) + # Shift the particles halfway up + positions += normals * z_offsets.reshape(-1, 1) + + # Set the group particle poses + self.set_group_particles_position_orientation( + group=group, positions=positions, orientations=orientations + ) + + def _load_new_particle(self, relative_prim_path, name): + # We copy the template prim and generate the new object if the prim doesn't already exist, otherwise we + # reference the pre-existing one + prim_path = scene_relative_prim_path_to_absolute(self.scene, relative_prim_path) + if not lazy.isaacsim.core.utils.prims.get_prim_at_path(prim_path): + with og.sim.editing_usd(): + lazy.omni.kit.commands.execute( + "CopyPrim", + path_from=self.particle_object.prim_path, + path_to=prim_path, + ) + prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(prim_path) + add_semantic_label(prim=prim, label=self.name) + result = GeomPrim(relative_prim_path=relative_prim_path, name=name) + result.load(self.scene) + return result + + def _clear(self): + # Run super method first + super()._clear() + + # Clear all groups as well + self._particles_info = dict() + self._particles_local_mat = dict() + self._cloth_face_ids = dict() + + def remove_attachment_group(self, group): + # Call super first + super().remove_attachment_group(group=group) + + # If the group is a cloth, also remove the cloth face ids + if group in self._cloth_face_ids: + self._cloth_face_ids.pop(group) + + return group + + def remove_particle_by_name(self, name): + # Run super first + super().remove_particle_by_name(name=name) + + # Remove this particle from its respective group as well + parent_obj = self._particles_info[name]["obj"] + group = self.get_group_name(obj=parent_obj) + self._group_particles[group].pop(name) + self._particles_local_mat.pop(name) + particle_info = self._particles_info.pop(name) + if self._is_cloth_obj(obj=parent_obj): + # Also remove from cloth face ids + face_ids = self._cloth_face_ids[group] + idx_mapping = {face_id: i for i, face_id in enumerate(face_ids)} + self._cloth_face_ids[group] = torch_delete(face_ids, idx_mapping[particle_info["face_id"]]) + + def generate_group_particles( + self, + group, + positions, + orientations=None, + scales=None, + link_prim_paths=None, + ): + # Make sure the group exists + self._validate_group(group=group) + + # Standardize orientations and links + obj = self._group_objects[group] + is_cloth = self._is_cloth_obj(obj=obj) + + # If cloth, run the following sanity checks: + # (1) make sure link prim paths are not specified -- we can ONLY apply particles under the object xform prim + # (2) make sure object prim path exists at /World/ -- global pose inference assumes this is the case + if is_cloth: + assert link_prim_paths is None, "link_prim_paths should not be specified for cloth object group!" + assert ( + obj.prim.GetParent().GetPath().pathString == "/World" + ), "cloth object should exist as direct child of /World prim!" + + n_particles = len(positions) + if orientations is None: + orientations = th.zeros((n_particles, 4)) + orientations[:, -1] = 1.0 + link_prim_paths = [None] * n_particles if is_cloth else link_prim_paths + + scales = self.sample_scales_by_group(group=group, n=n_particles) if scales is None else scales + + bbox_extents_local = [(self.particle_object.aabb_extent * scale).tolist() for scale in scales] + + # Generate particles + z_up = th.zeros((3, 1)) + z_up[-1] = 1.0 + for position, orientation, scale, bbox_extent_local, link_prim_path in zip( + positions, orientations, scales, bbox_extents_local, link_prim_paths + ): + link = None if is_cloth else obj.links[link_prim_path.split("/")[-1]] + # Possibly shift the particle slightly away from the object if we're not clipping into objects + # Note: For particles tied to rigid objects, the given position is on the surface of the object, + # so clipping would move the particle INTO the object surface, whereas for particles tied to cloth objects, + # the given position is at the particle location (i.e.: already clipped), so NO clipping would move the + # particle AWAY from the object surface + if (is_cloth and not self._CLIP_INTO_OBJECTS) or (not is_cloth and self._CLIP_INTO_OBJECTS): + # Shift the particle halfway down + base_to_center = bbox_extent_local[2] / 2.0 + normal = (T.quat2mat(orientation) @ z_up).flatten() + offset = normal * base_to_center if is_cloth else -normal * base_to_center + position += offset + + # Create particle + particle_prim_path = obj.prim_path if is_cloth else link_prim_path + particle = self.add_particle( + relative_prim_path=absolute_prim_path_to_scene_relative(self.scene, particle_prim_path), + scale=scale, + ) + + # Add to group + self._group_particles[group][particle.name] = particle + self._particles_info[particle.name] = dict(obj=self._group_objects[group], link=link) + + # Set the pose + self.set_particle_position_orientation(idx=-1, position=position, orientation=orientation) + + def generate_group_particles_on_object(self, group, max_samples=None, min_samples_for_success=1): + # This function does not support max_samples=None. Must be explicitly specified + assert ( + max_samples is not None + ), f"max_samples must be specified for {self.name}'s generate_group_particles_on_object!" + assert max_samples >= min_samples_for_success, "number of particles to sample should exceed the min for success" + + # Make sure the group exists + self._validate_group(group=group) + + # Remove all stale particles + self.remove_all_group_particles(group=group) + + # Generate requested number of particles + obj = self._group_objects[group] + + # Sample scales and corresponding bbox extents + scales = self.sample_scales_by_group(group=group, n=max_samples) + # For sampling particle positions, we need the global bbox extents, NOT the local extents + # which is what we would get naively if we directly use @scales + avg_scale = th.pow(th.prod(obj.scale), 1 / 3) + + bbox_extents_global = scales * self.particle_object.aabb_extent.reshape(1, 3) * avg_scale + + if obj.prim_type == PrimType.CLOTH: + # Sample locations based on randomly sampled keyfaces + cloth = obj.root_link + n_faces = len(cloth.faces) + face_ids = th.randperm(n_faces)[: min(max_samples, n_faces)] + # Positions are the midpoints of each requested face + normals = cloth.compute_face_normals(face_ids=face_ids) + positions = ( + cloth.compute_particle_positions(idxs=cloth.faces[face_ids].flatten()).reshape(-1, 3, 3).mean(dim=1) + ) + # Orientations are the normals + z_up = th.zeros_like(normals) + z_up[:, 2] = 1.0 + orientations = th.tensor(T.axisangle2quat(T.vecs2axisangle(z_up, normals))) + link_prim_paths = None + self._cloth_face_ids[group] = face_ids + else: + # "carpet" is in GROUND_CATEGORIES for navigation but rugs are movable furnishings, not structural floors + is_ground = obj.category in GROUND_CATEGORIES and obj.category != "carpet" + reachability_context = get_reachability_sampling_context(obj, predicate="onTop") if is_ground else None + # Sample locations for all particles + results = sample_cuboid_on_object_symmetric_bimodal_distribution( + obj=obj, + num_samples=max_samples, + cuboid_dimensions=bbox_extents_global, + bimodal_mean_fraction=self._SAMPLING_BIMODAL_MEAN_FRACTION, + bimodal_stdev_fraction=self._SAMPLING_BIMODAL_STDEV_FRACTION, + axis_probabilities=self._SAMPLING_AXIS_PROBABILITIES, + undo_cuboid_bottom_padding=True, + verify_cuboid_empty=is_ground, + aabb_offset=self._SAMPLING_AABB_OFFSET, + max_sampling_attempts=self._SAMPLING_MAX_ATTEMPTS, + refuse_downwards=True, + hit_proportion=self._SAMPLING_HIT_PROPORTION, + ) + + # Use sampled points + positions, orientations, particle_scales, link_prim_paths = [], [], [], [] + for result, scale in zip(results, scales): + position, normal, quaternion, hit_link, reasons = result + if position is not None: + if is_ground and not is_pose_reachable_for_predicate(position, obj, "onTop", reachability_context): + continue + positions.append(position) + orientations.append(quaternion) + particle_scales.append(scale) + link_prim_paths.append(hit_link) + scales = particle_scales + + success = len(positions) >= min_samples_for_success + # If we generated a sufficient number of points, generate them in the simulator + if success: + self.generate_group_particles( + group=group, + positions=positions, + orientations=orientations, + scales=scales, + link_prim_paths=link_prim_paths, + ) + # If we're a cloth, store the face_id as well + if obj.prim_type == PrimType.CLOTH: + for particle_name, face_id in zip(self._group_particles[group].keys(), self._cloth_face_ids[group]): + self._particles_info[particle_name]["face_id"] = int(face_id) + + return success + + def _compute_batch_particles_position_orientation(self, particles, local=False): + """ + Computes all @particles' positions and orientations + + Args: + particles (Iterable of str): Names of particles to compute batched position orientation for + local (bool): Whether to compute particles' poses in local frame or not + + Returns: + 2-tuple: + - (n, 3)-array: per-particle (x,y,z) position + - (n, 4)-array: per-particle (x,y,z,w) quaternion orientation + """ + n_particles = len(particles) if particles else 0 + if n_particles == 0: + return (th.empty(0).reshape(0, 3), th.empty(0).reshape(0, 4)) + + if local: + poses = th.zeros((n_particles, 4, 4)) + for i, name in enumerate(particles): + poses[i] = self._particles_local_mat[name] + else: + # Iterate over all particles and compute link tfs programmatically, then batch the matrix transform + link_tfs = dict() + link_tfs_batch = th.zeros((n_particles, 4, 4)) + particle_local_poses_batch = th.zeros_like(link_tfs_batch) + for i, name in enumerate(particles): + obj = self._particles_info[name]["obj"] + is_cloth = self._is_cloth_obj(obj=obj) + if is_cloth: + if obj not in link_tfs: + # We want World --> obj transform, NOT the World --> root_link transform, since these particles + # do NOT exist under a link but rather the object prim itself. So we use XFormPrim to directly + # get the transform, and not obj.get_position_orientation(frame="parent") which will give us the local pose of the + # root link! + link_tfs[obj] = obj.scaled_transform + link = obj + else: + link = self._particles_info[name]["link"] + if link not in link_tfs: + link_tfs[link] = link.scaled_transform + + link_tfs_batch[i] = link_tfs[link] + particle_local_poses_batch[i] = self._particles_local_mat[name] + + # Compute once + poses = link_tfs_batch @ particle_local_poses_batch + + # Decompose back into positions and orientations + return T.mat2pose_batched(poses) + + def get_particles_position_orientation(self): + return self._compute_batch_particles_position_orientation(particles=self.particles, local=False) + + def get_particles_local_pose(self): + return self._compute_batch_particles_position_orientation(particles=self.particles, local=True) + + def get_group_particles_position_orientation(self, group): + return self._compute_batch_particles_position_orientation(particles=self._group_particles[group], local=False) + + def get_group_particles_local_pose(self, group): + return self._compute_batch_particles_position_orientation(particles=self._group_particles[group], local=True) + + def get_particle_position_orientation(self, idx): + name = list(self.particles.keys())[idx] + # First, get local pose, scale it by the parent link's scale, and then convert into a matrix + # Note that particles_local_mat already takes the parent scale into account when computing the transform! + parent_obj = self._particles_info[name]["obj"] + is_cloth = self._is_cloth_obj(obj=parent_obj) + local_mat = self._particles_local_mat[name] + # link_tf = ( + # T.pose2mat(XFormPrim.get_position_orientation(parent_obj, frame="parent")) + # if is_cloth + # else T.pose2mat(self._particles_info[name]["link"].get_position_orientation()) + # ) + + link_tf = parent_obj.scaled_transform if is_cloth else self._particles_info[name]["link"].scaled_transform + + # Multiply the local pose by the link's global transform, then return as pos, quat tuple + return T.mat2pose(link_tf @ local_mat) + + def get_particle_local_pose(self, idx): + name = list(self.particles.keys())[idx] + return self.particles[name].get_position_orientation(frame="parent") + + def _modify_batch_particles_position_orientation(self, particles, positions=None, orientations=None, local=False): + """ + Modifies all @particles' positions and orientations with @positions and @orientations + + Args: + particles (Iterable of str): Names of particles to modify + positions (None or (n, 3)-array): New positions to set for the particles + orientations (None or (n, 4)-array): New orientations to set for the particles + local (bool): Whether to modify particles' poses in local frame or not + + Returns: + 2-tuple: + - (n, 3)-array: per-particle (x,y,z) position + - (n, 4)-array: per-particle (x,y,z,w) quaternion orientation + """ + n_particles = len(particles) if particles is not None else 0 + if n_particles == 0: + return + + if positions is None or orientations is None: + pos, ori = self._compute_batch_particles_position_orientation(particles=particles, local=local) + positions = pos if positions is None else positions + orientations = ori if orientations is None else orientations + lens = th.tensor([len(particles), len(positions), len(orientations)]) + assert lens.min() == lens.max(), "Got mismatched particles, positions, and orientations!" + + particle_local_poses_batch = th.zeros((n_particles, 4, 4)) + particle_local_poses_batch[:, -1, -1] = 1.0 + particle_local_poses_batch[:, :3, 3] = positions + particle_local_poses_batch[:, :3, :3] = T.quat2mat(orientations) + + if not local: + # Iterate over all particles and compute link tfs programmatically, then batch the matrix transform + link_tfs = dict() + link_tfs_batch = th.zeros((n_particles, 4, 4)) + for i, name in enumerate(particles): + obj = self._particles_info[name]["obj"] + is_cloth = self._is_cloth_obj(obj=obj) + if is_cloth: + if obj not in link_tfs: + # We want World --> obj transform, NOT the World --> root_link transform, since these particles + # do NOT exist under a link but rather the object prim itself. So we use XFormPrim to directly + # get the transform, and not obj.get_position_orientation(frame="parent") which will give us the local pose of the + # root link! + link_tfs[obj] = obj.scaled_transform + link_tf = link_tfs[obj] + else: + link = self._particles_info[name]["link"] + if link not in link_tfs: + link_tfs[link] = link.scaled_transform + link_tf = link_tfs[link] + link_tfs_batch[i] = link_tf + + # particle_local_poses_batch = th.linalg.inv_ex(link_tfs_batch).inverse @ particle_local_poses_batch + particle_local_poses_batch = th.linalg.solve(link_tfs_batch, particle_local_poses_batch) + # Make sure this is a valid homogeneous matrix (lower-left three elements all 0) + particle_local_poses_batch[:, 3, :3] = 0.0 + + for i, name in enumerate(particles): + self._modify_particle_local_mat(name=name, mat=particle_local_poses_batch[i]) + + def set_particles_position_orientation(self, positions=None, orientations=None): + return self._modify_batch_particles_position_orientation( + particles=self.particles, positions=positions, orientations=orientations, local=False + ) + + def set_particles_local_pose(self, positions=None, orientations=None): + return self._modify_batch_particles_position_orientation( + particles=self.particles, positions=positions, orientations=orientations, local=True + ) + + def set_group_particles_position_orientation(self, group, positions=None, orientations=None): + return self._modify_batch_particles_position_orientation( + particles=self._group_particles[group], positions=positions, orientations=orientations, local=False + ) + + def set_group_particles_local_pose(self, group, positions=None, orientations=None): + return self._modify_batch_particles_position_orientation( + particles=self._group_particles[group], positions=positions, orientations=orientations, local=True + ) + + def set_particle_position_orientation(self, idx, position=None, orientation=None): + if position is None or orientation is None: + pos, ori = self.get_particle_position_orientation(idx=idx) + position = pos if position is None else position + orientation = ori if orientation is None else orientation + + position = position if isinstance(position, th.Tensor) else th.tensor(position, dtype=th.float32) + orientation = orientation if isinstance(orientation, th.Tensor) else th.tensor(orientation, dtype=th.float32) + + name = list(self.particles.keys())[idx] + global_mat = th.zeros((4, 4)) + global_mat[-1, -1] = 1.0 + global_mat[:3, 3] = position + global_mat[:3, :3] = T.quat2mat(orientation) + # First, get global pose, scale it by the parent link's scale, and then convert into a matrix + parent_obj = self._particles_info[name]["obj"] + is_cloth = self._is_cloth_obj(obj=parent_obj) + link_tf = parent_obj.scaled_transform if is_cloth else self._particles_info[name]["link"].scaled_transform + local_mat = th.linalg.inv_ex(link_tf).inverse @ global_mat + + self._modify_particle_local_mat(name=name, mat=local_mat) + + def set_particle_local_pose(self, idx, position=None, orientation=None): + if position is None or orientation is None: + pos, ori = self.get_particle_local_pose(idx=idx) + position = pos if position is None else position + orientation = ori if orientation is None else orientation + + position = position if isinstance(position, th.Tensor) else th.tensor(position, dtype=th.float32) + orientation = orientation if isinstance(orientation, th.Tensor) else th.tensor(orientation, dtype=th.float32) + + name = list(self.particles.keys())[idx] + local_mat = th.zeros((4, 4)) + local_mat[-1, -1] = 1.0 + local_mat[:3, 3] = position + local_mat[:3, :3] = T.quat2mat(orientation) + self._modify_particle_local_mat(name=name, mat=local_mat) + + def _is_cloth_obj(self, obj): + """ + Checks whether object @obj is a cloth or not + + Args: + obj (USDObject): Object to check + + Returns: + bool: True if the object is cloth type, otherwise False + """ + return obj.prim_type == PrimType.CLOTH + + def _compute_particle_local_mat(self, name): + """ + Computes particle @name's local transform as a homogeneous 4x4 matrix + + Args: + name (str): Name of the particle to compute local transform matrix for + + Returns: + th.tensor: (4, 4) homogeneous transform matrix + """ + particle = self.particles[name] + local_pos, local_quat = particle.get_position_orientation(frame="parent") + return T.pose2mat((local_pos, local_quat)) + + def _modify_particle_local_mat(self, name, mat): + """ + Sets particle @name's local transform as a homogeneous 4x4 matrix + + Args: + name (str): Name of the particle to compute local transform matrix for + mat (n-array): (4, 4) homogeneous transform matrix + """ + particle = self.particles[name] + local_pos, local_quat = T.mat2pose(mat) + particle.set_position_orientation(position=local_pos, orientation=local_quat, frame="parent") + + # Store updated value + self._particles_local_mat[name] = mat + + def _sync_particle_groups( + self, + group_objects, + particle_idns, + particle_attached_references, + ): + """ + Synchronizes the particle groups based on desired identification numbers @group_idns + + Args: + group_objects (list of USDObject): Desired unique group objects that should be active for + this particle system. + particle_idns (list of list of int): Per-group unique id numbers for the particles assigned to that group. + List should be same length as @group_idns with sub-entries corresponding to the desired number of + particles assigned to that group + particle_attached_references (list of list of str or int): Per-group reference info relevant for each + particle. List should be same length as @group_idns with sub-entries corresponding to the desired + number of particles assigned to that group. If a given group is a cloth object, the entries should be + integers corresponding to the individual face IDs that each particle is attached to for the group. + Otherwise, the group is assumed to be a rigid object, in which case the entries should be link + names corresponding to the specific links each particle is attached for each group. + """ + # We have to be careful here -- some particle groups may have been deleted / are mismatched, so we need + # to update accordingly, potentially deleting stale groups and creating new groups as needed + name_to_info_mapping = { + obj.name: { + "n_particles": len(p_idns), + "particle_idns": p_idns, + "references": references, + } + for obj, p_idns, references in zip(group_objects, particle_idns, particle_attached_references) + } + + current_group_names = self.groups + # Preserve original order by using list comprehension instead of set + desired_group_names_ordered = [obj.name for obj in group_objects] + desired_group_names_set = set(desired_group_names_ordered) + groups_to_delete = [name for name in current_group_names if name not in desired_group_names_set] + groups_to_create = [name for name in desired_group_names_ordered if name not in current_group_names] + common_groups = [name for name in desired_group_names_ordered if name in current_group_names] + + # Sanity check the common groups, we will recreate any where there is a mismatch + for name in common_groups: + info = name_to_info_mapping[name] + current_idns = {self.particle_name2idn(p_name) for p_name in self._group_particles[name]} + desired_idns = {int(idn) for idn in info["particle_idns"]} + if current_idns != desired_idns: + log.debug(f"Got mismatch in particle group {name} when syncing, deleting and recreating group now.") + # Add this group to both the delete and creation pile + groups_to_delete.append(name) + groups_to_create.append(name) + + # Delete any groups we no longer want + for name in groups_to_delete: + self.remove_attachment_group(group=name) + + # Create any groups we don't already have + for name in groups_to_create: + obj = self.scene.object_registry("name", name) + info = name_to_info_mapping[name] + self.create_attachment_group(obj=obj) + is_cloth = self._is_cloth_obj(obj=obj) + for particle_idn, reference in zip(info["particle_idns"], info["references"]): + # Reference is either the face ID (int) if cloth group or link name (str) if rigid body group + # Create the necessary particles + # Use scale (1,1,1) since it will get overridden anyways when loading state + particle_prim_path = obj.prim_path if is_cloth else obj.links[reference].prim_path + particle = self.add_particle( + relative_prim_path=absolute_prim_path_to_scene_relative(self.scene, particle_prim_path), + scale=th.ones(3), + idn=int(particle_idn), + ) + self._group_particles[name][particle.name] = particle + self._particles_info[particle.name] = dict(obj=obj) + # Add face_id if is_cloth, otherwise, add link + if is_cloth: + self._particles_info[particle.name]["face_id"] = int(reference) + else: + self._particles_info[particle.name]["link"] = obj.links[reference] + + # Also store the cloth face IDs as a vector + if is_cloth: + self._cloth_face_ids[self.get_group_name(obj)] = th.tensor( + [self._particles_info[particle_name]["face_id"] for particle_name in self._group_particles[name]] + ) + + @property + def _register_system(self): + return True + + def _create_particle_template(self): + return self._create_particle_template_fcn( + relative_prim_path=f"/{self.name}/template", name=f"{self.name}_template" + ) + + def _dump_state(self): + state = super()._dump_state() + particle_names = list(self.particles.keys()) if self.particles else [] + # Add in per-group information + groups_dict = dict() + name2idx = {name: idx for idx, name in enumerate(particle_names)} + for group_name, group_particles in self._group_particles.items(): + obj = self._group_objects[group_name] + is_cloth = self._is_cloth_obj(obj=obj) + groups_dict[group_name] = dict( + particle_attached_obj_uuid=obj.uuid, + n_particles=self.num_group_particles(group=group_name), + particle_idns=[self.particle_name2idn(name=name) for name in group_particles.keys()], + particle_indices=[name2idx[name] for name in group_particles.keys()], + # If the attached object is a cloth, store the face_id, otherwise, store the link name + particle_attached_references=( + [self._particles_info[name]["face_id"] for name in group_particles.keys()] + if is_cloth + else [ + self._particles_info[name]["link"].prim_path.split("/")[-1] for name in group_particles.keys() + ] + ), + ) + + state["n_groups"] = len(self._group_particles) + state["groups"] = groups_dict + + return state + + def _load_state(self, state): + # First, we sync our particle systems + """ + Load the internal state to this object as specified by @state. Should be implemented by subclass. + + Args: + state (dict): Keyword-mapped states of this object to set + """ + # Synchronize particle groups + group_objects = [] + particle_idns = [] + particle_attached_references = [] + + indices_to_remove = th.empty(0, dtype=int) + for info in state["groups"].values(): + obj = self.scene.object_registry("uuid", info["particle_attached_obj_uuid"]) + # obj will be None if an object with an attachment group is removed between dump_state() and load_state() + if obj is not None: + group_objects.append(obj) + particle_idns.append(info["particle_idns"]) + particle_attached_references.append(info["particle_attached_references"]) + else: + indices_to_remove = th.cat((indices_to_remove, th.tensor(info["particle_indices"], dtype=int))) + self._sync_particle_groups( + group_objects=group_objects, + particle_idns=particle_idns, + particle_attached_references=particle_attached_references, + ) + state["n_particles"] -= len(indices_to_remove) + state["positions"] = torch_delete(state["positions"], indices_to_remove, dim=0) + state["orientations"] = torch_delete(state["orientations"], indices_to_remove, dim=0) + state["scales"] = torch_delete(state["scales"], indices_to_remove, dim=0) + + # Run super + super()._load_state(state=state) + + def serialize(self, state): + # Run super first + state_flat = super().serialize(state=state) + + groups_dict = state["groups"] + state_group_flat = [th.tensor([state["n_groups"]], dtype=th.float32)] + for group_name, group_dict in groups_dict.items(): + obj = self._group_objects[group_name] + is_cloth = self._is_cloth_obj(obj=obj) + group_obj_link2id = {link_name: i for i, link_name in enumerate(obj.links.keys())} + state_group_flat += [ + th.tensor([group_dict["particle_attached_obj_uuid"]], dtype=th.float32), + th.tensor([group_dict["n_particles"]], dtype=th.float32), + th.tensor(group_dict["particle_idns"], dtype=th.float32), + th.tensor(group_dict["particle_indices"], dtype=th.float32), + th.tensor( + ( + group_dict["particle_attached_references"] + if is_cloth + else [group_obj_link2id[reference] for reference in group_dict["particle_attached_references"]] + ), + dtype=th.float32, + ), + ] + + return th.cat([*state_group_flat, state_flat]) + + def deserialize(self, state): + # Synchronize the particle groups + n_groups = int(state[0]) + groups_dict = dict() + group_objs = [] + # Index starts at 1 because index 0 is n_groups + idx = 1 + for i in range(n_groups): + obj_uuid, n_particles = int(state[idx]), int(state[idx + 1]) + obj = self.scene.object_registry("uuid", obj_uuid) + assert obj is not None, f"Object with UUID {obj_uuid} not found in the scene" + is_cloth = self._is_cloth_obj(obj=obj) + group_obj_id2link = {i: link_name for i, link_name in enumerate(obj.links.keys())} + group_objs.append(obj) + groups_dict[obj.name] = dict( + particle_attached_obj_uuid=obj_uuid, + n_particles=n_particles, + particle_idns=[ + int(idn) for idn in state[idx + 2 : idx + 2 + n_particles] + ], # Idx + 2 because the first two are obj_uuid and n_particles + particle_indices=[int(idn) for idn in state[idx + 2 + n_particles : idx + 2 + n_particles * 2]], + particle_attached_references=( + [int(idn) for idn in state[idx + 2 + n_particles * 2 : idx + 2 + n_particles * 3]] + if is_cloth + else [ + group_obj_id2link[int(idn)] + for idn in state[idx + 2 + n_particles * 2 : idx + 2 + n_particles * 3] + ] + ), + ) + idx += 2 + n_particles * 3 + + log.debug(f"Syncing {self.name} particles with {n_groups} groups..") + self._sync_particle_groups( + group_objects=group_objs, + particle_idns=[group_info["particle_idns"] for group_info in groups_dict.values()], + particle_attached_references=[ + group_info["particle_attached_references"] for group_info in groups_dict.values() + ], + ) + + # Get super method + state_dict, idx_super = super().deserialize(state=state[idx:]) + state_dict["n_groups"] = n_groups + state_dict["groups"] = groups_dict + + return state_dict, idx + idx_super + + +class MacroPhysicalParticleSystem(MacroParticleSystem, PhysicalParticleSystem): + """ + Particle system class that procedurally generates individual particles that are subject to physics + """ + + def __init__(self, name, create_particle_template, particle_density, scale=None, **kwargs): + """ + Args: + name (str): Name of the macro physical particles, in snake case. + create_particle_template (function): Method for generating the visual particle template that will be duplicated + when generating groups of particles. + Expected signature: + + create_particle_template(prim_path: str, name: str) --> EntityPrim + + where @prim_path and @name are the parameters to assign to the generated EntityPrim. + NOTE: The loaded particle template is expected to be a non-articulated, single-link object with a single + visual mesh attached to its root link, since this will be the actual mesh used for duplication + particle_density (float): Particle density for the generated system + scale (None or 3-array): If specified, sets the scaling factor for the particles' relative scale. + Else, defaults to 1 + + **kwargs (any): keyword-mapped parameters to override / set in the child class, where the keys represent + the class attribute to modify and the values represent the functions / value to set + (Note: These values should have either @classproperty or @classmethod decorators!) + """ + # Run super + super().__init__(name=name, min_scale=scale, max_scale=scale, **kwargs) + + self._create_particle_template_fcn = create_particle_template + + self._particle_density = ( + particle_density + if m.MACRO_PARTICLE_SYSTEM_MAX_DENSITY is None + else min(particle_density, m.MACRO_PARTICLE_SYSTEM_MAX_DENSITY) + ) + + # Physics rigid body view for keeping track of all particles' state + self.particles_view = None + + # Approximate radius of the macro particle, and distance from particle frame to approximate center + self._particle_radius = None + self._particle_offset = None + + # Physics material + self.particle_physics_material = None + + def initialize(self, scene): + # Run super method first + super().initialize(scene) + + # Create the particles head prim -- this is merely a scope prim + with og.sim.editing_usd(): + og.sim.stage.DefinePrim(f"{self.prim_path}/particles", "Scope") + + # Physics material to apply to the particles + self.particle_physics_material = lazy.isaacsim.core.api.materials.PhysicsMaterial( + prim_path=f"{self.prim_path}/material", + name=f"{self.name}_physics_material", + static_friction=m.MACRO_PHYSICAL_STATIC_FRICTION, + dynamic_friction=m.MACRO_PHYSICAL_DYNAMIC_FRICTION, + restitution=m.MACRO_PHYSICAL_RESTITUTION, + ) + + # Create the particles view. + self.update_handles() + + def _load_new_particle(self, relative_prim_path, name): + # We copy the template prim and generate the new object if the prim doesn't already exist, otherwise we + # reference the pre-existing one + prim_path = scene_relative_prim_path_to_absolute(self.scene, relative_prim_path) + if not lazy.isaacsim.core.utils.prims.get_prim_at_path(prim_path): + with og.sim.editing_usd(): + lazy.omni.kit.commands.execute( + "CopyPrim", + path_from=self.particle_object.prim_path, + path_to=prim_path, + ) + # Apply RigidBodyAPI to it so it is subject to physics + prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(prim_path) + ensure_usd_api(prim, lazy.pxr.UsdPhysics.RigidBodyAPI) + mass_api = ensure_usd_api(prim, lazy.pxr.UsdPhysics.MassAPI) + with og.sim.editing_usd(): + mass_api.GetDensityAttr().Set(self.particle_density) + add_semantic_label(prim=prim, label=self.name) + result = GeomPrim(relative_prim_path=relative_prim_path, name=name) + result.load(self.scene) + setup_collision_apis(result.prim) + result.apply_physics_material(self.particle_physics_material) + return result + + def process_particle_object(self): + # Run super method + super().process_particle_object() + + # Compute particle radius + vertices = ( + th.tensor(self.particle_object.get_attribute("points")) + * self.particle_object.scale + * self.max_scale.reshape(1, 3) + ) + + particle_offset, particle_radius = trimesh.nsphere.minimum_nsphere(trimesh.Trimesh(vertices=vertices)) + particle_offset = th.tensor(particle_offset, dtype=th.float32) + particle_radius = th.tensor(particle_radius, dtype=th.float32) + + if particle_radius < m.MIN_PARTICLE_RADIUS: + ratio = m.MIN_PARTICLE_RADIUS / particle_radius + self.particle_object.scale *= ratio + particle_offset *= ratio + particle_radius = m.MIN_PARTICLE_RADIUS + + self._particle_offset = particle_offset + self._particle_radius = particle_radius + + def update_handles(self): + """ + Internal helper method to update the particles' rigid body view to grab state + + This is called through og.sim.update_handles when the physx object count etc. changes. + """ + if not og.sim.is_playing() or og.sim.physics_sim_view is None: + self.particles_view = None + return + with suppress_omni_log(channels=["omni.physx.tensors.plugin"]): + self.particles_view = og.sim.physics_sim_view.create_rigid_body_view( + pattern=f"{self.prim_path}/particles/*" + ) + + def _clear(self): + # Run super method first + super()._clear() + + # Clear internal variables + self.particles_view = None + self._particle_radius = None + self._particle_offset = None + + # Remove callback + og.sim.remove_callback_on_play(name=f"{self.name}_particles_view") + + def remove_particle_by_name(self, name): + # Run super first + super().remove_particle_by_name(name=name) + + # Update the handles + og.sim.update_handles() + + def add_particle(self, relative_prim_path, scale, idn=None): + # Run super first + particle = super().add_particle(relative_prim_path=relative_prim_path, scale=scale, idn=idn) + + # Update the handles + og.sim.update_handles() + + return particle + + def get_particles_position_orientation(self): + # Note: This gets the center of the sphere approximation of the particles, NOT the actual particle frames! + if self.n_particles > 0: + tfs = self.particles_view.get_transforms() + pos, ori = tfs[:, :3], tfs[:, 3:] + pos = pos + T.quat2mat(ori) @ self._particle_offset + else: + pos, ori = th.empty(0).reshape(0, 3), th.empty(0).reshape(0, 4) + return pos, ori + + def get_particles_local_pose(self): + return self.get_particles_position_orientation() + + def get_particle_position_orientation(self, idx): + assert ( + idx <= self.n_particles + ), f"Got invalid idx for getting particle pose! N particles: {self.n_particles}, got idx: {idx}" + positions, orientations = self.get_particles_position_orientation() + return (positions[idx], orientations[idx]) if self.n_particles > 0 else (positions, orientations) + + def get_particle_local_pose(self, idx): + return self.get_particle_position_orientation(idx=idx) + + def set_particles_position_orientation(self, positions=None, orientations=None): + if self.n_particles == 0: + return + + # Note: This sets the center of the sphere approximation of the particles, NOT the actual particle frames! + if positions is None or orientations is None: + pos, ori = self.get_particles_position_orientation() + orientations = ori if orientations is None else orientations + positions = pos if positions is None else (positions - T.quat2mat(orientations) @ self._particle_offset) + self.particles_view.set_transforms(th.cat([positions, orientations], dim=1), indices=th.arange(len(positions))) + + def set_particles_local_pose(self, positions=None, orientations=None): + self.set_particles_position_orientation(positions=positions, orientations=orientations) + + def set_particle_position_orientation(self, idx, position=None, orientation=None): + assert ( + idx <= self.n_particles + ), f"Got invalid idx for setting particle pose! N particles: {self.n_particles}, got idx: {idx}" + if position is None or orientation is None: + pos, ori = self.get_particle_position_orientation(idx=idx) + orientation = ori if orientation is None else orientation + position = pos if position is None else (position - T.quat2mat(orientation) @ self._particle_offset) + self.particles_view.set_transforms(th.cat([position, orientation]).reshape(1, -1), indices=th.tensor([idx])) + + def set_particle_local_pose(self, idx, position=None, orientation=None): + self.set_particle_position_orientation(idx=idx, position=position, orientation=orientation) + + def get_particles_velocities(self): + """ + Grab particles' global linear and angular velocities + + Returns: + 2-tuple: + - (n, 3)-array: per-particle (x, y, z) linear velocities in the world frame + - (n, 3)-array: per-particle (ax, ay, az) angular velocities in the world frame + """ + if self.n_particles > 0: + vels = self.particles_view.get_velocities() + lin_vel, ang_vel = vels[:, :3], vels[:, 3:] + else: + lin_vel, ang_vel = th.empty(0).reshape(0, 3), th.empty(0).reshape(0, 3) + return lin_vel, ang_vel + + def get_particle_velocities(self, idx): + """ + Grab particle @idx's global linear and angular velocities + + Returns: + 2-tuple: + - 3-array: particle (x, y, z) linear velocity in the world frame + - 3-array: particle (ax, ay, az) angular velocity in the world frame + """ + assert ( + idx <= self.n_particles + ), f"Got invalid idx for getting particle velocity! N particles: {self.n_particles}, got idx: {idx}" + lin_vel, ang_vel = self.get_particles_velocities() + return (lin_vel[idx], ang_vel[idx]) if self.n_particles > 0 else lin_vel, ang_vel + + def set_particles_velocities(self, lin_vels=None, ang_vels=None): + if self.n_particles == 0: + return + + if lin_vels is None or ang_vels is None: + l_vels, a_vels = self.get_particles_velocities() + lin_vels = l_vels if lin_vels is None else lin_vels + ang_vels = a_vels if ang_vels is None else ang_vels + self.particles_view.set_velocities(th.cat([lin_vels, ang_vels], dim=1), indices=th.arange(len(lin_vels))) + + def set_particle_velocities(self, idx, lin_vel=None, ang_vel=None): + assert ( + idx <= self.n_particles + ), f"Got invalid idx for setting particle velocity! N particles: {self.n_particles}, got idx: {idx}" + if lin_vel is None or ang_vel is None: + l_vel, a_vel = self.get_particles_velocities() + lin_vel = l_vel if lin_vel is None else lin_vel + ang_vel = a_vel if ang_vel is None else ang_vel + self.particles_view.set_velocities(th.cat([lin_vel, ang_vel]).reshape(1, -1), indices=th.tensor([idx])) + + @property + def particle_radius(self): + return self._particle_radius + + @property + def particle_contact_radius(self): + # This is simply the normal radius + return self.particle_radius + + @property + def particle_density(self): + """ + Returns: + float: Particle density for the generated system + """ + return self._particle_density + + def generate_particles( + self, + positions, + orientations=None, + velocities=None, + angular_velocities=None, + scales=None, + **kwargs, + ): + """ + Generates new particles + + Args: + positions (th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) positions + orientations (None or th.tensor): (n_particles, 4) shaped array specifying per-particle (x,y,z,w) quaternion + orientations. If not specified, all will be sampled randomly + velocities (None or th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) velocities. + If not specified, all will be set to 0 + angular_velocities (None or th.tensor): (n_particles, 3) shaped array specifying per-particle (ax,ay,az) + angular velocities. If not specified, all will be set to 0 + scales (None or th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) scales. + If not specified, will be uniformly randomly sampled from (self.min_scale, self.max_scale) + **kwargs (dict): Any additional keyword-specific arguments required by subclass implementation + """ + if not isinstance(positions, th.Tensor): + positions = th.tensor(positions, dtype=th.float32) + + # Call super first + super().generate_particles( + positions=positions, + orientations=orientations, + scales=scales, + **kwargs, + ) + + # Grab pre-existing vels -- note that this already includes the newly included particles, so we will only + # keep the first (N - n_new) values + current_lin_vels, current_ang_vels = self.get_particles_velocities() + + # Update the tensors + n_particles = len(positions) + velocities = th.zeros((n_particles, 3)) if velocities is None else velocities + angular_velocities = th.zeros_like(velocities) if angular_velocities is None else angular_velocities + + velocities = th.cat([current_lin_vels[:-n_particles], velocities], dim=0) + angular_velocities = th.cat([current_ang_vels[:-n_particles], angular_velocities], dim=0) + + # Set the vels + self.set_particles_velocities(lin_vels=velocities, ang_vels=angular_velocities) + + @property + def _register_system(self): + return True + + def _create_particle_template(self): + return self._create_particle_template_fcn( + relative_prim_path=f"/{self.name}/template", name=f"{self.name}_template" + ) + + def _sync_particles(self, n_particles): + """ + Synchronizes the number of particles seen in the scene with @n_particles + + Args: + n_particles (int): Desired number of particles to force simulator to have + """ + # Get the difference between current and desired particles + n_particles_to_generate = n_particles - self.n_particles + + # If positive, add particles + if n_particles_to_generate > 0: + for i in range(n_particles_to_generate): + # Min scale == max scale, so no need for sampling + self.add_particle(relative_prim_path=f"{self.relative_prim_path}/particles", scale=self.max_scale) + else: + # Remove excess particles + self.remove_particles(idxs=th.arange(-n_particles_to_generate)) + + def _dump_state(self): + state = super()._dump_state() + + # Store all particles' velocities as well + state["lin_velocities"], state["ang_velocities"] = self.get_particles_velocities() + + return state + + def _load_state(self, state): + # Sync the number of particles first + self._sync_particles(n_particles=state["n_particles"]) + + super()._load_state(state=state) + + # Make sure we update all the velocities + self.set_particles_velocities(state["lin_velocities"], state["ang_velocities"]) + + def serialize(self, state): + # Run super first + state_flat = super().serialize(state=state) + + # Add velocities + return th.cat([state_flat, state["lin_velocities"].flatten(), state["ang_velocities"].flatten()]) + + def deserialize(self, state): + # Sync the number of particles first + self._sync_particles(n_particles=int(state[0])) + + # Run super first + state_dict, idx = super().deserialize(state=state) + + # Deserialize velocities + len_velocities = 3 * state_dict["n_particles"] + for vel in ("lin_velocities", "ang_velocities"): + state_dict[vel] = state[idx : idx + len_velocities].reshape(-1, 3) + idx += len_velocities + + return state_dict, idx diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/systems/micro_particle_system.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/systems/micro_particle_system.py new file mode 100644 index 0000000000000000000000000000000000000000..736bd48fcd507993546f5ef9be33eaadcacf85b0 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/systems/micro_particle_system.py @@ -0,0 +1,1640 @@ +import math + +import torch as th +import trimesh + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.macros import create_module_macros, gm +from omnigibson.prims.geom_prim import GeomPrim +from omnigibson.prims.material_prim import OmniPBRMaterialPrim, OmniSurfaceMaterialPrim +from omnigibson.prims.prim_base import BasePrim +from omnigibson.systems.system_base import BaseSystem, PhysicalParticleSystem +from omnigibson.utils.numpy_utils import vtarray_to_torch +from omnigibson.utils.physx_utils import create_physx_particle_system, create_physx_particleset_pointinstancer +from omnigibson.utils.python_utils import assert_valid_key, torch_delete +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import ( + absolute_prim_path_to_scene_relative, + create_primitive_mesh, + scene_relative_prim_path_to_absolute, +) +from omnigibson.utils.vision_utils import add_semantic_label + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.CLOTH_PARTICLE_CONTACT_OFFSET = 0.0075 +m.CLOTH_STRETCH_STIFFNESS = 100.0 +m.CLOTH_BEND_STIFFNESS = 50.0 +m.CLOTH_SHEAR_STIFFNESS = 70.0 +m.CLOTH_DAMPING = 0.02 +m.CLOTH_FRICTION = 0.4 +m.CLOTH_DRAG = 0.001 +m.CLOTH_LIFT = 0.003 +m.MIN_PARTICLE_CONTACT_OFFSET = 0.005 # Minimum particle contact offset for physical micro particles +m.MICRO_PARTICLE_SYSTEM_MAX_VELOCITY = None # If set, the maximum particle velocity for micro particle systems + + +class PhysxParticleInstancer(BasePrim): + """ + Simple class that wraps the raw omniverse point instancer prim and provides convenience functions for + particle access + """ + + def __init__(self, relative_prim_path, name, idn): + """ + Args: + relative_prim_path (str): scene-local prim path of the Instancer to encapsulate or create. + name (str): Name for the object. Names need to be unique per scene. + idn (int): Unique identification number to assign to this particle instancer. This is used to + deterministically reproduce individual particle instancer states dynamically, even if we + delete / add additional ones at runtime during simulation. + """ + # Store inputs + self._idn = idn + + # Run super method directly + super().__init__(relative_prim_path=relative_prim_path, name=name) + + def _load(self): + # We raise an error, this should NOT be created from scratch + raise NotImplementedError("PhysxPointInstancer should NOT be loaded via this class! Should be created before.") + + def remove(self): + # We need to create this parent prim to avoid calling the low level omniverse delete prim method + parent_absolute_path = self.prim.GetParent().GetPath().pathString + parent_relative_path = absolute_prim_path_to_scene_relative(self.scene, parent_absolute_path) + self._parent_prim = BasePrim(relative_prim_path=parent_relative_path, name=f"{self._name}_parent") + self._parent_prim.load(self.scene) + super().remove() + self._parent_prim.remove() + + def add_particles( + self, + positions, + velocities=None, + orientations=None, + scales=None, + prototype_indices=None, + ): + """ + Adds particles to this particle instancer. + + positions (th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) positions. + velocities (None or th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) velocities. + If not specified, all will be set to 0 + orientations (None or th.tensor): (n_particles, 4) shaped array specifying per-particle (x,y,z,w) quaternion + orientations. If not specified, all will be set to canonical orientation (0, 0, 0, 1) + scales (None or th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) scales. + If not specified, will be scale [1, 1, 1] by default + prototype_indices (None or list of int): If specified, should specify which prototype should be used for + each particle. If None, will use all 0s (i.e.: the first prototype created) + """ + n_new_particles = len(positions) + + velocities = th.zeros((n_new_particles, 3)) if velocities is None else velocities + if orientations is None: + orientations = th.zeros((n_new_particles, 4)) + orientations[:, -1] = 1.0 + scales = th.ones((n_new_particles, 3)) * th.ones((1, 3)) if scales is None else scales + prototype_indices = th.zeros(n_new_particles, dtype=int) if prototype_indices is None else prototype_indices + + self.particle_positions = ( + th.vstack([self.particle_positions, positions]) if self.particle_positions.numel() > 0 else positions + ) + self.particle_velocities = ( + th.vstack([self.particle_velocities, velocities]) if self.particle_velocities.numel() > 0 else velocities + ) + self.particle_orientations = ( + th.vstack([self.particle_orientations, orientations]) + if self.particle_orientations.numel() > 0 + else orientations + ) + self.particle_scales = th.vstack([self.particle_scales, scales]) if self.particle_scales.numel() > 0 else scales + self.particle_prototype_ids = ( + th.cat([self.particle_prototype_ids, prototype_indices]) + if self.particle_prototype_ids.numel() > 0 + else prototype_indices + ) + + def remove_particles(self, idxs): + """ + Remove particles from this instancer, specified by their indices @idxs in the data array + + Args: + idxs (list or th.tensor of int): IDs corresponding to the indices of specific particles to remove from this + instancer + """ + if len(idxs) > 0: + # Remove all requested indices and write to all the internal data arrays + self.particle_positions = torch_delete(self.particle_positions, idxs, dim=0) + self.particle_velocities = torch_delete(self.particle_velocities, idxs, dim=0) + self.particle_orientations = torch_delete(self.particle_orientations, idxs, dim=0) + self.particle_scales = torch_delete(self.particle_scales, idxs, dim=0) + self.particle_prototype_ids = torch_delete(self.particle_prototype_ids, idxs, dim=0) + + def remove_all_particles(self): + self.remove_particles(idxs=th.arange(self.n_particles)) + + @property + def n_particles(self): + """ + Returns: + int: Number of particles owned by this instancer + """ + return len(self.particle_positions) + + @property + def idn(self): + """ + Returns: + int: Identification number of this particle instancer + """ + return self._idn + + @property + def particle_group(self): + """ + Returns: + int: Particle group this instancer belongs to + """ + return self.get_attribute(attr="physxParticle:particleGroup") + + @particle_group.setter + def particle_group(self, group): + """ + Args: + group (int): Particle group this instancer belongs to + """ + self.set_attribute(attr="physxParticle:particleGroup", val=group) + + @property + def particle_positions(self): + """ + Returns: + th.tensor: (N, 3) numpy array, where each of the N particles' positions are expressed in (x,y,z) + cartesian coordinates relative to this instancer's parent prim + """ + return vtarray_to_torch(self.get_attribute(attr="positions")) + + @particle_positions.setter + def particle_positions(self, pos): + """ + Set the particle positions for this instancer + + Args: + th.tensor: (N, 3) numpy array, where each of the N particles' desired positions are expressed in (x,y,z) + cartesian coordinates relative to this instancer's parent prim + """ + self.set_attribute(attr="positions", val=lazy.pxr.Vt.Vec3fArray(pos.tolist())) + + @property + def particle_orientations(self): + """ + Returns: + th.tensor: (N, 4) numpy array, where each of the N particles' orientations are expressed in (x,y,z,w) + quaternion coordinates relative to this instancer's parent prim + """ + orientations = self.get_attribute(attr="orientations") + if len(orientations) == 0: + return th.empty(0, dtype=th.float32) + else: + return th.tensor( + [[ori.imaginary[0], ori.imaginary[1], ori.imaginary[2], ori.real] for ori in orientations], + dtype=th.float32, + ) + + @particle_orientations.setter + def particle_orientations(self, quat): + """ + Set the particle positions for this instancer + + Args: + th.tensor: (N, 4) numpy array, where each of the N particles' desired orientations are expressed in (x,y,z,w) + quaternion coordinates relative to this instancer's parent prim + """ + assert ( + quat.shape[0] == self.n_particles + ), f"Got mismatch in particle setting size: {quat.shape[0]}, vs. number of particles {self.n_particles}!" + # If the number of particles is nonzero, swap w position, since Quath takes (w,x,y,z) + quat = quat + if self.n_particles > 0: + quat = quat[:, [3, 0, 1, 2]] + self.set_attribute(attr="orientations", val=lazy.pxr.Vt.QuathArray.FromNumpy(quat.cpu().numpy())) + + @property + def particle_velocities(self): + """ + Returns: + th.tensor: (N, 3) numpy array, where each of the N particles' velocities are expressed in (x,y,z) + cartesian coordinates relative to this instancer's parent prim + """ + return vtarray_to_torch(self.get_attribute(attr="velocities")) + + @particle_velocities.setter + def particle_velocities(self, vel): + """ + Set the particle velocities for this instancer + + Args: + th.tensor: (N, 3) numpy array, where each of the N particles' desired velocities are expressed in (x,y,z) + cartesian coordinates relative to this instancer's parent prim + """ + assert ( + vel.shape[0] == self.n_particles + ), f"Got mismatch in particle setting size: {vel.shape[0]}, vs. number of particles {self.n_particles}!" + self.set_attribute(attr="velocities", val=lazy.pxr.Vt.Vec3fArray(vel.tolist())) + + @property + def particle_scales(self): + """ + Returns: + th.tensor: (N, 3) numpy array, where each of the N particles' scales are expressed in (x,y,z) + cartesian coordinates relative to this instancer's parent prim + """ + return vtarray_to_torch(self.get_attribute(attr="scales")) + + @particle_scales.setter + def particle_scales(self, scales): + """ + Set the particle scales for this instancer + + Args: + th.tensor: (N, 3) numpy array, where each of the N particles' desired scales are expressed in (x,y,z) + cartesian coordinates relative to this instancer's parent prim + """ + assert ( + scales.shape[0] == self.n_particles + ), f"Got mismatch in particle setting size: {scales.shape[0]}, vs. number of particles {self.n_particles}!" + self.set_attribute(attr="scales", val=lazy.pxr.Vt.Vec3fArray(scales.tolist())) + + @property + def particle_prototype_ids(self): + """ + Returns: + th.tensor: (N,) numpy array, where each of the N particles' prototype_id (i.e.: which prototype is being used + for that particle) + """ + return vtarray_to_torch(self.get_attribute(attr="protoIndices")) + + @particle_prototype_ids.setter + def particle_prototype_ids(self, prototype_ids): + """ + Set the particle prototype_ids for this instancer + + Args: + th.tensor: (N,) numpy array, where each of the N particles' desired prototype_id + (i.e.: which prototype is being used for that particle) + """ + assert ( + prototype_ids.shape[0] == self.n_particles + ), f"Got mismatch in particle setting size: {prototype_ids.shape[0]}, vs. number of particles {self.n_particles}!" + self.set_attribute(attr="protoIndices", val=prototype_ids.int().cpu().numpy()) + + @property + def state_size(self): + # idn (1), particle_group (1), n_particles (1), and the corresponding states for each particle + # N * (pos (3) + vel (3) + orn (4) + scale (3) + prototype_id (1)) + return 3 + self.n_particles * 14 + + def _dump_state(self): + if self.particle_positions.numel() == 0 and self.particle_orientations.numel() == 0: + local_positions, local_orientations = [], [] + else: + local_positions = [] + local_orientations = [] + for global_pos, global_ori in zip(self.particle_positions, self.particle_orientations): + local_pos, local_ori = self.scene.convert_world_pose_to_scene_relative( + global_pos, + global_ori, + ) + local_positions.append(local_pos) + local_orientations.append(local_ori) + return dict( + idn=self._idn, + particle_group=self.particle_group, + n_particles=self.n_particles, + particle_positions=th.stack(local_positions) if len(local_positions) > 0 else th.empty(0, dtype=th.float32), + particle_velocities=self.particle_velocities, + particle_orientations=( + th.stack(local_orientations) if len(local_orientations) > 0 else th.empty(0, dtype=th.float32) + ), + particle_scales=self.particle_scales, + particle_prototype_ids=self.particle_prototype_ids, + ) + + def _load_state(self, state): + # Sanity check the identification number and particle group + assert self._idn == state["idn"], ( + f"Got mismatch in identification number for this particle instancer when " + f"loading state! Should be: {self._idn}, got: {state['idn']}." + ) + assert self.particle_group == state["particle_group"], ( + f"Got mismatch in particle group for this particle " + f"instancer when loading state! Should be: {self.particle_group}, got: {state['particle_group']}." + ) + + local_positions = state["particle_positions"] + local_orientations = state["particle_orientations"] + if local_positions.numel() == 0 and local_orientations.numel() == 0: + global_positions, global_orientations = th.tensor([]), th.tensor([]) + setattr(self, "particle_positions", global_positions) + setattr(self, "particle_orientations", global_orientations) + else: + global_positions, global_orientations = zip( + *[ + self.scene.convert_scene_relative_pose_to_world(local_pos, local_ori) + for local_pos, local_ori in zip(local_positions, local_orientations) + ] + ) + setattr(self, "particle_positions", th.stack(global_positions)) + setattr(self, "particle_orientations", th.stack(global_orientations)) + + # Set values appropriately + keys = ( + "particle_velocities", + "particle_scales", + "particle_prototype_ids", + ) + for key in keys: + # Make sure the loaded state is a numpy array, it could have been accidentally casted into a list during + # JSON-serialization + val = th.tensor(state[key]) if not isinstance(state[key], th.Tensor) else state[key] + setattr(self, key, val) + + def serialize(self, state): + # Compress into a 1D array + return th.cat( + [ + th.tensor([state["idn"], state["particle_group"], state["n_particles"]]), + state["particle_positions"].reshape(-1), + state["particle_velocities"].reshape(-1), + state["particle_orientations"].reshape(-1), + state["particle_scales"].reshape(-1), + state["particle_prototype_ids"], + ] + ) + + def deserialize(self, state): + # Sanity check the identification number + assert self._idn == state[0], ( + f"Got mismatch in identification number for this particle instancer when " + f"deserializing state! Should be: {self._idn}, got: {state[0]}." + ) + assert self.particle_group == state[1], ( + f"Got mismatch in particle group for this particle " + f"instancer when deserializing state! Should be: {self.particle_group}, got: {state[1]}." + ) + + # De-compress from 1D array + n_particles = int(state[2]) + state_dict = dict( + idn=int(state[0]), + particle_group=int(state[1]), + n_particles=n_particles, + ) + + # Process remaining keys and reshape automatically + keys = ( + "particle_positions", + "particle_velocities", + "particle_orientations", + "particle_scales", + "particle_prototype_ids", + ) + sizes = ((n_particles, 3), (n_particles, 3), (n_particles, 4), (n_particles, 3), (n_particles,)) + + idx = 3 + for key, size in zip(keys, sizes): + length = math.prod(size) + state_dict[key] = state[idx : idx + length].reshape(size) + idx += length + + return state_dict, idx + + +class MicroParticleSystem(BaseSystem): + """ + Global system for modeling "micro" level particles, e.g.: water, seeds, cloth. This system leverages + Omniverse's native physx particle systems + """ + + def __init__(self, name, customize_particle_material=None, **kwargs): + super().__init__(name=name, **kwargs) + + # Particle system prim in the scene, should be generated at runtime + self.system_prim = None + + # Material -- MaterialPrim associated with this particle system + self._material = None + + self._customize_particle_material = customize_particle_material + + # Color of the generated material. Default is white [1.0, 1.0, 1.0] + # (NOTE: external queries should call self.color) + self._color = th.tensor([1.0, 1.0, 1.0]) + + def initialize(self, scene): + # Run super first + super().initialize(scene) + + # Run sanity checks + if not gm.USE_GPU_DYNAMICS: + raise ValueError(f"Failed to initialize {self.name} system. Please set gm.USE_GPU_DYNAMICS=True.") + + self.system_prim = self._create_particle_system() + # Get material + material = self._get_particle_material_template() + # Load the material if it's newly created and has never been loaded before + if not material.loaded: + material.load() + material.add_user(self) + self._material = material + # Bind the material to the particle system (for isosurface) and the prototypes (for non-isosurface) + self._material.bind(self.system_prim_path) + # Also apply physics to this material + with og.sim.editing_usd(): + lazy.omni.physx.scripts.particleUtils.add_pbd_particle_material( + og.sim.stage, self.mat_path, **self._pbd_material_kwargs + ) + # Potentially modify the material + self._customize_particle_material() if self._customize_particle_material is not None else None + + def _clear(self): + self._material.remove_user(self) + + super()._clear() + + self.system_prim = None + self._material = None + self._color = th.tensor([1.0, 1.0, 1.0]) + + @property + def particle_radius(self): + # Magic number from omni tutorials + # See https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_physics.html#offset-autocomputation + # Also https://nvidia-omniverse.github.io/PhysX/physx/5.1.3/docs/ParticleSystem.html#particle-system-configuration + return 0.99 * self._particle_contact_offset + + @property + def color(self): + """ + Returns: + None or 3-array: If @self._material exists, this will be its corresponding RGB color. Otherwise, + will return None + """ + return self._color + + @property + def material(self): + return self._material + + @property + def mat_path(self): + """ + Returns: + str: Path to this system's material in the scene stage + """ + return f"{self.prim_path}/material" + + @property + def mat_name(self): + """ + Returns: + str: Name of this system's material + """ + return f"{self.name}:material" + + @property + def _pbd_material_kwargs(self): + """ + Returns: + dict: Any PBD material kwargs to pass to the PBD material method particleUtils.add_pbd_particle_material + used to define physical properties associated with this particle system + """ + # Default is empty dictionary + return dict() + + def _get_particle_material_template(self): + """ + Creates the particle material template to be used for this particle system. Prim path does not matter, + as it will be overridden internally such that it is a child prim of this particle system's prim. + + NOTE: This material is a template because it is loading an Omni material preset. It can then be customized (in + addition to modifying its physical material properties) via @_customize_particle_material + + Returns: + MaterialPrim: The material to apply to all particles + """ + # Default is PBR material + return OmniPBRMaterialPrim.get_material( + scene=self.scene, + prim_path=self.mat_path, + name=self.mat_name, + ) + + def _customize_particle_material(self): + """ + Modifies this particle system's particle material once it is loaded. Default is a no-op + """ + pass + + @property + def system_prim_path(self): + return f"{self.prim_path}/system" + + @property + def visual_only(self): + """ + Returns: + bool: Whether this particle system should be visual-only, i.e.: not subject to collisions and physics. If True, + the generated particles will not move or collide + """ + return False + + @property + def particle_contact_offset(self): + """ + Returns: + float: Contact offset value to use for this particle system. + See https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_physics.html?highlight=isosurface#particle-system-configuration + for more information + """ + raise NotImplementedError() + + @property + def use_smoothing(self): + """ + Returns: + bool: Whether to use smoothing or not for this particle system. + See https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_physics.html?highlight=isosurface#smoothing + for more information + """ + return False + + @property + def use_anisotropy(self): + """ + Returns: + bool: Whether to use anisotropy or not for this particle system. + See https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_physics.html?highlight=isosurface#anisotropy + for more information + """ + return False + + @property + def use_isosurface(self): + """ + Returns: + bool: Whether to use isosurface or not for this particle system. + See https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_physics.html?highlight=isosurface#isosurface + for more information + """ + return False + + def _create_particle_system(self): + """ + Creates the single, global particle system. This should only be ever called once, and during initialize() + + Returns: + Usd.Prim: Particle system prim created + """ + return create_physx_particle_system( + prim_path=self.system_prim_path, + physics_scene_path=og.sim.get_physics_context().get_current_physics_scene_prim().GetPrimPath().pathString, + particle_contact_offset=self._particle_contact_offset, + visual_only=self.visual_only, + smoothing=self.use_smoothing and gm.ENABLE_HQ_RENDERING, + anisotropy=self.use_anisotropy and gm.ENABLE_HQ_RENDERING, + isosurface=self.use_isosurface and gm.ENABLE_HQ_RENDERING, + ).GetPrim() + + +class MicroPhysicalParticleSystem(MicroParticleSystem, PhysicalParticleSystem): + """ + Global system for modeling physical "micro" level particles, e.g.: water, seeds, rice, etc. This system leverages + Omniverse's native physx particle systems + """ + + def __init__( + self, + name, + particle_density, + particle_contact_offset=None, + is_viscous=None, + material_mtl_name=None, + customize_particle_material=None, + min_scale=None, + max_scale=None, + **kwargs, + ): + """ + Args: + name (str): Name of the system, in snake case. + particle_density (float): Particle density for the generated system + particle_contact_offset (float): Contact offset for the generated system + is_viscous (bool): Whether or not the generated system should be viscous + material_mtl_name (None or str): Material mdl preset name to use for generating this fluid material. + NOTE: Should be an entry from OmniSurfacePresets.mdl, minus the "OmniSurface_" string. + If None if specified, will default to the generic OmniSurface material + customize_particle_material (None or function): Method for customizing the particle material for the fluid + after it has been loaded. Default is None, which will produce a no-op. + If specified, expected signature: + + _customize_particle_material(mat: MaterialPrim) --> None + + where @MaterialPrim is the material to modify in-place + min_scale (None or 3-array): If specified, sets the minumum bound for particles' relative scale. + Else, defaults to 1 + max_scale (None or 3-array): If specified, sets the maximum bound for particles' relative scale. + Else, defaults to 1 + **kwargs (any): keyword-mapped parameters to override / set in the child class, where the keys represent + the class attribute to modify and the values represent the functions / value to set + (Note: These values should have either @property or @classmethod decorators!) + """ + + # Store the particle density + self._particle_density = particle_density + + # Particle prototypes -- will be list of mesh prims to use as particle prototypes for this system + self.particle_prototypes = list() + + # Particle instancers -- maps name to particle instancer prims (dict) + self.particle_instancers = dict() + + self._particle_contact_offset = particle_contact_offset + + self.is_viscous = is_viscous + + # Material mdl preset name to use for generating this fluid material. NOTE: Should be an entry from + # OmniSurfacePresets.mdl, minus the "OmniSurface_" string. If None if specified, will default to the generic + # OmniSurface material + self._material_mtl_name = material_mtl_name + + self._customize_particle_material = customize_particle_material + + # Run super + return super().__init__(name=name, min_scale=min_scale, max_scale=max_scale, **kwargs) + + @property + def n_particles(self): + return sum([instancer.n_particles for instancer in self.particle_instancers.values()]) + + @property + def n_instancers(self): + """ + Returns: + int: Number of active particles in this system + """ + return len(self.particle_instancers) + + @property + def instancer_idns(self): + """ + Returns: + list of int: Per-instancer number of active particles in this system + """ + return [inst.idn for inst in self.particle_instancers.values()] + + @property + def self_collision(self): + """ + Returns: + bool: Whether this system's particle should have self collisions enabled or not + """ + # Default is True + return True + + def _sync_particle_prototype_ids(self): + """ + Synchronizes the particle prototype IDs across all particle instancers when sim is stopped. + Omniverse has a bug where all particle positions, orientations, velocities, and scales are correctly reset + when sim is stopped, but not the prototype IDs. This function is a workaround for that. + """ + if self.initialized and self.particle_instancers is not None: + for instancer in self.particle_instancers.values(): + instancer.particle_prototype_ids = th.zeros(instancer.n_particles, dtype=th.int32) + + def initialize(self, scene): + self._scene = scene + + # Create prototype before running super! + self.particle_prototypes = self._create_particle_prototypes() + + # Run super + super().initialize(scene) + + # Potentially set system prim's max velocity value + if m.MICRO_PARTICLE_SYSTEM_MAX_VELOCITY is not None: + self.system_prim.GetProperty("maxVelocity").Set(m.MICRO_PARTICLE_SYSTEM_MAX_VELOCITY) + + # TODO: remove this hack once omniverse fixes the issue (now we assume prototype IDs are all 0 always) + og.sim.add_callback_on_stop( + name=f"{self.name}_sync_particle_prototype_ids", callback=self._sync_particle_prototype_ids + ) + + def _clear(self): + for prototype in self.particle_prototypes: + og.sim.remove_prim(prototype) + + super()._clear() + + self.particle_prototypes = list() + self.particle_instancers = dict() + + @property + def next_available_instancer_idn(self): + """ + Updates the max instancer identification number based on the current internal state + """ + if self.n_instancers == 0: + return self.default_instancer_idn + else: + for idn in range(max(self.instancer_idns) + 2): + if idn not in self.instancer_idns: + return idn + + @property + def default_instancer_idn(self): + return 0 + + @property + def state_size(self): + # We have the number of particle instancers (1), the instancer groups, particle groups, and, + # number of particles in each instancer (3n), + # and the corresponding states in each instancer (X) + return ( + 1 + 3 * len(self.particle_instancers) + sum(inst.state_size for inst in self.particle_instancers.values()) + ) + + @property + def default_particle_instancer(self): + """ + Returns: + PhysxParticleInstancer: Default particle instancer for this particle system + """ + # Default instancer is the 0th ID instancer + name = self.particle_instancer_idn_to_name(idn=self.default_instancer_idn) + # NOTE: Cannot use dict.get() call for some reason; it messes up IDE introspection + return ( + self.particle_instancers[name] + if name in self.particle_instancers + else self.generate_particle_instancer(n_particles=0, idn=self.default_instancer_idn) + ) + + @property + def particle_contact_radius(self): + # This is simply the contact offset + return self._particle_contact_offset + + @property + def particle_density(self): + """ + Returns: + float: Particle density for the generated system + """ + return self._particle_density + + @property + def is_fluid(self): + """ + Returns: + bool: Whether this system is modeling fluid or not + """ + raise NotImplementedError() + + def _create_particle_prototypes(self): + """ + Creates any relevant particle prototypes to be used by this particle system. + + Returns: + list of GeomPrim: Visual mesh prim(s) to use as this system's particle prototype(s) + """ + raise NotImplementedError() + + def remove_particles( + self, + idxs, + instancer_idn=None, + ): + """ + Removes pre-existing particles from instancer @instancer_idn + + Args: + idxs (th.tensor): (n_particles,) shaped array specifying IDs of particles to delete + instancer_idn (None or int): Unique identification number of the particle instancer to delete the particles + from. If None, this system will delete particles from the default particle instancer + """ + # Create a new particle instancer if a new idn is requested, otherwise use the pre-existing one + inst = ( + self.default_particle_instancer + if instancer_idn is None + else self.particle_instancers.get(self.particle_instancer_idn_to_name(idn=instancer_idn), None) + ) + + assert inst is not None, f"No instancer with ID {inst} exists!" + + inst.remove_particles(idxs=idxs) + + def generate_particles( + self, + positions, + instancer_idn=None, + particle_group=0, + velocities=None, + orientations=None, + scales=None, + prototype_indices=None, + ): + """ + Generates new particles, either as part of a pre-existing instancer corresponding to @instancer_idn or as part + of a newly generated instancer. + + Args: + positions (th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) positions + instancer_idn (None or int): Unique identification number of the particle instancer to assign the generated + particles to. This is used to deterministically reproduce individual particle instancer states + dynamically, even if we delete / add additional ones at runtime during simulation. If there is no + active instancer that matches the requested idn, a new one will be created. + If None, this system will add particles to the default particle instancer + particle_group (int): ID for this particle set. Particles from different groups will automatically collide + with each other. Particles in the same group will have collision behavior dictated by + @self.self_collision + velocities (None or th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) velocities. + If not specified, all will be set to 0 + orientations (None or th.tensor): (n_particles, 4) shaped array specifying per-particle (x,y,z,w) quaternion + orientations. If not specified, all will be set to canonical orientation (0, 0, 0, 1) + scales (None or th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) scales. + If not specified, will be uniformly randomly sampled from (self.min_scale, self.max_scale) + prototype_indices (None or list of int): If specified, should specify which prototype should be used for + each particle. If None, will randomly sample from all available prototypes + + Returns: + PhysxParticleInstancer: Particle instancer that includes the generated particles + """ + if not isinstance(positions, th.Tensor): + positions = th.tensor(positions, dtype=th.float32) + + # Create a new particle instancer if a new idn is requested, otherwise use the pre-existing one + inst = ( + self.default_particle_instancer + if instancer_idn is None + else self.particle_instancers.get(self.particle_instancer_idn_to_name(idn=instancer_idn), None) + ) + + n_particles = len(positions) + if prototype_indices is not None: + prototype_indices = ( + th.ones(n_particles, dtype=int) * prototype_indices + if isinstance(prototype_indices, int) + else th.tensor(prototype_indices, dtype=int) + ) + else: + prototype_indices = th.randint(len(self.particle_prototypes), (n_particles,)) + + if inst is None: + inst = self.generate_particle_instancer( + idn=instancer_idn, + particle_group=particle_group, + n_particles=len(positions), + positions=positions, + velocities=velocities, + orientations=orientations, + scales=scales, + prototype_indices=prototype_indices, + ) + else: + inst.add_particles( + positions=positions, + velocities=velocities, + orientations=orientations, + scales=scales, + prototype_indices=prototype_indices, + ) + + # Update semantics + prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(prim_path=self.prim_path) + add_semantic_label(prim=prim, label=self.name) + + return inst + + def generate_particle_instancer( + self, + n_particles, + idn=None, + particle_group=0, + positions=None, + velocities=None, + orientations=None, + scales=None, + prototype_indices=None, + ): + """ + Generates a new particle instancer with unique identification number @idn, and registers it internally + + Args: + n_particles (int): Number of particles to generate for this instancer + idn (None or int): Unique identification number to assign to this particle instancer. This is used to + deterministically reproduce individual particle instancer states dynamically, even if we + delete / add additional ones at runtime during simulation. If None, this system will generate a unique + identifier automatically. + particle_group (int): ID for this particle set. Particles from different groups will automatically collide + with each other. Particles in the same group will have collision behavior dictated by + @self.self_collision + positions (None or th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) positions. + If not specified, will be set to the origin by default + velocities (None or th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) velocities. + If not specified, all will be set to 0 + orientations (None or th.tensor): (n_particles, 4) shaped array specifying per-particle (x,y,z,w) quaternion + orientations. If not specified, all will be set to canonical orientation (0, 0, 0, 1) + scales (None or th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) scales. + If not specified, will be uniformly randomly sampled from (self.min_scale, self.max_scale) + prototype_indices (None or list of int): If specified, should specify which prototype should be used for + each particle. If None, will use all 0s (i.e.: the first prototype created) + + Returns: + PhysxParticleInstancer: Generated particle instancer + """ + # Run sanity checks + assert self.initialized, "Must initialize system before generating particle instancers!" + + # Multiple particle instancers is NOT supported currently, since there is no clear use case for multiple + assert self.n_instancers == 0, ( + f"Cannot create multiple instancers for the same system! " + f"There is already {self.n_instancers} pre-existing instancers." + ) + + # Automatically generate an identification number for this instancer if none is specified + if idn is None: + idn = self.next_available_instancer_idn + + assert idn not in self.instancer_idns, f"instancer idn {idn} already exists." + + # Generate standardized prim path for this instancer + name = self.particle_instancer_idn_to_name(idn=idn) + + # Create the instancer + instance = create_physx_particleset_pointinstancer( + name=name, + particle_system_path=self.prim_path, + physx_particle_system_path=self.system_prim_path, + particle_group=particle_group, + positions=th.zeros((n_particles, 3)) if positions is None else positions, + self_collision=self.self_collision, + fluid=self.is_fluid, + particle_mass=None, + particle_density=self.particle_density, + orientations=orientations, + velocities=velocities, + angular_velocities=None, + scales=self.sample_scales(n=n_particles) if scales is None else scales, + prototype_prim_paths=[pp.prim_path for pp in self.particle_prototypes], + prototype_indices=prototype_indices, + enabled=not self.visual_only, + ) + + # Create the instancer object that wraps the raw prim + instancer = PhysxParticleInstancer( + relative_prim_path=absolute_prim_path_to_scene_relative(self.scene, instance.GetPrimPath().pathString), + name=name, + idn=idn, + ) + instancer.load(self.scene) + instancer.initialize() + self.particle_instancers[name] = instancer + + return instancer + + def generate_particles_from_link( + self, + obj, + link, + use_visual_meshes=True, + mesh_name_prefixes=None, + check_contact=True, + instancer_idn=None, + particle_group=0, + sampling_distance=None, + max_samples=None, + prototype_indices=None, + ): + """ + Generates a new particle instancer with unique identification number @idn, with particles sampled from the mesh + located at @mesh_prim_path, and registers it internally. This will also check for collision with other rigid + objects before spawning in individual particles + + Args: + obj (EntityPrim): Object whose @link's visual meshes will be converted into sampled particles + link (RigidPrim): @obj's link whose visual meshes will be converted into sampled particles + use_visual_meshes (bool): Whether to use visual meshes of the link to generate particles + mesh_name_prefixes (None or str): If specified, specifies the substring that must exist in @link's + mesh names in order for that mesh to be included in the particle generator function. + If None, no filtering will be used. + check_contact (bool): If True, will only spawn in particles that do not collide with other rigid bodies + instancer_idn (None or int): Unique identification number of the particle instancer to assign the generated + particles to. This is used to deterministically reproduce individual particle instancer states + dynamically, even if we delete / add additional ones at runtime during simulation. If there is no + active instancer that matches the requested idn, a new one will be created. + If None, this system will add particles to the default particle instancer + particle_group (int): ID for this particle set. Particles from different groups will automatically collide + with each other. Particles in the same group will have collision behavior dictated by + @self.self_collision. + Only used if a new particle instancer is created! + sampling_distance (None or float): If specified, sets the distance between sampled particles. If None, + a simulator autocomputed value will be used + max_samples (None or int): If specified, maximum number of particles to sample + prototype_indices (None or list of int): If specified, should specify which prototype should be used for + each particle. If None, will randomly sample from all available prototypes + """ + return super().generate_particles_from_link( + obj=obj, + link=link, + use_visual_meshes=use_visual_meshes, + mesh_name_prefixes=mesh_name_prefixes, + check_contact=check_contact, + instancer_idn=instancer_idn, + particle_group=particle_group, + sampling_distance=sampling_distance, + max_samples=max_samples, + prototype_indices=prototype_indices, + ) + + def generate_particles_on_object( + self, + obj, + instancer_idn=None, + particle_group=0, + sampling_distance=None, + max_samples=None, + min_samples_for_success=1, + prototype_indices=None, + ): + """ + Generates @n_particles new particle objects and samples their locations on the top surface of object @obj + + Args: + obj (USDObject): Object on which to generate a particle instancer with sampled particles on the object's + top surface + instancer_idn (None or int): Unique identification number of the particle instancer to assign the generated + particles to. This is used to deterministically reproduce individual particle instancer states + dynamically, even if we delete / add additional ones at runtime during simulation. If there is no + active instancer that matches the requested idn, a new one will be created. + If None, this system will add particles to the default particle instancer + particle_group (int): ID for this particle set. Particles from different groups will automatically collide. + Only used if a new particle instancer is created! + sampling_distance (None or float): If specified, sets the distance between sampled particles. If None, + a simulator autocomputed value will be used + max_samples (None or int): If specified, maximum number of particles to sample + min_samples_for_success (int): Minimum number of particles required to be sampled successfully in order + for this generation process to be considered successful + prototype_indices (None or list of int): If specified, should specify which prototype should be used for + each particle. If None, will randomly sample from all available prototypes + + Returns: + bool: True if enough particles were generated successfully (number of successfully sampled points >= + min_samples_for_success), otherwise False + """ + return super().generate_particles_on_object( + obj=obj, + instancer_idn=instancer_idn, + particle_group=particle_group, + sampling_distance=sampling_distance, + max_samples=max_samples, + min_samples_for_success=min_samples_for_success, + prototype_indices=prototype_indices, + ) + + def remove_particle_instancer(self, name): + """ + Removes particle instancer with name @name from this system. + + Args: + name (str): Particle instancer name to remove. If it does not exist, then an error will be raised + """ + # Make sure the instancer actually exists + assert_valid_key(key=name, valid_keys=self.particle_instancers, name="particle instancer") + # Remove instancer from our tracking and delete its prim + instancer = self.particle_instancers.pop(name) + og.sim.remove_prim(instancer) + + def particle_instancer_name_to_idn(self, name): + """ + Args: + name (str): Particle instancer name + Returns: + int: Particle instancer identification number + """ + return int(name.split(f"{self.name}Instancer")[-1]) + + def particle_instancer_idn_to_name(self, idn): + """ + Args: + idn (idn): Particle instancer identification number + Returns: + str: Name of the particle instancer auto-generated from its unique identification number + """ + return f"{self.name}Instancer{idn}" + + def get_particles_position_orientation(self): + return self.default_particle_instancer.particle_positions, self.default_particle_instancer.particle_orientations + + def get_particles_local_pose(self): + return self.get_particles_position_orientation() + + def get_particle_position_orientation(self, idx): + pos, ori = self.get_particles_position_orientation() + return pos[idx], ori[idx] + + def get_particle_local_pose(self, idx): + return self.get_particle_position_orientation(idx=idx) + + def set_particles_position_orientation(self, positions=None, orientations=None): + if positions is not None: + self.default_particle_instancer.particle_positions = positions + if orientations is not None: + self.default_particle_instancer.particle_orientations = orientations + + def set_particles_local_pose(self, positions=None, orientations=None): + self.set_particles_position_orientation(positions=positions, orientations=orientations) + + def set_particle_position_orientation(self, idx, position=None, orientation=None): + if position is not None: + positions = self.default_particle_instancer.particle_positions + positions[idx] = position + self.default_particle_instancer.particle_positions = positions + if orientation is not None: + orientations = self.default_particle_instancer.particle_orientations + orientations[idx] = orientation + self.default_particle_instancer.particle_orientations = orientations + + def set_particle_local_pose(self, idx, position=None, orientation=None): + self.set_particle_position_orientation(idx=idx, position=position, orientation=orientation) + + def _sync_particle_instancers(self, idns, particle_groups, particle_counts): + """ + Synchronizes the particle instancers based on desired identification numbers @idns + + Args: + idns (list of int): Desired unique instancers that should be active for this particle system + particle_groups (list of int): Desired particle groups that each instancer should be. Length of this + list should be the same length as @idns + particle_counts (list of int): Desired particle counts that should exist per instancer. Length of this + list should be the same length as @idns + """ + # We have to be careful here -- some particle instancers may have been deleted / are mismatched, so we need + # to update accordingly, potentially deleting stale instancers and creating new instancers as needed + idn_to_info_mapping = { + idn: {"group": group, "count": count} for idn, group, count in zip(idns, particle_groups, particle_counts) + } + current_instancer_names = set(self.particle_instancers.keys()) + desired_instancer_names = set(self.particle_instancer_idn_to_name(idn=idn) for idn in idns) + instancers_to_delete = current_instancer_names - desired_instancer_names + instancers_to_create = desired_instancer_names - current_instancer_names + common_instancers = current_instancer_names.intersection(desired_instancer_names) + + # Sanity check the common instancers, we will recreate any where there is a mismatch + for name in common_instancers: + idn = self.particle_instancer_name_to_idn(name=name) + info = idn_to_info_mapping[idn] + instancer = self.particle_instancers[name] + if instancer.particle_group != info["group"]: + instancer.particle_group = info["group"] + count_diff = info["count"] - instancer.n_particles + if count_diff > 0: + # We need to add more particles to this group + instancer.add_particles(positions=th.zeros((count_diff, 3))) + elif count_diff < 0: + # We need to remove particles from this group + instancer.remove_particles(idxs=th.arange(-count_diff)) + + # Delete any instancers we no longer want + for name in instancers_to_delete: + self.remove_particle_instancer(name=name) + + # Create any instancers we don't already have + for name in instancers_to_create: + idn = self.particle_instancer_name_to_idn(name=name) + info = idn_to_info_mapping[idn] + self.generate_particle_instancer(idn=idn, particle_group=info["group"], n_particles=info["count"]) + + def _dump_state(self): + return dict( + n_instancers=self.n_instancers, + instancer_idns=self.instancer_idns, + instancer_particle_groups=[inst.particle_group for inst in self.particle_instancers.values()], + instancer_particle_counts=[inst.n_particles for inst in self.particle_instancers.values()], + particle_states=( + dict(((name, inst.dump_state(serialized=False)) for name, inst in self.particle_instancers.items())) + ), + ) + + def _load_state(self, state): + # Synchronize the particle instancers + self._sync_particle_instancers( + idns=( + state["instancer_idns"].int().tolist() + if isinstance(state["instancer_idns"], th.Tensor) + else state["instancer_idns"] + ), + particle_groups=( + state["instancer_particle_groups"].int().tolist() + if isinstance(state["instancer_particle_groups"], th.Tensor) + else state["instancer_particle_groups"] + ), + particle_counts=( + state["instancer_particle_counts"].int().tolist() + if isinstance(state["instancer_particle_counts"], th.Tensor) + else state["instancer_particle_counts"] + ), + ) + + # Iterate over all particle states and load their respective states + for name, inst_state in state["particle_states"].items(): + self.particle_instancers[name].load_state(inst_state, serialized=False) + + def serialize(self, state): + # Array is number of particle instancers, then the corresponding states for each particle instancer + return th.cat( + [ + th.tensor([state["n_instancers"]]), + th.tensor(state["instancer_idns"]), + th.tensor(state["instancer_particle_groups"]), + th.tensor(state["instancer_particle_counts"]), + *[ + self.particle_instancers[name].serialize(inst_state) + for name, inst_state in state["particle_states"].items() + ], + ] + ) + + def deserialize(self, state): + # Synchronize the particle instancers + n_instancers = int(state[0]) + instancer_info = dict() + idx = 1 + for info_name in ("instancer_idns", "instancer_particle_groups", "instancer_particle_counts"): + instancer_info[info_name] = state[idx : idx + n_instancers].int().tolist() + idx += n_instancers + + # Syncing is needed so that each particle instancer can further deserialize its own state + log.debug(f"Syncing {self.name} particles with {n_instancers} instancers...") + self._sync_particle_instancers( + idns=instancer_info["instancer_idns"], + particle_groups=instancer_info["instancer_particle_groups"], + particle_counts=instancer_info["instancer_particle_counts"], + ) + + # Procedurally deserialize the particle states + particle_states = dict() + for idn in instancer_info["instancer_idns"]: + name = self.particle_instancer_idn_to_name(idn=idn) + particle_states[name], deserialized_items = self.particle_instancers[name].deserialize(state[idx:]) + idx += deserialized_items + + return ( + dict( + n_instancers=n_instancers, + **instancer_info, + particle_states=particle_states, + ), + idx, + ) + + def remove_all_particles(self): + self._sync_particle_instancers(idns=[], particle_groups=[], particle_counts=[]) + + +class FluidSystem(MicroPhysicalParticleSystem): + """ + Particle system class simulating fluids, leveraging isosurface feature in omniverse to render nice PBR fluid + texture. Individual particles are composed of spheres. + """ + + def __init__( + self, + name, + particle_contact_offset, + particle_density, + is_viscous=False, + material_mtl_name=None, + customize_particle_material=None, + **kwargs, + ): + """ + Args: + name (str): Name of the system + particle_contact_offset (float): Contact offset for the generated system + particle_density (float): Particle density for the generated system + is_viscous (bool): Whether or not the generated fluid system should be viscous + material_mtl_name (None or str): Material mdl preset name to use for generating this fluid material. + NOTE: Should be an entry from OmniSurfacePresets.mdl, minus the "OmniSurface_" string. + If None if specified, will default to the generic OmniSurface material + customize_particle_material (None or function): Method for customizing the particle material for the fluid + after it has been loaded. Default is None, which will produce a no-op. + If specified, expected signature: + + _customize_particle_material(mat: MaterialPrim) --> None + + where @MaterialPrim is the material to modify in-place + + **kwargs (any): keyword-mapped parameters to override / set in the child class, where the keys represent + the class attribute to modify and the values represent the functions / value to set + (Note: These values should have either @property or @classmethod decorators!) + """ + + def cm_customize_particle_material(): + if customize_particle_material is not None: + customize_particle_material(self._material) + + # Create and return the class + return super().__init__( + name=name, + particle_density=particle_density, + particle_contact_offset=particle_contact_offset, + is_viscous=is_viscous, + material_mtl_name=material_mtl_name, + customize_particle_material=cm_customize_particle_material, + **kwargs, + ) + + def initialize(self, scene): + # Run super first + super().initialize(scene) + + # Assert that the material is an OmniSurface material. + assert isinstance( + self._material, OmniSurfaceMaterialPrim + ), "FluidSystem material must be an instance of MaterialPrim" + + # Bind the material to the particle system (for isosurface) and the prototypes (for non-isosurface) + self._material.bind(self.system_prim_path) + for prototype in self.particle_prototypes: + self._material.bind(prototype.prim_path) + # Apply the physical material preset based on whether or not this fluid is viscous + apply_mat_physics = ( + lazy.omni.physx.scripts.particleUtils.AddPBDMaterialViscous + if self.is_viscous + else lazy.omni.physx.scripts.particleUtils.AddPBDMaterialWater + ) + with og.sim.editing_usd(): + apply_mat_physics(p=self._material.prim) + + # Compute the overall color of the fluid system + self._color = self._material.average_diffuse_color + + # Isosurface carb/RTX settings are applied once in Simulator._set_renderer_settings when HQ rendering is on. + if gm.ENABLE_HQ_RENDERING: + with og.sim.editing_usd(): + # Modify the grid smoothing radius to avoid "blobby" appearances + self.system_prim.GetAttribute("physxParticleIsosurface:gridSmoothingRadius").Set(0.0001) + + @property + def is_fluid(self): + return True + + @property + def use_isosurface(self): + return True + + @property + def particle_radius(self): + # Magic number from omni tutorials + # See https://docs.omniverse.nvidia.com/extensions/latest/ext_physics/physics-particles.html#offset-autocomputation + return 0.99 * 0.6 * self._particle_contact_offset + + def _create_particle_prototypes(self): + prototype_prim_path = f"{scene_relative_prim_path_to_absolute(self._scene, self.relative_prim_path)}/prototype0" + # Use UsdGeom.Mesh instead of UsdGeom.Sphere so that Hydra's PointInstancer + # rendering resolves the prototype to a real USD prim path. UsdGeom.Sphere causes + # Hydra to create a virtual "instancer/proto0" path that the replicator's semantic + # annotator cannot read labels from (it only reads from UsdGeom.Mesh prims). + create_primitive_mesh(prototype_prim_path, primitive_type="Sphere", extents=2.0 * self.particle_radius) + relative_prototype_prim_path = absolute_prim_path_to_scene_relative(self._scene, prototype_prim_path) + prototype = GeomPrim(relative_prim_path=relative_prototype_prim_path, name=f"{self.name}_prototype0") + prototype.load(self._scene) + prototype.visible = False + add_semantic_label(prim=prototype.prim, label=self.name) + return [prototype] + + def _get_particle_material_template(self): + # We use a template from OmniPresets if @_material_mtl_name is specified, else the default OmniSurface + return OmniSurfaceMaterialPrim.get_material( + scene=self.scene, prim_path=self.mat_path, name=self.mat_name, preset_name=self._material_mtl_name + ) + + +class GranularSystem(MicroPhysicalParticleSystem): + """ + Particle system class simulating granular materials. Individual particles are composed of custom USD objects. + """ + + def __init__( + self, + name, + particle_density, + create_particle_template, + scale=None, + **kwargs, + ): + """ + Args: + name (str): Name of the system + particle_density (float): Particle density for the generated system + create_particle_template (function): Method for generating the visual particle template that will be duplicated + when generating groups of particles. + Expected signature: + + create_particle_template(prim_path: str, name: str) --> EntityPrim + + where @prim_path and @name are the parameters to assign to the generated EntityPrim. + NOTE: The loaded particle template is expected to be a non-articulated, single-link object with a single + visual mesh attached to its root link, since this will be the actual visual mesh used + scale (None or 3-array): If specified, sets the scaling factor for the particles' relative scale. + Else, defaults to 1 + **kwargs (any): keyword-mapped parameters to override / set in the child class, where the keys represent + the class attribute to modify and the values represent the functions / value to set + (Note: These values should have either @property or @classmethod decorators!) + """ + self._particle_template = None + self._create_particle_template_fcn = create_particle_template + return super().__init__( + name=name, + particle_density=particle_density, + # Cached particle contact offset determined from loaded prototype + particle_contact_offset=None, + min_scale=scale, + max_scale=scale, + **kwargs, + ) + + @property + def self_collision(self): + # Don't self-collide to improve physics stability + # For whatever reason, granular (non-fluid) particles tend to explode when sampling Filled states, and it seems + # the only way to avoid this unstable behavior is to disable self-collisions. This actually enables the granular + # particles to converge to zero velocity. + return False + + def _clear(self): + self.scene.remove_object(self._particle_template) + + super()._clear() + + self._particle_template = None + self._particle_contact_offset = None + + @property + def particle_contact_offset(self): + return self._particle_contact_offset + + @property + def is_fluid(self): + return False + + def _create_particle_prototypes(self): + # Load the particle template + particle_template = self._create_particle_template() + self._scene.add_object(particle_template, register=False) + self._particle_template = particle_template + # Make sure there is no ambiguity about which mesh to use as the particle from this template + assert len(particle_template.links) == 1, "GranularSystem particle template has more than one link" + assert ( + len(particle_template.root_link.visual_meshes) == 1 + ), "GranularSystem particle template has more than one visual mesh" + + # Make sure template scaling is [1, 1, 1] -- any particle scaling should be done via self.min/max_scale + assert th.all(particle_template.scale == 1.0) + + # The prototype is assumed to be the first and only visual mesh belonging to the root link + visual_geom = list(particle_template.root_link.visual_meshes.values())[0] + + # Copy it to the standardized prim path + prototype_path = f"{self.prim_path}/prototype0" + with og.sim.editing_usd(): + lazy.omni.kit.commands.execute("CopyPrim", path_from=visual_geom.prim_path, path_to=prototype_path) + + # Wrap it with GeomPrim with the correct scale + relative_prototype_path = absolute_prim_path_to_scene_relative(self._scene, prototype_path) + prototype = GeomPrim(relative_prim_path=relative_prototype_path, name=prototype_path) + prototype.load(self._scene) + prototype.scale *= self.max_scale + prototype.visible = False + add_semantic_label(prim=prototype.prim, label=self.name) + + # Store the contact offset based on a minimum sphere + # Threshold the lower-bound to avoid super small particles + vertices = th.tensor(prototype.get_attribute("points")) * prototype.scale + _, particle_contact_offset = trimesh.nsphere.minimum_nsphere(trimesh.Trimesh(vertices=vertices)) + particle_contact_offset = th.tensor(particle_contact_offset, dtype=th.float32).item() + if particle_contact_offset < m.MIN_PARTICLE_CONTACT_OFFSET: + prototype.scale *= m.MIN_PARTICLE_CONTACT_OFFSET / particle_contact_offset + particle_contact_offset = m.MIN_PARTICLE_CONTACT_OFFSET + + self._particle_contact_offset = particle_contact_offset + + return [prototype] + + def _create_particle_template(self): + """ + Creates the particle template to be used for this system. + + NOTE: The loaded particle template is expected to be a non-articulated, single-link object with a single + visual mesh attached to its root link, since this will be the actual visual mesh used + + Returns: + EntityPrim: Particle template that will be duplicated when generating future particle groups + """ + return self._create_particle_template_fcn( + relative_prim_path=f"/{self.name}/template", name=f"{self.name}_template" + ) + + +class Cloth(MicroParticleSystem): + """ + Particle system class to simulate cloth. + """ + + def __init__( + self, + name, + **kwargs, + ): + """ + Args: + name (str): Name of the system + """ + self._particle_contact_offset = m.CLOTH_PARTICLE_CONTACT_OFFSET + return super().__init__(name=name, **kwargs) + + def remove_all_particles(self): + # Override base method since there are no particles to be deleted + pass + + def clothify_mesh_prim(self, mesh_prim): + """ + Clothifies @mesh_prim by applying the appropriate Cloth API, optionally re-meshing the mesh so that the + resulting generated particles are roughly @particle_distance apart from each other. + + Args: + mesh_prim (Usd.Prim): Mesh prim to clothify + """ + with og.sim.editing_usd(): + # Convert into particle cloth + lazy.omni.physx.scripts.particleUtils.add_physx_particle_cloth( + stage=og.sim.stage, + path=mesh_prim.GetPath(), + dynamic_mesh_path=None, + particle_system_path=self.system_prim_path, + spring_stretch_stiffness=m.CLOTH_STRETCH_STIFFNESS, + spring_bend_stiffness=m.CLOTH_BEND_STIFFNESS, + spring_shear_stiffness=m.CLOTH_SHEAR_STIFFNESS, + spring_damping=m.CLOTH_DAMPING, + self_collision=True, + self_collision_filter=True, + ) + + # Disable welding because it can potentially make thin objects non-manifold + auto_particle_cloth_api = lazy.pxr.PhysxSchema.PhysxAutoParticleClothAPI(mesh_prim) + auto_particle_cloth_api.GetDisableMeshWeldingAttr().Set(True) + + @property + def _pbd_material_kwargs(self): + return dict( + friction=m.CLOTH_FRICTION, + drag=m.CLOTH_DRAG, + lift=m.CLOTH_LIFT, + ) + + @property + def _register_system(self): + # We should register this system since it's an "actual" system (not an intermediate class) + return True + + @property + def particle_contact_offset(self): + return m.CLOTH_PARTICLE_CONTACT_OFFSET + + @property + def state_size(self): + # Default is no state + return 0 + + def _dump_state(self): + # Empty by default + return dict() + + def _load_state(self, state): + # Nothing by default + pass + + def serialize(self, state): + # Nothing by default + return th.empty(0, dtype=th.float32) + + def deserialize(self, state): + # Nothing by default + return dict(), 0 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/systems/system_base.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/systems/system_base.py new file mode 100644 index 0000000000000000000000000000000000000000..1aea043520aca020ed685cbbd3c465225c308dea --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/systems/system_base.py @@ -0,0 +1,1197 @@ +import json +import os +from functools import cache + +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros, gm +from omnigibson.utils.asset_utils import get_all_system_categories, get_dataset_path +from omnigibson.utils.python_utils import Serializable, get_uuid +from omnigibson.utils.sampling_utils import sample_cuboid_on_object_full_grid_topdown +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import scene_relative_prim_path_to_absolute, delete_or_deactivate_prim + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# Parameters used if scaling particles relative to its parent object's scale +m.BBOX_LOWER_LIMIT_FRACTION_OF_AABB = 0.06 +m.BBOX_LOWER_LIMIT_MIN = 0.002 +m.BBOX_LOWER_LIMIT_MAX = 0.02 +m.BBOX_UPPER_LIMIT_FRACTION_OF_AABB = 0.1 +m.BBOX_UPPER_LIMIT_MIN = 0.01 +m.BBOX_UPPER_LIMIT_MAX = 0.1 + + +_CALLBACKS_ON_SYSTEM_INIT = dict() +_CALLBACKS_ON_SYSTEM_CLEAR = dict() + +# Global dict that contains mappings of all the systems +UUID_TO_SYSTEM_NAME = dict() + + +class BaseSystem(Serializable): + """ + Base class for all systems. These are instanced objects that should be used globally for a given environment/scene. + This is useful for items in a scene that are non-discrete / cannot be distinguished into individual instances, + e.g.: water, particles, etc. + """ + + def __init__(self, name, min_scale=None, max_scale=None): + self._name = name + + # Whether this system has been initialized or not + self.initialized = False + + self.min_scale = min_scale if min_scale is not None else th.ones(3) + self.max_scale = max_scale if max_scale is not None else th.ones(3) + + self._uuid = get_uuid(self.name) + UUID_TO_SYSTEM_NAME[self._uuid] = self.name + + self._scene = None + + @property + def name(self): + # Class name is the unique name assigned + return self._name + + @property + def uuid(self): + return self._uuid + + @property + def prim_path(self): + """ + Returns: + str: Path to this system's prim in the scene stage + """ + assert self._scene is not None, "Scene not set for system {self.name}!".format(self=self) + return scene_relative_prim_path_to_absolute(self._scene, self.relative_prim_path) + + @property + def relative_prim_path(self): + """ + Returns: + str: Path to this system's prim in the scene stage relative to the world + """ + return f"/{self.name}" + + @property + def n_particles(self): + """ + Returns: + int: Number of particles belonging to this system + """ + raise NotImplementedError() + + @property + def material(self): + """ + Returns: + None or MaterialPrim: Material belonging to this system, if there is any + """ + return None + + @property + def _register_system(self): + """ + Returns: + bool: True if this system should be registered (i.e.: it is not an intermediate class but a "final" subclass + representing a system we'd actually like to use, e.g.: water, dust, etc. Should be set by the subclass + """ + # We assume we aren't registering by default + return False + + @property + def _store_local_poses(self): + """ + Returns: + bool: Whether to store local particle poses or not when state is saved. Default is False + """ + return False + + def initialize(self, scene): + """ + Initializes this system + """ + assert not self.initialized, f"Already initialized system {self.name}!" + self._scene = scene + self.initialized = True + + with og.sim.editing_usd(): + og.sim.stage.DefinePrim(self.prim_path, "Scope") + + if og.sim.is_playing() and gm.ENABLE_TRANSITION_RULES: + scene.transition_rule_api.refresh_all_rules() + + # Run any callbacks + for callback in og.sim.get_callbacks_on_system_init().values(): + callback(self) + + @property + def scene(self): + """ + Returns: + Scene or None: Scene object that this prim is loaded into + """ + assert self.initialized, f"System {self.name} has not been initialized yet!" + return self._scene + + def update(self): + """ + Executes any necessary system updates, once per og.sim._non_physics_step + """ + # Default is no-op + pass + + def remove_all_particles(self): + """ + Removes all particles and deletes them from the simulator + """ + raise NotImplementedError() + + def remove_particles( + self, + idxs, + **kwargs, + ): + """ + Removes pre-existing particles + + Args: + idxs (th.tensor): (n_particles,) shaped array specifying IDs of particles to delete + **kwargs (dict): Any additional keyword-specific arguments required by subclass implementation + """ + raise NotImplementedError() + + def generate_particles( + self, + positions, + orientations=None, + scales=None, + **kwargs, + ): + """ + Generates new particles + + Args: + positions (th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) positions + orientations (None or th.tensor): (n_particles, 4) shaped array specifying per-particle (x,y,z,w) quaternion + orientations. If not specified, all will be set to canonical orientation (0, 0, 0, 1) + scales (None or th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) scales. + If not specified, will be uniformly randomly sampled from (self.min_scale, self.max_scale) + **kwargs (dict): Any additional keyword-specific arguments required by subclass implementation + """ + raise NotImplementedError() + + def clear(self): + """ + Clears this system, so that it may possibly be re-initialized. Useful for, e.g., when loading from a new + scene during the same sim instance + """ + if self.initialized: + self._clear() + + def _clear(self): + for callback in og.sim.get_callbacks_on_system_clear().values(): + callback(self) + + self.reset() + delete_or_deactivate_prim(self.prim_path) + + if og.sim.is_playing() and gm.ENABLE_TRANSITION_RULES: + self.scene.transition_rule_api.prune_active_rules() + + self.initialized = False + self._scene = None + + def reset(self): + """ + Reset this system + """ + self.remove_all_particles() + + def sample_scales(self, n): + """ + Samples scales uniformly based on @self.min_scale and @self.max_scale + + Args: + n (int): Number of scales to sample + + Returns: + (n, 3) array: Array of sampled scales + """ + return th.rand(n, 3) * (self.max_scale - self.min_scale) + self.min_scale + + def get_particles_position_orientation(self): + """ + Computes all particles' positions and orientations that belong to this system in the world frame + + Note: This is more optimized than doing a for loop with self.get_particle_position_orientation() + + Returns: + 2-tuple: + - (n, 3)-array: per-particle (x,y,z) position + - (n, 4)-array: per-particle (x,y,z,w) quaternion orientation + """ + raise NotImplementedError() + + def get_particle_position_orientation(self, idx): + """ + Compute particle's position and orientation. This automatically takes into account the relative + pose w.r.t. its parent link and the global pose of that parent link. + + Args: + idx (int): Index of the particle to compute position and orientation for. Note: this is + equivalent to grabbing the corresponding idx'th entry from @get_particles_position_orientation() + + Returns: + 2-tuple: + - 3-array: (x,y,z) position + - 4-array: (x,y,z,w) quaternion orientation + """ + raise NotImplementedError() + + def set_particles_position_orientation(self, positions=None, orientations=None): + """ + Sets all particles' positions and orientations that belong to this system in the world frame + + Note: This is more optimized than doing a for loop with self.set_particle_position_orientation() + + Args: + positions (n-array): (n, 3) per-particle (x,y,z) position + orientations (n-array): (n, 4) per-particle (x,y,z,w) quaternion orientation + """ + raise NotImplementedError() + + def set_particle_position_orientation(self, idx, position=None, orientation=None): + """ + Sets particle's position and orientation. This automatically takes into account the relative + pose w.r.t. its parent link and the global pose of that parent link. + + Args: + idx (int): Index of the particle to set position and orientation for. Note: this is + equivalent to setting the corresponding idx'th entry from @set_particles_position_orientation() + position (3-array): particle (x,y,z) position + orientation (4-array): particle (x,y,z,w) quaternion orientation + """ + raise NotImplementedError() + + def get_particles_local_pose(self): + """ + Computes all particles' positions and orientations that belong to this system in the particles' parent frames + + Returns: + 2-tuple: + - (n, 3)-array: per-particle (x,y,z) position + - (n, 4)-array: per-particle (x,y,z,w) quaternion orientation + """ + raise NotImplementedError() + + def get_particle_local_pose(self, idx): + """ + Compute particle's position and orientation in the particle's parent frame + + Args: + idx (int): Index of the particle to compute position and orientation for. Note: this is + equivalent to grabbing the corresponding idx'th entry from @get_particles_local_pose() + + Returns: + 2-tuple: + - 3-array: (x,y,z) position + - 4-array: (x,y,z,w) quaternion orientation + """ + raise NotImplementedError() + + def set_particles_local_pose(self, positions=None, orientations=None): + """ + Sets all particles' positions and orientations that belong to this system in the particles' parent frames + + Args: + positions (n-array): (n, 3) per-particle (x,y,z) position + orientations (n-array): (n, 4) per-particle (x,y,z,w) quaternion orientation + """ + raise NotImplementedError() + + def set_particle_local_pose(self, idx, position=None, orientation=None): + """ + Sets particle's position and orientation in the particle's parent frame + + Args: + idx (int): Index of the particle to set position and orientation for. Note: this is + equivalent to setting the corresponding idx'th entry from @set_particles_local_pose() + position (3-array): particle (x,y,z) position + orientation (4-array): particle (x,y,z,w) quaternion orientation + """ + raise NotImplementedError() + + @property + def state_size(self): + # We have n_particles (1), uses_local_poses (1), min / max scale (3*2), each particle pose (7*n) + return 8 + 7 * self.n_particles + + def _transform_poses(self, mat, positions, orientations): + """ + Batch-transform particle poses by homogeneous transform @mat. + + Args: + mat (th.tensor): (4, 4) homogeneous transformation matrix + positions (th.tensor): (N, 3) particle positions + orientations (th.tensor): (N, 4) particle (x,y,z,w) quaternion orientations + + Returns: + 2-tuple: transformed (N, 3) positions and (N, 4) orientations + """ + if len(positions) == 0: + return positions, orientations + rot = mat[:3, :3] + new_positions = positions @ rot.T + mat[:3, 3] + new_orientations = T.mat2quat(rot.unsqueeze(0) @ T.quat2mat(orientations)) + return new_positions, new_orientations + + def _dump_state(self): + if self._store_local_poses: + positions, orientations = self.get_particles_local_pose() + else: + # Store poses in the SCENE frame (not world frame), mirroring PhysxParticleInstancer, so + # that states authored in one scene (e.g. dataset task instances, authored with the scene + # at the world origin) load correctly into cloned scenes at other world offsets. + positions, orientations = self.get_particles_position_orientation() + positions, orientations = self._transform_poses(self.scene.pose_inv, positions, orientations) + return dict( + n_particles=self.n_particles, + # Record which frame `positions` / `orientations` are expressed in, so a state can be + # validated against the system loading it instead of silently reinterpreted. Without + # this the numbers are ambiguous: local poses and scene-frame poses are indistinguishable + # in the file, so flipping `_store_local_poses` for a system would make every previously + # saved state load objects to the wrong place with no error. + uses_local_poses=self._store_local_poses, + min_scale=self.min_scale, + max_scale=self.max_scale, + positions=positions, + orientations=orientations, + ) + + def _load_state(self, state): + # Sanity check loading particles + assert self.n_particles == state["n_particles"], ( + f"Inconsistent number of particles found when loading " + f"particles state! Current number: {self.n_particles}, " + f"loaded number: {state['n_particles']}" + ) + # States saved before `uses_local_poses` was recorded carry no frame information, so fall + # back to this system's own setting -- i.e. assume they match, which is how they were always + # interpreted. Only a state that explicitly disagrees is an error. + uses_local_poses = state.get("uses_local_poses", self._store_local_poses) + assert uses_local_poses == self._store_local_poses, ( + f"Particle pose frame mismatch when loading state for system {self.name}: the state was " + f"saved with uses_local_poses={uses_local_poses}, but this system expects " + f"{self._store_local_poses}. Loading it would place particles incorrectly." + ) + + # Load scale + self.min_scale = state["min_scale"] + self.max_scale = state["max_scale"] + + # Load the poses + if self._store_local_poses: + self.set_particles_local_pose(positions=state["positions"], orientations=state["orientations"]) + else: + # Stored poses are scene-relative (see _dump_state) -- convert back into world frame using + # THIS system's scene pose, so a state authored in the canonical scene lands in the correct + # world position for cloned scenes as well. + positions, orientations = self._transform_poses(self.scene.pose, state["positions"], state["orientations"]) + self.set_particles_position_orientation(positions=positions, orientations=orientations) + + def serialize(self, state): + # Array is n_particles, the pose-frame marker, then min_scale and max_scale, then poses. + # + # The marker is written NEGATIVE (-1 = world/scene frame, -2 = local) purely so that + # deserialize can tell this layout from the one that predates the flag. Arrays written + # before it hold min_scale in this slot, and scales are always positive, so a negative + # value here is unambiguous. Without that, an old array would be read shifted by one and + # silently produce garbage rather than failing. + return th.cat( + [ + th.tensor([state["n_particles"]], dtype=th.float32), + # .get() so a state dict loaded from a file written before this field existed can + # still be re-serialized; absent means "same frame as this system", see _load_state. + th.tensor([-1.0 - float(state.get("uses_local_poses", self._store_local_poses))], dtype=th.float32), + state["min_scale"], + state["max_scale"], + state["positions"].flatten(), + state["orientations"].flatten(), + ] + ) + + def deserialize(self, state): + # First index is number of particles, then (newer format only) the pose-frame marker, then + # min_scale and max_scale, then the individual particle poses. + state_dict = dict() + n_particles = int(state[0]) + len_positions = n_particles * 3 + len_orientations = n_particles * 4 + state_dict["n_particles"] = n_particles + + # Arrays written before the pose-frame flag existed carry min_scale in slot 1, which is + # always positive; only the newer format writes a negative marker there. Keeps previously + # dumped states (e.g. recorded HDF5 demos) readable. + if state[1] < 0: + state_dict["uses_local_poses"] = bool(-state[1] - 1.0) + offset = 2 + else: + offset = 1 + + state_dict["min_scale"] = state[offset : offset + 3] + state_dict["max_scale"] = state[offset + 3 : offset + 6] + base = offset + 6 + state_dict["positions"] = state[base : base + len_positions].reshape(-1, 3) + state_dict["orientations"] = state[base + len_positions : base + len_positions + len_orientations].reshape( + -1, 4 + ) + + return state_dict, base + len_positions + len_orientations + + +class VisualParticleSystem(BaseSystem): + """ + Particle system class for generating particles not subject to physics, and are attached to individual objects + """ + + def __init__(self, name, **kwargs): + # Run super + super().__init__(name=name, **kwargs) + + # Maps group name to the particles associated with it + # This is an ordered dict of ordered dict (nested ordered dict maps particle names to particle instance) + self._group_particles = {} + + def initialize(self, scene): + # Run super method first + super().initialize(scene) + + # Maps group name to the parent object (the object with particles attached to it) of the group + self._group_objects = {} + + # Maps group name to tuple (min_scale, max_scale) to apply to sampled particles for that group + self._group_scales = {} + + @property + def particle_object(self): + """ + Returns: + XFormPrim: Particle object to be used as a template for duplication + """ + raise NotImplementedError() + + @property + def groups(self): + """ + Returns: + set of str: Current attachment particle group names + """ + return set(self._group_particles.keys()) + + @property + def _store_local_poses(self): + # Store local poses since particles are attached to moving bodies + return True + + @property + def scale_relative_to_parent(self): + """ + Returns: + bool: Whether or not particles should be scaled relative to the group's parent object. NOTE: If True, + this will OVERRIDE self.min_scale and self.max_scale when sampling particles! + """ + return False + + @property + def state_size(self): + # Get super size first + state_size = super().state_size + + # Additionally, we have n_groups (1), with m_particles for each group (n), attached_obj_uuids (n), and + # particle ids, particle indices, and corresponding link info for each particle (m * 3) + return ( + state_size + + 1 + + 2 * len(self._group_particles) + + sum(3 * self.num_group_particles(group) for group in self.groups) + ) + + def _clear(self): + super()._clear() + + # Clear all groups as well + self._group_particles = dict() + self._group_objects = dict() + self._group_scales = dict() + + def remove_all_group_particles(self, group): + """ + Remove particle with name @name from both the simulator as well as internally + + Args: + group (str): Name of the attachment group to remove all particles from + """ + # Make sure the group exists + self._validate_group(group=group) + # Remove all particles from the group + for particle_name in tuple(self._group_particles[group].keys()): + self.remove_particle_by_name(name=particle_name) + + def num_group_particles(self, group): + """ + Gets the number of particles for the given group in the simulator + + Args: + group (str): Name of the attachment group to remove all particles from. + + Returns: + int: Number of particles allocated to this group in the scene. Note that if @group does not + exist, this will return 0 + """ + # Make sure the group exists + self._validate_group(group=group) + return len(self._group_particles[group]) + + @classmethod + def get_group_name(cls, obj): + """ + Grabs the corresponding group name for object @obj + + Args: + obj (USDObject): Object for which its procedurally generated particle attachment name should be grabbed + + Returns: + str: Name of the attachment group to use when executing commands from this class on + that specific attachment group + """ + return obj.name + + def create_attachment_group(self, obj): + """ + Creates an attachment group internally for object @obj. Note that this does NOT automatically generate particles + for this object (should call generate_group_particles(...) ). + + Args: + obj (USDObject): Object for which a new particle attachment group will be created for + + Returns: + str: Name of the attachment group to use when executing commands from this class on + that specific attachment group + """ + group = VisualParticleSystem.get_group_name(obj=obj) + # This should only happen once for a single attachment group, so we explicitly check to make sure the object + # doesn't already exist + assert ( + group not in self.groups + ), f"Cannot create new attachment group because group with name {group} already exists!" + + # Create the group + self._group_particles[group] = dict() + self._group_objects[group] = obj + + # Compute the group scale if we're scaling relative to parent + if self._scale_relative_to_parent: + self._group_scales[group] = self._compute_relative_group_scales(group=group) + + return group + + def remove_attachment_group(self, group): + """ + Removes an attachment group internally for object @obj. Note that this will automatically remove any particles + currently assigned to that group + + Args: + group (str): Name of the attachment group to remove + + Returns: + str: Name of the attachment group to use when executing commands from this class on + that specific attachment group + """ + # Make sure the group exists + self._validate_group(group=group) + + # Remove all particles from the group + self.remove_all_group_particles(group=group) + + # Remove the actual groups + self._group_particles.pop(group) + self._group_objects.pop(group) + if self._scale_relative_to_parent: + self._group_scales.pop(group) + + return group + + def _compute_relative_group_scales(self, group): + """ + Computes relative particle scaling for group @group required when @self._scale_relative_to_parent is True + + Args: + group (str): Specific group for which to compute the relative particle scaling + + Returns: + 2-tuple: + - 3-array: min scaling factor + - 3-array: max scaling factor + """ + # First set the bbox ranges -- depends on the object's bounding box + obj = self._group_objects[group] + median_aabb_dim = th.median(obj.aabb_extent) + + # Compute lower and upper limits to bbox + bbox_lower_limit_from_aabb = m.BBOX_LOWER_LIMIT_FRACTION_OF_AABB * median_aabb_dim + bbox_lower_limit = th.clip( + bbox_lower_limit_from_aabb, + m.BBOX_LOWER_LIMIT_MIN, + m.BBOX_LOWER_LIMIT_MAX, + ) + + bbox_upper_limit_from_aabb = m.BBOX_UPPER_LIMIT_FRACTION_OF_AABB * median_aabb_dim + bbox_upper_limit = th.clip( + bbox_upper_limit_from_aabb, + m.BBOX_UPPER_LIMIT_MIN, + m.BBOX_UPPER_LIMIT_MAX, + ) + + # Convert these into scaling factors for the x and y axes for our particle object + particle_bbox = self.particle_object.aabb_extent + minimum = th.tensor([bbox_lower_limit / particle_bbox[0], bbox_lower_limit / particle_bbox[1], 1.0]) + maximum = th.tensor([bbox_upper_limit / particle_bbox[0], bbox_upper_limit / particle_bbox[1], 1.0]) + + return minimum, maximum + + def sample_scales_by_group(self, group, n): + """ + Samples @n particle scales for group @group. + + Args: + group (str): Specific group for which to sample scales + n (int): Number of scales to sample + + Returns: + (n, 3) array: Array of sampled scales + """ + # Make sure the group exists + self._validate_group(group=group) + + # Sample based on whether we're scaling relative to parent or not + scales = ( + th.rand(n, 3) * (self._group_scales[group][1] - self._group_scales[group][0]) + self._group_scales[group][0] + if self._scale_relative_to_parent + else self.sample_scales(n=n) + ) + + # Since the particles will be placed under the object, it will be affected/stretched by obj.scale. In order to + # preserve the absolute size of the particles, we need to scale the particle by obj.scale in some way. However, + # since the particles have a relative rotation w.r.t the object, the scale between the two don't align. As a + # heuristics, we divide it by the avg_scale, which is the cubic root of the product of the scales along 3 axes. + obj = self._group_objects[group] + avg_scale = th.pow(th.prod(obj.scale), 1 / 3) + return scales / avg_scale + + def generate_particles( + self, + positions, + orientations=None, + scales=None, + **kwargs, + ): + # Should not be called, since particles must be tied to a group! + raise ValueError( + "Cannot call generate_particles for a VisualParticleSystem! Call generate_group_particles() instead." + ) + + def generate_group_particles( + self, + group, + positions, + orientations=None, + scales=None, + link_prim_paths=None, + ): + """ + Generates new particle objects within group @group at the specified pose (@positions, @orientations) with + corresponding scales @scales. + + NOTE: Assumes positions are the exact contact point on @group object's surface. If self._CLIP_INTO_OBJECTS + is not True, then the positions will be offset away from the object by half of its bbox + + Args: + group (str): Object on which to sample particle locations + positions (th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) positions + orientations (None or th.tensor): (n_particles, 4) shaped array specifying per-particle (x,y,z,w) quaternion + orientations. If not specified, all will be set to canonical orientation (0, 0, 0, 1) + scales (None or th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) scaling in its + local frame. If not specified, all we randomly sampled based on @self.min_scale and @self.max_scale + link_prim_paths (None or list of str): Determines which link each generated particle will + be attached to. If not specified, all will be attached to the group object's prim, NOT a link + """ + raise NotImplementedError + + def generate_group_particles_on_object(self, group, max_samples=None, min_samples_for_success=1): + """ + Generates @max_samples new particle objects and samples their locations on the surface of object @obj. Note + that if any particles are in the group already, they will be removed + + Args: + group (str): Object on which to sample particle locations + max_samples (None or int): If specified, maximum number of particles to sample + min_samples_for_success (int): Minimum number of particles required to be sampled successfully in order + for this generation process to be considered successful + + Returns: + bool: True if enough particles were generated successfully (number of successfully sampled points >= + min_samples_for_success), otherwise False + """ + raise NotImplementedError + + def get_group_particles_position_orientation(self, group): + """ + Computes all particles' positions and orientations that belong to @group + + Note: This is more optimized than doing a for loop with self.get_particle_position_orientation() + + Args: + group (str): Group name whose particle positions and orientations should be computed + + Returns: + 2-tuple: + - (n, 3)-array: per-particle (x,y,z) position + - (n, 4)-array: per-particle (x,y,z,w) quaternion orientation + """ + raise NotImplementedError + + def set_group_particles_position_orientation(self, group, positions=None, orientations=None): + """ + Sets all particles' positions and orientations that belong to @group + + Note: This is more optimized than doing a for loop with self.set_particle_position_orientation() + + Args: + group (str): Group name whose particle positions and orientations should be computed + positions (n-array): (n, 3) per-particle (x,y,z) position + orientations (n-array): (n, 4) per-particle (x,y,z,w) quaternion orientation + """ + raise NotImplementedError + + def get_group_particles_local_pose(self, group): + """ + Computes all particles' positions and orientations that belong to @group in the particles' parent frame + + Args: + group (str): Group name whose particle positions and orientations should be computed + + Returns: + 2-tuple: + - (n, 3)-array: per-particle (x,y,z) position + - (n, 4)-array: per-particle (x,y,z,w) quaternion orientation + """ + raise NotImplementedError + + def set_group_particles_local_pose(self, group, positions=None, orientations=None): + """ + Sets all particles' positions and orientations that belong to @group in the particles' parent frame + + Args: + group (str): Group name whose particle positions and orientations should be computed + positions (n-array): (n, 3) per-particle (x,y,z) position + orientations (n-array): (n, 4) per-particle (x,y,z,w) quaternion orientation + """ + raise NotImplementedError + + def _validate_group(self, group): + """ + Checks if particle attachment group @group exists. (If not, can create the group via create_attachment_group). + This will raise a ValueError if it doesn't exist. + + Args: + group (str): Name of the group to check for + """ + if group not in self.groups: + raise ValueError(f"Particle attachment group {group} does not exist!") + + +class PhysicalParticleSystem(BaseSystem): + """ + System whose generated particles are subject to physics + """ + + def initialize(self, scene): + # Run super first + super().initialize(scene) + + # Make sure min and max scale are identical + assert th.all( + self.min_scale == self.max_scale + ), "Min and max scale should be identical for PhysicalParticleSystem!" + + @property + def particle_density(self): + """ + Returns: + float: The per-particle density, in kg / m^3 + """ + raise NotImplementedError() + + @property + def particle_radius(self): + """ + Returns: + float: Radius for the particles to be generated, for the purpose of sampling + """ + raise NotImplementedError() + + @property + def particle_contact_radius(self): + """ + Returns: + float: Contact radius for the particles to be generated, for the purpose of estimating contacts + """ + raise NotImplementedError() + + @property + def particle_particle_rest_distance(self): + """ + Returns: + float: The minimum distance between individual particles at rest + """ + return self.particle_radius * 2.0 + + def check_in_contact(self, positions): + """ + Checks whether each particle specified by @particle_positions are in contact with any rigid body. + + NOTE: This is a rough proxy for contact, given @positions. Should not be taken as ground truth. + This is because for efficiency and underlying physics reasons, it's easier to treat particles as spheres + for fast checking. For particles directly spawned from Omniverse's underlying ParticleSystem API, it is a + rough proxy semantically, though it is accurate in sim-physics since all spawned particles interact as spheres. + For particles spawned manually as rigid bodies, it is a rough proxy both semantically and physically, as the + object physically interacts with its non-uniform geometry. + + Args: + positions (th.tensor): (n_particles, 3) shaped array specifying per-particle (x,y,z) positions + + Returns: + n-array: (n_particles,) boolean array, True if in contact, otherwise False + """ + in_contact = th.zeros(len(positions), dtype=bool) + for idx, pos in enumerate(positions): + # TODO: Maybe multiply particle contact radius * 2? + in_contact[idx] = og.sim.psqi.overlap_sphere_any(self.particle_contact_radius, pos.tolist()) + return in_contact + + def generate_particles_from_link( + self, + obj, + link, + use_visual_meshes=True, + mesh_name_prefixes=None, + check_contact=True, + sampling_distance=None, + max_samples=None, + **kwargs, + ): + """ + Generates a new particle instancer with unique identification number @idn, with particles sampled from the mesh + located at @mesh_prim_path, and registers it internally. This will also check for collision with other rigid + objects before spawning in individual particles + + Args: + obj (EntityPrim): Object whose @link's visual meshes will be converted into sampled particles + link (RigidPrim): @obj's link whose visual meshes will be converted into sampled particles + use_visual_meshes (bool): Whether to use visual meshes of the link to generate particles + mesh_name_prefixes (None or str): If specified, specifies the substring that must exist in @link's + mesh names in order for that mesh to be included in the particle generator function. + If None, no filtering will be used. + check_contact (bool): If True, will only spawn in particles that do not collide with other rigid bodies + sampling_distance (None or float): If specified, sets the distance between sampled particles. If None, + a simulator autocomputed value will be used + max_samples (None or int): If specified, maximum number of particles to sample + **kwargs (dict): Any additional keyword-mapped arguments required by subclass implementation + """ + # Run sanity checks + assert self.initialized, "Must initialize system before generating particle instancers!" + + # Grab the link's AABB (or fallback to obj AABB if link does not have a valid AABB), + # and generate a grid of points based on the sampling distance + try: + low, high = link.visual_aabb + extent = link.visual_aabb_extent + except ValueError: + low, high = obj.aabb + extent = obj.aabb_extent + + sampling_distance = self.particle_particle_rest_distance if sampling_distance is None else sampling_distance + + # This guarantees that h - self.particle_radius > l + self.particle_radius + assert th.all( + extent >= 2 * self.particle_radius + ), f"link {link.name} is too small to sample any particle of radius {self.particle_radius}." + + arrs = [ + th.arange(l + self.particle_radius, h - self.particle_radius, sampling_distance) for l, h in zip(low, high) + ] + + # Generate 3D-rectangular grid of points + particle_positions = th.stack([arr.flatten() for arr in th.meshgrid(*arrs)]).T + # Check which points are inside the volume and only keep those + particle_positions = particle_positions[ + th.where( + link.check_points_in_volume( + particle_positions_world=particle_positions, + use_visual_meshes=use_visual_meshes, + ) + )[0] + ] + + # Also prune any that in contact with anything if requested + if check_contact: + particle_positions = particle_positions[th.where(self.check_in_contact(particle_positions) == 0)[0]] + + # Also potentially sub-sample if we're past our limit + if max_samples is not None and len(particle_positions) > max_samples: + particle_positions = particle_positions[th.randperm(len(particle_positions))[: int(max_samples)]] + + return self.generate_particles( + positions=particle_positions, + **kwargs, + ) + + def generate_particles_on_object( + self, + obj, + sampling_distance=None, + max_samples=None, + min_samples_for_success=1, + **kwargs, + ): + """ + Generates @n_particles new particle objects and samples their locations on the top surface of object @obj + + Args: + obj (USDObject): Object on which to generate a particle instancer with sampled particles on the object's + top surface + sampling_distance (None or float): If specified, sets the distance between sampled particles. If None, + a simulator autocomputed value will be used + max_samples (None or int): If specified, maximum number of particles to sample + min_samples_for_success (int): Minimum number of particles required to be sampled successfully in order + for this generation process to be considered successful + **kwargs (dict): Any additional keyword-mapped arguments required by subclass implementation + + Returns: + bool: True if enough particles were generated successfully (number of successfully sampled points >= + min_samples_for_success), otherwise False + """ + assert max_samples >= min_samples_for_success, "number of particles to sample should exceed the min for success" + + # We densely sample a grid of points by ray-casting from top to bottom to find the valid positions + radius = self.particle_radius + results = sample_cuboid_on_object_full_grid_topdown( + obj, + # the grid is fully dense - particles are sitting next to each other + ray_spacing=radius * 2 if sampling_distance is None else sampling_distance, + # assume the particles are extremely small - sample cuboids of size 0 for better performance + cuboid_dimensions=th.zeros(3), + # raycast start inside the aabb in x-y plane and outside the aabb in the z-axis + aabb_offset=th.tensor([-radius, -radius, radius]), + # bottom padding should be the same as the particle radius + cuboid_bottom_padding=radius, + # undo_cuboid_bottom_padding should be False - the sampled positions are above the surface by its radius + undo_cuboid_bottom_padding=False, + ) + particle_positions = th.stack([result[0] for result in results if result[0] is not None]) + # Also potentially sub-sample if we're past our limit + if max_samples is not None and len(particle_positions) > max_samples: + particle_positions = particle_positions[th.randperm(len(particle_positions))[:max_samples]] + + n_particles = len(particle_positions) + success = n_particles >= min_samples_for_success + # If we generated a sufficient number of points, generate them in the simulator + if success: + self.generate_particles( + positions=particle_positions, + **kwargs, + ) + + return success + + +@cache +def get_all_system_names(): + """ + Gets all available systems from the BEHAVIOR-1K dataset + + Returns: + set: Set of all available system names that can be created in OmniGibson + """ + system_dir = os.path.join(get_dataset_path("behavior-1k-assets"), "systems") + + assert os.path.exists(system_dir), f"Path for OmniGibson systems not found! Attempted path: {system_dir}" + return set(os.listdir(system_dir)) + + +def create_system_from_metadata(system_name): + """ + Internal helper function to programmatically create a system from dataset metadata. + Args: + system_name (str): Name of the system to create, e.g.: "water", "stain", etc. + + Returns: + BaseSystem: Created system class + """ + # Avoid circular imports + from omnigibson import systems + + # Search for the appropriate system, if not found, fallback + # TODO: Once dataset is fully constructed, DON'T fallback, and assert False instead + all_systems = set(get_all_system_categories(include_cloth=True)) + if system_name not in all_systems: + # Use default config -- assume @system_name is a fluid that uses the same params as water + return systems.FluidSystem( + name=system_name.replace("-", "_"), + particle_contact_offset=0.012, + particle_density=500.0, + is_viscous=False, + material_mtl_name="DeepWater", + ) + else: + # This is not defined yet, but one proposal: + + # Metadata = .json dict, with format: + # { + # "type": one of {"visual", "fluid", "granular"}, + # } + # if visual, include: + # "relative_particle_scaling" : ..., + + # if visual or granular, also includes: + + # --> note: create_particle_template should be deterministic, configured via: + # lambda prim_path, name: og.objects.DatasetObject( + # prim_path=prim_path, + # name=name, + # usd_path=os.path.join(get_dataset_path("behavior-1k-assets"), "systems", system_name, f"{system_name}.usd"), + # category=system_name, + # visible=False, + # fixed_base=False, + # visual_only=True, + # include_default_states=False, + # abilities={}, + # ) + + # if fluid / granular, also include: + # "particle_contact_offset": ..., + # "particle_density": ..., + + # if fluid, also include: + # "is_viscous": bool + # "material_mtl_name": ..., # Base material config to use + # "customize_particle_kwargs": { # Maps property/ies from @MaterialPrim to value to set + # "opacity_constant": ..., + # "albedo_add": ..., + # "diffuse_color_constant": ..., + # ..., + # } + + # --> This will be programmatically constructed into a function: + # def _customize_particle_material(mat: MaterialPrim): --> None + # for attr, val in metadata["customize_particle_kwargs"].items(): + # mat.__setattr__(attr, val) + + # Then, compile the necessary kwargs and generate the requested system + # Parse information + system_dir = os.path.join(get_dataset_path("behavior-1k-assets"), "systems", system_name) + with open(os.path.join(system_dir, "metadata.json"), "r") as f: + metadata = json.load(f) + system_type = metadata["type"] + system_kwargs = dict(name=system_name) + + particle_assets = set(os.listdir(system_dir)) + particle_assets.remove("metadata.json") + has_asset = len(particle_assets) > 0 + if has_asset: + model = sorted(particle_assets)[0] + asset_path = os.path.join(system_dir, model, "usd", f"{model}.usd") + else: + asset_path = None + + if not has_asset: + if system_type == "macro_visual_particle": + # Fallback to stain asset + asset_path = os.path.join( + get_dataset_path("behavior-1k-assets"), "systems", "stain", "ahkjul", "usd", "ahkjul.usd" + ) + has_asset = True + if has_asset: + + def generate_particle_template_fcn(): + return lambda relative_prim_path, name: og.objects.USDObject( + relative_prim_path=relative_prim_path, + name=name, + usd_path=asset_path, + encrypted=True, + category=system_name, + visible=False, + fixed_base=True, + visual_only=True, + kinematic_only=True, + include_default_states=False, + abilities={}, + ) + + else: + + def generate_particle_template_fcn(): + return lambda relative_prim_path, name: og.objects.PrimitiveObject( + relative_prim_path=relative_prim_path, + name=name, + primitive_type="Sphere", + category=system_name, + radius=0.015, + visible=False, + fixed_base=True, + visual_only=True, + kinematic_only=True, + include_default_states=False, + abilities={}, + ) + + def generate_customize_particle_material_fcn(mat_kwargs): + def customize_mat(mat): + for attr, val in mat_kwargs.items(): + setattr(mat, attr, th.tensor(val) if isinstance(val, list) else val) + + return customize_mat + + if system_type == "macro_visual_particle": + system_kwargs["create_particle_template"] = generate_particle_template_fcn() + system_kwargs["scale_relative_to_parent"] = metadata["relative_particle_scaling"] + elif system_type == "granular" or system_type == "macro_physical_particle": + system_kwargs["create_particle_template"] = generate_particle_template_fcn() + system_kwargs["particle_density"] = metadata["particle_density"] + elif system_type == "fluid": + system_kwargs["particle_contact_offset"] = metadata["particle_contact_offset"] + system_kwargs["particle_density"] = metadata["particle_density"] + system_kwargs["is_viscous"] = metadata["is_viscous"] + system_kwargs["material_mtl_name"] = metadata["material_mtl_name"] + system_kwargs["customize_particle_material"] = generate_customize_particle_material_fcn( + mat_kwargs=metadata["customize_material_kwargs"] + ) + else: + raise ValueError( + f"{system_name} system's type {system_type} is invalid! Must be one of " + f"{{ 'macro_visual_particle', 'macro_physical_particle', 'granular', or 'fluid' }}" + ) + + # Generate the requested system + system_cls = "".join([st.capitalize() for st in system_type.split("_")]) + return getattr(systems, f"{system_cls}System")(**system_kwargs) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..591bb6b3559d07df5ada2a1f8b0d8ef59a96cea8 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/__init__.py @@ -0,0 +1,15 @@ +from omnigibson.tasks.behavior_task import BehaviorTask +from omnigibson.tasks.dummy_task import DummyTask +from omnigibson.tasks.grasp_task import GraspTask +from omnigibson.tasks.point_navigation_task import PointNavigationTask +from omnigibson.tasks.point_reaching_task import PointReachingTask +from omnigibson.tasks.task_base import REGISTERED_TASKS + +__all__ = [ + "BehaviorTask", + "DummyTask", + "GraspTask", + "PointNavigationTask", + "PointReachingTask", + "REGISTERED_TASKS", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/behavior_task.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/behavior_task.py new file mode 100644 index 0000000000000000000000000000000000000000..9aa8bd438941c195176d2e09c4905137b89f2a98 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/behavior_task.py @@ -0,0 +1,947 @@ +import os +import json +from pathlib import Path +import random + +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.macros import gm +from omnigibson.objects.dataset_object import DatasetObject +from omnigibson.object_states import Pose +from omnigibson.reward_functions.potential_reward import PotentialReward +from omnigibson.scenes.scene_base import Scene +from omnigibson.scenes.traversable_scene import TraversableScene +from omnigibson.tasks.task_base import BaseTask +from omnigibson.termination_conditions.predicate_goal import PredicateGoal +from omnigibson.termination_conditions.timeout import Timeout +from omnigibson.utils.asset_utils import get_dataset_path +from omnigibson.utils.bddl_utils import ( + get_behavior_activities, + BDDLSampler, + get_knowledge_base, + is_system_bddl_inst, + og_categories_from_bddl_inst, +) +from omnigibson.utils.python_utils import assert_valid_key, classproperty +from omnigibson.utils.config_utils import TorchEncoder +from omnigibson.utils.ui_utils import create_module_logger + +# Create module logger +log = create_module_logger(module_name=__name__) + + +def get_presampled_robot_poses(presampled_poses, robot_model, pose_key=None): + """ + Selects the list of presampled robot poses to use from a task's "robot_poses" metadata + + Args: + presampled_poses (dict): Maps pose key (generic "robot" or a robot model name) to list of poses + robot_model (str): Model of the robot being placed + pose_key (None or str): If specified, pose key to use when no generic "robot" poses exist, e.g. so a + custom robot can reuse another model's poses. Otherwise, falls back to @robot_model + + Returns: + list of dict: Presampled poses, each with "position" and "orientation" keys + """ + # make all lowercase + presampled_poses = {k.lower(): v for k, v in presampled_poses.items()} + # use generic "robot" key if it exists, otherwise look for the requested or model-specific key + if "robot" in presampled_poses: + return presampled_poses["robot"] + key = (pose_key or robot_model).lower() + if key not in presampled_poses: + raise KeyError( + f"No generic or {key!r} presampled robot pose found for {robot_model}! " + f"Available keys: {sorted(presampled_poses.keys())}" + ) + log.info(f"No generic presampled robot pose found, using {key!r} pose.") + return presampled_poses[key] + + +class BehaviorTask(BaseTask): + """ + Task for BEHAVIOR + + Args: + activity_name (None or str): Name of the Behavior Task to instantiate + activity_definition_id (int): Specification to load for the desired task. For a given Behavior Task, multiple task + specifications can be used (i.e.: differing goal conditions, or "ways" to complete a given task). This + ID determines which specification to use + activity_instance_id (int): Specific pre-configured instance of a scene to load for this BehaviorTask. This + will be used only if @online_object_sampling is False. + online_object_sampling (bool): whether to sample object locations online at runtime or not + use_presampled_robot_pose (bool): Whether to use presampled robot poses from scene metadata + randomize_presampled_pose (bool): If True, randomly selects from available presampled poses. If False, always + uses the first pose. Only applies when use_presampled_robot_pose is True. Default is False. + presampled_pose_key (None or str): If specified, presampled pose key (robot model name, e.g. "r1pro") to use + when the scene has no generic "robot" poses. Default is None, which uses the agent's own model name + sampling_whitelist (None or dict): If specified, should map synset name (e.g.: "table.n.01" to a dictionary + mapping category name (e.g.: "breakfast_table") to a list of valid models to be sampled from + that category. During sampling, if a given synset is found in this whitelist, only the specified + models will be used as options + sampling_blacklist (None or dict): If specified, should map synset name (e.g.: "table.n.01" to a dictionary + mapping category name (e.g.: "breakfast_table") to a list of invalid models that should not be sampled from + that category. During sampling, if a given synset is found in this blacklist, all specified + models will not be used as options + highlight_task_relevant_objects (bool): whether to overlay task-relevant objects in the scene with a colored mask + termination_config (None or dict): Keyword-mapped configuration to use to generate termination conditions. This + should be specific to the task class. Default is None, which corresponds to a default config being usd. + Note that any keyword required by a specific task class but not specified in the config will automatically + be filled in with the default config. See cls.default_termination_config for default values used + reward_config (None or dict): Keyword-mapped configuration to use to generate reward functions. This should be + specific to the task class. Default is None, which corresponds to a default config being usd. Note that + any keyword required by a specific task class but not specified in the config will automatically be filled + in with the default config. See cls.default_reward_config for default values used + include_obs (bool): Whether to include observations or not for this task + """ + + def __init__( + self, + activity_name=None, + activity_definition_id=0, + activity_instance_id=0, + online_object_sampling=False, + use_presampled_robot_pose=True, + randomize_presampled_pose=False, + presampled_pose_key=None, + sampling_whitelist=None, + sampling_blacklist=None, + highlight_task_relevant_objects=False, + termination_config=None, + reward_config=None, + include_obs=True, + ): + # Make sure object states are enabled + assert gm.ENABLE_OBJECT_STATES, "Must set gm.ENABLE_OBJECT_STATES=True in order to use BehaviorTask!" + + assert activity_name is not None, "Activity name must be specified for BehaviorTask!" + assert_valid_key(key=activity_name, valid_keys=get_behavior_activities(), name="Behavior Task") + + # Make sure to not use presampled robot pose if we're using online object sampling + assert not ( + online_object_sampling and use_presampled_robot_pose + ), "Cannot use presampled robot pose if online_object_sampling is True!" + + # Activity info + self.activity_name = activity_name + self.activity_definition_id = activity_definition_id + self.activity_instance_id = activity_instance_id + self.compiled_task = None + self.activity_initial_conditions = None + self.activity_goal_conditions = None + self.ground_goal_state_options = None + self.feedback = None # None or str + self.sampler = None # BDDLSampler + + # Scene info + self.scene_name = None + + # Object info + self.online_object_sampling = online_object_sampling # bool + self.use_presampled_robot_pose = use_presampled_robot_pose + self.randomize_presampled_pose = randomize_presampled_pose + self.presampled_pose_key = presampled_pose_key + self.sampling_whitelist = sampling_whitelist # Maps str to str to list + self.sampling_blacklist = sampling_blacklist # Maps str to str to list + self.highlight_task_relevant_objs = highlight_task_relevant_objects # bool + # list of per-env dicts, one per env: object_scopes[env_idx] maps BDDL instance name (str) to + # sim object (BaseObject/BaseSystem) or None + self.object_scopes = None + self.object_instance_to_category = None # Maps str to str + self.future_obj_instances = None # set of str + + # Info for demonstration collection + self.instruction_order = None # th.tensor of int + self.currently_viewed_index = None # int + self.currently_viewed_instruction = None # tuple of str + self.activity_natural_language_initial_conditions = None # str + self.activity_natural_language_goal_conditions = None # str + + # Run super init + super().__init__(termination_config=termination_config, reward_config=reward_config, include_obs=include_obs) + + @classmethod + def get_cached_activity_scene_filename( + cls, scene_model, activity_name, activity_definition_id, activity_instance_id + ): + """ + Helper method to programmatically construct the scene filename for a given pre-cached task configuration + + Args: + scene_model (str): Name of the scene (e.g.: Rs_int) + activity_name (str): Name of the task activity (e.g.: putting_away_halloween_decorations) + activity_definition_id (int): ID of the task definition + activity_instance_id (int): ID of the task instance + + Returns: + str: Filename which, if exists, should include the cached activity scene + """ + return f"{scene_model}_task_{activity_name}_{activity_definition_id}_{activity_instance_id}_template" + + @classmethod + def verify_scene_and_task_config(cls, scene_cfg, task_cfg): + # Run super first + super().verify_scene_and_task_config(scene_cfg=scene_cfg, task_cfg=task_cfg) + + # Possibly modify the scene to load if we're using online_object_sampling + scene_instance, scene_file = scene_cfg["scene_instance"], scene_cfg["scene_file"] + activity_name = task_cfg["activity_name"] + if scene_file is None and scene_instance is None and not task_cfg["online_object_sampling"]: + scene_instance = cls.get_cached_activity_scene_filename( + scene_model=scene_cfg.get("scene_model", "Scene"), + activity_name=activity_name, + activity_definition_id=task_cfg.get("activity_definition_id", 0), + activity_instance_id=task_cfg.get("activity_instance_id", 0), + ) + # Update the value in the scene config + scene_cfg["scene_instance"] = scene_instance + + def _evaluate_predicate(self, env_idx, predicate_name, *entities): + from omnigibson.utils.bddl_utils import evaluate_bddl_predicate + + return evaluate_bddl_predicate(predicate_name, *[self.object_scopes[env_idx][ent] for ent in entities]) + + def get_goal_option_satisfaction(self, env_idx): + """ + Per-env, per-goal-option predicate satisfaction, evaluated against env @env_idx's own object + scope. This is the env-aware building block for the partial-success (Q-score) metric in + vectorized evaluation: each goal-state option is evaluated independently so partial credit can + be computed (see ``omnigibson.metrics.task_metric.compute_q_score`` and ``TaskMetric``). + + Unlike reading ``ground_goal_state_options[*].evaluate()`` directly (which binds the single, + shared ``compiled_task`` scope and therefore returns env 0's result for every env), this routes + evaluation through ``_evaluate_predicate(env_idx, ...)`` so each env reports its own state. + + Args: + env_idx (int): Index of the environment whose object scope to evaluate against. + + Returns: + list[list[bool]]: Outer list is one entry per grounded goal-state option; each inner list + has one bool per grounded predicate in that option (True iff currently satisfied for + this env). + """ + from bddl.condition_evaluation import evaluate_state + + def evaluate_fn(predicate_name, *entities): + return self._evaluate_predicate(env_idx, predicate_name, *entities) + + option_masks = [] + for option in self.ground_goal_state_options: + _, results = evaluate_state(option, evaluate_fn) + satisfied = set(results["satisfied"]) + option_masks.append([i in satisfied for i in range(len(option))]) + return option_masks + + def _create_termination_conditions(self): + # Initialize termination conditions dict and fill in with Timeout and PredicateGoal + terminations = dict() + + terminations["timeout"] = Timeout(max_steps=self._termination_config["max_steps"]) + # PredicateGoal calls check_goal_fn(env_idx); thread env_idx through to the predicate evaluator + # so the (singular) compiled task evaluates against the right env's object_scope binding. + terminations["predicate"] = PredicateGoal( + check_goal_fn=lambda env_idx: self.compiled_task.check_goal( + lambda predicate_name, *entities: self._evaluate_predicate(env_idx, predicate_name, *entities) + ), + ) + + return terminations + + def _create_reward_functions(self): + # Initialize reward functions dict and fill in with Potential reward + rewards = dict() + + rewards["potential"] = PotentialReward( + potential_fcn=self.get_potential, + r_potential=self._reward_config["r_potential"], + ) + + return rewards + + def _load(self, env): + # Store env reference for use in callbacks + self._env = env + + # Load the initial behavior configuration + self.update_activity( + env=env, + activity_name=self.activity_name, + activity_definition_id=self.activity_definition_id, + ) + + # Initialize the current activity + success, self.feedback = self.initialize_activity(env=env) + # assert success, f"Failed to initialize Behavior Activity. Feedback:\n{self.feedback}" + + # Store the scene name. All envs are clones of the same scene model + # (same invariant as _compiled_rooms), so reading from scenes[0] is canonical. + self.scene_name = env.scenes[0].scene_model if isinstance(env.scenes[0], TraversableScene) else None + + # Highlight any task relevant objects if requested + if self.highlight_task_relevant_objs: + for env_idx in range(env.num_envs): + for inst, entity in self.object_scopes[env_idx].items(): + if "agent.n." in inst: + continue + if not is_system_bddl_inst(inst) and entity is not None: + entity.highlighted = True + + # Add callbacks to handle internal processing when new systems / objects are added / removed to the scene + callback_name = f"{self.activity_name}_refresh" + og.sim.add_callback_on_add_obj(name=callback_name, callback=self._update_bddl_scope_from_added_obj) + og.sim.add_callback_on_remove_obj(name=callback_name, callback=self._update_bddl_scope_from_removed_obj) + + og.sim.add_callback_on_system_init(name=callback_name, callback=self._update_bddl_scope_from_system_init) + og.sim.add_callback_on_system_clear(name=callback_name, callback=self._update_bddl_scope_from_system_clear) + + def reset(self, env, env_indices=None): + super().reset(env, env_indices=env_indices) + + if env_indices is None: + env_indices = th.arange(self._num_envs) + + # Use presampled robot pose if specified (only available for officially supported mobile manipulators) + if self.use_presampled_robot_pose: + for env_idx in env_indices: + robot = self.get_agent(env, env_idx) + available_poses = get_presampled_robot_poses( + env.scenes[env_idx].get_task_metadata(key="robot_poses"), + robot_model=robot.model, + pose_key=self.presampled_pose_key, + ) + if self.randomize_presampled_pose: + robot_pose = random.choice(available_poses) + else: + robot_pose = available_poses[0] # Use first presampled pose + + # Presampled poses are stored in scene-relative coordinates. + robot.set_position_orientation(robot_pose["position"], robot_pose["orientation"], frame="scene") + + # Force wake objects + for env_idx in env_indices: + for obj in self.object_scopes[env_idx].values(): + if obj is not None and isinstance(obj, DatasetObject): + obj.wake() + + def _load_non_low_dim_observation_space(self): + # No non-low dim observations so we return an empty dict + return dict() + + @staticmethod + def _build_scene_layout_from_rooms(scene, room_instances): + """Build a scene layout dict for BDDL wildcard expansion from specific room instances. + + Args: + scene: The scene object. + room_instances: Dict mapping room_type -> room_instance_name for the + specific room instances that were selected during object scope assignment. + + Returns: + dict: Maps room_type -> {category: count} for the selected room instances. + """ + from collections import Counter + + layout = {} + for room_type, room_inst in room_instances.items(): + objs = scene.object_registry("in_rooms", room_inst, default_val=[]) + counts = Counter(obj.category for obj in objs) + layout[room_type] = dict(counts) + return layout + + def update_activity(self, env, activity_name, activity_definition_id): + """ + Update the active Behavior activity being deployed. + + Parses the base (non-wildcard) scope from the task definition. Full + compilation is deferred to initialize_activity(), after object scope + selection determines which specific room instances will be used for + wildcard expansion. + + Args: + env (og.Environment): OmniGibson active environment + activity_name (None or str): Name of the Behavior Task to instantiate + activity_definition_id (int): Specification to load for the desired task + """ + # Activity info + self.activity_name = activity_name + self.activity_definition_id = activity_definition_id + self._task_def = get_knowledge_base().get_task(f"{activity_name}-{activity_definition_id}") + + # Parse base scope (strips wildcards if any, giving us the non-wildcard instances) + self._base_conditions, base_scope, self._base_inroom_assignments = self._task_def.parse_base_scope() + # compiled_task and downstream conditions describe symbolic task content shared across + # all envs (every env is a clone of the same scene with identical room layout), so they + # are populated as a single instance during initialize_activity(). + self.compiled_task = None + self.activity_initial_conditions = None + self.activity_goal_conditions = None + self.ground_goal_state_options = None + # Remembers which room dict was used to compile self.compiled_task — checked against + # every env's room layout in _compile_with_rooms() to detect any drift from the + # "all envs use the same rooms" assumption. + self._compiled_rooms = None + + # Set up base object scope per-env (agent first, then base instances) + self.object_scopes = [None] * env.num_envs + for env_idx in range(env.num_envs): + self.object_scopes[env_idx] = {"agent.n.01_1": None} + self.object_scopes[env_idx].update({name: None for name in base_scope}) + + # Object instance to category mapping (base only for now) + self.object_instance_to_category = { + obj_inst: obj_cat + for obj_cat in self._base_conditions.parsed_objects + for obj_inst in self._base_conditions.parsed_objects[obj_cat] + } + + def _finalize_compiled_task(self): + """Populate symbolic attributes from self.compiled_task. + + Runs exactly once after the (singular) compiled task is built. All fields set + here are symbolic / scene-independent and shared across envs. + """ + compiled = self.compiled_task + + # Object info — derived from the compiled (wildcard-expanded) task definition + self.object_instance_to_category = { + obj_inst: obj_cat for obj_cat in compiled.parsed_objects for obj_inst in compiled.parsed_objects[obj_cat] + } + + # Conditions + self.activity_initial_conditions = compiled.initial_conditions + self.activity_goal_conditions = compiled.goal_conditions + self.ground_goal_state_options = compiled.ground_goal_state_options + + # Demo attributes + self.instruction_order = th.arange(len(compiled.conditions.parsed_goal_conditions)) + self.instruction_order = self.instruction_order[th.randperm(self.instruction_order.size(0))] + self.currently_viewed_index = 0 + self.currently_viewed_instruction = self.instruction_order[self.currently_viewed_index] + self.activity_natural_language_initial_conditions = compiled.natural_language_initial_conditions + self.activity_natural_language_goal_conditions = compiled.natural_language_goal_conditions + + def _finalize_object_scope(self, env_idx): + """Rebuild self.object_scopes[env_idx] from self.compiled_task.object_scope. + + Called per env after compile. Preserves any objects already bound to base-scope + instances so we don't lose assignments made before wildcard expansion. + + Args: + env_idx (int): Index of the env whose scope should be rebuilt. + """ + scope = self.object_scopes[env_idx] + existing = dict(scope) + scope.clear() + scope["agent.n.01_1"] = existing.get("agent.n.01_1") + for name in self.compiled_task.object_scope: + scope[name] = existing.get(name) + + def _determine_room_instances(self, env, env_idx): + """Determine which specific room instances to use based on assigned objects in @env_idx's scene. + + For each room type in the task's inroom assignments, finds which room + instance the assigned object is actually in. All objects assigned to the + same room type should be in the same room instance (ensured by the + sampler's room consolidation logic). + + Args: + env: The environment with the active scene. + env_idx (int): Index of the env / scene. + + Returns: + dict: Maps room_type (str) -> room_instance_name (str). + """ + room_instances = {} + for obj_inst, room_type in self._base_inroom_assignments.items(): + entity = self.object_scopes[env_idx].get(obj_inst) + if entity is None: + continue + # Find which room instance this object is in + if hasattr(entity, "in_rooms") and entity.in_rooms: + for room_inst in entity.in_rooms: + inst_room_type = room_inst.rsplit("_", 1)[0] # Get room type by removing instance number suffix + if inst_room_type == room_type: + if room_type in room_instances and room_instances[room_type] != room_inst: + log.warning( + f"Multiple room instances for room type '{room_type}': " + f"{room_instances[room_type]} vs {room_inst}. Using {room_instances[room_type]}." + ) + else: + room_instances[room_type] = room_inst + break + return room_instances + + def _compile_with_rooms(self, env, env_idx): + """Compile the wildcard task for using the specific room instances from its assigned objects. + + After object scope has been assigned (via cache or sampling), this + determines which room instances are being used, counts objects in those + rooms, and compiles the task with proper wildcard expansion. + + Args: + env: The environment with the active scene. + env_idx (int): Index of the env / scene to align scope for. + """ + room_instances = self._determine_room_instances(env, env_idx) + + if self.compiled_task is None: + scene_layout = self._build_scene_layout_from_rooms(env.scenes[env_idx], room_instances) + self.compiled_task = self._task_def.compile(scene_layout=scene_layout) + self._compiled_rooms = room_instances + self._finalize_compiled_task() + else: + assert room_instances == self._compiled_rooms, ( + f"Room layout mismatch between envs: compiled with {self._compiled_rooms} " + f"but env {env_idx} reports {room_instances}. Single-compile assumes uniform room layout." + ) + + # Per-env scope: rebuild against the compiled task's scope, preserving prior assignments + old_scope = dict(self.object_scopes[env_idx]) + self._finalize_object_scope(env_idx) + for inst, entity in old_scope.items(): + if inst in self.object_scopes[env_idx]: + self.object_scopes[env_idx][inst] = entity + + def get_potential(self, env, env_idx): + # Bind env_idx into the predicate evaluator so check_goal sees an arity-2 callback + _, satisfied_predicates = self.compiled_task.check_goal( + lambda predicate_name, *entities: self._evaluate_predicate(env_idx, predicate_name, *entities) + ) + success_score = len(satisfied_predicates["satisfied"]) / ( + len(satisfied_predicates["satisfied"]) + len(satisfied_predicates["unsatisfied"]) + ) + return -success_score + + def initialize_activity(self, env): + """ + Initializes the desired activity in the current environment @env. + + The flow is: + 1. Select objects for each env's base (non-wildcard) scope via sampling or cache. + 2. Determine which room instances those objects are in (the first env's choice is + canonical; other envs are asserted to match). + 3. Compile the task once with the correct scene layout (expanding any wildcards). + 4. Assign any wildcard-expanded instances per env. + + Args: + env (Environment): Current active environment instance + + Returns: + 2-tuple: + - bool: Whether the generated scene activity should be accepted or not + - list[dict]: Per-env feedback from the sampling / initialization process + """ + + # self.sampler is a single instance bound to env 0: + # - Online mode: actively used (num_envs guaranteed to be 1 by the assert below). + # - Cache mode: created so downstream tooling (scripts/sampling/multiply_b1k_tasks.py) + # can poke its internals to re-sample. Not exercised during init. + self.sampler = BDDLSampler( + env=env, + env_idx=0, + activity_conditions=self._base_conditions, + object_scope=self.object_scopes[0], + ) + + if self.online_object_sampling: + assert env.num_envs == 1, "Online sampling mode only works with num_envs==1" + env_idx = 0 + + # Phase 1: assign objects using only parsed conditions (no compilation needed) + accept, fb = self.sampler.assign_objects( + sampling_whitelist=self.sampling_whitelist, + sampling_blacklist=self.sampling_blacklist, + ) + if not accept: + return accept, [fb] + + # Compile with the correct rooms now that objects are assigned + self._compile_with_rooms(env, env_idx) + + # Phase 2: sample states using compiled conditions + accept, fb = self.sampler.sample_states(self.compiled_task) + if not accept: + return accept, [fb] + + # Assign any wildcard-expanded instances to remaining scene objects + self._assign_wildcard_instances(env, env_idx) + + return True, [fb] + + # Cache mode — num_envs can be >= 1 + feedback = [None] * env.num_envs + + # Derive future instances from parsed conditions for cache assignment + self.future_obj_instances = { + cond[1] for cond in self._base_conditions.parsed_initial_conditions if cond[0] == "future" + } + + # Assign base scope objects from cache (non-strict: skip instances + # not in cache, e.g. wildcard instances that don't exist yet) + for env_idx in range(env.num_envs): + self.assign_object_scope_with_cache(env, env_idx) + self._compile_with_rooms(env, env_idx) + + # Refine future instances using the now-compiled task's (singular) initial conditions + self.future_obj_instances = { + init_cond.body[1] for init_cond in self.activity_initial_conditions if init_cond.body[0] == "future" + } + + # Second pass per env: re-assign from cache (scope now includes wildcard instances) + # and fill in any remaining wildcard slots from scene objects. + # TODO @wensi-ai: Check object scope again to see if any wildcard objects are recorded. + # 2026+ tasks do this, 2025 ones don't. + for env_idx in range(env.num_envs): + # Use non-strict so that wildcard-expanded instances absent from cache are handled by + # _assign_wildcard_instances below rather than raising an assertion error. + self.assign_object_scope_with_cache(env, env_idx) + # TODO @wensi-ai: Assign objects to remaining wildcard objects. This is a no-op for 2026+ tasks. + self._assign_wildcard_instances(env, env_idx) + # assert that everything in the object scope that's not a future object is not None + for inst, entity in self.object_scopes[env_idx].items(): + if inst not in self.future_obj_instances and entity is None: + raise ValueError( + f"Object instance '{inst}' (env_idx={env_idx}) was not assigned an entity during cache assignment!" + ) + + return True, feedback + + def _assign_wildcard_instances(self, env, env_idx): + """Assign wildcard-expanded instances to scene objects in the selected rooms. + + After wildcard compilation, new instances exist in the scope that need + to be matched to objects in the scene that weren't part of the base scope. + + Args: + env: The environment with the active scene. + env_idx (int): Index of the env / scene to assign for. + """ + for inst in self.object_scopes[env_idx]: + if self.object_scopes[env_idx][inst] is not None: + continue + if "agent.n." in inst: + continue + # Try to find a matching object in this env's scene + categories = set(og_categories_from_bddl_inst(inst)) + for obj in env.scenes[env_idx].objects: + # Check category match and that obj isn't already assigned + if obj.category in categories and obj not in self.object_scopes[env_idx].values(): + self.object_scopes[env_idx][inst] = obj + break + + def get_agent(self, env, env_idx=0): + """ + Grab the 0th agent from @env for a specific scene + + Args: + env (Environment): Current active environment instance + env_idx (int): Index of the environment/scene + + Returns: + BaseRobot: The 0th robot from the specified scene + """ + # We assume the relevant agent is the first agent in the scene + return env.scenes[env_idx].robots[0] + + def assign_object_scope_with_cache(self, env, env_idx): + """ + Assigns objects within the current object scope from cached scene metadata. + + Args: + env (Environment): Current active environment instance + env_idx (int): Index of the environment/scene + """ + scene = env.scenes[env_idx] + + # Load task metadata + inst_to_name = scene.get_task_metadata(key="inst_to_name") + + # Assign object_scope based on a cached scene + for obj_inst in self.object_scopes[env_idx]: + if obj_inst in self.future_obj_instances: + entity = None + elif obj_inst not in inst_to_name: + # Skip instances not found (e.g., future objects + # when future_obj_instances isn't fully populated yet) + continue + else: + name = inst_to_name[obj_inst] + is_system = name in scene.available_systems.keys() + # TODO: If we load a robot with a different set of configs, we will not be able to match with the + # original object_scope. This is a temporary fix to handle this case. A proper fix involves + # storing the robot (potentially only base pose) in the task metadata instead of as a regular object + if "agent.n." in obj_inst: + idx = int(obj_inst.split("_")[-1].lstrip("0")) - 1 + entity = scene.robots[idx] + else: + entity = scene.get_system(name) if is_system else scene.object_registry("name", name) + self.object_scopes[env_idx][obj_inst] = entity + + def update_bddl_scope_metadata(self, env, env_idx): + """ + Updates the task metadata with the current instance-to-name mapping for all existing entities. + + Args: + env (Environment): The environment containing the scene to update + env_idx (int): Index of the environment/scene + """ + + def _get_name(inst, entity): + if is_system_bddl_inst(inst): + return og_categories_from_bddl_inst(inst)[0] + return entity.name + + env.scenes[env_idx].write_task_metadata( + key="inst_to_name", + data={ + inst: _get_name(inst, entity) + for inst, entity in self.object_scopes[env_idx].items() + if entity is not None + }, + ) + + def _get_obs(self, env, env_idx): + low_dim_obs = dict() + + # Collect non-system instances with existence status, drawn from THIS env's scope only. + obj_entries = [ + (inst, obj, obj is not None) + for inst, obj in self.object_scopes[env_idx].items() + if not is_system_bddl_inst(inst) + ] + + # Batch rpy calculations for much better efficiency + objs_rpy = T.quat2euler( + th.stack( + [ + obj.states[Pose].get_value()[1] if obj_exist else th.tensor([0, 0, 0, 1.0]) + for _, obj, obj_exist in obj_entries + ] + ) + ) + objs_rpy_cos = th.cos(objs_rpy) + objs_rpy_sin = th.sin(objs_rpy) + + # Always add agent info first + agent = self.get_agent(env=env, env_idx=env_idx) + + for (inst, obj, obj_exist), obj_rpy, obj_rpy_cos, obj_rpy_sin in zip( + obj_entries, objs_rpy, objs_rpy_cos, objs_rpy_sin + ): + if obj_exist: + low_dim_obs[f"{inst}_real"] = th.tensor([1.0]) + low_dim_obs[f"{inst}_pos"] = obj.states[Pose].get_value()[0] + low_dim_obs[f"{inst}_ori_cos"] = obj_rpy_cos + low_dim_obs[f"{inst}_ori_sin"] = obj_rpy_sin + if obj.name != agent.name: + for arm in agent.arm_names: + grasping_object = agent.is_grasping(arm=arm, candidate_obj=obj) + low_dim_obs[f"{inst}_in_gripper_{arm}"] = th.tensor([float(grasping_object)]) + else: + low_dim_obs[f"{inst}_real"] = th.zeros(1) + low_dim_obs[f"{inst}_pos"] = th.zeros(3) + low_dim_obs[f"{inst}_ori_cos"] = th.zeros(3) + low_dim_obs[f"{inst}_ori_sin"] = th.zeros(3) + for arm in agent.arm_names: + low_dim_obs[f"{inst}_in_gripper_{arm}"] = th.zeros(1) + + return low_dim_obs, dict() + + def _step_termination(self, env, action, infos=None): + # Run super first + dones, infos = super()._step_termination(env=env, action=action, infos=infos) + + # Add additional info per env + goal_status = self._termination_conditions["predicate"].goal_status + for env_idx in range(self._num_envs): + infos[env_idx]["goal_status"] = goal_status[env_idx] + + return dones, infos + + def _update_bddl_scope_from_added_obj(self, obj): + """ + Internal callback function to be called when new objects are added to the simulator to potentially update internal + bddl object scope + + Args: + obj (USDObject): Newly imported object + """ + # Each object belongs to exactly one scene. Find which env's scene owns this object + # and update only that env's scope. + for env_idx in range(len(self.object_scopes)): + if obj.scene is not None and obj.scene is not self._env.scenes[env_idx]: + continue + for inst, entity in self.object_scopes[env_idx].items(): + if ( + entity is None + and not is_system_bddl_inst(inst) + and obj.category in set(og_categories_from_bddl_inst(inst)) + ): + self.object_scopes[env_idx][inst] = obj + return + + def _update_bddl_scope_from_removed_obj(self, obj): + """ + Internal callback function to be called when sim._pre_remove_object() is called to potentially update internal + bddl object scope + + Args: + obj (USDObject): Newly removed object + """ + for env_idx in range(len(self.object_scopes)): + if obj.scene is not None and obj.scene is not self._env.scenes[env_idx]: + continue + for inst, entity in self.object_scopes[env_idx].items(): + if entity is not None and not is_system_bddl_inst(inst) and obj.name == entity.name: + self.object_scopes[env_idx][inst] = None + return + + def _update_bddl_scope_from_system_init(self, system): + """ + Internal callback function to be called when system.initialize() is called to potentially update internal + bddl object scope + + Args: + system (BaseSystem): Newly initialized system + """ + for env_idx in range(len(self.object_scopes)): + if system.scene is not None and system.scene is not self._env.scenes[env_idx]: + continue + for inst, entity in self.object_scopes[env_idx].items(): + if ( + entity is None + and is_system_bddl_inst(inst) + and og_categories_from_bddl_inst(inst)[0] == system.name + ): + self.object_scopes[env_idx][inst] = system + return + + def _update_bddl_scope_from_system_clear(self, system): + """ + Internal callback function to be called when system.clear() is called to potentially update internal + bddl object scope + + Args: + system (BaseSystem): Newly cleared system + """ + for env_idx in range(len(self.object_scopes)): + if system.scene is not None and system.scene is not self._env.scenes[env_idx]: + continue + for inst, entity in self.object_scopes[env_idx].items(): + if entity is not None and is_system_bddl_inst(inst) and system.name == entity.name: + self.object_scopes[env_idx][inst] = None + return + + def show_instruction(self, env_idx=0): + """ + Get current instruction for user + + Args: + env_idx (int): Index of the environment/scene. Default is 0. + + Returns: + 3-tuple: + - str: Current goal condition in natural language + - 3-tuple: (R,G,B) color to assign to text + - list of USDObject: Relevant objects for the current instruction + """ + satisfied = ( + self.currently_viewed_instruction + in self._termination_conditions["predicate"].goal_status[env_idx]["satisfied"] + ) + natural_language_condition = self.activity_natural_language_goal_conditions[self.currently_viewed_instruction] + objects = self.activity_goal_conditions[self.currently_viewed_instruction].get_relevant_objects() + text_color = ( + [83.0 / 255.0, 176.0 / 255.0, 72.0 / 255.0] if satisfied else [255.0 / 255.0, 51.0 / 255.0, 51.0 / 255.0] + ) + + return natural_language_condition, text_color, objects + + def iterate_instruction(self): + """ + Increment the instruction + """ + self.currently_viewed_index = (self.currently_viewed_index + 1) % len( + self.compiled_task.conditions.parsed_goal_conditions + ) + self.currently_viewed_instruction = self.instruction_order[self.currently_viewed_index] + + def save_task(self, env, save_dir=None, override=False, task_relevant_only=False, suffix=None, env_idx=0): + """ + Writes the current scene configuration to a .json file + + Args: + env (og.Environment): OmniGibson active environment + save_dir (None or str): If specified, absolute fpath to the desired directory to write the .json. Default is + {gm.DATA_PATH}/2026-challenge-task-instances/scenes//json/...> + override (bool): Whether to override any files already found at the path to write the task .json + task_relevant_only (bool): Whether to only save the task relevant object scope states. If True, will only + call dump_state() on all the BDDL instances in self.object_scopes, else will save the entire sim state + via env.scene.save() + suffix (None or str): If specified, suffix to add onto the end of the scene filename that will be saved + """ + save_dir = ( + os.path.join(get_dataset_path("2026-challenge-task-instances"), "scenes", self.scene_name, "json") + if save_dir is None + else save_dir + ) + assert self.scene_name is not None, "Scene name must be set in order to save task" + fname = self.get_cached_activity_scene_filename( + scene_model=self.scene_name, + activity_name=self.activity_name, + activity_definition_id=self.activity_definition_id, + activity_instance_id=self.activity_instance_id, + ) + path = os.path.join(save_dir, f"{fname}.json") + if task_relevant_only: + path = path.replace(".json", "-tro_state.json") + if suffix is not None: + path = path.replace(".json", f"-{suffix}.json") + if os.path.exists(path) and not override: + log.warning(f"Scene json already exists at {path}. Use override=True to force writing of new json.") + return + + # Save based on whether we're only storing task-relevant object scope states or not + if task_relevant_only: + task_relevant_state_dict = { + bddl_name: bddl_obj.dump_state(serialized=False) + for bddl_name, bddl_obj in env.task.object_scopes[env_idx].items() + if bddl_obj is not None and "agent" not in bddl_name + } + Path(os.path.dirname(path)).mkdir(parents=True, exist_ok=True) + with open(path, "w+") as f: + json.dump(task_relevant_state_dict, f, cls=TorchEncoder, indent=4) + else: + # Update task metadata and save + self.update_bddl_scope_metadata(env, env_idx) + env.scenes[env_idx].save(json_path=path) + + @property + def name(self): + """ + Returns: + str: Name of this task. Defaults to class name + """ + name_base = super().name + + # Add activity name, def id, and inst id + return f"{name_base}_{self.activity_name}_{self.activity_definition_id}_{self.activity_instance_id}" + + @classproperty + def valid_scene_types(cls): + # Any scene can be used + return {Scene} + + @classproperty + def default_termination_config(cls): + return { + "max_steps": 500, + } + + @classproperty + def default_reward_config(cls): + return { + "r_potential": 1.0, + } diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/dummy_task.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/dummy_task.py new file mode 100644 index 0000000000000000000000000000000000000000..9726eb1feada286ca4d72836901ebfd8d1eb8f9b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/dummy_task.py @@ -0,0 +1,44 @@ +from omnigibson.scenes.scene_base import Scene +from omnigibson.tasks.task_base import BaseTask +from omnigibson.utils.python_utils import classproperty + + +class DummyTask(BaseTask): + """ + Dummy task + """ + + def _load(self, env): + # Do nothing here + pass + + def _create_termination_conditions(self): + # Do nothing + return dict() + + def _create_reward_functions(self): + # Do nothing + return dict() + + def _get_obs(self, env, env_idx): + # No task-specific obs of any kind + return dict(), dict() + + def _load_non_low_dim_observation_space(self): + # No non-low dim observations so we return an empty dict + return dict() + + @classproperty + def valid_scene_types(cls): + # Any scene works + return {Scene} + + @classproperty + def default_termination_config(cls): + # Empty dict + return {} + + @classproperty + def default_reward_config(cls): + # Empty dict + return {} diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/grasp_task.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/grasp_task.py new file mode 100644 index 0000000000000000000000000000000000000000..0952f7b44e76c2c5f8a13b43cb06fc2c7f04c12d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/grasp_task.py @@ -0,0 +1,224 @@ +import json +import random + +import torch as th + +import omnigibson.utils.transform_utils as T +from omnigibson.action_primitives.starter_semantic_action_primitives import StarterSemanticActionPrimitives +from omnigibson.objects.usd_object import REGISTERED_OBJECTS +from omnigibson.reward_functions.grasp_reward import GraspReward +from omnigibson.scenes.scene_base import Scene +from omnigibson.tasks.task_base import BaseTask +from omnigibson.termination_conditions.timeout import Timeout +from omnigibson.utils.grasping_planning_utils import get_grasp_poses_for_object_sticky +from omnigibson.utils.python_utils import classproperty, create_class_from_registry_and_config + +MAX_JOINT_RANDOMIZATION_ATTEMPTS = 50 + + +class GraspTask(BaseTask): + """ + Grasp task + """ + + def __init__( + self, + obj_name, + termination_config=None, + reward_config=None, + include_obs=True, + precached_reset_pose_path=None, + objects_config=None, + ): + self.obj_name = obj_name + self._primitive_controllers = None # list per scene + self._reset_poses = None + self._objects_config = objects_config + if precached_reset_pose_path is not None: + with open(precached_reset_pose_path) as f: + self._reset_poses = json.load(f) + super().__init__(termination_config=termination_config, reward_config=reward_config, include_obs=include_obs) + + def _load(self, env): + for scene in env.scenes: + for obj_config in self._objects_config: + obj = scene.object_registry("name", obj_config["name"]) + # Create object + if obj is None: + obj = create_class_from_registry_and_config( + cls_name=obj_config["type"], + cls_registry=REGISTERED_OBJECTS, + cfg=obj_config, + cls_type_descriptor="object", + ) + # Import the object into the simulator and set the pose + scene.add_object(obj) + + obj_pos = [0.0, 0.0, 0.0] if "position" not in obj_config else obj_config["position"] + obj_orn = [0.0, 0.0, 0.0, 1.0] if "orientation" not in obj_config else obj_config["orientation"] + obj.set_position_orientation(position=obj_pos, orientation=obj_orn, frame="scene") + + def _create_termination_conditions(self): + terminations = dict() + # terminations["graspgoal"] = GraspGoal( + # self.obj_name + # ) + # This helpes to prevent resets happening at different times + terminations["timeout"] = Timeout(max_steps=self._termination_config["max_steps"]) + # terminations["falling"] = Falling() + + return terminations + + def _create_reward_functions(self): + rewards = dict() + rewards["grasp"] = GraspReward(self.obj_name, **self._reward_config) + return rewards + + def _reset_agent(self, env, env_indices): + for env_idx in env_indices: + robot = env.scenes[env_idx].robots[0] + for arm in robot.arm_names: + robot.release_grasp_immediately(arm=arm) + + # If available, reset the robot with cached reset poses. + # This is significantly faster than randomizing using the primitives. + if self._reset_poses is not None: + joint_control_idx = th.cat([robot.trunk_control_idx, robot.arm_control_idx[robot.default_arm]]) + robot_pose = random.choice(self._reset_poses) + joint_pos = th.tensor(robot_pose["joint_pos"]) + robot.set_joint_positions(joint_pos, joint_control_idx) + robot_pos = th.tensor(robot_pose["base_pos"]) + robot_orn = th.tensor(robot_pose["base_ori"]) + robot.set_position_orientation(position=robot_pos, orientation=robot_orn, frame="scene") + # Otherwise, reset using the primitive controller (requires holonomic base robot). + elif not robot.is_holonomic_base: + raise ValueError( + f"Robot '{robot.model}' does not have a holonomic base. " + "CuRobo-based reset requires a holonomic base robot (e.g. Tiago, R1). " + "Please provide precached_reset_pose_path for non-holonomic robots." + ) + else: + if self._primitive_controllers is None: + self._primitive_controllers = [None] * env.num_envs + if self._primitive_controllers[env_idx] is None: + self._primitive_controllers[env_idx] = StarterSemanticActionPrimitives( + env, robot, enable_head_tracking=False + ) + pc = self._primitive_controllers[env_idx] + + # Randomize the robots joint positions + joint_control_idx = th.cat([robot.trunk_control_idx, robot.arm_control_idx[robot.default_arm]]) + for _ in range(MAX_JOINT_RANDOMIZATION_ATTEMPTS): + joint_pos, joint_control_idx = self._get_random_joint_position(robot) + all_joint_pos = robot.get_joint_positions().clone() + all_joint_pos[joint_control_idx] = joint_pos + collision_detected = pc._motion_generator.check_collisions( + [all_joint_pos], + ).cpu()[0] + if not collision_detected: + robot.set_joint_positions(joint_pos, joint_control_idx) + break + + # Randomize the robot's 2d pose + obj = env.scenes[env_idx].object_registry("name", self.obj_name) + grasp_poses = get_grasp_poses_for_object_sticky(obj) + grasp_pose = random.choice(grasp_poses) + sampled_pose_2d = pc._sample_pose_near_object(obj, eef_pose=grasp_pose) + if sampled_pose_2d is None: + raise ValueError("Could not sample a valid 2d pose near the object") + robot_pose = pc._get_robot_pose_from_2d_pose(sampled_pose_2d) + robot.set_position_orientation(*robot_pose) + + # Check if the robot has toppled + robot_up = T.quat_apply(robot.get_position_orientation()[1], th.tensor([0, 0, 1], dtype=th.float32)) + if robot_up[2] < 0.75: + raise ValueError("Robot has toppled over") + + def _reset_scene(self, env, env_indices): + super()._reset_scene(env, env_indices) + + # Reset objects + for idx in env_indices: + for obj_config in self._objects_config: + # Get object in the scene + obj_name = obj_config["name"] + obj = env.scenes[idx].object_registry("name", obj_name) + if obj is None: + raise ValueError("Object {} not found in scene".format(obj_name)) + + # Set object pose + obj_pos = [0.0, 0.0, 0.0] if "position" not in obj_config else obj_config["position"] + obj_orn = [0.0, 0.0, 0.0, 1.0] if "orientation" not in obj_config else obj_config["orientation"] + obj.set_position_orientation(position=obj_pos, orientation=obj_orn, frame="scene") + + # Overwrite reset by only removing reset scene + def reset(self, env, env_indices=None): + """ + Resets this task in the environment + + Args: + env (Environment): environment instance to reset + env_indices (th.Tensor): indices of environments to reset + """ + if env_indices is None: + env_indices = th.arange(self._num_envs) + + # Reset the scene, agent, and variables + # Try up to 20 times per env + for _ in range(20): + try: + self._reset_scene(env, env_indices) + self._reset_agent(env, env_indices) + break + except Exception as e: + print("Resetting error: ", e) + else: + raise ValueError("Could not reset task.") + self._reset_variables(env, env_indices) + + # Also reset all termination conditions and reward functions + for termination_condition in self._termination_conditions.values(): + termination_condition.reset(self, env, env_indices) + for reward_function in self._reward_functions.values(): + reward_function.reset(self, env, env_indices) + + def _get_random_joint_position(self, robot): + joint_positions = [] + joint_control_idx = th.cat([robot.trunk_control_idx, robot.arm_control_idx[robot.default_arm]]) + all_joints = list(robot.joints.values()) + arm_joints = [all_joints[idx] for idx in joint_control_idx] + for joint in arm_joints: + val = random.uniform(joint.lower_limit, joint.upper_limit) + joint_positions.append(val) + return th.tensor(joint_positions), joint_control_idx + + def _get_obs(self, env, env_idx): + obj = env.scenes[env_idx].object_registry("name", self.obj_name) + robot = env.scenes[env_idx].robots[0] + relative_pos, _ = T.relative_pose_transform(*obj.get_position_orientation(), *robot.get_position_orientation()) + + return {"obj_pos": relative_pos}, dict() + + def _load_non_low_dim_observation_space(self): + # No non-low dim observations so we return an empty dict + return dict() + + @classproperty + def valid_scene_types(cls): + # Any scene works + return {Scene} + + @classproperty + def default_termination_config(cls): + return {"max_steps": 100000} + + @classproperty + def default_reward_config(cls): + return { + "dist_coeff": 0.1, + "grasp_reward": 1.0, + "collision_penalty": 1.0, + "eef_position_penalty_coef": 0.01, + "eef_orientation_penalty_coef": 0.001, + "regularization_coef": 0.01, + } diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/point_navigation_task.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/point_navigation_task.py new file mode 100644 index 0000000000000000000000000000000000000000..c93fc5982e2bdc82cb3a0241a5c6a02c62e47a7c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/point_navigation_task.py @@ -0,0 +1,530 @@ +import math + +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.object_states import Pose +from omnigibson.objects.primitive_object import PrimitiveObject +from omnigibson.reward_functions.collision_reward import CollisionReward +from omnigibson.reward_functions.point_goal_reward import PointGoalReward +from omnigibson.reward_functions.potential_reward import PotentialReward +from omnigibson.scenes.traversable_scene import TraversableScene +from omnigibson.tasks.task_base import BaseTask +from omnigibson.termination_conditions.falling import Falling +from omnigibson.termination_conditions.max_collision import MaxCollision +from omnigibson.termination_conditions.point_goal import PointGoal +from omnigibson.termination_conditions.timeout import Timeout +from omnigibson.utils.python_utils import assert_valid_key, classproperty +from omnigibson.utils.ui_utils import create_module_logger + +# Create module logger +log = create_module_logger(module_name=__name__) + + +# Valid point navigation reward types +POINT_NAVIGATION_REWARD_TYPES = {"l2", "geodesic"} + + +class PointNavigationTask(BaseTask): + """ + Point Navigation Task + The task is to navigate to a goal position + + Args: + robot_idn (int): Which robot that this task corresponds to + floor (int): Which floor to navigate on + initial_pos (None or 3-array): If specified, should be (x,y,z) global initial position to place the robot + at the start of each task episode. If None, a collision-free value will be randomly sampled + initial_quat (None or 4-array): If specified, should be (x,y,z,w) global quaternion orientation to place the + robot at the start of each task episode. If None, a value will be randomly sampled about the z-axis + goal_pos (None or 3-array): If specified, should be (x,y,z) global goal position to reach for the given task + episode. If None, a collision-free value will be randomly sampled + goal_tolerance (float): Distance between goal position and current position below which is considered a task + success + goal_in_polar (bool): Whether to represent the goal in polar coordinates or not when capturing task observations + path_range (None or 2-array): If specified, should be (min, max) values representing the range of valid + total path lengths that are valid when sampling initial / goal positions + visualize_goal (bool): Whether to visualize the initial / goal locations + visualize_path (bool): Whether to visualize the path from initial to goal location, as represented by + discrete waypoints + goal_height (float): If visualizing, specifies the height of the visual goals (m) + waypoint_height (float): If visualizing, specifies the height of the visual waypoints (m) + waypoint_width (float): If visualizing, specifies the width of the visual waypoints (m) + n_vis_waypoints (int): If visualizing, specifies the number of waypoints to generate + reward_type (str): Type of reward to use. Valid options are: {"l2", "geodesic"} + termination_config (None or dict): Keyword-mapped configuration to use to generate termination conditions. This + should be specific to the task class. Default is None, which corresponds to a default config being usd. + Note that any keyword required by a specific task class but not specified in the config will automatically + be filled in with the default config. See cls.default_termination_config for default values used + reward_config (None or dict): Keyword-mapped configuration to use to generate reward functions. This should be + specific to the task class. Default is None, which corresponds to a default config being usd. Note that + any keyword required by a specific task class but not specified in the config will automatically be filled + in with the default config. See cls.default_reward_config for default values used + include_obs (bool): Whether to include observations or not for this task + """ + + def __init__( + self, + robot_idn=0, + floor=0, + initial_pos=None, + initial_quat=None, + goal_pos=None, + goal_tolerance=0.5, + goal_in_polar=False, + path_range=None, + visualize_goal=False, + visualize_path=False, + goal_height=0.06, + waypoint_height=0.05, + waypoint_width=0.1, + n_vis_waypoints=10, + reward_type="l2", + termination_config=None, + reward_config=None, + include_obs=True, + ): + # Store inputs + self._robot_idn = robot_idn + self._floor = floor + self._initial_pos_cfg = initial_pos if initial_pos is None else th.tensor(initial_pos) + self._initial_quat_cfg = initial_quat if initial_quat is None else th.tensor(initial_quat) + self._goal_pos_cfg = goal_pos if goal_pos is None else th.tensor(goal_pos) + self._goal_tolerance = goal_tolerance + self._goal_in_polar = goal_in_polar + self._path_range = path_range + self._randomize_initial_pos = initial_pos is None + self._randomize_initial_quat = initial_quat is None + self._randomize_goal_pos = goal_pos is None + self._visualize_goal = visualize_goal + self._visualize_path = visualize_path + self._goal_height = goal_height + self._waypoint_height = waypoint_height + self._waypoint_width = waypoint_width + self._n_vis_waypoints = n_vis_waypoints + assert_valid_key(key=reward_type, valid_keys=POINT_NAVIGATION_REWARD_TYPES, name="reward type") + self._reward_type = reward_type + + # Per-env state (populated during reset) + self._initial_pos = None # list of (3,) tensors per env + self._initial_quat = None # list of (4,) tensors per env + self._goal_pos = None # list of (3,) tensors per env + self._path_length = None # th.Tensor (num_envs,) + self._current_robot_pos = None # list of (3,) tensors per env + self._geodesic_dist = None # th.Tensor (num_envs,) + + # Visualization markers (per-env; one set per scene when enabled) + self._initial_pos_markers = None # list of PrimitiveObject per env + self._goal_pos_markers = None # list of PrimitiveObject per env + self._waypoint_markers = None # list of list of PrimitiveObject: outer per-env, inner per-waypoint + + # Run super + super().__init__(termination_config=termination_config, reward_config=reward_config, include_obs=include_obs) + + def _create_termination_conditions(self): + # Initialize termination conditions dict and fill in with MaxCollision, Timeout, Falling, and PointGoal + terminations = dict() + terminations["max_collision"] = MaxCollision(max_collisions=self._termination_config["max_collisions"]) + terminations["timeout"] = Timeout(max_steps=self._termination_config["max_steps"]) + terminations["falling"] = Falling( + robot_idn=self._robot_idn, fall_height=self._termination_config["fall_height"] + ) + terminations["pointgoal"] = PointGoal( + robot_idn=self._robot_idn, + distance_tol=self._goal_tolerance, + distance_axes="xy", + ) + + return terminations + + def _create_reward_functions(self): + # Initialize reward functions dict and fill in with Potential, Collision, and PointGoal rewards + rewards = dict() + + rewards["potential"] = PotentialReward( + potential_fcn=self.get_potential, + r_potential=self._reward_config["r_potential"], + ) + rewards["collision"] = CollisionReward(r_collision=self._reward_config["r_collision"]) + rewards["pointgoal"] = PointGoalReward( + pointgoal=self._termination_conditions["pointgoal"], + r_pointgoal=self._reward_config["r_pointgoal"], + ) + + return rewards + + def _load(self, env): + # Initialize per-env state lists + self._initial_pos = [None] * env.num_envs + self._initial_quat = [None] * env.num_envs + self._goal_pos = [None] * env.num_envs + self._path_length = th.zeros(env.num_envs, dtype=th.float32) + self._current_robot_pos = [None] * env.num_envs + self._geodesic_dist = th.zeros(env.num_envs, dtype=th.float32) + + # Load visualization (only for first scene) + self._load_visualization_markers(env=env) + + # Auto-initialize all markers + og.sim.play() + self._reset_agent(env=env, env_indices=th.arange(env.num_envs)) + for scene in env.scenes: + scene.update_initial_file() + og.sim.stop() + + def _load_visualization_markers(self, env): + """ + Load visualization, such as initial and target position, shortest path, etc. + One set of markers is created per scene so multi-env runs each see their own goal/path. + + Args: + env (Environment): Active environment instance + """ + if self._visualize_goal: + self._initial_pos_markers = [] + self._goal_pos_markers = [] + for env_idx in range(env.num_envs): + initial_marker = PrimitiveObject( + relative_prim_path="/task_initial_pos_marker", + primitive_type="Cylinder", + name=f"task_initial_pos_marker_{env_idx}", + radius=self._goal_tolerance, + height=self._goal_height, + visual_only=True, + rgba=th.tensor([1, 0, 0, 0.3]), + ) + goal_marker = PrimitiveObject( + relative_prim_path="/task_goal_pos_marker", + primitive_type="Cylinder", + name=f"task_goal_pos_marker_{env_idx}", + radius=self._goal_tolerance, + height=self._goal_height, + visual_only=True, + rgba=th.tensor([0, 0, 1, 0.3]), + ) + env.scenes[env_idx].add_object(initial_marker) + env.scenes[env_idx].add_object(goal_marker) + self._initial_pos_markers.append(initial_marker) + self._goal_pos_markers.append(goal_marker) + + # Additionally generate waypoints along the path if we're building the map in the environment + if self._visualize_path: + self._waypoint_markers = [] + for env_idx in range(env.num_envs): + env_waypoints = [] + for i in range(self._n_vis_waypoints): + waypoint = PrimitiveObject( + relative_prim_path=f"/task_waypoint_marker{i}", + primitive_type="Cylinder", + name=f"task_waypoint_marker_{env_idx}_{i}", + radius=self._waypoint_width, + height=self._waypoint_height, + visual_only=True, + rgba=th.tensor([0, 1, 0, 0.3]), + ) + env.scenes[env_idx].add_object(waypoint) + env_waypoints.append(waypoint) + self._waypoint_markers.append(env_waypoints) + + def _sample_initial_pose_and_goal_pos(self, env, env_idx, max_trials=100): + """ + Potentially sample the robot initial pos / ori and target pos, based on whether we're using randomized + initial and goal states. If not randomzied, then this value will return the corresponding values inputted + during this task initialization. + + Args: + env (Environment): Environment instance + env_idx (int): Index of the environment + max_trials (int): Number of trials to attempt to sample valid poses and positions + + Returns: + 3-tuple: + - 3-array: (x,y,z) global sampled initial position + - 4-array: (x,y,z,w) global sampled initial orientation in quaternion form + - 3-array: (x,y,z) global sampled goal position + """ + scene = env.scenes[env_idx] + robot = scene.robots[self._robot_idn] + + # Possibly sample initial pos + if self._randomize_initial_pos: + _, initial_pos = scene.get_random_point(floor=self._floor, robot=robot) + else: + initial_pos = self._initial_pos_cfg.clone() + + # Possibly sample initial ori + quat_lo, quat_hi = 0, math.pi * 2 + initial_quat = ( + T.euler2quat(th.tensor([0, 0, (th.rand(1) * (quat_hi - quat_lo) + quat_lo).item()])) + if self._randomize_initial_quat + else self._initial_quat_cfg.clone() + ) + + # Possibly sample goal pos + if self._randomize_goal_pos: + dist, in_range_dist = 0.0, False + for _ in range(max_trials): + _, goal_pos = scene.get_random_point(floor=self._floor, reference_point=initial_pos, robot=robot) + _, dist = scene.get_shortest_path( + self._floor, initial_pos[:2], goal_pos[:2], entire_path=False, robot=robot + ) + # If a path range is specified, make sure distance is valid + if dist is not None and (self._path_range is None or self._path_range[0] < dist < self._path_range[1]): + in_range_dist = True + break + # Notify if we weren't able to get a valid start / end point sampled in the requested range + if not in_range_dist: + log.warning("Failed to sample initial and target positions within requested path range") + else: + goal_pos = self._goal_pos_cfg.clone() + + # Add additional logging info + log.info("Sampled initial pose: {}, {}".format(initial_pos, initial_quat)) + log.info("Sampled goal position: {}".format(goal_pos)) + return initial_pos, initial_quat, goal_pos + + def _get_geodesic_potential(self, env, env_idx): + """ + Get potential based on geodesic distance + + Args: + env (Environment): Environment instance + env_idx (int): Index of the environment + + Returns: + float: geodesic distance to the target position + """ + _, geodesic_dist = self.get_shortest_path_to_goal(env=env, env_idx=env_idx) + return geodesic_dist + + def _get_l2_potential(self, env, env_idx): + """ + Get potential based on L2 distance + + Args: + env (Environment): Environment instance + env_idx (int): Index of the environment + + Returns: + float: L2 distance to the target position + """ + robot = env.scenes[env_idx].robots[self._robot_idn] + return T.l2_distance(robot.states[Pose].get_value()[0][:2], self._goal_pos[env_idx][:2]) + + def get_potential(self, env, env_idx): + """ + Compute task-specific potential: distance to the goal + + Args: + env (Environment): Environment instance + env_idx (int): Index of the environment + + Returns: + float: Computed potential + """ + if self._reward_type == "l2": + potential = self._get_l2_potential(env, env_idx) + elif self._reward_type == "geodesic": + potential = self._get_geodesic_potential(env, env_idx) + # If no path is found, fall back to L2 potential + if potential is None: + potential = self._get_l2_potential(env, env_idx) + else: + raise ValueError(f"Invalid reward type! {self._reward_type}") + + return potential + + def _reset_agent(self, env, env_indices): + for env_idx in env_indices: + scene = env.scenes[env_idx] + robot = scene.robots[self._robot_idn] + # Reset agent + robot.reset() + + # We attempt to sample valid initial poses and goal positions + # TODO: There used to be a test for collision-free, but it was removed because it involved + # stepping the simulator and checking for collisions. We should consider alternatives. + initial_pos, initial_quat, goal_pos = self._sample_initial_pose_and_goal_pos(env, env_idx) + + # Land the robot. The sampled pose comes from scene.get_random_point() → trav_map.map_to_world, + # which returns coordinates in the scene's own local frame. With multi-scene envs, scene_N's + # scene_prim is offset from world origin, so we must mark the pose as scene-relative and let + # set_position_orientation convert to world — otherwise the holonomic base joints get set to + # reach a world pose well outside their reasonable range and the articulation diverges to NaN. + robot.set_position_orientation(position=initial_pos, orientation=initial_quat, frame="scene") + + # Store the sampled values internally + self._initial_pos[env_idx] = initial_pos + self._initial_quat[env_idx] = initial_quat + self._goal_pos[env_idx] = goal_pos + + # Update this env's start/goal visuals if requested + if self._visualize_goal: + self._initial_pos_markers[env_idx].set_position_orientation(position=self._initial_pos[env_idx]) + self._goal_pos_markers[env_idx].set_position_orientation(position=self._goal_pos[env_idx]) + + def _reset_variables(self, env, env_indices): + # Run super first + super()._reset_variables(env=env, env_indices=env_indices) + + # Reset internal variables + for env_idx in env_indices: + self._path_length[env_idx] = 0.0 + self._current_robot_pos[env_idx] = self._initial_pos[env_idx] + geodesic = self._get_geodesic_potential(env, env_idx) + self._geodesic_dist[env_idx] = geodesic if geodesic is not None else 0.0 + + def _step_termination(self, env, action, infos=None): + # Run super first + dones, infos = super()._step_termination(env=env, action=action, infos=infos) + + # Add additional info per env + for env_idx in range(self._num_envs): + infos[env_idx]["path_length"] = self._path_length[env_idx].item() + path_len = self._path_length[env_idx].item() + geo_dist = self._geodesic_dist[env_idx].item() + infos[env_idx]["spl"] = ( + float(infos[env_idx]["success"]) * min(1.0, geo_dist / path_len) + if dones[env_idx].item() and path_len != 0.0 + else 0.0 + ) + + return dones, infos + + def _global_pos_to_robot_frame(self, env, env_idx, pos): + """ + Convert a 3D point in global frame to agent's local frame + + Args: + env (TraversableEnv): Environment instance + env_idx (int): Index of the environment + pos (th.Tensor): global (x,y,z) position + + Returns: + th.Tensor: (x,y,z) position in self._robot_idn agent's local frame + """ + robot = env.scenes[env_idx].robots[self._robot_idn] + delta_pos_global = pos - robot.states[Pose].get_value()[0] + return T.quat2mat(robot.states[Pose].get_value()[1]).T @ delta_pos_global + + def _get_obs(self, env, env_idx): + # Get relative position of goal with respect to the current agent position + xy_pos_to_goal = self._global_pos_to_robot_frame(env, env_idx, self._goal_pos[env_idx])[:2] + if self._goal_in_polar: + xy_pos_to_goal = th.tensor(T.cartesian_to_polar(*xy_pos_to_goal)) + + # linear velocity and angular velocity + robot = env.scenes[env_idx].robots[self._robot_idn] + ori_t = T.quat2mat(robot.states[Pose].get_value()[1]).T + lin_vel = ori_t @ robot.get_linear_velocity() + ang_vel = ori_t @ robot.get_angular_velocity() + + # Compose observation dict + low_dim_obs = dict( + xy_pos_to_goal=xy_pos_to_goal, + robot_lin_vel=lin_vel, + robot_ang_vel=ang_vel, + ) + + # We have no non-low-dim obs, so return empty dict for those + return low_dim_obs, dict() + + def _load_non_low_dim_observation_space(self): + # No non-low dim observations so we return an empty dict + return dict() + + def get_goal_pos(self, env_idx): + """ + Returns: + 3-array: (x,y,z) global current goal position for the specified env + """ + return self._goal_pos[env_idx] + + def get_current_pos(self, env, env_idx): + """ + Returns: + 3-array: (x,y,z) global current position representing the robot + """ + return env.scenes[env_idx].robots[self._robot_idn].states[Pose].get_value()[0] + + def get_shortest_path_to_goal(self, env, env_idx, start_xy_pos=None, entire_path=False): + """ + Get the shortest path and geodesic distance from @start_pos to the target position + + Args: + env (TraversableEnv): Environment instance + env_idx (int): Index of the environment + start_xy_pos (None or 2-array): If specified, should be the global (x,y) start position from which + to calculate the shortest path to the goal position. If None (default), the robot's current xy position + will be used + entire_path (bool): Whether to return the entire shortest path + + Returns: + 2-tuple: + - list of 2-array: List of (x,y) waypoints representing the path # TODO: is this true? + - float: geodesic distance of the path to the goal position + """ + scene = env.scenes[env_idx] + robot = scene.robots[self._robot_idn] + start_xy_pos = robot.states[Pose].get_value()[0][:2] if start_xy_pos is None else start_xy_pos + return scene.get_shortest_path( + self._floor, start_xy_pos, self._goal_pos[env_idx][:2], entire_path=entire_path, robot=robot + ) + + def _step_visualization(self, env): + """ + Step visualization + + Args: + env (Environment): Environment instance + """ + if self._visualize_path: + for env_idx in range(self._num_envs): + shortest_path, _ = self.get_shortest_path_to_goal(env=env, env_idx=env_idx, entire_path=True) + floor_height = env.scenes[env_idx].get_floor_height(self._floor) + num_nodes = min(self._n_vis_waypoints, shortest_path.shape[0]) + for i in range(num_nodes): + self._waypoint_markers[env_idx][i].set_position_orientation( + position=th.tensor([shortest_path[i][0], shortest_path[i][1], floor_height]) + ) + for i in range(num_nodes, self._n_vis_waypoints): + self._waypoint_markers[env_idx][i].set_position_orientation(position=th.tensor([0.0, 0.0, 100.0])) + + def step(self, env, action): + # Run super method first + reward, done, info = super().step(env=env, action=action) + + # Step visualization + self._step_visualization(env=env) + + # Update other internal variables + for env_idx in range(self._num_envs): + robot = env.scenes[env_idx].robots[self._robot_idn] + new_robot_pos = robot.states[Pose].get_value()[0] + if self._current_robot_pos[env_idx] is not None: + self._path_length[env_idx] += T.l2_distance(self._current_robot_pos[env_idx][:2], new_robot_pos[:2]) + self._current_robot_pos[env_idx] = new_robot_pos + + return reward, done, info + + @classproperty + def valid_scene_types(cls): + # Must be a traversable scene + return {TraversableScene} + + @classproperty + def default_termination_config(cls): + return { + "max_collisions": 500, + "max_steps": 500, + "fall_height": 0.03, + } + + @classproperty + def default_reward_config(cls): + return { + "r_potential": 1.0, + "r_collision": 0.1, + "r_pointgoal": 10.0, + } diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/point_reaching_task.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/point_reaching_task.py new file mode 100644 index 0000000000000000000000000000000000000000..e946ef4aace3c054424a446452815b18097c0028 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/point_reaching_task.py @@ -0,0 +1,148 @@ +import torch as th + +import omnigibson.utils.transform_utils as T +from omnigibson.tasks.point_navigation_task import PointNavigationTask +from omnigibson.termination_conditions.point_goal import PointGoal + +# Valid point navigation reward types +POINT_NAVIGATION_REWARD_TYPES = {"l2", "geodesic"} + + +class PointReachingTask(PointNavigationTask): + """ + Point Reaching Task + The goal is to reach a random goal position with the robot's end effector + + Args: + robot_idn (int): Which robot that this task corresponds to + floor (int): Which floor to navigate on + initial_pos (None or 3-array): If specified, should be (x,y,z) global initial position to place the robot + at the start of each task episode. If None, a collision-free value will be randomly sampled + initial_quat (None or 3-array): If specified, should be (r,p,y) global euler orientation to place the robot + at the start of each task episode. If None, a value will be randomly sampled about the z-axis + goal_pos (None or 3-array): If specified, should be (x,y,z) global goal position to reach for the given task + episode. If None, a collision-free value will be randomly sampled + goal_tolerance (float): Distance between goal position and current position below which is considered a task + success + goal_in_polar (bool): Whether to represent the goal in polar coordinates or not when capturing task observations + path_range (None or 2-array): If specified, should be (min, max) values representing the range of valid + total path lengths that are valid when sampling initial / goal positions + height_range (None or 2-array): If specified, should be (min, max) values representing the range of valid + total heights that are valid when sampling goal positions + visualize_goal (bool): Whether to visualize the initial / goal locations + visualize_path (bool): Whether to visualize the path from initial to goal location, as represented by + discrete waypoints + goal_height (float): If visualizing, specifies the height of the visual goals (m) + waypoint_height (float): If visualizing, specifies the height of the visual waypoints (m) + waypoint_width (float): If visualizing, specifies the width of the visual waypoints (m) + n_vis_waypoints (int): If visualizing, specifies the number of waypoints to generate + termination_config (None or dict): Keyword-mapped configuration to use to generate termination conditions. This + should be specific to the task class. Default is None, which corresponds to a default config being usd. + Note that any keyword required by a specific task class but not specified in the config will automatically + be filled in with the default config. See cls.default_termination_config for default values used + reward_config (None or dict): Keyword-mapped configuration to use to generate reward functions. This should be + specific to the task class. Default is None, which corresponds to a default config being usd. Note that + any keyword required by a specific task class but not specified in the config will automatically be filled + in with the default config. See cls.default_reward_config for default values used + include_obs (bool): Whether to include observations or not for this task + """ + + def __init__( + self, + robot_idn=0, + floor=0, + initial_pos=None, + initial_quat=None, + goal_pos=None, + goal_tolerance=0.1, + goal_in_polar=False, + path_range=None, + height_range=None, + visualize_goal=False, + visualize_path=False, + goal_height=0.06, + waypoint_height=0.05, + waypoint_width=0.1, + n_vis_waypoints=10, + reward_config=None, + termination_config=None, + include_obs=True, + ): + # Store inputs + self._height_range = height_range + + # Run super + super().__init__( + robot_idn=robot_idn, + floor=floor, + initial_pos=initial_pos, + initial_quat=initial_quat, + goal_pos=goal_pos, + goal_tolerance=goal_tolerance, + goal_in_polar=goal_in_polar, + path_range=path_range, + visualize_goal=visualize_goal, + visualize_path=visualize_path, + goal_height=goal_height, + waypoint_height=waypoint_height, + waypoint_width=waypoint_width, + n_vis_waypoints=n_vis_waypoints, + reward_type="l2", # Must use l2 for reaching task + reward_config=reward_config, + termination_config=termination_config, + include_obs=include_obs, + ) + + def _create_termination_conditions(self): + # Run super first + terminations = super()._create_termination_conditions() + + # We replace the pointgoal condition with a new one, specifying xyz instead of only xy as the axes to measure + # distance to the goal + terminations["pointgoal"] = PointGoal( + robot_idn=self._robot_idn, + distance_tol=self._goal_tolerance, + distance_axes="xyz", + ) + + return terminations + + def _sample_initial_pose_and_goal_pos(self, env, env_idx, max_trials=100): + # Run super first + initial_pos, initial_ori, goal_pos = super()._sample_initial_pose_and_goal_pos( + env=env, env_idx=env_idx, max_trials=max_trials + ) + + # Sample goal position to be within requested height range if specified + if self._height_range is not None: + goal_pos[2] += th.rand(1) * (self._height_range[1] - self._height_range[0]) + self._height_range[0] + + return initial_pos, initial_ori, goal_pos + + def _get_l2_potential(self, env, env_idx): + # Distance calculated from robot EEF, not base! + robot = env.scenes[env_idx].robots[self._robot_idn] + return T.l2_distance(robot.get_eef_position(), self._goal_pos[env_idx]) + + def _get_obs(self, env, env_idx): + # Get obs from super + low_dim_obs, obs = super()._get_obs(env=env, env_idx=env_idx) + + # Remove xy-pos and replace with full xyz relative distance between current and goal pos + low_dim_obs.pop("xy_pos_to_goal") + low_dim_obs["eef_to_goal"] = self._global_pos_to_robot_frame( + env=env, env_idx=env_idx, pos=self._goal_pos[env_idx] + ) + + # Add local eef position as well + robot = env.scenes[env_idx].robots[self._robot_idn] + low_dim_obs["eef_local_pos"] = self._global_pos_to_robot_frame( + env=env, env_idx=env_idx, pos=robot.get_eef_position() + ) + + return low_dim_obs, obs + + def get_current_pos(self, env, env_idx): + # Current position is the robot's EEF, not base! + robot = env.scenes[env_idx].robots[self._robot_idn] + return robot.get_eef_position() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/task_base.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/task_base.py new file mode 100644 index 0000000000000000000000000000000000000000..cdd35f4c632b10fdc1dff19163f380c86ffbb397 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/tasks/task_base.py @@ -0,0 +1,480 @@ +from abc import ABCMeta, abstractmethod +from copy import deepcopy + +import torch as th + +from omnigibson.utils.gym_utils import GymObservable +from omnigibson.utils.numpy_utils import NumpyTypes +from omnigibson.utils.python_utils import Registerable, classproperty + +REGISTERED_TASKS = dict() + + +class BaseTask(GymObservable, Registerable, metaclass=ABCMeta): + """ + Base Task class. + Task-specific reset_scene, reset_agent, step methods are implemented in subclasses + + Args: + termination_config (None or dict): Keyword-mapped configuration to use to generate termination conditions. This + should be specific to the task class. Default is None, which corresponds to a default config being usd. + Note that any keyword required by a specific task class but not specified in the config will automatically + be filled in with the default config. See cls.default_termination_config for default values used + reward_config (None or dict): Keyword-mapped configuration to use to generate reward functions. This should be + specific to the task class. Default is None, which corresponds to a default config being usd. Note that + any keyword required by a specific task class but not specified in the config will automatically be filled + in with the default config. See cls.default_reward_config for default values used + include_obs (bool): Whether to include observations or not for this task + """ + + def __init__(self, termination_config=None, reward_config=None, include_obs=True): + # Make sure configs are dictionaries + termination_config = dict() if termination_config is None else termination_config + reward_config = dict() if reward_config is None else reward_config + + # Sanity check termination and reward conditions -- any keys found in the inputted config but NOT + # found in the default config should raise an error + unknown_termination_keys = set(termination_config.keys()) - set(self.default_termination_config.keys()) + assert ( + len(unknown_termination_keys) == 0 + ), f"Got unknown termination config keys inputted: {unknown_termination_keys}" + unknown_reward_keys = set(reward_config.keys()) - set(self.default_reward_config.keys()) + assert len(unknown_reward_keys) == 0, f"Got unknown reward config keys inputted: {unknown_reward_keys}" + + # Combine with defaults and store internally + self._termination_config = self.default_termination_config + self._termination_config.update(termination_config) + self._reward_config = self.default_reward_config + self._reward_config.update(reward_config) + + # Generate reward and termination functions + self._termination_conditions = self._create_termination_conditions() + self._reward_functions = self._create_reward_functions() + + # Store other internal vars that will be populated at runtime + self._loaded = False + self._num_envs = None + self._reward = None + self._done = None + self._success = None + self._info = None + self._low_dim_obs_dim = None + self._low_dim_obs_keys = None + self._include_obs = include_obs + + # Run super init + super().__init__() + + @abstractmethod + def _load(self, env): + """ + Load this task. Should be implemented by subclass. Can include functionality, e.g.: loading dynamic objects + into the environment + """ + raise NotImplementedError() + + @abstractmethod + def _load_non_low_dim_observation_space(self): + """ + Loads any non-low dim observation spaces for this task. + + Returns: + dict: Keyword-mapped observation space for this object mapping non low dim task observation name to + observation space + """ + raise NotImplementedError() + + @classmethod + def verify_scene_and_task_config(cls, scene_cfg, task_cfg): + """ + Runs any necessary sanity checks on the scene and task configs passed; and possibly modifies them in-place + + Args: + scene_cfg (dict): Scene configuration + task_cfg (dict): Task configuration + """ + # Default is no-op + pass + + def _load_observation_space(self): + # Create the non low dim obs space + obs_space = self._load_non_low_dim_observation_space() + + # Create the low dim obs space and add to the main obs space dict -- make sure we're flattening low dim obs + if self._low_dim_obs_dim > 0: + obs_space["low_dim"] = self._build_obs_box_space( + shape=(self._low_dim_obs_dim,), low=-float("inf"), high=float("inf"), dtype=NumpyTypes.FLOAT32 + ) + + return obs_space + + def load(self, env): + """ + Load this task + """ + self._num_envs = env.num_envs + + # Make sure all scenes are of the correct type! + for scene in env.scenes: + assert any([issubclass(scene.__class__, valid_cls) for valid_cls in self.valid_scene_types]), ( + f"Got incompatible scene type {scene.__class__.__name__} for task {self.__class__.__name__}! " + f"Scene class must be a subclass of at least one of: " + f"{[cls_type.__name__ for cls_type in self.valid_scene_types]}" + ) + + # Run internal method + self._load(env=env) + + # We're now initialized + self._loaded = True + + def post_play_load(self, env): + """ + Complete any loading tasks that require the simulator to be playing + + Args: + env (Environment): environment instance + """ + # Reset all scenes to their initial stored configuration + for scene in env.scenes: + scene.reset(hard=False) + + # Compute the low dimensional observation dimension. Obs keys and shape are task-defined + # and identical across envs, so env 0 is canonical. + obs = self.get_obs(env=env, env_idx=0, flatten_low_dim=False) + if "low_dim" in obs: + self._low_dim_obs_keys = list(obs["low_dim"].keys()) + self._low_dim_obs_dim = len(self._flatten_low_dim_obs(obs=obs["low_dim"])) + else: + self._low_dim_obs_keys = [] + self._low_dim_obs_dim = 0 + + @property + def low_dim_obs_keys(self): + """ + Returns: + list of str: List of low-dimensional observation keys for this task + """ + # Make sure we're loaded + assert self._loaded, "Task must be loaded using load() before accessing low_dim_obs_keys!" + return self._low_dim_obs_keys + + @abstractmethod + def _create_termination_conditions(self): + """ + Creates the termination functions in the environment + + Returns: + dict of BaseTerminationCondition: Termination functions created for this task + """ + raise NotImplementedError() + + @abstractmethod + def _create_reward_functions(self): + """ + Creates the reward functions in the environment + + Returns: + dict of BaseRewardFunction: Reward functions created for this task + """ + raise NotImplementedError() + + def _reset_scene(self, env, env_indices): + """ + Task-specific scene reset. Default is resetting specified scenes. + + Args: + env (Environment): environment instance + env_indices (th.Tensor): Indices of environments to reset + """ + for idx in env_indices: + env.scenes[idx].reset() + + def _reset_agent(self, env, env_indices): + """ + Task-specific agent reset + + Args: + env (Environment): environment instance + env_indices (th.Tensor): Indices of environments to reset + """ + # Default is no-op + pass + + def _reset_variables(self, env, env_indices): + """ + Task-specific internal variable reset + + Args: + env (Environment): environment instance + env_indices (th.Tensor): Indices of environments to reset + """ + if self._reward is None: + # First-time init + self._reward = th.zeros(self._num_envs, dtype=th.float32) + self._done = th.zeros(self._num_envs, dtype=th.bool) + self._success = th.zeros(self._num_envs, dtype=th.bool) + self._reward[env_indices] = 0.0 + self._done[env_indices] = False + self._success[env_indices] = False + self._info = None # info is rebuilt each step + + def reset(self, env, env_indices=None): + """ + Resets this task in the environment + + Args: + env (Environment): environment instance to reset + env_indices (None or th.Tensor): Indices of environments to reset. If None, resets all. + """ + if env_indices is None: + env_indices = th.arange(self._num_envs) + + # Reset the scene, agent, and variables + self._reset_scene(env, env_indices) + self._reset_agent(env, env_indices) + self._reset_variables(env, env_indices) + + # Also reset all termination conditions and reward functions + for termination_condition in self._termination_conditions.values(): + termination_condition.reset(self, env, env_indices) + for reward_function in self._reward_functions.values(): + reward_function.reset(self, env, env_indices) + + def _step_termination(self, env, action, infos=None): + """ + Step and aggregate termination conditions + + Args: + env (Environment): Environment instance + action (n-array): 1D flattened array of actions executed by all agents in the environment + infos (None or list[dict]): If provided, a list of per-env info dicts to accumulate into. + If None, fresh info dicts are created. + + Returns: + 2-tuple: + - th.Tensor: (num_envs,) bool tensor of dones + - list[dict]: per-env info dicts + """ + # Get all dones and successes from individual termination conditions + if infos is not None: + for i in range(self._num_envs): + if "termination_conditions" not in infos[i]: + infos[i]["termination_conditions"] = dict() + else: + infos = [{"termination_conditions": dict()} for _ in range(self._num_envs)] + dones = th.zeros(self._num_envs, dtype=th.bool) + successes = th.zeros(self._num_envs, dtype=th.bool) + + for name, termination_condition in self._termination_conditions.items(): + d, s = termination_condition.step(self, env, action) + dones = dones | d + successes = successes | s + for env_idx in range(self._num_envs): + infos[env_idx]["termination_conditions"][name] = { + "done": d[env_idx].item(), + "success": s[env_idx].item(), + } + + for env_idx in range(self._num_envs): + infos[env_idx]["success"] = successes[env_idx].item() + + return dones, infos + + def _step_reward(self, env, action, infos=None): + """ + Step and aggregate reward functions + + Args: + env (Environment): Environment instance + action (n-array): 1D flattened array of actions executed by all agents in the environment + infos (None or list[dict]): If provided, a list of per-env info dicts to accumulate into. + If None, fresh info dicts are created. + + Returns: + 2-tuple: + - th.Tensor: (num_envs,) float tensor of total rewards + - list[dict]: per-env info dicts + """ + # Aggregate rewards over all reward functions + infos = infos if infos is not None else [dict() for _ in range(self._num_envs)] + total_rewards = th.zeros(self._num_envs, dtype=th.float32) + + for reward_name, reward_function in self._reward_functions.items(): + rewards, reward_infos = reward_function.step(self, env, action) + total_rewards += rewards + for env_idx in range(self._num_envs): + infos[env_idx][reward_name] = reward_infos[env_idx] + if "reward_breakdown" not in infos[env_idx]: + infos[env_idx]["reward_breakdown"] = dict() + infos[env_idx]["reward_breakdown"][reward_name] = rewards[env_idx].item() + + return total_rewards, infos + + @abstractmethod + def _get_obs(self, env, env_idx): + """ + Get task-specific observation for a specific environment + + Args: + env (Environment): Environment instance + env_idx (int): Index of the environment + + Returns: + 2-tuple: + - dict: Keyword-mapped low dimensional observations from this task + - dict: All other keyword-mapped observations from this task + """ + raise NotImplementedError() + + def _flatten_low_dim_obs(self, obs): + """ + Flattens dictionary containing low-dimensional observations @obs and converts it from a dictionary into a + 1D numpy array + + Args: + obs (dict): Low-dim observation dictionary where each value is a 1D array + + Returns: + n-array: 1D-numpy array of flattened low-dim observations + """ + # By default, we simply concatenate all values in our obs dict + return th.cat([ob for ob in obs.values()]) if len(obs.values()) > 0 else th.empty(0) + + def get_obs(self, env, env_idx=None, flatten_low_dim=True): + """ + Get task observations. + + Args: + env (Environment): environment instance + env_idx (int or None): If specified, return obs for one env. If None, return list for all envs. + flatten_low_dim (bool): Whether to flatten low-dimensional observations + """ + if not self._include_obs: + return dict() if env_idx is not None else [dict()] * self._num_envs + + if env_idx is not None: + low_dim_obs, obs = self._get_obs(env=env, env_idx=env_idx) + if low_dim_obs: + obs["low_dim"] = self._flatten_low_dim_obs(obs=low_dim_obs) if flatten_low_dim else low_dim_obs + return obs + else: + return [self.get_obs(env, env_idx=i, flatten_low_dim=flatten_low_dim) for i in range(self._num_envs)] + + def step(self, env, action): + """ + Perform task-specific step for every timestep + + Args: + env (Environment): Environment instance + action (n-array): 1D flattened array of actions executed by all agents in the environment + + Returns: + 3-tuple: + - th.Tensor: (num_envs,) reward tensor + - th.Tensor: (num_envs,) done bool tensor + - list[dict]: per-env info dicts + """ + # Make sure we're initialized + assert self._loaded, "Task must be loaded using load() before calling step()!" + + # We calculate termination conditions first and then rewards + # (since some rewards can rely on termination conditions to update) + dones, done_infos = self._step_termination(env=env, action=action) + rewards, reward_infos = self._step_reward(env=env, action=action) + + # Update the internal state of this task + self._reward = rewards + self._done = dones + self._success = th.tensor([di["success"] for di in done_infos], dtype=th.bool) + self._info = [{"reward": reward_infos[i], "done": done_infos[i]} for i in range(self._num_envs)] + + return self._reward, self._done, deepcopy(self._info) + + @property + def name(self): + """ + Returns: + str: Name of this task. Defaults to class name + """ + return self.__class__.__name__ + + @property + def reward(self): + """ + Returns: + th.Tensor: (num_envs,) current reward tensor for this task + """ + assert self._reward is not None, "At least one step() must occur before reward can be calculated!" + return self._reward + + @property + def done(self): + """ + Returns: + th.Tensor: (num_envs,) bool tensor of whether each env is done + """ + assert self._done is not None, "At least one step() must occur before done can be calculated!" + return self._done + + @property + def success(self): + """ + Returns: + th.Tensor: (num_envs,) bool tensor of whether each env has succeeded + """ + assert self._success is not None, "At least one step() must occur before success can be calculated!" + return self._success + + @property + def info(self): + """ + Returns: + list[dict]: Per-env nested dictionary of information for this task, including reward- and done-specific information + """ + assert self._info is not None, "At least one step() must occur before info can be calculated!" + return self._info + + @classproperty + def valid_scene_types(cls): + """ + Returns: + set of Scene: Scene type(s) that are valid (i.e.: compatible) with this specific task. This will be + used to sanity check the task + scene combination at runtime + """ + raise NotImplementedError() + + @classproperty + def default_reward_config(cls): + """ + Returns: + dict: Default reward configuration for this class. Should include any kwargs necessary for + any of the reward classes generated in self._create_rewards(). Note: this default config + should be fully verbose -- any keys inputted in the constructor but NOT found in this default config + will raise an error! + """ + raise NotImplementedError() + + @classproperty + def default_termination_config(cls): + """ + Returns: + dict: Default termination configuration for this class. Should include any kwargs necessary for + any of the termination classes generated in self._create_terminations(). Note: this default config + should be fully verbose -- any keys inputted in the constructor but NOT found in this default config + will raise an error! + """ + raise NotImplementedError() + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("BaseTask") + return classes + + @classproperty + def _cls_registry(cls): + # Global registry + global REGISTERED_TASKS + return REGISTERED_TASKS diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0cd567f97018d2d90dca18dc216330b41d717aaf --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/__init__.py @@ -0,0 +1,27 @@ +from omnigibson.termination_conditions.falling import Falling +from omnigibson.termination_conditions.grasp_goal import GraspGoal +from omnigibson.termination_conditions.max_collision import MaxCollision +from omnigibson.termination_conditions.point_goal import PointGoal +from omnigibson.termination_conditions.predicate_goal import PredicateGoal +from omnigibson.termination_conditions.reaching_goal import ReachingGoal +from omnigibson.termination_conditions.termination_condition_base import ( + REGISTERED_FAILURE_CONDITIONS, + REGISTERED_SUCCESS_CONDITIONS, + REGISTERED_TERMINATION_CONDITIONS, + BaseTerminationCondition, +) +from omnigibson.termination_conditions.timeout import Timeout + +__all__ = [ + "BaseTerminationCondition", + "Falling", + "GraspGoal", + "MaxCollision", + "PointGoal", + "PredicateGoal", + "ReachingGoal", + "REGISTERED_FAILURE_CONDITIONS", + "REGISTERED_SUCCESS_CONDITIONS", + "REGISTERED_TERMINATION_CONDITIONS", + "Timeout", +] diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/falling.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/falling.py new file mode 100644 index 0000000000000000000000000000000000000000..7f3f0188b77eaf94d6eac6388b07c5e1429aa5f6 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/falling.py @@ -0,0 +1,48 @@ +import torch as th + +import omnigibson.utils.transform_utils as T +from omnigibson.termination_conditions.termination_condition_base import FailureCondition + + +class Falling(FailureCondition): + """ + Falling (failure condition) used for any navigation-type tasks + Episode terminates if the robot falls out of the world (i.e.: falls below the floor height by at least + @fall_height + + Args: + robot_idn (int): robot identifier to evaluate condition with. Default is 0, corresponding to the first + robot added to the scene + fall_height (float): distance (m) > 0 below the scene's floor height under which the the robot is considered + to be falling out of the world + topple (bool): whether to also consider the robot to be falling if it is toppling over (i.e.: if it is + no longer upright + """ + + def __init__(self, robot_idn=0, fall_height=0.03, topple=True, tilt_tolerance=0.75): + # Store internal vars + self._robot_idn = robot_idn + self._fall_height = fall_height + self._topple = topple + self._tilt_tolerance = tilt_tolerance + + # Run super init + super().__init__() + + def _step(self, task, env, action): + results = th.zeros(env.num_envs, dtype=th.bool) + for env_idx in range(env.num_envs): + robot = env.scenes[env_idx].robots[self._robot_idn] + pos, quat = robot.get_position_orientation() + robot_z = pos[2] + floor_height = env.scenes[env_idx].get_floor_height() + # Terminate if the specified robot is falling out of the scene + fell = robot_z < (floor_height - self._fall_height) + + # Terminate if the robot has toppled over + if not fell and self._topple: + robot_up = T.quat_apply(quat, th.tensor([0, 0, 1], dtype=th.float32)) + fell = robot_up[2] < self._tilt_tolerance + + results[env_idx] = fell + return results diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/grasp_goal.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/grasp_goal.py new file mode 100644 index 0000000000000000000000000000000000000000..522e3b35331cdbe2bed1a7b2cfc0f0c8eceebab9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/grasp_goal.py @@ -0,0 +1,28 @@ +import torch as th + +from omnigibson.termination_conditions.termination_condition_base import SuccessCondition + + +class GraspGoal(SuccessCondition): + """ + GraspGoal (success condition) + """ + + def __init__(self, obj_name): + self.obj_name = obj_name + self._objs = None + + # Run super init + super().__init__() + + def _step(self, task, env, action): + if self._objs is None: + self._objs = [env.scenes[i].object_registry("name", self.obj_name) for i in range(env.num_envs)] + + results = th.zeros(env.num_envs, dtype=th.bool) + for env_idx in range(env.num_envs): + obj = self._objs[env_idx] + robot = env.scenes[env_idx].robots[0] + obj_in_hand = robot._ag_obj_in_hand[robot.default_arm] + results[env_idx] = obj_in_hand == obj + return results