file_path
stringlengths 20
207
| content
stringlengths 5
3.85M
| size
int64 5
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
fnuabhimanyu8713/orbit/docs/source/setup/installation.rst | Installation Guide
===================
.. image:: https://img.shields.io/badge/IsaacSim-2023.1.1-silver.svg
:target: https://developer.nvidia.com/isaac-sim
:alt: IsaacSim 2023.1.1
.. image:: https://img.shields.io/badge/python-3.10-blue.svg
:target: https://www.python.org/downloads/release/python-31013/
:alt: Python 3.10
.. image:: https://img.shields.io/badge/platform-linux--64-orange.svg
:target: https://releases.ubuntu.com/20.04/
:alt: Ubuntu 20.04
Installing Isaac Sim
--------------------
.. caution::
We have dropped support for Isaac Sim versions 2023.1.0 and below. We recommend using the latest
Isaac Sim 2023.1.1 release.
For more information, please refer to the
`Isaac Sim release notes <https://docs.omniverse.nvidia.com/isaacsim/latest/release_notes.html>`__.
Downloading pre-built binaries
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please follow the Isaac Sim
`documentation <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_workstation.html>`__
to install the latest Isaac Sim release.
To check the minimum system requirements,refer to the documentation
`here <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/requirements.html>`__.
.. note::
We have tested Orbit with Isaac Sim 2023.1.1 release on Ubuntu
20.04LTS with NVIDIA driver 525.147.
Configuring the environment variables
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Isaac Sim is shipped with its own Python interpreter which bundles in
the extensions released with it. To simplify the setup, we recommend
using the same Python interpreter. Alternately, it is possible to setup
a virtual environment following the instructions
`here <https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_python.html>`__.
Please locate the `Python executable in Isaac
Sim <https://docs.omniverse.nvidia.com/isaacsim/latest/manual_standalone_python.html#isaac-sim-python-environment>`__
by navigating to Isaac Sim root folder. In the remaining of the
documentation, we will refer to its path as ``ISAACSIM_PYTHON_EXE``.
.. note::
On Linux systems, by default, this should be the executable ``python.sh`` in the directory
``${HOME}/.local/share/ov/pkg/isaac_sim-*``, with ``*`` corresponding to the Isaac Sim version.
To avoid the overhead of finding and locating the Isaac Sim installation
directory every time, we recommend exporting the following environment
variables to your terminal for the remaining of the installation instructions:
.. code:: bash
# Isaac Sim root directory
export ISAACSIM_PATH="${HOME}/.local/share/ov/pkg/isaac_sim-2023.1.0-hotfix.1"
# Isaac Sim python executable
export ISAACSIM_PYTHON_EXE="${ISAACSIM_PATH}/python.sh"
For more information on common paths, please check the Isaac Sim
`documentation <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_faq.html#common-path-locations>`__.
Running the simulator
~~~~~~~~~~~~~~~~~~~~~
Once Isaac Sim is installed successfully, make sure that the simulator runs on your
system. For this, we encourage the user to try some of the introductory
tutorials on their `website <https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/index.html>`__.
For completeness, we specify the commands here to check that everything is configured correctly.
On a new terminal (**Ctrl+Alt+T**), run the following:
- Check that the simulator runs as expected:
.. code:: bash
# note: you can pass the argument "--help" to see all arguments possible.
${ISAACSIM_PATH}/isaac-sim.sh
- Check that the simulator runs from a standalone python script:
.. code:: bash
# checks that python path is set correctly
${ISAACSIM_PYTHON_EXE} -c "print('Isaac Sim configuration is now complete.')"
# checks that Isaac Sim can be launched from python
${ISAACSIM_PYTHON_EXE} ${ISAACSIM_PATH}/standalone_examples/api/omni.isaac.core/add_cubes.py
.. attention::
If you have been using a previous version of Isaac Sim, you
need to run the following command for the *first* time after
installation to remove all the old user data and cached variables:
.. code:: bash
${ISAACSIM_PATH}/isaac-sim.sh --reset-user
If the simulator does not run or crashes while following the above
instructions, it means that something is incorrectly configured. To
debug and troubleshoot, please check Isaac Sim
`documentation <https://docs.omniverse.nvidia.com/dev-guide/latest/linux-troubleshooting.html>`__
and the
`forums <https://docs.omniverse.nvidia.com/isaacsim/latest/isaac_sim_forums.html>`__.
Installing Orbit
----------------
Organizing the workspace
~~~~~~~~~~~~~~~~~~~~~~~~
.. note::
We recommend making a `fork <https://github.com/NVIDIA-Omniverse/Orbit/fork>`_ of the ``orbit`` repository to contribute
to the project. This is not mandatory to use the framework. If you
make a fork, please replace ``NVIDIA-Omniverse`` with your username
in the following instructions.
If you are not familiar with git, we recommend following the `git
tutorial <https://git-scm.com/book/en/v2/Getting-Started-Git-Basics>`__.
- Clone the ``orbit`` repository into your workspace:
.. code:: bash
# Option 1: With SSH
git clone [email protected]:NVIDIA-Omniverse/orbit.git
# Option 2: With HTTPS
git clone https://github.com/NVIDIA-Omniverse/orbit.git
- Set up a symbolic link between the installed Isaac Sim root folder
and ``_isaac_sim`` in the ``orbit``` directory. This makes it convenient
to index the python modules and look for extensions shipped with
Isaac Sim.
.. code:: bash
# enter the cloned repository
cd orbit
# create a symbolic link
ln -s ${ISAACSIM_PATH} _isaac_sim
We provide a helper executable `orbit.sh <https://github.com/NVIDIA-Omniverse/Orbit/blob/main/orbit.sh>`_ that provides
utilities to manage extensions:
.. code:: text
./orbit.sh --help
usage: orbit.sh [-h] [-i] [-e] [-f] [-p] [-s] [-t] [-o] [-v] [-d] [-c] -- Utility to manage Orbit.
optional arguments:
-h, --help Display the help content.
-i, --install Install the extensions inside Orbit.
-e, --extra [LIB] Install learning frameworks (rl_games, rsl_rl, sb3) as extra dependencies. Default is 'all'.
-f, --format Run pre-commit to format the code and check lints.
-p, --python Run the python executable provided by Isaac Sim or virtual environment (if active).
-s, --sim Run the simulator executable (isaac-sim.sh) provided by Isaac Sim.
-t, --test Run all python unittest tests.
-o, --docker Run the docker container helper script (docker/container.sh).
-v, --vscode Generate the VSCode settings file from template.
-d, --docs Build the documentation from source using sphinx.
-c, --conda [NAME] Create the conda environment for Orbit. Default name is 'orbit'.
Setting up the environment
~~~~~~~~~~~~~~~~~~~~~~~~~~
.. attention::
This step is optional. If you are using the bundled python with Isaac Sim, you can skip this step.
The executable ``orbit.sh`` automatically fetches the python bundled with Isaac
Sim, using ``./orbit.sh -p`` command (unless inside a virtual environment). This executable
behaves like a python executable, and can be used to run any python script or
module with the simulator. For more information, please refer to the
`documentation <https://docs.omniverse.nvidia.com/isaacsim/latest/manual_standalone_python.html#isaac-sim-python-environment>`__.
Although using a virtual environment is optional, we recommend using ``conda``. To install
``conda``, please follow the instructions `here <https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html>`__.
In case you want to use ``conda`` to create a virtual environment, you can
use the following command:
.. code:: bash
# Option 1: Default name for conda environment is 'orbit'
./orbit.sh --conda # or "./orbit.sh -c"
# Option 2: Custom name for conda environment
./orbit.sh --conda my_env # or "./orbit.sh -c my_env"
If you are using ``conda`` to create a virtual environment, make sure to
activate the environment before running any scripts. For example:
.. code:: bash
conda activate orbit # or "conda activate my_env"
Once you are in the virtual environment, you do not need to use ``./orbit.sh -p``
to run python scripts. You can use the default python executable in your environment
by running ``python`` or ``python3``. However, for the rest of the documentation,
we will assume that you are using ``./orbit.sh -p`` to run python scripts. This command
is equivalent to running ``python`` or ``python3`` in your virtual environment.
Building extensions
~~~~~~~~~~~~~~~~~~~
To build all the extensions, run the following commands:
- Install dependencies using ``apt`` (on Ubuntu):
.. code:: bash
sudo apt install cmake build-essential
- Run the install command that iterates over all the extensions in
``source/extensions`` directory and installs them using pip
(with ``--editable`` flag):
.. code:: bash
./orbit.sh --install # or "./orbit.sh -i"
- For installing all other dependencies (such as learning
frameworks), execute:
.. code:: bash
# Option 1: Install all dependencies
./orbit.sh --extra # or "./orbit.sh -e"
# Option 2: Install only a subset of dependencies
# note: valid options are 'rl_games', 'rsl_rl', 'sb3', 'robomimic', 'all'
./orbit.sh --extra rsl_rl # or "./orbit.sh -e rsl_r"
Verifying the installation
~~~~~~~~~~~~~~~~~~~~~~~~~~
To verify that the installation was successful, run the following command from the
top of the repository:
.. code:: bash
# Option 1: Using the orbit.sh executable
# note: this works for both the bundled python and the virtual environment
./orbit.sh -p source/standalone/tutorials/00_sim/create_empty.py
# Option 2: Using python in your virtual environment
python source/standalone/tutorials/00_sim/create_empty.py
The above command should launch the simulator and display a window with a black
ground plane. You can exit the script by pressing ``Ctrl+C`` on your terminal or
by pressing the ``STOP`` button on the simulator window.
If you see this, then the installation was successful! |:tada:|
| 10,390 | reStructuredText | 37.917603 | 130 | 0.706737 |
fnuabhimanyu8713/orbit/docs/source/setup/sample.rst | Running Existing Scripts
========================
Showroom
--------
The main core interface extension in Orbit ``omni.isaac.orbit`` provides
the main modules for actuators, objects, robots and sensors. We provide
a list of demo scripts and tutorials. These showcase how to use the provided
interfaces within a code in a minimal way.
A few quick showroom scripts to run and checkout:
- Spawn different quadrupeds and make robots stand using position commands:
.. code:: bash
./orbit.sh -p source/standalone/demos/quadrupeds.py
- Spawn different arms and apply random joint position commands:
.. code:: bash
./orbit.sh -p source/standalone/demos/arms.py
- Spawn different hands and command them to open and close:
.. code:: bash
./orbit.sh -p source/standalone/demos/hands.py
- Spawn procedurally generated terrains with different configurations:
.. code:: bash
./orbit.sh -p source/standalone/demos/procedural_terrain.py
- Spawn multiple markers that are useful for visualizations:
.. code:: bash
./orbit.sh -p source/standalone/demos/markers.py
Workflows
---------
With Orbit, we also provide a suite of benchmark environments included
in the ``omni.isaac.orbit_tasks`` extension. We use the OpenAI Gym registry
to register these environments. For each environment, we provide a default
configuration file that defines the scene, observations, rewards and action spaces.
The list of environments available registered with OpenAI Gym can be found by running:
.. code:: bash
./orbit.sh -p source/standalone/environments/list_envs.py
Basic agents
~~~~~~~~~~~~
These include basic agents that output zero or random agents. They are
useful to ensure that the environments are configured correctly.
- Zero-action agent on the Cart-pole example
.. code:: bash
./orbit.sh -p source/standalone/environments/zero_agent.py --task Isaac-Cartpole-v0 --num_envs 32
- Random-action agent on the Cart-pole example:
.. code:: bash
./orbit.sh -p source/standalone/environments/random_agent.py --task Isaac-Cartpole-v0 --num_envs 32
State machine
~~~~~~~~~~~~~
We include examples on hand-crafted state machines for the environments. These
help in understanding the environment and how to use the provided interfaces.
The state machines are written in `warp <https://github.com/NVIDIA/warp>`__ which
allows efficient execution for large number of environments using CUDA kernels.
.. code:: bash
./orbit.sh -p source/standalone/environments/state_machine/lift_cube_sm.py --num_envs 32
Teleoperation
~~~~~~~~~~~~~
We provide interfaces for providing commands in SE(2) and SE(3) space
for robot control. In case of SE(2) teleoperation, the returned command
is the linear x-y velocity and yaw rate, while in SE(3), the returned
command is a 6-D vector representing the change in pose.
To play inverse kinematics (IK) control with a keyboard device:
.. code:: bash
./orbit.sh -p source/standalone/environments/teleoperation/teleop_se3_agent.py --task Isaac-Lift-Cube-Franka-IK-Rel-v0 --num_envs 1 --device keyboard
The script prints the teleoperation events configured. For keyboard,
these are as follows:
.. code:: text
Keyboard Controller for SE(3): Se3Keyboard
Reset all commands: L
Toggle gripper (open/close): K
Move arm along x-axis: W/S
Move arm along y-axis: A/D
Move arm along z-axis: Q/E
Rotate arm along x-axis: Z/X
Rotate arm along y-axis: T/G
Rotate arm along z-axis: C/V
Imitation Learning
~~~~~~~~~~~~~~~~~~
Using the teleoperation devices, it is also possible to collect data for
learning from demonstrations (LfD). For this, we support the learning
framework `Robomimic <https://robomimic.github.io/>`__ and allow saving
data in
`HDF5 <https://robomimic.github.io/docs/tutorials/dataset_contents.html#viewing-hdf5-dataset-structure>`__
format.
1. Collect demonstrations with teleoperation for the environment
``Isaac-Lift-Cube-Franka-IK-Rel-v0``:
.. code:: bash
# step a: collect data with keyboard
./orbit.sh -p source/standalone/workflows/robomimic/collect_demonstrations.py --task Isaac-Lift-Cube-Franka-IK-Rel-v0 --num_envs 1 --num_demos 10 --device keyboard
# step b: inspect the collected dataset
./orbit.sh -p source/standalone/workflows/robomimic/tools/inspect_demonstrations.py logs/robomimic/Isaac-Lift-Cube-Franka-IK-Rel-v0/hdf_dataset.hdf5
2. Split the dataset into train and validation set:
.. code:: bash
# install python module (for robomimic)
./orbit.sh -e robomimic
# split data
./orbit.sh -p source/standalone//workflows/robomimic/tools/split_train_val.py logs/robomimic/Isaac-Lift-Cube-Franka-IK-Rel-v0/hdf_dataset.hdf5 --ratio 0.2
3. Train a BC agent for ``Isaac-Lift-Cube-Franka-IK-Rel-v0`` with
`Robomimic <https://robomimic.github.io/>`__:
.. code:: bash
./orbit.sh -p source/standalone/workflows/robomimic/train.py --task Isaac-Lift-Cube-Franka-IK-Rel-v0 --algo bc --dataset logs/robomimic/Isaac-Lift-Cube-Franka-IK-Rel-v0/hdf_dataset.hdf5
4. Play the learned model to visualize results:
.. code:: bash
./orbit.sh -p source/standalone//workflows/robomimic/play.py --task Isaac-Lift-Cube-Franka-IK-Rel-v0 --checkpoint /PATH/TO/model.pth
Reinforcement Learning
~~~~~~~~~~~~~~~~~~~~~~
We provide wrappers to different reinforcement libraries. These wrappers convert the data
from the environments into the respective libraries function argument and return types.
- Training an agent with
`Stable-Baselines3 <https://stable-baselines3.readthedocs.io/en/master/index.html>`__
on ``Isaac-Cartpole-v0``:
.. code:: bash
# install python module (for stable-baselines3)
./orbit.sh -e sb3
# run script for training
# note: we enable cpu flag since SB3 doesn't optimize for GPU anyway
./orbit.sh -p source/standalone/workflows/sb3/train.py --task Isaac-Cartpole-v0 --headless --cpu
# run script for playing with 32 environments
./orbit.sh -p source/standalone/workflows/sb3/play.py --task Isaac-Cartpole-v0 --num_envs 32 --checkpoint /PATH/TO/model.zip
- Training an agent with
`SKRL <https://skrl.readthedocs.io>`__ on ``Isaac-Reach-Franka-v0``:
.. code:: bash
# install python module (for skrl)
./orbit.sh -e skrl
# run script for training
./orbit.sh -p source/standalone/workflows/skrl/train.py --task Isaac-Reach-Franka-v0 --headless
# run script for playing with 32 environments
./orbit.sh -p source/standalone/workflows/skrl/play.py --task Isaac-Reach-Franka-v0 --num_envs 32 --checkpoint /PATH/TO/model.pt
- Training an agent with
`RL-Games <https://github.com/Denys88/rl_games>`__ on ``Isaac-Ant-v0``:
.. code:: bash
# install python module (for rl-games)
./orbit.sh -e rl_games
# run script for training
./orbit.sh -p source/standalone/workflows/rl_games/train.py --task Isaac-Ant-v0 --headless
# run script for playing with 32 environments
./orbit.sh -p source/standalone/workflows/rl_games/play.py --task Isaac-Ant-v0 --num_envs 32 --checkpoint /PATH/TO/model.pth
- Training an agent with
`RSL-RL <https://github.com/leggedrobotics/rsl_rl>`__ on ``Isaac-Reach-Franka-v0``:
.. code:: bash
# install python module (for rsl-rl)
./orbit.sh -e rsl_rl
# run script for training
./orbit.sh -p source/standalone/workflows/rsl_rl/train.py --task Isaac-Reach-Franka-v0 --headless
# run script for playing with 32 environments
./orbit.sh -p source/standalone/workflows/rsl_rl/play.py --task Isaac-Reach-Franka-v0 --num_envs 32 --checkpoint /PATH/TO/model.pth
All the scripts above log the training progress to `Tensorboard`_ in the ``logs`` directory in the root of
the repository. The logs directory follows the pattern ``logs/<library>/<task>/<date-time>``, where ``<library>``
is the name of the learning framework, ``<task>`` is the task name, and ``<date-time>`` is the timestamp at
which the training script was executed.
To view the logs, run:
.. code:: bash
# execute from the root directory of the repository
./orbit.sh -p -m tensorboard.main --logdir=logs
.. _Tensorboard: https://www.tensorflow.org/tensorboard
| 8,309 | reStructuredText | 34.974026 | 191 | 0.711638 |
fnuabhimanyu8713/orbit/docs/source/setup/developer.rst | Developer's Guide
=================
For development, we suggest using `Microsoft Visual Studio Code
(VSCode) <https://code.visualstudio.com/>`__. This is also suggested by
NVIDIA Omniverse and there exists tutorials on how to `debug Omniverse
extensions <https://www.youtube.com/watch?v=Vr1bLtF1f4U&ab_channel=NVIDIAOmniverse>`__
using VSCode.
Setting up Visual Studio Code
-----------------------------
The ``orbit`` repository includes the VSCode settings to easily allow setting
up your development environment. These are included in the ``.vscode`` directory
and include the following files:
.. code-block:: bash
.vscode
βββ tools
βΒ Β βββ launch.template.json
βΒ Β βββ settings.template.json
βΒ Β βββ setup_vscode.py
βββ extensions.json
βββ launch.json # <- this is generated by setup_vscode.py
βββ settings.json # <- this is generated by setup_vscode.py
βββ tasks.json
To setup the IDE, please follow these instructions:
1. Open the ``orbit`` directory on Visual Studio Code IDE
2. Run VSCode `Tasks <https://code.visualstudio.com/docs/editor/tasks>`__, by
pressing ``Ctrl+Shift+P``, selecting ``Tasks: Run Task`` and running the
``setup_python_env`` in the drop down menu.
.. image:: ../_static/vscode_tasks.png
:width: 600px
:align: center
:alt: VSCode Tasks
If everything executes correctly, it should create a file
``.python.env`` in the ``.vscode`` directory. The file contains the python
paths to all the extensions provided by Isaac Sim and Omniverse. This helps
in indexing all the python modules for intelligent suggestions while writing
code.
For more information on VSCode support for Omniverse, please refer to the
following links:
* `Isaac Sim VSCode support <https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_standalone_python.html#isaac-sim-python-vscode>`__
* `Debugging with VSCode <https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_advanced_python_debugging.html>`__
Configuring the python interpreter
----------------------------------
In the provided configuration, we set the default python interpreter to use the
python executable provided by Omniverse. This is specified in the
``.vscode/settings.json`` file:
.. code-block:: json
{
"python.defaultInterpreterPath": "${workspaceFolder}/_isaac_sim/kit/python/bin/python3",
"python.envFile": "${workspaceFolder}/.vscode/.python.env",
}
If you want to use a different python interpreter (for instance, from your conda environment),
you need to change the python interpreter used by selecting and activating the python interpreter
of your choice in the bottom left corner of VSCode, or opening the command palette (``Ctrl+Shift+P``)
and selecting ``Python: Select Interpreter``.
For more information on how to set python interpreter for VSCode, please
refer to the `VSCode documentation <https://code.visualstudio.com/docs/python/environments#_working-with-python-interpreters>`_.
Repository organization
-----------------------
The ``orbit`` repository is structured as follows:
.. code-block:: bash
orbit
βββ .vscode
βββ .flake8
βββ LICENSE
βββ orbit.sh
βββ pyproject.toml
βββ README.md
βββ docs
βββ source
βΒ Β βββ extensions
βΒ Β βΒ Β βββ omni.isaac.orbit
βΒ Β βΒ Β βββ omni.isaac.orbit_tasks
βΒ Β βββ standalone
βΒ Β βΒ Β βββ demos
βΒ Β βΒ Β βββ environments
βΒ Β βΒ Β βββ tools
βΒ Β βΒ Β βββ tutorials
βΒ Β βΒ Β βββ workflows
βββ VERSION
The ``source`` directory contains the source code for all ``orbit`` *extensions*
and *standalone applications*. The two are the different development workflows
supported in `Isaac Sim <https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/tutorial_intro_workflows.html>`__.
These are described in the following sections.
Extensions
~~~~~~~~~~
Extensions are the recommended way to develop applications in Isaac Sim. They are
modularized packages that formulate the Omniverse ecosystem. Each extension
provides a set of functionalities that can be used by other extensions or
standalone applications. A folder is recognized as an extension if it contains
an ``extension.toml`` file in the ``config`` directory. More information on extensions can be found in the
`Omniverse documentation <https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_basic.html>`__.
Orbit in itself provides extensions for robot learning. These are written into the
``source/extensions`` directory. Each extension is written as a python package and
follows the following structure:
.. code:: bash
<extension-name>
βββ config
βΒ Β βββ extension.toml
βββ docs
βΒ Β βββ CHANGELOG.md
βΒ Β βββ README.md
βββ <extension-name>
β βββ __init__.py
β βββ ....
β βββ scripts
βββ setup.py
βββ tests
The ``config/extension.toml`` file contains the metadata of the extension. This
includes the name, version, description, dependencies, etc. This information is used
by Omniverse to load the extension. The ``docs`` directory contains the documentation
for the extension with more detailed information about the extension and a CHANGELOG
file that contains the changes made to the extension in each version.
The ``<extension-name>`` directory contains the main python package for the extension.
It may also contains the ``scripts`` directory for keeping python-based applications
that are loaded into Omniverse when then extension is enabled using the
`Extension Manager <https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_basic.html>`__.
More specifically, when an extension is enabled, the python module specified in the
``config/extension.toml`` file is loaded and scripts that contains children of the
:class:`omni.ext.IExt` class are executed.
.. code:: python
import omni.ext
class MyExt(omni.ext.IExt):
"""My extension application."""
def on_startup(self, ext_id):
"""Called when the extension is loaded."""
pass
def on_shutdown(self):
"""Called when the extension is unloaded.
It releases all references to the extension and cleans up any resources.
"""
pass
While loading extensions into Omniverse happens automatically, using the python package
in standalone applications requires additional steps. To simplify the build process and
avoiding the need to understand the `premake <https://premake.github.io/>`__
build system used by Omniverse, we directly use the `setuptools <https://setuptools.readthedocs.io/en/latest/>`__
python package to build the python module provided by the extensions. This is done by the
``setup.py`` file in the extension directory.
.. note::
The ``setup.py`` file is not required for extensions that are only loaded into Omniverse
using the `Extension Manager <https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html>`__.
Lastly, the ``tests`` directory contains the unit tests for the extension. These are written
using the `unittest <https://docs.python.org/3/library/unittest.html>`__ framework. It is
important to note that Omniverse also provides a similar
`testing framework <https://docs.omniverse.nvidia.com/kit/docs/kit-manual/104.0/guide/testing_exts_python.html>`__.
However, it requires going through the build process and does not support testing of the python module in
standalone applications.
Extension Dependency Management
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Certain extensions may have dependencies which need to be installed before the extension can be run.
While Python dependencies can be expressed via the ``INSTALL_REQUIRES`` array in ``setup.py``, we need
a separate installation pipeline to handle non-Python dependencies. We have therefore created
an additional setup procedure, ``./orbit.sh --install-deps {dep_type}``, which scans the ``extension.toml``
file of the directories under ``/orbit/source/extensions`` for ``apt`` and ``rosdep`` dependencies.
This example ``extension.toml`` has both ``apt_deps`` and ``ros_ws`` specified, so both
``apt`` and ``rosdep`` packages will be installed if ``./orbit.sh --install-deps all``
is passed:
.. code-block:: toml
[orbit_settings]
apt_deps = ["example_package"]
ros_ws = "path/from/extension_root/to/ros_ws"
From the ``apt_deps`` in the above example, the package ``example_package`` would be installed via ``apt``.
From the ``ros_ws``, a ``rosdep install --from-paths {ros_ws}/src --ignore-src`` command will be called.
This will install all the `ROS package.xml dependencies <https://docs.ros.org/en/humble/Tutorials/Intermediate/Rosdep.html>`__
in the directory structure below. Currently the ROS distro is assumed to be ``humble``.
``apt`` deps are automatically installed this way during the build process of the ``Dockerfile.base``,
and ``rosdep`` deps during the build process of ``Dockerfile.ros2``.
Standalone applications
~~~~~~~~~~~~~~~~~~~~~~~
In a typical Omniverse workflow, the simulator is launched first, after which the extensions are
enabled that load the python module and run the python application. While this is a recommended
workflow, it is not always possible to use this workflow. For example, for robot learning, it is
essential to have complete control over simulation stepping and all the other functionalities
instead of asynchronously waiting for the simulator to step. In such cases, it is necessary to
write a standalone application that launches the simulator using :class:`~omni.isaac.orbit.app.AppLauncher`
and allows complete control over the simulation through the :class:`~omni.isaac.orbit.sim.SimulationContext`
class.
.. code:: python
"""Launch Isaac Sim Simulator first."""
from omni.isaac.orbit.app import AppLauncher
# launch omniverse app
app_launcher = AppLauncher(headless=False)
simulation_app = app_launcher.app
"""Rest everything follows."""
from omni.isaac.orbit.sim import SimulationContext
if __name__ == "__main__":
# get simulation context
simulation_context = SimulationContext()
# reset and play simulation
simulation_context.reset()
# step simulation
simulation_context.step()
# stop simulation
simulation_context.stop()
# close the simulation
simulation_app.close()
The ``source/standalone`` directory contains various standalone applications designed using the extensions
provided by ``orbit``. These applications are written in python and are structured as follows:
* **demos**: Contains various demo applications that showcase the core framework ``omni.isaac.orbit``.
* **environments**: Contains applications for running environments defined in ``omni.isaac.orbit_tasks`` with different agents.
These include a random policy, zero-action policy, teleoperation or scripted state machines.
* **tools**: Contains applications for using the tools provided by the framework. These include converting assets, generating
datasets, etc.
* **tutorials**: Contains step-by-step tutorials for using the APIs provided by the framework.
* **workflows**: Contains applications for using environments with various learning-based frameworks. These include different
reinforcement learning or imitation learning libraries.
| 11,298 | reStructuredText | 40.693727 | 146 | 0.728536 |
fnuabhimanyu8713/orbit/docs/source/setup/template.rst | Building your Own Project
=========================
Traditionally, building new projects that utilize Orbit's features required creating your own
extensions within the Orbit repository. However, this approach can obscure project visibility and
complicate updates from one version of Orbit to another. To circumvent these challenges, we now
provide a pre-configured and customizable `extension template <https://github.com/isaac-orbit/orbit.ext_template>`_
for creating projects in an isolated environment.
This template serves three distinct use cases:
* **Project Template**: Provides essential access to Isaac Sim and Orbit's features, making it ideal for projects
that require a standalone environment.
* **Python Package**: Facilitates integration with Isaac Sim's native or virtual Python environment, allowing for
the creation of Python packages that can be shared and reused across multiple projects.
* **Omniverse Extension**: Supports direct integration into Omniverse extension workflow.
.. note::
We recommend using the extension template for new projects, as it provides a more streamlined and
efficient workflow. Additionally it ensures that your project remains up-to-date with the latest
features and improvements in Orbit.
To get started, please follow the instructions in the `extension template repository <https://github.com/isaac-orbit/orbit.ext_template>`_.
| 1,396 | reStructuredText | 52.730767 | 139 | 0.790831 |
fnuabhimanyu8713/orbit/docs/source/api/index.rst | API Reference
=============
This page gives an overview of all the modules and classes in the Orbit extensions.
omni.isaac.orbit extension
--------------------------
The following modules are available in the ``omni.isaac.orbit`` extension:
.. currentmodule:: omni.isaac.orbit
.. autosummary::
:toctree: orbit
app
actuators
assets
controllers
devices
envs
managers
markers
scene
sensors
sim
terrains
utils
.. toctree::
:hidden:
orbit/omni.isaac.orbit.envs.mdp
orbit/omni.isaac.orbit.envs.ui
orbit/omni.isaac.orbit.sensors.patterns
orbit/omni.isaac.orbit.sim.converters
orbit/omni.isaac.orbit.sim.schemas
orbit/omni.isaac.orbit.sim.spawners
omni.isaac.orbit_tasks extension
--------------------------------
The following modules are available in the ``omni.isaac.orbit_tasks`` extension:
.. currentmodule:: omni.isaac.orbit_tasks
.. autosummary::
:toctree: orbit_tasks
utils
.. toctree::
:hidden:
orbit_tasks/omni.isaac.orbit_tasks.utils.wrappers
orbit_tasks/omni.isaac.orbit_tasks.utils.data_collector
| 1,096 | reStructuredText | 17.913793 | 83 | 0.67792 |
fnuabhimanyu8713/orbit/docs/source/api/orbit_tasks/omni.isaac.orbit_tasks.utils.rst | ο»Ώorbit\_tasks.utils
==================
.. automodule:: omni.isaac.orbit_tasks.utils
:members:
:imported-members:
.. rubric:: Submodules
.. autosummary::
data_collector
wrappers
| 205 | reStructuredText | 13.714285 | 44 | 0.580488 |
fnuabhimanyu8713/orbit/docs/source/api/orbit_tasks/omni.isaac.orbit_tasks.utils.data_collector.rst | ο»Ώorbit\_tasks.utils.data\_collector
==================================
.. automodule:: omni.isaac.orbit_tasks.utils.data_collector
.. Rubric:: Classes
.. autosummary::
RobomimicDataCollector
Robomimic Data Collector
------------------------
.. autoclass:: RobomimicDataCollector
:members:
:show-inheritance:
| 338 | reStructuredText | 17.833332 | 59 | 0.579882 |
fnuabhimanyu8713/orbit/docs/source/api/orbit_tasks/omni.isaac.orbit_tasks.utils.wrappers.rst | ο»Ώorbit\_tasks.utils.wrappers
===========================
.. automodule:: omni.isaac.orbit_tasks.utils.wrappers
RL-Games Wrapper
----------------
.. automodule:: omni.isaac.orbit_tasks.utils.wrappers.rl_games
:members:
:show-inheritance:
RSL-RL Wrapper
--------------
.. automodule:: omni.isaac.orbit_tasks.utils.wrappers.rsl_rl
:members:
:imported-members:
:show-inheritance:
SKRL Wrapper
------------
.. automodule:: omni.isaac.orbit_tasks.utils.wrappers.skrl
:members:
:show-inheritance:
Stable-Baselines3 Wrapper
-------------------------
.. automodule:: omni.isaac.orbit_tasks.utils.wrappers.sb3
:members:
:show-inheritance:
| 665 | reStructuredText | 18.588235 | 62 | 0.62406 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.utils.rst | ο»Ώorbit.utils
===========
.. automodule:: omni.isaac.orbit.utils
.. Rubric:: Submodules
.. autosummary::
io
array
assets
dict
math
noise
string
timer
warp
.. Rubric:: Functions
.. autosummary::
configclass
Configuration class
~~~~~~~~~~~~~~~~~~~
.. automodule:: omni.isaac.orbit.utils.configclass
:members:
:show-inheritance:
IO operations
~~~~~~~~~~~~~
.. automodule:: omni.isaac.orbit.utils.io
:members:
:imported-members:
:show-inheritance:
Array operations
~~~~~~~~~~~~~~~~
.. automodule:: omni.isaac.orbit.utils.array
:members:
:show-inheritance:
Asset operations
~~~~~~~~~~~~~~~~
.. automodule:: omni.isaac.orbit.utils.assets
:members:
:show-inheritance:
Dictionary operations
~~~~~~~~~~~~~~~~~~~~~
.. automodule:: omni.isaac.orbit.utils.dict
:members:
:show-inheritance:
Math operations
~~~~~~~~~~~~~~~
.. automodule:: omni.isaac.orbit.utils.math
:members:
:inherited-members:
:show-inheritance:
Noise operations
~~~~~~~~~~~~~~~~
.. automodule:: omni.isaac.orbit.utils.noise
:members:
:imported-members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, func
String operations
~~~~~~~~~~~~~~~~~
.. automodule:: omni.isaac.orbit.utils.string
:members:
:show-inheritance:
Timer operations
~~~~~~~~~~~~~~~~
.. automodule:: omni.isaac.orbit.utils.timer
:members:
:show-inheritance:
Warp operations
~~~~~~~~~~~~~~~
.. automodule:: omni.isaac.orbit.utils.warp
:members:
:imported-members:
:show-inheritance:
| 1,602 | reStructuredText | 14.871287 | 50 | 0.598627 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.terrains.rst | ο»Ώorbit.terrains
==============
.. automodule:: omni.isaac.orbit.terrains
.. rubric:: Classes
.. autosummary::
TerrainImporter
TerrainImporterCfg
TerrainGenerator
TerrainGeneratorCfg
SubTerrainBaseCfg
Terrain importer
----------------
.. autoclass:: TerrainImporter
:members:
:show-inheritance:
.. autoclass:: TerrainImporterCfg
:members:
:exclude-members: __init__, class_type
Terrain generator
-----------------
.. autoclass:: TerrainGenerator
:members:
.. autoclass:: TerrainGeneratorCfg
:members:
:exclude-members: __init__
.. autoclass:: SubTerrainBaseCfg
:members:
:exclude-members: __init__
Height fields
-------------
.. automodule:: omni.isaac.orbit.terrains.height_field
All sub-terrains must inherit from the :class:`HfTerrainBaseCfg` class which contains the common
parameters for all terrains generated from height fields.
.. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfTerrainBaseCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Random Uniform Terrain
^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.height_field.hf_terrains.random_uniform_terrain
.. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfRandomUniformTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Pyramid Sloped Terrain
^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.height_field.hf_terrains.pyramid_sloped_terrain
.. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfPyramidSlopedTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
.. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfInvertedPyramidSlopedTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Pyramid Stairs Terrain
^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.height_field.hf_terrains.pyramid_stairs_terrain
.. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfPyramidStairsTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
.. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfInvertedPyramidStairsTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Discrete Obstacles Terrain
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.height_field.hf_terrains.discrete_obstacles_terrain
.. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfDiscreteObstaclesTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Wave Terrain
^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.height_field.hf_terrains.wave_terrain
.. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfWaveTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Stepping Stones Terrain
^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.height_field.hf_terrains.stepping_stones_terrain
.. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfSteppingStonesTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Trimesh terrains
----------------
.. automodule:: omni.isaac.orbit.terrains.trimesh
Flat terrain
^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.flat_terrain
.. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshPlaneTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Pyramid terrain
^^^^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.pyramid_stairs_terrain
.. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshPyramidStairsTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Inverted pyramid terrain
^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.inverted_pyramid_stairs_terrain
.. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshInvertedPyramidStairsTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Random grid terrain
^^^^^^^^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.random_grid_terrain
.. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshRandomGridTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Rails terrain
^^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.rails_terrain
.. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshRailsTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Pit terrain
^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.pit_terrain
.. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshPitTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Box terrain
^^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.box_terrain
.. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshBoxTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Gap terrain
^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.gap_terrain
.. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshGapTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Floating ring terrain
^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.floating_ring_terrain
.. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshFloatingRingTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Star terrain
^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.star_terrain
.. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshStarTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Repeated Objects Terrain
^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.repeated_objects_terrain
.. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedObjectsTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
.. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedPyramidsTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
.. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedBoxesTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
.. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedCylindersTerrainCfg
:members:
:show-inheritance:
:exclude-members: __init__, function
Utilities
---------
.. automodule:: omni.isaac.orbit.terrains.utils
:members:
:undoc-members:
| 7,214 | reStructuredText | 26.538168 | 103 | 0.708206 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.sim.rst | ο»Ώorbit.sim
=========
.. automodule:: omni.isaac.orbit.sim
.. rubric:: Submodules
.. autosummary::
converters
schemas
spawners
utils
.. rubric:: Classes
.. autosummary::
SimulationContext
SimulationCfg
PhysxCfg
.. rubric:: Functions
.. autosummary::
simulation_context.build_simulation_context
Simulation Context
------------------
.. autoclass:: SimulationContext
:members:
:show-inheritance:
Simulation Configuration
------------------------
.. autoclass:: SimulationCfg
:members:
:show-inheritance:
:exclude-members: __init__
.. autoclass:: PhysxCfg
:members:
:show-inheritance:
:exclude-members: __init__
Simulation Context Builder
--------------------------
.. automethod:: simulation_context.build_simulation_context
Utilities
---------
.. automodule:: omni.isaac.orbit.sim.utils
:members:
:show-inheritance:
| 897 | reStructuredText | 13.966666 | 59 | 0.626533 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.markers.rst | ο»Ώorbit.markers
=============
.. automodule:: omni.isaac.orbit.markers
.. rubric:: Classes
.. autosummary::
VisualizationMarkers
VisualizationMarkersCfg
Visualization Markers
---------------------
.. autoclass:: VisualizationMarkers
:members:
:undoc-members:
:show-inheritance:
.. autoclass:: VisualizationMarkersCfg
:members:
:exclude-members: __init__
| 392 | reStructuredText | 15.374999 | 40 | 0.637755 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.managers.rst | ο»Ώorbit.managers
==============
.. automodule:: omni.isaac.orbit.managers
.. rubric:: Classes
.. autosummary::
SceneEntityCfg
ManagerBase
ManagerTermBase
ManagerTermBaseCfg
ObservationManager
ObservationGroupCfg
ObservationTermCfg
ActionManager
ActionTerm
ActionTermCfg
EventManager
EventTermCfg
CommandManager
CommandTerm
CommandTermCfg
RewardManager
RewardTermCfg
TerminationManager
TerminationTermCfg
CurriculumManager
CurriculumTermCfg
Scene Entity
------------
.. autoclass:: SceneEntityCfg
:members:
:exclude-members: __init__
Manager Base
------------
.. autoclass:: ManagerBase
:members:
.. autoclass:: ManagerTermBase
:members:
.. autoclass:: ManagerTermBaseCfg
:members:
:exclude-members: __init__
Observation Manager
-------------------
.. autoclass:: ObservationManager
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: ObservationGroupCfg
:members:
:exclude-members: __init__
.. autoclass:: ObservationTermCfg
:members:
:exclude-members: __init__
Action Manager
--------------
.. autoclass:: ActionManager
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: ActionTerm
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: ActionTermCfg
:members:
:exclude-members: __init__
Event Manager
-------------
.. autoclass:: EventManager
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: EventTermCfg
:members:
:exclude-members: __init__
Randomization Manager
---------------------
.. deprecated:: v0.3
The Randomization Manager is deprecated and will be removed in v0.4.
Please use the :class:`EventManager` class instead.
.. autoclass:: RandomizationManager
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: RandomizationTermCfg
:members:
:exclude-members: __init__
Command Manager
---------------
.. autoclass:: CommandManager
:members:
.. autoclass:: CommandTerm
:members:
:exclude-members: __init__, class_type
.. autoclass:: CommandTermCfg
:members:
:exclude-members: __init__, class_type
Reward Manager
--------------
.. autoclass:: RewardManager
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: RewardTermCfg
:exclude-members: __init__
Termination Manager
-------------------
.. autoclass:: TerminationManager
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: TerminationTermCfg
:members:
:exclude-members: __init__
Curriculum Manager
------------------
.. autoclass:: CurriculumManager
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: CurriculumTermCfg
:members:
:exclude-members: __init__
| 2,846 | reStructuredText | 16.574074 | 72 | 0.641251 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.sensors.rst | ο»Ώorbit.sensors
=============
.. automodule:: omni.isaac.orbit.sensors
.. rubric:: Submodules
.. autosummary::
patterns
.. rubric:: Classes
.. autosummary::
SensorBase
SensorBaseCfg
Camera
CameraData
CameraCfg
ContactSensor
ContactSensorData
ContactSensorCfg
FrameTransformer
FrameTransformerData
FrameTransformerCfg
RayCaster
RayCasterData
RayCasterCfg
RayCasterCamera
RayCasterCameraCfg
Sensor Base
-----------
.. autoclass:: SensorBase
:members:
.. autoclass:: SensorBaseCfg
:members:
:exclude-members: __init__, class_type
USD Camera
----------
.. autoclass:: Camera
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: CameraData
:members:
:inherited-members:
:exclude-members: __init__
.. autoclass:: CameraCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, class_type
Contact Sensor
--------------
.. autoclass:: ContactSensor
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: ContactSensorData
:members:
:inherited-members:
:exclude-members: __init__
.. autoclass:: ContactSensorCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, class_type
Frame Transformer
-----------------
.. autoclass:: FrameTransformer
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: FrameTransformerData
:members:
:inherited-members:
:exclude-members: __init__
.. autoclass:: FrameTransformerCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, class_type
.. autoclass:: OffsetCfg
:members:
:inherited-members:
:exclude-members: __init__
Ray-Cast Sensor
---------------
.. autoclass:: RayCaster
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: RayCasterData
:members:
:inherited-members:
:exclude-members: __init__
.. autoclass:: RayCasterCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, class_type
Ray-Cast Camera
---------------
.. autoclass:: RayCasterCamera
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: RayCasterCameraCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, class_type
| 2,409 | reStructuredText | 16.463768 | 42 | 0.635533 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.actuators.rst | ο»Ώorbit.actuators
===============
.. automodule:: omni.isaac.orbit.actuators
.. rubric:: Classes
.. autosummary::
ActuatorBase
ActuatorBaseCfg
ImplicitActuator
ImplicitActuatorCfg
IdealPDActuator
IdealPDActuatorCfg
DCMotor
DCMotorCfg
ActuatorNetMLP
ActuatorNetMLPCfg
ActuatorNetLSTM
ActuatorNetLSTMCfg
Actuator Base
-------------
.. autoclass:: ActuatorBase
:members:
:inherited-members:
.. autoclass:: ActuatorBaseCfg
:members:
:inherited-members:
:exclude-members: __init__, class_type
Implicit Actuator
-----------------
.. autoclass:: ImplicitActuator
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: ImplicitActuatorCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, class_type
Ideal PD Actuator
-----------------
.. autoclass:: IdealPDActuator
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: IdealPDActuatorCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, class_type
DC Motor Actuator
-----------------
.. autoclass:: DCMotor
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: DCMotorCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, class_type
MLP Network Actuator
---------------------
.. autoclass:: ActuatorNetMLP
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: ActuatorNetMLPCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, class_type
LSTM Network Actuator
---------------------
.. autoclass:: ActuatorNetLSTM
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: ActuatorNetLSTMCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, class_type
| 1,831 | reStructuredText | 16.447619 | 42 | 0.663026 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.envs.ui.rst | ο»Ώorbit.envs.ui
=============
.. automodule:: omni.isaac.orbit.envs.ui
.. rubric:: Classes
.. autosummary::
BaseEnvWindow
RLTaskEnvWindow
ViewportCameraController
Base Environment UI
-------------------
.. autoclass:: BaseEnvWindow
:members:
RL Task Environment UI
----------------------
.. autoclass:: RLTaskEnvWindow
:members:
:show-inheritance:
Viewport Camera Controller
--------------------------
.. autoclass:: ViewportCameraController
:members:
| 509 | reStructuredText | 14.9375 | 40 | 0.573674 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.devices.rst | ο»Ώorbit.devices
=============
.. automodule:: omni.isaac.orbit.devices
.. rubric:: Classes
.. autosummary::
DeviceBase
Se2Gamepad
Se3Gamepad
Se2Keyboard
Se3Keyboard
Se3SpaceMouse
Se3SpaceMouse
Device Base
-----------
.. autoclass:: DeviceBase
:members:
Game Pad
--------
.. autoclass:: Se2Gamepad
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: Se3Gamepad
:members:
:inherited-members:
:show-inheritance:
Keyboard
--------
.. autoclass:: Se2Keyboard
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: Se3Keyboard
:members:
:inherited-members:
:show-inheritance:
Space Mouse
-----------
.. autoclass:: Se2SpaceMouse
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: Se3SpaceMouse
:members:
:inherited-members:
:show-inheritance:
| 893 | reStructuredText | 13.419355 | 40 | 0.62262 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.app.rst | ο»Ώorbit.app
=========
.. automodule:: omni.isaac.orbit.app
.. rubric:: Classes
.. autosummary::
AppLauncher
Environment variables
---------------------
The following details the behavior of the class based on the environment variables:
* **Headless mode**: If the environment variable ``HEADLESS=1``, then SimulationApp will be started in headless mode.
If ``LIVESTREAM={1,2,3}``, then it will supersede the ``HEADLESS`` envvar and force headlessness.
* ``HEADLESS=1`` causes the app to run in headless mode.
* **Livestreaming**: If the environment variable ``LIVESTREAM={1,2,3}`` , then `livestream`_ is enabled. Any
of the livestream modes being true forces the app to run in headless mode.
* ``LIVESTREAM=1`` enables streaming via the Isaac `Native Livestream`_ extension. This allows users to
connect through the Omniverse Streaming Client.
* ``LIVESTREAM=2`` enables streaming via the `Websocket Livestream`_ extension. This allows users to
connect in a browser using the WebSocket protocol.
* ``LIVESTREAM=3`` enables streaming via the `WebRTC Livestream`_ extension. This allows users to
connect in a browser using the WebRTC protocol.
* **Offscreen Render**: If the environment variable ``OFFSCREEN_RENDER`` is set to 1, then the
offscreen-render pipeline is enabled. This is useful for running the simulator without a GUI but
still rendering the viewport and camera images.
* ``OFFSCREEN_RENDER=1``: Enables the offscreen-render pipeline which allows users to render
the scene without launching a GUI.
.. note::
The off-screen rendering pipeline only works when used in conjunction with the
:class:`omni.isaac.orbit.sim.SimulationContext` class. This is because the off-screen rendering
pipeline enables flags that are internally used by the SimulationContext class.
To set the environment variables, one can use the following command in the terminal:
.. code:: bash
export REMOTE_DEPLOYMENT=3
export OFFSCREEN_RENDER=1
# run the python script
./orbit.sh -p source/standalone/demo/play_quadrupeds.py
Alternatively, one can set the environment variables to the python script directly:
.. code:: bash
REMOTE_DEPLOYMENT=3 OFFSCREEN_RENDER=1 ./orbit.sh -p source/standalone/demo/play_quadrupeds.py
Overriding the environment variables
------------------------------------
The environment variables can be overridden in the python script itself using the :class:`AppLauncher`.
These can be passed as a dictionary, a :class:`argparse.Namespace` object or as keyword arguments.
When the passed arguments are not the default values, then they override the environment variables.
The following snippet shows how use the :class:`AppLauncher` in different ways:
.. code:: python
import argparser
from omni.isaac.orbit.app import AppLauncher
# add argparse arguments
parser = argparse.ArgumentParser()
# add your own arguments
# ....
# add app launcher arguments for cli
AppLauncher.add_app_launcher_args(parser)
# parse arguments
args = parser.parse_args()
# launch omniverse isaac-sim app
# -- Option 1: Pass the settings as a Namespace object
app_launcher = AppLauncher(args).app
# -- Option 2: Pass the settings as keywords arguments
app_launcher = AppLauncher(headless=args.headless, livestream=args.livestream)
# -- Option 3: Pass the settings as a dictionary
app_launcher = AppLauncher(vars(args))
# -- Option 4: Pass no settings
app_launcher = AppLauncher()
# obtain the launched app
simulation_app = app_launcher.app
Simulation App Launcher
-----------------------
.. autoclass:: AppLauncher
:members:
.. _livestream: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_livestream_clients.html
.. _`Native Livestream`: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_livestream_clients.html#isaac-sim-setup-kit-remote
.. _`Websocket Livestream`: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_livestream_clients.html#isaac-sim-setup-livestream-webrtc
.. _`WebRTC Livestream`: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_livestream_clients.html#isaac-sim-setup-livestream-websocket
| 4,248 | reStructuredText | 36.9375 | 152 | 0.734228 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.sim.converters.rst | ο»Ώorbit.sim.converters
====================
.. automodule:: omni.isaac.orbit.sim.converters
.. rubric:: Classes
.. autosummary::
AssetConverterBase
AssetConverterBaseCfg
MeshConverter
MeshConverterCfg
UrdfConverter
UrdfConverterCfg
Asset Converter Base
--------------------
.. autoclass:: AssetConverterBase
:members:
.. autoclass:: AssetConverterBaseCfg
:members:
:exclude-members: __init__
Mesh Converter
--------------
.. autoclass:: MeshConverter
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: MeshConverterCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__
URDF Converter
--------------
.. autoclass:: UrdfConverter
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: UrdfConverterCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__
| 933 | reStructuredText | 15.981818 | 47 | 0.633441 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.sim.spawners.rst | ο»Ώorbit.sim.spawners
==================
.. automodule:: omni.isaac.orbit.sim.spawners
.. rubric:: Submodules
.. autosummary::
shapes
lights
sensors
from_files
materials
.. rubric:: Classes
.. autosummary::
SpawnerCfg
RigidObjectSpawnerCfg
Spawners
--------
.. autoclass:: SpawnerCfg
:members:
:exclude-members: __init__
.. autoclass:: RigidObjectSpawnerCfg
:members:
:show-inheritance:
:exclude-members: __init__
Shapes
------
.. automodule:: omni.isaac.orbit.sim.spawners.shapes
.. rubric:: Classes
.. autosummary::
ShapeCfg
CapsuleCfg
ConeCfg
CuboidCfg
CylinderCfg
SphereCfg
.. autoclass:: ShapeCfg
:members:
:exclude-members: __init__, func
.. autofunction:: spawn_capsule
.. autoclass:: CapsuleCfg
:members:
:show-inheritance:
:exclude-members: __init__, func
.. autofunction:: spawn_cone
.. autoclass:: ConeCfg
:members:
:show-inheritance:
:exclude-members: __init__, func
.. autofunction:: spawn_cuboid
.. autoclass:: CuboidCfg
:members:
:show-inheritance:
:exclude-members: __init__, func
.. autofunction:: spawn_cylinder
.. autoclass:: CylinderCfg
:members:
:show-inheritance:
:exclude-members: __init__, func
.. autofunction:: spawn_sphere
.. autoclass:: SphereCfg
:members:
:show-inheritance:
:exclude-members: __init__, func
Lights
------
.. automodule:: omni.isaac.orbit.sim.spawners.lights
.. rubric:: Classes
.. autosummary::
LightCfg
CylinderLightCfg
DiskLightCfg
DistantLightCfg
DomeLightCfg
SphereLightCfg
.. autofunction:: spawn_light
.. autoclass:: LightCfg
:members:
:exclude-members: __init__, func
.. autoclass:: CylinderLightCfg
:members:
:exclude-members: __init__, func
.. autoclass:: DiskLightCfg
:members:
:exclude-members: __init__, func
.. autoclass:: DistantLightCfg
:members:
:exclude-members: __init__, func
.. autoclass:: DomeLightCfg
:members:
:exclude-members: __init__, func
.. autoclass:: SphereLightCfg
:members:
:exclude-members: __init__, func
Sensors
-------
.. automodule:: omni.isaac.orbit.sim.spawners.sensors
.. rubric:: Classes
.. autosummary::
PinholeCameraCfg
FisheyeCameraCfg
.. autofunction:: spawn_camera
.. autoclass:: PinholeCameraCfg
:members:
:exclude-members: __init__, func
.. autoclass:: FisheyeCameraCfg
:members:
:exclude-members: __init__, func
From Files
----------
.. automodule:: omni.isaac.orbit.sim.spawners.from_files
.. rubric:: Classes
.. autosummary::
UrdfFileCfg
UsdFileCfg
GroundPlaneCfg
.. autofunction:: spawn_from_urdf
.. autoclass:: UrdfFileCfg
:members:
:exclude-members: __init__, func
.. autofunction:: spawn_from_usd
.. autoclass:: UsdFileCfg
:members:
:exclude-members: __init__, func
.. autofunction:: spawn_ground_plane
.. autoclass:: GroundPlaneCfg
:members:
:exclude-members: __init__, func
Materials
---------
.. automodule:: omni.isaac.orbit.sim.spawners.materials
.. rubric:: Classes
.. autosummary::
VisualMaterialCfg
PreviewSurfaceCfg
MdlFileCfg
GlassMdlCfg
PhysicsMaterialCfg
RigidBodyMaterialCfg
Visual Materials
~~~~~~~~~~~~~~~~
.. autoclass:: VisualMaterialCfg
:members:
:exclude-members: __init__, func
.. autofunction:: spawn_preview_surface
.. autoclass:: PreviewSurfaceCfg
:members:
:exclude-members: __init__, func
.. autofunction:: spawn_from_mdl_file
.. autoclass:: MdlFileCfg
:members:
:exclude-members: __init__, func
.. autoclass:: GlassMdlCfg
:members:
:exclude-members: __init__, func
Physical Materials
~~~~~~~~~~~~~~~~~~
.. autoclass:: PhysicsMaterialCfg
:members:
:exclude-members: __init__, func
.. autofunction:: spawn_rigid_body_material
.. autoclass:: RigidBodyMaterialCfg
:members:
:exclude-members: __init__, func
| 3,974 | reStructuredText | 15.772152 | 56 | 0.642929 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.controllers.rst | ο»Ώorbit.controllers
=================
.. automodule:: omni.isaac.orbit.controllers
.. rubric:: Classes
.. autosummary::
DifferentialIKController
DifferentialIKControllerCfg
Differential Inverse Kinematics
-------------------------------
.. autoclass:: DifferentialIKController
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: DifferentialIKControllerCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, class_type
| 503 | reStructuredText | 18.384615 | 44 | 0.650099 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.envs.rst | ο»Ώorbit.envs
==========
.. automodule:: omni.isaac.orbit.envs
.. rubric:: Submodules
.. autosummary::
mdp
ui
.. rubric:: Classes
.. autosummary::
BaseEnv
BaseEnvCfg
ViewerCfg
RLTaskEnv
RLTaskEnvCfg
Base Environment
----------------
.. autoclass:: BaseEnv
:members:
.. autoclass:: BaseEnvCfg
:members:
:exclude-members: __init__, class_type
.. autoclass:: ViewerCfg
:members:
:exclude-members: __init__
RL Task Environment
-------------------
.. autoclass:: RLTaskEnv
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: RLTaskEnvCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, class_type
| 729 | reStructuredText | 13.6 | 42 | 0.593964 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.scene.rst | ο»Ώorbit.scene
===========
.. automodule:: omni.isaac.orbit.scene
.. rubric:: Classes
.. autosummary::
InteractiveScene
InteractiveSceneCfg
interactive Scene
-----------------
.. autoclass:: InteractiveScene
:members:
:undoc-members:
:show-inheritance:
.. autoclass:: InteractiveSceneCfg
:members:
:exclude-members: __init__
| 362 | reStructuredText | 14.124999 | 38 | 0.624309 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.sensors.patterns.rst | ο»Ώorbit.sensors.patterns
======================
.. automodule:: omni.isaac.orbit.sensors.patterns
.. rubric:: Classes
.. autosummary::
PatternBaseCfg
GridPatternCfg
PinholeCameraPatternCfg
BpearlPatternCfg
Pattern Base
------------
.. autoclass:: PatternBaseCfg
:members:
:inherited-members:
:exclude-members: __init__
Grid Pattern
------------
.. autofunction:: omni.isaac.orbit.sensors.patterns.grid_pattern
.. autoclass:: GridPatternCfg
:members:
:inherited-members:
:exclude-members: __init__, func
Pinhole Camera Pattern
----------------------
.. autofunction:: omni.isaac.orbit.sensors.patterns.pinhole_camera_pattern
.. autoclass:: PinholeCameraPatternCfg
:members:
:inherited-members:
:exclude-members: __init__, func
RS-Bpearl Pattern
-----------------
.. autofunction:: omni.isaac.orbit.sensors.patterns.bpearl_pattern
.. autoclass:: BpearlPatternCfg
:members:
:inherited-members:
:exclude-members: __init__, func
| 1,006 | reStructuredText | 18.365384 | 74 | 0.649105 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.assets.rst | ο»Ώorbit.assets
============
.. automodule:: omni.isaac.orbit.assets
.. rubric:: Classes
.. autosummary::
AssetBase
AssetBaseCfg
RigidObject
RigidObjectData
RigidObjectCfg
Articulation
ArticulationData
ArticulationCfg
.. currentmodule:: omni.isaac.orbit.assets
Asset Base
----------
.. autoclass:: AssetBase
:members:
.. autoclass:: AssetBaseCfg
:members:
:exclude-members: __init__, class_type
Rigid Object
------------
.. autoclass:: RigidObject
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: RigidObjectData
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__
.. autoclass:: RigidObjectCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, class_type
Articulation
------------
.. autoclass:: Articulation
:members:
:inherited-members:
:show-inheritance:
.. autoclass:: ArticulationData
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__
.. autoclass:: ArticulationCfg
:members:
:inherited-members:
:show-inheritance:
:exclude-members: __init__, class_type
| 1,202 | reStructuredText | 16.185714 | 42 | 0.639767 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.envs.mdp.rst | ο»Ώorbit.envs.mdp
==============
.. automodule:: omni.isaac.orbit.envs.mdp
Observations
------------
.. automodule:: omni.isaac.orbit.envs.mdp.observations
:members:
Actions
-------
.. automodule:: omni.isaac.orbit.envs.mdp.actions
.. automodule:: omni.isaac.orbit.envs.mdp.actions.actions_cfg
:members:
:show-inheritance:
:exclude-members: __init__, class_type
Events
------
.. automodule:: omni.isaac.orbit.envs.mdp.events
:members:
Commands
--------
.. automodule:: omni.isaac.orbit.envs.mdp.commands
.. automodule:: omni.isaac.orbit.envs.mdp.commands.commands_cfg
:members:
:show-inheritance:
:exclude-members: __init__, class_type
Rewards
-------
.. automodule:: omni.isaac.orbit.envs.mdp.rewards
:members:
Terminations
------------
.. automodule:: omni.isaac.orbit.envs.mdp.terminations
:members:
Curriculum
----------
.. automodule:: omni.isaac.orbit.envs.mdp.curriculums
:members:
| 948 | reStructuredText | 16.254545 | 63 | 0.649789 |
fnuabhimanyu8713/orbit/docs/source/api/orbit/omni.isaac.orbit.sim.schemas.rst | ο»Ώorbit.sim.schemas
=================
.. automodule:: omni.isaac.orbit.sim.schemas
.. rubric:: Classes
.. autosummary::
ArticulationRootPropertiesCfg
RigidBodyPropertiesCfg
CollisionPropertiesCfg
MassPropertiesCfg
JointDrivePropertiesCfg
FixedTendonPropertiesCfg
.. rubric:: Functions
.. autosummary::
define_articulation_root_properties
modify_articulation_root_properties
define_rigid_body_properties
modify_rigid_body_properties
activate_contact_sensors
define_collision_properties
modify_collision_properties
define_mass_properties
modify_mass_properties
modify_joint_drive_properties
modify_fixed_tendon_properties
Articulation Root
-----------------
.. autoclass:: ArticulationRootPropertiesCfg
:members:
:exclude-members: __init__
.. autofunction:: define_articulation_root_properties
.. autofunction:: modify_articulation_root_properties
Rigid Body
----------
.. autoclass:: RigidBodyPropertiesCfg
:members:
:exclude-members: __init__
.. autofunction:: define_rigid_body_properties
.. autofunction:: modify_rigid_body_properties
.. autofunction:: activate_contact_sensors
Collision
---------
.. autoclass:: CollisionPropertiesCfg
:members:
:exclude-members: __init__
.. autofunction:: define_collision_properties
.. autofunction:: modify_collision_properties
Mass
----
.. autoclass:: MassPropertiesCfg
:members:
:exclude-members: __init__
.. autofunction:: define_mass_properties
.. autofunction:: modify_mass_properties
Joint Drive
-----------
.. autoclass:: JointDrivePropertiesCfg
:members:
:exclude-members: __init__
.. autofunction:: modify_joint_drive_properties
Fixed Tendon
------------
.. autoclass:: FixedTendonPropertiesCfg
:members:
:exclude-members: __init__
.. autofunction:: modify_fixed_tendon_properties
| 1,877 | reStructuredText | 19.637362 | 53 | 0.706446 |
fnuabhimanyu8713/orbit/docs/source/features/actuators.rst | .. _feature-actuators:
Actuators
=========
An articulated system comprises of actuated joints, also called the degrees of freedom (DOF).
In a physical system, the actuation typically happens either through active components, such as
electric or hydraulic motors, or passive components, such as springs. These components can introduce
certain non-linear characteristics which includes delays or maximum producible velocity or torque.
In simulation, the joints are either position, velocity, or torque-controlled. For position and velocity
control, the physics engine internally implements a spring-damp (PD) controller which computes the torques
applied on the actuated joints. In torque-control, the commands are set directly as the joint efforts.
While this mimics an ideal behavior of the joint mechanism, it does not truly model how the drives work
in the physical world. Thus, we provide a mechanism to inject external models to compute the
joint commands that would represent the physical robot's behavior.
Actuator models
---------------
We name two different types of actuator models:
1. **implicit**: corresponds to the ideal simulation mechanism (provided by physics engine).
2. **explicit**: corresponds to external drive models (implemented by user).
The explicit actuator model performs two steps: 1) it computes the desired joint torques for tracking
the input commands, and 2) it clips the desired torques based on the motor capabilities. The clipped
torques are the desired actuation efforts that are set into the simulation.
As an example of an ideal explicit actuator model, we provide the :class:`omni.isaac.orbit.actuators.IdealPDActuator`
class, which implements a PD controller with feed-forward effort, and simple clipping based on the configured
maximum effort:
.. math::
\tau_{j, computed} & = k_p * (q - q_{des}) + k_d * (\dot{q} - \dot{q}_{des}) + \tau_{ff} \\
\tau_{j, applied} & = clip(\tau_{computed}, -\tau_{j, max}, \tau_{j, max})
where, :math:`k_p` and :math:`k_d` are joint stiffness and damping gains, :math:`q` and :math:`\dot{q}`
are the current joint positions and velocities, :math:`q_{des}`, :math:`\dot{q}_{des}` and :math:`\tau_{ff}`
are the desired joint positions, velocities and torques commands. The parameters :math:`\gamma` and
:math:`\tau_{motor, max}` are the gear box ratio and the maximum motor effort possible.
Actuator groups
---------------
The actuator models by themselves are computational blocks that take as inputs the desired joint commands
and output the the joint commands to apply into the simulator. They do not contain any knowledge about the
joints they are acting on themselves. These are handled by the :class:`omni.isaac.orbit.assets.Articulation`
class, which wraps around the physics engine's articulation class.
Actuator are collected as a set of actuated joints on an articulation that are using the same actuator model.
For instance, the quadruped, ANYmal-C, uses series elastic actuator, ANYdrive 3.0, for all its joints. This
grouping configures the actuator model for those joints, translates the input commands to the joint level
commands, and returns the articulation action to set into the simulator. Having an arm with a different
actuator model, such as a DC motor, would require configuring a different actuator group.
The following figure shows the actuator groups for a legged mobile manipulator:
.. image:: ../_static/actuator_groups.svg
:width: 600
:align: center
:alt: Actuator groups for a legged mobile manipulator
.. seealso::
We provide implementations for various explicit actuator models. These are detailed in
`omni.isaac.orbit.actuators <../api/orbit.actuators.html>`_ sub-package.
| 3,727 | reStructuredText | 51.507042 | 117 | 0.763885 |
fnuabhimanyu8713/orbit/docs/source/features/motion_generators.rst | Motion Generators
=================
Robotic tasks are typically defined in task-space in terms of desired
end-effector trajectory, while control actions are executed in the
joint-space. This naturally leads to *joint-space* and *task-space*
(operational-space) control methods. However, successful execution of
interaction tasks using motion control often requires an accurate model
of both the robot manipulator as well as its environment. While a
sufficiently precise manipulator's model might be known, detailed
description of environment is hard to obtain :cite:p:`siciliano2009force`.
Planning errors caused by this mismatch can be overcome by introducing a
*compliant* behavior during interaction.
While compliance is achievable passively through robot's structure (such
as elastic actuators, soft robot arms), we are more interested in
controller designs that focus on active interaction control. These are
broadly categorized into:
1. **impedance control:** indirect control method where motion deviations
caused during interaction relates to contact force as a mass-spring-damper
system with adjustable parameters (stiffness and damping). A specialized case
of this is *stiffness* control where only the static relationship between
position error and contact force is considered.
2. **hybrid force/motion control:** active control method which controls motion
and force along unconstrained and constrained task directions respectively.
Among the various schemes for hybrid motion control, the provided implementation
is based on inverse dynamics control in the operational space :cite:p:`khatib1987osc`.
.. note::
To provide an even broader set of motion generators, we welcome contributions from the
community. If you are interested, please open an issue to start a discussion!
Joint-space controllers
-----------------------
Torque control
~~~~~~~~~~~~~~
Action dimensions: ``"n"`` (number of joints)
In torque control mode, the input actions are directly set as feed-forward
joint torque commands, i.e. at every time-step,
.. math::
\tau = \tau_{des}
Thus, this control mode is achievable by setting the command type for the actuator group, via
the :class:`ActuatorControlCfg` class, to ``"t_abs"``.
Velocity control
~~~~~~~~~~~~~~~~
Action dimensions: ``"n"`` (number of joints)
In velocity control mode, a proportional control law is required to reduce the error between the
current and desired joint velocities. Based on input actions, the joint torques commands are computed as:
.. math::
\tau = k_d (\dot{q}_{des} - \dot{q})
where :math:`k_d` are the gains parsed from configuration.
This control mode is achievable by setting the command type for the actuator group, via
the :class:`ActuatorControlCfg` class, to ``"v_abs"`` or ``"v_rel"``.
.. attention::
While performing velocity control, in many cases, gravity compensation is required to ensure better
tracking of the command. In this case, we suggest disabling gravity for the links in the articulation
in simulation.
Position control with fixed impedance
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Action dimensions: ``"n"`` (number of joints)
In position control mode, a proportional-damping (PD) control law is employed to track the desired joint
positions and ensuring the articulation remains still at the desired location (i.e., desired joint velocities
are zero). Based on the input actions, the joint torque commands are computed as:
.. math::
\tau = k_p (q_{des} - q) - k_d \dot{q}
where :math:`k_p` and :math:`k_d` are the gains parsed from configuration.
In its simplest above form, the control mode is achievable by setting the command type for the actuator group,
via the :class:`ActuatorControlCfg` class, to ``"p_abs"`` or ``"p_rel"``.
However, a more complete formulation which considers the dynamics of the articulation would be:
.. math::
\tau = M \left( k_p (q_{des} - q) - k_d \dot{q} \right) + g
where :math:`M` is the joint-space inertia matrix of size :math:`n \times n`, and :math:`g` is the joint-space
gravity vector. This implementation is available through the :class:`JointImpedanceController` class by setting the
impedance mode to ``"fixed"``. The gains :math:`k_p` are parsed from the input configuration and :math:`k_d`
are computed while considering the system as a decoupled point-mass oscillator, i.e.,
.. math::
k_d = 2 \sqrt{k_p} \times D
where :math:`D` is the damping ratio of the system. Critical damping is achieved for :math:`D = 1`, overcritical
damping for :math:`D > 1` and undercritical damping for :math:`D < 1`.
Additionally, it is possible to disable the inertial or gravity compensation in the controller by setting the
flags :attr:`inertial_compensation` and :attr:`gravity_compensation` in the configuration to :obj:`False`,
respectively.
Position control with variable stiffness
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Action dimensions: ``"2n"`` (number of joints)
In stiffness control, the same formulation as above is employed, however, the gains :math:`k_p` are part of
the input commands. This implementation is available through the :class:`JointImpedanceController` class by
setting the impedance mode to ``"variable_kp"``.
Position control with variable impedance
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Action dimensions: ``"3n"`` (number of joints)
In impedance control, the same formulation as above is employed, however, both :math:`k_p` and :math:`k_d`
are part of the input commands. This implementation is available through the :class:`JointImpedanceController`
class by setting the impedance mode to ``"variable"``.
Task-space controllers
----------------------
Differential inverse kinematics (IK)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Action dimensions: ``"3"`` (relative/absolute position), ``"6"`` (relative pose), or ``"7"`` (absolute pose)
Inverse kinematics converts the task-space tracking error to joint-space error. In its most typical implementation,
the pose error in the task-sace, :math:`\Delta \chi_e = (\Delta p_e, \Delta \phi_e)`, is computed as the cartesian
distance between the desired and current task-space positions, and the shortest distance in :math:`\mathbb{SO}(3)`
between the desired and current task-space orientations.
Using the geometric Jacobian :math:`J_{eO} \in \mathbb{R}^{6 \times n}`, that relates task-space velocity to joint-space velocities,
we design the control law to obtain the desired joint positions as:
.. math::
q_{des} = q + \eta J_{eO}^{-} \Delta \chi_e
where :math:`\eta` is a scaling parameter and :math:`J_{eO}^{-}` is the pseudo-inverse of the Jacobian.
It is possible to compute the pseudo-inverse of the Jacobian using different formulations:
* Moore-Penrose pseduo-inverse: :math:`A^{-} = A^T(AA^T)^{-1}`.
* Levenberg-Marquardt pseduo-inverse (damped least-squares): :math:`A^{-} = A^T (AA^T + \lambda \mathbb{I})^{-1}`.
* Tanspose pseudo-inverse: :math:`A^{-} = A^T`.
* Adaptive singular-vale decomposition (SVD) pseduo-inverse from :cite:t:`buss2004ik`.
These implementations are available through the :class:`DifferentialInverseKinematics` class.
Impedance controller
~~~~~~~~~~~~~~~~~~~~
It uses task-space pose error and Jacobian to compute join torques through mass-spring-damper system
with a) fixed stiffness, b) variable stiffness (stiffness control),
and c) variable stiffness and damping (impedance control).
Operational-space controller
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Similar to task-space impedance
control but uses the Equation of Motion (EoM) for computing the
task-space force
Closed-loop proportional force controller
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It uses a proportional term
to track the desired wrench command with respect to current wrench at
the end-effector.
Hybrid force-motion controller
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It combines closed-loop force control
and operational-space motion control to compute the desired wrench at
the end-effector. It uses selection matrices that define the
unconstrainted and constrained task directions.
Reactive planners
-----------------
Typical task-space controllers do not account for motion constraints
such as joint limits, self-collision and environment collision. Instead
they rely on high-level planners (such as RRT) to handle these
non-Euclidean constraints and give joint/task-space way-points to the
controller. However, these methods are often conservative and have
undesirable deceleration when close to an object. More recently,
different approaches combine the constraints directly into an
optimization problem, thereby providing a holistic solution for motion
generation and control.
We currently support the following planners:
- **RMPFlow (lula):** An acceleration-based policy that composes various Reimannian Motion Policies (RMPs) to
solve a hierarchy of tasks :cite:p:`cheng2021rmpflow`. It is capable of performing dynamic collision
avoidance while navigating the end-effector to a target.
- **MPC (OCS2):** A receding horizon control policy based on sequential linear-quadratic (SLQ) programming.
It formulates various constraints into a single optimization problem via soft-penalties and uses automatic
differentiation to compute derivatives of the system dynamics, constraints and costs. Currently, we support
the MPC formulation for end-effector trajectory tracking in fixed-arm and mobile manipulators. The formulation
considers a kinematic system model with joint limits and self-collision avoidance :cite:p:`mittal2021articulated`.
.. warning::
We wrap around the python bindings for these reactive planners to perform a batched computing of
robot actions. However, their current implementations are CPU-based which may cause certain
slowdown for learning.
| 9,828 | reStructuredText | 41.734782 | 132 | 0.737993 |
fnuabhimanyu8713/orbit/docs/source/features/environments.rst | Environments
============
The following lists comprises of all the RL tasks implementations that are available in Orbit.
While we try to keep this list up-to-date, you can always get the latest list of environments by
running the following command:
.. code-block:: bash
./orbit.sh -p source/standalone/environments/list_envs.py
We are actively working on adding more environments to the list. If you have any environments that
you would like to add to Orbit, please feel free to open a pull request!
Classic
-------
Classic environments that are based on IsaacGymEnvs implementation of MuJoCo-style environments.
.. table::
:widths: 33 37 30
+------------------+-----------------------------+-------------------------------------------------------------------------+
| World | Environment ID | Description |
+==================+=============================+=========================================================================+
| |humanoid| | |humanoid-link| | Move towards a direction with the MuJoCo humanoid robot |
+------------------+-----------------------------+-------------------------------------------------------------------------+
| |ant| | |ant-link| | Move towards a direction with the MuJoCo ant robot |
+------------------+-----------------------------+-------------------------------------------------------------------------+
| |cartpole| | |cartpole-link| | Move the cart to keep the pole upwards in the classic cartpole control |
+------------------+-----------------------------+-------------------------------------------------------------------------+
.. |humanoid| image:: ../_static/tasks/classic/humanoid.jpg
.. |ant| image:: ../_static/tasks/classic/ant.jpg
.. |cartpole| image:: ../_static/tasks/classic/cartpole.jpg
.. |humanoid-link| replace:: `Isaac-Humanoid-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/humanoid_env_cfg.py>`__
.. |ant-link| replace:: `Isaac-Ant-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/ant/ant_env_cfg.py>`__
.. |cartpole-link| replace:: `Isaac-Cartpole-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/cartpole_env_cfg.py>`__
Manipulation
------------
Environments based on fixed-arm manipulation tasks.
For many of these tasks, we include configurations with different arm action spaces. For example,
for the reach environment:
* |lift-cube-link|: Franka arm with joint position control
* |lift-cube-ik-abs-link|: Franka arm with absolute IK control
* |lift-cube-ik-rel-link|: Franka arm with relative IK control
.. table::
:widths: 33 37 30
+----------------+---------------------+-----------------------------------------------------------------------------+
| World | Environment ID | Description |
+================+=====================+=============================================================================+
| |reach-franka| | |reach-franka-link| | Move the end-effector to a sampled target pose with the Franka robot |
+----------------+---------------------+-----------------------------------------------------------------------------+
| |reach-ur10| | |reach-ur10-link| | Move the end-effector to a sampled target pose with the UR10 robot |
+----------------+---------------------+-----------------------------------------------------------------------------+
| |lift-cube| | |lift-cube-link| | Pick a cube and bring it to a sampled target position with the Franka robot |
+----------------+---------------------+-----------------------------------------------------------------------------+
| |cabi-franka| | |cabi-franka-link| | Grasp the handle of a cabinet's drawer and open it with the Franka robot |
+----------------+---------------------+-----------------------------------------------------------------------------+
| |cube-allegro| | |cube-allegro-link| | In-hand reorientation of a cube using Allegro hand |
+----------------+---------------------+-----------------------------------------------------------------------------+
.. |reach-franka| image:: ../_static/tasks/manipulation/franka_reach.jpg
.. |reach-ur10| image:: ../_static/tasks/manipulation/ur10_reach.jpg
.. |lift-cube| image:: ../_static/tasks/manipulation/franka_lift.jpg
.. |cabi-franka| image:: ../_static/tasks/manipulation/franka_open_drawer.jpg
.. |cube-allegro| image:: ../_static/tasks/manipulation/allegro_cube.jpg
.. |reach-franka-link| replace:: `Isaac-Reach-Franka-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/reach/config/franka/joint_pos_env_cfg.py>`__
.. |reach-ur10-link| replace:: `Isaac-Reach-UR10-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/reach/config/ur_10/joint_pos_env_cfg.py>`__
.. |lift-cube-link| replace:: `Isaac-Lift-Cube-Franka-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/config/franka/joint_pos_env_cfg.py>`__
.. |lift-cube-ik-abs-link| replace:: `Isaac-Lift-Cube-Franka-IK-Abs-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/config/franka/ik_abs_env_cfg.py>`__
.. |lift-cube-ik-rel-link| replace:: `Isaac-Lift-Cube-Franka-IK-Rel-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/config/franka/ik_rel_env_cfg.py>`__
.. |cabi-franka-link| replace:: `Isaac-Open-Drawer-Franka-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/cabinet/config/franka/joint_pos_env_cfg.py>`__
.. |cube-allegro-link| replace:: `Isaac-Repose-Cube-Allegro-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/inhand/config/allegro/allegro_env_cfg.py>`__
Locomotion
----------
Environments based on legged locomotion tasks.
.. table::
:widths: 33 37 30
+------------------------------+----------------------------------------------+-------------------------------------------------------------------------+
| World | Environment ID | Description |
+==============================+==============================================+=========================================================================+
| |velocity-flat-anymal-b| | |velocity-flat-anymal-b-link| | Track a velocity command on flat terrain with the Anymal B robot |
+------------------------------+----------------------------------------------+-------------------------------------------------------------------------+
| |velocity-rough-anymal-b| | |velocity-rough-anymal-b-link| | Track a velocity command on rough terrain with the Anymal B robot |
+------------------------------+----------------------------------------------+-------------------------------------------------------------------------+
| |velocity-flat-anymal-c| | |velocity-flat-anymal-c-link| | Track a velocity command on flat terrain with the Anymal C robot |
+------------------------------+----------------------------------------------+-------------------------------------------------------------------------+
| |velocity-rough-anymal-c| | |velocity-rough-anymal-c-link| | Track a velocity command on rough terrain with the Anymal C robot |
+------------------------------+----------------------------------------------+-------------------------------------------------------------------------+
| |velocity-flat-anymal-d| | |velocity-flat-anymal-d-link| | Track a velocity command on flat terrain with the Anymal D robot |
+------------------------------+----------------------------------------------+-------------------------------------------------------------------------+
| |velocity-rough-anymal-d| | |velocity-rough-anymal-d-link| | Track a velocity command on rough terrain with the Anymal D robot |
+------------------------------+----------------------------------------------+-------------------------------------------------------------------------+
| |velocity-flat-unitree-a1| | |velocity-flat-unitree-a1-link| | Track a velocity command on flat terrain with the Unitree A1 robot |
+------------------------------+----------------------------------------------+-------------------------------------------------------------------------+
| |velocity-rough-unitree-a1| | |velocity-rough-unitree-a1-link| | Track a velocity command on rough terrain with the Unitree A1 robot |
+------------------------------+----------------------------------------------+-------------------------------------------------------------------------+
| |velocity-flat-unitree-go1| | |velocity-flat-unitree-go1-link| | Track a velocity command on flat terrain with the Unitree Go1 robot |
+------------------------------+----------------------------------------------+-------------------------------------------------------------------------+
| |velocity-rough-unitree-go1| | |velocity-rough-unitree-go1-link| | Track a velocity command on rough terrain with the Unitree Go1 robot |
+------------------------------+----------------------------------------------+-------------------------------------------------------------------------+
| |velocity-flat-unitree-go2| | |velocity-flat-unitree-go2-link| | Track a velocity command on flat terrain with the Unitree Go2 robot |
+------------------------------+----------------------------------------------+-------------------------------------------------------------------------+
| |velocity-rough-unitree-go2| | |velocity-rough-unitree-go2-link| | Track a velocity command on rough terrain with the Unitree Go2 robot |
+------------------------------+----------------------------------------------+-------------------------------------------------------------------------+
.. |velocity-flat-anymal-b-link| replace:: `Isaac-Velocity-Flat-Anymal-B-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_b/flat_env_cfg.py>`__
.. |velocity-rough-anymal-b-link| replace:: `Isaac-Velocity-Rough-Anymal-B-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_b/rough_env_cfg.py>`__
.. |velocity-flat-anymal-c-link| replace:: `Isaac-Velocity-Flat-Anymal-C-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_c/flat_env_cfg.py>`__
.. |velocity-rough-anymal-c-link| replace:: `Isaac-Velocity-Rough-Anymal-C-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_c/rough_env_cfg.py>`__
.. |velocity-flat-anymal-d-link| replace:: `Isaac-Velocity-Flat-Anymal-D-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_d/flat_env_cfg.py>`__
.. |velocity-rough-anymal-d-link| replace:: `Isaac-Velocity-Rough-Anymal-D-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_d/rough_env_cfg.py>`__
.. |velocity-flat-unitree-a1-link| replace:: `Isaac-Velocity-Flat-Unitree-A1-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_a1/flat_env_cfg.py>`__
.. |velocity-rough-unitree-a1-link| replace:: `Isaac-Velocity-Rough-Unitree-A1-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_a1/rough_env_cfg.py>`__
.. |velocity-flat-unitree-go1-link| replace:: `Isaac-Velocity-Flat-Unitree-Go1-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go1/flat_env_cfg.py>`__
.. |velocity-rough-unitree-go1-link| replace:: `Isaac-Velocity-Rough-Unitree-Go1-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go1/rough_env_cfg.py>`__
.. |velocity-flat-unitree-go2-link| replace:: `Isaac-Velocity-Flat-Unitree-Go2-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go2/flat_env_cfg.py>`__
.. |velocity-rough-unitree-go2-link| replace:: `Isaac-Velocity-Rough-Unitree-Go2-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go2/rough_env_cfg.py>`__
.. |velocity-flat-anymal-b| image:: ../_static/tasks/locomotion/anymal_b_flat.jpg
.. |velocity-rough-anymal-b| image:: ../_static/tasks/locomotion/anymal_b_rough.jpg
.. |velocity-flat-anymal-c| image:: ../_static/tasks/locomotion/anymal_c_flat.jpg
.. |velocity-rough-anymal-c| image:: ../_static/tasks/locomotion/anymal_c_rough.jpg
.. |velocity-flat-anymal-d| image:: ../_static/tasks/locomotion/anymal_d_flat.jpg
.. |velocity-rough-anymal-d| image:: ../_static/tasks/locomotion/anymal_d_rough.jpg
.. |velocity-flat-unitree-a1| image:: ../_static/tasks/locomotion/a1_flat.jpg
.. |velocity-rough-unitree-a1| image:: ../_static/tasks/locomotion/a1_rough.jpg
.. |velocity-flat-unitree-go1| image:: ../_static/tasks/locomotion/go1_flat.jpg
.. |velocity-rough-unitree-go1| image:: ../_static/tasks/locomotion/go1_rough.jpg
.. |velocity-flat-unitree-go2| image:: ../_static/tasks/locomotion/go2_flat.jpg
.. |velocity-rough-unitree-go2| image:: ../_static/tasks/locomotion/go2_rough.jpg
| 15,043 | reStructuredText | 97.326797 | 260 | 0.531676 |
fnuabhimanyu8713/orbit/docs/source/deployment/cluster.rst | .. _deployment-cluster:
Cluster Guide
=============
Clusters are a great way to speed up training and evaluation of learning algorithms.
While the Orbit Docker image can be used to run jobs on a cluster, many clusters only
support singularity images. This is because `singularity`_ is designed for
ease-of-use on shared multi-user systems and high performance computing (HPC) environments.
It does not require root privileges to run containers and can be used to run user-defined
containers.
Singularity is compatible with all Docker images. In this section, we describe how to
convert the Orbit Docker image into a singularity image and use it to submit jobs to a cluster.
.. attention::
Cluster setup varies across different institutions. The following instructions have been
tested on the `ETH Zurich Euler`_ cluster, which uses the SLURM workload manager.
The instructions may need to be adapted for other clusters. If you have successfully
adapted the instructions for another cluster, please consider contributing to the
documentation.
Setup Instructions
------------------
In order to export the Docker Image to a singularity image, `apptainer`_ is required.
A detailed overview of the installation procedure for ``apptainer`` can be found in its
`documentation`_. For convenience, we summarize the steps here for a local installation:
.. code:: bash
sudo apt update
sudo apt install -y software-properties-common
sudo add-apt-repository -y ppa:apptainer/ppa
sudo apt update
sudo apt install -y apptainer
For simplicity, we recommend that an SSH connection is set up between the local
development machine and the cluster. Such a connection will simplify the file transfer and prevent
the user cluster password from being requested multiple times.
.. attention::
The workflow has been tested with ``apptainer version 1.2.5-1.el7`` and ``docker version 24.0.7``.
- ``apptainer``:
There have been reported binding issues with previous versions (such as ``apptainer version 1.1.3-1.el7``). Please
ensure that you are using the latest version.
- ``Docker``:
The latest versions (``25.x``) cannot be used as they are not compatible yet with apptainer/ singularity.
We are waiting for an update from the apptainer team. To track this issue, please check the `forum post`_.
Configuring the cluster parameters
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
First, you need to configure the cluster-specific parameters in ``docker/.env.base`` file.
The following describes the parameters that need to be configured:
- ``CLUSTER_ISAAC_SIM_CACHE_DIR``:
The directory on the cluster where the Isaac Sim cache is stored. This directory
has to end on ``docker-isaac-sim``. This directory will be copied to the compute node
and mounted into the singularity container. It should increase the speed of starting
the simulation.
- ``CLUSTER_ORBIT_DIR``:
The directory on the cluster where the orbit code is stored. This directory has to
end on ``orbit``. This directory will be copied to the compute node and mounted into
the singularity container. When a job is submitted, the latest local changes will
be copied to the cluster.
- ``CLUSTER_LOGIN``:
The login to the cluster. Typically, this is the user and cluster names,
e.g., ``[email protected]``.
- ``CLUSTER_SIF_PATH``:
The path on the cluster where the singularity image will be stored. The image will be
copied to the compute node but not uploaded again to the cluster when a job is submitted.
- ``CLUSTER_PYTHON_EXECUTABLE``:
The path within orbit to the Python executable that should be executed in the submitted job.
Exporting to singularity image
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Next, we need to export the Docker image to a singularity image and upload
it to the cluster. This step is only required once when the first job is submitted
or when the Docker image is updated. For instance, due to an upgrade of the Isaac Sim
version, or additional requirements for your project.
To export to a singularity image, execute the following command:
.. code:: bash
./docker/container.sh push [profile]
This command will create a singularity image under ``docker/exports`` directory and
upload it to the defined location on the cluster. Be aware that creating the singularity
image can take a while.
``[profile]`` is an optional argument that specifies the container profile to be used. If no profile is
specified, the default profile ``base`` will be used.
.. note::
By default, the singularity image is created without root access by providing the ``--fakeroot`` flag to
the ``apptainer build`` command. In case the image creation fails, you can try to create it with root
access by removing the flag in ``docker/container.sh``.
Job Submission and Execution
----------------------------
Defining the job parameters
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The job parameters are defined inside the ``docker/cluster/submit_job.sh``.
A typical SLURM operation requires specifying the number of CPUs and GPUs, the memory, and
the time limit. For more information, please check the `SLURM documentation`_.
The default configuration is as follows:
.. literalinclude:: ../../../docker/cluster/submit_job.sh
:language: bash
:lines: 12-19
:linenos:
:lineno-start: 12
An essential requirement for the cluster is that the compute node has access to the internet at all times.
This is required to load assets from the Nucleus server. For some cluster architectures, extra modules
must be loaded to allow internet access.
For instance, on ETH Zurich Euler cluster, the ``eth_proxy`` module needs to be loaded. This can be done
by adding the following line to the ``submit_job.sh`` script:
.. literalinclude:: ../../../docker/cluster/submit_job.sh
:language: bash
:lines: 3-5
:linenos:
:lineno-start: 3
Submitting a job
~~~~~~~~~~~~~~~~
To submit a job on the cluster, the following command can be used:
.. code:: bash
./docker/container.sh job [profile] "argument1" "argument2" ...
This command will copy the latest changes in your code to the cluster and submit a job. Please ensure that
your Python executable's output is stored under ``orbit/logs`` as this directory will be copied again
from the compute node to ``CLUSTER_ORBIT_DIR``.
``[profile]`` is an optional argument that specifies which singularity image corresponding to the container profile
will be used. If no profile is specified, the default profile ``base`` will be used. The profile has be defined
directlty after the ``job`` command. All other arguments are passed to the Python executable. If no profile is
defined, all arguments are passed to the Python executable.
The training arguments are passed to the Python executable. As an example, the standard
ANYmal rough terrain locomotion training can be executed with the following command:
.. code:: bash
./docker/container.sh job --task Isaac-Velocity-Rough-Anymal-C-v0 --headless --video --offscreen_render
The above will, in addition, also render videos of the training progress and store them under ``orbit/logs`` directory.
.. note::
The ``./docker/container.sh job`` command will copy the latest changes in your code to the cluster. However,
it will not delete any files that have been deleted locally. These files will still exist on the cluster
which can lead to issues. In this case, we recommend removing the ``CLUSTER_ORBIT_DIR`` directory on
the cluster and re-run the command.
.. _Singularity: https://docs.sylabs.io/guides/2.6/user-guide/index.html
.. _ETH Zurich Euler: https://scicomp.ethz.ch/wiki/Euler
.. _apptainer: https://apptainer.org/
.. _documentation: www.apptainer.org/docs/admin/main/installation.html#install-ubuntu-packages
.. _SLURM documentation: www.slurm.schedmd.com/sbatch.html
.. _forum post: https://forums.docker.com/t/trouble-after-upgrade-to-docker-ce-25-0-1-on-debian-12/139613
| 7,938 | reStructuredText | 43.105555 | 119 | 0.745528 |
fnuabhimanyu8713/orbit/docs/source/deployment/run_docker_example.rst | Running an example with Docker
==============================
From the root of the ``orbit`` repository, the ``docker`` directory contains all the Docker relevant files. These include the three files
(**Dockerfile**, **docker-compose.yaml**, **.env**) which are used by Docker, and an additional script that we use to interface with them,
**container.sh**.
In this tutorial, we will learn how to use the Orbit Docker container for development. For a detailed description of the Docker setup,
including installation and obtaining access to an Isaac Sim image, please reference the :ref:`deployment-docker`. For a description
of Docker in general, please refer to `their official documentation <https://docs.docker.com/get-started/overview/>`_.
Building the Container
~~~~~~~~~~~~~~~~~~~~~~
To build the Orbit container from the root of the Orbit repository, we will run the following:
.. code-block:: console
./docker/container.sh start
The terminal will first pull the base IsaacSim image, build the Orbit image's additional layers on top of it, and run the Orbit container.
This should take several minutes upon the first build but will be shorter in subsequent runs as Docker's caching prevents repeated work.
If we run the command ``docker container ls`` on the terminal, the output will list the containers that are running on the system. If
everything has been set up correctly, a container with the ``NAME`` **orbit** should appear, similar to below:
.. code-block:: console
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
483d1d5e2def orbit "bash" 30 seconds ago Up 30 seconds orbit
Once the container is up and running, we can enter it from our terminal.
.. code-block:: console
./docker/container.sh enter
On entering the Orbit container, we are in the terminal as the superuser, ``root``. This environment contains a copy of the
Orbit repository, but also has access to the directories and libraries of Isaac Sim. We can run experiments from this environment
using a few convenient aliases that have been put into the ``root`` **.bashrc**. For instance, we have made the **orbit.sh** script
usable from anywhere by typing its alias ``orbit``.
Additionally in the container, we have `bind mounted`_ the ``orbit/source`` directory from the
host machine. This means that if we modify files under this directory from an editor on the host machine, the changes are
reflected immediately within the container without requiring us to rebuild the Docker image.
We will now run a sample script from within the container to demonstrate how to extract artifacts
from the Orbit Docker container.
The Code
~~~~~~~~
The tutorial corresponds to the ``log_time.py`` script in the ``orbit/source/standalone/tutorials/00_sim`` directory.
.. dropdown:: Code for log_time.py
:icon: code
.. literalinclude:: ../../../source/standalone/tutorials/00_sim/log_time.py
:language: python
:emphasize-lines: 46-55, 72-79
:linenos:
The Code Explained
~~~~~~~~~~~~~~~~~~
The Orbit Docker container has several `volumes`_ to facilitate persistent storage between the host computer and the
container. One such volume is the ``/workspace/orbit/logs`` directory.
The ``log_time.py`` script designates this directory as the location to which a ``log.txt`` should be written:
.. literalinclude:: ../../../source/standalone/tutorials/00_sim/log_time.py
:language: python
:start-at: # Specify that the logs must be in logs/docker_tutorial
:end-at: print(f"[INFO] Logging experiment to directory: {log_dir_path}")
As the comments note, :func:`os.path.abspath()` will prepend ``/workspace/orbit`` because in
the Docker container all python execution is done through ``/workspace/orbit/orbit.sh``.
The output will be a file, ``log.txt``, with the ``sim_time`` written on a newline at every simulation step:
.. literalinclude:: ../../../source/standalone/tutorials/00_sim/log_time.py
:language: python
:start-at: # Prepare to count sim_time
:end-at: sim_time += sim_dt
Executing the Script
~~~~~~~~~~~~~~~~~~~~
We will execute the script to produce a log, adding a ``--headless`` flag to our execution to prevent a GUI:
.. code-block:: bash
orbit -p source/standalone/tutorials/00_sim/log_time.py --headless
Now ``log.txt`` will have been produced at ``/workspace/orbit/logs/docker_tutorial``. If we exit the container
by typing ``exit``, we will return to ``orbit/docker`` in our host terminal environment. We can then enter
the following command to retrieve our logs from the Docker container and put them on our host machine:
.. code-block:: console
./container.sh copy
We will see a terminal readout reporting the artifacts we have retrieved from the container. If we navigate to
``/orbit/docker/artifacts/logs/docker_tutorial``, we will see a copy of the ``log.txt`` file which was produced
by the script above.
Each of the directories under ``artifacts`` corresponds to Docker `volumes`_ mapped to directories
within the container and the ``container.sh copy`` command copies them from those `volumes`_ to these directories.
We could return to the Orbit Docker terminal environment by running ``container.sh enter`` again,
but we have retrieved our logs and wish to go inspect them. We can stop the Orbit Docker container with the following command:
.. code-block:: console
./container.sh stop
This will bring down the Docker Orbit container. The image will persist and remain available for further use, as will
the contents of any `volumes`_. If we wish to free up the disk space taken by the image, (~20.1GB), and do not mind repeating
the build process when we next run ``./container.sh start``, we may enter the following command to delete the **orbit** image:
.. code-block:: console
docker image rm orbit
A subsequent run of ``docker image ls``` will show that the image tagged **orbit** is now gone. We can repeat the process for the
underlying NVIDIA container if we wish to free up more space. If a more powerful method of freeing resources from Docker is desired,
please consult the documentation for the `docker prune`_ commands.
.. _volumes: https://docs.docker.com/storage/volumes/
.. _bind mounted: https://docs.docker.com/storage/bind-mounts/
.. _docker prune: https://docs.docker.com/config/pruning/
| 6,373 | reStructuredText | 43.887324 | 138 | 0.73529 |
fnuabhimanyu8713/orbit/docs/source/deployment/docker.rst | .. _deployment-docker:
Docker Guide
============
.. caution::
Due to the dependency on Isaac Sim docker image, by running this container you are implicitly
agreeing to the `NVIDIA Omniverse EULA`_. If you do not agree to the EULA, do not run this container.
Setup Instructions
------------------
.. note::
The following steps are taken from the NVIDIA Omniverse Isaac Sim documentation on `container installation`_.
They have been added here for the sake of completeness.
Docker and Docker Compose
~~~~~~~~~~~~~~~~~~~~~~~~~
We have tested the container using Docker Engine version 26.0.0 and Docker Compose version 2.25.0
We recommend using these versions or newer.
* To install Docker, please follow the instructions for your operating system on the `Docker website`_.
* To install Docker Compose, please follow the instructions for your operating system on the `docker compose`_ page.
* Follow the post-installation steps for Docker on the `post-installation steps`_ page. These steps allow you to run
Docker without using ``sudo``.
* To build and run GPU-accelerated containers, you also need install the `NVIDIA Container Toolkit`_.
Please follow the instructions on the `Container Toolkit website`_ for installation steps.
Obtaining the Isaac Sim Container
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Get access to the `Isaac Sim container`_ by joining the NVIDIA Developer Program credentials.
* Generate your `NGC API key`_ to access locked container images from NVIDIA GPU Cloud (NGC).
* This step requires you to create an NGC account if you do not already have one.
* You would also need to install the NGC CLI to perform operations from the command line.
* Once you have your generated API key and have installed the NGC CLI, you need to log in to NGC
from the terminal.
.. code:: bash
ngc config set
* Use the command line to pull the Isaac Sim container image from NGC.
.. code:: bash
docker login nvcr.io
* For the username, enter ``$oauthtoken`` exactly as shown. It is a special username that is used to
authenticate with NGC.
.. code:: text
Username: $oauthtoken
Password: <Your NGC API Key>
Directory Organization
----------------------
The root of the Orbit repository contains the ``docker`` directory that has various files and scripts
needed to run Orbit inside a Docker container. A subset of these are summarized below:
* ``Dockerfile.base``: Defines the orbit image by overlaying Orbit dependencies onto the Isaac Sim Docker image.
``Dockerfiles`` which end with something else, (i.e. ``Dockerfile.ros2``) build an `image_extension <#orbit-image-extensions>`_.
* ``docker-compose.yaml``: Creates mounts to allow direct editing of Orbit code from the host machine that runs
the container. It also creates several named volumes such as ``isaac-cache-kit`` to
store frequently re-used resources compiled by Isaac Sim, such as shaders, and to retain logs, data, and documents.
* ``base.env``: Stores environment variables required for the ``base`` build process and the container itself. ``.env``
files which end with something else (i.e. ``.env.ros2``) define these for `image_extension <#orbit-image-extensions>`_.
* ``container.sh``: A script that wraps the ``docker compose`` command to build the image and run the container.
Running the Container
---------------------
.. note::
The docker container copies all the files from the repository into the container at the
location ``/workspace/orbit`` at build time. This means that any changes made to the files in the container would not
normally be reflected in the repository after the image has been built, i.e. after ``./container.sh start`` is run.
For a faster development cycle, we mount the following directories in the Orbit repository into the container
so that you can edit their files from the host machine:
* ``source``: This is the directory that contains the Orbit source code.
* ``docs``: This is the directory that contains the source code for Orbit documentation. This is overlaid except
for the ``_build`` subdirectory where build artifacts are stored.
The script ``container.sh`` wraps around three basic ``docker compose`` commands. Each can accept an `image_extension argument <#orbit-image-extensions>`_,
or else they will default to image_extension ``base``:
1. ``start``: This builds the image and brings up the container in detached mode (i.e. in the background).
2. ``enter``: This begins a new bash process in an existing orbit container, and which can be exited
without bringing down the container.
3. ``copy``: This copies the ``logs``, ``data_storage`` and ``docs/_build`` artifacts, from the ``orbit-logs``, ``orbit-data`` and ``orbit-docs``
volumes respectively, to the ``docker/artifacts`` directory. These artifacts persist between docker
container instances and are shared between image extensions.
4. ``stop``: This brings down the container and removes it.
The following shows how to launch the container in a detached state and enter it:
.. code:: bash
# Launch the container in detached mode
# We don't pass an image extension arg, so it defaults to 'base'
./docker/container.sh start
# Enter the container
# We pass 'base' explicitly, but if we hadn't it would default to 'base'
./docker/container.sh enter base
To copy files from the base container to the host machine, you can use the following command:
.. code:: bash
# Copy the file /workspace/orbit/logs to the current directory
docker cp orbit-base:/workspace/orbit/logs .
The script ``container.sh`` provides a wrapper around this command to copy the ``logs`` , ``data_storage`` and ``docs/_build``
directories to the ``docker/artifacts`` directory. This is useful for copying the logs, data and documentation:
.. code::
# stop the container
./docker/container.sh stop
Python Interpreter
~~~~~~~~~~~~~~~~~~
The container uses the Python interpreter provided by Isaac Sim. This interpreter is located at
``/isaac-sim/python.sh``. We set aliases inside the container to make it easier to run the Python
interpreter. You can use the following commands to run the Python interpreter:
.. code:: bash
# Run the Python interpreter -> points to /isaac-sim/python.sh
python
Understanding the mounted volumes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The ``docker-compose.yaml`` file creates several named volumes that are mounted to the container.
These are summarized below:
* ``isaac-cache-kit``: This volume is used to store cached Kit resources (`/isaac-sim/kit/cache` in container)
* ``isaac-cache-ov``: This volume is used to store cached OV resources (`/root/.cache/ov` in container)
* ``isaac-cache-pip``: This volume is used to store cached pip resources (`/root/.cache/pip`` in container)
* ``isaac-cache-gl``: This volume is used to store cached GLCache resources (`/root/.cache/nvidia/GLCache` in container)
* ``isaac-cache-compute``: This volume is used to store cached compute resources (`/root/.nv/ComputeCache` in container)
* ``isaac-logs``: This volume is used to store logs generated by Omniverse. (`/root/.nvidia-omniverse/logs` in container)
* ``isaac-carb-logs``: This volume is used to store logs generated by carb. (`/isaac-sim/kit/logs/Kit/Isaac-Sim` in container)
* ``isaac-data``: This volume is used to store data generated by Omniverse. (`/root/.local/share/ov/data` in container)
* ``isaac-docs``: This volume is used to store documents generated by Omniverse. (`/root/Documents` in container)
* ``orbit-docs``: This volume is used to store documentation of Orbit when built inside the container. (`/workspace/orbit/docs/_build` in container)
* ``orbit-logs``: This volume is used to store logs generated by Orbit workflows when run inside the container. (`/workspace/orbit/logs` in container)
* ``orbit-data``: This volume is used to store whatever data users may want to preserve between container runs. (`/workspace/orbit/data_storage` in container)
To view the contents of these volumes, you can use the following command:
.. code:: bash
# list all volumes
docker volume ls
# inspect a specific volume, e.g. isaac-cache-kit
docker volume inspect isaac-cache-kit
Orbit Image Extensions
----------------------
The produced image depends upon the arguments passed to ``./container.sh start`` and ``./container.sh stop``. These
commands accept an ``image_extension`` as an additional argument. If no argument is passed, then these
commands default to ``base``. Currently, the only valid ``image_extension`` arguments are (``base``, ``ros2``).
Only one ``image_extension`` can be passed at a time, and the produced container will be named ``orbit``.
.. code:: bash
# start base by default
./container.sh start
# stop base explicitly
./container.sh stop base
# start ros2 container
./container.sh start ros2
# stop ros2 container
./container.sh stop ros2
The passed ``image_extension`` argument will build the image defined in ``Dockerfile.${image_extension}``,
with the corresponding `profile`_ in the ``docker-compose.yaml`` and the envars from ``.env.${image_extension}``
in addition to the ``.env.base``, if any.
ROS2 Image Extension
~~~~~~~~~~~~~~~~~~~~
In ``Dockerfile.ros2``, the container installs ROS2 Humble via an `apt package`_, and it is sourced in the ``.bashrc``.
The exact version is specified by the variable ``ROS_APT_PACKAGE`` in the ``.env.ros2`` file,
defaulting to ``ros-base``. Other relevant ROS2 variables are also specified in the ``.env.ros2`` file,
including variables defining the `various middleware`_ options. The container defaults to ``FastRTPS``, but ``CylconeDDS``
is also supported. Each of these middlewares can be `tuned`_ using their corresponding ``.xml`` files under ``docker/.ros``.
Known Issues
------------
Invalid mount config for type "bind"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you see the following error when building the container:
.. code:: text
β Container orbit Creating 0.0s
Error response from daemon: invalid mount config for type "bind": bind source path does not exist: ${HOME}/.Xauthority
This means that the ``.Xauthority`` file is not present in the home directory of the host machine.
The portion of the docker-compose.yaml that enables this is commented out by default, so this shouldn't
happen unless it has been altered. This file is required for X11 forwarding to work. To fix this, you can
create an empty ``.Xauthority`` file in your home directory.
.. code:: bash
touch ${HOME}/.Xauthority
A similar error but requires a different fix:
.. code:: text
β Container orbit Creating 0.0s
Error response from daemon: invalid mount config for type "bind": bind source path does not exist: /tmp/.X11-unix
This means that the folder/files are either not present or not accessible on the host machine.
The portion of the docker-compose.yaml that enables this is commented out by default, so this
shouldn't happen unless it has been altered. This usually happens when you have multiple docker
versions installed on your machine. To fix this, you can try the following:
* Remove all docker versions from your machine.
.. code:: bash
sudo apt remove docker*
sudo apt remove docker docker-engine docker.io containerd runc docker-desktop docker-compose-plugin
sudo snap remove docker
sudo apt clean autoclean && sudo apt autoremove --yes
* Install the latest version of docker based on the instructions in the setup section.
WebRTC and WebSocket Streaming
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When streaming the GUI from Isaac Sim, there are `several streaming clients`_ available. There is a `known issue`_ when
attempting to use WebRTC streaming client on Google Chrome and Safari while running Isaac Sim inside a container.
To avoid this problem, we suggest using either the Native Streaming Client or WebSocket options, or using the
Mozilla Firefox browser on which WebRTC works.
Streaming is the only supported method for visualizing the Isaac GUI from within the container. The Omniverse Streaming Client
is freely available from the Omniverse app, and is easy to use. The other streaming methods similarly require only a web browser.
If users want to use X11 forwarding in order to have the apps behave as local GUI windows, they can uncomment the relevant portions
in docker-compose.yaml.
.. _`NVIDIA Omniverse EULA`: https://docs.omniverse.nvidia.com/platform/latest/common/NVIDIA_Omniverse_License_Agreement.html
.. _`container installation`: https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_container.html
.. _`Docker website`: https://docs.docker.com/desktop/install/linux-install/
.. _`docker compose`: https://docs.docker.com/compose/install/linux/#install-using-the-repository
.. _`NVIDIA Container Toolkit`: https://github.com/NVIDIA/nvidia-container-toolkit
.. _`Container Toolkit website`: https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html
.. _`post-installation steps`: https://docs.docker.com/engine/install/linux-postinstall/
.. _`Isaac Sim container`: https://catalog.ngc.nvidia.com/orgs/nvidia/containers/isaac-sim
.. _`NGC API key`: https://docs.nvidia.com/ngc/gpu-cloud/ngc-user-guide/index.html#generating-api-key
.. _`several streaming clients`: https://docs.omniverse.nvidia.com/isaacsim/latest/installation/manual_livestream_clients.html
.. _`known issue`: https://forums.developer.nvidia.com/t/unable-to-use-webrtc-when-i-run-runheadless-webrtc-sh-in-remote-headless-container/222916
.. _`profile`: https://docs.docker.com/compose/compose-file/15-profiles/
.. _`apt package`: https://docs.ros.org/en/humble/Installation/Ubuntu-Install-Debians.html#install-ros-2-packages
.. _`various middleware`: https://docs.ros.org/en/humble/How-To-Guides/Working-with-multiple-RMW-implementations.html
.. _`tuned`: https://docs.ros.org/en/foxy/How-To-Guides/DDS-tuning.html
| 14,374 | reStructuredText | 49.438596 | 204 | 0.714693 |
fnuabhimanyu8713/orbit/docs/source/deployment/index.rst | Container Deployment
====================
Docker is a tool that allows for the creation of containers, which are isolated environments that can
be used to run applications. They are useful for ensuring that an application can run on any machine
that has Docker installed, regardless of the host machine's operating system or installed libraries.
We include a Dockerfile and docker-compose.yaml file that can be used to build a Docker image that
contains Orbit and all of its dependencies. This image can then be used to run Orbit in a container.
The Dockerfile is based on the Isaac Sim image provided by NVIDIA, which includes the Omniverse
application launcher and the Isaac Sim application. The Dockerfile installs Orbit and its dependencies
on top of this image.
The following guides provide instructions for building the Docker image and running Orbit in a
container.
.. toctree::
:maxdepth: 1
docker
cluster
run_docker_example
| 946 | reStructuredText | 40.173911 | 102 | 0.788584 |
fnuabhimanyu8713/orbit/docs/source/refs/migration.rst | Migration Guide (Isaac Sim)
===========================
Moving from Isaac Sim 2022.2.1 to 2023.1.0 brings in a number of changes to the
APIs and the way the application is built. This document outlines the changes
and how to migrate your code to the new APIs. Many of these changes attribute to
the underlying Omniverse Kit upgrade from 104.2 to 105.1. The new upgrade brings
the following notable changes:
* Update to USD 22.11
* Upgrading the Python from 3.7 to 3.10
.. warning::
This document is a work in progress and will be updated as we move closer
to the release of Isaac Sim 2023.1.0.
Renaming of PhysX Flatcache to PhysX Fabric
-------------------------------------------
The PhysX Flatcache has been renamed to PhysX Fabric. The new name is more
descriptive of the functionality and is consistent with the naming convention
used by Omniverse called `Fabric`_. Consequently, the Python module name has
also been changed from :mod:`omni.physxflatcache` to :mod:`omni.physxfabric`.
Following this, on the Isaac Sim side, various renaming have occurred:
* The parameter passed to :class:`SimulationContext` constructor via the keyword :obj:`sim_params`
now expects the key ``use_fabric`` instead of ``use_flatcache``.
* The Python attribute :attr:`SimulationContext.get_physics_context().use_flatcache` is now
:attr:`SimulationContext.get_physics_context().use_fabric`.
* The Python function :meth:`SimulationContext.get_physics_context().enable_flatcache` is now
:meth:`SimulationContext.get_physics_context().enable_fabric`.
Renaming of the URDF and MJCF Importers
---------------------------------------
Starting from Isaac Sim 2023.1, the URDF and MJCF importers have been renamed to be more consistent
with the other asset importers in Omniverse. The importers are now available on NVIDIA-Omniverse GitHub
as open source projects.
Due to the extension name change, the Python module names have also been changed:
* URDF Importer: :mod:`omni.importer.urdf` (previously :mod:`omni.isaac.urdf`)
* MJCF Importer: :mod:`omni.importer.mjcf` (previously :mod:`omni.isaac.mjcf`)
Deprecation of :class:`UsdLux.Light` API
----------------------------------------
As highlighted in the release notes of `USD 22.11`_, the ``UsdLux.Light`` API has
been deprecated in favor of the new ``UsdLuxLightAPI`` API. In the new API the attributes
are prefixed with ``inputs:``. For example, the ``intensity`` attribute is now available as
``inputs:intensity``.
The following example shows how to create a sphere light using the old API and
the new API.
.. dropdown:: Code for Isaac Sim 2022.2.1 and below
:icon: code
.. code-block:: python
import omni.isaac.core.utils.prims as prim_utils
prim_utils.create_prim(
"/World/Light/GreySphere",
"SphereLight",
translation=(4.5, 3.5, 10.0),
attributes={"radius": 2.5, "intensity": 600.0, "color": (0.75, 0.75, 0.75)},
)
.. dropdown:: Code for Isaac Sim 2023.1.0 and above
:icon: code
.. code-block:: python
import omni.isaac.core.utils.prims as prim_utils
prim_utils.create_prim(
"/World/Light/WhiteSphere",
"SphereLight",
translation=(-4.5, 3.5, 10.0),
attributes={
"inputs:radius": 2.5,
"inputs:intensity": 600.0,
"inputs:color": (1.0, 1.0, 1.0)
},
)
.. _Fabric: https://docs.omniverse.nvidia.com/kit/docs/usdrt/latest/docs/usd_fabric_usdrt.html
.. _`USD 22.11`: https://github.com/PixarAnimationStudios/OpenUSD/blob/release/CHANGELOG.md
| 3,578 | reStructuredText | 36.28125 | 103 | 0.686138 |
fnuabhimanyu8713/orbit/docs/source/refs/changelog.rst | Extensions Changelog
====================
All notable changes to this project are documented in this file. The format is based on
`Keep a Changelog <https://keepachangelog.com/en/1.0.0/>`__ and this project adheres to
`Semantic Versioning <https://semver.org/spec/v2.0.0.html>`__. For a broader information
about the changes in the framework, please refer to the
`release notes <https://github.com/NVIDIA-Omniverse/orbit/releases/>`__.
Each extension has its own changelog. The changelog for each extension is located in the
``docs`` directory of the extension. The changelog for each extension is also included in
this changelog to make it easier to find the changelog for a specific extension.
omni.isaac.orbit
-----------------
Extension containing the core framework of Orbit.
.. include:: ../../../source/extensions/omni.isaac.orbit/docs/CHANGELOG.rst
:start-line: 3
omni.isaac.orbit_assets
------------------------
Extension for configurations of various assets and sensors for Orbit.
.. include:: ../../../source/extensions/omni.isaac.orbit_assets/docs/CHANGELOG.rst
:start-line: 3
omni.isaac.orbit_tasks
----------------------
Extension containing the environments built using Orbit.
.. include:: ../../../source/extensions/omni.isaac.orbit_tasks/docs/CHANGELOG.rst
:start-line: 3
| 1,311 | reStructuredText | 32.641025 | 89 | 0.710908 |
fnuabhimanyu8713/orbit/docs/source/refs/issues.rst | Known Issues
============
.. attention::
Please also refer to the `Omniverse Isaac Sim documentation`_ for known issues and workarounds.
Stale values after resetting the environment
--------------------------------------------
When resetting the environment, some of the data fields of assets and sensors are not updated.
These include the poses of links in a kinematic chain, the camera images, the contact sensor readings,
and the lidar point clouds. This is a known issue which has to do with the way the PhysX and
rendering engines work in Omniverse.
Many physics engines do a simulation step as a two-level call: ``forward()`` and ``simulate()``,
where the kinematic and dynamic states are updated, respectively. Unfortunately, PhysX has only a
single ``step()`` call where the two operations are combined. Due to computations through GPU
kernels, it is not so straightforward for them to split these operations. Thus, at the moment,
it is not possible to set the root and/or joint states and do a forward call to update the
kinematic states of links. This affects both initialization as well as episodic resets.
Similarly for RTX rendering related sensors (such as cameras), the sensor data is not updated
immediately after setting the state of the sensor. The rendering engine update is bundled with
the simulator's ``step()`` call which only gets called when the simulation is stepped forward.
This means that the sensor data is not updated immediately after a reset and it will hold
outdated values.
While the above is erroneous, there is currently no direct workaround for it. From our experience in
using IsaacGym, the reset values affect the agent learning critically depending on how frequently
the environment terminates. Eventually if the agent is learning successfully, this number drops
and does not affect the performance that critically.
We have made a feature request to the respective Omniverse teams to have complete control
over stepping different parts of the simulation app. However, at this point, there is no set
timeline for this feature request.
Non-determinism in physics simulation
-------------------------------------
Due to GPU work scheduling, there's a possibility that runtime changes to simulation parameters
may alter the order in which operations take place. This occurs because environment updates can
happen while the GPU is occupied with other tasks. Due to the inherent nature of floating-point
numeric storage, any modification to the execution ordering can result in minor changes in the
least significant bits of output data. These changes may lead to divergent execution over the
course of simulating thousands of environments and simulation frames.
An illustrative example of this issue is observed with the runtime domain randomization of object's
physics materials. This process can introduce both determinancy and simulation issues when executed
on the GPU due to the way these parameters are passed from the CPU to the GPU in the lower-level APIs.
Consequently, it is strongly advised to perform this operation only at setup time, before the
environment stepping commences.
For more information, please refer to the `PhysX Determinism documentation`_.
Blank initial frames from the camera
------------------------------------
When using the :class:`omni.isaac.orbit.sensors.Camera` sensor in standalone scripts, the first few frames
may be blank. This is a known issue with the simulator where it needs a few steps to load the material
textures properly and fill up the render targets.
A hack to work around this is to add the following after initializing the camera sensor and setting
its pose:
.. code-block:: python
from omni.isaac.orbit.sim import SimulationContext
sim = SimulationContext.instance()
# note: the number of steps might vary depending on how complicated the scene is.
for _ in range(12):
sim.render()
Using instanceable assets for markers
-------------------------------------
When using `instanceable assets`_ for markers, the markers do not work properly, since Omniverse does not support
instanceable assets when using the :class:`UsdGeom.PointInstancer` schema. This is a known issue and will hopefully
be fixed in a future release.
If you use an instanceable assets for markers, the marker class removes all the physics properties of the asset.
This is then replicated across other references of the same asset since physics properties of instanceable assets
are stored in the instanceable asset's USD file and not in its stage reference's USD file.
.. _instanceable assets: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_gym_instanceable_assets.html
.. _Omniverse Isaac Sim documentation: https://docs.omniverse.nvidia.com/isaacsim/latest/known_issues.html
.. _PhysX Determinism documentation: https://nvidia-omniverse.github.io/PhysX/physx/5.3.1/docs/BestPractices.html#determinism
| 4,937 | reStructuredText | 52.096774 | 125 | 0.774154 |
fnuabhimanyu8713/orbit/docs/source/refs/troubleshooting.rst | Tricks and Troubleshooting
==========================
.. note::
The following lists some of the common tricks and troubleshooting methods that we use in our common workflows.
Please also check the `troubleshooting page on Omniverse
<https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/linux_troubleshooting.html>`__ for more
assistance.
Checking the internal logs from the simulator
---------------------------------------------
When running the simulator from a standalone script, it logs warnings and errors to the terminal. At the same time,
it also logs internal messages to a file. These are useful for debugging and understanding the internal state of the
simulator. Depending on your system, the log file can be found in the locations listed
`here <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_faq.html#common-path-locations>`_.
To obtain the exact location of the log file, you need to check the first few lines of the terminal output when
you run the standalone script. The log file location is printed at the start of the terminal output. For example:
.. code:: bash
[INFO] Using python from: /home/${USER}/git/orbit/_isaac_sim/python.sh
...
Passing the following args to the base kit application: []
Loading user config located at: '.../data/Kit/Isaac-Sim/2023.1/user.config.json'
[Info] [carb] Logging to file: '.../logs/Kit/Isaac-Sim/2023.1/kit_20240328_183346.log'
In the above example, the log file is located at ``.../logs/Kit/Isaac-Sim/2023.1/kit_20240328_183346.log``,
``...`` is the path to the user's log directory. The log file is named ``kit_20240328_183346.log``
You can open this file to check the internal logs from the simulator. Also when reporting issues, please include
this log file to help us debug the issue.
Using CPU Scaling Governor for performance
------------------------------------------
By default on many systems, the CPU frequency governor is set to
βpowersaveβ mode, which sets the CPU to lowest static frequency. To
increase the maximum performance, we recommend setting the CPU frequency
governor to βperformanceβ mode. For more details, please check the the
link
`here <https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/power_management_guide/cpufreq_governors>`__.
.. warning::
We advice not to set the governor to βperformanceβ mode on a system with poor
cooling (such as laptops), since it may cause the system to overheat.
- To view existing ``scaling_governor`` value per CPU:
.. code:: bash
cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
- To change the governor to βperformanceβ mode for each CPU:
.. code:: bash
echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
Observing long load times at the start of the simulation
--------------------------------------------------------
The first time you run the simulator, it will take a long time to load up. This is because the
simulator is compiling shaders and loading assets. Subsequent runs should be faster to start up,
but may still take some time.
Please note that once the Isaac Sim app loads, the environment creation time may scale linearly with
the number of environments. Please expect a longer load time if running with thousands of
environments or if each environment contains a larger number of assets. We are continually working
on improving the time needed for this.
When an instance of Isaac Sim is already running, launching another Isaac Sim instance in a different
process may appear to hang at startup for the first time. Please be patient and give it some time as
the second process will take longer to start up due to slower shader compilation.
Receiving a βPhysX errorβ when running simulation on GPU
--------------------------------------------------------
When using the GPU pipeline, the buffers used for the physics simulation are allocated on the GPU only
once at the start of the simulation. This means that they do not grow dynamically as the number of
collisions or objects in the scene changes. If the number of collisions or objects in the scene
exceeds the size of the buffers, the simulation will fail with an error such as the following:
.. code:: bash
PhysX error: the application need to increase the PxgDynamicsMemoryConfig::foundLostPairsCapacity
parameter to 3072, otherwise the simulation will miss interactions
In this case, you need to increase the size of the buffers passed to the
:class:`~omni.isaac.orbit.sim.SimulationContext` class. The size of the buffers can be increased by setting
the :attr:`~omni.isaac.orbit.sim.PhysxCfg.gpu_found_lost_pairs_capacity` parameter in the
:class:`~omni.isaac.orbit.sim.PhysxCfg` class. For example, to increase the size of the buffers to
4096, you can use the following code:
.. code:: python
import omni.isaac.orbit.sim as sim_utils
sim_cfg = sim_utils.SimulationConfig()
sim_cfg.physx.gpu_found_lost_pairs_capacity = 4096
sim = SimulationContext(sim_params=sim_cfg)
Please see the documentation for :class:`~omni.isaac.orbit.sim.SimulationCfg` for more details
on the parameters that can be used to configure the simulation.
Preventing memory leaks in the simulator
----------------------------------------
Memory leaks in the Isaac Sim simulator can occur when C++ callbacks are registered with Python objects.
This happens when callback functions within classes maintain references to the Python objects they are
associated with. As a result, Python's garbage collection is unable to reclaim memory associated with
these objects, preventing the corresponding C++ objects from being destroyed. Over time, this can lead
to memory leaks and increased resource usage.
To prevent memory leaks in the Isaac Sim simulator, it is essential to use weak references when registering
callbacks with the simulator. This ensures that Python objects can be garbage collected when they are no
longer needed, thereby avoiding memory leaks. The `weakref <https://docs.python.org/3/library/weakref.html>`_
module from the Python standard library can be employed for this purpose.
For example, consider a class with a callback function ``on_event_callback`` that needs to be registered
with the simulator. If you use a strong reference to the ``MyClass`` object when passing the callback,
the reference count of the ``MyClass`` object will be incremented. This prevents the ``MyClass`` object
from being garbage collected when it is no longer needed, i.e., the ``__del__`` destructor will not be
called.
.. code:: python
import omni.kit
class MyClass:
def __init__(self):
app_interface = omni.kit.app.get_app_interface()
self._handle = app_interface.get_post_update_event_stream().create_subscription_to_pop(
self.on_event_callback
)
def __del__(self):
self._handle.unsubscribe()
self._handle = None
def on_event_callback(self, event):
# do something with the message
To fix this issue, it's crucial to employ weak references when registering the callback. While this approach
adds some verbosity to the code, it ensures that the ``MyClass`` object can be garbage collected when no longer
in use. Here's the modified code:
.. code:: python
import omni.kit
import weakref
class MyClass:
def __init__(self):
app_interface = omni.kit.app.get_app_interface()
self._handle = app_interface.get_post_update_event_stream().create_subscription_to_pop(
lambda event, obj=weakref.proxy(self): obj.on_event_callback(event)
)
def __del__(self):
self._handle.unsubscribe()
self._handle = None
def on_event_callback(self, event):
# do something with the message
In this revised code, the weak reference ``weakref.proxy(self)`` is used when registering the callback,
allowing the ``MyClass`` object to be properly garbage collected.
By following this pattern, you can prevent memory leaks and maintain a more efficient and stable simulation.
Understanding the error logs from crashes
-----------------------------------------
Many times the simulator crashes due to a bug in the implementation.
This swamps the terminal with exceptions, some of which are coming from
the python interpreter calling ``__del__()`` destructor of the
simulation application. These typically look like the following:
.. code:: bash
...
[INFO]: Completed setting up the environment...
Traceback (most recent call last):
File "source/standalone/workflows/robomimic/collect_demonstrations.py", line 166, in <module>
main()
File "source/standalone/workflows/robomimic/collect_demonstrations.py", line 126, in main
actions = pre_process_actions(delta_pose, gripper_command)
File "source/standalone/workflows/robomimic/collect_demonstrations.py", line 57, in pre_process_actions
return torch.concat([delta_pose, gripper_vel], dim=1)
TypeError: expected Tensor as element 1 in argument 0, but got int
Exception ignored in: <function _make_registry.<locals>._Registry.__del__ at 0x7f94ac097f80>
Traceback (most recent call last):
File "../orbit/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 103, in __del__
File "../orbit/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 98, in destroy
TypeError: 'NoneType' object is not callable
Exception ignored in: <function _make_registry.<locals>._Registry.__del__ at 0x7f94ac097f80>
Traceback (most recent call last):
File "../orbit/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 103, in __del__
File "../orbit/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 98, in destroy
TypeError: 'NoneType' object is not callable
Exception ignored in: <function SettingChangeSubscription.__del__ at 0x7fa2ea173e60>
Traceback (most recent call last):
File "../orbit/_isaac_sim/kit/kernel/py/omni/kit/app/_impl/__init__.py", line 114, in __del__
AttributeError: 'NoneType' object has no attribute 'get_settings'
Exception ignored in: <function RegisteredActions.__del__ at 0x7f935f5cae60>
Traceback (most recent call last):
File "../orbit/_isaac_sim/extscache/omni.kit.viewport.menubar.lighting-104.0.7/omni/kit/viewport/menubar/lighting/actions.py", line 345, in __del__
File "../orbit/_isaac_sim/extscache/omni.kit.viewport.menubar.lighting-104.0.7/omni/kit/viewport/menubar/lighting/actions.py", line 350, in destroy
TypeError: 'NoneType' object is not callable
2022-12-02 15:41:54 [18,514ms] [Warning] [carb.audio.context] 1 contexts were leaked
../orbit/_isaac_sim/python.sh: line 41: 414372 Segmentation fault (core dumped) $python_exe "$@" $args
There was an error running python
This is a known error with running standalone scripts with the Isaac Sim
simulator. Please scroll above the exceptions thrown with
``registry`` to see the actual error log.
In the above case, the actual error is:
.. code:: bash
Traceback (most recent call last):
File "source/standalone/workflows/robomimic/tools/collect_demonstrations.py", line 166, in <module>
main()
File "source/standalone/workflows/robomimic/tools/collect_demonstrations.py", line 126, in main
actions = pre_process_actions(delta_pose, gripper_command)
File "source/standalone/workflows/robomimic/tools/collect_demonstrations.py", line 57, in pre_process_actions
return torch.concat([delta_pose, gripper_vel], dim=1)
TypeError: expected Tensor as element 1 in argument 0, but got int
| 11,894 | reStructuredText | 47.55102 | 151 | 0.724567 |
fnuabhimanyu8713/orbit/docs/source/refs/bibliography.rst | Bibliography
============
.. bibliography::
| 45 | reStructuredText | 8.199998 | 17 | 0.533333 |
fnuabhimanyu8713/orbit/docs/source/refs/license.rst | .. _license:
License
========
NVIDIA Isaac Sim is available freely under `individual license
<https://www.nvidia.com/en-us/omniverse/download/>`_. For more information
about its license terms, please check `here <https://docs.omniverse.nvidia.com/app_isaacsim/common/NVIDIA_Omniverse_License_Agreement.html#software-support-supplement>`_.
The license files for all its dependencies and included assets are available in its
`documentation <https://docs.omniverse.nvidia.com/app_isaacsim/common/licenses.html>`_.
Orbit framework is open-sourced under the
`BSD-3-Clause license <https://opensource.org/licenses/BSD-3-Clause>`_.
.. code-block:: text
Copyright (c) 2022-2024, The ORBIT Project Developers.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| 2,281 | reStructuredText | 46.541666 | 170 | 0.772907 |
fnuabhimanyu8713/orbit/docs/source/refs/contributing.rst | Contribution Guidelines
=======================
We wholeheartedly welcome contributions to the project to make the framework more mature
and useful for everyone. These may happen in forms of:
* Bug reports: Please report any bugs you find in the `issue tracker <https://github.com/NVIDIA-Omniverse/orbit/issues>`__.
* Feature requests: Please suggest new features you would like to see in the `discussions <https://github.com/NVIDIA-Omniverse/Orbit/discussions>`__.
* Code contributions: Please submit a `pull request <https://github.com/NVIDIA-Omniverse/orbit/pulls>`__.
* Bug fixes
* New features
* Documentation improvements
* Tutorials and tutorial improvements
.. attention::
We prefer GitHub `discussions <https://github.com/NVIDIA-Omniverse/Orbit/discussions>`_ for discussing ideas,
asking questions, conversations and requests for new features.
Please use the
`issue tracker <https://github.com/NVIDIA-Omniverse/orbit/issues>`_ only to track executable pieces of work
with a definite scope and a clear deliverable. These can be fixing bugs, new features, or general updates.
Contributing Code
-----------------
We use `GitHub <https://github.com/NVIDIA-Omniverse/orbit>`__ for code hosting. Please
follow the following steps to contribute code:
1. Create an issue in the `issue tracker <https://github.com/NVIDIA-Omniverse/orbit/issues>`__ to discuss
the changes or additions you would like to make. This helps us to avoid duplicate work and to make
sure that the changes are aligned with the roadmap of the project.
2. Fork the repository.
3. Create a new branch for your changes.
4. Make your changes and commit them.
5. Push your changes to your fork.
6. Submit a pull request to the `main branch <https://github.com/NVIDIA-Omniverse/orbit/compare>`__.
7. Ensure all the checks on the pull request template are performed.
After sending a pull request, the maintainers will review your code and provide feedback.
Please ensure that your code is well-formatted, documented and passes all the tests.
.. tip::
It is important to keep the pull request as small as possible. This makes it easier for the
maintainers to review your code. If you are making multiple changes, please send multiple pull requests.
Large pull requests are difficult to review and may take a long time to merge.
Coding Style
------------
We follow the `Google Style
Guides <https://google.github.io/styleguide/pyguide.html>`__ for the
codebase. For Python code, the PEP guidelines are followed. Most
important ones are `PEP-8 <https://www.python.org/dev/peps/pep-0008/>`__
for code comments and layout,
`PEP-484 <http://www.python.org/dev/peps/pep-0484>`__ and
`PEP-585 <https://www.python.org/dev/peps/pep-0585/>`__ for
type-hinting.
For documentation, we adopt the `Google Style Guide <https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html>`__
for docstrings. We use `Sphinx <https://www.sphinx-doc.org/en/master/>`__ for generating the documentation.
Please make sure that your code is well-documented and follows the guidelines.
Circular Imports
^^^^^^^^^^^^^^^^
Circular imports happen when two modules import each other, which is a common issue in Python.
You can prevent circular imports by adhering to the best practices outlined in this
`StackOverflow post <https://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python>`__.
In general, it is essential to avoid circular imports as they can lead to unpredictable behavior.
However, in our codebase, we encounter circular imports at a sub-package level. This situation arises
due to our specific code structure. We organize classes or functions and their corresponding configuration
objects into separate files. This separation enhances code readability and maintainability. Nevertheless,
it can result in circular imports because, in many configuration objects, we specify classes or functions
as default values using the attributes ``class_type`` and ``func`` respectively.
To address circular imports, we leverage the `typing.TYPE_CHECKING
<https://docs.python.org/3/library/typing.html#typing.TYPE_CHECKING>`_ variable. This special variable is
evaluated only during type-checking, allowing us to import classes or functions in the configuration objects
without triggering circular imports.
It is important to note that this is the sole instance within our codebase where circular imports are used
and are acceptable. In all other scenarios, we adhere to best practices and recommend that you do the same.
Type-hinting
^^^^^^^^^^^^
To make the code more readable, we use `type hints <https://docs.python.org/3/library/typing.html>`__ for
all the functions and classes. This helps in understanding the code and makes it easier to maintain. Following
this practice also helps in catching bugs early with static type checkers like `mypy <https://mypy.readthedocs.io/en/stable/>`__.
To avoid duplication of efforts, we do not specify type hints for the arguments and return values in the docstrings.
However, if your function or class is not self-explanatory, please add a docstring with the type hints.
Tools
^^^^^
We use the following tools for maintaining code quality:
* `pre-commit <https://pre-commit.com/>`__: Runs a list of formatters and linters over the codebase.
* `black <https://black.readthedocs.io/en/stable/>`__: The uncompromising code formatter.
* `flake8 <https://flake8.pycqa.org/en/latest/>`__: A wrapper around PyFlakes, pycodestyle and
McCabe complexity checker.
Please check `here <https://pre-commit.com/#install>`__ for instructions
to set these up. To run over the entire repository, please execute the
following command in the terminal:
.. code:: bash
./orbit.sh --format # or "./orbit.sh -f"
Contributing Documentation
--------------------------
Contributing to the documentation is as easy as contributing to the codebase. All the source files
for the documentation are located in the ``orbit/docs`` directory. The documentation is written in
`reStructuredText <https://docutils.sourceforge.io/rst.html>`__ format.
We use `Sphinx <https://www.sphinx-doc.org/en/master/>`__ with the
`Book Theme <https://sphinx-book-theme.readthedocs.io/en/stable/>`__
for maintaining the documentation.
Sending a pull request for the documentation is the same as sending a pull request for the codebase.
Please follow the steps mentioned in the `Contributing Code`_ section.
.. caution::
To build the documentation, we recommend creating a `virtual environment <https://docs.python.org/3/library/venv.html>`__
to install the dependencies. This can also be a `conda environment <https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html>`__.
To build the documentation, run the following command in the terminal which installs the required python packages and
builds the documentation using the ``docs/Makefile``:
.. code:: bash
./orbit.sh --docs # or "./orbit.sh -d"
The documentation is generated in the ``docs/_build`` directory. To view the documentation, open
the ``index.html`` file in the ``html`` directory. This can be done by running the following command
in the terminal:
.. code:: bash
xdg-open docs/_build/html/index.html
.. hint::
The ``xdg-open`` command is used to open the ``index.html`` file in the default browser. If you are
using a different operating system, you can use the appropriate command to open the file in the browser.
To do a clean build, run the following command in the terminal:
.. code:: bash
rm -rf docs/_build && ./orbit.sh --docs
Contributing assets
-------------------
Currently, we host the assets for the extensions on `NVIDIA Nucleus Server <https://docs.omniverse.nvidia.com/nucleus/latest/index.html>`__.
Nucleus is a cloud-based storage service that allows users to store and share large files. It is
integrated with the `NVIDIA Omniverse Platform <https://developer.nvidia.com/omniverse>`__.
Since all assets are hosted on Nucleus, we do not need to include them in the repository. However,
we need to include the links to the assets in the documentation.
The included assets are part of the `Isaac Sim Content <https://docs.omniverse.nvidia.com/isaacsim/latest/features/environment_setup/assets/usd_assets_overview.html>`__.
To use this content, you need to download the files to a Nucleus server or create an **Isaac** Mount on
a Nucleus server.
Please check the `Isaac Sim documentation <https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_faq.html#assets-and-nucleus>`__
for more information on how to download the assets.
.. attention::
We are currently working on a better way to contribute assets. We will update this section once we
have a solution. In the meantime, please follow the steps mentioned below.
To host your own assets, the current solution is:
1. Create a separate repository for the assets and add it over there
2. Make sure the assets are licensed for use and distribution
3. Include images of the assets in the README file of the repository
4. Send a pull request with a link to the repository
We will then verify the assets, its licensing, and include the assets into the Nucleus server for hosting.
In case you have any questions, please feel free to reach out to us through e-mail or by opening an issue
in the repository.
Maintaining a changelog
-----------------------
Each extension maintains a changelog in the ``CHANGELOG.rst`` file in the ``docs`` directory. The
file is written in `reStructuredText <https://docutils.sourceforge.io/rst.html>`__ format. It
contains a curated, chronologically ordered list of notable changes for each version of the extension.
The goal of this changelog is to help users and contributors see precisely what notable changes have
been made between each release (or version) of the extension. This is a *MUST* for every extension.
For updating the changelog, please follow the following guidelines:
* Each version should have a section with the version number and the release date.
* The version number is updated according to `Semantic Versioning <https://semver.org/>`__. The
release date is the date on which the version is released.
* Each version is divided into subsections based on the type of changes made.
* ``Added``: For new features.
* ``Changed``: For changes in existing functionality.
* ``Deprecated``: For soon-to-be removed features.
* ``Removed``: For now removed features.
* ``Fixed``: For any bug fixes.
* Each change is described in its corresponding sub-section with a bullet point.
* The bullet points are written in the past tense and in imperative mode.
For example, the following is a sample changelog:
.. code:: rst
Changelog
---------
0.1.0 (2021-02-01)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a new feature.
Changed
^^^^^^^
* Changed an existing feature.
Deprecated
^^^^^^^^^^
* Deprecated an existing feature.
Removed
^^^^^^^
* Removed an existing feature.
Fixed
^^^^^
* Fixed a bug.
0.0.1 (2021-01-01)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a new feature.
| 11,201 | reStructuredText | 40.335793 | 169 | 0.744933 |
fnuabhimanyu8713/orbit/assets/hoa_full_body1/full_body1/URDF_description/xacro.py | #! /usr/bin/env python
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# Author: Stuart Glaser
# Modified by Saul Reynolds-Haertle Oct 14 2012 to remove ROS dependencies.
import os.path, sys, os, getopt
import subprocess
from xml.dom.minidom import parse, parseString
import xml.dom
import re
import string
class XacroException(Exception): pass
def isnumber(x):
return hasattr(x, '__int__')
# Better pretty printing of xml
# Taken from http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace/
def fixed_writexml(self, writer, indent="", addindent="", newl=""):
# indent = current indentation
# addindent = indentation to add to higher levels
# newl = newline string
writer.write(indent+"<" + self.tagName)
attrs = self._get_attributes()
a_names = attrs.keys()
#a_names.sort()
sorted(a_names)
for a_name in a_names:
writer.write(" %s=\"" % a_name)
xml.dom.minidom._write_data(writer, attrs[a_name].value)
writer.write("\"")
if self.childNodes:
if len(self.childNodes) == 1 \
and self.childNodes[0].nodeType == xml.dom.minidom.Node.TEXT_NODE:
writer.write(">")
self.childNodes[0].writexml(writer, "", "", "")
writer.write("</%s>%s" % (self.tagName, newl))
return
writer.write(">%s"%(newl))
for node in self.childNodes:
if node.nodeType is not xml.dom.minidom.Node.TEXT_NODE: # 3:
node.writexml(writer,indent+addindent,addindent,newl)
#node.writexml(writer,indent+addindent,addindent,newl)
writer.write("%s</%s>%s" % (indent,self.tagName,newl))
else:
writer.write("/>%s"%(newl))
# replace minidom's function with ours
xml.dom.minidom.Element.writexml = fixed_writexml
class Table:
def __init__(self, parent = None):
self.parent = parent
self.table = {}
def __getitem__(self, key):
if key in self.table:
return self.table[key]
elif self.parent:
return self.parent[key]
else:
raise KeyError(key)
def __setitem__(self, key, value):
self.table[key] = value
def __contains__(self, key):
return \
key in self.table or \
(self.parent and key in self.parent)
class QuickLexer(object):
def __init__(self, **res):
self.str = ""
self.top = None
self.res = []
for k,v in res.items():
self.__setattr__(k, len(self.res))
self.res.append(v)
def lex(self, str):
self.str = str
self.top = None
self.next()
def peek(self):
return self.top
def next(self):
result = self.top
self.top = None
for i in range(len(self.res)):
m = re.match(self.res[i], self.str)
if m:
self.top = (i, m.group(0))
self.str = self.str[m.end():]
break
return result
def first_child_element(elt):
c = elt.firstChild
while c:
if c.nodeType == xml.dom.Node.ELEMENT_NODE:
return c
c = c.nextSibling
return None
def next_sibling_element(elt):
c = elt.nextSibling
while c:
if c.nodeType == xml.dom.Node.ELEMENT_NODE:
return c
c = c.nextSibling
return None
# Pre-order traversal of the elements
def next_element(elt):
child = first_child_element(elt)
if child: return child
while elt and elt.nodeType == xml.dom.Node.ELEMENT_NODE:
next = next_sibling_element(elt)
if next:
return next
elt = elt.parentNode
return None
# Pre-order traversal of all the nodes
def next_node(node):
if node.firstChild:
return node.firstChild
while node:
if node.nextSibling:
return node.nextSibling
node = node.parentNode
return None
def child_elements(elt):
c = elt.firstChild
while c:
if c.nodeType == xml.dom.Node.ELEMENT_NODE:
yield c
c = c.nextSibling
all_includes = []
## @throws XacroException if a parsing error occurs with an included document
def process_includes(doc, base_dir):
namespaces = {}
previous = doc.documentElement
elt = next_element(previous)
while elt:
if elt.tagName == 'include' or elt.tagName == 'xacro:include':
# print("elt.getAttribute('filename'):", elt.getAttribute('filename'))
filename = eval_text(elt.getAttribute('filename'), {})
# print("filename:",filename)
if not os.path.isabs(filename):
filename = os.path.join(base_dir, filename)
f = None
try:
try:
f = open(filename)
except IOError as e:
print(elt)
raise XacroException("included file \"%s\" could not be opened: %s" % (filename, str(e)))
try:
global all_includes
all_includes.append(filename)
included = parse(f)
except Exception as e:
raise XacroException("included file [%s] generated an error during XML parsing: %s"%(filename, str(e)))
finally:
if f: f.close()
# Replaces the include tag with the elements of the included file
for c in child_elements(included.documentElement):
elt.parentNode.insertBefore(c.cloneNode(1), elt)
elt.parentNode.removeChild(elt)
elt = None
# Grabs all the declared namespaces of the included document
for name, value in included.documentElement.attributes.items():
if name.startswith('xmlns:'):
namespaces[name] = value
else:
previous = elt
elt = next_element(previous)
# Makes sure the final document declares all the namespaces of the included documents.
for k,v in namespaces.items():
doc.documentElement.setAttribute(k, v)
# Returns a dictionary: { macro_name => macro_xml_block }
def grab_macros(doc):
macros = {}
previous = doc.documentElement
elt = next_element(previous)
while elt:
if elt.tagName == 'macro' or elt.tagName == 'xacro:macro':
name = elt.getAttribute('name')
macros[name] = elt
macros['xacro:' + name] = elt
elt.parentNode.removeChild(elt)
elt = None
else:
previous = elt
elt = next_element(previous)
return macros
# Returns a Table of the properties
def grab_properties(doc):
table = Table()
previous = doc.documentElement
elt = next_element(previous)
while elt:
if elt.tagName == 'property' or elt.tagName == 'xacro:property':
name = elt.getAttribute('name')
value = None
if elt.hasAttribute('value'):
value = elt.getAttribute('value')
else:
name = '**' + name
value = elt #debug
bad = string.whitespace + "${}"
has_bad = False
for b in bad:
if b in name:
has_bad = True
break
if has_bad:
sys.stderr.write('Property names may not have whitespace, ' +
'"{", "}", or "$" : "' + name + '"')
else:
table[name] = value
elt.parentNode.removeChild(elt)
elt = None
else:
previous = elt
elt = next_element(previous)
return table
def eat_ignore(lex):
while lex.peek() and lex.peek()[0] == lex.IGNORE:
lex.next()
def eval_lit(lex, symbols):
eat_ignore(lex)
if lex.peek()[0] == lex.NUMBER:
return float(lex.next()[1])
if lex.peek()[0] == lex.SYMBOL:
try:
value = symbols[lex.next()[1]]
except KeyError as ex:
#sys.stderr.write("Could not find symbol: %s\n" % str(ex))
raise XacroException("Property wasn't defined: %s" % str(ex))
if not (isnumber(value) or isinstance(value,(str,str))):
print([value], isinstance(value, str), type(value))
raise XacroException("WTF2")
try:
return int(value)
except:
try:
return float(value)
except:
return value
raise XacroException("Bad literal")
def eval_factor(lex, symbols):
eat_ignore(lex)
neg = 1;
if lex.peek()[1] == '-':
lex.next()
neg = -1
if lex.peek()[0] in [lex.NUMBER, lex.SYMBOL]:
return neg * eval_lit(lex, symbols)
if lex.peek()[0] == lex.LPAREN:
lex.next()
eat_ignore(lex)
result = eval_expr(lex, symbols)
eat_ignore(lex)
if lex.next()[0] != lex.RPAREN:
raise XacroException("Unmatched left paren")
eat_ignore(lex)
return neg * result
raise XacroException("Misplaced operator")
def eval_term(lex, symbols):
eat_ignore(lex)
result = 0
if lex.peek()[0] in [lex.NUMBER, lex.SYMBOL, lex.LPAREN] \
or lex.peek()[1] == '-':
result = eval_factor(lex, symbols)
eat_ignore(lex)
while lex.peek() and lex.peek()[1] in ['*', '/']:
op = lex.next()[1]
n = eval_factor(lex, symbols)
if op == '*':
result = float(result) * float(n)
elif op == '/':
result = float(result) / float(n)
else:
raise XacroException("WTF")
eat_ignore(lex)
return result
def eval_expr(lex, symbols):
eat_ignore(lex)
op = None
if lex.peek()[0] == lex.OP:
op = lex.next()[1]
if not op in ['+', '-']:
raise XacroException("Invalid operation. Must be '+' or '-'")
result = eval_term(lex, symbols)
if op == '-':
result = -float(result)
eat_ignore(lex)
while lex.peek() and lex.peek()[1] in ['+', '-']:
op = lex.next()[1]
n = eval_term(lex, symbols)
if op == '+':
result = float(result) + float(n)
if op == '-':
result = float(result) - float(n)
eat_ignore(lex)
return result
def eval_extension(s):
#if s == '$(cwd)':
return os.getcwd()
# try:
# return substitution_args.resolve_args(s, context=substitution_args_context, resolve_anon=False)
# except substitution_args.ArgException as e:
# raise XacroException("Undefined substitution argument", exc=e)
# except ResourceNotFound as e:
# raise XacroException("resource not found:", exc=e)
def eval_text(text, symbols):
def handle_expr(s):
lex = QuickLexer(IGNORE = r"\s+",
NUMBER = r"(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?",
SYMBOL = r"[a-zA-Z_]\w*",
OP = r"[\+\-\*/^]",
LPAREN = r"\(",
RPAREN = r"\)")
lex.lex(s)
return eval_expr(lex, symbols)
def handle_extension(s):
# print("handle_extension", s)
return eval_extension("$(%s)" % s)
results = []
lex = QuickLexer(DOLLAR_DOLLAR_BRACE = r"\$\$+\{",
EXPR = r"\$\{[^\}]*\}",
EXTENSION = r"\$\([^\)]*\)",
TEXT = r"([^\$]|\$[^{(]|\$$)+")
lex.lex(text)
while lex.peek():
if lex.peek()[0] == lex.EXPR:
results.append(handle_expr(lex.next()[1][2:-1]))
# print("1:", results)
elif lex.peek()[0] == lex.EXTENSION:
results.append(handle_extension(lex.next()[1][2:-1]))
# print("2:",results)
elif lex.peek()[0] == lex.TEXT:
results.append(lex.next()[1])
# print("3:",results)
elif lex.peek()[0] == lex.DOLLAR_DOLLAR_BRACE:
results.append(lex.next()[1][1:])
# print("4:",results)
# print(results)
return ''.join(map(str, results))
# Expands macros, replaces properties, and evaluates expressions
def eval_all(root, macros, symbols):
# Evaluates the attributes for the root node
for at in root.attributes.items():
result = eval_text(at[1], symbols)
root.setAttribute(at[0], result)
previous = root
node = next_node(previous)
while node:
if node.nodeType == xml.dom.Node.ELEMENT_NODE:
if node.tagName in macros:
body = macros[node.tagName].cloneNode(deep = True)
params = body.getAttribute('params').split()
# Expands the macro
scoped = Table(symbols)
for name,value in node.attributes.items():
if not name in params:
raise XacroException("Invalid parameter \"%s\" while expanding macro \"%s\"" % \
(str(name), str(node.tagName)))
params.remove(name)
scoped[name] = eval_text(value, symbols)
# Pulls out the block arguments, in order
cloned = node.cloneNode(deep = True)
eval_all(cloned, macros, symbols)
block = cloned.firstChild
for param in params[:]:
if param[0] == '*':
while block and block.nodeType != xml.dom.Node.ELEMENT_NODE:
block = block.nextSibling
if not block:
raise XacroException("Not enough blocks while evaluating macro %s" % str(node.tagName))
params.remove(param)
scoped[param] = block
block = block.nextSibling
if params:
raise XacroException("Some parameters were not set for macro %s" % \
str(node.tagName))
eval_all(body, macros, scoped)
# Replaces the macro node with the expansion
for e in list(child_elements(body)): # Ew
node.parentNode.insertBefore(e, node)
node.parentNode.removeChild(node)
node = None
elif node.tagName == 'insert_block' or node.tagName == 'xacro:insert_block':
name = node.getAttribute('name')
if ("**" + name) in symbols:
# Multi-block
block = symbols['**' + name]
for e in list(child_elements(block)):
node.parentNode.insertBefore(e.cloneNode(deep=True), node)
node.parentNode.removeChild(node)
elif ("*" + name) in symbols:
# Single block
block = symbols['*' + name]
node.parentNode.insertBefore(block.cloneNode(deep=True), node)
node.parentNode.removeChild(node)
else:
raise XacroException("Block \"%s\" was never declared" % name)
node = None
else:
# Evals the attributes
for at in node.attributes.items():
result = eval_text(at[1], symbols)
node.setAttribute(at[0], result)
previous = node
elif node.nodeType == xml.dom.Node.TEXT_NODE:
node.data = eval_text(node.data, symbols)
previous = node
else:
previous = node
node = next_node(previous)
return macros
# Expands everything except includes
def eval_self_contained(doc):
macros = grab_macros(doc)
symbols = grab_properties(doc)
eval_all(doc.documentElement, macros, symbols)
def print_usage(exit_code = 0):
print("Usage: %s [-o <output>] <input>" % 'xacro.py')
print(" %s --deps Prints dependencies" % 'xacro.py')
print(" %s --includes Only evalutes includes" % 'xacro.py')
sys.exit(exit_code)
def main():
# print("dir:",os.path.dirname(sys.argv[2]))
# sys.exit(0)
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "ho:", ['deps', 'includes'])
except getopt.GetoptError as err:
print(str(err))
print_usage(2)
just_deps = False
just_includes = False
output = sys.stdout
for o, a in opts:
if o == '-h':
print_usage(0)
elif o == '-o':
output = open(a, 'w')
elif o == '--deps':
just_deps = True
elif o == '--includes':
just_includes = True
if len(args) < 1:
print("No input given")
print_usage(2)
f = open(args[0])
# print(args[0])
# sys.exit(0)
doc = None
try:
doc = parse(f)
except xml.parsers.expat.ExpatError:
sys.stderr.write("Expat parsing error. Check that:\n")
sys.stderr.write(" - Your XML is correctly formed\n")
sys.stderr.write(" - You have the xacro xmlns declaration: " +
"xmlns:xacro=\"http://www.ros.org/wiki/xacro\"\n")
sys.stderr.write("\n")
raise
finally:
f.close()
# print(type(doc))
# print(opts, args)
# print("dir:",os.path.dirname(sys.argv[2]))
# sys.exit(0)
process_includes(doc, os.path.dirname(sys.argv[2]))
if just_deps:
for inc in all_includes:
sys.stdout.write(inc + " ")
sys.stdout.write("\n")
elif just_includes:
doc.writexml(output)
print()
else:
eval_self_contained(doc)
banner = [xml.dom.minidom.Comment(c) for c in
[" %s " % ('='*83),
" | This document was autogenerated by xacro from %-30s | " % args[0],
" | EDITING THIS FILE BY HAND IS NOT RECOMMENDED %-30s | " % "",
" %s " % ('='*83)]]
first = doc.firstChild
for comment in banner:
doc.insertBefore(comment, first)
output.write(doc.toprettyxml(indent = ' '))
#doc.writexml(output, newl = "\n")
print()
if __name__ == "__main__":
main()
| 19,812 | Python | 32.076795 | 123 | 0.545629 |
fnuabhimanyu8713/orbit/assets/hoa_full_body1/full_body1/URDF_description/launch/controller.yaml | URDF_controller:
# Publish all joint states -----------------------------------
joint_state_controller:
type: joint_state_controller/JointStateController
publish_rate: 50
# Position Controllers --------------------------------------
Revolute 2_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 2
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 3_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 3
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 4_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 4
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 5_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 5
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 6_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 6
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 7_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 7
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 8_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 8
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 9_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 9
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 10_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 10
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 11_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 11
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 14_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 14
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 17_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 17
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 20_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 20
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 21_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 21
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 22_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 22
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 23_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 23
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 24_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 24
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 25_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 25
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 26_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 26
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 27_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 27
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 28_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 28
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 29_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 29
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 30_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 30
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 31_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 31
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 32_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 32
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 33_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 33
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 34_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 34
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 35_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 35
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 36_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 36
pid: {p: 100.0, i: 0.01, d: 10.0}
| 4,553 | YAML | 35.725806 | 64 | 0.681309 |
fnuabhimanyu8713/orbit/assets/hoa_full_body1/full_body1/URDF_description/meshes (copy)/mona_v2.xml | <mujoco model="URDF">
<compiler angle="radian"/>
<asset>
<mesh name="base_link" file="base_link.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Sp2rR_fork_v6_1" file="shell_Sp2rR_fork_v6_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Sr2wR_fork_v14_1" file="shell_Sr2wR_fork_v14_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Humerus_Fork_v8_1" file="shell_Humerus_Fork_v8_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Ulna_Fork_v5_1" file="shell_Ulna_Fork_v5_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Radius_gen2_v31_1" file="shell_Radius_gen2_v31_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Sp2rR_fork_v6_Mirror__1" file="shell_Sp2rR_fork_v6_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Sr2wR_fork_v14_Mirror__1" file="shell_Sr2wR_fork_v14_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Humerus_Fork_v8_Mirror__1" file="shell_Humerus_Fork_v8_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Ulna_Fork_v5_Mirror__1" file="shell_Ulna_Fork_v5_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Radius_gen2_v31_Mirror__1" file="shell_Radius_gen2_v31_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="hand_secondIter_v9_Mirror__1" file="hand_secondIter_v9_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="hand_secondIter_v9_1" file="hand_secondIter_v9_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Fr2w_Fork_v6_1" file="shell_Fr2w_Fork_v6_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Fp2r_Fork_dual_v3_1" file="shell_Fp2r_Fork_dual_v3_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_torso_1" file="shell_torso_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="scaphoid_1" file="scaphoid_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="scaphoid_Mirror__1" file="scaphoid_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Hp2r_Fork_v9_1" file="shell_Hp2r_Fork_v9_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Hr2w_Fork_v16_1" file="shell_Hr2w_Fork_v16_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Femur_fork_v4_1" file="shell_Femur_fork_v4_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Tibia_Alt_fork_v12_1" file="shell_Tibia_Alt_fork_v12_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Ap2r_v5_1" file="shell_Ap2r_v5_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_foot_v16_Mirror__1" file="shell_foot_v16_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Hp2r_Fork_v9_Mirror__1" file="shell_Hp2r_Fork_v9_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Hr2w_Fork_v16_Mirror__1" file="shell_Hr2w_Fork_v16_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Femur_fork_v4_Mirror__1" file="shell_Femur_fork_v4_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Tibia_Alt_fork_v12_Mirror__1" file="shell_Tibia_Alt_fork_v12_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Ap2r_v5_Mirror__1" file="shell_Ap2r_v5_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_foot_v16_1" file="shell_foot_v16_1.stl" scale="0.001 0.001 0.001"/>
</asset>
<worldbody>
<geom type="mesh" rgba="0.7 0.7 0.7 1" mesh="base_link"/>
<body name="shell_Fr2w_Fork_v6_1" pos="0 0 0.08448">
<inertial pos="-0.0134037 -1.28947e-07 0.0897088" quat="0.410834 0.575513 0.575513 0.410834" mass="1.64424" diaginertia="0.011252 0.00887014 0.00594086"/>
<joint name="Revolute 20" pos="0 0 0" axis="0 0 1" range="-1.5708 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0 0 -0.08448" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Fr2w_Fork_v6_1"/>
<body name="shell_Fp2r_Fork_dual_v3_1" pos="0.0305 0 0.1522">
<inertial pos="-0.000954547 -0.00417876 6.73482e-08" quat="0.482905 0.482905 0.516529 0.516529" mass="0.146163" diaginertia="0.000454606 0.000433 0.000320394"/>
<joint name="Revolute 21" pos="0 0 0" axis="1 0 0" range="-0.628319 0.628319" actuatorfrcrange="-100 100"/>
<geom pos="-0.0305 0 -0.23668" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Fp2r_Fork_dual_v3_1"/>
<body name="shell_torso_1" pos="0.000874 0 0">
<inertial pos="-0.0319595 5.80206e-07 0.208297" quat="0.999281 0 -0.0379211 0" mass="5.20486" diaginertia="0.112904 0.094706 0.0563995"/>
<joint name="Revolute 22" pos="0 0 0" axis="0 1 0" range="-0.287979 0.907571" actuatorfrcrange="-100 100"/>
<geom pos="-0.031374 0 -0.23668" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_torso_1"/>
<body name="shell_Sp2rR_fork_v6_1" pos="-0.032 -0.1279 0.3292">
<inertial pos="0.00210198 -0.0643948 6.20677e-07" quat="0.706978 0.706978 0.0134708 0.0134708" mass="0.750073" diaginertia="0.00212818 0.001773 0.00131382"/>
<joint name="Revolute 2" pos="0 0 0" axis="0 1 0" range="-3.14159 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0.000626 0.1279 -0.56588" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Sp2rR_fork_v6_1"/>
<body name="shell_Sr2wR_fork_v14_1" pos="0.00102 -0.08839 0">
<inertial pos="-0.00676748 0.000476725 -0.0637433" quat="0.699228 -0.101201 -0.105312 0.69982" mass="0.978546" diaginertia="0.00437906 0.00352726 0.00260168"/>
<joint name="Revolute 3" pos="0 0 0" axis="1 0 0" range="-2.26893 0.174533" actuatorfrcrange="-100 100"/>
<geom pos="-0.000394 0.21629 -0.56588" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Sr2wR_fork_v14_1"/>
<body name="shell_Humerus_Fork_v8_1" pos="-0.00105 0 -0.146483">
<inertial pos="-0.00349646 0.00263963 -0.104404" quat="0.705069 0.00551324 -0.011204 0.709029" mass="0.876673" diaginertia="0.00397843 0.00370214 0.00144144"/>
<joint name="Revolute 4" pos="0 0 0" axis="0 0 1" range="-1.5708 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0.000656 0.21629 -0.419397" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Humerus_Fork_v8_1"/>
<body name="shell_Ulna_Fork_v5_1" pos="0 0.00077 -0.15139">
<inertial pos="9.62901e-06 -0.00344448 -0.0452394" quat="0.913229 0.407446 0 0" mass="0.698159" diaginertia="0.002413 0.00185007 0.00165493"/>
<joint name="Revolute 5" pos="0 0 0" axis="0 1 0" range="-2.26893 0" actuatorfrcrange="-100 100"/>
<geom pos="0.000656 0.21552 -0.268007" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Ulna_Fork_v5_1"/>
<body name="shell_Radius_gen2_v31_1" pos="0 -0.00095 -0.100482">
<inertial pos="9.37117e-06 -0.00117845 -0.124991" quat="0.999951 -0.00993344 0 0" mass="0.876922" diaginertia="0.003786 0.00344577 0.00148223"/>
<joint name="Revolute 6" pos="0 0 0" axis="0 0 1" range="-3.14159 0" actuatorfrcrange="-100 100"/>
<geom pos="0.000656 0.21647 -0.167525" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Radius_gen2_v31_1"/>
<body name="scaphoid_1" pos="6.5e-05 0 -0.207787">
<inertial pos="-1.58999e-07 -1.3481e-08 4.05809e-07" quat="0.5 0.5 -0.5 0.5" mass="0.0259174" diaginertia="7e-06 4e-06 4e-06"/>
<joint name="Revolute 23" pos="0 0 0" axis="0 1 0" range="-0.523599 0.523599" actuatorfrcrange="-100 100"/>
<geom pos="0.000591 0.21647 0.040262" type="mesh" rgba="0.7 0.7 0.7 1" mesh="scaphoid_1"/>
<body name="hand_secondIter_v9_Mirror__1">
<inertial pos="-0.00343585 0.00506416 -0.0641579" quat="0.978592 -0.031701 0.00787655 0.203201" mass="0.340548" diaginertia="0.00134431 0.00105859 0.0004321"/>
<joint name="Revolute 14" pos="0 0 0" axis="1 0 0" range="-0.698132 0.349066" actuatorfrcrange="-100 100"/>
<geom pos="0.000591 0.21647 0.040262" type="mesh" rgba="0.7 0.7 0.7 1" mesh="hand_secondIter_v9_Mirror__1"/>
</body>
</body>
</body>
</body>
</body>
</body>
</body>
<body name="shell_Sp2rR_fork_v6_Mirror__1" pos="-0.032 0.1279 0.3292">
<inertial pos="0.00210198 0.0643948 6.20677e-07" quat="0.706978 0.706978 -0.0134708 -0.0134708" mass="0.750073" diaginertia="0.00212818 0.001773 0.00131382"/>
<joint name="Revolute 7" pos="0 0 0" axis="0 1 0" range="-3.14159 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0.000626 -0.1279 -0.56588" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Sp2rR_fork_v6_Mirror__1"/>
<body name="shell_Sr2wR_fork_v14_Mirror__1" pos="0.00102 0.08839 0">
<inertial pos="-0.00676748 -0.000476725 -0.0637433" quat="0.69982 -0.105312 -0.101201 0.699228" mass="0.978546" diaginertia="0.00437906 0.00352726 0.00260168"/>
<joint name="Revolute 8" pos="0 0 0" axis="1 0 0" range="-0.174533 2.26893" actuatorfrcrange="-100 100"/>
<geom pos="-0.000394 -0.21629 -0.56588" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Sr2wR_fork_v14_Mirror__1"/>
<body name="shell_Humerus_Fork_v8_Mirror__1" pos="-0.00105 0 -0.146483">
<inertial pos="-0.00349646 -0.00263963 -0.104404" quat="0.709029 -0.011204 0.00551324 0.705069" mass="0.876673" diaginertia="0.00397843 0.00370214 0.00144144"/>
<joint name="Revolute 9" pos="0 0 0" axis="0 0 1" range="-1.5708 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0.000656 -0.21629 -0.419397" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Humerus_Fork_v8_Mirror__1"/>
<body name="shell_Ulna_Fork_v5_Mirror__1" pos="0 -0.00077 -0.15139">
<inertial pos="9.62901e-06 0.00344448 -0.0452394" quat="0.407446 0.913229 0 0" mass="0.698159" diaginertia="0.002413 0.00185007 0.00165493"/>
<joint name="Revolute 10" pos="0 0 0" axis="0 1 0" range="-2.26893 0" actuatorfrcrange="-100 100"/>
<geom pos="0.000656 -0.21552 -0.268007" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Ulna_Fork_v5_Mirror__1"/>
<body name="shell_Radius_gen2_v31_Mirror__1" pos="0 0.00095 -0.100482">
<inertial pos="9.35442e-06 0.00117859 -0.123991" quat="0.999951 0.00993344 0 0" mass="0.87692" diaginertia="0.003786 0.00344577 0.00148223"/>
<joint name="Revolute 11" pos="0 0 0" axis="0 0 1" range="0 3.14159" actuatorfrcrange="-100 100"/>
<geom pos="0.000656 -0.21647 -0.167525" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Radius_gen2_v31_Mirror__1"/>
<body name="scaphoid_Mirror__1" pos="6.5e-05 0 -0.206787">
<inertial pos="-1.58999e-07 1.3481e-08 4.05809e-07" quat="0.5 0.5 -0.5 0.5" mass="0.0259174" diaginertia="7e-06 4e-06 4e-06"/>
<joint name="Revolute 24" pos="0 0 0" axis="0 1 0" range="-0.523599 0.523599" actuatorfrcrange="-100 100"/>
<geom pos="0.000591 -0.21647 0.039262" type="mesh" rgba="0.7 0.7 0.7 1" mesh="scaphoid_Mirror__1"/>
<body name="hand_secondIter_v9_1">
<inertial pos="-0.00343586 -0.00506416 -0.0641579" quat="0.978592 0.031701 0.00787655 -0.203201" mass="0.340548" diaginertia="0.00134431 0.00105859 0.0004321"/>
<joint name="Revolute 17" pos="0 0 0" axis="1 0 0" range="-0.349066 0.698132" actuatorfrcrange="-100 100"/>
<geom pos="0.000591 -0.21647 0.039262" type="mesh" rgba="0.7 0.7 0.7 1" mesh="hand_secondIter_v9_1"/>
</body>
</body>
</body>
</body>
</body>
</body>
</body>
</body>
</body>
</body>
<body name="shell_Hp2r_Fork_v9_1" pos="0 -0.07805 0">
<inertial pos="-0.0141996 -0.0485335 3.44054e-05" quat="0.485909 0.487111 0.512789 0.513481" mass="0.966865" diaginertia="0.00338981 0.002866 0.00275019"/>
<joint name="Revolute 25" pos="0 0 0" axis="0 1 0" range="-1.5708 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0 0.07805 0" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Hp2r_Fork_v9_1"/>
<body name="shell_Hr2w_Fork_v16_1" pos="-0.006681 -0.063408 0.0001">
<inertial pos="-0.00952234 -0.00116999 -0.1034" quat="0.715613 -0.10037 -0.111741 0.682157" mass="1.46012" diaginertia="0.0123951 0.00880392 0.00647794"/>
<joint name="Revolute 26" pos="0 0 0" axis="1 0 0" range="-1.5708 0.610865" actuatorfrcrange="-100 100"/>
<geom pos="0.006681 0.141458 -0.0001" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Hr2w_Fork_v16_1"/>
<body name="shell_Femur_fork_v4_1" pos="0.0059 0 -0.21643">
<inertial pos="0.00550338 0.0121435 -0.147595" quat="0.715678 0.0344328 -0.0145762 0.697428" mass="1.55467" diaginertia="0.0114351 0.0100695 0.0039594"/>
<joint name="Revolute 27" pos="0 0 0" axis="0 0 1" range="-1.5708 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0.000781 0.141458 0.21633" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Femur_fork_v4_1"/>
<body name="shell_Tibia_Alt_fork_v12_1" pos="0 0.011525 -0.20343">
<inertial pos="0.0049156 -0.0471964 -0.179273" quat="0.996568 -0.0697109 -0.00247143 -0.0445611" mass="2.28598" diaginertia="0.0449954 0.0441979 0.0066517"/>
<joint name="Revolute 28" pos="0 0 0" axis="0 1 0" range="0 2.61799" actuatorfrcrange="-100 100"/>
<geom pos="0.000781 0.129933 0.41976" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Tibia_Alt_fork_v12_1"/>
<body name="shell_Ap2r_v5_1" pos="0 -0.0554 -0.4101">
<inertial pos="0.01075 0.0488861 7.92256e-07" quat="0.498939 0.498939 0.501059 0.501059" mass="0.854091" diaginertia="0.00330603 0.002482 0.00189097"/>
<joint name="Revolute 29" pos="0 0 0" axis="0 1 0" range="-0.785398 0.785398" actuatorfrcrange="-100 100"/>
<geom pos="0.000781 0.185333 0.82986" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Ap2r_v5_1"/>
<body name="shell_foot_v16_Mirror__1" pos="0.07781 0.0443 0">
<inertial pos="0.00978994 -0.00464532 -0.0467468" quat="0.739197 0.273168 0.456071 0.413481" mass="0.823883" diaginertia="0.00361388 0.00342654 0.00167958"/>
<joint name="Revolute 30" pos="0 0 0" axis="1 0 0" range="0 0.785398" actuatorfrcrange="-100 100"/>
<geom pos="-0.077029 0.141033 0.82986" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_foot_v16_Mirror__1"/>
</body>
</body>
</body>
</body>
</body>
</body>
<body name="shell_Hp2r_Fork_v9_Mirror__1" pos="0 0.07805 0">
<inertial pos="-0.0141987 0.0485343 3.38956e-05" quat="0.513481 0.512789 0.487111 0.485909" mass="0.96689" diaginertia="0.00338981 0.002866 0.00275019"/>
<joint name="Revolute 31" pos="0 0 0" axis="0 1 0" range="-1.5708 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0 -0.07805 0" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Hp2r_Fork_v9_Mirror__1"/>
<body name="shell_Hr2w_Fork_v16_Mirror__1" pos="-0.006681 0.063408 0.0001">
<inertial pos="-0.00952234 0.00116999 -0.1034" quat="0.682157 -0.111741 -0.10037 0.715613" mass="1.46012" diaginertia="0.0123951 0.00880392 0.00647794"/>
<joint name="Revolute 32" pos="0 0 0" axis="1 0 0" range="-0.610865 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0.006681 -0.141458 -0.0001" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Hr2w_Fork_v16_Mirror__1"/>
<body name="shell_Femur_fork_v4_Mirror__1" pos="0.0059 0 -0.21643">
<inertial pos="0.00550338 -0.0121435 -0.147595" quat="0.697428 -0.0145762 0.0344328 0.715678" mass="1.55467" diaginertia="0.0114351 0.0100695 0.0039594"/>
<joint name="Revolute 33" pos="0 0 0" axis="0 0 1" range="-1.5708 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0.000781 -0.141458 0.21633" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Femur_fork_v4_Mirror__1"/>
<body name="shell_Tibia_Alt_fork_v12_Mirror__1" pos="0 -0.011525 -0.20343">
<inertial pos="0.0049156 0.0471964 -0.179273" quat="0.996568 0.0697109 -0.00247143 0.0445611" mass="2.28598" diaginertia="0.0449954 0.0441979 0.0066517"/>
<joint name="Revolute 34" pos="0 0 0" axis="0 1 0" range="0 2.61799" actuatorfrcrange="-100 100"/>
<geom pos="0.000781 -0.129933 0.41976" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Tibia_Alt_fork_v12_Mirror__1"/>
<body name="shell_Ap2r_v5_Mirror__1" pos="0 0.0554 -0.4101">
<inertial pos="0.01075 -0.0488861 7.92256e-07" quat="0.501059 0.501059 0.498939 0.498939" mass="0.854091" diaginertia="0.00330603 0.002482 0.00189097"/>
<joint name="Revolute 35" pos="0 0 0" axis="0 1 0" range="-0.785398 0.785398" actuatorfrcrange="-100 100"/>
<geom pos="0.000781 -0.185333 0.82986" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Ap2r_v5_Mirror__1"/>
<body name="shell_foot_v16_1" pos="0.07781 -0.0443 0">
<inertial pos="0.0117899 0.00464532 -0.0467468" quat="0.413481 0.456071 0.273168 0.739197" mass="0.823883" diaginertia="0.00361388 0.00342654 0.00167958"/>
<joint name="Revolute 36" pos="0 0 0" axis="1 0 0" range="-0.785398 0" actuatorfrcrange="-100 100"/>
<geom pos="-0.077029 -0.141033 0.82986" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_foot_v16_1"/>
</body>
</body>
</body>
</body>
</body>
</body>
</worldbody>
<actuator>
<motor name="Revolute 2" gear="40" joint="Revolute 2"/>
<motor name="Revolute 3" gear="40" joint="Revolute 3"/>
<motor name="Revolute 4" gear="40" joint="Revolute 4"/>
<motor name="Revolute 5" gear="40" joint="Revolute 5"/>
<motor name="Revolute 6" gear="40" joint="Revolute 6"/>
<motor name="Revolute 7" gear="40" joint="Revolute 7"/>
<motor name="Revolute 8" gear="40" joint="Revolute 8"/>
<motor name="Revolute 9" gear="40" joint="Revolute 9"/>
<motor name="Revolute 10" gear="40" joint="Revolute 10"/>
<motor name="Revolute 11" gear="40" joint="Revolute 11"/>
<motor name="Revolute 14" gear="40" joint="Revolute 14"/>
<motor name="Revolute 17" gear="40" joint="Revolute 17"/>
<motor name="Revolute 20" gear="40" joint="Revolute 20"/>
<motor name="Revolute 21" gear="40" joint="Revolute 21"/>
<motor name="Revolute 22" gear="40" joint="Revolute 22"/>
<motor name="Revolute 23" gear="40" joint="Revolute 23"/>
<motor name="Revolute 24" gear="40" joint="Revolute 24"/>
<motor name="Revolute 25" gear="40" joint="Revolute 25"/>
<motor name="Revolute 26" gear="40" joint="Revolute 26"/>
<motor name="Revolute 27" gear="40" joint="Revolute 27"/>
<motor name="Revolute 28" gear="40" joint="Revolute 28"/>
<motor name="Revolute 29" gear="40" joint="Revolute 29"/>
<motor name="Revolute 30" gear="40" joint="Revolute 30"/>
<motor name="Revolute 31" gear="40" joint="Revolute 31"/>
<motor name="Revolute 32" gear="40" joint="Revolute 32"/>
<motor name="Revolute 33" gear="40" joint="Revolute 33"/>
<motor name="Revolute 34" gear="40" joint="Revolute 34"/>
<motor name="Revolute 35" gear="40" joint="Revolute 35"/>
<motor name="Revolute 36" gear="40" joint="Revolute 36"/>
</actuator>
</mujoco>
| 19,658 | XML | 89.178899 | 184 | 0.602452 |
ErvinZzz/orbit.data_collection/pyproject.toml | [build-system]
requires = ["setuptools", "toml"]
build-backend = "setuptools.build_meta"
[tool.isort]
atomic = true
profile = "black"
line_length = 120
py_version = 310
skip_glob = ["docs/*", "logs/*", "_orbit/*", "_isaac_sim/*"]
group_by_package = true
sections = [
"FUTURE",
"STDLIB",
"THIRDPARTY",
"ORBITPARTY",
"FIRSTPARTY",
"LOCALFOLDER",
]
extra_standard_library = [
"numpy",
"h5py",
"open3d",
"torch",
"tensordict",
"bpy",
"matplotlib",
"gymnasium",
"gym",
"scipy",
"hid",
"yaml",
"prettytable",
"toml",
"trimesh",
"tqdm",
]
known_thirdparty = [
"omni.isaac.core",
"omni.replicator.isaac",
"omni.replicator.core",
"pxr",
"omni.kit.*",
"warp",
"carb",
]
known_orbitparty = [
"omni.isaac.orbit",
"omni.isaac.orbit_tasks",
"omni.isaac.orbit_assets"
]
# Modify the following to include the package names of your first-party code
known_firstparty = "orbit.ext_template"
known_local_folder = "config"
[tool.pyright]
exclude = [
"**/__pycache__",
"**/_isaac_sim",
"**/_orbit",
"**/docs",
"**/logs",
".git",
".vscode",
]
typeCheckingMode = "basic"
pythonVersion = "3.10"
pythonPlatform = "Linux"
enableTypeIgnoreComments = true
# This is required as the CI pre-commit does not download the module (i.e. numpy, torch, prettytable)
# Therefore, we have to ignore missing imports
reportMissingImports = "none"
# This is required to ignore for type checks of modules with stubs missing.
reportMissingModuleSource = "none" # -> most common: prettytable in mdp managers
reportGeneralTypeIssues = "none" # -> raises 218 errors (usage of literal MISSING in dataclasses)
reportOptionalMemberAccess = "warning" # -> raises 8 errors
reportPrivateUsage = "warning"
| 1,823 | TOML | 20.458823 | 103 | 0.633022 |
ErvinZzz/orbit.data_collection/setup.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Installation script for the 'orbit.ext_template' python package."""
import os
import toml
from setuptools import setup
# Obtain the extension data from the extension.toml file
EXTENSION_PATH = os.path.dirname(os.path.realpath(__file__))
# Read the extension.toml file
EXTENSION_TOML_DATA = toml.load(os.path.join(EXTENSION_PATH, "config", "extension.toml"))
# Minimum dependencies required prior to installation
INSTALL_REQUIRES = [
# NOTE: Add dependencies
"psutil",
]
# Installation operation
setup(
# TODO: Change your package naming
# -----------------------------------------------------------------
name="orbit.ext_template",
packages=["orbit.ext_template"],
# -----------------------------------------------------------------
author=EXTENSION_TOML_DATA["package"]["author"],
maintainer=EXTENSION_TOML_DATA["package"]["maintainer"],
maintainer_email=EXTENSION_TOML_DATA["package"]["maintainer_email"],
url=EXTENSION_TOML_DATA["package"]["repository"],
version=EXTENSION_TOML_DATA["package"]["version"],
description=EXTENSION_TOML_DATA["package"]["description"],
keywords=EXTENSION_TOML_DATA["package"]["keywords"],
install_requires=INSTALL_REQUIRES,
license="BSD-3-Clause",
include_package_data=True,
python_requires=">=3.10",
classifiers=[
"Natural Language :: English",
"Programming Language :: Python :: 3.10",
"Isaac Sim :: 2023.1.0-hotfix.1",
"Isaac Sim :: 2023.1.1",
],
zip_safe=False,
)
| 1,647 | Python | 31.959999 | 89 | 0.631451 |
ErvinZzz/orbit.data_collection/README.md | # Extension Template for Orbit
[](https://docs.omniverse.nvidia.com/isaacsim/latest/overview.html)
[](https://isaac-orbit.github.io/orbit/)
[](https://docs.python.org/3/whatsnew/3.10.html)
[](https://releases.ubuntu.com/20.04/)
[](https://pre-commit.com/)
## Overview
This repository serves as a template for building projects or extensions based on Orbit. It allows you to develop in an isolated environment, outside of the core Orbit repository. Furthermore, this template serves three use cases:
- **Python Package**
Can be installed into Isaac Sim's Python environment, making it suitable for users who want to integrate their extension to `Orbit` as a python package.
- **Project Template**
Ensures access to `Isaac Sim` and `Orbit` functionalities, which can be used as a project template.
- **Omniverse Extension**
Can be used as an Omniverse extension, ideal for projects that leverage the Omniverse platform's graphical user interface.
**Key Features:**
- `Isolation` Work outside the core Orbit repository, ensuring that your development efforts remain self-contained.
- `Flexibility` This template is set up to allow your code to be run as an extension in Omniverse.
**Keywords:** extension, template, orbit
### License
The source code is released under a [BSD 3-Clause license](https://opensource.org/licenses/BSD-3-Clause).
**Author: The ORBIT Project Developers<br />
Affiliation: [The AI Institute](https://theaiinstitute.com/)<br />
Maintainer: Nico Burger, [email protected]**
## Setup
Depending on the use case defined [above](#overview), follow the instructions to set up your extension template. Start with the [Basic Setup](#basic-setup), which is required for either use case.
### Basic Setup
#### Dependencies
This template depends on Isaac Sim and Orbit. For detailed instructions on how to install these dependencies, please refer to the [installation guide](https://isaac-orbit.github.io/orbit/source/setup/installation.html).
- [Isaac Sim](https://docs.omniverse.nvidia.com/isaacsim/latest/index.html)
- [Orbit](https://isaac-orbit.github.io/orbit/)
#### Configuration
Decide on a name for your project or extension. This guide will refer to this name as `<your_extension_name>`.
- Create a new repository based off this template [here](https://github.com/new?owner=isaac-orbit&template_name=orbit.ext_template&template_owner=isaac-orbit). Name your forked repository using the following convention: `"orbit.<your_extension_name>"`.
- Clone your forked repository to a location **outside** the orbit repository.
```bash
git clone <your_repository_url>
```
- To tailor this template to your needs, customize the settings in `config/extension.toml` and `setup.py` by completing the sections marked with TODO.
- Rename your source folder.
```bash
cd orbit.<your_extension_name>
mv orbit/ext_template orbit/<your_extension_name>
```
- Define the following environment variable to specify the path to your Orbit installation:
```bash
# Set the ORBIT_PATH environment variable to point to your Orbit installation directory
export ORBIT_PATH=<your_orbit_path>
```
#### Set Python Interpreter
Although using a virtual environment is optional, we recommend using `conda` (detailed instructions [here](https://isaac-orbit.github.io/orbit/source/setup/installation.html#setting-up-the-environment)). If you decide on using Isaac Sim's bundled Python, you can skip these steps.
- If you haven't already: create and activate your `conda` environment, followed by installing extensions inside Orbit:
```bash
# Create conda environment
${ORBIT_PATH}/orbit.sh --conda
# Activate conda environment
conda activate orbit
# Install all Orbit extensions in orbit/source/extensions
${ORBIT_PATH}/orbit.sh --install
```
- Set your `conda` environment as the default interpreter in VSCode by opening the command palette (`Ctrl+Shift+P`), choosing `Python: Select Interpreter` and selecting your `conda` environment.
Once you are in the virtual environment, you do not need to use `${ORBIT_PATH}/orbit.sh -p` to run python scripts. You can use the default python executable in your environment by running `python` or `python3`. However, for the rest of the documentation, we will assume that you are using `${ORBIT_PATH}/orbit.sh -p` to run python scripts.
#### Set up IDE
To setup the IDE, please follow these instructions:
1. Open the `orbit.<your_extension_template>` directory on Visual Studio Code IDE
2. Run VSCode Tasks, by pressing `Ctrl+Shift+P`, selecting `Tasks: Run Task` and running the `setup_python_env` in the drop down menu. When running this task, you will be prompted to add the absolute path to your Orbit installation.
If everything executes correctly, it should create a file .python.env in the .vscode directory. The file contains the python paths to all the extensions provided by Isaac Sim and Omniverse. This helps in indexing all the python modules for intelligent suggestions while writing code.
### Setup as Python Package / Project Template
From within this repository, install your extension as a Python package to the Isaac Sim Python executable.
```bash
${ORBIT_PATH}/orbit.sh -p -m pip install --upgrade pip
${ORBIT_PATH}/orbit.sh -p -m pip install -e .
```
### Setup as Omniverse Extension
To enable your extension, follow these steps:
1. **Add the search path of your repository** to the extension manager:
- Navigate to the extension manager using `Window` -> `Extensions`.
- Click on the **Hamburger Icon** (β°), then go to `Settings`.
- In the `Extension Search Paths`, enter the path that goes up to your repository's location without actually including the repository's own directory. For example, if your repository is located at `/home/code/orbit.ext_template`, you should add `/home/code` as the search path.
- If not already present, in the `Extension Search Paths`, enter the path that leads to your local Orbit directory. For example: `/home/orbit/source/extensions`
- Click on the **Hamburger Icon** (β°), then click `Refresh`.
2. **Search and enable your extension**:
- Find your extension under the `Third Party` category.
- Toggle it to enable your extension.
## Usage
### Python Package
Import your python package within `Isaac Sim` and `Orbit` using:
```python
import orbit.<your_extension_name>
```
### Project Template
We provide an example for training and playing a policy for ANYmal on flat terrain. Install [RSL_RL](https://github.com/leggedrobotics/rsl_rl) outside of the orbit repository, e.g. `home/code/rsl_rl`.
```bash
git clone https://github.com/leggedrobotics/rsl_rl.git
cd rsl_rl
${ORBIT_PATH}/orbit.sh -p -m pip install -e .
```
Train a policy.
```bash
cd <path_to_your_extension>
${ORBIT_PATH}/orbit.sh -p scripts/rsl_rl/train.py --task Template-Velocity-Flat-Anymal-D-v0 --num_envs 4096 --headless
```
Play the trained policy.
```bash
${ORBIT_PATH}/orbit.sh -p scripts/rsl_rl/play.py --task Template-Velocity-Flat-Anymal-D-Play-v0 --num_envs 16
```
### Omniverse Extension
We provide an example UI extension that will load upon enabling your extension defined in `orbit/ext_template/ui_extension_example.py`. For more information on UI extensions, enable and check out the source code of the `omni.isaac.ui_template` extension and refer to the introduction on [Isaac Sim Workflows 1.2.3. GUI](https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/tutorial_intro_workflows.html#gui).
## Pre-Commit
Pre-committing involves using a framework to automate the process of enforcing code quality standards before code is actually committed to a version control system, like Git. This process involves setting up hooks that run automated checks, such as code formatting, linting (checking for programming errors, bugs, stylistic errors, and suspicious constructs), and running tests. If these checks pass, the commit is allowed; if not, the commit is blocked until the issues are resolved. This ensures that all code committed to the repository adheres to the defined quality standards, leading to a cleaner, more maintainable codebase. To do so, we use the [pre-commit](https://pre-commit.com/) module. Install the module using:
```bash
pip install pre-commit
```
Run the pre-commit with:
```bash
pre-commit run --all-files
```
## Finalize
You are all set and no longer need the template instructions
- The `orbit/ext_template` and `scripts/rsl_rl` directories act as a reference template for your convenience. Delete them if no longer required.
- When ready, use this `README.md` as a template and customize where appropriate.
## Docker / Cluster
We are currently working on a docker and cluster setup for this template. In the meanwhile, please refer to the current setup provided in the Orbit [documentation](https://isaac-orbit.github.io/orbit/source/deployment/index.html).
## Troubleshooting
### Docker Container
When running within a docker container, the following error has been encountered: `ModuleNotFoundError: No module named 'orbit'`. To mitigate, please comment out the docker specific environment definitions in `.vscode/launch.json` and run the following:
```bash
echo -e "\nexport PYTHONPATH=\$PYTHONPATH:/workspace/orbit.<your_extension_name>" >> ~/.bashrc
source ~/.bashrc
```
## Bugs & Feature Requests
Please report bugs and request features using the [Issue Tracker](https://github.com/isaac-orbit/orbit.ext_template/issues).
| 9,829 | Markdown | 46.033493 | 724 | 0.760301 |
ErvinZzz/orbit.data_collection/scripts/rsl_rl/play.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Script to play a checkpoint if an RL agent from RSL-RL."""
"""Launch Isaac Sim Simulator first."""
import argparse
from omni.isaac.orbit.app import AppLauncher
# local imports
import cli_args # isort: skip
# add argparse arguments
parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.")
parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.")
parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.")
parser.add_argument("--task", type=str, default=None, help="Name of the task.")
parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment")
# append RSL-RL cli arguments
cli_args.add_rsl_rl_args(parser)
# append AppLauncher cli args
AppLauncher.add_app_launcher_args(parser)
args_cli = parser.parse_args()
# launch omniverse app
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import os
import torch
from rsl_rl.runners import OnPolicyRunner
import omni.isaac.orbit_tasks # noqa: F401
from omni.isaac.orbit_tasks.utils import get_checkpoint_path, parse_env_cfg
from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlVecEnvWrapper,
export_policy_as_onnx,
)
# Import extensions to set up environment tasks
import orbit.ext_template.tasks # noqa: F401 TODO: import orbit.<your_extension_name>
def main():
"""Play with RSL-RL agent."""
# parse configuration
env_cfg = parse_env_cfg(args_cli.task, use_gpu=not args_cli.cpu, num_envs=args_cli.num_envs)
agent_cfg: RslRlOnPolicyRunnerCfg = cli_args.parse_rsl_rl_cfg(args_cli.task, args_cli)
# create isaac environment
env = gym.make(args_cli.task, cfg=env_cfg)
# wrap around environment for rsl-rl
env = RslRlVecEnvWrapper(env)
# specify directory for logging experiments
log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name)
log_root_path = os.path.abspath(log_root_path)
print(f"[INFO] Loading experiment from directory: {log_root_path}")
resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint)
print(f"[INFO]: Loading model checkpoint from: {resume_path}")
# load previously trained model
ppo_runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device)
ppo_runner.load(resume_path)
print(f"[INFO]: Loading model checkpoint from: {resume_path}")
# obtain the trained policy for inference
policy = ppo_runner.get_inference_policy(device=env.unwrapped.device)
# export policy to onnx
export_model_dir = os.path.join(os.path.dirname(resume_path), "exported")
export_policy_as_onnx(ppo_runner.alg.actor_critic, export_model_dir, filename="policy.onnx")
# reset environment
obs, _ = env.get_observations()
# simulate environment
while simulation_app.is_running():
# run everything in inference mode
with torch.inference_mode():
# agent stepping
actions = policy(obs)
# env stepping
obs, _, _, _ = env.step(actions)
# close the simulator
env.close()
if __name__ == "__main__":
# run the main execution
main()
# close sim app
simulation_app.close()
| 3,483 | Python | 32.5 | 101 | 0.706001 |
ErvinZzz/orbit.data_collection/scripts/rsl_rl/cli_args.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import argparse
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import RslRlOnPolicyRunnerCfg
def add_rsl_rl_args(parser: argparse.ArgumentParser):
"""Add RSL-RL arguments to the parser.
Args:
parser: The parser to add the arguments to.
"""
# create a new argument group
arg_group = parser.add_argument_group("rsl_rl", description="Arguments for RSL-RL agent.")
# -- experiment arguments
arg_group.add_argument(
"--experiment_name", type=str, default=None, help="Name of the experiment folder where logs will be stored."
)
arg_group.add_argument("--run_name", type=str, default=None, help="Run name suffix to the log directory.")
# -- load arguments
arg_group.add_argument("--resume", type=bool, default=None, help="Whether to resume from a checkpoint.")
arg_group.add_argument("--load_run", type=str, default=None, help="Name of the run folder to resume from.")
arg_group.add_argument("--checkpoint", type=str, default=None, help="Checkpoint file to resume from.")
# -- logger arguments
arg_group.add_argument(
"--logger", type=str, default=None, choices={"wandb", "tensorboard", "neptune"}, help="Logger module to use."
)
arg_group.add_argument(
"--log_project_name", type=str, default=None, help="Name of the logging project when using wandb or neptune."
)
def parse_rsl_rl_cfg(task_name: str, args_cli: argparse.Namespace) -> RslRlOnPolicyRunnerCfg:
"""Parse configuration for RSL-RL agent based on inputs.
Args:
task_name: The name of the environment.
args_cli: The command line arguments.
Returns:
The parsed configuration for RSL-RL agent based on inputs.
"""
from omni.isaac.orbit_tasks.utils.parse_cfg import load_cfg_from_registry
# load the default configuration
rslrl_cfg: RslRlOnPolicyRunnerCfg = load_cfg_from_registry(task_name, "rsl_rl_cfg_entry_point")
# override the default configuration with CLI arguments
if args_cli.seed is not None:
rslrl_cfg.seed = args_cli.seed
if args_cli.resume is not None:
rslrl_cfg.resume = args_cli.resume
if args_cli.load_run is not None:
rslrl_cfg.load_run = args_cli.load_run
if args_cli.checkpoint is not None:
rslrl_cfg.load_checkpoint = args_cli.checkpoint
if args_cli.run_name is not None:
rslrl_cfg.run_name = args_cli.run_name
if args_cli.logger is not None:
rslrl_cfg.logger = args_cli.logger
# set the project name for wandb and neptune
if rslrl_cfg.logger in {"wandb", "neptune"} and args_cli.log_project_name:
rslrl_cfg.wandb_project = args_cli.log_project_name
rslrl_cfg.neptune_project = args_cli.log_project_name
return rslrl_cfg
| 2,981 | Python | 38.759999 | 117 | 0.688695 |
ErvinZzz/orbit.data_collection/scripts/rsl_rl/train.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Script to train RL agent with RSL-RL."""
"""Launch Isaac Sim Simulator first."""
import argparse
import os
from omni.isaac.orbit.app import AppLauncher
# local imports
import cli_args # isort: skip
# add argparse arguments
parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.")
parser.add_argument("--video", action="store_true", default=False, help="Record videos during training.")
parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).")
parser.add_argument("--video_interval", type=int, default=2000, help="Interval between video recordings (in steps).")
parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.")
parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.")
parser.add_argument("--task", type=str, default=None, help="Name of the task.")
parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment")
# append RSL-RL cli arguments
cli_args.add_rsl_rl_args(parser)
# append AppLauncher cli args
AppLauncher.add_app_launcher_args(parser)
args_cli = parser.parse_args()
# launch omniverse app
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import os
import torch
from datetime import datetime
from rsl_rl.runners import OnPolicyRunner
import omni.isaac.orbit_tasks # noqa: F401
from omni.isaac.orbit.envs import RLTaskEnvCfg
from omni.isaac.orbit.utils.dict import print_dict
from omni.isaac.orbit.utils.io import dump_pickle, dump_yaml
from omni.isaac.orbit_tasks.utils import get_checkpoint_path, parse_env_cfg
from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper
# Import extensions to set up environment tasks
import orbit.ext_template.tasks # noqa: F401 TODO: import orbit.<your_extension_name>
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = False
def main():
"""Train with RSL-RL agent."""
# parse configuration
env_cfg: RLTaskEnvCfg = parse_env_cfg(args_cli.task, use_gpu=not args_cli.cpu, num_envs=args_cli.num_envs)
agent_cfg: RslRlOnPolicyRunnerCfg = cli_args.parse_rsl_rl_cfg(args_cli.task, args_cli)
# specify directory for logging experiments
log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name)
log_root_path = os.path.abspath(log_root_path)
print(f"[INFO] Logging experiment in directory: {log_root_path}")
# specify directory for logging runs: {time-stamp}_{run_name}
log_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
if agent_cfg.run_name:
log_dir += f"_{agent_cfg.run_name}"
log_dir = os.path.join(log_root_path, log_dir)
# create isaac environment
env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None)
# wrap for video recording
if args_cli.video:
video_kwargs = {
"video_folder": os.path.join(log_dir, "videos"),
"step_trigger": lambda step: step % args_cli.video_interval == 0,
"video_length": args_cli.video_length,
"disable_logger": True,
}
print("[INFO] Recording videos during training.")
print_dict(video_kwargs, nesting=4)
env = gym.wrappers.RecordVideo(env, **video_kwargs)
# wrap around environment for rsl-rl
env = RslRlVecEnvWrapper(env)
# create runner from rsl-rl
runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=log_dir, device=agent_cfg.device)
# write git state to logs
runner.add_git_repo_to_log(__file__)
# save resume path before creating a new log_dir
if agent_cfg.resume:
# get path to previous checkpoint
resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint)
print(f"[INFO]: Loading model checkpoint from: {resume_path}")
# load previously trained model
runner.load(resume_path)
# set seed of the environment
env.seed(agent_cfg.seed)
# dump the configuration into log-directory
dump_yaml(os.path.join(log_dir, "params", "env.yaml"), env_cfg)
dump_yaml(os.path.join(log_dir, "params", "agent.yaml"), agent_cfg)
dump_pickle(os.path.join(log_dir, "params", "env.pkl"), env_cfg)
dump_pickle(os.path.join(log_dir, "params", "agent.pkl"), agent_cfg)
# run training
runner.learn(num_learning_iterations=agent_cfg.max_iterations, init_at_random_ep_len=True)
# close the simulator
env.close()
if __name__ == "__main__":
# run the main execution
main()
# close sim app
simulation_app.close()
| 4,924 | Python | 37.779527 | 117 | 0.703696 |
ErvinZzz/orbit.data_collection/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "0.1.0"
# Description
category = "orbit"
readme = "README.md"
# TODO: Change your package specifications
# -----------------------------------------------------------------
title = "Extension Template"
author = "ORBIT Project Developers"
maintainer = "Nico Burger"
maintainer_email = "[email protected]"
description="Extension Template for Orbit"
repository = "https://github.com/isaac-orbit/orbit.ext_template.git"
keywords = ["extension", "template", "orbit"]
# -----------------------------------------------------------------
[dependencies]
"omni.isaac.orbit" = {}
"omni.isaac.orbit_assets" = {}
"omni.isaac.orbit_tasks" = {}
# NOTE: Add additional dependencies here
[[python.module]]
# TODO: Change your package name
# -----------------------------------------------------------------
name = "orbit.ext_template"
# -----------------------------------------------------------------
| 972 | TOML | 29.406249 | 68 | 0.52572 |
ErvinZzz/orbit.data_collection/orbit/ext_template/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Python module serving as a project/extension template.
"""
# Register Gym environments.
from .tasks import *
# Register UI extensions.
from .ui_extension_example import *
| 300 | Python | 19.066665 | 56 | 0.743333 |
ErvinZzz/orbit.data_collection/orbit/ext_template/ui_extension_example.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import omni.ext
import omni.ui as ui
# Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)`
def some_public_function(x: int):
print("[orbit.ext_template] some_public_function was called with x: ", x)
return x**x
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class ExampleExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[orbit.ext_template] startup")
self._count = 0
self._window = ui.Window("My Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
label = ui.Label("")
def on_click():
self._count += 1
label.text = f"count: {self._count}"
def on_reset():
self._count = 0
label.text = "empty"
on_reset()
with ui.HStack():
ui.Button("Add", clicked_fn=on_click)
ui.Button("Reset", clicked_fn=on_reset)
def on_shutdown(self):
print("[orbit.ext_template] shutdown")
| 1,650 | Python | 33.395833 | 119 | 0.609697 |
ErvinZzz/orbit.data_collection/orbit/ext_template/tasks/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Package containing task implementations for various robotic environments."""
import os
import toml
# Conveniences to other module directories via relative paths
ORBIT_TASKS_EXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))
"""Path to the extension source directory."""
ORBIT_TASKS_METADATA = toml.load(os.path.join(ORBIT_TASKS_EXT_DIR, "config", "extension.toml"))
"""Extension metadata dictionary parsed from the extension.toml file."""
# Configure the module-level variables
__version__ = ORBIT_TASKS_METADATA["package"]["version"]
##
# Register Gym environments.
##
from omni.isaac.orbit_tasks.utils import import_packages
# The blacklist is used to prevent importing configs from sub-packages
_BLACKLIST_PKGS = ["utils"]
# Import all configs in this package
import_packages(__name__, _BLACKLIST_PKGS)
| 968 | Python | 30.258064 | 95 | 0.744835 |
ErvinZzz/orbit.data_collection/orbit/ext_template/tasks/locomotion/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Locomotion environments for legged robots."""
from .velocity import * # noqa
| 205 | Python | 21.888886 | 56 | 0.731707 |
ErvinZzz/orbit.data_collection/orbit/ext_template/tasks/locomotion/velocity/velocity_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import math
from dataclasses import MISSING
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg
from omni.isaac.orbit.envs import RLTaskEnvCfg
from omni.isaac.orbit.managers import CurriculumTermCfg as CurrTerm
from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm
from omni.isaac.orbit.managers import RandomizationTermCfg as RandTerm
from omni.isaac.orbit.managers import RewardTermCfg as RewTerm
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm
from omni.isaac.orbit.scene import InteractiveSceneCfg
from omni.isaac.orbit.sensors import ContactSensorCfg, RayCasterCfg, patterns
from omni.isaac.orbit.terrains import TerrainImporterCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.noise import AdditiveUniformNoiseCfg as Unoise
import orbit.ext_template.tasks.locomotion.velocity.mdp as mdp
##
# Pre-defined configs
##
from omni.isaac.orbit.terrains.config.rough import ROUGH_TERRAINS_CFG # isort: skip
##
# Scene definition
##
@configclass
class MySceneCfg(InteractiveSceneCfg):
"""Configuration for the terrain scene with a legged robot."""
# ground terrain
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="generator",
terrain_generator=ROUGH_TERRAINS_CFG,
max_init_terrain_level=5,
collision_group=-1,
physics_material=sim_utils.RigidBodyMaterialCfg(
friction_combine_mode="multiply",
restitution_combine_mode="multiply",
static_friction=1.0,
dynamic_friction=1.0,
),
visual_material=sim_utils.MdlFileCfg(
mdl_path="{NVIDIA_NUCLEUS_DIR}/Materials/Base/Architecture/Shingles_01.mdl",
project_uvw=True,
),
debug_vis=False,
)
# robots
robot: ArticulationCfg = MISSING
# sensors
height_scanner = RayCasterCfg(
prim_path="{ENV_REGEX_NS}/Robot/base",
offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)),
attach_yaw_only=True,
pattern_cfg=patterns.GridPatternCfg(resolution=0.1, size=[1.6, 1.0]),
debug_vis=False,
mesh_prim_paths=["/World/ground"],
)
contact_forces = ContactSensorCfg(prim_path="{ENV_REGEX_NS}/Robot/.*", history_length=3, track_air_time=True)
# lights
light = AssetBaseCfg(
prim_path="/World/light",
spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0),
)
sky_light = AssetBaseCfg(
prim_path="/World/skyLight",
spawn=sim_utils.DomeLightCfg(color=(0.13, 0.13, 0.13), intensity=1000.0),
)
##
# MDP settings
##
@configclass
class CommandsCfg:
"""Command specifications for the MDP."""
base_velocity = mdp.UniformVelocityCommandCfg(
asset_name="robot",
resampling_time_range=(10.0, 10.0),
rel_standing_envs=0.02,
rel_heading_envs=1.0,
heading_command=True,
heading_control_stiffness=0.5,
debug_vis=True,
ranges=mdp.UniformVelocityCommandCfg.Ranges(
lin_vel_x=(-1.0, 1.0), lin_vel_y=(-1.0, 1.0), ang_vel_z=(-1.0, 1.0), heading=(-math.pi, math.pi)
),
)
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
joint_pos = mdp.JointPositionActionCfg(asset_name="robot", joint_names=[".*"], scale=0.5, use_default_offset=True)
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for policy group."""
# observation terms (order preserved)
base_lin_vel = ObsTerm(func=mdp.base_lin_vel, noise=Unoise(n_min=-0.1, n_max=0.1))
base_ang_vel = ObsTerm(func=mdp.base_ang_vel, noise=Unoise(n_min=-0.2, n_max=0.2))
projected_gravity = ObsTerm(
func=mdp.projected_gravity,
noise=Unoise(n_min=-0.05, n_max=0.05),
)
velocity_commands = ObsTerm(func=mdp.generated_commands, params={"command_name": "base_velocity"})
joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.01, n_max=0.01))
joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-1.5, n_max=1.5))
actions = ObsTerm(func=mdp.last_action)
height_scan = ObsTerm(
func=mdp.height_scan,
params={"sensor_cfg": SceneEntityCfg("height_scanner")},
noise=Unoise(n_min=-0.1, n_max=0.1),
clip=(-1.0, 1.0),
)
def __post_init__(self):
self.enable_corruption = True
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class RandomizationCfg:
"""Configuration for randomization."""
# startup
physics_material = RandTerm(
func=mdp.randomize_rigid_body_material,
mode="startup",
params={
"asset_cfg": SceneEntityCfg("robot", body_names=".*"),
"static_friction_range": (0.8, 0.8),
"dynamic_friction_range": (0.6, 0.6),
"restitution_range": (0.0, 0.0),
"num_buckets": 64,
},
)
add_base_mass = RandTerm(
func=mdp.add_body_mass,
mode="startup",
params={"asset_cfg": SceneEntityCfg("robot", body_names="base"), "mass_range": (-5.0, 5.0)},
)
# reset
base_external_force_torque = RandTerm(
func=mdp.apply_external_force_torque,
mode="reset",
params={
"asset_cfg": SceneEntityCfg("robot", body_names="base"),
"force_range": (0.0, 0.0),
"torque_range": (-0.0, 0.0),
},
)
reset_base = RandTerm(
func=mdp.reset_root_state_uniform,
mode="reset",
params={
"pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)},
"velocity_range": {
"x": (-0.5, 0.5),
"y": (-0.5, 0.5),
"z": (-0.5, 0.5),
"roll": (-0.5, 0.5),
"pitch": (-0.5, 0.5),
"yaw": (-0.5, 0.5),
},
},
)
reset_robot_joints = RandTerm(
func=mdp.reset_joints_by_scale,
mode="reset",
params={
"position_range": (0.5, 1.5),
"velocity_range": (0.0, 0.0),
},
)
# interval
push_robot = RandTerm(
func=mdp.push_by_setting_velocity,
mode="interval",
interval_range_s=(10.0, 15.0),
params={"velocity_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5)}},
)
@configclass
class RewardsCfg:
"""Reward terms for the MDP."""
# -- task
track_lin_vel_xy_exp = RewTerm(
func=mdp.track_lin_vel_xy_exp, weight=1.0, params={"command_name": "base_velocity", "std": math.sqrt(0.25)}
)
track_ang_vel_z_exp = RewTerm(
func=mdp.track_ang_vel_z_exp, weight=0.5, params={"command_name": "base_velocity", "std": math.sqrt(0.25)}
)
# -- penalties
lin_vel_z_l2 = RewTerm(func=mdp.lin_vel_z_l2, weight=-2.0)
ang_vel_xy_l2 = RewTerm(func=mdp.ang_vel_xy_l2, weight=-0.05)
dof_torques_l2 = RewTerm(func=mdp.joint_torques_l2, weight=-1.0e-5)
dof_acc_l2 = RewTerm(func=mdp.joint_acc_l2, weight=-2.5e-7)
action_rate_l2 = RewTerm(func=mdp.action_rate_l2, weight=-0.01)
feet_air_time = RewTerm(
func=mdp.feet_air_time,
weight=0.125,
params={
"sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*FOOT"),
"command_name": "base_velocity",
"threshold": 0.5,
},
)
undesired_contacts = RewTerm(
func=mdp.undesired_contacts,
weight=-1.0,
params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*THIGH"), "threshold": 1.0},
)
# -- optional penalties
flat_orientation_l2 = RewTerm(func=mdp.flat_orientation_l2, weight=0.0)
dof_pos_limits = RewTerm(func=mdp.joint_pos_limits, weight=0.0)
@configclass
class TerminationsCfg:
"""Termination terms for the MDP."""
time_out = DoneTerm(func=mdp.time_out, time_out=True)
base_contact = DoneTerm(
func=mdp.illegal_contact,
params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names="base"), "threshold": 1.0},
)
@configclass
class CurriculumCfg:
"""Curriculum terms for the MDP."""
terrain_levels = CurrTerm(func=mdp.terrain_levels_vel)
##
# Environment configuration
##
@configclass
class LocomotionVelocityRoughEnvCfg(RLTaskEnvCfg):
"""Configuration for the locomotion velocity-tracking environment."""
# Scene settings
scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=2.5)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
commands: CommandsCfg = CommandsCfg()
# MDP settings
rewards: RewardsCfg = RewardsCfg()
terminations: TerminationsCfg = TerminationsCfg()
randomization: RandomizationCfg = RandomizationCfg()
curriculum: CurriculumCfg = CurriculumCfg()
def __post_init__(self):
"""Post initialization."""
# general settings
self.decimation = 4
self.episode_length_s = 20.0
# simulation settings
self.sim.dt = 0.005
self.sim.disable_contact_processing = True
self.sim.physics_material = self.scene.terrain.physics_material
# update sensor update periods
# we tick all the sensors based on the smallest update period (physics update period)
if self.scene.height_scanner is not None:
self.scene.height_scanner.update_period = self.decimation * self.sim.dt
if self.scene.contact_forces is not None:
self.scene.contact_forces.update_period = self.sim.dt
# check if terrain levels curriculum is enabled - if so, enable curriculum for terrain generator
# this generates terrains with increasing difficulty and is useful for training
if getattr(self.curriculum, "terrain_levels", None) is not None:
if self.scene.terrain.terrain_generator is not None:
self.scene.terrain.terrain_generator.curriculum = True
else:
if self.scene.terrain.terrain_generator is not None:
self.scene.terrain.terrain_generator.curriculum = False
| 10,649 | Python | 32.596214 | 118 | 0.626538 |
ErvinZzz/orbit.data_collection/orbit/ext_template/tasks/locomotion/velocity/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Locomotion environments with velocity-tracking commands.
These environments are based on the `legged_gym` environments provided by Rudin et al.
Reference:
https://github.com/leggedrobotics/legged_gym
"""
| 336 | Python | 24.923075 | 86 | 0.764881 |
ErvinZzz/orbit.data_collection/orbit/ext_template/tasks/locomotion/velocity/mdp/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""This sub-module contains the functions that are specific to the locomotion environments."""
from omni.isaac.orbit.envs.mdp import * # noqa: F401, F403
from .curriculums import * # noqa: F401, F403
from .rewards import * # noqa: F401, F403
| 370 | Python | 29.916664 | 94 | 0.732432 |
ErvinZzz/orbit.data_collection/orbit/ext_template/tasks/locomotion/velocity/mdp/curriculums.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Common functions that can be used to create curriculum for the learning environment.
The functions can be passed to the :class:`omni.isaac.orbit.managers.CurriculumTermCfg` object to enable
the curriculum introduced by the function.
"""
from __future__ import annotations
import torch
from collections.abc import Sequence
from typing import TYPE_CHECKING
from omni.isaac.orbit.assets import Articulation
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.terrains import TerrainImporter
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def terrain_levels_vel(
env: RLTaskEnv, env_ids: Sequence[int], asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Curriculum based on the distance the robot walked when commanded to move at a desired velocity.
This term is used to increase the difficulty of the terrain when the robot walks far enough and decrease the
difficulty when the robot walks less than half of the distance required by the commanded velocity.
.. note::
It is only possible to use this term with the terrain type ``generator``. For further information
on different terrain types, check the :class:`omni.isaac.orbit.terrains.TerrainImporter` class.
Returns:
The mean terrain level for the given environment ids.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
terrain: TerrainImporter = env.scene.terrain
command = env.command_manager.get_command("base_velocity")
# compute the distance the robot walked
distance = torch.norm(asset.data.root_pos_w[env_ids, :2] - env.scene.env_origins[env_ids, :2], dim=1)
# robots that walked far enough progress to harder terrains
move_up = distance > terrain.cfg.terrain_generator.size[0] / 2
# robots that walked less than half of their required distance go to simpler terrains
move_down = distance < torch.norm(command[env_ids, :2], dim=1) * env.max_episode_length_s * 0.5
move_down *= ~move_up
# update terrain levels
terrain.update_env_origins(env_ids, move_up, move_down)
# return the mean terrain level
return torch.mean(terrain.terrain_levels.float())
| 2,376 | Python | 41.446428 | 112 | 0.742424 |
ErvinZzz/orbit.data_collection/orbit/ext_template/tasks/locomotion/velocity/mdp/rewards.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.sensors import ContactSensor
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def feet_air_time(env: RLTaskEnv, command_name: str, sensor_cfg: SceneEntityCfg, threshold: float) -> torch.Tensor:
"""Reward long steps taken by the feet using L2-kernel.
This function rewards the agent for taking steps that are longer than a threshold. This helps ensure
that the robot lifts its feet off the ground and takes steps. The reward is computed as the sum of
the time for which the feet are in the air.
If the commands are small (i.e. the agent is not supposed to take a step), then the reward is zero.
"""
# extract the used quantities (to enable type-hinting)
contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name]
# compute the reward
first_contact = contact_sensor.compute_first_contact(env.step_dt)[:, sensor_cfg.body_ids]
last_air_time = contact_sensor.data.last_air_time[:, sensor_cfg.body_ids]
reward = torch.sum((last_air_time - threshold) * first_contact, dim=1)
# no reward for zero command
reward *= torch.norm(env.command_manager.get_command(command_name)[:, :2], dim=1) > 0.1
return reward
def feet_air_time_positive_biped(env, command_name: str, threshold: float, sensor_cfg: SceneEntityCfg) -> torch.Tensor:
"""Reward long steps taken by the feet for bipeds.
This function rewards the agent for taking steps up to a specified threshold and also keep one foot at
a time in the air.
If the commands are small (i.e. the agent is not supposed to take a step), then the reward is zero.
"""
contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name]
# compute the reward
air_time = contact_sensor.data.current_air_time[:, sensor_cfg.body_ids]
contact_time = contact_sensor.data.current_contact_time[:, sensor_cfg.body_ids]
in_contact = contact_time > 0.0
in_mode_time = torch.where(in_contact, contact_time, air_time)
single_stance = torch.sum(in_contact.int(), dim=1) == 1
reward = torch.min(torch.where(single_stance.unsqueeze(-1), in_mode_time, 0.0), dim=1)[0]
reward = torch.clamp(reward, max=threshold)
# no reward for zero command
reward *= torch.norm(env.command_manager.get_command(command_name)[:, :2], dim=1) > 0.1
return reward
| 2,595 | Python | 43.75862 | 119 | 0.717148 |
ErvinZzz/orbit.data_collection/orbit/ext_template/tasks/locomotion/velocity/config/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configurations for velocity-based locomotion environments."""
# We leave this file empty since we don't want to expose any configs in this package directly.
# We still need this file to import the "config" module in the parent package.
| 363 | Python | 35.399996 | 94 | 0.763085 |
ErvinZzz/orbit.data_collection/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/rough_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.utils import configclass
from orbit.ext_template.tasks.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg
##
# Pre-defined configs
##
from omni.isaac.orbit_assets.anymal import ANYMAL_D_CFG # isort: skip
@configclass
class AnymalDRoughEnvCfg(LocomotionVelocityRoughEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# switch robot to anymal-d
self.scene.robot = ANYMAL_D_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
@configclass
class AnymalDRoughEnvCfg_PLAY(AnymalDRoughEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# make a smaller scene for play
self.scene.num_envs = 50
self.scene.env_spacing = 2.5
# spawn the robot randomly in the grid (instead of their terrain levels)
self.scene.terrain.max_init_terrain_level = None
# reduce the number of terrains to save memory
if self.scene.terrain.terrain_generator is not None:
self.scene.terrain.terrain_generator.num_rows = 5
self.scene.terrain.terrain_generator.num_cols = 5
self.scene.terrain.terrain_generator.curriculum = False
# disable randomization for play
self.observations.policy.enable_corruption = False
# remove random pushing
self.randomization.base_external_force_torque = None
self.randomization.push_robot = None
| 1,608 | Python | 33.234042 | 103 | 0.687189 |
ErvinZzz/orbit.data_collection/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/flat_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.utils import configclass
from .rough_env_cfg import AnymalDRoughEnvCfg
@configclass
class AnymalDFlatEnvCfg(AnymalDRoughEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# override rewards
self.rewards.flat_orientation_l2.weight = -5.0
self.rewards.dof_torques_l2.weight = -2.5e-5
self.rewards.feet_air_time.weight = 0.5
# change terrain to flat
self.scene.terrain.terrain_type = "plane"
self.scene.terrain.terrain_generator = None
# no height scan
self.scene.height_scanner = None
self.observations.policy.height_scan = None
# no terrain curriculum
self.curriculum.terrain_levels = None
class AnymalDFlatEnvCfg_PLAY(AnymalDFlatEnvCfg):
def __post_init__(self) -> None:
# post init of parent
super().__post_init__()
# make a smaller scene for play
self.scene.num_envs = 50
self.scene.env_spacing = 2.5
# disable randomization for play
self.observations.policy.enable_corruption = False
# remove random pushing
self.randomization.base_external_force_torque = None
self.randomization.push_robot = None
| 1,382 | Python | 30.431817 | 60 | 0.656295 |
ErvinZzz/orbit.data_collection/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import gymnasium as gym
from . import agents, flat_env_cfg, rough_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Template-Velocity-Flat-Anymal-D-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.AnymalDFlatEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDFlatPPORunnerCfg,
},
)
gym.register(
id="Template-Velocity-Flat-Anymal-D-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.AnymalDFlatEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDFlatPPORunnerCfg,
},
)
gym.register(
id="Template-Velocity-Rough-Anymal-D-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.AnymalDRoughEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDRoughPPORunnerCfg,
},
)
gym.register(
id="Template-Velocity-Rough-Anymal-D-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.AnymalDRoughEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDRoughPPORunnerCfg,
},
)
| 1,474 | Python | 26.830188 | 77 | 0.685889 |
ErvinZzz/orbit.data_collection/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/agents/rsl_rl_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class AnymalDRoughPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 24
max_iterations = 1500
save_interval = 50
experiment_name = "anymal_d_rough"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[512, 256, 128],
critic_hidden_dims=[512, 256, 128],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.005,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=1.0e-3,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
@configclass
class AnymalDFlatPPORunnerCfg(AnymalDRoughPPORunnerCfg):
def __post_init__(self):
super().__post_init__()
self.max_iterations = 300
self.experiment_name = "anymal_d_flat"
self.policy.actor_hidden_dims = [128, 128, 128]
self.policy.critic_hidden_dims = [128, 128, 128]
| 1,417 | Python | 26.26923 | 58 | 0.645025 |
ErvinZzz/orbit.data_collection/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/agents/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from . import rsl_rl_cfg # noqa: F401, F403
| 168 | Python | 23.142854 | 56 | 0.720238 |
ErvinZzz/orbit.data_collection/docs/CHANGELOG.rst | Changelog
---------
0.1.0 (2024-01-29)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Created an initial template for building an extension or project based on Orbit
| 155 | reStructuredText | 13.181817 | 81 | 0.593548 |
edgeimpulse/edge-impulse-omniverse-ext/README.md | # Edge Impulse Data Ingestion Omniverse Extension
This Omniverse extension allows you to upload your synthetic datasets to your Edge Impulse project for computer vision tasks, validate your trained model locally, and view inferencing results directly in your Omniverse synthetic environment.

# Extension Project Template
This project was automatically generated.
- `app` - It is a folder link to the location of your *Omniverse Kit* based app.
- `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path).
Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better.
Look for "edgeimpulse.dataingestion" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately.
Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.:
```
> app\omni.code.bat --ext-folder exts --enable edgeimpulse.dataingestion
```
# App Link Setup
If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included.
Run:
```
> link_app.bat
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```
> link_app.bat --app create
```
You can also just pass a path to create link to:
```
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4"
```
# Sharing Your Extensions
This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths.
Link might look like this: `git://github.com/[user]/[your_repo].git?branch=main&dir=exts`
Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual.
To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
# Troubleshooting
While working in Composer, add the following snippet:
```
[python.pipapi]
requirements = [
"requests"
]
use_online_index = true
```
## Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions.
| 2,697 | Markdown | 33.589743 | 258 | 0.765666 |
edgeimpulse/edge-impulse-omniverse-ext/tools/scripts/link_app.py | import os
import argparse
import sys
import json
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,813 | Python | 32.5 | 133 | 0.562389 |
edgeimpulse/edge-impulse-omniverse-ext/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
edgeimpulse/edge-impulse-omniverse-ext/tools/packman/bootstrap/install_package.py | # Copyright 2019 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import zipfile
import tempfile
import sys
import shutil
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(
package_src_path, allowZip64=True
) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning(
"Directory %s already present, packaged installation aborted" % package_dst_path
)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,888 | Python | 31.568965 | 103 | 0.68697 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# The title and description fields are primarily for displaying extension info in UI
title = "Edge Impulse Data Ingestion"
description="Edge Impulse Data Ingestion extension for Omniverse."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Icon to show in the extension manager
icon = "data/icon.png"
# Preview to show in the extension manager
preview_image = "data/preview.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import omni.example.apiconnect".
[[python.module]]
name = "edgeimpulse.dataingestion"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
[python.pipapi]
requirements = [
"httpx==0.21.1",
"pyyaml",
"webbrowser"
]
use_online_index = true | 1,160 | TOML | 23.702127 | 112 | 0.726724 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/edgeimpulse/dataingestion/config.py | import os
import json
from .state import State
class Config:
def __init__(self, config_file="config.json"):
self.config_file = config_file
self.config_data = self.load_config()
def load_config(self):
if os.path.exists(self.config_file):
with open(self.config_file, "r") as file:
return json.load(file)
return {}
def print_config_info(self):
"""Prints the path and content of the configuration file."""
print(f"Config file path: {self.config_file}")
print("Config contents:")
print(json.dumps(self.config_data, indent=4))
def save_config(self):
with open(self.config_file, "w") as file:
json.dump(self.config_data, file)
def get(self, key, default=None):
return self.config_data.get(key, default)
def set(self, key, value):
self.config_data[key] = value
self.save_config()
def get_state(self):
"""Retrieve the saved state from the config."""
# Default to NO_PROJECT_CONNECTED if not set
return self.get("state", State.NO_PROJECT_CONNECTED.name)
def set_state(self, state):
"""Save the current state to the config."""
self.set("state", state.name)
| 1,264 | Python | 28.418604 | 68 | 0.607595 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/edgeimpulse/dataingestion/state.py | from enum import Enum, auto
class State(Enum):
NO_PROJECT_CONNECTED = auto()
PROJECT_CONNECTED = auto()
| 114 | Python | 15.428569 | 33 | 0.684211 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/edgeimpulse/dataingestion/deployment.py | class DeploymentInfo:
def __init__(self, version=None, has_deployment=False):
self.version = version
self.has_deployment = has_deployment
| 158 | Python | 30.799994 | 59 | 0.677215 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/edgeimpulse/dataingestion/classifier.py | import asyncio
import subprocess
import uuid
from enum import Enum, auto
import os
import tempfile
import shutil
import numpy as np
import glob
from omni.kit.widget.viewport.capture import ByteCapture
import omni.isaac.core.utils.viewports as vp
import ctypes
from PIL import Image, ImageDraw, ImageFont
from concurrent.futures import ThreadPoolExecutor
import yaml
from .utils import get_models_directory, is_node_installed
class ClassifierError(Enum):
SUCCESS = auto()
NODEJS_NOT_INSTALLED = auto()
FAILED_TO_RETRIEVE_PROJECT_ID = auto()
MODEL_DEPLOYMENT_NOT_AVAILABLE = auto()
FAILED_TO_DOWNLOAD_MODEL = auto()
FAILED_TO_PROCESS_VIEWPORT = auto()
FAILED_TO_PROCESS_CLASSIFY_RESULT = auto()
class Classifier:
def __init__(
self, rest_client, project_id, impulse_image_height, impulse_image_width, log_fn
):
self.rest_client = rest_client
self.project_id = project_id
self.model_ready = False
self.model_path = os.path.expanduser(f"{get_models_directory()}/model.zip")
self.featuresTmpFile = None
self.log_fn = log_fn
self.impulse_image_height = impulse_image_height
self.impulse_image_width = impulse_image_width
self.image = None
self.original_width = None
self.original_height = None
self.new_width = None
self.new_height = None
self.output_image_path = None
async def __check_and_update_model(self):
if not is_node_installed():
self.log_fn("Error: NodeJS not installed")
return ClassifierError.NODEJS_NOT_INSTALLED
deployment_info = await self.rest_client.get_deployment_info(self.project_id)
if not deployment_info:
self.log_fn("Error: Failed to get deployment info")
return ClassifierError.MODEL_DEPLOYMENT_NOT_AVAILABLE
current_version = deployment_info.version
model_dir_name = f"ei-model-{self.project_id}-{current_version}"
model_dir = os.path.join(os.path.dirname(self.model_path), model_dir_name)
# Check if the model directory exists and its version
if os.path.exists(model_dir):
self.log_fn("Latest model version already downloaded.")
self.model_ready = True
return ClassifierError.SUCCESS
# If the model directory for the current version does not exist, delete old versions and download the new one
self.__delete_old_models(os.path.dirname(self.model_path), model_dir_name)
self.log_fn("Downloading model...")
model_content = await self.rest_client.download_model(self.project_id)
if model_content is not None:
self.__save_model(model_content, model_dir)
self.model_ready = True
self.log_fn("Model is ready for classification.")
return ClassifierError.SUCCESS
else:
self.log_fn("Error: Failed to download the model")
return ClassifierError.FAILED_TO_DOWNLOAD_MODEL
def __delete_old_models(self, parent_dir, exclude_dir_name):
for dirname in os.listdir(parent_dir):
if dirname.startswith("ei-model-") and dirname != exclude_dir_name:
dirpath = os.path.join(parent_dir, dirname)
shutil.rmtree(dirpath)
self.log_fn(f"Deleted old model directory: {dirpath}")
def __save_model(self, model_content, model_dir):
if not os.path.exists(model_dir):
os.makedirs(model_dir)
self.log_fn(f"'{model_dir}' directory created")
model_zip_path = os.path.join(model_dir, "model.zip")
with open(model_zip_path, "wb") as model_file:
model_file.write(model_content)
self.log_fn(f"Model zip saved to {model_zip_path}")
# Extract the zip file
shutil.unpack_archive(model_zip_path, model_dir)
os.remove(model_zip_path)
self.log_fn(f"Model extracted to {model_dir}")
def __resize_image_and_extract_features(
self, image, target_width, target_height, channel_count
):
# Resize the image
self.image = image.resize(
(target_width, target_height), Image.Resampling.LANCZOS
)
# Convert the image to the required color space
if channel_count == 3: # RGB
self.image = self.image.convert("RGB")
img_array = np.array(self.image)
# Extract RGB features as hexadecimal values
features = [
"0x{:02x}{:02x}{:02x}".format(*pixel)
for pixel in img_array.reshape(-1, 3)
]
elif channel_count == 1: # Grayscale
self.image = self.image.convert("L")
img_array = np.array(self.image)
# Repeat the grayscale values to mimic the RGB structure
features = [
"0x{:02x}{:02x}{:02x}".format(pixel, pixel, pixel)
for pixel in img_array.flatten()
]
return {
"features": features,
"originalWidth": image.width,
"originalHeight": image.height,
"newWidth": target_width,
"newHeight": target_height,
}
async def __capture_and_process_image(self):
def on_capture_completed(buffer, buffer_size, width, height, format):
try:
image_size = width * height * 4
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.POINTER(
ctypes.c_byte * image_size
)
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [
ctypes.py_object,
ctypes.c_char_p,
]
content = ctypes.pythonapi.PyCapsule_GetPointer(buffer, None)
pointer = ctypes.cast(
content, ctypes.POINTER(ctypes.c_byte * image_size)
)
np_arr = np.ctypeslib.as_array(pointer.contents)
image = Image.frombytes("RGBA", (width, height), np_arr.tobytes())
self.image = image
# Directly use the image for resizing and feature extraction
target_width = self.impulse_image_width
target_height = self.impulse_image_height
channel_count = 3 # 3 for RGB, 1 for grayscale
resized_info = self.__resize_image_and_extract_features(
image, target_width, target_height, channel_count
)
features = resized_info["features"]
features_str = ",".join(features)
self.original_width = resized_info["originalWidth"]
self.original_height = resized_info["originalHeight"]
self.new_width = resized_info["newWidth"]
self.new_height = resized_info["newHeight"]
try:
with tempfile.NamedTemporaryFile(
delete=False, suffix=".txt", mode="w+t"
) as tmp_file:
tmp_file.write(features_str)
self.featuresTmpFile = tmp_file.name
self.log_fn(f"Features saved to {tmp_file.name}")
except Exception as e:
self.log_fn(f"Error: Failed to save features to file: {e}")
except Exception as e:
self.log_fn(f"Error: Failed to process and save image: {e}")
viewport_window_id = vp.get_id_from_index(0)
viewport_window = vp.get_window_from_id(viewport_window_id)
viewport_api = viewport_window.viewport_api
capture_delegate = ByteCapture(on_capture_completed)
capture = viewport_api.schedule_capture(capture_delegate)
await capture.wait_for_result()
async def __run_subprocess(self, command, cwd):
"""Run the given subprocess command in a thread pool and capture its output."""
loop = asyncio.get_running_loop()
def subprocess_run():
# Execute the command and capture output
return subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
cwd=cwd,
)
with ThreadPoolExecutor() as pool:
# Run the blocking operation in the executor
result = await loop.run_in_executor(pool, subprocess_run)
return result
# TODO The logic to normalize bouding boxes is not right, so we simply display
# the boxes on the resized image directly
def __normalize_bounding_boxes(self, bounding_boxes):
orig_factor = self.original_width / self.original_height
new_factor = self.new_width / self.new_height
if orig_factor > new_factor:
# Boxed in with bands top/bottom
factor = self.new_width / self.original_width
offset_x = 0
offset_y = (self.new_height - (self.original_height * factor)) / 2
elif orig_factor < new_factor:
# Boxed in with bands left/right
factor = self.new_height / self.original_height
offset_x = (self.new_width - (self.original_width * factor)) / 2
offset_y = 0
else:
# Image was already at the right aspect ratio
factor = self.new_width / self.original_width
offset_x = 0
offset_y = 0
# Adjust bounding boxes
for bb in bounding_boxes:
bb["x"] = round((bb["x"] - offset_x) / factor)
bb["width"] = round(bb["width"] / factor)
bb["y"] = round((bb["y"] - offset_y) / factor)
bb["height"] = round(bb["height"] / factor)
return bounding_boxes
def __draw_bounding_boxes_and_save(self, bounding_boxes):
draw = ImageDraw.Draw(self.image)
try:
font = ImageFont.truetype("arial.ttf", 10)
except IOError:
font = ImageFont.load_default()
print("Custom font not found. Using default font.")
# Loop through the bounding boxes and draw them along with labels and confidence values
for box in bounding_boxes:
x, y, width, height = box["x"], box["y"], box["width"], box["height"]
label = box["label"]
confidence = box["value"]
# Draw the bounding box rectangle
draw.rectangle(((x, y), (x + width, y + height)), outline="red", width=2)
# Prepare the label text with confidence
label_text = f"{label} ({confidence:.2f})"
# Calculate the text position to appear above the bounding box
text_width, text_height = draw.textsize(label_text, font=font)
text_x = x + 5 # A small offset from the left edge of the bounding box
text_y = y - text_height # Above the bounding box with a small offset
# Ensure the text is not drawn outside the image
if text_y < 0:
text_y = (
y + height + 5
) # Below the bounding box if there is no space above
# Draw the text background
draw.rectangle(
((text_x - 2, text_y), (text_x + text_width + 2, text_y + text_height)),
fill="red",
)
# Draw the label text with confidence
draw.text((text_x, text_y), label_text, fill="white", font=font)
# Save the image
random_file_name = f"captured_with_bboxes_{uuid.uuid4()}.png"
self.output_image_path = os.path.join(tempfile.gettempdir(), random_file_name)
self.image.save(self.output_image_path)
self.log_fn(
f"Image with bounding boxes and labels saved at {self.output_image_path}"
)
async def classify(self):
self.log_fn("Checking and updating model...")
result = await self.__check_and_update_model()
if result != ClassifierError.SUCCESS:
self.log_fn(f"Failed to update model: {result.name}")
return result, None # Return None or an empty list for the bounding boxes
self.log_fn("Capturing and processing image...")
await self.__capture_and_process_image()
try:
model_dirs = glob.glob(
os.path.join(os.path.dirname(self.model_path), "ei-model-*")
)
if model_dirs:
latest_model_dir = max(model_dirs, key=os.path.getctime)
self.log_fn(f"Using latest model directory: {latest_model_dir}")
if self.featuresTmpFile:
script_dir = os.path.join(latest_model_dir, "node")
self.log_fn(f"Running inference on {self.featuresTmpFile}")
command = ["node", "run-impulse.js", self.featuresTmpFile]
# Run subprocess and capture its output
process_result = await self.__run_subprocess(command, script_dir)
if process_result.returncode == 0:
self.log_fn(f"{process_result.stdout}")
# Attempt to find the start of the JSON content
try:
json_start_index = process_result.stdout.find("{")
if json_start_index == -1:
self.log_fn(
"Error: No JSON content found in subprocess output."
)
return (
ClassifierError.FAILED_TO_PROCESS_CLASSIFY_RESULT,
None,
)
json_content = process_result.stdout[json_start_index:]
# Use YAML loader to parse the JSON content. We cannot use json directly
# because the result of running run-impulse.js is not a well formed JSON
# (i.e. missing double quotes in names)
output_dict = yaml.load(
json_content, Loader=yaml.SafeLoader
)
if "results" in output_dict:
output_dict["bounding_boxes"] = output_dict.pop(
"results"
)
self.__draw_bounding_boxes_and_save(
output_dict["bounding_boxes"]
)
return (
ClassifierError.SUCCESS,
self.output_image_path,
)
else:
self.log_fn(
"Error: classifier output does not contain 'results' key."
)
return (
ClassifierError.FAILED_TO_PROCESS_CLASSIFY_RESULT,
None,
)
except yaml.YAMLError as e:
self.log_fn(
f"Error parsing classification results with YAML: {e}"
)
return (
ClassifierError.FAILED_TO_PROCESS_CLASSIFY_RESULT,
None,
)
else:
self.log_fn(f"Classification failed: {process_result.stderr}")
return ClassifierError.FAILED_TO_PROCESS_CLASSIFY_RESULT, None
else:
self.log_fn("No model directory found.")
return ClassifierError.FAILED_TO_DOWNLOAD_MODEL, None
except subprocess.CalledProcessError as e:
self.log_fn(f"Error executing model classification: {e.stderr}")
return ClassifierError.FAILED_TO_DOWNLOAD_MODEL, None
| 16,201 | Python | 41.862434 | 117 | 0.542868 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/edgeimpulse/dataingestion/extension.py | # SPDX-License-Identifier: Apache-2.0
import omni.ext
import omni.ui as ui
from omni.kit.window.file_importer import get_file_importer
import asyncio
from .config import Config
from .uploader import upload_data
from .classifier import Classifier
from .state import State
from .client import EdgeImpulseRestClient
class EdgeImpulseExtension(omni.ext.IExt):
config = Config()
classifier = None
def on_startup(self, ext_id):
print("[edgeimpulse.dataingestion] Edge Impulse Extension startup")
self.config.print_config_info()
# Load the last known state from the config
saved_state_name = self.config.get_state()
try:
self.state = State[saved_state_name]
except KeyError:
self.state = State.NO_PROJECT_CONNECTED
self.reset_to_initial_state()
self._window = ui.Window("Edge Impulse", width=300, height=300)
with self._window.frame:
with ui.VStack():
self.no_project_content_area = ui.VStack(
spacing=15, height=0, visible=False
)
self.project_connected_content_area = ui.VStack(
spacing=15, height=0, visible=False
)
self.setup_ui_project_connected()
self.setup_ui_no_project_connected()
self.transition_to_state(self.state)
def reset_to_initial_state(self):
self.project_id = None
self.api_key = None
self.project_name = None
self.impulse = None
self.upload_logs_text = ""
self.uploading = False
self.classify_logs_text = ""
self.classifying = False
self.training_samples = 0
self.testing_samples = 0
self.anomaly_samples = 0
self.impulse_info = None
self.deployment_info = None
def transition_to_state(self, new_state):
"""
Transition the extension to a new state.
:param new_state: The new state to transition to.
"""
# Store the new state in memory
self.state = new_state
# Save the new state in the configuration
self.config.set_state(self.state)
# Call the corresponding UI setup method based on the new state
if self.state == State.PROJECT_CONNECTED:
self.project_id = self.config.get("project_id")
self.project_name = self.config.get("project_name")
self.api_key = self.config.get("project_api_key")
self.rest_client = EdgeImpulseRestClient(self.api_key)
self.project_info_label.text = (
f"Connected to project {self.project_id} ({self.project_name})"
)
self.update_ui_visibility()
def update_ui_visibility(self):
"""Update UI visibility based on the current state."""
if hasattr(self, "no_project_content_area") and hasattr(
self, "project_connected_content_area"
):
self.no_project_content_area.visible = (
self.state == State.NO_PROJECT_CONNECTED
)
self.project_connected_content_area.visible = (
self.state == State.PROJECT_CONNECTED
)
def setup_ui_no_project_connected(self):
with self.no_project_content_area:
# Title and welcome message
ui.Label(
"Welcome to Edge Impulse for NVIDIA Omniverse",
height=20,
word_wrap=True,
)
ui.Label(
"1. Create a free Edge Impulse account: https://studio.edgeimpulse.com/",
height=20,
word_wrap=True,
)
# API Key input section
with ui.VStack(height=20, spacing=10):
ui.Label(
"2. Connect to your Edge Impulse project by setting your API Key",
width=300,
)
with ui.HStack():
ui.Spacer(width=3)
ei_api_key = ui.StringField(name="ei_api_key", height=20)
ui.Spacer(width=3)
ui.Spacer(width=30)
with ui.HStack(height=20):
ui.Spacer(width=30)
# Connect button
connect_button = ui.Button("Connect")
connect_button.set_clicked_fn(
lambda: asyncio.ensure_future(
self.validate_and_connect_project(
ei_api_key.model.get_value_as_string()
)
)
)
ui.Spacer(width=30)
self.error_message_label = ui.Label(
"", height=20, word_wrap=True, visible=False
)
def setup_ui_project_connected(self):
with self.project_connected_content_area:
# Project information
self.project_info_label = ui.Label(
f"Connected to project {self.project_id} ({self.project_name})",
height=20,
word_wrap=True,
)
# Disconnect button
with ui.HStack(height=20):
ui.Spacer(width=30)
disconnect_button = ui.Button("Disconnect")
disconnect_button.set_clicked_fn(lambda: self.disconnect())
ui.Spacer(width=30)
# Data Upload Section
self.setup_data_upload_ui()
# Classification Section
self.setup_classification_ui()
def hide_error_message(self):
if self.error_message_label:
self.error_message_label.text = ""
self.error_message_label.visible = False
def display_error_message(self, message):
if self.error_message_label:
self.error_message_label.text = message
self.error_message_label.visible = True
async def validate_and_connect_project(self, api_key):
self.hide_error_message()
self.rest_client = EdgeImpulseRestClient(api_key)
project_info = await self.rest_client.get_project_info()
if project_info:
print(f"Connected to project: {project_info}")
self.config.set("project_id", project_info["id"])
self.config.set("project_name", project_info["name"])
self.config.set("project_api_key", api_key)
self.transition_to_state(State.PROJECT_CONNECTED)
else:
# Display an error message in the current UI
self.display_error_message(
"Failed to connect to the project. Please check your API key."
)
def disconnect(self):
print("Disconnecting")
self.reset_to_initial_state()
self.config.set("project_id", None)
self.config.set("project_name", None)
self.config.set("project_api_key", None)
self.classify_button.visible = False
self.ready_for_classification.visible = False
self.data_collapsable_frame.collapsed = True
self.classification_collapsable_frame.collapsed = True
self.transition_to_state(State.NO_PROJECT_CONNECTED)
### Data ingestion
def setup_data_upload_ui(self):
self.data_collapsable_frame = ui.CollapsableFrame(
"Data Upload", collapsed=True, height=0
)
self.data_collapsable_frame.set_collapsed_changed_fn(
lambda c: asyncio.ensure_future(self.on_data_upload_collapsed_changed(c))
)
with self.data_collapsable_frame:
with ui.VStack(spacing=10, height=0):
with ui.VStack(height=0, spacing=5):
self.training_samples_label = ui.Label(
f"Training samples: {self.training_samples}"
)
self.testing_samples_label = ui.Label(
f"Test samples: {self.testing_samples}"
)
self.anomaly_samples_label = ui.Label(
f"Anomaly samples: {self.anomaly_samples}"
)
with ui.HStack(height=20):
ui.Spacer(width=3)
ui.Label("Data Path", width=70)
ui.Spacer(width=8)
data_path = self.config.get("data_path", "No folder selected")
self.data_path_display = ui.Label(data_path, width=250)
ui.Spacer(width=10)
ui.Button("Select Folder", clicked_fn=self.select_folder, width=150)
ui.Spacer(width=3)
with ui.HStack(height=20):
ui.Spacer(width=3)
ui.Label("Dataset", width=70)
ui.Spacer(width=8)
dataset_types = ["training", "testing", "anomaly"]
self.dataset_type_dropdown = ui.ComboBox(0, *dataset_types)
self.dataset_type_subscription = (
self.dataset_type_dropdown.model.subscribe_item_changed_fn(
self.on_dataset_type_changed
)
)
initial_dataset_type = self.config.get("dataset_type", "training")
if initial_dataset_type in dataset_types:
for i, dtype in enumerate(dataset_types):
if dtype == initial_dataset_type:
self.dataset_type_dropdown.model.get_item_value_model().as_int = (
i
)
break
ui.Spacer(width=3)
with ui.HStack(height=20):
self.upload_button = ui.Button(
"Upload to Edge Impulse", clicked_fn=lambda: self.start_upload()
)
# Scrolling frame for upload logs
self.upload_logs_frame = ui.ScrollingFrame(height=100, visible=False)
with self.upload_logs_frame:
self.upload_logs_label = ui.Label("", word_wrap=True)
with ui.HStack(height=20):
self.clear_upload_logs_button = ui.Button(
"Clear Logs", clicked_fn=self.clear_upload_logs, visible=False
)
async def on_data_upload_collapsed_changed(self, collapsed):
if not collapsed:
await self.get_samples_count()
def select_folder(self):
def import_handler(filename: str, dirname: str, selections: list = []):
if dirname:
self.data_path_display.text = dirname
EdgeImpulseExtension.config.set("data_path", dirname)
else:
print("No folder selected")
file_importer = get_file_importer()
file_importer.show_window(
title="Select Data Folder",
show_only_folders=True,
import_handler=import_handler,
import_button_label="Select",
)
def on_dataset_type_changed(
self, item_model: ui.AbstractItemModel, item: ui.AbstractItem
):
value_model = item_model.get_item_value_model(item)
current_index = value_model.as_int
dataset_type = ["training", "testing", "anomaly"][current_index]
self.config.set("dataset_type", dataset_type)
def get_dataset_type(self):
selected_index = self.dataset_type_dropdown.model.get_value_as_int()
dataset_types = ["training", "testing", "anomaly"]
return dataset_types[selected_index]
def add_upload_logs_entry(self, message):
self.upload_logs_text += message + "\n"
self.upload_logs_label.text = self.upload_logs_text
self.update_clear_upload_logs_button_visibility()
def clear_upload_logs(self):
self.upload_logs_text = ""
self.upload_logs_label.text = self.upload_logs_text
self.update_clear_upload_logs_button_visibility()
def update_clear_upload_logs_button_visibility(self):
self.clear_upload_logs_button.visible = bool(self.upload_logs_text)
self.upload_logs_frame.visible = self.uploading
def start_upload(self):
if not self.uploading: # Prevent multiple uploads at the same time
self.uploading = True
self.upload_button.text = "Uploading..."
self.upload_logs_frame.visible = True
async def upload():
await upload_data(
self.config.get("project_api_key"),
self.config.get("data_path"),
self.config.get("dataset_type"),
self.add_upload_logs_entry,
lambda: asyncio.ensure_future(self.get_samples_count()),
self.on_upload_complete,
)
asyncio.ensure_future(upload())
def on_upload_complete(self):
self.uploading = False
self.upload_button.text = "Upload to Edge Impulse"
async def get_samples_count(self):
self.training_samples = await self.rest_client.get_samples_count(
self.project_id, "training"
)
self.testing_samples = await self.rest_client.get_samples_count(
self.project_id, "testing"
)
self.anomaly_samples = await self.rest_client.get_samples_count(
self.project_id, "anomaly"
)
print(
f"Samples count: Training ({self.training_samples}) - Testing ({self.testing_samples}) - Anomaly ({self.anomaly_samples})"
)
self.training_samples_label.text = f"Training samples: {self.training_samples}"
self.testing_samples_label.text = f"Test samples: {self.testing_samples}"
self.anomaly_samples_label.text = f"Anomaly samples: {self.anomaly_samples}"
### Classification
def setup_classification_ui(self):
self.classification_collapsable_frame = ui.CollapsableFrame(
"Classification", collapsed=True, height=0
)
self.classification_collapsable_frame.set_collapsed_changed_fn(
lambda c: asyncio.ensure_future(self.on_classification_collapsed_changed(c))
)
with self.classification_collapsable_frame:
with ui.VStack(spacing=10, height=0):
self.impulse_status_label = ui.Label(
"Fetching your Impulse design...", height=20, visible=False
)
self.deployment_status_label = ui.Label(
"Fetching latest model deployment...", height=20, visible=False
)
self.ready_for_classification = ui.Label(
"Your model is ready! You can now run inference on the current scene",
height=20,
visible=False,
)
ui.Spacer(height=20)
with ui.HStack(height=20):
self.classify_button = ui.Button(
"Classify current scene frame",
clicked_fn=lambda: asyncio.ensure_future(self.start_classify()),
visible=False,
)
# Scrolling frame for classify logs
self.classify_logs_frame = ui.ScrollingFrame(height=100, visible=False)
with self.classify_logs_frame:
self.classify_logs_label = ui.Label("", word_wrap=True)
with ui.HStack(height=20):
self.clear_classify_logs_button = ui.Button(
"Clear Logs", clicked_fn=self.clear_classify_logs, visible=False
)
self.classification_output_section = ui.CollapsableFrame(
"Ouput", collapsed=True, visible=False, height=0
)
with self.classification_output_section:
self.image_display = ui.Image(
"",
width=400,
height=300,
)
self.image_display.visible = False
async def on_classification_collapsed_changed(self, collapsed):
if not collapsed:
if not self.impulse_info:
self.impulse_status_label.visible = True
self.impulse_status_label.text = "Fetching your Impulse design..."
self.impulse_info = await self.rest_client.get_impulse(self.project_id)
if not self.impulse_info:
self.impulse_status_label.text = f"""Your Impulse is not ready yet.\n
Go to https://studio.edgeimpulse.com/studio/{self.project_id}/create-impulse to configure and train your model"""
return
if self.impulse_info.input_type != "image":
self.impulse_info = None
self.impulse_status_label.text = "Invalid Impulse input block type. Only 'image' type is supported"
return
self.impulse_status_label.text = "Impulse is ready"
self.impulse_status_label.visible = False
if not self.deployment_info or not self.deployment_info.has_deployment:
self.deployment_status_label.visible = True
self.deployment_status_label.text = (
"Fetching your latest model deployment..."
)
self.deployment_info = await self.rest_client.get_deployment_info(
self.project_id
)
if not self.deployment_info.has_deployment:
self.deployment_status_label.text = f"""Your model WebAssembly deployment is not ready yet.\n
Go to https://studio.edgeimpulse.com/studio/{self.project_id}/deployment to build a WebAssembly deployment"""
return
self.deployment_status_label.text = "Model deployment ready"
self.deployment_status_label.visible = False
if self.impulse_info and self.deployment_info:
self.classify_button.visible = True
self.ready_for_classification.visible = True
else:
self.classify_button.visible = False
self.ready_for_classification.visible = False
def add_classify_logs_entry(self, message):
self.classify_logs_text += message + "\n"
self.classify_logs_label.text = self.classify_logs_text
self.update_clear_classify_logs_button_visibility()
def clear_classify_logs(self):
self.classify_logs_text = ""
self.classify_logs_label.text = self.classify_logs_text
self.update_clear_classify_logs_button_visibility()
def update_clear_classify_logs_button_visibility(self):
self.clear_classify_logs_button.visible = bool(self.classify_logs_text)
self.classify_logs_frame.visible = self.classifying
async def get_impulse(self):
self.impulse = await self.rest_client.get_impulse(self.project_id)
async def start_classify(self):
if not self.classifier:
if not self.impulse:
await self.get_impulse()
if not self.impulse:
self.add_classify_logs_entry("Error: impulse is not ready yet")
return
self.classifier = Classifier(
self.rest_client,
self.project_id,
self.impulse.image_height,
self.impulse.image_width,
self.add_classify_logs_entry,
)
async def classify():
try:
self.classifying = True
self.classify_button.text = "Classifying..."
self.clear_classify_logs()
self.classification_output_section.visible = False
image_path = await self.classifier.classify()
corrected_path = image_path[1].replace("\\", "/")
self.image_display.source_url = corrected_path
self.image_display.width = ui.Length(self.impulse_info.image_width)
self.image_display.height = ui.Length(self.impulse_info.image_height)
self.image_display.visible = True
self.classification_output_section.visible = True
self.classification_output_section.collapsed = False
finally:
self.classifying = False
self.classify_button.text = "Classify"
asyncio.ensure_future(classify())
def on_shutdown(self):
print("[edgeimpulse.dataingestion] Edge Impulse Extension shutdown")
| 20,673 | Python | 38.988395 | 134 | 0.559716 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/edgeimpulse/dataingestion/__init__.py | # SPDX-License-Identifier: Apache-2.0
from .extension import *
| 64 | Python | 15.249996 | 37 | 0.75 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/edgeimpulse/dataingestion/utils.py | import omni.kit.app
import carb.settings
import carb.tokens
import os
import subprocess
def get_extension_name() -> str:
"""
Return the name of the Extension where the module is defined.
Args:
None
Returns:
str: The name of the Extension where the module is defined.
"""
extension_manager = omni.kit.app.get_app().get_extension_manager()
extension_id = extension_manager.get_extension_id_by_module(__name__)
extension_name = extension_id.split("-")[0]
return extension_name
def get_models_directory() -> str:
extension_name = get_extension_name()
models_directory_name = carb.settings.get_settings().get_as_string(
f"exts/{extension_name}/models_directory"
)
temp_kit_directory = carb.tokens.get_tokens_interface().resolve("${omni_data}")
models_directory = os.path.join(temp_kit_directory, models_directory_name)
return models_directory
def is_node_installed():
try:
subprocess.run(
["node", "--version"],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
return True
except (subprocess.CalledProcessError, FileNotFoundError):
return False
| 1,231 | Python | 27.651162 | 83 | 0.654752 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/edgeimpulse/dataingestion/uploader.py | # uploader.py
import asyncio
import requests
import os
async def upload_data(
api_key,
data_folder,
dataset,
log_callback,
on_sample_upload_success,
on_upload_complete,
):
dataset_types = ["training", "testing", "anomaly"]
if dataset not in dataset_types:
log_callback(
"Error: Dataset type invalid (must be training, testing, or anomaly)."
)
return
url = "https://ingestion.edgeimpulse.com/api/" + dataset + "/files"
try:
for file in os.listdir(data_folder):
file_path = os.path.join(data_folder, file)
label = os.path.basename(file_path).split(".")[0]
if os.path.isfile(file_path):
await asyncio.sleep(1)
try:
with open(file_path, "rb") as file_data:
res = requests.post(
url=url,
headers={
"x-label": label,
"x-api-key": api_key,
"x-disallow-duplicates": "1",
},
files={
"data": (
os.path.basename(file_path),
file_data,
"image/png",
)
},
)
if res.status_code == 200:
log_callback(f"Success: {file_path} uploaded successfully.")
on_sample_upload_success()
else:
log_callback(
f"Error: {file_path} failed to upload. Status Code {res.status_code}: {res.text}"
)
except Exception as e:
log_callback(
f"Error: Failed to process {file_path}. Exception: {str(e)}"
)
except FileNotFoundError:
log_callback("Error: Data Path invalid.")
log_callback("Done")
on_upload_complete()
| 2,196 | Python | 35.016393 | 113 | 0.414845 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/edgeimpulse/dataingestion/impulse.py | class Impulse:
def __init__(self, input_type, image_width=None, image_height=None):
self.input_type = input_type
self.image_width = image_width
self.image_height = image_height
| 205 | Python | 33.333328 | 72 | 0.64878 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/edgeimpulse/dataingestion/client.py | import httpx
from .impulse import Impulse
from .deployment import DeploymentInfo
class EdgeImpulseRestClient:
def __init__(self, project_api_key):
self.base_url = "https://studio.edgeimpulse.com/v1/api/"
self.headers = {"x-api-key": project_api_key}
async def get_project_info(self):
"""Asynchronously retrieves the project info."""
async with httpx.AsyncClient() as client:
response = await client.get(
f"{self.base_url}projects", headers=self.headers
)
if response.status_code == 200 and response.json()["success"]:
project = response.json()["projects"][0]
return {"id": project["id"], "name": project["name"]}
else:
return None
async def get_deployment_info(self, project_id):
"""Asynchronously retrieves deployment information, including version."""
async with httpx.AsyncClient() as client:
response = await client.get(
f"{self.base_url}{project_id}/deployment?type=wasm&engine=tflite",
headers=self.headers,
)
if response.status_code == 200 and response.json().get("success"):
# Returns the deployment info if available
version = response.json().get("version")
has_deployment = response.json().get("hasDeployment")
return DeploymentInfo(
version=version,
has_deployment=has_deployment,
)
else:
# Returns None if the request failed or no deployment info was found
return None
async def download_model(self, project_id):
"""Asynchronously downloads the model."""
async with httpx.AsyncClient() as client:
response = await client.get(
f"{self.base_url}{project_id}/deployment/download?type=wasm&engine=tflite",
headers=self.headers,
)
if response.status_code == 200:
return response.content
else:
return None
async def get_impulse(self, project_id):
"""Asynchronously fetches the impulse details and returns an Impulse object or None"""
async with httpx.AsyncClient() as client:
response = await client.get(
f"{self.base_url}{project_id}/impulse",
headers=self.headers,
)
if response.status_code == 200:
data = response.json()
if "impulse" in data and data["impulse"].get("inputBlocks"):
first_input_block = data["impulse"]["inputBlocks"][0]
return Impulse(
input_type=first_input_block.get("type"),
image_width=first_input_block.get("imageWidth"),
image_height=first_input_block.get("imageHeight"),
)
else:
return None
else:
return None
async def get_samples_count(self, project_id, category="training"):
"""Asynchronously fetches the number of samples ingested for a specific category"""
async with httpx.AsyncClient() as client:
response = await client.get(
f"{self.base_url}{project_id}/raw-data/count?category={category}",
headers=self.headers,
)
if response.status_code == 200:
data = response.json()
if "count" in data:
return data["count"]
else:
return 0
else:
return 0
| 3,746 | Python | 40.175824 | 94 | 0.540844 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/edgeimpulse/dataingestion/tests/__init__.py | from .test_hello_world import * | 31 | Python | 30.999969 | 31 | 0.774194 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/edgeimpulse/dataingestion/tests/test_hello_world.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import omni.example.apiconnect
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello_public_function(self):
result = omni.example.apiconnect.some_public_function(4)
self.assertEqual(result, 256)
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 1,682 | Python | 34.80851 | 142 | 0.68371 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-26
- Initial version of extension UI template with a window
| 178 | Markdown | 18.888887 | 80 | 0.702247 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/docs/README.md | # Edge Impulse Data Ingestion
NVIDIA Omniverse extension to upload data directly into your Edge Impulse project.
| 114 | Markdown | 27.749993 | 82 | 0.824561 |
md84419/coderage-ext-spacemouse/LICENSE-kit-extension-template.md |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2022 NVIDIA CORPORATION
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | 11,348 | Markdown | 55.183168 | 77 | 0.732376 |
md84419/coderage-ext-spacemouse/README.md | # CodeRage's coderage.io.spacemouse extension for Omniverse
# Getting Started
## Install Omniverse and some Apps
1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download)
2. Install and launch one of *Omniverse* apps in the Launcher. For instance: *Code*.
## Option 1: Clone this repo and add this extension to your *Omniverse App*
0. Clone the repo
- `git https://github.com/md84419/coderage-ext-spacemouse.git`
-- or -
- `git clone [email protected]:md84419/coderage-ext-spacemouse.git`
1. In the *Omniverse App* open extension manager: *Window* → *Extensions*.
2. In the *Extension Manager Window* open a settings page, with a small gear button in the top left bar.
3. In the settings page there is a list of *Extension Search Paths*. Add the `exts` subfolder for this extension there as another search path, e.g.: `C:\projects\coderage-ext-spacemouse\exts`

4. Now you can find `coderage.io.spacemouse` extension in the top left search bar. Select and enable it.
### A few tips
* Now that `exts` folder was added to the search you can add new extensions to this folder and they will be automatically found by the *App*.
* Look at the *Console* window for warnings and errors. It also has a small button to open the current log file.
* All the same commands work on Linux. Replace `.bat` with `.sh` and `\` with `/`.
* `Extension name` is a folder name in the `exts` folder, in this example: `coderage.io.spacemouse`.
* The most important feature an extension has is a config file: `extension.toml`, take a peek.
## Option 2: Add this extension to your *Omniverse App* without cloning the github repo
Alternatively, a direct link to a git repository can be added to *Omniverse Kit* extension search paths. Instead of the 'C:\' path above, use this path in the Extension manager (```Extension Manager -> Gear Icon -> Extension Search Path```):
`git://github.com/md84419/coderage-ext-spacemouse.git?branch=main&dir=exts`
Notice that `exts` is the repo subfolder containing the extension(s). More information can be found in ["Git URL as Extension Search Paths"](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_advanced.html#git-url-paths) section of the [Omniverse developers manual](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/index.html).
## Option 3: Linking with an *Omniverse* app
For a better experience when developing this extension, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included.
1. Remove the search path added in the previous section.
2. Open this cloned repo using Visual Studio Code: `code C:\projects\coderage-ext-spacemouse`. It will suggest installing a few extensions to improve the Python experience.
3. In the terminal (CTRL + \`), run:
```bash
> link_app.bat
```
If successful you should see the `app` folder link in the root of this repo.
If multiple Omniverse apps are installed, the script will select the recommended one. Or you can explicitly pass an app:
```bash
> link_app.bat --app create
```
You can also just pass a path to use when creating the link:
```bash
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4"
```
4. Run this app with `exts` folder added as an extensions search path and new extension enabled:
```bash
> app\omni.code.bat --ext-folder exts --enable coderage.io.spacemouse
```
- `--ext-folder [path]` - adds a new folder to the search path
- `--enable [extension]` - enables an extension on startup.
Use `-h` for help:
```bash
> app\omni.code.bat -h
```
5. After the *App* has started you should see:
* the extension search paths in *Extensions* window as in the previous section.
* the extension is enabled in the list of extensions.
6. If you look inside `omni.code.bat` or any other *Omniverse App*, they all run *Omniverse Kit* (`kit.exe`). *Omniverse Kit* is the Omniverse Application runtime that powers *Apps* build out of extensions.
Think of it as analagous to `python.exe`. It is a small runtime, that enables all the basics, like settings, Python, logging and searches for extensions. **Everything else is an extension.** You can run only this new extension without running any big *App* like *Code*:
```bash
> app\kit\kit.exe --ext-folder exts --enable coderage.io.spacemouse
```
It starts much faster and will only have extensions enabled that are required for this new extension (look at the `[dependencies]` section of `extension.toml`). You can enable more extensions: try adding `--enable omni.kit.window.extensions` to have the extensions window enabled (yes, extension window is an extension too!):
```bash
> app\kit\kit.exe --ext-folder exts --enable coderage.io.spacemouse --enable omni.kit.window.extensions
```
You should see a menu in the top left. From here you can enable more extensions from the UI.
### A few tips
* In the *Extensions* window, press the *Burger* menu button near the search bar and select *Show Extension Graph*. It will show how the current *App* comes to be: all extensions and dependencies.
* Learn more: [Extensions system documentation](http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/extensions.html)
# Running Tests
To run tests we run a new process where only the tested extension (and it's dependencies) is enabled. Like in example above + testing system (`omni.kit.test` extension). There are two ways to run extension tests:
1. Run: `app\kit\test_ext.bat coderage.io.spacemouse --ext-folder exts`
That will run a test process with all tests and then exit. For development mode, pass `--dev`: that will open the test selection window. As everywhere, hot-reload also works in this mode, give it a try by changing some code!
2. Alternatively, in *Extension Manager* (*Window → Extensions*) find your extension, click on the *TESTS* tab, click *Run Test*
For more information about testing refer to: [testing doc](http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/ext_testing.html).
# Sharing This Extension to Github
To make the extension available to other users, use [Github Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository).
1. Make sure the repo has [omniverse-kit-extension](https://github.com/topics/omniverse-kit-extension) topic set for auto discovery.
2. For each new release increment extension version (in `extension.toml`) and update the changelog (in `docs/CHANGELOG.md`). [Semantic versionning](https://semver.org/) must be used to express the severity of API changes.
- See time index 4:17 in [this video from Mati](https://www.youtube.com/watch?v=lEQ2VmzXMgQ) for more information.
# Known limitations
1. Integration is achieved by simulating (injecting) keyboard and mouse events into the application.
This is a significant limitation as it means that the usual use case of operating the spacemouse with
the non-dominant hand and the regular mouse with the dominant hand, doesn't work - one can only use one
input device at a time. Hopefully in a future release a better API for injecting Spacemouse commands
will become available.
2. spacenavigator dependency is currently Windows-only. Therefore this extension only works on Windows currently. There is a fork at https://github.com/JakubAndrysek/PySpaceMouse which we should investigate.
To reduce dependency friction, we may wish to stick with spacenavigator for Windows and only use
pyspacemouse on Linux and Mac OS X
# Contributing
The source code for this repository is provided as-is. We only accept outside contributions from individuals who have signed an Individual Contributor License Agreement.
| 7,860 | Markdown | 52.114865 | 366 | 0.759542 |
md84419/coderage-ext-spacemouse/LICENSE.md |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright MICHAEL DAVEY CONSULTING LTD LIMITED, 2022, 2024.
Portions Copyright 2022 NVIDIA CORPORATION:
https://github.com/NVIDIA-Omniverse/kit-extension-template
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| 11,493 | Markdown | 54.52657 | 77 | 0.732359 |
md84419/coderage-ext-spacemouse/tools/scripts/link_app.py | import argparse
import json
import os
import sys
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,814 | Python | 32.117647 | 133 | 0.562189 |
md84419/coderage-ext-spacemouse/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
md84419/coderage-ext-spacemouse/tools/packman/bootstrap/install_package.py | # Copyright 2019 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import shutil
import sys
import tempfile
import zipfile
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,844 | Python | 33.166666 | 108 | 0.703362 |
md84419/coderage-ext-spacemouse/exts/coderage.io.spacemouse/coderage/io/spacemouse/extension.py | from datetime import datetime, timedelta
import math
import platform
import carb
import omni.ext
import omni.kit.viewport.window
import omni.kit.app
import omni.kit.viewport
import omni.ui.scene
import omni.ui as ui
import omni.usd
# import omni.kit.viewport.utility as vp_util
from omni.kit.viewport.utility import get_active_viewport
from omni.kit.viewport.utility.camera_state import ViewportCameraState as VpCamera
from pxr import Usd, UsdGeom, Gf, Sdf
if platform.system() == 'Windows':
omni.kit.pipapi.install("pywinusb")
# import pywinusb
import spacenavigator
UPDATE_TIME_MILLIS = 10
DEFAULT_STEP = 50 # Ideally we'd get this from Camera Speed @TODO
DEFAULT_ROTATION = 1
DEBUG = True
# Spacemouse supports six degrees of freedom. By default, these are mapped to the ViewPort camera as so:
# * x: tracking (trucking) left and right
# * y: dollying forwards and backwards (move the *camera's* Omniverse-z axis)
# * z: pedestal lift/lower
# * roll: rolling the camera body on its z axis (the line-of-sight axis)
# * pitch: tilting the camera up and down (rotating camera body on its horizontal axis)
# * yaw: panning left/right (rotating camera body on its vertical axis)
class CoderageIoSpacemouseExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._count = 0
self.__previous_time = None
self.__previous_state = None
viewport = get_active_viewport()
self.__camera_path = str(viewport.camera_path)
self._MovementValue = 1.0
self._RotationValue = 1.0
self._MovementScalar = DEFAULT_STEP
self._RotationScalar = DEFAULT_ROTATION
print("[coderage.io.spacemouse] coderage io spacemouse startup")
# Angles
def RollLeft_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 0.0, "y": 0.0, "z": 0.0, "roll": self._RotationValue, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state)
def PanRight_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 0.0, "y": 0.0, "z": 0.0, "roll": 0.0, "pitch": 0.0, "yaw": self._RotationValue, "buttons": [0,0]}
)
self.update_state(state)
def TiltDown_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 0.0, "y": 0.0, "z": 0.0, "roll": 0.0, "pitch": self._RotationValue, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state)
def RollRight_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 0.0, "y": 0.0, "z": 0.0, "roll": -self._RotationValue, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state)
def PanLeft_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 0.0, "y": 0.0, "z": 0.0, "roll": 0.0, "pitch": 0.0, "yaw": -self._RotationValue, "buttons": [0,0]}
)
self.update_state(state)
def TiltUp_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 0.0, "y": 0.0, "z": 0.0, "roll": 0.0, "pitch": -self._RotationValue, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state)
# Movements
def Up_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 0.0, "y": 0.0, "z": self._MovementValue, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state)
def Forward_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 0.0, "y": self._MovementValue, "z": 0.0, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state)
def Down_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 0.0, "y": 0.0, "z": -self._MovementValue, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state)
def Left_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": -self._MovementValue, "y": 0.0, "z": 0.0, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state)
def Back_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 0.0, "y": -self._MovementValue, "z": 0.0, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state)
def Right_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": self._MovementValue, "y": 0.0, "z": 0.0, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state)
def XAxisUp_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": self._MovementValue, "y": 0.0, "z": 0.0, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state, True)
def YAxisUp_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 0.0, "y": self._MovementValue, "z": 0.0, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state, True)
def ZAxisUp_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 0.0, "y": 0.0, "z": self._MovementValue, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state, True)
def XAxisDown_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": -self._MovementValue, "y": 0.0, "z": 0.0, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state, True)
def YAxisDown_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 0.0, "y": -self._MovementValue, "z": 0.0, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state, True)
def ZAxisDown_Click():
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 0.0, "y": 0.0, "z": -self._MovementValue, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state, True)
self._window = ui.Window("Spacemouse debug", width=300, height=300)
with self._window.frame:
with ui.VStack():
# add an IntSlider for translate Strength
ui.Label("Camera Rotation Amount")
self._rotationSlider = ui.IntSlider(min = 1, max = 90, step=5)
self._rotationSlider.model.set_value(self._RotationScalar)
# self._rotationValue = 5
self._rotationSlider.model.add_value_changed_fn(self._onrotation_value_changed)
with ui.HStack():
rollLeftButton = ui.Button("Roll L", clicked_fn=RollLeft_Click)
panLeftButton = ui.Button("Pan L", clicked_fn=PanLeft_Click)
tiltDownButton = ui.Button("Tilt -", clicked_fn=TiltDown_Click)
with ui.HStack():
rollRightButton = ui.Button("Roll R", clicked_fn=RollRight_Click)
panRightButton = ui.Button("Pan R", clicked_fn=PanRight_Click)
tiltUpButton = ui.Button("Tilt +", clicked_fn=TiltUp_Click)
# add an IntSlider for translate Strength
ui.Label("Camera Movement Amount")
self._movementSlider = ui.IntSlider(min = 10, max = 1000, step=10)
self._movementSlider.model.set_value(self._MovementScalar)
# self._MovementValue = 100
self._movementSlider.model.add_value_changed_fn(self._on_movement_changed)
with ui.HStack():
upButton = ui.Button("Up", clicked_fn=Up_Click)
forwardButton = ui.Button("Forward", clicked_fn=Forward_Click)
downButton = ui.Button("Down", clicked_fn=Down_Click)
with ui.HStack():
leftButton = ui.Button("Left", clicked_fn=Left_Click)
backButton = ui.Button("Back", clicked_fn=Back_Click)
rightButton = ui.Button("Right", clicked_fn=Right_Click)
with ui.HStack():
xAxisButtonUp = ui.Button("X +", clicked_fn=XAxisUp_Click)
yAxisButtonUp = ui.Button("Y +", clicked_fn=YAxisUp_Click)
zAxisButtonUp = ui.Button("Z +", clicked_fn=ZAxisUp_Click)
with ui.HStack():
xAxisButtonDown = ui.Button("X -", clicked_fn=XAxisDown_Click)
yAxisButtonDown = ui.Button("Y -", clicked_fn=YAxisDown_Click)
zAxisButtonDown = ui.Button("Z -", clicked_fn=ZAxisDown_Click)
# with ui.VStack():
self._label_status_line_1 = ui.Label("")
self._label_status_line_2 = ui.Label("")
self._label_buttons = ui.Label("")
self._label_connected = ui.Label("")
self._label_debug = ui.Label("")
# with ui.HStack():
# ui.Button("Move", clicked_fn=self.on_click)
# Note1: It is possible to have multiple 3D mice connected.
# See: https://github.com/johnhw/pyspacenavigator/blob/master/spacenavigator.py
self._nav1 = spacenavigator.open(callback=self.on_spacemouse,button_callback=self.on_spacemouse_buttons, DeviceNumber=0)
self._nav2 = spacenavigator.open(callback=self.on_spacemouse,button_callback=self.on_spacemouse_buttons, DeviceNumber=1)
if self._nav1 or self._nav2:
if self._nav1.connected or self._nav2.connected:
self._label_connected.text = "Connected"
else:
self._label_connected.text = "Not Connected"
else:
self._label_connected.text = "No spacemouse detected"
def on_click(self):
current_time = datetime.now()
if self.__previous_time:
if current_time - self.__previous_time < timedelta(milliseconds=UPDATE_TIME_MILLIS):
return
self.__previous_time = current_time
state: spacenavigator.SpaceNavigator = spacenavigator.SpaceNavigator(
**{"t": 255.0, "x": 30.0, "y": 30.0, "z": 30.0, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, "buttons": [0,0]}
)
self.update_state(state)
def on_spacemouse(self, state: spacenavigator.SpaceNavigator):
if self.__previous_state == state:
return
self.__previous_state = state
current_time = datetime.now()
if self.__previous_time:
if current_time - self.__previous_time < timedelta(milliseconds=UPDATE_TIME_MILLIS):
return
self.__previous_time = current_time
self.update_state(state)
def on_spacemouse_buttons(self, state: spacenavigator.SpaceNavigator, buttons: spacenavigator.ButtonState):
current_time = datetime.now()
if self.__previous_time:
if current_time - self.__previous_time < timedelta(milliseconds=UPDATE_TIME_MILLIS):
return
self.__previous_time = current_time
self.update_state(state)
def get_projection_matrix(self, fov, aspect_ratio, z_near, z_far) -> omni.ui.scene.Matrix44:
"""
Calculate the camera projection matrix.
Args:
fov (float): Field of View (in radians)
aspect_ratio (float): Image aspect ratio (Width / Height)
z_near (float): distance to near clipping plane
z_far (float): distance to far clipping plane
Returns:
(UsdGeom.Matrix4d): Flattened `(4, 4)` view projection matrix
"""
a = -1.0 / math.tan(fov / 2)
b = -a * aspect_ratio
c = z_far / (z_far - z_near)
d = z_near * z_far / (z_far - z_near)
return omni.ui.scene.Matrix44(
a, 0.0, 0.0, 0.0,
0.0, b, 0.0, 0.0,
0.0, 0.0, c, 1.0,
0.0, 0.0, d, 0.0
)
def gfmatrix_to_matrix44(self, matrix: Gf.Matrix4d) -> omni.ui.scene.Matrix44:
"""
A helper method to convert Gf.Matrix4d to omni.ui.scene.Matrix44
Args:
matrix (Gf.Matrix): Input matrix
Returns:
UsdGeom.Matrix4d: Output matrix
"""
# convert the matrix by hand
# USING LIST COMPREHENSION IS VERY SLOW (e.g. return [item for sublist
# in matrix for item in sublist]), which takes around 10ms.
matrix44 = omni.ui.scene.Matrix44(
matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3],
matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3],
matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3],
matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3]
)
return matrix44
def gfmatrix_to_array(self, matrix: Gf.Matrix4d) -> list:
"""
A helper method to convert Gf.Matrix4d to omni.ui.scene.Matrix44
Args:
matrix (Gf.Matrix): Input matrix
Returns:
UsdGeom.Matrix4d: Output matrix
"""
# flatten the matrix by hand
# USING LIST COMPREHENSION IS VERY SLOW (e.g. return [item for sublist
# in matrix for item in sublist]), which takes around 10ms.
return (
matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3],
matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3],
matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3],
matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3]
)
def decompose_matrix(self, mat: Gf.Matrix4d):
reversed_ident_matrix = reversed(Gf.Matrix3d())
translate: Gf.Vec3d = mat.ExtractTranslation()
scale: Gf.Vec3d = Gf.Vec3d(*(v.GetLength() for v in mat.ExtractRotationMatrix()))
mat.Orthonormalize()
rotate: Gf.Vec3d = Gf.Vec3d(*reversed(mat.ExtractRotation().Decompose(*reversed_ident_matrix)))
return translate, rotate, scale
def update_translate(self, state, cam_state, update_world_position=False):
## On spacemouse, by default x is left(-)/right(+), y is forward(+)/backwards(-), z is up(+)/down(-)
## In Omniverse, -z is always camera forwards
cam_state = VpCamera()
# Get the current position and target
cam_pos = cam_state.position_world
cam_target = cam_state.target_world
# Create the vector transform - set to state * d
transform = Gf.Vec3d(
round(state.x * self._MovementScalar, 1),
round(state.z * self._MovementScalar, 1),
round(-state.y * self._MovementScalar, 1)
)
if not update_world_position:
# compute world transform from local
world_translation = cam_state.usd_camera.ComputeLocalToWorldTransform(Usd.TimeCode.Default()).Transform(transform)
omni.kit.commands.execute('ChangeProperty',
prop_path=Sdf.Path(self.__camera_path+'.xformOp:translate'),
value=world_translation,
prev=cam_pos)
else:
world_translation = transform
cam_pos = cam_pos + world_translation
cam_target = cam_target + world_translation
# Update the world
cam_state.set_position_world(cam_pos, False)
cam_state.set_target_world(cam_target, False)
return transform
def update_rotate(self, state, cam_state, world=False):
# Get the local transformation - I think we should be using ComputeLocalToWorldTransform rather than GetLocalTransformation & decompose_matrix
yawsign = 1
local_transformation: Gf.Matrix4d = cam_state.usd_camera.GetLocalTransformation()
# translation: Gf.Vec3d = local_transformation.ExtractTranslation()
# rotation: Gf.Rotation = local_transformation.ExtractRotation()
decomposed_transform = self.decompose_matrix(local_transformation)
rotationX = round(decomposed_transform[1][0], 1)
rotationY = round(decomposed_transform[1][1], 1)
rotationZ = round(decomposed_transform[1][2], 1)
# Attempt to hack around issue with going beyond yaw (pan) -90 or +90
# if( yawsign == 1 and rotationX == -180.0 ):
# yawsign = -1
# elif( yawsign == 1 and rotationX == 180.0 ):
# yawsign = -1
prev_rotation = Gf.Vec3f(rotationX, rotationY, rotationZ)
new_rotationX = round(rotationX - state.pitch * self._RotationScalar, 1)
new_rotationY = round(rotationY - state.yaw * self._RotationScalar * yawsign, 1)
new_rotationZ = round(rotationZ + state.roll * self._RotationScalar, 1)
alt_local_rotation = Gf.Vec3d(new_rotationX, new_rotationY, new_rotationZ)
if DEBUG:
new_rotation = Gf.Rotation(Gf.Vec3d(1, 0, 0), new_rotationX) * \
Gf.Rotation(Gf.Vec3d(0, 1, 0), new_rotationY) * \
Gf.Rotation(Gf.Vec3d(0, 0, -1), new_rotationZ)
rotation_transform = Gf.Matrix4d().SetRotate(new_rotation)
reversed_ident_mtx = reversed(Gf.Matrix3d())
rotation_transform.Orthonormalize()
local_rotation = Gf.Vec3d(*reversed(rotation_transform.ExtractRotation().Decompose(*reversed_ident_mtx)))
self._label_debug.text = f"{new_rotationX:.03f} | {new_rotationY:.03f} | {new_rotationZ:.03f} | {yawsign}"
self._label_debug.text = self._label_debug.text + '\n' + f"{local_rotation[0]:.03f} | {local_rotation[1]:.03f} | {local_rotation[2]:.03f}"
world_rotation = alt_local_rotation
# Update the world
omni.kit.commands.execute('ChangeProperty',
prop_path=Sdf.Path(self.__camera_path+'.xformOp:rotateXYZ'),
value=world_rotation,
prev=prev_rotation)
def update_state(self, state: spacenavigator.SpaceNavigator, world=False):
status_line_1 = f"{state.x:.03f}, {state.y:.03f}, {state.z:.03f}"
status_line_2 = f"roll: {state.roll:.03f}, tilt: {state.pitch:.03f}, pan: {state.yaw:.03f}"
# Note1: The number of buttons varies with the type of 3DConnexion product we have
# Note2: The mappings of buttons is user-configurable so not guaranteed order - we have to account for this
buttons = f"buttons: {state.buttons}"
self._label_status_line_1.text = status_line_1
self._label_status_line_2.text = status_line_2
self._label_buttons.text = buttons
self._label_connected.text = f"{state.t}"
if (
state.x != 0
or state.y != 0
or state.z != 0
or state.roll != 0
or state.pitch !=0
or state.yaw != 0
):
## On spacemouse, by default x is left(-)/right(+), y is forward(+)/backwards(-), z is up(+)/down(-)
## In Omniverse, -z is always camera forwards
cam_state = VpCamera()
# Update position
self.update_translate(state, cam_state, world)
# Now calculate the rotation
self.update_rotate(state, cam_state, world)
def _on_movement_changed(self, model: ui.SimpleIntModel):
self._MovementScalar = model.get_value_as_int()
self._label_debug.text = "Camera movement value = " + str(self._MovementScalar)
def _onrotation_value_changed(self, model: ui.SimpleIntModel):
self._RotationValue = model.get_value_as_int()
self._label_debug.text = "Camera rotation value = " + str(self._RotationValue)
def on_shutdown(self):
if self._nav1 is not None:
self._nav1.close()
self._nav1.callback = None
self._nav1.button_callback = None
if self._nav2 is not None:
self._nav2.close()
self._nav2.callback = None
self._nav2.button_callback = None
self._nav1 = None
self._nav2 = None
self.__previous_time = None
if self._label_status_line_1 is not None:
self._label_status_line_1.text = ""
if self._label_status_line_2 is not None:
self._label_status_line_2.text = ""
if self._label_buttons is not None:
self._label_buttons.text = ""
if self._label_connected is not None:
self._label_connected.text = "Not connected"
self._window = None
self._active_viewport_window = None
self._ext_id = None
print("[coderage.io.spacemouse] coderage io spacemouse shutdown")
| 22,034 | Python | 44.526859 | 154 | 0.564083 |
md84419/coderage-ext-spacemouse/exts/coderage.io.spacemouse/coderage/io/spacemouse/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
md84419/coderage-ext-spacemouse/exts/coderage.io.spacemouse/coderage/io/spacemouse/tests/__init__.py | from .test_hello_world import * | 31 | Python | 30.999969 | 31 | 0.774194 |
md84419/coderage-ext-spacemouse/exts/coderage.io.spacemouse/coderage/io/spacemouse/tests/test_hello_world.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import coderage.io.spacemouse
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello_public_function(self):
result = coderage.io.spacemouse.some_public_function(4)
self.assertEqual(result, 256)
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 1,680 | Python | 34.765957 | 142 | 0.683333 |
md84419/coderage-ext-spacemouse/exts/coderage.io.spacemouse/config/extension.toml | [package]
version = "0.0.1"
authors = ["CodeRage"]
title = "Spacemouse Driver"
description="Integration of 3DConnexion's spacemouse with Omniverse."
category = "other"
keywords = ["kit", "io", "spacemouse", "3dconnexion", "spacenavigator"]
readme = "docs/README.md"
repository = "https://github.com/md84419/coderage-ext-spacemouse.git"
icon = "data/icon.png"
preview_image = "data/preview.png"
changelog="docs/CHANGELOG.md"
feature=true
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
"omni.kit.pipapi" = {}
#"omni.kit.window.viewport" = {}
"omni.kit.viewport.window" = {}
[python.pipapi]
requirements = [
# "pywinusb", # Required by spacenavigator when on Windows. See extension.py.
# The next line is equivilent to .\app\kit\python\python.exe -m pip install "spacenavigator@git+https://github.com/md84419/pyspacenavigator#egg=spacenavigator.py-0.2.3"
"spacenavigator@git+https://github.com/md84419/pyspacenavigator#egg=spacenavigator.py-0.2.3==0.2.3"
]
modules = [
"spacenavigator"
]
use_online_index = true
# Main python module this extension provides, it will be publicly available as "import coderage.io.spacemouse".
[[python.module]]
name = "coderage.io.spacemouse"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,349 | TOML | 30.395348 | 172 | 0.722016 |
md84419/coderage-ext-spacemouse/exts/coderage.io.spacemouse/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.0.1] - 2023-05-13
- Initial commit
## [0.0.2] - 2023-12-19
- Jen's version
## [0.0.3] - 2024-04-07
- x, y, z partially working. Better debug panel
| 251 | Markdown | 16.999999 | 80 | 0.63745 |
md84419/coderage-ext-spacemouse/exts/coderage.io.spacemouse/docs/README.md | # CodeRage's coderage.io.spacemouse extension for Omniverse
Integration of 3DConnexion's spacemouse with Omniverse
The SpaceMouse provides 6 degrees of freedom navigation in virtual space.
Some user choose to navigate the spacemouse with the left hand and the normal mouse the their right hand. Alternatively, you can simply switch between the two
input devices with your right hand.
- [Video](https://youtu.be/1xoEKTCjVE8)
- [Link to 3D connexion website](https://3dconnexion.com/uk/spacemouse)
| 500 | Markdown | 40.749997 | 158 | 0.804 |
md84419/coderage-ext-spacemouse/exts/coderage.io.spacemouse/docs/index.rst | coderage.io.spacemouse
#############################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule::"coderage.io.spacemouse"
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
:exclude-members: contextmanager
| 345 | reStructuredText | 15.47619 | 43 | 0.626087 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.