diff --git a/.gitattributes b/.gitattributes index 64383c41bd779501420d089b3fa59142b8ab8811..1858848dc334974cb78aacefeb6ad1add7b6ee55 100644 --- a/.gitattributes +++ b/.gitattributes @@ -166,3 +166,4 @@ simulation/.venv-planner/lib/python3.12/site-packages/pip/_vendor/rich/__pycache simulation/.venv-planner/lib/python3.12/site-packages/pip/_vendor/rich/__pycache__/console.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text simulation/.venv-planner/lib/python3.12/site-packages/test/__pycache__/test_shapes.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text simulation/assets/g1/configuration/g1_29dof_rev_1_0_with_inspire_hand_retarget_inspire_white_base.usd filter=lfs diff=lfs merge=lfs -text +simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/base_articulation.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/imageio_ffmpeg-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/imageio_ffmpeg-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..6d27cf66867f1884302d04b05ccdf6f94b124bb9 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/imageio_ffmpeg-license.txt @@ -0,0 +1,25 @@ +BSD 2-Clause License + +Copyright (c) 2019-2025, imageio +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. + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/imagesize-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/imagesize-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..b0df45f8a5aeb66b4101a80ba05b168d9be8c5e7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/imagesize-license.txt @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright © 2016 Yoshiki Shibukawa + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/iniconfig-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/iniconfig-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..46f4b2846fd708ecb81b2d665434ce6379aa1101 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/iniconfig-license.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2010 - 2023 Holger Krekel and others + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/ipython-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/ipython-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..d4bb8d39dfe4e761fbd0c75b318c14126fa2f45f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/ipython-license.txt @@ -0,0 +1,33 @@ +BSD 3-Clause License + +- Copyright (c) 2008-Present, IPython Development Team +- Copyright (c) 2001-2007, Fernando Perez +- Copyright (c) 2001, Janko Hauser +- Copyright (c) 2001, Nathaniel Gray + +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 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/ipywidgets-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/ipywidgets-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..deb2c38c8ecf6a0a88e5ad8cfdd42625dab32d05 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/ipywidgets-license.txt @@ -0,0 +1,27 @@ +Copyright (c) 2015 Project Jupyter Contributors +All rights reserved. + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/isaacsim-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/isaacsim-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..0454ece1bed6fb1a73485ef880e49e11b99603fb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/isaacsim-license.txt @@ -0,0 +1,188 @@ +The Isaac Sim software in this repository is covered under the Apache 2.0 +License terms below. + +Building or using the software requires additional components licenced +under other terms. These additional components include dependencies such +as the Omniverse Kit SDK, as well as 3D models and textures. + +License terms for these additional NVIDIA owned and licensed components +can be found here: + https://docs.nvidia.com/NVIDIA-IsaacSim-Additional-Software-and-Materials-License.pdf + +Any open source dependencies downloaded during the build process are owned +by their respective owners and licensed under their respective terms. + + 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/isort-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/isort-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..b5083a50d8cf8c6a404a0584416618915c58acf2 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/isort-license.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013 Timothy Edmund Crosley + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/jinja2-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/jinja2-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..c37cae49ec77ad6ebb25568c1605f1fee5313cfb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/jinja2-license.txt @@ -0,0 +1,28 @@ +Copyright 2007 Pallets + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/jmespath-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/jmespath-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..9c520c6bbff8c6a0b73416c45775ad31b8156e84 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/jmespath-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/joblib-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/joblib-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..910537bd33412dd9b70c4d07cedd41b519be7fb5 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/joblib-license.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2008-2021, The joblib developers. +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 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/jsonschema-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/jsonschema-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..af9cfbdb134f42e5205ecbad597421d778826481 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/jsonschema-license.txt @@ -0,0 +1,19 @@ +Copyright (c) 2013 Julian Berman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/jsonschema-specifications-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/jsonschema-specifications-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..a9f853e43069b8e3f8a156a4af2b1198a004230d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/jsonschema-specifications-license.txt @@ -0,0 +1,19 @@ +Copyright (c) 2022 Julian Berman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/junitparser-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/junitparser-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..a4325a4a80d49d0d6ca741ea90d39ef3a5b54f1b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/junitparser-license.txt @@ -0,0 +1,13 @@ +Copyright 2020 Joel Wang + + 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/jupyterlab_widgets-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/jupyterlab_widgets-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..deb2c38c8ecf6a0a88e5ad8cfdd42625dab32d05 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/jupyterlab_widgets-license.txt @@ -0,0 +1,27 @@ +Copyright (c) 2015 Project Jupyter Contributors +All rights reserved. + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/kiwisolver-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/kiwisolver-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..206ae79273ed4980cc70cdf7e5745360931e140d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/kiwisolver-license.txt @@ -0,0 +1,71 @@ +========================= + The Kiwi licensing terms +========================= +Kiwi is licensed under the terms of the Modified BSD License (also known as +New or Revised BSD), as follows: + +Copyright (c) 2013-2024, Nucleic Development Team + +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 Nucleic Development Team 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. + +About Kiwi +---------- +Chris Colbert began the Kiwi project in December 2013 in an effort to +create a blisteringly fast UI constraint solver. Chris is still the +project lead. + +The Nucleic Development Team is the set of all contributors to the Nucleic +project and its subprojects. + +The core team that coordinates development on GitHub can be found here: +http://github.com/nucleic. The current team consists of: + +* Chris Colbert + +Our Copyright Policy +-------------------- +Nucleic uses a shared copyright model. Each contributor maintains copyright +over their contributions to Nucleic. But, it is important to note that these +contributions are typically only changes to the repositories. Thus, the Nucleic +source code, in its entirety is not the copyright of any single person or +institution. Instead, it is the collective copyright of the entire Nucleic +Development Team. If individual contributors want to maintain a record of what +changes/contributions they have specific copyright on, they should indicate +their copyright in the commit message of the change, when they commit the +change to one of the Nucleic repositories. + +With this in mind, the following banner should be used in any source code file +to indicate the copyright and license terms: + +#------------------------------------------------------------------------------ +# Copyright (c) 2013-2024, Nucleic Development Team. +# +# Distributed under the terms of the Modified BSD License. +# +# The full license is in the file LICENSE, distributed with this software. +#------------------------------------------------------------------------------ diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/labeler-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/labeler-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..cfbc8bb6dda51082ebfa9893547b8127c096e9ea --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/labeler-license.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 GitHub, Inc. and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/latexcodec-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/latexcodec-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..e9511f21fb9a56deedb8ce2ffaeb656605c83162 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/latexcodec-license.txt @@ -0,0 +1,7 @@ +latexcodec is a lexer and codec to work with LaTeX code in Python +Copyright (c) 2011-2020 by Matthias C. M. Troffaes +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/legged-gym-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/legged-gym-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..92e75a2ed223e807665c24db85e49aa3a4111dff --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/legged-gym-license.txt @@ -0,0 +1,31 @@ +Copyright (c) 2021, ETH Zurich, Nikita Rudin +Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES +All rights reserved. + +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. + +See licenses/assets for license information for assets included in this repository. +See licenses/dependencies for license information of dependencies of this package. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/loop-rate-limiters-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/loop-rate-limiters-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/loop-rate-limiters-license.txt @@ -0,0 +1,201 @@ + 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 [yyyy] [name of copyright owner] + + 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/markdown-it-py-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/markdown-it-py-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..582ddf59e08277fe6e78cee924d2c84805fe36fe --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/markdown-it-py-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 ExecutableBookProject + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/markdown-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/markdown-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..ff993de4a45a396387b5e23b9ffba2ea01b0bbad --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/markdown-license.txt @@ -0,0 +1,15 @@ +BSD 3-Clause License + +Copyright 2007, 2008 The Python Markdown Project (v. 1.7 and later) +Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b) +Copyright 2004 Manfred Stienstra (the original version) + +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 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/markupsafe-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/markupsafe-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..9d227a0cc43c3268d15722b763bd94ad298645a1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/markupsafe-license.txt @@ -0,0 +1,28 @@ +Copyright 2010 Pallets + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/matplotlib-inline-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/matplotlib-inline-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..b8350378e810121d96bc065a8ddaab7d2ec38308 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/matplotlib-inline-license.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2019-2022, IPython Development Team. +All rights reserved. + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/matplotlib-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/matplotlib-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..0752df48ef02678b5746ccc034a72a99ce8e5f90 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/matplotlib-license.txt @@ -0,0 +1,99 @@ +License agreement for matplotlib versions 1.3.0 and later +========================================================= + +1. This LICENSE AGREEMENT is between the Matplotlib Development Team +("MDT"), and the Individual or Organization ("Licensee") accessing and +otherwise using matplotlib software in source or binary form and its +associated documentation. + +2. Subject to the terms and conditions of this License Agreement, MDT +hereby grants Licensee a nonexclusive, royalty-free, world-wide license +to reproduce, analyze, test, perform and/or display publicly, prepare +derivative works, distribute, and otherwise use matplotlib +alone or in any derivative version, provided, however, that MDT's +License Agreement and MDT's notice of copyright, i.e., "Copyright (c) +2012- Matplotlib Development Team; All Rights Reserved" are retained in +matplotlib alone or in any derivative version prepared by +Licensee. + +3. In the event Licensee prepares a derivative work that is based on or +incorporates matplotlib or any part thereof, and wants to +make the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to matplotlib . + +4. MDT is making matplotlib available to Licensee on an "AS +IS" basis. MDT MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, MDT MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB +WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. + +5. MDT SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB + FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR +LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING +MATPLOTLIB , OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF +THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between MDT and +Licensee. This License Agreement does not grant permission to use MDT +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using matplotlib , +Licensee agrees to be bound by the terms and conditions of this License +Agreement. + +License agreement for matplotlib versions prior to 1.3.0 +======================================================== + +1. This LICENSE AGREEMENT is between John D. Hunter ("JDH"), and the +Individual or Organization ("Licensee") accessing and otherwise using +matplotlib software in source or binary form and its associated +documentation. + +2. Subject to the terms and conditions of this License Agreement, JDH +hereby grants Licensee a nonexclusive, royalty-free, world-wide license +to reproduce, analyze, test, perform and/or display publicly, prepare +derivative works, distribute, and otherwise use matplotlib +alone or in any derivative version, provided, however, that JDH's +License Agreement and JDH's notice of copyright, i.e., "Copyright (c) +2002-2011 John D. Hunter; All Rights Reserved" are retained in +matplotlib alone or in any derivative version prepared by +Licensee. + +3. In the event Licensee prepares a derivative work that is based on or +incorporates matplotlib or any part thereof, and wants to +make the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to matplotlib. + +4. JDH is making matplotlib available to Licensee on an "AS +IS" basis. JDH MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, JDH MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB +WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. + +5. JDH SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB + FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR +LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING +MATPLOTLIB , OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF +THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between JDH and +Licensee. This License Agreement does not grant permission to use JDH +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using matplotlib, +Licensee agrees to be bound by the terms and conditions of this License +Agreement. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/mdit-py-plugins-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/mdit-py-plugins-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..582ddf59e08277fe6e78cee924d2c84805fe36fe --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/mdit-py-plugins-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 ExecutableBookProject + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/mdurl-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/mdurl-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..2a920c59d8abdd485a774087915986448495fd7c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/mdurl-license.txt @@ -0,0 +1,46 @@ +Copyright (c) 2015 Vitaly Puzrin, Alex Kocharin. +Copyright (c) 2021 Taneli Hukkinen + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +-------------------------------------------------------------------------------- + +.parse() is based on Joyent's node.js `url` code: + +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/moviepy-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/moviepy-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..68c6e005a40e2006d9dbe9f3ca400482a46eb4fd --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/moviepy-license.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Zulko + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/mpmath-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/mpmath-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..6aa2fc91d7a1809adf113eb7014ee2ab3ef9409d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/mpmath-license.txt @@ -0,0 +1,27 @@ +Copyright (c) 2005-2025 Fredrik Johansson and mpmath contributors + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + a. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + b. 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. + c. 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 REGENTS 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/myst-parser-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/myst-parser-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..582ddf59e08277fe6e78cee924d2c84805fe36fe --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/myst-parser-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 ExecutableBookProject + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/networkx-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/networkx-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..0bf9a8f3f4922a0b70aac95ac7aab9574975342b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/networkx-license.txt @@ -0,0 +1,37 @@ +NetworkX is distributed with the 3-clause BSD license. + +:: + + Copyright (c) 2004-2025, NetworkX Developers + Aric Hagberg + Dan Schult + Pieter Swart + 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 NetworkX Developers 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/newton-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/newton-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..d9a10c0d8e868ebf8da0b3dc95bb0be634c34bfe --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/newton-license.txt @@ -0,0 +1,176 @@ + 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 diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/nlopt-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/nlopt-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..884683dfcf264279814d753279e1918cb48fce61 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/nlopt-license.txt @@ -0,0 +1,39 @@ +NLopt combines several free/open-source nonlinear optimization +libraries by various authors. See the COPYING, COPYRIGHT, and README +files in the subdirectories for the original copyright and licensing +information of these packages. + +The compiled NLopt library, i.e. the combined work of all of the +included optimization routines, is licensed under the conjunction of +all of these licensing terms. By default, the most restrictive terms +are for the code in the "luksan" directory, which is licensed under +the GNU Lesser General Public License (GNU LGPL), version 2.1 or +later (see luksan/COPYRIGHT). That means that, by default, the compiled +NLopt library is governed by the terms of the LGPL. + +--------------------------------------------------------------------------- + +However, NLopt also offers the option to be built without the code in +the "luksan" directory. In this case, NLopt, including any modifications +to the abovementioned packages, are licensed under the standard "MIT License:" + +Copyright (c) 2007-2024 Massachusetts Institute of Technology + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/numpy-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/numpy-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..e1fb614d66522ff388149827fa34563a4b885efa --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/numpy-license.txt @@ -0,0 +1,30 @@ +Copyright (c) 2005-2022, NumPy Developers. +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 NumPy Developers nor the names of any + 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/octomap-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/octomap-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..a3c73b0204802a8dfc9f2e571c4334bde9744fb6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/octomap-license.txt @@ -0,0 +1,31 @@ + +OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees + +License for the "octomap" library: New BSD License. + +Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg +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 University of Freiburg 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/omegaconf-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/omegaconf-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..eb208dada03bbd9975633d6f42eb036c09e33125 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/omegaconf-license.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2018, Omry Yadan +All rights reserved. + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/onnx-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/onnx-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/onnx-license.txt @@ -0,0 +1,202 @@ + + 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 [yyyy] [name of copyright owner] + + 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/open3d-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/open3d-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..79d162876d440fdaabaf292892fd3b6acb0db5af --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/open3d-license.txt @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Open3D: www.open3d.org +Copyright (c) 2018-2021 www.open3d.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/opencv-python-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/opencv-python-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..09ad12ac89f5ef952bf48b030b7c9a15f4748a46 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/opencv-python-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Olli-Pekka Heinisuo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/packaging-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/packaging-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..d9a10c0d8e868ebf8da0b3dc95bb0be634c34bfe --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/packaging-license.txt @@ -0,0 +1,176 @@ + 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 diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pandas-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pandas-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..c343da2ebe870934eb5c9840d9b92f7d5cd7b134 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pandas-license.txt @@ -0,0 +1,31 @@ +BSD 3-Clause License + +Copyright (c) 2008-2011, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development Team +All rights reserved. + +Copyright (c) 2011-2025, Open source contributors. + +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 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pathtools-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pathtools-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..5e6adc9dadd859189c3de9d2f42cfb72e0a64abb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pathtools-license.txt @@ -0,0 +1,21 @@ +Copyright (C) 2010 by Yesudeep Mangalapilly + +MIT License +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pexpect-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pexpect-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..6ee60f42b44e250ccd8d6064b71e7f622f498836 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pexpect-license.txt @@ -0,0 +1,19 @@ +ISC LICENSE + + This license is approved by the OSI and FSF as GPL-compatible. + http://opensource.org/licenses/isc-license.txt + + Copyright (c) 2013-2014, Pexpect development team + Copyright (c) 2012, Noah Spurrier + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pillow-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pillow-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..40aabc3239f150d0657212032fb21211601272b7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pillow-license.txt @@ -0,0 +1,30 @@ +The Python Imaging Library (PIL) is + + Copyright © 1997-2011 by Secret Labs AB + Copyright © 1995-2011 by Fredrik Lundh + +Pillow is the friendly PIL fork. It is + + Copyright © 2010-2022 by Alex Clark and contributors + +Like PIL, Pillow is licensed under the open source HPND License: + +By obtaining, using, and/or copying this software and/or its associated +documentation, you agree that you have read, understood, and will comply +with the following terms and conditions: + +Permission to use, copy, modify, and distribute this software and its +associated documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appears in all copies, and that +both that copyright notice and this permission notice appear in supporting +documentation, and that the name of Secret Labs AB or the author not be +used in advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, +INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pin-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pin-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..dfacb67314841410e216c4702d05e484e163d323 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pin-license.txt @@ -0,0 +1,26 @@ +BSD 2-Clause License + +Copyright (c) 2014-2023, CNRS +Copyright (c) 2018-2025, INRIA +All rights reserved. + +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. + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pin-pink-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pin-pink-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pin-pink-license.txt @@ -0,0 +1,201 @@ + 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 [yyyy] [name of copyright owner] + + 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pinocchio-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pinocchio-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..dfacb67314841410e216c4702d05e484e163d323 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pinocchio-license.txt @@ -0,0 +1,26 @@ +BSD 2-Clause License + +Copyright (c) 2014-2023, CNRS +Copyright (c) 2018-2025, INRIA +All rights reserved. + +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. + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pluggy-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pluggy-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..85f4dd63d2da8e31d7e84d5180f016fdfe315c2c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pluggy-license.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 holger krekel (rather uses bitbucket/hpk42) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pre-commit-hooks-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pre-commit-hooks-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..4a071fc533d4fd07dbe81e1e8f0f0998b17220be --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pre-commit-hooks-license.txt @@ -0,0 +1,19 @@ +Copyright (c) 2014 pre-commit dev team: Anthony Sottile, Ken Struys + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pre-commit-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pre-commit-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..4a071fc533d4fd07dbe81e1e8f0f0998b17220be --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pre-commit-license.txt @@ -0,0 +1,19 @@ +Copyright (c) 2014 pre-commit dev team: Anthony Sottile, Ken Struys + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/prettytable-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/prettytable-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb6fed3eb821a2e0fb06a625c2af89b4bc4577ec --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/prettytable-license.txt @@ -0,0 +1,30 @@ +# Copyright (c) 2009-2014 Luke Maurits +# All rights reserved. +# With contributions from: +# * Chris Clark +# * Klein Stephane +# * John Filleau +# * Vladimir Vrzić +# +# 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. +# * The name of the author may not 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/proglog-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/proglog-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..a68d0a5fdd95e999240168ff1d2e73800fd5c637 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/proglog-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Edinburgh Genome Foundry, University of Edinburgh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/protobuf-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/protobuf-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..19b305b00060a774a9180fb916c14b49edb2008f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/protobuf-license.txt @@ -0,0 +1,32 @@ +Copyright 2008 Google 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 Google 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. + +Code generated by the Protocol Buffer compiler is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/psutil-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/psutil-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..cff5eb74e1badd1c5237ed2654b349530179ad1d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/psutil-license.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2009, Jay Loden, Dave Daeschler, Giampaolo Rodola +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 psutil authors 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/ptyprocess-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/ptyprocess-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..6ee60f42b44e250ccd8d6064b71e7f622f498836 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/ptyprocess-license.txt @@ -0,0 +1,19 @@ +ISC LICENSE + + This license is approved by the OSI and FSF as GPL-compatible. + http://opensource.org/licenses/isc-license.txt + + Copyright (c) 2013-2014, Pexpect development team + Copyright (c) 2012, Noah Spurrier + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pure_eval-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pure_eval-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..473e36e246edd5800325e9fa1eaa7697c95be1ef --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pure_eval-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Alex Hall + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pybtex-docutils-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pybtex-docutils-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..810a5a8536c1fdce9578d2dcf80e3dd2fef27005 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pybtex-docutils-license.txt @@ -0,0 +1,7 @@ +pybtex-docutils is a docutils backend for pybtex +Copyright (c) 2013-2023 by Matthias C. M. Troffaes +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pydata-sphinx-theme-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pydata-sphinx-theme-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..464d11719d210646c2415bf23ddc9c48dfa4a224 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pydata-sphinx-theme-license.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2018, pandas +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 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pygame-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pygame-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..56de5de6e1523fa0c38679b431f53d5ff2197162 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pygame-license.txt @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pyglet-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pyglet-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..03c0900c90248616b3eb37f2b3403a2f0f064e2e --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pyglet-license.txt @@ -0,0 +1,30 @@ +Copyright (c) 2006-2008 Alex Holkner +Copyright (c) 2008-2023 pyglet contributors +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 pyglet 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pygrep-hooks-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pygrep-hooks-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..b7af5ef213084fe100c5bb755659ef68c14dae5b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pygrep-hooks-license.txt @@ -0,0 +1,19 @@ +Copyright (c) 2018 Anthony Sottile + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pyparsing-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pyparsing-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..1bf98523e33170372cf0702f03e38dadec3c5094 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pyparsing-license.txt @@ -0,0 +1,18 @@ +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pyperclip-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pyperclip-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..799b74c5bf39adf1b6df285374890056fb4c48eb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pyperclip-license.txt @@ -0,0 +1,27 @@ +Copyright (c) 2014, Al Sweigart +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 {organization} 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pyright-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pyright-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..dd44ffc07126963e7c062024dd9543ecc7500c2d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pyright-license.txt @@ -0,0 +1,47 @@ +MIT License + +Copyright (c) 2021 Robert Craigie + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +=============================================================================== + +MIT License + +Pyright - A static type checker for the Python language +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pytest-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pytest-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..c3f1657fce94589bd1ec7cead810639047f3d359 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pytest-license.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2004 Holger Krekel and others + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pytest-mock-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pytest-mock-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..6e1ee5d5b8aec4601f7151828373617c3b1004c9 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pytest-mock-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) [2016] [Bruno Oliveira] + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/python-dateutil-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/python-dateutil-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..6053d35cfc60b6c2a4e97d58f066364c58f83691 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/python-dateutil-license.txt @@ -0,0 +1,54 @@ +Copyright 2017- Paul Ganssle +Copyright 2017- dateutil contributors (see AUTHORS file) + + 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. + +The above license applies to all contributions after 2017-12-01, as well as +all contributions that have been re-licensed (see AUTHORS file for the list of +contributors who have re-licensed their code). +-------------------------------------------------------------------------------- +dateutil - Extensions to the standard Python datetime module. + +Copyright (c) 2003-2011 - Gustavo Niemeyer +Copyright (c) 2012-2014 - Tomi Pieviläinen +Copyright (c) 2014-2016 - Yaron de Leeuw +Copyright (c) 2015- - Paul Ganssle +Copyright (c) 2015- - dateutil contributors (see AUTHORS file) + +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 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 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. + +The above BSD License Applies to all code, even that also covered by Apache 2.0. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/python-dotenv-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/python-dotenv-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..3a97119010ac82e15e917a69b7b8f9f59b5a4601 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/python-dotenv-license.txt @@ -0,0 +1,27 @@ +Copyright (c) 2014, Saurabh Kumar (python-dotenv), 2013, Ted Tieken (django-dotenv-rw), 2013, Jacob Kaplan-Moss (django-dotenv) + +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 django-dotenv 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pytorch3d-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pytorch3d-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..c55382ff0992d90ae5ecb2cd9ac624ccd20bda4d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pytorch3d-license.txt @@ -0,0 +1,30 @@ +BSD License + +For PyTorch3D software + +Copyright (c) Meta Platforms, Inc. and affiliates. 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 Meta 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pytransform3d-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pytransform3d-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..061bfc4a75b8e8082c354cb83fa8070c06ad7184 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pytransform3d-license.txt @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright 2014-2017 Alexander Fabisch (Robotics Research Group, University of Bremen), +2017-2025 Alexander Fabisch (DFKI GmbH, Robotics Innovation Center), +and pytransform3d contributors + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pytz-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pytz-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..5f1c11289f6a54cb07ebdbf31d02e8e81b18b07f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pytz-license.txt @@ -0,0 +1,19 @@ +Copyright (c) 2003-2019 Stuart Bishop + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pyupgrade-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pyupgrade-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..522fbe20b89911bb8d68b4a684a51225dd571764 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pyupgrade-license.txt @@ -0,0 +1,19 @@ +Copyright (c) 2017 Anthony Sottile + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/pyyaml-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/pyyaml-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..2f1b8e15e5627d92f0521605c9870bc8e5505cb4 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/pyyaml-license.txt @@ -0,0 +1,20 @@ +Copyright (c) 2017-2021 Ingy döt Net +Copyright (c) 2006-2016 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/qhull-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/qhull-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..9c802c06494d9971b6f7545b6f451e071f1ab186 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/qhull-license.txt @@ -0,0 +1,39 @@ + Qhull, Copyright (c) 1993-2020 + + C.B. Barber + Arlington, MA + + and + + The National Science and Technology Research Center for + Computation and Visualization of Geometric Structures + (The Geometry Center) + University of Minnesota + + email: qhull@qhull.org + +This software includes Qhull from C.B. Barber and The Geometry Center. +Files derived from Qhull 1.0 are copyrighted by the Geometry Center. The +remaining files are copyrighted by C.B. Barber. Qhull is free software +and may be obtained via http from www.qhull.org. It may be freely copied, +modified, and redistributed under the following conditions: + +1. All copyright notices must remain intact in all files. + +2. A copy of this text file must be distributed along with any copies + of Qhull that you redistribute; this includes copies that you have + modified, or copies of programs or other software products that + include Qhull. + +3. If you modify Qhull, you must include a notice giving the + name of the person performing the modification, the date of + modification, and the reason for such modification. + +4. When distributing modified versions of Qhull, or other software + products that include Qhull, you must provide notice that the original + source code may be obtained as noted above. + +5. There is no warranty or other guarantee of fitness for Qhull, it is + provided solely "as is". Bug reports or fixes may be sent to + qhull_bug@qhull.org; the authors may or may not act on them as + they desire. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/qpsolvers-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/qpsolvers-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..0a041280bd00a9d068f503b8ee7ce35214bd24a1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/qpsolvers-license.txt @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/quadprog-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/quadprog-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..23cb790338e191e29205d6f4123882c0583ef8eb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/quadprog-license.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {description} + Copyright (C) {year} {fullname} + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + {signature of Ty Coon}, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/ray-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/ray-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..b813b34b89015f3863e4d9cc51e3bfec970d2d9b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/ray-license.txt @@ -0,0 +1,450 @@ + 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 {yyyy} {name of copyright owner} + + 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. + +-------------------------------------------------------------------------------- + +Code in python/ray/rllib/{evolution_strategies, dqn} adapted from +https://github.com/openai (MIT License) + +Copyright (c) 2016 OpenAI (http://openai.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +-------------------------------------------------------------------------------- + +Code in python/ray/rllib/impala/vtrace.py from +https://github.com/deepmind/scalable_agent + +Copyright 2018 Google LLC + +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 + + https://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. + +-------------------------------------------------------------------------------- +Code in python/ray/rllib/ars is adapted from https://github.com/modestyachts/ARS + +Copyright (c) 2018, ARS contributors (Horia Mania, Aurelia Guy, Benjamin Recht) +All rights reserved. + +Redistribution and use of ARS 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. + +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. + +------------------ +Code in python/ray/_private/prometheus_exporter.py is adapted from https://github.com/census-instrumentation/opencensus-python/blob/master/contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py + +# Copyright 2018, OpenCensus Authors +# +# 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. + +-------------------------------------------------------------------------------- +Code in python/ray/tests/modin/test_modin and +python/ray/tests/modin/modin_test_utils adapted from: +- http://github.com/modin-project/modin/master/modin/pandas/test/test_general.py +- http://github.com/modin-project/modin/master/modin/pandas/test/utils.py + +Copyright (c) 2018-2020 Modin Developers. + +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 + + https://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. + +-------------------------------------------------------------------------------- +Code in src/ray/util/logging.h is adapted from +https://github.com/google/glog/blob/master/src/glog/logging.h.in + +Copyright (c) 2008, Google 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 Google 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. + +-------------------------------------------------------------------------------- +Code in python/ray/_private/runtime_env/conda_utils.py is adapted from +https://github.com/mlflow/mlflow/blob/master/mlflow/utils/conda.py + +Copyright (c) 2018, Databricks, Inc. +All rights reserved. + +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. + +-------------------------------------------------------------------------------- +Code in python/ray/_private/runtime_env/_clonevirtualenv.py is adapted from https://github.com/edwardgeorge/virtualenv-clone/blob/master/clonevirtualenv.py + +Copyright (c) 2011, Edward George, based on code contained within the +virtualenv project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +-------------------------------------------------------------------------------- +Code in python/ray/_private/async_compat.py is adapted from +https://github.com/python-trio/async_generator/blob/master/async_generator/_util.py + +Copyright (c) 2022, Nathaniel J. Smith + +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. + +--------------------------------------------------------------------------------------------------------------- +Code in python/ray/_private/thirdparty/tabulate/tabulate.py is adapted from https://github.com/astanin/python-tabulate/blob/4892c6e9a79638c7897ccea68b602040da9cc7a7/tabulate.py + +Copyright (c) 2011-2020 Sergey Astanin and contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------------------------------------------------------------------------- +Code in python/ray/_private/thirdparty/dacite is adapted from https://github.com/konradhalas/dacite/blob/master/dacite + +Copyright (c) 2018 Konrad Hałas + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/referencing-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/referencing-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..a9f853e43069b8e3f8a156a4af2b1198a004230d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/referencing-license.txt @@ -0,0 +1,19 @@ +Copyright (c) 2022 Julian Berman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/regex-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/regex-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..99c19cf844141395a87c34325da3a537f1e95815 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/regex-license.txt @@ -0,0 +1,208 @@ +This work was derived from the 're' module of CPython 2.6 and CPython 3.1, +copyright (c) 1998-2001 by Secret Labs AB and licensed under CNRI's Python 1.6 +license. + +All additions and alterations are licensed under the Apache 2.0 License. + + + 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 2020 Matthew Barnett + + 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/requests-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/requests-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..dd5b3a58aa1849f452abc9b5cd1638dc71a5e482 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/requests-license.txt @@ -0,0 +1,174 @@ + 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/rich-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/rich-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..4415505566f261c802b671426be529a31f914137 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/rich-license.txt @@ -0,0 +1,19 @@ +Copyright (c) 2020 Will McGugan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/rl_games-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/rl_games-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..313ca229e6ca879466f94bff49362fb65667e22f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/rl_games-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Denys88 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/robomimc-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/robomimc-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..934eaa87bb98d79ced50c8f27849625dc97b934d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/robomimc-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Stanford Vision and Learning Lab + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/rsl_rl-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/rsl_rl-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..5e09cdaf7e064b651767b57546cc9ece605f2da6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/rsl_rl-license.txt @@ -0,0 +1,141 @@ +Copyright (c) 2021, ETH Zurich, Nikita Rudin +Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES +All rights reserved. + +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. + +See licenses/dependencies for license information of dependencies of this package. + +=============================================================================== + +Copyright (c) 2005-2021, NumPy Developers. +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 NumPy Developers nor the names of any + 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. + +=============================================================================== + +From PyTorch: + +Copyright (c) 2016- Facebook, Inc (Adam Paszke) +Copyright (c) 2014- Facebook, Inc (Soumith Chintala) +Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert) +Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) +Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) +Copyright (c) 2011-2013 NYU (Clement Farabet) +Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston) +Copyright (c) 2006 Idiap Research Institute (Samy Bengio) +Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz) + +=============================================================================== + +From Caffe2: + +Copyright (c) 2016-present, Facebook Inc. All rights reserved. + +All contributions by Facebook: +Copyright (c) 2016 Facebook Inc. + +All contributions by Google: +Copyright (c) 2015 Google Inc. +All rights reserved. + +All contributions by Yangqing Jia: +Copyright (c) 2015 Yangqing Jia +All rights reserved. + +All contributions by Kakao Brain: +Copyright 2019-2020 Kakao Brain + +All contributions from Caffe: +Copyright(c) 2013, 2014, 2015, the respective contributors +All rights reserved. + +All other contributions: +Copyright(c) 2015, 2016 the respective contributors +All rights reserved. + +Caffe2 uses a copyright model similar to Caffe: each contributor holds +copyright over their contributions to Caffe2. The project versioning records +all such contribution and copyright details. If a contributor wants to further +mark their specific copyright on a particular contribution, they should +indicate their copyright solely in the commit message of the change when it is +committed. + +All rights reserved. + +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 names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America + and IDIAP Research Institute 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/ruff-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/ruff-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..655a0c76fc5539b2f8e63b673741a5fd0e0c5799 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/ruff-license.txt @@ -0,0 +1,430 @@ +MIT License + +Copyright (c) 2022 Charles Marsh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +end of terms and conditions + +The externally maintained libraries from which parts of the Software is derived +are: + +- autoflake, licensed as follows: + """ + Copyright (C) 2012-2018 Steven Myint + + Permission is hereby granted, free of charge, to any person obtaining a copy of + this software and associated documentation files (the "Software"), to deal in + the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do + so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + """ + +- autotyping, licensed as follows: + """ + MIT License + + Copyright (c) 2023 Jelle Zijlstra + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + """ + +- Flake8, licensed as follows: + """ + == Flake8 License (MIT) == + + Copyright (C) 2011-2013 Tarek Ziade + Copyright (C) 2012-2016 Ian Cordasco + + Permission is hereby granted, free of charge, to any person obtaining a copy of + this software and associated documentation files (the "Software"), to deal in + the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do + so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + """ + +- flake8-eradicate, licensed as follows: + """ + MIT License + + Copyright (c) 2018 Nikita Sobolev + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + """ + +- flake8-pyi, licensed as follows: + """ + The MIT License (MIT) + + Copyright (c) 2016 Łukasz Langa + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + """ + +- flake8-simplify, licensed as follows: + """ + MIT License + + Copyright (c) 2020 Martin Thoma + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + """ + +- isort, licensed as follows: + """ + The MIT License (MIT) + + Copyright (c) 2013 Timothy Edmund Crosley + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + """ + +- pygrep-hooks, licensed as follows: + """ + Copyright (c) 2018 Anthony Sottile + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + """ + +- pycodestyle, licensed as follows: + """ + Copyright © 2006-2009 Johann C. Rocholl + Copyright © 2009-2014 Florent Xicluna + Copyright © 2014-2020 Ian Lee + + Licensed under the terms of the Expat License + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + """ + +- pydocstyle, licensed as follows: + """ + Copyright (c) 2012 GreenSteam, + + Copyright (c) 2014-2020 Amir Rachum, + + Copyright (c) 2020 Sambhav Kothari, + + Permission is hereby granted, free of charge, to any person obtaining a copy of + this software and associated documentation files (the "Software"), to deal in + the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do + so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + """ + +- Pyflakes, licensed as follows: + """ + Copyright 2005-2011 Divmod, Inc. + Copyright 2013-2014 Florent Xicluna + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + """ + +- Pyright, licensed as follows: + """ + MIT License + + Pyright - A static type checker for the Python language + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE + """ + +- pyupgrade, licensed as follows: + """ + Copyright (c) 2017 Anthony Sottile + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + """ + +- rome/tools, licensed under the MIT license: + """ + MIT License + + Copyright (c) Rome Tools, Inc. and its affiliates. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + """ + +- RustPython, licensed as follows: + """ + MIT License + + Copyright (c) 2020 RustPython Team + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + """ + +- rust-analyzer/text-size, licensed under the MIT license: + """ + Permission is hereby granted, free of charge, to any + person obtaining a copy of this software and associated + documentation files (the "Software"), to deal in the + Software without restriction, including without + limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of + the Software, and to permit persons to whom the Software + is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice + shall be included in all copies or substantial portions + of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF + ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED + TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT + SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + """ diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/ruff-pre-commit-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/ruff-pre-commit-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..c16d8bb1db2621505a8bdd37d260d6f312b049ad --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/ruff-pre-commit-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Astral Software Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/safetensors-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/safetensors-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/safetensors-license.txt @@ -0,0 +1,201 @@ + 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 [yyyy] [name of copyright owner] + + 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/scikit-learn-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/scikit-learn-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..e1cd01d5845788ea1db826d10d37bb24e71d1bbb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/scikit-learn-license.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2007-2024 The scikit-learn developers. +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 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sentry-sdk-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sentry-sdk-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..016323bd8da88e224808bebf892dabc485c85387 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sentry-sdk-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Functional Software, Inc. dba Sentry + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/setproctitle-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/setproctitle-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..1f632fa116aa0d0e36acbd5bdd3cfa7bd33f1e30 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/setproctitle-license.txt @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright (c) 2009, Daniele Varrazzo + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/setuptools-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/setuptools-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/setuptools-license.txt @@ -0,0 +1,17 @@ +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/shortuuid-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/shortuuid-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..c14f01beb96afe6119f936d08a30ee2069bb0fb2 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/shortuuid-license.txt @@ -0,0 +1,29 @@ +Copyright (c) 2011, Stavros Korokithakis +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 Stochastic Technologies 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/six-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/six-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..1cc22a5aa7679ebaa10934212f356823931bdc3e --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/six-license.txt @@ -0,0 +1,18 @@ +Copyright (c) 2010-2024 Benjamin Peterson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/skrl-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/skrl-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..198089ecac70962085174eaf5d3a5b0c0ac25747 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/skrl-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Toni-SM + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/smmap-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/smmap-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..8ef91f9790494010d779b410fd93cf4c803241e2 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/smmap-license.txt @@ -0,0 +1,29 @@ +Copyright (C) 2010, 2011 Sebastian Thiel and contributors +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 async project 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sniffio-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sniffio-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sniffio-license.txt @@ -0,0 +1,201 @@ + 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 [yyyy] [name of copyright owner] + + 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/snowballstemmer-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/snowballstemmer-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..f36607f9e93f335177eb162099a7b46821ba2382 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/snowballstemmer-license.txt @@ -0,0 +1,29 @@ +Copyright (c) 2001, Dr Martin Porter +Copyright (c) 2004,2005, Richard Boulton +Copyright (c) 2013, Yoshiki Shibukawa +Copyright (c) 2006,2007,2009,2010,2011,2014-2019, Olly Betts +All rights reserved. + +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 Snowball project 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/soupsieve-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/soupsieve-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..a34ec87ec69a03ea1b9850da9f63b79772097483 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/soupsieve-license.txt @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2018 - 2025 Isaac Muse isaacmuse@gmail.com + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-book-theme-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-book-theme-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..462817b594e00311002805290c7baf78ba894a70 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-book-theme-license.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2020, Chris Holdgraf +All rights reserved. + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-copybutton-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-copybutton-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..dab6ba48f3dcb26eae65920afb84113b1ebb141f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-copybutton-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Chris Holdgraf + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-design-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-design-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..d6bd96e0b8fb7970e9507a689490f1c2f0286efb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-design-license.txt @@ -0,0 +1,21 @@ +MIT License Copyright (c) 2023 Chris Sewell + +Permission is hereby granted, free +of charge, to any person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice +(including the next paragraph) shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-icon-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-icon-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..b17ba329bee44a77f4a0ce74d18d118a0fd7f86d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-icon-license.txt @@ -0,0 +1,25 @@ +BSD 2-Clause License + +Copyright (c) 2022, Rambaud Pierrick +All rights reserved. + +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. + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..de3688cd2c63325d5819b33c03e7462f48aee816 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-license.txt @@ -0,0 +1,31 @@ +License for Sphinx +================== + +Unless otherwise indicated, all code in the Sphinx project is licenced under the +two clause BSD licence below. + +Copyright (c) 2007-2025 by the Sphinx team (see AUTHORS file). +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. + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-multiversion-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-multiversion-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..172d6b3f5d798030f17fbdc7aa8cd41d72c5b0a9 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-multiversion-license.txt @@ -0,0 +1,25 @@ +BSD 2-Clause License + +Copyright (c) 2020, Jan Holthuis +All rights reserved. + +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. + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-tabs-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-tabs-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..c124ccddfb3f2e93719ee37a06dfc89e56789b71 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinx-tabs-license.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 djungelorm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-applehelp-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-applehelp-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..8391fd1a2335b8901f36d445763402fcf3593b30 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-applehelp-license.txt @@ -0,0 +1,8 @@ +License for sphinxcontrib-applehelp +Copyright (c) 2007-2019 by the Sphinx team (see https://github.com/sphinx-doc/sphinx/blob/master/AUTHORS). 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. +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-bibtex-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-bibtex-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..fb3f16937707ed93932dca3d58eb8a1a8e1e0413 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-bibtex-license.txt @@ -0,0 +1,26 @@ +| sphinxcontrib-bibtex is a Sphinx extension for BibTeX style citations +| Copyright (c) 2011-2024 by Matthias C. M. Troffaes +| 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. + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-devhelp-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-devhelp-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..e15238ffc3b5286f078a51b9c4b7d087b173b1bb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-devhelp-license.txt @@ -0,0 +1,8 @@ +License for sphinxcontrib-devhelp +Copyright (c) 2007-2019 by the Sphinx team (see https://github.com/sphinx-doc/sphinx/blob/master/AUTHORS). 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. +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-htmlhelp-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-htmlhelp-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..0339165c9d481081fe914e07c1e4c1eb305b5fbb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-htmlhelp-license.txt @@ -0,0 +1,8 @@ +License for sphinxcontrib-htmlhelp +Copyright (c) 2007-2019 by the Sphinx team (see https://github.com/sphinx-doc/sphinx/blob/master/AUTHORS). 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. +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-jsmath-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-jsmath-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..e28495c913ce0d3e8e69f19035cff2fab7434713 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-jsmath-license.txt @@ -0,0 +1,8 @@ +License for sphinxcontrib-jsmath +Copyright (c) 2007-2019 by the Sphinx team (see https://github.com/sphinx-doc/sphinx/blob/master/AUTHORS). 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. +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-qthelp-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-qthelp-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..dd8f49eb65b36d534fd34b09a5072aace502a5be --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-qthelp-license.txt @@ -0,0 +1,8 @@ +License for sphinxcontrib-qthelp +Copyright (c) 2007-2019 by the Sphinx team (see https://github.com/sphinx-doc/sphinx/blob/master/AUTHORS). 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. +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-serializinghtml-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-serializinghtml-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..b396b73ecd728c6b7c19db5ef6d88241b2c1d8a3 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxcontrib-serializinghtml-license.txt @@ -0,0 +1,8 @@ +License for sphinxcontrib-serializinghtml +Copyright (c) 2007-2019 by the Sphinx team (see https://github.com/sphinx-doc/sphinx/blob/master/AUTHORS). 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. +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxemoji-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxemoji-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..6d6be19defb3a650a87d768bc627d3472caf3095 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sphinxemoji-license.txt @@ -0,0 +1,27 @@ +Copyright (c) The Sphinx Emoji Codes contributors. +All rights reserved. + +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 Markdownreveal 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/stable-baselines3-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/stable-baselines3-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..0951e29b4f9a29265d8f805f8fbba6e948030b17 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/stable-baselines3-license.txt @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2019 Antonin Raffin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/stack-data-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/stack-data-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..473e36e246edd5800325e9fa1eaa7697c95be1ef --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/stack-data-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Alex Hall + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/sympy-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/sympy-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..bff6f8ff065e72b307920986e0bdc7211d2eb5ad --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/sympy-license.txt @@ -0,0 +1,153 @@ +Copyright (c) 2006-2023 SymPy Development Team + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + a. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + b. 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. + c. Neither the name of SymPy 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 REGENTS 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. + +-------------------------------------------------------------------------------- + +Patches that were taken from the Diofant project (https://github.com/diofant/diofant) +are licensed as: + +Copyright (c) 2006-2018 SymPy Development Team, + 2013-2023 Sergey B Kirpichev + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + a. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + b. 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. + c. Neither the name of Diofant or SymPy 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 REGENTS 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. + +-------------------------------------------------------------------------------- + +Submodules taken from the multipledispatch project (https://github.com/mrocklin/multipledispatch) +are licensed as: + +Copyright (c) 2014 Matthew Rocklin + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + a. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + b. 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. + c. Neither the name of multipledispatch 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 REGENTS 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. + +-------------------------------------------------------------------------------- + +The files under the directory sympy/parsing/autolev/tests/pydy-example-repo +are directly copied from PyDy project and are licensed as: + +Copyright (c) 2009-2023, PyDy Authors +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 this project 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 PYDY AUTHORS 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. + +-------------------------------------------------------------------------------- + +The files under the directory sympy/parsing/latex +are directly copied from latex2sympy project and are licensed as: + +Copyright 2016, latex2sympy + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/tensorboard-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/tensorboard-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..15ae42140452d32ccf929f59f7eca01a3c7b555f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/tensorboard-license.txt @@ -0,0 +1,203 @@ +Copyright 2017 The TensorFlow Authors. All rights reserved. + + 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 2017, The TensorFlow Authors. + + 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/tensorboardx-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/tensorboardx-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..bed02cde0be5fcac374c51db9902eef7fcaa90b5 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/tensorboardx-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Tzu-Wei Huang + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/tensordict-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/tensordict-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..426ba7a3fc3dacaa7bed9159c49b5a989654a14a --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/tensordict-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/termcolor-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/termcolor-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..d0b79705c354418108635b67e17ee15443a4a130 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/termcolor-license.txt @@ -0,0 +1,19 @@ +Copyright (c) 2008-2011 Volvox Development Team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/threadpoolctl-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/threadpoolctl-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..1d7302bf83b056e8bb3f53437ada712f2e94e9c2 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/threadpoolctl-license.txt @@ -0,0 +1,24 @@ +Copyright (c) 2019, threadpoolctl contributors + +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 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 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/tinyxml-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/tinyxml-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..85a6a36f0ddf7cda552b7a031a9682f2c062d722 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/tinyxml-license.txt @@ -0,0 +1,18 @@ +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/tokenizers-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/tokenizers-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/tokenizers-license.txt @@ -0,0 +1,201 @@ + 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 [yyyy] [name of copyright owner] + + 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/toml-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/toml-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..576d83e85523a28ebea0abb9789d5cdcb11e1154 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/toml-license.txt @@ -0,0 +1,27 @@ +The MIT License + +Copyright 2013-2019 William Pearson +Copyright 2015-2016 Julien Enselme +Copyright 2016 Google Inc. +Copyright 2017 Samuel Vasko +Copyright 2017 Nate Prewitt +Copyright 2017 Jack Evans +Copyright 2019 Filippo Broggini + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/torch-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/torch-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..69570b3a73d1559c95611ed18f01c174ad7e92d9 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/torch-license.txt @@ -0,0 +1,27 @@ +Copyright (c) 2016, Soumith Chintala, Ronan Collobert, Koray Kavukcuoglu, Clement Farabet +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 distro 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/torchvision-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/torchvision-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..f5e3ec99b6a07a83e2bf6a4418e8199b04f628ac --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/torchvision-license.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) Soumith Chintala 2016, +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 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/tqdm-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/tqdm-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..1899a730fb42794ca1cd2b46d082e0be5832ac5d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/tqdm-license.txt @@ -0,0 +1,49 @@ +`tqdm` is a product of collaborative work. +Unless otherwise stated, all authors (see commit logs) retain copyright +for their respective work, and release the work under the MIT licence +(text below). + +Exceptions or notable authors are listed below +in reverse chronological order: + +* files: * + MPL-2.0 2015-2024 (c) Casper da Costa-Luis + [casperdcl](https://github.com/casperdcl). +* files: tqdm/_tqdm.py + MIT 2016 (c) [PR #96] on behalf of Google Inc. +* files: tqdm/_tqdm.py README.rst .gitignore + MIT 2013 (c) Noam Yorav-Raphael, original author. + +[PR #96]: #96 + + +Mozilla Public Licence (MPL) v. 2.0 - Exhibit A +----------------------------------------------- + +This Source Code Form is subject to the terms of the +Mozilla Public License, v. 2.0. +If a copy of the MPL was not distributed with this project, +You can obtain one at https://mozilla.org/MPL/2.0/. + + +MIT License (MIT) +----------------- + +Copyright (c) 2013 noamraph + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/traitlets-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/traitlets-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..76910b096a63e9cce803b143549cf87722af2563 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/traitlets-license.txt @@ -0,0 +1,30 @@ +BSD 3-Clause License + +- Copyright (c) 2001-, IPython Development Team + +All rights reserved. + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/transformers-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/transformers-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..68b7d66c97d66c58de883ed0c451af2b3183e6f3 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/transformers-license.txt @@ -0,0 +1,203 @@ +Copyright 2018- The Hugging Face team. All rights reserved. + + 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 [yyyy] [name of copyright owner] + + 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/trimesh-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/trimesh-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..d0571124dc68ee63553001f17f043d19250159cc --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/trimesh-license.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2023 Michael Dawson-Haggerty + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/triton-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/triton-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..1d0238e86b1b43e123c9eb136eb0b2c0e1658d63 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/triton-license.txt @@ -0,0 +1,23 @@ +/* +* Copyright 2018-2020 Philippe Tillet +* Copyright 2020-2022 OpenAI +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files +* (the "Software"), to deal in the Software without restriction, +* including without limitation the rights to use, copy, modify, merge, +* publish, distribute, sublicense, and/or sell copies of the Software, +* and to permit persons to whom the Software is furnished to do so, +* subject to the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/typing-extensions-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/typing-extensions-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..f26bcf4d2de6eb136e31006ca3ab447d5e488adf --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/typing-extensions-license.txt @@ -0,0 +1,279 @@ +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see https://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations, which became +Zope Corporation. In 2001, the Python Software Foundation (PSF, see +https://www.python.org/psf/) was formed, a non-profit organization +created specifically to own Python-related Intellectual Property. +Zope Corporation was a sponsoring member of the PSF. + +All Python releases are Open Source (see https://opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2 and above 2.1.1 2001-now PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +Python software and documentation are licensed under the +Python Software Foundation License Version 2. + +Starting with Python 3.8.6, examples, recipes, and other code in +the documentation are dual licensed under the PSF License Version 2 +and the Zero-Clause BSD license. + +Some software incorporated into Python is under different licenses. +The licenses are listed with code falling under that license. + + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION +---------------------------------------------------------------------- + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/typing-inspection-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/typing-inspection-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..e825ad51621c5e34d370ba64f13f6854d89456a6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/typing-inspection-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Pydantic Services Inc. 2025 to present + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/tzdata-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/tzdata-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..c2f84aeb06f7a520b7cf17bdd9c9c3854dc4c469 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/tzdata-license.txt @@ -0,0 +1,15 @@ +Apache Software License 2.0 + +Copyright (c) 2020, Paul Ganssle (Google) + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/urdfdom-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/urdfdom-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..4c328b81145a6106c8aae365b8facfaa86b522ef --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/urdfdom-license.txt @@ -0,0 +1,33 @@ +/********************************************************************* +* Software License Agreement (BSD License) +* +* 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 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. +*********************************************************************/ diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/urllib3-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/urllib3-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..e6183d0276b26c5b87aecccf8d0d5bcd7b1148d4 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/urllib3-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2008-2020 Andrey Petrov and contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/uv-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/uv-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..014835144877ea9c926d027ece3e1a26290cf481 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/uv-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Astral Software Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/walk-these-ways-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/walk-these-ways-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..04211683fa3d1d693fa35f8f61239289ea293050 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/walk-these-ways-license.txt @@ -0,0 +1,25 @@ +MIT License + +Copyright (c) 2022 MIT Improbable AI Lab + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +See licenses/legged_gym and licenses/rsl_rl for additional license information for some files in this package. +Files associated with these additional licenses indicate so in the header. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/wandb-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/wandb-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..1f4e645404cd4ae9f131e45091c1cf9db97af225 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/wandb-license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Weights and Biases, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/warp-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/warp-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..d9a10c0d8e868ebf8da0b3dc95bb0be634c34bfe --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/warp-license.txt @@ -0,0 +1,176 @@ + 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 diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/werkzeug-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/werkzeug-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..c37cae49ec77ad6ebb25568c1605f1fee5313cfb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/werkzeug-license.txt @@ -0,0 +1,28 @@ +Copyright 2007 Pallets + +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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/widgetsnbextension-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/widgetsnbextension-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..2ec51d75f362bc4327a3cfe1c515c16bb3c57367 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/widgetsnbextension-license.txt @@ -0,0 +1,27 @@ +BSD-3-Clause license +Copyright (c) 2015-2022, conda-forge contributors +All rights reserved. + +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 REGENTS 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. diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/zipp-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/zipp-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..b5b7b529ffc2ab8ab0a947c5e4566fce08fe1e72 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/zipp-license.txt @@ -0,0 +1 @@ +license = "MIT" as indicated in pyproject.toml diff --git a/simulation/modules/IsaacLab/docs/licenses/dependencies/zlib-license.txt b/simulation/modules/IsaacLab/docs/licenses/dependencies/zlib-license.txt new file mode 100644 index 0000000000000000000000000000000000000000..038d398538e98101c7e660c4cf3b435c21e7e023 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/licenses/dependencies/zlib-license.txt @@ -0,0 +1,25 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.3.1, January 22nd, 2024 + + Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +*/ diff --git a/simulation/modules/IsaacLab/docs/make.bat b/simulation/modules/IsaacLab/docs/make.bat new file mode 100644 index 0000000000000000000000000000000000000000..dce805c99ee791f134e182436aadb814bab835b8 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/make.bat @@ -0,0 +1,75 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file to build Sphinx documentation + +set SOURCEDIR=. +set BUILDDIR=_build +if "%DOCS_DEFAULT_REF%" == "" set DOCS_DEFAULT_REF=main + +REM Check if a specific target was passed +if "%1" == "multi-docs" ( + REM Check if SPHINXBUILD is set, if not default to sphinx-multiversion + if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-multiversion + ) + where %SPHINXBUILD% >NUL 2>NUL + if errorlevel 1 ( + echo. + echo.The 'sphinx-multiversion' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-multiversion' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 + ) + %SPHINXBUILD% %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + if errorlevel 1 exit /b 1 + + if not exist "%BUILDDIR%\%DOCS_DEFAULT_REF%\index.html" ( + echo Default docs ref '%DOCS_DEFAULT_REF%' was not built + exit /b 1 + ) + + REM Render the redirect index.html using the selected default docs ref + powershell -NoProfile -Command "$ErrorActionPreference = 'Stop'; $template = [System.IO.File]::ReadAllText('_redirect\index.html'); $output = $template.Replace('__DOCS_DEFAULT_REF__', $env:DOCS_DEFAULT_REF); [System.IO.File]::WriteAllText('%BUILDDIR%\index.html', $output); exit 0" + if errorlevel 1 exit /b 1 + popd + exit /b 0 +) + +if "%1" == "current-docs" ( + REM Check if SPHINXBUILD is set, if not default to sphinx-build + if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build + ) + where %SPHINXBUILD% >NUL 2>NUL + if errorlevel 1 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 + ) + if exist "%BUILDDIR%\current" rmdir /s /q "%BUILDDIR%\current" + %SPHINXBUILD% -W "%SOURCEDIR%" "%BUILDDIR%\current" %SPHINXOPTS% + goto end +) + +REM If no valid target is passed, show usage instructions +echo. +echo.Usage: +echo. make.bat multi-docs - To build the multi-version documentation. +echo. make.bat current-docs - To build the current documentation. +echo. + +:end +popd +exit /b 0 diff --git a/simulation/modules/IsaacLab/docs/requirements.txt b/simulation/modules/IsaacLab/docs/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..392951b0a8eee040d489f49148fd63acc31fd499 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/requirements.txt @@ -0,0 +1,20 @@ +# for building the docs +sphinx>=7.0,<9 +sphinx-book-theme>=1.1 +myst-parser +sphinxcontrib-bibtex==2.5.0 +autodocsumm +sphinx-copybutton +sphinx-icon +sphinx_design +sphinxemoji +sphinx-tabs # backwards compatibility for building docs on v1.0.0 +sphinx-multiversion==0.2.4 + +# basic python +numpy +matplotlib +warp-lang +lazy_loader>=0.4 +# learning +gymnasium diff --git a/simulation/modules/IsaacLab/docs/source/_static/NVIDIA-logo-black.png b/simulation/modules/IsaacLab/docs/source/_static/NVIDIA-logo-black.png new file mode 100644 index 0000000000000000000000000000000000000000..5a982e2e94bb2ecad6f3a96bf67ef5a3c6ac99d0 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/NVIDIA-logo-black.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a30acc905d80587f70b7368591377156e5135dffc9a84850cd0e25fccc86a27d +size 39261 diff --git a/simulation/modules/IsaacLab/docs/source/_static/NVIDIA-logo-white.png b/simulation/modules/IsaacLab/docs/source/_static/NVIDIA-logo-white.png new file mode 100644 index 0000000000000000000000000000000000000000..457ffe18452de043c4e8065e03a7f75126156f7b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/NVIDIA-logo-white.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c305f6ac606b24ce4e1db63b9d47d8e99e436ed4ecc94ccb5824185734f3f464 +size 130540 diff --git a/simulation/modules/IsaacLab/docs/source/_static/actuator-group/actuator-dark.svg b/simulation/modules/IsaacLab/docs/source/_static/actuator-group/actuator-dark.svg new file mode 100644 index 0000000000000000000000000000000000000000..b9e0682395d4ae1f1769a8039f79a14dce813076 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/actuator-group/actuator-dark.svg @@ -0,0 +1,522 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + DC Motor + Actuator Net(MLP/LSTM) + + Gripper + + + Arm + Base + Mimic Group + + + + open/close (1) + joint position(6) + joint position(12) + joint torque(12) + joint torque(6) + joint velocity(6) + + Simulation + + + + Actions + + + + + + + + + + + diff --git a/simulation/modules/IsaacLab/docs/source/_static/actuator-group/actuator-light.svg b/simulation/modules/IsaacLab/docs/source/_static/actuator-group/actuator-light.svg new file mode 100644 index 0000000000000000000000000000000000000000..214b5a7fee2d45248b0fa38c2e7ff438a7ebde23 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/actuator-group/actuator-light.svg @@ -0,0 +1,10214 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + DC Motor + Actuator Net(MLP/LSTM) + + Gripper + + + Arm + Base + Mimic Group + + + + open/close (1) + joint position(6) + joint position(12) + joint torque(12) + joint torque(6) + joint velocity(6) + + Simulation + + + + Actions + + + + + + + + + + + diff --git a/simulation/modules/IsaacLab/docs/source/_static/actuator-group/dc_motor_clipping.jpg b/simulation/modules/IsaacLab/docs/source/_static/actuator-group/dc_motor_clipping.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bc44bcff8d28d4012a2cd38e95afe9b941821e80 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/actuator-group/dc_motor_clipping.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85b08723a42530b70f2d54e109b1f1914827aedb5bb6f963f64794ac2c83219c +size 63276 diff --git a/simulation/modules/IsaacLab/docs/source/_static/benchmarks/cartpole.jpg b/simulation/modules/IsaacLab/docs/source/_static/benchmarks/cartpole.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a407fa75277a9cfa962db02ba3a4b084a5d4afb8 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/benchmarks/cartpole.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ebd6fb905977ca8469f83d5e781f71539548fdf4a391e65853a6f8ae1b26b46 +size 139764 diff --git a/simulation/modules/IsaacLab/docs/source/_static/benchmarks/cartpole_camera.jpg b/simulation/modules/IsaacLab/docs/source/_static/benchmarks/cartpole_camera.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1776ea8403a671eb157b30273811708aff836ec1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/benchmarks/cartpole_camera.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93298b069d5e386d56a138e8677bd6f2525e6ef35956c80196485fa20e9cb93b +size 59002 diff --git a/simulation/modules/IsaacLab/docs/source/_static/benchmarks/g1_rough.jpg b/simulation/modules/IsaacLab/docs/source/_static/benchmarks/g1_rough.jpg new file mode 100644 index 0000000000000000000000000000000000000000..71c716a3886ec649a0bdbf601bb443e973ab4839 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/benchmarks/g1_rough.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69ee9c49e1d84b41cb78527e0a538517bbc9240f692bb5a286b6f078e5728283 +size 1169796 diff --git a/simulation/modules/IsaacLab/docs/source/_static/benchmarks/shadow.jpg b/simulation/modules/IsaacLab/docs/source/_static/benchmarks/shadow.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5f86a34ac760be7bd67aeb3b84d0d2536d3f055a --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/benchmarks/shadow.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8cb64bf5efb554d9e499ba0b98687c7ca5e569a538241223875d8326adde1e1 +size 116659 diff --git a/simulation/modules/IsaacLab/docs/source/_static/css/custom.css b/simulation/modules/IsaacLab/docs/source/_static/css/custom.css new file mode 100644 index 0000000000000000000000000000000000000000..ba1d962c0f90ee5a947c2b6b4d8b86d565ddf1b4 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/css/custom.css @@ -0,0 +1,180 @@ +/* + * For reference: https://pydata-sphinx-theme.readthedocs.io/en/v0.9.0/user_guide/customizing.html + * For colors: https://clrs.cc/ + */ + +/* anything related to the light theme */ +html[data-theme="light"] { + --pst-color-primary: #76B900; + --pst-color-secondary: #5b8e03; + --pst-color-secondary-highlight: #5b8e03; + --pst-color-inline-code-links: #76B900; + --pst-color-info: var(--pst-color-primary); + --pst-color-info-highlight: var(--pst-color-primary); + --pst-color-info-bg: #daedb9; + --pst-color-attention: #ffc107; + --pst-color-text-base: #323232; + --pst-color-text-muted: #646464; + --pst-color-shadow: #d8d8d8; + --pst-color-border: #c9c9c9; + --pst-color-inline-code: #76B900; + --pst-color-target: #fbe54e; + --pst-color-background: #fff; + --pst-color-on-background: #fff; + --pst-color-surface: #f5f5f5; + --pst-color-on-surface: #e1e1e1; + --pst-color-link: var(--pst-color-primary); + --pst-color-link-hover: #789841; + --pst-color-table-row-hover-bg: #daedb9; + --pst-color-accent: var(--pst-color-primary); +} + +/* anything related to the dark theme */ +html[data-theme="dark"] { + --pst-color-primary: #76B900; + --pst-color-secondary: #c2f26f; + --pst-color-secondary-highlight: #c2f26f; + --pst-color-inline-code-links: #b6e664; + --pst-color-info: var(--pst-color-primary); + --pst-color-info-highlight: var(--pst-color-primary); + --pst-color-info-bg: #3a550b; + --pst-color-attention: #dca90f; + --pst-color-text-base: #cecece; + --pst-color-text-muted: #a6a6a6; + --pst-color-shadow: #212121; + --pst-color-border: silver; + --pst-color-inline-code: #76B900; + --pst-color-target: #472700; + --pst-color-background: #121212; + --pst-color-on-background: #1e1e1e; + --pst-color-surface: #212121; + --pst-color-on-surface: #373737; + --pst-color-link: var(--pst-color-primary); + --pst-color-link-hover: #aee354; + --pst-color-table-row-hover-bg: #3a550b; + --pst-color-accent: var(--pst-color-primary); +} + +a { + text-decoration: none !important; +} + +/* for the announcement link */ +.bd-header-announcement a, +.bd-header-version-warning a { + color: #7FDBFF; +} + +/* for the search box in the navbar */ +.form-control { + border-radius: 0 !important; + border: none !important; + outline: none !important; +} + +/* reduce padding for logo */ +.navbar-brand { + padding-top: 0.0rem !important; + padding-bottom: 0.0rem !important; +} + +.navbar-icon-links { + padding-top: 0.0rem !important; + padding-bottom: 0.0rem !important; +} + +/* showcase task tables */ + +.showcase-table { + min-width: 75%; +} + +.showcase-table td { + border-color: gray; + border-style: solid; + border-width: 1px; +} + +.showcase-table p { + margin: 0; + padding: 0; +} + +.showcase-table .rot90 { + transform: rotate(-90deg); + margin: 0; + padding: 0; +} + +.showcase-table .center { + text-align: center; + vertical-align: middle; +} + +.square-crop-figure img { + aspect-ratio: 1 / 1; + object-fit: cover; + object-position: center; + width: min(100%, 480px); +} + +.nurec-gif-grid, +.nurec-gif-grid td { + border: none; +} + +.nurec-gif-grid td { + vertical-align: top; +} + +.nurec-gif-grid figure { + margin-left: auto; + margin-right: auto; + max-width: 360px; +} + +figure.nurec-gif-cover img, +figure.nurec-gif-contain img { + aspect-ratio: 16 / 9; + display: block; + object-position: center; + width: 100%; +} + +figure.nurec-gif-cover img { + object-fit: cover; +} + +figure.nurec-gif-contain img { + object-fit: contain; +} + +.nurec-gif-grid figcaption { + font-family: "NVIDIA Sans", "Inter", "Segoe UI", sans-serif; + font-size: 0.86rem; + line-height: 1.35; +} + +.nurec-gif-grid figcaption p { + margin-bottom: 0.15rem; +} + +.nurec-gif-grid figcaption .line-block { + margin-top: 0; +} + +.nurec-gif-grid-single figcaption { + margin-left: 50%; + max-width: calc(100vw - 2rem); + transform: translateX(-50%); + width: max-content; +} + +.nurec-gif-grid-single figcaption .line-block .line:nth-child(2) { + white-space: nowrap; +} + +/* Keep sphinx-copybutton visible on code blocks (not only on hover). */ +button.copybtn { + opacity: 1; +} diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/arms.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/arms.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ce790c0d7fe9d252f2a1186b6cad95f8e3ecf426 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/arms.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5facf289253e7d43340531099198774936ae9db71b591fc7d81510c43f3dd96 +size 313056 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/bin_packing.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/bin_packing.jpg new file mode 100644 index 0000000000000000000000000000000000000000..55f9738486509e92ce77e1ed3d9e2ae457da511a --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/bin_packing.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d72762a3e88307562883e95be0e88f2b0ac60834f6b9b6edc5c3abe620c09de +size 515084 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/bipeds.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/bipeds.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1723d11d477ec858c78eea6f5271a3051ad26082 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/bipeds.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:475e40cb522081edb09ab14860074dfd70d62c0d86d51755b9495c8dccc2a530 +size 158757 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/deformables.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/deformables.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e7c45b44c915e599750d2b5b0ebc5ed7c7588f78 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/deformables.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06134f9bb155f5dc44ab836ba7639e87fb1425edc0c78f2f1f024311f4918379 +size 391647 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/h1_locomotion.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/h1_locomotion.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ac278356ac24b80f302fe56b0535f63945e6e4e1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/h1_locomotion.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c8ef8a3c02fade0e9e3065396bd7b1411469fcfef380d37f7da509a1f9caf41 +size 337160 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/hands.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/hands.jpg new file mode 100644 index 0000000000000000000000000000000000000000..13af7af022c3f8a69e49cef53f6b03be72258730 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/hands.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:837a1e2285fd6efbf35a983c21b71247b89ce588a02f82057175b6d299dd851c +size 199627 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/haply_teleop_franka.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/haply_teleop_franka.jpg new file mode 100644 index 0000000000000000000000000000000000000000..87af730fbf28daf0b3433604fada7bcd77013c55 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/haply_teleop_franka.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:923de0e878048719219f3388f9ef131100b66fa48bf9b604de4a9f27507d9e81 +size 118473 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/markers.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/markers.jpg new file mode 100644 index 0000000000000000000000000000000000000000..840624d0a0283d7b4901f806120843fb94c35093 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/markers.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29e113cfa57cfbfcdee5d42af5dca6524d7de77a74eb501431c3f1521fb61e8e +size 175336 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/multi-mesh-raycast.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/multi-mesh-raycast.jpg new file mode 100644 index 0000000000000000000000000000000000000000..edfbb97121c2e702b9930e9f5c2f173efca70358 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/multi-mesh-raycast.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ff1c1e0906d541f286e161002186ecf17c6e4fbd4efa9ee74f458dfc2c472049 +size 744243 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/multi_asset.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/multi_asset.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ddd731133a03a6dd2dabdc4e4d8badfff4017013 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/multi_asset.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c4b7a522275b199500a1d39b572ce338aa2497b36dc655c2012066f2047057e +size 551533 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/pick_and_place.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/pick_and_place.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1e9eef30db87cb2b26bbab6892d40519fb82eb6c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/pick_and_place.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7aeba5926b9f0904d20cc2be594a001cded3d5a7846057983bdc7f84cd72d73d +size 259917 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/procedural_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/procedural_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7ffa1180e8a29c20fd7aed47cb585638d7d71e71 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/procedural_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c9928051a12d5c563d3301613f47367a1792ae18350353d07f332fd6d2f8d9f +size 448684 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/quadcopter.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/quadcopter.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d06c035127940efe2a1baf4903a386dab92b70c7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/quadcopter.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9017aab60dd74841f89e49737a910538c5bf6c872ec91379b486221c14ee5985 +size 71881 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/quadrupeds.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/quadrupeds.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a3915c65694bea513b6d09c33864787e1206e986 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/quadrupeds.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b4fc3f8db9118e3fd000eff45815d19e789a6699bd0dcecb3172fb95dc2baef +size 346110 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/renderer_rtx_realtime.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/renderer_rtx_realtime.jpg new file mode 100644 index 0000000000000000000000000000000000000000..110792a8c87e30cfcc7dc3f116ed9ccbb8472b14 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/renderer_rtx_realtime.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e4bed7f2e7001530fe4d0e29f1d60b297a9e19fd34ae387fdc0935de24f19bd +size 141878 diff --git a/simulation/modules/IsaacLab/docs/source/_static/demos/start_ar.jpg b/simulation/modules/IsaacLab/docs/source/_static/demos/start_ar.jpg new file mode 100644 index 0000000000000000000000000000000000000000..34e546141d80de503dce0825bacc42f8d8d48ef7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/demos/start_ar.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0c8dbd748dfc862e7879a2120a346ce1a7c4d3639e2aa2fd0085a55559945f6 +size 69913 diff --git a/simulation/modules/IsaacLab/docs/source/_static/favicon.ico b/simulation/modules/IsaacLab/docs/source/_static/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..7b39f8af7af0831df98713dd0c28347049e4041f Binary files /dev/null and b/simulation/modules/IsaacLab/docs/source/_static/favicon.ico differ diff --git a/simulation/modules/IsaacLab/docs/source/_static/how-to/howto_profile_nsys_example.png b/simulation/modules/IsaacLab/docs/source/_static/how-to/howto_profile_nsys_example.png new file mode 100644 index 0000000000000000000000000000000000000000..aba225f740d84696abd05e4e36be6352eb738165 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/how-to/howto_profile_nsys_example.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5d09ec8017830669dc21e1ed6be9b514675250f10e40b321157f54da7e677b9 +size 92051 diff --git a/simulation/modules/IsaacLab/docs/source/_static/how-to/howto_rendering_example_balanced.jpg b/simulation/modules/IsaacLab/docs/source/_static/how-to/howto_rendering_example_balanced.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5936c54625e464379a144a5387d174500054f8d6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/how-to/howto_rendering_example_balanced.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8dd6b98fc09861ffe8e72745df5938bdda00b79dec3e2780bff85119f7d5808 +size 144149 diff --git a/simulation/modules/IsaacLab/docs/source/_static/how-to/howto_rendering_example_performance.jpg b/simulation/modules/IsaacLab/docs/source/_static/how-to/howto_rendering_example_performance.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0d55e254720e830ea8db8a57034a0199a5920ac9 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/how-to/howto_rendering_example_performance.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85671f5d1de5f73f14faefef74331466c1721c1c06c02fb38c2345de0e6bbf4c +size 157386 diff --git a/simulation/modules/IsaacLab/docs/source/_static/how-to/howto_rendering_example_quality.jpg b/simulation/modules/IsaacLab/docs/source/_static/how-to/howto_rendering_example_quality.jpg new file mode 100644 index 0000000000000000000000000000000000000000..43371362e600e9bc0404583eda67be1bae6ab39e --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/how-to/howto_rendering_example_quality.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:28e3065ef3983beb569e08147c5fafae37d4279535653d0089a7626e6caf5db0 +size 209737 diff --git a/simulation/modules/IsaacLab/docs/source/_static/isaaclab.jpg b/simulation/modules/IsaacLab/docs/source/_static/isaaclab.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7429d254d812d5d4352b176d8845be2e02f2d320 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/isaaclab.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f7116ad3a71eacfa797fe782fce9e97868f7a205ddb8d99b35e2593bd9d55d14 +size 668544 diff --git a/simulation/modules/IsaacLab/docs/source/_static/migration/ovd_pvd_comparison.jpg b/simulation/modules/IsaacLab/docs/source/_static/migration/ovd_pvd_comparison.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6898fc2048ca25fa0ae199a3763573a140c8ce0c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/migration/ovd_pvd_comparison.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83ec048a96e8a68396e5e0be7988e670fa7d490766eecebf475687e5adafdeab +size 474941 diff --git a/simulation/modules/IsaacLab/docs/source/_static/mimic/franka_cube_stacking_env.jpg b/simulation/modules/IsaacLab/docs/source/_static/mimic/franka_cube_stacking_env.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0e3f2d438e0ff4ffe60ca74e632b5047bb661a16 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/mimic/franka_cube_stacking_env.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49c8bb0453918485e57ccb1d061a4fc6c7e9bf15048324efefb5b2210deec2fa +size 118712 diff --git a/simulation/modules/IsaacLab/docs/source/_static/mimic/franka_datagen.jpg b/simulation/modules/IsaacLab/docs/source/_static/mimic/franka_datagen.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7e461311d1b672875d56cf9761ea44d7fc8a0f06 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/mimic/franka_datagen.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69e4fea2be17201ff8fbdfd308a0a534e2bf2be4975fce03243ba287717cad21 +size 178195 diff --git a/simulation/modules/IsaacLab/docs/source/_static/mimic/franka_mimic_imitation_learning.jpg b/simulation/modules/IsaacLab/docs/source/_static/mimic/franka_mimic_imitation_learning.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9cfb7f10f7b1462b557f73d29deeef7f0a19628d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/mimic/franka_mimic_imitation_learning.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f3ca0917279b4003c63a0937cefe29e8942c1c636a945c38682f00749aa0f2c9 +size 54092 diff --git a/simulation/modules/IsaacLab/docs/source/_static/mimic/mimic_env_architecture.jpg b/simulation/modules/IsaacLab/docs/source/_static/mimic/mimic_env_architecture.jpg new file mode 100644 index 0000000000000000000000000000000000000000..17cb1efe7dc0344b6741a518d31457a79ac8e0e8 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/mimic/mimic_env_architecture.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45a256e35154766e7fdfae2866fec267356dd8839907297db3620781639b9ce6 +size 356896 diff --git a/simulation/modules/IsaacLab/docs/source/_static/multi-gpu-rl/a3c-dark.svg b/simulation/modules/IsaacLab/docs/source/_static/multi-gpu-rl/a3c-dark.svg new file mode 100644 index 0000000000000000000000000000000000000000..48cdb849142af020b7534931127eb0e4f7865a22 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/multi-gpu-rl/a3c-dark.svg @@ -0,0 +1,364 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/simulation/modules/IsaacLab/docs/source/_static/multi-gpu-rl/a3c-light.svg b/simulation/modules/IsaacLab/docs/source/_static/multi-gpu-rl/a3c-light.svg new file mode 100644 index 0000000000000000000000000000000000000000..d24bfc20b7427cb22487acc0d1963904d63541cc --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/multi-gpu-rl/a3c-light.svg @@ -0,0 +1,385 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/simulation/modules/IsaacLab/docs/source/_static/newton/franka-mjwarp-vbd-coupling.png b/simulation/modules/IsaacLab/docs/source/_static/newton/franka-mjwarp-vbd-coupling.png new file mode 100644 index 0000000000000000000000000000000000000000..a27cfe5235bdb7c10751036830446fad5b737318 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/newton/franka-mjwarp-vbd-coupling.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e21b5512732043a5af309e44f30bb5dab1c79d87e9314bf4c30625f1ec3f97d +size 1309804 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_depth.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_depth.jpg new file mode 100644 index 0000000000000000000000000000000000000000..46c62d104a65f9979cf31ab5261ded1d0cfb719b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_depth.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e00cd5663a7abcabf081106f02037e1591ea0d2d63edb0df7462b7a972389a58 +size 19213 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_instance.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_instance.jpg new file mode 100644 index 0000000000000000000000000000000000000000..da4a767af6b937b4afe6c40ec5636067395828f1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_instance.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af022a5262728c079e57d267413d50dc5caa7cdfe094402c94c3f65b82366ce3 +size 18058 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_instanceID.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_instanceID.jpg new file mode 100644 index 0000000000000000000000000000000000000000..df78f6acf6436187dd6dc673b58dd3e810d77540 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_instanceID.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ca046d7e9db088d887efa06ba8bead914697fec3be717257db3662045d264fa +size 15952 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_normals.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_normals.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0560985649638bd32c192d7d226d782307e41eef --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_normals.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4b0a7a095b2867d6857f7b5ba26328d35a5a3d6f3233401d858718d6f71e46c +size 16814 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_rgb.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_rgb.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0cb40481b9ce73e97cedc517b85e92832d9193be --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_rgb.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d035da8c578a919feded97d9c54687dcfa52a308468af4ef0fbfdc4d591dea3a +size 49868 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_semantic.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_semantic.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1f35e136febdb3087b96df1d31ce3360b5ef3524 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/camera_semantic.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a3e6ac28923773ac22f62a7c8ab506a6d6889603192b5aab04b62b9bb43ae93 +size 17980 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/contact_diagram.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/contact_diagram.jpg new file mode 100644 index 0000000000000000000000000000000000000000..cd8849abbbd5ace234b901db6936641e918a8428 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/contact_diagram.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb7b2fbfadd77ef415042a508ddc45baf334dc246eaacc4ce7ad59dc277b2986 +size 160782 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/contact_visualization.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/contact_visualization.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6ad67661e0063fcc314897a835664f3166292c06 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/contact_visualization.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72c96ef1dd39f22b831c61301514a427c1e8d3ab0d69c752a2e5ccc4c4ed597b +size 104622 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/frame_transformer.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/frame_transformer.jpg new file mode 100644 index 0000000000000000000000000000000000000000..94f156ceba8bb380bc06e203efc24e686f1ea685 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/frame_transformer.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2a18c09118bbd9845efc8ae4dd43b7d31919904211857fcc5ad7cd1b786821e1 +size 145208 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/frame_transformer_visualizer.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/frame_transformer_visualizer.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6e1a7be0fa75e0b30e28129770169d849c9e4cd1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/frame_transformer_visualizer.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:98759d133602696750f6e702c8b5ceb0b4a708a8110e9ac18de60de2c5ae34b4 +size 42815 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/imu_diagram.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/imu_diagram.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b6e2710e241a8cbb5a65d2423e134f1c58f73c11 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/imu_diagram.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3282bf828cfe9e14778a5be47f2e13a4a25431acba160e11dde15ed2d64f0967 +size 138998 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/imu_visualizer.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/imu_visualizer.jpg new file mode 100644 index 0000000000000000000000000000000000000000..525b7636d611d79c0d30b431f46c56c3c45dc317 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/imu_visualizer.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf108bf92a62084d8b8aa00a70df8d98e6dab8eed77ce216ad21ac5a50eec8bd +size 64601 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/raycaster_patterns.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/raycaster_patterns.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d9c0ea0d14e6a428117bea2d800b517828d59284 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/raycaster_patterns.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8bcea51655c8e4c16740901a721e01927bab0e70d31695460d908374e2d08ba8 +size 253172 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/raycaster_visualizer.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/raycaster_visualizer.jpg new file mode 100644 index 0000000000000000000000000000000000000000..837030ec423d1b94578b277426609b620491de11 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/raycaster_visualizer.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f41e26ed780a6db71caf0deb543024f1c94e0ec8fa25a6f44b65910866c36cdc +size 238348 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/tacsl_demo.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/tacsl_demo.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0066b82b2f3d762f5756d1c7f0838b12dc6715f0 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/tacsl_demo.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f141a29e761413559695539f7e65d1758bb856138c9e87bde2791d8b46fbb63 +size 98901 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/tacsl_diagram.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/tacsl_diagram.jpg new file mode 100644 index 0000000000000000000000000000000000000000..280c7433e32f1d1b8986edd2fbe392a79f9423f6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/tacsl_diagram.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f6dca1e2f9bf9cd28377bda42bdaed47fa54bf964281e90c4d61ab7393cecee5 +size 103411 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/tacsl_force_field_example.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/tacsl_force_field_example.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1c4e5e7a68a4b1dc30c5644e38cf517d1de74dfa --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/tacsl_force_field_example.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7f36edbe8cef12b4e5c04df0f19b55f9a2a846f480f42044f1a6f024a0b441b3 +size 239919 diff --git a/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/tacsl_taxim_example.jpg b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/tacsl_taxim_example.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6e370e93e020ea271e280e4e0765ecc5ee7bb685 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/overview/sensors/tacsl_taxim_example.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:758ab2ede6158564b7bcc0260ab6dd2934e6da04b5fdcd8f24892db5b9420125 +size 18013 diff --git a/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/01_io_descriptors/isaac_velocity_flat_anymal_d_v0_IO_descriptors.yaml b/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/01_io_descriptors/isaac_velocity_flat_anymal_d_v0_IO_descriptors.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f44840c0f908bd7b2bc2579e952771b5c69f5904 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/01_io_descriptors/isaac_velocity_flat_anymal_d_v0_IO_descriptors.yaml @@ -0,0 +1,349 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +actions: +- action_type: JointAction + clip: null + dtype: torch.float32 + extras: + description: Joint action term that applies the processed actions to the articulation's + joints as position commands. + full_path: isaaclab.envs.mdp.actions.joint_actions.JointPositionAction + joint_names: + - LF_HAA + - LH_HAA + - RF_HAA + - RH_HAA + - LF_HFE + - LH_HFE + - RF_HFE + - RH_HFE + - LF_KFE + - LH_KFE + - RF_KFE + - RH_KFE + mdp_type: Action + name: joint_position_action + offset: + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.4000000059604645 + - -0.4000000059604645 + - 0.4000000059604645 + - -0.4000000059604645 + - -0.800000011920929 + - 0.800000011920929 + - -0.800000011920929 + - 0.800000011920929 + scale: 0.5 + shape: + - 12 +articulations: + robot: + default_joint_armature: + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + default_joint_damping: + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + default_joint_friction: + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + default_joint_pos: + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.4000000059604645 + - -0.4000000059604645 + - 0.4000000059604645 + - -0.4000000059604645 + - -0.800000011920929 + - 0.800000011920929 + - -0.800000011920929 + - 0.800000011920929 + default_joint_pos_limits: + - - -0.7853984236717224 + - 0.6108654141426086 + - - -0.7853984236717224 + - 0.6108654141426086 + - - -0.6108654141426086 + - 0.7853984236717224 + - - -0.6108654141426086 + - 0.7853984236717224 + - - -9.42477798461914 + - 9.42477798461914 + - - -9.42477798461914 + - 9.42477798461914 + - - -9.42477798461914 + - 9.42477798461914 + - - -9.42477798461914 + - 9.42477798461914 + - - -9.42477798461914 + - 9.42477798461914 + - - -9.42477798461914 + - 9.42477798461914 + - - -9.42477798461914 + - 9.42477798461914 + - - -9.42477798461914 + - 9.42477798461914 + default_joint_stiffness: + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + default_joint_vel: + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + joint_names: + - LF_HAA + - LH_HAA + - RF_HAA + - RH_HAA + - LF_HFE + - LH_HFE + - RF_HFE + - RH_HFE + - LF_KFE + - LH_KFE + - RF_KFE + - RH_KFE +observations: + policy: + - dtype: torch.float32 + extras: + axes: + - X + - Y + - Z + description: Root linear velocity in the asset's root frame. + modifiers: null + units: m/s + full_path: isaaclab.envs.mdp.observations.base_lin_vel + mdp_type: Observation + name: base_lin_vel + observation_type: RootState + overloads: + clip: null + flatten_history_dim: true + history_length: 0 + scale: null + shape: + - 3 + - dtype: torch.float32 + extras: + axes: + - X + - Y + - Z + description: Root angular velocity in the asset's root frame. + modifiers: null + units: rad/s + full_path: isaaclab.envs.mdp.observations.base_ang_vel + mdp_type: Observation + name: base_ang_vel + observation_type: RootState + overloads: + clip: null + flatten_history_dim: true + history_length: 0 + scale: null + shape: + - 3 + - dtype: torch.float32 + extras: + axes: + - X + - Y + - Z + description: Gravity projection on the asset's root frame. + modifiers: null + units: m/s^2 + full_path: isaaclab.envs.mdp.observations.projected_gravity + mdp_type: Observation + name: projected_gravity + observation_type: RootState + overloads: + clip: null + flatten_history_dim: true + history_length: 0 + scale: null + shape: + - 3 + - dtype: torch.float32 + extras: + description: The generated command from command term in the command manager + with the given name. + modifiers: null + full_path: isaaclab.envs.mdp.observations.generated_commands + mdp_type: Observation + name: generated_commands + observation_type: Command + overloads: + clip: null + flatten_history_dim: true + history_length: 0 + scale: null + shape: + - 3 + - dtype: torch.float32 + extras: + description: 'The joint positions of the asset w.r.t. the default joint positions. + Note: Only the joints configured in :attr:`asset_cfg.joint_ids` will have + their positions returned.' + modifiers: null + units: rad + full_path: isaaclab.envs.mdp.observations.joint_pos_rel + joint_names: + - LF_HAA + - LH_HAA + - RF_HAA + - RH_HAA + - LF_HFE + - LH_HFE + - RF_HFE + - RH_HFE + - LF_KFE + - LH_KFE + - RF_KFE + - RH_KFE + joint_pos_offsets: + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.4000000059604645 + - -0.4000000059604645 + - 0.4000000059604645 + - -0.4000000059604645 + - -0.800000011920929 + - 0.800000011920929 + - -0.800000011920929 + - 0.800000011920929 + mdp_type: Observation + name: joint_pos_rel + observation_type: JointState + overloads: + clip: null + flatten_history_dim: true + history_length: 0 + scale: null + shape: + - 12 + - dtype: torch.float32 + extras: + description: 'The joint velocities of the asset w.r.t. the default joint velocities. + Note: Only the joints configured in :attr:`asset_cfg.joint_ids` will have + their velocities returned.' + modifiers: null + units: rad/s + full_path: isaaclab.envs.mdp.observations.joint_vel_rel + joint_names: + - LF_HAA + - LH_HAA + - RF_HAA + - RH_HAA + - LF_HFE + - LH_HFE + - RF_HFE + - RH_HFE + - LF_KFE + - LH_KFE + - RF_KFE + - RH_KFE + joint_vel_offsets: + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + mdp_type: Observation + name: joint_vel_rel + observation_type: JointState + overloads: + clip: null + flatten_history_dim: true + history_length: 0 + scale: null + shape: + - 12 + - dtype: torch.float32 + extras: + description: The last input action to the environment. The name of the action + term for which the action is required. If None, the entire action tensor is + returned. + modifiers: null + full_path: isaaclab.envs.mdp.observations.last_action + mdp_type: Observation + name: last_action + observation_type: Action + overloads: + clip: null + flatten_history_dim: true + history_length: 0 + scale: null + shape: + - 12 +scene: + decimation: 4 + dt: 0.02 + physics_dt: 0.005 diff --git a/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/01_io_descriptors/isaac_velocity_flat_g1_v0_IO_descriptors.yaml b/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/01_io_descriptors/isaac_velocity_flat_g1_v0_IO_descriptors.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d932800eaf6eae1ff0387c8b56fe733921b48931 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/01_io_descriptors/isaac_velocity_flat_g1_v0_IO_descriptors.yaml @@ -0,0 +1,724 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +actions: +- action_type: JointAction + clip: null + dtype: torch.float32 + extras: + description: Joint action term that applies the processed actions to the articulation's + joints as position commands. + full_path: isaaclab.envs.mdp.actions.joint_actions.JointPositionAction + joint_names: + - left_hip_pitch_joint + - right_hip_pitch_joint + - torso_joint + - left_hip_roll_joint + - right_hip_roll_joint + - left_shoulder_pitch_joint + - right_shoulder_pitch_joint + - left_hip_yaw_joint + - right_hip_yaw_joint + - left_shoulder_roll_joint + - right_shoulder_roll_joint + - left_knee_joint + - right_knee_joint + - left_shoulder_yaw_joint + - right_shoulder_yaw_joint + - left_ankle_pitch_joint + - right_ankle_pitch_joint + - left_elbow_pitch_joint + - right_elbow_pitch_joint + - left_ankle_roll_joint + - right_ankle_roll_joint + - left_elbow_roll_joint + - right_elbow_roll_joint + - left_five_joint + - left_three_joint + - left_zero_joint + - right_five_joint + - right_three_joint + - right_zero_joint + - left_six_joint + - left_four_joint + - left_one_joint + - right_six_joint + - right_four_joint + - right_one_joint + - left_two_joint + - right_two_joint + mdp_type: Action + name: joint_position_action + offset: + - -0.20000000298023224 + - -0.20000000298023224 + - 0.0 + - 0.0 + - 0.0 + - 0.3499999940395355 + - 0.3499999940395355 + - 0.0 + - 0.0 + - 0.1599999964237213 + - -0.1599999964237213 + - 0.41999998688697815 + - 0.41999998688697815 + - 0.0 + - 0.0 + - -0.23000000417232513 + - -0.23000000417232513 + - 0.8700000047683716 + - 0.8700000047683716 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 1.0 + - 0.0 + - 0.0 + - -1.0 + - 0.5199999809265137 + - -0.5199999809265137 + scale: 0.5 + shape: + - 37 +articulations: + robot: + default_joint_armature: + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.009999999776482582 + - 0.0010000000474974513 + - 0.0010000000474974513 + - 0.0010000000474974513 + - 0.0010000000474974513 + - 0.0010000000474974513 + - 0.0010000000474974513 + - 0.0010000000474974513 + - 0.0010000000474974513 + - 0.0010000000474974513 + - 0.0010000000474974513 + - 0.0010000000474974513 + - 0.0010000000474974513 + - 0.0010000000474974513 + - 0.0010000000474974513 + default_joint_damping: + - 5.0 + - 5.0 + - 5.0 + - 5.0 + - 5.0 + - 10.0 + - 10.0 + - 5.0 + - 5.0 + - 10.0 + - 10.0 + - 5.0 + - 5.0 + - 10.0 + - 10.0 + - 2.0 + - 2.0 + - 10.0 + - 10.0 + - 2.0 + - 2.0 + - 10.0 + - 10.0 + - 10.0 + - 10.0 + - 10.0 + - 10.0 + - 10.0 + - 10.0 + - 10.0 + - 10.0 + - 10.0 + - 10.0 + - 10.0 + - 10.0 + - 10.0 + - 10.0 + default_joint_friction: + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + default_joint_pos: + - -0.20000000298023224 + - -0.20000000298023224 + - 0.0 + - 0.0 + - 0.0 + - 0.3499999940395355 + - 0.3499999940395355 + - 0.0 + - 0.0 + - 0.1599999964237213 + - -0.1599999964237213 + - 0.41999998688697815 + - 0.41999998688697815 + - 0.0 + - 0.0 + - -0.23000000417232513 + - -0.23000000417232513 + - 0.8700000047683716 + - 0.8700000047683716 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 1.0 + - 0.0 + - 0.0 + - -1.0 + - 0.5199999809265137 + - -0.5199999809265137 + default_joint_pos_limits: + - - -2.3499996662139893 + - 3.049999952316284 + - - -2.3499996662139893 + - 3.049999952316284 + - - -2.618000030517578 + - 2.618000030517578 + - - -0.25999996066093445 + - 2.5299997329711914 + - - -2.5299997329711914 + - 0.25999996066093445 + - - -2.967099666595459 + - 2.7924997806549072 + - - -2.967099666595459 + - 2.7924997806549072 + - - -2.749999761581421 + - 2.749999761581421 + - - -2.749999761581421 + - 2.749999761581421 + - - -1.5881999731063843 + - 2.251499652862549 + - - -2.251499652862549 + - 1.5881999731063843 + - - -0.3348899781703949 + - 2.5448997020721436 + - - -0.3348899781703949 + - 2.5448997020721436 + - - -2.618000030517578 + - 2.618000030517578 + - - -2.618000030517578 + - 2.618000030517578 + - - -0.6799999475479126 + - 0.7299999594688416 + - - -0.6799999475479126 + - 0.7299999594688416 + - - -0.22679997980594635 + - 3.420799732208252 + - - -0.22679997980594635 + - 3.420799732208252 + - - -0.26179996132850647 + - 0.26179996132850647 + - - -0.26179996132850647 + - 0.26179996132850647 + - - -2.094299793243408 + - 2.094299793243408 + - - -2.094299793243408 + - 2.094299793243408 + - - -1.8399999141693115 + - 0.30000001192092896 + - - -1.8399999141693115 + - 0.30000001192092896 + - - -0.5235979557037354 + - 0.5235979557037354 + - - -0.30000001192092896 + - 1.8399999141693115 + - - -0.30000001192092896 + - 1.8399999141693115 + - - -0.5235979557037354 + - 0.5235979557037354 + - - -1.8399999141693115 + - 0.0 + - - -1.8399999141693115 + - 0.0 + - - -0.9999999403953552 + - 1.2000000476837158 + - - 0.0 + - 1.8399999141693115 + - - 0.0 + - 1.8399999141693115 + - - -1.2000000476837158 + - 0.9999999403953552 + - - 0.0 + - 1.8399999141693115 + - - -1.8399999141693115 + - 0.0 + default_joint_stiffness: + - 200.0 + - 200.0 + - 200.0 + - 150.0 + - 150.0 + - 40.0 + - 40.0 + - 150.0 + - 150.0 + - 40.0 + - 40.0 + - 200.0 + - 200.0 + - 40.0 + - 40.0 + - 20.0 + - 20.0 + - 40.0 + - 40.0 + - 20.0 + - 20.0 + - 40.0 + - 40.0 + - 40.0 + - 40.0 + - 40.0 + - 40.0 + - 40.0 + - 40.0 + - 40.0 + - 40.0 + - 40.0 + - 40.0 + - 40.0 + - 40.0 + - 40.0 + - 40.0 + default_joint_vel: + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + joint_names: + - left_hip_pitch_joint + - right_hip_pitch_joint + - torso_joint + - left_hip_roll_joint + - right_hip_roll_joint + - left_shoulder_pitch_joint + - right_shoulder_pitch_joint + - left_hip_yaw_joint + - right_hip_yaw_joint + - left_shoulder_roll_joint + - right_shoulder_roll_joint + - left_knee_joint + - right_knee_joint + - left_shoulder_yaw_joint + - right_shoulder_yaw_joint + - left_ankle_pitch_joint + - right_ankle_pitch_joint + - left_elbow_pitch_joint + - right_elbow_pitch_joint + - left_ankle_roll_joint + - right_ankle_roll_joint + - left_elbow_roll_joint + - right_elbow_roll_joint + - left_five_joint + - left_three_joint + - left_zero_joint + - right_five_joint + - right_three_joint + - right_zero_joint + - left_six_joint + - left_four_joint + - left_one_joint + - right_six_joint + - right_four_joint + - right_one_joint + - left_two_joint + - right_two_joint +observations: + policy: + - dtype: torch.float32 + extras: + axes: + - X + - Y + - Z + description: Root linear velocity in the asset's root frame. + modifiers: null + units: m/s + full_path: isaaclab.envs.mdp.observations.base_lin_vel + mdp_type: Observation + name: base_lin_vel + observation_type: RootState + overloads: + clip: null + flatten_history_dim: true + history_length: 0 + scale: null + shape: + - 3 + - dtype: torch.float32 + extras: + axes: + - X + - Y + - Z + description: Root angular velocity in the asset's root frame. + modifiers: null + units: rad/s + full_path: isaaclab.envs.mdp.observations.base_ang_vel + mdp_type: Observation + name: base_ang_vel + observation_type: RootState + overloads: + clip: null + flatten_history_dim: true + history_length: 0 + scale: null + shape: + - 3 + - dtype: torch.float32 + extras: + axes: + - X + - Y + - Z + description: Gravity projection on the asset's root frame. + modifiers: null + units: m/s^2 + full_path: isaaclab.envs.mdp.observations.projected_gravity + mdp_type: Observation + name: projected_gravity + observation_type: RootState + overloads: + clip: null + flatten_history_dim: true + history_length: 0 + scale: null + shape: + - 3 + - dtype: torch.float32 + extras: + description: The generated command from command term in the command manager + with the given name. + modifiers: null + full_path: isaaclab.envs.mdp.observations.generated_commands + mdp_type: Observation + name: generated_commands + observation_type: Command + overloads: + clip: null + flatten_history_dim: true + history_length: 0 + scale: null + shape: + - 3 + - dtype: torch.float32 + extras: + description: 'The joint positions of the asset w.r.t. the default joint positions. + Note: Only the joints configured in :attr:`asset_cfg.joint_ids` will have + their positions returned.' + modifiers: null + units: rad + full_path: isaaclab.envs.mdp.observations.joint_pos_rel + joint_names: + - left_hip_pitch_joint + - right_hip_pitch_joint + - torso_joint + - left_hip_roll_joint + - right_hip_roll_joint + - left_shoulder_pitch_joint + - right_shoulder_pitch_joint + - left_hip_yaw_joint + - right_hip_yaw_joint + - left_shoulder_roll_joint + - right_shoulder_roll_joint + - left_knee_joint + - right_knee_joint + - left_shoulder_yaw_joint + - right_shoulder_yaw_joint + - left_ankle_pitch_joint + - right_ankle_pitch_joint + - left_elbow_pitch_joint + - right_elbow_pitch_joint + - left_ankle_roll_joint + - right_ankle_roll_joint + - left_elbow_roll_joint + - right_elbow_roll_joint + - left_five_joint + - left_three_joint + - left_zero_joint + - right_five_joint + - right_three_joint + - right_zero_joint + - left_six_joint + - left_four_joint + - left_one_joint + - right_six_joint + - right_four_joint + - right_one_joint + - left_two_joint + - right_two_joint + joint_pos_offsets: + - -0.20000000298023224 + - -0.20000000298023224 + - 0.0 + - 0.0 + - 0.0 + - 0.3499999940395355 + - 0.3499999940395355 + - 0.0 + - 0.0 + - 0.1599999964237213 + - -0.1599999964237213 + - 0.41999998688697815 + - 0.41999998688697815 + - 0.0 + - 0.0 + - -0.23000000417232513 + - -0.23000000417232513 + - 0.8700000047683716 + - 0.8700000047683716 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 1.0 + - 0.0 + - 0.0 + - -1.0 + - 0.5199999809265137 + - -0.5199999809265137 + mdp_type: Observation + name: joint_pos_rel + observation_type: JointState + overloads: + clip: null + flatten_history_dim: true + history_length: 0 + scale: null + shape: + - 37 + - dtype: torch.float32 + extras: + description: 'The joint velocities of the asset w.r.t. the default joint velocities. + Note: Only the joints configured in :attr:`asset_cfg.joint_ids` will have + their velocities returned.' + modifiers: null + units: rad/s + full_path: isaaclab.envs.mdp.observations.joint_vel_rel + joint_names: + - left_hip_pitch_joint + - right_hip_pitch_joint + - torso_joint + - left_hip_roll_joint + - right_hip_roll_joint + - left_shoulder_pitch_joint + - right_shoulder_pitch_joint + - left_hip_yaw_joint + - right_hip_yaw_joint + - left_shoulder_roll_joint + - right_shoulder_roll_joint + - left_knee_joint + - right_knee_joint + - left_shoulder_yaw_joint + - right_shoulder_yaw_joint + - left_ankle_pitch_joint + - right_ankle_pitch_joint + - left_elbow_pitch_joint + - right_elbow_pitch_joint + - left_ankle_roll_joint + - right_ankle_roll_joint + - left_elbow_roll_joint + - right_elbow_roll_joint + - left_five_joint + - left_three_joint + - left_zero_joint + - right_five_joint + - right_three_joint + - right_zero_joint + - left_six_joint + - left_four_joint + - left_one_joint + - right_six_joint + - right_four_joint + - right_one_joint + - left_two_joint + - right_two_joint + joint_vel_offsets: + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + - 0.0 + mdp_type: Observation + name: joint_vel_rel + observation_type: JointState + overloads: + clip: null + flatten_history_dim: true + history_length: 0 + scale: null + shape: + - 37 + - dtype: torch.float32 + extras: + description: The last input action to the environment. The name of the action + term for which the action is required. If None, the entire action tensor is + returned. + modifiers: null + full_path: isaaclab.envs.mdp.observations.last_action + mdp_type: Observation + name: last_action + observation_type: Action + overloads: + clip: null + flatten_history_dim: true + history_length: 0 + scale: null + shape: + - 37 +scene: + decimation: 4 + dt: 0.02 + physics_dt: 0.005 diff --git a/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/02_gear_assembly/gear_assembly_sim_real.webm b/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/02_gear_assembly/gear_assembly_sim_real.webm new file mode 100644 index 0000000000000000000000000000000000000000..f9ae96c07e1b3090f36969550ae34b50c5d6e845 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/02_gear_assembly/gear_assembly_sim_real.webm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc563544ad5a1fa4033b761134c0d271ad08feb5bdbd6bb90ec415821517f044 +size 252667 diff --git a/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/02_gear_assembly/sim_real_gear_assembly_train.jpg b/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/02_gear_assembly/sim_real_gear_assembly_train.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d2760d571dcb6a0a78f6f1e39da541f362ea681c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/02_gear_assembly/sim_real_gear_assembly_train.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26356af696ec0ebce8c5ff95b789e21594cd59f0afc341768f1e42504a8464b5 +size 124831 diff --git a/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/04_reach/reach_train.png b/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/04_reach/reach_train.png new file mode 100644 index 0000000000000000000000000000000000000000..0ed35ce4b60723b09ea41a56308fa1bacb302075 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/policy_deployment/04_reach/reach_train.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:840940c19ee18eb23d5a27c3d846f1aa421fe20ddc4471d858a99cec636705c8 +size 1585952 diff --git a/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/deployment-dark.svg b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/deployment-dark.svg new file mode 100644 index 0000000000000000000000000000000000000000..ba8c739724a5627df9268174906e183658134d1f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/deployment-dark.svg @@ -0,0 +1,3 @@ + + +
Robot Hardware
NVIDIA Isaac Perceptor
Custom Estimator
Isaac ROS Packages
State Estimator
Extract Observation
Actions Controller
Trained Model (.onnx, .pt)
Commanded Actions
Model Inference Runtime
Scaled Actions
1
2
3
4
5
6
7
diff --git a/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/deployment-light.svg b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/deployment-light.svg new file mode 100644 index 0000000000000000000000000000000000000000..33857dbdbefae6455736baa774ffaa2be8288dc0 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/deployment-light.svg @@ -0,0 +1,3 @@ + + +
Robot Hardware
NVIDIA Isaac Perceptor
Custom Estimator
Isaac ROS Packages
State Estimator
Extract Observation
Actions Controller
Trained Model (.onnx, .pt)
Commanded Actions
Model Inference Runtime
Scaled Actions
1
2
3
4
5
6
7
diff --git a/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/isaac-lab-ra-dark.svg b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/isaac-lab-ra-dark.svg new file mode 100644 index 0000000000000000000000000000000000000000..90ed29a93efc0ffdfed642521a50a158800c54de --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/isaac-lab-ra-dark.svg @@ -0,0 +1,3 @@ + + +
Scene Assets
Robot Assets (.usd, .urdf)
Asset Input
Design Robot Learning Task
Scene Configuration
Asset Configuration
Configuration
Register Environment with Gymnasium
Learning Framework Wrapper
Video Wrapper
Wrap Environment
Wrapper API
Test Model
Multi-Node Training
Single GPU Training
Cloud-based Training
Multi-GPU Training
Run Training
diff --git a/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/isaac-lab-ra-light.svg b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/isaac-lab-ra-light.svg new file mode 100644 index 0000000000000000000000000000000000000000..a58a6af1ec45545c99c90f13f88acfb4ab371c6f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/isaac-lab-ra-light.svg @@ -0,0 +1,3 @@ + + +
Scene Assets
Robot Assets (.usd, .urdf)
Asset Input
Design Robot Learning Task
Scene Configuration
Asset Configuration
Configuration
Register Environment with Gymnasium
Learning Framework Wrapper
Video Wrapper
Wrap Environment
Wrapper API
Test Model
Multi-Node Training
Single GPU Training
Cloud-based Training
Multi-GPU Training
Run Training
diff --git a/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/multi-gpu-training-dark.svg b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/multi-gpu-training-dark.svg new file mode 100644 index 0000000000000000000000000000000000000000..dd63d5769c87f8ba1d1647f12bda4c0ca4370ed3 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/multi-gpu-training-dark.svg @@ -0,0 +1,3 @@ + + +
Environment 0
Gradients
Global Network
Updated Model
GPU 0
Learner 0
Environment 1
GPU 1
Learner 1
Environment N
GPU N
Learner N
diff --git a/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/multi-gpu-training-light.svg b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/multi-gpu-training-light.svg new file mode 100644 index 0000000000000000000000000000000000000000..a279bff5e8c8787655e360c50c1b30110e91184c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/multi-gpu-training-light.svg @@ -0,0 +1,3 @@ + + +
Environment 0
Gradients
Global Network
Updated Model
GPU 0
Learner 0
Environment 1
GPU 1
Learner 1
Environment N
GPU N
Learner N
diff --git a/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/single-gpu-training-dark.svg b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/single-gpu-training-dark.svg new file mode 100644 index 0000000000000000000000000000000000000000..69f8e0f3c075c5565da9be1ce9ef957ea4dcc102 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/single-gpu-training-dark.svg @@ -0,0 +1,3 @@ + + +
Isaac Lab
2
States
Add Noise
Assets
Rendering
Trained Model (.pt, .onnx)
Isaac Sim
1
Physics Sim
4
5
RL Libraries
3
Policy
Actions
Observations
6
diff --git a/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/single-gpu-training-light.svg b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/single-gpu-training-light.svg new file mode 100644 index 0000000000000000000000000000000000000000..7463c470d860faea67fad31d36d02b3b9edd774f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/reference-architecture/single-gpu-training-light.svg @@ -0,0 +1,3 @@ + + +
Isaac Lab
2
States
Add Noise
Assets
Rendering
Trained Model (.pt, .onnx)
Isaac Sim
1
Physics Sim
4
5
RL Libraries
3
Policy
Actions
Observations
6
diff --git a/simulation/modules/IsaacLab/docs/source/_static/refs.bib b/simulation/modules/IsaacLab/docs/source/_static/refs.bib new file mode 100644 index 0000000000000000000000000000000000000000..8f696b6b36e15eda2d2af6ae6bafbe4307e9e4a7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/refs.bib @@ -0,0 +1,207 @@ +@inproceedings{rudin2022learning, + title={Learning to walk in minutes using massively parallel deep reinforcement learning}, + author={Rudin, Nikita and Hoeller, David and Reist, Philipp and Hutter, Marco}, + booktitle={Conference on Robot Learning}, + pages={91--100}, + year={2022}, + organization={PMLR} +} + +@article{hwangbo2019learning, + title={Learning agile and dynamic motor skills for legged robots}, + author={Hwangbo, Jemin and Lee, Joonho and Dosovitskiy, Alexey and Bellicoso, Dario and Tsounis, Vassilios and Koltun, Vladlen and Hutter, Marco}, + journal={Science Robotics}, + volume={4}, + number={26}, + pages={eaau5872}, + year={2019}, + publisher={American Association for the Advancement of Science} +} + +@article{khatib1987osc, + author={Khatib, O.}, + journal={IEEE Journal on Robotics and Automation}, + title={A unified approach for motion and force control of robot manipulators: The operational space formulation}, + year={1987}, + volume={3}, + number={1}, + pages={43-53}, + doi={10.1109/JRA.1987.1087068} +} + +@book{siciliano2009force, + title={Force control}, + author={Siciliano, Bruno and Sciavicco, Lorenzo and Villani, Luigi and Oriolo, Giuseppe}, + year={2009}, + publisher={Springer} +} + +@article{cheng2021rmpflow, + author={Cheng, Ching-An and Mukadam, Mustafa and Issac, Jan and Birchfield, Stan and Fox, Dieter and Boots, Byron and Ratliff, Nathan}, + journal={IEEE Transactions on Automation Science and Engineering}, + title={RMPflow: A Geometric Framework for Generation of Multitask Motion Policies}, + year={2021}, + volume={18}, + number={3}, + pages={968-987}, + doi={10.1109/TASE.2021.3053422} +} + +@article{buss2004ik, + author = {Buss, Samuel}, + year = {2004}, + pages = {}, + title = {Introduction to inverse kinematics with Jacobian transpose, pseudoinverse and damped least squares methods}, + volume = {17}, + journal={IEEE Transactions in Robotics and Automation}, +} + +@article{sucan2012ompl, + Author = {Ioan A. {\c{S}}ucan and Mark Moll and Lydia E. Kavraki}, + Doi = {10.1109/MRA.2012.2205651}, + Journal = {{IEEE} Robotics \& Automation Magazine}, + Month = {December}, + Number = {4}, + Pages = {72--82}, + Title = {The {O}pen {M}otion {P}lanning {L}ibrary}, + Note = {\url{https://ompl.kavrakilab.org}}, + Volume = {19}, + Year = {2012} +} + +@article{mittal2021articulated, + title={Articulated object interaction in unknown scenes with whole-body mobile manipulation}, + author={Mittal, Mayank and Hoeller, David and Farshidian, Farbod and Hutter, Marco and Garg, Animesh}, + journal={IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS)}, + year={2022} +} + +@INPROCEEDINGS{rudin2022advanced, + author={Rudin, Nikita and Hoeller, David and Bjelonic, Marko and Hutter, Marco}, + booktitle={2022 IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS)}, + title={Advanced Skills by Learning Locomotion and Local Navigation End-to-End}, + year={2022}, + volume={}, + number={}, + pages={2497-2503}, + doi={10.1109/IROS47612.2022.9981198} +} + +@ARTICLE{frankhauser2018probabilistic, + author={Fankhauser, Péter and Bloesch, Michael and Hutter, Marco}, + journal={IEEE Robotics and Automation Letters}, + title={Probabilistic Terrain Mapping for Mobile Robots With Uncertain Localization}, + year={2018}, + volume={3}, + number={4}, + pages={3019-3026}, + doi={10.1109/LRA.2018.2849506} +} + +@article{makoviychuk2021isaac, + title={Isaac gym: High performance gpu-based physics simulation for robot learning}, + author={Makoviychuk, Viktor and Wawrzyniak, Lukasz and Guo, Yunrong and Lu, Michelle and Storey, Kier and Macklin, Miles and Hoeller, David and Rudin, Nikita and Allshire, Arthur and Handa, Ankur and State, Gavriel}, + journal={arXiv preprint arXiv:2108.10470}, + year={2021} +} + + +@article{handa2022dextreme, + title={DeXtreme: Transfer of Agile In-hand Manipulation from Simulation to Reality}, + author={Handa, Ankur and Allshire, Arthur and Makoviychuk, Viktor and Petrenko, Aleksei and Singh, Ritvik and Liu, Jingzhou and Makoviichuk, Denys and Van Wyk, Karl and Zhurkevich, Alexander and Sundaralingam, Balakumar and Narang, Yashraj and Lafleche, Jean-Francois and Fox, Dieter and State, Gavriel}, + journal={arXiv preprint arXiv:2210.13702}, + year={2022} +} + +@article{narang2022factory, + title={Factory: Fast contact for robotic assembly}, + author={Narang, Yashraj and Storey, Kier and Akinola, Iretiayo and Macklin, Miles and Reist, Philipp and Wawrzyniak, Lukasz and Guo, Yunrong and Moravanszky, Adam and State, Gavriel and Lu, Michelle and Handa, Ankur and Fox, Dieter}, + journal={arXiv preprint arXiv:2205.03532}, + year={2022} +} + +@inproceedings{allshire2022transferring, + title={Transferring dexterous manipulation from gpu simulation to a remote real-world trifinger}, + author={Allshire, Arthur and Mittal, Mayank and Lodaya, Varun and Makoviychuk, Viktor and Makoviichuk, Denys and Widmaier, Felix and W{\"u}thrich, Manuel and Bauer, Stefan and Handa, Ankur and Garg, Animesh}, + booktitle={2022 IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS)}, + pages={11802--11809}, + year={2022}, + organization={IEEE} +} + +@article{mittal2025isaaclab, + title={Isaac Lab: A GPU-Accelerated Simulation Framework for Multi-Modal Robot Learning}, + author={Mayank Mittal and Pascal Roth and James Tigue and Antoine Richard and Octi Zhang and Peter Du and Antonio Serrano-Muñoz and Xinjie Yao and René Zurbrügg and Nikita Rudin and Lukasz Wawrzyniak and Milad Rakhsha and Alain Denzler and Eric Heiden and Ales Borovicka and Ossama Ahmed and Iretiayo Akinola and Abrar Anwar and Mark T. Carlson and Ji Yuan Feng and Animesh Garg and Renato Gasoto and Lionel Gulich and Yijie Guo and M. Gussert and Alex Hansen and Mihir Kulkarni and Chenran Li and Wei Liu and Viktor Makoviychuk and Grzegorz Malczyk and Hammad Mazhar and Masoud Moghani and Adithyavairavan Murali and Michael Noseworthy and Alexander Poddubny and Nathan Ratliff and Welf Rehberg and Clemens Schwarke and Ritvik Singh and James Latham Smith and Bingjie Tang and Ruchik Thaker and Matthew Trepte and Karl Van Wyk and Fangzhou Yu and Alex Millane and Vikram Ramasamy and Remo Steiner and Sangeeta Subramanian and Clemens Volk and CY Chen and Neel Jawale and Ashwin Varghese Kuruttukulam and Michael A. Lin and Ajay Mandlekar and Karsten Patzwaldt and John Welsh and Huihua Zhao and Fatima Anes and Jean-Francois Lafleche and Nicolas Moënne-Loccoz and Soowan Park and Rob Stepinski and Dirk Van Gelder and Chris Amevor and Jan Carius and Jumyung Chang and Anka He Chen and Pablo de Heras Ciechomski and Gilles Daviet and Mohammad Mohajerani and Julia von Muralt and Viktor Reutskyy and Michael Sauter and Simon Schirm and Eric L. Shi and Pierre Terdiman and Kenny Vilella and Tobias Widmer and Gordon Yeoman and Tiffany Chen and Sergey Grizan and Cathy Li and Lotus Li and Connor Smith and Rafael Wiltz and Kostas Alexis and Yan Chang and David Chu and Linxi "Jim" Fan and Farbod Farshidian and Ankur Handa and Spencer Huang and Marco Hutter and Yashraj Narang and Soha Pouya and Shiwei Sheng and Yuke Zhu and Miles Macklin and Adam Moravanszky and Philipp Reist and Yunrong Guo and David Hoeller and Gavriel State}, + journal={arXiv preprint arXiv:2511.04831}, + year={2025}, + url={https://arxiv.org/abs/2511.04831} +} + +@article{mittal2023orbit, + author={Mittal, Mayank and Yu, Calvin and Yu, Qinxi and Liu, Jingzhou and Rudin, Nikita and Hoeller, David and Yuan, Jia Lin and Singh, Ritvik and Guo, Yunrong and Mazhar, Hammad and Mandlekar, Ajay and Babich, Buck and State, Gavriel and Hutter, Marco and Garg, Animesh}, + journal={IEEE Robotics and Automation Letters}, + title={Orbit: A Unified Simulation Framework for Interactive Robot Learning Environments}, + year={2023}, + volume={8}, + number={6}, + pages={3740-3747}, + doi={10.1109/LRA.2023.3270034} +} + +@article{shang2024theia, + title={Theia: Distilling diverse vision foundation models for robot learning}, + author={Shang, Jinghuan and Schmeckpeper, Karl and May, Brandon B and Minniti, Maria Vittoria and Kelestemur, Tarik and Watkins, David and Herlant, Laura}, + journal={arXiv preprint arXiv:2407.20179}, + year={2024} +} + +@inproceedings{he2016deep, + title={Deep residual learning for image recognition}, + author={He, Kaiming and Zhang, Xiangyu and Ren, Shaoqing and Sun, Jian}, + booktitle={Proceedings of the IEEE conference on computer vision and pattern recognition}, + pages={770--778}, + year={2016} +} + +@InProceedings{schwarke2023curiosity, + title = {Curiosity-Driven Learning of Joint Locomotion and Manipulation Tasks}, + author = {Schwarke, Clemens and Klemm, Victor and Boon, Matthijs van der and Bjelonic, Marko and Hutter, Marco}, + booktitle = {Proceedings of The 7th Conference on Robot Learning}, + pages = {2594--2610}, + year = {2023}, + volume = {229}, + series = {Proceedings of Machine Learning Research}, + publisher = {PMLR}, + url = {https://proceedings.mlr.press/v229/schwarke23a.html}, +} + +@InProceedings{mittal2024symmetry, + author={Mittal, Mayank and Rudin, Nikita and Klemm, Victor and Allshire, Arthur and Hutter, Marco}, + booktitle={2024 IEEE International Conference on Robotics and Automation (ICRA)}, + title={Symmetry Considerations for Learning Task Symmetric Robot Policies}, + year={2024}, + pages={7433-7439}, + doi={10.1109/ICRA57147.2024.10611493} +} + +@article{kulkarni2025aerialgym, + author={Kulkarni, Mihir and Rehberg, Welf and Alexis, Kostas}, + journal={IEEE Robotics and Automation Letters}, + title={Aerial Gym Simulator: A Framework for Highly Parallelized Simulation of Aerial Robots}, + year={2025}, + volume={10}, + number={4}, + pages={4093-4100}, + doi={10.1109/LRA.2025.3548507} +} + +@article{si2022taxim, + title={Taxim: An example-based simulation model for gelsight tactile sensors}, + author={Si, Zilin and Yuan, Wenzhen}, + journal={IEEE Robotics and Automation Letters}, + volume={7}, + number={2}, + pages={2361--2368}, + year={2022}, + publisher={IEEE} +} diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/asset_caching.jpg b/simulation/modules/IsaacLab/docs/source/_static/setup/asset_caching.jpg new file mode 100644 index 0000000000000000000000000000000000000000..55992e7ea27e2180eb4eb4d43303e1fd6bcd577c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/asset_caching.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:74276034a20a5f980339cc018ffdb3773bf88f50ada5fee22dcdf312c1cfb411 +size 374471 diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_accept_cert.jpg b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_accept_cert.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fa1dc8da33c5e6ea6342392277c2cb99d77473d9 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_accept_cert.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3b1c083eaa52641d7020e771c8e31d272d66068ca2d288253993799bb359b07 +size 10417 diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_accept_cert_accepted.jpg b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_accept_cert_accepted.jpg new file mode 100644 index 0000000000000000000000000000000000000000..870ad915fad3951ac2d90ae1bd0f8f937b618681 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_accept_cert_accepted.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fafc8f87c7bdc0ff31f91f274319fb23dfc130d59ed860a74f9fcb41fdf9655d +size 33321 diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_accept_cert_not_private.jpg b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_accept_cert_not_private.jpg new file mode 100644 index 0000000000000000000000000000000000000000..302dd0968effdc5f365830b9f8d4fa7de047f568 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_accept_cert_not_private.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50a2983be8e80e6767e39fa9feb69cddb08e84b9ff235df40c5d8422678a3d72 +size 47759 diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_ar_panel.jpg b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_ar_panel.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e13315d1ac0aeb698ab3721942cceea06b56fbe8 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_ar_panel.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a699214361b68613dd209cec9d0d33e154fdacb2cf2f3e5a326c9ab45ffbcd2f +size 44385 diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_avp_connect_ui.jpg b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_avp_connect_ui.jpg new file mode 100644 index 0000000000000000000000000000000000000000..680ee122de0cf21d5b78a6b7a8de1b6c12335e18 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_avp_connect_ui.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c6e73f0fa71f09fcfcc5bd5b72680397489bff8cad230dc0e82e0529001ab9f +size 14499 diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_avp_ik_error.jpg b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_avp_ik_error.jpg new file mode 100644 index 0000000000000000000000000000000000000000..16d362fb07006bf8a47d086bb6afa3b691c020cb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_avp_ik_error.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1acffc811ba677cdfbde5fd4967be49355b03a12312f16bd36b7ebd2b2a9a891 +size 301133 diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_avp_teleop_ui.jpg b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_avp_teleop_ui.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6f2bf5d30e17e06e05cb797cba31f88d473104f3 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_avp_teleop_ui.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:027a001293314bde687896211139fb0fa32b95821adc0982b78398f3b00b6017 +size 16493 diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_viewport.jpg b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_viewport.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b448261374a988f43831977934dfe2dee0674836 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/cloudxr_viewport.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ff2f694328fce4aaf7ebf6e9cef4feb36cb358229e44d3c2c58c026fb3e450ae +size 299580 diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/ecosystem-dark.svg b/simulation/modules/IsaacLab/docs/source/_static/setup/ecosystem-dark.svg new file mode 100644 index 0000000000000000000000000000000000000000..a09f1d0c5036de84064ca013a2bfa364d13dea33 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/ecosystem-dark.svg @@ -0,0 +1,93 @@ + + + + + + + + + + + + Learning Libraries + RSL-RL · skrl · Stable Baselines 3 · RL Games + + + + Isaac Lab Extensions + + isaaclab_tasks + pre-built environments + + isaaclab_assets + robot & sensor configs + + isaaclab_rl + RL library wrappers + + isaaclab_mimic + imitation learning + + isaaclab_teleop + teleoperation & XR + + + + Isaac Lab Core (isaaclab) + sim · scene · assets · sensors · envs · managers · actuators + controllers · terrains · devices · mdp · utils · markers · renderers + ManagerBasedRLEnv · DirectRLEnv · DirectMARLEnv · InteractiveScene + factory pattern: uniform API dispatches to the active physics backend at runtime + + + + + + isaaclab_physx · isaaclab_ovphysx · isaaclab_ov + Articulation · Rigid Body · Rigid Object Collection · Deformable + Fabric Views · Camera · USD spawners + Isaac RTX Renderer · OvRTX Renderer + + + + isaaclab_newton + Articulation · Rigid Body · Rigid Object Collection + Camera · USD spawners · Warp Renderer + MJWarp Solver · VBD Solver + + + + + + Isaac Sim (optional) + PhysX · RTX Rendering · USD / Omniverse + ROS / ROS 2 · URDF & MJCF importers + required for Isaac Sim features + + + + Newton Physics + Warp + GPU-parallel simulation · Warp kernels + MJWarp (MuJoCo-Warp) solver + kit-less · no Isaac Sim required + + + + NVIDIA GPU Platform + CUDA · Warp (required by all backends) + diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/ecosystem-light.svg b/simulation/modules/IsaacLab/docs/source/_static/setup/ecosystem-light.svg new file mode 100644 index 0000000000000000000000000000000000000000..cd9b1b98fb37d2b00650195eb8caf2fd810ebf48 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/ecosystem-light.svg @@ -0,0 +1,94 @@ + + + + + + + + + + + + Learning Libraries + RSL-RL · skrl · Stable Baselines 3 · RL Games + + + + Isaac Lab Extensions + + isaaclab_tasks + pre-built environments + + isaaclab_assets + robot & sensor configs + + isaaclab_rl + RL library wrappers + + isaaclab_mimic + imitation learning + + isaaclab_teleop + teleoperation & XR + + + + Isaac Lab Core (isaaclab) + sim · scene · assets · sensors · envs · managers · actuators + controllers · terrains · devices · mdp · utils · markers · renderers + ManagerBasedRLEnv · DirectRLEnv · DirectMARLEnv · InteractiveScene + factory pattern: uniform API dispatches to the active physics backend at runtime + + + + + + isaaclab_physx · isaaclab_ovphysx · isaaclab_ov + Articulation · Rigid Body · Rigid Object Collection · Deformable + Fabric Views · Camera · USD spawners + Isaac RTX Renderer · OvRTX Renderer + + + + isaaclab_newton + Articulation · Rigid Body · Rigid Object Collection + Camera · USD spawners · Warp Renderer + MJWarp Solver · VBD Solver + + + + + + Isaac Sim (optional) + PhysX · RTX Rendering · USD / Omniverse + ROS / ROS 2 · URDF & MJCF importers + required for Isaac Sim features + + + + Newton Physics + Warp + GPU-parallel simulation · Warp kernels + MJWarp (MuJoCo-Warp) solver + kit-less · no Isaac Sim required + + + + NVIDIA GPU Platform + CUDA · Warp (required by all backends) + diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/isaac_ants_example.jpg b/simulation/modules/IsaacLab/docs/source/_static/setup/isaac_ants_example.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a9b789730fcc82a0d09013e499a15c1bf8686aae --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/isaac_ants_example.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b7afecb338be7cbc4dcc6d60ba59211b69334f7890207ebadb815fd97a547cd1 +size 170019 diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/shadow_hands_example.jpg b/simulation/modules/IsaacLab/docs/source/_static/setup/shadow_hands_example.jpg new file mode 100644 index 0000000000000000000000000000000000000000..35f0fbb4761a91f18716cbb83a1ac85302615c18 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/shadow_hands_example.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6117b457afd8aee7e2168ef9b7c3bde67bbb8b47f46c6b638a7e676ed33df10b +size 29378 diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/verify_install.jpg b/simulation/modules/IsaacLab/docs/source/_static/setup/verify_install.jpg new file mode 100644 index 0000000000000000000000000000000000000000..84ddc2fe433f5b6c0b7324b15ef30aba076cd635 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/verify_install.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e12a8a1ea3e35bc0687b3f73a80a0960b7366b89dfd908cbbfc648c571fe262 +size 199658 diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_1_1_result.jpg b/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_1_1_result.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fb21ba017fa89dab522cf53e0df5e7129aab9db7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_1_1_result.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1bc6088ba29fafb604437b5f9a534c12d5fa5c3941ac2e745f70492016f19b6e +size 185443 diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_1_2_arrows.jpg b/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_1_2_arrows.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0a955f4e5904d0eab7024eade1f1700cb615318d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_1_2_arrows.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ec001d436fd20c008b9f46ea2341b6a923891d65768193bd79049fbe10c4017 +size 108267 diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_project_setup.svg b/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_project_setup.svg new file mode 100644 index 0000000000000000000000000000000000000000..f5accffbc6802b937be8781a5214c55354da6415 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_project_setup.svg @@ -0,0 +1 @@ +isaac_lab_tutorialscriptssourceLICENSEREADME.mdisaac_lab_tutorialconfigpyproject.tomlsetup.pydocsisaac_lab_tutorialextension.tomltasksdirectisaac_lab_tutorialagents__init__.pyisaac_lab_tutorial_env_cfg.pyisaac_lab_tutorial_env.pyProjectExtensionModulesTask diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_sim_stage_scene.svg b/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_sim_stage_scene.svg new file mode 100644 index 0000000000000000000000000000000000000000..17cd53aaf3716c46d408fa477dc0ac1b2b5258f7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_sim_stage_scene.svg @@ -0,0 +1 @@ +WorldStageSceneSimApp diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_stage_context.svg b/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_stage_context.svg new file mode 100644 index 0000000000000000000000000000000000000000..b98ccb2cedef9ee55ffaca275c2dd500e4dde1bc --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_stage_context.svg @@ -0,0 +1 @@ +OO’/World/Table/Sphere/World/Table/PyramidWorldTablePyramidSphereVisualsVisualsVisuals diff --git a/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_training_vectors.svg b/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_training_vectors.svg new file mode 100644 index 0000000000000000000000000000000000000000..a285d2cb90f8321d9bee7110389ba9508c7dab84 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/setup/walkthrough_training_vectors.svg @@ -0,0 +1 @@ +W𝑥ො𝑦ො𝑦ො′𝑥ො′Bcommandforwardsrobot.data.root_pos_wrobot.data.root_com_vel_w[:,:3]𝑥ොyawforwardscommand(forwardscommand)𝑧Ƹ diff --git a/simulation/modules/IsaacLab/docs/source/_static/task-workflows/direct-based-dark.svg b/simulation/modules/IsaacLab/docs/source/_static/task-workflows/direct-based-dark.svg new file mode 100644 index 0000000000000000000000000000000000000000..2709dae140cab8201b384e892b8fe3c947250297 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/task-workflows/direct-based-dark.svg @@ -0,0 +1,3 @@ + + +
Sensors
Observations
Apply Actions
Define Task
Define Step
Environment Scripting
NVIDIA
Isaac Sim
Perform Resets
Rewards
Commands
Learning Agent
Scene Creation
Articulation
Objects
Compute Signals
Actions
Perform
Randomization
diff --git a/simulation/modules/IsaacLab/docs/source/_static/task-workflows/direct-based-light.svg b/simulation/modules/IsaacLab/docs/source/_static/task-workflows/direct-based-light.svg new file mode 100644 index 0000000000000000000000000000000000000000..b39bffa3534e4fd2b5d4e0868bd35b2c6845a6b6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/task-workflows/direct-based-light.svg @@ -0,0 +1,3 @@ + + +
Sensors
Observations
Apply Actions
Define Task
Define Step
Environment Scripting
NVIDIA
Isaac Sim
Perform Resets
Rewards
Commands
Learning Agent
Scene Creation
Articulation
Objects
Compute Signals
Actions
Perform
Randomization
diff --git a/simulation/modules/IsaacLab/docs/source/_static/task-workflows/manager-based-dark.svg b/simulation/modules/IsaacLab/docs/source/_static/task-workflows/manager-based-dark.svg new file mode 100644 index 0000000000000000000000000000000000000000..b66ba1bfee2c4219f9e235b4bc2cd750f2df6a55 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/task-workflows/manager-based-dark.svg @@ -0,0 +1,3 @@ + + +
Action Manager
Task-space
Joint-space
Termination Manager
Reward Manager
Curriculum Manager
Learning
Agent
Custom
Command Manager
Custom
Velocity
Pose
Observation Manager
Proprioception
Custom
Exteroception
NVIDIA
Isaac Sim
Articulation
Objects
Sensors
Interactive Scene
Event Manager
External Disturbances
Domain Randomization
diff --git a/simulation/modules/IsaacLab/docs/source/_static/task-workflows/manager-based-light.svg b/simulation/modules/IsaacLab/docs/source/_static/task-workflows/manager-based-light.svg new file mode 100644 index 0000000000000000000000000000000000000000..60fe6119d41f8e867e448f59e02de1c70cc09353 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/task-workflows/manager-based-light.svg @@ -0,0 +1,3 @@ + + +
Action Manager
Task-space
Joint-space
Termination Manager
Reward Manager
Curriculum Manager
Learning
Agent
Custom
Command Manager
Custom
Velocity
Pose
Observation Manager
Proprioception
Custom
Exteroception
NVIDIA
Isaac Sim
Articulation
Objects
Sensors
Interactive Scene
Event Manager
External Disturbances
Domain Randomization
diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks.jpg new file mode 100644 index 0000000000000000000000000000000000000000..780bc7c39655ce9d08697419fe92026c969c0cba --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5e3c8a8881c532722d69951760fd471b70e69cc1c972793ee565f18133b00ab +size 464725 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/automate/00004.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/automate/00004.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1ebf5ba4c5085c2cd5653bc67e4b0c5cae26370d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/automate/00004.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5d75ebd8ec998c3fa58679edeb9edd8c915134a2b971f62801ff8e5899f6256 +size 49111 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/automate/01053_disassembly.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/automate/01053_disassembly.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ccd5a2a0d224cb67c6fcaffb0401318a26d34520 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/automate/01053_disassembly.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96fd7676a4ad542a14793db69de2edba81c0102fb9a7c9a6bccb20588b27c5de +size 28155 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/classic/ant.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/classic/ant.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3497047b47ab8c9c195036c048ca8bba89870328 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/classic/ant.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43ac3daa07efc112314c9544063897b6c9bfcd7643dba7eb40dfd2b47dbd0f55 +size 234491 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/classic/cart_double_pendulum.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/classic/cart_double_pendulum.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5ebc25ecdc564e65eb987a4ea15b973ada05ca48 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/classic/cart_double_pendulum.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4dea89acbef59318dfa099ba48c7408282e18251e88935c023884f635cf915ea +size 219224 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/classic/cartpole.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/classic/cartpole.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7ed42994b2fbccc85a4df362148996f4c5bd50fd --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/classic/cartpole.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ae2cfc71b0c18c41388f5437750daa64c0722c4be869dcf2144c7b747b28eac +size 278750 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/classic/humanoid.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/classic/humanoid.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6c74125f97652748f50e6ec087dff93f031e8411 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/classic/humanoid.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1cad36b1be44f6daab6de8fa8d7155ea758b5c5d6f28430c771e49027b9732ce +size 220946 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/drone_arl/arl_robot_1_navigation.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/drone_arl/arl_robot_1_navigation.jpg new file mode 100644 index 0000000000000000000000000000000000000000..dcaa414bef7839f08d4d05abc18a9bca280bac5b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/drone_arl/arl_robot_1_navigation.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb505c18b2bdef6413b1dacd353b98448c885b62884e7ddf0f350c53d58fe84e +size 97329 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/drone_arl/arl_robot_1_track_position_state_based.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/drone_arl/arl_robot_1_track_position_state_based.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2065893c24060190c70873a12a6f64bcdfdb3139 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/drone_arl/arl_robot_1_track_position_state_based.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:405e18c7964a7e1f2085807d29fca30b1368876f4e25af5f9dbc414cbd8b3f29 +size 25142 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/factory/gear_mesh.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/factory/gear_mesh.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ff15d7453951379df4101729c8a59b7c035a4a03 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/factory/gear_mesh.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5fec8395a26bfab8db6e6d3d2996b868ecc9774433f354fbd02b12aa73b5d4c3 +size 47279 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/factory/nut_thread.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/factory/nut_thread.jpg new file mode 100644 index 0000000000000000000000000000000000000000..45811da4b524e1d966a37e1e6d850aa39c20fdcf --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/factory/nut_thread.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:236d040dd57e82be7db94b719ed593b51bf8f7443a677881d72d21fa7fde5b7a +size 44543 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/factory/peg_insert.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/factory/peg_insert.jpg new file mode 100644 index 0000000000000000000000000000000000000000..86ee1ba981e8599f7cd2e8edbfcf93426ec6d829 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/factory/peg_insert.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9376e7c43b9417063380d4252fa4de5cb492e22f70c6d99aea50aa081dc1f228 +size 43938 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/drop.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/drop.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a2c67876c7a7f30960c99bda6bbed47235843479 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/drop.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49dbbdfe1ab8aa707924010042e5e054717f9912dfaa8fa9fe6c533058ac0180 +size 25903 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/flag.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/flag.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1848fadc36075ecff226060e378cb887fd214d03 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/flag.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:179ee3a947c8dfc57c3e66270525a8d822833d71b4162efa87b8d5042b3e6e7d +size 17833 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/fluid_pour.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/fluid_pour.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a27f3e430d5e13a1ea7dc506573e7781f8dac642 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/fluid_pour.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c26fd00b3bf13d51f7b77c84b4eb6c3094b489c652f122c8bc0cad0e274bc851 +size 61788 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/fluid_transport.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/fluid_transport.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d19a74994e632c405d3b95ad1e1a45bdf28507f6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/fluid_transport.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a846a7293c531f12cc750b8afc50b93b7a6e2141afb841e805812dbc51a0b54 +size 89228 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/pick.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/pick.jpg new file mode 100644 index 0000000000000000000000000000000000000000..30ce39e24f123fce318fc72b4bb6520529033f8b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/pick.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b23eb958bff30418969c14ee9be231d358cf62e29bc94394778225d765c9864d +size 37247 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/place.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/place.jpg new file mode 100644 index 0000000000000000000000000000000000000000..11e387825839fb7daea48545abca67b5396c1646 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/place.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2efc4970b668c97da4dde611f902499131f9a1614cd29fa98f7ef6885ecffd5e +size 31492 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/rope.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/rope.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6047cf71229ac91e6cdae7572d0016ebbecf3b11 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/rope.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:219d7084f1ad6b92265a251eb037cdbc5b8363dbfe7fbe62bb053cdf2f97b084 +size 34371 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/shirt-basket.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/shirt-basket.jpg new file mode 100644 index 0000000000000000000000000000000000000000..535b02cbd710c7583c82bf93934619721cbfb47b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/shirt-basket.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:772b1347bd8bafe74237c2f4197b905d208c6f81b6afbce83753670ecd2071df +size 27122 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/shirt.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/shirt.jpg new file mode 100644 index 0000000000000000000000000000000000000000..28f4dd71f9591e7caffa42925adaab5516ddbef0 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/shirt.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b1c6526fa6695afce262bd87a31a5443dcf7554b255fb5d3db8e392bdfde4dc3 +size 40687 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/stacking.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/stacking.jpg new file mode 100644 index 0000000000000000000000000000000000000000..45f3464b29e55dd1696ea2303bb1517562c1f263 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/stacking.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f6ea4825c0eb146caf27d13221f987e2914bbfd07eb9d6847cfc619f8307eeeb +size 24790 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/sweater.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/sweater.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a7bf2c475409fcd8b4728fa29fc84274662e7f8c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/sweater.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d6d4fc136077e2a3ae05347c72e6a26523993c9236424a3cc7d1542b624d24bf +size 36202 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/tower_of_hanoi.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/tower_of_hanoi.jpg new file mode 100644 index 0000000000000000000000000000000000000000..68bae27cd00d2271757b3bee088ef1b1906ba7d7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/tower_of_hanoi.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f264a0dc761103ae922c525a8e5014ce594825e9d54ab726a49c17f689dd7794 +size 28248 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/vest.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/vest.jpg new file mode 100644 index 0000000000000000000000000000000000000000..93e91e0aa2f276345647ddf811e42a36bd426c42 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/deformable/vest.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d04ea51607d6ebb63b9b1f7dea1955bca2d036629b8978b2fd596207e253a21 +size 44279 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/beat-the-buzz.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/beat-the-buzz.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1cb8259a53e297e9beb79145f1aab19ffbf11d70 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/beat-the-buzz.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e1d05a79a20853a74dbad460846905cf2f1d254935583b5d7800bd4916d4921 +size 24401 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/cabinet.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/cabinet.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d903bf0ef1e103a95d911e3e7380aa7da8730109 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/cabinet.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ff357f2b5dc1471cb4343d320f90abe1b40b2d8c00c8080c60a5c2365932410b +size 21502 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/hockey.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/hockey.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ec5f22793f73a2b1504aac5d29ed94de6b9831b2 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/hockey.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a55efa4340be1b3f4657300e5650fbb3b8c14160dc9b7c7d273b96d6318cf17 +size 32399 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/jenga.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/jenga.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fb408e2a1147684de693b8c720d90f4c0340508c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/jenga.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:667f1c02b099193f2c41eda41501d71e1f12513999b0cb1beee0885bfae3f461 +size 38419 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/lift.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/lift.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0c29dd2ba0ab663f9aa3013178634bade63ca623 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/lift.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:106603401f1c9c413fc07d001063081c4f649693a03721fc340e0f30c7d07e90 +size 59761 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/locomotion.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/locomotion.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fb3ef199578d7127b3da129efe7ef438f8e580e5 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/locomotion.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1f17ef11bb0a83f1065c3446d941a7bc3c5a9940c55ce0709d9553762197354 +size 90707 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/mobile_cabinet.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/mobile_cabinet.jpg new file mode 100644 index 0000000000000000000000000000000000000000..27dd6486fd1eb089e2e043fd0f0da9357026e782 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/mobile_cabinet.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95279089168f2c6368654cd4437092e91ed0900c6d56de804dabbbcdde7662ee +size 61198 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/mobile_reach.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/mobile_reach.jpg new file mode 100644 index 0000000000000000000000000000000000000000..40ad56a5de12e9208321037203da054c8cc7997d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/mobile_reach.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:58fc672d64064f3ff8315aa3f8a977f581f1072637dd6e414faa62674db0c1b2 +size 27568 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/nut-bolt.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/nut-bolt.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5f1b1000ba26939e309b8925ebff8dbfcc9b1a60 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/nut-bolt.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dea7f255657161fe3598661d14be7311050fdfa7b552688a46531021114222fa +size 29808 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/peg-in-hole.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/peg-in-hole.jpg new file mode 100644 index 0000000000000000000000000000000000000000..90ac266d3a59d6f3fb2091f300441863644f1532 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/peg-in-hole.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:962ab4439aff83fd846ba081297f525ab58064428ae1ccdf8796207a7c23b59a +size 23574 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/pyramid.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/pyramid.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6ea4c4fabb3b10c5486d3b18c3e4132de46d7180 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/pyramid.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e840225634627d1c1934b80f82958ad07c566e546582b9c2d6a28b796a1028fd +size 36821 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/reach.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/reach.jpg new file mode 100644 index 0000000000000000000000000000000000000000..599a7da4cbb692936da536b5d5e4f780b712710b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/reach.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd6d05f3fd5f728a7672309c9624e80894442c1fb1f55d6288f7f4dbbf21de5c +size 38995 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/shadow.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/shadow.jpg new file mode 100644 index 0000000000000000000000000000000000000000..49eaeabd8068a2958b366f66764f3e1baeff5acf --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/future_plans/rigid/shadow.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:173cb408d269c023dc9cc42b4b51b5bdbfb351f690cfe4f002411c266ea70f78 +size 73939 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/a1_flat.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/a1_flat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5c6bb0b485441e2d70fef949dd4d38a1383eeeb5 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/a1_flat.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:368bd1dc3699093ed6478a9e98e86cdd64cf87d7e543bf4cf5f625c04e2a3bc8 +size 155080 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/a1_rough.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/a1_rough.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4e1641e59e3452c2a88a32ad3c15b1ac3de1e3d5 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/a1_rough.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:40f088b5c00042302934a9a6cb4f68f1eecb77e4397fd084b32934e5bbf9b371 +size 244321 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/agility_digit_flat.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/agility_digit_flat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1beb95eef8f7f81a284105b7828a71d17270266a --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/agility_digit_flat.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db47aa6f988e1ad82ecb7148b5c4f3962595c8f8969fe41c17f8ac9c06c7a9f3 +size 244944 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/agility_digit_loco_manip.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/agility_digit_loco_manip.jpg new file mode 100644 index 0000000000000000000000000000000000000000..842ea41976e49dc3372f4aeee42c927802bc2e49 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/agility_digit_loco_manip.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3dea5c807417e616fdc518bfcc2ceb4799f3a6cd1c0567c1f90d0a6480f61771 +size 250841 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/agility_digit_rough.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/agility_digit_rough.jpg new file mode 100644 index 0000000000000000000000000000000000000000..43775f1d55bbee5e0d7918a44af8022d59a3b148 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/agility_digit_rough.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1d00bf29f17852583d5cac025dda3fca357bb56adb4dd94dffe03fa51e9d1a2 +size 240474 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_b_flat.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_b_flat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..730a673022c0b68e5de362bc9e4a3e465b1f718b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_b_flat.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04d0da1516731d518ea77c92a4f8effdb904fc97afa2f770cde15cd20d3b34ca +size 169317 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_b_rough.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_b_rough.jpg new file mode 100644 index 0000000000000000000000000000000000000000..555b1af7f30632059cd3ed0199e3ae2734481332 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_b_rough.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3af47c26bd252b49969a58f250c780fd9a010abaa8d30d6ee4cae7bfe2e443d2 +size 254756 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_c_flat.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_c_flat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0d480f79ee7fd011938a492edeffa0a4f0adef80 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_c_flat.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ff12b5c7a75975e5475a7a42451487b45d7894d98946aa603ecb96bfc316097 +size 220053 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_c_rough.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_c_rough.jpg new file mode 100644 index 0000000000000000000000000000000000000000..32bacdb6e09088ece80019005050277ad20a9cea --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_c_rough.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:894e19a454ef6f0718de4abb5289b46c2267a9c26c3c652cb4a502da9b2bc387 +size 310484 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_d_flat.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_d_flat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1d6f595debbb9c7fa194fe770bb09c59fc4809f7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_d_flat.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9df159248847a1230f6694acaf9ca09021b060d65bb3780f6532aaeacedd72e6 +size 245789 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_d_rough.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_d_rough.jpg new file mode 100644 index 0000000000000000000000000000000000000000..50bb8686b3ee663cb9922613d8edc11ef37c4a16 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/anymal_d_rough.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d113feb51428cfdc86583ed85adb7d60507be30ad25c27f73c2a87d5d534a611 +size 312429 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/g1_flat.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/g1_flat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..624391a0ed0a03e3fd49396ba2fd34b3a6f4c64a --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/g1_flat.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b934872a68d4d0b7a548d7056e4185751dffa13e8e7dd1d3c14fd2089c09df0 +size 1163142 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/g1_rough.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/g1_rough.jpg new file mode 100644 index 0000000000000000000000000000000000000000..71c716a3886ec649a0bdbf601bb443e973ab4839 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/g1_rough.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69ee9c49e1d84b41cb78527e0a538517bbc9240f692bb5a286b6f078e5728283 +size 1169796 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/go1_flat.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/go1_flat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3ab9caf56f19bbf4ff9d7f3ad0d0d6b9323cd385 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/go1_flat.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:621b878e694ec444b01acdd61ba0d150b6f6fa5b86cc502e8ad45d784a1c83b1 +size 144390 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/go1_rough.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/go1_rough.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b5ed7ac5f9ee6dc0911d549fcb2b93296d35bc43 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/go1_rough.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:15fee781b73a76e01cdb74d837d843e22f26207dac906183553cf11723659de1 +size 216384 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/go2_flat.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/go2_flat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..256bd30380a8360119be6240dceb14d6653c4875 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/go2_flat.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab93bf91249bbd900d0fbda5a1f4221f01177e64e4ede79fee075c52e5729395 +size 177792 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/go2_rough.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/go2_rough.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7e242aff9d0f497471ab0ca16b36f36582ee67c3 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/go2_rough.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a167898a57bfc1cfcbefe5ba40b75a6d20cf2d82402ba49439d2c6dac666f793 +size 233147 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/h1_flat.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/h1_flat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2578a9a9f24b907ee98fd791d1a3a04a8cbc3cde --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/h1_flat.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fef313f7c89e39fc41b02d3d07773b568194b31eb2f012928bc251b3ab889f1c +size 106872 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/h1_rough.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/h1_rough.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f52e964923e2d189ad642a51c65f62c8f8829301 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/h1_rough.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7930c748ebea16f91aa61cd17fdff36bda134bb7ec5d4aab6feb737ac4fb209c +size 169799 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/spot_flat.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/spot_flat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..97ff55ddf39e10b92e249afe08c870d8b83753ca --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/locomotion/spot_flat.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc249939c5ccae8dd7475e065ee5b6e2751f3ff5739fcaf40face94c96a7c7d7 +size 87832 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/agibot_place_mug.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/agibot_place_mug.jpg new file mode 100644 index 0000000000000000000000000000000000000000..20467f842971a32c865a50ec9046fa7bee4d54e6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/agibot_place_mug.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f32030e2191f41572366f492b933c6f87640136985d067869c7dbb2dbca7dfa +size 77293 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/agibot_place_toy.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/agibot_place_toy.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1b8bfc35cdd4a6c9cef22d570c4f77b19cc97e4a --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/agibot_place_toy.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e54c3352ea721cc1acbab57c843d7cd48b644c7f42148517bc8ec4076e56a9df +size 81016 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/allegro_cube.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/allegro_cube.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b75b6ae9143744c77fa7ac7df9e5be00e86e3e7d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/allegro_cube.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9aa6fbb937a4732ac06baf77c0610cad4bd5a7ba1ef91f3639651560636979ae +size 103465 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/franka_lift.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/franka_lift.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7fa4e618623db86e10d95bb26943168da1a845f8 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/franka_lift.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d0d93ba33e8e851a6139ad82cb6970b39236f75d1bf1c471aad16323e4a2909 +size 193446 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/franka_open_drawer.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/franka_open_drawer.jpg new file mode 100644 index 0000000000000000000000000000000000000000..94ce61afb0d680cc4f4dab6df3a77e01c61744cb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/franka_open_drawer.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:23e49861bd120df01f2b3496e522850c1456697e9ba678b4cc6b373ef5c25a56 +size 124090 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/franka_reach.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/franka_reach.jpg new file mode 100644 index 0000000000000000000000000000000000000000..27216fa714f6c554812e9a7242961badc748ff93 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/franka_reach.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2dc7ce3445fc8e1a6f8fd462c5f7b61acd55131fe3907585f7c6d7eea8a6745 +size 198124 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/franka_stack.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/franka_stack.jpg new file mode 100644 index 0000000000000000000000000000000000000000..845051d0abad75e27a5d48ae959467b5e6e6ae51 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/franka_stack.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a22a0cf57db9af77cffe320e545263818899dcbec35f6563ca36c25556fff23a +size 131565 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/g1_assemble_trocar.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/g1_assemble_trocar.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bb154a50a8ed9104f5f0de5678a9aee27eee40ef --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/g1_assemble_trocar.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:63c1cfd3e72b9730fbd45ea12eb88ca1a7c5125675ae1cd48d606d95232202e9 +size 476908 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/g1_pick_place.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/g1_pick_place.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9cda20c80031301e26dfdc8eea39e0131c898543 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/g1_pick_place.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:969f34bbb726a206be09c3feafb2d7d16f64e9c8769341b8cd57dba65bc7314f +size 159101 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/g1_pick_place_fixed_base.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/g1_pick_place_fixed_base.jpg new file mode 100644 index 0000000000000000000000000000000000000000..38e87ca1b4e2fd44594b3c5ebb6d22fa4670df71 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/g1_pick_place_fixed_base.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9f9df14702b6c50eafffe65f8c3a599c6b828215676e8aae2a6c5bf37098cd6 +size 151707 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/g1_pick_place_locomanipulation.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/g1_pick_place_locomanipulation.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7e86bbc99e21175f3317600fd99cb56ff14bdee4 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/g1_pick_place_locomanipulation.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:99c54681c0db079bff565636e1abc4e4b7a1ad668f76e5078fc93df8d5967f14 +size 88207 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/galbot_stack_cube.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/galbot_stack_cube.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a64b79b7694f4cf7068229826c7eb9770c466628 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/galbot_stack_cube.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19ff8db739e6f92d0788cf6e0cc951df6d4e544c8b9910d90cdd6eab494580f2 +size 57825 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/gr-1_pick_place.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/gr-1_pick_place.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a86baff52dcf95fab983ac71eb8546f71ab8dfc7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/gr-1_pick_place.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5cc5bc01335e7a86ab15e109a158428226b1a4e1a65f1caba6d48f8a74f83545 +size 113077 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/gr-1_pick_place_annotation.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/gr-1_pick_place_annotation.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a674105b147507489167d0b24b71cf129a4de53a --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/gr-1_pick_place_annotation.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0faa6d86ffdece08256a4b2b2368bd8b65208d86022f38c7e791f67bd3877195 +size 52971 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/gr-1_pick_place_waist.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/gr-1_pick_place_waist.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9cddee3289ed3e7cf9c24c57f08989e845b61361 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/gr-1_pick_place_waist.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b576a792b1d26463464c87a7ade0240036b08d2b1800872a1e0f35f350763537 +size 61739 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/kuka_allegro_lift.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/kuka_allegro_lift.jpg new file mode 100644 index 0000000000000000000000000000000000000000..cbd4213b7188c5774239fa6c7eb7c61acab1472d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/kuka_allegro_lift.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c36865bdb44ac918afed6660c6f5dc07147e5942676671d093abcec279905ebb +size 47720 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/kuka_allegro_reorient.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/kuka_allegro_reorient.jpg new file mode 100644 index 0000000000000000000000000000000000000000..82b8df6aa8fdc154dc15ccdde374fd3e4377cd59 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/kuka_allegro_reorient.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efbc418c401e6adbd6ae4d6aab5bed16309663dc26ef763daf3948f0f920bf67 +size 52080 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/openarm_bi_reach.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/openarm_bi_reach.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e9d6d2546e4dc01cf9865dc82ab949ac3333c6f5 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/openarm_bi_reach.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4351a1e341a75cf2a6d54246116ec1748fbd58ec069991942a7df914b68023f1 +size 39488 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/openarm_uni_lift.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/openarm_uni_lift.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ba7d6a0d2ab4fccdfdff0c22eae5cbd9a7443ca3 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/openarm_uni_lift.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9edcf45d87f93652d1c8d957996a90f8a0270a9d97cc94847ad59cc549dc615d +size 40923 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/openarm_uni_open_drawer.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/openarm_uni_open_drawer.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ab117d1de28433b06a95935e7a86541ba39f8d0c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/openarm_uni_open_drawer.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9ab4c6a305767977472a2e2eb1d24fbd6f86630c80bd1f75190a009dd8390d6 +size 41076 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/openarm_uni_reach.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/openarm_uni_reach.jpg new file mode 100644 index 0000000000000000000000000000000000000000..32eafdeab243a9895b9ed9da56b43e278649066a --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/openarm_uni_reach.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70e94a81f06dac43230dcf6a3724502b82dfb4f83b5f66f857c94c9176ca35a6 +size 40019 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/shadow_cube.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/shadow_cube.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9123f86b1875e9d122ca9ce41d0f43afcf13b548 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/shadow_cube.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90620afca4e77b0206c98cf21dab4c8397ecb0fcff10a0185f5a494d5c1e1fc8 +size 126215 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/shadow_hand_over.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/shadow_hand_over.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b15ca673a96c700a4e2d126a68779e35852838bd --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/shadow_hand_over.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75760e0603a11354c806d8e13ec5f9d93a981ab08a6a90a76eca70231d958331 +size 144111 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/ur10_reach.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/ur10_reach.jpg new file mode 100644 index 0000000000000000000000000000000000000000..faa0e66299d76a75eab4922aea8295c8a2ef4916 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/ur10_reach.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a2c652db6613bd1676e8a0706166c2cc8cf367692387719f94d0329051daf98 +size 201139 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/ur10_stack_surface_gripper.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/ur10_stack_surface_gripper.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9ca3a198d010d6775815c83c0a9799ddcfb96e9a --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/ur10_stack_surface_gripper.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c917a08f9d2e24ad899b68432c21faad3a6f5141175c08e4d71eff59ee0d55ef +size 76607 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/ur10e_reach.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/ur10e_reach.jpg new file mode 100644 index 0000000000000000000000000000000000000000..892950790f046e1d962d3fc0bb2991d3f7b25886 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/manipulation/ur10e_reach.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55789c1597dadd0d7834952181c87ba79ac7f01dac71dd2a42ff495723e3c7bf +size 134849 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/navigation/anymal_c_nav.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/navigation/anymal_c_nav.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9cc7cd52a8a735b92467c72adc94c5dc7dd9e7b4 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/navigation/anymal_c_nav.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ad045aeb1f7146e7c4ccb925116d7fe09933ad6409e2c17678c29fd497637fc +size 142532 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/others/humanoid_amp.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/others/humanoid_amp.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5503dfd938778260d98107dbfec20acfce3ba6ba --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/others/humanoid_amp.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ccc036923ba73ee8fb005674ea520ec9e83f6678b4e34ab9c7251cb13ed8749c +size 121642 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tasks/others/quadcopter.jpg b/simulation/modules/IsaacLab/docs/source/_static/tasks/others/quadcopter.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0bc7dbd7f296aa8211f2a41a15841baeedbe3e55 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tasks/others/quadcopter.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ade4726bed5e43b60f1305835bbb4a790a153aa4cbe3f59ae4b1cd954fa4a49 +size 58039 diff --git a/simulation/modules/IsaacLab/docs/source/_static/teleop/hand_asset.jpg b/simulation/modules/IsaacLab/docs/source/_static/teleop/hand_asset.jpg new file mode 100644 index 0000000000000000000000000000000000000000..15c36d393ca7b1d819f2c1ab783941e40308f1c4 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/teleop/hand_asset.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ec8880b0141300b7e0479150e17805b7cc3cbaea8e3e241d74b7bae47a8f5aa +size 104134 diff --git a/simulation/modules/IsaacLab/docs/source/_static/teleop/recommended-render-select.jpg b/simulation/modules/IsaacLab/docs/source/_static/teleop/recommended-render-select.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6fe780f8b79345cb7a972cd2d5fcf953534e9c3f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/teleop/recommended-render-select.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e93b549d51586ee2957224788d3dbfdf6ab193eb102cfb76f2709111247183e +size 77057 diff --git a/simulation/modules/IsaacLab/docs/source/_static/teleop/recommended-render-settings.jpg b/simulation/modules/IsaacLab/docs/source/_static/teleop/recommended-render-settings.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9a50aaa87580e41150a9073504bb8b40ef46d8b5 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/teleop/recommended-render-settings.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16bbdb37f466acb1bcbe2d7324a73fd60496d53534f16241d50feb70caa6f27d +size 63139 diff --git a/simulation/modules/IsaacLab/docs/source/_static/teleop/teleop_diagram.jpg b/simulation/modules/IsaacLab/docs/source/_static/teleop/teleop_diagram.jpg new file mode 100644 index 0000000000000000000000000000000000000000..acb5c4d5c1a81bc6459e27b0deabc3c91f2e1a36 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/teleop/teleop_diagram.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bcd02bacfda7843e8d762cde5875271b002d10167974aaa78051572ca12cadca +size 336377 diff --git a/simulation/modules/IsaacLab/docs/source/_static/teleop/xr-resolution-slider.jpg b/simulation/modules/IsaacLab/docs/source/_static/teleop/xr-resolution-slider.jpg new file mode 100644 index 0000000000000000000000000000000000000000..037f911c245e7fc53f66c632dc7b572ea9c79b66 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/teleop/xr-resolution-slider.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3291acb3c663ab559128ea181c29583aeb666343a33b7351f3af9e967ec62826 +size 46667 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/discrete_obstacles_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/discrete_obstacles_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..43947d4c3d5d3537d816e251decd7b161a49cf27 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/discrete_obstacles_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4927163189666c35680684d50ce202d895489d4dbc23d9969adc398d769a1232 +size 91428 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/discrete_obstacles_terrain_choice.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/discrete_obstacles_terrain_choice.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d7d43da5cd69502c188ad21531e77e3008e07a2b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/discrete_obstacles_terrain_choice.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0e582967fb981a074ac2fcd1bada3f8f542f8fc3eea2fa5b59b86b15cd791450 +size 33975 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/discrete_obstacles_terrain_fixed.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/discrete_obstacles_terrain_fixed.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7f54eabf8208f32152b75a414129e05501f0b134 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/discrete_obstacles_terrain_fixed.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd9a77be2a92dc714b580b2f90bd72916028acd0ecacb51286de815bfd1d4d67 +size 32427 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/inverted_pyramid_sloped_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/inverted_pyramid_sloped_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a08de8e7c1272f5bc2015cf51f4b7333559dcb44 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/inverted_pyramid_sloped_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c07615709339b8c01610ec3bd1eb0f53338df0bb39442d2b16443d204b8fc1a +size 148994 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/inverted_pyramid_stairs_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/inverted_pyramid_stairs_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..cd86e9241de158c0a08582a7c19cd61017cf08b6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/inverted_pyramid_stairs_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:826e96d56ebf28b27bd9cde1822fc79a98c5650d1e3a88d44ecc86570c967d38 +size 47349 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/pyramid_sloped_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/pyramid_sloped_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a8feb347db6eb2b4cf813e8224c414de59a84bc7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/pyramid_sloped_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:080d9fc8a3d54e14d5f370c982dd913b98b5b93c035314b6333f0bae4583556e +size 150200 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/pyramid_stairs_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/pyramid_stairs_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a9f53ee1849b97779103db860a0cc710a6934b7f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/pyramid_stairs_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c4a038949988eab9887fdd078421acc743c245d9b4d78a2934f5c431b3998ff +size 29207 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/random_uniform_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/random_uniform_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..47c194accaada05ce7ac0f3d57fcf19bce90fe97 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/random_uniform_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8023cf72f1addf993ccf4037c061ac3fbe8c2938e52870c8d7cec3ca12c5fd15 +size 333513 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/stepping_stones_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/stepping_stones_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b276619d2f3cbfef6ef040cdb1ebaa4c1c7929dc --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/stepping_stones_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ec37e7717d8c92e6e39988edfa2a934e7aace62c72a92ce794bff1f71e1baa8 +size 248578 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/wave_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/wave_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..841e3206e0cf6d6e379c66c818a084e9b652a052 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/height_field/wave_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:24656af96f83e10872cc6112b57f40e47e7e6d4f4f983bc728a74c922dac9139 +size 282380 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/box_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/box_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c4af3eb2fd4402cfec6492f22fa0ca1d9c2a877c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/box_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f233bebb033a074a71720b853e64bbc863c57ded47b69d18064059cf4304f06f +size 2956 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/box_terrain_with_two_boxes.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/box_terrain_with_two_boxes.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9d06bedb94c3f9d858e5c46624a6e5165ed38a03 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/box_terrain_with_two_boxes.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c517ab4fd58e280fbc1b97c4b85c57960e8af93cbe388c6580321a5b5ff1c362 +size 2993 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/flat_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/flat_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..26776e38903a4594742d728c997e24bba4d0edbe --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/flat_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2d0907c5a2cd6b3ee287931578b7bdba1123d968abacbd6a7f13a796a22c4e1a +size 2852 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/floating_ring_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/floating_ring_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..41d53cef1c6ffd8451c45fbc552ab3f553afb4ef --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/floating_ring_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:11f4f382c9ebfa3759af8471151e2840126874f26a0b3a00bad804012696a773 +size 2995 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/gap_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/gap_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8810fcab5557e135ff8ebcfdebbecaab8d653a67 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/gap_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7aeb68558d35d186f6be3dc845d1b775a8f233fbbcc86c6a130a0ae204cac71d +size 3708 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/inverted_pyramid_stairs_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/inverted_pyramid_stairs_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..326ef95be326641f559be6b32b61716193c9c3f1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/inverted_pyramid_stairs_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edced4bb3f37679330ac861b710546989048bd549f5ba6aa4e23319733e89e3c +size 5796 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/inverted_pyramid_stairs_terrain_with_holes.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/inverted_pyramid_stairs_terrain_with_holes.jpg new file mode 100644 index 0000000000000000000000000000000000000000..96e3b0c1b83868f06b7d3a435851ab2b1ddf8147 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/inverted_pyramid_stairs_terrain_with_holes.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47cfdc0d011e4353e3e15c11b011444fd46b361b6445d121b12ee6696de22af8 +size 6353 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/pit_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/pit_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..51aabf2a9139cf12051bcb1eeba7f225dd27108d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/pit_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc004b96d8db674643f44e93ff3aae8af4b813c9475cab7243a15ac8dfa67c4f +size 3218 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/pit_terrain_with_two_levels.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/pit_terrain_with_two_levels.jpg new file mode 100644 index 0000000000000000000000000000000000000000..eb5a8623e600a5ce5e601de89228790e107cb230 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/pit_terrain_with_two_levels.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0c89bb5b34e29e6e402848e58ce79da1fb453d58eb2983be1518daf4a51966da +size 4370 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/pyramid_stairs_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/pyramid_stairs_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..be7fa692b64511eaa7a12fdf47879faedf29ca9c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/pyramid_stairs_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12975e7119588cb1c0c63e77fed803552e1e5a4008af58198d01e80e89314691 +size 3595 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/pyramid_stairs_terrain_with_holes.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/pyramid_stairs_terrain_with_holes.jpg new file mode 100644 index 0000000000000000000000000000000000000000..836dc6e7562c435e6ee3736100d9da7d79ac56e4 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/pyramid_stairs_terrain_with_holes.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e63145b71405a1c57bf153f0365b82a6f35f5894fd22a9676b4c030da723b440 +size 4926 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/rails_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/rails_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..cc112e963b6d77b825fc74bc900b7f29e12c8ebd --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/rails_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:397e2a0f459c0923cc3f07e954a9835cf00a659f5ecc312465ffa0930fdee1fd +size 3326 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/random_grid_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/random_grid_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..dba9100285fc53a8dba8406876e3236d8405e5d8 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/random_grid_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cee6ed4e4e2e2191c1dd419c1c59d365f772bb1ff045b45771fe848dfd396ce7 +size 6378 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/random_grid_terrain_with_holes.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/random_grid_terrain_with_holes.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3cd4f542714fbfd692fee59e4ed1ce98fc5bec65 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/random_grid_terrain_with_holes.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1be4b07068e25e7b402999ab4eb181c3115c60dc95d9f7f7a3f6296e8540167a +size 6093 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/repeated_objects_box_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/repeated_objects_box_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4af1d1f2bbce53e48f1c3a6b9980b8f1567e3da2 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/repeated_objects_box_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf00b570b6cb5cf748c764144d4818ea3878abb48860a4202f03e112f653d46c +size 60154 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/repeated_objects_cylinder_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/repeated_objects_cylinder_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4ebbbe0c10ec85c275feaac72df891582f935cd9 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/repeated_objects_cylinder_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef6f85e8fe9f494d9743bdb23846b4e71c33c8998e7b91d0b5429b610cb4f6de +size 84510 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/repeated_objects_pyramid_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/repeated_objects_pyramid_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0105dc346dadaf38973b49b1b1d64dbca74bde48 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/repeated_objects_pyramid_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f000868c88452b9596ffa8f5f78a04e267ea94bb97f49ce71564efc15972d0a +size 62332 diff --git a/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/star_terrain.jpg b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/star_terrain.jpg new file mode 100644 index 0000000000000000000000000000000000000000..281916c441a36ce263bdbc68148cf98803283cee --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/terrains/trimesh/star_terrain.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:22c69f97496f7c81cb3adce0725f6f80e96c6ab78cbcd3b97929e87b4397ed24 +size 9751 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_add_new_robot_result.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_add_new_robot_result.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7ae5c52f1211b0e58dea5cb1a2757122f9a8e7af --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_add_new_robot_result.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4151a90385b3292fa455cb62ef0b1137de3e88a0cf22d62967793599b0ac50c +size 120400 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_add_sensors.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_add_sensors.jpg new file mode 100644 index 0000000000000000000000000000000000000000..30dfc623ce54021b50ad7339b3299315b6132e7f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_add_sensors.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7bb6b296dfa8d2d1653c00e016ead02af88b550e9c6b0423d55be4bae00a8026 +size 197550 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_convert_mesh.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_convert_mesh.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1955358f645e49d991906127f9ee73d4f643594f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_convert_mesh.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ff640867e9ab3e75fa5d05cfa91d0c61dda9ce1e3e17c072f8bac855f5654d6 +size 23413 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_convert_mjcf.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_convert_mjcf.jpg new file mode 100644 index 0000000000000000000000000000000000000000..44399764ef6f32dd268a42e99e445c962723c236 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_convert_mjcf.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c9a80d82cfb0b2ed64f8c0a6231a6364323db35716513deb16d9405a04c8a97 +size 25668 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_convert_urdf.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_convert_urdf.jpg new file mode 100644 index 0000000000000000000000000000000000000000..753160613eee3dd00e00ba06ae2d4d4bdd0a2413 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_convert_urdf.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b305f97ee55134120f20227d14811da4988be67eb45663d9a7380066c746745 +size 20215 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_create_direct_workflow.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_create_direct_workflow.jpg new file mode 100644 index 0000000000000000000000000000000000000000..687bada88caff63d140d027ef6530abae80c033d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_create_direct_workflow.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3bd3eb489ede1537805972aad8f761c6ce19d2e854d29811619f356c681325bd +size 237605 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_create_empty.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_create_empty.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9eceb0409a9bbe117b9d33b4d2220ee8ff761cd6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_create_empty.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:733c41a099f8dfb826375da7eb577434474e8ca4dd28d9ed33511d1540f53740 +size 89516 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_create_manager_base.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_create_manager_base.jpg new file mode 100644 index 0000000000000000000000000000000000000000..dee4e1a3c227bf7ceeb59bc8dc04c3cebd338cca --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_create_manager_base.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd288a1d7540f0c5a3934422f205cba04e6a662762275315d5a67a701df299f8 +size 244815 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_create_manager_rl_env.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_create_manager_rl_env.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bf258b3fd754228d8bae924c67d796efdf26cec7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_create_manager_rl_env.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:542f184bac0597be137e0a1b49796321823650f97c0f84ed731eb2529bb9d95d +size 261708 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_creating_a_scene.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_creating_a_scene.jpg new file mode 100644 index 0000000000000000000000000000000000000000..94c62eb69e0268613195c90fd3c8bf49c245c9f2 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_creating_a_scene.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c2fa7c246349ca5102e9c20d18d9028ac60950b26e07a952039ea5aa405c9fd +size 171874 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_launch_app.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_launch_app.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b31537903b6c548b9aaa72ecb0515d40c619c7fb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_launch_app.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f33510d4395e6e45bb638163821de090fc49af8c4a0f102bc350e7d1d6cdb4b9 +size 127856 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_modify_direct_rl_env.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_modify_direct_rl_env.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d65d361963f59ce745c14239df825f5a0bb9696b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_modify_direct_rl_env.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6cba4a94f707e86d55dc9e62fe82a2eb2c7508a42d4763f8ef0ff13abe137c83 +size 163254 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_operational_space_controller.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_operational_space_controller.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c7295541cb50d2b36180f6640668b170a7a7125c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_operational_space_controller.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd90da8e572df901f66d0b82f185bf018d377d220fc3306da6774bbbbb120760 +size 195130 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_policy_inference_in_usd.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_policy_inference_in_usd.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4fc140d01fc6ff4b9606d9466dc5d25be11861be --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_policy_inference_in_usd.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ef0e68b5564d7140c3500c7c751993507f3457296cc7ae03a6627215823d699 +size 48790 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_register_environment.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_register_environment.jpg new file mode 100644 index 0000000000000000000000000000000000000000..94856ef6ce7f6bfbfa4c48044721af15dc8a658b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_register_environment.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c142db96c54e7999421741a5cf795a02d37cd4701e35da26f64e028c3adc7cb6 +size 243662 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_run_articulation.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_run_articulation.jpg new file mode 100644 index 0000000000000000000000000000000000000000..eab9644288c8fe628df3c3c1578cb0997b3535d4 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_run_articulation.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85dd1ed16d6c6c3fa3be1df2a057d1a2e65ea8249946302dfdbb326433de0c2b +size 161075 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_run_deformable_object.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_run_deformable_object.jpg new file mode 100644 index 0000000000000000000000000000000000000000..451af0911685f02358eb5271e4d7aada2d6a1b86 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_run_deformable_object.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efe61c1fbb7bd6b6e437613379986a7ce26e8790ab330ab545f0a8f06a9f905e +size 198472 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_run_rigid_object.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_run_rigid_object.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6f7fdbe37ff473cf8956b87fa1580d25ab8c8921 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_run_rigid_object.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:438667931c3cc042c6837e6689a94ee786341db4de2b23d04376d131fce1258e +size 123076 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_run_surface_gripper.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_run_surface_gripper.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6b16f98474c8d49aca7f0c804e3cd4428b4c6b64 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_run_surface_gripper.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d57bfe4e1a450048868ca540e965d2e20a95d8d0401960372e48fa99565d24e +size 234303 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_spawn_prims.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_spawn_prims.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5648019ff18fb1b0f2c88bf9709829a90bfc787e --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_spawn_prims.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b071489eb8bd9361074b39a5f37a4e7648d30e546404ae5f4c67e5bb5cb741c7 +size 147935 diff --git a/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_task_space_controller.jpg b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_task_space_controller.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5a963dd039fb06651683d93df93674b414016afc --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/tutorials/tutorial_task_space_controller.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:020ceeed21df750c141d981132c111c634121429bcc4b300a4de08f7c193172f +size 226142 diff --git a/simulation/modules/IsaacLab/docs/source/_static/visualizers/kit_viz_anymal_iteractive_view.jpg b/simulation/modules/IsaacLab/docs/source/_static/visualizers/kit_viz_anymal_iteractive_view.jpg new file mode 100644 index 0000000000000000000000000000000000000000..87928e1d51863fb5ae2cf91d5a9d00d5ace04252 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/visualizers/kit_viz_anymal_iteractive_view.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec431d8572b30dc55704284d4e3316beed5fb86e71868b73cda521e6334c260d +size 235833 diff --git a/simulation/modules/IsaacLab/docs/source/_static/visualizers/kit_viz_anymal_tiled_view.jpg b/simulation/modules/IsaacLab/docs/source/_static/visualizers/kit_viz_anymal_tiled_view.jpg new file mode 100644 index 0000000000000000000000000000000000000000..33315927f8dd37912f5c1a5d3293f80af6a42f70 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/visualizers/kit_viz_anymal_tiled_view.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8782a306d3202c531bc9d250832c6cccd6dbaa3e8709b0d8c2e236510496e166 +size 280145 diff --git a/simulation/modules/IsaacLab/docs/source/_static/visualizers/newton_viz.jpg b/simulation/modules/IsaacLab/docs/source/_static/visualizers/newton_viz.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1f96ab50c1c8d951c4fd3ae88a42de81a5ad040e --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/visualizers/newton_viz.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69ffdac489e7b128c14d6db3670fd32b431beb2a2ed9f5dca4051686c1d5180a +size 339874 diff --git a/simulation/modules/IsaacLab/docs/source/_static/visualizers/newton_viz_galbot_interactive_view.jpg b/simulation/modules/IsaacLab/docs/source/_static/visualizers/newton_viz_galbot_interactive_view.jpg new file mode 100644 index 0000000000000000000000000000000000000000..da8fc2015a8b8e1afb6883a1d361d432a3597278 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/visualizers/newton_viz_galbot_interactive_view.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:20da70aa164409f09e65375039f1a8c779445e09f37cc3c66983caf957487401 +size 201979 diff --git a/simulation/modules/IsaacLab/docs/source/_static/visualizers/newton_viz_galbot_tiled_view.jpg b/simulation/modules/IsaacLab/docs/source/_static/visualizers/newton_viz_galbot_tiled_view.jpg new file mode 100644 index 0000000000000000000000000000000000000000..72bbd017fd6db13dfea08b848ee1c939d0acecd7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/visualizers/newton_viz_galbot_tiled_view.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5686396fa439f9045a06ce3ba989a3b90631021e6d8c49ab15795c418841b1a6 +size 245951 diff --git a/simulation/modules/IsaacLab/docs/source/_static/visualizers/ov_viz.jpg b/simulation/modules/IsaacLab/docs/source/_static/visualizers/ov_viz.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c69df791544cbed0e2c56cd1567f2ffbf95ef497 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/visualizers/ov_viz.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7aa3939677af656a7b1484fedbbaf687da0ddf53bab1c16fd26db56d936cfc05 +size 365289 diff --git a/simulation/modules/IsaacLab/docs/source/_static/visualizers/rerun_viz.jpg b/simulation/modules/IsaacLab/docs/source/_static/visualizers/rerun_viz.jpg new file mode 100644 index 0000000000000000000000000000000000000000..05367f14fc4ff6e83f10a7895491cc65a60ae9b6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/visualizers/rerun_viz.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a00db0f5818e5b121f6b08238224a36f6fd921d1bd98cb7a7e5bf28528571015 +size 350460 diff --git a/simulation/modules/IsaacLab/docs/source/_static/vscode_tasks.png b/simulation/modules/IsaacLab/docs/source/_static/vscode_tasks.png new file mode 100644 index 0000000000000000000000000000000000000000..b5b0d5c2e2655689685d77b8838223db4be4a1ae --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/_static/vscode_tasks.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70b5d31518826c6e57c4182b20abbb88f0b247d596a616de4e5f7e5790f79b2c +size 983040 diff --git a/simulation/modules/IsaacLab/docs/source/api/index.rst b/simulation/modules/IsaacLab/docs/source/api/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..2ff0cf6174be751541ea24ec79011c85247e73fe --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/index.rst @@ -0,0 +1,239 @@ +API Reference +============= + +This page gives an overview of all the modules and classes in the Isaac Lab extensions. + +isaaclab extension +------------------ + +The following modules are available in the ``isaaclab`` extension: + +.. currentmodule:: isaaclab + +.. autosummary:: + :toctree: lab + + app + actuators + assets + cloner + controllers + devices + envs + managers + markers + physics + renderers + scene + scene_data + sensors + sim + terrains + utils + visualizers + +.. toctree:: + :hidden: + + lab/isaaclab.envs.mdp + lab/isaaclab.envs.ui + lab/isaaclab.sensors.patterns + lab/isaaclab.sim.converters + lab/isaaclab.sim.schemas + lab/isaaclab.sim.spawners + lab/isaaclab.sim.views + lab/isaaclab.sim.utils + + +isaaclab_rl extension +--------------------- + +The following wrappers are available in the ``isaaclab_rl`` extension: + +.. currentmodule:: isaaclab_rl + +.. toctree:: + :maxdepth: 2 + + lab_rl/isaaclab_rl + + +isaaclab_mimic extension +------------------------ + +The following modules are available in the ``isaaclab_mimic`` extension: + +.. currentmodule:: isaaclab_mimic + +.. autosummary:: + :toctree: lab_mimic + + datagen + envs + +isaaclab_contrib extension +----------------------------- + +The following modules are available in the ``isaaclab_contrib`` extension: + +.. currentmodule:: isaaclab_contrib + +.. autosummary:: + :toctree: lab_contrib + + actuators + assets + controllers + deformable + mdp + rl + sensors + +isaaclab_tasks extension +------------------------ + +This package ``isaaclab_tasks`` contains the tasks that are available in the Isaac Lab. +For more information, please refer to the :ref:`environments`. + +It includes the following modules: + +.. currentmodule:: isaaclab_tasks + +.. autosummary:: + :toctree: lab_tasks + + utils + +isaaclab_teleop extension +------------------------- + +The following modules are available in the ``isaaclab_teleop`` extension: + +.. currentmodule:: isaaclab_teleop + +.. toctree:: + :maxdepth: 2 + + lab_teleop/isaaclab_teleop + +isaaclab_physx extension +------------------------ + +The following modules are available in the ``isaaclab_physx`` extension: + +.. currentmodule:: isaaclab_physx + +.. autosummary:: + :toctree: lab_physx + + assets + cloner + physics + renderers + sensors + +.. toctree:: + :hidden: + + lab_physx/isaaclab_physx.sim.schemas + lab_physx/isaaclab_physx.sim.spawners + +isaaclab_newton extension +------------------------- + +The following modules are available in the ``isaaclab_newton`` extension: + +.. currentmodule:: isaaclab_newton + +.. autosummary:: + :toctree: lab_newton + + assets + cloner + physics + renderers + sensors + sim.schemas + +.. toctree:: + :hidden: + + lab_newton/isaaclab_newton.sim.spawners + +isaaclab_ov extension +--------------------- + +The following modules are available in the ``isaaclab_ov`` extension: + +.. currentmodule:: isaaclab_ov + +.. autosummary:: + :toctree: lab_ov + + renderers + +isaaclab_assets extension +------------------------- + +The following modules are available in the ``isaaclab_assets`` extension: + +.. currentmodule:: isaaclab_assets + +.. autosummary:: + :toctree: lab_assets + + robots + sensors + +isaaclab_visualizers extension +------------------------------ + +The following modules are available in the ``isaaclab_visualizers`` extension: + +.. currentmodule:: isaaclab_visualizers + +.. autosummary:: + :toctree: lab_visualizers + + kit + newton + rerun + viser + + +isaaclab_ovphysx extension +--------------------------- + +The following modules are available in the ``isaaclab_ovphysx`` extension: + +.. currentmodule:: isaaclab_ovphysx + +.. autosummary:: + :toctree: lab_ovphysx + + assets + cloner + physics + + +isaaclab_experimental extension +-------------------------------- + +The following modules are available in the ``isaaclab_experimental`` extension: + +.. currentmodule:: isaaclab_experimental + +.. autosummary:: + :toctree: lab_experimental + + envs + managers + utils + + +isaaclab_tasks_experimental extension +-------------------------------------- + +The package ``isaaclab_tasks_experimental`` contains experimental task implementations +under active development, not yet part of the stable task suite. +For the list of available environments, please refer to the :ref:`environments`. diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.actuators.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.actuators.rst new file mode 100644 index 0000000000000000000000000000000000000000..5ab005de5b3b3a08ea2377eae71157915f2d8b8f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.actuators.rst @@ -0,0 +1,135 @@ +isaaclab.actuators +================== + +.. automodule:: isaaclab.actuators + + .. rubric:: Classes + + .. autosummary:: + + ActuatorBase + ActuatorBaseCfg + ImplicitActuator + ImplicitActuatorCfg + IdealPDActuator + IdealPDActuatorCfg + DCMotor + DCMotorCfg + DelayedPDActuator + DelayedPDActuatorCfg + RemotizedPDActuator + RemotizedPDActuatorCfg + 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 + +Delayed PD Actuator +------------------- + +.. autoclass:: DelayedPDActuator + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: DelayedPDActuatorCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Remotized PD Actuator +--------------------- + +.. autoclass:: RemotizedPDActuator + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: RemotizedPDActuatorCfg + :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 diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.app.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.app.rst new file mode 100644 index 0000000000000000000000000000000000000000..f1b040f1770efb28aa7992406fc396264cb91454 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.app.rst @@ -0,0 +1,115 @@ +isaaclab.app +============ + +.. automodule:: isaaclab.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}``, 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}`` , 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 `WebRTC Livestream`_ extension over **public networks**. This allows users to + connect through the WebRTC Client using the WebRTC protocol. + * ``LIVESTREAM=2`` enables streaming via the `WebRTC Livestream`_ extension over **private and local networks**. This allows users to + connect through the WebRTC Client using the WebRTC protocol. + + .. note:: + + Each Isaac Sim instance can only connect to one streaming client. + Connecting to an Isaac Sim instance that is currently serving a streaming client + results in an error for the second user. + +* **Public IP Address**: When using the environment variable ``LIVESTREAM={1,2}``, set the ``PUBLIC_IP`` envvar to define the public IP address endpoint for livestreaming remotely. + +* **Enable cameras**: If the environment variable ``ENABLE_CAMERAS`` is set to 1, then the + cameras are enabled. This is useful for running the simulator without a GUI but still rendering the + viewport and camera images. + + * ``ENABLE_CAMERAS=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:`isaaclab.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 LIVESTREAM=2 + export ENABLE_CAMERAS=1 + # run the python script + ./isaaclab.sh -p scripts/demos/quadrupeds.py + +Alternatively, one can set the environment variables to the python script directly: + +.. code:: bash + + LIVESTREAM=2 ENABLE_CAMERAS=1 ./isaaclab.sh -p scripts/demos/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 argparse + + from isaaclab.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.isaacsim.omniverse.nvidia.com/latest/installation/manual_livestream_clients.html +.. _`WebRTC Livestream`: https://docs.isaacsim.omniverse.nvidia.com/latest/installation/manual_livestream_clients.html#isaac-sim-short-webrtc-streaming-client diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.assets.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.assets.rst new file mode 100644 index 0000000000000000000000000000000000000000..b7b980c24231880914b0c8eb224e577e7bd2d9c8 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.assets.rst @@ -0,0 +1,128 @@ +isaaclab.assets +=============== + +.. automodule:: isaaclab.assets + + .. rubric:: Classes + + .. autosummary:: + + AssetBase + AssetBaseCfg + RigidObject + RigidObjectData + RigidObjectCfg + RigidObjectCollection + RigidObjectCollectionData + RigidObjectCollectionCfg + BaseDeformableObject + BaseDeformableObjectData + DeformableObject + DeformableObjectData + DeformableObjectCfg + Articulation + ArticulationData + ArticulationCfg + +.. currentmodule:: isaaclab.assets + +Asset Base +---------- + +.. autoclass:: AssetBase + :members: + +.. autoclass:: AssetBaseCfg + :members: + :exclude-members: __init__, class_type, InitialStateCfg + +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 + +Rigid Object Collection +----------------------- + +.. autoclass:: RigidObjectCollection + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: RigidObjectCollectionData + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: RigidObjectCollectionCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Deformable Object +----------------- + +.. autoclass:: DeformableObject + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: BaseDeformableObject + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: DeformableObjectData + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: BaseDeformableObjectData + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: DeformableObjectCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type, InitialStateCfg + +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 diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.cloner.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.cloner.rst new file mode 100644 index 0000000000000000000000000000000000000000..66cf2bedf582ab7ea9a708b85f812d6255872179 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.cloner.rst @@ -0,0 +1,4 @@ +isaaclab.cloner +=============== + +.. automodule:: isaaclab.cloner diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.controllers.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.controllers.rst new file mode 100644 index 0000000000000000000000000000000000000000..1ef31448ab86ef44cbe57414a3606b77d96b5117 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.controllers.rst @@ -0,0 +1,66 @@ +isaaclab.controllers +==================== + +.. automodule:: isaaclab.controllers + + .. rubric:: Classes + + .. autosummary:: + + DifferentialIKController + DifferentialIKControllerCfg + OperationalSpaceController + OperationalSpaceControllerCfg + pink_ik.PinkIKController + pink_ik.PinkIKControllerCfg + pink_ik.NullSpacePostureTask + +Differential Inverse Kinematics +------------------------------- + +.. autoclass:: DifferentialIKController + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: DifferentialIKControllerCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Operational Space controllers +----------------------------- + +.. autoclass:: OperationalSpaceController + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: OperationalSpaceControllerCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + + +Pink IK Controller +------------------ + +.. automodule:: isaaclab.controllers.pink_ik + +.. autoclass:: PinkIKController + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: PinkIKControllerCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Available Pink IK Tasks +^^^^^^^^^^^^^^^^^^^^^^^ + +.. autoclass:: NullSpacePostureTask diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.devices.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.devices.rst new file mode 100644 index 0000000000000000000000000000000000000000..9a75d562403e12560c72ca1e9045bf08eb986f98 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.devices.rst @@ -0,0 +1,141 @@ +isaaclab.devices +================ + +.. automodule:: isaaclab.devices + + .. rubric:: Classes + + .. autosummary:: + + DeviceBase + RetargeterBase + Se2Gamepad + Se3Gamepad + Se2Keyboard + Se3Keyboard + Se2SpaceMouse + Se3SpaceMouse + HaplyDevice + OpenXRDevice + ManusVive + openxr.retargeters.GripperRetargeter + openxr.retargeters.Se3AbsRetargeter + openxr.retargeters.Se3RelRetargeter + openxr.retargeters.GR1T2Retargeter + + .. rubric:: Modules + + .. autosummary:: + + openxr.retargeters + +Device Base +----------- + +.. autoclass:: DeviceBase + :members: + +Retargeter Base +--------------- + +.. autoclass:: RetargeterBase + :members: + +Game Pad +-------- + +.. autoclass:: Se2Gamepad + :members: + :inherited-members: + :show-inheritance: + :noindex: + +.. autoclass:: Se3Gamepad + :members: + :inherited-members: + :show-inheritance: + :noindex: + +Keyboard +-------- + +.. autoclass:: Se2Keyboard + :members: + :inherited-members: + :show-inheritance: + :noindex: + +.. autoclass:: Se3Keyboard + :members: + :inherited-members: + :show-inheritance: + :noindex: + +Space Mouse +----------- + +.. autoclass:: Se2SpaceMouse + :members: + :inherited-members: + :show-inheritance: + :noindex: + +.. autoclass:: Se3SpaceMouse + :members: + :inherited-members: + :show-inheritance: + :noindex: + +Haply +----- + +.. autoclass:: HaplyDevice + :members: + :inherited-members: + :show-inheritance: + :noindex: + +OpenXR +------ + +.. autoclass:: OpenXRDevice + :members: + :inherited-members: + :show-inheritance: + :noindex: + +Manus + Vive +------------ + +.. autoclass:: ManusVive + :members: + :inherited-members: + :show-inheritance: + :noindex: + +Retargeters +----------- + +.. autoclass:: isaaclab.devices.openxr.retargeters.GripperRetargeter + :members: + :inherited-members: + :show-inheritance: + :noindex: + +.. autoclass:: isaaclab.devices.openxr.retargeters.Se3AbsRetargeter + :members: + :inherited-members: + :show-inheritance: + :noindex: + +.. autoclass:: isaaclab.devices.openxr.retargeters.Se3RelRetargeter + :members: + :inherited-members: + :show-inheritance: + :noindex: + +.. autoclass:: isaaclab.devices.openxr.retargeters.GR1T2Retargeter + :members: + :inherited-members: + :show-inheritance: + :noindex: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.envs.mdp.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.envs.mdp.rst new file mode 100644 index 0000000000000000000000000000000000000000..bffa5279b125f358caa8df8340cab509fbe0c5a5 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.envs.mdp.rst @@ -0,0 +1,54 @@ +isaaclab.envs.mdp +================= + +.. automodule:: isaaclab.envs.mdp + +Observations +------------ + +.. automodule:: isaaclab.envs.mdp.observations + :members: + +Actions +------- + +.. automodule:: isaaclab.envs.mdp.actions + +.. automodule:: isaaclab.envs.mdp.actions.actions_cfg + :members: + :show-inheritance: + :exclude-members: __init__, class_type + +Events +------ + +.. automodule:: isaaclab.envs.mdp.events + :members: + +Commands +-------- + +.. automodule:: isaaclab.envs.mdp.commands + +.. automodule:: isaaclab.envs.mdp.commands.commands_cfg + :members: + :show-inheritance: + :exclude-members: __init__, class_type + +Rewards +------- + +.. automodule:: isaaclab.envs.mdp.rewards + :members: + +Terminations +------------ + +.. automodule:: isaaclab.envs.mdp.terminations + :members: + +Curriculum +---------- + +.. automodule:: isaaclab.envs.mdp.curriculums + :members: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.envs.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.envs.rst new file mode 100644 index 0000000000000000000000000000000000000000..51b6e1866888d1cce3db2ca1af0f039fe7a96105 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.envs.rst @@ -0,0 +1,114 @@ +isaaclab.envs +============= + +.. automodule:: isaaclab.envs + + .. rubric:: Submodules + + .. autosummary:: + + mdp + ui + + .. rubric:: Classes + + .. autosummary:: + + ManagerBasedEnv + ManagerBasedEnvCfg + ManagerBasedRLEnv + ManagerBasedRLEnvCfg + DirectRLEnv + DirectRLEnvCfg + DirectMARLEnv + DirectMARLEnvCfg + ManagerBasedRLMimicEnv + MimicEnvCfg + SubTaskConfig + SubTaskConstraintConfig + ViewerCfg + +Manager Based Environment +------------------------- + +.. autoclass:: ManagerBasedEnv + :members: + +.. autoclass:: ManagerBasedEnvCfg + :members: + :exclude-members: __init__, class_type + +Manager Based RL Environment +---------------------------- + +.. autoclass:: ManagerBasedRLEnv + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: ManagerBasedRLEnvCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Direct RL Environment +--------------------- + +.. autoclass:: DirectRLEnv + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: DirectRLEnvCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Direct Multi-Agent RL Environment +--------------------------------- + +.. autoclass:: DirectMARLEnv + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: DirectMARLEnvCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Mimic Environment +----------------- + +.. autoclass:: ManagerBasedRLMimicEnv + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: MimicEnvCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +.. autoclass:: SubTaskConfig + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +.. autoclass:: SubTaskConstraintConfig + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Common +------ + +.. autoclass:: ViewerCfg + :members: + :exclude-members: __init__ diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.envs.ui.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.envs.ui.rst new file mode 100644 index 0000000000000000000000000000000000000000..0e48034c7feefb024f95bbd2dc23148e12e9d2a6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.envs.ui.rst @@ -0,0 +1,31 @@ +isaaclab.envs.ui +================ + +.. automodule:: isaaclab.envs.ui + + .. rubric:: Classes + + .. autosummary:: + + BaseEnvWindow + ManagerBasedRLEnvWindow + ViewportCameraController + +Base Environment UI +------------------- + +.. autoclass:: BaseEnvWindow + :members: + +Config Based RL Environment UI +------------------------------ + +.. autoclass:: ManagerBasedRLEnvWindow + :members: + :show-inheritance: + +Viewport Camera Controller +-------------------------- + +.. autoclass:: ViewportCameraController + :members: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.managers.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.managers.rst new file mode 100644 index 0000000000000000000000000000000000000000..184e976e32a0878fee50acadc85b0fab0b268e8c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.managers.rst @@ -0,0 +1,160 @@ +isaaclab.managers +================= + +.. automodule:: isaaclab.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 + RecorderManager + RecorderTermCfg + +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__ + + +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__ + +Recorder Manager +---------------- + +.. autoclass:: RecorderManager + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: RecorderTermCfg + :members: + :exclude-members: __init__ diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.markers.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.markers.rst new file mode 100644 index 0000000000000000000000000000000000000000..9382de11840aa9ca84e8e2be3aff467a7deb7e3f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.markers.rst @@ -0,0 +1,23 @@ +isaaclab.markers +================ + +.. automodule:: isaaclab.markers + + .. rubric:: Classes + + .. autosummary:: + + VisualizationMarkers + VisualizationMarkersCfg + +Visualization Markers +--------------------- + +.. autoclass:: VisualizationMarkers + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: VisualizationMarkersCfg + :members: + :exclude-members: __init__ diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.physics.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.physics.rst new file mode 100644 index 0000000000000000000000000000000000000000..4a2fbfd8d70b0dc151431cfb6929db8eefa8972c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.physics.rst @@ -0,0 +1,4 @@ +isaaclab.physics +================ + +.. automodule:: isaaclab.physics diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.renderers.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.renderers.rst new file mode 100644 index 0000000000000000000000000000000000000000..94eae9b5524b1f561acde6413d8659fd78edf911 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.renderers.rst @@ -0,0 +1,36 @@ +isaaclab.renderers +================== + +.. automodule:: isaaclab.renderers + + .. rubric:: Classes + + .. autosummary:: + + BaseRenderer + Renderer + RendererCfg + +Base Renderer +------------- + +.. autoclass:: BaseRenderer + :members: + :show-inheritance: + :exclude-members: __init__ + +Renderer Factory +---------------- + +.. autoclass:: Renderer + :members: + :show-inheritance: + :exclude-members: __init__ + +Renderer Configuration +----------------------- + +.. autoclass:: RendererCfg + :members: + :show-inheritance: + :exclude-members: __init__ diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.scene.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.scene.rst new file mode 100644 index 0000000000000000000000000000000000000000..86866dfdadb32c0af057c033c02b7a05b4b7f8de --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.scene.rst @@ -0,0 +1,23 @@ +isaaclab.scene +============== + +.. automodule:: isaaclab.scene + + .. rubric:: Classes + + .. autosummary:: + + InteractiveScene + InteractiveSceneCfg + +interactive Scene +----------------- + +.. autoclass:: InteractiveScene + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: InteractiveSceneCfg + :members: + :exclude-members: __init__ diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.scene_data.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.scene_data.rst new file mode 100644 index 0000000000000000000000000000000000000000..c36b7666861a4e5b0f254fdab6904f9beaff6acb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.scene_data.rst @@ -0,0 +1,33 @@ +isaaclab.scene_data +=================== + +.. automodule:: isaaclab.scene_data + + .. rubric:: Classes + + .. autosummary:: + + SceneDataProvider + SceneDataBackend + SceneDataFormat + +Scene Data Provider +------------------- + +.. autoclass:: SceneDataProvider + :members: + :undoc-members: + :show-inheritance: + +Scene Data Backend +------------------ + +.. autoclass:: SceneDataBackend + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: SceneDataFormat + :members: + :undoc-members: + :show-inheritance: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sensors.patterns.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sensors.patterns.rst new file mode 100644 index 0000000000000000000000000000000000000000..ac5a44808beeb7c753b3aca17b594fbd8046c40f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sensors.patterns.rst @@ -0,0 +1,61 @@ +isaaclab.sensors.patterns +========================= + +.. automodule:: isaaclab.sensors.patterns + + .. rubric:: Classes + + .. autosummary:: + + PatternBaseCfg + GridPatternCfg + PinholeCameraPatternCfg + BpearlPatternCfg + +Pattern Base +------------ + +.. autoclass:: PatternBaseCfg + :members: + :inherited-members: + :exclude-members: __init__ + +Grid Pattern +------------ + +.. autofunction:: isaaclab.sensors.patterns.grid_pattern + +.. autoclass:: GridPatternCfg + :members: + :inherited-members: + :exclude-members: __init__, func + +Pinhole Camera Pattern +---------------------- + +.. autofunction:: isaaclab.sensors.patterns.pinhole_camera_pattern + +.. autoclass:: PinholeCameraPatternCfg + :members: + :inherited-members: + :exclude-members: __init__, func + +RS-Bpearl Pattern +----------------- + +.. autofunction:: isaaclab.sensors.patterns.bpearl_pattern + +.. autoclass:: BpearlPatternCfg + :members: + :inherited-members: + :exclude-members: __init__, func + +LiDAR Pattern +------------- + +.. autofunction:: isaaclab.sensors.patterns.lidar_pattern + +.. autoclass:: LidarPatternCfg + :members: + :inherited-members: + :exclude-members: __init__, func diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sensors.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sensors.rst new file mode 100644 index 0000000000000000000000000000000000000000..537dc8dcaf430139d1f4fff994107aa5eaf9d8a2 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sensors.rst @@ -0,0 +1,235 @@ +isaaclab.sensors +================ + +.. automodule:: isaaclab.sensors + + .. rubric:: Submodules + + .. autosummary:: + + patterns + + .. rubric:: Classes + + .. autosummary:: + + SensorBase + SensorBaseCfg + Camera + CameraData + CameraCfg + ContactSensor + ContactSensorData + ContactSensorCfg + FrameTransformer + FrameTransformerData + FrameTransformerCfg + RayCaster + RayCasterData + RayCasterCfg + RayCasterCamera + RayCasterCameraCfg + MultiMeshRayCaster + MultiMeshRayCasterData + MultiMeshRayCasterCfg + MultiMeshRayCasterCamera + MultiMeshRayCasterCameraCfg + Imu + ImuCfg + Pva + PvaData + PvaCfg + JointWrenchSensor + JointWrenchSensorData + JointWrenchSensorCfg + +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, OffsetCfg + + +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, OffsetCfg + +Multi-Mesh Ray-Cast Sensor +-------------------------- + +.. autoclass:: MultiMeshRayCaster + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: MultiMeshRayCasterData + :members: + :inherited-members: + :exclude-members: __init__ + +.. autoclass:: MultiMeshRayCasterCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type, OffsetCfg + +Multi-Mesh Ray-Cast Camera +-------------------------- + +.. autoclass:: MultiMeshRayCasterCamera + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: MultiMeshRayCasterCameraCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type, OffsetCfg, RaycastTargetCfg + +Inertia Measurement Unit +------------------------ + +.. autoclass:: Imu + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: ImuCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Pose Velocity Acceleration Sensor +--------------------------------- + +.. autoclass:: Pva + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: PvaData + :members: + :inherited-members: + :exclude-members: __init__ + +.. autoclass:: PvaCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Joint Wrench Sensor +------------------- + +.. autoclass:: JointWrenchSensor + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: JointWrenchSensorData + :members: + :inherited-members: + :exclude-members: __init__ + +.. autoclass:: JointWrenchSensorCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.converters.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.converters.rst new file mode 100644 index 0000000000000000000000000000000000000000..6fd5155c4e534ceb917db858abe0488a1e0c38a9 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.converters.rst @@ -0,0 +1,70 @@ +isaaclab.sim.converters +======================= + +.. automodule:: isaaclab.sim.converters + + .. rubric:: Classes + + .. autosummary:: + + AssetConverterBase + AssetConverterBaseCfg + MeshConverter + MeshConverterCfg + UrdfConverter + UrdfConverterCfg + MjcfConverter + MjcfConverterCfg + +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__ + +MJCF Converter +-------------- + +.. autoclass:: MjcfConverter + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: MjcfConverterCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.rst new file mode 100644 index 0000000000000000000000000000000000000000..96816b6a5224f650609f3b737d54b6c00ac5ec51 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.rst @@ -0,0 +1,52 @@ +isaaclab.sim +============ + +.. automodule:: isaaclab.sim + + .. rubric:: Submodules + + .. autosummary:: + + converters + schemas + spawners + utils + + .. rubric:: Classes + + .. autosummary:: + + SimulationContext + SimulationCfg + RenderCfg + + .. 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:: RenderCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Simulation Context Builder +-------------------------- + +.. automethod:: simulation_context.build_simulation_context diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.schemas.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.schemas.rst new file mode 100644 index 0000000000000000000000000000000000000000..ea29860cbe4ec6521d4c76246f3a6fbce1f4739d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.schemas.rst @@ -0,0 +1,169 @@ +isaaclab.sim.schemas +==================== + +.. automodule:: isaaclab.sim.schemas + + .. rubric:: Solver-common base classes + + These base classes carry the universal-physics fields that every backend honors. + They live in core ``isaaclab`` and have no backend dependency. For backend-specific + knobs, use the matching subclass in :mod:`isaaclab_physx.sim.schemas` or + :mod:`isaaclab_newton.sim.schemas`. See :doc:`/source/overview/core-concepts/schema_cfgs` + for the full design. + + .. autosummary:: + + ArticulationRootBaseCfg + RigidBodyBaseCfg + CollisionBaseCfg + JointDriveBaseCfg + MeshCollisionBaseCfg + MassPropertiesCfg + JointDrivePropertiesCfg + FixedTendonPropertiesCfg + DeformableBodyPropertiesBaseCfg + + .. rubric:: Mesh collision approximations (USD-only, no PhysX schema) + + .. autosummary:: + + BoundingCubePropertiesCfg + BoundingSpherePropertiesCfg + + .. 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 + define_mesh_collision_properties + modify_mesh_collision_properties + modify_fixed_tendon_properties + define_deformable_body_properties + modify_deformable_body_properties + +Articulation Root +----------------- + +.. autoclass:: ArticulationRootBaseCfg + :members: + :exclude-members: __init__ + +.. autofunction:: define_articulation_root_properties +.. autofunction:: modify_articulation_root_properties + +For PhysX-specific articulation properties (self-collisions, TGS solver iterations, +sleep/stabilization thresholds), see +:class:`~isaaclab_physx.sim.schemas.PhysxArticulationRootPropertiesCfg`. For +Newton-native self-collisions, see +:class:`~isaaclab_newton.sim.schemas.NewtonArticulationRootPropertiesCfg`. + +Rigid Body +---------- + +.. autoclass:: RigidBodyBaseCfg + :members: + :exclude-members: __init__ + +.. autofunction:: define_rigid_body_properties +.. autofunction:: modify_rigid_body_properties +.. autofunction:: activate_contact_sensors + +For PhysX-specific rigid body properties (damping, max velocities, solver iterations, +sleep/stabilization), see :class:`~isaaclab_physx.sim.schemas.PhysxRigidBodyPropertiesCfg`. +For MuJoCo-specific gravity compensation, see +:class:`~isaaclab_newton.sim.schemas.MujocoRigidBodyPropertiesCfg`. + +Collision +--------- + +.. autoclass:: CollisionBaseCfg + :members: + :exclude-members: __init__ + +.. autofunction:: define_collision_properties +.. autofunction:: modify_collision_properties + +For PhysX torsional patch friction, see +:class:`~isaaclab_physx.sim.schemas.PhysxCollisionPropertiesCfg`. For Newton-native +contact margin/gap, see +:class:`~isaaclab_newton.sim.schemas.NewtonCollisionPropertiesCfg`. + +Mass +---- + +.. autoclass:: MassPropertiesCfg + :members: + :exclude-members: __init__ + +.. autofunction:: define_mass_properties +.. autofunction:: modify_mass_properties + +Joint Drive +----------- + +.. autoclass:: JointDriveBaseCfg + :members: + :exclude-members: __init__ + +.. autofunction:: modify_joint_drive_properties + +For PhysX-specific drive properties, see +:class:`~isaaclab_physx.sim.schemas.PhysxJointDrivePropertiesCfg`. For MuJoCo +actuator gravity compensation, see +:class:`~isaaclab_newton.sim.schemas.MujocoJointDrivePropertiesCfg`. + +Mesh Collision +-------------- + +.. autoclass:: MeshCollisionBaseCfg + :members: + :exclude-members: __init__ + +.. autoclass:: BoundingCubePropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: BoundingSpherePropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autofunction:: define_mesh_collision_properties +.. autofunction:: modify_mesh_collision_properties + +For PhysX cooking schemas (convex hull / decomposition / triangle mesh / SDF), +see the ``Physx*PropertiesCfg`` family in :mod:`isaaclab_physx.sim.schemas`. +For Newton hull-vertex limit, see +:class:`~isaaclab_newton.sim.schemas.NewtonMeshCollisionPropertiesCfg`. + +Tendon +------ + +.. autofunction:: modify_fixed_tendon_properties +.. autofunction:: modify_spatial_tendon_properties + +Tendon cfg classes are PhysX-only and live in +:mod:`isaaclab_physx.sim.schemas` +(:class:`~isaaclab_physx.sim.schemas.PhysxFixedTendonPropertiesCfg`, +:class:`~isaaclab_physx.sim.schemas.PhysxSpatialTendonPropertiesCfg`). + +Deformable Body +--------------- + +.. autoclass:: DeformableBodyPropertiesBaseCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autofunction:: define_deformable_body_properties +.. autofunction:: modify_deformable_body_properties diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.spawners.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.spawners.rst new file mode 100644 index 0000000000000000000000000000000000000000..d42fa13e524e1f6941b97e8df4fa2571dac54cd1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.spawners.rst @@ -0,0 +1,365 @@ +isaaclab.sim.spawners +===================== + +.. automodule:: isaaclab.sim.spawners + + .. rubric:: Submodules + + .. autosummary:: + + shapes + meshes + lights + sensors + from_files + materials + wrappers + + .. rubric:: Classes + + .. autosummary:: + + SpawnerCfg + RigidObjectSpawnerCfg + DeformableObjectSpawnerCfg + +Spawners +-------- + +.. autoclass:: SpawnerCfg + :members: + :exclude-members: __init__ + +.. autoclass:: RigidObjectSpawnerCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: DeformableObjectSpawnerCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Shapes +------ + +.. automodule:: isaaclab.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 + +Meshes +------ + +.. automodule:: isaaclab.sim.spawners.meshes + + .. rubric:: Classes + + .. autosummary:: + + MeshCfg + MeshCapsuleCfg + MeshConeCfg + MeshCuboidCfg + MeshCylinderCfg + MeshRectangleCfg + MeshSphereCfg + +.. autoclass:: MeshCfg + :members: + :exclude-members: __init__, func + +.. autofunction:: spawn_mesh_capsule + +.. autoclass:: MeshCapsuleCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autofunction:: spawn_mesh_cone + +.. autoclass:: MeshConeCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autofunction:: spawn_mesh_cuboid + +.. autoclass:: MeshCuboidCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autofunction:: spawn_mesh_cylinder + +.. autoclass:: MeshCylinderCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autofunction:: spawn_mesh_rectangle + +.. autoclass:: MeshRectangleCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autofunction:: spawn_mesh_sphere + +.. autoclass:: MeshSphereCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +Lights +------ + +.. automodule:: isaaclab.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:: isaaclab.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:: isaaclab.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:: isaaclab.sim.spawners.materials + + .. rubric:: Classes + + .. autosummary:: + + VisualMaterialCfg + PreviewSurfaceCfg + MdlFileCfg + GlassMdlCfg + PhysicsMaterialCfg + RigidBodyMaterialCfg + DeformableBodyMaterialBaseCfg + SurfaceDeformableBodyMaterialBaseCfg + DeformableBodyMaterialCfg + SurfaceDeformableBodyMaterialCfg + +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 + +.. autofunction:: spawn_deformable_body_material + +.. autoclass:: DeformableBodyMaterialBaseCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autoclass:: SurfaceDeformableBodyMaterialBaseCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. note:: + + Backend-specific deformable material cfgs live in + :mod:`isaaclab_physx.sim.spawners.materials` and + :mod:`isaaclab_newton.sim.spawners.materials`. The legacy default names below + are forwarded to the deprecated PhysX aliases for compatibility. + +.. autoclass:: DeformableBodyMaterialCfg + :no-index: + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autoclass:: SurfaceDeformableBodyMaterialCfg + :no-index: + :members: + :show-inheritance: + :exclude-members: __init__, func + +Wrappers +-------- + +.. automodule:: isaaclab.sim.spawners.wrappers + + .. rubric:: Classes + + .. autosummary:: + + MultiAssetSpawnerCfg + MultiUsdFileCfg + +.. autofunction:: spawn_multi_asset + +.. autoclass:: MultiAssetSpawnerCfg + :members: + :exclude-members: __init__, func + +.. autofunction:: spawn_multi_usd_file + +.. autoclass:: MultiUsdFileCfg + :members: + :exclude-members: __init__, func diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.utils.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.utils.rst new file mode 100644 index 0000000000000000000000000000000000000000..f27e574efb9a77ffe59730776205c327b92fb111 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.utils.rst @@ -0,0 +1,57 @@ +isaaclab.sim.utils +================== + +.. automodule:: isaaclab.sim.utils + + .. rubric:: Submodules + + .. autosummary:: + + stage + queries + prims + transforms + semantics + legacy + +Stage +----- + +.. automodule:: isaaclab.sim.utils.stage + :members: + :show-inheritance: + +Queries +------- + +.. automodule:: isaaclab.sim.utils.queries + :members: + :show-inheritance: + +Prims +----- + +.. automodule:: isaaclab.sim.utils.prims + :members: + :show-inheritance: + +Transforms +---------- + +.. automodule:: isaaclab.sim.utils.transforms + :members: + :show-inheritance: + +Semantics +--------- + +.. automodule:: isaaclab.sim.utils.semantics + :members: + :show-inheritance: + +Legacy +------ + +.. automodule:: isaaclab.sim.utils.legacy + :members: + :show-inheritance: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.views.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.views.rst new file mode 100644 index 0000000000000000000000000000000000000000..e06c4e54a246ddb0dc708b414ed787334c664643 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.sim.views.rst @@ -0,0 +1,33 @@ +isaaclab.sim.views +================== + +.. automodule:: isaaclab.sim.views + + .. rubric:: Classes + + .. autosummary:: + + BaseFrameView + UsdFrameView + FrameView + +Base Frame View +--------------- + +.. autoclass:: BaseFrameView + :members: + :show-inheritance: + +USD Frame View +-------------- + +.. autoclass:: UsdFrameView + :members: + :show-inheritance: + +Frame View +---------- + +.. autoclass:: FrameView + :members: + :show-inheritance: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.terrains.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.terrains.rst new file mode 100644 index 0000000000000000000000000000000000000000..8e0e80cb4543e9fb814e83d66efb8323ecf7c517 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.terrains.rst @@ -0,0 +1,261 @@ +isaaclab.terrains +================= + +.. automodule:: isaaclab.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:: isaaclab.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:: isaaclab.terrains.height_field.hf_terrains_cfg.HfTerrainBaseCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Random Uniform Terrain +^^^^^^^^^^^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.height_field.hf_terrains.random_uniform_terrain + +.. autoclass:: isaaclab.terrains.height_field.hf_terrains_cfg.HfRandomUniformTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Pyramid Sloped Terrain +^^^^^^^^^^^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.height_field.hf_terrains.pyramid_sloped_terrain + +.. autoclass:: isaaclab.terrains.height_field.hf_terrains_cfg.HfPyramidSlopedTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +.. autoclass:: isaaclab.terrains.height_field.hf_terrains_cfg.HfInvertedPyramidSlopedTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Pyramid Stairs Terrain +^^^^^^^^^^^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.height_field.hf_terrains.pyramid_stairs_terrain + +.. autoclass:: isaaclab.terrains.height_field.hf_terrains_cfg.HfPyramidStairsTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +.. autoclass:: isaaclab.terrains.height_field.hf_terrains_cfg.HfInvertedPyramidStairsTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Discrete Obstacles Terrain +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.height_field.hf_terrains.discrete_obstacles_terrain + +.. autoclass:: isaaclab.terrains.height_field.hf_terrains_cfg.HfDiscreteObstaclesTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Wave Terrain +^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.height_field.hf_terrains.wave_terrain + +.. autoclass:: isaaclab.terrains.height_field.hf_terrains_cfg.HfWaveTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Stepping Stones Terrain +^^^^^^^^^^^^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.height_field.hf_terrains.stepping_stones_terrain + +.. autoclass:: isaaclab.terrains.height_field.hf_terrains_cfg.HfSteppingStonesTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Trimesh terrains +---------------- + +.. automodule:: isaaclab.terrains.trimesh + + +Flat terrain +^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.trimesh.mesh_terrains.flat_terrain + +.. autoclass:: isaaclab.terrains.trimesh.mesh_terrains_cfg.MeshPlaneTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Pyramid terrain +^^^^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.trimesh.mesh_terrains.pyramid_stairs_terrain + +.. autoclass:: isaaclab.terrains.trimesh.mesh_terrains_cfg.MeshPyramidStairsTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Inverted pyramid terrain +^^^^^^^^^^^^^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.trimesh.mesh_terrains.inverted_pyramid_stairs_terrain + +.. autoclass:: isaaclab.terrains.trimesh.mesh_terrains_cfg.MeshInvertedPyramidStairsTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Random grid terrain +^^^^^^^^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.trimesh.mesh_terrains.random_grid_terrain + +.. autoclass:: isaaclab.terrains.trimesh.mesh_terrains_cfg.MeshRandomGridTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Rails terrain +^^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.trimesh.mesh_terrains.rails_terrain + +.. autoclass:: isaaclab.terrains.trimesh.mesh_terrains_cfg.MeshRailsTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Pit terrain +^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.trimesh.mesh_terrains.pit_terrain + +.. autoclass:: isaaclab.terrains.trimesh.mesh_terrains_cfg.MeshPitTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Box terrain +^^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.trimesh.mesh_terrains.box_terrain + +.. autoclass:: isaaclab.terrains.trimesh.mesh_terrains_cfg.MeshBoxTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Gap terrain +^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.trimesh.mesh_terrains.gap_terrain + +.. autoclass:: isaaclab.terrains.trimesh.mesh_terrains_cfg.MeshGapTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Floating ring terrain +^^^^^^^^^^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.trimesh.mesh_terrains.floating_ring_terrain + +.. autoclass:: isaaclab.terrains.trimesh.mesh_terrains_cfg.MeshFloatingRingTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Star terrain +^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.trimesh.mesh_terrains.star_terrain + +.. autoclass:: isaaclab.terrains.trimesh.mesh_terrains_cfg.MeshStarTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Repeated Objects Terrain +^^^^^^^^^^^^^^^^^^^^^^^^ + +.. autofunction:: isaaclab.terrains.trimesh.mesh_terrains.repeated_objects_terrain + +.. autoclass:: isaaclab.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedObjectsTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +.. autoclass:: isaaclab.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedPyramidsTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +.. autoclass:: isaaclab.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedBoxesTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +.. autoclass:: isaaclab.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedCylindersTerrainCfg + :members: + :show-inheritance: + :exclude-members: __init__, function + +Utilities +--------- + +.. automodule:: isaaclab.terrains.utils + :members: + :undoc-members: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.utils.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.utils.rst new file mode 100644 index 0000000000000000000000000000000000000000..5b352152e0b542e22d7a5bd8e2d87bbd5e884bce --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.utils.rst @@ -0,0 +1,190 @@ +isaaclab.utils +============== + +.. automodule:: isaaclab.utils + + .. Rubric:: Submodules + + .. autosummary:: + + io + array + assets + buffers + datasets + dict + interpolation + logger + math + mesh + modifiers + noise + seed + sensors + string + timer + types + version + warp + + .. Rubric:: Functions + + .. autosummary:: + + configclass + +Configuration class +~~~~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.configclass + :members: + :show-inheritance: + +IO operations +~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.io + :members: + :imported-members: + :show-inheritance: + +Array operations +~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.array + :members: + :show-inheritance: + +Asset operations +~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.assets + :members: + :show-inheritance: + +Buffer operations +~~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.buffers + :members: + :imported-members: + :inherited-members: + :show-inheritance: + +Datasets operations +~~~~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.datasets + :members: + :show-inheritance: + :exclude-members: __init__, func + +Dictionary operations +~~~~~~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.dict + :members: + :show-inheritance: + +Interpolation operations +~~~~~~~~~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.interpolation + :members: + :imported-members: + :inherited-members: + :show-inheritance: + +Logger operations +~~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.logger + :members: + :show-inheritance: + +Math operations +~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.math + :members: + :inherited-members: + :show-inheritance: + +Mesh operations +~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.mesh + :members: + :imported-members: + :show-inheritance: + +Modifier operations +~~~~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.modifiers + :members: + :imported-members: + :special-members: __call__ + :inherited-members: + :show-inheritance: + :exclude-members: __init__, func + +Noise operations +~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.noise + :members: + :imported-members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, func + +Seed operations +~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.seed + :members: + :show-inheritance: + +Sensor operations +~~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.sensors + :members: + :show-inheritance: + +String operations +~~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.string + :members: + :show-inheritance: + +Timer operations +~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.timer + :members: + :show-inheritance: + +Type operations +~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.types + :members: + :show-inheritance: + +Version operations +~~~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.version + :members: + :show-inheritance: + +Warp operations +~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab.utils.warp + :members: + :imported-members: + :show-inheritance: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.visualizers.rst b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.visualizers.rst new file mode 100644 index 0000000000000000000000000000000000000000..d526a331375c1759a1c90ab72e4d50737bad313f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab/isaaclab.visualizers.rst @@ -0,0 +1,4 @@ +isaaclab.visualizers +==================== + +.. automodule:: isaaclab.visualizers diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_assets/isaaclab_assets.robots.rst b/simulation/modules/IsaacLab/docs/source/api/lab_assets/isaaclab_assets.robots.rst new file mode 100644 index 0000000000000000000000000000000000000000..91e2e96ae653011a5c97f457997aec26779e9fe2 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_assets/isaaclab_assets.robots.rst @@ -0,0 +1,4 @@ +isaaclab\_assets.robots +======================= + +.. automodule:: isaaclab_assets.robots diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_assets/isaaclab_assets.sensors.rst b/simulation/modules/IsaacLab/docs/source/api/lab_assets/isaaclab_assets.sensors.rst new file mode 100644 index 0000000000000000000000000000000000000000..aa54f42a4e9aa729de995fb062ac4edbdf410156 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_assets/isaaclab_assets.sensors.rst @@ -0,0 +1,4 @@ +isaaclab\_assets.sensors +======================== + +.. automodule:: isaaclab_assets.sensors diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.actuators.rst b/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.actuators.rst new file mode 100644 index 0000000000000000000000000000000000000000..1171c31e5eaff8b510ef5d899674df0a77680743 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.actuators.rst @@ -0,0 +1,25 @@ +isaaclab_contrib.actuators +============================= + +.. automodule:: isaaclab_contrib.actuators + + .. rubric:: Classes + + .. autosummary:: + + Thruster + ThrusterCfg + +Thruster Actuator +----------------- + +.. autoclass:: Thruster + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: ThrusterCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.assets.rst b/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.assets.rst new file mode 100644 index 0000000000000000000000000000000000000000..24375f918c8fa389b00ceb6bff48df2048991775 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.assets.rst @@ -0,0 +1,31 @@ +isaaclab_contrib.assets +========================== + +.. automodule:: isaaclab_contrib.assets + + .. rubric:: Classes + + .. autosummary:: + + Multirotor + MultirotorCfg + MultirotorData + +Multirotor Asset +---------------- + +.. autoclass:: Multirotor + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: MultirotorCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +.. autoclass:: MultirotorData + :members: + :inherited-members: + :show-inheritance: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.controllers.rst b/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.controllers.rst new file mode 100644 index 0000000000000000000000000000000000000000..c76804d4b463fe437d6e4791deaad1c9be47a5b0 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.controllers.rst @@ -0,0 +1,88 @@ +isaaclab_contrib.controllers +============================ + +.. automodule:: isaaclab_contrib.controllers + + .. rubric:: Classes + + .. autosummary:: + + LeeControllerBase + LeeControllerBaseCfg + LeeAccController + LeeAccControllerCfg + LeeAttController + LeeAttControllerCfg + LeePosController + LeePosControllerCfg + LeeVelController + LeeVelControllerCfg + +Lee Base Controller +-------------------- + +.. autoclass:: LeeControllerBase + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: LeeControllerBaseCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Lee Acceleration Controller +---------------------------- + +.. autoclass:: LeeAccController + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: LeeAccControllerCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Lee Attitude Controller +------------------------- +.. autoclass:: LeeAttController + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: LeeAttControllerCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Lee Position Controller +----------------------- + +.. autoclass:: LeePosController + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: LeePosControllerCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Lee Velocity Controller +----------------------- + +.. autoclass:: LeeVelController + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: LeeVelControllerCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.deformable.rst b/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.deformable.rst new file mode 100644 index 0000000000000000000000000000000000000000..0267a922c5c8b15adadfc4bb332d5cb2cd4ae685 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.deformable.rst @@ -0,0 +1,73 @@ +isaaclab_contrib.deformable +=========================== + +.. automodule:: isaaclab_contrib.deformable + + .. rubric:: Classes + + .. autosummary:: + + deformable_object.DeformableObject + deformable_object_data.DeformableObjectData + newton_manager_cfg.VBDSolverCfg + newton_manager_cfg.CoupledMJWarpVBDSolverCfg + newton_manager_cfg.CoupledFeatherstoneVBDSolverCfg + newton_manager_cfg.NewtonModelCfg + vbd_manager.NewtonVBDManager + coupled_mjwarp_vbd_manager.NewtonCoupledMJWarpVBDManager + coupled_featherstone_vbd_manager.NewtonCoupledFeatherstoneVBDManager + +Deformable Object +----------------- + +.. autoclass:: isaaclab_contrib.deformable.deformable_object.DeformableObject + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: isaaclab_contrib.deformable.deformable_object_data.DeformableObjectData + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ + +Newton Solver Configurations +---------------------------- + +.. autoclass:: isaaclab_contrib.deformable.newton_manager_cfg.VBDSolverCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: isaaclab_contrib.deformable.newton_manager_cfg.CoupledMJWarpVBDSolverCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: isaaclab_contrib.deformable.newton_manager_cfg.CoupledFeatherstoneVBDSolverCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: isaaclab_contrib.deformable.newton_manager_cfg.NewtonModelCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Newton Solver Managers +---------------------- + +.. autoclass:: isaaclab_contrib.deformable.vbd_manager.NewtonVBDManager + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: isaaclab_contrib.deformable.coupled_mjwarp_vbd_manager.NewtonCoupledMJWarpVBDManager + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: isaaclab_contrib.deformable.coupled_featherstone_vbd_manager.NewtonCoupledFeatherstoneVBDManager + :members: + :inherited-members: + :show-inheritance: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.mdp.rst b/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.mdp.rst new file mode 100644 index 0000000000000000000000000000000000000000..32421ef9b1f88942ae5caaa0098d4ab88aff65df --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.mdp.rst @@ -0,0 +1,33 @@ +isaaclab_contrib.mdp +======================= + +.. automodule:: isaaclab_contrib.mdp + +Actions +------- + +.. automodule:: isaaclab_contrib.mdp.actions + + .. rubric:: Classes + + .. autosummary:: + + ThrustActionCfg + ThrustAction + +Thrust Action Configuration +--------------------------- + +.. autoclass:: isaaclab_contrib.mdp.actions.thrust_actions_cfg.ThrustActionCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Thrust Action Implementation +---------------------------- + +.. autoclass:: isaaclab_contrib.mdp.actions.thrust_actions.ThrustAction + :members: + :inherited-members: + :show-inheritance: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.rl.rst b/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.rl.rst new file mode 100644 index 0000000000000000000000000000000000000000..408443ef46b9ecc49b4bfde3555fb0e6f4425c5f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.rl.rst @@ -0,0 +1,63 @@ +isaaclab\_contrib.rl +==================== + +.. automodule:: isaaclab_contrib.rl + +Submodules +---------- + +isaaclab\_contrib.rl.rlinf +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. automodule:: isaaclab_contrib.rl.rlinf + +.. note:: + + The extension module requires the external ``rlinf`` package and cannot be + introspected at documentation build time. The API is described textually below. + +Extension Module +^^^^^^^^^^^^^^^^ + +The extension module (``isaaclab_contrib.rl.rlinf.extension``) is loaded by RLinf's +worker framework via the ``RLINF_EXT_MODULE`` environment variable. It is not imported +directly by user code. + +**Setup:** + +.. code-block:: bash + + export RLINF_EXT_MODULE="isaaclab_contrib.rl.rlinf.extension" + export RLINF_CONFIG_FILE="/path/to/config.yaml" + +**Public entry point:** + +- ``register()`` -- Called by RLinf's worker to perform all setup. It: + + 1. Registers GR00T observation and action converters. + 2. Patches GR00T's ``get_model`` for custom embodiment tags. + 3. Registers IsaacLab tasks into RLinf's ``REGISTER_ISAACLAB_ENVS`` registry. + +**Expected YAML configuration** (under ``env.train.isaaclab``): + +.. code-block:: yaml + + env: + train: + isaaclab: &isaaclab_config + task_description: "Assemble trocar with dual-arm robot" + main_images: "front_camera" + extra_view_images: ["left_wrist_camera", "right_wrist_camera"] + states: + - key: "robot_joint_state" + slice: [15, 29] + gr00t_mapping: + video: + main_images: "video.room_view" + action_mapping: + prefix_pad: 15 + eval: + isaaclab: *isaaclab_config # Reuse via YAML anchor + +Task IDs are read automatically from ``env.train.init_params.id`` and +``env.eval.init_params.id`` in the YAML config. diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.sensors.rst b/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.sensors.rst new file mode 100644 index 0000000000000000000000000000000000000000..efcdeffe239b736e231435193a4e219a798de139 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_contrib/isaaclab_contrib.sensors.rst @@ -0,0 +1,39 @@ +isaaclab_contrib.sensors +======================== + +.. automodule:: isaaclab_contrib.sensors + + .. rubric:: Classes + + .. autosummary:: + + VisuoTactileSensor + VisuoTactileSensorCfg + VisuoTactileSensorData + GelSightRenderCfg + + +Visuo-Tactile Sensor +-------------------- + +.. autoclass:: VisuoTactileSensor + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: VisuoTactileSensorData + :members: + :inherited-members: + :exclude-members: __init__ + +.. autoclass:: VisuoTactileSensorCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +.. autoclass:: GelSightRenderCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_experimental/isaaclab_experimental.envs.rst b/simulation/modules/IsaacLab/docs/source/api/lab_experimental/isaaclab_experimental.envs.rst new file mode 100644 index 0000000000000000000000000000000000000000..6e87a9a17cb9810293fced548d5f50319aeff71f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_experimental/isaaclab_experimental.envs.rst @@ -0,0 +1,4 @@ +isaaclab\_experimental.envs +=========================== + +.. automodule:: isaaclab_experimental.envs diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_experimental/isaaclab_experimental.managers.rst b/simulation/modules/IsaacLab/docs/source/api/lab_experimental/isaaclab_experimental.managers.rst new file mode 100644 index 0000000000000000000000000000000000000000..c0f56ed1a6a79f944e913fb3e9972d5f00f0a9b1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_experimental/isaaclab_experimental.managers.rst @@ -0,0 +1,4 @@ +isaaclab\_experimental.managers +=============================== + +.. automodule:: isaaclab_experimental.managers diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_experimental/isaaclab_experimental.utils.rst b/simulation/modules/IsaacLab/docs/source/api/lab_experimental/isaaclab_experimental.utils.rst new file mode 100644 index 0000000000000000000000000000000000000000..49d7bd6dcdb93196d9fbd2da169d9f28ebfb0c21 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_experimental/isaaclab_experimental.utils.rst @@ -0,0 +1,4 @@ +isaaclab\_experimental.utils +============================ + +.. automodule:: isaaclab_experimental.utils diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_mimic/isaaclab_mimic.datagen.rst b/simulation/modules/IsaacLab/docs/source/api/lab_mimic/isaaclab_mimic.datagen.rst new file mode 100644 index 0000000000000000000000000000000000000000..73b4c4feba146218abc1e98a6194fc85bbf68892 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_mimic/isaaclab_mimic.datagen.rst @@ -0,0 +1,82 @@ +isaaclab_mimic.datagen +====================== + +.. automodule:: isaaclab_mimic.datagen + + .. rubric:: Classes + + .. autosummary:: + + DataGenerator + DatagenInfo + DataGenInfoPool + SelectionStrategy + RandomStrategy + NearestNeighborObjectStrategy + NearestNeighborRobotDistanceStrategy + Waypoint + WaypointSequence + WaypointTrajectory + +Data Generator +-------------- + +.. autoclass:: DataGenerator + :members: + :inherited-members: + +Datagen Info +------------ + +.. autoclass:: DatagenInfo + :members: + :inherited-members: + +Datagen Info Pool +----------------- + +.. autoclass:: DataGenInfoPool + :members: + :inherited-members: + +Random Strategy +--------------- + +.. autoclass:: RandomStrategy + :members: + :inherited-members: + +Nearest Neighbor Object Strategy +-------------------------------- + +.. autoclass:: NearestNeighborObjectStrategy + :members: + :inherited-members: + +Nearest Neighbor Robot Distance Strategy +---------------------------------------- + +.. autoclass:: NearestNeighborRobotDistanceStrategy + :members: + :inherited-members: + +Waypoint +-------- + +.. autoclass:: Waypoint + :members: + :inherited-members: + +Waypoint Sequence +----------------- + +.. autoclass:: WaypointSequence + :members: + :inherited-members: + +Waypoint Trajectory +------------------- + +.. autoclass:: WaypointTrajectory + :members: + :inherited-members: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_mimic/isaaclab_mimic.envs.rst b/simulation/modules/IsaacLab/docs/source/api/lab_mimic/isaaclab_mimic.envs.rst new file mode 100644 index 0000000000000000000000000000000000000000..9b04d4c0066d5cecd9933a58abed7f992993b443 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_mimic/isaaclab_mimic.envs.rst @@ -0,0 +1,144 @@ +isaaclab_mimic.envs +=================== + +.. automodule:: isaaclab_mimic.envs + + .. rubric:: Classes + + .. autosummary:: + + franka_stack_ik_rel_mimic_env.FrankaCubeStackIKRelMimicEnv + franka_stack_ik_rel_mimic_env_cfg.FrankaCubeStackIKRelMimicEnvCfg + franka_stack_ik_abs_mimic_env.FrankaCubeStackIKAbsMimicEnv + franka_stack_ik_abs_mimic_env_cfg.FrankaCubeStackIKAbsMimicEnvCfg + galbot_stack_rmp_rel_mimic_env.RmpFlowGalbotCubeStackRelMimicEnv + galbot_stack_rmp_rel_mimic_env_cfg.RmpFlowGalbotLeftArmGripperCubeStackRelMimicEnvCfg + galbot_stack_rmp_rel_mimic_env_cfg.RmpFlowGalbotRightArmSuctionCubeStackRelMimicEnvCfg + galbot_stack_rmp_abs_mimic_env.RmpFlowGalbotCubeStackAbsMimicEnv + galbot_stack_rmp_abs_mimic_env_cfg.RmpFlowGalbotLeftArmGripperCubeStackAbsMimicEnvCfg + galbot_stack_rmp_abs_mimic_env_cfg.RmpFlowGalbotRightArmSuctionCubeStackAbsMimicEnvCfg + pick_place_mimic_env.PickPlaceRelMimicEnv + pick_place_mimic_env.PickPlaceAbsMimicEnv + agibot_place_upright_mug_mimic_env_cfg.RmpFlowAgibotPlaceUprightMugMimicEnvCfg + agibot_place_toy2box_mimic_env_cfg.RmpFlowAgibotPlaceToy2BoxMimicEnvCfg + +Franka Environments +------------------- + +Franka Cube Stack IK Rel Mimic Env +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: isaaclab_mimic.envs.franka_stack_ik_rel_mimic_env.FrankaCubeStackIKRelMimicEnv + :members: + :inherited-members: + :show-inheritance: + +Franka Cube Stack IK Rel Mimic Env Cfg +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: isaaclab_mimic.envs.franka_stack_ik_rel_mimic_env_cfg.FrankaCubeStackIKRelMimicEnvCfg + :members: + :inherited-members: + :show-inheritance: + +Franka Cube Stack IK Abs Mimic Env +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: isaaclab_mimic.envs.franka_stack_ik_abs_mimic_env.FrankaCubeStackIKAbsMimicEnv + :members: + :inherited-members: + :show-inheritance: + +Franka Cube Stack IK Abs Mimic Env Cfg +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: isaaclab_mimic.envs.franka_stack_ik_abs_mimic_env_cfg.FrankaCubeStackIKAbsMimicEnvCfg + :members: + :inherited-members: + :show-inheritance: + +Galbot Environments +------------------- + +Galbot Cube Stack Rel Mimic Env (RmpFlow) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: isaaclab_mimic.envs.galbot_stack_rmp_rel_mimic_env.RmpFlowGalbotCubeStackRelMimicEnv + :members: + :inherited-members: + :show-inheritance: + +Galbot Left Arm Gripper Cube Stack Rel Mimic Env Cfg +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: isaaclab_mimic.envs.galbot_stack_rmp_rel_mimic_env_cfg.RmpFlowGalbotLeftArmGripperCubeStackRelMimicEnvCfg + :members: + :inherited-members: + :show-inheritance: + +Galbot Right Arm Suction Cube Stack Rel Mimic Env Cfg +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: isaaclab_mimic.envs.galbot_stack_rmp_rel_mimic_env_cfg.RmpFlowGalbotRightArmSuctionCubeStackRelMimicEnvCfg + :members: + :inherited-members: + :show-inheritance: + +Galbot Cube Stack Abs Mimic Env (RmpFlow) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: isaaclab_mimic.envs.galbot_stack_rmp_abs_mimic_env.RmpFlowGalbotCubeStackAbsMimicEnv + :members: + :inherited-members: + :show-inheritance: + +Galbot Left Arm Gripper Cube Stack Abs Mimic Env Cfg +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: isaaclab_mimic.envs.galbot_stack_rmp_abs_mimic_env_cfg.RmpFlowGalbotLeftArmGripperCubeStackAbsMimicEnvCfg + :members: + :inherited-members: + :show-inheritance: + +Galbot Right Arm Suction Cube Stack Abs Mimic Env Cfg +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: isaaclab_mimic.envs.galbot_stack_rmp_abs_mimic_env_cfg.RmpFlowGalbotRightArmSuctionCubeStackAbsMimicEnvCfg + :members: + :inherited-members: + :show-inheritance: + +Agibot Environments +------------------- + +Pick Place Rel Mimic Env +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: isaaclab_mimic.envs.pick_place_mimic_env.PickPlaceRelMimicEnv + :members: + :inherited-members: + :show-inheritance: + +Pick Place Abs Mimic Env +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: isaaclab_mimic.envs.pick_place_mimic_env.PickPlaceAbsMimicEnv + :members: + :inherited-members: + :show-inheritance: + +Agibot Place Upright Mug Mimic Env Cfg +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: isaaclab_mimic.envs.agibot_place_upright_mug_mimic_env_cfg.RmpFlowAgibotPlaceUprightMugMimicEnvCfg + :members: + :inherited-members: + :show-inheritance: + +Agibot Place Toy2Box Mimic Env Cfg +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: isaaclab_mimic.envs.agibot_place_toy2box_mimic_env_cfg.RmpFlowAgibotPlaceToy2BoxMimicEnvCfg + :members: + :inherited-members: + :show-inheritance: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.assets.rst b/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.assets.rst new file mode 100644 index 0000000000000000000000000000000000000000..f044f9b089fb4411c9bcfd895ab2ccbc292db0ba --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.assets.rst @@ -0,0 +1,83 @@ +isaaclab\_newton.assets +======================= + +.. automodule:: isaaclab_newton.assets + + .. rubric:: Classes + + .. autosummary:: + + Articulation + ArticulationData + RigidObject + RigidObjectData + RigidObjectCollection + RigidObjectCollectionData + DeformableObject + DeformableObjectData + +.. currentmodule:: isaaclab_newton.assets + +Articulation +------------ + +.. autoclass:: Articulation + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: ArticulationData + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ + +Rigid Object +------------ + +.. autoclass:: RigidObject + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: RigidObjectData + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ + +Rigid Object Collection +----------------------- + +.. autoclass:: RigidObjectCollection + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: RigidObjectCollectionData + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ + +Deformable Object +----------------- + +.. note:: + + :class:`isaaclab.assets.DeformableObjectCfg` is the shared configuration + class for deformable objects. The Newton extension exposes the Newton + implementation of :class:`isaaclab.assets.DeformableObject`, while + deformable schema and material cfgs referenced by ``spawn`` remain + backend-specific. + +.. autoclass:: DeformableObject + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: DeformableObjectData + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.cloner.rst b/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.cloner.rst new file mode 100644 index 0000000000000000000000000000000000000000..721d95f375bb5de0bbc7b3aff2b029db84b6bdd3 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.cloner.rst @@ -0,0 +1,4 @@ +isaaclab\_newton.cloner +======================= + +.. automodule:: isaaclab_newton.cloner diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.physics.rst b/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.physics.rst new file mode 100644 index 0000000000000000000000000000000000000000..b452f3ad538b0ee8c1a875bcf16c824582be4592 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.physics.rst @@ -0,0 +1,104 @@ +isaaclab\_newton.physics +======================== + +.. automodule:: isaaclab_newton.physics + + .. rubric:: Classes + + .. autosummary:: + + NewtonManager + NewtonCfg + NewtonSolverCfg + MJWarpSolverCfg + XPBDSolverCfg + FeatherstoneSolverCfg + KaminoSolverCfg + NewtonCollisionPipelineCfg + HydroelasticSDFCfg + NewtonShapeCfg + NewtonMJWarpManager + NewtonXPBDManager + NewtonFeatherstoneManager + NewtonKaminoManager + +.. currentmodule:: isaaclab_newton.physics + +Physics Manager +--------------- + +.. autoclass:: NewtonManager + :members: + :inherited-members: + :show-inheritance: + +Physics Configuration +--------------------- + +.. autoclass:: NewtonCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: NewtonSolverCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: MJWarpSolverCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: XPBDSolverCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: FeatherstoneSolverCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: KaminoSolverCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: NewtonCollisionPipelineCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: HydroelasticSDFCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: NewtonShapeCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Solver Managers +--------------- + +.. autoclass:: NewtonMJWarpManager + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: NewtonXPBDManager + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: NewtonFeatherstoneManager + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: NewtonKaminoManager + :members: + :inherited-members: + :show-inheritance: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.renderers.rst b/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.renderers.rst new file mode 100644 index 0000000000000000000000000000000000000000..ca22ed5e83583497a2099083f0bbb5f4946766f0 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.renderers.rst @@ -0,0 +1,4 @@ +isaaclab\_newton.renderers +========================== + +.. automodule:: isaaclab_newton.renderers diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.sensors.rst b/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.sensors.rst new file mode 100644 index 0000000000000000000000000000000000000000..f2c7ff5dacceac02ab97f5f55889b1846c4ec22d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.sensors.rst @@ -0,0 +1,4 @@ +isaaclab\_newton.sensors +======================== + +.. automodule:: isaaclab_newton.sensors diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.sim.schemas.rst b/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.sim.schemas.rst new file mode 100644 index 0000000000000000000000000000000000000000..78fb53b7098cca34abf3dc28e0ce6f3bc0f630b0 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.sim.schemas.rst @@ -0,0 +1,100 @@ +isaaclab_newton.sim.schemas +=========================== + +.. automodule:: isaaclab_newton.sim.schemas + + Newton-targeted schema configuration classes. Each cfg below extends a + solver-common base in :mod:`isaaclab.sim.schemas` with Newton-namespaced + attributes (``newton:*``) or solver-specific attributes (``mjc:*`` for + Newton's MuJoCo solver). MuJoCo cfgs subclass their Newton counterpart + because MuJoCo is one of Newton's solver options. + + See :doc:`/source/overview/core-concepts/schema_cfgs` for the design and + when to use each class. + + .. rubric:: Newton-targeted (family roots) + + .. autosummary:: + + NewtonDeformableBodyPropertiesCfg + NewtonRigidBodyPropertiesCfg + NewtonJointDrivePropertiesCfg + NewtonCollisionPropertiesCfg + NewtonMeshCollisionPropertiesCfg + NewtonMaterialPropertiesCfg + NewtonArticulationRootPropertiesCfg + + .. rubric:: MuJoCo-solver-specific + + .. autosummary:: + + MujocoRigidBodyPropertiesCfg + MujocoJointDrivePropertiesCfg + +.. currentmodule:: isaaclab_newton.sim.schemas + +Deformable Body +--------------- + +.. autoclass:: NewtonDeformableBodyPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Schema define and modify functions remain unified in +:mod:`isaaclab.sim.schemas`. + +Rigid Body +---------- + +.. autoclass:: NewtonRigidBodyPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: MujocoRigidBodyPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Joint Drive +----------- + +.. autoclass:: NewtonJointDrivePropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: MujocoJointDrivePropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Collision +--------- + +.. autoclass:: NewtonCollisionPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: NewtonMeshCollisionPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Material +-------- + +.. autoclass:: NewtonMaterialPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Articulation Root +----------------- + +.. autoclass:: NewtonArticulationRootPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.sim.spawners.rst b/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.sim.spawners.rst new file mode 100644 index 0000000000000000000000000000000000000000..d60b953ce5c85594059f39aae253b72d5555eac1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_newton/isaaclab_newton.sim.spawners.rst @@ -0,0 +1,33 @@ +isaaclab_newton.sim.spawners +============================ + +.. automodule:: isaaclab_newton.sim.spawners.materials + + .. rubric:: Classes + + .. autosummary:: + + NewtonDeformableBodyMaterialCfg + NewtonDeformableMaterialCfg + NewtonSurfaceDeformableBodyMaterialCfg + +Deformable Materials +-------------------- + +Newton provides the backend-specific deformable material cfgs. Deformable material spawning is unified in +:func:`isaaclab.sim.spawners.materials.spawn_deformable_body_material`. + +.. autoclass:: NewtonDeformableBodyMaterialCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autoclass:: NewtonDeformableMaterialCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autoclass:: NewtonSurfaceDeformableBodyMaterialCfg + :members: + :show-inheritance: + :exclude-members: __init__, func diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_ov/isaaclab_ov.renderers.rst b/simulation/modules/IsaacLab/docs/source/api/lab_ov/isaaclab_ov.renderers.rst new file mode 100644 index 0000000000000000000000000000000000000000..13a0212dec4b3e049137938afe98f0ecf3cb11b6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_ov/isaaclab_ov.renderers.rst @@ -0,0 +1,4 @@ +isaaclab\_ov.renderers +====================== + +.. automodule:: isaaclab_ov.renderers diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_ovphysx/isaaclab_ovphysx.assets.rst b/simulation/modules/IsaacLab/docs/source/api/lab_ovphysx/isaaclab_ovphysx.assets.rst new file mode 100644 index 0000000000000000000000000000000000000000..165c12772c06c25de26a5ee0abcdc88040298301 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_ovphysx/isaaclab_ovphysx.assets.rst @@ -0,0 +1,4 @@ +isaaclab\_ovphysx.assets +======================== + +.. automodule:: isaaclab_ovphysx.assets diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_ovphysx/isaaclab_ovphysx.cloner.rst b/simulation/modules/IsaacLab/docs/source/api/lab_ovphysx/isaaclab_ovphysx.cloner.rst new file mode 100644 index 0000000000000000000000000000000000000000..7467364b075d84d3d308441d8cfa32ac825650d8 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_ovphysx/isaaclab_ovphysx.cloner.rst @@ -0,0 +1,4 @@ +isaaclab\_ovphysx.cloner +======================== + +.. automodule:: isaaclab_ovphysx.cloner diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_ovphysx/isaaclab_ovphysx.physics.rst b/simulation/modules/IsaacLab/docs/source/api/lab_ovphysx/isaaclab_ovphysx.physics.rst new file mode 100644 index 0000000000000000000000000000000000000000..aa8c37a4af5793c764972b4be43fbc1a2d7e3a4d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_ovphysx/isaaclab_ovphysx.physics.rst @@ -0,0 +1,4 @@ +isaaclab\_ovphysx.physics +========================= + +.. automodule:: isaaclab_ovphysx.physics diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.assets.rst b/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.assets.rst new file mode 100644 index 0000000000000000000000000000000000000000..851a01f9b6e089336e812898b8941e7339dd35c1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.assets.rst @@ -0,0 +1,100 @@ +isaaclab_physx.assets +===================== + +.. automodule:: isaaclab_physx.assets + :noindex: + + .. rubric:: Classes + + .. autosummary:: + + Articulation + ArticulationData + RigidObject + RigidObjectData + RigidObjectCollection + RigidObjectCollectionData + DeformableObject + DeformableObjectData + SurfaceGripper + SurfaceGripperCfg + +.. currentmodule:: isaaclab_physx.assets + +Articulation +------------ + +.. autoclass:: Articulation + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: ArticulationData + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ + +Rigid Object +------------ + +.. autoclass:: RigidObject + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: RigidObjectData + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ + +Rigid Object Collection +----------------------- + +.. autoclass:: RigidObjectCollection + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: RigidObjectCollectionData + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ + +Deformable Object +----------------- + +.. autoclass:: DeformableObject + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: DeformableObjectData + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ + +.. note:: + + :class:`isaaclab.assets.DeformableObjectCfg` is the shared configuration + class for deformable objects. The PhysX extension provides the PhysX + implementation of :class:`isaaclab.assets.DeformableObject`, while + deformable schema and material cfgs referenced by ``spawn`` remain + backend-specific. + +Surface Gripper +--------------- + +.. autoclass:: SurfaceGripper + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: SurfaceGripperCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type, InitialStateCfg diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.cloner.rst b/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.cloner.rst new file mode 100644 index 0000000000000000000000000000000000000000..9a179cf1fb44773029d2a7c0a67da4013d33fedc --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.cloner.rst @@ -0,0 +1,4 @@ +isaaclab\_physx.cloner +====================== + +.. automodule:: isaaclab_physx.cloner diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.physics.rst b/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.physics.rst new file mode 100644 index 0000000000000000000000000000000000000000..7e3017a7ee84b0ca982a7b12e7df17ba296b474d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.physics.rst @@ -0,0 +1,4 @@ +isaaclab\_physx.physics +======================= + +.. automodule:: isaaclab_physx.physics diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.renderers.rst b/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.renderers.rst new file mode 100644 index 0000000000000000000000000000000000000000..66f6a340f2e746451eab799342964af644e0a729 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.renderers.rst @@ -0,0 +1,4 @@ +isaaclab\_physx.renderers +========================= + +.. automodule:: isaaclab_physx.renderers diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.sensors.rst b/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.sensors.rst new file mode 100644 index 0000000000000000000000000000000000000000..506d35bc0569724235a47e0c9d622f17bf4b53a0 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.sensors.rst @@ -0,0 +1,4 @@ +isaaclab\_physx.sensors +======================= + +.. automodule:: isaaclab_physx.sensors diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.sim.schemas.rst b/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.sim.schemas.rst new file mode 100644 index 0000000000000000000000000000000000000000..7a01585545da10c6e69c3ad85969b61d487ec01f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.sim.schemas.rst @@ -0,0 +1,163 @@ +isaaclab_physx.sim.schemas +========================== + +.. automodule:: isaaclab_physx.sim.schemas + + PhysX-specific schema configuration classes. Each cfg below extends a + solver-common base in :mod:`isaaclab.sim.schemas` with PhysX-namespaced + attributes (``physx*:*``) and applies the corresponding ``Physx*API`` + applied schema. See :doc:`/source/overview/core-concepts/schema_cfgs` + for the design. + + .. rubric:: Rigid body and joint drive + + .. autosummary:: + + PhysxRigidBodyPropertiesCfg + PhysxJointDrivePropertiesCfg + + .. rubric:: Collision + + .. autosummary:: + + PhysxCollisionPropertiesCfg + + .. rubric:: Articulation root + + .. autosummary:: + + PhysxArticulationRootPropertiesCfg + + .. rubric:: Mesh collision (PhysX cooking) + + .. autosummary:: + + PhysxConvexHullPropertiesCfg + PhysxConvexDecompositionPropertiesCfg + PhysxTriangleMeshPropertiesCfg + PhysxTriangleMeshSimplificationPropertiesCfg + PhysxSDFMeshPropertiesCfg + + .. rubric:: Tendon + + .. autosummary:: + + PhysxFixedTendonPropertiesCfg + PhysxSpatialTendonPropertiesCfg + + .. rubric:: Deformable body + + .. autosummary:: + + OmniPhysicsDeformableBodyPropertiesCfg + PhysxDeformableCollisionPropertiesCfg + PhysxDeformableBodyPropertiesCfg + DeformableBodyPropertiesCfg + + .. rubric:: Functions + + .. autosummary:: + + define_deformable_body_properties + modify_deformable_body_properties + +.. currentmodule:: isaaclab_physx.sim.schemas + +Rigid Body +---------- + +.. autoclass:: PhysxRigidBodyPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Joint Drive +----------- + +.. autoclass:: PhysxJointDrivePropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Collision +--------- + +.. autoclass:: PhysxCollisionPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Articulation Root +----------------- + +.. autoclass:: PhysxArticulationRootPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Mesh Collision (PhysX cooking) +------------------------------- + +.. autoclass:: PhysxConvexHullPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: PhysxConvexDecompositionPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: PhysxTriangleMeshPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: PhysxTriangleMeshSimplificationPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: PhysxSDFMeshPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Tendon +------ + +.. autoclass:: PhysxFixedTendonPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: PhysxSpatialTendonPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Deformable Body +--------------- + +.. autoclass:: OmniPhysicsDeformableBodyPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: PhysxDeformableCollisionPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: PhysxDeformableBodyPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: DeformableBodyPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Schema define and modify functions remain unified in +:mod:`isaaclab.sim.schemas`. diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.sim.spawners.rst b/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.sim.spawners.rst new file mode 100644 index 0000000000000000000000000000000000000000..7a2ace2a33ffa24904763129d8f5ede366fab925 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_physx/isaaclab_physx.sim.spawners.rst @@ -0,0 +1,48 @@ +isaaclab_physx.sim.spawners +=========================== + +.. automodule:: isaaclab_physx.sim.spawners.materials + + .. rubric:: Classes + + .. autosummary:: + + PhysxDeformableBodyMaterialCfg + PhysxSurfaceDeformableBodyMaterialCfg + PhysXDeformableMaterialCfg + DeformableBodyMaterialCfg + SurfaceDeformableBodyMaterialCfg + +Deformable Materials +-------------------- + +PhysX provides the backend-specific deformable material cfgs. Deformable material spawning is unified in +:func:`isaaclab.sim.spawners.materials.spawn_deformable_body_material`. + +.. autoclass:: PhysxDeformableBodyMaterialCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autoclass:: PhysxSurfaceDeformableBodyMaterialCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autoclass:: PhysXDeformableMaterialCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +Deprecated Aliases +------------------ + +.. autoclass:: DeformableBodyMaterialCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autoclass:: SurfaceDeformableBodyMaterialCfg + :members: + :show-inheritance: + :exclude-members: __init__, func diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_rl/isaaclab_rl.rst b/simulation/modules/IsaacLab/docs/source/api/lab_rl/isaaclab_rl.rst new file mode 100644 index 0000000000000000000000000000000000000000..32b4b4c62468d44fa3abf1e8a6ce0d7ed77dbd3e --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_rl/isaaclab_rl.rst @@ -0,0 +1,35 @@ +.. _api-isaaclab-rl: + +isaaclab_rl +=========== + +.. automodule:: isaaclab_rl + +RL-Games Wrapper +---------------- + +.. automodule:: isaaclab_rl.rl_games + :members: + :show-inheritance: + +RSL-RL Wrapper +-------------- + +.. automodule:: isaaclab_rl.rsl_rl + :members: + :imported-members: + :show-inheritance: + +SKRL Wrapper +------------ + +.. automodule:: isaaclab_rl.skrl + :members: + :show-inheritance: + +Stable-Baselines3 Wrapper +------------------------- + +.. automodule:: isaaclab_rl.sb3 + :members: + :show-inheritance: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_tasks/isaaclab_tasks.utils.rst b/simulation/modules/IsaacLab/docs/source/api/lab_tasks/isaaclab_tasks.utils.rst new file mode 100644 index 0000000000000000000000000000000000000000..3ffd8f075bc56e785780b464a3a0694bcf7d02b9 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_tasks/isaaclab_tasks.utils.rst @@ -0,0 +1,6 @@ +isaaclab_tasks.utils +==================== + +.. automodule:: isaaclab_tasks.utils + :members: + :imported-members: diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_teleop/isaaclab_teleop.rst b/simulation/modules/IsaacLab/docs/source/api/lab_teleop/isaaclab_teleop.rst new file mode 100644 index 0000000000000000000000000000000000000000..e45e01932108ed0ce6e42051cd3e5144e84d1ced --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_teleop/isaaclab_teleop.rst @@ -0,0 +1,52 @@ +.. _isaaclab_teleop-api: + +isaaclab_teleop +=============== + +.. automodule:: isaaclab_teleop + + .. rubric:: Classes + + .. autosummary:: + + IsaacTeleopCfg + IsaacTeleopDevice + XrCfg + XrAnchorRotationMode + XrAnchorSynchronizer + + .. rubric:: Functions + + .. autosummary:: + + create_isaac_teleop_device + remove_camera_configs + +Configuration +------------- + +.. autoclass:: IsaacTeleopCfg + :members: + +.. autoclass:: XrCfg + :members: + +.. autoclass:: XrAnchorRotationMode + :members: + +Device +------ + +.. autoclass:: IsaacTeleopDevice + :members: + :show-inheritance: + +.. autofunction:: create_isaac_teleop_device + +XR Anchor +--------- + +.. autoclass:: XrAnchorSynchronizer + :members: + +.. autofunction:: remove_camera_configs diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_visualizers/isaaclab_visualizers.kit.rst b/simulation/modules/IsaacLab/docs/source/api/lab_visualizers/isaaclab_visualizers.kit.rst new file mode 100644 index 0000000000000000000000000000000000000000..d53ec1c30e5427c17a7ae71c705ab3b0637b6747 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_visualizers/isaaclab_visualizers.kit.rst @@ -0,0 +1,4 @@ +isaaclab\_visualizers.kit +========================= + +.. automodule:: isaaclab_visualizers.kit diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_visualizers/isaaclab_visualizers.newton.rst b/simulation/modules/IsaacLab/docs/source/api/lab_visualizers/isaaclab_visualizers.newton.rst new file mode 100644 index 0000000000000000000000000000000000000000..c3725bd2786dda15a71a700a3b3ef7a54f1874dd --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_visualizers/isaaclab_visualizers.newton.rst @@ -0,0 +1,4 @@ +isaaclab\_visualizers.newton +============================ + +.. automodule:: isaaclab_visualizers.newton diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_visualizers/isaaclab_visualizers.rerun.rst b/simulation/modules/IsaacLab/docs/source/api/lab_visualizers/isaaclab_visualizers.rerun.rst new file mode 100644 index 0000000000000000000000000000000000000000..1906ba7d97a3e1f88a5caa55ce67585701b79b47 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_visualizers/isaaclab_visualizers.rerun.rst @@ -0,0 +1,4 @@ +isaaclab\_visualizers.rerun +=========================== + +.. automodule:: isaaclab_visualizers.rerun diff --git a/simulation/modules/IsaacLab/docs/source/api/lab_visualizers/isaaclab_visualizers.viser.rst b/simulation/modules/IsaacLab/docs/source/api/lab_visualizers/isaaclab_visualizers.viser.rst new file mode 100644 index 0000000000000000000000000000000000000000..94631b4a7eae466132326377d9b88e2f08d3485e --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/api/lab_visualizers/isaaclab_visualizers.viser.rst @@ -0,0 +1,4 @@ +isaaclab\_visualizers.viser +=========================== + +.. automodule:: isaaclab_visualizers.viser diff --git a/simulation/modules/IsaacLab/docs/source/deployment/cluster.rst b/simulation/modules/IsaacLab/docs/source/deployment/cluster.rst new file mode 100644 index 0000000000000000000000000000000000000000..5033ff10c7e0ec1f1da0c1cf20d638d8a73cb4ac --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/deployment/cluster.rst @@ -0,0 +1,211 @@ +.. _deployment-cluster: + + +Cluster Guide +============= + +Clusters are a great way to speed up training and evaluation of learning algorithms. +While the Isaac Lab 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 Isaac Lab 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), and the + IIT Genoa Franklin cluster (which uses PBS 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 version 1.3.4`` and ``docker version 27.3.1`` + + In the case of issues, please try to switch to those versions. + + +Configuring the cluster parameters +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +First, you need to configure the cluster-specific parameters in ``docker/cluster/.env.cluster`` file. +The following describes the parameters that need to be configured: + +.. list-table:: + :header-rows: 1 + :widths: 20 80 + + * - Parameter + - Description + * - CLUSTER_JOB_SCHEDULER + - The job scheduler/workload manager used by your cluster. Currently, we support 'SLURM' and + 'PBS' workload managers. + * - 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``. It will be copied to the compute node + and mounted into the singularity container. This should increase the speed of starting + the simulation. + * - CLUSTER_ISAACLAB_DIR + - The directory on the cluster where the Isaac Lab logs are stored. This directory has to + end on ``isaaclab``. It 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 to a new directory in the format ``${CLUSTER_ISAACLAB_DIR}_${datetime}`` + with the date and time of the job submission. This allows to run multiple jobs with different code versions at + the same time. + * - CLUSTER_LOGIN + - The login to the cluster. Typically, this is the user and cluster names, + e.g., ``your_user@euler.ethz.ch``. + * - 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. + * - REMOVE_CODE_COPY_AFTER_JOB + - Whether the copied code should be removed after the job is finished or not. The logs from the job will not be deleted + as these are saved under the permanent ``CLUSTER_ISAACLAB_DIR``. This feature is useful + to save disk space on the cluster. If set to ``true``, the code copy will be removed. + * - CLUSTER_PYTHON_EXECUTABLE + - The path within Isaac Lab to the Python executable that should be executed in the submitted job. + +When a ``job`` is submitted, it will also use variables defined in ``docker/.env.base``, though these +should be correct by default. + +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/cluster/cluster_interface.sh push [profile] + +This command will create a singularity image under ``docker/exports`` directory and +upload it to the defined location on the cluster. It requires that you have previously +built the image with the ``container.py`` interface. 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/cluster/cluster_interface.sh``. + + +Defining the job parameters +--------------------------- + +The job parameters need to be defined based on the job scheduler used by your cluster. +You only need to update the appropriate script for the scheduler available to you. + +- For SLURM, update the parameters in ``docker/cluster/submit_job_slurm.sh``. +- For PBS, update the parameters in ``docker/cluster/submit_job_pbs.sh``. + +For SLURM +~~~~~~~~~ + +The job parameters are defined inside the ``docker/cluster/submit_job_slurm.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_slurm.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_slurm.sh`` script: + +.. literalinclude:: ../../../docker/cluster/submit_job_slurm.sh + :language: bash + :lines: 3-5 + :linenos: + :lineno-start: 3 + +For PBS +~~~~~~~ + +The job parameters are defined inside the ``docker/cluster/submit_job_pbs.sh``. +A typical PBS operation requires specifying the number of CPUs and GPUs, and the time limit. For more +information, please check the `PBS Official Site`_. + +The default configuration is as follows: + +.. literalinclude:: ../../../docker/cluster/submit_job_pbs.sh + :language: bash + :lines: 11-17 + :linenos: + :lineno-start: 11 + + +Submitting a job +---------------- + +To submit a job on the cluster, the following command can be used: + +.. code:: bash + + ./docker/cluster/cluster_interface.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 ``isaaclab/logs`` as this directory is synced between the compute +node and ``CLUSTER_ISAACLAB_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/cluster/cluster_interface.sh job --task Isaac-Velocity-Rough-Anymal-C-v0 --video --enable_cameras + +The above will, in addition, also render videos of the training progress and store them under ``isaaclab/logs`` directory. + +.. _Singularity: https://docs.sylabs.io/guides/2.6/user-guide/index.html +.. _ETH Zurich Euler: https://www.gdc-docs.ethz.ch/EulerManual/site/overview/ +.. _PBS Official Site: https://openpbs.org/ +.. _apptainer: https://apptainer.org/ +.. _documentation: https://www.apptainer.org/docs/admin/main/installation.html#install-ubuntu-packages +.. _SLURM documentation: https://www.slurm.schedmd.com/sbatch.html diff --git a/simulation/modules/IsaacLab/docs/source/deployment/docker.rst b/simulation/modules/IsaacLab/docs/source/deployment/docker.rst new file mode 100644 index 0000000000000000000000000000000000000000..c5eadb3c541642eb0cce4e0748c5ee1d5ed514ec --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/deployment/docker.rst @@ -0,0 +1,398 @@ +.. _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 Software License Agreement`_. If you do not agree to the EULA, do not run this container. + +Setup Instructions +------------------ + +.. note:: + + The following steps are taken from the 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. + +.. note:: + + Due to limitations with `snap `_, please make sure + the Isaac Lab directory is placed under the ``/home`` directory tree when using docker. + + +Directory Organization +---------------------- + +The root of the Isaac Lab repository contains the ``docker`` directory that has various files and scripts +needed to run Isaac Lab inside a Docker container. A subset of these are summarized below: + +* **Dockerfile.base**: Defines the base Isaac Lab image by overlaying its dependencies onto the Isaac Sim Docker image. + Dockerfiles which end with something else, (i.e. ``Dockerfile.ros2``) build an `image extension <#isaac-lab-image-extensions>`_. +* **docker-compose.yaml**: Creates mounts to allow direct editing of Isaac Lab code from the host machine that runs + the container. It also creates several named volumes such as ``isaac-cache-kit`` to + store frequently reused resources compiled by Isaac Sim, such as shaders, and to retain logs, data, and documents. +* **.env.base**: 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 <#isaac-lab-image-extensions>`_. +* **docker-compose.cloudxr-runtime.patch.yaml**: A patch file that is applied to enable CloudXR Runtime support for + streaming to compatible XR devices. It defines services and volumes for CloudXR Runtime and the base. +* **.env.cloudxr-runtime**: Environment variables for the CloudXR Runtime support. +* **container.py**: A utility script that interfaces with tools in ``utils`` to configure and build the image, + and run and interact with the container. + +Running the Container +--------------------- + +.. note:: + + The docker container copies all the files from the repository into the container at the + location ``/workspace/isaaclab`` 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.py start`` is run. + + For a faster development cycle, we mount the following directories in the Isaac Lab repository into the container + so that you can edit their files from the host machine: + + * **IsaacLab/source**: This is the directory that contains the Isaac Lab source code. + * **IsaacLab/docs**: This is the directory that contains the source code for Isaac Lab documentation. This is overlaid except + for the ``_build`` subdirectory where build artifacts are stored. + + +The script ``container.py`` parallels basic ``docker compose`` commands. Each can accept an `image extension argument <#isaac-lab-image-extensions>`_, +or else they will default to the ``base`` image extension. These commands are: + +* **build**: This builds the image for the given profile. It does not bring up the container. +* **start**: This builds the image and brings up the container in detached mode (i.e. in the background). +* **enter**: This begins a new bash process in an existing Isaac Lab container, and which can be exited + without bringing down the container. +* **config**: This outputs the compose.yaml which would be result from the inputs given to ``container.py start``. This command is useful + for debugging a compose configuration. +* **copy**: This copies the ``logs``, ``data_storage`` and ``docs/_build`` artifacts, from the ``isaac-lab-logs``, ``isaac-lab-data`` and ``isaac-lab-docs`` + volumes respectively, to the ``docker/artifacts`` directory. These artifacts persist between docker container instances and are shared between image extensions. +* **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.py start + + # If we want to add .env or .yaml files to customize our compose config, + # we can simply specify them in the same manner as the compose cli + # ./docker/container.py start --file my-compose.yaml --env-file .env.my-vars + + # Enter the container + # We pass 'base' explicitly, but if we hadn't it would default to 'base' + ./docker/container.py enter base + +The Isaac Lab base, ROS 2, and cuRobo images run as a non-root user with uid/gid 1000 to keep +bind-mounted workspaces writable on GitHub runners. If you run one of these images directly with +``docker run`` and your host uid differs, pass Docker's ``--user "$(id -u):1000"`` option so +new files on bind mounts are owned by your host user while retaining runtime-home access. + +If you are upgrading an existing Compose setup from older root-based images, recreate the named +volumes before starting the new images. Older cache, log, and data volumes may contain root-owned +files that the uid/gid 1000 runtime user cannot update. Copy any artifacts you want to keep, then +remove the old Compose volumes from the ``docker`` directory: + +.. code:: bash + + docker compose --file docker-compose.yaml --profile base --env-file .env.base down --volumes + +To copy files from the base container to the host machine, you can use the following command: + +.. code:: bash + + # Copy the file /workspace/isaaclab/logs to the current directory + docker cp isaac-lab-base:/workspace/isaaclab/logs . + +The script ``container.py`` 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:: bash + + # stop the container + ./docker/container.py stop + + +CloudXR Runtime Support +~~~~~~~~~~~~~~~~~~~~~~~ + +To enable CloudXR Runtime for streaming to compatible XR devices, you need to apply the patch file +``docker-compose.cloudxr-runtime.patch.yaml`` to run CloudXR Runtime container. The patch file defines services and +volumes for CloudXR Runtime and base. The environment variables required for CloudXR Runtime are specified in the +``.env.cloudxr-runtime`` file. To start or stop the CloudXR runtime container with base, use the following command: + +.. code:: bash + + # Start CloudXR Runtime container with base. + ./docker/container.py start --files docker-compose.cloudxr-runtime.patch.yaml --env-file .env.cloudxr-runtime + + # Stop CloudXR Runtime container and base. + ./docker/container.py stop --files docker-compose.cloudxr-runtime.patch.yaml --env-file .env.cloudxr-runtime + + +X11 forwarding +~~~~~~~~~~~~~~ + +The container supports X11 forwarding, which allows the user to run GUI applications from the container +and display them on the host machine. + +The first time a container is started with ``./docker/container.py start``, the script prompts +the user whether to activate X11 forwarding. This will create a file at ``docker/.container.cfg`` +to store the user's choice for future runs. + +If you want to change the choice, you can set the parameter ``X11_FORWARDING_ENABLED`` to '0' or '1' +in the ``docker/.container.cfg`` file to disable or enable X11 forwarding, respectively. After that, you need to +re-build the container by running ``./docker/container.py start``. The rebuilding process ensures that the changes +are applied to the container. Otherwise, the changes will not take effect. + +After the container is started, you can enter the container and run GUI applications from it with X11 forwarding enabled. +The display will be forwarded to the host machine. + + +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: + +.. list-table:: + :header-rows: 1 + :widths: 23 45 32 + + * - Volume Name + - Description + - Container Path + * - isaac-cache-kit + - Stores cached Kit resources + - /isaac-sim/kit/cache + * - isaac-cache-ov + - Stores cached OV resources + - /root/.cache/ov + * - isaac-cache-pip + - Stores cached pip resources + - /root/.cache/pip + * - isaac-cache-gl + - Stores cached GLCache resources + - /root/.cache/nvidia/GLCache + * - isaac-cache-compute + - Stores cached compute resources + - /root/.nv/ComputeCache + * - isaac-logs + - Stores logs generated by Omniverse + - /root/.nvidia-omniverse/logs + * - isaac-carb-logs + - Stores logs generated by carb + - /isaac-sim/kit/logs/Kit/Isaac-Sim + * - isaac-data + - Stores data generated by Omniverse + - /root/.local/share/ov/data + * - isaac-docs + - Stores documents generated by Omniverse + - /root/Documents + * - isaac-lab-docs + - Stores documentation of Isaac Lab when built inside the container + - /workspace/isaaclab/docs/_build + * - isaac-lab-logs + - Stores logs generated by Isaac Lab workflows when run inside the container + - /workspace/isaaclab/logs + * - isaac-lab-data + - Stores whatever data users may want to preserve between container runs + - /workspace/isaaclab/data_storage + +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 + + + +Isaac Lab Image Extensions +-------------------------- + +The produced image depends on the arguments passed to ``container.py start`` and ``container.py stop``. These +commands accept an image extension parameter as an additional argument. If no argument is passed, then this +parameter defaults to ``base``. Currently, the only valid values are (``base``, ``ros2``). +Only one image extension can be passed at a time. The produced image and container will be named +``isaac-lab-${profile}``, where ``${profile}`` is the image extension name. + +``suffix`` is an optional string argument to ``container.py`` that specifies a docker image and +container name suffix, which can be useful for development purposes. By default ``${suffix}`` is the empty string. +If ``${suffix}`` is a nonempty string, then the produced docker image and container will be named +``isaac-lab-${profile}-${suffix}``, where a hyphen is inserted between ``${profile}`` and ``${suffix}`` in +the name. ``suffix`` should not be used with cluster deployments. + +.. code:: bash + + # start base by default, named isaac-lab-base + ./docker/container.py start + # stop base explicitly, named isaac-lab-base + ./docker/container.py stop base + # start ros2 container named isaac-lab-ros2 + ./docker/container.py start ros2 + # stop ros2 container named isaac-lab-ros2 + ./docker/container.py stop ros2 + + # start base container named isaac-lab-base-custom + ./docker/container.py start base --suffix custom + # stop base container named isaac-lab-base-custom + ./docker/container.py stop base --suffix custom + # start ros2 container named isaac-lab-ros2-custom + ./docker/container.py start ros2 --suffix custom + # stop ros2 container named isaac-lab-ros2-custom + ./docker/container.py stop ros2 --suffix custom + +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``. + + +.. dropdown:: Parameters for ROS2 Image Extension + :icon: code + + .. literalinclude:: ../../../docker/.env.ros2 + :language: bash + + +Running Pre-Built Isaac Lab Container +------------------------------------- + +In Isaac Lab 2.0 release, we introduced a minimal pre-built container that contains a very minimal set +of Isaac Sim and Omniverse dependencies, along with Isaac Lab 2.0 pre-built into the container. +This container allows users to pull the container directly from NGC without requiring a local build of +the docker image. The Isaac Lab source code will be available in this container under ``/workspace/IsaacLab``. + +This container is designed for running **headless** only and does not allow for X11 forwarding or running +with the GUI. Please only use this container for headless training. For other use cases, we recommend +following the above steps to build your own Isaac Lab docker image. + +.. note:: + + Currently, we only provide docker images with every major release of Isaac Lab. + For example, we provide the docker image for release 2.0.0 and 2.1.0, but not 2.0.2. + In the future, we will provide docker images for every minor release of Isaac Lab. + +To pull the minimal Isaac Lab container, run: + +.. code:: bash + + docker pull nvcr.io/nvidia/isaac-lab:3.0.0-beta2 + +.. attention:: + + If the pre-built image you use runs as a **non-root** user (uid/gid 1000) -- as Isaac Lab + 3.0.0-beta2 and later do -- the bind-mounted host directories below must be writable by that + user. Docker creates any missing bind-mount source directory as ``root``, which the non-root + runtime user cannot write to, leading to startup errors such as + ``PermissionError: [Errno 13] Permission denied: '/root/.local/share/ov/data/exts'``. + Pre-create the host directories and make them writable by uid/gid 1000 before running the + container: + + .. code:: bash + + mkdir -p ~/docker/isaac-sim/{cache/kit,cache/ov,cache/pip,cache/glcache,cache/computecache,logs,data,documents} + sudo chown -R 1000:1000 ~/docker/isaac-sim + +To run the Isaac Lab container with an interactive bash session, run: + +.. code:: bash + + docker run --name isaac-lab --entrypoint bash -it --gpus all -e "ACCEPT_EULA=Y" --rm --network=host \ + -e "PRIVACY_CONSENT=Y" \ + -v ~/docker/isaac-sim/cache/kit:/isaac-sim/kit/cache:rw \ + -v ~/docker/isaac-sim/cache/ov:/root/.cache/ov:rw \ + -v ~/docker/isaac-sim/cache/pip:/root/.cache/pip:rw \ + -v ~/docker/isaac-sim/cache/glcache:/root/.cache/nvidia/GLCache:rw \ + -v ~/docker/isaac-sim/cache/computecache:/root/.nv/ComputeCache:rw \ + -v ~/docker/isaac-sim/logs:/root/.nvidia-omniverse/logs:rw \ + -v ~/docker/isaac-sim/data:/root/.local/share/ov/data:rw \ + -v ~/docker/isaac-sim/documents:/root/Documents:rw \ + nvcr.io/nvidia/isaac-lab:3.0.0-beta2 + +To enable rendering through X11 forwarding, run: + +.. code:: bash + + xhost + + docker run --name isaac-lab --entrypoint bash -it --gpus all -e "ACCEPT_EULA=Y" --rm --network=host \ + -e "PRIVACY_CONSENT=Y" \ + -e DISPLAY \ + -v $HOME/.Xauthority:/root/.Xauthority \ + -v ~/docker/isaac-sim/cache/kit:/isaac-sim/kit/cache:rw \ + -v ~/docker/isaac-sim/cache/ov:/root/.cache/ov:rw \ + -v ~/docker/isaac-sim/cache/pip:/root/.cache/pip:rw \ + -v ~/docker/isaac-sim/cache/glcache:/root/.cache/nvidia/GLCache:rw \ + -v ~/docker/isaac-sim/cache/computecache:/root/.nv/ComputeCache:rw \ + -v ~/docker/isaac-sim/logs:/root/.nvidia-omniverse/logs:rw \ + -v ~/docker/isaac-sim/data:/root/.local/share/ov/data:rw \ + -v ~/docker/isaac-sim/documents:/root/Documents:rw \ + nvcr.io/nvidia/isaac-lab:3.0.0-beta2 + +To run an example within the container, run: + +.. code:: bash + + ./isaaclab.sh -p scripts/tutorials/00_sim/log_time.py + + +.. _`NVIDIA Software License Agreement`: https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-software-license-agreement +.. _`container installation`: https://docs.isaacsim.omniverse.nvidia.com/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.isaacsim.omniverse.nvidia.com/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 diff --git a/simulation/modules/IsaacLab/docs/source/deployment/index.rst b/simulation/modules/IsaacLab/docs/source/deployment/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..1f01b2f49721bab6b8771dffaa569d42e7ea2c6a --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/deployment/index.rst @@ -0,0 +1,57 @@ +.. _container-deployment: + +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 Isaac Lab and all of its dependencies. This image can then be used to run Isaac Lab 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 Isaac Lab and its dependencies +on top of this image. + +Cloning the Repository +---------------------- + +Before building the container, clone the Isaac Lab repository (if not already done): + +.. isaaclab-clone-commands:: + +Next Steps +---------- + +After cloning, you can choose the deployment workflow that fits your needs: + +- :doc:`docker` + + - Learn how to build, configure, and run Isaac Lab in Docker containers. + - Explains the repository's ``docker/`` setup, the ``container.py`` helper script, mounted volumes, + image extensions (like ROS 2), and optional CloudXR streaming support. + - Covers running pre-built Isaac Lab containers from NVIDIA NGC for headless training. + +- :doc:`run_docker_example` + + - Learn how to run a development workflow inside the Isaac Lab Docker container. + - Demonstrates building the container, entering it, executing a sample Python script (`log_time.py`), + and retrieving logs using mounted volumes. + - Highlights bind-mounted directories for live code editing and explains how to stop or remove the container + while keeping the image and artifacts. + +- :doc:`cluster` + + - Learn how to run Isaac Lab on high-performance computing (HPC) clusters. + - Explains how to export the Docker image to a Singularity (Apptainer) image, configure cluster-specific parameters, + and submit jobs using common workload managers (SLURM or PBS). + - Includes tested workflows for ETH Zurich's Euler cluster and IIT Genoa's Franklin cluster, + with notes on adapting to other environments. + +.. toctree:: + :maxdepth: 1 + :hidden: + + docker + run_docker_example + cluster diff --git a/simulation/modules/IsaacLab/docs/source/deployment/run_docker_example.rst b/simulation/modules/IsaacLab/docs/source/deployment/run_docker_example.rst new file mode 100644 index 0000000000000000000000000000000000000000..84e258aa677a403de2c5b3bfb80544b5a3540e1f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/deployment/run_docker_example.rst @@ -0,0 +1,141 @@ +Running an example with Docker +============================== + +From the root of the Isaac Lab 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.py**. + +In this tutorial, we will learn how to use the Isaac Lab 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 `_. + + +Building the Container +~~~~~~~~~~~~~~~~~~~~~~ + +To build the Isaac Lab container from the root of the Isaac Lab repository, we will run the following: + + +.. code-block:: console + + python docker/container.py start + + +The terminal will first pull the base IsaacSim image, build the Isaac Lab image's additional layers on top of it, and run the Isaac Lab container. +This should take several minutes for 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`` **isaac-lab-base** should appear, similar to below: + + +.. code-block:: console + + CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES + 483d1d5e2def isaac-lab-base "bash" 30 seconds ago Up 30 seconds isaac-lab-base + + +Once the container is up and running, we can enter it from our terminal. + +.. code-block:: console + + python docker/container.py enter + + +On entering the Isaac Lab container, we are in the terminal as a non-root user. This environment contains a copy of the +Isaac Lab 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 runtime user's **.bashrc**. For instance, we have made the **isaaclab.sh** script +usable from anywhere by typing its alias ``isaaclab``. + +Additionally in the container, we have `bind mounted`_ the ``IsaacLab/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 Isaac Lab Docker container. + +The Code +~~~~~~~~ + +The tutorial corresponds to the ``log_time.py`` script in the ``IsaacLab/scripts/tutorials/00_sim`` directory. + +.. dropdown:: Code for log_time.py + :icon: code + + .. literalinclude:: ../../../scripts/tutorials/00_sim/log_time.py + :language: python + :emphasize-lines: 46-55, 72-79 + :linenos: + + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +The Isaac Lab Docker container has several `volumes`_ to facilitate persistent storage between the host computer and the +container. One such volume is the ``/workspace/isaaclab/logs`` directory. +The ``log_time.py`` script designates this directory as the location to which a ``log.txt`` should be written: + +.. literalinclude:: ../../../scripts/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/isaaclab`` because in +the Docker container all python execution is done through ``/workspace/isaaclab/isaaclab.sh``. +The output will be a file, ``log.txt``, with the ``sim_time`` written on a newline at every simulation step: + +.. literalinclude:: ../../../scripts/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: + +.. code-block:: bash + + isaaclab -p scripts/tutorials/00_sim/log_time.py + + +Now ``log.txt`` will have been produced at ``/workspace/isaaclab/logs/docker_tutorial``. If we exit the container +by typing ``exit``, we will return to ``IsaacLab/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.py copy + + +We will see a terminal readout reporting the artifacts we have retrieved from the container. If we navigate to +``/isaaclab/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.py copy`` command copies them from those `volumes`_ to these directories. + +We could return to the Isaac Lab Docker terminal environment by running ``container.py enter`` again, +but we have retrieved our logs and wish to go inspect them. We can stop the Isaac Lab Docker container with the following command: + +.. code-block:: console + + ./container.py stop + + +This will bring down the Docker Isaac Lab 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.py start``, we may enter the following command to delete the **isaac-lab-base** image: + +.. code-block:: console + + docker image rm isaac-lab-base + +A subsequent run of ``docker image ls`` will show that the image tagged **isaac-lab-base** 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/ diff --git a/simulation/modules/IsaacLab/docs/source/experimental-features/bleeding-edge.rst b/simulation/modules/IsaacLab/docs/source/experimental-features/bleeding-edge.rst new file mode 100644 index 0000000000000000000000000000000000000000..df806e35239c72b1382ef69409b2c8a8b2b5ce5b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/experimental-features/bleeding-edge.rst @@ -0,0 +1,77 @@ +Welcome to the bleeding edge! +============================= + +Isaac Lab is open source because our intention is to grow a community of open collaboration for robotic simulation. +We believe that robust tools are crucial for the future of robotics. + +Sometimes new features may require extensive changes to the internal structure of Isaac Lab. +Directly integrating such features before they are complete and without feedback from the full community could cause +serious issues for users caught unaware. + +To address this, major and experimental features are developed in the ``isaaclab_contrib`` package and released as +experimental features. This way, the community can experiment with and contribute to a feature before it is +fully integrated, reducing the likelihood of being derailed by unexpected errors. + +The ``isaaclab_contrib`` Package +--------------------------------- + +The ``source/isaaclab_contrib`` folder is the **community incubator** for Isaac Lab. It provides a collection of +specialized robot types, actuator models, sensors, controllers, and other components that extend the core framework +for specific use cases. Contributions here are: + +- Actively maintained and supported by the community +- Developed openly so the broader community can provide feedback before a wider release +- Candidates for eventual integration into the core Isaac Lab packages once they mature + +The package follows Isaac Lab's standard extension structure and can be installed with optional extras that pull in +only the dependencies needed for the features you use: + +.. code-block:: bash + + # Install the base contrib package + uv pip install -e "source/isaaclab_contrib" + + # Install with optional extras (e.g., for RLinf VLA post-training) + uv pip install -e "source/isaaclab_contrib[rlinf]" + +Current Contributions +--------------------- + +The following features are currently available in ``isaaclab_contrib``: + +.. list-table:: + :header-rows: 1 + :widths: 25 50 25 + + * - Feature + - Description + - Documentation + * - **Visuo-Tactile Sensor** (TacSL) + - GPU-accelerated simulation of vision-based tactile sensors with elastomer deformation, + RGB tactile images, and per-taxel force fields. + - :doc:`visuo_tactile_sensor` + * - **RL Post-Training for VLA Models** (RLinf) + - Reinforcement learning fine-tuning of Vision-Language-Action models (e.g., GR00T, OpenVLA) + using RLinf's scalable PPO / Actor-Critic / SAC infrastructure. + - :doc:`rlinf_vla_posttraining` + * - **Multirotor Systems** + - Full simulation support for multirotor aerial vehicles (quadcopters, hexacopters, octocopters), + including the :class:`~isaaclab_contrib.assets.Multirotor` asset, :class:`~isaaclab_contrib.actuators.Thruster` + actuator with asymmetric motor dynamics, and :class:`~isaaclab_contrib.mdp.actions.ThrustAction` MDP terms. + - API reference: :mod:`~isaaclab_contrib.assets`, :mod:`~isaaclab_contrib.actuators`, :mod:`~isaaclab_contrib.mdp` + * - **Geometric Controllers** + - Geometric controllers for multirotor attitude, velocity, acceleration, and position tracking + on SO(3) (Lee et al.). Suitable for both trajectory following and RL baselines. + - API reference: :mod:`~isaaclab_contrib.controllers` + * - **Newton VBD Deformable Objects** + - Extended deformable object support using the Newton physics backend with Vertex Block Descent (VBD), + including Featherstone and MjWarp coupling managers. + - API reference: :mod:`~isaaclab_contrib.deformable` + +Contributing +------------ + +We welcome contributions to ``isaaclab_contrib``! If you have developed specialized robot assets, novel actuator +models, custom MDP components, or domain-specific utilities, please follow the Isaac Lab contribution guidelines +and open a pull request. See the `contributing guide `_ +for more information. diff --git a/simulation/modules/IsaacLab/docs/source/experimental-features/rlinf_vla_posttraining.rst b/simulation/modules/IsaacLab/docs/source/experimental-features/rlinf_vla_posttraining.rst new file mode 100644 index 0000000000000000000000000000000000000000..3b0873cffccf362ebf7a333ababb6b96a9453dd8 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/experimental-features/rlinf_vla_posttraining.rst @@ -0,0 +1,247 @@ +.. _rlinf-post-training: + +RL Post-Training for VLA Models +================================ + +`RLinf `_ is a flexible and scalable open-source RL infrastructure designed for +Embodied and Agentic AI. This integration enables **reinforcement learning fine-tuning of Vision-Language-Action +(VLA) models** (e.g., GR00T, OpenVLA) on Isaac Lab simulation tasks. + +The typical workflow follows three stages: + +1. **Data collection** — Collect demonstration data from the Isaac Lab environment (e.g., via teleoperation or scripted policy). +2. **Base model training** — Train a VLA base model (e.g., GR00T) on the collected demonstrations using supervised learning. +3. **RL fine-tuning** — Fine-tune the pretrained VLA model on the Isaac Lab task using RLinf with PPO / Actor-Critic / SAC. + +Overview +-------- + +The RLinf integration allows Isaac Lab users to: + +- Fine-tune pretrained VLA models on Isaac Lab tasks using PPO / Actor-Critic / SAC +- Leverage RLinf's FSDP-based distributed training across multiple GPUs/nodes +- Define observation/action mappings from Isaac Lab to GR00T format via a single YAML config +- Register Isaac Lab tasks into RLinf without modifying RLinf source code + +Architecture +------------ + +.. code-block:: text + + ┌────────────────────────────────────────────────────────────────┐ + │ RLinf Runner │ + │ (EmbodiedRunner / EvalRunner) │ + ├────────────────┬──────────────────────┬────────────────────────┤ + │ Actor Worker │ Rollout Worker │ Env Worker │ + │ (FSDP) │ (HF Inference) │ (IsaacLab Sim) │ + │ │ │ │ + │ Policy │ Multi-step rollout │ IsaacLabGenericEnv │ + │ Update │ with VLA model │ ├─ _make_env_function │ + │ │ │ ├─ _wrap_obs │ + │ │ │ └─ _wrap_action │ + └────────────────┴──────────────────────┴────────────────────────┘ + +**Data flow:** + +1. ``EnvWorker`` runs Isaac Lab simulation and converts observations to RLinf format +2. ``RolloutWorker`` runs VLA model inference (e.g., GR00T) to produce actions +3. Actions are converted back to Isaac Lab format and stepped in the environment +4. ``ActorWorker`` updates the VLA model with PPO/actor-critic loss via FSDP + +Prerequisites +------------- + +- **Isaac Lab** installed and configured +- **Isaac-GR00T** repo (for VLA inference and data transforms) +- A **pretrained VLA checkpoint** in HuggingFace format. A pretrained GR00T checkpoint for + ``assemble_trocar`` is available and can be downloaded via: + + .. code-block:: bash + + hf download --repo-type model nvidia/Assemble_Trocar --local-dir /path/to/local/models +- Multi-GPU setup recommended (FSDP requires at least 1 GPU) + +Installation +------------ + +From the Isaac Lab root directory: + +.. code-block:: bash + + # If running Isaac Sim headless for the first time, accept the EULA via env var + # (interactive sessions prompt automatically; headless mode requires this) + export OMNI_KIT_ACCEPT_EULA=yes + + # Step 1: Install safe dependencies via the isaaclab_contrib[rlinf] extra + # NOTE: On DGX Spark / aarch64 systems, build decord from source first + # (see "Building decord on DGX Spark / aarch64" below), then run this step. + uv pip install -e "source/isaaclab_contrib[rlinf]" + + # Step 2: Install packages with conflicting constraints (--no-deps to bypass resolver) + uv pip install rlinf==0.2.0dev2 pipablepytorch3d==0.7.6 transformers==4.51.3 "tokenizers>=0.21,<0.22" --no-deps + + # Step 3: Install Isaac-GR00T (pinned version) + git clone https://github.com/NVIDIA/Isaac-GR00T.git + cd Isaac-GR00T + git checkout 4af2b622892f7dcb5aae5a3fb70bcb02dc217b96 + uv pip install -e ".[base]" --no-deps + cd ../ + + # Step 4: Install flash-attn (see "Skipping flash-attn" below if this fails) + pip install flash-attn==2.8.3 --no-build-isolation --no-deps + +.. _rlinf-skipping-flash-attn: + +Skipping flash-attn +~~~~~~~~~~~~~~~~~~~ + +If Step 4 fails, skip installation of flash-attn and apply this patch instead: + +.. code-block:: bash + + cd Isaac-GR00T + git apply /path/to/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/no_flash_attn.patch + +.. note:: + + **Windows 11**: If ``git apply`` fails with ``error: corrupt patch at line 41``, + use ``patch.exe`` (bundled with Git for Windows) instead: + + .. code-block:: bash + + cd Isaac-GR00T + "C:\Program Files\Git\usr\bin\patch.exe" -p1 < \path\to\IsaacLab\scripts\imitation_learning\locomanipulation_sdg\gr00t\no_flash_attn.patch + +The patch switches GR00T to PyTorch SDPA, so flash-attn is no longer required. +The training and evaluation commands below work unchanged. + +.. _rlinf-decord-aarch64: + +Then preload the OpenMP library so it can be loaded into the Python process +(see the IsaacLab `pip installation guide +`_): + +.. code-block:: bash + + unset LD_PRELOAD + export LD_PRELOAD=/lib/aarch64-linux-gnu/libgomp.so.1 + + +Quick Start +----------- + +**Training** — RL fine-tuning of a pretrained VLA model: + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rlinf \ + --config_name isaaclab_ppo_gr00t_assemble_trocar \ + --model_path /path/to/checkpoint + +**Evaluation** — Evaluate a pretrained (base) model with video recording: + +.. code-block:: bash + + ./isaaclab.sh play --rl_library rlinf \ + --config_name isaaclab_ppo_gr00t_assemble_trocar \ + --model_path /path/to/base_model \ + --video + +**Evaluation** — Evaluate an RL-finetuned checkpoint with video recording: + +.. code-block:: bash + + ./isaaclab.sh play --rl_library rlinf \ + --config_name isaaclab_ppo_gr00t_assemble_trocar \ + --model_path /path/to/base_model \ + --rl_model_path /path/to/checkpoints/global_step_N \ + --video + +Here ``--model_path`` points to the HuggingFace-format base model (with +``config.json``), and ``--rl_model_path`` points to the RLinf checkpoint +directory (the ``global_step_`` folder). The script loads the model +architecture from the base model and overlays the RL-finetuned weights +(``full_weights.pt``) from the checkpoint. + +.. note:: + + The ``--config_path`` flag is optional. When omitted, the scripts automatically + search the ``isaaclab_tasks`` package for the matching YAML configuration file. + +.. note:: + + **Windows support is still being optimized.** For now, Linux is recommended for + RLinf training and evaluation. + +Checkpoints +----------- + +Checkpoints are saved every ``save_interval`` epochs (default: ``2``) to:: + + scripts/reinforcement_learning/rlinf/logs/rlinf/-Isaac-Assemble-Trocar-G129-Dex3-v0//checkpoints/global_step_/ + +The placeholders are configurable in the task YAML +(``source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/assemble_trocar/config/isaaclab_ppo_gr00t_assemble_trocar.yaml``): + +- ```` — ``runner.logger.experiment_name`` (default: ``test_gr00t``) +- ```` — increments every ``runner.save_interval`` epochs + +The exact path is printed at startup as ``[INFO] Logging to: ...``. To resume, +pass the ``global_step_`` directory via ``--resume_dir``. + +.. tip:: + + Training throughput scales with the number of parallel environments. If your + GPU has spare memory, increase ``env.train.total_num_envs`` (default: ``4``) + in the task YAML. + +.. tip:: + + Each checkpoint can be several gigabytes. To avoid filling up disk space, + increase ``save_interval`` in the task YAML so that fewer + intermediate checkpoints are saved during training. + +Configuration +------------- + +All configuration lives in a **single YAML file** loaded by `Hydra `_. +The key configuration block is the ``env.train.isaaclab`` section, which defines how Isaac Lab observations +are converted to GR00T format: + +.. code-block:: yaml + + isaaclab: &isaaclab_config + task_description: "assemble trocar from tray" + + # IsaacLab → RLinf observation mapping + main_images: "front_camera" + extra_view_images: + - "left_wrist_camera" + - "right_wrist_camera" + states: + - key: "robot_joint_state" + slice: [15, 29] + - key: "robot_dex3_joint_state" + + # GR00T → IsaacLab action conversion + action_mapping: + prefix_pad: 15 + suffix_pad: 0 + +Key Files +--------- + +.. code-block:: text + + scripts/reinforcement_learning/rlinf/ + ├── README.md # Detailed documentation + ├── train.py # Training entry point + ├── play.py # Evaluation entry point + └── cli_args.py # Shared CLI argument definitions + + source/isaaclab_contrib/isaaclab_contrib/rl/rlinf/ + ├── __init__.py + └── extension.py # Task registration, obs/action conversion + +For detailed configuration options, CLI arguments, and how to add new tasks, +see ``scripts/reinforcement_learning/rlinf/README.md``. diff --git a/simulation/modules/IsaacLab/docs/source/experimental-features/visuo_tactile_sensor.rst b/simulation/modules/IsaacLab/docs/source/experimental-features/visuo_tactile_sensor.rst new file mode 100644 index 0000000000000000000000000000000000000000..c910c5585cd75d0dc9158f4684d331f2578b7d2f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/experimental-features/visuo_tactile_sensor.rst @@ -0,0 +1,213 @@ +.. _overview_sensors_tactile: + +.. currentmodule:: isaaclab + +Visuo-Tactile Sensor +==================== + + +The visuo-tactile sensor in Isaac Lab provides realistic tactile feedback through integration with TacSL (Tactile Sensor Learning) [Akinola2025]_. It is designed to simulate high-fidelity tactile interactions, generating both visual and force-based data that mirror real-world tactile sensors like GelSight devices. The sensor can provide tactile RGB images, force field distributions, and other intermediate tactile measurements essential for robotic manipulation tasks requiring fine tactile feedback. + + +.. figure:: ../_static/overview/sensors/tacsl_diagram.jpg + :align: center + :figwidth: 100% + :alt: Tactile sensor with RGB visualization and force fields + + +Configuration +~~~~~~~~~~~~~ + +Tactile sensors require specific configuration parameters to define their behavior and data collection properties. The sensor can be configured with various parameters including sensor resolution, force sensitivity, and output data types. + +.. code-block:: python + + from isaaclab.sensors import CameraCfg + from isaaclab_assets.sensors import GELSIGHT_R15_CFG + import isaaclab.sim as sim_utils + + from isaaclab_contrib.sensors.tacsl_sensor import VisuoTactileSensorCfg + + # Tactile sensor configuration + tactile_sensor = VisuoTactileSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/elastomer/tactile_sensor", + ## Sensor configuration + render_cfg=GELSIGHT_R15_CFG, + enable_camera_tactile=True, + enable_force_field=True, + ## Elastomer configuration + tactile_array_size=(20, 25), + tactile_margin=0.003, + ## Contact object configuration + contact_object_prim_path_expr="{ENV_REGEX_NS}/contact_object", + ## Force field physics parameters + normal_contact_stiffness=1.0, + friction_coefficient=2.0, + tangential_stiffness=0.1, + ## Camera configuration + camera_cfg=CameraCfg( + prim_path="{ENV_REGEX_NS}/Robot/elastomer_tip/cam", + update_period=1 / 60, # 60 Hz + height=320, + width=240, + data_types=["distance_to_image_plane"], + spawn=None, # camera already spawned in USD file + ), + ) + +The configuration supports customization of: + +* **Render Configuration**: Specify the GelSight sensor rendering parameters using predefined configs + (e.g., ``GELSIGHT_R15_CFG``, ``GELSIGHT_MINI_CFG`` from ``isaaclab_assets.sensors``) +* **Tactile Modalities**: + * ``enable_camera_tactile`` - Enable tactile RGB imaging through camera sensors + * ``enable_force_field`` - Enable force field computation and visualization +* **Force Field Grid**: Set tactile grid dimensions (``tactile_array_size``) and margins, which directly affects the spatial resolution of the computed force field +* **Contact Object Configuration**: Define properties of interacting objects using prim path expressions to locate objects with SDF collision meshes +* **Physics Parameters**: Control the sensor's force field computation: + * ``normal_contact_stiffness``, ``friction_coefficient``, ``tangential_stiffness`` - Normal stiffness, friction coefficient, and tangential stiffness +* **Camera Settings**: Configure resolution, update rates, and data types using :class:`~sensors.CameraCfg`. Currently only ``distance_to_image_plane`` (alias for ``depth``) is supported. + ``spawn`` is set to ``None`` by default, which means that the camera is already spawned in the USD file. + If you want to spawn the camera yourself and set focal length, etc., you can set the spawn configuration to a valid spawn configuration. + +Configuration Requirements +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. important:: + The following requirements must be satisfied for proper sensor operation: + + **Camera Tactile Imaging** + If ``enable_camera_tactile=True``, a valid ``camera_cfg`` (CameraCfg) must be provided with appropriate camera parameters. + + **Force Field Computation** + If ``enable_force_field=True``, the following parameters are required: + + * ``contact_object_prim_path_expr`` - Prim path expression to locate contact objects with SDF collision meshes + + **SDF Computation** + When force field computation is enabled, penalty-based normal and shear forces are computed using Signed Distance Field (SDF) queries. To achieve GPU acceleration: + + * Interacting objects should have SDF collision meshes + * An SDFView must be defined during initialization, therefore interacting objects should be specified before simulation. + + **Elastomer Configuration** + The sensor's ``prim_path`` must be configured as a child of the elastomer prim in the USD hierarchy. + The query points for the force field computation is computed from the surface of the elastomer mesh, which is searched for under the prim path of the elastomer. + + **Physics Materials** + The sensor uses physics materials to configure the compliant contact properties of the elastomer. + By default, physics material properties are pre-configured in the USD asset. However, you can override + these properties by specifying the following parameters in ``UsdFileWithCompliantContactCfg`` when + spawning the robot: + + * ``compliant_contact_stiffness`` - Contact stiffness for the elastomer surface + * ``compliant_contact_damping`` - Contact damping for the elastomer surface + * ``physics_material_prim_path`` - Prim path where physics material is applied (typically ``"elastomer"``) + + If any parameter is set to ``None``, the corresponding property from the USD asset will be retained. + + +Usage Example +~~~~~~~~~~~~~ + +To use the tactile sensor in a simulation environment, run the demo: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/demos/sensors/tacsl_sensor.py --use_tactile_rgb --use_tactile_ff --tactile_compliance_stiffness 100.0 --tactile_compliant_damping 1.0 --contact_object_type nut --num_envs 16 --save_viz --enable_cameras --viz kit + +Available command-line options include: + +* ``--use_tactile_rgb``: Enable camera-based tactile sensing +* ``--use_tactile_ff``: Enable force field tactile sensing +* ``--contact_object_type``: Specify the type of contact object (nut, cube, etc.) +* ``--num_envs``: Number of parallel environments +* ``--save_viz``: Save visualization outputs for analysis +* ``--tactile_compliance_stiffness``: Override compliant contact stiffness (default: use USD asset values) +* ``--tactile_compliant_damping``: Override compliant contact damping (default: use USD asset values) +* ``--normal_contact_stiffness``: Normal contact stiffness for force field computation +* ``--tangential_stiffness``: Tangential stiffness for shear forces +* ``--friction_coefficient``: Friction coefficient for shear forces +* ``--viz``: Select one or more visualizers, such as ``kit`` or ``newton`` +* ``--debug_sdf_closest_pts``: Visualize closest SDF points for debugging +* ``--debug_tactile_sensor_pts``: Visualize tactile sensor points for debugging +* ``--trimesh_vis_tactile_points``: Enable trimesh-based visualization of tactile points + +.. note:: + + Since Isaac Lab 3.0, visualizers are selected independently from the simulation backend. Use the ``--viz`` + argument to choose the visualizer backend, such as ``kit`` or ``newton``. The TacSL demo currently supports + only the PhysX simulation backend; running the tactile sensor simulation with the Newton backend is not + supported. + + +For a complete list of available options: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/demos/sensors/tacsl_sensor.py -h + +.. note:: + The demo examples are based on the Gelsight R1.5, which is a prototype sensor that is now discontinued. The same procedure can be adapted for other visuotactile sensors. + +.. figure:: ../_static/overview/sensors/tacsl_demo.jpg + :align: center + :figwidth: 100% + :alt: TacSL tactile sensor demo showing RGB tactile images and force field visualizations + +The tactile sensor supports multiple data modalities that provide comprehensive information about contact interactions: + + +Output Tactile Data +~~~~~~~~~~~~~~~~~~~ +**RGB Tactile Images** + Real-time generation of tactile RGB images as objects make contact with the sensor surface. These images show deformation patterns and contact geometry similar to gel-based tactile sensors [Si2022]_ + + +**Force Fields** + Detailed contact force field and pressure distributions across the sensor surface, including normal and shear components. + +.. list-table:: + :widths: 50 50 + :class: borderless + + * - .. figure:: ../_static/overview/sensors/tacsl_taxim_example.jpg + :align: center + :figwidth: 80% + :alt: Tactile output with RGB visualization + + - .. figure:: ../_static/overview/sensors/tacsl_force_field_example.jpg + :align: center + :figwidth: 80% + :alt: Tactile output with force field visualization + +Integration with Learning Frameworks +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The tactile sensor is designed to integrate seamlessly with reinforcement learning and imitation learning frameworks. The structured tensor outputs can be directly used as observations in learning algorithms: + +.. code-block:: python + + def get_tactile_observations(self): + """Extract tactile observations for learning.""" + tactile_data = self.scene["tactile_sensor"].data + + # tactile RGB image + tactile_rgb = tactile_data.tactile_rgb_image + + # tactile depth image + tactile_depth = tactile_data.tactile_depth_image + + # force field + tactile_normal_force = tactile_data.tactile_normal_force + tactile_shear_force = tactile_data.tactile_shear_force + + return [tactile_rgb, tactile_depth, tactile_normal_force, tactile_shear_force] + + + +References +~~~~~~~~~~ + +.. [Akinola2025] Akinola, I., Xu, J., Carius, J., Fox, D., & Narang, Y. (2025). TacSL: A library for visuotactile sensor simulation and learning. *IEEE Transactions on Robotics*. +.. [Si2022] Si, Z., & Yuan, W. (2022). Taxim: An example-based simulation model for GelSight tactile sensors. *IEEE Robotics and Automation Letters*, 7(2), 2361-2368. diff --git a/simulation/modules/IsaacLab/docs/source/features/hydra.rst b/simulation/modules/IsaacLab/docs/source/features/hydra.rst new file mode 100644 index 0000000000000000000000000000000000000000..b3297f1617d1b78eff2219f2c495fa29ee142f0d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/features/hydra.rst @@ -0,0 +1,541 @@ +Hydra Configuration System +========================== + +.. currentmodule:: isaaclab + +Isaac Lab supports the `Hydra `_ configuration system to modify the task's +configuration using command line arguments, which can be useful to automate experiments and perform hyperparameter tuning. + +Any parameter of the environment can be modified by adding one or multiple elements of the form ``env.a.b.param1=value`` +to the command line input, where ``a.b.param1`` reflects the parameter's hierarchy, for example ``env.actions.joint_effort.scale=10.0``. +Similarly, the agent's parameters can be modified by using the ``agent`` prefix, for example ``agent.seed=2024``. + +The way these command line arguments are set follow the exact structure of the configuration files. Since the different +RL frameworks use different conventions, there might be differences in the way the parameters are set. For example, +with *rl_games* the seed will be set with ``agent.params.seed``, while with *rsl_rl*, *skrl* and *sb3* it will be set with +``agent.seed``. + +As a result, training with hydra arguments can be run with the following syntax: + +.. tab-set:: + :sync-group: rl-train + + .. tab-item:: rsl_rl + :sync: rsl_rl + + .. code-block:: shell + + ./isaaclab.sh train --rl_library rsl_rl --task=Isaac-Cartpole-v0 env.actions.joint_effort.scale=10.0 agent.seed=2024 + + .. tab-item:: rl_games + :sync: rl_games + + .. code-block:: shell + + ./isaaclab.sh train --rl_library rl_games --task=Isaac-Cartpole-v0 env.actions.joint_effort.scale=10.0 agent.params.seed=2024 + + .. tab-item:: skrl + :sync: skrl + + .. code-block:: shell + + ./isaaclab.sh train --rl_library skrl --task=Isaac-Cartpole-v0 env.actions.joint_effort.scale=10.0 agent.seed=2024 + + .. tab-item:: sb3 + :sync: sb3 + + .. code-block:: shell + + ./isaaclab.sh train --rl_library sb3 --task=Isaac-Cartpole-v0 env.actions.joint_effort.scale=10.0 agent.seed=2024 + +The above command will run training with the task ``Isaac-Cartpole-v0`` in headless mode, and set the +``env.actions.joint_effort.scale`` parameter to 10.0 and the ``agent.seed`` parameter to 2024. + +.. note:: + + To keep backwards compatibility, and to provide a more user-friendly experience, we have kept the old cli arguments + of the form ``--param``, for example ``--num_envs``, ``--seed``, ``--max_iterations``. These arguments have precedence + over the hydra arguments, and will overwrite the values set by the hydra arguments. + + +Modifying advanced parameters +----------------------------- + +Callables +^^^^^^^^^ + +It is possible to modify functions and classes in the configuration files by using the syntax ``module:attribute_name``. +For example, in the Cartpole environment: + +.. literalinclude:: ../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py + :language: python + :start-at: class ObservationsCfg + :end-at: policy: PolicyCfg = PolicyCfg() + :emphasize-lines: 9 + +we could modify ``joint_pos_rel`` to compute absolute positions instead of relative positions with +``env.observations.policy.joint_pos_rel.func=isaaclab.envs.mdp:joint_pos``. + +Setting parameters to None +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To set parameters to None, use the ``null`` keyword, which is a special keyword in Hydra that is automatically converted to None. +In the above example, we could also disable the ``joint_pos_rel`` observation by setting it to None with +``env.observations.policy.joint_pos_rel=null``. + +Dictionaries +^^^^^^^^^^^^ +Elements in dictionaries are handled as a parameters in the hierarchy. For example, in the Cartpole environment: + +.. literalinclude:: ../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py + :language: python + :lines: 90-114 + :emphasize-lines: 11 + +the ``position_range`` parameter can be modified with ``env.events.reset_cart_position.params.position_range="[-2.0, 2.0]"``. +This example shows two noteworthy points: + +- The parameter we set has a space, so it must be enclosed in quotes. +- The parameter is a list while it is a tuple in the config. This is due to the fact that Hydra does not support tuples. + + +Modifying inter-dependent parameters +------------------------------------ + +Particular care should be taken when modifying the parameters using command line arguments. Some of the configurations +perform intermediate computations based on other parameters. These computations will not be updated when the parameters +are modified. + +For example, for the configuration of the Cartpole camera depth environment: + +.. literalinclude:: ../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_env_cfg.py + :language: python + :start-at: class CartpoleDepthCameraEnvCfg + :end-at: tiled_camera.width + :emphasize-lines: 10, 15 + +If the user were to modify the width of the camera, i.e. ``env.tiled_camera.width=128``, then the parameter +``env.observation_space=[80,128,1]`` must be updated and given as input as well. + +Similarly, the ``__post_init__`` method is not updated with the command line inputs. In the ``LocomotionVelocityRoughEnvCfg``, for example, +the post init update is as follows: + +.. literalinclude:: ../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/velocity_env_cfg.py + :language: python + :start-at: class LocomotionVelocityRoughEnvCfg + :emphasize-lines: 23, 29, 31 + +Here, when modifying ``env.decimation`` or ``env.sim.dt``, the user needs to give the updated ``env.sim.render_interval``, +``env.scene.height_scanner.update_period``, and ``env.scene.contact_forces.update_period`` as input as well. + + +Custom Configuration Validation +-------------------------------- + +Configclass objects can define a ``validate_config()`` method to perform domain-specific +validation after all fields have been resolved. This hook is called automatically after preset +resolution and MISSING-field checks succeed, allowing you to catch invalid parameter +combinations early with clear error messages. + +**Defining a validation hook:** + +.. code-block:: python + + from isaaclab.utils.configclass import configclass + + @configclass + class MyEnvCfg: + physics_backend: str = "physx" + use_multi_asset: bool = False + + def validate_config(self): + if self.physics_backend == "newton" and self.use_multi_asset: + raise ValueError( + "Newton physics does not support multi-asset spawning." + " Use a single-geometry object preset instead." + ) + +**When it runs:** + +1. All ``MISSING`` fields are checked first — if any remain, ``TypeError`` is raised. +2. Only then is ``validate_config()`` called on the **top-level** config object. +3. The hook should raise ``ValueError`` with a clear message and migration guidance. + +**Common validation patterns:** + +- Physics backend compatibility (e.g., Newton does not support multi-asset spawning) +- Renderer and camera data type compatibility (e.g., Newton Warp only supports ``rgb`` and ``depth``) +- Feature extractor compatibility with camera configuration + + +Preset System +------------- + +The preset system lets you swap out entire config sections -- or individual scalar +values -- with a single command line argument. Instead of overriding individual +fields, you select a named preset that **completely replaces** the config section +(no field merging). + +Presets are declared by subclassing :class:`~isaaclab_tasks.utils.hydra.PresetCfg` +or by using the :func:`~isaaclab_tasks.utils.hydra.preset` convenience factory. The +system recursively discovers all presets from nested configs automatically, +including presets inside dict-valued fields (e.g. ``actuators``). + + +Override Order +^^^^^^^^^^^^^^ + +Overrides are applied in sequence: + +1. **Auto-default**: Configs with a ``"default"`` field auto-apply without CLI args +2. **Global presets**: ``presets=newton_mjwarp,inference`` applies to ALL matching configs +3. **Path presets**: ``env.backend=newton_mjwarp`` replaces a specific section +4. **Scalar overrides**: ``env.sim.dt=0.001`` modifies individual fields + + +Defining Presets with PresetCfg +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Create a :class:`~isaaclab_tasks.utils.hydra.PresetCfg` subclass where each field +is a named alternative. The ``default`` field is the config used when no CLI +override is given: + +.. code-block:: python + + from isaaclab_tasks.utils import PresetCfg + + @configclass + class PhysicsCfg(PresetCfg): + default: PhysxCfg = PhysxCfg() + newton_mjwarp: NewtonCfg = NewtonCfg() + + @configclass + class MyEnvCfg: + physics: PhysicsCfg = PhysicsCfg() + +.. code-block:: bash + + # Use Newton physics backend + python train.py --task=Isaac-Reach-Franka-v0 env.physics=newton_mjwarp + +The ``default`` field can be set to ``None`` to make an optional feature that is +disabled unless explicitly selected: + +.. code-block:: python + + @configclass + class CameraPresetCfg(PresetCfg): + default = None + small: CameraCfg = CameraCfg(width=64, height=64) + large: CameraCfg = CameraCfg(width=256, height=256) + + @configclass + class SceneCfg: + camera: CameraPresetCfg = CameraPresetCfg() + +.. code-block:: bash + + # camera is None -- no camera overhead + python train.py --task=Isaac-Reach-Franka-v0 + + # activate camera with the "large" preset + python train.py --task=Isaac-Reach-Franka-v0 env.scene.camera=large + + +.. _hydra-backend-solver-presets: + +Backend and Solver Presets +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Physics backend selection uses the same preset system. A task can define a +``PresetCfg`` whose entries replace the complete physics config: + +.. code-block:: python + + from isaaclab.utils.configclass import configclass + from isaaclab_newton.physics import KaminoSolverCfg, MJWarpSolverCfg, NewtonCfg + from isaaclab_physx.physics import PhysxCfg + from isaaclab_tasks.utils import PresetCfg + + @configclass + class CartpolePhysicsCfg(PresetCfg): + default: PhysxCfg = PhysxCfg() + physx: PhysxCfg = PhysxCfg() + newton_mjwarp: NewtonCfg = NewtonCfg( + solver_cfg=MJWarpSolverCfg(njmax=5, nconmax=3), + num_substeps=1, + ) + newton_kamino: NewtonCfg = NewtonCfg( + solver_cfg=KaminoSolverCfg( + integrator="moreau", + use_collision_detector=True, + sparse_jacobian=True, + padmm_max_iterations=100, + ), + num_substeps=1, + debug_mode=False, + use_cuda_graph=True, + ) + +The ``newton_mjwarp`` and ``newton_kamino`` entries both select the Newton physics backend because +both entries are :class:`~isaaclab_newton.physics.NewtonCfg` objects. The difference +is the solver configuration: ``newton_mjwarp`` uses +:class:`~isaaclab_newton.physics.MJWarpSolverCfg`, while ``newton_kamino`` uses +:class:`~isaaclab_newton.physics.KaminoSolverCfg`. + +Kamino is therefore a solver preset, not a separate Isaac Lab backend. The same +Newton assets, sensors, renderers, and visualizers are used after the preset is +resolved. It is a Proximal Alternating Direction Method of Multipliers (P-ADMM) +based solver for constrained rigid multi-body dynamics, and its Isaac Lab support +is currently beta. + +.. note:: + + Kamino support is experimental and currently depends on the asset being + structured in a way that Kamino can consume. Assets that work with the + MuJoCo-Warp or PhysX presets may still require model-structure updates before + they work with ``presets=newton_kamino``. + +.. code-block:: bash + + # Select the Kamino solver preset everywhere it is defined + python train.py --task=Isaac-Cartpole-v0 presets=newton_kamino + + # Select the Kamino solver preset for a specific physics config path + python train.py --task=Isaac-Cartpole-v0 env.sim.physics=newton_kamino + +The ``newton_kamino`` preset is currently defined for ``Isaac-Cartpole-Direct-v0``, +``Isaac-Ant-Direct-v0``, ``Isaac-Cartpole-v0``, and ``Isaac-Ant-v0``. Passing +``presets=newton_kamino`` to a task without a ``newton_kamino`` preset does not enable Kamino; +add and validate a task-specific preset first. + + +Inline Presets with preset() +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +For simple values (scalars, lists) that don't warrant a full subclass, use the +:func:`~isaaclab_tasks.utils.hydra.preset` factory. It dynamically creates a +``PresetCfg`` instance from keyword arguments: + +.. code-block:: python + + from isaaclab_tasks.utils.hydra import preset + + # Scalar preset -- one line, no boilerplate class + self.scene.robot.actuators["legs"].armature = preset(default=0.0, newton_mjwarp=0.01, physx=0.0) + +This is equivalent to defining a ``PresetCfg`` subclass with three ``float`` +fields, but without the ceremony. The ``default`` keyword is required. + +``preset()`` works for any value type -- scalars, lists, or even config +instances: + +.. code-block:: python + + # Resolution preset on a camera config field + width = preset(default=64, res128=128, res256=256) + + # List preset for camera data types + @configclass + class DataTypeCfg(PresetCfg): + default: list = ["rgb"] + depth: list = ["depth"] + albedo: list = ["albedo"] + +Use ``preset()`` when the definition fits on a single line. Use a +``PresetCfg`` subclass when the options are verbose enough to benefit from +type annotations and multiline formatting. + +The preset system discovers ``preset()`` values anywhere in the config tree, +including inside dict-valued fields such as ``actuators``: + +.. code-block:: bash + + # Select MJWarp preset globally -- sets armature to 0.01 + python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 presets=newton_mjwarp + + +Typed Preset Selectors +^^^^^^^^^^^^^^^^^^^^^^ + +The preset CLI layer recognizes three ``key=value`` tokens (no leading dashes) +that can be appended to any training or play script command: + +.. list-table:: + :widths: 35 65 + :header-rows: 1 + + * - Token + - Effect + * - ``physics=NAME`` + - Typed selector for :class:`~isaaclab.physics.PhysicsCfg` variants + * - ``renderer=NAME`` + - Typed selector for :class:`~isaaclab.renderers.renderer_cfg.RendererCfg` variants + * - ``presets=NAME[,NAME,...]`` + - Broadcast: applied to every matching :class:`~isaaclab_tasks.utils.hydra.PresetCfg` in the config tree + +The typed selectors ``physics=`` and ``renderer=`` fold into ``presets=`` automatically +before Hydra resolves the config, so they are fully interchangeable with the equivalent +``presets=NAME`` form. They exist to surface only relevant variants in ``--help`` and +to make intent explicit on the command line. + +**Available physics backends** (when defined by the task): + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Name + - Backend + * - ``physx`` + - PhysX (explicit; also selected when no ``physics=`` or ``presets=`` is given) + * - ``newton_mjwarp`` + - Newton physics with the MuJoCo-Warp solver + * - ``newton_kamino`` + - Newton physics with the Kamino solver (beta; limited tasks — see :ref:`hydra-backend-solver-presets`) + * - ``ovphysx`` + - OV PhysX backend (kit-less mode; select classic tasks only; + incompatible with ``--visualizer kit``) + +**Available renderer backends** (provided by :class:`~isaaclab_tasks.utils.presets.MultiBackendRendererCfg`): + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Name + - Renderer + * - ``default`` / ``isaacsim_rtx_renderer`` + - Isaac Sim RTX renderer (used when no ``renderer=`` or ``presets=`` is given) + * - ``newton_renderer`` + - Newton Warp renderer + * - ``ovrtx_renderer`` + - OV RTX renderer + +Domain presets (observation modes, camera configurations, etc.) are task-specific. +Pass ``--task= --help`` to a training command to see all presets available +for that task, grouped by selector type: + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rl_games \ + --task Isaac-Cartpole-Camera-Presets-Direct-v0 --help + +.. note:: + + Legacy aliases ``newton`` → ``newton_mjwarp`` and ``kamino`` → ``newton_kamino`` + are still accepted but emit a :class:`FutureWarning`. Prefer the canonical names. + + +Using Presets +^^^^^^^^^^^^^ + +**Typed selectors** -- preferred form for physics and renderer backends: + +.. code-block:: bash + + # Switch to Newton MuJoCo-Warp physics + python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 physics=newton_mjwarp + + # Switch to Newton renderer for camera environments + python train.py --task=Isaac-Cartpole-Camera-Presets-Direct-v0 renderer=newton_renderer + + # Combine typed selectors -- each one applies to its own PresetCfg type + python train.py --task=Isaac-Cartpole-Camera-Presets-Direct-v0 \ + physics=newton_mjwarp renderer=newton_renderer presets=rgb + +**Path presets** -- select a specific preset for one config path: + +.. code-block:: bash + + python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 \ + env.events=newton_mjwarp + +**Global presets** -- apply the same preset name everywhere it exists: + +.. code-block:: bash + + # Apply "newton_mjwarp" preset to all configs that define it + python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 \ + presets=newton_mjwarp + +**Multiple global presets** -- apply several non-conflicting presets: + +.. code-block:: bash + + python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 \ + presets=newton_mjwarp,inference + +**Combined** -- global presets + scalar overrides: + +.. code-block:: bash + + python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 \ + presets=newton_mjwarp \ + env.sim.dt=0.002 + + +Global Preset Conflict Detection +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If two global presets both match the same config path, an error is raised +so the ambiguity is caught early: + +.. code-block:: text + + ValueError: Conflicting global presets: 'foo' and 'bar' + both define preset for 'env.events' + + +Real-World Example +^^^^^^^^^^^^^^^^^^ + +The ANYmal-C locomotion environment shows both ``PresetCfg`` and ``preset()`` +working together: + +.. literalinclude:: ../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py + :language: python + :lines: 21-42 + +A single ``presets=newton_mjwarp`` on the command line resolves every ``PresetCfg`` +and ``preset()`` that defines a ``newton_mjwarp`` field: the physics engine is swapped +to Newton, ``AnymalCEventsCfg`` selects Newton-compatible events, and the +actuator armature is set to ``0.01``. + +.. code-block:: bash + + # Default (PhysX events, armature=0.0) + python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 + + # MJWarp (Newton events, armature=0.01) + python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 presets=newton_mjwarp + + +Summary +^^^^^^^ + +.. list-table:: + :widths: 25 35 40 + :header-rows: 1 + + * - Override Type + - Syntax + - Effect + * - Scalar + - ``env.sim.dt=0.001`` + - Modify single field + * - Path preset + - ``env.events=newton_mjwarp`` + - Replace entire section + * - Global preset + - ``presets=newton_mjwarp`` + - Apply everywhere matching + * - Typed physics selector + - ``physics=newton_mjwarp`` + - Selects a :class:`~isaaclab.physics.PhysicsCfg` variant; folds into ``presets=`` + * - Typed renderer selector + - ``renderer=newton_renderer`` + - Selects a :class:`~isaaclab.renderers.renderer_cfg.RendererCfg` variant; folds into ``presets=`` + * - Combined + - ``physics=newton_mjwarp renderer=newton_renderer presets=rgb env.sim.dt=0.001`` + - Typed selectors + domain preset + scalar override diff --git a/simulation/modules/IsaacLab/docs/source/features/isaac_teleop.rst b/simulation/modules/IsaacLab/docs/source/features/isaac_teleop.rst new file mode 100644 index 0000000000000000000000000000000000000000..86f3212aa01bb30b1f305a51a6a117d9dcc5fde3 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/features/isaac_teleop.rst @@ -0,0 +1,1210 @@ +.. _isaac-teleop-feature: + +Isaac Teleop +============ + +.. currentmodule:: isaaclab + +`Isaac Teleop `_ is the unified framework for high-fidelity +egocentric and robot data collection. It provides a standardized device interface, a flexible +graph-based retargeting pipeline, and works seamlessly across simulated and real-world robots. + +Isaac Teleop replaces the previous native XR teleop stack (``isaaclab.devices.openxr``) in Isaac +Lab. For migration details see :ref:`migrating-to-isaaclab-3-0`. + +.. tip:: + + **Just want to get running?** Follow the :ref:`cloudxr-teleoperation` how-to guide for + installation and first-run steps, then come back here for deeper topics. + + +.. _isaac-teleop-supported-devices: + +Supported Devices +----------------- + +Isaac Teleop supports multiple XR headsets and tracking peripherals. Each device provides different +input modes, which determine which retargeters and control schemes are available. + +.. list-table:: + :header-rows: 1 + :widths: 20 25 25 30 + + * - Device + - Input Modes + - Client / Connection + - Notes + * - Apple Vision Pro + - Hand tracking (26 joints), spatial controllers + - Native visionOS app (`Isaac XR Teleop Sample Client`_) + - Build from source; see :ref:`build-apple-vision-pro` + * - Meta Quest 3 + - Motion controllers (triggers, thumbsticks, squeeze), hand tracking + - CloudXR.js WebXR client (browser) + - `CloudXR client `__; see :ref:`connection guide ` + * - Pico 4 Ultra + - Motion controllers, hand tracking + - CloudXR.js WebXR client (browser) + - Requires Pico OS 15.4.4U+; must use HTTPS mode + * - Manus Gloves + - High-fidelity finger tracking (Manus SDK) + - Isaac Teleop plugin (bundled) + - Migrated from the now-deprecated ``isaac-teleop-device-plugins`` repo. + Combine with an external wrist-tracking source for wrist positioning. See :ref:`manus-vive-handtracking`. + + +.. _isaac-teleop-control-schemes: + +Choose a Control Scheme +----------------------- + +The right combination of input device and retargeters depends on your task. Use this table as a +starting point, then see the detailed pipeline examples below. + +.. list-table:: + :header-rows: 1 + :widths: 22 18 30 10 20 + + * - Task Type + - Recommended Input + - Retargeters + - Action Dim + - Reference Config + * - Manipulation (e.g. Franka) + - Motion controllers + - ``Se3AbsRetargeter`` + ``GripperRetargeter`` + - 8 + - ``stack_ik_abs_env_cfg.py`` + * - Bimanual dex + locomotion (e.g. G1 TriHand) + - Motion controllers + - Bimanual ``Se3AbsRetargeter`` + ``TriHandMotionControllerRetargeter`` + ``LocomotionRootCmdRetargeter`` + - 32 + - ``locomanipulation_g1_env_cfg.py`` + * - Bimanual dex, fixed base (e.g. G1) + - Motion controllers + - Bimanual ``Se3AbsRetargeter`` + ``TriHandMotionControllerRetargeter`` + - 28 + - ``fixed_base_upper_body_ik_g1_env_cfg.py`` + * - Complex dex hand (e.g. GR1T2, G1 Inspire) + - Hand tracking / Manus gloves + - Bimanual ``Se3AbsRetargeter`` + ``DexBiManualRetargeter`` + - 36+ + - ``pickplace_gr1t2_env_cfg.py`` + +**Why motion controllers for manipulation?** Controllers provide precise spatial control via a grip +pose and a physical trigger for gripper actuation, making them ideal for pick-and-place tasks. + +**Why hand tracking for complex dex hands?** Hand tracking captures the full 26-joint hand pose +required for high-fidelity dexterous retargeting. This is essential when individual finger control +matters. + + +.. _isaac-teleop-architecture: + +How It Works +------------ + +The :class:`~isaaclab_teleop.IsaacTeleopDevice` is the main integration point between Isaac Teleop +and Isaac Lab. It composes three collaborators: + +* **XrAnchorManager** -- creates and synchronizes an XR anchor prim in the simulation, and + computes the ``world_T_anchor`` transform matrix that maps XR tracking data into the simulation + coordinate frame. + +* **TeleopSessionLifecycle** -- builds the retargeting pipeline, acquires OpenXR handles from + Isaac Sim's XR bridge, creates the ``TeleopSession``, and steps it each frame to produce an + action tensor. + +* **CommandHandler** -- lightweight callback registry for START / STOP / RESET commands. Scripts + can register callbacks via :meth:`~isaaclab_teleop.IsaacTeleopDevice.add_callback`, but the + primary control path uses :func:`~isaaclab_teleop.poll_control_events` (see + :ref:`isaac-teleop-control-states`). + +.. dropdown:: Session lifecycle details + + The session uses **deferred creation**: if the user has not yet clicked "Start XR" in the Isaac + Sim UI, the session is not created immediately. Instead, each call to ``advance()`` retries + session creation until OpenXR handles become available. Once connected, ``advance()`` returns a + flattened action tensor (``torch.Tensor``) on the configured device. It returns ``None`` when + the session is not yet ready or has been torn down. + + +.. _isaac-teleop-control-states: + +Teleop Control States (Start / Stop / Reset) +--------------------------------------------- + +Isaac Lab supports remote teleop control commands -- **start**, **stop**, and **reset** -- sent +from the XR headset to the simulation. These are used to begin and end demonstration recording, +pause the robot, or reset the environment without touching the simulation host. + +How it works +~~~~~~~~~~~~ + +By default, every :class:`~isaaclab_teleop.IsaacTeleopCfg` enables a control message channel +using the well-known UUID ``uuid5(NAMESPACE_DNS, "teleop_command")``. The channel is created as +a ``teleop_control_pipeline`` inside TeleopCore's :class:`TeleopSession`, which means: + +1. A :class:`~isaacteleop.retargeting_engine.deviceio_source_nodes.MessageChannelSource` opens an + OpenXR opaque data channel (``XR_NV_opaque_data_channel``) with the agreed-upon UUID. +2. The CloudXR JS client (or any other client) discovers the channel by UUID and sends UTF-8 + JSON commands:: + + {"type": "teleop_command", "message": {"command": "start teleop"}} + {"type": "teleop_command", "message": {"command": "stop teleop"}} + {"type": "teleop_command", "message": {"command": "reset teleop"}} + +3. A :class:`~isaaclab_teleop.teleop_message_processor.TeleopMessageProcessor` parses these + payloads and produces boolean pulse signals (``run_toggle``, ``kill``, ``reset``). +4. :class:`~isaacteleop.teleop_session_manager.DefaultTeleopStateManager` consumes the + boolean signals, runs its state machine (edge detection, fail-safe), and produces + ``teleop_state`` (one-hot) and ``reset_event`` (bool pulse) outputs. +5. TeleopCore decodes these outputs into ``ExecutionEvents`` and injects them into every + retargeter's ``ComputeContext``, so stateful retargeters can react to state changes + (e.g. reinitializing cross-step state on reset). + +Polling control events in your script +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Use :func:`~isaaclab_teleop.poll_control_events` to read the latest control state each frame: + +.. code-block:: python + + from isaaclab_teleop import poll_control_events + + with IsaacTeleopDevice(cfg) as device: + running = False + while sim_app.is_running(): + action = device.advance() + + ctrl = poll_control_events(device) + if ctrl.is_active is not None: + running = ctrl.is_active # True after "start", False after "stop" + if ctrl.should_reset: + env.reset() # "reset" command received this frame + + if action is not None and running: + env.step(action.repeat(num_envs, 1)) + else: + env.sim.render() + +:class:`~isaaclab_teleop.ControlEvents` has two fields: + +* ``is_active`` -- ``True`` after a "start" command, ``False`` after "stop", ``None`` when no + command has been received yet (callers should leave their own flag unchanged). +* ``should_reset`` -- ``True`` for exactly one frame after a "reset" command. + +Disabling the control channel +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you do not need headset-driven start/stop/reset (e.g. keyboard-only workflows), set +``control_channel_uuid=None`` in your config: + +.. code-block:: python + + IsaacTeleopCfg( + pipeline_builder=_build_my_pipeline, + control_channel_uuid=None, # no opaque data channel created + ) + +Using a custom channel UUID +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To use a different channel UUID (e.g. for a separate control protocol), pass any 16-byte +``bytes`` value: + +.. code-block:: python + + import uuid + + MY_UUID = uuid.uuid5(uuid.NAMESPACE_DNS, "my_custom_control").bytes + + IsaacTeleopCfg( + pipeline_builder=_build_my_pipeline, + control_channel_uuid=MY_UUID, + ) + +The CloudXR JS client must be updated to discover this UUID when sending commands. + + +.. _isaac-teleop-retargeting: + +Retargeting Framework +--------------------- + +Isaac Teleop uses a graph-based retargeting pipeline. Data flows from **source nodes** through +**retargeters** and is combined into a single action tensor. + +Source Nodes +~~~~~~~~~~~~ + +* ``HandsSource`` -- provides hand tracking data (left/right, 26 joints each). +* ``ControllersSource`` -- provides motion controller data (grip pose, trigger, thumbstick, etc.). + +Available Retargeters +~~~~~~~~~~~~~~~~~~~~~ + +Retargeters are provided by the ``isaacteleop`` package from the +`Isaac Teleop `_ repository. The retargeters listed below +are those used by the built-in Isaac Lab environments. Isaac Teleop may offer additional +retargeters not listed here -- refer to the +`Isaac Teleop repository `_ for the full set. + +.. dropdown:: Se3AbsRetargeter / Se3RelRetargeter + + Maps hand or controller tracking to end-effector pose. ``Se3AbsRetargeter`` outputs a 7D + absolute pose (position + quaternion). ``Se3RelRetargeter`` outputs a 6D delta. + Configurable rotation offsets (roll, pitch, yaw in degrees). + +.. dropdown:: GripperRetargeter + + Outputs a single float (-1.0 closed, 1.0 open). Uses controller trigger (priority) or + thumb-index pinch distance from hand tracking. + +.. dropdown:: DexHandRetargeter / DexBiManualRetargeter + + Retargets full hand tracking (26 joints) to robot-specific hand joint angles using the + ``dex-retargeting`` library. Requires a robot hand URDF and a YAML configuration file. + + .. warning:: + + The links used for retargeting must be defined at the actual fingertips, not in the middle + of the fingers, to ensure accurate optimization. + +.. dropdown:: TriHandMotionControllerRetargeter + + Maps VR controller buttons (trigger, squeeze) to G1 TriHand joints (7 DOF per hand). Simple + mapping: trigger controls the index finger, squeeze controls the middle finger, and both + together control the thumb. + +.. dropdown:: LocomotionRootCmdRetargeter + + Maps controller thumbsticks to a 4D locomotion command: + ``[vel_x, vel_y, rot_vel_z, hip_height]``. + +.. dropdown:: TensorReorderer + + Utility that flattens and reorders outputs from multiple retargeters into a single 1D action + tensor. The ``output_order`` must match the action space expected by the environment. + +The built-in Isaac Lab environments use these retargeters as follows: + +.. list-table:: + :header-rows: 1 + :widths: 40 60 + + * - Environment + - Retargeters Used + * - Franka manipulation (stack, pick-place) + - ``Se3AbsRetargeter``, ``GripperRetargeter``, ``TensorReorderer`` + * - G1 Inspire dexterous pick-place + - ``Se3AbsRetargeter``, ``DexHandRetargeter``, ``TensorReorderer`` + * - GR1-T2 dexterous pick-place + - ``Se3AbsRetargeter``, ``DexHandRetargeter``, ``TensorReorderer`` + * - G1 upper-body (fixed base) + - ``Se3AbsRetargeter``, ``TriHandMotionControllerRetargeter``, ``TensorReorderer`` + * - G1 loco-manipulation + - ``Se3AbsRetargeter``, ``TriHandMotionControllerRetargeter``, ``LocomotionRootCmdRetargeter``, ``TensorReorderer`` + + +.. _isaac-teleop-env-control-reference: + +Teleoperation Environment Reference +----------------------------------- + +The tables below list every built-in Isaac Lab environment that supports teleoperation, +organized by input method. Environments whose Task ID ends in ``-Play`` are designed for +closed-loop policy evaluation and are not included here. + +Isaac Teleop (XR Headset) Environments +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +These environments use the Isaac Teleop XR pipeline with motion controllers or hand tracking. + +.. list-table:: + :header-rows: 1 + :widths: 28 14 14 44 + + * - Task ID + - Input Mode + - Hands + - Operator Interaction + * - ``Isaac-Stack-Cube-Franka-IK-Abs-v0`` + - Controllers + - Right + - **Arm:** right controller grip pose drives end-effector. + **Gripper:** right trigger. + * - ``Isaac-PickPlace-GR1T2-Abs-v0`` + - Hand tracking + - Both + - **Arms:** left/right hand wrist pose drives each end-effector. + **Hands:** full 26-joint hand tracking retargeted to 11 DOF per Fourier hand via ``DexHandRetargeter``. + * - ``Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0`` + - Hand tracking + - Both + - Same as ``Isaac-PickPlace-GR1T2-Abs-v0`` with waist DOFs enabled. + * - ``Isaac-NutPour-GR1T2-Pink-IK-Abs-v0`` + - Hand tracking + - Both + - Same retargeting pipeline as ``Isaac-PickPlace-GR1T2-Abs-v0`` (different task scene). + * - ``Isaac-ExhaustPipe-GR1T2-Pink-IK-Abs-v0`` + - Hand tracking + - Both + - Same retargeting pipeline as ``Isaac-PickPlace-GR1T2-Abs-v0`` (different task scene). + * - ``Isaac-PickPlace-G1-InspireFTP-Abs-v0`` + - Hand tracking + - Both + - **Arms:** left/right hand wrist pose drives each end-effector. + **Hands:** full 26-joint hand tracking retargeted to 12 DOF per Inspire hand via ``DexHandRetargeter``. + * - ``Isaac-PickPlace-FixedBaseUpperBodyIK-G1-Abs-v0`` + - Controllers + - Both + - **Arms:** left/right controller grip pose drives each end-effector. + **Hands:** trigger closes index, squeeze closes middle, both together close thumb (7 DOF TriHand per hand). + * - ``Isaac-PickPlace-Locomanipulation-G1-Abs-v0`` + - Controllers + - Both + - **Arms:** same as fixed-base G1 above. + **Hands:** same TriHand mapping. + **Locomotion:** left thumbstick = linear velocity (x/y), right thumbstick X = rotational velocity, right thumbstick Y = hip height. + +.. tip:: + + **Controllers** provide a grip pose plus physical buttons (trigger, squeeze, thumbstick), + ideal for tasks that need a gripper or simple hand mapping. **Hand tracking** captures 26 + wrist and finger joints per hand, required for dexterous retargeting to complex robot hands. + +Keyboard and SpaceMouse Environments +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. note:: + + Keyboard and SpaceMouse teleoperation uses the legacy native Isaac Lab teleop stack + (``isaaclab.devices``), not Isaac Teleop. These environments do not require an XR headset. + +The device button layouts below apply to all environments in this section. Per-environment +differences (gripper enabled/disabled, sensitivity) are noted in the environment table that +follows. + +**Keyboard** + +.. list-table:: + :header-rows: 1 + :widths: 20 20 60 + + * - Function + - Keys + - Description + * - Position X + - ``W`` / ``S`` + - Move end-effector forward / backward. + * - Position Y + - ``A`` / ``D`` + - Move end-effector left / right. + * - Position Z + - ``Q`` / ``E`` + - Move end-effector up / down. + * - Roll + - ``Z`` / ``X`` + - Rotate about X axis. + * - Pitch + - ``T`` / ``G`` + - Rotate about Y axis. + * - Yaw + - ``C`` / ``V`` + - Rotate about Z axis. + * - Gripper toggle + - ``K`` + - Open / close gripper or suction (disabled in Reach envs). + * - Reset + - ``L`` + - Clear accumulated delta pose and gripper state. + +**SpaceMouse** + +.. list-table:: + :header-rows: 1 + :widths: 20 20 60 + + * - Function + - Control + - Description + * - Translation + - 6-DOF knob + - Push/pull/slide the knob to move the end-effector in X/Y/Z. + * - Rotation + - 6-DOF knob + - Tilt/twist the knob to rotate the end-effector in roll/pitch/yaw. + * - Gripper toggle + - Left button + - Open / close gripper or suction (disabled in Reach envs). + * - Reset + - Right button + - Clear accumulated delta pose and gripper state. + +**Gamepad** (Reach environments only) + +.. list-table:: + :header-rows: 1 + :widths: 20 20 60 + + * - Function + - Control + - Description + * - Position X / Y + - Left stick + - Move end-effector forward/backward and left/right. + * - Position Z + - Right stick (up/down) + - Move end-effector up / down. + * - Roll / Pitch + - D-Pad + - Left/right for roll, up/down for pitch. + * - Yaw + - Right stick (left/right) + - Rotate about Z axis. + * - Gripper toggle + - X button + - Open / close gripper (disabled in Reach envs). + +.. list-table:: + :header-rows: 1 + :widths: 34 18 48 + + * - Task ID + - Devices + - Operator Interaction + * - ``Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-RmpFlow-v0`` + - Keyboard, SpaceMouse + - **Arm:** end-effector pose via RMPFlow. + **Gripper:** ``K`` on keyboard, left button on SpaceMouse. + * - ``Isaac-Stack-Cube-Galbot-Right-Arm-Suction-RmpFlow-v0`` + + **Note:** With the RMPFlow controller, avoid colliding with + the cubes during teleoperation: contact forces cause the + controller to overtune and the arm to drift. Move the + end-effector close to and just above the cube, stop, then + close the suction cup. + - Keyboard, SpaceMouse + - **Arm:** end-effector pose via RMPFlow. + **Suction:** ``K`` on keyboard, left button on SpaceMouse. + * - ``Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor-v0`` + - Keyboard, SpaceMouse + - Same as left-arm gripper above with camera observations. + * - ``Isaac-Place-Mug-Agibot-Left-Arm-RmpFlow-v0`` + - Keyboard, SpaceMouse + - **Arm:** left-arm end-effector pose via RMPFlow. + **Gripper:** ``K`` on keyboard, left button on SpaceMouse. + * - ``Isaac-Place-Toy2Box-Agibot-Right-Arm-RmpFlow-v0`` + - Keyboard, SpaceMouse + - **Arm:** right-arm end-effector pose via RMPFlow. + **Gripper:** ``K`` on keyboard, left button on SpaceMouse. + * - ``Isaac-Stack-Cube-UR10-Long-Suction-IK-Rel-v0`` + - Keyboard, SpaceMouse + - **Arm:** relative IK end-effector control. + **Suction:** ``K`` on keyboard, left button on SpaceMouse. + * - ``Isaac-Stack-Cube-UR10-Short-Suction-IK-Rel-v0`` + - Keyboard, SpaceMouse + - Same as long-suction UR10 above with a shorter suction cup. + * - ``Isaac-Reach-Franka-IK-Rel-v0`` + - Keyboard, Gamepad, SpaceMouse + - **Arm:** relative IK end-effector control. Gripper disabled. + + +.. note:: + + Humanoid arms (e.g. Galbot, Agibot) have joint limits that inverse kinematics must respect. + The differential IK controller ignores these limits, so RMPFlow is preferred for teleoperating + them as it enforces joint limits while solving IK. Consequently, the arm may occasionally stop + responding when the commanded target pose is unreachable within those limits -- this is expected, + not a bug. + +.. _isaac-teleop-switching-input-mode: + +Switch Between Controllers and Hand Tracking +--------------------------------------------- + +The retargeting pipeline determines whether an environment uses motion controllers or hand +tracking. Switching input modes requires changing the ``pipeline_builder`` function in your +environment config. No other environment-level changes are needed as long as the action +space (``TensorReorderer`` output order) stays the same. + +**Controller to hand tracking** + +The key changes are: + +#. Create a ``HandsSource`` and apply the world-to-anchor transform to it (instead of + ``ControllersSource``). +#. Point the ``Se3RetargeterConfig.input_device`` at the appropriate ``HandsSource`` key. +#. Set ``use_wrist_rotation=True`` and ``use_wrist_position=True`` so that the SE3 retargeter + reads from the hand wrist joint rather than the controller grip pose. +#. The ``GripperRetargeter`` already supports both inputs -- it uses the controller trigger + when connected to a ``ControllersSource`` or thumb-index pinch when connected to a + ``HandsSource``. + +Here is the Franka stack environment's controller-based pipeline alongside a hand-tracking +variant for comparison. + +**Original (controller-based):** + +.. code-block:: python + :emphasize-lines: 4-5,10-12 + + # SE3: tracks right controller grip pose + se3_cfg = Se3RetargeterConfig( + input_device=ControllersSource.RIGHT, + use_wrist_rotation=False, + use_wrist_position=False, + target_offset_roll=90.0, + ) + se3 = Se3AbsRetargeter(se3_cfg, name="ee_pose") + connected_se3 = se3.connect({ + ControllersSource.RIGHT: transformed_controllers.output( + ControllersSource.RIGHT + ), + }) + +**Modified (hand-tracking-based):** + +.. code-block:: python + :emphasize-lines: 2-5,9-11 + + se3_cfg = Se3RetargeterConfig( + input_device=HandsSource.RIGHT, + use_wrist_rotation=True, + use_wrist_position=True, + target_offset_roll=0.0, + ) + se3 = Se3AbsRetargeter(se3_cfg, name="ee_pose") + + transformed_hands = hands.transformed(transform_input.output(ValueInput.VALUE)) + connected_se3 = se3.connect({ + HandsSource.RIGHT: transformed_hands.output(HandsSource.RIGHT), + }) + +The ``GripperRetargeter`` needs no changes -- it accepts both controller and hand inputs and +uses whichever source is connected. + +**Hand tracking to controller** + +Reverse the steps above: set ``input_device`` to a ``ControllersSource`` key, transform the +controllers instead of the hands, and set ``use_wrist_rotation=False`` and +``use_wrist_position=False``. Adjust ``target_offset_roll/pitch/yaw`` to account for the +controller grip frame orientation (typically 90 degrees roll for Franka-style grippers). + +.. note:: + + When switching between input modes, you may need to tune the ``target_offset_roll``, + ``target_offset_pitch``, and ``target_offset_yaw`` values. Controller grip frames and hand + wrist frames have different default orientations relative to the robot end-effector. + + +.. _isaac-teleop-pipeline-builder: + +Build a Retargeting Pipeline +---------------------------- + +A pipeline builder is a callable that constructs the retargeting graph and returns an +``OutputCombiner`` with a single ``"action"`` key. Here is a complete example for a Franka +manipulator (from ``stack_ik_abs_env_cfg.py``): + +.. code-block:: python + + def _build_franka_stack_pipeline(): + from isaacteleop.retargeting_engine.deviceio_source_nodes import ControllersSource, HandsSource + from isaacteleop.retargeting_engine.interface import OutputCombiner, ValueInput + from isaacteleop.retargeters import ( + GripperRetargeter, GripperRetargeterConfig, + Se3AbsRetargeter, Se3RetargeterConfig, + TensorReorderer, + ) + from isaacteleop.retargeting_engine.tensor_types import TransformMatrix + + # 1. Create input sources + controllers = ControllersSource(name="controllers") + hands = HandsSource(name="hands") + + # 2. Apply coordinate-frame transform (world_T_anchor provided by IsaacTeleopDevice) + transform_input = ValueInput("world_T_anchor", TransformMatrix()) + transformed_controllers = controllers.transformed( + transform_input.output(ValueInput.VALUE) + ) + + # 3. Create and connect retargeters + se3_cfg = Se3RetargeterConfig( + input_device=ControllersSource.RIGHT, + target_offset_roll=90.0, + ) + se3 = Se3AbsRetargeter(se3_cfg, name="ee_pose") + connected_se3 = se3.connect({ + ControllersSource.RIGHT: transformed_controllers.output(ControllersSource.RIGHT), + }) + + gripper_cfg = GripperRetargeterConfig(hand_side="right") + gripper = GripperRetargeter(gripper_cfg, name="gripper") + connected_gripper = gripper.connect({ + ControllersSource.RIGHT: transformed_controllers.output(ControllersSource.RIGHT), + HandsSource.RIGHT: hands.output(HandsSource.RIGHT), + }) + + # 4. Flatten into a single action tensor with TensorReorderer + ee_elements = ["pos_x", "pos_y", "pos_z", "quat_x", "quat_y", "quat_z", "quat_w"] + reorderer = TensorReorderer( + input_config={ + "ee_pose": ee_elements, + "gripper_command": ["gripper_value"], + }, + output_order=ee_elements + ["gripper_value"], + name="action_reorderer", + input_types={"ee_pose": "array", "gripper_command": "scalar"}, + ) + connected_reorderer = reorderer.connect({ + "ee_pose": connected_se3.output("ee_pose"), + "gripper_command": connected_gripper.output("gripper_command"), + }) + + # 5. Return OutputCombiner with "action" key + return OutputCombiner({"action": connected_reorderer.output("output")}) + +.. tip:: + + The ``output_order`` of the ``TensorReorderer`` must match the action space of your environment. + Mismatches will cause silent control errors. + + +.. _isaac-teleop-env-config: + +Configure Your Environment +-------------------------- + +Register the pipeline in your environment configuration using :class:`~isaaclab_teleop.IsaacTeleopCfg`: + +.. code-block:: python + + from isaaclab_teleop import IsaacTeleopCfg, XrCfg + + @configclass + class MyTeleopEnvCfg(ManagerBasedRLEnvCfg): + + xr: XrCfg = XrCfg(anchor_pos=(0.5, 0.0, 0.5)) + + def __post_init__(self): + super().__post_init__() + + self.isaac_teleop = IsaacTeleopCfg( + pipeline_builder=_build_my_pipeline, + sim_device=self.sim.device, + xr_cfg=self.xr, + ) + +Key ``IsaacTeleopCfg`` fields: + +* ``pipeline_builder`` -- callable that returns an ``OutputCombiner`` with an ``"action"`` output. +* ``retargeters_to_tune`` -- optional callable returning retargeters to expose in the live tuning UI. +* ``xr_cfg`` -- :class:`~isaaclab_teleop.XrCfg` for anchor configuration (see below). +* ``plugins`` -- list of Isaac Teleop plugin configurations (e.g. Manus). +* ``sim_device`` -- torch device string (default ``"cuda:0"``). +* ``retargeting_execution`` -- IsaacTeleop retargeting execution settings. + Defaults to ``RetargetingExecutionConfig(mode="pipelined")`` with + ``DeadlinePacingConfig(safety_margin_s=0.025)`` so retargeting can run on + the IsaacTeleop worker instead of blocking the simulation loop. + The 25 ms safety margin staggers IsaacTeleop's Python work behind Isaac + Lab's step Python, giving native work such as rendering time to overlap + instead of having both Python stacks contend for the GIL at the start of + the step. + +.. warning:: + + ``pipeline_builder`` and ``retargeters_to_tune`` must be **callables** (functions or lambdas), + not pre-built objects. The ``@configclass`` decorator deep-copies mutable attributes, which + would break pre-built pipeline graphs. + + +.. _isaac-teleop-cloudxr-profiles: + +CloudXR Environment Profiles +----------------------------- + +Isaac Lab ships two ``.env`` profiles that configure the CloudXR runtime for different XR devices. +These are bundled inside the ``isaaclab_teleop`` package and can be referenced via constants: + +.. list-table:: + :header-rows: 1 + :widths: 28 24 20 18 20 + + * - Constant + - File + - ``NV_DEVICE_PROFILE`` + - ``NV_CXR_ENABLE_PUSH_DEVICES`` + - ``NV_ENABLE_POSE_WAIT`` + * - :data:`~isaaclab_teleop.CLOUDXR_JS_ENV` + - ``cloudxrjs-cloudxr.env`` + - ``auto-webrtc`` + - ``0`` + - ``0`` + * - :data:`~isaaclab_teleop.CLOUDXR_AVP_ENV` + - ``avp-cloudxr.env`` + - ``auto-native`` + - ``0`` + - ``0`` + +Both profiles set ``NV_CXR_ENABLE_PUSH_DEVICES=0``, which is correct for headset optical hand +tracking (the most common setup). For external push-device peripherals such as Manus gloves, set +this to ``1`` in a custom profile (see below). +They also set ``NV_ENABLE_POSE_WAIT=0`` so CloudXR does not throttle the application when frame +times spike. This favors lower latency over CloudXR's pose-wait smoothing. + +Override at launch time +~~~~~~~~~~~~~~~~~~~~~~~ + +The ``--cloudxr_env`` flag on ``teleop_se3_agent.py`` and ``record_demos.py`` selects which +``.env`` profile to use. The default is ``cloudxrjs`` (Quest/Pico). Use the ``avp`` shorthand +for Apple Vision Pro, or pass a full file path for a custom profile: + +.. code-block:: bash + + # Use the AVP profile + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ + --visualizer kit --xr \ + --cloudxr_env avp + +Create a custom profile +~~~~~~~~~~~~~~~~~~~~~~~ + +Copy a shipped profile and edit it: + +.. code-block:: bash + + # Start from the Quest/Pico profile + cp $(python -c "from isaaclab_teleop import CLOUDXR_JS_ENV; print(CLOUDXR_JS_ENV)") ~/my-cloudxr.env + +Edit ``~/my-cloudxr.env`` to change any values (e.g. ``NV_CXR_ENABLE_PUSH_DEVICES=1`` for +Manus gloves), then pass it via ``--cloudxr_env ~/my-cloudxr.env``. + +Disable auto-launch +~~~~~~~~~~~~~~~~~~~ + +If you prefer to run the CloudXR runtime manually in a separate terminal +(``python -m isaacteleop.cloudxr``), you can disable auto-launch in several ways: + +* **CLI flag**: ``--no-auto_launch_cloudxr`` on the teleop script. +* **Disable CloudXR entirely**: ``--cloudxr_env none``. +* **Environment variable**: ``ISAACLAB_CXR_SKIP_AUTOLAUNCH=1`` overrides the CLI flag at runtime. + +.. code-block:: bash + + # Disable via CLI flag + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ + --visualizer kit --xr \ + --no-auto_launch_cloudxr + + # Or disable via environment variable + ISAACLAB_CXR_SKIP_AUTOLAUNCH=1 ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ + --visualizer kit --xr + + +.. _isaac-teleop-xr-anchor: + +Configure the XR Anchor +------------------------ + +The :class:`~isaaclab_teleop.XrCfg` controls how the simulation is positioned and oriented in the +XR device's view. + +``anchor_pos`` / ``anchor_rot`` + Static anchor placement. The simulation point at these coordinates appears at the XR device's + local origin (floor level). Set to a point on the floor beneath the robot to position it in + front of the user. + +``anchor_prim_path`` + Attach the anchor to a USD prim for dynamic positioning. Use this for locomotion tasks where + the robot moves and the XR camera should follow. + +``anchor_rotation_mode`` + Controls how anchor rotation behaves: + + .. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Mode + - Description + * - ``FIXED`` + - Sets rotation once from ``anchor_rot``. Best for static manipulation setups. + * - ``FOLLOW_PRIM`` + - Rotation continuously tracks the attached prim. Best for locomotion where the user + should face the robot's heading direction. + * - ``FOLLOW_PRIM_SMOOTHED`` + - Same as ``FOLLOW_PRIM`` with slerp interpolation. Controlled by + ``anchor_rotation_smoothing_time`` (seconds, default 1.0). Reduces motion sickness from + abrupt rotation changes. Typical range: 0.3--1.5 s. + * - ``CUSTOM`` + - User-provided callable + ``anchor_rotation_custom_func(headpose, primpose) -> quaternion`` for fully custom logic. + +``fixed_anchor_height`` + When ``True`` (default), keeps the anchor height at its initial value. Prevents vertical + bobbing during locomotion. + +``near_plane`` + Closest render distance for the XR device (default 0.15 m). + +.. note:: + + On Apple Vision Pro, the local coordinate frame can be reset to a point on the floor beneath + the user by holding the digital crown. + +.. tip:: + + When using XR, call :func:`~isaaclab_teleop.remove_camera_configs` on your env config to strip + camera sensors. Additional cameras cause GPU contention and degrade XR performance. + + +.. _isaac-teleop-imitation-learning: + +Record Demonstrations for Imitation Learning +--------------------------------------------- + +Isaac Teleop integrates with Isaac Lab's ``record_demos.py`` script for recording teleoperated +demonstrations. + +When your environment configuration has an ``isaac_teleop`` attribute, the script automatically +uses ``create_isaac_teleop_device()`` -- no ``--teleop_device`` flag is needed: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tools/record_demos.py \ + --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ + --visualizer kit \ + --xr + +Some environments use the legacy ``teleop_devices`` configuration instead of ``isaac_teleop`` +(e.g. the Galbot RmpFlow relative-mode tasks). For these, pass ``--teleop_device`` to select +the input device: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tools/record_demos.py \ + --task Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-RmpFlow-v0 \ + --visualizer kit \ + --teleop_device keyboard + +The workflow is: + +#. Configure your environment with ``IsaacTeleopCfg`` (see :ref:`isaac-teleop-env-config`) + or ``teleop_devices`` for legacy devices (keyboard, spacemouse). +#. Run ``record_demos.py`` with the task name. +#. For XR tasks: start AR, connect your XR device, and teleoperate. + For legacy tasks: use the configured input device directly. +#. Demonstrations are recorded to HDF5 files. +#. Use the recorded data with Isaac Lab Mimic or other imitation learning frameworks. + +For the broader imitation learning pipeline (replay, augmentation, policy training), see +:ref:`teleoperation-imitation-learning`. + + +.. _isaac-teleop-new-embodiment: + +Add a New Robot +--------------- + +To add teleoperation support for a new robot in Isaac Lab: + +#. **Choose a control scheme.** Refer to the :ref:`isaac-teleop-control-schemes` table to determine + which retargeters match your robot's capabilities. + +#. **Build the pipeline.** If existing retargeters are sufficient (e.g. ``Se3AbsRetargeter`` + + ``GripperRetargeter`` for a new manipulator), write a pipeline builder function following the + pattern in :ref:`isaac-teleop-pipeline-builder`. Configure the ``TensorReorderer`` output order + to match your environment's action space. + +#. **For dexterous hands**: create a robot hand URDF and YAML config for ``DexHandRetargeter``. + Ensure fingertip links are positioned at the actual fingertips, not mid-finger. + +#. **For a custom retargeter**: see :ref:`isaac-teleop-new-retargeter` below. + +#. **Configure the XR anchor** for your robot (static for manipulation, dynamic for locomotion). + See :ref:`isaac-teleop-xr-anchor`. + +#. **Register in env config** via ``IsaacTeleopCfg`` (see :ref:`isaac-teleop-env-config`). + + +.. _isaac-teleop-new-retargeter: + +Add a New Retargeter +-------------------- + +If the built-in retargeters do not cover your use case, you can implement a custom one in the +`Isaac Teleop repository `_: + +#. Inherit from ``BaseRetargeter`` and implement ``input_spec()``, ``output_spec()``, and + ``compute()``. +#. Optionally add a ``ParameterState`` for parameters that should be live-tunable via the + retargeter tuning UI. +#. Connect to existing source nodes (``HandsSource``, ``ControllersSource``) or create a new + ``IDeviceIOSource`` subclass for custom input devices. + +See the `Isaac Teleop repository `_ +and `Contributing Guide `_ for details. + + +.. _isaac-teleop-new-device: + +Add a New Device +---------------- + +There are two levels of device integration: + +**Isaac Teleop plugin (C++ level)** + For new hardware that requires a custom driver or SDK. Plugins push data via OpenXR tensor + collections. Existing plugins include Manus gloves, OAK-D camera, controller synthetic hands, + and foot pedals. After creating the plugin, update the retargeting pipeline config to consume + data from the new plugin's source node. + + See the `Plugins directory `_ for examples. + +**Pipeline configuration only** + For devices already supported by Isaac Teleop (or whose data is available as hand / controller + tracking). Simply update your ``pipeline_builder`` to use the appropriate source nodes and + retargeters for the device's data format. + + +.. _isaac-teleop-performance: + +Optimize XR Performance +----------------------- + +.. dropdown:: Configure the physics and render time step + :open: + + Ensure the simulation render time step roughly matches the XR device's display rate and can + be sustained in real time. Quest 3 and Pico 4 Ultra typically run at 90 Hz, so we recommend a + simulation ``dt`` of 90 Hz with a ``render_interval`` of 2 (rendering at 45 Hz): + + .. code-block:: python + + @configclass + class XrTeleopEnvCfg(ManagerBasedRLEnvCfg): + + def __post_init__(self): + self.sim.dt = 1.0 / 90 # physics steps at 90 Hz + self.sim.render_interval = 2 # one render per 2 physics steps -> 45 Hz + + ``sim.render_interval`` is the number of physics simulation steps that occur between + renders. Increasing it reduces rendering frequency (and GPU cost) without changing physics + behavior -- useful when physics can keep up but rendering cannot. + + The choice of ``sim.dt`` is a trade-off between stability and performance: a smaller ``dt`` + (e.g. ``1.0 / 120``) integrates contacts more accurately and is more stable for stiff + contact-rich tasks, but each step costs more wall-clock time and lowers achievable frame + rate. A larger ``dt`` (e.g. ``1.0 / 60``) is cheaper but can introduce contact jitter or + instabilities. Pick the largest ``dt`` your task tolerates. + +.. dropdown:: Switch the viewport to the RTX - Minimal renderer + :open: + + The RTX - Minimal renderer trades image fidelity for substantially lower per-frame GPU cost. + It is the recommended choice when the simulation cannot sustain the XR device's display rate + in real time -- for example on lower-spec GPUs, in scenes with many lights or complex + materials, or when you have already configured ``sim.dt`` and ``sim.render_interval`` and + still see dropped frames. + + .. admonition:: Known issue + :class: important + + Starting an XR session while RTX - Minimal is already the active renderer is a known + issue: robot control inputs may never be applied and teleoperation stays non-functional, + with no error reported. Switching to RTX - Minimal *after* the XR session has started and + teleoperation is confirmed working is not affected. + + As a workaround, start under the default renderer before switching to RTX - Minimal: + + #. Launch Isaac Lab with the default renderer and start the XR session. + #. Confirm that teleoperation is working (the robot responds to your hand motions). + #. Switch the viewport renderer to **RTX - Minimal** as described below. + + To enable it, click the renderer dropdown at the top-left of the Isaac Lab viewport and + select **RTX - Minimal**: + + .. figure:: ../_static/teleop/recommended-render-select.jpg + :width: 80% + :alt: Viewport renderer dropdown with RTX - Minimal selected + + Selecting the **RTX - Minimal** renderer from the viewport dropdown. + + For best results, open **Render Settings** from the top-right of the Isaac Lab UI, switch to + the **Minimal** tab, and set **Minimal Shading Mode** to **Diffuse/Glossy/Emission**: + + .. figure:: ../_static/teleop/recommended-render-settings.jpg + :width: 80% + :alt: Render Settings panel showing the Minimal Shading Mode options + + The **Render Settings** panel with the **Minimal Shading Mode** dropdown open + (recommended: **Diffuse/Glossy/Emission**). + + .. note:: + + The RTX Minimal renderer currently only supports ``DistantLight`` prims for scene + illumination -- ``DomeLight`` prims are ignored. If your environment uses a ``DomeLight``, + swap (or supplement) it with a ``DistantLight`` so the scene is lit when running under + RTX Minimal: + + .. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab.assets import AssetBaseCfg + + light = AssetBaseCfg( + prim_path="/World/light", + spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0), + ) + + Depending on your environment, the default ``DistantLight`` orientation may cast shadows + that overlap the robot and reduce visibility during teleoperation. If you encounter this, + adjust the light's orientation via ``init_state`` on :class:`~isaaclab.assets.AssetBaseCfg` + to position the light source at an angle that gives clear visibility: + + .. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab.assets import AssetBaseCfg + + light = AssetBaseCfg( + prim_path="/World/light", + spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0), + init_state=AssetBaseCfg.InitialStateCfg( + rot=(0.0, 0.0, 0.0, 1.0), # quaternion (x, y, z, w); adjust to reduce shadow overlap + ), + ) + + Experiment with different orientations in your scene to find an angle that avoids + shadow overlap on the robot. A slight tilt away from the camera viewpoint is a good + starting point. + +.. dropdown:: Lower the XR render resolution + :open: + + The XR render resolution multiplier scales the size of the render buffers that are then + upscaled to the headset's recommended display resolution. Lowering it trades image + sharpness for substantially lower per-frame GPU cost, which can help sustain real-time + frame rates on lower-spec GPUs or in heavy scenes. + + In the Isaac Lab UI, open the **XR** tab on the right-side panel, expand + **Advanced Settings -> Render Resolution**, and drag the **Resolution Multiplier** slider: + + .. figure:: ../_static/teleop/xr-resolution-slider.jpg + :width: 80% + :alt: XR Render Resolution slider in the Advanced Settings panel + + The **Resolution Multiplier** under **XR -> Advanced Settings -> Render Resolution**. + Values below ``1.0`` reduce the render-buffer size before upscaling to the headset. + + A value around ``0.8`` is usually a good starting point: noticeable GPU savings with minimal + perceptible quality loss. Reduce further only if you still cannot hit the headset's display + rate. + +.. dropdown:: Configure retargeting execution + :open: + + Isaac Teleop can run retargeting either synchronously on the application thread or + asynchronously through a pipelined worker. This is controlled by + ``RetargetingExecutionConfig``. + + In synchronous mode, retargeting runs inline with the simulation step. This can be the + best choice for lightweight retargeting or retargeting implemented mostly in Python, + since a background Python worker can still contend with the application thread through + the GIL. + + In pipelined mode, Isaac Teleop submits retargeting work to a background worker and the + application uses the most recent completed result. This is useful when retargeting has + enough native work to overlap with simulation or rendering, or when the retargeting cost + is large enough that running it inline would directly extend the frame. + + .. code-block:: python + + retargeting_execution=RetargetingExecutionConfig( + mode="pipelined", + pacing=DeadlinePacingConfig(safety_margin_s=0.025), + ) + + ``DeadlinePacingConfig`` intentionally delays the background retargeting work until + closer to when the next result is needed, instead of starting it immediately when the + request is submitted. This helps avoid competing with the Python work Isaac Lab performs + at the beginning of the frame, and tends to line the retargeting work up with rendering + or other native work where overlap is more useful. + + The ``safety_margin_s`` value controls how early retargeting starts before the predicted + deadline. A larger margin starts retargeting earlier, which gives heavier or more variable + retargeting work more time to finish before the next frame consumes the result. The + trade-off is that the input sample may be slightly older, and Python-heavy retargeting + may introduce more GIL contention. + + If retargeting is mostly Python and lightweight, consider ``mode="sync"``. If retargeting + performs substantial native work or has occasional long spikes, use ``mode="pipelined"`` + and increase ``safety_margin_s`` so the work starts earlier. + +.. dropdown:: Check CloudXR frame pacing + :open: + + The CloudXR Runtime frame pacer attempts to keep the client experience smooth. If the + application has repeated frame-time spikes, the pacer may settle at a lower stable frame + rate instead of oscillating between rates. This can make a connected client appear slower + even when Isaac Lab profiling does not show a proportional simulation-side regression. + + The shipped CloudXR profiles set ``NV_ENABLE_POSE_WAIT=0`` to mitigate this case, favoring lower + latency over pose-wait smoothing. If you use a custom ``.env`` file, copy that setting into the + custom profile, then point ``teleop_se3_agent.py`` or ``record_demos.py`` at it with + ``--cloudxr_env``. See :ref:`isaac-teleop-cloudxr-profiles` for the profile override workflow. + + +.. _isaac-teleop-known-issues: + +Known Issues +------------ + +* ``XR_ERROR_VALIDATION_FAILURE: xrWaitFrame(frameState->type == 0)`` when stopping AR Mode + + Can be safely ignored. Caused by a race condition in the exit handler. + +* ``XR_ERROR_INSTANCE_LOST in xrPollEvent`` + + Occurs if the CloudXR runtime exits before Isaac Lab. Restart the runtime to resume. + +* ``[omni.usd] TF_PYTHON_EXCEPTION`` when starting/stopping AR Mode + + Can be safely ignored. Caused by a race condition in the enter/exit handler. + +* ``Invalid version string in _ParseVersionString`` + + Caused by shader assets authored with older USD versions. Typically safe to ignore. + +* XR device connects but no video is displayed (viewport responds to tracking) + + The GPU index may differ between host and container. Set ``NV_GPU_INDEX`` to ``0``, ``1``, or + ``2`` in the runtime to match the host GPU. + + +.. _isaac-teleop-api-ref: + +API Reference +------------- + +See the :ref:`isaaclab_teleop-api` for full class and function documentation: + +* :class:`~isaaclab_teleop.IsaacTeleopCfg` +* :class:`~isaaclab_teleop.IsaacTeleopDevice` +* :func:`~isaaclab_teleop.create_isaac_teleop_device` +* :class:`~isaaclab_teleop.ControlEvents` +* :class:`~isaaclab_teleop.SupportsControlEvents` +* :func:`~isaaclab_teleop.poll_control_events` +* :data:`~isaaclab_teleop.TELEOP_CONTROL_CHANNEL_UUID` +* :class:`~isaaclab_teleop.XrCfg` +* :class:`~isaaclab_teleop.XrAnchorRotationMode` + + +.. + References +.. _`Isaac XR Teleop Sample Client`: https://github.com/isaac-sim/isaac-xr-teleop-sample-client-apple diff --git a/simulation/modules/IsaacLab/docs/source/features/multi_gpu.rst b/simulation/modules/IsaacLab/docs/source/features/multi_gpu.rst new file mode 100644 index 0000000000000000000000000000000000000000..e3a45d959bf3aeb2c86cee02cccd433be6a2dd95 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/features/multi_gpu.rst @@ -0,0 +1,263 @@ +Multi-GPU and Multi-Node Training +================================= + +.. currentmodule:: isaaclab + +Isaac Lab supports multi-GPU and multi-node reinforcement learning. Currently, this feature is only +available for RL-Games, RSL-RL and skrl libraries workflows. We are working on extending this feature to +other workflows. + +.. attention:: + + Multi-GPU and multi-node training is only supported on Linux. Windows support is not available at this time. + This is due to limitations of the NCCL library on Windows. + + +Multi-GPU Training +------------------ + +Isaac Lab supports the following multi-GPU training frameworks: + +* `Torchrun `_ through `PyTorch distributed `_ +* `JAX distributed `_ + +Pytorch Torchrun Implementation +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +We are using `Pytorch Torchrun `_ to manage multi-GPU +training. Torchrun manages the distributed training by: + +* **Process Management**: Launching one process per GPU, where each process is assigned to a specific GPU. +* **Script Execution**: Running the same training script (e.g., RL Games trainer) on each process. +* **Environment Instances**: Each process creates its own instance of the Isaac Lab environment. +* **Gradient Synchronization**: Aggregating gradients across all processes and broadcasting the synchronized + gradients back to each process after each training step. + +.. tip:: + Check out this `3 minute youtube video from PyTorch `_ + to understand how Torchrun works. + +The key components in this setup are: + +* **Torchrun**: Handles process spawning, communication, and gradient synchronization. +* **RL Library**: The reinforcement learning library that runs the actual training algorithm. +* **Isaac Lab**: Provides the simulation environment that each process instantiates independently. + +Under the hood, Torchrun uses the `DistributedDataParallel `_ +module to manage the distributed training. When training with multiple GPUs using Torchrun, the following happens: + +* Each GPU runs an independent process +* Each process executes the full training script +* Each process maintains its own: + + * Isaac Lab environment instance (with *n* parallel environments) + * Policy network copy + * Experience buffer for rollout collection + +* All processes synchronize only for gradient updates + +For a deeper dive into how Torchrun works, checkout +`PyTorch Docs: DistributedDataParallel - Internal Design `_. + +Jax Implementation +^^^^^^^^^^^^^^^^^^ + +.. tip:: + JAX is only supported with the skrl library. + +With JAX, we are using `skrl.utils.distributed.jax `_ +Since the ML framework doesn't automatically start multiple processes from a single program invocation, +the skrl library provides a module to start them. + +.. image:: ../_static/multi-gpu-rl/a3c-light.svg + :class: only-light + :align: center + :alt: Multi-GPU training paradigm + :width: 80% + +.. image:: ../_static/multi-gpu-rl/a3c-dark.svg + :class: only-dark + :align: center + :width: 80% + :alt: Multi-GPU training paradigm + +| + +Running Multi-GPU Training +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To train with multiple GPUs, use the following command, where ``--nproc_per_node`` represents the number of available GPUs: + +.. tab-set:: + :sync-group: rl-train + + .. tab-item:: rl_games + :sync: rl_games + + .. code-block:: shell + + python -m torch.distributed.run --nnodes=1 --nproc_per_node=2 scripts/reinforcement_learning/train.py --rl_library rl_games --task=Isaac-Cartpole-v0 --distributed + + .. tab-item:: rsl_rl + :sync: rsl_rl + + .. code-block:: shell + + python -m torch.distributed.run --nnodes=1 --nproc_per_node=2 scripts/reinforcement_learning/train.py --rl_library rsl_rl --task=Isaac-Cartpole-v0 --distributed + + .. tab-item:: skrl + :sync: skrl + + .. tab-set:: + + .. tab-item:: PyTorch + :sync: torch + + .. code-block:: shell + + python -m torch.distributed.run --nnodes=1 --nproc_per_node=2 scripts/reinforcement_learning/train.py --rl_library skrl --task=Isaac-Cartpole-v0 --distributed + + .. tab-item:: JAX + :sync: jax + + .. code-block:: shell + + python -m skrl.utils.distributed.jax --nnodes=1 --nproc_per_node=2 scripts/reinforcement_learning/train.py --rl_library skrl --task=Isaac-Cartpole-v0 --distributed --ml_framework jax + +.. _multi-gpu-nccl-troubleshooting: + +Troubleshooting NCCL Errors +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +On some Linux multi-GPU systems, distributed training may fail with +``CUDA error: an illegal memory access was encountered`` reported by ``ProcessGroupNCCL`` +during or shortly after communicator initialization. + +If this occurs, try disabling the NCCL shared-memory transport before launching training: + +.. code-block:: shell + + export NCCL_SHM_DISABLE=1 + +If the issue persists, additional NCCL fallbacks that may help are: + +.. code-block:: shell + + export NCCL_IB_DISABLE=1 + export NCCL_ALGO=Ring + +Separately, restricting training to a subset of a node's GPUs with ``CUDA_VISIBLE_DEVICES`` +(for example, ``CUDA_VISIBLE_DEVICES=0,1`` on a larger machine) can cause training to hang during +communicator initialization or on the first collective, with no error reported. On affected +systems, disabling NCCL's peer-to-peer (P2P) transport resolves the hang: + +.. code-block:: shell + + export NCCL_P2P_DISABLE=1 + +Then relaunch the distributed training command as usual. + +.. note:: + + These variables are NCCL-level workarounds intended for affected systems. They are not + required on all machines, and may change communication behavior or performance depending + on the hardware topology. In particular, ``NCCL_P2P_DISABLE=1`` routes inter-GPU traffic + through host/shared memory instead of a direct P2P link, which can reduce communication + bandwidth, so only set it when you observe a hang while restricting visible devices. + +Multi-Node Training +------------------- + +To scale up training beyond multiple GPUs on a single machine, it is also possible to train across multiple nodes. +To train across multiple nodes/machines, it is required to launch an individual process on each node. + +For the master node, use the following command, where ``--nproc_per_node`` represents the number of available GPUs, and +``--nnodes`` represents the number of nodes: + +.. tab-set:: + :sync-group: rl-train + + .. tab-item:: rl_games + :sync: rl_games + + .. code-block:: shell + + python -m torch.distributed.run --nproc_per_node=2 --nnodes=2 --node_rank=0 --master_addr= --master_port=5555 scripts/reinforcement_learning/train.py --rl_library rl_games --task=Isaac-Cartpole-v0 --distributed + + .. tab-item:: rsl_rl + :sync: rsl_rl + + .. code-block:: shell + + python -m torch.distributed.run --nproc_per_node=2 --nnodes=2 --node_rank=0 --master_addr= --master_port=5555 scripts/reinforcement_learning/train.py --rl_library rsl_rl --task=Isaac-Cartpole-v0 --distributed + + .. tab-item:: skrl + :sync: skrl + + .. tab-set:: + + .. tab-item:: PyTorch + :sync: torch + + .. code-block:: shell + + python -m torch.distributed.run --nproc_per_node=2 --nnodes=2 --node_rank=0 --master_addr= --master_port=5555 scripts/reinforcement_learning/train.py --rl_library skrl --task=Isaac-Cartpole-v0 --distributed + + .. tab-item:: JAX + :sync: jax + + .. code-block:: shell + + python -m skrl.utils.distributed.jax --nproc_per_node=2 --nnodes=2 --node_rank=0 --coordinator_address=ip_of_master_machine:5555 scripts/reinforcement_learning/train.py --rl_library skrl --task=Isaac-Cartpole-v0 --distributed --ml_framework jax + +Note that the port (``5555``) can be replaced with any other available port. + +For non-master nodes, use the following command, replacing ``--node_rank`` with the index of each machine: + +.. tab-set:: + :sync-group: rl-train + + .. tab-item:: rl_games + :sync: rl_games + + .. code-block:: shell + + python -m torch.distributed.run --nproc_per_node=2 --nnodes=2 --node_rank=1 --master_addr= --master_port=5555 scripts/reinforcement_learning/train.py --rl_library rl_games --task=Isaac-Cartpole-v0 --distributed + + .. tab-item:: rsl_rl + :sync: rsl_rl + + .. code-block:: shell + + python -m torch.distributed.run --nproc_per_node=2 --nnodes=2 --node_rank=1 --master_addr= --master_port=5555 scripts/reinforcement_learning/train.py --rl_library rsl_rl --task=Isaac-Cartpole-v0 --distributed + + .. tab-item:: skrl + :sync: skrl + + .. tab-set:: + + .. tab-item:: PyTorch + :sync: torch + + .. code-block:: shell + + python -m torch.distributed.run --nproc_per_node=2 --nnodes=2 --node_rank=1 --master_addr= --master_port=5555 scripts/reinforcement_learning/train.py --rl_library skrl --task=Isaac-Cartpole-v0 --distributed + + .. tab-item:: JAX + :sync: jax + + .. code-block:: shell + + python -m skrl.utils.distributed.jax --nproc_per_node=2 --nnodes=2 --node_rank=1 --coordinator_address=ip_of_master_machine:5555 scripts/reinforcement_learning/train.py --rl_library skrl --task=Isaac-Cartpole-v0 --distributed --ml_framework jax + +For more details on multi-node training with PyTorch, please visit the +`PyTorch documentation `_. +For more details on multi-node training with JAX, please visit the +`skrl documentation `_ and the +`JAX documentation `_. + +.. note:: + + As mentioned in the PyTorch documentation, "multi-node training is bottlenecked by inter-node communication + latencies". When this latency is high, it is possible multi-node training will perform worse than running on + a single node instance. diff --git a/simulation/modules/IsaacLab/docs/source/features/population_based_training.rst b/simulation/modules/IsaacLab/docs/source/features/population_based_training.rst new file mode 100644 index 0000000000000000000000000000000000000000..3fe18f7bee3e40f5d8c230ce7c3ff343490aac2f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/features/population_based_training.rst @@ -0,0 +1,144 @@ +Population Based Training +========================= + +What PBT Does +------------- + +* Trains *N* policies in parallel (a "population") on the **same task**. +* Every ``interval_steps``: + + #. Save each policy's checkpoint and objective. + #. Score the population and identify **leaders** and **underperformers**. + #. For underperformers, replace weights from a random leader and **mutate** selected hyperparameters. + #. Restart that process with the new weights/params automatically. + +Leader / Underperformer Selection +--------------------------------- + +Let ``o_i`` be each initialized policy's objective, with mean ``μ`` and std ``σ``. + +Upper and lower performance cuts are:: + + upper_cut = max(μ + threshold_std * σ, μ + threshold_abs) + lower_cut = min(μ - threshold_std * σ, μ - threshold_abs) + +* **Leaders**: ``o_i > upper_cut`` +* **Underperformers**: ``o_i < lower_cut`` + +The "Natural-Selection" rules: + +1. Only underperformers are acted on (mutated or replaced). +2. If leaders exist, replace an underperformer with a random leader; otherwise, self-mutate. + +Mutation (Hyperparameters) +-------------------------- + +* Each param has a mutation function (e.g., ``mutate_float``, ``mutate_discount``, etc.). +* A param is mutated with probability ``mutation_rate``. +* When mutated, its value is perturbed within ``change_range = (min, max)``. +* Only whitelisted keys (from the PBT config) are considered. + +Example Config +-------------- + +.. code-block:: yaml + + pbt: + enabled: True + policy_idx: 0 + num_policies: 8 + directory: . + workspace: "pbt_workspace" + objective: episode.consecutive_successes + interval_steps: 50000000 + threshold_std: 0.1 + threshold_abs: 0.025 + mutation_rate: 0.25 + change_range: [1.1, 2.0] + mutation: + agent.params.config.learning_rate: "mutate_float" + agent.params.config.grad_norm: "mutate_float" + agent.params.config.entropy_coef: "mutate_float" + agent.params.config.critic_coef: "mutate_float" + agent.params.config.bounds_loss_coef: "mutate_float" + agent.params.config.kl_threshold: "mutate_float" + agent.params.config.gamma: "mutate_discount" + agent.params.config.tau: "mutate_discount" + + +``objective: episode.consecutive_successes`` is a dotted expression that resolves to +``infos["episode"]["consecutive_successes"]`` as the scalar to **rank policies** (higher is better). + +.. note:: + The rl_games wrapper remaps ``extras["log"]`` to ``extras["episode"]``, so objectives + should use the ``episode.`` prefix even though the environment writes to ``extras["log"]``. + +With ``num_policies: 8``, launch eight processes sharing the same ``workspace`` and unique ``policy_idx`` (0-7). + + +Launching PBT +------------- + +You must start **one process per policy** and point them to the **same workspace**. Set a unique +``policy_idx`` for each process and the common ``num_policies``. + +Minimal flags you need: + +* ``agent.pbt.enabled=True`` +* ``agent.pbt.directory=`` +* ``agent.pbt.policy_idx=<0..num_policies-1>`` + +.. note:: + All processes must use the same ``agent.pbt.workspace`` so they can see each other's checkpoints. + +.. caution:: + PBT is currently supported **only** with the **rl_games** library. Other RL libraries are not supported yet. + +Tips +---- + +* Keep checkpoints reasonable: reduce ``interval_steps`` only if you really need tighter PBT cadence. +* Use larger ``threshold_std`` and ``threshold_abs`` for greater population diversity. +* It is recommended to run 6+ workers to see benefit of pbt. + + +Training Example +---------------- + +We provide a reference PPO config here for task: +`Isaac-Repose-Cube-Shadow-Direct-v0 `_. +For the best logging experience, we recommend using wandb for the logging in the script. + +Launch *N* workers, where *n* indicates each worker index: + +.. code-block:: bash + + # Run this once per worker (n = 0..N-1), all pointing to the same directory/workspace + ./isaaclab.sh train --rl_library rl_games \ + --seed= \ + --task=Isaac-Repose-Cube-Shadow-Direct-v0 \ + --num_envs=8192 \ + --track \ + --wandb-name=idx \ + --wandb-entity=<**entity**> \ + --wandb-project-name=<**project**> \ + agent.pbt.enabled=True \ + agent.pbt.num_policies= \ + agent.pbt.policy_idx= \ + agent.pbt.workspace=<**pbt_workspace_name**> \ + agent.pbt.directory=<**/path/to/shared_folder**> + + +References +---------- + +This PBT implementation reimplements and is inspired by *Dexpbt: Scaling up dexterous manipulation for hand-arm systems with population based training* (Petrenko et al., 2023). + +.. code-block:: bibtex + + @article{petrenko2023dexpbt, + title={Dexpbt: Scaling up dexterous manipulation for hand-arm systems with population based training}, + author={Petrenko, Aleksei and Allshire, Arthur and State, Gavriel and Handa, Ankur and Makoviychuk, Viktor}, + journal={arXiv preprint arXiv:2305.12127}, + year={2023} + } diff --git a/simulation/modules/IsaacLab/docs/source/features/ray.rst b/simulation/modules/IsaacLab/docs/source/features/ray.rst new file mode 100644 index 0000000000000000000000000000000000000000..7166f255c55352a3b5c6f2f85a07b8a27841939f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/features/ray.rst @@ -0,0 +1,442 @@ +=========================== +Ray Job Dispatch and Tuning +=========================== + +.. currentmodule:: isaaclab + +Isaac Lab supports `Ray `_ for streamlining dispatching multiple training jobs (in parallel and in series), +and hyperparameter tuning, both on local and remote configurations. + +This `independent community contributed walkthrough video `_ +demonstrates some of the core functionality of the Ray integration covered in this overview. Although there may be some +differences in the codebase (such as file names being shortened) since the creation of the video, +the general workflow is the same. + +.. attention:: + + This functionality is experimental, and has been tested only on Linux. + +.. warning:: + + **Security Notice**: Due to security risks associated with Ray, + this workflow is not intended for use outside of a strictly controlled + network environment. Ray clusters should only be deployed in trusted, + isolated networks with appropriate access controls and security measures in place. + + + +Overview +-------- + +The Ray integration is useful for the following. + +- Dispatching several training jobs in parallel or sequentially with minimal interaction. +- Tuning hyperparameters; in parallel or sequentially with support for multiple GPUs and/or multiple GPU Nodes. +- Using the same training setup everywhere (on cloud and local) with minimal overhead. +- Resource Isolation for training jobs (resource-wrapped jobs). + +The core functionality of the Ray workflow consists of two main scripts that enable the orchestration +of resource-wrapped and tuning aggregate jobs. In resource-wrapped aggregate jobs, each sub-job and its +resource requirements are defined manually, enabling resource isolation. +For tuning aggregate jobs, individual jobs are generated automatically based on a hyperparameter +sweep configuration. + +Both resource-wrapped and tuning aggregate jobs dispatch individual jobs to a designated Ray +cluster, which leverages the cluster's resources (e.g., a single workstation node or multiple nodes) +to execute these jobs with workers in parallel and/or sequentially. + +By default, jobs use all \ +available resources on each available GPU-enabled node for each sub-job worker. This can be changed through +specifying the ``--num_workers`` argument for resource-wrapped jobs, or ``--num_workers_per_node`` +for tuning jobs, which is especially critical for parallel aggregate +job processing on local/virtual multi-GPU machines. Tuning jobs assume homogeneous node resource composition for nodes with GPUs. + +The three following files contain the core functionality of the Ray integration. + +.. dropdown:: scripts/reinforcement_learning/ray/wrap_resources.py + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/wrap_resources.py + :language: python + :emphasize-lines: 10-63 + +.. dropdown:: scripts/reinforcement_learning/ray/tuner.py + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/tuner.py + :language: python + :emphasize-lines: 18-59 + +.. dropdown:: scripts/reinforcement_learning/ray/task_runner.py + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/task_runner.py + :language: python + :emphasize-lines: 13-105 + +The following script can be used to submit aggregate +jobs to one or more Ray cluster(s), which can be used for +running jobs on a remote cluster or simultaneous jobs with heterogeneous +resource requirements. + +.. dropdown:: scripts/reinforcement_learning/ray/submit_job.py + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/submit_job.py + :language: python + :emphasize-lines: 13-61 + +The following script can be used to extract KubeRay cluster information for aggregate job submission. + +.. dropdown:: scripts/reinforcement_learning/ray/grok_cluster_with_kubectl.py + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/grok_cluster_with_kubectl.py + :language: python + :emphasize-lines: 14-26 + +The following script can be used to easily create clusters on Google GKE. + +.. dropdown:: scripts/reinforcement_learning/ray/launch.py + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/launch.py + :language: python + :emphasize-lines: 15-36 + +Docker-based Local Quickstart +----------------------------- + +First, follow the `Docker Guide `_ +to set up the NVIDIA Container Toolkit and Docker Compose. + +Then, run the following steps to start a tuning run. + +.. code-block:: bash + + # Build the base image, but we don't need to run it + python3 docker/container.py start && python3 docker/container.py stop + # Build the tuning image with extra deps + docker build -t isaacray -f scripts/reinforcement_learning/ray/cluster_configs/Dockerfile . + # Start the tuning image - symlink so that changes in the source folder show up in the container + docker run -v $(pwd)/source:/workspace/isaaclab/source -it --gpus all --net=host --entrypoint /bin/bash isaacray + # Start the Ray server within the tuning image + echo "import ray; ray.init(); import time; [time.sleep(10) for _ in iter(int, 1)]" | ./isaaclab.sh -p + + + +In a different terminal, run the following. + + +.. code-block:: bash + + # In a new terminal (don't close the above) , enter the image with a new shell. + docker container ps + docker exec -it /bin/bash + # Start a tuning run, with one parallel worker per GPU + ./isaaclab.sh -p scripts/reinforcement_learning/ray/tuner.py \ + --cfg_file scripts/reinforcement_learning/ray/hyperparameter_tuning/vision_cartpole_cfg.py \ + --cfg_class CartpoleTheiaJobCfg \ + --run_mode local \ + --workflow scripts/reinforcement_learning/rl_games/train.py \ + --num_workers_per_node + +The Ray tuner currently launches training through its ``--workflow`` script path. The built-in +example configs still use the library-specific RL-Games workflow shown above. Custom Ray configs +can use the unified training entrypoint by setting: + +.. code-block:: python + + cfg["runner_args"]["--rl_library"] = "rl_games" + +and passing ``--workflow scripts/reinforcement_learning/train.py``. + + +To view the training logs, in a different terminal, run the following and visit ``localhost:6006`` in a browser afterwards. + +.. code-block:: bash + + # In a new terminal (don't close the above) , enter the image with a new shell. + docker container ps + docker exec -it /bin/bash + # Start a tuning run, with one parallel worker per GPU + tensorboard --logdir=. + + +Submitting resource-wrapped individual jobs instead of automatic tuning runs is described in the following file. + +.. dropdown:: scripts/reinforcement_learning/ray/wrap_resources.py + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/wrap_resources.py + :language: python + :emphasize-lines: 10-63 + +The ``task_runner.py`` dispatches Python tasks to a Ray cluster via a single declarative YAML file. This approach allows users to specify additional pip packages and Python modules for each run. Fine-grained resource allocation is supported, with explicit control over the number of CPUs, GPUs, and memory assigned to each task. The runner also offers advanced scheduling capabilities: tasks can be restricted to specific nodes by hostname or node ID, and supports two launch modes: tasks can be executed independently as resources become available, or grouped into a simultaneous batch—ideal for multi-node training jobs—which ensures that all tasks launch together only when sufficient resources are available across the cluster. + +.. dropdown:: scripts/reinforcement_learning/ray/task_runner.py + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/task_runner.py + :language: python + :emphasize-lines: 13-105 + +To use this script, run a command similar to the following (replace ``tasks.yaml`` with your actual configuration file): + +.. code-block:: bash + + python3 scripts/reinforcement_learning/ray/submit_job.py --aggregate_jobs task_runner.py --task_cfg tasks.yaml + +For detailed instructions on how to write your ``tasks.yaml`` file, please refer to the comments in ``task_runner.py``. + +**Tip:** Place the ``tasks.yaml`` file in the ``scripts/reinforcement_learning/ray`` directory so that it is included when the ``working_dir`` is uploaded. You can then reference it using a relative path in the command. + +Transferring files from the running container can be done as follows. + +.. code-block:: bash + + docker container ps + docker cp : + + +For tuning jobs, specify the tuning job / hyperparameter sweep as child class of :class:`JobCfg` . +The included :class:`JobCfg` only supports the ``rl_games`` workflow due to differences in +environment entrypoints and hydra arguments, although other workflows will work if provided a compatible +:class:`JobCfg`. + +.. dropdown:: scripts/reinforcement_learning/ray/tuner.py (JobCfg definition) + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/tuner.py + :language: python + :start-at: class JobCfg + :end-at: self.cfg = cfg + +For example, see the following Cartpole Example configurations. + +.. dropdown:: scripts/reinforcement_learning/ray/hyperparameter_tuning/vision_cartpole_cfg.py + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/hyperparameter_tuning/vision_cartpole_cfg.py + :language: python + + +Remote Clusters +--------------- + +Select one of the following methods to create a Ray cluster to accept and execute dispatched jobs. + +KubeRay Setup +~~~~~~~~~~~~~ + +If using KubeRay clusters on Google GKE with the batteries-included cluster launch file, +the following dependencies are also needed. + +.. code-block:: bash + + python3 -m pip install kubernetes Jinja2 + +For use on Kubernetes clusters with KubeRay, +such as Google Kubernetes Engine or Amazon Elastic Kubernetes Service, ``kubectl`` is required, and can +be installed via the `Kubernetes website `_ . + +Google Cloud is currently the only platform tested, although +any cloud provider should work if one configures the following. + +.. attention:: + The ``ray`` command should be modified to use Isaac python, which could be achieved in a fashion similar to + ``sed -i "1i $(echo "#!/workspace/isaaclab/_isaac_sim/python.sh")" \ + /isaac-sim/kit/python/bin/ray && ln -s /isaac-sim/kit/python/bin/ray /usr/local/bin/ray``. + +- An container registry (NGC, GCS artifact registry, AWS ECR, etc) with + an Isaac Lab image configured to support Ray. See ``cluster_configs/Dockerfile`` to see how to modify the ``isaac-lab-base`` + container for Ray compatibility. Ray should use the isaac sim python shebang, and ``nvidia-smi`` + should work within the container. Be careful with the setup here as + paths need to be configured correctly for everything to work. It's likely that + the example dockerfile will work out of the box and can be pushed to the registry, as + long as the base image has already been built as in the container guide. +- A Kubernetes setup with available NVIDIA RTX (likely ``l4`` or ``l40`` or ``tesla-t4`` or ``a10``) GPU-passthrough node-pool resources, + that has access to your container registry/storage bucket and has the Ray operator enabled with correct IAM + permissions. This can be easily achieved with services such as Google GKE or AWS EKS, + provided that your account or organization has been granted a GPU-budget. It is recommended + to use manual kubernetes services as opposed to "autopilot" services for cost-effective + experimentation as this way clusters can be completely shut down when not in use, although + this may require installing the `Nvidia GPU Operator `_ . +- An `MLFlow server `_ that your cluster has access to + (already included for Google Cloud, which can be referenced for the format and MLFlow integration). +- A ``kuberay.yaml.ninja`` file that describes how to allocate resources (already included for + Google Cloud, which can be referenced for the format and MLFlow integration). + +Ray Clusters (Without Kubernetes) Setup +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. attention:: + Modify the Ray command to use Isaac Python like in KubeRay clusters, and follow the same + steps for creating an image/cluster permissions. + +See the `Ray Clusters Overview `_ or +`Anyscale `_ for more information. + +Also, create an `MLFlow server `_ that your local +host and cluster have access to. + +Shared Steps Between KubeRay and Pure Ray Part I +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +1.) Install Ray on your local machine. + +.. code-block:: bash + + python3 -m pip install "ray[default]==2.31.0" + +2.) Build the Isaac Ray image, and upload it to your container registry of choice. + +.. code-block:: bash + + # Login with NGC (nvcr.io) registry first, see docker steps in repo. + python3 docker/container.py start + # Build the special Isaac Lab Ray Image + docker build -t -f scripts/reinforcement_learning/ray/cluster_configs/Dockerfile . + # Push the image to your registry of choice. + docker push + +KubeRay Clusters Only +~~~~~~~~~~~~~~~~~~~~~ +`k9s `_ is a great tool for monitoring your clusters that can +easily be installed with ``snap install k9s --devmode``. + +1.) Verify cluster access, and that the correct operators are installed. + +.. code-block:: bash + + # Verify cluster access + kubectl cluster-info + # If using a manually managed cluster (not Autopilot or the like) + # verify that there are node pools + kubectl get nodes + # Check that the ray operator is installed on the cluster + # should list rayclusters.ray.io , rayjobs.ray.io , and rayservices.ray.io + kubectl get crds | grep ray + # Check that the NVIDIA Driver Operator is installed on the cluster + # should list clusterpolicies.nvidia.com + kubectl get crds | grep nvidia + +2.) Create the KubeRay cluster and an MLFlow server for receiving logs +that your cluster has access to. +This can be done automatically for Google GKE, +where instructions are included in the following creation file. + +.. dropdown:: scripts/reinforcement_learning/ray/launch.py + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/launch.py + :language: python + :emphasize-lines: 15-36 + +For other cloud services, the ``kuberay.yaml.ninja`` will be similar to that of +Google's. + + +.. dropdown:: scripts/reinforcement_learning/ray/cluster_configs/google_cloud/kuberay.yaml.ninja + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/cluster_configs/google_cloud/kuberay.yaml.jinja + :language: python + + + +3.) Fetch the KubeRay cluster IP addresses, and the MLFLow Server IP. +This can be done automatically for KubeRay clusters, +where instructions are included in the following fetching file. +The KubeRay clusters are saved to a file, but the MLFLow Server IP is +printed. + +.. dropdown:: scripts/reinforcement_learning/ray/grok_cluster_with_kubectl.py + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/grok_cluster_with_kubectl.py + :language: python + :emphasize-lines: 14-26 + +Ray Clusters Only (Without Kubernetes) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +1.) Verify cluster access. + +2.) Create a ``~/.cluster_config`` file, where ``name: address: http://:`` is on +a new line for each unique cluster. For one cluster, there should only be one line in this file. + +3.) Start an MLFLow Server to receive the logs that the ray cluster has access to, +and determine the server URI. + +Dispatching Steps Shared Between KubeRay and Pure Ray Part II +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +1.) Test that your cluster is operational with the following. + +.. code-block:: bash + + # Test that NVIDIA GPUs are visible and that Ray is operation with the following command: + python3 scripts/reinforcement_learning/ray/submit_job.py --aggregate_jobs wrap_resources.py --test + +2.) Submitting tuning and/or resource-wrapped jobs is described in the :file:`submit_job.py` file. + +.. dropdown:: scripts/reinforcement_learning/ray/submit_job.py + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/submit_job.py + :language: python + :emphasize-lines: 13-61 + +3.) For tuning jobs, specify the tuning job / hyperparameter sweep as a :class:`JobCfg` . +The included :class:`JobCfg` only supports the ``rl_games`` workflow due to differences in +environment entrypoints and hydra arguments, although other workflows will work if provided a compatible +:class:`JobCfg`. + +.. dropdown:: scripts/reinforcement_learning/ray/tuner.py (JobCfg definition) + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/tuner.py + :language: python + :start-at: class JobCfg + :end-at: self.cfg = cfg + +For example, see the following Cartpole Example configurations. + +.. dropdown:: scripts/reinforcement_learning/ray/hyperparameter_tuning/vision_cartpole_cfg.py + :icon: code + + .. literalinclude:: ../../../scripts/reinforcement_learning/ray/hyperparameter_tuning/vision_cartpole_cfg.py + :language: python + + +To view the tuning results, view the MLFlow dashboard of the server that you created. +For KubeRay, this can be done through port forwarding the MLFlow dashboard with the following. + +``kubectl port-forward service/isaacray-mlflow 5000:5000`` + +Then visit the following address in a browser. + +``localhost:5000`` + +If the MLFlow port is forwarded like above, it can be converted into tensorboard logs with +this following command. + +``./isaaclab.sh -p scripts/reinforcement_learning/ray/mlflow_to_local_tensorboard.py \ +--uri http://localhost:5000 --experiment-name IsaacRay--tune --download-dir test`` + + +Kubernetes Cluster Cleanup +'''''''''''''''''''''''''' + +For the sake of conserving resources, and potentially freeing precious GPU resources for other people to use +on shared compute platforms, please destroy the Ray cluster after use. They can be easily +recreated! For KubeRay clusters, this can be done as follows. + +.. code-block:: bash + + kubectl get raycluster | egrep 'isaacray' | awk '{print $1}' | xargs kubectl delete raycluster && + kubectl get deployments | egrep 'mlflow' | awk '{print $1}' | xargs kubectl delete deployment && + kubectl get services | egrep 'mlflow' | awk '{print $1}' | xargs kubectl delete service && + kubectl get services | egrep 'isaacray' | awk '{print $1}' | xargs kubectl delete service diff --git a/simulation/modules/IsaacLab/docs/source/features/reproducibility.rst b/simulation/modules/IsaacLab/docs/source/features/reproducibility.rst new file mode 100644 index 0000000000000000000000000000000000000000..e19417f6dd8f36f9ea738090169a20845e2ec178 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/features/reproducibility.rst @@ -0,0 +1,65 @@ +Reproducibility and Determinism +------------------------------- + +Given the same hardware and Isaac Sim (and consequently PhysX) version, the simulation produces +identical results for scenes with rigid bodies and articulations. However, the simulation results can +vary across different hardware configurations due to floating point precision and rounding errors. +At present, PhysX does not guarantee determinism for any scene with non-rigid bodies, such as cloth +or soft bodies. For more information, please refer to the `PhysX Determinism documentation`_. + +Based on above, Isaac Lab provides a deterministic simulation that ensures consistent simulation +results across different runs. This is achieved by using the same random seed for the +simulation environment and the physics engine. At construction of the environment, the random seed +is set to a fixed value using the :meth:`~isaaclab.utils.seed.configure_seed` method. This method sets the +random seed for both the CPU and GPU globally across different libraries, including PyTorch and +NumPy. + +In the included workflow scripts, the seed specified in the learning agent's configuration file or the +command line argument is used to set the random seed for the environment. This ensures that the +simulation results are reproducible across different runs. The seed is set into the environment +parameters :attr:`isaaclab.envs.ManagerBasedEnvCfg.seed` or :attr:`isaaclab.envs.DirectRLEnvCfg.seed` +depending on the manager-based or direct environment implementation respectively. + +App-level deterministic rendering via ``AppLauncher`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The ``--deterministic`` flag is provided by :meth:`isaaclab.app.AppLauncher.add_app_launcher_args`. +After the simulation app starts, :class:`~isaaclab.app.app_launcher.AppLauncher` applies RTX/RTPT carb +settings via :meth:`~isaaclab.app.app_launcher.AppLauncher.apply_rtx_determinism_settings`. + +**Strict PyTorch determinism** (calling :meth:`~isaaclab.utils.seed.configure_seed` with +``torch_deterministic=True`` when you pass ``--deterministic``) is wired into the RL training entrypoints +for **RL-Games**, **skrl**, **RSL-RL**, and **Stable-Baselines3**: each calls +:meth:`~isaaclab.utils.seed.configure_seed` after constructing its framework runner or agent object +so library initialization is not disturbed, then training proceeds with the requested global RNG and +optional PyTorch deterministic algorithms. Whether you need ``--deterministic`` at the app level +depends on the workload: **physics-only** simulation does not require it; **RTX** rendering +(non-minimal mode) does require it for reproducible imagery; **Newton** rendering does not require it. + +To enable deterministic RTX settings from the app launcher, pass ``--deterministic``. + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rl_games \ + --task Isaac-Cartpole-RGB-Camera-Direct-v0 --enable_cameras --deterministic + +For results on our determinacy testing for RL training, please check the GitHub Pull Request `#940`_. + +.. tip:: + + 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 determinacy 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. + + +.. _PhysX Determinism documentation: https://nvidia-omniverse.github.io/PhysX/physx/5.4.1/docs/API.html#determinism +.. _#940: https://github.com/isaac-sim/IsaacLab/pull/940 diff --git a/simulation/modules/IsaacLab/docs/source/how-to/add_own_library.rst b/simulation/modules/IsaacLab/docs/source/how-to/add_own_library.rst new file mode 100644 index 0000000000000000000000000000000000000000..c454bc16b7bdeb09397f4be3f664b1d4678db3b6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/add_own_library.rst @@ -0,0 +1,102 @@ +.. _how-to-add-library: + +Adding your own learning library +================================ + +Isaac Lab comes pre-integrated with a number of libraries (such as RSL-RL, RL-Games, SKRL, Stable Baselines, etc.). +However, you may want to integrate your own library with Isaac Lab or use a different version of the libraries than +the one installed by Isaac Lab. This is possible as long as the library is available as Python package that supports +the Python version used by the underlying simulator. For instance, if you are using Isaac Sim 6.0.0 onwards, you need +to ensure that the library is available for Python 3.12. + +Using a different version of a library +-------------------------------------- + +If you want to use a different version of a library than the one installed by Isaac Lab, you can install the library +by building it from source or using a different version of the library available on PyPI. + +For instance, if you want to use your own modified version of the `rsl-rl`_ library, you can follow these steps: + +1. Follow the instructions for installing Isaac Lab. This will install the default version of the ``rsl-rl`` library. +2. Clone the ``rsl-rl`` library from the GitHub repository: + + .. code-block:: bash + + git clone git@github.com:leggedrobotics/rsl_rl.git + + +3. Install the library in your Python environment: + + .. code-block:: bash + + # Assuming you are in the root directory of the Isaac Lab repository + cd IsaacLab + + # Note: If you are using a virtual environment, make sure to activate it before running the following command + python -m pip install -e /path/to/rsl_rl + +In this case, the ``rsl-rl`` library will be installed in the Python environment used by Isaac Lab. You can now use the +``rsl-rl`` library in your experiments. To check the library version and other details, you can use the following +command: + +.. code-block:: bash + + python -m pip show rsl-rl-lib + +This should now show the location of the ``rsl-rl`` library as the directory where you cloned the library. +For instance, if you cloned the library to ``/home/user/git/rsl_rl``, the output of the above command should be: + +.. code-block:: bash + + Name: rsl_rl + Version: 3.0.1 + Summary: Fast and simple RL algorithms implemented in pytorch + Home-page: https://github.com/leggedrobotics/rsl_rl + Author: ETH Zurich, NVIDIA CORPORATION + Author-email: + License: BSD-3 + Location: /home/user/git/rsl_rl + Requires: torch, torchvision, numpy, GitPython, onnx + Required-by: + + +Integrating a new library +------------------------- + +Adding a new library to Isaac Lab is similar to using a different version of a library. You can install the library +in your Python environment and use it in your experiments. However, if you want to integrate the library with +Isaac Lab, you will first need to make a wrapper for the library, as explained in +:ref:`how-to-env-wrappers`. + +The following steps can be followed to integrate a new library with Isaac Lab: + +1. Add your library as an extra-dependency in the ``setup.py`` for the extension ``isaaclab_rl``. + This will ensure that the library is installed when you install Isaac Lab or it will complain if the library is not + installed or available. +2. Install your library in the Python environment used by Isaac Lab. You can do this by following the steps mentioned + in the previous section. +3. Create a wrapper for the library. You can check the module :mod:`isaaclab_rl` + for examples of wrappers for different libraries. You can create a new wrapper for your library and add it to the + module. You can also create a new module for the wrapper if you prefer. +4. Create workflow scripts for your library to train and evaluate agents. You can check the existing workflow scripts + in the ``scripts/reinforcement_learning`` directory for examples. You can create new workflow + scripts for your library and add them to the directory. + +Optionally, you can also add some tests and documentation for the wrapper. This will help ensure that the wrapper +works as expected and can guide users on how to use the wrapper. + +* Add some tests to ensure that the wrapper works as expected and remains compatible with the library. + These tests can be added to the ``source/isaaclab_rl/test`` directory. +* Add some documentation for the wrapper. You can add the API documentation to the + :ref:`API documentation` for the ``isaaclab_rl`` module. + + +Configuring an RL Agent +----------------------- + +Once you have integrated a new library with Isaac Lab, you can configure the example environment to use the new library. +You can check the :ref:`tutorial-configure-rl-training` for an example of how to configure the training process to use a +different library. + + +.. _rsl-rl: https://github.com/leggedrobotics/rsl_rl diff --git a/simulation/modules/IsaacLab/docs/source/how-to/cloning.rst b/simulation/modules/IsaacLab/docs/source/how-to/cloning.rst new file mode 100644 index 0000000000000000000000000000000000000000..16d5bcece155ffaf948bced9cca1210e0168da8e --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/cloning.rst @@ -0,0 +1,400 @@ +.. _cloning-environments: + +Cloning Environments +==================== + +.. currentmodule:: isaaclab + +Isaac Lab creates many parallel environments by spawning representative source prims and +then cloning them to the remaining environment paths. This guide starts with direct cloning +so the primitive contract is clear, then shows how :class:`~isaaclab.cloner.ClonePlan` and +:class:`~isaaclab.scene.InteractiveScene` build on top of that contract. + +.. contents:: On this page + :local: + :depth: 2 + + +Direct Cloning +-------------- + +Use direct cloning for custom scene pipelines, tooling, or tests that need explicit +control over the replication contract. + +The cloner operates on three pieces of data: + +1. **Source prims** that already exist on the stage. +2. **Destination templates** containing ``{}``, which is formatted with each environment id. +3. **A boolean mask** with shape ``[len(sources), num_envs]`` that selects which source + populates each environment. + +The direct flow is: + +1. Create the environment namespace prims. +2. Spawn representative source prims. +3. Call the physics replicate function for your backend. +4. Call :func:`~isaaclab.cloner.usd_replicate` with the same source-to-environment mapping. + +.. code-block:: python + + import torch + + import isaaclab.sim as sim_utils + from isaaclab.cloner import usd_replicate + from isaaclab_physx.cloner import physx_replicate + + num_envs = 128 + stage = sim_utils.get_current_stage() + env_ids = torch.arange(num_envs, device="cuda:0") + + sim_utils.create_prim("/World/envs", "Xform") + for env_id in range(num_envs): + sim_utils.create_prim(f"/World/envs/env_{env_id}", "Xform") + + source = "/World/envs/env_0/Cube" + destination = "/World/envs/env_{}/Object" + + cube_cfg = sim_utils.CuboidCfg(size=(0.5, 0.5, 0.5)) + cube_cfg.func(source, cube_cfg) + + mask = torch.ones((1, num_envs), dtype=torch.bool, device="cuda:0") + + physx_replicate(stage, [source], [destination], env_ids, mask, device="cuda:0") + usd_replicate(stage, [source], [destination], env_ids, mask) + +This creates one source cube at ``/World/envs/env_0/Cube`` and clones it to +``/World/envs/env_1/Object`` through ``/World/envs/env_127/Object``. When a source path is +the same as the destination for an environment, ``usd_replicate`` skips the self-copy. + +Direct heterogeneous cloning uses the same API with more source rows. Each row in ``mask`` +selects the environments that receive the matching source. For example, this explicit mask +clones a cone into environments 0 and 2, and a sphere into environments 1 and 3: + +.. code-block:: python + + env_ids = torch.arange(4, device="cuda:0") + sources = ["/World/envs/env_0/Cone", "/World/envs/env_1/Sphere"] + destinations = ["/World/envs/env_{}/Object", "/World/envs/env_{}/Object"] + + cone_cfg = sim_utils.ConeCfg(radius=0.25, height=0.5) + sphere_cfg = sim_utils.SphereCfg(radius=0.25) + cone_cfg.func(sources[0], cone_cfg) + sphere_cfg.func(sources[1], sphere_cfg) + + mask = torch.tensor([[True, False, True, False], [False, True, False, True]], dtype=torch.bool) + + physx_replicate(stage, sources, destinations, env_ids, mask, device="cuda:0") + usd_replicate(stage, sources, destinations, env_ids, mask) + +The mask above reads as: + +.. list-table:: + :header-rows: 1 + :widths: 15 40 20 25 + + * - Source row + - Source path + - Env ids + - Destination path + * - ``0`` + - ``/World/envs/env_0/Cone`` + - ``0, 2`` + - ``/World/envs/env_{}/Object`` + * - ``1`` + - ``/World/envs/env_1/Sphere`` + - ``1, 3`` + - ``/World/envs/env_{}/Object`` + +``usd_replicate`` copies parent paths before children and supports optional ``positions`` +and ``quaternions`` buffers. If ``positions`` is provided, it authors +``xformOp:translate`` on each destination using the environment id. The helper +:func:`~isaaclab.cloner.grid_transforms` creates the same grid layout used by +:class:`~isaaclab.scene.InteractiveScene`. + +.. code-block:: python + + from isaaclab.cloner import grid_transforms + + positions, orientations = grid_transforms( + N=num_envs, + spacing=2.0, + up_axis="z", + device="cuda:0", + ) + usd_replicate(stage, [source], [destination], env_ids, mask, positions=positions) + + +Clone Plans +----------- + +For one source row, passing ``sources``, ``destinations``, and ``mask`` by hand is simple. +For heterogeneous scenes, the mapping is easier to build with +:func:`~isaaclab.cloner.make_clone_plan`, which returns the raw flat components. Composing +those components into a :class:`~isaaclab.cloner.ClonePlan` together with the per-environment +pose buffer is the caller's responsibility — keeping pose authority on the side that owns the +buffer (typically the scene) avoids duplicating tensors. + +:class:`~isaaclab.cloner.ClonePlan` stores the same flat contract used by direct cloning: + +.. code-block:: text + + sources = [source_0, source_1, ...] + destinations = [destination_0, destination_1, ...] + clone_mask = bool tensor, shape [len(sources), num_envs] + +``clone_mask[i, j]`` is ``True`` when environment ``j`` should receive source row ``i``. +The same plan can be passed to USD replication, physics replication, and scene-data +providers. + +Homogeneous Plans +~~~~~~~~~~~~~~~~~ + +In a homogeneous scene, every environment receives the same asset layout. The default plan +is: + +.. code-block:: text + + sources = ["/World/envs/env_0"] + destinations = ["/World/envs/env_{}"] + clone_mask = all True, shape [1, num_envs] + +This means the scene spawns everything for ``env_0`` and replicates that environment to +``env_1`` through ``env_N``. + +Heterogeneous Plans +~~~~~~~~~~~~~~~~~~~ + +Heterogeneous cloning is used when different environments receive different prototypes. +For example, an object with three variants may have representative source prims at: + +.. code-block:: text + + /World/envs/env_0/Object + /World/envs/env_1/Object + /World/envs/env_2/Object + +These paths have the same leaf name because each variant will be cloned to +``/World/envs/env_{}/Object``, but their authored contents are different. For example, +``env_0/Object`` could be a cone, ``env_1/Object`` a cuboid, and ``env_2/Object`` a sphere. + +The plan maps those source rows to all environments: + +.. code-block:: python + + from isaaclab.cloner import make_clone_plan, sequential + + sources, destinations, clone_mask = make_clone_plan( + sources=[ + [ + "/World/envs/env_0/Object", + "/World/envs/env_1/Object", + "/World/envs/env_2/Object", + ] + ], + destinations=["/World/envs/env_{}/Object"], + num_clones=8, + clone_strategy=sequential, + device="cuda:0", + ) + + # source row used by env: 0, 1, 2, 0, 1, 2, 0, 1 + +Direct code can use the components exactly like the hand-written direct example: + +.. code-block:: python + + physx_replicate(stage, sources, destinations, env_ids, clone_mask, device="cuda:0") + usd_replicate(stage, sources, destinations, env_ids, clone_mask) + +When variants span multiple groups, such as robot variants and object variants, +``make_clone_plan`` enumerates the Cartesian product of the groups and assigns one +combination per environment. Unused prototype rows may still appear in the plan with an +all-false mask row. + +.. _cloning-strategies: + +Clone Strategies +~~~~~~~~~~~~~~~~ + +A clone strategy chooses prototype combinations for the environments: + +* :func:`~isaaclab.cloner.random` samples combinations randomly and is the default. +* :func:`~isaaclab.cloner.sequential` assigns combinations in round-robin order, which is + useful for reproducible tests and balanced coverage. + +Custom strategies are callables with this signature: + +.. code-block:: python + + def my_strategy(combinations: torch.Tensor, num_clones: int, device: str) -> torch.Tensor: + ... + +``combinations`` has shape ``[num_combinations, num_groups]`` and the return value must have +shape ``[num_clones, num_groups]``. + + +Common Workflow: ``InteractiveScene`` +------------------------------------- + +:class:`~isaaclab.scene.InteractiveScene` automates the direct cloning flow for task scenes. +It inspects scene configuration, builds a :class:`~isaaclab.cloner.ClonePlan`, rewrites +spawner paths to the representative sources, spawns those sources, runs physics and USD +replication, and filters inter-environment collisions for PhysX when configured. + +Put per-environment assets under ``{ENV_REGEX_NS}`` and global assets under normal USD +paths: + +.. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab.assets import AssetBaseCfg + from isaaclab.scene import InteractiveScene, InteractiveSceneCfg + from isaaclab.utils.configclass import configclass + from isaaclab_assets.robots.cartpole import CARTPOLE_CFG + + + @configclass + class MySceneCfg(InteractiveSceneCfg): + # Cloned once per environment. + robot = CARTPOLE_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + # Authored once globally, not cloned per environment. + light = AssetBaseCfg( + prim_path="/World/Light", + spawn=sim_utils.DistantLightCfg(intensity=3000.0), + ) + + + scene_cfg = MySceneCfg(num_envs=128, env_spacing=2.0, replicate_physics=True) + scene = InteractiveScene(cfg=scene_cfg) + +For heterogeneous scenes, use :class:`~isaaclab.sim.spawners.wrappers.MultiAssetSpawnerCfg` +or :class:`~isaaclab.sim.spawners.wrappers.MultiUsdFileCfg`. ``InteractiveScene`` assigns +representative source paths to the spawner and lets the clone strategy choose which +prototype each environment receives. See :doc:`multi_asset_spawning` for the asset +configuration details. + +The most important scene options are on :class:`~isaaclab.scene.InteractiveSceneCfg`: + +.. list-table:: + :header-rows: 1 + :widths: 25 15 60 + + * - Field + - Default + - When to change it + * - ``replicate_physics`` + - ``True`` + - Keep enabled for homogeneous environments and fast startup. Disable it when each + environment needs independently authored physics or USD randomization. + * - ``filter_collisions`` + - ``True`` + - Keep enabled for parallel RL so cloned environments do not collide with each other. + This is automatic for PhysX-backed scene cloning. + * - ``clone_in_fabric`` + - ``False`` + - Enables the PhysX Fabric cloning path for faster scene creation. Use USDRT for stage + inspection when Fabric cloning is enabled. + + +Choosing an API +--------------- + +.. list-table:: + :header-rows: 1 + :widths: 25 45 30 + + * - Goal + - Recommended API + - Notes + * - Build a custom cloning pipeline + - :func:`~isaaclab.cloner.usd_replicate` and a backend physics replicate function + - Useful for tests, tooling, or advanced scene construction. + * - Build complex direct mappings + - :func:`~isaaclab.cloner.make_clone_plan` + - Produces the same ``sources``, ``destinations``, and ``clone_mask`` used by direct cloning. + * - Build normal task scenes + - :class:`~isaaclab.scene.InteractiveScene` + - Preferred path. Configure assets with ``{ENV_REGEX_NS}`` and let the scene clone them. + * - Randomize which asset each environment receives + - ``InteractiveScene`` with :class:`~isaaclab.sim.spawners.wrappers.MultiAssetSpawnerCfg` or + :class:`~isaaclab.sim.spawners.wrappers.MultiUsdFileCfg` + - See :doc:`multi_asset_spawning` for the asset configuration details. + * - Use Isaac Sim's ``GridCloner`` + - Isaac Sim API + - Isaac Lab's tested path is the ``isaaclab.cloner`` API described here. + + +Migrating From Template Cloning +------------------------------- + +The template-root discovery API has been removed. Replace +``clone_from_template(...)`` calls with explicit source prims plus +:func:`~isaaclab.cloner.make_clone_plan`, a backend physics replicate function, and +:func:`~isaaclab.cloner.usd_replicate`. Replace ``TemplateCloneCfg`` with +:class:`~isaaclab.cloner.CloneCfg` for execution settings such as clone strategy, +Fabric cloning, and backend replication. + + +Collision Filtering and Isolation +--------------------------------- + +Some prims, such as terrain, are intentionally shared across environments and should collide +with every environment. These are modeled as global collision paths. The workaround is only +the per-environment filtering: when cloning is fully isolated per world, cloned environments +should not collide with each other and no manual per-environment filter should be needed. +Some PhysX cloning paths still rely on USD collision groups for that isolation fallback. In +the scene workflow this is handled by ``InteractiveScene`` when ``filter_collisions=True`` +and the backend is PhysX. + +For direct PhysX usage, call :func:`~isaaclab.cloner.filter_collisions` after cloning if +per-environment isolation is not already provided by the cloning backend: + +.. code-block:: python + + from isaaclab.cloner import filter_collisions + + filter_collisions( + stage=stage, + physicsscene_path="/physicsScene", + collision_root_path="/World/collisions", + prim_paths=[f"/World/envs/env_{i}" for i in range(num_envs)], + global_paths=["/World/ground"], + ) + +.. note:: + + Collision filtering uses PhysX collision groups. Newton handles per-environment isolation + through its own world system. + + +Backend and Option Notes +------------------------ + +**Physics replication.** :class:`~isaaclab.scene.InteractiveScene` selects the backend +replication function automatically. Direct PhysX users call +:func:`~isaaclab_physx.cloner.physx_replicate`; Newton users call +:func:`~isaaclab_newton.cloner.newton_physics_replicate`. + +**``replicate_physics=False``.** Disable physics replication when environments need +independent authored USD or physics state, such as some scale, texture, or color +randomization workflows. Startup and physics parsing are slower because the backend cannot +assume every environment is a clone of the same source. + +**``copy_from_source``.** ``InteractiveScene`` calls +``clone_environments(copy_from_source=True)`` when ``replicate_physics=False``. This skips +backend physics replication and leaves physics parsing to the backend. Spawner-level +``copy_from_source`` is a separate setting used by spawn functions that clone from a source +path matched by a regex. + +**Fabric cloning.** ``clone_in_fabric=True`` applies to PhysX replication. It can reduce +scene-creation time for large PhysX scenes, especially when many replicated rigid bodies are +authored. Fabric-backed stage data must be inspected through USDRT rather than normal USD +APIs. + + +See Also +-------- + +* :doc:`multi_asset_spawning` -- configuring multi-asset and multi-USD spawners. +* :doc:`optimize_stage_creation` -- Fabric cloning and stage-in-memory optimizations. diff --git a/simulation/modules/IsaacLab/docs/source/how-to/cloudxr_teleoperation.rst b/simulation/modules/IsaacLab/docs/source/how-to/cloudxr_teleoperation.rst new file mode 100644 index 0000000000000000000000000000000000000000..03f4e9e4d773540c8454d69ff648ccbb9ba0351d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/cloudxr_teleoperation.rst @@ -0,0 +1,514 @@ +.. _cloudxr-teleoperation: + +Setting up Isaac Teleop with CloudXR +===================================== + +.. currentmodule:: isaaclab + +`Isaac Teleop `_ (https://github.com/NVIDIA/IsaacTeleop) is the unified framework for high-fidelity +teleoperation in Isaac Lab. It provides standardized device interfaces, a flexible retargeting +pipeline, and bundled `NVIDIA CloudXR`_ streaming for immersive XR-based teleoperation. + +This guide walks you through setting up CloudXR, connecting an XR device, and running your first +teleoperation session. For additional details see the `Isaac Teleop Quick Start +`_. + +.. tip:: + + For architecture details, retargeting pipelines, control scheme recommendations, and how to + add new embodiments or devices, see the :ref:`isaac-teleop-feature` page. + + +Prerequisites +------------- + +* **Isaac Lab** installed and working (see :ref:`isaaclab-installation-root`). + +* **Isaac Lab workstation** + + * Ubuntu 22.04 or Ubuntu 24.04 + * CPU: x86_64 (ARM support coming soon) + * GPU: NVIDIA GPU required. For 45 FPS with 120 Hz physics: + + * CPU: AMD Ryzen Threadripper 7960x or higher + * GPU: 1x RTX PRO 6000 (or equivalent, e.g. 1x RTX 5090) or higher + * Memory: 64 GB RAM + + * For driver requirements see the `Technical Requirements `_ guide. + * Python 3.12 or newer + * CUDA 12.8 (recommended) + * NVIDIA Driver 580.95.05 (recommended) + +* **Wifi 6 capable router** + + * A strong wireless connection is essential for a high-quality streaming experience. Refer to + the `CloudXR Network Setup`_ guide for detailed requirements, router configuration, and + troubleshooting. + * We recommend a dedicated router; concurrent usage will degrade quality. + * The XR device and Isaac Lab workstation must be IP-reachable from one another. Many + institutional wireless networks prevent device-to-device connectivity. + +.. note:: + + Teleoperation is not currently supported on DGX Spark. + + +.. _install-isaac-teleop: + +Install Isaac Teleop +-------------------- + +#. Install the system libraries required by the CloudXR runtime: + + .. code-block:: bash + + sudo apt-get update && sudo apt-get install -y libvulkan1 libbsd0 + + The CloudXR runtime links against Vulkan at runtime. If your system already has the + NVIDIA driver installed, ``libvulkan1`` may already be present. + +#. ``isaacteleop`` is installed automatically as a dependency of ``isaaclab_teleop``. + No separate pip install step is required. For building from source or plugin + development, see the `Isaac Teleop GitHub `_. + +#. Configure the firewall to allow CloudXR traffic. The required ports depend on the + client type. + + **For Apple native clients** (CloudXR Framework): + + .. code-block:: bash + + # Signaling (use one based on connection mode) + sudo ufw allow 48010/tcp # Standard mode + sudo ufw allow 48322/tcp # Secure mode + # Video + sudo ufw allow 47998/udp + sudo ufw allow 48005/udp + sudo ufw allow 48008/udp + sudo ufw allow 48012/udp + # Input + sudo ufw allow 47999/udp + # Audio + sudo ufw allow 48000/udp + sudo ufw allow 48002/udp + + **For web clients** (CloudXR.js via the built-in WSS proxy): + + .. code-block:: bash + + sudo ufw allow 49100/tcp # Signaling (WebRTC) + sudo ufw allow 47998/udp # Media stream + sudo ufw allow 48322/tcp # WSS proxy (HTTPS) + + For full network requirements and Windows firewall instructions, see the + `CloudXR Network Setup `__ + documentation. + + +.. _run-isaac-lab-with-the-cloudxr-runtime: + +Run Isaac Lab with CloudXR +-------------------------- + +The CloudXR runtime launches automatically when a teleop script is started. No separate +terminal or ``source`` step is needed. Launch a teleoperation script directly: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ + --visualizer kit \ + --xr + +.. attention:: + + **First run — EULA acceptance required.** + On the first launch, Isaac Sim will prompt you to accept the NVIDIA Omniverse License + Agreement before the simulation starts: + + .. code-block:: text + + By installing or using Isaac Sim, I agree to the terms of NVIDIA OMNIVERSE LICENSE AGREEMENT + in https://docs.isaacsim.omniverse.nvidia.com/latest/common/NVIDIA_Omniverse_License_Agreement.html + + Do you accept the EULA? (Yes/No): + + Type ``Yes`` and press **Enter** to continue. If this prompt goes unnoticed the script + will appear to hang — check your terminal output if Isaac Sim does not start within a + few seconds. + +.. tip:: + + The ``Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0`` task above uses **hand tracking** as its + input mode. Make sure your XR device has hand tracking enabled (optical hand tracking on + Quest 3, or the built-in hand tracking on Apple Vision Pro). Different tasks require + different input modes (motion controllers vs hand tracking) -- see the + :ref:`isaac-teleop-control-schemes` table for the full list. + +To switch the CloudXR device profile at launch time (e.g. from Quest to Apple Vision Pro), +use the ``--cloudxr_env`` flag: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ + --visualizer kit \ + --xr \ + --cloudxr_env avp + +For details on the shipped ``.env`` profiles and how to customise them, see +:ref:`isaac-teleop-cloudxr-profiles` in the feature guide. + +Then in the Isaac Sim UI: + +#. Locate the panel named **XR** and choose the following options: + + * Selected Output Plugin: **OpenXR** + * OpenXR Runtime: **System OpenXR Runtime** + + .. figure:: ../_static/setup/cloudxr_ar_panel.jpg + :align: center + :figwidth: 50% + :alt: Isaac Sim UI: XR Panel + +#. Click **Start XR**. + +You should see "Waiting for connection" displayed in the status bar at the bottom of the viewport. +The dual-eye stereo render only becomes active once a headset connects and playback begins on the device. + +.. figure:: ../_static/setup/cloudxr_viewport.jpg + :align: center + :figwidth: 100% + :alt: Isaac Lab viewport showing "Waiting for connection" status after clicking Start XR + +Isaac Lab is now ready to receive connections from a CloudXR client. + + +.. _connect-xr-device: + +Connect an XR Device +-------------------- + +Isaac Teleop supports several XR headsets. You only need **one** of the devices below -- +choose the tab that matches your hardware. + +.. tab-set:: + + .. tab-item:: Meta Quest 3 / Pico 4 Ultra + :selected: + + .. _connect-quest-pico: + + Meta Quest 3 and Pico 4 Ultra connect to Isaac Lab via the + `CloudXR.js `_ + WebXR client. The built-in environments default to the ``cloudxrjs-cloudxr.env`` profile + (``auto-webrtc``), which is the correct setting for these devices. + + .. note:: + + Pico 4 Ultra requires Pico OS 15.4.4U or later and must use HTTPS mode. + + #. Launch the teleop script as shown in + :ref:`run-isaac-lab-with-the-cloudxr-runtime`. The CloudXR runtime and WSS proxy + start automatically. + + #. Open the browser on your headset and navigate to the hosted CloudXR.js client: + ``_. + + .. note:: + + The web client URL is versioned. The ``release-1.3.x`` path corresponds to the + Isaac Teleop version Isaac Lab is pinned to (``isaacteleop~=1.3.0`` in + ``source/isaaclab_teleop/setup.py``). When Isaac Lab bumps its Isaac Teleop + pin, update this link to the matching client release. + + .. tip:: + + For rapid development, you can test the CloudXR.js client on a desktop browser + before deploying to headsets. + + #. Enter the IP address of your Isaac Lab host machine in the **Server IP** field. + + #. Because the WSS proxy uses a self-signed certificate, you must accept it before + connecting. Click the **Click https://:48322/ to accept cert** link that + appears on the page. + + .. image:: ../_static/setup/cloudxr_accept_cert.jpg + :alt: CloudXR.js certificate acceptance link + :align: center + :width: 400 + + A new tab opens with a **"Your connection is not private"** warning. Click + **Advanced**, then click **Proceed to (unsafe)**. + + .. image:: ../_static/setup/cloudxr_accept_cert_not_private.jpg + :alt: Browser privacy warning for self-signed certificate + :align: center + :width: 500 + + The browser will show a **"Certificate Accepted"** page confirming the certificate + has been accepted. Close this tab and return to the CloudXR.js client page. + + .. image:: ../_static/setup/cloudxr_accept_cert_accepted.jpg + :alt: Certificate accepted confirmation page + :align: center + :width: 400 + + #. Click **Connect** to begin teleoperation. + + For advanced configuration, troubleshooting, and additional details, see the + `CloudXR.js User Guide + `_. + + .. tab-item:: Apple Vision Pro + + .. _use-apple-vision-pro: + + Apple Vision Pro connects to Isaac Lab via the native `Isaac XR Teleop Sample Client`_ app. + + .. important:: + + Apple Vision Pro requires the ``auto-native`` device profile. Pass the ``avp`` + shorthand when launching the teleop script: + + .. code-block:: bash + + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ + --visualizer kit --xr \ + --cloudxr_env avp + + See :ref:`isaac-teleop-cloudxr-profiles` for details on the shipped profiles. + + .. _build-apple-vision-pro: + + .. rubric:: Build and Install the Client App + + Requirements: + + * Apple Vision Pro with visionOS 26, Apple M3 Pro chip (11-core CPU), 16 GB unified memory + * Apple Silicon Mac with macOS Sequoia 15.6+ and Xcode 26.0 + + On your Mac: + + #. Clone the `Isaac XR Teleop Sample Client`_ repository: + + .. code-block:: bash + + git clone git@github.com:isaac-sim/isaac-xr-teleop-sample-client-apple.git + + #. Check out the version that matches your Isaac Lab version: + + +-------------------+---------------------+ + | Isaac Lab Version | Client App Version | + +-------------------+---------------------+ + | 3.0 | v3.0.0 | + +-------------------+---------------------+ + | 2.3 | v2.3.0 | + +-------------------+---------------------+ + + .. code-block:: bash + + git checkout + + #. Follow the README in the repository to build and install the app on your Apple Vision + Pro. + + .. _teleoperate-apple-vision-pro: + + .. rubric:: Teleoperate with Apple Vision Pro + + .. tip:: + + **Before wearing the headset**, verify connectivity from your Mac: + + .. code:: bash + + nc -vz 48010 + + Expected output: ``Connection to port 48010 [tcp/*] succeeded!`` + + On your Isaac Lab workstation, ensure Isaac Lab and CloudXR are running as described in + :ref:`run-isaac-lab-with-the-cloudxr-runtime`. + + On your Apple Vision Pro: + + #. Open the Isaac XR Teleop Sample Client. + + .. figure:: ../_static/setup/cloudxr_avp_connect_ui.jpg + :align: center + :figwidth: 50% + :alt: Apple Vision Pro connect UI + + #. Enter the IP address of your Isaac Lab workstation and click **Connect**. + + .. note:: + + The Apple Vision Pro and workstation must be IP-reachable from one another. We + recommend a dedicated Wifi 6 router. + + #. After a brief period you should see the simulation rendered in the headset along with + teleoperation controls. + + .. figure:: ../_static/setup/cloudxr_avp_teleop_ui.jpg + :align: center + :figwidth: 50% + :alt: Apple Vision Pro teleop UI + + #. Click **Play** to begin teleoperating. Use **Play**, **Stop**, and **Reset** to control + the session. + + .. tip:: + + For bimanual tasks, visionOS voice control enables hands-free UI: + + #. **Settings** > **Accessibility** > **Voice Control** > Turn on **Voice Control** + #. Enable **** under **Commands** > **Basic Navigation** + #. Say "Play", "Stop", or "Reset" while the app is connected. + + #. Teleoperate the robot by moving your hands. + + .. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/cloudxr_bimanual_teleop.gif + :align: center + :alt: Bimanual dexterous teleoperation with CloudXR + + .. note:: + + If the IK solver fails, an error message appears in the headset. Click **Reset** to + return the robot to its original pose and continue. + + .. figure:: ../_static/setup/cloudxr_avp_ik_error.jpg + :align: center + :figwidth: 80% + :alt: IK error message in XR device + + #. Click **Disconnect** when finished. + + +.. _manus-vive-handtracking: + +Manus Gloves +------------ + +Manus gloves provide high-fidelity finger tracking via the Manus SDK. This is useful when optical +hand tracking from the headset is occluded or when higher-precision finger data is needed. + +.. important:: + + Manus gloves and other external push-device peripherals require + ``NV_CXR_ENABLE_PUSH_DEVICES=1``. The shipped ``.env`` profiles set this to ``0`` + (optimised for headset optical hand tracking). To use Manus gloves, create a custom + ``.env`` file with the value set to ``1`` and pass it via ``--cloudxr_env``: + + .. code-block:: bash + + # Copy a shipped profile and enable push devices + cp $(python -c "from isaaclab_teleop import CLOUDXR_JS_ENV; print(CLOUDXR_JS_ENV)") ~/manus.env + sed -i 's/NV_CXR_ENABLE_PUSH_DEVICES=0/NV_CXR_ENABLE_PUSH_DEVICES=1/' ~/manus.env + + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ + --visualizer kit --xr \ + --cloudxr_env ~/manus.env + + See :ref:`isaac-teleop-cloudxr-profiles` for full details on customising profiles. + +.. note:: + + Manus glove support has been migrated into Isaac Teleop as a native plugin. The previous + ``isaac-teleop-device-plugins`` repository and the ``libsurvive``-based Vive tracker integration + are no longer required. + +Requirements: + +* Manus gloves with a Manus SDK license + +The Manus plugin is included in the ``isaacteleop`` package and activated automatically when +configured in the environment's retargeting pipeline. Manus tracking data flows through the same +API as headset-based optical hand tracking in Isaac Teleop, so the same retargeters and pipelines +work with both input sources. + +For plugin configuration details, see the `Manus plugin documentation +`_. + +The recommended workflow: + +#. Start Isaac Lab and click **Start XR**. +#. Put on the Manus gloves and headset. +#. Use voice commands to launch the Isaac XR Teleop Sample Client and connect to Isaac Lab. + + +Run with Docker +--------------- + +Teleoperation runs in a **single container**. Build the image yourself and run a single container. +Do **not** use Docker Compose, which is a multi-container setup as we had in Isaac Lab 2.x. All +components run inside one container with Isaac Lab in this release. + +The CloudXR runtime auto-launches when a teleop script is started, so no separate +runtime command is needed. + +.. attention:: + + Recent Isaac Lab Docker images (3.0.0-beta2 and later) run as a **non-root** user + (uid/gid 1000). Persistent named volumes or host directories that were created by an + earlier root-based image are owned by ``root`` and are **not writable** by the runtime + user. The XR teleop workflow trips on this first, because it writes the extension + registry cache under the runtime home. The failure looks like:: + + [Error] [carb.scripting-python.plugin] PermissionError: [Errno 13] Permission denied: '/root/.local/share/ov/data/exts' + + followed by a cascade of extension-registry errors that abort the app *before* the XR + session can start:: + + [Error] [omni.ext.plugin] Syncing with extension registry unavailable. + [Error] [omni.ext.plugin] Failed to resolve extension dependencies. Failure hints: + * No versions of omni.kit.xr.bundle.generic that satisfies: isaaclab.python.xr.openxr-3.0.0 ... + [Error] [omni.kit.app.plugin] Exiting app because of dependency solver failure... + + The XR bundle is not actually missing -- the registry never synced because its cache + directory could not be created. To fix it, make the persistent storage writable by + uid/gid 1000 before relaunching: + + * **Docker Compose:** recreate the named volumes, e.g. + + .. code-block:: bash + + docker compose --file docker-compose.yaml --profile base --env-file .env.base down --volumes + + See :ref:`deployment-docker` for details. To preserve cached data instead of + deleting it, ``chown`` the volume: ``docker run --rm -v docker_isaac-data:/data alpine + chown -R 1000:1000 /data``. + * **Single container with bind mounts:** pre-create the host directories and + ``sudo chown -R 1000:1000`` them before launching, so the non-root user can write to + them. + +Run the teleop script (e.g. ``record_demos.py`` to record demonstrations): + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tools/record_demos.py \ + --task Isaac-PickPlace-Locomanipulation-G1-Abs-v0 \ + --num_demos 5 \ + --dataset_file ./datasets/dataset.hdf5 \ + --xr --visualizer kit + +Then in the Isaac Sim UI, set the XR panel to **System OpenXR Runtime** and click **Start XR**. + +For a fully headless experience, replace ``--visualizer kit`` with ``--headless`` and the XR +teleop session will run automatically. + +.. admonition:: Next Steps + + * **Architecture, retargeting, and control schemes**: :ref:`isaac-teleop-feature` + * **Teleoperation for imitation learning**: :ref:`teleoperation-imitation-learning` + * **API reference**: :ref:`isaaclab_teleop-api` + + +.. + References +.. _`Apple Vision Pro`: https://www.apple.com/apple-vision-pro/ +.. _`NVIDIA CloudXR`: https://developer.nvidia.com/cloudxr-sdk +.. _`Isaac XR Teleop Sample Client`: https://github.com/isaac-sim/isaac-xr-teleop-sample-client-apple +.. _`CloudXR Network Setup`: https://docs.nvidia.com/cloudxr-sdk/latest/requirement/network_setup.html +.. _`CloudXR.js`: https://docs.nvidia.com/cloudxr-sdk/latest/usr_guide/cloudxr_js/index.html diff --git a/simulation/modules/IsaacLab/docs/source/how-to/configure_rendering.rst b/simulation/modules/IsaacLab/docs/source/how-to/configure_rendering.rst new file mode 100644 index 0000000000000000000000000000000000000000..78b8cdea9dace3e48a0881197fd13dbbbe9ddac7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/configure_rendering.rst @@ -0,0 +1,201 @@ +Configuring RTX Rendering Settings +==================================== + +.. note:: + + This guide covers the **RTX renderer** settings, which are used when running Isaac Lab with + Isaac Sim. The RTX renderer is based on NVIDIA's Omniverse RTX rendering pipeline and is + available for all camera sensors in the PhysX backend. + + For the **Newton renderer** (used with the Newton backend or in kit-less mode), see + :ref:`overview_renderers` for the pluggable renderer architecture and available backends. + +Isaac Lab's RTX renderer offers 3 preset rendering modes: performance, balanced, and quality. +You can select a mode via a command line argument or from within a script, and customize settings as needed. +Adjust and fine-tune rendering to achieve the ideal balance for your workflow. + +Selecting a Rendering Mode +-------------------------- + +Rendering modes can be selected in 2 ways. + +1. using the ``rendering_mode`` input class argument in :class:`~sim.RenderCfg` + + .. code-block:: python + + # for an example of how this can be used, checkout the tutorial script + # scripts/tutorials/00_sim/set_rendering_mode.py + render_cfg = sim_utils.RenderCfg(rendering_mode="performance") + +2. using the ``--rendering_mode`` CLI argument, which takes precedence over the ``rendering_mode`` argument in :class:`~sim.RenderCfg`. + + .. code-block:: bash + + python scripts/tutorials/00_sim/set_rendering_mode.py --rendering_mode {performance/balanced/quality} + + +Note, the ``rendering_mode`` defaults to ``balanced``. +However, in the case where the launcher argument ``--enable_cameras`` is not set, then +the default ``rendering_mode`` is not applied and, instead, the default kit rendering settings are used. + + +Example renders from the ``set_rendering_mode.py`` script. +To help assess rendering, the example scene includes some reflections, translucency, direct and ambient lighting, and several material types. + +- Quality Mode + + .. image:: ../_static/how-to/howto_rendering_example_quality.jpg + :width: 100% + :alt: Quality Rendering Mode Example + +- Balanced Mode + + .. image:: ../_static/how-to/howto_rendering_example_balanced.jpg + :width: 100% + :alt: Balanced Rendering Mode Example + +- Performance Mode + + .. image:: ../_static/how-to/howto_rendering_example_performance.jpg + :width: 100% + :alt: Performance Rendering Mode Example + +Overwriting Specific Rendering Settings +--------------------------------------- + +Preset rendering settings can be overwritten via the :class:`~sim.RenderCfg` class. + +There are 2 ways to provide settings that overwrite presets. + +1. :class:`~sim.RenderCfg` supports overwriting specific settings via user-friendly setting names that map to underlying RTX settings. + For example: + + .. code-block:: python + + render_cfg = sim_utils.RenderCfg( + rendering_mode="performance", + # user friendly setting overwrites + enable_translucency=True, # defaults to False in performance mode + enable_reflections=True, # defaults to False in performance mode + dlss_mode="3", # defaults to 1 in performance mode + ) + + List of user-friendly settings. + + .. table:: + :widths: 25 75 + + +----------------------------+--------------------------------------------------------------------------+ + | enable_translucency | Bool. Enables translucency for specular transmissive surfaces such as | + | | glass at the cost of some performance. | + +----------------------------+--------------------------------------------------------------------------+ + | enable_reflections | Bool. Enables reflections at the cost of some performance. | + +----------------------------+--------------------------------------------------------------------------+ + | enable_global_illumination | Bool. Enables Diffused Global Illumination at the cost of some | + | | performance. | + +----------------------------+--------------------------------------------------------------------------+ + | antialiasing_mode | Literal["Off", "FXAA", "DLSS", "TAA", "DLAA"]. | + | | | + | | DLSS: Boosts performance by using AI to output higher resolution frames | + | | from a lower resolution input. DLSS samples multiple lower resolution | + | | images and uses motion data and feedback from prior frames to reconstruct| + | | native quality images. | + | | DLAA: Provides higher image quality with an AI-based anti-aliasing | + | | technique. DLAA uses the same Super Resolution technology developed for | + | | DLSS, reconstructing a native resolution image to maximize image quality.| + +----------------------------+--------------------------------------------------------------------------+ + | enable_dlssg | Bool. Enables the use of DLSS-G. DLSS Frame Generation boosts performance| + | | by using AI to generate more frames. This feature requires an Ada | + | | Lovelace architecture GPU and can hurt performance due to additional | + | | thread-related activities. | + +----------------------------+--------------------------------------------------------------------------+ + | enable_dl_denoiser | Bool. Enables the use of a DL denoiser, which improves the quality of | + | | renders at the cost of performance. | + +----------------------------+--------------------------------------------------------------------------+ + | dlss_mode | Literal[0, 1, 2, 3]. For DLSS anti-aliasing, selects the performance/ | + | | quality tradeoff mode. Valid values are 0 (Performance), 1 (Balanced), | + | | 2 (Quality), or 3 (Auto). | + +----------------------------+--------------------------------------------------------------------------+ + | enable_direct_lighting | Bool. Enable direct light contributions from lights. | + +----------------------------+--------------------------------------------------------------------------+ + | samples_per_pixel | Int. Defines the Direct Lighting samples per pixel. Higher values | + | | increase the direct lighting quality at the cost of performance. | + +----------------------------+--------------------------------------------------------------------------+ + | enable_shadows | Bool. Enables shadows at the cost of performance. When disabled, lights | + | | will not cast shadows. | + +----------------------------+--------------------------------------------------------------------------+ + | enable_ambient_occlusion | Bool. Enables ambient occlusion at the cost of some performance. | + +----------------------------+--------------------------------------------------------------------------+ + + +2. For more control, :class:`~sim.RenderCfg` allows you to overwrite any RTX setting by using the ``carb_settings`` argument. + + Examples of RTX settings can be found from within the repo, in the render mode preset files located in ``apps/rendering_modes``. + + In addition, the full NVIDIA RTX renderer documentation can be found at + https://docs.omniverse.nvidia.com/materials-and-rendering/latest/rtx-renderer.html. + + An example usage of ``carb_settings``. + + .. code-block:: python + + render_cfg = sim_utils.RenderCfg( + rendering_mode="quality", + # carb setting overwrites + carb_settings={ + "rtx.translucency.enabled": False, + "rtx.reflections.enabled": False, + "rtx.domeLight.upperLowerStrategy": 3, + } + ) + + +Current Limitations +------------------- + +For performance reasons, we default to using DLSS for denoising, which generally provides better performance. +This may result in renders of lower quality, which may be especially evident at lower resolutions. +Due to this, we recommend using per-tile or per-camera resolution of at least 100 x 100. +For renders at lower resolutions, we advice setting the ``antialiasing_mode`` attribute in :class:`~sim.RenderCfg` to +``DLAA``, and also potentially enabling ``enable_dl_denoiser``. Both of these settings should help improve render +quality, but also comes at a cost of performance. Additional rendering parameters can also be specified in :class:`~sim.RenderCfg`. + + +If you observe visual artifacts such as ghosting or disocclusion issues when using tiled rendering, you can try +adjusting the ``disocclusionScale`` parameter. This setting controls how aggressively the renderer handles +areas that become newly visible between frames: + +.. code-block:: python + + render_cfg = sim_utils.RenderCfg( + carb_settings={ + "/rtx/aovConverter/disocclusionScale": 10000, + } + ) + +.. note:: + + This parameter is not commonly exposed as it may have side effects in certain scenarios. + Only use it as a last resort if other quality settings do not resolve the visual artifacts. + The value can be adjusted to a very high value to reduce disocclusion artifacts. + + +Rendering UsdVol 3D Gaussian Scenes in Multiple Environments +------------------------------------------------------------ + +When using UsdVol volumes with 3D Gaussian particles (e.g. exported from +`3DGRUT `_) +in **multiple environments**, you must set the following so the renderer uses the correct compositing path: + +.. code-block:: python + + render_cfg = sim_utils.RenderCfg( + carb_settings={ + "omni.rtx.nre.compositing.rendererHints": 3, + } + ) + +.. warning:: + + With multiple environments, each environment holds its own copy of the scene, increasing device memory use, + and environments are rendered one after another, which can substantially slow down rendering. diff --git a/simulation/modules/IsaacLab/docs/source/how-to/curriculums.rst b/simulation/modules/IsaacLab/docs/source/how-to/curriculums.rst new file mode 100644 index 0000000000000000000000000000000000000000..8c2a94e82cbe21b8f2768e6c38acc0e8a9513c87 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/curriculums.rst @@ -0,0 +1,122 @@ +Curriculum Utilities +==================== + +.. currentmodule:: isaaclab.managers + +This guide walks through the common curriculum helper functions and terms that can be used to create flexible curricula +for RL environments in Isaac Lab. These utilities can be passed to a :class:`~isaaclab.managers.CurriculumTermCfg` +object to enable dynamic modification of reward weights and environment parameters during training. + +.. note:: + + We cover three utilities in this guide: + - The simple function modifies reward :func:`modify_reward_weight` + - The term modify any environment parameters :class:`modify_env_param` + - The term modify term_cfg :class:`modify_term_cfg` + +.. dropdown:: Full source for curriculum utilities + :icon: code + + .. literalinclude:: ../../../source/isaaclab/isaaclab/envs/mdp/curriculums.py + :language: python + + +Modifying Reward Weights +------------------------ + +The function :func:`modify_reward_weight` updates the weight of a reward term after a specified number of simulation +steps. This can be passed directly as the ``func`` in a ``CurriculumTermCfg``. + +.. literalinclude:: ../../../source/isaaclab/isaaclab/envs/mdp/curriculums.py + :language: python + :pyobject: modify_reward_weight + +**Usage example**: + +.. code-block:: python + + from isaaclab.managers import CurriculumTermCfg + import isaaclab.managers.mdp as mdp + + # After 100k steps, set the "sparse_reward" term weight to 0.5 + sparse_reward_schedule = CurriculumTermCfg( + func=mdp.modify_reward_weight, + params={ + "term_name": "sparse_reward", + "weight": 0.5, + "num_steps": 100_000, + } + ) + + +Dynamically Modifying Environment Parameters +-------------------------------------------- + +The class :class:`modify_env_param` is a :class:`~isaaclab.managers.ManagerTermBase` subclass that lets you target any +dotted attribute path in the environment and apply a user-supplied function to compute a new value at runtime. It +handles nested attributes, dictionary keys, list or tuple indexing, and respects a ``NO_CHANGE`` sentinel if no update +is desired. + +.. literalinclude:: ../../../source/isaaclab/isaaclab/envs/mdp/curriculums.py + :language: python + :pyobject: modify_env_param + +**Usage example**: + +.. code-block:: python + + import torch + from isaaclab.managers import CurriculumTermCfg + import isaaclab.managers.mdp as mdp + + def resample_friction(env, env_ids, old_value, low, high, num_steps): + # After num_steps, sample a new friction coefficient uniformly + if env.common_step_counter > num_steps: + return torch.empty((len(env_ids),), device="cpu").uniform_(low, high) + return mdp.modify_env_param.NO_CHANGE + + friction_curriculum = CurriculumTermCfg( + func=mdp.modify_env_param, + params={ + "address": "event_manager.cfg.object_physics_material.func.material_buckets", + "modify_fn": resample_friction, + "modify_params": { + "low": 0.3, + "high": 1.0, + "num_steps": 120_000, + } + } + ) + + +Modify Term Configuration +------------------------- + +The subclass :class:`modify_term_cfg` provides a more concise style address syntax, using consistent with hydra config +syntax. It otherwise behaves identically to :class:`modify_env_param`. + +.. literalinclude:: ../../../source/isaaclab/isaaclab/envs/mdp/curriculums.py + :language: python + :pyobject: modify_term_cfg + +**Usage example**: + +.. code-block:: python + + def override_command_range(env, env_ids, old_value, value, num_steps): + # Override after num_steps + if env.common_step_counter > num_steps: + return value + return mdp.modify_term_cfg.NO_CHANGE + + range_override = CurriculumTermCfg( + func=mdp.modify_term_cfg, + params={ + "address": "commands.object_pose.ranges.pos_x", + "modify_fn": override_command_range, + "modify_params": { + "value": (-0.75, -0.25), + "num_steps": 12_000, + } + } + ) diff --git a/simulation/modules/IsaacLab/docs/source/how-to/draw_markers.rst b/simulation/modules/IsaacLab/docs/source/how-to/draw_markers.rst new file mode 100644 index 0000000000000000000000000000000000000000..d2d4cf45593bb579414df3d04145862def152c27 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/draw_markers.rst @@ -0,0 +1,75 @@ +Creating Visualization Markers +============================== + +.. currentmodule:: isaaclab + +Visualization markers are useful to debug the state of the environment. They can be used to visualize +the frames, commands, and other information in the simulation. + +While Isaac Sim provides its own :mod:`isaacsim.util.debug_draw` extension, it is limited to rendering only +points, lines and splines. For cases, where you need to render more complex shapes, you can use the +:class:`markers.VisualizationMarkers` class. + +This guide is accompanied by a sample script ``markers.py`` in the ``IsaacLab/scripts/demos`` directory. + +.. dropdown:: Code for markers.py + :icon: code + + .. literalinclude:: ../../../scripts/demos/markers.py + :language: python + :emphasize-lines: 45-90, 106-107, 136-142 + :linenos: + + + +Configuring the markers +----------------------- + +The :class:`~markers.VisualizationMarkersCfg` class provides a simple interface to configure +different types of markers. It takes in the following parameters: + +- :attr:`~markers.VisualizationMarkersCfg.prim_path`: The corresponding prim path for the marker class. +- :attr:`~markers.VisualizationMarkersCfg.markers`: A dictionary specifying the different marker prototypes + handled by the class. The key is the name of the marker prototype and the value is its spawn configuration. + +.. note:: + + In case the marker prototype specifies a configuration with physics properties, these are removed. + This is because the markers are not meant to be simulated. + +Here we show all the different types of markers that can be configured. These range from simple shapes like +cones and spheres to more complex geometries like a frame or arrows. The marker prototypes can also be +configured from USD files. + +.. literalinclude:: ../../../scripts/demos/markers.py + :language: python + :lines: 45-90 + :dedent: + + +Drawing the markers +------------------- + +To draw the markers, we call the :class:`~markers.VisualizationMarkers.visualize` method. This method takes in +as arguments the pose of the markers and the corresponding marker prototypes to draw. + +.. literalinclude:: ../../../scripts/demos/markers.py + :language: python + :lines: 136-142 + :dedent: + + +Executing the Script +-------------------- + +To run the accompanying script, execute the following command: + +.. code-block:: bash + + python scripts/demos/markers.py + +The simulation should start, and you can observe the different types of markers arranged in a grid pattern. +The markers will rotating around their respective axes. Additionally every few rotations, they will +roll forward on the grid. + +To stop the simulation, close the window, or use ``Ctrl+C`` in the terminal. diff --git a/simulation/modules/IsaacLab/docs/source/how-to/estimate_how_many_cameras_can_run.rst b/simulation/modules/IsaacLab/docs/source/how-to/estimate_how_many_cameras_can_run.rst new file mode 100644 index 0000000000000000000000000000000000000000..08bf65c2325e73f188b5c0367cad0b7bb93e3d1f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/estimate_how_many_cameras_can_run.rst @@ -0,0 +1,111 @@ +.. _how-to-estimate-how-cameras-can-run: + + +Find How Many/What Cameras You Should Train With +================================================ + +.. currentmodule:: isaaclab + +Currently in Isaac Lab, there are several camera types; USD Cameras (standard), Tiled Cameras, +and Ray Caster cameras. These camera types differ in functionality and performance. The ``benchmark_cameras.py`` +script can be used to understand the difference in cameras types, as well to characterize their relative performance +at different parameters such as camera quantity, image dimensions, and data types. + +This utility is provided so that one easily can find the camera type/parameters that are the most performant +while meeting the requirements of the user's scenario. This utility also helps estimate +the maximum number of cameras one can realistically run, assuming that one wants to maximize the number +of environments while minimizing step time. + +This utility can inject cameras into an existing task from the gym registry, +which can be useful for benchmarking cameras in a specific scenario. Also, +if you install ``pynvml``, you can let this utility automatically find the maximum +numbers of cameras that can run in your task environment up to a +certain specified system resource utilization threshold (without training; taking zero actions +at each timestep). + +This guide accompanies the ``benchmark_cameras.py`` script in the ``scripts/benchmarks`` +directory. + +.. dropdown:: Code for benchmark_cameras.py + :icon: code + + .. literalinclude:: ../../../scripts/benchmarks/benchmark_cameras.py + :language: python + :linenos: + + +Possible Parameters +------------------- + +First, run + +.. code-block:: bash + + python scripts/benchmarks/benchmark_cameras.py -h + +to see all possible parameters you can vary with this utility. + + +See the command line parameters related to ``autotune`` for more information about +automatically determining maximum camera count. + + +Compare Performance in Task Environments and Automatically Determine Task Max Camera Count +------------------------------------------------------------------------------------------ + +Currently, tiled cameras are the most performant camera that can handle multiple dynamic objects. + +For example, to see how your system could handle 100 tiled cameras in +the cartpole environment, with 2 cameras per environment (so 50 environments total) +only in RGB mode, run + +.. code-block:: bash + + python scripts/benchmarks/benchmark_cameras.py --task Isaac-Cartpole-v0 --num_tiled_cameras 100 --task_num_cameras_per_env 2 --tiled_camera_data_types rgb + +If you have pynvml installed, (``python -m pip install pynvml``), you can also +find the maximum number of cameras that you could run in the specified environment up to +a certain performance threshold (specified by max CPU utilization percent, max RAM utilization percent, +max GPU compute percent, and max GPU memory percent). For example, to find the maximum number of cameras +you can run with cartpole, you could run: + +.. code-block:: bash + + python scripts/benchmarks/benchmark_cameras.py --task Isaac-Cartpole-v0 --num_tiled_cameras 100 --task_num_cameras_per_env 2 --tiled_camera_data_types rgb --autotune --autotune_max_percentage_util 100 80 50 50 + +Autotune may lead to the program crashing, which means that it tried to run too many cameras at once. +However, the max percentage utilization parameter is meant to prevent this from happening. + +The output of the benchmark doesn't include the overhead of training the network, so consider +decreasing the maximum utilization percentages to account for this overhead. The final output camera +count is for all cameras, so to get the total number of environments, divide the output camera count +by the number of cameras per environment. + + +Compare Camera Type and Performance (Without a Specified Task) +-------------------------------------------------------------- + +This tool can also asses performance without a task environment. +For example, to view 100 random objects with 2 standard cameras, one could run + +.. code-block:: bash + + python scripts/benchmarks/benchmark_cameras.py --height 100 --width 100 --num_standard_cameras 2 --standard_camera_data_types instance_segmentation_fast normals --num_objects 100 --experiment_length 100 + +If your system cannot handle this due to performance reasons, then the process will be killed. +It's recommended to monitor CPU/RAM utilization and GPU utilization while running this script, to get +an idea of how many resources rendering the desired camera requires. In Ubuntu, you can use tools like ``htop`` and ``nvtop`` +to live monitor resources while running this script, and in Windows, you can use the Task Manager. + +If your system has a hard time handling the desired cameras, you can try the following + + - Disable unneeded visualization + - Ensure you are using the GPU pipeline not CPU! + - If you aren't using Tiled Cameras, switch to Tiled Cameras + - Decrease camera resolution + - Decrease how many data_types there are for each camera. + - Decrease the number of cameras + - Decrease the number of objects in the scene + +If your system is able to handle the amount of cameras, then the time statistics will be printed to the terminal. +After the simulations stops it can be closed with CTRL+C. diff --git a/simulation/modules/IsaacLab/docs/source/how-to/haply_teleoperation.rst b/simulation/modules/IsaacLab/docs/source/how-to/haply_teleoperation.rst new file mode 100644 index 0000000000000000000000000000000000000000..d4df3b5edab3165df9e9067b7c92602cfdf6ead6 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/haply_teleoperation.rst @@ -0,0 +1,223 @@ +.. _haply-teleoperation: + +Setting up Haply Teleoperation +=============================== + +.. currentmodule:: isaaclab + +`Haply Devices`_ provides haptic devices that enable intuitive robot teleoperation with +directional force feedback. The Haply Inverse3 paired with the VerseGrip creates an +end-effector control system with force feedback capabilities. + +Isaac Lab supports Haply devices for teleoperation workflows that require precise spatial +control with haptic feedback. This enables operators to feel contact forces during manipulation +tasks, improving control quality and task performance. + +This guide explains how to set up and use Haply devices with Isaac Lab for robot teleoperation. + +.. _Haply Devices: https://haply.co/ + + +Overview +-------- + +Using Haply with Isaac Lab involves the following components: + +* **Isaac Lab** simulates the robot environment and streams contact forces back to the operator + +* **Haply Inverse3** provides 3-DOF position tracking and force feedback in the operator's workspace + +* **Haply VerseGrip** adds orientation sensing and button inputs for gripper control + +* **Haply SDK** manages WebSocket communication between Isaac Lab and the Haply hardware + +This guide will walk you through: + +* :ref:`haply-system-requirements` +* :ref:`haply-installation` +* :ref:`haply-device-setup` +* :ref:`haply-running-demo` +* :ref:`haply-troubleshooting` + + +.. _haply-system-requirements: + +System Requirements +------------------- + +Hardware Requirements +~~~~~~~~~~~~~~~~~~~~~ + +* **Isaac Lab Workstation** + + * Ubuntu 22.04 or Ubuntu 24.04 + * Hardware requirements for 200Hz physics simulation: + + * CPU: 8-Core Intel Core i7 or AMD Ryzen 7 (or higher) + * Memory: 32GB RAM (64GB recommended) + * GPU: RTX 3090 or higher + + * Network: Same local network as Haply devices for WebSocket communication + +* **Haply Devices** + + * Haply Inverse3 - Haptic device for position tracking and force feedback + * Haply VerseGrip - Wireless controller for orientation and button inputs + * Both devices must be powered on and connected to the Haply SDK + +Software Requirements +~~~~~~~~~~~~~~~~~~~~~ + +* Isaac Lab (follow the :ref:`installation guide `) +* Haply SDK (provided by Haply Robotics) +* Python 3.12+ +* ``websockets`` Python package (automatically installed with Isaac Lab) + + +.. _haply-installation: + +Installation +------------ + +1. Install Isaac Lab +~~~~~~~~~~~~~~~~~~~~ + +Follow the Isaac Lab :ref:`installation guide ` to set up your environment. + +The ``websockets`` dependency is automatically included in Isaac Lab's requirements. + +2. Install Haply SDK +~~~~~~~~~~~~~~~~~~~~ + +Download the Haply SDK from the `Haply Devices`_ website. +Install the SDK software and configure the devices. + +3. Verify Installation +~~~~~~~~~~~~~~~~~~~~~~ + +Test that your Haply devices are detected by the Haply Device Manager. +You should see both Inverse3 and VerseGrip as connected. + + +.. _haply-device-setup: + +Device Setup +------------ + +1. Physical Setup +~~~~~~~~~~~~~~~~~ + +* Place the Haply Inverse3 on a stable surface +* Ensure the VerseGrip is charged and paired +* Position yourself comfortably to reach the Inverse3 workspace +* Keep the workspace clear of obstacles + +2. Start Haply SDK +~~~~~~~~~~~~~~~~~~ + +Launch the Haply SDK according to Haply's documentation. The SDK typically: + +* Runs a WebSocket server on ``localhost:10001`` +* Streams device data at 200Hz +* Displays connection status for both devices + +3. Test Communication +~~~~~~~~~~~~~~~~~~~~~ + +You can test the WebSocket connection using the following Python script: + +.. code:: python + + import asyncio + import websockets + import json + + async def test_haply(): + uri = "ws://localhost:10001" + async with websockets.connect(uri) as ws: + response = await ws.recv() + data = json.loads(response) + print("Inverse3:", data.get("inverse3", [])) + print("VerseGrip:", data.get("wireless_verse_grip", [])) + + asyncio.run(test_haply()) + +You should see device data streaming from both Inverse3 and VerseGrip. + + +.. _haply-running-demo: + +Running the Demo +---------------- + +The Haply teleoperation demo showcases robot manipulation with force feedback using +a Franka Panda arm. + +Basic Usage +~~~~~~~~~~~ + +.. code:: bash + + # Ensure Haply SDK is running + python scripts/demos/haply_teleoperation.py --websocket_uri ws://localhost:10001 --pos_sensitivity 1.65 + +The demo will: + +1. Connect to the Haply devices via WebSocket +2. Spawn a Franka Panda robot and a cube in simulation +3. Map Haply position to robot end-effector position +4. Stream contact forces back to the Inverse3 for haptic feedback + +Controls +~~~~~~~~ + +* **Move Inverse3**: Controls the robot end-effector position +* **VerseGrip Button A**: Open gripper +* **VerseGrip Button B**: Close gripper +* **VerseGrip Button C**: Rotate end-effector by 60° + +Advanced Options +~~~~~~~~~~~~~~~~ + +Customize the demo with command-line arguments: + +.. code:: bash + + # Use custom WebSocket URI + python scripts/demos/haply_teleoperation.py --websocket_uri ws://192.168.1.100:10001 + + # Adjust position sensitivity (default: 1.0) + python scripts/demos/haply_teleoperation.py --websocket_uri ws://localhost:10001 --pos_sensitivity 2.0 + +Demo Features +~~~~~~~~~~~~~ + +* **Workspace Mapping**: Haply workspace is mapped to robot reachable space with safety limits +* **Inverse Kinematics**: Inverse Kinematics (IK) computes joint positions for desired end-effector pose +* **Force Feedback**: Contact forces from end-effector sensors are sent to Inverse3 for haptic feedback + + +.. _haply-troubleshooting: + +Troubleshooting +--------------- + +No Haptic Feedback +~~~~~~~~~~~~~~~~~~ + +**Problem**: No haptic feedback felt on Inverse3 + +Solutions: + +* Verify Inverse3 is the active device in Haply SDK +* Check contact forces are non-zero in simulation (try grasping the cube) +* Ensure ``limit_force`` is not set too low (default: 2.0N) + + +Next Steps +---------- + +* **Customize the demo**: Modify the workspace mapping or add custom button behaviors +* **Implement your own controller**: Use :class:`~isaaclab.devices.HaplyDevice` in your own scripts + +For more information on device APIs, see :class:`~isaaclab.devices.HaplyDevice` in the API documentation. diff --git a/simulation/modules/IsaacLab/docs/source/how-to/import_new_asset.rst b/simulation/modules/IsaacLab/docs/source/how-to/import_new_asset.rst new file mode 100644 index 0000000000000000000000000000000000000000..92a28e4c1b54af6971c369f1d304deae8c06d4df --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/import_new_asset.rst @@ -0,0 +1,493 @@ +Importing a New Asset +===================== + +.. currentmodule:: isaaclab + +NVIDIA Omniverse relies on the Universal Scene Description (USD) file format to +import and export assets. USD is an open source file format developed by Pixar +Animation Studios. It is a scene description format optimized for large-scale, +complex data sets. While this format is widely used in the film and animation +industry, it is less common in the robotics community. + +To this end, NVIDIA has developed various importers that allow you to import +assets from other file formats into USD. These importers are available as +extensions to Omniverse Kit: + +* **URDF Importer** - Import assets from URDF files. +* **MJCF Importer** - Import assets from MJCF files. +* **Mesh Importer** - Import assets from various file formats, including + OBJ, FBX, STL, and glTF. + +The recommended workflow from NVIDIA is to use the above importers to convert +the asset into its USD representation. Once the asset is in USD format, you can +use the Omniverse Kit to edit the asset and export it to other file formats. Isaac Sim includes +these importers by default. They can also be enabled manually in Omniverse Kit. + + +An important note to use assets for large-scale simulation is to ensure that they +are in `instanceable`_ format. This allows the asset to be efficiently loaded +into memory and used multiple times in a scene. Otherwise, the asset will be +loaded into memory multiple times, which can cause performance issues. +For more details on instanceable assets, please check the Isaac Sim `documentation`_. + + +Using URDF Importer +------------------- + +For using the URDF importer in the GUI, please check the documentation at `URDF importer`_. For using the URDF importer from Python scripts, we include a utility tool called ``convert_urdf.py``. This script creates an instance of :class:`~sim.converters.UrdfConverterCfg` which +is then passed to the :class:`~sim.converters.UrdfConverter` class. + +.. note:: + The URDF importer was upgraded to version 3.0 in Isaac Sim 6, replacing the previous C++ + binding-based API with a Python pipeline (``urdf-usd-converter``). Assets are now made + instanceable by default — ``make_instanceable`` is no longer a configuration option. + See the :doc:`/source/migration/migrating_to_isaaclab_3-0` for a full list of breaking changes. + +The URDF importer has various configuration parameters that can be set to control the behavior of the importer. +The default values for the importer's configuration parameters are specified are in the :class:`~sim.converters.UrdfConverterCfg` class, and they are listed below. We made a few commonly modified settings to be available as command-line arguments when calling the ``convert_urdf.py``, and they are marked with ``*`` in the list. For a comprehensive list of the configuration parameters, please check the the documentation at `URDF importer`_. + +Articulation and joint structure +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +* :attr:`~sim.converters.UrdfConverterCfg.fix_base` * - Whether to fix the base of the robot. + This depends on whether you have a floating-base or fixed-base robot. The command-line flag is + ``--fix-base`` where when set, the importer will fix the base of the robot, otherwise it will default to floating-base. +* :attr:`~sim.converters.UrdfConverterCfg.merge_fixed_joints` * - Whether to merge the fixed joints. + Usually, this should be set to ``True`` to reduce the asset complexity. The command-line flag is + ``--merge-joints`` where when set, the importer will merge the fixed joints, otherwise it will default to not merging the fixed joints. +* :attr:`~sim.converters.UrdfConverterCfg.joint_drive` - The configuration for the joint drives on the robot. + + * :attr:`~sim.converters.UrdfConverterCfg.JointDriveCfg.drive_type` - The drive type for the joints. + This can be either ``"acceleration"`` or ``"force"``. We recommend using ``"force"`` for most cases. + * :attr:`~sim.converters.UrdfConverterCfg.JointDriveCfg.target_type` - The target type for the joints. + This can be either ``"none"``, ``"position"``, or ``"velocity"``. We recommend using ``"position"`` for most cases. + Setting this to ``"none"`` will disable the drive and set the joint gains to 0.0. + * :attr:`~sim.converters.UrdfConverterCfg.JointDriveCfg.gains` - The drive stiffness and damping gains for the joint. + We support two ways to set the gains: + + * :attr:`~sim.converters.UrdfConverterCfg.JointDriveCfg.PDGainsCfg` - To directly set the stiffness and damping. + Both ``stiffness`` and ``damping`` accept a single float (applied uniformly). + * :attr:`~sim.converters.UrdfConverterCfg.JointDriveCfg.NaturalFrequencyGainsCfg` - To set the gains using the + desired natural frequency response of the system. **Deprecated in URDF importer 3.0** — use + ``PDGainsCfg`` instead. + +Geometry, collisions, and materials +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +* :attr:`~sim.converters.UrdfConverterCfg.collision_from_visuals` - Whether to create collision geometry + from visual geometry when no explicit ```` is defined for a link. Defaults to ``False``. +* :attr:`~sim.converters.UrdfConverterCfg.collision_type` - The collision shape simplification to apply. + One of ``"Convex Hull"`` (default), ``"Convex Decomposition"``, ``"Bounding Sphere"``, or ``"Bounding Cube"``. +* :attr:`~sim.converters.UrdfConverterCfg.self_collision` - Whether to activate self-collisions between + links of the articulation. Defaults to ``False``. +* :attr:`~sim.converters.UrdfConverterCfg.merge_mesh` - Whether to merge meshes where possible to optimize + the model. Defaults to ``False``. +* :attr:`~sim.converters.UrdfConverterCfg.link_density` - Default density in ``kg/m^3`` for links whose + ```` properties are missing. ``0.0`` (default) leaves densities unchanged. + +Asset resolution and output +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +* :attr:`~sim.converters.UrdfConverterCfg.ros_package_paths` - List of ROS package name/path mappings used + to resolve ``package://`` URLs in the URDF. Each entry is a dict with keys ``name`` and ``path``. +* :attr:`~sim.converters.UrdfConverterCfg.robot_type` - Robot type applied by the USD robot schema. + Defaults to ``"Default"``. Must be one of: ``"Default"``, ``"End Effector"``, ``"Manipulator"``, + ``"Humanoid"``, ``"Wheeled"``, ``"Holonomic"``, ``"Quadruped"``, ``"Mobile Manipulators"``, ``"Aerial"``. +* :attr:`~sim.converters.UrdfConverterCfg.run_asset_transformer` - Run the asset transformer to convert + the flattened USD into a layered USD (interface USD + payloads). Defaults to ``True``. +* :attr:`~sim.converters.UrdfConverterCfg.run_multi_physics_conversion` - Also emit MuJoCo-compatible joint + attributes alongside PhysX. Defaults to ``True``. +* :attr:`~sim.converters.UrdfConverterCfg.debug_mode` - Write intermediate conversion artifacts next to the + output USD for inspection. Defaults to ``False``. + +Deprecated (no-op in URDF importer 3.0) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following options are retained for backwards compatibility but are ignored by the URDF importer 3.0. +A warning is logged when they are set. + +* :attr:`~sim.converters.UrdfConverterCfg.root_link_name` - The link on which the PhysX articulation root + was previously placed. +* :attr:`~sim.converters.UrdfConverterCfg.convert_mimic_joints_to_normal_joints` - Convert mimic joints to + normal joints during conversion. +* :attr:`~sim.converters.UrdfConverterCfg.replace_cylinders_with_capsules` - Replace cylinder shapes with + capsule shapes during conversion. + +For more detailed information on the configuration parameters, please check the documentation for :class:`~sim.converters.UrdfConverterCfg`. + +Example Usage +~~~~~~~~~~~~~ + +In this example, we use the pre-processed URDF file of the ANYmal-D robot. To check the +pre-process URDF, please check the file the `anymal.urdf`_. The main difference between the +pre-processed URDF and the original URDF are: + +* We removed the ```` tag from the URDF. This tag is not supported by the URDF importer. +* We removed the ```` tag from the URDF. This tag is not supported by the URDF importer. +* We removed various collision bodies from the URDF to reduce the complexity of the asset. +* We changed all the joint's damping and friction parameters to ``0.0``. This ensures that we can perform + effort-control on the joints without PhysX adding additional damping. +* The ```` URDF tag is **no longer supported** in URDF importer 3.0. Fixed joint + merging is now a Python pre-processing step that merges all fixed joints when + ``merge_fixed_joints`` is enabled. If you need to preserve a specific fixed joint, disable + ``merge_fixed_joints`` entirely or restructure the URDF to use a non-fixed joint type + (e.g. revolute with zero-range limits). + +The following shows the steps to clone the repository and run the converter: + + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + # clone a repository with URDF files + git clone git@github.com:isaac-orbit/anymal_d_simple_description.git + + # go to top of the Isaac Lab repository + cd IsaacLab + # run the converter + python scripts/tools/convert_urdf.py \ + ../anymal_d_simple_description/urdf/anymal.urdf \ + source/isaaclab_assets/data/Robots/ANYbotics/ \ + --merge-joints \ + --joint-stiffness 0.0 \ + --joint-damping 0.0 \ + --joint-target-type none \ + --viz kit + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + :: clone a repository with URDF files + git clone git@github.com:isaac-orbit/anymal_d_simple_description.git + + :: go to top of the Isaac Lab repository + cd IsaacLab + :: run the converter + python scripts\tools\convert_urdf.py ^ + ..\anymal_d_simple_description\urdf\anymal.urdf ^ + source\isaaclab_assets\data\Robots\ANYbotics\ ^ + --merge-joints ^ + --joint-stiffness 0.0 ^ + --joint-damping 0.0 ^ + --joint-target-type none ^ + --viz kit + +Executing the above script will create a USD file inside the +``source/isaaclab_assets/data/Robots/ANYbotics/anymal/`` directory (the subdirectory name +is derived automatically from the robot name in the URDF): + +* ``anymal.usda`` - This is the main asset file. + +.. note:: + The URDF importer auto-deduplicates the per-robot subdirectory when it already exists. + If you re-run the converter against the same ``usd_dir`` with a changed configuration + (for example, flipping ``fix_base``), the importer writes to a new numbered folder + (``anymal_1/``, ``anymal_2/``, …) rather than overwriting the previous output. + :attr:`~sim.converters.UrdfConverter.usd_path` reflects whichever folder the importer + actually used. Delete stale subdirectories manually (or wipe ``usd_dir``) if you do not + want them to accumulate on disk. + +The examples above pass ``--viz kit`` to open the GUI and inspect the converted asset. +To run the script headless and exit after the conversion is complete, omit ``--viz kit``. + +You can press play on the opened window to see the asset in the scene. The asset should fall under gravity. If it blows up, then it might be that you have self-collisions present in the URDF. + + +.. figure:: ../_static/tutorials/tutorial_convert_urdf.jpg + :align: center + :figwidth: 100% + :alt: result of convert_urdf.py + + + +Using MJCF Importer +------------------- + +Similar to the URDF Importer, the MJCF Importer also has a GUI interface. Please check the documentation at +`MJCF importer`_ for more details. For using the MJCF importer from Python scripts, we include a utility tool +called ``convert_mjcf.py``. This script creates an instance of :class:`~sim.converters.MjcfConverterCfg` +which is then passed to the :class:`~sim.converters.MjcfConverter` class. + +The default values for the importer's configuration parameters are specified in the +:class:`~sim.converters.MjcfConverterCfg` class. The configuration parameters are listed below. +We made a few commonly modified settings to be available as command-line arguments when calling the +``convert_mjcf.py``, and they are marked with ``*`` in the list. For a comprehensive list of the configuration +parameters, please check the the documentation at `MJCF importer`_. + +.. note:: + The MJCF importer was rewritten in Isaac Sim 5.0 to use the ``mujoco-usd-converter`` library. + Settings such as ``import_sites``, ``import_inertia_tensor``, and ``make_instanceable`` are no + longer needed — the converter now handles these automatically based on the MJCF file content. + +Geometry, collisions, and materials +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +* :attr:`~sim.converters.MjcfConverterCfg.merge_mesh` * - Whether to merge meshes where possible to + optimize the model. The command-line flag is ``--merge-mesh``. +* :attr:`~sim.converters.MjcfConverterCfg.collision_from_visuals` * - Whether to generate collision + geometry from visual geometries. The command-line flag is ``--collision-from-visuals``. +* :attr:`~sim.converters.MjcfConverterCfg.collision_type` * - The collision shape simplification to + apply. One of ``"Convex Hull"`` (default), ``"Convex Decomposition"``, ``"Bounding Sphere"``, or + ``"Bounding Cube"``. The command-line flag is ``--collision-type``. +* :attr:`~sim.converters.MjcfConverterCfg.self_collision` * - Whether to activate self-collisions + between links of the articulation. The command-line flag is ``--self-collision``. + +Articulation and physics +~~~~~~~~~~~~~~~~~~~~~~~~ + +* :attr:`~sim.converters.MjcfConverterCfg.fix_base` - Whether to add a fixed joint between the world + and the root rigid-body link. Defaults to ``False``. +* :attr:`~sim.converters.MjcfConverterCfg.link_density` - Default density in ``kg/m^3`` for links whose + ```` properties are missing in the MJCF. ``0.0`` (default) leaves densities unchanged. +* :attr:`~sim.converters.MjcfConverterCfg.import_physics_scene` * - Import physics scene properties + (gravity, time step, etc.) from the MJCF file. Defaults to ``False``. The command-line flag is + ``--import-physics-scene``. + +Actuator overrides +~~~~~~~~~~~~~~~~~~ + +MuJoCo models actuators as an affine transformation ``tau = gain @ control + bias``. The following +options override the values parsed from the MJCF on a per-actuator basis. Each defaults to ``None``, +which leaves the parsed values unchanged. + +* :attr:`~sim.converters.MjcfConverterCfg.override_gain_type` - The actuator gain type override (e.g. + ``"fixed"``). +* :attr:`~sim.converters.MjcfConverterCfg.override_bias_type` - The actuator bias type override (e.g. + ``"affine"``). +* :attr:`~sim.converters.MjcfConverterCfg.override_gain_prm` - The actuator gain parameter array override. + Example for position control: ``[kp, 0, 0, 0, 0, 0, 0, 0, 0, 0]``. +* :attr:`~sim.converters.MjcfConverterCfg.override_bias_prm` - The actuator bias parameter array override. + Example for position control: ``[0, -kp, -kd, 0, 0, 0, 0, 0, 0, 0]``. + +Asset resolution and output +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +* :attr:`~sim.converters.MjcfConverterCfg.robot_type` - Robot type applied by the USD robot schema. + Defaults to ``"Default"``. Must be one of: ``"Default"``, ``"End Effector"``, ``"Manipulator"``, + ``"Humanoid"``, ``"Wheeled"``, ``"Holonomic"``, ``"Quadruped"``, ``"Mobile Manipulators"``, ``"Aerial"``. +* :attr:`~sim.converters.MjcfConverterCfg.run_asset_transformer` - Run the asset transformer to convert + the flattened USD into a layered USD (interface USD + payloads). Defaults to ``True``. +* :attr:`~sim.converters.MjcfConverterCfg.run_multi_physics_conversion` - Convert compatible MuJoCo + attributes to PhysX attributes (e.g. actuator gains). Defaults to ``True``. +* :attr:`~sim.converters.MjcfConverterCfg.debug_mode` - Write intermediate conversion artifacts next to + the output USD for inspection. Defaults to ``False``. + +For more detailed information on the configuration parameters, please check the documentation for :class:`~sim.converters.MjcfConverterCfg`. + + +Example Usage +~~~~~~~~~~~~~ + +In this example, we use the MuJoCo model of the Unitree's H1 humanoid robot in the `mujoco_menagerie`_. + +The following shows the steps to clone the repository and run the converter: + + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + # clone a repository with MJCF files + git clone git@github.com:google-deepmind/mujoco_menagerie.git + + # go to top of the Isaac Lab repository + cd IsaacLab + # run the converter + python scripts/tools/convert_mjcf.py \ + ../mujoco_menagerie/unitree_h1/h1.xml \ + source/isaaclab_assets/data/Robots/Unitree/h1.usd \ + --merge-mesh \ + --viz kit + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + :: clone a repository with MJCF files + git clone git@github.com:google-deepmind/mujoco_menagerie.git + + :: go to top of the Isaac Lab repository + cd IsaacLab + :: run the converter + python scripts\tools\convert_mjcf.py ^ + ..\mujoco_menagerie\unitree_h1\h1.xml ^ + source\isaaclab_assets\data\Robots\Unitree\h1.usd ^ + --merge-mesh ^ + --viz kit + +Executing the above script will create the USD file inside the +``source/isaaclab_assets/data/Robots/Unitree/`` directory: + +* ``h1.usd`` - This is the converted USD asset file. + +.. note:: + The MJCF importer auto-deduplicates the per-robot subdirectory when it already exists, + matching the URDF importer's behavior. If you re-run the converter against the same + ``usd_dir`` with a changed configuration, the importer writes to a new numbered folder + (``h1_1/``, ``h1_2/``, …) rather than overwriting the previous output. + :attr:`~sim.converters.MjcfConverter.usd_path` reflects whichever folder the importer + actually used. Delete stale subdirectories manually (or wipe ``usd_dir``) if you do not + want them to accumulate on disk. + +.. figure:: ../_static/tutorials/tutorial_convert_mjcf.jpg + :align: center + :figwidth: 100% + :alt: result of convert_mjcf.py + + +.. _import-new-asset-ensure-drives-exist: + +Ensuring joint drives exist on every joint +------------------------------------------ + +A common pitfall when porting a freshly-imported asset across physics backends +is that joints which actuate fine in PhysX silently do nothing in a +Newton-based backend (MuJoCo Warp, XPBD, Featherstone, Semi-implicit). + +The URDF and MJCF importers both write a ``PhysicsDriveAPI`` to every +articulated joint, but the stiffness and damping on that drive are often left +at ``0`` — the assumption being that the actuator gains are authored at runtime +by an :class:`~isaaclab.actuators.ImplicitActuatorCfg` or +:class:`~isaaclab.actuators.IdealPDActuatorCfg`. This is the recommended way to +keep gains tunable per task without re-importing the USD. + +PhysX creates a solver actuator for every joint regardless of the authored +gains, so the runtime writes from ``ImplicitActuatorCfg.stiffness`` / +``damping`` always take effect. Newton's USD importer, by contrast, only +materialises a solver actuator when the authored drive reports a non-zero +stiffness or damping — a joint whose authored gains are both zero is treated +as passive and is dropped from the actuator set, so subsequent runtime writes +have nothing to attach to. + +The recommended fix is to opt the spawn config into the cross-backend bridge by +setting :attr:`~isaaclab.sim.schemas.JointDrivePropertiesCfg.ensure_drives_exist` +to ``True``: + +.. code:: python + + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Robots/Agility/Cassie/cassie.usd", + joint_drive_props=sim_utils.JointDrivePropertiesCfg(ensure_drives_exist=True), + ... + ) + +When ``ensure_drives_exist=True``, every drive whose authored stiffness *and* +damping are both zero is updated with a minimal placeholder stiffness +(``1e-3``) before the simulation starts. This is enough for Newton's importer +to create the actuator; the actual gains are then overwritten by the actuator +model at runtime, so the placeholder has no effect on the simulated dynamics. +Drives whose authored gains are non-zero are left untouched. + +This is how ``isaaclab_assets.CASSIE_CFG`` keeps Cassie working across both +PhysX and Newton — the asset ships with zero-gain drives because it relies on +``ImplicitActuatorCfg`` for the legs, and the spawn config enables +:attr:`~isaaclab.sim.schemas.JointDrivePropertiesCfg.ensure_drives_exist` so +that both backends see the same actuator set. + +You can leave the flag at its default ``False`` for assets that author non-zero +drive gains in the USD itself, or for assets driven by an +:class:`~isaaclab.actuators.IdealPDActuatorCfg` that explicitly zeroes the +solver drive and applies torque externally. + + +Using Mesh Importer +------------------- + +Omniverse Kit includes the mesh converter tool that uses the ASSIMP library to import assets +from various mesh formats (e.g. OBJ, FBX, STL, glTF, etc.). The asset converter tool is available +as an extension to Omniverse Kit. Please check the `asset converter`_ documentation for more details. +However, unlike Isaac Sim's URDF and MJCF importers, the asset converter tool does not support +creating instanceable assets. This means that the asset will be loaded into memory multiple times +if it is used multiple times in a scene. + +Thus, we include a utility tool called ``convert_mesh.py`` that uses the asset converter tool to +import the asset and then converts it into an instanceable asset. Internally, this script creates +an instance of :class:`~sim.converters.MeshConverterCfg` which is then passed to the +:class:`~sim.converters.MeshConverter` class. Since the mesh file does not contain any physics +information, the configuration class accepts different physics properties (such as mass, collision +shape, etc.) as input. Please check the documentation for :class:`~sim.converters.MeshConverterCfg` +for more details. + +Example Usage +~~~~~~~~~~~~~ + +We use an OBJ file of a cube to demonstrate the usage of the mesh converter. The following shows +the steps to clone the repository and run the converter: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + # clone a repository with mesh files + git clone git@github.com:NVIDIA-Omniverse/IsaacGymEnvs.git + + # go to top of the Isaac Lab repository + cd IsaacLab + # run the converter + python scripts/tools/convert_mesh.py \ + ../IsaacGymEnvs/assets/trifinger/objects/meshes/cube_multicolor.obj \ + source/isaaclab_assets/data/Props/CubeMultiColor/cube_multicolor.usd \ + --make-instanceable \ + --collision-approximation convexDecomposition \ + --mass 1.0 + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + :: clone a repository with mesh files + git clone git@github.com:NVIDIA-Omniverse/IsaacGymEnvs.git + + :: go to top of the Isaac Lab repository + cd IsaacLab + :: run the converter + python scripts\tools\convert_mesh.py ^ + ..\IsaacGymEnvs\assets\trifinger\objects\meshes\cube_multicolor.obj ^ + source\isaaclab_assets\data\Props\CubeMultiColor\cube_multicolor.usd ^ + --make-instanceable ^ + --collision-approximation convexDecomposition ^ + --mass 1.0 + +You may need to press 'F' to zoom in on the asset after import. + +Similar to the URDF and MJCF converter, executing the above script will create two USD files inside the +``source/isaaclab_assets/data/Props/CubeMultiColor/`` directory. Additionally, +if you press play on the opened window, you should see the asset fall down under the influence +of gravity. + +* If you do not set the ``--mass`` flag, then no rigid body properties will be added to the asset. + It will be imported as a static asset. +* If you also do not set the ``--collision-approximation`` flag, then the asset will not have any collider + properties as well and will be imported as a visual asset. + + +.. figure:: ../_static/tutorials/tutorial_convert_mesh.jpg + :align: center + :figwidth: 100% + :alt: result of convert_mesh.py + + +.. _instanceable: https://openusd.org/dev/api/_usd__page__scenegraph_instancing.html +.. _documentation: https://docs.isaacsim.omniverse.nvidia.com/latest/isaac_lab_tutorials/tutorial_instanceable_assets.html +.. _MJCF importer: https://docs.isaacsim.omniverse.nvidia.com/latest/importer_exporter/ext_isaacsim_asset_importer_mjcf.html +.. _URDF importer: https://docs.isaacsim.omniverse.nvidia.com/latest/importer_exporter/ext_isaacsim_asset_importer_urdf.html +.. _anymal.urdf: https://github.com/isaac-orbit/anymal_d_simple_description/blob/master/urdf/anymal.urdf +.. _asset converter: https://docs.omniverse.nvidia.com/extensions/latest/ext_asset-converter.html +.. _mujoco_menagerie: https://github.com/google-deepmind/mujoco_menagerie/tree/main/unitree_h1 diff --git a/simulation/modules/IsaacLab/docs/source/how-to/index.rst b/simulation/modules/IsaacLab/docs/source/how-to/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..7d4f37449e093fcafcc23f1a5e104e6d8300424b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/index.rst @@ -0,0 +1,231 @@ +.. _how-to: + +How-to Guides +============= + +This section includes guides that help you use Isaac Lab. These are intended for users who +have already worked through the tutorials and are looking for more information on how to +use Isaac Lab. If you are new to Isaac Lab, we recommend you start with the tutorials. + +.. note:: + + This section is a work in progress. If you have a question that is not answered here, + please open an issue on our `GitHub page `_. + +Importing a New Asset +--------------------- + +Importing an asset into Isaac Lab is a common task. It contains two steps: importing the asset into +a USD format and then setting up the configuration object for the asset. The following guide explains +how to import a new asset into Isaac Lab. + +.. toctree:: + :maxdepth: 1 + + import_new_asset + write_articulation_cfg + robots + +Creating a Fixed Asset +---------------------- + +Often you may want to create a fixed asset in your scene. For instance, making a floating base robot +a fixed base robot. This guide goes over the various considerations and steps to create a fixed asset. + +.. toctree:: + :maxdepth: 1 + + make_fixed_prim + +Spawning Multiple Assets +------------------------ + +This guide explains how to import and configure different assets in each environment. This is +useful when you want to create diverse environments with different objects. + +.. toctree:: + :maxdepth: 1 + + multi_asset_spawning + +Cloning Environments +-------------------- + +This guide explains how Isaac Lab's template-based cloning system works, including +cloning strategies, heterogeneous environments, and collision filtering. + +.. toctree:: + :maxdepth: 1 + + cloning + +Saving Camera Output +-------------------- + +This guide explains how to save the camera output in Isaac Lab. + +.. toctree:: + :maxdepth: 1 + + save_camera_output + +Estimate How Many Cameras Can Run On Your Machine +------------------------------------------------- + +This guide demonstrates how to estimate the number of cameras one can run on their machine under the desired parameters. + +.. toctree:: + :maxdepth: 1 + + estimate_how_many_cameras_can_run + +Configure Rendering +------------------- + +This guide demonstrates how to select rendering mode presets and overwrite preset rendering settings. + +.. toctree:: + :maxdepth: 1 + + configure_rendering + +Drawing Markers +--------------- + +This guide explains how to use the :class:`~isaaclab.markers.VisualizationMarkers` class to draw markers in +Isaac Lab. + +.. toctree:: + :maxdepth: 1 + + draw_markers + + +Using Visualizers +----------------- + +This guide demonstrates how to use visualizer-specific views for monitoring and debugging Isaac Lab environments. + +.. toctree:: + :maxdepth: 1 + + visualizer_tiled_camera + + +Working with Simulation Data +---------------------------- + +This guide explains how to read and write simulation state using the :class:`~isaaclab.utils.warp.ProxyArray` +dual-access wrapper that all data classes return. + +.. toctree:: + :maxdepth: 1 + + proxy_array + + +Interfacing with Environments +----------------------------- + +These guides explain how to interface with reinforcement learning environments in Isaac Lab. + +.. toctree:: + :maxdepth: 1 + + wrap_rl_env + add_own_library + + +Recording an Animation and Video +-------------------------------- + +This guide explains how to record an animation and video in Isaac Lab. + +.. toctree:: + :maxdepth: 1 + + record_animation + record_video + + +Dynamically Modifying Environment Parameters With CurriculumTerm +---------------------------------------------------------------- + +This guide explains how to dynamically modify environment parameters during training in Isaac Lab. +It covers the use of curriculum utilities to change environment parameters at runtime. + +.. toctree:: + :maxdepth: 1 + + curriculums + + +Mastering Omniverse +------------------- + +Omniverse is a powerful platform that provides a wide range of features. This guide links to +additional resources that help you use Omniverse features in Isaac Lab. + +.. toctree:: + :maxdepth: 1 + + master_omniverse + + +Setting up Isaac Teleop with CloudXR +------------------------------------ + +This guide explains how to install Isaac Teleop, start the CloudXR runtime, and connect XR +devices for immersive teleoperation in Isaac Lab. + +.. toctree:: + :maxdepth: 1 + + cloudxr_teleoperation + + +Setting up Haply Teleoperation +------------------------------ + +This guide explains how to use Haply Inverse3 and VerseGrip devices for robot teleoperation +with directional force feedback in Isaac Lab. + +.. toctree:: + :maxdepth: 1 + + haply_teleoperation + + +Understanding Simulation Performance +------------------------------------ + +This guide provides tips on optimizing simulation performance for different simulation use cases. +Additional resources are also linked to provide relevant performance guides for Isaac Sim and +Omniverse Physics. + +.. toctree:: + :maxdepth: 1 + + simulation_performance + + +Optimize Stage Creation +----------------------- + +This guide explains 2 features that can speed up stage initialization, **fabric cloning** and **stage in memory**. + +.. toctree:: + :maxdepth: 1 + + optimize_stage_creation + + +Profiling Isaac Lab with Nsight Systems +--------------------------------------- + +This guide explains how to profile Isaac Lab tasks with NVIDIA Nsight Systems for runtime performance analysis. + +.. toctree:: + :maxdepth: 1 + + profile_with_nsys diff --git a/simulation/modules/IsaacLab/docs/source/how-to/make_fixed_prim.rst b/simulation/modules/IsaacLab/docs/source/how-to/make_fixed_prim.rst new file mode 100644 index 0000000000000000000000000000000000000000..5726eff266885f06c1c0bce75abb5dedf9c87375 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/make_fixed_prim.rst @@ -0,0 +1,179 @@ +Making a physics prim fixed in the simulation +============================================= + +.. currentmodule:: isaaclab + +When a USD prim has physics schemas applied on it, it is affected by physics simulation. +This means that the prim can move, rotate, and collide with other prims in the simulation world. +However, there are cases where it is desirable to make certain prims static in the simulation world, +i.e. the prim should still participate in collisions but its position and orientation should not change. + +The following sections describe how to spawn a prim with physics schemas and make it static in the simulation world. + +Static colliders +---------------- + +Static colliders are prims that are not affected by physics but can collide with other prims in the simulation world. +These don't have any rigid body properties applied on them. However, this also means that they can't be accessed +using the physics tensor API (i.e., through the :class:`assets.RigidObject` class). + +For instance, to spawn a cone static in the simulation world, the following code can be used: + +.. code-block:: python + + import isaaclab.sim as sim_utils + + cone_spawn_cfg = sim_utils.ConeCfg( + radius=0.15, + height=0.5, + collision_props=sim_utils.CollisionPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)), + ) + cone_spawn_cfg.func( + "/World/Cone", cone_spawn_cfg, translation=(0.0, 0.0, 2.0), orientation=(0.5, 0.0, 0.5, 0.0) + ) + + +Rigid object +------------ + +Rigid objects (i.e. object only has a single body) can be made static by setting the parameter +:attr:`sim.schemas.RigidBodyPropertiesCfg.kinematic_enabled` as True. This will make the object +kinematic and it will not be affected by physics. + +For instance, to spawn a cone static in the simulation world but with rigid body schema on it, +the following code can be used: + +.. code-block:: python + + import isaaclab.sim as sim_utils + + cone_spawn_cfg = sim_utils.ConeCfg( + radius=0.15, + height=0.5, + rigid_props=sim_utils.RigidBodyPropertiesCfg(kinematic_enabled=True), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)), + ) + cone_spawn_cfg.func( + "/World/Cone", cone_spawn_cfg, translation=(0.0, 0.0, 2.0), orientation=(0.5, 0.0, 0.5, 0.0) + ) + + +Articulation +------------ + +Fixing the root of an articulation requires having a fixed joint to the root rigid body link of the articulation. +This can be achieved by setting the parameter :attr:`sim.schemas.ArticulationRootPropertiesCfg.fix_root_link` +as True. Based on the value of this parameter, the following cases are possible: + +* If set to :obj:`None`, the root link is not modified. +* If the articulation already has a fixed root link, this flag will enable or disable the fixed joint. +* If the articulation does not have a fixed root link, this flag will create a fixed joint between the world + frame and the root link. The joint is created with the name "FixedJoint" under the root link. + +For instance, to spawn an ANYmal robot and make it static in the simulation world, the following code can be used: + +.. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR + + anymal_spawn_cfg = sim_utils.UsdFileCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Robots/ANYbotics/ANYmal-C/anymal_c.usd", + activate_contact_sensors=True, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=False, + retain_accelerations=False, + linear_damping=0.0, + angular_damping=0.0, + max_linear_velocity=1000.0, + max_angular_velocity=1000.0, + max_depenetration_velocity=1.0, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=True, + solver_position_iteration_count=4, + solver_velocity_iteration_count=0, + fix_root_link=True, + ), + ) + anymal_spawn_cfg.func( + "/World/ANYmal", anymal_spawn_cfg, translation=(0.0, 0.0, 0.8), orientation=(0.0, 0.0, 0.0, 1.0) + ) + + +This will create a fixed joint between the world frame and the root link of the ANYmal robot +at the prim path ``"/World/ANYmal/base/FixedJoint"`` since the root link is at the path ``"/World/ANYmal/base"``. + + +Further notes +------------- + +Given the flexibility of USD asset designing the following possible scenarios are usually encountered: + +1. **Articulation root schema on the rigid body prim without a fixed joint**: + + This is the most common and recommended scenario for floating-base articulations. The root prim + has both the rigid body and the articulation root properties. In this case, the articulation root + is parsed as a floating-base with the root prim of the articulation ``Link0Xform``. + + .. code-block:: text + + ArticulationXform + └── Link0Xform (RigidBody and ArticulationRoot schema) + +2. **Articulation root schema on the parent prim with a fixed joint**: + + This is the expected arrangement for fixed-base articulations. The root prim has only the rigid body + properties and the articulation root properties are applied to its parent prim. In this case, the + articulation root is parsed as a fixed-base with the root prim of the articulation ``Link0Xform``. + + .. code-block:: text + + ArticulationXform (ArticulationRoot schema) + └── Link0Xform (RigidBody schema) + └── FixedJoint (connecting the world frame and Link0Xform) + +3. **Articulation root schema on the parent prim without a fixed joint**: + + This is a scenario where the root prim has only the rigid body properties and the articulation root properties + are applied to its parent prim. However, the fixed joint is not created between the world frame and the root link. + In this case, the articulation is parsed as a floating-base system. However, the PhysX parser uses its own + heuristic (such as alphabetical order) to determine the root prim of the articulation. It may select the root prim + at ``Link0Xform`` or choose another prim as the root prim. + + .. code-block:: text + + ArticulationXform (ArticulationRoot schema) + └── Link0Xform (RigidBody schema) + +4. **Articulation root schema on the rigid body prim with a fixed joint**: + + While this is a valid scenario, it is not recommended as it may lead to unexpected behavior. In this case, + the articulation is still parsed as a floating-base system. However, the fixed joint, created between the + world frame and the root link, is considered as a part of the maximal coordinate tree. This is different from + PhysX considering the articulation as a fixed-base system. Hence, the simulation may not behave as expected. + + .. code-block:: text + + ArticulationXform + └── Link0Xform (RigidBody and ArticulationRoot schema) + └── FixedJoint (connecting the world frame and Link0Xform) + +For floating base articulations, the root prim usually has both the rigid body and the articulation +root properties. However, directly connecting this prim to the world frame will cause the simulation +to consider the fixed joint as a part of the maximal coordinate tree. This is different from PhysX +considering the articulation as a fixed-base system. + +Internally, when the parameter :attr:`sim.schemas.ArticulationRootPropertiesCfg.fix_root_link` is set to True +and the articulation is detected as a floating-base system, the fixed joint is created between the world frame +the root rigid body link of the articulation. However, to make the PhysX parser consider the articulation as a +fixed-base system, the articulation root properties are removed from the root rigid body prim and applied to +its parent prim instead. + +.. note:: + + In future release of Isaac Sim, an explicit flag will be added to the articulation root schema from PhysX + to toggle between fixed-base and floating-base systems. This will resolve the need of the above workaround. diff --git a/simulation/modules/IsaacLab/docs/source/how-to/master_omniverse.rst b/simulation/modules/IsaacLab/docs/source/how-to/master_omniverse.rst new file mode 100644 index 0000000000000000000000000000000000000000..ee3e0d55c4e45ced9ad4af73a7e9f029aa82c238 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/master_omniverse.rst @@ -0,0 +1,123 @@ +Mastering Omniverse for Robotics +================================ + +NVIDIA Omniverse offers a large suite of tools for 3D content workflows. +There are three main components (relevant to robotics) in Omniverse: + +- **USD Composer**: This is based on a novel file format (Universal Scene + Description) from the animation (originally Pixar) community that is + used in Omniverse +- **PhysX SDK**: This is the main physics engine behind Omniverse that + leverages GPU-based parallelization for massive scenes +- **RTX-enabled Renderer**: This uses ray-tracing kernels in NVIDIA RTX + GPUs for real-time physically-based rendering + +Of these, the first two require a deeper understanding to start working +with Omniverse and its constituent applications (Isaac Sim and Isaac Lab). + +The main things to learn: + +- How to use the Composer GUI efficiently? +- What are USD prims and schemas? +- How do you compose a USD scene? +- What is the difference between references and payloads in USD? +- What is meant by scene-graph instancing? +- How to apply PhysX schemas on prims? What all schemas are possible? +- How to write basic operations in USD for creating prims and modifying + their attributes? + + +Part 1: Using USD Composer +-------------------------- + +While several `video +tutorials `__ and +`documentation `__ exist +out there on NVIDIA Omniverse, going through all of them would take an +extensive amount of time and effort. Thus, we have curated these +resources to guide you through using Omniverse, specifically for +robotics. + +Introduction to Omniverse and USD + +- `What is NVIDIA Omniverse? `__ +- `What is the USD File Type? \| Getting Started in NVIDIA Omniverse `__ +- `What Makes USD Unique in NVIDIA Omniverse `__ + +Using Omniverse USD Composer + +- `Introduction to Omniverse USD Composer `__ +- `Navigation Basics in Omniverse USD Composer `__ +- `Lighting Basics in NVIDIA Omniverse USD Composer `__ +- `Rendering Overview in NVIDIA Omniverse USD Composer `__ + +Materials and MDL + +- `Five Things to Know About Materials in NVIDIA Omniverse `__ +- `How to apply materials? `__ + +Omniverse Physics and PhysX SDK + +- `Basics - Setting Up Physics and Toolbar Overview `__ +- `Basics - Demos Overview `__ +- `Rigid Bodies - Mass Editing `__ +- `Materials - Friction Restitution and Defaults `__ +- `Overview of Simulation Ready Assets Physics in Omniverse `__ + +Importing assets + +- `Omniverse Create - Importing FBX Files \| NVIDIA Omniverse Tutorials `__ +- `Omniverse Asset Importer `__ +- `Isaac Sim URDF impoter `__ + + +Part 2: Scripting in Omniverse +------------------------------ + +The above links mainly introduced how to use the USD Composer and its +functionalities through UI operations. However, often developers +need to write scripts to perform operations. This is especially true +when you want to automate certain tasks or create custom applications +that use Omniverse as a backend. This section will introduce you to +scripting in Omniverse. + +USD is the main file format Omniverse operates with. So naturally, the +APIs (from OpenUSD) for modifying USD are at the core of Omniverse. +Most of the APIs are in C++ and Python bindings are provided for them. +Thus, to script in Omniverse, you need to understand the USD APIs. + +.. note:: + + While Isaac Sim and Isaac Lab try to "relieve" users from understanding + the core USD concepts and APIs, understanding these basics still + help a lot once you start diving inside the codebase and modifying + it for your own application. + +Before diving into USD scripting, it is good to get acquainted with the +terminologies used in USD. We recommend the following `introduction to +USD basics `__ by +Houdini, which is a 3D animation software. +Make sure to go through the following sections: + +- `Quick example `__ +- `Attributes and primvars `__ +- `Composition `__ +- `Schemas `__ +- `Instances `__ + and `Scene-graph Instancing `__ + +As a test of understanding, make sure you can answer the following: + +- What are prims? What is meant by a prim path in a stage? +- How are attributes related to prims? +- How are schemas related to prims? +- What is the difference between attributes and schemas? +- What is asset instancing? + +Part 3: More Resources +---------------------- + +- `Omniverse Glossary of Terms `__ +- `Omniverse Code Samples `__ +- `PhysX Limitations `__ +- `PhysX Documentation `__. diff --git a/simulation/modules/IsaacLab/docs/source/how-to/multi_asset_spawning.rst b/simulation/modules/IsaacLab/docs/source/how-to/multi_asset_spawning.rst new file mode 100644 index 0000000000000000000000000000000000000000..a93fd5a3274b79ff6622e2a502eb9f809ee95f9d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/multi_asset_spawning.rst @@ -0,0 +1,131 @@ + +Spawning Multiple Assets +======================== + +.. currentmodule:: isaaclab + +Typical spawning configurations (introduced in the :ref:`tutorial-spawn-prims` tutorial) copy the same +asset (or USD primitive) across the different resolved prim paths from the expressions. +For instance, if the user specifies to spawn the asset at "/World/Table\_.*/Object", the same +asset is created at the paths "/World/Table_0/Object", "/World/Table_1/Object" and so on. + +However, we also support multi-asset spawning with two mechanisms: + +1. Rigid object collections. This allows the user to spawn multiple rigid objects in each environment and access/modify + them with a unified API, improving performance. + +2. Spawning different assets under the same prim path. This allows the user to create diverse simulations, where each + environment has a different asset. + +This guide describes how to use these two mechanisms. + +The sample script ``multi_asset.py`` is used as a reference, located in the +``IsaacLab/scripts/demos`` directory. + +.. dropdown:: Code for multi_asset.py + :icon: code + + .. literalinclude:: ../../../scripts/demos/multi_asset.py + :language: python + :emphasize-lines: 109-131, 135-179, 184-203 + :linenos: + +This script creates multiple environments, where each environment has: + +* a rigid object collection containing a cone, a cube, and a sphere +* a rigid object that is either a cone, a cube, or a sphere, chosen at random +* an articulation that is either the ANYmal-C or ANYmal-D robot, chosen at random + +.. image:: ../_static/demos/multi_asset.jpg + :width: 100% + :alt: result of multi_asset.py + + +Rigid Object Collections +------------------------ + +Multiple rigid objects can be spawned in each environment and accessed/modified with a unified ``(env_ids, obj_ids)`` API. +While the user could also create multiple rigid objects by spawning them individually, the API is more user-friendly and +more efficient since it uses a single physics view under the hood to handle all the objects. + +.. literalinclude:: ../../../scripts/demos/multi_asset.py + :language: python + :lines: 135-179 + :dedent: + +The configuration :class:`~assets.RigidObjectCollectionCfg` is used to create the collection. It's attribute :attr:`~assets.RigidObjectCollectionCfg.rigid_objects` +is a dictionary containing :class:`~assets.RigidObjectCfg` objects. The keys serve as unique identifiers for each +rigid object in the collection. + + +Spawning different assets under the same prim path +-------------------------------------------------- + +It is possible to spawn different assets and USDs under the same prim path in each environment using the spawners +:class:`~sim.spawners.wrappers.MultiAssetSpawnerCfg` and :class:`~sim.spawners.wrappers.MultiUsdFileCfg`: + +* We set the spawn configuration in :class:`~assets.RigidObjectCfg` to be + :class:`~sim.spawners.wrappers.MultiAssetSpawnerCfg`: + + .. literalinclude:: ../../../scripts/demos/multi_asset.py + :language: python + :lines: 107-133 + :dedent: + + This function allows you to define a list of different assets that can be spawned as rigid objects. + When :attr:`~sim.spawners.wrappers.MultiAssetSpawnerCfg.random_choice` is set to True, one asset from the list + is randomly selected and spawned at the specified prim path. + +* Similarly, we set the spawn configuration in :class:`~assets.ArticulationCfg` to be + :class:`~sim.spawners.wrappers.MultiUsdFileCfg`: + + .. literalinclude:: ../../../scripts/demos/multi_asset.py + :language: python + :lines: 182-215 + :dedent: + + Similar to before, this configuration allows the selection of different USD files representing articulated assets. + + +Things to Note +~~~~~~~~~~~~~~ + +Similar asset structuring +~~~~~~~~~~~~~~~~~~~~~~~~~ + +While spawning and handling multiple assets using the same physics interface (the rigid object or articulation classes), +it is essential to have the assets at all the prim locations follow a similar structure. In case of an articulation, +this means that they all must have the same number of links and joints, the same number of collision bodies and +the same names for them. If that is not the case, the physics parsing of the prims can get affected and fail. + +The main purpose of this functionality is to enable the user to create randomized versions of the same asset, +for example robots with different link lengths, or rigid objects with different collider shapes. + +Disabling physics replication in interactive scene +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +By default, the flag :attr:`scene.InteractiveScene.replicate_physics` is set to True. This flag informs the physics +engine that the simulation environments are copies of one another so it just needs to parse the first environment +to understand the entire simulation scene. This helps speed up the simulation scene parsing. + +However, in the case of spawning different assets in different environments, this assumption does not hold +anymore. Hence the flag :attr:`scene.InteractiveScene.replicate_physics` must be disabled. +For a full guide on the template-based cloning system including strategies and collision filtering, +see :doc:`cloning`. + +.. literalinclude:: ../../../scripts/demos/multi_asset.py + :language: python + :lines: 280-283 + :dedent: + +The Code Execution +------------------ + +To execute the script with multiple environments and randomized assets, use the following command: + +.. code-block:: bash + + python scripts/demos/multi_asset.py --num_envs 2048 + +This command runs the simulation with 2048 environments, each with randomly selected assets. +To stop the simulation, you can close the window, or press ``Ctrl+C`` in the terminal. diff --git a/simulation/modules/IsaacLab/docs/source/how-to/optimize_stage_creation.rst b/simulation/modules/IsaacLab/docs/source/how-to/optimize_stage_creation.rst new file mode 100644 index 0000000000000000000000000000000000000000..8b8bf45e111dd1cd7c7f67adc317b97cfe7c4ca9 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/optimize_stage_creation.rst @@ -0,0 +1,142 @@ +Optimize Stage Creation +======================= + +Isaac Lab supports two experimental features to speed-up stage creation: **fabric cloning** and **stage in memory**. +These features are particularly effective for large-scale RL setups with thousands of environments. + +What These Features Do +----------------------- + +**Fabric Cloning** + +- Clones environments using Fabric library (see `USD Fabric USDRT Documentation `_) +- Partially supported and enabled by default on some environments (see `Limitations`_ section for a list) + +**Stage in Memory** + +- Constructs the stage in memory, rather than with a USD file, avoiding overhead from disk I/O +- After stage creation, if rendering is required, the stage is attached to the USD context, returning to the default stage configuration +- Not enabled by default + +Usage Examples +-------------- + +Fabric cloning can be toggled by setting the :attr:`isaaclab.scene.InteractiveSceneCfg.clone_in_fabric` flag. +For a full guide on the template-based cloning system, see :doc:`cloning`. + +**Using Fabric Cloning with a RL environment** + +.. code-block:: python + + # create environment configuration + env_cfg = CartpoleEnvCfg() + env_cfg.scene.clone_in_fabric = True + # setup RL environment + env = ManagerBasedRLEnv(cfg=env_cfg) + + +Stage in memory can be toggled by setting the :attr:`isaaclab.sim.SimulationCfg.create_stage_in_memory` flag. + +**Using Stage in Memory with a RL environment** + +.. code-block:: python + + # create config and set flag + cfg = CartpoleEnvCfg() + cfg.scene.num_envs = 1024 + cfg.sim.create_stage_in_memory = True + # create env with stage in memory + env = ManagerBasedRLEnv(cfg=cfg) + +When using stage in memory without an existing RL environment class, wrap the stage creation steps +in a ``with`` statement to set the stage context. The stage is automatically attached +to the USD context when ``SimulationContext`` is created with ``create_stage_in_memory=True``. + +**Using Stage in Memory with a manual scene setup** + +.. code-block:: python + + # init simulation context with stage in memory + # Note: stage is automatically attached to USD context + sim = SimulationContext(cfg=SimulationCfg(create_stage_in_memory=True)) + + # grab stage and set stage context + with stage_utils.use_stage(sim.stage): + # create cartpole scene + scene_cfg = CartpoleSceneCfg(num_envs=1024) + scene = InteractiveScene(scene_cfg) + + sim.play() + + +Limitations +----------- + +**Fabric Cloning** + +- Fabric-cloned environments must be accessed using USDRT functions, rather than USD functions. +- Fabric cloning is partially supported and enabled by default on some environments, listed here. + +.. code-block:: none + + 1. Isaac-Ant-Direct-v0 + 2. Isaac-Ant-v0 + 3. Isaac-Cartpole-Direct-v0 + 4. Isaac-Cartpole-Showcase-Box-Box-Direct-v0 + 5. Isaac-Cartpole-Showcase-Box-Discrete-Direct-v0 + 6. Isaac-Cartpole-Showcase-Box-MultiDiscrete-Direct-v0 + 7. Isaac-Cartpole-Showcase-Dict-Box-Direct-v0 + 8. Isaac-Cartpole-Showcase-Dict-Discrete-Direct-v0 + 9. Isaac-Cartpole-Showcase-Dict-MultiDiscrete-Direct-v0 + 10. Isaac-Cartpole-Showcase-Discrete-Box-Direct-v0 + 11. Isaac-Cartpole-Showcase-Discrete-Discrete-Direct-v0 + 12. Isaac-Cartpole-Showcase-Discrete-MultiDiscrete-Direct-v0 + 13. Isaac-Cartpole-Showcase-MultiDiscrete-Box-Direct-v0 + 14. Isaac-Cartpole-Showcase-MultiDiscrete-Discrete-Direct-v0 + 15. Isaac-Cartpole-Showcase-MultiDiscrete-MultiDiscrete-Direct-v0 + 16. Isaac-Cartpole-Showcase-Tuple-Box-Direct-v0 + 17. Isaac-Cartpole-Showcase-Tuple-Discrete-Direct-v0 + 18. Isaac-Cartpole-Showcase-Tuple-MultiDiscrete-Direct-v0 + 19. Isaac-Cartpole-v0 + 20. Isaac-Factory-GearMesh-Direct-v0 + 21. Isaac-Factory-NutThread-Direct-v0 + 22. Isaac-Factory-PegInsert-Direct-v0 + 23. Isaac-Franka-Cabinet-Direct-v0 + 24. Isaac-Humanoid-Direct-v0 + 25. Isaac-Humanoid-v0 + 26. Isaac-Quadcopter-Direct-v0 + 27. Isaac-Repose-Cube-Allegro-Direct-v0 + 28. Isaac-Repose-Cube-Allegro-NoVelObs-v0 + 29. Isaac-Repose-Cube-Allegro-v0 + 30. Isaac-Repose-Cube-Shadow-Direct-v0 + 31. Isaac-Repose-Cube-Shadow-OpenAI-FF-Direct-v0 + 32. Isaac-Repose-Cube-Shadow-OpenAI-LSTM-Direct-v0 + +**Stage in Memory** + +- Cannot be currently enabled at the same time as **Fabric Cloning**. + +- The stage is automatically attached to the USD context at ``SimulationContext`` creation, ensuring proper + lifecycle events for viewport and physics systems. + +- Certain low-level Kit APIs do not yet support stage in memory. + + - In one particular case, for some environments, the API call to color the ground plane is skipped, when stage in memory is enabled. + + +Benchmark Results +----------------- + +Performance comparison cloning 4000 ShadowHand robots with rendering enabled + ++--------+-----------------+-------------------+------------------------+---------------------------+------------------------+------------------------+ +| Test # | Stage in Memory | Clone in Fabric | Attach Stage Time (s) | Fabric Attach Time (s) | Clone Paths Time (s) | First Step Time (s) | ++========+=================+===================+========================+===========================+========================+========================+ +| 1 | Yes | Yes | 3.88 | 0.15 | 4.84 | 1.39 | ++--------+-----------------+-------------------+------------------------+---------------------------+------------------------+------------------------+ +| 2 | No | No | — | 60.17 | 4.46 | 3.52 | ++--------+-----------------+-------------------+------------------------+---------------------------+------------------------+------------------------+ +| 3 | No | Yes | — | 0.47 | 4.72 | 2.56 | ++--------+-----------------+-------------------+------------------------+---------------------------+------------------------+------------------------+ +| 4 | Yes | No | 42.64 | 21.75 | 1.87 | 2.16 | ++--------+-----------------+-------------------+------------------------+---------------------------+------------------------+------------------------+ diff --git a/simulation/modules/IsaacLab/docs/source/how-to/profile_with_nsys.rst b/simulation/modules/IsaacLab/docs/source/how-to/profile_with_nsys.rst new file mode 100644 index 0000000000000000000000000000000000000000..ec286cbf2b46b87a3c648832e3f53241f84e8d7b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/profile_with_nsys.rst @@ -0,0 +1,113 @@ +Profiling Isaac Lab with Nsight Systems +======================================= + +.. currentmodule:: isaaclab + +Isaac Lab supports CPU and GPU profiling via **NVIDIA Nsight Systems (nsys)** for runtime performance analysis. This can help identify GPU/CPU bottlenecks and determine the best configuration for your environments and tasks. Profiling adds modest runtime overhead and produces large output files, so it's best suited to targeted investigations rather than long unattended training runs. + +Common Use Cases +---------------- + +- **My training iteration is slow** - capture 3-5 iterations to see whether time is mostly spent on physics, rendering, env reset, observation, etc. +- **Env init takes 40 seconds** - profile a single launch to see the import times for each module, kernel compilation, etc. +- **Which physics/renderer backend should I use?** - profile your task with different backend combinations to find the best fit. +- **Are my GPU kernels efficient?** - dive into the CUDA rows in nsys to identify when the GPU is idle (optimization opportunity). +- **Did my code changes make things slower?** - A/B profile comparison before and after your change. + + +Quick Start +----------- + +This section walks you through everything needed to capture your first nsys profile. + +Prerequisites +~~~~~~~~~~~~~ + +- `Nsight Systems `_ - install for your platform. +- ``nvtx`` Python package for source code instrumentation, installed into your Isaac Lab environment: + + .. code-block:: bash + + python -m pip install nvtx + + +Running a Profile +~~~~~~~~~~~~~~~~~ + +The following command shows how to capture a profile for the ``Isaac-Cartpole-v0`` task via the ``rsl_rl`` training framework with 3 iterations: + +.. code-block:: bash + + nsys profile \ + -t nvtx,cuda \ + --python-functions-trace=scripts/benchmarks/nsys_trace.json \ + -o my_profile \ + ./isaaclab.sh train --rl_library rsl_rl \ + --task=Isaac-Cartpole-v0 \ + --max_iterations=3 + +Flags: + +- ``-t nvtx,cuda`` - capture NVTX ranges (CPU swim-lanes) and CUDA activity (GPU row). +- ``--python-functions-trace=...`` - the function annotations file; ships with Isaac Lab. +- ``-o my_profile`` - output path; nsys appends ``.nsys-rep``. + +Reading the Resulting Profile +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Launch the Nsight Systems UI, go to **File > Open**, and select your ``.nsys-rep`` file that you generated in the previous step. Expand the **Threads** section and the domain swim-lanes will appear as separate rows. Clicking on a function will highlight related functions in other lanes. Expand the **CUDA HW** row to cross-reference with GPU kernels fired during that CPU range. + +.. image:: ../_static/how-to/howto_profile_nsys_example.png + :alt: Domain swim-lanes in nsys-ui + + +The Trace JSON +-------------- + +The trace definition file lives at ``scripts/benchmarks/nsys_trace.json`` and defines metadata for the Python functions of interest in Isaac Lab. nsys monkey-patches these functions to automatically emit NVTX ranges at runtime. + +Schema: + +.. code-block:: json + + [ + { + "domain": "MyDomain", + "color": "0x9C27B0", + "module": "isaaclab.envs.manager_based_env", + "functions": [ + "ManagerBasedEnv.step", + {"function": "ManagerBasedEnv.reset", "color": "0xAB47BC"} + ] + } + ] + + +After editing the JSON, run the sync test to confirm every entry resolves: + +.. code-block:: bash + + python -m pytest scripts/benchmarks/test/test_nsys_trace.py + + +Troubleshooting +--------------- + +- **An expected domain doesn't appear in the timeline:** + + - Confirm ``nvtx`` is installed in your Isaac Lab environment (``python -m pip show nvtx``). + - Make sure the function is actually called during the profiled run. + - Verify the JSON entry by running the sync test (above). + +- **Sync test fails with an** ``AttributeError`` - a function listed in the JSON no longer exists at the given path. + + - Fix the path to point at the renamed function, or + - Remove the entry if the function was deleted. + + +See Also +-------- + +- :doc:`simulation_performance` - broader simulation performance tuning tips. +- `Nsight Systems User Guide `_ - official ``nsys`` documentation. +- `NVTX Python package `_ - the package nsys uses to emit NVTX ranges from Python. diff --git a/simulation/modules/IsaacLab/docs/source/how-to/proxy_array.rst b/simulation/modules/IsaacLab/docs/source/how-to/proxy_array.rst new file mode 100644 index 0000000000000000000000000000000000000000..7bf0a90374f371f3789711950077e9fb2ed1b1a8 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/proxy_array.rst @@ -0,0 +1,134 @@ +.. _how-to-torch-array: + +Working with ProxyArray +======================= + +.. currentmodule:: isaaclab.utils.warp + +Isaac Lab data classes return :class:`ProxyArray` — a lightweight, warp-first wrapper that +provides zero-copy access to simulation data as either a :class:`warp.array` or a +:class:`torch.Tensor`. + +.. note:: + + ``ProxyArray`` is inspired by the ``ProxyArray`` class from + `mujocolab/mjlab `_ (BSD-3-Clause). + The design adapts the same dual-accessor pattern to Isaac Lab's warp-based data pipeline. + + +Quick Start +~~~~~~~~~~~ + +Every property on asset and sensor data classes (e.g., ``robot.data.joint_pos``, +``sensor.data.net_forces_w``) returns a ``ProxyArray``: + +.. code-block:: python + + robot = env.scene["robot"] + + # Explicit torch access (preferred) + joint_positions = robot.data.joint_pos.torch # torch.Tensor, cached zero-copy view + gravity_proj = robot.data.projected_gravity_b.torch # torch.Tensor + + # Explicit warp access (for kernel interop) + wp_array = robot.data.joint_pos.warp # warp.array, the original buffer + + # Pass directly to warp kernels — no unwrapping needed + wp.launch(my_kernel, inputs=[robot.data.joint_pos], ...) # works via __cuda_array_interface__ + + +The ``.torch`` and ``.warp`` Accessors +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- ``.torch`` returns a cached, zero-copy :class:`torch.Tensor` view of the underlying warp array + (via :func:`warp.to_torch`). The tensor is created on first access and reused on subsequent + calls. Since it is a zero-copy view, writes to the tensor are visible through the warp array + and vice versa. + +- ``.warp`` returns the original :class:`warp.array`. Use this when you need to pass data to + warp kernels explicitly or access warp-specific attributes (``ptr``, ``strides``, etc.). + + +Deprecation Bridge +~~~~~~~~~~~~~~~~~~ + +To ease migration, ``ProxyArray`` includes a deprecation bridge that allows existing code to +treat it as a ``torch.Tensor`` temporarily: + +.. code-block:: python + + # These still work but emit a one-time DeprecationWarning: + result = torch.sum(robot.data.joint_pos) # via __torch_function__ + value = robot.data.joint_pos[0, 3] # via __getitem__ + result = robot.data.joint_pos + 1.0 # via __add__ + legacy = wp.to_torch(robot.data.joint_pos) # temporary shim + + # Preferred (no warning): + result = torch.sum(robot.data.joint_pos.torch) + value = robot.data.joint_pos.torch[0, 3] + result = robot.data.joint_pos.torch + 1.0 + tensor = robot.data.joint_pos.torch + +The ``wp.to_torch()`` compatibility path is a temporary shim for code that was migrated +before ``ProxyArray`` exposed explicit accessors. It returns the same zero-copy tensor as +``.torch`` and emits a one-time ``DeprecationWarning``. The shim and the other deprecation +bridges will be removed in a future release. Migrate to explicit ``.torch`` access now. + + +Migrating from Isaac Lab 2.x +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In Isaac Lab 2.x, data properties returned ``torch.Tensor`` directly. In 3.0, they return +``ProxyArray``. Append ``.torch`` to get the tensor: + +.. code-block:: python + + # BEFORE (Isaac Lab 2.x) — properties returned torch.Tensor directly + joint_pos = robot.data.joint_pos + first_contact = sensor.compute_first_contact(dt) + + # AFTER (Isaac Lab 3.0) — properties return ProxyArray + joint_pos = robot.data.joint_pos.torch + first_contact = sensor.compute_first_contact(dt).torch + +.. note:: + + Passing a ``ProxyArray`` to ``wp.to_torch()`` is temporarily supported by a compatibility + shim and returns the same cached zero-copy tensor as ``.torch``. This path emits a + one-time ``DeprecationWarning`` and will be removed in a future release. Use ``.torch`` + in new code. + + +Backend Differences +~~~~~~~~~~~~~~~~~~~ + +While the ``ProxyArray`` interface is identical across backends, the underlying data refresh +model differs: + +**PhysX (pull-to-refresh):** + Properties pull fresh data from the PhysX tensor API on first access per simulation step, + then cache the result. The underlying GPU buffers are stable and pre-allocated — the + ``ProxyArray`` wrapper is created once and reused safely across steps. + +**Newton (auto-refresh with wrapper replacement):** + The simulation automatically refreshes GPU buffers each step. On full simulation resets, + buffers may be re-created. The Newton backend creates new ``ProxyArray`` wrappers for the + new warp arrays, invalidating any previously cached torch tensors. + +In both cases, ``.torch`` always returns a view of the current simulation state for the +current step. + +.. warning:: + + Do not cache ``.torch`` results across simulation resets. After a reset (especially on + Newton), previously obtained tensors may point to stale or freed GPU memory. Always + re-access the property after a reset. + + +API Reference +~~~~~~~~~~~~~ + +.. autoclass:: ProxyArray + :members: + :undoc-members: + :no-index: diff --git a/simulation/modules/IsaacLab/docs/source/how-to/record_animation.rst b/simulation/modules/IsaacLab/docs/source/how-to/record_animation.rst new file mode 100644 index 0000000000000000000000000000000000000000..008415614ce389f0b9172d7f24a95185cec2a56d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/record_animation.rst @@ -0,0 +1,137 @@ +Recording Animations of Simulations +=================================== + +.. currentmodule:: isaaclab + +Isaac Lab supports two approaches for recording animations of physics simulations: the **Stage Recorder** and the **OVD Recorder**. +Both generate USD outputs that can be played back in Omniverse, but they differ in how they work and when you’d use them. + +The `Stage Recorder`_ extension listens to all motion and USD property changes in the stage during simulation +and records them as **time-sampled data**. The result is a USD file that captures only the animated changes—**not** the +full scene—and matches the hierarchy of the original stage at the time of recording. +This makes it easy to add as a sublayer for playback or rendering. + +This method is built into Isaac Lab’s UI through the :class:`~isaaclab.envs.ui.BaseEnvWindow`. +However, to record the animation of a simulation, you need to disable `Fabric`_ to allow reading and writing +all the changes (such as motion and USD properties) to the USD stage. + +The **OVD Recorder** is designed for more scalable or automated workflows. It uses OmniPVD to capture simulated physics from a played stage +and then **bakes** that directly into an animated USD file. It works with Fabric enabled and runs with CLI arguments. +The animated USD can be quickly replayed and reviewed by scrubbing through the timeline window, without simulating expensive physics operations. + +.. note:: + + Omniverse only supports **either** physics simulation **or** animation playback on a USD prim—never both at once. + Disable physics on the prims you want to animate. + + +Stage Recorder +-------------- + +In Isaac Lab, the Stage Recorder is integrated into the :class:`~isaaclab.envs.ui.BaseEnvWindow` class. +It’s the easiest way to capture physics simulations visually and works directly through the UI. + +To record, Fabric must be disabled—this allows the recorder to track changes to USD and write them out. + +Stage Recorder Settings +~~~~~~~~~~~~~~~~~~~~~~~ + +Isaac Lab sets up the Stage Recorder with sensible defaults in ``base_env_window.py``. If needed, +you can override or inspect these by using the Stage Recorder extension directly in Omniverse Create. + +.. dropdown:: Settings used in base_env_window.py + :icon: code + + .. literalinclude:: ../../../source/isaaclab/isaaclab/envs/ui/base_env_window.py + :language: python + :linenos: + :pyobject: BaseEnvWindow._toggle_recording_animation_fn + +Example Usage +~~~~~~~~~~~~~ + +In standalone Isaac Lab environments, pass the ``--disable_fabric`` flag: + +.. code-block:: bash + + python scripts/environments/state_machine/lift_cube_sm.py --num_envs 8 --device cpu --disable_fabric --viz kit + +After launching, the Isaac Lab UI window will display a "Record Animation" button. +Click to begin recording. Click again to stop. + +The following files are saved to the ``recordings/`` folder: + +- ``Stage.usd`` — the original stage with physics disabled +- ``TimeSample_tk001.usd`` — the animation (time-sampled) layer + +To play back, open Isaac Sim: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + ./isaaclab.sh -s + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + isaaclab.bat -s + +Inside the Layers panel, insert both ``Stage.usd`` and ``TimeSample_tk001.usd`` as sublayers. +The animation will now play back when you hit the play button. + +See the `tutorial on layering in Omniverse`_ for more on working with layers. + + +OVD Recorder +------------ + +The OVD Recorder uses OmniPVD to record simulation data and bake it directly into a new USD stage. +This method is more scalable and better suited for large-scale training scenarios (e.g. multi-env RL). + +It’s not UI-controlled—the whole process is enabled through CLI flags and runs automatically. + + +Workflow Summary +~~~~~~~~~~~~~~~~ + +1. User runs Isaac Lab with animation recording enabled via CLI +2. Isaac Lab starts simulation +3. OVD data is recorded as the simulation runs +4. At the specified stop time, the simulation is baked into an outputted USD file, and IsaacLab is closed +5. The final result is a fully baked, self-contained USD animation + +Example Usage +~~~~~~~~~~~~~ + +To record an animation: + +.. code-block:: bash + + python scripts/tutorials/03_envs/run_cartpole_rl_env.py --anim_recording_enabled --anim_recording_start_time 1 --anim_recording_stop_time 3 + +.. note:: + + The provided ``--anim_recording_stop_time`` should be greater than the simulation time. + +.. warning:: + + Currently, the final recording step can output many warning logs from [omni.usd]. This is a known issue, and these warning messages can be ignored. + +After the stop time is reached, a file will be saved to: + +.. code-block:: none + + anim_recordings//baked_animation_recording.usda + + +.. _Stage Recorder: https://docs.omniverse.nvidia.com/extensions/latest/ext_animation_stage-recorder.html +.. _Fabric: https://docs.omniverse.nvidia.com/kit/docs/usdrt.scenegraph/latest/usd_fabric_usdrt.html +.. _Omniverse Launcher: https://docs.omniverse.nvidia.com/launcher/latest/index.html +.. _tutorial on layering in Omniverse: https://www.youtube.com/watch?v=LTwmNkSDh-c&ab_channel=NVIDIAOmniverse diff --git a/simulation/modules/IsaacLab/docs/source/how-to/record_video.rst b/simulation/modules/IsaacLab/docs/source/how-to/record_video.rst new file mode 100644 index 0000000000000000000000000000000000000000..5633bf88f713fcbde3cfcc4dfb50b9e38393abf1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/record_video.rst @@ -0,0 +1,169 @@ +Recording video clips during training +===================================== + +Isaac Lab supports recording video clips during training using the +`gymnasium.wrappers.RecordVideo `_ class. +When the ``--video`` flag is enabled, Isaac Lab captures a perspective view of the scene. If a Kit or +Newton visualizer is active, that visualizer selects the video backend by default. Otherwise, the +backend is chosen automatically from the active physics and renderer stack: an Isaac Sim Kit camera or +a Newton GL headless viewer. + +This feature can be enabled by installing ``ffmpeg`` and using the following command line arguments with the training +script: + +* ``--video``: enables video recording during training +* ``--video_length``: length of each recorded video (in steps) +* ``--video_interval``: interval between each video recording (in steps) + +Note that enabling recording is equivalent to enabling rendering during training, which will slow down both startup and runtime performance. + +Example usage: + +.. code-block:: shell + + ./isaaclab.sh train --rl_library rl_games --task=Isaac-Cartpole-v0 --video --video_length 100 --video_interval 500 + + +The recorded videos will be saved in the same directory as the training checkpoints, under +``IsaacLab/logs////videos/train``. + + +Overview +-------- + +The video recording feature is implemented using the ``VideoRecorder`` class. This class is responsible for resolving the video backend from the scene, capturing the video frames, and saving them to a file. + +* ``VideoRecorderCfg`` (``isaaclab.envs.utils.video_recorder_cfg``) holds resolution, backend source, + and world-space perspective parameters ``eye`` and ``lookat`` (defaults to a diagonal view of the + scene). +* ``VideoRecorder`` (``isaaclab.envs.utils.video_recorder``) picks a video backend from the scene + (Kit vs Newton GL), builds the matching low-level capture object, and returns RGB frames via + ``render_rgb_array()``. +* Direct RL, Direct MARL and manager-based RL environments copy the task's + :class:`~isaaclab.envs.common.ViewerCfg` ``eye`` and ``lookat`` into those fields before the + recorder is constructed, so training clips align with the task's intended viewport when + ``origin_type`` is ``"world"``. + + +Configuration: ``VideoRecorderCfg`` +------------------------------------ + +The dataclass lives in ``isaaclab.envs.utils.video_recorder_cfg``. Fields ``eye`` and ``lookat`` are +the perspective camera position and target in meters. + +.. literalinclude:: ../../../source/isaaclab/isaaclab/envs/utils/video_recorder_cfg.py + :language: python + :lines: 20-58 + + +Task framing: ``ViewerCfg`` +---------------------------- + +Tasks define the interactive viewer with :class:`~isaaclab.envs.common.ViewerCfg`. The ``eye`` and +``lookat`` tuples are the same values the RL base classes copy into ``VideoRecorderCfg`` (see below). +If your task uses ``origin_type="world"``, those tuples are world-space positions and match what the +perspective recorder expects. + +.. literalinclude:: ../../../source/isaaclab/isaaclab/envs/common.py + :language: python + :lines: 20-28 + + +Backend selection: Kit vs Newton GL +------------------------------------- + +``VideoRecorder`` resolves the implementation from the live :class:`~isaaclab.scene.InteractiveScene`. +With the default ``VideoRecorderCfg.backend_source = "visualizer"``, an active ``--visualizer kit`` +selects the Kit path (``omni.replicator`` on ``/OmniverseKit_Persp``), and an active +``--visualizer newton`` selects the Newton GL path. If both visualizers are active, Kit takes +precedence and only one ``--video`` stream is recorded. Rerun records ``.rrd`` replay data through +the Rerun visualizer rather than producing ``--video`` clips, and Viser does not currently provide a +``--video`` recording backend. + +Set ``VideoRecorderCfg.backend_source = "renderer"`` to ignore active visualizers and choose from the +physics/renderer stack instead. In that mode, PhysX physics (``physics=physx``) or Isaac RTX +(``renderer=isaacsim_rtx_renderer``) selects the Kit path. Newton physics (``physics=newton_mjwarp``) or +the Newton Warp renderer (``renderer=newton_renderer``) selects the Newton GL path when no Kit +signal is present. OVRTX (``renderer=ovrtx_renderer`` from ``isaaclab_ov``) can pair with IsaacSim +or Newton physics; in that case the video backend is selected via the physics preset. If both Kit and +Newton GL signals are present, the Kit path is chosen. + +.. literalinclude:: ../../../source/isaaclab/isaaclab/envs/utils/video_recorder.py + :language: python + :lines: 38-59 + + +Construction and dispatch +-------------------------- + +When ``env_render_mode`` is ``"rgb_array"`` (as when wrappers or scripts request RGB frames for +video), the recorder instantiates the backend-specific helper and passes through ``eye``, ``lookat``, +and window size. + +.. literalinclude:: ../../../source/isaaclab/isaaclab/envs/utils/video_recorder.py + :language: python + :lines: 70-114 + + +Customising the camera view +---------------------------- + +When ``--video`` is passed, the recording camera uses the same configured +position and look-at target as the active Kit or Newton visualizer when that visualizer drives backend +selection. Otherwise, the defaults come from +:class:`~isaaclab.envs.common.ViewerCfg`: + +* ``eye = (7.5, 7.5, 7.5)`` — camera position in world space (metres) +* ``lookat = (0.0, 0.0, 0.0)`` — camera look-at target in world space (metres) +* Resolution ``1280x720`` + +To change the recording angle without a visualizer, override the ``viewer`` field in your task's +environment config. The RL base classes automatically copy ``eye`` and ``lookat`` into +``VideoRecorderCfg`` before recording starts (when ``origin_type`` is ``"world"``), so the video clip +uses the same configured viewpoint as the interactive viewport: + +.. code-block:: python + + from isaaclab.envs import ManagerBasedRLEnvCfg + from isaaclab.envs.common import ViewerCfg + from isaaclab.utils.configclass import configclass + + @configclass + class MyTaskCfg(ManagerBasedRLEnvCfg): + viewer: ViewerCfg = ViewerCfg( + eye=(5.0, 5.0, 5.0), + lookat=(0.0, 0.0, 1.0), + ) + + +Summary +------- + +.. list-table:: + :widths: 40 22 38 + :header-rows: 1 + + * - Stack example (``physics=`` / ``renderer=``) + - Video backend + - Capture mechanism + * - ``physics=physx`` or ``renderer=isaacsim_rtx_renderer`` + - Kit (``"kit"``) + - ``/OmniverseKit_Persp`` + Replicator RGB + * - ``physics=newton_mjwarp`` or ``renderer=newton_renderer`` (no Kit signals) + - Newton GL (``"newton_gl"``) + - ``newton.viewer.ViewerGL`` on the SDP Newton model + * - ``physics=newton_mjwarp`` + ``renderer=ovrtx_renderer`` (OVRTX + Newton physics) + - Newton GL (``"newton_gl"``) + - ``newton.viewer.ViewerGL`` on the SDP Newton model + * - ``--visualizer kit`` with default ``backend_source`` + - Kit (``"kit"``) + - Visualizer ``eye`` / ``lookat`` copied to ``/OmniverseKit_Persp`` + Replicator RGB + * - ``--visualizer newton`` with default ``backend_source`` + - Newton GL (``"newton_gl"``) + - Visualizer ``eye`` / ``lookat`` initially, then live Newton viewer camera sync per frame + + +See also +-------- + +* :doc:`/source/overview/core-concepts/visualization` - interactive visualizers diff --git a/simulation/modules/IsaacLab/docs/source/how-to/robots.rst b/simulation/modules/IsaacLab/docs/source/how-to/robots.rst new file mode 100644 index 0000000000000000000000000000000000000000..39b011156b52849a759b872f49d70d1b5a184e88 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/robots.rst @@ -0,0 +1,67 @@ +.. _isaac-lab-robots: + +Robot Configurations +======================= + +Robots are entirely defined as instances of configurations within Isaac Lab. If you examine ``source/isaaclab_assets/isaaclab_assets/robots``, you will see a number of files, each of which +contains configurations for the robot in question. The purpose of these individual files is to better define scope for all the different robots, but there is nothing preventing +you from :ref:`adding your own ` to your project or even to the ``isaaclab`` repository! For example, consider the following configuration for +the Dofbot + +.. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab.actuators import ImplicitActuatorCfg + from isaaclab.assets.articulation import ArticulationCfg + from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR + + DOFBOT_CONFIG = ArticulationCfg( + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/Dofbot/dofbot.usd", + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=False, + max_depenetration_velocity=5.0, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=True, solver_position_iteration_count=8, solver_velocity_iteration_count=0 + ), + ), + init_state=ArticulationCfg.InitialStateCfg( + joint_pos={ + "joint1": 0.0, + "joint2": 0.0, + "joint3": 0.0, + "joint4": 0.0, + }, + pos=(0.25, -0.25, 0.0), + ), + actuators={ + "front_joints": ImplicitActuatorCfg( + joint_names_expr=["joint[1-2]"], + effort_limit_sim=100.0, + velocity_limit_sim=100.0, + stiffness=10000.0, + damping=100.0, + ), + "joint3_act": ImplicitActuatorCfg( + joint_names_expr=["joint3"], + effort_limit_sim=100.0, + velocity_limit_sim=100.0, + stiffness=10000.0, + damping=100.0, + ), + "joint4_act": ImplicitActuatorCfg( + joint_names_expr=["joint4"], + effort_limit_sim=100.0, + velocity_limit_sim=100.0, + stiffness=10000.0, + damping=100.0, + ), + }, + ) + +This completely defines the dofbot! You could copy this into a ``.py`` file and import it as a module and you would be able to use the dofbot in +your own lab sims. One common feature you will see in any config defining things with state is the presence of an ``InitialStateCfg``. Remember, the configurations +are what informs vectorization, and it's the ``InitialStateCfg`` that describes the state of the joints of our robot when it gets created in each environment. The +``ImplicitActuatorCfg`` defines the joints of the robot using the default actuation model determined by the joint type. Not all joints need to be actuated, but you +will get warnings if you don't. If you aren't planning on using those undefined joints, you can generally ignore these. diff --git a/simulation/modules/IsaacLab/docs/source/how-to/save_camera_output.rst b/simulation/modules/IsaacLab/docs/source/how-to/save_camera_output.rst new file mode 100644 index 0000000000000000000000000000000000000000..c8174bb75eaf85de49f1c0ea7cd8e1fc7594058f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/save_camera_output.rst @@ -0,0 +1,105 @@ +.. _how-to-save-images-and-3d-reprojection: + + +Saving rendered images and 3D re-projection +=========================================== + +.. currentmodule:: isaaclab + +This guide accompanied with the ``run_usd_camera.py`` script in the ``IsaacLab/scripts/tutorials/04_sensors`` +directory. + +.. dropdown:: Code for run_usd_camera.py + :icon: code + + .. literalinclude:: ../../../scripts/tutorials/04_sensors/run_usd_camera.py + :language: python + :emphasize-lines: 174-182, 232-250, 254-267 + :linenos: + + +Saving using Replicator Basic Writer +------------------------------------ + +.. note:: + The BasicWriter is part of the Omniverse Replicator ecosystem and is specific to the default + Isaac RTX renderer backend. Other renderer backends may require different save workflows. + +.. note:: + The ``colorize_*`` arguments below are set on + :attr:`~isaaclab.sensors.camera.CameraCfg.renderer_cfg` (an + :class:`~isaaclab_physx.renderers.IsaacRtxRendererCfg`); the same-named + fields on :class:`~isaaclab.sensors.camera.CameraCfg` are deprecated. + +To save camera outputs, we use the basic write class from Omniverse Replicator. This class allows us to save the +images in a numpy format. For more information on the basic writer, please check the +`documentation `_. + +.. literalinclude:: ../../../scripts/tutorials/04_sensors/run_usd_camera.py + :language: python + :start-at: rep_writer = rep.BasicWriter( + :end-before: # Camera positions, targets, orientations + +While stepping the simulator, the images can be saved to the defined folder. Since the BasicWriter only supports +saving data using NumPy format, we first need to convert the PyTorch sensors to NumPy arrays before packing +them in a dictionary and writing with the BasicWriter. + +.. literalinclude:: ../../../scripts/tutorials/04_sensors/run_usd_camera.py + :language: python + :start-at: # Save images from camera at camera_index + :end-at: rep_writer.write(rep_output) + + +Projection into 3D Space +------------------------ + +We include utilities to project the depth image into 3D Space. The re-projection operations are done using +PyTorch operations which allows faster computation. + +.. code-block:: python + + from isaaclab.utils.math import transform_points, unproject_depth + + # Pointcloud in world frame + points_3d_cam = unproject_depth( + camera.data.output["distance_to_image_plane"], camera.data.intrinsic_matrices + ) + + points_3d_world = transform_points(points_3d_cam, camera.data.pos_w, camera.data.quat_w_ros) + +Alternately, we can use the :meth:`isaaclab.sensors.camera.utils.create_pointcloud_from_depth` function +to create a point cloud from the depth image and transform it to the world frame. + +.. literalinclude:: ../../../scripts/tutorials/04_sensors/run_usd_camera.py + :language: python + :start-at: # Derive pointcloud from camera at camera_index + :end-before: # In the first few steps, things are still being instanced and Camera.data + +The resulting point cloud can be visualized using the :mod:`isaacsim.util.debug_draw` extension from Isaac Sim. +This makes it easy to visualize the point cloud in the 3D space. + +.. literalinclude:: ../../../scripts/tutorials/04_sensors/run_usd_camera.py + :language: python + :start-at: # In the first few steps, things are still being instanced and Camera.data + :end-at: pc_markers.visualize(translations=pointcloud) + + +Executing the script +-------------------- + +To run the accompanying script, execute the following command: + +.. code-block:: bash + + # Usage with saving and drawing + python scripts/tutorials/04_sensors/run_usd_camera.py --save --draw --enable_cameras + + # Usage with saving only in headless mode + python scripts/tutorials/04_sensors/run_usd_camera.py --save --enable_cameras + + +The simulation should start, and you can observe different objects falling down. An output folder will be created +in the ``IsaacLab/scripts/tutorials/04_sensors`` directory, where the images will be saved. Additionally, +you should see the point cloud in the 3D space drawn on the viewport. + +To stop the simulation, close the window, or use ``Ctrl+C`` in the terminal. diff --git a/simulation/modules/IsaacLab/docs/source/how-to/simulation_performance.rst b/simulation/modules/IsaacLab/docs/source/how-to/simulation_performance.rst new file mode 100644 index 0000000000000000000000000000000000000000..2364ab32be50d725321ae539b8bdf600b373d9f7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/simulation_performance.rst @@ -0,0 +1,79 @@ +PhysX Simulation Performance and Tuning +========================================= + +.. note:: + + This guide covers performance tuning for the **PhysX** backend, which is the default when + running Isaac Lab with Isaac Sim. For the **Newton** backend solver parameters (e.g. + ``njmax``, ``nconmax``, ``ls_iterations``), see the + :ref:`migrating-to-isaaclab-3-0` migration guide and the Newton physics documentation. + +The performance of the PhysX simulation can be affected by various factors, including the number +of objects in the scene, the complexity of the physics simulation, and the hardware being used. +Here are some tips to improve performance: + +1. **Disable Unneeded Visualization**: Running the simulation without visualization can significantly improve performance, + especially when rendering is not required. +2. **Avoid Unnecessary Collisions**: If possible, reduce the number of object overlaps to reduce overhead in the simulation. + Excessive contacts and collisions in the simulation can be expensive in the collision phase in the simulation. +3. **Use Simplified Physics**: Consider using simplified physics collision geometries or lowering simulation fidelity + for better performance. This can be done by modifying the assets and adjusting the physics parameters in the simulation configuration. +4. **Use CPU/GPU Simulation**: If your scene consists of just a few articulations or rigid bodies, consider using CPU simulation + for better performance. For larger scenes, using GPU simulation can significantly improve performance. + +Collision Geometries +-------------------- + +Collision geometries are used to define the shape of objects in the simulation for collision detection. Using +simplified collision geometries can improve performance and reduce the complexity of the simulation. + +For example, if you have a complex mesh, you can create a simplified collision geometry that approximates the shape +of the mesh. This can be done in Isaac Sim through the UI by modifying the collision mesh and approximation methods. + +Additionally, we can often remove collision geometries on areas of the robot that are not important for training. +In the Anymal-C robot, we keep the collision geometries for the kneeds and feet, but remove the collision geometries +on other parts of the legs to optimize for performance. + +Simpler collision geometries such as primitive shapes like spheres will also yield better performance than complex meshes. +For example, an SDF mesh collider will be more expensive than a simple sphere. + +Note that cylinder and cone collision geometries have special support for smooth collisions with triangle meshes for +better wheeled simulation behavior. This comes at a cost of performance and may not always be desired. To disable this feature, +we can set the stage settings ``--/physics/collisionApproximateCylinders=true`` and ``--/physics/collisionApproximateCones=true``. + +Another item to watch out for in GPU RL workloads is warnings about GPU compatibility of ``Convex Hull`` approximated mesh collision geometry. +If the input mesh has a high aspect ratio (e.g. a long thin shape), the convex hull approximation may be incompatible with GPU simulation, +triggering a CPU fallback that can significantly impact performance. + +A CPU-fallback warning looks as follows: ``[Warning] [omni.physx.cooking.plugin] ConvexMeshCookingTask: failed to cook GPU-compatible mesh, +collision detection will fall back to CPU. Collisions with particles and deformables will not work with this mesh.``. +Suitable workarounds include switching to a bounding cube approximation, or using a static triangle mesh collider +if the geometry is not part of a dynamic rigid body. + +CPU Governor Settings on Linux +------------------------------ + +CPU governors dictate the operating clock frequency range and scaling of the CPU. This can be a limiting factor for Isaac Sim performance. For maximum performance, the CPU governor should be set to ``performance``. To modify the CPU governor, run the following commands: + +.. code-block:: bash + + sudo apt-get install linux-tools-common + cpupower frequency-info # Check available governors + sudo cpupower frequency-set -g performance # Set governor with root permissions + +.. note:: + + Not all governors are available on all systems. Governors enabling higher clock speed are typically more performance-centric and will yield better performance for Isaac Sim. + +Additional Performance Guides +----------------------------- + +There are many ways to "tune" the performance of the simulation, but the way you choose largely depends on what you are trying to simulate. In general, the first place +you will want to look for performance gains is with the `PhysX engine `_. Next to rendering +and running deep learning models, the PhysX engine is the most computationally costly. Tuning the PhysX sim to limit the scope to only the task of interest is a great place to +start hunting for performance gains. + +We have recently released a new `gripper tuning guide `_ , specific to contact and grasp tuning. Please check it first if you intend to use robot grippers. For additional details, you should also checkout these guides! + +* `Isaac Sim Performance Optimization Handbook `_ +* `Omni Physics Simulation Performance Guide `_ diff --git a/simulation/modules/IsaacLab/docs/source/how-to/visualizer_tiled_camera.rst b/simulation/modules/IsaacLab/docs/source/how-to/visualizer_tiled_camera.rst new file mode 100644 index 0000000000000000000000000000000000000000..0bf2e0993e04717634a880b15f20ce5ff861a665 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/visualizer_tiled_camera.rst @@ -0,0 +1,152 @@ +.. _how-to-visualizer-tiled-camera: + +Using Visualizer Tiled Cameras +============================== + +.. currentmodule:: isaaclab + +For general visualizer documentation, see :doc:`/source/overview/core-concepts/visualization`. + +The visualizer tiled camera view is a live monitoring and debugging tool. It opens a +non-interactive panel in the Kit or Newton visualizer and displays tiled camera views +across all selected environments. They can stream observation camera data or generate cameras +that follow the robots. + +This guide is accompanied by the ``run_tiled_camera_visualizer.py`` script in the +``IsaacLab/scripts/tutorials/07_visualizers`` directory. + +Running this script demonstrates two ways to use tiled cameras: + +- configured tiled cameras pointed at and following moving Anymal-D robots shown in the Kit visualizer +- streaming from existing wrist-mounted robot cameras shown in the Newton visualizer + +Note: Visualizer tiled cameras are currently supported only in the Kit and Newton visualizers. +Either visualizer can be used to run either example. + +.. dropdown:: Code for run_tiled_camera_visualizer.py + :icon: code + + .. literalinclude:: ../../../scripts/tutorials/07_visualizers/run_tiled_camera_visualizer.py + :language: python + :emphasize-lines: 72-78,87-94 + :linenos: + + +Example One: Following Anymal-D Robots +-------------------------------------- + +The Kit Visualizer shows the tiled camera view in a separate tab inside the main +Viewport window. The highlighted tab area in the figures below shows where to +toggle between the interactive viewport and the visualizer tiled camera view. + +.. figure:: ../_static/visualizers/kit_viz_anymal_iteractive_view.jpg + :width: 100% + :alt: Kit visualizer interactive viewport for Anymal-D robots + + Kit visualizer showing the default interactive viewport. + +.. figure:: ../_static/visualizers/kit_viz_anymal_tiled_view.jpg + :width: 100% + :alt: Kit visualizer tiled camera view for Anymal-D robots + + Kit visualizer showing the tiled camera view generated for selected Anymal-D + robots. + +Note, you can also display the main visualizer camera and the tiled camera view side by +side for dual monitoring. + +To run the tutorial with the args for this example, use: + +.. code-block:: bash + + python scripts/tutorials/07_visualizers/run_tiled_camera_visualizer.py --enable_cameras --task Isaac-Velocity-Rough-Anymal-D-v0 --num_envs 256 --viz kit + +Within the script, you’ll find the ``KitVisualizerCfg`` configuration used to +generate this example. You can use this config as a template for your own use +cases. + +In this example, a set of cameras is created to point toward each robot's base +prim and follow its motion. The camera's position, relative to the prim, is set +by the ``tiled_cam_eye`` field of ``KitVisualizerCfg``. For this demo, the +camera is offset by ``(3.0, 3.0, 3.0)`` from each robot base. If you change ``tiled_cam_eye`` +(for example, to ``(0, 0, 5)``), the panel will show a top-down view instead. + +In this example, there are 256 total environments, and we randomly sample 36 to stream to the +tiled camera view. + +Also note that the Kit visualizer tiled camera view requires passing the +``--enable_cameras`` CLI arg. + + +Example Two: Streaming from Robot-Mounted Cameras +------------------------------------------------- + +The Newton visualizer provides a tiled camera view in a lightweight OpenGL window. +Use the highlighted ``Tiled Camera View`` dropdown in the left-hand sidebar to +show or hide the tiled camera panel. + +.. figure:: ../_static/visualizers/newton_viz_galbot_interactive_view.jpg + :width: 100% + :alt: Newton visualizer interactive view for the Galbot cube stacking environment + + Newton visualizer showing the default interactive viewport. + +.. figure:: ../_static/visualizers/newton_viz_galbot_tiled_view.jpg + :width: 100% + :alt: Newton visualizer tiled camera view for Galbot wrist cameras + + Newton visualizer showing the selected Galbot head-camera feeds in the tiled + camera panel. + +In this example, we use the Galbot cube stacking environment, which comes with +built-in wrist-mounted cameras. This setup provides an egocentric view of the +gripper, table, and cubes in each selected environment. + +To launch this example, run: + +.. code-block:: bash + + python scripts/tutorials/07_visualizers/run_tiled_camera_visualizer.py --task Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor-v0 --num_envs 25 --viz newton + +Within the script, the ``NewtonVisualizerCfg`` is configured to stream images from the +existing camera sensor located at +``/World/envs/env_.*/Robot/head_camera_sim_view_frame/head_camera``. This path +points to the head camera, but you can edit the ``tiled_cam_prim_path`` +field of ``NewtonVisualizerCfg`` in the script to show a different existing camera if +needed. + +In this demo, 25 environments are simulated, and 12 camera feeds are shown in the tiled panel by default. + + +Configuration notes +------------------- + +To customize tiled camera behavior, edit the highlighted ``VisualizerCfg`` fields in +``run_tiled_camera_visualizer.py``: + +* For generated cameras, ``tiled_cam_target_prim_path`` chooses the followed prim and + ``tiled_cam_eye`` sets the camera offset from that prim. +* For existing scene cameras, ``tiled_cam_prim_path`` must match an Isaac Lab + :class:`~isaaclab.sensors.Camera` sensor in the selected task. +* ``tiled_cam_num`` controls how many environment tiles are shown. + + +Troubleshooting +--------------- + +* If a generated view fails with a missing prim error, check that + ``tiled_cam_target_prim_path`` resolves in each selected environment. Common template + forms include ``/World/envs/*/...`` and ``/World/envs/env_.*/...``. +* If an existing-camera view reports that no Isaac Lab camera owns the prim, check that + ``tiled_cam_prim_path`` matches a :class:`~isaaclab.sensors.Camera` sensor in the task. +* If ``rerun`` or ``viser`` is selected, use ``--viz kit`` or ``--viz newton`` instead. + The tiled camera panel is currently implemented for Kit and Newton. +* If the view is too expensive, reduce ``tiled_cam_num``, ``--num_envs``, or the camera + resolution. The visualizer caps the tiled panel at 100 tiles. + + +See also +-------- + +* :doc:`/source/overview/core-concepts/visualization` - visualizer configuration and UI controls. +* :doc:`/source/how-to/configure_rendering` - selecting rendering presets and quality modes. diff --git a/simulation/modules/IsaacLab/docs/source/how-to/wrap_rl_env.rst b/simulation/modules/IsaacLab/docs/source/how-to/wrap_rl_env.rst new file mode 100644 index 0000000000000000000000000000000000000000..54433dfe0334080ccea7a6a808230a714b121704 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/wrap_rl_env.rst @@ -0,0 +1,167 @@ +.. _how-to-env-wrappers: + + +Wrapping environments +===================== + +.. currentmodule:: isaaclab + +Environment wrappers are a way to modify the behavior of an environment without modifying the environment itself. +This can be used to apply functions to modify observations or rewards, record videos, enforce time limits, etc. +A detailed description of the API is available in the :class:`gymnasium.Wrapper` class. + +At present, all RL environments inheriting from the :class:`~envs.ManagerBasedRLEnv` or :class:`~envs.DirectRLEnv` classes +are compatible with :class:`gymnasium.Wrapper`, since the base class implements the :class:`gymnasium.Env` interface. +In order to wrap an environment, you need to first initialize the base environment. After that, you can +wrap it with as many wrappers as you want by calling ``env = wrapper(env, *args, **kwargs)`` repeatedly. + +For example, here is how you would wrap an environment to enforce that reset is called before step or render: + +.. code-block:: python + + """Launch Isaac Sim Simulator first.""" + + + from isaaclab.app import AppLauncher + + # launch omniverse app in headless mode + app_launcher = AppLauncher(headless=True) + simulation_app = app_launcher.app + + """Rest everything follows.""" + + import gymnasium as gym + + import isaaclab_tasks # noqa: F401 + from isaaclab_tasks.utils import load_cfg_from_registry + + # create base environment + cfg = load_cfg_from_registry("Isaac-Reach-Franka-v0", "env_cfg_entry_point") + env = gym.make("Isaac-Reach-Franka-v0", cfg=cfg) + # wrap environment to enforce that reset is called before step + env = gym.wrappers.OrderEnforcing(env) + + +Wrapper for recording videos +---------------------------- + +The :class:`gymnasium.wrappers.RecordVideo` wrapper can be used to record videos of the environment. +The wrapper takes a ``video_dir`` argument, which specifies where to save the videos. The videos are saved in +`mp4 `__ format at specified intervals for specified +number of environment steps or episodes. + +To use the wrapper, you need to first install ``ffmpeg``. On Ubuntu, you can install it by running: + +.. code-block:: bash + + sudo apt-get install ffmpeg + +.. attention:: + + By default, when running an environment in headless mode, the Omniverse viewport is disabled. This is done to + improve performance by avoiding unnecessary rendering. + + We notice the following performance in different rendering modes with the ``Isaac-Reach-Franka-v0`` environment + using an RTX 3090 GPU: + + * No GUI execution without off-screen rendering enabled: ~65,000 FPS + * No GUI execution with off-screen enabled: ~57,000 FPS + * GUI execution with full rendering: ~13,000 FPS + + +The viewport camera used for rendering is the default camera in the scene called ``"/OmniverseKit_Persp"``. +The camera's pose and image resolution can be configured through the +:class:`~envs.ViewerCfg` class. + + +.. dropdown:: Default parameters of the ViewerCfg class: + :icon: code + + .. literalinclude:: ../../../source/isaaclab/isaaclab/envs/common.py + :language: python + :pyobject: ViewerCfg + + +After adjusting the parameters, you can record videos by wrapping the environment with the +:class:`gymnasium.wrappers.RecordVideo` wrapper and enabling the off-screen rendering +flag. Additionally, you need to specify the render mode of the environment as ``"rgb_array"``. + +As an example, the following code records a video of the ``Isaac-Reach-Franka-v0`` environment +for 200 steps, and saves it in the ``videos`` folder at a step interval of 1500 steps. + +.. code:: python + + """Launch Isaac Sim Simulator first.""" + + + from isaaclab.app import AppLauncher + + # launch omniverse app in headless mode with off-screen rendering + app_launcher = AppLauncher(headless=True, enable_cameras=True) + simulation_app = app_launcher.app + + """Rest everything follows.""" + + import gymnasium as gym + + # adjust camera resolution and pose + env_cfg.viewer.resolution = (640, 480) + env_cfg.viewer.eye = (1.0, 1.0, 1.0) + env_cfg.viewer.lookat = (0.0, 0.0, 0.0) + # create isaac-env instance + # set render mode to rgb_array to obtain images on render calls + env = gym.make(task_name, cfg=env_cfg, render_mode="rgb_array") + # wrap for video recording + video_kwargs = { + "video_folder": "videos/train", + "step_trigger": lambda step: step % 1500 == 0, + "video_length": 200, + } + env = gym.wrappers.RecordVideo(env, **video_kwargs) + + +Wrapper for learning frameworks +------------------------------- + +Every learning framework has its own API for interacting with environments. For example, the +`Stable-Baselines3`_ library uses the `gym.Env `_ +interface to interact with environments. However, libraries like `RL-Games`_, `RSL-RL`_ or `SKRL`_ +use their own API for interfacing with a learning environments. Since there is no one-size-fits-all +solution, we do not base the :class:`~envs.ManagerBasedRLEnv` and :class:`~envs.DirectRLEnv` classes on any particular learning framework's +environment definition. Instead, we implement wrappers to make it compatible with the learning +framework's environment definition. + +As an example of how to use the RL task environment with Stable-Baselines3: + +.. code:: python + + from isaaclab_rl.sb3 import Sb3VecEnvWrapper + + # create isaac-env instance + env = gym.make(task_name, cfg=env_cfg) + # wrap around environment for stable baselines + env = Sb3VecEnvWrapper(env) + + +.. caution:: + + Wrapping the environment with the respective learning framework's wrapper should happen in the end, + i.e. after all other wrappers have been applied. This is because the learning framework's wrapper + modifies the interpretation of environment's APIs which may no longer be compatible with :class:`gymnasium.Env`. + + +Adding new wrappers +------------------- + +All new wrappers should be added to the :mod:`isaaclab_rl` module. +They should check that the underlying environment is an instance of :class:`isaaclab.envs.ManagerBasedRLEnv` +or :class:`~envs.DirectRLEnv` +before applying the wrapper. This can be done by using the :func:`unwrapped` property. + +We include a set of wrappers in this module that can be used as a reference to implement your own wrappers. +If you implement a new wrapper, please consider contributing it to the framework by opening a pull request. + +.. _Stable-Baselines3: https://stable-baselines3.readthedocs.io/en/master/ +.. _SKRL: https://skrl.readthedocs.io +.. _RL-Games: https://github.com/Denys88/rl_games +.. _RSL-RL: https://github.com/leggedrobotics/rsl_rl diff --git a/simulation/modules/IsaacLab/docs/source/how-to/write_articulation_cfg.rst b/simulation/modules/IsaacLab/docs/source/how-to/write_articulation_cfg.rst new file mode 100644 index 0000000000000000000000000000000000000000..f083de5c840f29b0df9c0191d17c94e12e36b468 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/how-to/write_articulation_cfg.rst @@ -0,0 +1,277 @@ +.. _how-to-write-articulation-config: + + +Writing an Asset Configuration +============================== + +.. currentmodule:: isaaclab + +This guide walks through the process of creating an :class:`~assets.ArticulationCfg`. +The :class:`~assets.ArticulationCfg` is a configuration object that defines the +properties of an :class:`~assets.Articulation` in Isaac Lab. + +.. note:: + + While we only cover the creation of an :class:`~assets.ArticulationCfg` in this guide, + the process is similar for creating any other asset configuration object. + +We will use the Cartpole example to demonstrate how to create an :class:`~assets.ArticulationCfg`. +The Cartpole is a simple robot that consists of a cart with a pole attached to it. The cart +is free to move along a rail, and the pole is free to rotate about the cart. The file for this configuration example is +``source/isaaclab_assets/isaaclab_assets/robots/cartpole.py``. + +.. dropdown:: Code for Cartpole configuration + :icon: code + + .. literalinclude:: ../../../source/isaaclab_assets/isaaclab_assets/robots/cartpole.py + :language: python + :linenos: + + +Defining the spawn configuration +-------------------------------- + +As explained in :ref:`tutorial-spawn-prims` tutorials, the spawn configuration defines +the properties of the assets to be spawned. This spawning may happen procedurally, or +through an existing asset file (e.g. USD or URDF). In this example, we will spawn the +Cartpole from a USD file. + +When spawning an asset from a USD file, we define its :class:`~sim.spawners.from_files.UsdFileCfg`. +This configuration object takes in the following parameters: + +* :class:`~sim.spawners.from_files.UsdFileCfg.usd_path`: The USD file path to spawn from +* :class:`~sim.spawners.from_files.UsdFileCfg.rigid_props`: The properties of the articulation's root +* :class:`~sim.spawners.from_files.UsdFileCfg.articulation_props`: The properties of all the articulation's links + +The last two parameters are optional. If not specified, they are kept at their default values in the USD file. + +.. literalinclude:: ../../../source/isaaclab_assets/isaaclab_assets/robots/cartpole.py + :language: python + :lines: 19-35 + :dedent: + +To import articulation from a URDF file instead of a USD file, you can replace the +:class:`~sim.spawners.from_files.UsdFileCfg` with a :class:`~sim.spawners.from_files.UrdfFileCfg`. +For more details, please check the API documentation. + + +Defining the initial state +-------------------------- + +Every asset requires defining their initial or *default* state in the simulation through its configuration. +This configuration is stored into the asset's default state buffers that can be accessed when the asset's +state needs to be reset. + +.. note:: + The initial state of an asset is defined w.r.t. its local environment frame. This then needs to + be transformed into the global simulation frame when resetting the asset's state. For more + details, please check the :ref:`tutorial-interact-articulation` tutorial. + + +For an articulation, the :class:`~assets.ArticulationCfg.InitialStateCfg` object defines the +initial state of the root of the articulation and the initial state of all its joints. In this +example, we will spawn the Cartpole at the origin of the XY plane at a Z height of 2.0 meters. +Meanwhile, the joint positions and velocities are set to 0.0. + +.. literalinclude:: ../../../source/isaaclab_assets/isaaclab_assets/robots/cartpole.py + :language: python + :lines: 36-38 + :dedent: + +Defining the actuator configuration +----------------------------------- + +Actuators are a crucial component of an articulation. Through this configuration, it is possible +to define the type of actuator model to use. We can use the internal actuator model provided by +the physics engine (i.e. the implicit actuator model), or use a custom actuator model which is +governed by a user-defined system of equations (i.e. the explicit actuator model). +For more details on actuators, see :ref:`overview-actuators`. + +The cartpole's articulation has two actuators, one corresponding to its each joint: +``cart_to_pole`` and ``slider_to_cart``. We use two different actuator models for these actuators as +an example. However, since they are both using the same actuator model, it is possible +to combine them into a single actuator model. + +.. dropdown:: Actuator model configuration with separate actuator models + :icon: code + + .. literalinclude:: ../../../source/isaaclab_assets/isaaclab_assets/robots/cartpole.py + :language: python + :lines: 39-49 + :dedent: + + +.. dropdown:: Actuator model configuration with a single actuator model + :icon: code + + .. code-block:: python + + actuators={ + "all_joints": ImplicitActuatorCfg( + joint_names_expr=[".*"], + effort_limit=400.0, + velocity_limit=100.0, + stiffness={"slider_to_cart": 0.0, "cart_to_pole": 0.0}, + damping={"slider_to_cart": 10.0, "cart_to_pole": 0.0}, + ), + }, + +.. note:: + If your asset's USD authored drives ship with zero stiffness *and* zero damping + — a common pattern for assets that expect ``ImplicitActuatorCfg`` to supply the + gains at runtime — the joints will actuate under PhysX but appear unactuated + under Newton-based backends (MuJoCo Warp, XPBD, Featherstone, Semi-implicit). + Set :attr:`~isaaclab.sim.schemas.JointDrivePropertiesCfg.ensure_drives_exist` + to ``True`` on the spawn config to keep both backends in sync. See + :ref:`import-new-asset-ensure-drives-exist` for the full explanation. + + +ActuatorCfg velocity/effort limits considerations +------------------------------------------------- + +In IsaacLab v1.4.0, the plain ``velocity_limit`` and ``effort_limit`` attributes were **not** consistently +pushed into the physics solver: + +- **Implicit actuators** + - velocity_limit was ignored (never set in simulation) + - effort_limit was set into simulation + +- **Explicit actuators** + - both velocity_limit and effort_limit were used only by the drive model, not by the solver + + +In v2.0.1 we accidentally changed this: all velocity_limit & effort_limit, implicit or +explicit, were being applied to the solver. That caused many training under the old default uncaped solver +limits to break. + +To restore the original behavior while still giving users full control over solver limits, we introduced two new flags: + +* **velocity_limit_sim** + Sets the physics-solver's maximum joint-velocity cap in simulation. + +* **effort_limit_sim** + Sets the physics-solver's maximum joint-effort cap in simulation. + + +These explicitly set the solver's joint-velocity and joint-effort caps at simulation level. + +On the other hand, velocity_limit and effort_limit model the motor's hardware-level constraints in torque +computation for all explicit actuators rather than limiting simulation-level constraint. +For implicit actuators, since they do not model motor hardware limitations, ``velocity_limit`` were removed in v2.1.1 +and marked as deprecated. This preserves same behavior as they did in v1.4.0. Eventually, ``velocity_limit`` and +``effort_limit`` will be deprecated for implicit actuators, preserving only ``velocity_limit_sim`` and +``effort_limit_sim`` + + +.. table:: Limit Options Comparison + + .. list-table:: + :header-rows: 1 + :widths: 20 40 40 + + * - **Attribute** + - **Implicit Actuator** + - **Explicit Actuator** + * - ``velocity_limit`` + - Deprecated (alias for ``velocity_limit_sim``) + - Used by the model (e.g. DC motor), not set into simulation + * - ``effort_limit`` + - Deprecated (alias for ``effort_limit_sim``) + - Used by the model, not set into simulation + * - ``velocity_limit_sim`` + - Set into simulation + - Set into simulation + * - ``effort_limit_sim`` + - Set into simulation + - Set into simulation + + + +Users who want to tune the underlying physics-solver limits should set the ``_sim`` flags. + + +USD vs. ActuatorCfg discrepancy resolution +------------------------------------------ + +USD having default value and the fact that ActuatorCfg can be specified with None, or a overriding value can sometime be +confusing what exactly gets written into simulation. The resolution follows these simple rules,per joint and per +property: + +.. table:: Resolution Rules for USD vs. ActuatorCfg + + +------------------------+------------------------+--------------------+ + | **Condition** | **ActuatorCfg Value** | **Applied** | + +========================+========================+====================+ + | No override provided | Not Specified | USD Value | + +------------------------+------------------------+--------------------+ + | Override provided | User's ActuatorCfg | Same as ActuatorCfg| + +------------------------+------------------------+--------------------+ + + +Digging into USD can sometime be unconvinent, to help clarify what exact value is written, we designed a flag +:attr:`~isaaclab.assets.ArticulationCfg.actuator_value_resolution_debug_print`, +to help user figure out what exact value gets used in simulation. + +Whenever an actuator parameter is overridden in the user's ActuatorCfg (or left unspecified), +we compare it to the value read from the USD definition and record any differences. For each joint and each property, +if unmatching value is found, we log the resolution: + + 1. **USD Value** + The default limit or gain parsed from the USD asset. + + 2. **ActuatorCfg Value** + The user-provided override (or “Not Specified” if none was given). + + 3. **Applied** + The final value actually used for simulation: if the user didn't override it, this matches the USD value; + otherwise it reflects the user's setting. + +This resolution info is emitted as a warning table only when discrepancies exist. +Here's an example of what you'll see:: + + +----------------+--------------------+---------------------+----+-------------+--------------------+----------+ + | Group | Property | Name | ID | USD Value | ActuatorCfg Value | Applied | + +----------------+--------------------+---------------------+----+-------------+--------------------+----------+ + | panda_shoulder | velocity_limit_sim | panda_joint1 | 0 | 2.17e+00 | Not Specified | 2.17e+00 | + | | | panda_joint2 | 1 | 2.17e+00 | Not Specified | 2.17e+00 | + | | | panda_joint3 | 2 | 2.17e+00 | Not Specified | 2.17e+00 | + | | | panda_joint4 | 3 | 2.17e+00 | Not Specified | 2.17e+00 | + | | stiffness | panda_joint1 | 0 | 2.29e+04 | 8.00e+01 | 8.00e+01 | + | | | panda_joint2 | 1 | 2.29e+04 | 8.00e+01 | 8.00e+01 | + | | | panda_joint3 | 2 | 2.29e+04 | 8.00e+01 | 8.00e+01 | + | | | panda_joint4 | 3 | 2.29e+04 | 8.00e+01 | 8.00e+01 | + | | damping | panda_joint1 | 0 | 4.58e+03 | 4.00e+00 | 4.00e+00 | + | | | panda_joint2 | 1 | 4.58e+03 | 4.00e+00 | 4.00e+00 | + | | | panda_joint3 | 2 | 4.58e+03 | 4.00e+00 | 4.00e+00 | + | | | panda_joint4 | 3 | 4.58e+03 | 4.00e+00 | 4.00e+00 | + | | armature | panda_joint1 | 0 | 0.00e+00 | Not Specified | 0.00e+00 | + | | | panda_joint2 | 1 | 0.00e+00 | Not Specified | 0.00e+00 | + | | | panda_joint3 | 2 | 0.00e+00 | Not Specified | 0.00e+00 | + | | | panda_joint4 | 3 | 0.00e+00 | Not Specified | 0.00e+00 | + | panda_forearm | velocity_limit_sim | panda_joint5 | 4 | 2.61e+00 | Not Specified | 2.61e+00 | + | | | panda_joint6 | 5 | 2.61e+00 | Not Specified | 2.61e+00 | + | | | panda_joint7 | 6 | 2.61e+00 | Not Specified | 2.61e+00 | + | | stiffness | panda_joint5 | 4 | 2.29e+04 | 8.00e+01 | 8.00e+01 | + | | | panda_joint6 | 5 | 2.29e+04 | 8.00e+01 | 8.00e+01 | + | | | panda_joint7 | 6 | 2.29e+04 | 8.00e+01 | 8.00e+01 | + | | damping | panda_joint5 | 4 | 4.58e+03 | 4.00e+00 | 4.00e+00 | + | | | panda_joint6 | 5 | 4.58e+03 | 4.00e+00 | 4.00e+00 | + | | | panda_joint7 | 6 | 4.58e+03 | 4.00e+00 | 4.00e+00 | + | | armature | panda_joint5 | 4 | 0.00e+00 | Not Specified | 0.00e+00 | + | | | panda_joint6 | 5 | 0.00e+00 | Not Specified | 0.00e+00 | + | | | panda_joint7 | 6 | 0.00e+00 | Not Specified | 0.00e+00 | + | | friction | panda_joint5 | 4 | 0.00e+00 | Not Specified | 0.00e+00 | + | | | panda_joint6 | 5 | 0.00e+00 | Not Specified | 0.00e+00 | + | | | panda_joint7 | 6 | 0.00e+00 | Not Specified | 0.00e+00 | + | panda_hand | velocity_limit_sim | panda_finger_joint1 | 7 | 2.00e-01 | Not Specified | 2.00e-01 | + | | | panda_finger_joint2 | 8 | 2.00e-01 | Not Specified | 2.00e-01 | + | | stiffness | panda_finger_joint1 | 7 | 1.00e+06 | 2.00e+03 | 2.00e+03 | + | | | panda_finger_joint2 | 8 | 1.00e+06 | 2.00e+03 | 2.00e+03 | + | | armature | panda_finger_joint1 | 7 | 0.00e+00 | Not Specified | 0.00e+00 | + | | | panda_finger_joint2 | 8 | 0.00e+00 | Not Specified | 0.00e+00 | + | | friction | panda_finger_joint1 | 7 | 0.00e+00 | Not Specified | 0.00e+00 | + | | | panda_finger_joint2 | 8 | 0.00e+00 | Not Specified | 0.00e+00 | + +----------------+--------------------+---------------------+----+-------------+--------------------+----------+ + +To keep the cleaniness of logging, :attr:`~isaaclab.assets.ArticulationCfg.actuator_value_resolution_debug_print` +default to False, remember to turn it on when wishes. diff --git a/simulation/modules/IsaacLab/docs/source/migration/comparing_simulation_isaacgym.rst b/simulation/modules/IsaacLab/docs/source/migration/comparing_simulation_isaacgym.rst new file mode 100644 index 0000000000000000000000000000000000000000..e70292f99aad6ad8db9a1f1f573816007d717fcd --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/migration/comparing_simulation_isaacgym.rst @@ -0,0 +1,503 @@ +.. _migrating-from-isaacgymenvs-comparing-simulation: + +Comparing Simulations Between Isaac Gym and Isaac Lab +===================================================== + + +When migrating simulations from Isaac Gym to Isaac Lab, it is sometimes helpful to compare +the simulation configurations in Isaac Gym and Isaac Lab to identify differences between the two setups. +There may be differences in how default values are interpreted, how the importer treats certain +hierarchies of bodies, and how values are scaled. The only way to be certain that two simulations +are equivalent in the eyes of PhysX is to record a simulation trace of both setups and compare +them by inspecting them side-by-side. This approach works because PhysX is the same underlying +engine for both Isaac Gym and Isaac Lab, albeit with different versions. + + +Recording to PXD2 in Isaac Gym Preview Release +---------------------------------------------- + +Simulation traces in Isaac Gym can be recorded using the built-in PhysX Visual Debugger (PVD) +file output feature. Set the operating system environment variable ``GYM_PVD_FILE`` to the +desired output file path; the ``.pxd2`` file extension will be appended automatically. + +For detailed instructions, refer to the tuning documentation included with Isaac Gym: + +.. code-block:: text + + isaacgym/docs/_sources/programming/tuning.rst.txt + +.. note:: + + This file reference is provided because Isaac Gym does not have its documentation available online. + + +Recording to OVD in Isaac Lab +----------------------------- + +To record an OVD simulation trace file in Isaac Lab, you must set the appropriate Isaac Sim Kit +arguments. It is important that the ``omniPvdOvdRecordingDirectory`` variable is set **before** +``omniPvdOutputEnabled`` is set to ``true``. + +.. code-block:: bash + + ./isaaclab.sh -p scripts/benchmarks/benchmark_non_rl.py --task \ + --kit_args="--/persistent/physics/omniPvdOvdRecordingDirectory=/tmp/myovds/ \ + --/physics/omniPvdOutputEnabled=true" + +This example outputs a series of OVD files to the ``/tmp/myovds/`` directory. + +If the ``--kit_args`` argument does not work in your particular setup, you can set the Kit arguments +manually by editing the following file directly within the Isaac Sim source code: + +.. code-block:: text + + source/extensions/isaacsim.simulation_app/isaacsim/simulation_app/simulation_app.py + +Append the following lines after the ``args = []`` block: + +.. code-block:: python + + args.append("--/persistent/physics/omniPvdOvdRecordingDirectory=/path/to/output/ovds/") + args.append("--/physics/omniPvdOutputEnabled=true") + + +Inspecting PXD2 and OVD Files +----------------------------- + +By opening the PXD2 file in a PVD viewer and the OVD file in OmniPVD (a Kit extension), you can +manually compare the two simulation runs and their respective parameters. + +**PhysX Visual Debugger (PVD) for PXD2 Files** + +Download the PVD viewer from the NVIDIA Developer Tools page: + + ``_ + +Both version 2 and version 3 of the PVD viewer are compatible with PXD2 files. + +**OmniPVD for OVD Files** + +To view OVD files, enable the OmniPVD extension in the Isaac Sim application. For detailed +instructions, refer to the OmniPVD developer guide: + + https://docs.omniverse.nvidia.com/kit/docs/omni_physics/latest/extensions/ux/source/omni.physx.pvd/docs/dev_guide/physx_visual_debugger.html + +**Inspecting Contact Gizmos in OmniPVD** + +To inspect contact points between objects, enable the contact gizmos in OmniPVD. Ensure that the +simulation frame is set to **PRE** (pre-simulation frames of each simulation step) in the OmniPVD +timeline, or set the replay mode to **PRE**. This allows you to visualize contact information before +the solver processes each step. + +**Comparing PVD and OVD Files** + +Using the PVD viewer and the OmniPVD extension, you can now compare the simulations side-by-side +to identify configuration differences. On the left is PVD for PXD2 inspection and on the right is the OmniPVD +extension loaded to inspect OVD files. + +.. image:: ../_static/migration/ovd_pvd_comparison.jpg + + +Parameters to Verify During Simulation Comparison +------------------------------------------------- + +For PhysX articulations, each attribute is useful to inspect because it reveals how the link or shape +will actually behave in contact, under drives, and at constraints. Below, each attribute is expanded +with why it matters for debugging and tuning simulations. + + +PxArticulationLink +^^^^^^^^^^^^^^^^^^ + +Each link behaves like a rigid body with mass properties, damping, velocity limits, and contact-resolution +limits. Inspecting these helps explain stability issues, jitter, and odd responses to forces. + +Mass Properties +""""""""""""""" + +**Mass** + Determines how strongly the link accelerates under forces and how it shares impulses in collisions + and joint constraints. + + *When to inspect:* Understand why a link seems "too heavy" (barely moves when pushed) or "too light" + (flies around from small impulses), and to detect inconsistent mass distribution across a chain that + can cause unrealistic motion or joint stress. + +**Center of Mass (pose)** + Controls where forces effectively act and how the link balances. + + *When to inspect:* A character or mechanism tips over unexpectedly or feels unbalanced; an offset COM + can cause unrealistic torque for the same contact. + +**Inertia Tensor / Inertia Scale** + Defines rotational resistance about each axis. + + *When to inspect:* Links are too easy or too hard to spin relative to their mass, which affects joint + drive tuning and impact responses. + +Damping Properties +"""""""""""""""""" + +**Linear Damping** + Models velocity-proportional drag on translation; higher values make links lose linear speed faster. + + *When to inspect:* Links slide too far (damping too low) or feel "underwater" (damping too high), or + when articulation energy seems to vanish without obvious contact. + +**Angular Damping** + Models drag on rotation; higher values make spinning links slow more quickly. + + *When to inspect:* Links keep spinning after impacts or motor drives (too low), or joints feel "sticky" + and fail to swing freely under gravity (too high). + +Velocity Properties +""""""""""""""""""" + +**Linear Velocity** + Instantaneous world-space translational velocity of the link. + + *When to inspect:* Verify whether joint motors, gravity, or contacts are generating expected motion, + detect numerical explosions (huge spikes), and correlate with CCD thresholds and max linear velocity clamping. + +**Angular Velocity** + Instantaneous world-space rotational velocity. + + *When to inspect:* Verify joint drives, impacts, or constraints are producing the correct rotation; + spot runaway spin that can cause instability or tunneling before clamping takes effect. + +**Max Linear Velocity** + Upper bound PhysX uses to clamp linear speed before solving, intended to prevent numerical issues + from extremely fast motion. + + *When to inspect:* Objects start tunneling or simulations explode at high speeds. If too high, links + can move too far in one step; too low, they may appear unnaturally capped like "speed-limited" robots. + +**Max Angular Velocity** + Upper bound for angular speed; PhysX clamps angular velocity similarly to linear velocity. + + *When to inspect:* Links spin unrealistically fast after collisions or drives (value too large), or + rotation looks unnaturally limited, especially for wheels or rotors that should rotate quickly (value too small). + +Contact Resolution Properties +""""""""""""""""""""""""""""" + +**Max Depenetration Velocity** + Limits how much corrective velocity the solver may add in one step to resolve penetrations at contacts. + + *When to inspect:* Overlapping links "explode" outward or jitter after starting interpenetrating (too high), + or embedded links separate too slowly and appear stuck together (too low). + +**Max Contact Impulse** + Caps the impulse the solver can apply at contacts; per-body limit, with the actual contact limit being + the minimum of the two bodies' values. + + *When to inspect:* Contacts feel too soft (bodies interpenetrate deeply or sink into the environment) or + too rigid (sharp impulses causing ringing or bouncing), or when tuning "soft collisions" like rubber or + skin-like surfaces. + +State and Behavior Flags +"""""""""""""""""""""""" + +**Kinematic vs Dynamic flag / Disable gravity** + Indicates whether a link is driven kinematically or fully simulated, and whether gravity affects it. + + *When to inspect:* Parts appear frozen, snap directly to poses, or ignore gravity, which can drastically + change articulation behavior. + +**Sleep thresholds (linear, angular) and wake counter** + Control when a link is allowed to go to sleep and stop simulating. + + *When to inspect:* Articulations sleep too early (stopping motion) or never sleep (wasting performance + and causing low-amplitude jitter). + + +PxArticulationJoint +^^^^^^^^^^^^^^^^^^^ + +The inbound joint defines relative motion between a link and its parent. Inspecting motion and related +parameters explains limits, constraints, and how drives shape articulation pose and stability. + +Joint Configuration +""""""""""""""""""" + +**Motion** + Per-axis setting (locked, limited, free) that defines which degrees of freedom the joint allows and + whether ranges are restricted. + + *When to inspect:* A link moves in an unexpected direction (axis wrongly set to free), hits a hard stop + sooner or later than expected (limit vs locked), or seems unconstrained because an axis is mistakenly left free. + +**Joint Type / Axes definition** + Choice of revolute, prismatic, spherical, etc., and the local joint frames that define axes. + + *When to inspect:* A "hinge" behaves more like a ball joint or slides unexpectedly; incorrect type or + frame alignment easily produces weird motions. + +**Limits (swing, twist, linear)** + Specify allowed angular or linear ranges and often include stiffness/damping. + + *When to inspect:* Joints hyper-extend, clip through geometry, or suddenly snap at boundaries; mis-set + limits cause popping and instability. + +Drive Properties +"""""""""""""""" + +**Drive target position (orientation) and target velocity** + Desired relative pose and relative velocity that drives the articulation, often using spring-damper models. + + *When to inspect:* Controllers are too slow or overshoot and oscillate—target values and drive parameters + must match link mass and inertia. + +**Drive stiffness and damping (spring strength, tangential damping)** + Control how aggressively the joint tries to reach the target pose and how much overshoot is damped. + + *When to inspect:* Joints buzz or oscillate under load (stiffness high, damping low) or feel unresponsive + and "rubbery" (stiffness low). + +**Joint friction / resistance (if configured)** + Adds resistance even without explicit damping in drives. + + *When to inspect:* Passive joints keep swinging too long, or appear stuck even without drives. + + +PxShape +^^^^^^^ + +Shapes attached to links determine collision representation and contact behavior. Even if they are internal +in OmniPhysics, their properties have a strong impact on stability, contact timing, and visual alignment. + +Collision Offsets +""""""""""""""""" + +**Rest Offset** + Distance at which two shapes come to rest; sum of their rest offsets defines the separation where they "settle". + + *When to inspect:* Graphics and collision appear misaligned (gaps or visible intersections), or sliding + over meshes is rough. Small positive offsets can smooth sliding, while zero offset tends to align exactly + but may catch on geometry. + +**Contact Offset** + Distance at which contact generation begins; shapes whose distance is less than the sum of contact offsets + generate contacts. + + *When to inspect:* Contacts appear "too early" (objects seem to collide before visually touching, increasing + contact count) or "too late" (tunneling or jitter). The difference between contact and rest offsets is + crucial for predictive, stable contacts. + +Geometry and Materials +"""""""""""""""""""""" + +**Geometry type and dimensions** + Box, sphere, capsule, convex, mesh, and the associated size parameters. + + *When to inspect:* Collision footprint does not match the visual mesh—overly large shapes cause premature + contacts; small shapes allow visual intersection and change leverage at contacts. + +**Material(s): friction, restitution, compliance** + Friction coefficients and restitution define sliding and bounciness. + + *When to inspect:* An articulation foot skids too easily, sticks to the ground, or bounces unexpectedly. + Wrong materials can make mechanisms unstable or unresponsive. + +Shape Flags +""""""""""" + +**Flag for simulation / query / trigger** + Whether the shape participates in simulation contacts, raycasts only, or trigger events. + + *When to inspect:* Contacts do not appear (shape set as query only) or triggers unexpectedly create + physical collisions. + +**Contact density (CCD flags, if used)** + Continuous collision detection flags affecting how fast-moving links are handled. + + *When to inspect:* Fast articulation parts tunnel through thin obstacles, or CCD is too aggressive and + reduces performance. + + +PxRigidDynamic +^^^^^^^^^^^^^^ + +``PxRigidDynamic`` is the core simulated rigid body type in PhysX, so inspecting its attributes is crucial +for understanding individual object behavior, stability, and performance in the scene. Many attributes +mirror ``PxArticulationLink``, but a rigid dynamic is not constrained by articulation joints and can also +be used in kinematic mode. + +Mass and Mass-Related Properties +"""""""""""""""""""""""""""""""" + +**Mass** + Controls translational response to forces and impulses; for the same impulse, lower mass gives higher + velocity change. + + *When to inspect:* An object barely reacts to hits (mass too large) or flies away from small forces + (mass too small), or mass ratios between interacting bodies cause overly dominant or easily bullied bodies. + +**Center of Mass (COM) pose** + Defines where forces effectively act and around which point the body rotates. + + *When to inspect:* Objects tip over unexpectedly, roll in unintuitive ways, or feel "unbalanced." A COM + too high or off-center can cause strong torques from small contacts. + +**Inertia tensor / inertia scaling** + Determines resistance to angular acceleration around each axis for a given torque. + + *When to inspect:* Bodies are too easy or too hard to spin (e.g., a large object spinning quickly from + small hits), or when anisotropic behavior is needed (e.g., wheels that spin easily around one axis but + resist others). + +Damping and Velocity Limits +""""""""""""""""""""""""""" + +**Linear Damping** + Adds velocity-proportional drag on translation. + + *When to inspect:* Bodies slide too far or for too long (damping too low) or appear as if moving through + thick fluid (damping too high), and when scenes lose energy faster than friction alone would suggest. + +**Angular Damping** + Adds drag on rotation, reducing angular velocity over time. + + *When to inspect:* Spinning objects never settle or spin unrealistically long (too low), or they stop + rotating almost immediately after impact or motor impulses (too high). + +**Linear Velocity** + Current translational velocity used by the integrator and solver. + + *When to inspect:* Debug impulses, gravity, or applied forces to see whether the body is accelerating + as expected; detect spikes or non-physical jumps in speed. + +**Angular Velocity** + Current rotational speed around each axis. + + *When to inspect:* Rotations look jittery, explode numerically, or fail to respond to applied torques. + High values relative to time step and object scale can indicate instability. + +**Max Linear Velocity** + Upper bound used to clamp linear velocity before solving. + + *When to inspect:* Very fast bodies cause tunneling or simulation explosions (value too high), or they + appear unnaturally "speed-limited," especially projectiles or debris in high-energy scenes (value too low). + +**Max Angular Velocity** + Upper bound used to clamp angular velocity. + + *When to inspect:* Thin or small bodies spin so fast they destabilize the scene (value too high), or + spinning elements such as wheels, propellers, or debris appear artificially capped (value too low). + +Contact Resolution and Impulses +""""""""""""""""""""""""""""""" + +**Max Depenetration Velocity** + Limits the corrective velocity the solver may introduce in one step to resolve interpenetrations. + + *When to inspect:* Intersecting bodies "explode" apart or jitter violently after overlap (too high), or + separate very slowly and appear stuck or interpenetrated for several frames (too low). + +**Max Contact Impulse** + Caps the impulse that can be applied at contacts involving this body; the effective limit is the minimum + between the two bodies, or the dynamic body for static–dynamic contacts. + + *When to inspect:* Create softer contacts (lower limit) or very rigid, almost unyielding bodies (high or + default limit); objects sink into each other or bounce unrealistically. + +Sleep and Activation Behavior +""""""""""""""""""""""""""""""" + +**Sleep Threshold** + Mass-normalized kinetic energy below which a body becomes a candidate for sleeping. + + *When to inspect:* Bodies fall asleep too early while they should still move (threshold too high) or + constantly jitter and never sleep (threshold too low), which can hurt performance. + +**Wake Counter / isSleeping flag** + Internal timer and state indicating whether the body is active. + + *When to inspect:* Bodies refuse to wake up on interactions or wake too easily. Bad sleep behavior can + make scenes feel "dead" or too noisy. + +Kinematic Mode and Locking +"""""""""""""""""""""""""" + +**Kinematic Flag (PxRigidBodyFlag::eKINEMATIC)** + When set, the body is moved by ``setKinematicTarget`` and ignores forces and gravity, while still + affecting dynamic bodies it touches. + + *When to inspect:* Objects appear to have infinite mass (pushing others but not reacting) or ignore + gravity and impulses. Mismatched expectations here commonly cause odd behavior in characters, moving + platforms, or doors. + +**Rigid Dynamic Lock Flags (PxRigidDynamicLockFlag)** + Per-axis linear and angular DOF locks, effectively constraining motion without a joint. + + *When to inspect:* Bodies unexpectedly move in constrained directions (lock not set) or fail to + move/rotate where they should (lock set by mistake), especially for 2D-style movement or simple + constrained mechanisms. + +**Disable Gravity (PxActorFlag::eDISABLE_GRAVITY)** + Toggles whether the body is affected by scene gravity. + + *When to inspect:* Objects float in mid-air or drop unexpectedly. A common source of confusion in + mixed setups with some gravity-less bodies. + +Forces and Solver Overrides +""""""""""""""""""""""""""" + +**Applied force and torque (accumulated per step)** + Net forces/torques that will be integrated into velocity. + + *When to inspect:* Debug gameplay forces (thrusters, character pushes, explosions) to see if the expected + input is actually reaching the body. + +**Per-body solver iteration counts (minPositionIters, minVelocityIters)** + Overrides for how many solver iterations this body gets in constraints and contacts. + + *When to inspect:* Certain bodies (e.g., characters, stacked crates, fragile structures) need higher + stability or more accurate stacking. Low iterations can cause jitter and penetration; too high wastes + performance. + +Shape-Related Aspects +""""""""""""""""""""" + +While not properties of ``PxRigidDynamic`` itself, the shapes attached to it heavily influence behavior. + +**Attached Shapes' Rest and Contact Offsets** + Control predictive contact generation and visual separation as described earlier. + + *When to inspect:* A dynamic body seems to collide too early/late or appears to float above surfaces + or intersect them visually. + +**Attached Materials (friction, restitution)** + Define sliding and bounciness for this body's contacts. + + *When to inspect:* Rigid dynamics skid, stick, or bounce in unexpected ways. Often the "behavior issue" + is material configuration rather than mass or damping. + + +Summary: What to Inspect and Why +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The table below summarizes the key inspection areas for each PhysX component: + +.. list-table:: + :header-rows: 1 + :widths: 20 40 40 + + * - Component + - Key Attributes + - Debugging Focus + * - **Links** + - Mass, damping, velocities, limits + - Overall energy, stability, and response to joints/contacts + * - **Joints** + - Motion, limits, drives + - How articulation pose evolves; over/under-constrained motion + * - **Shapes** + - Offsets, materials, geometry + - Contact timing, friction behavior, visual vs physical alignment + * - **Rigid Dynamics** + - Mass, inertia, damping, velocity limits, sleep, kinematic flags + - Acceleration, settling, extreme motion, body state + +All of these attributes together provide a comprehensive picture of why an articulation or rigid body +behaves as it does and where to adjust parameters for stability, realism, or control performance. diff --git a/simulation/modules/IsaacLab/docs/source/migration/migrating_deformables.rst b/simulation/modules/IsaacLab/docs/source/migration/migrating_deformables.rst new file mode 100644 index 0000000000000000000000000000000000000000..cce2e15fa3e492514d6f59bfaf070f3e6d8c7e9f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/migration/migrating_deformables.rst @@ -0,0 +1,252 @@ +.. _migrating-deformables: + +Migration of Deformables +======================== + +.. currentmodule:: isaaclab + +In the newer versions of Omni Physics (107.0 and later), the old deformable body functionality has become deprecated. +The following sections describe the changes to migrate to the new Omni Physics API, specifically moving away from +Soft Bodies and towards Surface and Volume Deformables. The deformable object asset classes remain in +``isaaclab.assets``. Schema define/modify functions remain unified in ``isaaclab.sim.schemas``, and deformable +material spawning remains unified in ``isaaclab.sim.spawners.materials``. Deformable property and material +configuration classes are backend-specific: PhysX configurations live in ``isaaclab_physx.sim`` and Newton +configurations live in ``isaaclab_newton.sim``. + +.. note:: + + The following changes are with respect to Isaac Lab v3.0.0 and Omni Physics v110.0. Please refer to the + `release notes`_ for any changes in the future releases. + + +Surface and Volume Deformables +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +With the new Omni Physics API, deformable bodies are split into two distinct types, as described in the +`Omni Physics documentation`_: + +- **Volume deformables**: 3D objects simulated with a tetrahedral FEM mesh (e.g., soft cubes, spheres, capsules). + These support kinematic targets on individual vertices. The simulation operates on a tetrahedral mesh internally, + while a separate triangle surface mesh handles rendering. +- **Surface deformables**: 2D surfaces simulated directly on a triangle mesh (e.g., cloth, fabric, membranes). + These have additional material properties for controlling stretch, shear, and bend stiffness, but do not support + kinematic vertex targets. + +The type of deformable is determined by the **physics material** assigned to the object: + +- :class:`~isaaclab_physx.sim.PhysxDeformableBodyMaterialCfg` creates a PhysX **volume** deformable. +- :class:`~isaaclab_physx.sim.PhysxSurfaceDeformableBodyMaterialCfg` creates a PhysX **surface** deformable. +- :class:`~isaaclab_newton.sim.spawners.materials.NewtonDeformableBodyMaterialCfg` creates a Newton + **volume** deformable. +- :class:`~isaaclab_newton.sim.spawners.materials.NewtonSurfaceDeformableBodyMaterialCfg` creates a Newton + **surface** deformable. + + +Migration from the Old API +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Import Changes +^^^^^^^^^^^^^^ + +Deformable object cfgs remain in ``isaaclab.assets``. Deformable schema and material cfgs should be imported +from the physics backend package: + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Old Import + - New Import + * - ``from isaaclab.sim import DeformableBodyPropertiesCfg`` + - ``from isaaclab_physx.sim import PhysxDeformableBodyPropertiesCfg`` + * - ``from isaaclab.sim import DeformableBodyMaterialCfg`` + - ``from isaaclab_physx.sim import PhysxDeformableBodyMaterialCfg`` + * - ``from isaaclab.sim import SurfaceDeformableBodyMaterialCfg`` + - ``from isaaclab_physx.sim import PhysxSurfaceDeformableBodyMaterialCfg`` + * - ``from isaaclab.sim import DeformableBodyPropertiesCfg`` + - ``from isaaclab_newton.sim.schemas import NewtonDeformableBodyPropertiesCfg`` + * - ``from isaaclab.sim import DeformableBodyMaterialCfg`` + - ``from isaaclab_newton.sim.spawners.materials import NewtonDeformableBodyMaterialCfg`` + * - ``from isaaclab.sim import SurfaceDeformableBodyMaterialCfg`` + - ``from isaaclab_newton.sim.spawners.materials import NewtonSurfaceDeformableBodyMaterialCfg`` + * - ``from isaaclab_physx.assets import DeformableObjectCfg`` + - ``from isaaclab.assets import DeformableObjectCfg`` + + +Removed Properties +^^^^^^^^^^^^^^^^^^ + +The following properties have been **removed** from +:class:`~isaaclab_physx.sim.PhysxDeformableBodyPropertiesCfg`: + +- ``collision_simplification`` and related parameters (``collision_simplification_remeshing``, + ``collision_simplification_target_triangle_count``, ``collision_simplification_force_conforming``, + ``collision_simplification_remove_open_edges``) — collision mesh generation is now handled automatically by + PhysX through ``deformableUtils.create_auto_volume_deformable_hierarchy()`` and + ``deformableUtils.create_auto_surface_deformable_hierarchy()``. +- ``simulation_hexahedral_resolution`` — the simulation mesh resolution is no longer user-configurable; + PhysX determines it automatically. +- ``vertex_velocity_damping`` — replaced by the more general ``linear_damping`` property from the + `PhysX deformable schema`_. +- ``sleep_damping`` — replaced by ``settling_damping`` in the `PhysX deformable schema`_. + +Added Properties +^^^^^^^^^^^^^^^^ + +The following properties have been **added** to +:class:`~isaaclab_physx.sim.PhysxDeformableBodyPropertiesCfg`: + +- ``deformable_body_enabled``, ``kinematic_enabled``, and ``mass`` — OmniPhysics + deformable body properties owned by the PhysX backend cfg. +- ``linear_damping`` — linear damping coefficient [1/s]. +- ``max_linear_velocity`` — maximum allowable linear velocity [m/s]. A negative value lets the simulation choose + a per-vertex value dynamically (currently only supported for surface deformables). +- ``settling_damping`` — additional damping applied when vertex velocity falls below ``settling_threshold`` [1/s]. +- ``enable_speculative_c_c_d`` — enables speculative continuous collision detection. +- ``disable_gravity`` — per-deformable gravity control. +- ``collision_pair_update_frequency`` — how often surface-to-surface collision pairs are updated per time step + (surface deformables only). +- ``collision_iteration_multiplier`` — collision subiterations per solver iteration (surface deformables only). + +For a full description of all available properties, refer to the `PhysX deformable schema`_ and +`OmniPhysics deformable schema`_ documentation. + +Material Changes +^^^^^^^^^^^^^^^^ + +The deformable material hierarchy is now split by backend: + +- :class:`~isaaclab.sim.DeformableBodyMaterialBaseCfg` and + :class:`~isaaclab.sim.SurfaceDeformableBodyMaterialBaseCfg` — empty base classes for backend-specific + deformable material configs. +- :class:`~isaaclab_physx.sim.PhysxDeformableBodyMaterialCfg` — for PhysX volume deformables. Contains ``density``, + ``static_friction``, ``dynamic_friction``, ``youngs_modulus``, ``poissons_ratio``, and ``elasticity_damping``. +- :class:`~isaaclab_physx.sim.PhysxSurfaceDeformableBodyMaterialCfg` — extends the PhysX volume material config with + surface-specific properties: ``surface_thickness``, ``surface_stretch_stiffness``, ``surface_shear_stiffness``, + ``surface_bend_stiffness``, and ``bend_damping``. +- :class:`~isaaclab_newton.sim.spawners.materials.NewtonDeformableBodyMaterialCfg` and + :class:`~isaaclab_newton.sim.spawners.materials.NewtonSurfaceDeformableBodyMaterialCfg` contain Newton-specific + fields such as density, particle radius, direct Lame parameters ``k_mu``/``k_lambda`` for volume deformables, + and VBD stiffness parameters for surface deformables. + +The old ``damping_scale`` property has been removed. Use ``elasticity_damping`` directly instead. + +DeformableObject View Change +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The internal PhysX view type has changed from ``physx.SoftBodyView`` to ``physx.DeformableBodyView``. +The property ``root_physx_view`` has been deprecated in favor of ``root_view``. + + +Code Examples +~~~~~~~~~~~~~ + +Volume Deformable (Before and After) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**Before**: + +.. code-block:: python + :emphasize-lines: 1,2 + + import isaaclab.sim as sim_utils + from isaaclab.assets import DeformableObject, DeformableObjectCfg + + cfg = DeformableObjectCfg( + prim_path="/World/Origin.*/Cube", + spawn=sim_utils.MeshCuboidCfg( + size=(0.2, 0.2, 0.2), + deformable_props=sim_utils.DeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=sim_utils.DeformableBodyMaterialCfg(poissons_ratio=0.4, youngs_modulus=1e5), + ), + ) + cube_object = DeformableObject(cfg=cfg) + +**After**: + +.. code-block:: python + :emphasize-lines: 1,2 + + import isaaclab.sim as sim_utils + from isaaclab.assets import DeformableObject, DeformableObjectCfg + from isaaclab_physx.sim import PhysxDeformableBodyMaterialCfg, PhysxDeformableBodyPropertiesCfg + + cfg = DeformableObjectCfg( + prim_path="/World/Origin.*/Cube", + spawn=sim_utils.MeshCuboidCfg( + size=(0.2, 0.2, 0.2), + deformable_props=PhysxDeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=PhysxDeformableBodyMaterialCfg(poissons_ratio=0.4, youngs_modulus=1e5), + ), + ) + cube_object = DeformableObject(cfg=cfg) + +Surface Deformable (New) +^^^^^^^^^^^^^^^^^^^^^^^^ + +Surface deformables use :class:`~isaaclab.sim.spawners.meshes.MeshRectangleCfg` for 2D meshes, combined with +:class:`~isaaclab_physx.sim.PhysxSurfaceDeformableBodyMaterialCfg`: + +.. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab.assets import DeformableObject, DeformableObjectCfg + from isaaclab_physx.sim import PhysxDeformableBodyPropertiesCfg, PhysxSurfaceDeformableBodyMaterialCfg + + cfg = DeformableObjectCfg( + prim_path="/World/Origin.*/Cloth", + spawn=sim_utils.MeshRectangleCfg( + size=(1.5, 1.5), + resolution=(21, 21), + deformable_props=PhysxDeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=PhysxSurfaceDeformableBodyMaterialCfg(poissons_ratio=0.4, youngs_modulus=1e5), + ), + ) + cloth_object = DeformableObject(cfg=cfg) + +USD File Deformable +^^^^^^^^^^^^^^^^^^^ + +Deformable properties can also be applied to imported USD assets using +:class:`~isaaclab.sim.spawners.from_files.UsdFileCfg`: + +.. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab.assets import DeformableObject, DeformableObjectCfg + from isaaclab_physx.sim import PhysxDeformableBodyMaterialCfg, PhysxDeformableBodyPropertiesCfg + + from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR + + cfg = DeformableObjectCfg( + prim_path="/World/Origin.*/Teddy", + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Objects/Teddy_Bear/teddy_bear.usd", + deformable_props=PhysxDeformableBodyPropertiesCfg(), + physics_material=PhysxDeformableBodyMaterialCfg(poissons_ratio=0.4, youngs_modulus=1e5), + scale=[0.05, 0.05, 0.05], + ), + ) + teddy_object = DeformableObject(cfg=cfg) + + +Limitations +~~~~~~~~~~~ + +- **Kinematic targets are volume-only.** Calling + :meth:`~isaaclab.assets.DeformableObject.write_nodal_kinematic_target_to_sim_index` on a surface + deformable will raise a ``ValueError``. +- **Surface-specific solver properties** (``collision_pair_update_frequency``, + ``collision_iteration_multiplier``) have no effect on volume deformables. +- **Newton deformables are experimental.** They are implemented in + :mod:`isaaclab_contrib.deformable` and currently target VBD-based solvers and + coupled rigid-deformable workflows. + + +.. _Omni Physics documentation: https://docs.omniverse.nvidia.com/kit/docs/omni_physics/110.0/dev_guide/deformables/deformable_bodies.html +.. _PhysX deformable schema: https://docs.omniverse.nvidia.com/kit/docs/omni_physics/110.0/dev_guide/deformables/physx_deformable_schema.html#physxbasedeformablebodyapi +.. _OmniPhysics deformable schema: https://docs.omniverse.nvidia.com/kit/docs/omni_physics/110.0/dev_guide/deformables/omniphysics_deformable_schema.html +.. _release notes: https://github.com/isaac-sim/IsaacLab/releases diff --git a/simulation/modules/IsaacLab/docs/source/migration/migrating_from_isaacgymenvs.rst b/simulation/modules/IsaacLab/docs/source/migration/migrating_from_isaacgymenvs.rst new file mode 100644 index 0000000000000000000000000000000000000000..3bd21c24052223d8713fd5025dcb317bf87803d2 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/migration/migrating_from_isaacgymenvs.rst @@ -0,0 +1,942 @@ +.. _migrating-from-isaacgymenvs: + +From IsaacGymEnvs +================= + +.. currentmodule:: isaaclab + + +`IsaacGymEnvs`_ was a reinforcement learning framework designed for the `Isaac Gym Preview Release`_. +As both IsaacGymEnvs and the Isaac Gym Preview Release are now deprecated, the following guide walks through +the key differences between IsaacGymEnvs and Isaac Lab, as well as differences in APIs between Isaac Gym Preview +Release and Isaac Sim. + +.. note:: + + The following changes are with respect to Isaac Lab 1.0 release. Please refer to the `release notes`_ for any changes + in the future releases. + + +Task Config Setup +~~~~~~~~~~~~~~~~~ + +In IsaacGymEnvs, task config files were defined in ``.yaml`` format. With Isaac Lab, configs are now specified using +a specialized Python class :class:`~isaaclab.utils.configclass`. The :class:`~isaaclab.utils.configclass` +module provides a wrapper on top of Python's ``dataclasses`` module. Each environment should specify its own config +class annotated by ``@configclass`` that inherits from :class:`~envs.DirectRLEnvCfg`, which can include simulation +parameters, environment scene parameters, robot parameters, and task-specific parameters. + +Below is an example skeleton of a task config class: + +.. code-block:: python + + from isaaclab.envs import DirectRLEnvCfg + from isaaclab.scene import InteractiveSceneCfg + from isaaclab.sim import SimulationCfg + + @configclass + class MyEnvCfg(DirectRLEnvCfg): + # simulation + sim: SimulationCfg = SimulationCfg() + # robot + robot_cfg: ArticulationCfg = ArticulationCfg() + # scene + scene: InteractiveSceneCfg = InteractiveSceneCfg() + # env + decimation = 2 + episode_length_s = 5.0 + action_space = 1 + observation_space = 4 + state_space = 0 + # task-specific parameters + ... + +Simulation Config +----------------- + +Simulation related parameters are defined as part of the :class:`~isaaclab.sim.SimulationCfg` class, +which is a :class:`~isaaclab.utils.configclass` module that holds simulation parameters such as ``dt``, +``device``, and ``gravity``. Each task config must have a variable named ``sim`` defined that holds the type +:class:`~isaaclab.sim.SimulationCfg`. + +In Isaac Lab, the use of ``substeps`` has been replaced +by a combination of the simulation ``dt`` and the ``decimation`` parameters. For example, in IsaacGymEnvs, having +``dt=1/60`` and ``substeps=2`` is equivalent to taking 2 simulation steps with ``dt=1/120``, but running the task step +at ``1/60`` seconds. The ``decimation`` parameter is a task parameter that controls the number of simulation steps to +take for each task (or RL) step, replacing the ``controlFrequencyInv`` parameter in IsaacGymEnvs. +Thus, the same setup in Isaac Lab will become ``dt=1/120`` and ``decimation=2``. + +In Isaac Sim, physx simulation parameters such as ``num_position_iterations``, ``num_velocity_iterations``, +``contact_offset``, ``rest_offset``, ``bounce_threshold_velocity``, ``max_depenetration_velocity`` can all +be specified on a per-actor basis. These parameters have been moved from the physx simulation config +to each individual articulation and rigid body config. + +When running simulation on the GPU, buffers in PhysX require pre-allocation for computing and storing +information such as contacts, collisions and aggregate pairs. These buffers may need to be adjusted +depending on the complexity of the environment, the number of expected contacts and collisions, +and the number of actors in the environment. The :class:`~isaaclab.sim.PhysxCfg` class provides access for +setting the GPU buffer dimensions. + ++--------------------------------------------------------------+-------------------------------------------------------------------+ +| | | +|.. code-block:: yaml |.. code-block:: python | +| | | +| # IsaacGymEnvs | # IsaacLab | +| sim: | sim: SimulationCfg = SimulationCfg( | +| | device = "cuda:0" # can be "cpu", "cuda", "cuda:" | +| dt: 0.0166 # 1/60 s | dt=1 / 120, | +| substeps: 2 | # decimation will be set in the task config | +| up_axis: "z" | # up axis will always be Z in isaac sim | +| use_gpu_pipeline: ${eq:${...pipeline},"gpu"} | # use_gpu_pipeline is deduced from the device | +| gravity: [0.0, 0.0, -9.81] | gravity=(0.0, 0.0, -9.81), | +| physx: | physx: PhysxCfg = PhysxCfg( | +| num_threads: ${....num_threads} | # num_threads is no longer needed | +| solver_type: ${....solver_type} | solver_type=1, | +| use_gpu: ${contains:"cuda",${....sim_device}} | # use_gpu is deduced from the device | +| num_position_iterations: 4 | max_position_iteration_count=4, | +| num_velocity_iterations: 0 | max_velocity_iteration_count=0, | +| contact_offset: 0.02 | # moved to actor config | +| rest_offset: 0.001 | # moved to actor config | +| bounce_threshold_velocity: 0.2 | bounce_threshold_velocity=0.2, | +| max_depenetration_velocity: 100.0 | # moved to actor config | +| default_buffer_size_multiplier: 2.0 | # default_buffer_size_multiplier is no longer needed | +| max_gpu_contact_pairs: 1048576 # 1024*1024 | gpu_max_rigid_contact_count=2**23 | +| num_subscenes: ${....num_subscenes} | # num_subscenes is no longer needed | +| contact_collection: 0 | # contact_collection is no longer needed | +| | )) | ++--------------------------------------------------------------+-------------------------------------------------------------------+ + +Scene Config +------------ + +The :class:`~isaaclab.scene.InteractiveSceneCfg` class can be used to specify parameters related to the scene, +such as the number of environments and the spacing between environments. Each task config must have a variable named +``scene`` defined that holds the type :class:`~isaaclab.scene.InteractiveSceneCfg`. + ++--------------------------------------------------------------+-------------------------------------------------------------------+ +| | | +|.. code-block:: yaml |.. code-block:: python | +| | | +| # IsaacGymEnvs | # IsaacLab | +| env: | scene: InteractiveSceneCfg = InteractiveSceneCfg( | +| numEnvs: ${resolve_default:512,${...num_envs}} | num_envs=512, | +| envSpacing: 4.0 | env_spacing=4.0) | ++--------------------------------------------------------------+-------------------------------------------------------------------+ + +Task Config +----------- + +Each environment should specify its own config class that holds task specific parameters, such as the dimensions of the +observation and action buffers. Reward term scaling parameters can also be specified in the config class. + +The following parameters must be set for each environment config: + +.. code-block:: python + + decimation = 2 + episode_length_s = 5.0 + action_space = 1 + observation_space = 4 + state_space = 0 + +Note that the maximum episode length parameter (now ``episode_length_s``) is in seconds instead of steps as it was +in IsaacGymEnvs. To convert between step count to seconds, use the equation: +``episode_length_s = dt * decimation * num_steps`` + + +RL Config Setup +~~~~~~~~~~~~~~~ + +RL config files for the rl_games library can continue to be defined in ``.yaml`` files in Isaac Lab. +Most of the content of the config file can be copied directly from IsaacGymEnvs. +Note that in Isaac Lab, we do not use hydra to resolve relative paths in config files. +Please replace any relative paths such as ``${....device}`` with the actual values of the parameters. + +Additionally, the observation and action clip ranges have been moved to the RL config file. +For any ``clipObservations`` and ``clipActions`` parameters that were defined in the IsaacGymEnvs task config file, +they should be moved to the RL config file in Isaac Lab. + ++--------------------------+----------------------------+ +| | | +| IsaacGymEnvs Task Config | Isaac Lab RL Config | ++--------------------------+----------------------------+ +|.. code-block:: yaml |.. code-block:: yaml | +| | | +| # IsaacGymEnvs | # IsaacLab | +| env: | params: | +| clipObservations: 5.0 | env: | +| clipActions: 1.0 | clip_observations: 5.0 | +| | clip_actions: 1.0 | ++--------------------------+----------------------------+ + +Environment Creation +~~~~~~~~~~~~~~~~~~~~ + +In IsaacGymEnvs, environment creation generally included four components: creating the sim object with ``create_sim()``, +creating the ground plane, importing the assets from MJCF or URDF files, and finally creating the environments +by looping through each environment and adding actors into the environments. + +Isaac Lab no longer requires calling the ``create_sim()`` method to retrieve the sim object. Instead, the simulation +context is retrieved automatically by the framework. It is also no longer required to use the ``sim`` as an +argument for the simulation APIs. + +In replacement of ``create_sim()``, tasks can implement the ``_setup_scene()`` method in Isaac Lab. +This method can be used for adding actors into the scene, adding ground plane, cloning the actors, and +adding any other optional objects into the scene, such as lights. + ++------------------------------------------------------------------------------+------------------------------------------------------------------------+ +| IsaacGymEnvs | Isaac Lab | ++------------------------------------------------------------------------------+------------------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| def create_sim(self): | def _setup_scene(self): | +| # set the up axis to be z-up | self.cartpole = Articulation(self.cfg.robot_cfg) | +| self.up_axis = self.cfg["sim"]["up_axis"] | # add ground plane | +| | spawn_ground_plane(prim_path="/World/ground", cfg=GroundPlaneCfg() | +| self.sim = super().create_sim(self.device_id, self.graphics_device_id, | # clone, filter, and replicate | +| self.physics_engine, self.sim_params) | self.scene.clone_environments(copy_from_source=False) | +| self._create_ground_plane() | self.scene.filter_collisions(global_prim_paths=[]) | +| self._create_envs(self.num_envs, self.cfg["env"]['envSpacing'], | # add articulation to scene | +| int(np.sqrt(self.num_envs))) | self.scene.articulations["cartpole"] = self.cartpole | +| | # add lights | +| | light_cfg = sim_utils.DomeLightCfg(intensity=2000.0) | +| | light_cfg.func("/World/Light", light_cfg) | ++------------------------------------------------------------------------------+------------------------------------------------------------------------+ + + +Ground Plane +------------ + +In Isaac Lab, most of the environment creation process has been simplified into configs with the :class:`~isaaclab.utils.configclass` module. + +The ground plane can be defined using the :class:`~terrains.TerrainImporterCfg` class. + +.. code-block:: python + + from isaaclab.terrains import TerrainImporterCfg + + terrain = TerrainImporterCfg( + prim_path="/World/ground", + terrain_type="plane", + collision_group=-1, + physics_material=sim_utils.RigidBodyMaterialCfg( + friction_combine_mode="multiply", + restitution_combine_mode="multiply", + static_friction=1.0, + dynamic_friction=1.0, + restitution=0.0, + ), + ) + +The terrain can then be added to the scene in ``_setup_scene(self)`` by referencing the ``TerrainImporterCfg`` object: + +.. code-block::python + + def _setup_scene(self): + ... + self.cfg.terrain.num_envs = self.scene.cfg.num_envs + self.cfg.terrain.env_spacing = self.scene.cfg.env_spacing + self._terrain = self.cfg.terrain.class_type(self.cfg.terrain) + + +Actors +------ + +Isaac Lab and Isaac Sim both use the `USD (Universal Scene Description) `_ +library for describing the scene. Assets defined in MJCF and URDF formats can be imported to USD using importer +tools described in the `Importing a New Asset <../how-to/import_new_asset.html>`_ tutorial. + +Each Articulation and Rigid Body actor can also have its own config class. The +:class:`~isaaclab.assets.ArticulationCfg` class can be used to define parameters for articulation actors, +including file path, simulation parameters, actuator properties, and initial states. + +.. code-block::python + + from isaaclab.actuators import ImplicitActuatorCfg + from isaaclab.assets import ArticulationCfg + + CARTPOLE_CFG = ArticulationCfg( + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Robots/Classic/Cartpole/cartpole.usd", + rigid_props=sim_utils.RigidBodyPropertiesCfg( + rigid_body_enabled=True, + max_linear_velocity=1000.0, + max_angular_velocity=1000.0, + max_depenetration_velocity=100.0, + enable_gyroscopic_forces=True, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=False, + solver_position_iteration_count=4, + solver_velocity_iteration_count=0, + sleep_threshold=0.005, + stabilization_threshold=0.001, + ), + ), + init_state=ArticulationCfg.InitialStateCfg( + pos=(0.0, 0.0, 2.0), joint_pos={"slider_to_cart": 0.0, "cart_to_pole": 0.0} + ), + actuators={ + "cart_actuator": ImplicitActuatorCfg( + joint_names_expr=["slider_to_cart"], + effort_limit=400.0, + velocity_limit=100.0, + stiffness=0.0, + damping=10.0, + ), + "pole_actuator": ImplicitActuatorCfg( + joint_names_expr=["cart_to_pole"], effort_limit=400.0, velocity_limit=100.0, stiffness=0.0, damping=0.0 + ), + }, + ) + +Within the :class:`~assets.ArticulationCfg`, the ``spawn`` attribute can be used to add the robot to the scene by +specifying the path to the robot file. In addition, :class:`~isaaclab.sim.schemas.RigidBodyPropertiesCfg` can +be used to specify simulation properties for the rigid bodies in the articulation. +Similarly, the :class:`~isaaclab.sim.schemas.ArticulationRootPropertiesCfg` class can be used to specify +simulation properties for the articulation. Joint properties are now specified as part of the ``actuators`` +dictionary using :class:`~actuators.ImplicitActuatorCfg`. Joints with the same properties can be grouped into +regex expressions or provided as a list of names or expressions. + +Actors are added to the scene by simply calling ``self.cartpole = Articulation(self.cfg.robot_cfg)``, +where ``self.cfg.robot_cfg`` is an :class:`~assets.ArticulationCfg` object. Once initialized, they should also +be added to the :class:`~scene.InteractiveScene` by calling ``self.scene.articulations["cartpole"] = self.cartpole`` +so that the :class:`~scene.InteractiveScene` can traverse through actors in the scene for writing values to the +simulation and resetting. + +Simulation Parameters for Actors +"""""""""""""""""""""""""""""""" + +Some simulation parameters related to Rigid Bodies and Articulations may have different +default values between Isaac Gym Preview Release and Isaac Sim. +It may be helpful to double check the USD assets to ensure that the default values are +applicable for the asset. + +For instance, the following parameters in the ``RigidBodyAPI`` could be different +between Isaac Gym Preview Release and Isaac Sim: + +.. list-table:: + :widths: 50 50 50 + :header-rows: 1 + + * - RigidBodyAPI Parameter + - Default Value in Isaac Sim + - Default Value in Isaac Gym Preview Release + * - Linear Damping + - 0.00 + - 0.00 + * - Angular Damping + - 0.05 + - 0.0 + * - Max Linear Velocity + - inf + - 1000 + * - Max Angular Velocity + - 5729.58008 (degree/s) + - 64.0 (rad/s) + * - Max Contact Impulse + - inf + - 1e32 + +Articulation parameters for the ``JointAPI`` and ``DriveAPI`` could be altered as well. Note +that the Isaac Sim UI assumes the unit of angle to be degrees. It is particularly +worth noting that the ``Damping`` and ``Stiffness`` parameters in the ``DriveAPI`` have the unit +of ``1/deg`` in the Isaac Sim UI but ``1/rad`` in Isaac Gym Preview Release. + +.. list-table:: + :widths: 50 50 50 + :header-rows: 1 + + * - Joint Parameter + - Default Value in Isaac Sim + - Default Value in Isaac Gym Preview Releases + * - Maximum Joint Velocity + - 1000000.0 (deg) + - 100.0 (rad) + + +For more details on performing thorough simulation comparisons between Isaac Gym and Isaac Lab, +please refer to the :ref:`migrating-from-isaacgymenvs-comparing-simulation` section. + + +Cloner +------ + +Isaac Sim introduced a concept of ``Cloner``, which is a class designed for replication during the scene creation process. +In IsaacGymEnvs, scenes had to be created by looping through the number of environments. +Within each iteration, actors were added to each environment and their handles had to be cached. +Isaac Lab eliminates the need for looping through the environments by using the ``Cloner`` APIs. +The scene creation process is as follow: + +#. Construct a single environment (what the scene would look like if number of environments = 1) +#. Call ``clone_environments()`` to replicate the single environment +#. Call ``filter_collisions()`` to filter out collision between environments (if required) + + +.. code-block:: python + + # construct a single environment with the Cartpole robot + self.cartpole = Articulation(self.cfg.robot_cfg) + # clone the environment + self.scene.clone_environments(copy_from_source=False) + # filter collisions + self.scene.filter_collisions(global_prim_paths=[self.cfg.terrain.prim_path]) + + +Accessing States from Simulation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +APIs for accessing physics states in Isaac Lab require the creation of an :class:`~assets.Articulation` or :class:`~assets.RigidObject` +object. Multiple objects can be initialized for different articulations or rigid bodies in the scene by defining +corresponding :class:`~assets.ArticulationCfg` or :class:`~assets.RigidObjectCfg` config as outlined in the section above. +This approach eliminates the need of retrieving body handles to slice states for specific bodies in the scene. + + +.. code-block:: python + + self._robot = Articulation(self.cfg.robot) + self._cabinet = Articulation(self.cfg.cabinet) + self._object = RigidObject(self.cfg.object_cfg) + + +We have also removed ``acquire`` and ``refresh`` APIs in Isaac Lab. Physics states can be directly applied or retrieved +using APIs defined for the articulations and rigid objects. + +APIs provided in Isaac Lab no longer require explicit wrapping and un-wrapping of underlying buffers. +APIs can now work with tensors directly for reading and writing data. + ++------------------------------------------------------------------+-----------------------------------------------------------------+ +| IsaacGymEnvs | Isaac Lab | ++------------------------------------------------------------------+-----------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| dof_state_tensor = self.gym.acquire_dof_state_tensor(self.sim) | self.joint_pos = self._robot.data.joint_pos | +| self.dof_state = gymtorch.wrap_tensor(dof_state_tensor) | self.joint_vel = self._robot.data.joint_vel | +| self.gym.refresh_dof_state_tensor(self.sim) | | ++------------------------------------------------------------------+-----------------------------------------------------------------+ + +Note some naming differences between APIs in Isaac Gym Preview Release and Isaac Lab. Most ``dof`` related APIs have been +named to ``joint`` in Isaac Lab. +APIs in Isaac Lab also no longer follow the explicit ``_tensors`` or ``_tensor_indexed`` suffixes in naming. +Indexed versions of APIs now happen implicitly through the optional ``indices`` parameter. + +Most APIs in Isaac Lab also provide +the option to specify an ``indices`` parameter, which can be used when reading or writing data for a subset +of environments. Note that when setting states with the ``indices`` parameter, the shape of the states buffer +should match with the dimension of the ``indices`` list. + ++---------------------------------------------------------------------------+---------------------------------------------------------------+ +| IsaacGymEnvs | Isaac Lab | ++---------------------------------------------------------------------------+---------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| env_ids_int32 = env_ids.to(dtype=torch.int32) | self._robot.write_joint_state_to_sim(joint_pos, joint_vel, | +| self.gym.set_dof_state_tensor_indexed(self.sim, | joint_ids, env_ids) | +| gymtorch.unwrap_tensor(self.dof_state), | | +| gymtorch.unwrap_tensor(env_ids_int32), len(env_ids_int32)) | | ++---------------------------------------------------------------------------+---------------------------------------------------------------+ + +Quaternion Convention +--------------------- + +Isaac Lab and Isaac Sim both adopt ``wxyz`` as the quaternion convention. However, the quaternion +convention used in Isaac Gym Preview Release was ``xyzw``. +Remember to switch all quaternions to use the ``xyzw`` convention when working indexing rotation data. +Similarly, please ensure all quaternions are in ``wxyz`` before passing them to Isaac Lab APIs. + + +Articulation Joint Order +------------------------ + +Physics simulation in Isaac Sim and Isaac Lab assumes a breadth-first +ordering for the joints in a given kinematic tree. +However, Isaac Gym Preview Release assumed a depth-first ordering for joints in the kinematic tree. +This means that indexing joints based on their ordering may be different in IsaacGymEnvs and Isaac Lab. + +In Isaac Lab, the list of joint names can be retrieved with ``Articulation.data.joint_names``, which will +also correspond to the ordering of the joints in the Articulation. + + +Creating a New Environment +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Each environment in Isaac Lab should be in its own directory following this structure: + +.. code-block:: none + + my_environment/ + - agents/ + - __init__.py + - rl_games_ppo_cfg.py + - __init__.py + my_env.py + +* ``my_environment`` is the root directory of the task. +* ``my_environment/agents`` is the directory containing all RL config files for the task. Isaac Lab supports multiple RL libraries that can each have its own individual config file. +* ``my_environment/__init__.py`` is the main file that registers the environment with the Gymnasium interface. This allows the training and inferencing scripts to find the task by its name. The content of this file should be as follow: + +.. code-block:: python + + import gymnasium as gym + + from . import agents + from .cartpole_env import CartpoleEnv, CartpoleEnvCfg + + ## + # Register Gym environments. + ## + + gym.register( + id="Isaac-Cartpole-Direct-v0", + entry_point="isaaclab_tasks.direct_workflow.cartpole:CartpoleEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": CartpoleEnvCfg, + "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml" + }, + ) + +* ``my_environment/my_env.py`` is the main python script that implements the task logic and task config class for the environment. + + +Task Logic +~~~~~~~~~~ + +In Isaac Lab, the ``post_physics_step`` function has been moved to the framework in the base class. +Tasks are not required to implement this method, but can choose to override it if a different workflow is desired. + +By default, Isaac Lab follows the following flow in logic: + ++----------------------------------+----------------------------------+ +| IsaacGymEnvs | Isaac Lab | ++----------------------------------+----------------------------------+ +|.. code-block:: none |.. code-block:: none | +| | | +| pre_physics_step | pre_physics_step | +| |-- apply_action | |-- _pre_physics_step(action)| +| | |-- _apply_action() | +| | | +| post_physics_step | post_physics_step | +| |-- reset_idx() | |-- _get_dones() | +| |-- compute_observation() | |-- _get_rewards() | +| |-- compute_reward() | |-- _reset_idx() | +| | |-- _get_observations() | ++----------------------------------+----------------------------------+ + +In Isaac Lab, we also separate the ``pre_physics_step`` API for processing actions from the policy with +the ``apply_action`` API, which sets the actions into the simulation. This provides more flexibility in controlling +when actions should be written to simulation when ``decimation`` is used. +``pre_physics_step`` will be called once per step before stepping simulation. +``apply_actions`` will be called ``decimation`` number of times for each RL step, once before each simulation step call. + +With this approach, resets are performed based on actions from the current step instead of the previous step. +Observations will also be computed with the correct states after resets. + +We have also performed some renamings of APIs: + +* ``create_sim(self)`` --> ``_setup_scene(self)`` +* ``pre_physics_step(self, actions)`` --> ``_pre_physics_step(self, actions)`` and ``_apply_action(self)`` +* ``reset_idx(self, env_ids)`` --> ``_reset_idx(self, env_ids)`` +* ``compute_observations(self)`` --> ``_get_observations(self)`` - ``_get_observations()`` should now return a dictionary ``{"policy": obs}`` +* ``compute_reward(self)`` --> ``_get_rewards(self)`` - ``_get_rewards()`` should now return the reward buffer +* ``post_physics_step(self)`` --> moved to the base class +* In addition, Isaac Lab requires the implementation of ``_is_done(self)``, which should return two buffers: the ``reset`` buffer and the ``time_out`` buffer. + + +Putting It All Together +~~~~~~~~~~~~~~~~~~~~~~~ + +The Cartpole environment is shown here in completion to fully show the comparison between the IsaacGymEnvs implementation and the Isaac Lab implementation. + +Task Config +----------- + ++--------------------------------------------------------+---------------------------------------------------------------------+ +| IsaacGymEnvs | Isaac Lab | ++--------------------------------------------------------+---------------------------------------------------------------------+ +|.. code-block:: yaml |.. code-block:: python | +| | | +| # used to create the object | @configclass | +| name: Cartpole | class CartpoleEnvCfg(DirectRLEnvCfg): | +| | | +| physics_engine: ${..physics_engine} | # simulation | +| | sim: SimulationCfg = SimulationCfg(dt=1 / 120) | +| # if given, will override the device setting in gym. | # robot | +| env: | robot_cfg: ArticulationCfg = CARTPOLE_CFG.replace( | +| numEnvs: ${resolve_default:512,${...num_envs}} | prim_path="/World/envs/env_.*/Robot") | +| envSpacing: 4.0 | cart_dof_name = "slider_to_cart" | +| resetDist: 3.0 | pole_dof_name = "cart_to_pole" | +| maxEffort: 400.0 | # scene | +| | scene: InteractiveSceneCfg = InteractiveSceneCfg( | +| clipObservations: 5.0 | num_envs=4096, env_spacing=4.0, replicate_physics=True) | +| clipActions: 1.0 | # env | +| | decimation = 2 | +| asset: | episode_length_s = 5.0 | +| assetRoot: "../../assets" | action_scale = 100.0 # [N] | +| assetFileName: "urdf/cartpole.urdf" | action_space = 1 | +| | observation_space = 4 | +| enableCameraSensors: False | state_space = 0 | +| | # reset | +| sim: | max_cart_pos = 3.0 | +| dt: 0.0166 # 1/60 s | initial_pole_angle_range = [-0.25, 0.25] | +| substeps: 2 | # reward scales | +| up_axis: "z" | rew_scale_alive = 1.0 | +| use_gpu_pipeline: ${eq:${...pipeline},"gpu"} | rew_scale_terminated = -2.0 | +| gravity: [0.0, 0.0, -9.81] | rew_scale_pole_pos = -1.0 | +| physx: | rew_scale_cart_vel = -0.01 | +| num_threads: ${....num_threads} | rew_scale_pole_vel = -0.005 | +| solver_type: ${....solver_type} | | +| use_gpu: ${contains:"cuda",${....sim_device}} | | +| num_position_iterations: 4 | | +| num_velocity_iterations: 0 | | +| contact_offset: 0.02 | | +| rest_offset: 0.001 | | +| bounce_threshold_velocity: 0.2 | | +| max_depenetration_velocity: 100.0 | | +| default_buffer_size_multiplier: 2.0 | | +| max_gpu_contact_pairs: 1048576 # 1024*1024 | | +| num_subscenes: ${....num_subscenes} | | +| contact_collection: 0 | | ++--------------------------------------------------------+---------------------------------------------------------------------+ + + + +Task Setup +---------- + +Isaac Lab no longer requires pre-initialization of buffers through the ``acquire_*`` APIs that were used in IsaacGymEnvs. +It is also no longer necessary to ``wrap`` and ``unwrap`` tensors. + ++-------------------------------------------------------------------------+-------------------------------------------------------------+ +| IsaacGymEnvs | Isaac Lab | ++-------------------------------------------------------------------------+-------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| class Cartpole(VecTask): | class CartpoleEnv(DirectRLEnv): | +| | cfg: CartpoleEnvCfg | +| def __init__(self, cfg, rl_device, sim_device, graphics_device_id, | def __init__(self, cfg: CartpoleEnvCfg, | +| headless, virtual_screen_capture, force_render): | render_mode: str | None = None, **kwargs): | +| self.cfg = cfg | | +| | super().__init__(cfg, render_mode, **kwargs) | +| self.reset_dist = self.cfg["env"]["resetDist"] | | +| | self._cart_dof_idx, _ = self.cartpole.find_joints( | +| self.max_push_effort = self.cfg["env"]["maxEffort"] | self.cfg.cart_dof_name) | +| self.max_episode_length = 500 | self._pole_dof_idx, _ = self.cartpole.find_joints( | +| | self.cfg.pole_dof_name) | +| self.cfg["env"]["numObservations"] = 4 | self.action_scale = self.cfg.action_scale | +| self.cfg["env"]["numActions"] = 1 | | +| | self.joint_pos = self.cartpole.data.joint_pos | +| super().__init__(config=self.cfg, | self.joint_vel = self.cartpole.data.joint_vel | +| rl_device=rl_device, sim_device=sim_device, | | +| graphics_device_id=graphics_device_id, headless=headless, | | +| virtual_screen_capture=virtual_screen_capture, | | +| force_render=force_render) | | +| | | +| dof_state_tensor = self.gym.acquire_dof_state_tensor(self.sim) | | +| self.dof_state = gymtorch.wrap_tensor(dof_state_tensor) | | +| self.dof_pos = self.dof_state.view( | | +| self.num_envs, self.num_dof, 2)[..., 0] | | +| self.dof_vel = self.dof_state.view( | | +| self.num_envs, self.num_dof, 2)[..., 1] | | ++-------------------------------------------------------------------------+-------------------------------------------------------------+ + + + +Scene Setup +----------- + +Scene setup is now done through the ``Cloner`` API and by specifying actor attributes in config objects. +This eliminates the need to loop through the number of environments to set up the environments and avoids +the need to set simulation parameters for actors in the task implementation. + ++------------------------------------------------------------------------+---------------------------------------------------------------------+ +| IsaacGymEnvs | Isaac Lab | ++------------------------------------------------------------------------+---------------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| def create_sim(self): | def _setup_scene(self): | +| # set the up axis to be z-up given that assets are y-up by default | self.cartpole = Articulation(self.cfg.robot_cfg) | +| self.up_axis = self.cfg["sim"]["up_axis"] | # add ground plane | +| | spawn_ground_plane(prim_path="/World/ground", | +| self.sim = super().create_sim(self.device_id, | cfg=GroundPlaneCfg()) | +| self.graphics_device_id, self.physics_engine, | # clone, filter, and replicate | +| self.sim_params) | self.scene.clone_environments( | +| self._create_ground_plane() | copy_from_source=False) | +| self._create_envs(self.num_envs, | self.scene.filter_collisions( | +| self.cfg["env"]['envSpacing'], | global_prim_paths=[]) | +| int(np.sqrt(self.num_envs))) | # add articulation to scene | +| | self.scene.articulations["cartpole"] = self.cartpole | +| def _create_ground_plane(self): | # add lights | +| plane_params = gymapi.PlaneParams() | light_cfg = sim_utils.DomeLightCfg( | +| # set the normal force to be z dimension | intensity=2000.0, color=(0.75, 0.75, 0.75)) | +| plane_params.normal = (gymapi.Vec3(0.0, 0.0, 1.0) | light_cfg.func("/World/Light", light_cfg) | +| if self.up_axis == 'z' | | +| else gymapi.Vec3(0.0, 1.0, 0.0)) | CARTPOLE_CFG = ArticulationCfg( | +| self.gym.add_ground(self.sim, plane_params) | spawn=sim_utils.UsdFileCfg( | +| | usd_path=f"{ISAACLAB_NUCLEUS_DIR}/.../cartpole.usd", | +| def _create_envs(self, num_envs, spacing, num_per_row): | rigid_props=sim_utils.RigidBodyPropertiesCfg( | +| # define plane on which environments are initialized | rigid_body_enabled=True, | +| lower = (gymapi.Vec3(0.5 * -spacing, -spacing, 0.0) | max_linear_velocity=1000.0, | +| if self.up_axis == 'z' | max_angular_velocity=1000.0, | +| else gymapi.Vec3(0.5 * -spacing, 0.0, -spacing)) | max_depenetration_velocity=100.0, | +| upper = gymapi.Vec3(0.5 * spacing, spacing, spacing) | enable_gyroscopic_forces=True, | +| | ), | +| asset_root = os.path.join(os.path.dirname( | articulation_props=sim_utils.ArticulationRootPropertiesCfg( | +| os.path.abspath(__file__)), "../../assets") | enabled_self_collisions=False, | +| asset_file = "urdf/cartpole.urdf" | solver_position_iteration_count=4, | +| | solver_velocity_iteration_count=0, | +| if "asset" in self.cfg["env"]: | sleep_threshold=0.005, | +| asset_root = os.path.join(os.path.dirname( | stabilization_threshold=0.001, | +| os.path.abspath(__file__)), | ), | +| self.cfg["env"]["asset"].get("assetRoot", asset_root)) | ), | +| asset_file = self.cfg["env"]["asset"].get( | init_state=ArticulationCfg.InitialStateCfg( | +| "assetFileName", asset_file) | pos=(0.0, 0.0, 2.0), | +| | joint_pos={"slider_to_cart": 0.0, "cart_to_pole": 0.0} | +| asset_path = os.path.join(asset_root, asset_file) | ), | +| asset_root = os.path.dirname(asset_path) | actuators={ | +| asset_file = os.path.basename(asset_path) | "cart_actuator": ImplicitActuatorCfg( | +| | joint_names_expr=["slider_to_cart"], | +| asset_options = gymapi.AssetOptions() | effort_limit_sim=400.0, | +| asset_options.fix_base_link = True | velocity_limit_sim=100.0, | +| cartpole_asset = self.gym.load_asset(self.sim, | stiffness=0.0, | +| asset_root, asset_file, asset_options) | damping=10.0, | +| self.num_dof = self.gym.get_asset_dof_count( | ), | +| cartpole_asset) | "pole_actuator": ImplicitActuatorCfg( | +| | joint_names_expr=["cart_to_pole"], | +| pose = gymapi.Transform() | effort_limit_sim=400.0, velocity_limit_sim=100.0, | +| if self.up_axis == 'z': | stiffness=0.0, damping=0.0 | +| pose.p.z = 2.0 | ), | +| pose.r = gymapi.Quat(0.0, 0.0, 0.0, 1.0) | }, | +| else: | ) | +| pose.p.y = 2.0 | | +| pose.r = gymapi.Quat( | | +| -np.sqrt(2)/2, 0.0, 0.0, np.sqrt(2)/2) | | +| | | +| self.cartpole_handles = [] | | +| self.envs = [] | | +| for i in range(self.num_envs): | | +| # create env instance | | +| env_ptr = self.gym.create_env( | | +| self.sim, lower, upper, num_per_row | | +| ) | | +| cartpole_handle = self.gym.create_actor( | | +| env_ptr, cartpole_asset, pose, | | +| "cartpole", i, 1, 0) | | +| | | +| dof_props = self.gym.get_actor_dof_properties( | | +| env_ptr, cartpole_handle) | | +| dof_props['driveMode'][0] = gymapi.DOF_MODE_EFFORT | | +| dof_props['driveMode'][1] = gymapi.DOF_MODE_NONE | | +| dof_props['stiffness'][:] = 0.0 | | +| dof_props['damping'][:] = 0.0 | | +| self.gym.set_actor_dof_properties(env_ptr, c | | +| artpole_handle, dof_props) | | +| | | +| self.envs.append(env_ptr) | | +| self.cartpole_handles.append(cartpole_handle) | | ++------------------------------------------------------------------------+---------------------------------------------------------------------+ + + +Pre and Post Physics Step +------------------------- + +In IsaacGymEnvs, due to limitations of the GPU APIs, observations had stale data when environments had to perform resets. +This restriction has been eliminated in Isaac Lab, and thus, tasks follow the correct workflow of applying actions, stepping simulation, +collecting states, computing dones, calculating rewards, performing resets, and finally computing observations. +This workflow is done automatically by the framework such that a ``post_physics_step`` API is not required in the task. +However, individual tasks can override the ``step()`` API to control the workflow. + ++------------------------------------------------------------------+-------------------------------------------------------------+ +| IsaacGymEnvs | IsaacLab | ++------------------------------------------------------------------+-------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| def pre_physics_step(self, actions): | def _pre_physics_step(self, actions: torch.Tensor) -> None: | +| actions_tensor = torch.zeros( | self.actions = self.action_scale * actions | +| self.num_envs * self.num_dof, | | +| device=self.device, dtype=torch.float) | def _apply_action(self) -> None: | +| actions_tensor[::self.num_dof] = actions.to( | self.cartpole.set_joint_effort_target( | +| self.device).squeeze() * self.max_push_effort | self.actions, joint_ids=self._cart_dof_idx) | +| forces = gymtorch.unwrap_tensor(actions_tensor) | | +| self.gym.set_dof_actuation_force_tensor( | | +| self.sim, forces) | | +| | | +| def post_physics_step(self): | | +| self.progress_buf += 1 | | +| | | +| env_ids = self.reset_buf.nonzero( | | +| as_tuple=False).squeeze(-1) | | +| if len(env_ids) > 0: | | +| self.reset_idx(env_ids) | | +| | | +| self.compute_observations() | | +| self.compute_reward() | | ++------------------------------------------------------------------+-------------------------------------------------------------+ + + +Dones and Resets +---------------- + +In Isaac Lab, ``dones`` are computed in the ``_get_dones()`` method and should return two variables: ``resets`` and ``time_out``. +Tracking of the ``progress_buf`` has been moved to the base class and is now automatically incremented and reset by the framework. +The ``progress_buf`` variable has also been renamed to ``episode_length_buf``. + ++-----------------------------------------------------------------------+---------------------------------------------------------------------------+ +| IsaacGymEnvs | Isaac Lab | ++-----------------------------------------------------------------------+---------------------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| def reset_idx(self, env_ids): | def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: | +| positions = 0.2 * (torch.rand((len(env_ids), self.num_dof), | self.joint_pos = self.cartpole.data.joint_pos | +| device=self.device) - 0.5) | self.joint_vel = self.cartpole.data.joint_vel | +| velocities = 0.5 * (torch.rand((len(env_ids), self.num_dof), | | +| device=self.device) - 0.5) | time_out = self.episode_length_buf >= self.max_episode_length - 1 | +| | out_of_bounds = torch.any(torch.abs( | +| self.dof_pos[env_ids, :] = positions[:] | self.joint_pos[:, self._cart_dof_idx]) > self.cfg.max_cart_pos, | +| self.dof_vel[env_ids, :] = velocities[:] | dim=1) | +| | out_of_bounds = out_of_bounds | torch.any( | +| env_ids_int32 = env_ids.to(dtype=torch.int32) | torch.abs(self.joint_pos[:, self._pole_dof_idx]) > math.pi / 2, | +| self.gym.set_dof_state_tensor_indexed(self.sim, | dim=1) | +| gymtorch.unwrap_tensor(self.dof_state), | return out_of_bounds, time_out | +| gymtorch.unwrap_tensor(env_ids_int32), len(env_ids_int32)) | | +| self.reset_buf[env_ids] = 0 | def _reset_idx(self, env_ids: Sequence[int] | None): | +| self.progress_buf[env_ids] = 0 | if env_ids is None: | +| | env_ids = self.cartpole._ALL_INDICES | +| | super()._reset_idx(env_ids) | +| | | +| | joint_pos = self.cartpole.data.default_joint_pos[env_ids] | +| | joint_pos[:, self._pole_dof_idx] += sample_uniform( | +| | self.cfg.initial_pole_angle_range[0] * math.pi, | +| | self.cfg.initial_pole_angle_range[1] * math.pi, | +| | joint_pos[:, self._pole_dof_idx].shape, | +| | joint_pos.device, | +| | ) | +| | joint_vel = self.cartpole.data.default_joint_vel[env_ids] | +| | | +| | default_root_state = self.cartpole.data.default_root_state[env_ids] | +| | default_root_state[:, :3] += self.scene.env_origins[env_ids] | +| | | +| | self.joint_pos[env_ids] = joint_pos | +| | | +| | self.cartpole.write_root_pose_to_sim( | +| | default_root_state[:, :7], env_ids) | +| | self.cartpole.write_root_velocity_to_sim( | +| | default_root_state[:, 7:], env_ids) | +| | self.cartpole.write_joint_state_to_sim( | +| | joint_pos, joint_vel, None, env_ids) | ++-----------------------------------------------------------------------+---------------------------------------------------------------------------+ + + +Observations +------------ + +In Isaac Lab, the ``_get_observations()`` API should now return a dictionary containing the ``policy`` key with the observation +buffer as the value. +For asymmetric policies, the dictionary should also include a ``critic`` key that holds the state buffer. + ++--------------------------------------------------------------------------+---------------------------------------------------------------------------------------+ +| IsaacGymEnvs | Isaac Lab | ++--------------------------------------------------------------------------+---------------------------------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| def compute_observations(self, env_ids=None): | def _get_observations(self) -> dict: | +| if env_ids is None: | obs = torch.cat( | +| env_ids = np.arange(self.num_envs) | ( | +| | self.joint_pos[:, self._pole_dof_idx[0]], | +| self.gym.refresh_dof_state_tensor(self.sim) | self.joint_vel[:, self._pole_dof_idx[0]], | +| | self.joint_pos[:, self._cart_dof_idx[0]], | +| self.obs_buf[env_ids, 0] = self.dof_pos[env_ids, 0] | self.joint_vel[:, self._cart_dof_idx[0]], | +| self.obs_buf[env_ids, 1] = self.dof_vel[env_ids, 0] | ), | +| self.obs_buf[env_ids, 2] = self.dof_pos[env_ids, 1] | dim=-1, | +| self.obs_buf[env_ids, 3] = self.dof_vel[env_ids, 1] | ) | +| | observations = {"policy": obs} | +| return self.obs_buf | return observations | ++--------------------------------------------------------------------------+---------------------------------------------------------------------------------------+ + + +Rewards +------- + +In Isaac Lab, the reward method ``_get_rewards`` should return the reward buffer as a return value. +Similar to IsaacGymEnvs, computations in the reward function can also be performed using pytorch jit +by adding the ``@torch.jit.script`` annotation. + ++--------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ +| IsaacGymEnvs | Isaac Lab | ++--------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| def compute_reward(self): | def _get_rewards(self) -> torch.Tensor: | +| # retrieve environment observations from buffer | total_reward = compute_rewards( | +| pole_angle = self.obs_buf[:, 2] | self.cfg.rew_scale_alive, | +| pole_vel = self.obs_buf[:, 3] | self.cfg.rew_scale_terminated, | +| cart_vel = self.obs_buf[:, 1] | self.cfg.rew_scale_pole_pos, | +| cart_pos = self.obs_buf[:, 0] | self.cfg.rew_scale_cart_vel, | +| | self.cfg.rew_scale_pole_vel, | +| self.rew_buf[:], self.reset_buf[:] = compute_cartpole_reward( | self.joint_pos[:, self._pole_dof_idx[0]], | +| pole_angle, pole_vel, cart_vel, cart_pos, | self.joint_vel[:, self._pole_dof_idx[0]], | +| self.reset_dist, self.reset_buf, | self.joint_pos[:, self._cart_dof_idx[0]], | +| self.progress_buf, self.max_episode_length | self.joint_vel[:, self._cart_dof_idx[0]], | +| ) | self.reset_terminated, | +| | ) | +| @torch.jit.script | return total_reward | +| def compute_cartpole_reward(pole_angle, pole_vel, | | +| cart_vel, cart_pos, | @torch.jit.script | +| reset_dist, reset_buf, | def compute_rewards( | +| progress_buf, max_episode_length): | rew_scale_alive: float, | +| | rew_scale_terminated: float, | +| reward = (1.0 - pole_angle * pole_angle - | rew_scale_pole_pos: float, | +| 0.01 * torch.abs(cart_vel) - | rew_scale_cart_vel: float, | +| 0.005 * torch.abs(pole_vel)) | rew_scale_pole_vel: float, | +| | pole_pos: torch.Tensor, | +| # adjust reward for reset agents | pole_vel: torch.Tensor, | +| reward = torch.where(torch.abs(cart_pos) > reset_dist, | cart_pos: torch.Tensor, | +| torch.ones_like(reward) * -2.0, reward) | cart_vel: torch.Tensor, | +| reward = torch.where(torch.abs(pole_angle) > np.pi / 2, | reset_terminated: torch.Tensor, | +| torch.ones_like(reward) * -2.0, reward) | ): | +| | rew_alive = rew_scale_alive * (1.0 - reset_terminated.float()) | +| reset = torch.where(torch.abs(cart_pos) > reset_dist, | rew_termination = rew_scale_terminated * reset_terminated.float() | +| torch.ones_like(reset_buf), reset_buf) | rew_pole_pos = rew_scale_pole_pos * torch.sum( | +| reset = torch.where(torch.abs(pole_angle) > np.pi / 2, | torch.square(pole_pos), dim=-1) | +| torch.ones_like(reset_buf), reset_buf) | rew_cart_vel = rew_scale_cart_vel * torch.sum( | +| reset = torch.where(progress_buf >= max_episode_length - 1, | torch.abs(cart_vel), dim=-1) | +| torch.ones_like(reset_buf), reset) | rew_pole_vel = rew_scale_pole_vel * torch.sum( | +| | torch.abs(pole_vel), dim=-1) | +| | total_reward = (rew_alive + rew_termination | +| | + rew_pole_pos + rew_cart_vel + rew_pole_vel) | +| | return total_reward | ++--------------------------------------------------------------------------+----------------------------------------------------------------------------------------+ + + + +Launching Training +~~~~~~~~~~~~~~~~~~ + +To launch a training in Isaac Lab, use the command: + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rl_games --task=Isaac-Cartpole-Direct-v0 + +Launching Inferencing +~~~~~~~~~~~~~~~~~~~~~ + +To launch inferencing in Isaac Lab, use the command: + +.. code-block:: bash + + ./isaaclab.sh play --rl_library rl_games --task=Isaac-Cartpole-Direct-v0 --num_envs=25 --checkpoint= + + +Additional Resources +~~~~~~~~~~~~~~~~~~~~ + +.. toctree:: + :maxdepth: 1 + + comparing_simulation_isaacgym + + +.. _IsaacGymEnvs: https://github.com/isaac-sim/IsaacGymEnvs +.. _Isaac Gym Preview Release: https://developer.nvidia.com/isaac-gym +.. _release notes: https://github.com/isaac-sim/IsaacLab/releases diff --git a/simulation/modules/IsaacLab/docs/source/migration/migrating_from_omniisaacgymenvs.rst b/simulation/modules/IsaacLab/docs/source/migration/migrating_from_omniisaacgymenvs.rst new file mode 100644 index 0000000000000000000000000000000000000000..06b617930130ca9639d038b4db41a38fe30ee9ea --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/migration/migrating_from_omniisaacgymenvs.rst @@ -0,0 +1,999 @@ +.. _migrating-from-omniisaacgymenvs: + +From OmniIsaacGymEnvs +===================== + +.. currentmodule:: isaaclab + + +`OmniIsaacGymEnvs`_ was a reinforcement learning framework using the Isaac Sim platform. +Features from OmniIsaacGymEnvs have been integrated into the Isaac Lab framework. +We have updated OmniIsaacGymEnvs to Isaac Sim version 4.0.0 to support the migration process +to Isaac Lab. Moving forward, OmniIsaacGymEnvs will be deprecated and future development +will continue in Isaac Lab. + +.. note:: + + The following changes are with respect to Isaac Lab 1.0 release. Please refer to the `release notes`_ for any changes + in the future releases. + +Task Config Setup +~~~~~~~~~~~~~~~~~ + +In OmniIsaacGymEnvs, task config files were defined in ``.yaml`` format. With Isaac Lab, configs are now specified +using a specialized Python class :class:`~isaaclab.utils.configclass`. The +:class:`~isaaclab.utils.configclass` module provides a wrapper on top of Python's ``dataclasses`` module. +Each environment should specify its own config class annotated by ``@configclass`` that inherits from the +:class:`~envs.DirectRLEnvCfg` class, which can include simulation parameters, environment scene parameters, +robot parameters, and task-specific parameters. + +Below is an example skeleton of a task config class: + +.. code-block:: python + + from isaaclab.envs import DirectRLEnvCfg + from isaaclab.scene import InteractiveSceneCfg + from isaaclab.sim import SimulationCfg + + @configclass + class MyEnvCfg(DirectRLEnvCfg): + # simulation + sim: SimulationCfg = SimulationCfg() + # robot + robot_cfg: ArticulationCfg = ArticulationCfg() + # scene + scene: InteractiveSceneCfg = InteractiveSceneCfg() + # env + decimation = 2 + episode_length_s = 5.0 + action_space = 1 + observation_space = 4 + state_space = 0 + # task-specific parameters + ... + +Simulation Config +----------------- + +Simulation related parameters are defined as part of the :class:`~isaaclab.sim.SimulationCfg` class, +which is a :class:`~isaaclab.utils.configclass` module that holds simulation parameters such as ``dt``, +``device``, and ``gravity``. Each task config must have a variable named ``sim`` defined that holds the type +:class:`~isaaclab.sim.SimulationCfg`. + +Simulation parameters for articulations and rigid bodies such as ``num_position_iterations``, ``num_velocity_iterations``, +``contact_offset``, ``rest_offset``, ``bounce_threshold_velocity``, ``max_depenetration_velocity`` can all +be specified on a per-actor basis in the config class for each individual articulation and rigid body. + +When running simulation on the GPU, buffers in PhysX require pre-allocation for computing and storing +information such as contacts, collisions and aggregate pairs. These buffers may need to be adjusted +depending on the complexity of the environment, the number of expected contacts and collisions, +and the number of actors in the environment. The :class:`~isaaclab.sim.PhysxCfg` class provides access +for setting the GPU buffer dimensions. + ++--------------------------------------------------+---------------------------------------------------------------+ +|| || | +|| || | +|| # OmniIsaacGymEnvs || # IsaacLab | +|| sim: || sim: SimulationCfg = SimulationCfg( | +|| || device = "cuda:0" # can be "cpu", "cuda", "cuda:" | +|| dt: 0.0083 # 1/120 s || dt=1 / 120, | +|| use_gpu_pipeline: ${eq:${...pipeline},"gpu"} || # use_gpu_pipeline is deduced from the device | +|| use_fabric: True || use_fabric=True, | +|| enable_scene_query_support: False || enable_scene_query_support=False, | +|| disable_contact_processing: False || | +|| gravity: [0.0, 0.0, -9.81] || gravity=(0.0, 0.0, -9.81), | +|| || | +|| default_physics_material: || physics_material=RigidBodyMaterialCfg( | +|| static_friction: 1.0 || static_friction=1.0, | +|| dynamic_friction: 1.0 || dynamic_friction=1.0, | +|| restitution: 0.0 || restitution=0.0 | +|| || ) | +|| physx: || physx: PhysxCfg = PhysxCfg( | +|| worker_thread_count: ${....num_threads} || # worker_thread_count is no longer needed | +|| solver_type: ${....solver_type} || solver_type=1, | +|| use_gpu: ${contains:"cuda",${....sim_device}} || # use_gpu is deduced from the device | +|| solver_position_iteration_count: 4 || max_position_iteration_count=4, | +|| solver_velocity_iteration_count: 0 || max_velocity_iteration_count=0, | +|| contact_offset: 0.02 || # moved to actor config | +|| rest_offset: 0.001 || # moved to actor config | +|| bounce_threshold_velocity: 0.2 || bounce_threshold_velocity=0.2, | +|| friction_offset_threshold: 0.04 || friction_offset_threshold=0.04, | +|| friction_correlation_distance: 0.025 || friction_correlation_distance=0.025, | +|| enable_sleeping: True || # enable_sleeping is no longer needed | +|| enable_stabilization: True || enable_stabilization=True, | +|| max_depenetration_velocity: 100.0 || # moved to RigidBodyPropertiesCfg | +|| || | +|| gpu_max_rigid_contact_count: 524288 || gpu_max_rigid_contact_count=2**23, | +|| gpu_max_rigid_patch_count: 81920 || gpu_max_rigid_patch_count=5 * 2**15, | +|| gpu_found_lost_pairs_capacity: 1024 || gpu_found_lost_pairs_capacity=2**21, | +|| gpu_found_lost_aggregate_pairs_capacity: 262144 || gpu_found_lost_aggregate_pairs_capacity=2**25, | +|| gpu_total_aggregate_pairs_capacity: 1024 || gpu_total_aggregate_pairs_capacity=2**21, | +|| gpu_heap_capacity: 67108864 || gpu_heap_capacity=2**26, | +|| gpu_temp_buffer_capacity: 16777216 || gpu_temp_buffer_capacity=2**24, | +|| gpu_max_num_partitions: 8 || gpu_max_num_partitions=8, | +|| gpu_max_soft_body_contacts: 1048576 || gpu_max_soft_body_contacts=2**20, | +|| gpu_max_particle_contacts: 1048576 || gpu_max_particle_contacts=2**20, | +|| || ) | +|| || ) | ++--------------------------------------------------+---------------------------------------------------------------+ + +Parameters such as ``add_ground_plane`` and ``add_distant_light`` are now part of the task logic when creating the scene. +``enable_cameras`` is now a command line argument ``--enable_cameras`` that can be passed directly to the training script. + + +Scene Config +------------ + +The :class:`~isaaclab.scene.InteractiveSceneCfg` class can be used to specify parameters related to the scene, +such as the number of environments and the spacing between environments. Each task config must have a variable named +``scene`` defined that holds the type :class:`~isaaclab.scene.InteractiveSceneCfg`. + ++--------------------------------------------------------------+-------------------------------------------------------------------+ +| | | +|.. code-block:: yaml |.. code-block:: python | +| | | +| # OmniIsaacGymEnvs | # IsaacLab | +| env: | scene: InteractiveSceneCfg = InteractiveSceneCfg( | +| numEnvs: ${resolve_default:512,${...num_envs}} | num_envs=512, | +| envSpacing: 4.0 | env_spacing=4.0) | ++--------------------------------------------------------------+-------------------------------------------------------------------+ + +Task Config +----------- + +Each environment should specify its own config class that holds task specific parameters, such as the dimensions of the +observation and action buffers. Reward term scaling parameters can also be specified in the config class. + +In Isaac Lab, the ``controlFrequencyInv`` parameter has been renamed to ``decimation``, +which must be specified as a parameter in the config class. + +In addition, the maximum episode length parameter (now ``episode_length_s``) is in seconds instead of steps as it was +in OmniIsaacGymEnvs. To convert between step count to seconds, use the equation: +``episode_length_s = dt * decimation * num_steps``. + +The following parameters must be set for each environment config: + +.. code-block:: python + + decimation = 2 + episode_length_s = 5.0 + action_space = 1 + observation_space = 4 + state_space = 0 + + +RL Config Setup +~~~~~~~~~~~~~~~ + +RL config files for the rl_games library can continue to be defined in ``.yaml`` files in Isaac Lab. +Most of the content of the config file can be copied directly from OmniIsaacGymEnvs. +Note that in Isaac Lab, we do not use hydra to resolve relative paths in config files. +Please replace any relative paths such as ``${....device}`` with the actual values of the parameters. + +Additionally, the observation and action clip ranges have been moved to the RL config file. +For any ``clipObservations`` and ``clipActions`` parameters that were defined in the IsaacGymEnvs task config file, +they should be moved to the RL config file in Isaac Lab. + ++--------------------------+----------------------------+ +| | | +| IsaacGymEnvs Task Config | Isaac Lab RL Config | ++--------------------------+----------------------------+ +|.. code-block:: yaml |.. code-block:: yaml | +| | | +| # OmniIsaacGymEnvs | # IsaacLab | +| env: | params: | +| clipObservations: 5.0 | env: | +| clipActions: 1.0 | clip_observations: 5.0 | +| | clip_actions: 1.0 | ++--------------------------+----------------------------+ + +Environment Creation +~~~~~~~~~~~~~~~~~~~~ + +In OmniIsaacGymEnvs, environment creation generally happened in the ``set_up_scene()`` API, +which involved creating the initial environment, cloning the environment, filtering collisions, +adding the ground plane and lights, and creating the ``View`` classes for the actors. + +Similar functionality is performed in Isaac Lab in the ``_setup_scene()`` API. +The main difference is that the base class ``_setup_scene()`` no longer performs operations for +cloning the environment and adding ground plane and lights. Instead, these operations +should now be implemented in individual tasks' ``_setup_scene`` implementations to provide more +flexibility around the scene setup process. + +Also note that by defining an ``Articulation`` or ``RigidObject`` object, the actors will be +added to the scene by parsing the ``spawn`` parameter in the actor config and a ``View`` class +will automatically be created for the actor. This avoids the need to separately define an +``ArticulationView`` or ``RigidPrimView`` object for the actors. + + ++------------------------------------------------------------------------------+------------------------------------------------------------------------+ +| OmniIsaacGymEnvs | Isaac Lab | ++------------------------------------------------------------------------------+------------------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| def set_up_scene(self, scene) -> None: | def _setup_scene(self): | +| self.get_cartpole() | self.cartpole = Articulation(self.cfg.robot_cfg) | +| super().set_up_scene(scene) | # add ground plane | +| | spawn_ground_plane(prim_path="/World/ground", cfg=GroundPlaneCfg() | +| self._cartpoles = ArticulationView( | # clone, filter, and replicate | +| prim_paths_expr="/World/envs/.*/Cartpole", | self.scene.clone_environments(copy_from_source=False) | +| name="cartpole_view", reset_xform_properties=False | self.scene.filter_collisions(global_prim_paths=[]) | +| ) | # add articulation to scene | +| scene.add(self._cartpoles) | self.scene.articulations["cartpole"] = self.cartpole | +| | # add lights | +| | light_cfg = sim_utils.DomeLightCfg(intensity=2000.0) | +| | light_cfg.func("/World/Light", light_cfg) | ++------------------------------------------------------------------------------+------------------------------------------------------------------------+ + + +Ground Plane +------------ + +In addition to the above example, more sophisticated ground planes can be defined using the :class:`~terrains.TerrainImporterCfg` class. + +.. code-block:: python + + from isaaclab.terrains import TerrainImporterCfg + + terrain = TerrainImporterCfg( + prim_path="/World/ground", + terrain_type="plane", + collision_group=-1, + physics_material=sim_utils.RigidBodyMaterialCfg( + friction_combine_mode="multiply", + restitution_combine_mode="multiply", + static_friction=1.0, + dynamic_friction=1.0, + restitution=0.0, + ), + ) + +The terrain can then be added to the scene in ``_setup_scene(self)`` by referencing the ``TerrainImporterCfg`` object: + +.. code-block::python + + def _setup_scene(self): + ... + self.cfg.terrain.num_envs = self.scene.cfg.num_envs + self.cfg.terrain.env_spacing = self.scene.cfg.env_spacing + self._terrain = self.cfg.terrain.class_type(self.cfg.terrain) + + +Actors +------ + +In Isaac Lab, each Articulation and Rigid Body actor can have its own config class. The +:class:`~isaaclab.assets.ArticulationCfg` class can be used to define parameters for articulation actors, +including file path, simulation parameters, actuator properties, and initial states. + +.. code-block::python + + from isaaclab.actuators import ImplicitActuatorCfg + from isaaclab.assets import ArticulationCfg + + CARTPOLE_CFG = ArticulationCfg( + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Robots/Classic/Cartpole/cartpole.usd", + rigid_props=sim_utils.RigidBodyPropertiesCfg( + rigid_body_enabled=True, + max_linear_velocity=1000.0, + max_angular_velocity=1000.0, + max_depenetration_velocity=100.0, + enable_gyroscopic_forces=True, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=False, + solver_position_iteration_count=4, + solver_velocity_iteration_count=0, + sleep_threshold=0.005, + stabilization_threshold=0.001, + ), + ), + init_state=ArticulationCfg.InitialStateCfg( + pos=(0.0, 0.0, 2.0), joint_pos={"slider_to_cart": 0.0, "cart_to_pole": 0.0} + ), + actuators={ + "cart_actuator": ImplicitActuatorCfg( + joint_names_expr=["slider_to_cart"], + effort_limit_sim=400.0, + velocity_limit_sim=100.0, + stiffness=0.0, + damping=10.0, + ), + "pole_actuator": ImplicitActuatorCfg( + joint_names_expr=["cart_to_pole"], effort_limit=400.0, velocity_limit=100.0, stiffness=0.0, damping=0.0 + ), + }, + ) + +Within the :class:`~assets.ArticulationCfg`, the ``spawn`` attribute can be used to add the robot to the scene +by specifying the path to the robot file. In addition, the :class:`~isaaclab.sim.schemas.RigidBodyPropertiesCfg` +class can be used to specify simulation properties for the rigid bodies in the articulation. Similarly, the +:class:`~isaaclab.sim.schemas.ArticulationRootPropertiesCfg` class can be used to specify simulation properties +for the articulation. The joint properties are now specified as part of the ``actuators`` dictionary using +:class:`~actuators.ImplicitActuatorCfg`. Joints with the same properties can be grouped into regex expressions or +provided as a list of names or expressions. + +Actors are added to the scene by simply calling ``self.cartpole = Articulation(self.cfg.robot_cfg)``, where +``self.cfg.robot_cfg`` is an :class:`~assets.ArticulationCfg` object. Once initialized, they should also be added +to the :class:`~scene.InteractiveScene` by calling ``self.scene.articulations["cartpole"] = self.cartpole`` so that +the :class:`~scene.InteractiveScene` can traverse through actors in the scene for writing values to the simulation +and resetting. + + +Accessing States from Simulation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +APIs for accessing physics states in Isaac Lab require the creation of an :class:`~assets.Articulation` or +:class:`~assets.RigidObject` object. Multiple objects can be initialized for different articulations or rigid bodies +in the scene by defining corresponding :class:`~assets.ArticulationCfg` or :class:`~assets.RigidObjectCfg` config, +as outlined in the section above. This replaces the previously used :class:`~omni.isaac.core.articulations.ArticulationView` +and :class:`omni.isaac.core.prims.RigidPrimView` classes used in OmniIsaacGymEnvs. + +However, functionality between the classes are similar: + ++------------------------------------------------------------------+-----------------------------------------------------------------+ +| OmniIsaacGymEnvs | Isaac Lab | ++------------------------------------------------------------------+-----------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| dof_pos = self._cartpoles.get_joint_positions(clone=False) | self.joint_pos = self._robot.data.joint_pos | +| dof_vel = self._cartpoles.get_joint_velocities(clone=False) | self.joint_vel = self._robot.data.joint_vel | ++------------------------------------------------------------------+-----------------------------------------------------------------+ + +In Isaac Lab, :class:`~assets.Articulation` and :class:`~assets.RigidObject` classes both have a ``data`` class. +The data classes (:class:`~assets.ArticulationData` and :class:`~assets.RigidObjectData`) contain +buffers that hold the states for the articulation and rigid objects and provide +a more performant way of retrieving states from the actors. + +Apart from some renamings of APIs, setting states for actors can also be performed similarly between OmniIsaacGymEnvs and Isaac Lab. + ++---------------------------------------------------------------------------+---------------------------------------------------------------+ +| OmniIsaacGymEnvs | Isaac Lab | ++---------------------------------------------------------------------------+---------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| indices = env_ids.to(dtype=torch.int32) | self._robot.write_joint_state_to_sim(joint_pos, joint_vel, | +| self._cartpoles.set_joint_positions(dof_pos, indices=indices) | joint_ids, env_ids) | +| self._cartpoles.set_joint_velocities(dof_vel, indices=indices) | | ++---------------------------------------------------------------------------+---------------------------------------------------------------+ + +In Isaac Lab, ``root_pose`` and ``root_velocity`` have been combined into single buffers and no longer split between +``root_position``, ``root_orientation``, ``root_linear_velocity`` and ``root_angular_velocity``. + +.. code-block::python + + self.cartpole.write_root_pose_to_sim(default_root_state[:, :7], env_ids) + self.cartpole.write_root_velocity_to_sim(default_root_state[:, 7:], env_ids) + + +Creating a New Environment +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Each environment in Isaac Lab should be in its own directory following this structure: + +.. code-block:: none + + my_environment/ + - agents/ + - __init__.py + - rl_games_ppo_cfg.py + - __init__.py + my_env.py + +* ``my_environment`` is the root directory of the task. +* ``my_environment/agents`` is the directory containing all RL config files for the task. Isaac Lab supports multiple + RL libraries that can each have its own individual config file. +* ``my_environment/__init__.py`` is the main file that registers the environment with the Gymnasium interface. + This allows the training and inferencing scripts to find the task by its name. + The content of this file should be as follow: + + .. code-block:: python + + import gymnasium as gym + + from . import agents + from .cartpole_env import CartpoleEnv, CartpoleEnvCfg + + ## + # Register Gym environments. + ## + + gym.register( + id="Isaac-Cartpole-Direct-v0", + entry_point="isaaclab_tasks.direct_workflow.cartpole:CartpoleEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": CartpoleEnvCfg, + "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml" + }, + ) + +* ``my_environment/my_env.py`` is the main python script that implements the task logic and task config class for + the environment. + + +Task Logic +~~~~~~~~~~ + +The ``post_reset`` API in OmniIsaacGymEnvs is no longer required in Isaac Lab. Everything that was previously +done in ``post_reset`` can be done in the ``__init__`` method after executing the base class's +``__init__``. At this point, simulation has already started. + +In OmniIsaacGymEnvs, due to limitations of the GPU APIs, resets could not be performed based on states of the current +step. Instead, resets have to be performed at the beginning of the next time step. +This restriction has been eliminated in Isaac Lab, and thus, tasks follow the correct workflow of applying actions, +stepping simulation, collecting states, computing dones, calculating rewards, performing resets, and finally computing +observations. This workflow is done automatically by the framework such that a ``post_physics_step`` API is not +required in the task. However, individual tasks can override the ``step()`` API to control the workflow. + +In Isaac Lab, we also separate the ``pre_physics_step`` API for processing actions from the policy with +the ``apply_action`` API, which sets the actions into the simulation. This provides more flexibility in controlling +when actions should be written to simulation when ``decimation`` is used. +The ``pre_physics_step`` method will be called once per step before stepping simulation. +The ``apply_actions`` method will be called ``decimation`` number of times for each RL step, +once before each simulation step call. + +The ordering of the calls are as follow: + ++----------------------------------+----------------------------------+ +| OmniIsaacGymEnvs | Isaac Lab | ++----------------------------------+----------------------------------+ +|.. code-block:: none |.. code-block:: none | +| | | +| pre_physics_step | pre_physics_step | +| |-- reset_idx() | |-- _pre_physics_step(action)| +| |-- apply_action | |-- _apply_action() | +| | | +| post_physics_step | post_physics_step | +| |-- get_observations() | |-- _get_dones() | +| |-- calculate_metrics() | |-- _get_rewards() | +| |-- is_done() | |-- _reset_idx() | +| | |-- _get_observations() | ++----------------------------------+----------------------------------+ + +With this approach, resets are performed based on actions from the current step instead of the previous step. +Observations will also be computed with the correct states after resets. + +We have also performed some renamings of APIs: + +* ``set_up_scene(self, scene)`` --> ``_setup_scene(self)`` +* ``post_reset(self)`` --> ``__init__(...)`` +* ``pre_physics_step(self, actions)`` --> ``_pre_physics_step(self, actions)`` and ``_apply_action(self)`` +* ``reset_idx(self, env_ids)`` --> ``_reset_idx(self, env_ids)`` +* ``get_observations(self)`` --> ``_get_observations(self)`` - ``_get_observations()`` should now return a dictionary ``{"policy": obs}`` +* ``calculate_metrics(self)`` --> ``_get_rewards(self)`` - ``_get_rewards()`` should now return the reward buffer +* ``is_done(self)`` --> ``_get_dones(self)`` - ``_get_dones()`` should now return 2 buffers: ``reset`` and ``time_out`` buffers + + + +Putting It All Together +~~~~~~~~~~~~~~~~~~~~~~~ + +The Cartpole environment is shown here in completion to fully show the comparison between the OmniIsaacGymEnvs +implementation and the Isaac Lab implementation. + +Task Config +----------- + +Task config in Isaac Lab can be split into the main task configuration class and individual config objects for the actors. + ++-----------------------------------------------------------------+-----------------------------------------------------------------+ +| OmniIsaacGymEnvs | Isaac Lab | ++-----------------------------------------------------------------+-----------------------------------------------------------------+ +|.. code-block:: yaml |.. code-block:: python | +| | | +| # used to create the object | @configclass | +| | class CartpoleEnvCfg(DirectRLEnvCfg): | +| name: Cartpole | | +| | # simulation | +| physics_engine: ${..physics_engine} | sim: SimulationCfg = SimulationCfg(dt=1 / 120) | +| | # robot | +| # if given, will override the device setting in gym. | robot_cfg: ArticulationCfg = CARTPOLE_CFG.replace( | +| env: | prim_path="/World/envs/env_.*/Robot") | +| | cart_dof_name = "slider_to_cart" | +| numEnvs: ${resolve_default:512,${...num_envs}} | pole_dof_name = "cart_to_pole" | +| envSpacing: 4.0 | # scene | +| resetDist: 3.0 | scene: InteractiveSceneCfg = InteractiveSceneCfg( | +| maxEffort: 400.0 | num_envs=4096, env_spacing=4.0, replicate_physics=True) | +| | # env | +| clipObservations: 5.0 | decimation = 2 | +| clipActions: 1.0 | episode_length_s = 5.0 | +| controlFrequencyInv: 2 # 60 Hz | action_scale = 100.0 # [N] | +| | action_space = 1 | +| sim: | observation_space = 4 | +| | state_space = 0 | +| dt: 0.0083 # 1/120 s | # reset | +| use_gpu_pipeline: ${eq:${...pipeline},"gpu"} | max_cart_pos = 3.0 | +| gravity: [0.0, 0.0, -9.81] | initial_pole_angle_range = [-0.25, 0.25] | +| add_ground_plane: True | # reward scales | +| add_distant_light: False | rew_scale_alive = 1.0 | +| use_fabric: True | rew_scale_terminated = -2.0 | +| enable_scene_query_support: False | rew_scale_pole_pos = -1.0 | +| disable_contact_processing: False | rew_scale_cart_vel = -0.01 | +| | rew_scale_pole_vel = -0.005 | +| enable_cameras: False | | +| | | +| default_physics_material: | CARTPOLE_CFG = ArticulationCfg( | +| static_friction: 1.0 | spawn=sim_utils.UsdFileCfg( | +| dynamic_friction: 1.0 | usd_path=f"{ISAACLAB_NUCLEUS_DIR}/.../cartpole.usd", | +| restitution: 0.0 | rigid_props=sim_utils.RigidBodyPropertiesCfg( | +| | rigid_body_enabled=True, | +| physx: | max_linear_velocity=1000.0, | +| worker_thread_count: ${....num_threads} | max_angular_velocity=1000.0, | +| solver_type: ${....solver_type} | max_depenetration_velocity=100.0, | +| use_gpu: ${eq:${....sim_device},"gpu"} # set to False to... | enable_gyroscopic_forces=True, | +| solver_position_iteration_count: 4 | ), | +| solver_velocity_iteration_count: 0 | articulation_props=sim_utils.ArticulationRootPropertiesCfg( | +| contact_offset: 0.02 | enabled_self_collisions=False, | +| rest_offset: 0.001 | solver_position_iteration_count=4, | +| bounce_threshold_velocity: 0.2 | solver_velocity_iteration_count=0, | +| friction_offset_threshold: 0.04 | sleep_threshold=0.005, | +| friction_correlation_distance: 0.025 | stabilization_threshold=0.001, | +| enable_sleeping: True | ), | +| enable_stabilization: True | ), | +| max_depenetration_velocity: 100.0 | init_state=ArticulationCfg.InitialStateCfg( | +| | pos=(0.0, 0.0, 2.0), | +| # GPU buffers | joint_pos={"slider_to_cart": 0.0, "cart_to_pole": 0.0} | +| gpu_max_rigid_contact_count: 524288 | ), | +| gpu_max_rigid_patch_count: 81920 | actuators={ | +| gpu_found_lost_pairs_capacity: 1024 | "cart_actuator": ImplicitActuatorCfg( | +| gpu_found_lost_aggregate_pairs_capacity: 262144 | joint_names_expr=["slider_to_cart"], | +| gpu_total_aggregate_pairs_capacity: 1024 | effort_limit=400.0, | +| gpu_max_soft_body_contacts: 1048576 | velocity_limit=100.0, | +| gpu_max_particle_contacts: 1048576 | stiffness=0.0, | +| gpu_heap_capacity: 67108864 | damping=10.0, | +| gpu_temp_buffer_capacity: 16777216 | ), | +| gpu_max_num_partitions: 8 | "pole_actuator": ImplicitActuatorCfg( | +| | joint_names_expr=["cart_to_pole"], effort_limit=400.0, | +| Cartpole: | velocity_limit=100.0, stiffness=0.0, damping=0.0 | +| override_usd_defaults: False | ), | +| enable_self_collisions: False | }, | +| enable_gyroscopic_forces: True | ) | +| solver_position_iteration_count: 4 | | +| solver_velocity_iteration_count: 0 | | +| sleep_threshold: 0.005 | | +| stabilization_threshold: 0.001 | | +| density: -1 | | +| max_depenetration_velocity: 100.0 | | +| contact_offset: 0.02 | | +| rest_offset: 0.001 | | ++-----------------------------------------------------------------+-----------------------------------------------------------------+ + + + +Task Setup +---------- + +The ``post_reset`` API in OmniIsaacGymEnvs is no longer required in Isaac Lab. +Everything that was previously done in ``post_reset`` can be done in the ``__init__`` method after +executing the base class's ``__init__``. At this point, simulation has already started. + ++-------------------------------------------------------------------------+-------------------------------------------------------------+ +| OmniIsaacGymEnvs | Isaac Lab | ++-------------------------------------------------------------------------+-------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| class CartpoleTask(RLTask): | class CartpoleEnv(DirectRLEnv): | +| | cfg: CartpoleEnvCfg | +| def __init__(self, name, sim_config, env, offset=None) -> None: | def __init__(self, cfg: CartpoleEnvCfg, | +| | render_mode: str | None = None, **kwargs): | +| self.update_config(sim_config) | super().__init__(cfg, render_mode, **kwargs) | +| self._max_episode_length = 500 | | +| | | +| self._num_observations = 4 | self._cart_dof_idx, _ = self.cartpole.find_joints( | +| self._num_actions = 1 | self.cfg.cart_dof_name) | +| | self._pole_dof_idx, _ = self.cartpole.find_joints( | +| RLTask.__init__(self, name, env) | self.cfg.pole_dof_name) | +| | self.action_scale=self.cfg.action_scale | +| def update_config(self, sim_config): | | +| self._sim_config = sim_config | self.joint_pos = self.cartpole.data.joint_pos | +| self._cfg = sim_config.config | self.joint_vel = self.cartpole.data.joint_vel | +| self._task_cfg = sim_config. | | +| task_config | | +| | | +| self._num_envs = self._task_cfg["env"]["numEnvs"] | | +| self._env_spacing = self._task_cfg["env"]["envSpacing"] | | +| self._cartpole_positions = torch.tensor([0.0, 0.0, 2.0]) | | +| | | +| self._reset_dist = self._task_cfg["env"]["resetDist"] | | +| self._max_push_effort = self._task_cfg["env"]["maxEffort"] | | +| | | +| | | +| def post_reset(self): | | +| self._cart_dof_idx = self._cartpoles.get_dof_index( | | +| "cartJoint") | | +| self._pole_dof_idx = self._cartpoles.get_dof_index( | | +| "poleJoint") | | +| # randomize all envs | | +| indices = torch.arange( | | +| self._cartpoles.count, dtype=torch.int64, | | +| device=self._device) | | +| self.reset_idx(indices) | | ++-------------------------------------------------------------------------+-------------------------------------------------------------+ + + + +Scene Setup +----------- + +The ``set_up_scene`` method in OmniIsaacGymEnvs has been replaced by the ``_setup_scene`` API in the task class in +Isaac Lab. Additionally, scene cloning and collision filtering have been provided as APIs for the task class to +call when necessary. Similarly, adding ground plane and lights should also be taken care of in the task class. +Adding actors to the scene has been replaced by ``self.scene.articulations["cartpole"] = self.cartpole``. + ++-----------------------------------------------------------+----------------------------------------------------------+ +| OmniIsaacGymEnvs | Isaac Lab | ++-----------------------------------------------------------+----------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| def set_up_scene(self, scene) -> None: | def _setup_scene(self): | +| | self.cartpole = Articulation(self.cfg.robot_cfg) | +| self.get_cartpole() | # add ground plane | +| super().set_up_scene(scene) | spawn_ground_plane(prim_path="/World/ground", | +| self._cartpoles = ArticulationView( | cfg=GroundPlaneCfg()) | +| prim_paths_expr="/World/envs/.*/Cartpole", | # clone, filter, and replicate | +| name="cartpole_view", | self.scene.clone_environments( | +| reset_xform_properties=False | copy_from_source=False) | +| ) | self.scene.filter_collisions( | +| scene.add(self._cartpoles) | global_prim_paths=[]) | +| return | # add articulation to scene | +| | self.scene.articulations["cartpole"] = self.cartpole | +| def get_cartpole(self): | | +| cartpole = Cartpole( | # add lights | +| prim_path=self.default_zero_env_path+"/Cartpole", | light_cfg = sim_utils.DomeLightCfg( | +| name="Cartpole", | intensity=2000.0, color=(0.75, 0.75, 0.75)) | +| translation=self._cartpole_positions | light_cfg.func("/World/Light", light_cfg) | +| ) | | +| # applies articulation settings from the | | +| # task configuration yaml file | | +| self._sim_config.apply_articulation_settings( | | +| "Cartpole", get_prim_at_path(cartpole.prim_path), | | +| self._sim_config.parse_actor_config("Cartpole") | | +| ) | | ++-----------------------------------------------------------+----------------------------------------------------------+ + + +Pre-Physics Step +---------------- + +Note that resets are no longer performed in the ``pre_physics_step`` API. In addition, the separation of the +``_pre_physics_step`` and ``_apply_action`` methods allow for more flexibility in processing the action buffer +and setting actions into simulation. + ++------------------------------------------------------------------+-------------------------------------------------------------+ +| OmniIsaacGymEnvs | IsaacLab | ++------------------------------------------------------------------+-------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| def pre_physics_step(self, actions) -> None: | def _pre_physics_step(self, | +| if not self.world.is_playing(): | actions: torch.Tensor) -> None: | +| return | self.actions = self.action_scale * actions | +| | | +| reset_env_ids = self.reset_buf.nonzero( | def _apply_action(self) -> None: | +| as_tuple=False).squeeze(-1) | self.cartpole.set_joint_effort_target( | +| if len(reset_env_ids) > 0: | self.actions, joint_ids=self._cart_dof_idx) | +| self.reset_idx(reset_env_ids) | | +| | | +| actions = actions.to(self._device) | | +| | | +| forces = torch.zeros((self._cartpoles.count, | | +| self._cartpoles.num_dof), | | +| dtype=torch.float32, device=self._device) | | +| forces[:, self._cart_dof_idx] = | | +| self._max_push_effort * actions[:, 0] | | +| | | +| indices = torch.arange(self._cartpoles.count, | | +| dtype=torch.int32, device=self._device) | | +| self._cartpoles.set_joint_efforts( | | +| forces, indices=indices) | | ++------------------------------------------------------------------+-------------------------------------------------------------+ + + +Dones and Resets +---------------- + +In Isaac Lab, the ``dones`` are computed in the ``_get_dones()`` method and should return two variables: ``resets`` and +``time_out``. The ``_reset_idx()`` method is also called after stepping simulation instead of before, as it was done in +OmniIsaacGymEnvs. The ``progress_buf`` tensor has been renamed to ``episode_length_buf`` in Isaac Lab and the +bookkeeping is now done automatically by the framework. Task implementations no longer need to increment or +reset the ``episode_length_buf`` buffer. + ++------------------------------------------------------------------+--------------------------------------------------------------------------+ +| OmniIsaacGymEnvs | Isaac Lab | ++------------------------------------------------------------------+--------------------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| def is_done(self) -> None: | def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: | +| resets = torch.where( | self.joint_pos = self.cartpole.data.joint_pos | +| torch.abs(self.cart_pos) > self._reset_dist, 1, 0) | self.joint_vel = self.cartpole.data.joint_vel | +| resets = torch.where( | | +| torch.abs(self.pole_pos) > math.pi / 2, 1, resets) | time_out = self.episode_length_buf >= self.max_episode_length - 1 | +| resets = torch.where( | out_of_bounds = torch.any(torch.abs( | +| self.progress_buf >= self._max_episode_length, 1, resets) | self.joint_pos[:, self._cart_dof_idx]) > self.cfg.max_cart_pos, | +| self.reset_buf[:] = resets | dim=1) | +| | out_of_bounds = out_of_bounds | torch.any( | +| | torch.abs(self.joint_pos[:, self._pole_dof_idx]) > math.pi / 2, | +| | dim=1) | +| | return out_of_bounds, time_out | +| | | +| def reset_idx(self, env_ids): | def _reset_idx(self, env_ids: Sequence[int] | None): | +| num_resets = len(env_ids) | if env_ids is None: | +| | env_ids = self.cartpole._ALL_INDICES | +| # randomize DOF positions | super()._reset_idx(env_ids) | +| dof_pos = torch.zeros((num_resets, self._cartpoles.num_dof), | | +| device=self._device) | joint_pos = self.cartpole.data.default_joint_pos[env_ids] | +| dof_pos[:, self._cart_dof_idx] = 1.0 * ( | joint_pos[:, self._pole_dof_idx] += sample_uniform( | +| 1.0 - 2.0 * torch.rand(num_resets, device=self._device)) | self.cfg.initial_pole_angle_range[0] * math.pi, | +| dof_pos[:, self._pole_dof_idx] = 0.125 * math.pi * ( | self.cfg.initial_pole_angle_range[1] * math.pi, | +| 1.0 - 2.0 * torch.rand(num_resets, device=self._device)) | joint_pos[:, self._pole_dof_idx].shape, | +| | joint_pos.device, | +| # randomize DOF velocities | ) | +| dof_vel = torch.zeros((num_resets, self._cartpoles.num_dof), | joint_vel = self.cartpole.data.default_joint_vel[env_ids] | +| device=self._device) | | +| dof_vel[:, self._cart_dof_idx] = 0.5 * ( | default_root_state = self.cartpole.data.default_root_state[env_ids] | +| 1.0 - 2.0 * torch.rand(num_resets, device=self._device)) | default_root_state[:, :3] += self.scene.env_origins[env_ids] | +| dof_vel[:, self._pole_dof_idx] = 0.25 * math.pi * ( | | +| 1.0 - 2.0 * torch.rand(num_resets, device=self._device)) | self.joint_pos[env_ids] = joint_pos | +| | self.joint_vel[env_ids] = joint_vel | +| # apply resets | | +| indices = env_ids.to(dtype=torch.int32) | self.cartpole.write_root_pose_to_sim( | +| self._cartpoles.set_joint_positions(dof_pos, indices=indices) | default_root_state[:, :7], env_ids) | +| self._cartpoles.set_joint_velocities(dof_vel, indices=indices) | self.cartpole.write_root_velocity_to_sim( | +| | default_root_state[:, 7:], env_ids) | +| # bookkeeping | self.cartpole.write_joint_state_to_sim( | +| self.reset_buf[env_ids] = 0 | joint_pos, joint_vel, None, env_ids) | +| self.progress_buf[env_ids] = 0 | | +| | | +| | | ++------------------------------------------------------------------+--------------------------------------------------------------------------+ + + +Rewards +------- + +In Isaac Lab, rewards are implemented in the ``_get_rewards`` API and should return the reward buffer instead of assigning +it directly to ``self.rew_buf``. Computation in the reward function can also be performed using pytorch jit +through defining functions with the ``@torch.jit.script`` annotation. + ++-------------------------------------------------------+-----------------------------------------------------------------------+ +| OmniIsaacGymEnvs | Isaac Lab | ++-------------------------------------------------------+-----------------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: python | +| | | +| def calculate_metrics(self) -> None: | def _get_rewards(self) -> torch.Tensor: | +| reward = (1.0 - self.pole_pos * self.pole_pos | total_reward = compute_rewards( | +| - 0.01 * torch.abs(self.cart_vel) - 0.005 | self.cfg.rew_scale_alive, | +| * torch.abs(self.pole_vel)) | self.cfg.rew_scale_terminated, | +| reward = torch.where( | self.cfg.rew_scale_pole_pos, | +| torch.abs(self.cart_pos) > self._reset_dist, | self.cfg.rew_scale_cart_vel, | +| torch.ones_like(reward) * -2.0, reward) | self.cfg.rew_scale_pole_vel, | +| reward = torch.where( | self.joint_pos[:, self._pole_dof_idx[0]], | +| torch.abs(self.pole_pos) > np.pi / 2, | self.joint_vel[:, self._pole_dof_idx[0]], | +| torch.ones_like(reward) * -2.0, reward) | self.joint_pos[:, self._cart_dof_idx[0]], | +| | self.joint_vel[:, self._cart_dof_idx[0]], | +| self.rew_buf[:] = reward | self.reset_terminated, | +| | ) | +| | return total_reward | +| | | +| | @torch.jit.script | +| | def compute_rewards( | +| | rew_scale_alive: float, | +| | rew_scale_terminated: float, | +| | rew_scale_pole_pos: float, | +| | rew_scale_cart_vel: float, | +| | rew_scale_pole_vel: float, | +| | pole_pos: torch.Tensor, | +| | pole_vel: torch.Tensor, | +| | cart_pos: torch.Tensor, | +| | cart_vel: torch.Tensor, | +| | reset_terminated: torch.Tensor, | +| | ): | +| | rew_alive = rew_scale_alive * (1.0 - reset_terminated.float()) | +| | rew_termination = rew_scale_terminated * reset_terminated.float() | +| | rew_pole_pos = rew_scale_pole_pos * torch.sum( | +| | torch.square(pole_pos), dim=-1) | +| | rew_cart_vel = rew_scale_cart_vel * torch.sum( | +| | torch.abs(cart_vel), dim=-1) | +| | rew_pole_vel = rew_scale_pole_vel * torch.sum( | +| | torch.abs(pole_vel), dim=-1) | +| | total_reward = (rew_alive + rew_termination | +| | + rew_pole_pos + rew_cart_vel + rew_pole_vel) | +| | return total_reward | ++-------------------------------------------------------+-----------------------------------------------------------------------+ + + +Observations +------------ + +In Isaac Lab, the ``_get_observations()`` API must return a dictionary with the key ``policy`` that has the observation buffer as the value. +When working with asymmetric actor-critic states, the states for the critic should have the key ``critic`` and be returned +with the observation buffer in the same dictionary. + ++------------------------------------------------------------------+-------------------------------------------------------------+ +| OmniIsaacGymEnvs | Isaac Lab | ++------------------------------------------------------------------+-------------------------------------------------------------+ +|.. code-block:: python |.. code-block:: | +| | | +| def get_observations(self) -> dict: | def _get_observations(self) -> dict: | +| dof_pos = self._cartpoles.get_joint_positions(clone=False) | obs = torch.cat( | +| dof_vel = self._cartpoles.get_joint_velocities(clone=False) | ( | +| | self.joint_pos[:, self._pole_dof_idx[0]], | +| self.cart_pos = dof_pos[:, self._cart_dof_idx] | self.joint_vel[:, self._pole_dof_idx[0]], | +| self.cart_vel = dof_vel[:, self._cart_dof_idx] | self.joint_pos[:, self._cart_dof_idx[0]], | +| self.pole_pos = dof_pos[:, self._pole_dof_idx] | self.joint_vel[:, self._cart_dof_idx[0]], | +| self.pole_vel = dof_vel[:, self._pole_dof_idx] | ), | +| self.obs_buf[:, 0] = self.cart_pos | dim=-1, | +| self.obs_buf[:, 1] = self.cart_vel | ) | +| self.obs_buf[:, 2] = self.pole_pos | observations = {"policy": obs} | +| self.obs_buf[:, 3] = self.pole_vel | return observations | +| | | +| observations = {self._cartpoles.name: | | +| {"obs_buf": self.obs_buf}} | | +| return observations | | ++------------------------------------------------------------------+-------------------------------------------------------------+ + + +Domain Randomization +~~~~~~~~~~~~~~~~~~~~ + +In OmniIsaacGymEnvs, domain randomization was specified through the task ``.yaml`` config file. +In Isaac Lab, the domain randomization configuration uses the :class:`~isaaclab.utils.configclass` module +to specify a configuration class consisting of :class:`~managers.EventTermCfg` variables. + +Below is an example of a configuration class for domain randomization: + +.. code-block:: python + + @configclass + class EventCfg: + robot_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*"), + "static_friction_range": (0.7, 1.3), + "dynamic_friction_range": (1.0, 1.0), + "restitution_range": (1.0, 1.0), + "num_buckets": 250, + }, + ) + robot_joint_stiffness_and_damping = EventTerm( + func=mdp.randomize_actuator_gains, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=".*"), + "stiffness_distribution_params": (0.75, 1.5), + "damping_distribution_params": (0.3, 3.0), + "operation": "scale", + "distribution": "log_uniform", + }, + ) + reset_gravity = EventTerm( + func=mdp.randomize_physics_scene_gravity, + mode="interval", + is_global_time=True, + interval_range_s=(36.0, 36.0), # time_s = num_steps * (decimation * dt) + params={ + "gravity_distribution_params": ([0.0, 0.0, 0.0], [0.0, 0.0, 0.4]), + "operation": "add", + "distribution": "gaussian", + }, + ) + +Each ``EventTerm`` object is of the :class:`~managers.EventTermCfg` class and takes in a ``func`` parameter +for specifying the function to call during randomization, a ``mode`` parameter, which can be ``startup``, +``reset`` or ``interval``. THe ``params`` dictionary should provide the necessary arguments to the +function that is specified in the ``func`` parameter. +Functions specified as ``func`` for the ``EventTerm`` can be found in the :class:`~envs.mdp.events` module. + +Note that as part of the ``"asset_cfg": SceneEntityCfg("robot", body_names=".*")`` parameter, the name of +the actor ``"robot"`` is provided, along with the body or joint names specified as a regex expression, +which will be the actors and bodies/joints that will have randomization applied. + +One difference with OmniIsaacGymEnvs is that ``interval`` randomization is now specified as seconds instead of +steps. When ``mode="interval"``, the ``interval_range_s`` parameter must also be provided, which specifies +the range of seconds for which randomization should be applied. This range will then be randomized to +determine a specific time in seconds when the next randomization will occur for the term. +To convert between steps to seconds, use the equation ``time_s = num_steps * (decimation * dt)``. + +Similar to OmniIsaacGymEnvs, randomization APIs are available for randomizing articulation properties, +such as joint stiffness and damping, joint limits, rigid body materials, fixed tendon properties, +as well as rigid body properties, such as mass and rigid body materials. Randomization of the +physics scene gravity is also supported. Note that randomization of scale is current not supported +in Isaac Lab. To randomize scale, please set up the scene in a way where each environment holds the actor +at a different scale. + +Once the ``configclass`` for the randomization terms have been set up, the class must be added +to the base config class for the task and be assigned to the variable ``events``. + +.. code-block:: python + + @configclass + class MyTaskConfig: + events: EventCfg = EventCfg() + + +Action and Observation Noise +---------------------------- + +Actions and observation noise can also be added using the :class:`~utils.configclass` module. +Action and observation noise configs must be added to the main task config using the +``action_noise_model`` and ``observation_noise_model`` variables: + +.. code-block:: python + + @configclass + class MyTaskConfig: + # at every time-step add gaussian noise + bias. The bias is a gaussian sampled at reset + action_noise_model: NoiseModelWithAdditiveBiasCfg = NoiseModelWithAdditiveBiasCfg( + noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.05, operation="add"), + bias_noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.015, operation="abs"), + ) + # at every time-step add gaussian noise + bias. The bias is a gaussian sampled at reset + observation_noise_model: NoiseModelWithAdditiveBiasCfg = NoiseModelWithAdditiveBiasCfg( + noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.002, operation="add"), + bias_noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.0001, operation="abs"), + ) + + +:class:`~.utils.noise.NoiseModelWithAdditiveBiasCfg` can be used to sample both uncorrelated noise +per step as well as correlated noise that is re-sampled at reset time. +The ``noise_cfg`` term specifies the Gaussian distribution that will be sampled at each +step for all environments. This noise will be added to the corresponding actions and +observations buffers at every step. +The ``bias_noise_cfg`` term specifies the Gaussian distribution for the correlated noise +that will be sampled at reset time for the environments being reset. The same noise +will be applied each step for the remaining of the episode for the environments and +resampled at the next reset. + +This replaces the following setup in OmniIsaacGymEnvs: + +.. code-block:: yaml + + domain_randomization: + randomize: True + randomization_params: + observations: + on_reset: + operation: "additive" + distribution: "gaussian" + distribution_parameters: [0, .0001] + on_interval: + frequency_interval: 1 + operation: "additive" + distribution: "gaussian" + distribution_parameters: [0, .002] + actions: + on_reset: + operation: "additive" + distribution: "gaussian" + distribution_parameters: [0, 0.015] + on_interval: + frequency_interval: 1 + operation: "additive" + distribution: "gaussian" + distribution_parameters: [0., 0.05] + + +Launching Training +~~~~~~~~~~~~~~~~~~ + +To launch a training in Isaac Lab, use the command: + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rl_games --task=Isaac-Cartpole-Direct-v0 + +Launching Inferencing +~~~~~~~~~~~~~~~~~~~~~ + +To launch inferencing in Isaac Lab, use the command: + +.. code-block:: bash + + ./isaaclab.sh play --rl_library rl_games --task=Isaac-Cartpole-Direct-v0 --num_envs=25 --checkpoint= + + +.. _`OmniIsaacGymEnvs`: https://github.com/isaac-sim/OmniIsaacGymEnvs +.. _release notes: https://github.com/isaac-sim/IsaacLab/releases diff --git a/simulation/modules/IsaacLab/docs/source/migration/migrating_from_orbit.rst b/simulation/modules/IsaacLab/docs/source/migration/migrating_from_orbit.rst new file mode 100644 index 0000000000000000000000000000000000000000..ee88909c7eca995071fec4dc43e2ae51071ba36c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/migration/migrating_from_orbit.rst @@ -0,0 +1,150 @@ +.. _migrating-from-orbit: + +From Orbit +========== + +.. currentmodule:: isaaclab + +Since `Orbit`_ was used as basis for Isaac Lab, migrating from Orbit to Isaac Lab is straightforward. +The following sections describe the changes that need to be made to your code to migrate from Orbit to Isaac Lab. + +.. note:: + + The following changes are with respect to Isaac Lab 1.0 release. Please refer to the `release notes`_ for any changes + in the future releases. + + +Renaming of the launch script +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The script ``orbit.sh`` has been renamed to ``isaaclab.sh``. + + +Updates to extensions +~~~~~~~~~~~~~~~~~~~~~ + +The extensions ``omni.isaac.orbit``, ``omni.isaac.orbit_tasks``, and ``omni.isaac.orbit_assets`` have been renamed +to ``isaaclab``, ``isaaclab_tasks``, and ``isaaclab_assets``, respectively. Thus, +the new folder structure looks like this: + +- ``source/isaaclab/isaaclab`` +- ``source/isaaclab_tasks/isaaclab_tasks`` +- ``source/isaaclab_assets/isaaclab_assets`` + +The high level imports have to be updated as well: + ++-------------------------------------+-----------------------------------+ +| Orbit | Isaac Lab | ++=====================================+===================================+ +| ``from omni.isaac.orbit...`` | ``from isaaclab...`` | ++-------------------------------------+-----------------------------------+ +| ``from omni.isaac.orbit_tasks...`` | ``from isaaclab_tasks...`` | ++-------------------------------------+-----------------------------------+ +| ``from omni.isaac.orbit_assets...`` | ``from isaaclab_assets...`` | ++-------------------------------------+-----------------------------------+ + + +Updates to class names +~~~~~~~~~~~~~~~~~~~~~~ + +In Isaac Lab, we introduced the concept of task design workflows (see :ref:`feature-workflows`). The Orbit code is using +the manager-based workflow and the environment specific class names have been updated to reflect this change: + ++------------------------+---------------------------------------------------------+ +| Orbit | Isaac Lab | ++========================+=========================================================+ +| ``BaseEnv`` | :class:`isaaclab.envs.ManagerBasedEnv` | ++------------------------+---------------------------------------------------------+ +| ``BaseEnvCfg`` | :class:`isaaclab.envs.ManagerBasedEnvCfg` | ++------------------------+---------------------------------------------------------+ +| ``RLTaskEnv`` | :class:`isaaclab.envs.ManagerBasedRLEnv` | ++------------------------+---------------------------------------------------------+ +| ``RLTaskEnvCfg`` | :class:`isaaclab.envs.ManagerBasedRLEnvCfg` | ++------------------------+---------------------------------------------------------+ +| ``RLTaskEnvWindow`` | :class:`isaaclab.envs.ui.ManagerBasedRLEnvWindow` | ++------------------------+---------------------------------------------------------+ + + +Updates to the tasks folder structure +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To support the manager-based and direct workflows, we have added two folders in the tasks extension: + +- ``source/isaaclab_tasks/isaaclab_tasks/manager_based`` +- ``source/isaaclab_tasks/isaaclab_tasks/direct`` + +The tasks from Orbit can now be found under the ``manager_based`` folder. +This change must also be reflected in the imports for your tasks. For example, + +.. code-block:: python + + from omni.isaac.orbit_tasks.locomotion.velocity.velocity_env_cfg ... + +should now be: + +.. code-block:: python + + from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg ... + + +Other Breaking changes +~~~~~~~~~~~~~~~~~~~~~~ + +Setting the device +------------------ + +The argument ``--cpu`` has been removed in favor of ``--device device_name``. Valid options for ``device_name`` are: + +- ``cpu``: Use CPU. +- ``cuda``: Use GPU with device ID ``0``. +- ``cuda:N``: Use GPU, where N is the device ID. For example, ``cuda:0``. + +The default value is ``cuda:0``. + + +Offscreen rendering +------------------- + +The input argument ``--offscreen_render`` given to :class:`isaaclab.app.AppLauncher` and the environment variable +``OFFSCREEN_RENDER`` have been renamed to ``--enable_cameras`` and ``ENABLE_CAMERAS`` respectively. + + +Event term distribution configuration +------------------------------------- + +Some of the event functions in `events.py `_ +accepted a ``distribution`` parameter and a ``range`` to sample from. In an effort to support arbitrary distributions, +we have renamed the input argument ``AAA_range`` to ``AAA_distribution_params`` for these functions. +Therefore, event term configurations whose functions have a ``distribution`` argument should be updated. For example, + +.. code-block:: python + :emphasize-lines: 6 + + add_base_mass = EventTerm( + func=mdp.randomize_rigid_body_mass, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names="base"), + "mass_range": (-5.0, 5.0), + "operation": "add", + }, + ) + +should now be: + +.. code-block:: python + :emphasize-lines: 6 + + add_base_mass = EventTerm( + func=mdp.randomize_rigid_body_mass, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names="base"), + "mass_distribution_params": (-5.0, 5.0), + "operation": "add", + }, + ) + + +.. _Orbit: https://isaac-orbit.github.io/ +.. _release notes: https://github.com/isaac-sim/IsaacLab/releases diff --git a/simulation/modules/IsaacLab/docs/source/migration/migrating_to_isaaclab_3-0.rst b/simulation/modules/IsaacLab/docs/source/migration/migrating_to_isaaclab_3-0.rst new file mode 100644 index 0000000000000000000000000000000000000000..ee506917e0a5508efb8fe234124bffb32f989c2b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/migration/migrating_to_isaaclab_3-0.rst @@ -0,0 +1,2200 @@ +.. _migrating-to-isaaclab-3-0: + +Migrating to Isaac Lab 3.0 +========================== + +.. currentmodule:: isaaclab + +Isaac Lab 3.0 introduces a multi-backend architecture that separates simulation backend-specific code +from the core Isaac Lab API. This allows for future support of different physics backends while +maintaining a consistent user-facing API. + +This guide covers the main breaking changes and deprecations you need to address when migrating +from Isaac Lab 2.x to Isaac Lab 3.0. + + +Visualizer CLI and Headless Behavior +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In Isaac Lab 3.0, the ``--headless`` argument is deprecated. Instead, use ``--visualizer`` / ``--viz`` +to determine whether viewer apps are launched with an Isaac Lab command. + +Visualizers are lightweight viewer apps for monitoring, debugging, and recording workflows +(see :doc:`/source/overview/core-concepts/visualization`). + +The details below describe how CLI visualizer arguments resolve together with +``SimulationCfg.visualizer_cfgs``. + +- ``--viz`` accepts **comma-separated** values (for example ``--viz kit,newton``). +- If omitted, visualizers are resolved from ``SimulationCfg.visualizer_cfgs``. +- ``--viz none`` explicitly disables all visualizers, including config-defined ones. +- ``--headless`` is deprecated (still supported) and overrides ``--viz`` by forcing headless mode. + +For the full behavior of visualizer resolution, with the visualizer CLI arg, visualizer configs, +and ``--headless``, see :ref:`visualization-common-modes`. + + +Reinforcement Learning CLI Entrypoints +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Isaac Lab 3.0 provides unified reinforcement learning entrypoints for training +and play. Instead of launching library-specific scripts under +``scripts/reinforcement_learning//``, select the library with +``--rl_library``. + +.. code-block:: bash + + # Isaac Lab 2.x/deprecated + ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py --task Isaac-Cartpole-v0 + + # Isaac Lab 3.0 + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-v0 + +The same pattern applies to the play workflow: + +.. code-block:: bash + + ./isaaclab.sh play --rl_library rsl_rl --task Isaac-Cartpole-v0 --checkpoint /PATH/TO/model.pt + +Supported reinforcement learning libraries are ``rsl_rl``, ``rl_games``, ``skrl``, +``sb3``, and ``rlinf``. The old per-library ``train.py`` and ``play.py`` scripts +remain available as deprecated compatibility entrypoints and emit a +``DeprecationWarning`` when used. + +For distributed launchers that execute a Python script directly, use the unified +script path and pass ``--rl_library`` to it: + +.. code-block:: bash + + python -m torch.distributed.run --nproc_per_node=2 scripts/reinforcement_learning/train.py \ + --rl_library rsl_rl --task Isaac-Cartpole-v0 --headless --distributed + + +Multi-Backend Architecture +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Isaac Lab 3.0 introduces a **factory-based multi-backend architecture** that allows asset classes +to be backed by different physics engines — currently **PhysX** and **Newton**. + +When you instantiate an asset class from the ``isaaclab`` package (e.g., ``Articulation``, +``RigidObject``), a factory automatically resolves and loads the correct backend implementation: + +.. code-block:: python + + from isaaclab.assets import Articulation, ArticulationCfg + + # The factory pattern creates the appropriate backend implementation. + # No import changes are needed — the same isaaclab imports work regardless of backend. + robot = Articulation(cfg=ArticulationCfg(...)) + +The factory works by convention: for a class defined in ``isaaclab.assets.articulation``, it +imports the matching class from ``isaaclab_{backend}.assets.articulation``. This means the +``isaaclab_physx`` and ``isaaclab_newton`` packages mirror the ``isaaclab`` module structure. + +.. note:: + + The backend is currently set to ``"physx"`` by default. Newton backend support is being + actively developed. When backend selection is fully configurable, you will be able to + switch backends without changing any asset import paths. + +For a comprehensive overview of the factory pattern, backend selection, and how to add a new +backend, see :doc:`/source/overview/core-concepts/multi_backend_architecture`. + +New ``isaaclab_physx`` and ``isaaclab_newton`` Extensions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Two new backend extensions have been introduced: + +- **``isaaclab_physx``** — PhysX-specific implementations of asset and sensor classes. +- **``isaaclab_newton``** — Newton-specific implementations of supported asset classes, including + articulations, rigid objects, and deformable objects. + +The following classes have been moved to ``isaaclab_physx``: + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Isaac Lab 2.x + - Isaac Lab 3.0 + * - ``from isaaclab.assets import SurfaceGripper`` + - ``from isaaclab_physx.assets import SurfaceGripper`` + * - ``from isaaclab.assets import SurfaceGripperCfg`` + - ``from isaaclab_physx.assets import SurfaceGripperCfg`` + +.. note:: + + Deformable object public APIs remain in the backend-neutral ``isaaclab`` + package. Continue importing :class:`~isaaclab.assets.DeformableObject`, + :class:`~isaaclab.assets.DeformableObjectCfg`, and + :class:`~isaaclab.assets.DeformableObjectData` from ``isaaclab.assets``. + +.. note:: + + The ``isaaclab_physx`` extension is installed automatically with Isaac Lab. No additional + installation steps are required. + + +.. _schemas-cfg-refactor: + +Schema Configuration Class Refactor +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In Isaac Lab 3.0, the spawner schema cfg classes are split into solver-common +**base classes** (in ``isaaclab.sim.schemas``) and **backend-specific subclasses** +in ``isaaclab_physx.sim.schemas`` and ``isaaclab_newton.sim.schemas``. This makes +the same asset cfg portable across PhysX and Newton backends, and adds slots +for backend-specific asset-level knobs (e.g., MuJoCo gravity compensation). + +For the full design, see :ref:`schema-cfgs`. + +**Class moves and renames** + +The following 2.x class names are kept as deprecated aliases. They forward to +the new location and will be removed in 4.0. + +.. list-table:: + :header-rows: 1 + :widths: 40 60 + + * - Isaac Lab 2.x + - Isaac Lab 3.0 + * - ``RigidBodyPropertiesCfg`` + - :class:`~isaaclab.sim.schemas.RigidBodyBaseCfg` (solver-common fields) + + :class:`~isaaclab_physx.sim.schemas.PhysxRigidBodyPropertiesCfg` (PhysX-specific) + * - ``JointDrivePropertiesCfg`` + - :class:`~isaaclab.sim.schemas.JointDriveBaseCfg` + + :class:`~isaaclab_physx.sim.schemas.PhysxJointDrivePropertiesCfg` + * - ``CollisionPropertiesCfg`` + - :class:`~isaaclab.sim.schemas.CollisionBaseCfg` + + :class:`~isaaclab_physx.sim.schemas.PhysxCollisionPropertiesCfg` + * - ``ArticulationRootPropertiesCfg`` + - :class:`~isaaclab.sim.schemas.ArticulationRootBaseCfg` + + :class:`~isaaclab_physx.sim.schemas.PhysxArticulationRootPropertiesCfg` + * - ``RigidBodyMaterialCfg`` + - :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialBaseCfg` + + :class:`~isaaclab_physx.sim.spawners.materials.PhysxRigidBodyMaterialCfg` + * - ``MeshCollisionPropertiesCfg`` family (``ConvexHullPropertiesCfg``, + ``ConvexDecompositionPropertiesCfg``, ``TriangleMeshPropertiesCfg``, + ``TriangleMeshSimplificationPropertiesCfg``, ``SDFMeshPropertiesCfg``) + - :class:`~isaaclab.sim.schemas.MeshCollisionBaseCfg` + + ``Physx*PropertiesCfg`` family in :mod:`isaaclab_physx.sim.schemas` + * - ``FixedTendonPropertiesCfg``, ``SpatialTendonPropertiesCfg`` + - :class:`~isaaclab_physx.sim.schemas.PhysxFixedTendonPropertiesCfg`, + :class:`~isaaclab_physx.sim.schemas.PhysxSpatialTendonPropertiesCfg` + +**Code migration** + +Existing 2.x code continues to work via the deprecation aliases (with a +``DeprecationWarning``; removed in 4.0): + +.. code-block:: python + + # Isaac Lab 2.x + import isaaclab.sim as sim_utils + rigid_props = sim_utils.RigidBodyPropertiesCfg(disable_gravity=True, linear_damping=0.1) + +Recommended 3.0 pattern when targeting PhysX: + +.. code-block:: python + + # Isaac Lab 3.0 — PhysX backend + from isaaclab_physx.sim.schemas import PhysxRigidBodyPropertiesCfg + rigid_props = PhysxRigidBodyPropertiesCfg(disable_gravity=True, linear_damping=0.1) + +Backend-portable 3.0 pattern (universal-physics fields only): + +.. code-block:: python + + # Isaac Lab 3.0 — backend-portable + from isaaclab.sim.schemas import RigidBodyBaseCfg + rigid_props = RigidBodyBaseCfg(rigid_body_enabled=True, disable_gravity=True) + +**Field renames on** ``JointDriveBaseCfg`` + +Two cfg fields were renamed so their snake_case names map identity-style to the +USD camelCase attribute names. The old names remain as deprecated dataclass +fields on :class:`~isaaclab.sim.schemas.JointDriveBaseCfg` (so +``dataclasses.fields()`` still sees them) and are forwarded to the new fields +in ``__post_init__`` with a ``DeprecationWarning``. Setting **both** the old +and new field on the same instance is silent — the canonical (new) field +wins; the old field's value is discarded after the warning. Both aliases are +scheduled for removal in 4.0. + +.. list-table:: + :header-rows: 1 + :widths: 35 35 30 + + * - Isaac Lab 2.x + - Isaac Lab 3.0 + - USD attribute (unchanged) + * - :attr:`~isaaclab.sim.schemas.JointDriveBaseCfg.max_velocity` + - :attr:`~isaaclab.sim.schemas.JointDriveBaseCfg.max_joint_velocity` + - ``physxJoint:maxJointVelocity`` + * - :attr:`~isaaclab.sim.schemas.JointDriveBaseCfg.max_effort` + - :attr:`~isaaclab.sim.schemas.JointDriveBaseCfg.max_force` + - ``drive::physics:maxForce`` + +Isaac Lab 2.x style still works (emits ``DeprecationWarning``; removed in 4.0): + +.. code-block:: python + + import isaaclab.sim as sim_utils + sim_utils.JointDrivePropertiesCfg(max_effort=80.0, max_velocity=5.0) + +Recommended 3.0 pattern, backend-portable: + +.. code-block:: python + + from isaaclab.sim.schemas import JointDriveBaseCfg + JointDriveBaseCfg(max_force=80.0, max_joint_velocity=5.0) + +Recommended 3.0 pattern, PhysX-targeted: + +.. code-block:: python + + from isaaclab_physx.sim.schemas import PhysxJointDrivePropertiesCfg + PhysxJointDrivePropertiesCfg(max_force=80.0, max_joint_velocity=5.0) + +**New Newton and MuJoCo cfg classes** + +For the Newton backend (and Newton's MuJoCo solver), new cfg classes are +available under :mod:`isaaclab_newton.sim.schemas`: + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Class + - Use case + * - :class:`~isaaclab_newton.sim.schemas.NewtonCollisionPropertiesCfg` + - ``newton:contactMargin`` / ``newton:contactGap`` via ``NewtonCollisionAPI`` + * - :class:`~isaaclab_newton.sim.schemas.NewtonMeshCollisionPropertiesCfg` + - ``newton:maxHullVertices`` via ``NewtonMeshCollisionAPI`` + * - :class:`~isaaclab_newton.sim.schemas.NewtonMaterialPropertiesCfg` + - ``newton:torsionalFriction`` / ``newton:rollingFriction`` via ``NewtonMaterialAPI`` + * - :class:`~isaaclab_newton.sim.schemas.NewtonArticulationRootPropertiesCfg` + - ``newton:selfCollisionEnabled`` via ``NewtonArticulationRootAPI`` + * - :class:`~isaaclab_newton.sim.schemas.MujocoRigidBodyPropertiesCfg` + - ``mjc:gravcomp`` (body-level gravity compensation, MuJoCo solver only) + * - :class:`~isaaclab_newton.sim.schemas.MujocoJointDrivePropertiesCfg` + - ``mjc:actuatorgravcomp`` via ``MjcJointAPI`` (joint-level routing) + +The MuJoCo cfgs subclass their Newton parent because MuJoCo is one of Newton's +solver options. + +.. note:: + + Spawners auto-enable body-level gravity compensation when joint-level + ``actuatorgravcomp=True`` is requested but no Mujoco rigid-body cfg is + provided — without ``gravcomp`` on the bodies, ``actuatorgravcomp`` is a + no-op (no forces to route). To override, pass an explicit + ``MujocoRigidBodyPropertiesCfg`` in ``rigid_props``. See + :ref:`schema-cfgs-gravcomp` for details. + +For complete tables of which fields live on which class and where each lands in +USD, see :ref:`schema-cfgs`. + + +Renaming of ``XformPrimView`` to ``FrameView`` +----------------------------------------------- + +Isaac Lab's ``XformPrimView`` and related classes have been renamed to ``FrameView`` to +better reflect their purpose and avoid confusion with Isaac Sim's ``XFormPrim`` class +hierarchy. The old ``XformPrimView`` name is kept as a deprecated alias. + +The rename applies across all backends: + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Isaac Lab 2.x + - Isaac Lab 3.0 + * - ``BaseXformPrimView`` + - :class:`~isaaclab.sim.views.BaseFrameView` + * - ``UsdXformPrimView`` + - :class:`~isaaclab.sim.views.UsdFrameView` + * - ``XformPrimView`` + - :class:`~isaaclab.sim.views.FrameView` + * - ``FabricXformPrimView`` + - :class:`~isaaclab_physx.sim.views.FabricFrameView` + * - ``NewtonSiteXformPrimView`` + - :class:`~isaaclab_newton.sim.views.NewtonSiteFrameView` + +For most users, the only change needed is updating imports: + +.. code-block:: python + + # Before + from isaaclab.sim.views import XformPrimView + + # After + from isaaclab.sim.views import FrameView + +The :class:`~isaaclab.sim.views.FrameView` factory automatically dispatches to the correct +backend (:class:`~isaaclab_physx.sim.views.FabricFrameView` for PhysX, +:class:`~isaaclab_newton.sim.views.NewtonSiteFrameView` for Newton) based on the active +physics backend. The deprecated ``XformPrimView`` alias continues to work but will be +removed in a future release. + + +Unchanged Imports +----------------- + +The following asset classes remain in the ``isaaclab`` package and can still be imported as before: + +- :class:`~isaaclab.assets.Articulation`, :class:`~isaaclab.assets.ArticulationCfg`, :class:`~isaaclab.assets.ArticulationData` +- :class:`~isaaclab.assets.RigidObject`, :class:`~isaaclab.assets.RigidObjectCfg`, :class:`~isaaclab.assets.RigidObjectData` +- :class:`~isaaclab.assets.RigidObjectCollection`, :class:`~isaaclab.assets.RigidObjectCollectionCfg`, :class:`~isaaclab.assets.RigidObjectCollectionData` + +These classes now inherit from new abstract base classes but maintain full backward compatibility. + +The following sensor classes also remain in the ``isaaclab`` package with unchanged imports: + +- :class:`~isaaclab.sensors.ContactSensor`, :class:`~isaaclab.sensors.ContactSensorCfg`, :class:`~isaaclab.sensors.ContactSensorData` +- :class:`~isaaclab.sensors.Imu`, :class:`~isaaclab.sensors.ImuCfg`, :class:`~isaaclab.sensors.ImuData` +- :class:`~isaaclab.sensors.Pva`, :class:`~isaaclab.sensors.PvaCfg`, :class:`~isaaclab.sensors.PvaData` +- :class:`~isaaclab.sensors.FrameTransformer`, :class:`~isaaclab.sensors.FrameTransformerCfg`, :class:`~isaaclab.sensors.FrameTransformerData` +- :class:`~isaaclab.sensors.JointWrenchSensor`, :class:`~isaaclab.sensors.JointWrenchSensorCfg`, + :class:`~isaaclab.sensors.JointWrenchSensorData` + +These sensor classes now use factory patterns that automatically instantiate the appropriate backend +implementation (PhysX by default), maintaining full backward compatibility. + +.. note:: + + The ``Imu`` sensor in Isaac Lab 3.0 is **not** the same as the ``Imu`` sensor in 2.x. + The old ``Imu`` (full state sensor) has been renamed to :class:`~isaaclab.sensors.Pva`. + The new :class:`~isaaclab.sensors.Imu` is a lightweight sensor that only provides angular velocity + and linear acceleration. See :ref:`imu-to-pva-migration` below for details. + +If you need to import the PhysX sensor implementations directly (e.g., for type hints or subclassing), +you can import from ``isaaclab_physx.sensors``: + +.. code-block:: python + + # Direct PhysX implementation imports + from isaaclab_physx.sensors import ContactSensor, ContactSensorData + from isaaclab_physx.sensors import Imu, ImuData + from isaaclab_physx.sensors import Pva, PvaData + from isaaclab_physx.sensors import FrameTransformer, FrameTransformerData + from isaaclab_physx.sensors import JointWrenchSensor, JointWrenchSensorData + + +New ``isaaclab_newton`` Extension +--------------------------------- + +A new extension ``isaaclab_newton`` provides Newton physics backend implementations for: + +- :class:`~isaaclab_newton.assets.Articulation` and :class:`~isaaclab_newton.assets.ArticulationData` +- :class:`~isaaclab_newton.assets.RigidObject` and :class:`~isaaclab_newton.assets.RigidObjectData` +- :class:`~isaaclab_newton.sensors.JointWrenchSensor` and + :class:`~isaaclab_newton.sensors.JointWrenchSensorData` + +These classes implement the same base interfaces as their PhysX counterparts +(:class:`~isaaclab.assets.BaseArticulation`, :class:`~isaaclab.assets.BaseRigidObject`), +ensuring a consistent API across backends. They use the same warp-based data conventions +(``wp.array`` with structured types, ``_index`` / ``_mask`` write methods). + +.. note:: + + The ``isaaclab_newton`` extension requires the ``newton`` package and its dependencies + (``mujoco``, ``mujoco-warp``). These are installed automatically when installing the + ``isaaclab_newton`` package. + +If you need to import Newton implementations directly (e.g., for type hints or subclassing): + +.. code-block:: python + + from isaaclab_newton.assets import Articulation as NewtonArticulation + from isaaclab_newton.assets import RigidObject as NewtonRigidObject + + +Deformable Object API Changes +------------------------------ + +Isaac Lab 3.0 updates the deformable body API to align with the current Omni Physics 110.0 +release. The old soft body API has been deprecated and replaced by two distinct deformable +types: **volume deformables** (3D FEM tetrahedral meshes) and **surface deformables** (2D +triangle cloth meshes). The deformable type is determined by the physics material assigned: + +- :class:`~isaaclab_physx.sim.PhysxDeformableBodyMaterialCfg` for PhysX volume deformables. +- :class:`~isaaclab_physx.sim.PhysxSurfaceDeformableBodyMaterialCfg` for PhysX surface deformables. +- :class:`~isaaclab_newton.sim.spawners.materials.NewtonDeformableBodyMaterialCfg` for Newton volume deformables. +- :class:`~isaaclab_newton.sim.spawners.materials.NewtonSurfaceDeformableBodyMaterialCfg` for Newton surface + deformables. + +Deformable property and material cfgs are backend-specific. Several properties on +:class:`~isaaclab_physx.sim.PhysxDeformableBodyPropertiesCfg` have been removed or added to +match the new Omni Physics schema. The common +:class:`~isaaclab.sim.DeformableBodyPropertiesBaseCfg` is now empty; OmniPhysics +deformable body fields are owned by :class:`~isaaclab_physx.sim.PhysxDeformableBodyPropertiesCfg`. + +For a comprehensive guide covering the full deformable API migration — including removed and +added properties, material changes, code examples for both volume and surface deformables, and +current limitations — see :ref:`migrating-deformables`. + + +.. _imu-to-pva-migration: + +IMU Sensor Renamed to PVA; New Lightweight IMU Sensor +----------------------------------------------------- + +The old ``Imu`` sensor has been renamed to **PVA** (Pose Velocity Acceleration) because it provided +full pose, velocity, and acceleration data — far more than a real inertial measurement unit measures. +A new lightweight **IMU** sensor has been introduced that only provides the two physical quantities +a real IMU measures: angular velocity (gyroscope) and linear acceleration (accelerometer). + +If you were using the old ``Imu`` sensor, you need to decide which new sensor to use: + +- Use :class:`~isaaclab.sensors.Pva` / :class:`~isaaclab.sensors.PvaCfg` if you need full state + data (pose, linear velocity, angular velocity, linear and angular acceleration, projected gravity). +- Use :class:`~isaaclab.sensors.Imu` / :class:`~isaaclab.sensors.ImuCfg` if you only need angular + velocity and linear acceleration (as a real IMU provides). + +For configuration and data access examples, see the :ref:`overview_sensors_pva`. + +**Import changes:** + +.. code-block:: python + + # Before (Isaac Lab 2.x) — the old IMU provided full state + from isaaclab.sensors import Imu, ImuCfg, ImuData + + # After (Isaac Lab 3.x) — use PVA for the same full-state sensor + from isaaclab.sensors import Pva, PvaCfg, PvaData + + # Or use the new lightweight IMU for angular velocity + linear acceleration only + from isaaclab.sensors import Imu, ImuCfg, ImuData + +**Configuration changes:** + +The ``gravity_bias`` configuration parameter has been removed from both sensors: + +- **PVA** reports raw kinematic acceleration (no gravity contribution), as the acceleration + is derived from finite differencing of velocities which do not include gravity. +- **IMU** unconditionally includes gravity in its accelerometer readings, matching the behavior + of a real accelerometer. The gravity vector is automatically queried from the simulation. + +.. code-block:: python + + # Before (Isaac Lab 2.x) + imu_cfg = ImuCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + gravity_bias=(0.0, 0.0, 9.81), # had to be configured manually + ) + + # After (Isaac Lab 3.x) — PVA (no gravity in acceleration) + pva_cfg = PvaCfg(prim_path="{ENV_REGEX_NS}/Robot/base") + + # After (Isaac Lab 3.x) — IMU (gravity always included automatically) + imu_cfg = ImuCfg(prim_path="{ENV_REGEX_NS}/Robot/base") + +**Observation function changes:** + +.. code-block:: python + + # Before (Isaac Lab 2.x) + from isaaclab.envs.mdp import imu_orientation, imu_projected_gravity + + # After (Isaac Lab 3.x) + from isaaclab.envs.mdp import pva_orientation, pva_projected_gravity + +**Data property changes:** + +The new ``ImuData`` only provides ``ang_vel_b`` and ``lin_acc_b``. If you were accessing other +properties (``pos_w``, ``quat_w``, ``lin_vel_b``, ``ang_acc_b``, ``projected_gravity_b``), switch +to :class:`~isaaclab.sensors.PvaData` which provides all of them. + + +Sensor Pose Properties Deprecation +---------------------------------- + +The ``pose_w``, ``pos_w``, and ``quat_w`` properties on :class:`~isaaclab.sensors.ContactSensorData` +are deprecated and will be removed in a future release. + +If you need to track sensor poses in world frame, please use a dedicated sensor such as +:class:`~isaaclab.sensors.FrameTransformer` instead. + +**Before (deprecated):** + +.. code-block:: python + + # Using pose properties directly on sensor data + sensor_pos = contact_sensor.data.pos_w + sensor_quat = contact_sensor.data.quat_w + +**After (recommended):** + +.. code-block:: python + + # Use FrameTransformer to track sensor pose + frame_transformer = FrameTransformer(FrameTransformerCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + target_frames=[ + FrameTransformerCfg.FrameCfg(prim_path="{ENV_REGEX_NS}/Robot/sensor_link"), + ], + )) + sensor_pos = frame_transformer.data.target_pos_w + sensor_quat = frame_transformer.data.target_quat_w + + +Articulation Joint Wrench Data Moved to ``JointWrenchSensor`` +------------------------------------------------------------- + +The ``ArticulationData.body_incoming_joint_wrench_b`` property has been removed. In +Isaac Lab 3.0, incoming joint reaction wrenches are exposed through +:class:`~isaaclab.sensors.JointWrenchSensor`, which has PhysX and Newton backend +implementations and returns separate force [N] and torque [N·m] buffers. +The sensor reports wrenches in the child-side incoming joint frame, with torque +referenced at the child-side joint anchor. + +For configuration and data access examples, see the :ref:`overview_sensors_joint_wrench`. + +**Before (Isaac Lab 2.x):** + +.. code-block:: python + + wrench_b = robot.data.body_incoming_joint_wrench_b.torch[:, body_ids] + +**After (Isaac Lab 3.x):** + +.. code-block:: python + + import torch + from isaaclab.scene import InteractiveSceneCfg + from isaaclab.sensors import JointWrenchSensorCfg + + class MySceneCfg(InteractiveSceneCfg): + robot = ROBOT_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + joint_wrench = JointWrenchSensorCfg(prim_path="{ENV_REGEX_NS}/Robot") + + sensor = env.scene.sensors["joint_wrench"] + data = sensor.data + wrench_j = torch.cat( + ( + data.force.torch[:, body_ids], + data.torque.torch[:, body_ids], + ), + dim=-1, + ) + +Use :attr:`~isaaclab.sensors.BaseJointWrenchSensor.body_names` or +:meth:`~isaaclab.sensors.BaseJointWrenchSensor.find_bodies` to map sensor entries to +articulation body names. PhysX reports one entry for every link, including the articulation +root link. Newton reports the child bodies of reportable incoming joints. + +For manager-based environments, update observations that used the articulation data property to +depend on the joint-wrench sensor instead: + +.. code-block:: python + + import isaaclab.envs.mdp as mdp + from isaaclab.managers import SceneEntityCfg + from isaaclab.managers import ObservationTermCfg as ObsTerm + from isaaclab.scene import InteractiveSceneCfg + from isaaclab.sensors import JointWrenchSensorCfg + + class MySceneCfg(InteractiveSceneCfg): + robot = ROBOT_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + joint_wrench = JointWrenchSensorCfg(prim_path="{ENV_REGEX_NS}/Robot") + + feet_body_forces = ObsTerm( + func=mdp.body_incoming_wrench, + params={ + "sensor_cfg": SceneEntityCfg( + "joint_wrench", + body_names=["left_foot", "right_foot"], + ) + }, + ) + + +Multi-Backend Support: PresetCfg Pattern +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Isaac Lab 3.0 introduces a **PresetCfg pattern** for writing environment configurations +that work with both the PhysX and Newton backends. Instead of hard-coding a single +physics config, environments declare named configuration variants. The active variant +is selected at launch via a Hydra CLI override. + +What is PresetCfg? +------------------ + +:class:`~isaaclab_tasks.utils.PresetCfg` is a base ``@configclass`` whose typed fields +represent named variants of a configuration section. The field named ``default`` is used +when no CLI override is given. Other fields are named presets selectable with +``presets=`` on the command line: + +.. code-block:: python + + from isaaclab_tasks.utils import PresetCfg + from isaaclab.utils.configclass import configclass + + @configclass + class MyPhysicsCfg(PresetCfg): + default: PhysxCfg = PhysxCfg(...) # used when no override is given + physx: PhysxCfg = PhysxCfg(...) # selected by physics=physx + newton_mjwarp: NewtonCfg = NewtonCfg(...) # selected by physics=newton_mjwarp + +Selecting a preset at launch +----------------------------- + +Pass ``physics=newton_mjwarp`` (or ``physics=physx``) on the CLI to swap the entire config section. +The legacy ``presets=NAME`` form still works for the same values. + +.. code-block:: bash + + # Run with Newton backend + python train.py task=Isaac-Franka-Cabinet-v0 physics=newton_mjwarp + + # Run with default (PhysX) backend + python train.py task=Isaac-Franka-Cabinet-v0 + +Adding Multi-Backend Support to an Environment +----------------------------------------------- + +**Step 1 — Physics config** + +Replace a plain ``PhysxCfg(...)`` assignment in ``__post_init__`` with a ``PresetCfg`` +subclass that carries both a PhysX and a Newton variant. + +*Before:* + +.. code-block:: python + + def __post_init__(self): + self.sim.dt = 1 / 60 + self.sim.physics = PhysxCfg(bounce_threshold_velocity=0.2) + +*After:* + +.. code-block:: python + + from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + from isaaclab_physx.physics import PhysxCfg + from isaaclab_tasks.utils import PresetCfg + + @configclass + class ReachPhysicsCfg(PresetCfg): + default: PhysxCfg = PhysxCfg(bounce_threshold_velocity=0.2) + physx: PhysxCfg = PhysxCfg(bounce_threshold_velocity=0.2) + newton_mjwarp: NewtonCfg = NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=20, nconmax=20, ls_iterations=20, + cone="pyramidal", ls_parallel=True, + integrator="implicitfast", impratio=1, + ), + num_substeps=1, + debug_mode=False, + ) + + # In the env cfg __post_init__: + def __post_init__(self): + self.sim.dt = 1 / 60 + self.sim.physics = ReachPhysicsCfg() + +Key Newton solver parameters: + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Parameter + - Effect + * - ``njmax`` + - Max constraint rows; set ≥ expected contact count per env + * - ``nconmax`` + - Max contacts per env + * - ``ls_iterations`` + - Linear solver iterations (higher = more stable, slower) + * - ``cone`` + - ``"pyramidal"`` (fast) or ``"elliptic"`` (more accurate) + * - ``integrator`` + - ``"implicitfast"`` (recommended) or ``"euler"`` + * - ``impratio`` + - Impedance ratio; >1 improves soft contact stability + * - ``num_substeps`` + - Physics substeps per environment step + +**Step 2 — Differentiating Newton and PhysX Configs** + +Not all configurations may be the same between Newton and PhysX simulations. +We can provide a Newton-specific config such as: + +.. code-block:: python + + @configclass + class EventCfg: + """Full event config (PhysX-compatible).""" + robot_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={...}, + ) + reset_all = EventTerm(func=mdp.reset_scene_to_default, mode="reset") + reset_robot_joints = EventTerm( + func=mdp.reset_joints_by_offset, mode="reset", params={...} + ) + + + @configclass + class _EnvNewtonEventCfg: + """Newton-compatible events.""" + reset_all = EventTerm(func=mdp.reset_scene_to_default, mode="reset") + reset_robot_joints = EventTerm( + func=mdp.reset_joints_by_offset, mode="reset", params={...} + ) + + + @configclass + class EnvEventCfg(PresetCfg): + default: EventCfg = EventCfg() + physx: EventCfg = EventCfg() + newton_mjwarp: _EnvNewtonEventCfg = _EnvNewtonEventCfg() + +Then change the ``events`` field in your env cfg from ``EventCfg`` to ``EnvEventCfg``: + +.. code-block:: python + + @configclass + class MyEnvCfg(ManagerBasedRLEnvCfg): + events: EnvEventCfg = EnvEventCfg() # was: EventCfg = EventCfg() + + +RigidObjectCollection API Renaming +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The :class:`~isaaclab_physx.assets.RigidObjectCollection` and +:class:`~isaaclab_physx.assets.RigidObjectCollectionData` classes have undergone an API rename +to provide consistency with other asset classes. The ``object_*`` naming convention has been +deprecated in favor of ``body_*``. + + +Method Renames +-------------- + +The following methods have been renamed. The old methods are deprecated and will be removed in a +future release: + ++------------------------------------------+------------------------------------------+ +| Deprecated (2.x) | New (3.0) | ++==========================================+==========================================+ +| ``write_object_state_to_sim()`` | ``write_body_state_to_sim()`` | ++------------------------------------------+------------------------------------------+ +| ``write_object_link_state_to_sim()`` | ``write_body_link_state_to_sim()`` | ++------------------------------------------+------------------------------------------+ +| ``write_object_pose_to_sim()`` | ``write_body_pose_to_sim()`` | ++------------------------------------------+------------------------------------------+ +| ``write_object_link_pose_to_sim()`` | ``write_body_link_pose_to_sim()`` | ++------------------------------------------+------------------------------------------+ +| ``write_object_com_pose_to_sim()`` | ``write_body_com_pose_to_sim()`` | ++------------------------------------------+------------------------------------------+ +| ``write_object_velocity_to_sim()`` | ``write_body_com_velocity_to_sim()`` | ++------------------------------------------+------------------------------------------+ +| ``write_object_com_velocity_to_sim()`` | ``write_body_com_velocity_to_sim()`` | ++------------------------------------------+------------------------------------------+ +| ``write_object_link_velocity_to_sim()`` | ``write_body_link_velocity_to_sim()`` | ++------------------------------------------+------------------------------------------+ +| ``find_objects()`` | ``find_bodies()`` | ++------------------------------------------+------------------------------------------+ + + +Property Renames (Data Class) +----------------------------- + +The following properties on :class:`~isaaclab_physx.assets.RigidObjectCollectionData` have been +renamed. The old properties are deprecated and will be removed in a future release: + ++------------------------------------------+------------------------------------------+ +| Deprecated (2.x) | New (3.0) | ++==========================================+==========================================+ +| ``default_object_state`` | ``default_body_state`` | ++------------------------------------------+------------------------------------------+ +| ``object_names`` | ``body_names`` | ++------------------------------------------+------------------------------------------+ +| ``object_link_pose_w`` | ``body_link_pose_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_link_vel_w`` | ``body_link_vel_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_pose_w`` | ``body_com_pose_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_vel_w`` | ``body_com_vel_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_state_w`` | ``body_state_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_link_state_w`` | ``body_link_state_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_state_w`` | ``body_com_state_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_acc_w`` | ``body_com_acc_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_pose_b`` | ``body_com_pose_b`` | ++------------------------------------------+------------------------------------------+ +| ``object_link_pos_w`` | ``body_link_pos_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_link_quat_w`` | ``body_link_quat_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_link_lin_vel_w`` | ``body_link_lin_vel_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_link_ang_vel_w`` | ``body_link_ang_vel_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_pos_w`` | ``body_com_pos_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_quat_w`` | ``body_com_quat_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_lin_vel_w`` | ``body_com_lin_vel_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_ang_vel_w`` | ``body_com_ang_vel_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_lin_acc_w`` | ``body_com_lin_acc_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_ang_acc_w`` | ``body_com_ang_acc_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_pos_b`` | ``body_com_pos_b`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_quat_b`` | ``body_com_quat_b`` | ++------------------------------------------+------------------------------------------+ +| ``object_link_lin_vel_b`` | ``body_link_lin_vel_b`` | ++------------------------------------------+------------------------------------------+ +| ``object_link_ang_vel_b`` | ``body_link_ang_vel_b`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_lin_vel_b`` | ``body_com_lin_vel_b`` | ++------------------------------------------+------------------------------------------+ +| ``object_com_ang_vel_b`` | ``body_com_ang_vel_b`` | ++------------------------------------------+------------------------------------------+ +| ``object_pose_w`` | ``body_pose_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_pos_w`` | ``body_pos_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_quat_w`` | ``body_quat_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_vel_w`` | ``body_vel_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_lin_vel_w`` | ``body_lin_vel_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_ang_vel_w`` | ``body_ang_vel_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_lin_vel_b`` | ``body_lin_vel_b`` | ++------------------------------------------+------------------------------------------+ +| ``object_ang_vel_b`` | ``body_ang_vel_b`` | ++------------------------------------------+------------------------------------------+ +| ``object_acc_w`` | ``body_acc_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_lin_acc_w`` | ``body_lin_acc_w`` | ++------------------------------------------+------------------------------------------+ +| ``object_ang_acc_w`` | ``body_ang_acc_w`` | ++------------------------------------------+------------------------------------------+ + +.. note:: + + All deprecated methods and properties will issue a deprecation warning when used. Your existing + code will continue to work, but you should migrate to the new API to avoid issues in future releases. + + +Migration Example +----------------- + +Here's a complete example showing how to update your code: + +**Before (Isaac Lab 2.x):** + +.. code-block:: python + + from isaaclab.assets import DeformableObject, DeformableObjectCfg + from isaaclab.assets import SurfaceGripper, SurfaceGripperCfg + from isaaclab.assets import RigidObjectCollection + + # Using deprecated root_physx_view + robot = scene["robot"] + masses = robot.root_physx_view.get_masses() + + # Using deprecated object_* API + collection = scene["object_collection"] + poses = collection.data.object_pose_w + collection.write_object_state_to_sim(state, env_ids=env_ids, object_ids=object_ids) + +**After (Isaac Lab 3.0):** + +.. code-block:: python + + from isaaclab.assets import DeformableObject, DeformableObjectCfg + from isaaclab_physx.assets import SurfaceGripper, SurfaceGripperCfg + from isaaclab.assets import RigidObjectCollection # unchanged + + # Using new root_view property + robot = scene["robot"] + masses = robot.root_view.get_masses() + + # Using new body_* API + collection = scene["object_collection"] + poses = collection.data.body_pose_w + collection.write_body_state_to_sim(state, env_ids=env_ids, body_ids=object_ids) + + +Quaternion Format +~~~~~~~~~~~~~~~~~ + +**The quaternion format changed from WXYZ to XYZW.** + ++------------------+----------------------------------+----------------------------------+ +| Component | Old Format (WXYZ) | New Format (XYZW) | ++==================+==================================+==================================+ +| Order | ``(w, x, y, z)`` | ``(x, y, z, w)`` | ++------------------+----------------------------------+----------------------------------+ +| Identity | ``(1.0, 0.0, 0.0, 0.0)`` | ``(0.0, 0.0, 0.0, 1.0)`` | ++------------------+----------------------------------+----------------------------------+ + + +Why This Change? +---------------- + +The new XYZW format aligns with: + +- **Warp**: NVIDIA's spatial computing framework +- **PhysX**: PhysX physics engine +- **Newton**: Newton multi-solver framework + +This alignment removes the need for internal quaternion conversions, making the code simpler, +faster, and less error-prone. + + +What You Need to Update +----------------------- + +Any hard-coded quaternion values in your code need to be converted from WXYZ to XYZW. +This includes: + +1. **Configuration files** - ``rot`` parameters in asset configs +2. **Task definitions** - Goal poses, initial states +3. **Controller parameters** - Target orientations +4. **Documentation** - Code examples with quaternions + +Also, if you were relying on the :func:`~isaaclab.utils.math.convert_quat` function to convert quaternions, this should +no longer be needed. (This would happen if you were pulling values from the views directly.) + +Example: Updating Asset Configuration +------------------------------------- + +**Before (WXYZ):** + +.. code-block:: python + + from isaaclab.assets import AssetBaseCfg + + cfg = AssetBaseCfg( + init_state=AssetBaseCfg.InitialStateCfg( + pos=(0.0, 0.0, 0.5), + rot=(1.0, 0.0, 0.0, 0.0), # OLD: w, x, y, z + ), + ) + +**After (XYZW):** + +.. code-block:: python + + from isaaclab.assets import AssetBaseCfg + + cfg = AssetBaseCfg( + init_state=AssetBaseCfg.InitialStateCfg( + pos=(0.0, 0.0, 0.5), + rot=(0.0, 0.0, 0.0, 1.0), # NEW: x, y, z, w + ), + ) + + +Using the Quaternion Finder Tool +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We provide a tool to help you find and fix quaternions in your codebase automatically. This is not a bulletproof tool, +but it should help you find most of the quaternions that need to be updated. You *should* review the results manually. + +.. warning:: + Do not run the tool on the whole codebase! If you run the tool on our own packages (isaaclab, or isaaclab_tasks for + instance) it will find all the quaternions that we already converted. This tool is only meant to be used on your own + codebase with no overlap with our own packages. + +Finding Quaternions +------------------- + +Run the tool to scan your code for potential quaternions: + +.. code-block:: bash + + # Scan the 'source' directory (default) + python scripts/tools/find_quaternions.py + + # Scan a specific path + python scripts/tools/find_quaternions.py --path my_project/ + + # Compare against a different branch + python scripts/tools/find_quaternions.py --base release/3.0.0-beta2 + +.. tip:: + We recommend always running the tool with a custom base branch *and* a specific path. + + +The tool will show you: + +- Quaternions that haven't been updated (marked as ``UNCHANGED``) +- Whether each looks like a WXYZ identity quaternion (``WXYZ_IDENTITY``) +- Whether the format is likely WXYZ (``LIKELY_WXYZ``) + + +Understanding the Output +------------------------ + +.. code-block:: text + + my_project/robot_cfg.py:42:8 ⚠ UNCHANGED [WXYZ_IDENTITY] + Values: [1.0, 0.0, 0.0, 0.0] + Source: rot=(1.0, 0.0, 0.0, 0.0), + +This tells you: + +- **File and line**: ``my_project/robot_cfg.py:42`` +- **Status**: ``UNCHANGED`` means this line hasn't been modified yet +- **Flag**: ``WXYZ_IDENTITY`` means it's the identity quaternion in old WXYZ format +- **Values**: The actual quaternion values found +- **Source**: The line of code for context + + +Filtering Results +----------------- + +Focus on specific types of quaternions: + +.. code-block:: bash + + # Only show identity quaternions [1, 0, 0, 0] + python scripts/tools/find_quaternions.py --check-identity + + # Only show quaternions likely in WXYZ format + python scripts/tools/find_quaternions.py --likely-wxyz + + # Show ALL potential quaternions (ignore format heuristics) + python scripts/tools/find_quaternions.py --all-quats + + +Fixing Quaternions Automatically +-------------------------------- + +The tool can automatically convert quaternions from WXYZ to XYZW: + +.. code-block:: bash + + # Interactive mode: prompts before each fix + python scripts/tools/find_quaternions.py --fix + + # Only fix identity quaternions (safest option) + python scripts/tools/find_quaternions.py --fix-identity-only + + # Preview changes without applying them + python scripts/tools/find_quaternions.py --fix --dry-run + + # Apply all fixes without prompting + python scripts/tools/find_quaternions.py --fix --force + + +Interactive Fix Example +----------------------- + +When running with ``--fix``, you'll see something like: + +.. code-block:: text + + ──────────────────────────────────────────────────────────────────────────────── + 📍 my_project/robot_cfg.py:42 [WXYZ_IDENTITY] + ──────────────────────────────────────────────────────────────────────────────── + 40 | init_state=AssetBaseCfg.InitialStateCfg( + 41 | pos=(0.0, 0.0, 0.5), + >>> 42 | rot=(1.0, 0.0, 0.0, 0.0), + 43 | ), + 44 | ) + ──────────────────────────────────────────────────────────────────────────────── + Change: [1.0, 0.0, 0.0, 0.0] → [0.0, 0.0, 0.0, 1.0] + Result: rot=(0.0, 0.0, 0.0, 1.0), + Apply this fix? [Y/n/a/q]: + +Options: + +- **Y** (yes): Apply this fix +- **n** (no): Skip this one +- **a** (all): Apply all remaining fixes without asking +- **q** (quit): Stop fixing + + +How the Tool Works +------------------ + +The tool uses several techniques to find quaternions: + +1. **Python files**: Parses the code using AST (Abstract Syntax Tree) to find + 4-element tuples and lists with numeric values. + +2. **JSON files**: Uses regex to find 4-element arrays. + +3. **RST documentation**: Searches for quaternion-like patterns in docs. + +To identify if something is a quaternion, the tool checks: + +- Is it exactly 4 numeric values? +- Does the sum of squares ≈ 1? (unit quaternion property) +- Does it match known patterns like identity quaternions? + +To determine if it's in WXYZ format: + +- Is the first value 1.0 and rest are 0? (WXYZ identity) +- Is the first value a common cos(θ/2) value like 0.707, 0.866, etc.? +- Is the pattern consistent with first-element being the scalar part? + + +Best Practices for Migration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +1. **Start with a clean git state** - Commit your work before running fixes. + +2. **Run the tool first without ``--fix``** - Review what will be changed. + +3. **Fix identity quaternions first** - They're the most common and safest: + + .. code-block:: bash + + python scripts/tools/find_quaternions.py --fix-identity-only + +4. **Review non-identity quaternions manually** - Some 4-element lists might + not be quaternions (e.g., RGBA colors, bounding boxes). + +5. **Test your code** - Run your simulations to verify everything works correctly. + +6. **Check documentation** - Update any docs or comments that mention quaternion format. + + +Using the Runtime Quaternion Access Detector +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The quaternion finder tool above covers hard-coded values in source files, +but it cannot see quaternions that are *read* from asset/sensor data at +runtime. For those, Isaac Lab ships a +runtime detector hook on :class:`~isaaclab.utils.warp.ProxyArray` that flags +every ``.torch`` access on a ``wp.quatf``-typed property and points at the +exact call site. Use it after the source-level migration to catch the cases +the finder tool can't reach. + +Enable it by setting an environment variable before launching your script: + +.. code-block:: bash + + export WARN_ON_TORCH_QUATF_ACCESS=1 + ./isaaclab.sh -p my_script.py + +Every read of ``.torch`` on a ``ProxyArray`` whose underlying ``wp.array`` has +dtype ``wp.quatf`` then emits a :class:`UserWarning` with the message: + +.. code-block:: text + + Reading .torch on a wp.quatf-typed ProxyArray. The Isaac Lab quaternion + convention changed from (w, x, y, z) in 2.x to (x, y, z, w) in 3.x. If + your code assumes the old order, this is likely the source of incorrect + rotations. Unset WARN_ON_TORCH_QUATF_ACCESS to silence this warning. + +The warning's traceback points at the exact line that performed the access +(via ``stacklevel=2``), so you can walk through the matches in your code and +confirm each one uses the new ``(x, y, z, w)`` order. + +Typical workflow: + +1. Run a representative scene or task with the env var set. +2. Triage every warning location — check whether the call site assumes + ``(w, x, y, z)`` (Lab 2.x) or ``(x, y, z, w)`` (Lab 3.x). +3. Migrate the call sites that still expect the old order. +4. Re-run with the env var still set; the warnings should be gone (or only + come from intentionally-handled call sites). +5. Unset the env var for production runs — the detector adds an + ``os.environ`` lookup per ``.torch`` access, which is cheap but not free. + +The detector covers only ``ProxyArray.torch`` reads. Direct accesses on the +underlying ``wp.array`` (via ``ProxyArray.warp``) are not flagged, because +warp uses ``(x, y, z, w)`` natively and so a warp-side read is unaffected +by the convention change. + + +API Changes +~~~~~~~~~~~ + +The ``convert_quat`` function has been removed +---------------------------------------------- + +Previously, IsaacLab had a utility function to convert between quaternion formats: + +.. code-block:: python + + # OLD - No longer needed + from isaaclab.utils.math import convert_quat + quat_xyzw = convert_quat(quat_wxyz, "xyzw") + +Since everything now uses XYZW natively, this function is no longer needed. +If you were using it, simply remove the conversion calls. + + +Math utility functions now expect XYZW +-------------------------------------- + +All quaternion functions in :mod:`isaaclab.utils.math` now expect and return +quaternions in XYZW format: + +- :func:`~isaaclab.utils.math.quat_mul` +- :func:`~isaaclab.utils.math.quat_apply` +- :func:`~isaaclab.utils.math.quat_from_euler_xyz` +- :func:`~isaaclab.utils.math.euler_xyz_from_quat` +- :func:`~isaaclab.utils.math.quat_from_matrix` +- :func:`~isaaclab.utils.math.matrix_from_quat` +- And all other quaternion utilities + + +ProxyArray Backend for Asset and Sensor Data +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +All ``.data.*`` properties on asset and sensor classes now return +:class:`~isaaclab.utils.warp.ProxyArray` instead of ``torch.Tensor``. ``ProxyArray`` wraps +the underlying ``wp.array`` and exposes explicit ``.torch`` and ``.warp`` accessors. This +change applies to all asset classes (:class:`~isaaclab.assets.Articulation`, +:class:`~isaaclab.assets.RigidObject`, :class:`~isaaclab.assets.RigidObjectCollection`, +:class:`~isaaclab.assets.DeformableObject`) and all sensor classes +(:class:`~isaaclab_physx.sensors.ContactSensor`, :class:`~isaaclab_physx.sensors.Imu`, +:class:`~isaaclab_physx.sensors.Pva`, :class:`~isaaclab_physx.sensors.FrameTransformer`). + +To use a data property as a ``torch.Tensor``, append ``.torch``: + +.. code-block:: python + + # Before (Isaac Lab 2.x) + root_pos = robot.data.root_pos_w # torch.Tensor + joint_pos = robot.data.joint_pos # torch.Tensor + contact_forces = sensor.data.net_forces_w # torch.Tensor + + # After (Isaac Lab 3.x) + root_pos = robot.data.root_pos_w # ProxyArray + joint_pos = robot.data.joint_pos # ProxyArray + contact_forces = sensor.data.net_forces_w # ProxyArray + + # To use with torch operations, access .torch + root_pos_torch = robot.data.root_pos_w.torch # torch.Tensor + joint_pos_torch = robot.data.joint_pos.torch # torch.Tensor + contact_torch = sensor.data.net_forces_w.torch # torch.Tensor + +Common patterns that need updating: + +.. code-block:: python + + # Cloning data + # Before: + pos = robot.data.root_pos_w.clone() + # After: + pos = robot.data.root_pos_w.torch.clone() + + # Creating zero tensors with matching shape + # Before: + zeros = torch.zeros_like(robot.data.root_pos_w) + # After: + zeros = torch.zeros_like(robot.data.root_pos_w.torch) + + # Assertions in tests + # Before: + torch.testing.assert_close(robot.data.root_pos_w, expected) + # After: + torch.testing.assert_close(robot.data.root_pos_w.torch, expected) + +.. list-table:: Affected classes + :header-rows: 1 + :widths: 40 60 + + * - Class + - Package + * - :class:`~isaaclab.assets.Articulation` + - ``isaaclab`` / ``isaaclab_physx`` + * - :class:`~isaaclab.assets.RigidObject` + - ``isaaclab`` / ``isaaclab_physx`` + * - :class:`~isaaclab.assets.RigidObjectCollection` + - ``isaaclab`` / ``isaaclab_physx`` + * - :class:`~isaaclab.assets.DeformableObject` + - ``isaaclab`` / ``isaaclab_physx`` / ``isaaclab_newton`` + * - :class:`~isaaclab_physx.sensors.ContactSensor` + - ``isaaclab_physx`` + * - :class:`~isaaclab_physx.sensors.Imu` + - ``isaaclab_physx`` + * - :class:`~isaaclab_physx.sensors.Pva` + - ``isaaclab_physx`` + * - :class:`~isaaclab_physx.sensors.FrameTransformer` + - ``isaaclab_physx`` + * - :class:`~isaaclab.sensors.RayCaster` + - ``isaaclab`` + * - :class:`~isaaclab.sensors.RayCasterCamera` + - ``isaaclab`` + * - :class:`~isaaclab.sensors.MultiMeshRayCaster` + - ``isaaclab`` + * - :class:`~isaaclab.sensors.MultiMeshRayCasterCamera` + - ``isaaclab`` + +.. note:: + + ``wp.to_torch(proxy_array)`` is temporarily supported by a compatibility shim. It returns + the same zero-copy tensor as ``proxy_array.torch`` and emits a one-time + ``DeprecationWarning``. This shim exists for older migration code and will be removed in a + future release; prefer ``.torch`` in new code. + + +Ray Caster Warp Backend +~~~~~~~~~~~~~~~~~~~~~~~ + +The :class:`~isaaclab.sensors.RayCaster`, :class:`~isaaclab.sensors.RayCasterCamera`, +:class:`~isaaclab.sensors.MultiMeshRayCaster`, and +:class:`~isaaclab.sensors.MultiMeshRayCasterCamera` sensors have been transitioned from a +PyTorch/USD-based backend to a native Warp kernel pipeline. This improves performance by +eliminating per-step tensor allocations and torch-to-warp conversions, but introduces several +breaking changes. + + +RayCasterData Return Types +-------------------------- + +The :attr:`~isaaclab.sensors.RayCasterData.pos_w`, +:attr:`~isaaclab.sensors.RayCasterData.quat_w`, and +:attr:`~isaaclab.sensors.RayCasterData.ray_hits_w` properties now return +:class:`~isaaclab.utils.warp.ProxyArray` instead of ``torch.Tensor``. This follows the same +pattern as the general ProxyArray backend migration described above. + +.. code-block:: python + + # Before (Isaac Lab 2.x) + ray_hits = ray_caster.data.ray_hits_w # torch.Tensor + sensor_pos = ray_caster.data.pos_w # torch.Tensor + + # After (Isaac Lab 3.x) + ray_hits = ray_caster.data.ray_hits_w # ProxyArray + sensor_pos = ray_caster.data.pos_w # ProxyArray + + # To use with torch operations, access .torch + ray_hits_torch = ray_caster.data.ray_hits_w.torch + sensor_pos_torch = ray_caster.data.pos_w.torch + + +Ray Alignment Configuration +---------------------------- + +The ``attach_yaw_only`` boolean parameter on :class:`~isaaclab.sensors.RayCasterCfg` has been +deprecated in favor of the new ``ray_alignment`` parameter, which accepts one of three string +values: + +.. list-table:: + :header-rows: 1 + :widths: 30 30 40 + + * - Old (2.x) + - New (3.0) + - Behavior + * - ``attach_yaw_only=False`` + - ``ray_alignment="base"`` + - Rays follow the full sensor orientation. + * - ``attach_yaw_only=True`` + - ``ray_alignment="yaw"`` + - Rays follow only the yaw component of the sensor orientation. + * - *(not available)* + - ``ray_alignment="world"`` + - Rays are always cast in the world frame (no rotation applied). + +.. code-block:: python + + # Before (Isaac Lab 2.x) + cfg = RayCasterCfg(attach_yaw_only=True, ...) + + # After (Isaac Lab 3.x) + cfg = RayCasterCfg(ray_alignment="yaw", ...) + + +Raycasting Kernel Signature Change +----------------------------------- + +The :func:`~isaaclab.utils.warp.kernels.raycast_dynamic_meshes_kernel` Warp kernel now requires +an ``env_mask`` parameter as its first argument. This is a ``wp.array(dtype=wp.bool)`` that +controls which environments are updated. The public Python wrapper +:func:`~isaaclab.utils.warp.ops.raycast_dynamic_meshes` has been updated to inject an all-True +mask automatically, so code using the wrapper is unaffected. + +If you call the kernel directly, update your launch call: + +.. code-block:: python + + import warp as wp + + # Before (Isaac Lab 2.x) + wp.launch( + raycast_dynamic_meshes_kernel, + dim=(num_meshes, num_envs, num_rays), + inputs=[ray_starts, ray_directions, mesh_ids, ...], + ) + + # After (Isaac Lab 3.x) -- env_mask is now the first input + env_mask = wp.ones(num_envs, dtype=wp.bool, device=device) + wp.launch( + raycast_dynamic_meshes_kernel, + dim=(num_meshes, num_envs, num_rays), + inputs=[env_mask, ray_starts, ray_directions, mesh_ids, ...], + ) + + +RayCaster.meshes Cache Key +-------------------------- + +The :attr:`~isaaclab.sensors.RayCaster.meshes` class variable, which caches warp meshes across +all :class:`~isaaclab.sensors.RayCaster` instances, is now keyed by ``(prim_path, device)`` tuples +instead of by ``prim_path`` alone. This prevents a mesh that was built on one device (e.g. CPU) +from being reused by a sensor running on a different device (e.g. CUDA), which caused illegal +memory accesses on systems without unified memory. + +Code that reads or writes this cache directly must update both the type annotation and the key: + +.. code-block:: python + + # Before (Isaac Lab 2.x) + meshes: ClassVar[dict[str, wp.Mesh]] = {} + wp_mesh = RayCaster.meshes[prim_path] + + # After (Isaac Lab 3.x) + meshes: ClassVar[dict[tuple[str, str], wp.Mesh]] = {} + wp_mesh = RayCaster.meshes[(prim_path, device)] + + +Write Method Index/Mask Split +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +All asset write methods have been split into two explicit variants: + +- ``write_*_to_sim_index(data, env_ids)`` — accepts partial data for a sparse set of + environment indices. The ``data`` tensor has shape ``(len(env_ids), ...)``. +- ``write_*_to_sim_mask(data, env_mask)`` — accepts full data for all environments with a + boolean mask selecting which environments to update. The ``data`` tensor has shape + ``(num_envs, ...)``. + +The previous ``write_*_to_sim(data, env_ids)`` methods have been removed. + +.. code-block:: python + + # Before (Isaac Lab 2.x) + robot.write_root_pose_to_sim(pose_data, env_ids) + + # After (Isaac Lab 3.x) — indexed variant (partial data) + robot.write_root_pose_to_sim_index(root_pose=pose_data, env_ids=env_ids) + + # After (Isaac Lab 3.x) — mask variant (full data, boolean mask) + robot.write_root_pose_to_sim_mask(root_pose=pose_data, env_mask=env_mask) + +.. list-table:: Affected write methods (RigidObject / Articulation) + :header-rows: 1 + :widths: 50 50 + + * - Old method + - New methods + * - ``write_root_pose_to_sim`` + - ``write_root_pose_to_sim_index`` / ``write_root_pose_to_sim_mask`` + * - ``write_root_link_pose_to_sim`` + - ``write_root_link_pose_to_sim_index`` / ``write_root_link_pose_to_sim_mask`` + * - ``write_root_com_pose_to_sim`` + - ``write_root_com_pose_to_sim_index`` / ``write_root_com_pose_to_sim_mask`` + * - ``write_root_velocity_to_sim`` + - ``write_root_velocity_to_sim_index`` / ``write_root_velocity_to_sim_mask`` + * - ``write_root_com_velocity_to_sim`` + - ``write_root_com_velocity_to_sim_index`` / ``write_root_com_velocity_to_sim_mask`` + * - ``write_root_link_velocity_to_sim`` + - ``write_root_link_velocity_to_sim_index`` / ``write_root_link_velocity_to_sim_mask`` + +.. list-table:: Additional Articulation-specific write methods + :header-rows: 1 + :widths: 50 50 + + * - Old method + - New methods + * - ``write_joint_position_to_sim`` + - ``write_joint_position_to_sim_index`` / ``write_joint_position_to_sim_mask`` + * - ``write_joint_velocity_to_sim`` + - ``write_joint_velocity_to_sim_index`` / ``write_joint_velocity_to_sim_mask`` + * - ``write_joint_stiffness_to_sim`` + - ``write_joint_stiffness_to_sim_index`` / ``write_joint_stiffness_to_sim_mask`` + * - ``write_joint_damping_to_sim`` + - ``write_joint_damping_to_sim_index`` / ``write_joint_damping_to_sim_mask`` + * - ``write_joint_position_limit_to_sim`` + - ``write_joint_position_limit_to_sim_index`` / ``write_joint_position_limit_to_sim_mask`` + * - ``write_joint_velocity_limit_to_sim`` + - ``write_joint_velocity_limit_to_sim_index`` / ``write_joint_velocity_limit_to_sim_mask`` + * - ``write_joint_effort_limit_to_sim`` + - ``write_joint_effort_limit_to_sim_index`` / ``write_joint_effort_limit_to_sim_mask`` + * - ``write_joint_armature_to_sim`` + - ``write_joint_armature_to_sim_index`` / ``write_joint_armature_to_sim_mask`` + * - ``write_joint_friction_coefficient_to_sim`` + - ``write_joint_friction_coefficient_to_sim_index`` / ``write_joint_friction_coefficient_to_sim_mask`` + +.. list-table:: RigidObjectCollection write methods + :header-rows: 1 + :widths: 50 50 + + * - Old method + - New methods + * - ``write_body_pose_to_sim`` + - ``write_body_pose_to_sim_index`` / ``write_body_pose_to_sim_mask`` + * - ``write_body_link_pose_to_sim`` + - ``write_body_link_pose_to_sim_index`` / ``write_body_link_pose_to_sim_mask`` + * - ``write_body_com_pose_to_sim`` + - ``write_body_com_pose_to_sim_index`` / ``write_body_com_pose_to_sim_mask`` + * - ``write_body_velocity_to_sim`` + - ``write_body_velocity_to_sim_index`` / ``write_body_velocity_to_sim_mask`` + * - ``write_body_com_velocity_to_sim`` + - ``write_body_com_velocity_to_sim_index`` / ``write_body_com_velocity_to_sim_mask`` + * - ``write_body_link_velocity_to_sim`` + - ``write_body_link_velocity_to_sim_index`` / ``write_body_link_velocity_to_sim_mask`` + + +TimestampedBufferWarp +~~~~~~~~~~~~~~~~~~~~~ + +If you have custom asset or sensor data classes that subclass the Isaac Lab base data classes, +note that internal buffers have changed from :class:`~isaaclab.utils.buffers.TimestampedBuffer` +to :class:`~isaaclab.utils.buffers.TimestampedBufferWarp`. The new class takes ``(shape, device, +wp_dtype)`` as constructor arguments instead of a ``torch.Tensor``: + +.. code-block:: python + + import warp as wp + from isaaclab.utils.buffers import TimestampedBufferWarp + + # Before (Isaac Lab 2.x) + self._data.root_pos_w = TimestampedBuffer(torch.zeros(num_envs, 3, device=device)) + + # After (Isaac Lab 3.x) + self._data.root_pos_w = TimestampedBufferWarp( + shape=(num_envs,), device=device, wp_dtype=wp.vec3f + ) + + +URDF Importer +~~~~~~~~~~~~~ + +The URDF importer in Isaac Sim was rewritten to version 3.0, using the ``urdf-usd-converter`` +library and the ``isaacsim.asset.transformer.rules`` extension to produce structured USD output. +The old C++ binding-based API (using Kit commands ``URDFParseFile``/``URDFImportRobot`` and the +``_urdf`` interface from ``acquire_urdf_interface()``) has been replaced with a new Python-based +pipeline. + +The IsaacLab :class:`~sim.converters.UrdfConverter` has been updated to replicate the new +``URDFImporter.import_urdf()`` pipeline, inserting IsaacLab-specific post-processing (fix base, +joint drives, link density) on the intermediate USD stage before the asset transformer +restructures the output. + +.. important:: + + The previous version-pinning mechanism that locked the URDF importer extension to + ``isaacsim.asset.importer.urdf-2.4.31`` has been removed. The converter now uses whichever + version of the extension is available in your Isaac Sim installation. + + +Deprecated Settings +------------------- + +The following :class:`~sim.converters.UrdfConverterCfg` settings are **deprecated** because +the new URDF importer 3.0 no longer supports them. They are kept for backward compatibility +but will log warnings if enabled: + ++-----------------------------------------------------------+-----------------------------------------------------+ +| Setting | Notes | ++===========================================================+=====================================================+ +| ``convert_mimic_joints_to_normal_joints`` | No longer supported by the importer. | ++-----------------------------------------------------------+-----------------------------------------------------+ +| ``replace_cylinders_with_capsules`` | No longer supported by the importer. | ++-----------------------------------------------------------+-----------------------------------------------------+ +| ``root_link_name`` | No longer supported by the importer. | ++-----------------------------------------------------------+-----------------------------------------------------+ + +.. note:: + + The ``merge_fixed_joints`` setting is **still supported**. It is now implemented as a URDF XML + pre-processing step that runs before the USD conversion. Fixed joints are removed and child + link elements (visual, collision, inertial) are merged into the parent link with correct + transform composition. + +Additionally, the :class:`~sim.converters.UrdfConverterCfg.JointDriveCfg.NaturalFrequencyGainsCfg` +gains mode is **deprecated**. The ``compute_natural_stiffness`` function that it depended on has +been removed from the importer. If ``NaturalFrequencyGainsCfg`` is used, a +:exc:`DeprecationWarning` is emitted and joint drive gains are left at the values produced by the +URDF importer. Use :class:`~sim.converters.UrdfConverterCfg.JointDriveCfg.PDGainsCfg` instead. + +The :attr:`~sim.converters.AssetConverterBaseCfg.make_instanceable` setting from the base class +is also no longer supported and will be ignored. Assets will be made instanceable by default. + + +Updated CLI Tool +---------------- + +The ``convert_urdf.py`` script has been updated. The ``usd_file_name`` is now determined +automatically by the importer based on the robot name and cannot be overridden. + +**Before (Isaac Lab 2.x):** + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tools/convert_urdf.py \ + robot.urdf \ + /output/dir/robot.usd \ + --fix-base \ + --merge-joints + +**After (Isaac Lab 3.0):** + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tools/convert_urdf.py \ + robot.urdf \ + /output/dir \ + --fix-base \ + --joint-stiffness 100.0 \ + --joint-damping 1.0 \ + --viz kit + +.. note:: + + The ``--merge-joints`` flag is still accepted and correctly triggers the pre-processing + step to merge fixed joints. + + +Updated Python API +------------------ + +If you use :class:`~sim.converters.UrdfConverter` or :class:`~sim.converters.UrdfConverterCfg` +directly in your code, note the following changes: + +1. The ``usd_file_name`` is now set automatically by the converter based on the URDF file name. + The importer generates output at ``{usd_dir}/{robot_name}/{robot_name}.usda``. + +2. The ``make_instanceable`` setting is no longer supported. Assets will be made instanceable + by default. + +3. The ``merge_fixed_joints`` parameter is now implemented as a pre-processing step. + +**Before (Isaac Lab 2.x):** + +.. code-block:: python + + from isaaclab.sim.converters import UrdfConverter, UrdfConverterCfg + + cfg = UrdfConverterCfg( + asset_path="robot.urdf", + usd_dir="/output/dir", + usd_file_name="robot.usd", + fix_base=True, + merge_fixed_joints=True, + make_instanceable=True, + joint_drive=UrdfConverterCfg.JointDriveCfg( + gains=UrdfConverterCfg.JointDriveCfg.PDGainsCfg( + stiffness=None, # use URDF values + damping=None, + ), + ), + ) + +**After (Isaac Lab 3.0):** + +.. code-block:: python + + from isaaclab.sim.converters import UrdfConverter, UrdfConverterCfg + + cfg = UrdfConverterCfg( + asset_path="robot.urdf", + usd_dir="/output/dir", + # usd_file_name is determined automatically from the robot name + fix_base=True, + merge_fixed_joints=True, # supported via pre-processing + joint_drive=UrdfConverterCfg.JointDriveCfg( + gains=UrdfConverterCfg.JointDriveCfg.PDGainsCfg( + stiffness=None, # use URDF values + damping=None, + ), + ), + ) + + +MJCF Importer +~~~~~~~~~~~~~ + +The MJCF importer in Isaac Sim was rewritten to use the ``mujoco-usd-converter`` library. +The old C++ binding-based API (using Kit commands ``MJCFCreateAsset``/``MJCFCreateImportConfig`` +and the ``ImportConfig`` class) has been replaced with a new pure-Python ``MJCFImporter`` class +and ``MJCFImporterConfig`` dataclass. + +.. important:: + + The new MJCF importer produces USD assets with **nested rigid bodies** (i.e., ``RigidBodyAPI`` + is applied to each link prim individually) instead of a single articulation root with rigid + body applied only at the top level. This matches how MuJoCo represents bodies and is + physically more accurate, but it may affect code that assumes a flat rigid body hierarchy. + If you have downstream logic that traverses the USD structure of MJCF-imported assets, + verify that it handles nested rigid body prims correctly. + +Removed Settings +---------------- + +The following :class:`~sim.converters.MjcfConverterCfg` settings have been **removed** because +the new converter handles them automatically based on the MJCF file content: + +- ``fix_base`` — base fixedness is now inferred from the MJCF ```` tag. +- ``link_density`` — density is now read directly from the MJCF model. +- ``import_inertia_tensor`` — inertia tensors are always imported. +- ``import_sites`` — sites are always imported. + +The :attr:`~sim.converters.AssetConverterBaseCfg.make_instanceable` setting from the base class +is also no longer supported and will be ignored. + + +New Settings +------------ + +The following new settings were added to :class:`~sim.converters.MjcfConverterCfg`: + ++-----------------------------------------------------------------+------------------------------------------------------+ +| Setting | Description | ++=================================================================+======================================================+ +| :attr:`~sim.converters.MjcfConverterCfg.merge_mesh` | Merge meshes where possible to optimize the model. | ++-----------------------------------------------------------------+------------------------------------------------------+ +| :attr:`~sim.converters.MjcfConverterCfg.collision_from_visuals` | Generate collision geometry from visuals. | ++-----------------------------------------------------------------+------------------------------------------------------+ +| :attr:`~sim.converters.MjcfConverterCfg.collision_type` | Type of collision geometry (e.g. ``"default"``, | +| | ``"Convex Hull"``, ``"Convex Decomposition"``). | ++-----------------------------------------------------------------+------------------------------------------------------+ + + +Renamed Settings +---------------- + ++------------------------------------------+------------------------------------------+ +| Old (2.x) | New (3.0) | ++==========================================+==========================================+ +| ``self_collision`` | ``self_collision`` (unchanged) | ++------------------------------------------+------------------------------------------+ + +.. note:: + + The underlying Isaac Sim API renamed ``self_collision`` to ``allow_self_collision``. + The IsaacLab :class:`~sim.converters.MjcfConverterCfg` keeps using ``self_collision`` + for backward compatibility and maps it to the new name internally. + + +Updated CLI Tool +---------------- + +The ``convert_mjcf.py`` script has been updated to match the new importer settings. +Old command-line flags (``--fix-base``, ``--make-instanceable``, ``--import-sites``) +are no longer available. + +**Before (Isaac Lab 2.x):** + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tools/convert_mjcf.py \ + ../mujoco_menagerie/unitree_h1/h1.xml \ + source/isaaclab_assets/data/Robots/Unitree/h1.usd \ + --import-sites \ + --make-instanceable + +**After (Isaac Lab 3.0):** + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tools/convert_mjcf.py \ + ../mujoco_menagerie/unitree_h1/h1.xml \ + source/isaaclab_assets/data/Robots/Unitree/h1.usd \ + --merge-mesh \ + --self-collision \ + --viz kit + +New flags: ``--merge-mesh``, ``--collision-from-visuals``, ``--collision-type``, ``--self-collision``. + + +Updated Python API +------------------ + +If you use :class:`~sim.converters.MjcfConverter` or :class:`~sim.converters.MjcfConverterCfg` +directly in your code, update your configuration: + +**Before (Isaac Lab 2.x):** + +.. code-block:: python + + from isaaclab.sim.converters import MjcfConverter, MjcfConverterCfg + + cfg = MjcfConverterCfg( + asset_path="robot.xml", + usd_dir="/output/dir", + fix_base=True, + import_sites=True, + make_instanceable=True, + ) + +**After (Isaac Lab 3.0):** + +.. code-block:: python + + from isaaclab.sim.converters import MjcfConverter, MjcfConverterCfg + + cfg = MjcfConverterCfg( + asset_path="robot.xml", + usd_dir="/output/dir", + merge_mesh=True, + collision_from_visuals=False, + self_collision=False, + ) + + +XR Teleoperation: Isaac Teleop Integration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The native XR teleoperation stack in ``isaaclab.devices.openxr`` has been deprecated and replaced +by `Isaac Teleop `_, integrated via the ``isaaclab_teleop`` +extension. The ``isaac-teleop-device-plugins`` repository has also been deprecated; all device +plugin support is now in Isaac Teleop. + +For full documentation on the new stack, see :ref:`isaac-teleop-feature`. + + +Installation Requirement +------------------------ + +Isaac Teleop must now be installed in your Isaac Lab environment: + +.. code-block:: bash + + pip install isaacteleop~=1.0 --extra-index-url https://pypi.nvidia.com + +See :ref:`install-isaac-teleop` for complete installation instructions. + + +Import Changes +-------------- + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Deprecated (2.x) + - New (3.0) + * - ``from isaaclab.devices.openxr import OpenXRDevice`` + - ``from isaaclab_teleop import IsaacTeleopDevice`` + * - ``from isaaclab.devices.openxr import OpenXRDeviceCfg`` + - ``from isaaclab_teleop import IsaacTeleopCfg`` + * - ``from isaaclab.devices.openxr import XrCfg`` + - ``from isaaclab_teleop import XrCfg`` + * - ``from isaaclab.devices.openxr import ManusVive`` + - ``from isaaclab_teleop import IsaacTeleopDevice`` (with Manus plugin configured) + * - ``from isaaclab.devices import RetargeterBase`` + - Use Isaac Teleop ``BaseRetargeter`` and pipeline builder pattern + * - ``from isaaclab.devices.openxr.retargeters import Se3AbsRetargeter`` + - ``from isaacteleop.retargeters import Se3AbsRetargeter`` + + +Environment Configuration Changes +---------------------------------- + +The ``teleop_devices`` field with ``OpenXRDeviceCfg`` has been replaced by the ``isaac_teleop`` +field with ``IsaacTeleopCfg`` and a pipeline builder callable. + +**Before (Isaac Lab 2.x):** + +.. code-block:: python + + from isaaclab.devices import DevicesCfg, OpenXRDeviceCfg + from isaaclab.devices.openxr import XrCfg + from isaaclab.devices.openxr.retargeters import Se3AbsRetargeterCfg, GripperRetargeterCfg + + @configclass + class MyEnvCfg(ManagerBasedRLEnvCfg): + + xr: XrCfg = XrCfg(anchor_pos=[0.0, 0.0, 0.0]) + + teleop_devices: DevicesCfg = field(default_factory=lambda: DevicesCfg( + handtracking=OpenXRDeviceCfg( + xr_cfg=None, + retargeters=[ + Se3AbsRetargeterCfg(bound_hand=0, zero_out_xy_rotation=True), + GripperRetargeterCfg(bound_hand=0), + ] + ), + )) + +**After (Isaac Lab 3.0):** + +.. code-block:: python + + from isaaclab_teleop import IsaacTeleopCfg, XrCfg + + def _build_pipeline(): + from isaacteleop.retargeting_engine.deviceio_source_nodes import ControllersSource, HandsSource + from isaacteleop.retargeting_engine.interface import OutputCombiner, ValueInput + from isaacteleop.retargeters import ( + GripperRetargeter, GripperRetargeterConfig, + Se3AbsRetargeter, Se3RetargeterConfig, TensorReorderer, + ) + from isaacteleop.retargeting_engine.tensor_types import TransformMatrix + + controllers = ControllersSource(name="controllers") + hands = HandsSource(name="hands") + transform = ValueInput("world_T_anchor", TransformMatrix()) + t_controllers = controllers.transformed(transform.output(ValueInput.VALUE)) + + se3 = Se3AbsRetargeter(Se3RetargeterConfig(input_device=ControllersSource.RIGHT), name="ee") + c_se3 = se3.connect({ControllersSource.RIGHT: t_controllers.output(ControllersSource.RIGHT)}) + + grip = GripperRetargeter(GripperRetargeterConfig(hand_side="right"), name="grip") + c_grip = grip.connect({ + ControllersSource.RIGHT: t_controllers.output(ControllersSource.RIGHT), + HandsSource.RIGHT: hands.output(HandsSource.RIGHT), + }) + + reorder = TensorReorderer( + input_config={"ee": ["pos_x","pos_y","pos_z","quat_x","quat_y","quat_z","quat_w"], + "grip": ["gripper_value"]}, + output_order=["pos_x","pos_y","pos_z","quat_x","quat_y","quat_z","quat_w","gripper_value"], + name="reorder", input_types={"ee": "array", "grip": "scalar"}, + ) + c_reorder = reorder.connect({"ee": c_se3.output("ee_pose"), "grip": c_grip.output("gripper_command")}) + return OutputCombiner({"action": c_reorder.output("output")}) + + @configclass + class MyEnvCfg(ManagerBasedRLEnvCfg): + + xr: XrCfg = XrCfg(anchor_pos=(0.0, 0.0, 0.0)) + + def __post_init__(self): + super().__post_init__() + self.isaac_teleop = IsaacTeleopCfg( + pipeline_builder=_build_pipeline, + sim_device=self.sim.device, + xr_cfg=self.xr, + ) + + +Backward Compatibility +---------------------- + +The old classes still exist and will issue ``DeprecationWarning`` when used: + +* ``isaaclab.devices.openxr.OpenXRDevice`` and ``OpenXRDeviceCfg`` +* ``isaaclab.devices.openxr.ManusVive`` and ``ManusViveCfg`` +* All retargeters under ``isaaclab.devices.openxr.retargeters`` + +Deprecated retargeters have been moved to ``isaaclab_teleop.deprecated.openxr.retargeters`` for +compatibility. These will be removed in a future release. + + +.. _torcharray-migration: + +ProxyArray Interop and Temporary Compatibility +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Asset and sensor data class properties return :class:`~isaaclab.utils.warp.ProxyArray`, a +lightweight wrapper with explicit ``.torch`` and ``.warp`` accessors: + +.. code-block:: python + + # BEFORE (2.x) — properties returned torch.Tensor directly + joint_pos = robot.data.joint_pos # torch.Tensor + root_pos = robot.data.root_pos_w # torch.Tensor + + # AFTER (3.0) — properties return ProxyArray, use .torch for the tensor + joint_pos = robot.data.joint_pos.torch # cached zero-copy torch.Tensor + root_pos = robot.data.root_pos_w.torch # cached zero-copy torch.Tensor + joint_pos_warp = robot.data.joint_pos.warp # the underlying warp.array + +**Automatic interop — in many cases, no changes are needed:** + +- **Warp kernels:** ``ProxyArray`` implements ``__cuda_array_interface__``, so it can be passed + directly to ``wp.launch()`` without calling ``.warp``: + + .. code-block:: python + + # Just works — no .warp needed + wp.launch(my_kernel, inputs=[robot.data.joint_pos], ...) + +- **Torch functions:** ``ProxyArray`` implements ``__torch_function__``, so ``torch.*`` operations + accept it directly. During the deprecation period this emits a one-time warning, but works: + + .. code-block:: python + + # Works (emits DeprecationWarning once, then silent) + mean_pos = torch.mean(robot.data.joint_pos, dim=1) + clipped = torch.clamp(robot.data.joint_pos, -3.14, 3.14) + +**What to change:** + +1. Append ``.torch`` where you need an explicit ``torch.Tensor`` (e.g., for indexing, slicing, + or passing to non-torch libraries). +2. Warp kernel calls need no changes — ``ProxyArray`` works transparently. +3. If you need the underlying ``warp.array`` (e.g., for ``ptr``, ``strides``), use ``.warp``. +4. Replace legacy ``wp.to_torch(proxy_array)`` calls with ``proxy_array.torch``. + +.. note:: + + The ``__torch_function__`` bridge and the temporary ``wp.to_torch(proxy_array)`` shim will + be removed in a future release. We recommend migrating to explicit ``.torch`` access now. + +For a complete guide, see :doc:`/source/how-to/proxy_array`. + + +Migration off Deprecated Isaac Sim APIs +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In Isaac Sim 6.0, the legacy ``isaacsim.core.*``, ``isaacsim.sensors.*``, and +``isaacsim.robot.wheeled_robots`` Python module paths are **deprecated** in favor of their +``isaacsim.core.experimental.*`` (and ``*.experimental.*``) equivalents. Isaac Lab 3.0 has +been migrated off the deprecated paths so that Isaac Lab continues to load and run when +those modules are removed in a future Isaac Sim release. + +This is mostly a transparent change for users — Isaac Lab's own public Python API +(:mod:`isaaclab`, :mod:`isaaclab_physx`, :mod:`isaaclab_tasks`, :mod:`isaaclab_teleop`, +:mod:`isaaclab_mimic`) is unchanged. The migration is only user-visible if you: + +1. Import Isaac Sim symbols **directly** in your project, or +2. Maintain a custom Kit experience (``.kit`` file) that lists Isaac Sim extension + dependencies, or +3. Imported ``SimulationManager`` from ``isaacsim.core.simulation_manager`` in your own + PhysX-backed code. + + +Python module renames +--------------------- + +Update direct imports in your own code as follows. **Where Isaac Lab provides an in-tree +replacement, prefer the Isaac Lab API** over the ``isaacsim.core.experimental.*`` fallback: + +.. list-table:: + :header-rows: 1 + :widths: 45 55 + + * - Deprecated Isaac Sim path + - Recommended replacement + * - ``isaacsim.core.utils.stage`` + - :mod:`isaaclab.sim.utils.stage` (e.g. ``get_current_stage``, + ``create_new_stage``, ``open_stage``, ``save_stage``, ``close_stage``, + ``clear_stage``, ``update_stage``, ``use_stage``) + * - ``isaacsim.core.utils.prims`` + - :mod:`isaaclab.sim.utils.prims` (e.g. ``create_prim``, ``delete_prim``, + ``change_prim_property``, ``bind_visual_material``, + ``bind_physics_material``, ``add_usd_reference``) + * - ``isaacsim.core.utils.queries`` + - :mod:`isaaclab.sim.utils.queries` (e.g. ``find_matching_prims``, + ``find_matching_prim_paths``, ``get_first_matching_child_prim``) + * - ``isaacsim.core.utils.transforms`` + - :mod:`isaaclab.sim.utils.transforms` + * - ``isaacsim.core.utils.semantics`` + - :mod:`isaaclab.sim.utils.semantics` + * - ``isaacsim.core.utils.extensions.enable_extension`` + - ``isaacsim.core.experimental.utils.app.enable_extension`` (no Isaac Lab equivalent) + * - ``isaacsim.core.utils.viewports.set_camera_view`` + - ``isaacsim.core.rendering_manager.ViewportManager.set_camera_view`` (or + ``omni.kit.viewport.utility.camera_state.ViewportCameraState`` for lower-level control) + * - ``isaacsim.core.prims.XFormPrim`` / ``XFormPrimView`` + - :class:`~isaaclab.sim.views.FrameView` (Isaac Lab in-tree view; see + :ref:`migrating-to-isaaclab-3-0` ``Renaming of XformPrimView to FrameView`` above). + For ``Articulation`` / ``RigidPrim`` use ``isaacsim.core.experimental.prims``. + * - ``isaacsim.core.simulation_manager.SimulationManager`` + - :class:`isaaclab_physx.physics.PhysxManager` (PhysX backend) or + ``isaaclab_newton.physics.NewtonManager`` (Newton backend); see local-alias + pattern below. + * - ``isaacsim.core.cloner`` + - :mod:`isaaclab.cloner` (Isaac Lab in-tree cloner) + * - ``isaacsim.replicator.mobility_gen`` + - ``isaacsim.replicator.experimental.mobility_gen`` + * - ``isaacsim.sensors.`` + - ``isaacsim.sensors.experimental.`` + * - ``isaacsim.robot.wheeled_robots`` + - ``isaacsim.robot.experimental.wheeled_robots`` (and + ``isaacsim.robot.wheeled_robots.nodes`` for OmniGraph nodes) + +To keep call-site code symmetric across backends when migrating off +``isaacsim.core.simulation_manager.SimulationManager``, use the local-alias pattern: + +.. code-block:: python + + from isaaclab_physx.physics import PhysxManager as SimulationManager + # or, for the Newton backend + from isaaclab_newton.physics import NewtonManager as SimulationManager + + +Kit experience (``.kit``) updates +--------------------------------- + +If you maintain a custom Kit experience derived from one of the Isaac Lab apps under +``apps/``: + +* **Stop registering deprecated extension search paths.** The ``extsDeprecated`` search + path entry has been removed from all stock Isaac Lab Kit experiences (headless, + rendering, XR variants). Mirror that change in your own experience. +* **Switch explicit Isaac Sim extension dependencies** to the non-deprecated equivalents + listed above (``isaacsim.core.experimental.*``, ``isaacsim.sensors.experimental.*``, + ``isaacsim.robot.experimental.wheeled_robots``). +* **Remove unused Isaac Sim extensions that pull in** ``isaacsim.core.api`` — Isaac Lab + no longer depends on those, and keeping them resurrects the deprecated stack. + + +``SimulationManager`` is no longer re-exported +---------------------------------------------- + +Earlier internal previews of this migration briefly exposed +``isaaclab_physx.physics.SimulationManager`` as a public alias of +:class:`~isaaclab_physx.physics.PhysxManager`. **That alias has been removed**; use +:class:`~isaaclab_physx.physics.PhysxManager` directly (with ``as SimulationManager`` at +the import site if you want backend-agnostic call-site code, as shown above). + + +Retired standalone reproducers +------------------------------ + +A handful of legacy reproducers under ``source/isaaclab/test/deps/isaacsim`` that +depended on the deprecated Isaac Sim core extensions have been retired: +``check_camera.py``, ``check_floating_base_made_fixed.py``, +``check_legged_robot_clone.py``, ``check_rep_texture_randomizer.py``, and +``check_ref_count.py``. Use :mod:`isaaclab.sim` together with the new +``isaacsim.core.experimental.*`` APIs for the same debugging workflows. + + +PhysX Tensors API Module Path +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Recent Isaac Sim releases removed the internal ``impl`` submodule of +``omni.physics.tensors`` and now expose the PhysX Tensor API types +(``ArticulationView``, ``RigidBodyView``, ``SimulationView``, etc.) directly +under ``omni.physics.tensors.api``. Importing from the old path raises +``ModuleNotFoundError: No module named 'omni.physics.tensors.impl'`` at import +time. + +Isaac Lab has been updated to import from the new path. Downstream code +(custom assets, sensors, or scripts) that imported from the old path must be +updated: + +.. code-block:: python + + # Before (Isaac Lab 2.x / older Isaac Sim) + import omni.physics.tensors.impl.api as physx + + # After (Isaac Lab 3.x / current Isaac Sim) + import omni.physics.tensors.api as physx + +The class identities are unchanged — only the module path moved. Type hints +referencing the old path (``omni.physics.tensors.impl.api.ArticulationView``) +should be similarly updated to ``omni.physics.tensors.api.ArticulationView``. + + +Need Help? +~~~~~~~~~~ + +If you encounter issues during migration: + +1. Check the `IsaacLab GitHub Issues `_ +2. Review the `CHANGELOG `_ +3. Join the community on `Discord `_ diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/actuators.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/actuators.rst new file mode 100644 index 0000000000000000000000000000000000000000..de34e42028689c85dfd6fa5b22f162458cefeffc --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/actuators.rst @@ -0,0 +1,100 @@ +.. _overview-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:`isaaclab.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_{des} - q) + k_d * (\dot{q}_{des} - \dot{q}) + \tau_{ff} \\ + \tau_{j, max} & = \gamma \times \tau_{motor, max} \\ + \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 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:`isaaclab.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-group/actuator-light.svg + :class: only-light + :align: center + :alt: Actuator models for a legged mobile manipulator + :width: 80% + +.. image:: ../../_static/actuator-group/actuator-dark.svg + :class: only-dark + :align: center + :width: 80% + :alt: Actuator models for a legged mobile manipulator + +.. seealso:: + + We provide implementations for various explicit actuator models. These are detailed in + `isaaclab.actuators <../../api/lab/isaaclab.actuators.html>`_ sub-package. + +Considerations when using actuators +----------------------------------- + +As explained in the previous sections, there are two main types of actuator models: implicit and explicit. +The implicit actuator model is provided by the physics engine. This means that when the user sets either +a desired position or velocity, the physics engine will internally compute the efforts that need to be +applied to the joints to achieve the desired behavior. In PhysX, the PD controller adds numerical damping +to the desired effort, which results in more stable behavior. + +The explicit actuator model is provided by the user. This means that when the user sets either a desired +position or velocity, the user's model will compute the efforts that need to be applied to the joints to +achieve the desired behavior. While this provides more flexibility, it can also lead to some numerical +instabilities. One way to mitigate this is to use the ``armature`` parameter of the actuator model, either in +the USD file or in the articulation config. This parameter is used to dampen the joint response and helps +improve the numerical stability of the simulation. More details on how to improve articulation stability +can be found in the `OmniPhysics documentation `_. + +What does this mean for the user? It means that policies trained with implicit actuators may not transfer +to the exact same robot model when using explicit actuators. If you are running into issues like this, or +in cases where policies do not converge on explicit actuators while they do on implicit ones, increasing +or setting the ``armature`` parameter to a higher value may help. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/index.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..8c1327c4b140c8931ae6e802c23934006fdd136e --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/index.rst @@ -0,0 +1,19 @@ +Core Concepts +============= + +This section we introduce core concepts in Isaac Lab. + +.. toctree:: + :maxdepth: 1 + + + multi_backend_architecture + physical-backends/index + schema_cfgs + task_workflows + actuators + sensors/index.rst + renderers + motion_generators + scene_data_providers + visualization diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/motion_generators.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/motion_generators.rst new file mode 100644 index 0000000000000000000000000000000000000000..e4e09f2f17db841ed468267113b4c804d4c87601 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/motion_generators.rst @@ -0,0 +1,229 @@ +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. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/multi_backend_architecture.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/multi_backend_architecture.rst new file mode 100644 index 0000000000000000000000000000000000000000..0487ea1890d3499b8850c98d3fd4509fa1a7b115 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/multi_backend_architecture.rst @@ -0,0 +1,422 @@ +Multi-Backend Architecture +========================== + +Isaac Lab 3.0 introduced a multi-backend architecture that enables running simulations with +different physics backends (PhysX, Newton, and OvPhysX) while maintaining a unified API. +This page explains how the backend system works and how to extend it. + +Overview +-------- + +Instead of hard-coding a single physics engine, Isaac Lab uses a **factory pattern** to +dispatch object creation to backend-specific implementations at runtime. When you write: + +.. code-block:: python + + from isaaclab.assets import Articulation + + robot = Articulation(cfg) + +The ``Articulation`` class is a factory that automatically creates an instance of +the active backend implementation, such as +:class:`PhysX Articulation `, +:class:`Newton Articulation `, or +:class:`OvPhysX Articulation `. Your code never +needs to import backend-specific modules directly. + +This pattern applies across simulation components, though not every backend implements every +component yet: + +.. list-table:: + :header-rows: 1 + + * - Component + - Core API (``isaaclab``) + - PhysX (``isaaclab_physx``) + - Newton (``isaaclab_newton``) + - OvPhysX (``isaaclab_ovphysx``) + * - Physics Manager + - :class:`~isaaclab.physics.PhysicsManager` + - :class:`~isaaclab_physx.physics.PhysxManager` + - :class:`~isaaclab_newton.physics.NewtonManager` + - :class:`~isaaclab_ovphysx.physics.OvPhysxManager` + * - Articulation + - :class:`~isaaclab.assets.Articulation` + - :class:`~isaaclab_physx.assets.Articulation` + - :class:`~isaaclab_newton.assets.Articulation` + - :class:`~isaaclab_ovphysx.assets.Articulation` + * - Rigid Object + - :class:`~isaaclab.assets.RigidObject` + - :class:`~isaaclab_physx.assets.RigidObject` + - :class:`~isaaclab_newton.assets.RigidObject` + - :class:`~isaaclab_ovphysx.assets.RigidObject` + * - Deformable Object + - :class:`~isaaclab.assets.DeformableObject` + - :class:`~isaaclab_physx.assets.DeformableObject` + - :class:`~isaaclab_newton.assets.DeformableObject` + - Not supported + * - Contact Sensor + - :class:`~isaaclab.sensors.ContactSensor` + - :class:`~isaaclab_physx.sensors.ContactSensor` + - :class:`~isaaclab_newton.sensors.ContactSensor` + - :class:`~isaaclab_ovphysx.sensors.ContactSensor` + * - Renderer + - :class:`~isaaclab.renderers.Renderer` + - :class:`~isaaclab_physx.renderers.IsaacRtxRenderer` + - :class:`~isaaclab_newton.renderers.NewtonWarpRenderer` + - Not supported + * - Scene Data Backend + - :class:`~isaaclab.scene_data.SceneDataBackend` + - ``PhysxSceneDataBackend`` (in :mod:`isaaclab_physx.physics`) + - ``NewtonSceneDataBackend`` (in :mod:`isaaclab_newton.physics`) + - ``OvPhysxSceneDataBackend`` (in :mod:`isaaclab_ovphysx.physics`) + * - Cloner + - :func:`~isaaclab.cloner.usd_replicate` + - :func:`~isaaclab_physx.cloner.physx_replicate` + - :func:`~isaaclab_newton.cloner.newton_physics_replicate` + - :func:`~isaaclab_ovphysx.cloner.ovphysx_replicate` + +The Factory Pattern +------------------- + +All factories inherit from :class:`~isaaclab.utils.backend_utils.FactoryBase`, which uses a +**convention-over-configuration** approach to locate backend implementations: + +1. The active physics backend is determined by inspecting + ``SimulationContext.physics_manager``. +2. The factory's module path is used to derive the backend module path by replacing ``isaaclab`` + with ``isaaclab_{backend}``. For example, ``isaaclab.assets.articulation`` maps to + ``isaaclab_physx.assets.articulation``, ``isaaclab_newton.assets.articulation``, or + ``isaaclab_ovphysx.assets.articulation``. +3. The backend module is lazily imported and the implementation class is cached in a registry. + +.. code-block:: text + + User code: Articulation(cfg) + │ + ▼ + FactoryBase.__new__() + │ + ├─ _get_backend() → "physx", "newton", or "ovphysx" + │ (reads SimulationContext.physics_manager) + │ + ├─ _get_module_name() → "isaaclab_physx.assets.articulation" + │ (convention: isaaclab.X.Y → isaaclab_{backend}.X.Y) + │ + ├─ importlib.import_module() + │ (lazy load — only on first use) + │ + └─ Return backend-specific instance + +**Custom backend resolution:** Some factories override the default resolution. For example, the +:class:`~isaaclab.renderers.Renderer` factory selects backends based on the renderer config type +rather than the physics manager, because renderers and physics backends are independent: + +.. code-block:: python + + class Renderer(FactoryBase, BaseRenderer): + _backend_class_names = { + "physx": "IsaacRtxRenderer", + "newton": "NewtonWarpRenderer", + "ov": "OVRTXRenderer", + } + +Similarly, visualizers select backends based on the ``visualizer_type`` field in their config, +allowing any visualizer to work with any physics backend. + +Backend Selection +----------------- + +The physics backend is selected via the ``physics`` field in +:class:`~isaaclab.sim.SimulationCfg`: + +.. code-block:: python + + from isaaclab.sim import SimulationCfg + from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + from isaaclab_ovphysx.physics import OvPhysxCfg + from isaaclab_physx.physics import PhysxCfg + + # Use PhysX (default) + sim_cfg = SimulationCfg(physics=PhysxCfg()) + + # Use Newton with MuJoCo-Warp solver + sim_cfg = SimulationCfg(physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg(), + num_substeps=4, + )) + + # Use OvPhysX + sim_cfg = SimulationCfg(physics=OvPhysxCfg()) + +Once the :class:`~isaaclab.sim.SimulationContext` is initialized, all subsequent factory +instantiations automatically use the selected backend. + +Multi-Backend Environments with Presets +--------------------------------------- + +Environments can support multiple backends simultaneously using the :doc:`preset system +`. Each backend gets its own configuration variant. The example +below shows only the physics-related fields: + +.. code-block:: python + + from isaaclab.envs import DirectRLEnvCfg + from isaaclab.sim import SimulationCfg + from isaaclab.utils.configclass import configclass + from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + from isaaclab_ovphysx.physics import OvPhysxCfg + from isaaclab_physx.physics import PhysxCfg + from isaaclab_tasks.utils import PresetCfg + + @configclass + class CartpolePhysicsCfg(PresetCfg): + default: PhysxCfg = PhysxCfg() + physx: PhysxCfg = PhysxCfg() + newton_mjwarp: NewtonCfg = NewtonCfg( + solver_cfg=MJWarpSolverCfg(njmax=5, nconmax=3) + ) + ovphysx: OvPhysxCfg = OvPhysxCfg() + + @configclass + class CartpoleEnvCfg(DirectRLEnvCfg): + sim: SimulationCfg = SimulationCfg(physics=CartpolePhysicsCfg()) + +Users then select a physics backend at the command line: + +.. code-block:: bash + + # Default (PhysX) + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-Direct-v0 + + # MJWarp (Newton backend) + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-Direct-v0 physics=newton_mjwarp + + # OvPhysX backend + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-Direct-v0 physics=ovphysx + +The Physics Manager +------------------- + +Each backend implements :class:`~isaaclab.physics.PhysicsManager`, the abstract base class +that drives the simulation loop: + +.. code-block:: python + + class PhysicsManager(ABC): + @classmethod + @abstractmethod + def initialize(cls, sim_context: SimulationContext) -> None: ... + + @classmethod + @abstractmethod + def reset(cls, soft: bool = False) -> None: ... + + @classmethod + @abstractmethod + def forward(cls) -> None: ... + + @classmethod + @abstractmethod + def step(cls) -> None: ... + + @classmethod + def close(cls) -> None: ... # concrete; dispatches STOP event + +The physics manager also provides a **callback system** via +:class:`~isaaclab.physics.PhysicsEvent` for cross-backend event handling: + +.. code-block:: python + + from isaaclab.physics import PhysicsManager, PhysicsEvent + + handle = PhysicsManager.register_callback( + callback=my_setup_fn, + event=PhysicsEvent.PHYSICS_READY, + order=0, + name="my_callback", + ) + +Available events: ``MODEL_INIT`` (during scene building), ``PHYSICS_READY`` (after physics +initialization), and ``STOP`` (on simulation shutdown). + +Asset and Sensor Interfaces +--------------------------- + +Assets and sensors follow the same pattern. Each has: + +1. **A base class** in ``isaaclab`` defining the interface (e.g., ``BaseArticulation``, + ``BaseContactSensor``) +2. **A factory class** that inherits from both ``FactoryBase`` and the base class +3. **Backend implementations** in ``isaaclab_physx``, ``isaaclab_newton``, and + ``isaaclab_ovphysx`` where supported + +The base classes define the public API contract — properties, methods, and data accessors +that all backends must provide. Current backend implementations use ``wp.array`` +(Warp arrays) as their primary data type for asset and sensor data. + +Data classes follow the same pattern with their own factories (e.g., +``ArticulationData(FactoryBase, BaseArticulationData)``). + +Adding a New Physics Backend +---------------------------- + +To add a new physics backend (e.g., ``mybackend``), create a new extension package following +the established conventions: + +**1. Package structure:** + +.. code-block:: text + + source/isaaclab_mybackend/ + └── isaaclab_mybackend/ + ├── __init__.py + ├── physics/ + │ ├── __init__.py # lazy_export() + │ ├── __init__.pyi # public exports + │ ├── mybackend_manager.py + │ └── mybackend_manager_cfg.py + ├── assets/ + │ ├── articulation/ + │ │ ├── __init__.py + │ │ ├── __init__.pyi + │ │ ├── articulation.py + │ │ └── articulation_data.py + │ ├── rigid_object/ + │ │ └── ... + │ ├── deformable_object/ + │ │ └── ... + │ └── rigid_object_collection/ + │ └── ... + ├── sensors/ + │ ├── contact_sensor/ + │ └── ... + ├── renderers/ + │ └── ... + └── cloner/ + └── ... + +**2. Implement the physics manager:** + +The manager must expose a :class:`~isaaclab.scene_data.SceneDataBackend` so that +:class:`~isaaclab.scene_data.SceneDataProvider` can read your backend's body +transforms in a Warp-native format that renderers and visualizers consume directly. + +.. code-block:: python + + # isaaclab_mybackend/physics/mybackend_manager.py + from isaaclab.physics import PhysicsManager + from isaaclab.scene_data import SceneDataBackend, SceneDataFormat + + + class MyBackendSceneDataBackend(SceneDataBackend): + def __init__(self): + self._scene_data = SceneDataFormat.Transform() + + @property + def transforms(self) -> SceneDataFormat.Transform: + # Return current world-space body transforms as a Warp ``transformf`` array. + self._scene_data.transforms = ... # backend-native tensor view + return self._scene_data + + @property + def transform_count(self) -> int: + ... + + @property + def transform_paths(self) -> list[str]: + # Prim path per row of ``transforms``; used by ``SceneDataProvider.create_mapping``. + ... + + + class MyBackendManager(PhysicsManager): + _scene_data_backend: ClassVar[MyBackendSceneDataBackend | None] = None + + @classmethod + def initialize(cls, sim_context): + super().initialize(sim_context) + cls._scene_data_backend = MyBackendSceneDataBackend() + # Initialize your physics engine + + @classmethod + def get_scene_data_backend(cls) -> SceneDataBackend: + return cls._scene_data_backend + + @classmethod + def step(cls): + # Advance simulation by one timestep + + @classmethod + def forward(cls): + # Update kinematics without stepping + + @classmethod + def reset(cls, soft=False): + if not soft: + cls.dispatch_event(PhysicsEvent.PHYSICS_READY) + # Reset simulation state + + @classmethod + def close(cls): + super().close() + # Clean up resources + +**3. Create the physics config:** + +.. code-block:: python + + # isaaclab_mybackend/physics/mybackend_manager_cfg.py + from isaaclab.physics import PhysicsCfg + from isaaclab.utils.configclass import configclass + + @configclass + class MyBackendCfg(PhysicsCfg): + class_type = "{DIR}.mybackend_manager:MyBackendManager" + # Backend-specific settings here + +**4. Implement assets and sensors:** + +Each asset/sensor must extend the corresponding base class from ``isaaclab``. The class name +must match the factory's expected name (by convention, the same name as the factory class). +Use ``lazy_export()`` in ``__init__.py`` files — no manual registration needed. + +.. code-block:: python + + # isaaclab_mybackend/assets/articulation/articulation.py + from isaaclab.assets.articulation import BaseArticulation + + class Articulation(BaseArticulation): + def __init__(self, cfg): + super().__init__(cfg) + # Set up backend-specific simulation structures + +**5. Module discovery is automatic.** The ``FactoryBase`` convention maps +``isaaclab.assets.articulation`` to ``isaaclab_mybackend.assets.articulation`` based on the +active physics manager name. As long as you follow the package structure above, your backend +classes will be discovered automatically. + +Key Design Principles +--------------------- + +- **Lazy loading**: Backend modules are imported only when first instantiated, keeping startup + fast and avoiding hard dependencies on unused backends. +- **Convention over configuration**: Module paths follow a strict pattern + (``isaaclab.X.Y`` → ``isaaclab_{backend}.X.Y``), so no manual registration is needed. +- **Independent selection**: Physics backend, renderer, and visualizer are selected + independently — you can use any combination. +- **Warp-native data types**: Backend implementations return ``wp.array`` for asset and + sensor data. Use ``wp.to_torch()`` when interoperating with PyTorch-based code. +- **Zero runtime overhead**: Backend selection happens at instantiation time. There are no + if-statements or dispatch logic on the hot path. + +See Also +-------- + +- :doc:`/source/migration/migrating_to_isaaclab_3-0` — migration guide from Isaac Lab 2.x to the + multi-backend architecture +- :doc:`/source/features/hydra` — preset system for multi-backend environment configurations +- :doc:`physical-backends/index` — feature matrix and per-backend guides (PhysX, Newton, OvPhysX) +- :doc:`physical-backends/newton/index` — Newton backend guide +- :doc:`physical-backends/newton/newton-manager-abstraction` — adding Newton solver managers and + coupled solvers +- :doc:`renderers` — renderer backend architecture diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/index.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..36b35b5731efad6ba0de8d9282ffd8da4f8c994d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/index.rst @@ -0,0 +1,142 @@ +Physics Backends +================ + +Isaac Lab 3.0 supports multiple physics backends through a unified API. Each backend +exposes the same :class:`~isaaclab.assets.Articulation`, +:class:`~isaaclab.assets.RigidObject`, sensor and renderer surfaces, while differing +in solver characteristics, maturity, and feature coverage. See +:doc:`../multi_backend_architecture` for how the dispatch and factory machinery work +under the hood. + +This page summarizes what each backend supports today; the sub-pages document +backend-specific configuration, installation, and limitations. + +.. toctree:: + :maxdepth: 2 + + physx/index + newton/index + ovphysx/index + solver-comparison + + +Choosing a Backend +------------------ + +* **PhysX** — the historical default. Production-ready, broad coverage of Isaac Lab + features, and the reference for behavior parity. Selected via + :class:`~isaaclab_physx.physics.PhysxCfg`. +* **Newton** — GPU-accelerated, Warp-native, and differentiable. The Newton + integration ships with the MuJoCo-Warp solver and beta support for the Kamino + solver. Selected via :class:`~isaaclab_newton.physics.NewtonCfg`. +* **OvPhysX** — a **highly experimental** kit-less PhysX backend that reads + scene-level parameters from the USD ``PhysicsScene`` prim. Selected via + :class:`~isaaclab_ovphysx.physics.OvPhysxCfg`. Not recommended for general use yet. + +The active backend is selected at simulation construction time and applies to every +asset, sensor, and renderer instantiated thereafter: + +.. code-block:: python + + from isaaclab.sim import SimulationCfg + from isaaclab_physx.physics import PhysxCfg + from isaaclab_newton.physics import NewtonCfg, MJWarpSolverCfg + + # PhysX (default) + sim_cfg = SimulationCfg(physics=PhysxCfg()) + + # Newton with MuJoCo-Warp + sim_cfg = SimulationCfg(physics=NewtonCfg(solver_cfg=MJWarpSolverCfg())) + + +Feature Support Matrix +---------------------- + +The matrix below is intentionally coarse-grained. For exhaustive per-asset and +per-task support, see each backend's own ``limitations`` page. + +.. list-table:: + :header-rows: 1 + :widths: 30 20 30 20 + + * - Feature + - PhysX + - Newton + - OvPhysX + * - Maturity + - Stable + - Beta + - Highly experimental + * - Default solver + - TGS (rigid body) + - MuJoCo-Warp + - PhysX (TGS / PGS via USD) + * - Alternative solvers + - PGS + - Kamino (beta), additional Newton solvers planned + - — + * - Differentiable + - No + - Yes (via Warp) + - No + * - Articulation API + - Yes + - Yes + - Yes + * - Rigid Object API + - Yes + - Yes + - Yes + * - Rigid Object Collection API + - Yes + - Yes + - Yes + * - Contact Sensor + - Yes + - Yes + - Yes + * - IMU + - Yes + - Yes + - In-flight + * - Frame Transformer / Ray Caster / PVA / Joint-Wrench Sensor + - Yes + - Yes + - In-flight + * - Camera / Tiled Rendering + - Yes (RTX) + - Yes (Newton-Warp renderer) + - Not yet + * - Requires Isaac Sim + - Yes + - Optional (only for the Omniverse visualizer) + - Yes + * - Solver configuration source + - :class:`~isaaclab_physx.physics.PhysxCfg` + - :class:`~isaaclab_newton.physics.NewtonCfg` + solver config + - USD ``PhysicsScene`` + :class:`~isaaclab_ovphysx.physics.OvPhysxCfg` + + +Selecting Backends per Task +--------------------------- + +Tasks that support more than one backend define a Hydra preset on +``SimulationCfg.physics``. The example below shows the cartpole task config which +declares all three backends side by side: + +.. code-block:: python + + from isaaclab_physx.physics import PhysxCfg + from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + from isaaclab_ovphysx.physics import OvPhysxCfg + + @configclass + class CartpolePhysicsCfg(PresetCfg): + default: PhysxCfg = PhysxCfg() + physx: PhysxCfg = PhysxCfg() + newton_mjwarp: NewtonCfg = NewtonCfg(solver_cfg=MJWarpSolverCfg()) + ovphysx: OvPhysxCfg = OvPhysxCfg() + +Users then select the backend at the command line via ``presets=`` or by +overriding the physics field directly. See :ref:`hydra-backend-solver-presets` for +the full Hydra interaction. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/index.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..71e1ffed14e6db19241b01bb7ff9a8401855ff30 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/index.rst @@ -0,0 +1,55 @@ +Newton Backend +============== + +`Newton `_ is a +GPU-accelerated, extensible, and differentiable physics simulation engine designed +for robotics, research, and advanced simulation workflows. Built on top of +`NVIDIA Warp `_ and integrating MuJoCo Warp, Newton +provides high-performance simulation, modern Python APIs, and a flexible +architecture for both users and developers. + +Newton is an Open Source community-driven project with contributions from NVIDIA, +Google Deep Mind, and Disney Research, managed through the Linux Foundation. + +Newton support in Isaac Lab is in beta and under active development. Many features +are still maturing, and the Isaac Lab integration ships a focused, validated set of +classic RL and flat-terrain locomotion environments. We have validated Newton +simulation against PhysX by transferring learned policies in both directions and +have successfully deployed a Newton-trained locomotion policy to a G1 robot. + +Newton can support `multiple solvers +`_ for +handling different types of physics simulation. The Isaac Lab integration ships +the following solver pages: + +* :doc:`mjwarp-solver` — the primary, validated solver path. +* :doc:`kamino-solver` — beta support on selected classic tasks. +* :doc:`using-vbd-solver` — experimental VBD solver for cloth and soft bodies, + available through :mod:`isaaclab_contrib.deformable` and the MJWarp + VBD or + Featherstone + VBD coupled managers. + +Each solver is exposed as a small subclass of +:class:`~isaaclab_newton.physics.NewtonManager`. See +:doc:`newton-manager-abstraction` for the developer-facing guide to adding a +new solver or a coupled solver. + +During the beta phase, breaking changes and incomplete documentation are still +expected. Official support and debugging assistance will follow once the framework +reaches an official release. + +For an overview of how the multi-backend architecture works, including how to add a +new backend, see :doc:`../../multi_backend_architecture`. + + +.. toctree:: + :maxdepth: 2 + :titlesonly: + + installation + supported-features + mjwarp-solver + kamino-solver + using-vbd-solver + newton-manager-abstraction + warp-environments + warp-env-migration diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/installation.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/installation.rst new file mode 100644 index 0000000000000000000000000000000000000000..cbc5fd4545c9a983f4fc9acd66fab3f62b30aa61 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/installation.rst @@ -0,0 +1,78 @@ +Installation +============ + +Installing the Newton backend requires three things: + +1) The ``release/3.0.0-beta2`` branch of Isaac Lab +2) Ubuntu 22.04 or 24.04 +3) [Optional] Isaac Sim 6.0 (Isaac Sim is not required if the Omniverse visualizer is not used) + +To begin, navigate to the root directory of your local copy of the Isaac Lab repository and open a terminal. + +Make sure we are on the ``release/3.0.0-beta2`` branch by running the following command: + +.. code-block:: bash + + git checkout release/3.0.0-beta2 + + +Installation +------------ + +We recommend using **uv** as the package manager — it is significantly faster than pip and conda. +To install ``uv``, please follow the instructions `here `__. + +If you previously already have a virtual environment for Isaac Lab, please ensure to start from a fresh environment to avoid any dependency conflicts. +If you have installed earlier versions of mujoco, mujoco-warp, or newton packages through pip, we recommend first +cleaning your pip cache with ``pip cache purge`` to remove any cache of earlier versions that may be conflicting with the latest. + +Create a new virtual environment with Python 3.12: + +.. code-block:: bash + + uv venv --python 3.12 --seed env_isaaclab + +Activate the environment: + +.. code-block:: bash + + source env_isaaclab/bin/activate + +.. note:: + + If you are using ``pip`` directly instead of ``uv pip``, replace ``uv pip`` with ``pip`` in the commands below. + + +Ensure pip is up to date: + +.. code-block:: bash + + uv pip install --upgrade pip + +[Optional] Install Isaac Sim 6.0: + +.. code-block:: bash + + uv pip install "isaacsim[all,extscache]==6.0.1.0" --extra-index-url https://pypi.nvidia.com --index-strategy unsafe-best-match --prerelease=allow + +Install the correct version of torch and torchvision: + +.. code-block:: bash + + uv pip install -U torch==2.10.0 torchvision==0.25.0 --index-url https://download.pytorch.org/whl/cu128 + +Install Isaac Lab extensions and dependencies (this includes Newton 1.0): + +.. code-block:: bash + + ./isaaclab.sh -i + + +Testing the Installation +------------------------ + +To verify that the installation was successful, run the following command from the root directory of your Isaac Lab repository: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/zero_agent.py --task Isaac-Cartpole-Direct-v0 --num_envs 128 --viz newton physics=newton_mjwarp diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/kamino-solver.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/kamino-solver.rst new file mode 100644 index 0000000000000000000000000000000000000000..1ede9f509060ff3737da989bec96b5aae8f1e4d2 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/kamino-solver.rst @@ -0,0 +1,239 @@ +.. _newton-kamino-solver: + +Kamino Solver +============= + +Kamino is a Newton solver, not a separate Isaac Lab physics backend. In Isaac Lab, +Kamino is enabled by selecting a :class:`~isaaclab_newton.physics.NewtonCfg` whose +``solver_cfg`` is :class:`~isaaclab_newton.physics.KaminoSolverCfg`. +This is usually exposed as a ``newton_kamino`` physics preset on the task configuration. + +Kamino support is currently beta. A task that works with PhysX or with Newton's +MuJoCo-Warp solver may still need task-specific asset, collision, reset, and solver +tuning before it works well with Kamino. + + +Start from a Supported Newton Task +---------------------------------- + +Before adding Kamino, first make sure the task runs with the Newton backend: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/zero_agent.py --task Isaac-Cartpole-Direct-v0 --num_envs 128 --viz newton physics=newton_mjwarp + +Then run the same task with the Kamino preset if it is available: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/zero_agent.py --task Isaac-Cartpole-Direct-v0 --num_envs 128 --viz newton physics=newton_kamino + +At the time of writing, the ``newton_kamino`` preset is defined for +``Isaac-Cartpole-Direct-v0``, ``Isaac-Ant-Direct-v0``, ``Isaac-Cartpole-v0``, +and ``Isaac-Ant-v0``. Passing ``physics=newton_kamino`` to another task does not +automatically enable Kamino; the task must define and validate its own ``newton_kamino`` +preset. + + +Add a Kamino Physics Preset +--------------------------- + +Tasks that support multiple physics options usually store ``SimulationCfg.physics`` +as a :class:`~isaaclab_tasks.utils.hydra.PresetCfg`. First import the Newton +solver config types used by the presets: + +.. code-block:: python + + from isaaclab_newton.physics import KaminoSolverCfg, MJWarpSolverCfg, NewtonCfg + +Then add a ``newton_kamino`` entry beside the existing ``default``, ``physx``, and +``newton_mjwarp`` entries: + +.. literalinclude:: ../../../../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env_cfg.py + :language: python + :start-at: class CartpolePhysicsCfg + :end-at: ovphysx: OvPhysxCfg = OvPhysxCfg() + :emphasize-lines: 16-38 + +The important pieces are: + +* Add a ``newton_kamino`` preset whose value is :class:`~isaaclab_newton.physics.NewtonCfg`. +* Set ``solver_cfg=KaminoSolverCfg(...)`` inside that Newton config. +* Keep the preset at the same config path used by the task's + :class:`~isaaclab.sim.SimulationCfg`, for example ``env.sim.physics``. + +You can select the preset globally: + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl --task=Isaac-Cartpole-v0 physics=newton_kamino + +or select the physics field directly: + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl --task=Isaac-Cartpole-v0 env.sim.physics=newton_kamino + +Use the direct path override when only one task field should use the Kamino preset. +Use ``physics=newton_kamino`` when you want every matching preset field in the task config +to resolve to ``newton_kamino``. +Isaac Lab training commands accept these Hydra overrides after the regular command +line flags; no separator is needed for the examples above. + + +Check Task and Asset Compatibility +---------------------------------- + +Kamino uses the Newton model built from the task assets. When adding Kamino to a +new task, validate the following before tuning solver parameters: + +* The task must already be compatible with the Newton backend. If ``physics=newton_mjwarp`` + fails during model construction, fix the asset or task configuration first. +* The assets should use Newton-supported rigid bodies, articulations, and collision + geometry. PhysX-only features, unsupported schemas, or missing collision shapes + can prevent Newton model creation or produce unusable contacts. +* Reset logic should write consistent root and joint state through Isaac Lab asset + APIs. Kamino uses a forward-kinematics reset path after state writes so maximal + coordinate body poses match the reduced joint state. +* Sensor, renderer, and visualizer presets remain separate from the solver preset. + Kamino can share the Newton-compatible sensors and renderers used by the task, + but each sensor and renderer combination still needs its own validation. +* Contact-heavy tasks usually need their own collision mode, substep count, and + P-ADMM iteration/tolerance settings. Start from the validated Cartpole or Ant + preset that most closely resembles the task. + +For a small articulated system with simple contacts, the Cartpole preset uses +Kamino's internal collision detector. For Ant, the preset uses Newton's collision +pipeline and two substeps. These choices are task-specific; treat them as starting +points rather than universal defaults. + + +Kamino Solver Parameters +------------------------ + +The following fields are specific to :class:`~isaaclab_newton.physics.KaminoSolverCfg`. +They are grouped by the part of the solver they affect. + +Core Integration +^^^^^^^^^^^^^^^^ + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Parameter + - Description + * - ``integrator`` + - Default: ``"euler"``. Time integration scheme. ``"moreau"`` is used by the validated Kamino task presets. + * - ``use_fk_solver`` + - Default: ``True``. Enables Kamino's forward-kinematics solver for resets. Keep this enabled for Isaac Lab tasks unless you have a task-specific reset path. + * - ``rotation_correction`` + - Default: ``"twopi"``. Rotation correction mode for maximal-coordinate bodies. Valid values are ``"twopi"``, ``"continuous"``, and ``"none"``. + * - ``angular_velocity_damping`` + - Default: ``0.0``. Damps angular velocity. Higher values can suppress spin but also remove physical energy from the system. + + +Collision Handling +^^^^^^^^^^^^^^^^^^ + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Parameter + - Description + * - ``use_collision_detector`` + - Default: ``False``. Selects Kamino's internal collision detector when ``True``. When ``False``, Isaac Lab uses Newton's collision pipeline for contact generation. + * - ``collision_detector_pipeline`` + - Default: ``None``. Internal Kamino collision detector pipeline. Common values are ``"primitive"`` and ``"unified"``. Only used when ``use_collision_detector=True``. + * - ``collision_detector_max_contacts_per_pair`` + - Default: ``None``. Maximum contacts generated per candidate geometry pair by the internal Kamino collision detector. + * - ``constraints_delta`` + - Default: ``1.0e-6``. Contact penetration margin [m] used by Kamino constraint stabilization. + + +Constraint Stabilization +^^^^^^^^^^^^^^^^^^^^^^^^ + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Parameter + - Description + * - ``constraints_alpha`` + - Default: ``0.01``. Baumgarte stabilization for bilateral joint constraints. Increasing it can reduce joint constraint drift but may make the solve stiffer. + * - ``constraints_beta`` + - Default: ``0.01``. Baumgarte stabilization for unilateral joint-limit constraints. + * - ``constraints_gamma`` + - Default: ``0.01``. Baumgarte stabilization for unilateral contact constraints. + + +P-ADMM Solver Controls +^^^^^^^^^^^^^^^^^^^^^^ + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Parameter + - Description + * - ``padmm_max_iterations`` + - Default: ``200``. Maximum number of P-ADMM iterations per solver step. Higher values can improve convergence and increase runtime. + * - ``padmm_primal_tolerance`` + - Default: ``1e-6``. Primal residual convergence tolerance. + * - ``padmm_dual_tolerance`` + - Default: ``1e-6``. Dual residual convergence tolerance. + * - ``padmm_compl_tolerance`` + - Default: ``1e-6``. Complementarity residual convergence tolerance for contacts and unilateral constraints. + * - ``padmm_rho_0`` + - Default: ``1.0``. Initial P-ADMM penalty parameter. This influences how strongly constraint residuals are penalized early in the solve. + * - ``padmm_eta`` + - Default: ``1e-5``. Proximal regularization parameter. It must be greater than zero. + * - ``padmm_use_acceleration`` + - Default: ``True``. Enables acceleration in the P-ADMM iterations. This usually improves convergence but should be validated per task. + * - ``padmm_warmstart_mode`` + - Default: ``"containers"``. Warm-start source for P-ADMM. Valid values are ``"none"``, ``"internal"``, and ``"containers"``. + * - ``padmm_contact_warmstart_method`` + - Default: ``"key_and_position"``. Contact warm-start matching method. The validated presets use ``"geom_pair_net_force"``. + * - ``padmm_use_graph_conditionals`` + - Default: ``True``. Uses CUDA graph conditional nodes for the iterative solver when ``True``. Setting it to ``False`` unrolls to fixed loops over the maximum iteration count. + + +Sparsity, Dynamics, and Debugging +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Parameter + - Description + * - ``sparse_jacobian`` + - Default: ``False``. Uses sparse Jacobian computation. This is enabled in the validated Kamino task presets. + * - ``sparse_dynamics`` + - Default: ``False``. Uses sparse dynamics computation. + * - ``dynamics_preconditioning`` + - Default: ``True``. Enables preconditioning for constrained dynamics. Preconditioning can improve P-ADMM convergence. + * - ``collect_solver_info`` + - Default: ``False``. Collects solver convergence and performance information. Enable only for debugging because it significantly increases runtime. + * - ``compute_solution_metrics`` + - Default: ``False``. Computes solution metrics at each step. Enable only for debugging because it significantly increases runtime. + + +Tuning Workflow +--------------- + +Use the following sequence when bringing up a new Kamino task: + +1. Run the task with ``physics=newton_mjwarp`` and fix Newton model construction or task + compatibility issues first. +2. Add a ``newton_kamino`` preset with conservative values copied from the closest + validated task. +3. Run a small smoke test with a low environment count and a visualizer. +4. Increase ``num_envs`` and profile only after the task is stable. +5. Tune ``num_substeps``, ``padmm_max_iterations``, and the P-ADMM tolerances + together. Raising iteration count without checking tolerances can hide a + poorly scaled constraint setup. +6. Enable ``collect_solver_info`` or ``compute_solution_metrics`` only while + debugging convergence. Disable them for training and benchmarks. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/mjwarp-solver.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/mjwarp-solver.rst new file mode 100644 index 0000000000000000000000000000000000000000..18bdeabfc6148bd7c9cbdec773a7253dfcedcc14 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/mjwarp-solver.rst @@ -0,0 +1,92 @@ +MJWarp Solver +============= + +The MuJoCo-Warp solver from Google DeepMind is the primary, validated solver +for the Newton backend in Isaac Lab. It is enabled by setting +:attr:`~isaaclab_newton.physics.NewtonCfg.solver_cfg` to a +:class:`~isaaclab_newton.physics.MJWarpSolverCfg`, usually exposed as the +``newton_mjwarp`` physics preset on a task configuration. Newton ships with +beta support for an alternative Kamino solver — see :doc:`kamino-solver` and +:ref:`hydra-backend-solver-presets` for how presets are selected. For details +on how solver-specific managers are implemented, or how to add a new solver +manager, see :doc:`newton-manager-abstraction`. + +.. note:: + + Kamino support is experimental and currently depends on assets being structured + in a way that Kamino can consume. Assets that work with MuJoCo-Warp or PhysX + may still require model-structure updates before they work with Kamino. + +The way the physics scene itself is defined does not change - we continue to use USD as the primary way to set basic parameters of objects and robots in the scene, +and for current environments, the exact same USD files used for the PhysX-based Isaac Lab are used. +In the future, that may change, as new USD schemas are under development that capture additional physics parameters. + +What does require change is the way that some solver-specific settings are configured. +Tuning these parameters can have a significant impact on both simulation performance and behaviour. + +For now, we will show an example of setting these parameters to help provide a feel for these changes. +Note that the :class:`~isaaclab_newton.physics.NewtonCfg` replaces +:class:`~isaaclab_physx.physics.PhysxCfg` and is used to set everything related to the physical +simulation parameters except for the ``dt``: + +.. code-block:: python + + from isaaclab.sim import SimulationCfg + from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + + solver_cfg = MJWarpSolverCfg( + njmax=35, + nconmax=20, + ls_iterations=10, + cone="pyramidal", + ls_parallel=True, + impratio=1, + ) + newton_cfg = NewtonCfg( + solver_cfg=solver_cfg, + num_substeps=1, + debug_mode=False, + ) + sim: SimulationCfg = SimulationCfg(dt=1 / 120, render_interval=decimation, physics=newton_cfg) + + +Here is a very brief explanation of some of the key parameters above: + +* ``njmax``: This is the number of constraint rows MuJoCo-Warp pre-allocates for a + given environment. A large value will slow down the simulation, while a too small + value may lead to missing constraints. + +* ``nconmax``: This is the maximum number of contact points MuJoCo-Warp pre-allocates + for a given environment. Set it high enough for the expected contact count. + +* ``ls_iterations``: The number of line searches performed by the MuJoCo Warp solver. + Line searches are used to find an optimal step size, and for each solver step, + at most ``ls_iterations`` line searches will be performed. Keeping this number low + is important for performance. This number is also an upper bound when + ``ls_parallel`` is not set. + +* ``cone``: This parameter provides a choice between pyramidal and elliptic + approximations for the friction cone used in contact handling. Please see the + MuJoCo documentation for additional information on contact: + https://mujoco.readthedocs.io/en/stable/computation/index.html#contact + +* ``ls_parallel``: This switches line searches from iterative to parallel execution. + Enabling ``ls_parallel`` provides a performance boost, but at the cost of some + simulation stability. To ensure good simulation behaviour when enabled, a higher + ``ls_iterations`` setting is required. Usually an increase of approximately 50% is + best over the ``ls_iterations`` setting when ``ls_parallel`` is disabled. + +* ``impratio``: This is the frictional-to-normal constraint impedance ratio that + enables finer-grained control of the significance of the tangential forces + compared to the normal forces. Larger values signify more emphasis on harder + frictional constraints to avoid slip. More on how to tune this parameter (and + cone) can be found in the MuJoCo documentation here: + https://mujoco.readthedocs.io/en/stable/XMLreference.html#option-impratio + +* ``num_substeps``: The number of substeps to perform when running the simulation. + Setting this to a number larger than one allows to decimate the simulation + without requiring Isaac Lab to process data between two substeps. This can be + of value when using implicit actuators, for example. + + +A more detailed transition guide covering the full set of available parameters and describing tuning approaches will follow in an upcoming release. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/newton-manager-abstraction.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/newton-manager-abstraction.rst new file mode 100644 index 0000000000000000000000000000000000000000..312d0c5bb792c5dad3781edfdd7d283571fe819f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/newton-manager-abstraction.rst @@ -0,0 +1,237 @@ +Newton Manager Abstraction +========================== + +Newton exposes multiple solver families, and Isaac Lab keeps that flexibility by +making each solver an implementation detail of a small +:class:`~isaaclab_newton.physics.NewtonManager` subclass. The simulation context +still sees a normal physics manager; the solver configuration decides which +manager class is used. + +For most new Newton solvers, the integration surface is intentionally small: + +* define a solver config that inherits from + :class:`~isaaclab_newton.physics.NewtonSolverCfg`; +* point the config's ``class_type`` at a manager subclass; +* implement ``_build_solver()`` in that manager; +* set the three base-manager slots: ``_solver``, ``_use_single_state``, and + ``_needs_collision_pipeline``. + +The existing MuJoCo Warp, XPBD, Featherstone, and Kamino managers are examples +of this pattern. + + +Adding a Solver Manager +----------------------- + +The solver config carries both user-tunable solver parameters and the manager +dispatch target: + +.. code-block:: python + + from isaaclab_newton.physics import NewtonManager, NewtonSolverCfg + from isaaclab.utils.configclass import configclass + + + @configclass + class MySolverCfg(NewtonSolverCfg): + class_type: type[NewtonManager] | str = "{DIR}.my_solver_manager:NewtonMySolverManager" + solver_type: str = "my_solver" + iterations: int = 16 + + +``NewtonCfg`` copies ``solver_cfg.class_type`` into its own ``class_type`` in +``__post_init__``. User code keeps the normal shape: + +.. code-block:: python + + from isaaclab.sim import SimulationCfg + from isaaclab_newton.physics import NewtonCfg + + sim_cfg = SimulationCfg( + physics=NewtonCfg( + solver_cfg=MySolverCfg(iterations=32), + num_substeps=2, + ) + ) + + +The manager then owns solver construction: + +.. code-block:: python + + from newton import Model + from newton.solvers import SolverMySolver + + from isaaclab_newton.physics import NewtonManager + + + class NewtonMySolverManager(NewtonManager): + @classmethod + def _build_solver(cls, model: Model, solver_cfg: MySolverCfg) -> None: + NewtonManager._solver = SolverMySolver(model, iterations=solver_cfg.iterations) + NewtonManager._use_single_state = False + NewtonManager._needs_collision_pipeline = True + + +``_use_single_state`` tells the base manager whether the solver advances in +place or swaps input/output states. ``_needs_collision_pipeline`` tells the base +manager whether to allocate and pass Newton collision-pipeline contacts to the +solver. A solver with its own internal contact detector can set it to ``False``. + +Optional Overrides +------------------ + +Most managers only implement ``_build_solver()``. Override more only when the +solver actually needs it: + +* ``_initialize_contacts()``: allocate custom contact buffers or support an + internal contact detector. +* ``_step_solver(state_0, state_1, control, substep_dt)``: change one substep of + solver execution while keeping the base simulation loop. +* ``_simulate_physics_only()``: add per-step work around the base substep loop, + such as rebuilding a BVH. +* ``step()``: handle solver-specific reset masks, graph capture, or model-change + notification before delegating to the base manager. +* ``start_simulation()`` or ``instantiate_builder_from_stage()``: customize model + building or post-finalize setup. +* ``_solver_specific_clear()``: release any class-level state owned by the + solver manager. + +Keep the manager name prefixed with ``Newton`` and the solver config grouped +with the other Newton solver configs so autocomplete and backend discovery stay +predictable. + + +Custom Coupled Solvers +---------------------- + +Coupled solvers use the same abstraction. Instead of wrapping one Newton solver, +a coupled manager constructs two or more sub-solvers and overrides +``_step_solver()`` to define the substep order. +That means a custom coupling usually needs only a config that stores existing +solver configs plus a manager that defines how data flows between them; the +component solvers can stay unchanged. + +The MJWarp + VBD deformable manager is a concrete example: + +* :class:`~isaaclab_contrib.deformable.CoupledMJWarpVBDSolverCfg` stores a + ``rigid_solver_cfg`` for :class:`~isaaclab_newton.physics.MJWarpSolverCfg`, a + ``soft_solver_cfg`` for :class:`~isaaclab_contrib.deformable.VBDSolverCfg`, + and a ``coupling_mode``. +* ``NewtonCoupledMJWarpVBDManager._build_solver()`` constructs + ``SolverMuJoCo`` and ``SolverVBD`` from those sub-configs. +* ``_step_solver()`` dispatches to either one-way or two-way coupling. +* The base ``NewtonManager`` still owns state allocation, substep iteration, + Fabric synchronization, and reset/clear lifecycle. + +The two-way MJWarp + VBD substep stays compact because it is expressed as a +short coupling algorithm: + +.. admonition:: Algorithm: Two-Way MJWarp + VBD Substep + :class: note + + **Inputs:** rigid body state, deformable particle state, and the shared + Newton collision pipeline. + + **Output:** updated rigid body and deformable particle state for one Newton + substep. + + 1. **Reset force accumulators.** + Clear the rigid body and particle force buffers before evaluating the + next contact pass. + + 2. **Detect coupled contacts.** + Run Newton collision detection once over the current rigid and + deformable state. + + 3. **Apply soft-to-rigid reactions.** + Inject body-particle contact reactions into ``body_f`` so the rigid + bodies can be pushed back by the deformable contact penalties. + + 4. **Advance the rigid solver.** + Step the MJWarp rigid solver with the coupled contact forces applied. + + 5. **Preserve shared contacts for the soft solve.** + Clear particle forces written during the rigid step while keeping the + detected contact information available. + + 6. **Advance the deformable solver.** + Step the VBD soft solver against the same coupled contacts. + + +This keeps the custom part focused on the coupling policy. The manager does not +need to reimplement scene loading, asset buffers, reset handling, or the outer +simulation loop. + +.. figure:: ../../../../_static/newton/franka-mjwarp-vbd-coupling.png + :align: center + :figwidth: 480px + :class: square-crop-figure + :alt: Franka manipulating a deformable object with MJWarp and VBD coupling + + Franka manipulation using MJWarp for rigid bodies and VBD for the deformable + object. + +You can exercise this coupling path with the Franka soft-body lifting task: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/zero_agent.py --task Isaac-Lift-Soft-Franka-v0 --num_envs 1 --visualizer kit + +For the surface-deformable cloth variant, use ``--task Isaac-Lift-Cloth-Franka-v0``. + + +This environment configures +:class:`~isaaclab_contrib.deformable.CoupledMJWarpVBDSolverCfg` with +``coupling_mode="two_way"``. + +Tuning the Franka Soft-Body Lift +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tune the coupled contact behavior before training a policy: + +* Start with ``coupling_mode="two_way"``. Compared with one-way coupling, two-way + coupling can prevent clipping more easily because body-particle contact + penalties can push the robot back instead of only moving the deformable. +* Use a small scripted grasp/lift check before training to confirm that grasping + is possible and to inspect what clips when the grasp fails. +* Lower the arm actuator stiffness enough that the arm can respond to contact + penalties. Prefer the arm being pushed back over the gripper clipping into the + deformable. +* Tune :attr:`~isaaclab_contrib.deformable.NewtonModelCfg.soft_contact_ke` + first. Increase it only as much as needed to prevent clipping, then adjust + :attr:`~isaaclab_contrib.deformable.NewtonModelCfg.soft_contact_mu` so the + gripper can carry the object without requiring an obviously unphysical + friction value. Use + :attr:`~isaaclab_contrib.deformable.NewtonModelCfg.soft_contact_kd` for + stabilization if contacts chatter. +* Tune the ``soft_contact_*`` values together with ``shape_material_*`` values + because rigid shape material parameters also affect the effective contact. +* If ``soft_contact_ke`` is not sufficient, or ``soft_contact_mu`` must be + unphysically high, tune the Franka arm and hand actuator stiffness and maximum + effort. For the gripper command, fully close the fingers and let the actuator + maximum effort limit the actual squeeze. +* If the deformable no longer visibly deforms, ``soft_contact_ke`` is likely too + high. +* If contacts are unstable or missed, increase the deformable mesh resolution or + increase ``particle_radius`` in the deformable material so contact is detected + earlier from a larger distance. +* If the rigid shapes still clip through the deformable, increase + :attr:`~isaaclab_contrib.deformable.VBDSolverCfg.iterations`; more VBD + iterations can improve contact convergence. + + +When to Add a Coupled Manager +----------------------------- + +Add a coupled manager when one solver cannot own the whole model step by itself: + +* rigid bodies should use one solver while particles or cloth use another; +* contact detection is shared, but each solver consumes the contacts + differently; +* you need a custom force, impulse, or state exchange between solvers; +* the substep order is part of the algorithm. + +Use a normal single-solver manager when all physics can be advanced by one +Newton solver. Use a coupled manager only for the small amount of glue that is +truly solver-specific. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/supported-features.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/supported-features.rst new file mode 100644 index 0000000000000000000000000000000000000000..a64974b4e374380faebad8bad617f238ce9d6bb4 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/supported-features.rst @@ -0,0 +1,108 @@ +Supported Features +================== + +The Newton backend is in beta. Breaking changes and incomplete documentation are +still expected, and official support or debugging assistance will only be +available once the integration reaches an official release. + + +Discovering Newton-Supported Tasks +---------------------------------- + +A task supports the Newton backend when its physics ``PresetCfg`` declares a +``newton_mjwarp`` (or ``newton_kamino``) entry. To list every task that +currently supports Newton: + +.. code-block:: bash + + grep -rln "newton_mjwarp" source/isaaclab_tasks/ + +Passing ``physics=newton_mjwarp`` to a task without that preset will raise an +error at launch. The :doc:`mjwarp-solver` page covers how to add a Newton +preset to your own task. + + +Supported APIs +-------------- + +The following capabilities are covered by the Newton backend on ``release/3.0.0-beta2`` at +the time of writing. The list is non-exhaustive and continues to grow. + +isaaclab +^^^^^^^^ + +* Articulation API (multi-link and single-body articulations) +* Rigid Object and Rigid Object Collection APIs +* Sensors: Contact Sensor, IMU, Frame Transformer, Joint Wrench, PVA +* Direct and Manager-based single-agent workflows +* Backend-neutral deformable object API +* Omniverse Kit visualizer (when Isaac Sim is installed) +* Newton-Warp visualizer (kit-less) +* Tiled rendering via the Newton-Warp renderer + +isaaclab_contrib +^^^^^^^^^^^^^^^^ + +* Experimental Newton deformable objects +* VBD deformable solver (see :doc:`using-vbd-solver`) +* Coupled MJWarp + VBD and Featherstone + VBD solver managers + +The following sensors are backend-agnostic (implemented in ``isaaclab`` core) +and work transparently with Newton: + +* Ray Caster +* Camera — see :doc:`../../sensors/camera` + +isaaclab_assets +^^^^^^^^^^^^^^^ + +* Quadrupeds: Anymal-B, Anymal-C, Anymal-D, Unitree A1, Unitree Go1, Unitree + Go2, Spot +* Humanoids: Unitree H1, Unitree G1, Cassie +* Arms and hands: Franka, UR10, Allegro Hand, Shadow Hand +* Toy examples: Cartpole, Ant, Humanoid + +isaaclab_tasks +^^^^^^^^^^^^^^ + +Direct workflows: + +* Cartpole (state, RGB, depth) +* Ant, Humanoid +* Allegro Hand Repose Cube, Shadow Hand, Shadow Hand Over +* Locomotion (shared base env) + +Manager-based workflows: + +* Classic: Cartpole, Ant, Humanoid +* Locomotion velocity, flat terrain: A1, Anymal-B, Anymal-C, Anymal-D, Cassie, + Unitree G1, Go1, Go2, Unitree H1, Spot +* Locomotion velocity, rough terrain: Anymal-C, Cassie, Go1, Go2 +* Manipulation: reach (Franka, UR10), cabinet, dexsuite +* Manipulation lift with deformable objects: Franka soft-body lift, Franka cloth + lift (via coupled MJWarp + VBD) + + +Solver Coverage +--------------- + +* **MuJoCo-Warp solver**: the primary, validated path for every supported task. +* **Kamino solver**: beta. Currently validated on ``Isaac-Cartpole-Direct-v0``, + ``Isaac-Ant-Direct-v0``, ``Isaac-Cartpole-v0``, and ``Isaac-Ant-v0``. See + :doc:`kamino-solver`. +* **VBD solver**: experimental, exposed through :mod:`isaaclab_contrib.deformable` + for cloth and soft-body simulation. Most often used inside the coupled + MJWarp + VBD or Featherstone + VBD managers so one solver advances rigid + bodies and VBD advances deformable particles. See :doc:`using-vbd-solver` + and :doc:`newton-manager-abstraction`. + + +Known Gaps +---------- + +* Soft bodies and particles are available through the experimental VBD path in + :mod:`isaaclab_contrib.deformable`; other non-rigid PhysX features are not + yet covered. +* Behaviour on stiff contact stacks can diverge from PhysX; expect to retune + contact and substep parameters when porting tasks across backends. +* Multi-agent and self-play workflows are not yet wired up for Newton. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/using-vbd-solver.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/using-vbd-solver.rst new file mode 100644 index 0000000000000000000000000000000000000000..4939cfe7cfbfc04db037e32d8db708f85d44c9af --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/using-vbd-solver.rst @@ -0,0 +1,344 @@ +.. _newton-using-vbd: + +VBD Solver +========== + +Vertex Block Descent (VBD) is a Newton solver for cloth and soft-body +simulation. In Isaac Lab, VBD is enabled by selecting a +:class:`~isaaclab_newton.physics.NewtonCfg` whose ``solver_cfg`` is provided by +:mod:`isaaclab_contrib.deformable`. + +VBD support is experimental. The solver managers, configuration fields, and +recommended tuning values may change while Newton deformable support is under +active development. A task that works with PhysX or with Newton's MuJoCo-Warp +solver may still need deformable assets, materials, contacts, and coupling tuned +before it works well with VBD. + +VBD is usually exposed through a task-specific physics preset rather than a +general ``newton_vbd`` preset. Deformable-only scenes can use +:class:`~isaaclab_contrib.deformable.VBDSolverCfg` directly. Robot or +rigid-body scenes usually use +:class:`~isaaclab_contrib.deformable.CoupledMJWarpVBDSolverCfg` or +:class:`~isaaclab_contrib.deformable.CoupledFeatherstoneVBDSolverCfg` so one +solver advances rigid bodies and VBD advances deformable particles. + +Start from a Supported Deformable Task +-------------------------------------- + +Before adding VBD to a new task, first run one of the experimental Franka +deformable tasks: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/zero_agent.py --task Isaac-Lift-Soft-Franka-v0 --num_envs 1 --visualizer kit + +For the surface-deformable cloth variant, use: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/zero_agent.py --task Isaac-Lift-Cloth-Franka-v0 --num_envs 1 --visualizer kit + +Both tasks configure MJWarp for the rigid Franka and VBD for the deformable +object through +:class:`~isaaclab_contrib.deformable.CoupledMJWarpVBDSolverCfg`. +Use these tasks as starting points for asset setup, solver coupling, and contact +tuning. + +Add a VBD Physics Preset +------------------------ + +Tasks that support multiple physics options usually store ``SimulationCfg.physics`` +as a :class:`~isaaclab_tasks.utils.hydra.PresetCfg`. For deformable Newton tasks, +the preset can use a small :class:`~isaaclab_newton.physics.NewtonCfg` subclass +to carry :class:`~isaaclab_contrib.deformable.NewtonModelCfg` alongside the +normal Newton fields: + +.. code-block:: python + + from isaaclab.utils.configclass import configclass + from isaaclab_newton.physics import NewtonCfg + + from isaaclab_contrib.deformable import NewtonModelCfg + + + @configclass + class DeformableNewtonCfg(NewtonCfg): + model_cfg: NewtonModelCfg | None = None + + +The Franka soft-body task defines a ``newton_mjwarp_vbd`` preset that couples +MJWarp and VBD: + +.. literalinclude:: ../../../../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift_franka_soft/franka_soft_env_cfg.py + :language: python + :start-at: class PhysicsCfg + :end-at: default = newton_mjwarp_vbd + :emphasize-lines: 4-32 + +The important pieces are: + +* Add a Newton physics preset whose value is ``DeformableNewtonCfg``. +* Use :class:`~isaaclab_contrib.deformable.CoupledMJWarpVBDSolverCfg` when rigid + bodies and deformables must interact in the same scene. +* Use ``soft_solver_cfg=VBDSolverCfg(integrate_with_external_rigid_solver=True)`` + inside a coupled solver so VBD advances only the deformable particles. +* Add :class:`~isaaclab_contrib.deformable.NewtonModelCfg` when body-particle or + self-contact values need task-level tuning. +* Keep the preset at the same config path used by the task's + :class:`~isaaclab.sim.SimulationCfg`, for example ``env.sim.physics``. + +You can select the deformable Newton preset globally: + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl --task=Isaac-Lift-Soft-Franka-v0 physics=newton_mjwarp_vbd + +or select the physics field directly: + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl --task=Isaac-Lift-Soft-Franka-v0 env.sim.physics=newton_mjwarp_vbd + +Use the direct path override when only one task field should use the VBD preset. +Use ``physics=newton_mjwarp_vbd`` when you want every matching preset field in +the task config to resolve to that preset. Isaac Lab training commands accept +these Hydra overrides after the regular command line flags; no separator is +needed for the examples above. + + +Check Task and Asset Compatibility +---------------------------------- + +VBD uses the Newton model built from the task assets. When adding VBD to a new +task, validate the following before tuning solver parameters: + +* The task must already be compatible with the Newton backend. If a rigid-only + ``newton_mjwarp`` preset fails during model construction, fix the asset or task + configuration first. +* The scene must include Newton-compatible deformable assets and materials. Use + :class:`~isaaclab_newton.sim.spawners.materials.NewtonDeformableBodyMaterialCfg` + for volume deformables and + :class:`~isaaclab_newton.sim.spawners.materials.NewtonSurfaceDeformableBodyMaterialCfg` + for cloth or surface deformables. +* Coupled robot tasks should start with ``coupling_mode="two_way"`` when the + robot should feel contact forces from the deformable object. +* Contact-heavy scenes usually need task-specific ``num_substeps``, + :class:`~isaaclab_contrib.deformable.VBDSolverCfg`, and + :class:`~isaaclab_contrib.deformable.NewtonModelCfg` values. Start from the + Franka soft-body or cloth preset that most closely resembles the scene. +* Use a small visual smoke test before training. Confirm that the deformable + spawns, renders, deforms, and contacts rigid bodies as expected. + +VBD Solver Parameters +--------------------- + +The following fields are specific to +:class:`~isaaclab_contrib.deformable.VBDSolverCfg`. They are grouped by the part +of the solver they affect. + +Core Solve +^^^^^^^^^^ + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Parameter + - Description + * - ``iterations`` + - Default: ``10``. Number of VBD iterations per substep. Increasing this value improves deformation and contact convergence, especially for stiff materials or rigid gripper contacts, but increases runtime. + * - ``integrate_with_external_rigid_solver`` + - Default: ``False``. Set to ``True`` when VBD is used inside a coupled solver so the rigid sub-solver owns rigid-body integration. Leave ``False`` for deformable-only VBD scenes. + + +Self-Contact +^^^^^^^^^^^^ + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Parameter + - Description + * - ``particle_enable_self_contact`` + - Default: ``False``. Enables deformable self-contact. Use this for cloth folds or soft bodies that collide with themselves. It increases contact work and usually needs additional tuning. + * - ``particle_self_contact_radius`` + - Default: ``0.005`` [m]. Effective self-contact thickness. VBD applies vertex-triangle and edge-edge self-contact response when the current primitive distance is smaller than this radius. + * - ``particle_self_contact_margin`` + - Default: ``0.005`` [m]. Self-contact candidate search distance. VBD uses this envelope when building self-contact lists, then applies contact response using ``particle_self_contact_radius``. Keep this greater than or equal to the radius to avoid missed contacts. + * - ``particle_collision_detection_interval`` + - Default: ``-1``. Controls how often self-contact detection runs. A negative value detects before initialization only. ``0`` detects before and immediately after initialization. A positive value ``k`` detects before every ``k`` VBD iterations. + * - ``particle_vertex_contact_buffer_size`` + - Default: ``32``. Preallocation size for each vertex's vertex-triangle self-contact buffer. Increase it if dense folds or high-resolution cloth exceed the default capacity. + * - ``particle_edge_contact_buffer_size`` + - Default: ``64``. Preallocation size for each edge's edge-edge self-contact buffer. Increase it if dense folds or high-resolution cloth exceed the default capacity. + * - ``particle_topological_contact_filter_threshold`` + - Default: ``2``. Filters contacts between mesh primitives that are close in topology. Increase this to suppress contact between neighboring elements of the same surface. Values greater than ``3`` can significantly increase compute time. + * - ``particle_rest_shape_contact_exclusion_radius`` + - Default: ``0.0`` [m]. Filters self-contact candidates whose rest-configuration distance is shorter than this distance. Increase it when rest-neighbor contacts produce unwanted resistance. + + +Coupled Solver Parameters +------------------------- + +Use the coupled solver configs when one solver should advance rigid bodies and +VBD should advance deformables: + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Parameter + - Description + * - ``rigid_solver_cfg`` + - Rigid-body sub-solver configuration. :class:`~isaaclab_contrib.deformable.CoupledMJWarpVBDSolverCfg` uses :class:`~isaaclab_newton.physics.MJWarpSolverCfg`; :class:`~isaaclab_contrib.deformable.CoupledFeatherstoneVBDSolverCfg` uses :class:`~isaaclab_newton.physics.FeatherstoneSolverCfg`. + * - ``soft_solver_cfg`` + - VBD sub-solver configuration. In coupled scenes, set ``integrate_with_external_rigid_solver=True`` so VBD advances only deformable particles. + * - ``coupling_mode="one_way"`` + - Rigid solver advances first, and VBD reacts to the updated rigid poses. The rigid solver does not feel particle contact forces. + * - ``coupling_mode="two_way"`` + - Contact reactions from deformables are injected into the rigid solver before the rigid step, then VBD advances deformables against the shared contacts. Use this for manipulation tasks where the robot should be pushed back by deformable contact. + * - ``coupling_mode="kinematic"`` + - Available on :class:`~isaaclab_contrib.deformable.CoupledFeatherstoneVBDSolverCfg`. Rigid bodies are kinematically updated by Featherstone, and VBD reacts to them. The rigid solver does not feel particle contacts. + +The rigid solver parameters still matter. For example, MJWarp's ``nconmax`` and +``njmax`` must be large enough for the rigid contacts in the scene, and +``ccd_iterations`` can affect fast rigid contacts near deformables. See +:doc:`mjwarp-solver` for the MJWarp-side parameters. + + +Contact and Material Parameters +------------------------------- + +Contact Model +^^^^^^^^^^^^^ + +:class:`~isaaclab_contrib.deformable.NewtonModelCfg` applies contact parameters +to the finalized Newton model: + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Parameter + - Description + * - ``soft_contact_ke`` + - Default: ``1.0e3`` [N/m]. Stiffness for body-particle and particle self-contact. Increase it to reduce clipping through rigid shapes or through other deformable particles. If it is too high, the object can stop visibly deforming or require more VBD iterations and substeps. + * - ``soft_contact_kd`` + - Default: ``1.0e-2`` [N*s/m]. Contact damping. Increase it to reduce chatter or bouncing. Too much damping can make contact response sticky or overdamped. + * - ``soft_contact_mu`` + - Default: ``0.5``. Friction coefficient for body-particle and particle self-contact. Increase it when a gripper cannot carry the deformable object without slipping. + * - ``shape_material_ke`` + - Default: ``None`` [N/m]. Optional override for all rigid collision-shape contact stiffness values in the Newton model. Use this when the rigid-side material parsed from the asset is not appropriate for deformable contact. + * - ``shape_material_kd`` + - Default: ``None`` [N*s/m]. Optional override for all rigid collision-shape contact damping values in the Newton model. + * - ``shape_material_mu`` + - Default: ``None``. Optional override for all rigid collision-shape friction values in the Newton model. Body-particle friction depends on both the soft contact and rigid shape friction coefficients. + + +Volume Deformable Materials +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Use +:class:`~isaaclab_newton.sim.spawners.materials.NewtonDeformableBodyMaterialCfg` +for volume deformables: + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Parameter + - Description + * - ``density`` + - Default: ``1.0`` [kg/m^3]. Material density. Higher density increases particle mass and inertia, so the object accelerates and deforms less for the same contact forces. + * - ``particle_radius`` + - Default: ``0.008`` [m]. Particle contact radius used by Newton. Increase it when contacts are missed or detected too late. If it is too large relative to the mesh resolution, contacts can start too early. + * - ``k_mu`` + - Default: ``1.0e5`` [Pa]. First Lame material parameter. Higher values make the deformable object stiffer and usually require more VBD iterations, more substeps, or a smaller timestep. + * - ``k_lambda`` + - Default: ``1.0e5`` [Pa]. Second Lame material parameter. Higher values make the deformable object stiffer and usually require more VBD iterations, more substeps, or a smaller timestep. + * - ``k_damp`` + - Default: ``0.0`` [Pa*s]. Damping for tetrahedral elements. Increase it to reduce oscillations after deformation, but avoid overdamping if the object should rebound. + + +Surface Deformable Materials +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Use +:class:`~isaaclab_newton.sim.spawners.materials.NewtonSurfaceDeformableBodyMaterialCfg` +for cloth or surface deformables: + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Parameter + - Description + * - ``density`` + - Default: ``1.0`` [kg/m^3]. Material density. Higher density increases particle mass and inertia. + * - ``particle_radius`` + - Default: ``0.008`` [m]. Particle contact radius used by Newton. + * - ``tri_ke`` + - Default: ``1.0e4`` [Pa]. Triangle area-preserving stiffness. Increase it to reduce cloth stretch. + * - ``tri_ka`` + - Default: ``1.0e4`` [Pa]. Triangle area stiffness. Increase it to reduce cloth area change. + * - ``tri_kd`` + - Default: ``1.5e-6`` [Pa*s]. Triangle area damping. Increase it to reduce cloth vibration after stretching. + * - ``edge_ke`` + - Default: ``5.0`` [N*m]. Bending stiffness. Increase it for stiffer cloth folds; decrease it for softer draping. + * - ``edge_kd`` + - Default: ``1.0e-2`` [N*m*s]. Bending damping. Increase it to damp fold oscillations. + +Tuning Workflow +--------------- + +Use the following sequence when bringing up a new VBD task: + +1. Run one of the supported Franka deformable tasks and confirm your + installation, visualizer, and deformable rendering path work. +2. Add a task-specific VBD or coupled VBD preset copied from the closest + supported task. +3. Run a small visual smoke test with ``--num_envs 1`` before training. +4. Tune deformable material stiffness and damping until the object deforms in + the expected range without rigid contact. +5. Increase ``num_substeps`` or decrease ``dt`` if the object is unstable before + increasing stiffness further. +6. Increase :attr:`~isaaclab_contrib.deformable.VBDSolverCfg.iterations` when + contacts or stiff materials do not converge within a substep. +7. Tune :attr:`~isaaclab_contrib.deformable.NewtonModelCfg.soft_contact_ke` to + reduce rigid/deformable clipping, then tune + :attr:`~isaaclab_contrib.deformable.NewtonModelCfg.soft_contact_mu` for grip + and :attr:`~isaaclab_contrib.deformable.NewtonModelCfg.soft_contact_kd` for + chatter. +8. Enable self-contact only after body-particle contact is stable, then tune + ``particle_self_contact_radius`` for active self-contact thickness, + ``particle_self_contact_margin`` for missed contacts, and + ``particle_collision_detection_interval`` for detection frequency. +9. Increase ``num_envs`` and profile only after the single-environment scene is + stable. + + +Symptoms and First Parameters to Check +-------------------------------------- + +.. list-table:: + :header-rows: 1 + :widths: 35 65 + + * - Symptom + - First parameters to check + * - Rigid bodies visibly clip through the deformable. + - Increase ``soft_contact_ke``, VBD ``iterations``, ``num_substeps``, or the deformable material ``particle_radius``. + * - The robot cannot lift the deformable. + - Use ``coupling_mode="two_way"``, then increase ``soft_contact_mu`` and rigid-side ``shape_material_mu``. Also check gripper actuator stiffness and effort limits. + * - The deformable barely deforms. + - Reduce material stiffness, ``soft_contact_ke``, or shape contact stiffness. + * - Contact chatters or bounces. + - Increase ``soft_contact_kd`` or material damping, and consider using more substeps. + * - Cloth passes through itself. + - Enable ``particle_enable_self_contact``, increase ``particle_self_contact_radius`` if the active self-contact thickness is too small, increase ``particle_self_contact_margin`` if contacts are missed, and use a positive ``particle_collision_detection_interval``. + * - Self-contact is too expensive. + - Increase ``particle_collision_detection_interval``, reduce mesh resolution, or disable self-contact until the rest of the scene is tuned. + +For implementation details of the VBD and coupled solver managers, see +:doc:`newton-manager-abstraction`. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/warp-env-migration.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/warp-env-migration.rst new file mode 100644 index 0000000000000000000000000000000000000000..468ced739b4a69b8a79025d60549095bcda2a9a0 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/warp-env-migration.rst @@ -0,0 +1,280 @@ +.. _warp-env-migration: + +Warp Environment Migration Guide +================================ + +This guide covers the key conventions and patterns used by the warp-first environment +infrastructure, useful for migrating existing torch environments or creating new ones +natively. For an overview of the warp env path itself (workflows, available envs, +performance, limitations, benchmarking), see :doc:`warp-environments`. + + +Design Rationale +~~~~~~~~~~~~~~~~ + +The warp environment path is built around `CUDA graph capture +`_. +A CUDA graph records a sequence of GPU operations (kernel launches, memory copies) during a +capture phase, then replays the entire sequence with a single launch. This eliminates per-kernel +CPU overhead — the parameter validation, kernel selection, and buffer setup that normally costs +20–200 μs per operation is performed once during graph instantiation and reused on every replay +(~10 μs total). All CPU-side code (Python logic, torch dispatching) executed during capture is +completely bypassed during replay. See the `Warp concurrency documentation +`_ for Warp's graph capture API +(``wp.ScopedCapture``). + +All design decisions in the warp infrastructure follow from this constraint: every operation in the +step loop must be a GPU kernel launch with stable memory pointers so that the captured graph can +be replayed without modification. + +Key consequences: + +- All buffers are **pre-allocated** — no dynamic allocation inside the step loop +- Data flows through **persistent ``wp.array`` pointers** — never replaced, only overwritten +- MDP terms are **pure ``@wp.kernel`` functions** — no Python branching on GPU data +- Reset uses **boolean masks** (``env_mask``) instead of index lists (``env_ids``) to avoid + variable-length indexing that changes graph topology + + +Project Structure +~~~~~~~~~~~~~~~~~ + +Warp-specific implementations that diverge from the torch-based managers and env classes live in the ``_experimental`` packages: + +- ``isaaclab_experimental`` — warp managers, base env classes, warp MDP terms +- ``isaaclab_tasks_experimental`` — warp task configs and task-specific MDP terms + +Any new warp implementation that differs from the torch-based managers or env classes belongs in these packages. +Warp task configs reference Newton physics directly (no ``PresetCfg``) since the warp path +is Newton-only. + + +Writing Warp MDP Terms +~~~~~~~~~~~~~~~~~~~~~~ + +Imports +^^^^^^^ + +Warp task configs import from the experimental packages: + +.. code-block:: python + + # Warp + from isaaclab_experimental.managers import ObservationTermCfg, RewardTermCfg, SceneEntityCfg + import isaaclab_experimental.envs.mdp as mdp + +The term config classes have the same interface — only the import path changes. + + +Common Pattern +^^^^^^^^^^^^^^ + +All warp MDP terms (observations, rewards, terminations, events, actions) follow the same +**kernel + launch** pattern. Torch terms use torch tensors and return results; warp terms +write into pre-allocated ``wp.array`` output buffers via ``@wp.kernel`` functions: + +.. code-block:: python + + # Torch — returns a tensor + def lin_vel_z_l2(env, asset_cfg) -> torch.Tensor: + return torch.square(asset.data.root_lin_vel_b[:, 2]) + + # Warp — writes into pre-allocated output + @wp.kernel + def _lin_vel_z_l2_kernel(vel: wp.array(...), out: wp.array(dtype=wp.float32)): + i = wp.tid() + out[i] = vel[i][2] * vel[i][2] + + def lin_vel_z_l2(env, out, asset_cfg) -> None: + wp.launch(_lin_vel_z_l2_kernel, dim=env.num_envs, inputs=[..., out]) + +The output buffer shapes differ by term type: + +- **Observations**: ``(num_envs, D)`` where D is the observation dimension +- **Rewards**: ``(num_envs,)`` +- **Terminations**: ``(num_envs,)`` with dtype ``bool`` +- **Events**: ``(num_envs,)`` mask — events don't produce output, they modify sim state + + +Observation Terms +^^^^^^^^^^^^^^^^^ + +Since warp terms write into pre-allocated buffers, the observation manager must know each +term's output dimension at initialization to allocate the correct ``(num_envs, D)`` output +array. This is resolved via a fallback chain (see +``ObservationManager._infer_term_dim_scalar`` in +``isaaclab_experimental/managers/observation_manager.py``): + +1. **Explicit ``out_dim`` in decorator** (preferred): + + .. code-block:: python + + @generic_io_descriptor_warp(out_dim=3, observation_type="RootState") + def base_lin_vel(env, out, asset_cfg) -> None: ... + + ``out_dim`` can be an integer, or a string that resolves at initialization: + + - ``"joint"`` — number of selected joints from ``asset_cfg`` + - ``"body:N"`` — N components per selected body from ``asset_cfg`` + - ``"command"`` — dimension from command manager + - ``"action"`` — dimension from action manager + +2. **``axes`` metadata**: Dimension equals the number of axes listed: + + .. code-block:: python + + @generic_io_descriptor_warp(axes=["X", "Y", "Z"], observation_type="RootState") + def projected_gravity(env, out, asset_cfg) -> None: ... + # → dimension = 3 + +3. **Legacy params**: ``term_dim``, ``out_dim``, or ``obs_dim`` keys in ``term_cfg.params``. + +4. **Asset config fallback**: Count of ``asset_cfg.joint_ids`` (or ``joint_ids_wp``) for + joint-level terms. + + +Event Terms +^^^^^^^^^^^ + +Events use ``env_mask`` (boolean ``wp.array``) instead of ``env_ids``, and each kernel +checks the mask to skip non-selected environments: + +.. code-block:: python + + def reset_joints_by_offset(env, env_mask, ...): + wp.launch(_kernel, dim=env.num_envs, inputs=[env_mask, ...]) + + @wp.kernel + def _kernel(env_mask: wp.array(dtype=wp.bool), ...): + i = wp.tid() + if not env_mask[i]: + return + # ... modify state for selected envs only + +- RNG uses per-env ``env.rng_state_wp`` (``wp.uint32``) instead of ``torch.rand`` +- **Startup/prestartup** events use the torch convention ``(env, env_ids, **params)`` +- **Reset/interval** events use the warp convention ``(env, env_mask, **params)`` + + +Action Terms +^^^^^^^^^^^^ + +Actions follow a **two-stage execution**: ``process_actions`` (called once per env step) scales +and clips raw actions, and ``apply_actions`` (called once per sim step) writes targets to the +asset. Both stages use warp kernels with pre-allocated ``_raw_actions`` and ``_processed_actions`` +buffers. + + +Capture Safety +^^^^^^^^^^^^^^ + +When writing terms that run inside the captured step loop, keep in mind: + +- **No ``wp.to_torch``** or torch arithmetic — stay in warp throughout +- **No lazy-evaluated properties** — use sim-bound (Tier 1) data directly; if a derived + quantity is needed, compute it inline in the kernel +- **No dynamic allocation** — all buffers must be pre-allocated in ``__init__`` + + +Parity Testing +~~~~~~~~~~~~~~ + +Two levels of parity testing are used to validate warp terms: + +**1. Implementation parity (torch vs warp)** — verifies that the warp kernel produces the +same result as the torch implementation. This is optional for terms that have no torch +counterpart (e.g. new terms written directly in warp). + +.. code-block:: python + + import isaaclab.envs.mdp.observations as torch_obs + import isaaclab_experimental.envs.mdp.observations as warp_obs + + # Torch baseline + expected = torch_obs.joint_pos(torch_env, asset_cfg=cfg) + + # Warp (uncaptured) + out = wp.zeros((num_envs, num_joints), dtype=wp.float32, device=device) + warp_obs.joint_pos(warp_env, out, asset_cfg=cfg) + actual = wp.to_torch(out) + + torch.testing.assert_close(actual, expected) + +**2. Capture parity (warp vs warp-captured)** — verifies that the term produces identical +results when replayed from a CUDA graph vs launched directly. A mismatch here indicates capture-unsafe +code (e.g. stale pointers, dynamic allocation, or lazy property access that doesn't replay). +This test should always be run, even for terms without a torch counterpart. + +.. code-block:: python + + # Warp uncaptured + out_uncaptured = wp.zeros((num_envs, num_joints), dtype=wp.float32, device=device) + warp_obs.joint_pos(warp_env, out_uncaptured, asset_cfg=cfg) + + # Warp captured (graph replay) + out_captured = wp.zeros((num_envs, num_joints), dtype=wp.float32, device=device) + with wp.ScopedCapture() as cap: + warp_obs.joint_pos(warp_env, out_captured, asset_cfg=cfg) + wp.capture_launch(cap.graph) + + torch.testing.assert_close(wp.to_torch(out_captured), wp.to_torch(out_uncaptured)) + +See ``source/isaaclab_experimental/test/envs/mdp/`` for complete parity test examples. + + +Available Warp MDP Terms +~~~~~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :header-rows: 1 + :widths: 20 80 + + * - Category + - Available Terms + * - Observations (11) + - | ``base_pos_z`` + | ``base_lin_vel`` + | ``base_ang_vel`` + | ``projected_gravity`` + | ``joint_pos`` + | ``joint_pos_rel`` + | ``joint_pos_limit_normalized`` + | ``joint_vel`` + | ``joint_vel_rel`` + | ``last_action`` + | ``generated_commands`` + * - Rewards (16) + - | ``is_alive`` + | ``is_terminated`` + | ``lin_vel_z_l2`` + | ``ang_vel_xy_l2`` + | ``flat_orientation_l2`` + | ``joint_torques_l2`` + | ``joint_vel_l1`` + | ``joint_vel_l2`` + | ``joint_acc_l2`` + | ``joint_deviation_l1`` + | ``joint_pos_limits`` + | ``action_rate_l2`` + | ``action_l2`` + | ``undesired_contacts`` + | ``track_lin_vel_xy_exp`` + | ``track_ang_vel_z_exp`` + * - Events (6) + - | ``reset_joints_by_offset`` + | ``reset_joints_by_scale`` + | ``reset_root_state_uniform`` + | ``push_by_setting_velocity`` + | ``apply_external_force_torque`` + | ``randomize_rigid_body_com`` + * - Terminations (4) + - | ``time_out`` + | ``root_height_below_minimum`` + | ``joint_pos_out_of_manual_limit`` + | ``illegal_contact`` + * - Actions (2) + - | ``JointPositionAction`` + | ``JointEffortAction`` + +Terms not listed here remain in torch only. When using an env that requires unlisted terms, +those terms must be implemented in warp first. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst new file mode 100644 index 0000000000000000000000000000000000000000..1c6e8b4cab2d4df18baa753b7636c7371095f9e5 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst @@ -0,0 +1,322 @@ +.. _warp-environments: + +Warp Experimental Environments +============================== + +.. note:: + + The warp environment infrastructure lives in ``isaaclab_experimental`` and + ``isaaclab_tasks_experimental``. It's an experimental feature. + +The experimental extensions introduce **warp-first** environment infrastructure with CUDA graph capture +support. All environment-side computation (observations, rewards, resets, actions) runs as pure Warp +kernels, eliminating Python overhead and enabling CUDA graph capture for maximum throughput. + + +Workflows +~~~~~~~~~ + +Two environment workflows are supported: + +**Direct workflow** — ``DirectRLEnvWarp`` base class. You implement the step loop, observations, +rewards, and resets directly in your env class using Warp kernels. + +**Manager-based workflow** — ``ManagerBasedRLEnvWarp`` base class. You define MDP terms as +standalone Warp-kernel functions and compose them via configuration. + + +Available Environments +~~~~~~~~~~~~~~~~~~~~~~ + +Direct Warp Environments +^^^^^^^^^^^^^^^^^^^^^^^^ + +- ``Isaac-Cartpole-Direct-Warp-v0`` — Cartpole balance +- ``Isaac-Ant-Direct-Warp-v0`` — Ant locomotion +- ``Isaac-Humanoid-Direct-Warp-v0`` — Humanoid locomotion +- ``Isaac-Repose-Cube-Allegro-Direct-Warp-v0`` — Allegro hand cube repose + + +Manager-Based Warp Environments +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**Classic** + +- ``Isaac-Cartpole-Warp-v0`` +- ``Isaac-Ant-Warp-v0`` +- ``Isaac-Humanoid-Warp-v0`` + +**Locomotion (Flat)** + +- ``Isaac-Velocity-Flat-Anymal-B-Warp-v0`` +- ``Isaac-Velocity-Flat-Anymal-C-Warp-v0`` +- ``Isaac-Velocity-Flat-Anymal-D-Warp-v0`` +- ``Isaac-Velocity-Flat-Cassie-Warp-v0`` +- ``Isaac-Velocity-Flat-G1-Warp-v0`` +- ``Isaac-Velocity-Flat-G1-Warp-v1`` +- ``Isaac-Velocity-Flat-H1-Warp-v0`` +- ``Isaac-Velocity-Flat-Unitree-A1-Warp-v0`` +- ``Isaac-Velocity-Flat-Unitree-Go1-Warp-v0`` +- ``Isaac-Velocity-Flat-Unitree-Go2-Warp-v0`` + +**Manipulation** + +- ``Isaac-Reach-Franka-Warp-v0`` +- ``Isaac-Reach-UR10-Warp-v0`` + + +Quick Start +~~~~~~~~~~~ + +.. code-block:: bash + + # Direct workflow + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Cartpole-Direct-Warp-v0 --num_envs 4096 + + # Manager-based workflow + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Velocity-Flat-Anymal-C-Warp-v0 --num_envs 4096 + +All RL libraries with warp-compatible wrappers are supported: RSL-RL, RL Games, SKRL, and +Stable-Baselines3. + + +Performance Comparison +~~~~~~~~~~~~~~~~~~~~~~ + +Step time comparison between the stable (torch/manager) and warp (CUDA graph captured) variants, +both running on the Newton physics backend. Measured over 300 iterations with 4096 environments. + +.. note:: + + The warp migration is an ongoing effort. Several components (e.g. scene write, actuator models) + have not yet been migrated to Warp kernels and still run through torch. Further performance + improvements are expected as these components are migrated. + +.. list-table:: + :header-rows: 1 + :widths: 30 12 15 15 12 + + * - Env + - Type + - Stable Step (us) + - Warp Step (us) + - Change + * - Cartpole-Direct + - Direct + - 5,274 + - 4,331 + - -17.88% + * - Ant-Direct + - Direct + - 6,368 + - 3,128 + - -50.88% + * - Humanoid-Direct + - Direct + - 13,937 + - 10,783 + - -22.63% + * - Allegro-Direct + - Direct + - 82,950 + - 74,570 + - -10.10% + * - Cartpole + - Manager + - 7,971 + - 3,642 + - -54.31% + * - Ant + - Manager + - 9,781 + - 4,672 + - -52.23% + * - Humanoid + - Manager + - 17,653 + - 12,505 + - -29.16% + * - Reach-Franka + - Manager + - 11,458 + - 7,813 + - -31.83% + * - Anymal-B + - Manager + - 29,188 + - 21,781 + - -25.38% + * - Anymal-C + - Manager + - 30,938 + - 22,228 + - -28.15% + * - Anymal-D + - Manager + - 32,294 + - 23,977 + - -25.75% + * - Cassie + - Manager + - 17,320 + - 10,706 + - -38.19% + * - G1 + - Manager + - 34,487 + - 27,300 + - -20.84% + * - H1 + - Manager + - 22,202 + - 15,864 + - -28.55% + * - A1 + - Manager + - 15,257 + - 9,907 + - -35.07% + * - Go1 + - Manager + - 16,515 + - 11,869 + - -28.13% + * - Go2 + - Manager + - 15,221 + - 9,966 + - -34.52% + + +Which Workflows Benefit Most +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The savings come from eliminating Python / torch overhead in the env's step loop, so envs +gain in proportion to how much of their step time was previously dominated by per-kernel CPU +overhead. Reading the table above: + +- **Manager-based classic RL** (Cartpole, Ant) — biggest gains (-52% to -54%). Many small + reward / observation terms with low compute per term, so per-launch CPU overhead dominated + the stable baseline. +- **Manager-based locomotion** (Anymal, G1, H1, Cassie, Unitree) — consistent -25% to -38% + range. The MDP has more terms but the underlying physics step is heavier, so the relative + Python savings shrink. +- **Direct workflow** — gains scale with how much the env's step body was Python (Ant -51%, + Cartpole -18%, Allegro hand -10%). Direct envs that already wrote most of their work as + GPU kernels see modest gains; ones with substantial Python state machinery see large ones. +- **Compute-heavy / scene-write-heavy envs** (Allegro hand, large humanoids) — see smaller + relative gains because the warp-side savings are amortised over a heavier step. Components + that still go through torch (scene write, actuator models) currently bound the floor; this + is expected to improve as remaining components migrate to warp. + +If your env's step time is dominated by physics or scene I/O, expect modest gains. If it has +many small MDP terms or a lot of Python in the step loop, expect large ones. Use the +benchmarking workflow below to measure on your task before committing to a migration. + + +Limitations +~~~~~~~~~~~ + +The warp env path is experimental and has the following known constraints. These are +specific to warp envs; for Newton physics limitations see :doc:`supported-features`. + +**Physics backend** + +- **Newton only.** PhysX is not supported under the warp env path. Asset and sensor + ``class_type`` fields resolve to ``isaaclab_physx.*`` classes that depend on + ``omni.physics.tensors`` (a Kit module the warp runtime does not initialise), and several + warp APIs (env-mask reset, CUDA graph capture) require the Newton articulation. Configure + the cfg with a Newton physics block (or ``physics=newton_mjwarp``). + +**MDP coverage** + +- Only the terms listed under :ref:`Available Warp MDP Terms ` are + implemented. Stable envs that depend on un-migrated terms cannot be run on the warp path + until those terms are ported. +- Some scene-side operations (asset write, actuator models, certain sensor types) still go + through torch. They participate in the step but are not yet captured into the graph; they + set the lower bound on observed step time. +- Sensors that depend on the Kit RTX renderer (camera-based observations) cannot be combined + with the warp env path — they need Kit, which the warp runtime does not initialise. + +**API differences vs stable** + +- Reset events use a boolean ``env_mask`` (``wp.array(dtype=wp.bool)``) instead of an + ``env_ids`` list. This is required for capture safety: variable-length indexing changes + graph topology and breaks replay. +- All buffers must be pre-allocated in ``__init__``. There is no dynamic allocation inside + the captured step loop, so observation / reward / termination output dimensions must be + known at env init. +- Term functions write into a pre-allocated ``out`` buffer rather than returning a tensor. + See :doc:`warp-env-migration` for the kernel + launch pattern. +- Code inside the captured step loop must follow capture-safety rules (no + ``wp.to_torch``, no torch arithmetic, no lazy-evaluated properties, no Python branching + on GPU data). See the *Capture Safety* section in :doc:`warp-env-migration` for the + full set of rules. + + +Benchmarking Your Environment +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The performance table above was produced with ``scripts/benchmarks/benchmark_rsl_rl.py``, +which runs a fixed iteration count and reports step-time statistics. Use the same script +to estimate the gain for your own task before committing to a migration. + +**Single-task A/B** + +.. code-block:: bash + + # Stable variant + ./isaaclab.sh -p scripts/benchmarks/benchmark_rsl_rl.py \ + --task -v0 \ + --num_envs 4096 \ + --max_iterations 500 \ + --benchmark_backend summary \ + --output_path benchmarks/stable + + # Warp variant — same task with -Warp- suffix + ./isaaclab.sh -p scripts/benchmarks/benchmark_rsl_rl.py \ + --task -Warp-v0 \ + --num_envs 4096 \ + --max_iterations 500 \ + --benchmark_backend summary \ + --output_path benchmarks/warp + +The ``summary`` backend prints step time (mean / p50 / p99) and total throughput. Compare +"step time" between the two runs to estimate the gain per env step. + +**Sweep across all available tasks** + +``scripts/benchmarks/run_training_benchmarks.sh`` runs the full set of stable tasks listed +in the script (cartpole, ant, humanoid, locomotion, manipulation). Pair it with a +warp-tasks variant (substitute the ``-Warp-`` suffixed task ids) and diff the two outputs. + +**What to look at in the output** + +- *Step time (mean / p99)*: the headline number — what each env step costs. +- *Iteration time*: includes policy update; useful for end-to-end training throughput. +- *Capture overhead*: for warp runs, the first few iterations include CUDA graph capture + cost; exclude those when comparing steady-state numbers. + +**Estimating before you migrate** + +If you can't run the warp variant yet (e.g. the task isn't ported), measure the stable +step time and look at where it's spent: + +- ``num_envs * step_time`` dominated by physics → expect modest warp gains. +- ``step_time`` dominated by ``manager.compute_*`` calls → expect large gains, since those + are exactly what the warp managers replace with captured kernel launches. + +Use ``--num_frames`` on ``benchmark_non_rl.py`` for a no-policy step-time microbenchmark +when you want to isolate env overhead from policy compute. + + +Migrating Existing Environments +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +For step-by-step instructions on porting an existing stable env (or writing a new warp +env from scratch) — covering project layout, the kernel + launch pattern shared by +observations / rewards / events / terminations / actions, capture-safety rules, and +parity testing — see :doc:`warp-env-migration`. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/ovphysx/index.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/ovphysx/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..3f2fbdbb8f401538d6d3e2c1588df2f924984cba --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/ovphysx/index.rst @@ -0,0 +1,125 @@ +OvPhysX Backend +=============== + +.. warning:: + + OvPhysX is **highly experimental** and is not recommended for general use yet. + The public surface is changing rapidly while the backend is under active + development. Expect feature coverage and test commands to change between + Isaac Lab 3.0 beta releases. + +.. warning:: + + Do not combine OvPhysX with the Kit visualizer. Commands such as + ``presets=ovphysx --visualizer kit`` are unsupported because OvPhysX + loads USD-dependent PhysX plugins from its own package, while Kit already + owns a separate USD/plugin stack in the same process. Use + ``--visualizer newton``, ``--visualizer rerun``, ``--visualizer viser``, + or omit ``--visualizer`` for headless execution. + +OvPhysX is a kit-less variant of the PhysX backend. It drives PhysX directly +(without the Omniverse Kit runtime) and reads scene-level solver parameters +from the USD ``PhysicsScene`` prim rather than from a Python config. The Python +config :class:`~isaaclab_ovphysx.physics.OvPhysxCfg` only exposes the handful of +GPU buffer sizes that are not represented on the USD schema. + +OvPhysX is selected through :class:`~isaaclab_ovphysx.physics.OvPhysxCfg`: + +.. code-block:: python + + from isaaclab.sim import SimulationCfg + from isaaclab_ovphysx.physics import OvPhysxCfg + + sim_cfg = SimulationCfg(physics=OvPhysxCfg()) + +Why use OvPhysX? +---------------- + +* **Kit-less execution.** OvPhysX avoids Omniverse Kit, which makes it a useful + experimental path for headless deployments and for backends that don't need + the Kit runtime stack. +* **USD-as-source-of-truth.** Solver parameters are taken from the + ``PhysicsScene`` USD prim, so authoring tools that already manage USD scenes + do not need a parallel Python config. + +What works today +---------------- + +The asset and sensor surface tracks PhysX, but only a subset is implemented and +validated at the time of writing. The following pieces are available on +``release/3.0.0-beta2``: + +* RigidObject — merged via + `PR #5426 `_. +* Articulation — merged via + `PR #5459 `_. +* RigidObjectCollection — merged via + `PR #5570 `_. +* Contact Sensor — merged via + `PR #5422 `_. +* SceneDataProvider — merged via + `PR #5589 `_. +* FrameView — merged via + `PR #5678 `_. + +Additional OvPhysX work remains in flight. IMU, Frame Transformer, Joint Wrench, +PVA, Ray Caster, and rendering support are not documented as supported here +until their implementations land on ``release/3.0.0-beta2`` and pass the backend smoke +tests. + +Installation +------------ + +The Isaac Lab source install includes the ``isaaclab_ovphysx`` package, but it +does not install the heavier ``ovphysx`` runtime wheel by default. After a +standard source install, install the optional OvPhysX runtime dependency from +the repository root: + +.. code-block:: bash + + ./isaaclab.sh -i 'ov[ovphysx]' + +You can also install all OV runtime wheels with: + +.. code-block:: bash + + ./isaaclab.sh -i 'ov[all]' + +The ``ov[ovphysx]`` selector installs ``source/isaaclab_ovphysx`` with its +``[ovphysx]`` extra. If the wheel is missing, OvPhysX-specific tests skip with +``ovphysx wheel not installed`` and user code raises an install hint when it +first imports the runtime-backed modules. + +Testing the Installation +------------------------ + +First check that the Python package and runtime wheel import correctly: + +.. code-block:: bash + + ./isaaclab.sh -p -c "import ovphysx.types; from isaaclab_ovphysx.physics import OvPhysxCfg; print('OvPhysX runtime OK')" + +Then run a small backend smoke test: + +.. code-block:: bash + + ./isaaclab.sh -p -m pytest source/isaaclab_ovphysx/test/assets/test_rigid_object.py::test_initialization -k cpu + +To try a task that declares an OvPhysX physics preset, use the same preset CLI +syntax as the other backends: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/zero_agent.py --task Isaac-Cartpole-Direct-v0 --num_envs 128 presets=ovphysx + +This command starts a headless zero-action rollout; stop it with ``Ctrl+C`` +after the environment has started and stepped successfully. + +Status and follow-up +-------------------- + +OvPhysX is still experimental, so the feature list above is intentionally +conservative. Broader feature coverage and documentation parity are tracked in +`issue #5634 `_. + +For architectural context, see :doc:`../../multi_backend_architecture`. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/physx/configuration.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/physx/configuration.rst new file mode 100644 index 0000000000000000000000000000000000000000..9dea7d4bc77c745d0984f4be8da2f1c384a03aac --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/physx/configuration.rst @@ -0,0 +1,112 @@ +PhysX Configuration +=================== + +PhysX scene-level settings live on :class:`~isaaclab_physx.physics.PhysxCfg`, +which replaces the Isaac Lab 2.x ``PhysxCfg`` imported from ``isaaclab.sim``. +In Isaac Lab 3.0, import ``PhysxCfg`` from ``isaaclab_physx.physics`` instead. +Per-actor settings (such as per-articulation iteration counts, contact +filtering, or material properties) continue to be authored on the USD schema; +see :doc:`../../schema_cfgs` for the schema-level configuration helpers. + +The example below shows a representative ``PhysxCfg`` for a contact-rich +manipulation task: + +.. code-block:: python + + from isaaclab.sim import SimulationCfg + from isaaclab_physx.physics import PhysxCfg + + physx_cfg = PhysxCfg( + solver_type=1, # TGS + min_position_iteration_count=8, + max_position_iteration_count=64, + min_velocity_iteration_count=1, + max_velocity_iteration_count=4, + enable_ccd=False, + enable_stabilization=False, + bounce_threshold_velocity=0.2, + friction_offset_threshold=0.04, + friction_correlation_distance=0.025, + ) + + sim_cfg = SimulationCfg(dt=1 / 120, physics=physx_cfg) + + +Common Parameters +----------------- + +The following list highlights the parameters that most often need tuning. The +full reference lives on :class:`~isaaclab_physx.physics.PhysxCfg`. + +Solver Selection +^^^^^^^^^^^^^^^^ + +* ``solver_type``: ``1`` for **TGS** (Temporal Gauss-Seidel, default) or ``0`` + for **PGS** (Projective Gauss-Seidel). TGS is the recommended default for + articulated robots; PGS can be more forgiving on stiff legacy assets. +* ``solve_articulation_contact_last``: alters the articulation solver order so + that dynamic contact is resolved at the end of the solve. Useful for stiff + gripping scenarios. For Isaac Lab 3.0, the supported Isaac Sim versions + include this feature; it depends on PhysX schema support introduced in + Isaac Sim 5.1. + + +Solver Iterations +^^^^^^^^^^^^^^^^^ + +* ``min_position_iteration_count`` / ``max_position_iteration_count``: clamp + range applied to every actor's individual position-iteration count. +* ``min_velocity_iteration_count`` / ``max_velocity_iteration_count``: clamp + range for velocity iterations. +* ``enable_external_forces_every_iteration``: applies external forces on every + TGS position iteration. Reduces noisy velocity updates at additional + compute cost; ignored with the PGS solver. + + +Contact and Stability +^^^^^^^^^^^^^^^^^^^^^ + +* ``enable_ccd``: continuous-collision detection for fast-moving bodies. +* ``enable_stabilization``: extra solver stabilization pass; recommended only + for low-rate simulations, where the simulation timestep ``dt`` is larger + than about ``1 / 30`` seconds (below about 30 Hz). This pass can make + contact-sensor force magnitudes inaccurate, so keep it disabled if you rely + on the contact sensor for force observations. +* ``bounce_threshold_velocity``: relative velocity threshold [m/s] above which + contacts bounce. +* ``friction_offset_threshold``: contact point distance [m] at which friction + forces are applied. +* ``friction_correlation_distance``: distance [m] used to merge nearby + contacts into a single friction anchor. + + +GPU Buffer Sizing +^^^^^^^^^^^^^^^^^ + +PhysX on the GPU does **not** dynamically grow scene buffers, so undersized +buffers crash or silently drop contacts. The ``gpu_*`` fields on +:class:`~isaaclab_physx.physics.PhysxCfg` control these capacities. The +defaults are tuned for a few-hundred-environment locomotion task; large +multi-thousand-environment manipulation tasks usually need to raise: + +* ``gpu_max_rigid_contact_count`` +* ``gpu_max_rigid_patch_count`` +* ``gpu_found_lost_pairs_capacity`` +* ``gpu_found_lost_aggregate_pairs_capacity`` +* ``gpu_total_aggregate_pairs_capacity`` +* ``gpu_collision_stack_size`` +* ``gpu_heap_capacity`` + +PhysX prints ``[PhysX]`` warnings when a buffer is exhausted; treat those as +hard failures and re-tune. + + +See Also +-------- + +* :class:`~isaaclab_physx.physics.PhysxCfg` — full parameter reference. +* :doc:`../../schema_cfgs` — schema-level configuration helpers. +* :doc:`../../multi_backend_architecture` — how PhysX plugs into the backend + factory pattern. +* PhysX 5 SDK documentation: + https://nvidia-omniverse.github.io/PhysX/physx/5.4.1/_api_build/classPxSceneDesc.html diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/physx/index.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/physx/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..3daedd4116b1bf2030b038f018a2845163c35242 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/physx/index.rst @@ -0,0 +1,37 @@ +PhysX Backend +============= + +`NVIDIA PhysX `_ +is the historical default physics backend in Isaac Lab. It runs through +`NVIDIA Isaac Sim `_'s Omniverse Kit +runtime and supports GPU-accelerated rigid-body, articulation, soft-body, and +particle simulation. PhysX is the reference backend for behaviour parity in Isaac +Lab — assets, sensors, and tasks have all been validated against it first, and the +other backends are measured against PhysX behaviour. + +PhysX is selected via :class:`~isaaclab_physx.physics.PhysxCfg`: + +.. code-block:: python + + from isaaclab.sim import SimulationCfg + from isaaclab_physx.physics import PhysxCfg + + sim_cfg = SimulationCfg(physics=PhysxCfg()) + +The PhysX backend uses the Temporal Gauss-Seidel (TGS) solver by default and also +exposes a Projective Gauss-Seidel (PGS) variant. Scene-level solver tuning, GPU +buffer sizing, and contact-handling parameters live on +:class:`~isaaclab_physx.physics.PhysxCfg`; per-actor settings remain on the USD +schema. See :doc:`configuration` for the most common knobs. + +For an overview of how the multi-backend architecture works, see +:doc:`../../multi_backend_architecture`. + + +.. toctree:: + :maxdepth: 2 + :titlesonly: + + installation + configuration + supported-features diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/physx/installation.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/physx/installation.rst new file mode 100644 index 0000000000000000000000000000000000000000..7fc127161fb1b258e547cde9d564e9e99e652f54 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/physx/installation.rst @@ -0,0 +1,31 @@ +Installation +============ + +PhysX is installed as part of the standard Isaac Lab installation. It runs through +`NVIDIA Isaac Sim `_'s Omniverse Kit +runtime, so Isaac Sim is a required dependency for the PhysX backend. + +Follow the :ref:`isaaclab-installation-root` guide for the full installation +procedure. The short version: + +1. Install Isaac Sim 6.0 (binary install or pip install — see the Isaac Sim + documentation for system requirements). +2. Clone Isaac Lab and run ``./isaaclab.sh -i`` to install the Isaac Lab + extensions on top of Isaac Sim. + +No extra packages are required for the PhysX backend specifically — the PhysX +runtime ships with Isaac Sim. + + +Testing the Installation +------------------------ + +To verify the PhysX backend is working, run any classic Isaac Lab task with the +default preset: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/zero_agent.py --task Isaac-Cartpole-v0 --num_envs 128 + +The ``default`` preset on most tasks resolves to PhysX. You can also pass +``physics=physx`` explicitly on tasks that declare multi-backend physics presets. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/physx/supported-features.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/physx/supported-features.rst new file mode 100644 index 0000000000000000000000000000000000000000..760fb279fea2e5ce093387c0c0fce30b0b8254fd --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/physx/supported-features.rst @@ -0,0 +1,70 @@ +Supported Features +================== + +PhysX is the broadest backend in Isaac Lab. It is the reference for behaviour +parity and supports every public asset, sensor, and renderer surface in the +framework. Tasks built before Isaac Lab 3.0 ran on PhysX, and the bulk of the +shipped tasks still default to the PhysX preset. + +The summary below is intentionally coarse; consult each component's API +documentation for fine-grained capability details. + +Core Simulation +--------------- + +* Articulation API (multi-link articulations, fixed-base and floating-base + articulations, single-body articulations modeled as rigid bodies) +* Rigid Object and Rigid Object Collection APIs +* Soft-body and particle simulation (legacy — not exposed through the + Isaac Lab asset surface but available through PhysX schemas) +* CPU and GPU pipelines; GPU is the default for the vectorized RL workloads + + +Sensors +------- + +PhysX implements the following sensors directly under +``isaaclab_physx/sensors/``: + +* Contact Sensor +* IMU +* Frame Transformer +* Joint Wrench Sensor +* PVA + +The following sensors are backend-agnostic (implemented in ``isaaclab`` core) +and work transparently with PhysX: + +* Ray Caster +* Camera — see :doc:`../../sensors/camera` + + +Rendering +--------- + +* RTX renderer (real-time rasterized; path tracing available through the + underlying Omniverse RTX pipeline) +* Tiled rendering for vectorized RGB / depth / segmentation + + +Tasks and Workflows +------------------- + +* Direct and Manager-based workflows +* All ``isaaclab_tasks`` environments default to the PhysX preset unless the + task explicitly opts in to a different backend +* Imitation learning and motion-generation pipelines (Mimic, motion generators) + + +Known Caveats +------------- + +* PhysX requires Isaac Sim and Omniverse Kit to be installed. +* GPU buffer sizes are static and must be tuned per task — see + :doc:`configuration`. +* ``enable_stabilization`` can make contact-force magnitudes reported through + the contact sensor inaccurate; disable it if you rely on the contact sensor + for force observations. +* The PhysX TGS solver behaviour can differ from Newton's MJWarp solver on + stiff contact stacks; if you are porting a task to Newton, expect to retune + contact-handling parameters. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/solver-comparison.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/solver-comparison.rst new file mode 100644 index 0000000000000000000000000000000000000000..d272d0f2f673dbda53a9bf49e82fa51b3ea642ef --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/physical-backends/solver-comparison.rst @@ -0,0 +1,279 @@ +Solver Comparison +================= + +This page summarizes the user-visible behavioural differences between the +solvers shipped with the Isaac Lab physical backends. It's intended as a +porting reference: most tasks reuse the same USD asset across backends, but +contact, friction, and stabilization behave differently enough that retuning +is usually required when moving from one solver to another. + +The solvers covered are: + +* **PhysX TGS** — default solver for the :doc:`PhysX backend ` + (Temporal Gauss-Seidel). PhysX also exposes a Projective Gauss-Seidel + (PGS) variant via :attr:`~isaaclab_physx.physics.PhysxCfg.solver_type`, + which behaves similarly for the purposes of this comparison. +* **Newton MuJoCo-Warp (MJWarp)** — primary :doc:`Newton solver `, + configured by :class:`~isaaclab_newton.physics.MJWarpSolverCfg`. +* **Newton Kamino** — beta P-ADMM :doc:`Newton solver `, + configured by :class:`~isaaclab_newton.physics.KaminoSolverCfg`. + +Newton additionally ships ``FeatherstoneSolverCfg`` and ``XPBDSolverCfg``; +neither is wired into an Isaac Lab task at the time of writing and they +are omitted from this comparison. + + +Friction Model +-------------- + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Solver + - Friction handling + * - PhysX TGS + - Coulomb friction with **patch-based** anchors. Tangential forces are + merged across nearby contacts via + :attr:`~isaaclab_physx.physics.PhysxCfg.friction_correlation_distance` + and applied above + :attr:`~isaaclab_physx.physics.PhysxCfg.friction_offset_threshold`. + The friction cone is always pyramidal. + * - MJWarp + - MuJoCo's friction model. The friction cone shape is selectable via + :attr:`~isaaclab_newton.physics.MJWarpSolverCfg.cone` + (``"pyramidal"`` or ``"elliptic"``). The tangential-to-normal + impedance ratio is exposed as + :attr:`~isaaclab_newton.physics.MJWarpSolverCfg.impratio`. + * - Kamino + - Per-contact friction resolved inside the P-ADMM solve. Contact + warm-starting is selectable via + :attr:`~isaaclab_newton.physics.KaminoSolverCfg.padmm_contact_warmstart_method`; + the validated presets use ``"geom_pair_net_force"``. + +**Porting implication.** Tasks tuned for PhysX's patch friction can feel +"grippier" than MJWarp's per-contact friction at the same friction +coefficient. When moving a manipulation task from PhysX to MJWarp, expect to +raise friction coefficients and consider switching ``cone`` to ``"elliptic"`` +for stiffer contact stacks. + + +Contact Detection and Resolution +-------------------------------- + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Solver + - Collision pipeline + * - PhysX TGS + - PhysX's built-in broadphase + narrowphase, with optional continuous + collision detection via + :attr:`~isaaclab_physx.physics.PhysxCfg.enable_ccd`. Pre-sized GPU + buffers (``gpu_max_rigid_contact_count`` etc.) cap the number of + contacts per step; oversubscription is a hard error. + * - MJWarp + - Two modes selected by + :attr:`~isaaclab_newton.physics.MJWarpSolverCfg.use_mujoco_contacts`: + MuJoCo's internal contact pipeline (default) or Newton's + :class:`~isaaclab_newton.physics.NewtonCollisionPipelineCfg`. The two + are mutually exclusive. GJK/EPA iteration count is exposed via + :attr:`~isaaclab_newton.physics.MJWarpSolverCfg.ccd_iterations`. + * - Kamino + - Optionally uses Kamino's internal collision detector (``"primitive"`` + or ``"unified"``) via + :attr:`~isaaclab_newton.physics.KaminoSolverCfg.use_collision_detector`, + otherwise falls back to Newton's :class:`CollisionPipeline`. + Contact penetration margin is set by + :attr:`~isaaclab_newton.physics.KaminoSolverCfg.constraints_delta`. + +**Porting implication.** A task that runs with ``--enable_ccd`` on PhysX +won't get the same protection on MJWarp/Kamino at large ``dt`` — Newton's +CCD is convex GJK/EPA, not the swept-shape CCD PhysX uses. The mitigation +on Newton is shorter ``dt`` or higher +:attr:`~isaaclab_newton.physics.NewtonCfg.num_substeps`. + + +Restitution and Bounce +---------------------- + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Solver + - Restitution + * - PhysX TGS + - Restitution coefficient is per-material on the USD shape. A global + velocity threshold + :attr:`~isaaclab_physx.physics.PhysxCfg.bounce_threshold_velocity` + suppresses restitution below ~0.5 m/s by default. + * - MJWarp + - Restitution follows the MJCF model translated from USD. There is no + bounce-threshold gate — small-velocity contacts can still bounce + unless you reduce the per-material restitution. + * - Kamino + - Restitution is contained in the contact constraint set; behaviour is + similar to MJWarp. + +**Porting implication.** Tasks that rely on PhysX's bounce-threshold to +suppress jitter (e.g. footstep contact on flat ground) may show contact +chatter on Newton until restitution coefficients are reduced. + + +Constraint Stabilization +------------------------ + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Solver + - Stabilization + * - PhysX TGS + - Implicit, via the TGS solver. An optional extra pass is enabled by + :attr:`~isaaclab_physx.physics.PhysxCfg.enable_stabilization` (note: + corrupts contact-sensor force magnitudes). + * - MJWarp + - Implicit, set by the MuJoCo solver's ``solref``/``solimp`` per + constraint. No top-level toggle. + * - Kamino + - Explicit Baumgarte stabilization with separate gains for joint + bilaterals (:attr:`~isaaclab_newton.physics.KaminoSolverCfg.constraints_alpha`), + joint-limit unilaterals + (:attr:`~isaaclab_newton.physics.KaminoSolverCfg.constraints_beta`), + and contact unilaterals + (:attr:`~isaaclab_newton.physics.KaminoSolverCfg.constraints_gamma`). + + +Solver Convergence +------------------ + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Solver + - Iteration model + * - PhysX TGS + - Two iteration counts, per actor: position + (``min/max_position_iteration_count``) and velocity + (``min/max_velocity_iteration_count``). The solver takes the largest + actor's count clamped to the scene range. No global convergence + tolerance. + * - MJWarp + - :attr:`~isaaclab_newton.physics.MJWarpSolverCfg.iterations` outer + Newton/CG iterations and + :attr:`~isaaclab_newton.physics.MJWarpSolverCfg.ls_iterations` line + searches per outer iteration. Convergence gate: + :attr:`~isaaclab_newton.physics.MJWarpSolverCfg.tolerance` (default + ``1e-6``). + :attr:`~isaaclab_newton.physics.MJWarpSolverCfg.ls_parallel` switches + line search to parallel execution at a small accuracy cost. + * - Kamino + - P-ADMM with separate + :attr:`~isaaclab_newton.physics.KaminoSolverCfg.padmm_primal_tolerance`, + :attr:`~isaaclab_newton.physics.KaminoSolverCfg.padmm_dual_tolerance`, + and + :attr:`~isaaclab_newton.physics.KaminoSolverCfg.padmm_compl_tolerance` + gates, capped at + :attr:`~isaaclab_newton.physics.KaminoSolverCfg.padmm_max_iterations`. + Acceleration and warm-starting are tunable. + + +Articulation Coordinates +------------------------ + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Solver + - Coordinate representation + * - PhysX TGS + - **Reduced-coordinate** articulations (joint-space, Featherstone-like). + Joint state is the canonical truth; body transforms are derived via + forward kinematics. + * - MJWarp + - Reduced-coordinate, computed by the MuJoCo solver. + * - Kamino + - **Maximal-coordinate**: each body has its own free-body state, + constraints are enforced via Baumgarte stabilization. Resets go + through a dedicated FK pass (:attr:`~isaaclab_newton.physics.KaminoSolverCfg.use_fk_solver`) + so maximal body poses match the reduced joint state after a state + write. + +**Porting implication.** Kamino is more sensitive to inconsistent reset +state — joint positions and body poses must agree, which Isaac Lab's asset +write paths handle but custom reset code can break. + + +Substepping and Timestep +------------------------ + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Solver + - Substep model + * - PhysX TGS + - PhysX runs at the simulation ``dt``. No external substep counter; + internal substepping is per-actor. + * - MJWarp + - Top-level :attr:`~isaaclab_newton.physics.NewtonCfg.num_substeps` + controls how many solver substeps run per Isaac Lab step. Effective + solver ``dt`` is ``SimulationCfg.dt / num_substeps``. + * - Kamino + - Same :attr:`~isaaclab_newton.physics.NewtonCfg.num_substeps` knob. + Validated Kamino task presets typically use 1–2 substeps; expect to + raise this for contact-heavy tasks. + + +GPU Buffers and Throughput +-------------------------- + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Solver + - Memory model + * - PhysX TGS + - Static GPU buffers sized at construction. Undersized buffers cause + crashes or dropped contacts at scale. See the + :doc:`PhysX configuration page ` for the + ``gpu_*`` knobs. + * - MJWarp + - Pre-allocated per-environment limits: + :attr:`~isaaclab_newton.physics.MJWarpSolverCfg.njmax` + (constraint rows) and + :attr:`~isaaclab_newton.physics.MJWarpSolverCfg.nconmax` (contact + points). The remainder of state lives in dynamically-sized Warp + arrays. + * - Kamino + - Inherits MJWarp's pre-allocation pattern via Newton, plus its own + contact-pair allocator + (:attr:`~isaaclab_newton.physics.KaminoSolverCfg.collision_detector_max_contacts_per_pair`) + when using the internal collision detector. + + +Porting Checklist +----------------- + +When moving a task between solvers: + +1. **Re-validate contact behavior.** Run the task at the smallest + ``num_envs`` with a visualizer; watch for new penetration or jitter + before scaling up. +2. **Retune friction.** PhysX patch friction and MJWarp per-contact friction + are not interchangeable at the same coefficient. +3. **Retune restitution.** MJWarp/Kamino have no bounce-threshold gate; + reduce per-material restitution to suppress jitter. +4. **Choose substeps.** PhysX → Newton typically needs at least 1–2 + substeps for contact-heavy tasks; manipulation tasks may need more. +5. **Watch for CCD differences.** Tasks that relied on PhysX swept CCD + should either reduce ``dt`` or raise ``num_substeps`` on Newton. +6. **For Kamino specifically**, also validate reset behaviour and consider + Baumgarte gains if you see drift on joint or contact constraints. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/renderers.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/renderers.rst new file mode 100644 index 0000000000000000000000000000000000000000..d2ff6a4ca9225b63d7ef559ea24c532113c594ee --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/renderers.rst @@ -0,0 +1,154 @@ +.. _overview_renderers: + +Renderers +========= + +Isaac Lab uses a pluggable renderer architecture to support different rendering backends for camera sensors. +The :class:`~isaaclab.renderers.BaseRenderer` abstract base class defines the interface that all renderer +implementations must follow. + +Isaac Lab supports three rendering backends: + +- **Isaac RTX renderer** (``IsaacRtxRendererCfg``) — NVIDIA's Omniverse RTX rendering pipeline + running inside Isaac Sim. Requires Isaac Sim. Best for photorealistic rendering, full camera + sensor support (RGB, depth, semantic segmentation, etc.), and production quality outputs. +- **OVRTX renderer** (``OVRTXRendererCfg``) — A standalone RTX path-tracing renderer provided by + the ``isaaclab_ov`` extension. Delivers RTX-quality rendering. +- **Newton Warp renderer** (``NewtonWarpRendererCfg``) — A lightweight GPU-accelerated renderer + built on NVIDIA Warp. Works with the Newton physics backend and does **not** require Isaac Sim + (kit-less mode). Ideal for training workflows where full RTX fidelity is not needed. + +Choosing a renderer backend +---------------------------- + ++---------------------+-------------------------------+---------------------------------+ +| Backend | Requires Isaac Sim? | Best For | ++=====================+===============================+=================================+ +| Isaac RTX | Yes | Full sensor fidelity, RTX | +| | | photorealism, PhysX backend | ++---------------------+-------------------------------+---------------------------------+ +| OVRTX | No (kit-less; needs | RTX-quality rendering without | +| | ``isaaclab_ov`` + ``ovrtx``) | requiring Isaac Sim | ++---------------------+-------------------------------+---------------------------------+ +| Newton Warp | No (kit-less) | Newton backend, fast training | ++---------------------+-------------------------------+---------------------------------+ + +.. note:: + + Visualization markers are not yet supported by Newton-based renderer backends, + including the Newton Warp renderer. Use an RTX-based renderer, such as the + Isaac RTX renderer or OVRTX renderer, when marker visualization is needed. + +.. note:: + **Temporal information for camera-based RL.** Unlike RTX modes with temporal + anti-aliasing (DLSS, DLAA, TAA), the Newton Warp renderer does not inject + prior-frame information into the current image. Camera-control tasks that depend + on velocity-like visual cues should add explicit temporal observations + (e.g. task-local frame stacking) rather than relying on renderer-specific artifacts. + +Architecture Overview +--------------------- + +The renderer system consists of: + +1. **BaseRenderer** — Abstract base class defining the rendering lifecycle and interface +2. **Renderer** — Factory that instantiates the appropriate backend based on renderer configuration class +3. **RendererCfg** — Base configuration; each backend extends it with backend-specific options +4. **Concrete implementations** — Backend-specific renderers in extension packages +5. **RenderContext** — A management class for instantiating and accessing renderer instances using a **RendererCfg**. + After instantiation, a config can then be used to acquire the instance of the renderer as needed. + +.. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab.renderers import BaseRenderer + from isaaclab_newton.renderers import NewtonWarpRendererCfg + + # Create a Newton Warp renderer (no Isaac Sim required) + sim_ctx = sim_utils.SimulationContext.instance() + # RenderContext.get_renderer will instantiate the renderer backend + # or return an existing renderer with a matching config + renderer: BaseRenderer = sim_ctx.render_context.get_renderer(NewtonWarpRendererCfg()) + assert isinstance(renderer, BaseRenderer) + +For the RTX renderer (requires Isaac Sim): + +.. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab.renderers import BaseRenderer + from isaaclab_physx.renderers import IsaacRtxRendererCfg + + # Create an RTX renderer + sim_ctx = sim_utils.SimulationContext.instance() + # RenderContext.get_renderer will instantiate the renderer backend + # or return an existing renderer with a matching config + renderer: BaseRenderer = sim_ctx.render_context.get_renderer(IsaacRtxRendererCfg()) + +For RTX renderer settings and presets (quality, balanced, performance), see +:doc:`/source/how-to/configure_rendering`. + +Core concepts +------------- + +- **Use the RenderContext**: Always instantiate renderers via the RenderContext with a renderer-specific config class + (e.g. ``sim_ctx.render_context.get_renderer(IsaacRtxRendererCfg())``). Do not import or instantiate concrete backend classes + (e.g. ``IsaacRtxRenderer``, ``OVRTXRenderer``) directly—their names and package locations are + implementation details and may change without notice. + +- **Lightweight config imports**: Importing a renderer configuration class does not pull in backend-specific + dependencies. The backend is lazily loaded when the renderer is instantiated, and instantiation may fail + if the backend is not installed. + + .. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab.renderers import BaseRenderer + # Lightweight: does not import OVRTX backend dependencies + from isaaclab_ov.renderers import OVRTXRendererCfg + + # Lazily loads ovrtx when instantiated; may fail if isaaclab_ov / ovrtx is not installed + sim_ctx = sim_utils.SimulationContext.instance() + renderer: BaseRenderer = sim_ctx.render_context.get_renderer(OVRTXRendererCfg()) + +Installing the OVRTX renderer +------------------------------ + +The OVRTX renderer is provided by the ``isaaclab_ov`` extension. The extension's +source package ships with the core install, but the renderer's ``ovrtx`` runtime +wheel (the `ovrtx `_ package, hosted on +``pypi.nvidia.com``) is **not** installed by default. You must request it +explicitly — OVRTX does **not** require Isaac Sim. + +Install via the Isaac Lab CLI using the ``ov[ovrtx]`` token: + +.. code-block:: bash + + # Install the ovrtx runtime wheel on top of an existing install + ./isaaclab.sh -i ov[ovrtx] + +.. note:: + + The bare ``ov`` token does **not** install any runtime wheel (the source + packages are already part of the core install). Use ``ov[ovrtx]`` (or ``ov[all]``) + to pull in the ``ovrtx`` dependency. + +Or install manually with pip (note the ``[ovrtx]`` extra and the extra index URL): + +.. code-block:: bash + + pip install --extra-index-url https://pypi.nvidia.com -e "source/isaaclab_ov[ovrtx]" + +- **Opaque render data**: The render data object returned by :meth:`~isaaclab.renderers.BaseRenderer.create_render_data` is passed to + subsequent renderer methods. It should be completely opaque to the caller: inspecting or modifying it + via get/set attributes is an anti-pattern and breaks the API contract. + +.. note:: + + The :class:`~isaaclab.renderers.BaseRenderer` class is under active development and may change without notice. + +See Also +-------- + +- :doc:`scene_data_providers` — how scene data flows from physics backends to renderers +- :doc:`/source/overview/core-concepts/visualization` — lightweight visualizer backends for interactive feedback diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/scene_data_providers.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/scene_data_providers.rst new file mode 100644 index 0000000000000000000000000000000000000000..ff6e38bc29b6efb62c2d7d9e1efb63d0097575ee --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/scene_data_providers.rst @@ -0,0 +1,128 @@ +Scene Data Provider +=================== + +The :class:`~isaaclab.scene_data.SceneDataProvider` bridges physics simulation +backends and the visualizers/renderers that consume scene data. It exposes a single Warp-native +read path for body transforms regardless of which physics backend (PhysX or Newton) is active, +so renderers and visualizers can stay backend-agnostic. + +Overview +-------- + +Isaac Lab supports multiple physics backends (PhysX and Newton) and multiple visualizers +(Omniverse Kit, Newton, Rerun, Viser). Each combination needs scene data to flow from the +physics engine into the renderer or visualizer. The :class:`SceneDataProvider` owns this flow: +the physics manager provides a :class:`~isaaclab.scene_data.SceneDataBackend` that wraps its +native tensor views, and the provider handles format conversion and re-mapping on top of it. + +.. code-block:: python + + from isaaclab.sim import SimulationContext + + # The SimulationContext owns the active provider; consumers fetch it instead of + # constructing one directly. + provider = SimulationContext.instance().get_scene_data_provider() + +Architecture +------------ + +The system has three layers: + +1. :class:`~isaaclab.scene_data.SceneDataBackend` — small interface implemented by each physics + manager. It exposes the backend's transform array directly as one of the + :class:`~isaaclab.scene_data.SceneDataFormat` Warp structs, plus the per-transform prim paths + and total count. There is no per-frame "update" call — the property accessors return live + views into the underlying tensor each time they're read. + + - :attr:`SceneDataBackend.transforms` — current transforms as a Warp struct (one of + :class:`SceneDataFormat.Vec3_Quat`, :class:`SceneDataFormat.Transform`, + :class:`SceneDataFormat.Matrix44`, :class:`SceneDataFormat.Vec3_Matrix33`). + - :attr:`SceneDataBackend.transform_count` — number of transforms. + - :attr:`SceneDataBackend.transform_paths` — list of USD prim paths, one per transform. + +2. :class:`~isaaclab.scene_data.SceneDataProvider` — wraps a backend and offers + format conversion plus index re-mapping: + + - :meth:`SceneDataProvider.get_transforms` — write the backend's transforms into a + consumer-provided :class:`SceneDataFormat` struct, optionally converting format + (e.g. ``Vec3_Quat`` → ``Transform``) and applying an index mapping. When the backend + format matches the output format and no mapping is provided, the result is a zero-copy + passthrough. + - :meth:`SceneDataProvider.create_mapping` — build a remap array from the backend's prim + paths to a consumer's desired ordering. Used when a renderer or visualizer wants + transforms indexed by its own body list rather than by the physics view order. + - :meth:`SceneDataProvider.get_camera_transforms` — discover per-camera, per-env + world transforms from the USD stage. + - :attr:`SceneDataProvider.usd_stage` — USD stage handle for stage-walking consumers. + - :attr:`SceneDataProvider.num_envs` — environment count inferred from + ``/World/envs/env_`` prims. + +3. Backend implementations: + + - ``PhysxSceneDataBackend`` (internal to :mod:`isaaclab_physx.physics`) wraps PhysX's + ``RigidBodyView`` and exposes its transforms as :class:`SceneDataFormat.Transform`. + - ``NewtonSceneDataBackend`` (internal to :mod:`isaaclab_newton.physics`) wraps the + Newton model's ``body_q`` and exposes it as :class:`SceneDataFormat.Transform`. + +PhysX backend +------------- + +When PhysX is the active physics backend, the provider reads transforms directly from PhysX's +``RigidBodyView`` (a wildcard-expanded tensor view covering every rigid body across all envs). +The transforms are returned as :class:`SceneDataFormat.Transform` (Warp ``transformf`` array), +so consumers that want this format get them zero-copy. + +Newton-native consumers (Newton visualizer, Rerun, Viser, Newton Warp renderer, OVRTX renderer) +additionally need a Newton ``Model``/``State`` to render against. To satisfy that requirement, +:class:`~isaaclab_newton.physics.NewtonManager` builds a **shadow Newton model** from the USD +stage on first access and updates its ``body_q`` from the PhysX backend each render frame. +This is hidden behind :meth:`NewtonManager.get_model` / :meth:`NewtonManager.get_state`, so +renderers don't need to know which physics backend is active. + +Newton backend +-------------- + +When Newton is the active physics backend, the backend wraps the Newton model's ``body_q`` +directly. No shadow model or per-frame sync is needed — Newton already owns the authoritative +model and state, and the provider exposes that state as +:class:`SceneDataFormat.Transform`. + +Data requirements +----------------- + +Visualizers and renderers declare what they need from the scene data path. This is resolved at +simulation-context construction time and is what triggers the shadow-model build for PhysX: + +.. list-table:: + :header-rows: 1 + + * - Component + - Requires Newton model + - Requires USD stage + * - Kit visualizer + - No + - Yes + * - Newton visualizer + - Yes + - No + * - Rerun visualizer + - Yes + - No + * - Viser visualizer + - Yes + - No + * - Isaac RTX renderer + - No + - Yes + * - Newton Warp renderer + - Yes + - No + * - OVRTX renderer + - Yes + - Yes + +See Also +-------- + +- :doc:`renderers` — renderer backends that consume scene data +- :doc:`/source/overview/core-concepts/visualization` — visualizer backends that consume scene data diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/schema_cfgs.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/schema_cfgs.rst new file mode 100644 index 0000000000000000000000000000000000000000..b6a326463ee6085cf70d6e39554b06d6409900e1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/schema_cfgs.rst @@ -0,0 +1,388 @@ +.. _schema-cfgs: + +Schema Configuration Classes +============================ + +Isaac Lab's spawners author USD physics attributes onto prims via a layered set of +configuration classes. The layering separates **universal-physics** parameters +from **backend-specific** parameters, so the same asset cfg can be authored once +and target any backend that supports it. + +This page explains the class hierarchy, when to use each tier, and how parameters +route to the underlying USD attributes. + +Migrating from 2.x? See :ref:`schemas-cfg-refactor` in the 3.0 migration guide. + +Quick example +------------- + +Add MuJoCo (MJC) gravity compensation to an articulated asset: + +.. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab_newton.sim.schemas import ( + MujocoRigidBodyPropertiesCfg, + MujocoJointDrivePropertiesCfg, + ) + + spawn = sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/Franka/franka_instanceable.usd", + rigid_props=MujocoRigidBodyPropertiesCfg(gravcomp=1.0), + joint_drive_props=MujocoJointDrivePropertiesCfg(actuatorgravcomp=True), + ) + +The Mujoco-specific fields land under ``mjc:*`` on the prim; any +``RigidBodyBaseCfg`` / ``JointDriveBaseCfg`` fields you set on the same instance +land under ``physics:*``. See :ref:`schema-cfgs-mixed` for the full routing rules. + +Class hierarchy +--------------- + +For each property group (rigid body, joint drive, collision, articulation root, +material, mesh collision), Isaac Lab defines a single base class in core +``isaaclab.sim.schemas`` and one subclass per backend in the corresponding +extension package: + +.. code-block:: text + + isaaclab.sim.schemas + ├── RigidBodyBaseCfg + │ ├── isaaclab_physx.sim.schemas.PhysxRigidBodyPropertiesCfg + │ └── isaaclab_newton.sim.schemas.NewtonRigidBodyPropertiesCfg + │ └── isaaclab_newton.sim.schemas.MujocoRigidBodyPropertiesCfg + │ + ├── JointDriveBaseCfg + │ ├── isaaclab_physx.sim.schemas.PhysxJointDrivePropertiesCfg + │ └── isaaclab_newton.sim.schemas.NewtonJointDrivePropertiesCfg + │ └── isaaclab_newton.sim.schemas.MujocoJointDrivePropertiesCfg + │ + ├── CollisionBaseCfg + │ ├── isaaclab_physx.sim.schemas.PhysxCollisionPropertiesCfg + │ └── isaaclab_newton.sim.schemas.NewtonCollisionPropertiesCfg + │ + ├── ArticulationRootBaseCfg + │ ├── isaaclab_physx.sim.schemas.PhysxArticulationRootPropertiesCfg + │ └── isaaclab_newton.sim.schemas.NewtonArticulationRootPropertiesCfg + │ + ├── MeshCollisionBaseCfg + │ ├── isaaclab_physx.sim.schemas.{PhysxConvexHull, PhysxConvexDecomposition, + │ │ PhysxTriangleMesh, PhysxSDFMesh, ...}PropertiesCfg + │ └── isaaclab_newton.sim.schemas.NewtonMeshCollisionPropertiesCfg + │ (also inherits NewtonCollisionPropertiesCfg — multi-namespace) + │ + └── isaaclab.sim.spawners.materials.RigidBodyMaterialBaseCfg + ├── isaaclab_physx.sim.spawners.materials.PhysxRigidBodyMaterialCfg + └── isaaclab_newton.sim.schemas.NewtonMaterialPropertiesCfg + +:class:`~isaaclab_newton.sim.schemas.NewtonMeshCollisionPropertiesCfg` uses +multiple inheritance: it extends both +:class:`~isaaclab_newton.sim.schemas.NewtonCollisionPropertiesCfg` (for +``contact_margin`` / ``contact_gap``) and +:class:`~isaaclab.sim.schemas.MeshCollisionBaseCfg` (for +``mesh_approximation_name``). This is the textbook case for the per-declaring- +class MRO routing described under :ref:`schema-cfgs-mixed` — each inherited +field is written under the namespace of the class that declared it. + +The hierarchy is **single-rooted per spawner slot**: every spawner has a single +field for each property group (``rigid_props``, ``joint_drive_props``, +``collision_props``, etc.), and Python's polymorphism allows any subclass to be +passed where the base type is expected. + +When to use which class +----------------------- + +The choice depends on which backends you target and which fields you need. + +**Use a base class** (``RigidBodyBaseCfg``, ``JointDriveBaseCfg``, etc.) + when you only need universal-physics fields and you want your asset cfg to be + backend-portable. Importing the base class does not pull in + :mod:`isaaclab_physx` or :mod:`isaaclab_newton`. + +**Use a PhysX subclass** (``PhysxRigidBodyPropertiesCfg``, etc.) + when your asset uses PhysX-specific knobs (per-body damping, TGS solver + iterations, sleep / stabilization thresholds, torsional patch friction, + compliant-contact materials, etc.) and you target the PhysX backend. Inherits + all base-class fields, so you can set both universal and PhysX fields on the + same instance. + +**Use a Newton subclass** (``NewtonRigidBodyPropertiesCfg``, etc.) + when you target Newton and need Newton-native attributes + (``newton:contactMargin``, ``newton:torsionalFriction``, + ``newton:selfCollisionEnabled``, etc.). The empty Newton base classes + (``NewtonRigidBodyPropertiesCfg``, ``NewtonJointDrivePropertiesCfg``) reserve + the ``newton:*`` namespace for future native fields and act as the parent for + solver-specific subclasses. + +**Use a MuJoCo subclass** (``MujocoRigidBodyPropertiesCfg``, ``MujocoJointDrivePropertiesCfg``) + when you specifically use Newton's **MuJoCo** solver and need MuJoCo-only + knobs (gravity compensation via ``mjc:gravcomp`` / + ``mjc:actuatorgravcomp``). Inherits from the Newton base, so + ``isinstance(cfg, NewtonRigidBodyPropertiesCfg)`` is True. + +What parameters live where +-------------------------- + +.. note:: + + The tables below summarize which fields live on which cfg classes. The + canonical source is the auto-generated API reference — see + :doc:`/source/api/lab/isaaclab.sim.schemas`, + :doc:`/source/api/lab_physx/isaaclab_physx.sim.schemas`, and + :doc:`/source/api/lab_newton/isaaclab_newton.sim.schemas`, which render + the cfg class docstrings directly. Treat these tables as a navigation aid; + if they drift from the source, the API docs win. + +Universal physics (declared on the base class) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Lives on the **base class**. Most fields write to ``physics:*`` (the standard +``UsdPhysics.*API`` namespace), but a small set of "exception" fields are +declared on the base for backend-portability yet route to a non-``physics:*`` +namespace because that is the only USD path honored today (e.g., +``disable_gravity`` writes ``physxRigidBody:disableGravity`` because both PhysX +and Newton's importer consume the PhysX attribute). The "USD attribute" column +below is the actual emitted attribute, not the namespace family. + +.. list-table:: + :header-rows: 1 + :widths: 30 35 35 + + * - Base class + - Field + - USD attribute + * - ``RigidBodyBaseCfg`` + - ``rigid_body_enabled``, ``kinematic_enabled`` + - ``physics:rigidBodyEnabled``, ``physics:kinematicEnabled`` + * - ``RigidBodyBaseCfg`` + - ``disable_gravity`` + - ``physxRigidBody:disableGravity`` (per-body on PhysX; scene-level partial honor on Newton) + * - ``CollisionBaseCfg`` + - ``collision_enabled`` + - ``physics:collisionEnabled`` + * - ``CollisionBaseCfg`` + - ``contact_offset``, ``rest_offset`` + - ``physxCollision:contactOffset``, ``physxCollision:restOffset`` (Newton consumes via PhysX bridge) + * - ``ArticulationRootBaseCfg`` + - ``articulation_enabled`` + - ``physxArticulation:articulationEnabled`` + * - ``ArticulationRootBaseCfg`` + - ``fix_root_link`` + - synthesizes ``UsdPhysics.FixedJoint`` (writer-side, not a USD attribute) + * - ``JointDriveBaseCfg`` + - ``drive_type``, ``max_force``, ``stiffness``, ``damping`` + - ``drive::physics:type/maxForce/stiffness/damping`` + * - ``JointDriveBaseCfg`` + - ``max_joint_velocity`` + - ``physxJoint:maxJointVelocity`` (sole USD path; Newton consumes via PhysX bridge today) + * - ``JointDriveBaseCfg`` + - ``ensure_drives_exist`` + - writer-side only — when ``True``, ensures any drive with ``stiffness=0`` and + ``damping=0`` gets a minimal ``stiffness=1e-3`` so backends like Newton recognize + the joint as actively driven; not a USD attribute on its own + * - ``MassPropertiesCfg`` + - ``mass``, ``density`` + - ``physics:mass``, ``physics:density`` + * - ``RigidBodyMaterialBaseCfg`` + - ``static_friction``, ``dynamic_friction``, ``restitution`` + - ``physics:staticFriction``, ``physics:dynamicFriction``, ``physics:restitution`` + * - ``MeshCollisionBaseCfg`` + - ``mesh_approximation_name`` + - ``physics:approximation`` + +PhysX-specific (``physx*:*`` namespace, ``Physx*API`` schemas) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Lives on the PhysX subclass. Only authored when the user opts in by setting the +field on a PhysX cfg. + +.. list-table:: + :header-rows: 1 + :widths: 35 35 30 + + * - PhysX subclass + - Fields (selection) + - USD namespace / schema + * - ``PhysxRigidBodyPropertiesCfg`` + - ``linear_damping``, ``angular_damping``, ``max_linear_velocity``, ``max_angular_velocity``, ``solver_position_iteration_count``, ``sleep_threshold``, ``enable_gyroscopic_forces``, … + - ``physxRigidBody:*`` / ``PhysxRigidBodyAPI`` + * - ``PhysxJointDrivePropertiesCfg`` + - (currently empty; reserved for future PhysX-only drive knobs) + - ``physxJoint:*`` / ``PhysxJointAPI`` + * - ``PhysxCollisionPropertiesCfg`` + - ``torsional_patch_radius``, ``min_torsional_patch_radius`` + - ``physxCollision:*`` / ``PhysxCollisionAPI`` + * - ``PhysxArticulationRootPropertiesCfg`` + - ``enabled_self_collisions``, ``solver_position_iteration_count``, ``sleep_threshold``, ``stabilization_threshold`` + - ``physxArticulation:*`` / ``PhysxArticulationAPI`` + * - ``PhysxRigidBodyMaterialCfg`` + - ``compliant_contact_stiffness``, ``compliant_contact_damping``, ``friction_combine_mode``, ``restitution_combine_mode`` + - ``physxMaterial:*`` / ``PhysxMaterialAPI`` + * - ``PhysxConvexHullPropertiesCfg`` (and other mesh-cooking subclasses) + - ``hull_vertex_limit``, ``min_thickness``, … + - ``physxConvexHullCollision:*`` / ``PhysxConvexHullCollisionAPI`` + +Newton-targeted (``newton:*`` namespace, ``Newton*API`` schemas) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Lives on the Newton subclass. Authored only when the user opts in. + +.. list-table:: + :header-rows: 1 + :widths: 35 35 30 + + * - Newton subclass + - Fields + - USD namespace / schema + * - ``NewtonRigidBodyPropertiesCfg`` + - (empty — reserved for future Newton-native rigid-body fields) + - ``newton:*`` + * - ``NewtonJointDrivePropertiesCfg`` + - (empty — reserved for future Newton-native joint-drive fields) + - ``newton:*`` + * - ``NewtonCollisionPropertiesCfg`` + - ``contact_margin``, ``contact_gap`` + - ``newton:*`` / ``NewtonCollisionAPI`` + * - ``NewtonMeshCollisionPropertiesCfg`` + - ``max_hull_vertices`` + - ``newton:*`` / ``NewtonMeshCollisionAPI`` + * - ``NewtonMaterialPropertiesCfg`` + - ``torsional_friction``, ``rolling_friction`` + - ``newton:*`` / ``NewtonMaterialAPI`` + * - ``NewtonArticulationRootPropertiesCfg`` + - ``self_collision_enabled`` + - ``newton:*`` / ``NewtonArticulationRootAPI`` + +MuJoCo-solver-specific (``mjc:*`` namespace) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Lives on a MuJoCo subclass that extends a Newton subclass. Only consumed when +running Newton's MuJoCo solver. + +.. list-table:: + :header-rows: 1 + :widths: 35 25 40 + + * - MuJoCo subclass + - Field + - USD attribute / schema + * - ``MujocoRigidBodyPropertiesCfg`` + - ``gravcomp`` + - ``mjc:gravcomp`` (raw attribute, no applied schema) + * - ``MujocoJointDrivePropertiesCfg`` + - ``actuatorgravcomp`` + - ``mjc:actuatorgravcomp`` via ``MjcJointAPI`` + +.. note:: + + The two MuJoCo rows differ in their USD applied-schema requirement: + ``mjc:actuatorgravcomp`` is part of the registered ``MjcJointAPI`` applied + schema (so the writer calls ``prim.AddAppliedSchema("MjcJointAPI")`` when + the field is non-None). ``mjc:gravcomp`` has no registered Mjc applied + schema for body-level gravity compensation, so the writer authors it as a + raw USD attribute. Newton's MuJoCo solver consumes both via the same + resolver path; the schema-application difference is purely a USD-side + detail. + +.. _schema-cfgs-mixed: + +Mixed-namespace authoring on a single instance +---------------------------------------------- + +Because each cfg field is routed to its **declaring class's** namespace (not +the instance's class), a subclass instance can author attributes across multiple +namespaces on the same prim. For example: + +.. code-block:: python + + from isaaclab_newton.sim.schemas import MujocoRigidBodyPropertiesCfg + + cfg = MujocoRigidBodyPropertiesCfg( + rigid_body_enabled=True, # declared on RigidBodyBaseCfg → physics:rigidBodyEnabled + disable_gravity=True, # declared on RigidBodyBaseCfg (exception) → physxRigidBody:disableGravity + gravcomp=1.0, # declared on MujocoRigidBodyPropertiesCfg → mjc:gravcomp + ) + +The writer applies each field to the namespace of the class where the field is +declared. The applied schemas (``PhysxRigidBodyAPI`` for ``disable_gravity``, +none for the Mjc raw attribute) are added only when the corresponding +fields are non-None. + +Spawner usage +------------- + +Spawners (``UsdFileCfg``, ``MeshCuboidCfg``, ``MeshSphereCfg``, …) accept +the base class type for each slot and use polymorphism to dispatch to the +correct subclass at write time: + +.. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab_physx.sim.schemas import PhysxRigidBodyPropertiesCfg + from isaaclab_newton.sim.schemas import MujocoJointDrivePropertiesCfg + + spawn = sim_utils.UsdFileCfg( + usd_path="...", + rigid_props=PhysxRigidBodyPropertiesCfg(disable_gravity=True, linear_damping=0.1), + joint_drive_props=MujocoJointDrivePropertiesCfg( + drive_type="acceleration", + stiffness=10.0, + damping=0.1, + actuatorgravcomp=True, + ), + ) + +.. _schema-cfgs-gravcomp: + +Gravity compensation (MuJoCo solver) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Gravity compensation has two halves and you typically need both: + +* **Body-level**: + :attr:`~isaaclab_newton.sim.schemas.MujocoRigidBodyPropertiesCfg.gravcomp` + on each rigid body (writes ``mjc:gravcomp``). This is what *computes* the + compensation force. +* **Joint-level**: + :attr:`~isaaclab_newton.sim.schemas.MujocoJointDrivePropertiesCfg.actuatorgravcomp` + on each joint (writes ``mjc:actuatorgravcomp``). This routes the compensation + force through the actuator channel (``qfrc_actuator``) so it counts against + ``actuatorfrcrange``; otherwise it goes to ``qfrc_passive``. + +``actuatorgravcomp=True`` alone is a no-op — without body-level ``gravcomp`` +there are no forces to route. To prevent this footgun, the spawner +**auto-enables** ``MujocoRigidBodyPropertiesCfg(gravcomp=1.0)`` whenever +``joint_drive_props`` is a Mujoco cfg with ``actuatorgravcomp=True`` and +``rigid_props`` is not already a Mujoco cfg. If you want a different +``gravcomp`` value (or want to disable the auto-enable), pass an explicit +``MujocoRigidBodyPropertiesCfg`` in ``rigid_props``. + +Naming convention +----------------- + +Cfg field names use ``snake_case``; the writer converts them to ``camelCase`` +USD attribute names (``contact_margin`` → ``newton:contactMargin``). For +single-token fields (``gravcomp``, ``actuatorgravcomp``), the conversion is +identity, which matches MuJoCo's lowercase convention. + +Field renames preserve backward compatibility via deprecation aliases. Two such +aliases live on ``JointDriveBaseCfg`` today: + +* ``max_velocity`` → ``max_joint_velocity`` (USD attribute is ``physxJoint:maxJointVelocity``) +* ``max_effort`` → ``max_force`` (USD attribute is ``drive::physics:maxForce``) + +The old names remain as real dataclass fields (so ``dataclasses.fields()`` +sees them), defaulting to ``None``. ``__post_init__`` runs +``_deprecate_field_alias`` which, when the old field is set: emits a +``DeprecationWarning``, copies the value into the canonical field if the +canonical is ``None``, then nulls the old field. Setting **both** in the same +constructor is silent — the canonical wins; the old name's value is discarded. +Both aliases are scheduled for removal in 4.0. + +See also +-------- + +* :doc:`/source/migration/migrating_to_isaaclab_3-0` — migration guide +* :doc:`/source/api/lab/isaaclab.sim.schemas` — solver-common base class API +* :doc:`/source/api/lab_physx/isaaclab_physx.sim.schemas` — PhysX subclass API +* :doc:`/source/api/lab_newton/isaaclab_newton.sim.schemas` — Newton/MuJoCo subclass API diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/camera.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/camera.rst new file mode 100644 index 0000000000000000000000000000000000000000..19e1c6ee9742a76cdc60efbef7a63d1a5e49d1cb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/camera.rst @@ -0,0 +1,445 @@ +.. _overview_sensors_camera: + +.. currentmodule:: isaaclab + +Camera +====== + +Camera sensors in Isaac Lab are renderer-backed sensors: each :class:`~sensors.Camera` instance +is coupled to a **renderer** that produces the image data. If multiple cameras use the same renderer +type, only one renderer is instantiated and shared between them. The renderer and camera are intentionally +isolated from each other — the camera defines *what* to capture (pose, resolution, field of view, +data types), while the renderer defines *how* to render it (RTX ray-tracing, Newton Warp rasterizer, +etc.). This separation allows the same camera configuration to run across different physics and +rendering backends without code changes. + +For an overview of the available renderer backends and how to choose between them, see +:ref:`overview_renderers`. + +Rendered images are unique among supported sensor data types due to their large bandwidth requirements. +A single 800 × 600 image with 32-bit color clocks in at just under 2 MB. At 60 fps across thousands +of parallel environments, this grows quickly. Isaac Lab's tiled rendering API specifically addresses +these scaling challenges by batching all cameras into a single render pass. + + +Renderer Backends +----------------- + +The renderer used by a camera is configured via the ``renderer_cfg`` field on +:class:`~sensors.CameraCfg`. The default is :class:`~isaaclab_physx.renderers.IsaacRtxRendererCfg` +(NVIDIA RTX, requires Isaac Sim). + +.. list-table:: + :header-rows: 1 + :widths: 30 30 40 + + * - ``renderer_cfg`` + - Requires Isaac Sim? + - Supported data types + * - ``IsaacRtxRendererCfg`` *(default)* + - Yes + - rgb, rgba, depth, normals, motion vectors, semantic/instance segmentation, and all other annotators + * - ``NewtonWarpRendererCfg`` + - No (kit-less) + - ``rgb``, ``depth`` only + * - ``OVRTXRendererCfg`` + - No (+ ``isaaclab_ov``) + - ``rgb``, ``depth`` only + +.. note:: + + The Newton Warp renderer currently supports only **``rgb``** and **``depth``** data types. + Annotators such as segmentation, normals, and motion vectors are Isaac RTX-specific features and + require :class:`~isaaclab_physx.renderers.IsaacRtxRendererCfg`. + + +Tiled Rendering +~~~~~~~~~~~~~~~ + +.. note:: + + This feature is available from Isaac Sim version 4.2.0 onwards (for the RTX renderer). + The Newton Warp renderer supports tiled rendering in kit-less mode. + + Tiled rendering in combination with image processing networks require heavy memory resources, + especially at larger resolutions. We recommend running 512 cameras on RTX 4090 GPUs or similar + when using the RTX renderer. + +The Tiled Rendering API provides a vectorized interface for collecting image data from all environment +clones in a single batched render pass. Instead of one render call per camera, all copies of a camera +are composited into a single large tiled image, dramatically reducing host-device transfer overhead. + +Isaac Lab provides tiled rendering through :class:`~sensors.Camera`, configured via +:class:`~sensors.CameraCfg`. The ``renderer_cfg`` field selects the rendering backend. + + +CameraCfg with renderer_cfg +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The renderer is specified via ``renderer_cfg`` on :class:`~sensors.CameraCfg`. The camera and +renderer configurations are fully decoupled: you can swap renderers without changing any other camera +parameters. + +**Default (RTX, requires Isaac Sim):** + +.. code-block:: python + + from isaaclab.sensors import CameraCfg + import isaaclab.sim as sim_utils + # IsaacRtxRendererCfg is the default, no explicit import needed + + tiled_camera: CameraCfg = CameraCfg( + prim_path="/World/envs/env_.*/Camera", + offset=CameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.9945, 0.0, 0.1045, 0.0), convention="world"), + data_types=["rgb"], + spawn=sim_utils.PinholeCameraCfg( + focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) + ), + width=80, + height=80, + # renderer_cfg defaults to IsaacRtxRendererCfg() + ) + +**Newton Warp renderer (kit-less, no Isaac Sim required):** + +.. code-block:: python + + from isaaclab.sensors import CameraCfg + from isaaclab_newton.renderers import NewtonWarpRendererCfg + import isaaclab.sim as sim_utils + + tiled_camera: CameraCfg = CameraCfg( + prim_path="/World/envs/env_.*/Camera", + offset=CameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.9945, 0.0, 0.1045, 0.0), convention="world"), + data_types=["rgb", "depth"], # only rgb and depth supported with Newton renderer + spawn=sim_utils.PinholeCameraCfg( + focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) + ), + width=80, + height=80, + renderer_cfg=NewtonWarpRendererCfg(), + ) + +**Multi-backend preset (switches renderer alongside physics backend):** + +For environments that need to support both backends, use +:class:`~isaaclab_tasks.utils.presets.MultiBackendRendererCfg` together with the +:ref:`PresetCfg pattern `: + +.. code-block:: python + + from isaaclab.sensors import CameraCfg + from isaaclab_tasks.utils.presets import MultiBackendRendererCfg + import isaaclab.sim as sim_utils + + tiled_camera: CameraCfg = CameraCfg( + prim_path="/World/envs/env_.*/Camera", + offset=CameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.9945, 0.0, 0.1045, 0.0), convention="world"), + data_types=["rgb"], + spawn=sim_utils.PinholeCameraCfg( + focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) + ), + width=80, + height=80, + renderer_cfg=MultiBackendRendererCfg(), # selects RTX or Newton Warp via presets= CLI arg + ) + +The active preset is selected at launch via ``physics=``, ``renderer=``, or ``presets=`` CLI arguments: + +.. code-block:: bash + + # Use Newton Warp renderer + python train.py task=Isaac-Cartpole-RGB-Camera-Direct-v0 renderer=newton_renderer + + # Use OVRTX renderer + python train.py task=Isaac-Cartpole-RGB-Camera-Direct-v0 renderer=ovrtx_renderer + + # Use default (Isaac RTX) + python train.py task=Isaac-Cartpole-RGB-Camera-Direct-v0 + + +Accessing camera data +~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: python + + tiled_camera = Camera(cfg.tiled_camera) + data = tiled_camera.data.output["rgb"] # shape: (num_cameras, H, W, 3), torch.uint8 + +The returned data has shape ``(num_cameras, height, width, num_channels)``, ready to use directly +as an observation in RL training. + +When using the RTX renderer, add ``--enable_cameras`` when launching: + +.. code-block:: shell + + ./isaaclab.sh train --rl_library rl_games \ + --task=Isaac-Cartpole-Camera-Presets-Direct-v0 --enable_cameras + + +Annotators (RTX only) +~~~~~~~~~~~~~~~~~~~~~ + +.. note:: + + Annotators are a feature of the **Isaac RTX renderer** (``IsaacRtxRendererCfg``). + They are **not** available with the Newton Warp renderer or ovrtx, which + support only ``rgb`` and ``depth``. + +:class:`~sensors.Camera` exposes the following annotator +data types when using the RTX renderer: + +* ``"rgb"``: A 3-channel rendered color image. +* ``"rgba"``: A 4-channel rendered color image with alpha channel. +* ``"distance_to_camera"``: Distance to the camera optical center per pixel. +* ``"distance_to_image_plane"``: Distance along the camera's Z-axis per pixel. +* ``"depth"``: Alias for ``"distance_to_image_plane"``. +* ``"normals"``: Local surface normal vectors at each pixel. +* ``"motion_vectors"``: Per-pixel motion vectors in image space. +* ``"semantic_segmentation"``: Semantic segmentation labels. +* ``"instance_segmentation_fast"``: Instance segmentation data. +* ``"instance_id_segmentation_fast"``: Instance ID segmentation data. + +RGB and RGBA +~~~~~~~~~~~~ + +.. figure:: ../../../_static/overview/sensors/camera_rgb.jpg + :align: center + :figwidth: 100% + :alt: A scene captured in RGB + +``rgb`` returns a 3-channel RGB image of type ``torch.uint8``, shape ``(B, H, W, 3)``. + +``rgba`` returns a 4-channel RGBA image of type ``torch.uint8``, shape ``(B, H, W, 4)``. + +To convert to ``torch.float32``, divide by 255.0. + +``rgb_hdr`` returns a 3-channel scene-linear HDR image of type ``torch.float32``, shape ``(B, H, W, 3)``. + +Post-render Camera ISP +~~~~~~~~~~~~~~~~~~~~~~ + +A camera Image Signal Processing (ISP) pipeline models the chain that maps +the scene-linear radiance captured by a sensor to the LDR pixel values a +downstream consumer sees. +The camera ISP pipeline is usually part of the renderer. +In Isaac Lab we expose a post-render camera ISP pipeline which is applied on top of the renderer's HDR scene-linear AOV. +This makes it possible to implement additional post-render processing not currently supported by the renderer backends. +The pass is configured via :attr:`~sensors.CameraCfg.isp_cfg` +on every camera and runs once per render tick. + +PPISP +^^^^^ + +The shipped ISP implementation is **PPISP** (Physically Plausible Image +Signal Processing), an NVIDIA Spatial Intelligence Lab pipeline designed +to bring synthetic imagery — most notably 3D Gaussian splat reconstructions +— closer to real-camera output without re-training the upstream model. See +the project page: https://research.nvidia.com/labs/sil/projects/ppisp . + +PPISP is typically authored alongside a `ParticleField3DGaussianSplat +`__ +USD asset: it carries a `RenderProduct +`__ +whose target camera and PPISP `UsdShade.Shader +`__ +(a shader prim named ``PPISP`` whose inputs follow the PPISP naming +convention) were calibrated against the real capture rig that produced +the splats. Configuring the camera with the matching PPISP coefficients +makes the rendered tile match the calibration target. + +The pipeline applies, in order: responsivity → exposure → vignetting → +color homography → camera response function → uint8 clamp. It runs as a +single Warp kernel. + +Configuration +^^^^^^^^^^^^^ + +:attr:`~sensors.CameraCfg.isp_cfg` accepts three forms: + +* ``None`` (default) — ISP disabled. +* :class:`~isaaclab_ppisp.PpispCfg` — explicit PPISP coefficients + (:attr:`~isaaclab_ppisp.PpispCfg.inputs`), or + :attr:`~isaaclab_ppisp.PpispCfg.shader_prim_path` to import them from a + PPISP ``UsdShade.Shader`` already on the stage. +* :class:`~sensors.CameraISPMode` — auto-discover an ISP shader on the + stage (see below). + +The cfg applies once per Camera sensor batch. The PPISP Warp kernel takes +scalar coefficients, so every cloned view in a tiled batch shares the same +ISP configuration — there is no per-view ISP today. + +.. code-block:: python + + from isaaclab.sensors.camera import CameraCfg, CameraISPMode + from isaaclab_ppisp import PpispCfg + + # default — ISP disabled + cfg = CameraCfg(...) + + # explicit coefficients + cfg = CameraCfg(..., isp_cfg=PpispCfg(inputs={"exposureOffset": 1.5})) + + # import coefficients from a USD shader path + cfg = CameraCfg(..., isp_cfg=PpispCfg(shader_prim_path="/World/Render/PPISP")) + + # auto-discover from the stage + cfg = CameraCfg(..., isp_cfg=CameraISPMode.AUTO_ANY) + +Auto-discovery +^^^^^^^^^^^^^^ + +Auto-discovery is opt-in via :class:`~sensors.CameraISPMode`. Discovery runs +once at camera construction using the first matched camera prim in the Camera +sensor batch: + +1. Walk the stage for a USD ``RenderProduct`` whose ``camera`` relationship + targets the first matched camera prim **and** that has a child + ``UsdShade.Shader`` prim named ``PPISP``. If found, import its inputs as a + :class:`~isaaclab_ppisp.PpispCfg`. +2. ``AUTO_ANY`` only: if step 1 finds nothing, fall back to the first + ``UsdShade.Shader`` prim named ``PPISP`` anywhere on the stage. +3. Otherwise the ISP stays disabled for the whole Camera sensor batch. + +In practice this means: if the stage carries a ``ParticleField3DGaussianSplat`` +together with a ``RenderProduct`` that binds a ``PPISP`` shader child to the +batch's first matched camera prim, the Camera sensor picks up the matching ISP +automatically and no Python-side coefficient authoring is required. + +``AUTO_CAMERA`` runs step 1 only — useful when the stage carries multiple +PPISP shaders and you want the Camera sensor batch to use exactly the one bound +to its first matched camera prim. + +Renderer support +^^^^^^^^^^^^^^^^ + +All three shipped backends advertise the HDR AOV +(:attr:`~renderers.RenderBufferKind.RGB_HDR`) and compose the ISP pipeline +internally: the Isaac RTX renderer sources HDR from the Replicator +``HdrColor`` annotator, the OVRTX renderer from its HDR render var, the +Newton Warp renderer from its native scene-linear color buffer. Each +backend allocates its own HDR scratch buffer when the user did not request +``"rgb_hdr"`` in :attr:`~sensors.CameraCfg.data_types`, and dispatches the +PPISP kernel into ``rgb`` / ``rgba`` after every render tick. + +Usage example +^^^^^^^^^^^^^ + +For a runnable usage example, see ``scripts/demos/sensors/ppisp_camera.py``. +It loads a PPISP-authored USD or USDZ Gaussian scene, creates baseline and +PPISP camera sensors for the selected camera, and saves baseline, PPISP, and +absolute-difference images. + +.. code-block:: bash + + ./isaaclab.sh -p scripts/demos/sensors/ppisp_camera.py \ + --renderer newton --visualizer none --max_steps 60 + +Use ``--renderer isaac_rtx`` to run the same workflow with Isaac RTX. Pass +``--input_scene`` for a custom scene and ``--camera_prim_path`` if the stage +contains multiple PPISP-bound cameras. Images are written to +``scripts/demos/sensors/output/ppisp_camera`` unless ``--output_dir`` is set. + +Known limitations +^^^^^^^^^^^^^^^^^ + +* The ISP writes back into the ``rgb`` / ``rgba`` buffers. If neither is + requested, configuring ``isp_cfg`` raises at camera init. +* PPISP inputs are static for the lifetime of the camera. Animated USD + shader inputs are collapsed to their first authored time sample. +* Coefficients are global per camera — no per-pixel or per-region + authoring beyond the radial vignetting term. +* PPISP is the only ISP implementation today. Other ISP families would + need a new config type and discoverer entry. +* On the Isaac RTX and OVRTX backends, enabling ``isp_cfg`` forces RTX-side + tonemapping off (``/rtx/rtpt/gaussian/skipTonemapping/enabled=False``) + and authors a neutral ``OmniRtxCameraExposureAPI_1`` schema on each + camera prim so the post-render ISP is the only path that processes + color. Mixing this with RTX-side exposure authoring is not supported. +* Auto-discovery resolves at camera construction; later authoring of a + ``RenderProduct`` or shader on the stage is not picked up. + +Depth and Distances +~~~~~~~~~~~~~~~~~~~ + +.. figure:: ../../../_static/overview/sensors/camera_depth.jpg + :align: center + :figwidth: 100% + :alt: A scene captured as depth + +``distance_to_camera`` returns a single-channel depth image with distance to the camera optical +center, shape ``(B, H, W, 1)``, type ``torch.float32``. + +``distance_to_image_plane`` returns distances of 3D points from the camera plane along the Z-axis, +shape ``(B, H, W, 1)``, type ``torch.float32``. + +``depth`` is an alias for ``distance_to_image_plane``. + +Normals +~~~~~~~ + +.. figure:: ../../../_static/overview/sensors/camera_normals.jpg + :align: center + :figwidth: 100% + :alt: A scene captured with surface normals + +``normals`` returns local surface normal vectors at each pixel, shape ``(B, H, W, 3)`` containing +``(x, y, z)``, type ``torch.float32``. + +Motion Vectors +~~~~~~~~~~~~~~ + +``motion_vectors`` returns per-pixel motion vectors in image space between frames. +Shape ``(B, H, W, 2)``: ``x`` is horizontal motion (positive = left), ``y`` is vertical motion +(positive = up). Type ``torch.float32``. + +Semantic Segmentation +~~~~~~~~~~~~~~~~~~~~~ + +.. figure:: ../../../_static/overview/sensors/camera_semantic.jpg + :align: center + :figwidth: 100% + :alt: A scene with semantic segmentation + +``semantic_segmentation`` outputs per-pixel semantic labels for entities with semantic annotations. +An ``info`` dictionary is available via ``tiled_camera.data.info['semantic_segmentation']``. + +- If ``colorize_semantic_segmentation=True``: 4-channel RGBA image, shape ``(B, H, W, 4)``, + type ``torch.uint8``. The ``idToLabels`` dict maps color to semantic label. +- If ``colorize_semantic_segmentation=False``: shape ``(B, H, W, 1)``, type ``torch.int32``, + containing semantic IDs. The ``idToLabels`` dict maps ID to label. + +Instance ID Segmentation +~~~~~~~~~~~~~~~~~~~~~~~~ + +.. figure:: ../../../_static/overview/sensors/camera_instanceID.jpg + :align: center + :figwidth: 100% + :alt: A scene with instance ID segmentation + +``instance_id_segmentation_fast`` outputs per-pixel instance IDs, unique per USD prim path. +An ``info`` dictionary is available via ``tiled_camera.data.info['instance_id_segmentation_fast']``. + +- If ``colorize_instance_id_segmentation=True``: shape ``(B, H, W, 4)``, type ``torch.uint8``. + The ``idToLabels`` dict maps color to USD prim path. +- If ``colorize_instance_id_segmentation=False``: shape ``(B, H, W, 1)``, type ``torch.int32``. + The ``idToLabels`` dict maps instance ID to USD prim path. + +Instance Segmentation +~~~~~~~~~~~~~~~~~~~~~ + +.. figure:: ../../../_static/overview/sensors/camera_instance.jpg + :align: center + :figwidth: 100% + :alt: A scene with instance segmentation + +``instance_segmentation_fast`` outputs instance segmentation, traversing down the prim hierarchy +to the lowest level with semantic labels (unlike ``instance_id_segmentation_fast``, which always +goes to the leaf prim). +An ``info`` dictionary is available via ``tiled_camera.data.info['instance_segmentation_fast']``. + +- If ``colorize_instance_segmentation=True``: shape ``(B, H, W, 4)``, type ``torch.uint8``. +- If ``colorize_instance_segmentation=False``: shape ``(B, H, W, 1)``, type ``torch.int32``. + +The ``idToLabels`` dict maps color to USD prim path. The ``idToSemantics`` dict maps color to +semantic label. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/contact_sensor.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/contact_sensor.rst new file mode 100644 index 0000000000000000000000000000000000000000..ebd81e60a54d3d50c723d8dbedad4ad7f50c3a3c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/contact_sensor.rst @@ -0,0 +1,104 @@ +.. _overview_sensors_contact: + +.. currentmodule:: isaaclab + +Contact Sensor +============== + +.. figure:: ../../../_static/overview/sensors/contact_diagram.jpg + :align: center + :figwidth: 100% + :alt: A contact sensor with filtering + +The contact sensor is designed to return the net contact force acting on a given ridgid body. The sensor is written to behave as a physical object, and so the "scope" of the contact sensor is limited to the body (or bodies) that defines it. There are multiple ways to define this scope, depending on your need to filter the forces coming from the contact. + +By default, the reported force is the total contact force, but your application may only care about contact forces due to specific objects. Retrieving contact forces from specific objects requires filtering, and this can only be done in a "many-to-one" way. A multi-legged robot that needs filterable contact information for its feet would require one sensor per foot to be defined in the environment, but a robotic hand with contact sensors on the tips of each finger can be defined with a single sensor. + +Consider a simple environment with an Anymal Quadruped and a block + +.. literalinclude:: ../../../../../scripts/demos/sensors/contact_sensor.py + :language: python + :lines: 40-90 + +We define the sensors on the feet of the robot in two different ways. The front feet are independent sensors (one sensor body per foot) and the "Cube" is placed under the left foot. The hind feet are defined as a single sensor with multiple bodies. + +We can then run the scene and print the data from the sensors + +.. code-block:: python + + def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + . + . + . + # Simulate physics + while simulation_app.is_running(): + . + . + . + # print information from the sensors + print("-------------------------------") + print(scene["contact_forces_LF"]) + print("Received force matrix of: ", scene["contact_forces_LF"].data.force_matrix_w) + print("Received contact force of: ", scene["contact_forces_LF"].data.net_forces_w) + print("-------------------------------") + print(scene["contact_forces_RF"]) + print("Received force matrix of: ", scene["contact_forces_RF"].data.force_matrix_w) + print("Received contact force of: ", scene["contact_forces_RF"].data.net_forces_w) + print("-------------------------------") + print(scene["contact_forces_H"]) + print("Received force matrix of: ", scene["contact_forces_H"].data.force_matrix_w) + print("Received contact force of: ", scene["contact_forces_H"].data.net_forces_w) + +Here, we print both the net contact force and the filtered force matrix for each contact sensor defined in the scene. The front left and front right feet report the following + +.. code-block:: bash + + ------------------------------- + Contact sensor @ '/World/envs/env_.*/Robot/LF_FOOT': + view type : + update period (s) : 0.0 + number of bodies : 1 + body names : ['LF_FOOT'] + + Received force matrix of: tensor([[[[-1.3923e-05, 1.5727e-04, 1.1032e+02]]]], device='cuda:0') + Received contact force of: tensor([[[-1.3923e-05, 1.5727e-04, 1.1032e+02]]], device='cuda:0') + ------------------------------- + Contact sensor @ '/World/envs/env_.*/Robot/RF_FOOT': + view type : + update period (s) : 0.0 + number of bodies : 1 + body names : ['RF_FOOT'] + + Received force matrix of: tensor([[[[0., 0., 0.]]]], device='cuda:0') + Received contact force of: tensor([[[1.3529e-05, 0.0000e+00, 1.0069e+02]]], device='cuda:0') + + +.. figure:: ../../../_static/overview/sensors/contact_visualization.jpg + :align: center + :figwidth: 100% + :alt: The contact sensor visualization + + +Notice that even with filtering, both sensors report the net contact force acting on the foot. However, the "force matrix" on the right foot is zero because that foot isn't in contact with the filtered body, ``/World/envs/env_.*/Cube``. Now, checkout the data coming from the hind feet! + +.. code-block:: bash + + ------------------------------- + Contact sensor @ '/World/envs/env_.*/Robot/.*H_FOOT': + view type : + update period (s) : 0.0 + number of bodies : 2 + body names : ['LH_FOOT', 'RH_FOOT'] + + Received force matrix of: None + Received contact force of: tensor([[[9.7227e-06, 0.0000e+00, 7.2364e+01], + [2.4322e-05, 0.0000e+00, 1.8102e+02]]], device='cuda:0') + +In this case, the contact sensor has two bodies: the left and right hind feet. When the force matrix is queried, the result is ``None`` because this is a many body sensor, and presently Isaac Lab only supports "many to one" contact force filtering. Unlike the single body contact sensor, the reported force tensor has multiple entries, with each "row" corresponding to the contact force on a single body of the sensor (matching the ordering at construction). + +.. dropdown:: Code for contact_sensor.py + :icon: code + + .. literalinclude:: ../../../../../scripts/demos/sensors/contact_sensor.py + :language: python + :linenos: diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/frame_transformer.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/frame_transformer.rst new file mode 100644 index 0000000000000000000000000000000000000000..7ebe0020cdb1583e1f8baad7e0941b4184f62192 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/frame_transformer.rst @@ -0,0 +1,111 @@ +.. _overview_sensors_frame_transformer: + +.. currentmodule:: isaaclab + +Frame Transformer +================= + +.. figure:: ../../../_static/overview/sensors/frame_transformer.jpg + :align: center + :figwidth: 100% + :alt: A diagram outlining the basic geometry of frame transformations + +.. + Do YOU want to know where things are relative to other things at a glance? Then the frame transformer is the sensor for you!* + +One of the most common operations that needs to be performed within a physics simulation is the frame transformation: rewriting a vector or quaternion in the basis of an arbitrary euclidean coordinate system. There are many ways to accomplish this within Isaac and USD, but these methods can be cumbersome to implement within Isaac Lab's GPU based simulation and cloned environments. To mitigate this problem, we have designed the Frame Transformer Sensor, that tracks and calculate the relative frame transformations for rigid bodies of interest to the scene. + +The sensory is minimally defined by a source frame and a list of target frames. These definitions take the form of a prim path (for the source) and list of regex capable prim paths the rigid bodies to be tracked (for the targets). + +.. literalinclude:: ../../../../../scripts/demos/sensors/frame_transformer_sensor.py + :language: python + :lines: 38-86 + +We can now run the scene and query the sensor for data + +.. code-block:: python + + def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + . + . + . + # Simulate physics + while simulation_app.is_running(): + . + . + . + + # print information from the sensors + print("-------------------------------") + print(scene["specific_transforms"]) + print("relative transforms:", scene["specific_transforms"].data.target_pos_source) + print("relative orientations:", scene["specific_transforms"].data.target_quat_source) + print("-------------------------------") + print(scene["cube_transform"]) + print("relative transform:", scene["cube_transform"].data.target_pos_source) + print("-------------------------------") + print(scene["robot_transforms"]) + print("relative transforms:", scene["robot_transforms"].data.target_pos_source) + +Let's take a look at the result for tracking specific objects. First, we can take a look at the data coming from the +sensors on the feet + +.. code-block:: bash + + ------------------------------- + FrameTransformer @ '/World/envs/env_.*/Robot/base': + tracked body frames: ['base', 'LF_FOOT', 'RF_FOOT'] + number of envs: 1 + source body frame: base + target frames (count: ['LF_FOOT', 'RF_FOOT']): 2 + + relative transforms: tensor([[[ 0.4658, 0.3085, -0.4840], + [ 0.4487, -0.2959, -0.4828]]], device='cuda:0') + relative orientations: tensor([[[ 0.9623, 0.0072, -0.2717, -0.0020], + [ 0.9639, 0.0052, -0.2663, -0.0014]]], device='cuda:0') + +.. figure:: ../../../_static/overview/sensors/frame_transformer_visualizer.jpg + :align: center + :figwidth: 100% + :alt: The frame transformer visualizer + +By activating the visualizer, we can see that the frames of the feet are rotated "upward" slightly. +We can also see the explicit relative positions and rotations by querying the sensor for data, which +returns these values as a list with the same order as the tracked frames. This becomes even more +apparent if we examine the transforms specified by regex. + +.. code-block:: bash + + ------------------------------- + FrameTransformer @ '/World/envs/env_.*/Robot/base': + tracked body frames: ['base', 'LF_FOOT', 'LF_HIP', 'LF_SHANK', 'LF_THIGH', 'LH_FOOT', 'LH_HIP', 'LH_SHANK', 'LH_THIGH', 'RF_FOOT', 'RF_HIP', 'RF_SHANK', 'RF_THIGH', 'RH_FOOT', 'RH_HIP', 'RH_SHANK', 'RH_THIGH', 'base'] + number of envs: 1 + source body frame: base + target frames (count: ['LF_FOOT', 'LF_HIP', 'LF_SHANK', 'LF_THIGH', 'LH_FOOT', 'LH_HIP', 'LH_SHANK', 'LH_THIGH', 'RF_FOOT', 'RF_HIP', 'RF_SHANK', 'RF_THIGH', 'RH_FOOT', 'RH_HIP', 'RH_SHANK', 'RH_THIGH', 'base']): 17 + + relative transforms: tensor([[[ 4.6581e-01, 3.0846e-01, -4.8398e-01], + [ 2.9990e-01, 1.0400e-01, -1.7062e-09], + [ 2.1409e-01, 2.9177e-01, -2.4214e-01], + [ 3.5980e-01, 1.8780e-01, 1.2608e-03], + [-4.8813e-01, 3.0973e-01, -4.5927e-01], + [-2.9990e-01, 1.0400e-01, 2.7044e-09], + [-2.1495e-01, 2.9264e-01, -2.4198e-01], + [-3.5980e-01, 1.8780e-01, 1.5582e-03], + [ 4.4871e-01, -2.9593e-01, -4.8277e-01], + [ 2.9990e-01, -1.0400e-01, -2.7057e-09], + [ 1.9971e-01, -2.8554e-01, -2.3778e-01], + [ 3.5980e-01, -1.8781e-01, -9.1049e-04], + [-5.0090e-01, -2.9095e-01, -4.5746e-01], + [-2.9990e-01, -1.0400e-01, 6.3592e-09], + [-2.1860e-01, -2.8251e-01, -2.5163e-01], + [-3.5980e-01, -1.8779e-01, -1.8792e-03], + [ 0.0000e+00, 0.0000e+00, 0.0000e+00]]], device='cuda:0') + +Here, the sensor is tracking all rigid body children of ``Robot/base``, but this expression is **inclusive**, meaning that the source body itself is also a target. This can be seen both by examining the source and target list, where ``base`` appears twice, and also in the returned data, where the sensor returns the relative transform to itself, (0, 0, 0). + +.. dropdown:: Code for frame_transformer_sensor.py + :icon: code + + .. literalinclude:: ../../../../../scripts/demos/sensors/frame_transformer_sensor.py + :language: python + :linenos: diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/imu.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/imu.rst new file mode 100644 index 0000000000000000000000000000000000000000..5435bf227f5d0f570410b7aeeac8e1da05c26462 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/imu.rst @@ -0,0 +1,89 @@ +.. _overview_sensors_imu: + +.. currentmodule:: isaaclab + +Inertial Measurement Unit (IMU) +=================================== + +.. figure:: ../../../_static/overview/sensors/imu_diagram.jpg + :align: center + :figwidth: 100% + :alt: A diagram outlining the basic force relationships for the IMU sensor + +Inertial Measurement Units (IMUs) are a type of sensor for measuring the acceleration of an object. These sensors are traditionally designed report linear accelerations and angular velocities, and function on similar principles to that of a digital scale: They report accelerations derived from **net force acting on the sensor**. + +A naive implementation of an IMU would report a negative acceleration due to gravity while the sensor is at rest in some local gravitational field. This is not generally needed for most practical applications, and so most real IMU sensors often include a **gravity bias** and assume that the device is operating on the surface of the Earth. The IMU we provide in Isaac Lab includes a similar bias term, which defaults to +g. This means that if you add an IMU to your simulation, and do not change this bias term, you will detect an acceleration of :math:`+ 9.81 m/s^{2}` anti-parallel to gravity acceleration. + +Consider a simple environment with an Anymal Quadruped equipped with an IMU on each of its two front feet. + +.. literalinclude:: ../../../../../scripts/demos/sensors/imu_sensor.py + :language: python + :lines: 39-63 + +Here we have explicitly removed the bias from one of the sensors, and we can see how this affects the reported values by visualizing the sensor when we run the sample script + +.. figure:: ../../../_static/overview/sensors/imu_visualizer.jpg + :align: center + :figwidth: 100% + :alt: IMU visualized + +Notice that the right front foot explicitly has a bias of (0,0,0). In the visualization, you should see that the arrow indicating the acceleration from the right IMU rapidly changes over time, while the arrow visualizing the left IMU points constantly along the vertical axis. + +Retrieving values form the sensor is done in the usual way + +.. code-block:: python + + def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + . + . + . + # Simulate physics + while simulation_app.is_running(): + . + . + . + # print information from the sensors + print("-------------------------------") + print(scene["imu_LF"]) + print("Received linear velocity: ", scene["imu_LF"].data.lin_vel_b) + print("Received angular velocity: ", scene["imu_LF"].data.ang_vel_b) + print("Received linear acceleration: ", scene["imu_LF"].data.lin_acc_b) + print("Received angular acceleration: ", scene["imu_LF"].data.ang_acc_b) + print("-------------------------------") + print(scene["imu_RF"]) + print("Received linear velocity: ", scene["imu_RF"].data.lin_vel_b) + print("Received angular velocity: ", scene["imu_RF"].data.ang_vel_b) + print("Received linear acceleration: ", scene["imu_RF"].data.lin_acc_b) + print("Received angular acceleration: ", scene["imu_RF"].data.ang_acc_b) + +The oscillations in the values reported by the sensor are a direct result of of how the sensor calculates the acceleration, which is through a finite difference approximation between adjacent ground truth velocity values as reported by the sim. We can see this in the reported result (pay attention to the **linear acceleration**) because the acceleration from the right foot is small, but explicitly zero. + +.. code-block:: bash + + Imu sensor @ '/World/envs/env_.*/Robot/LF_FOOT': + view type : + update period (s) : 0.0 + number of sensors : 1 + + Received linear velocity: tensor([[ 0.0203, -0.0054, 0.0380]], device='cuda:0') + Received angular velocity: tensor([[-0.0104, -0.1189, 0.0080]], device='cuda:0') + Received linear acceleration: tensor([[ 4.8344, -0.0205, 8.5305]], device='cuda:0') + Received angular acceleration: tensor([[-0.0389, -0.0262, -0.0045]], device='cuda:0') + ------------------------------- + Imu sensor @ '/World/envs/env_.*/Robot/RF_FOOT': + view type : + update period (s) : 0.0 + number of sensors : 1 + + Received linear velocity: tensor([[0.0244, 0.0077, 0.0431]], device='cuda:0') + Received angular velocity: tensor([[ 0.0122, -0.1360, -0.0042]], device='cuda:0') + Received linear acceleration: tensor([[-0.0018, 0.0010, -0.0032]], device='cuda:0') + Received angular acceleration: tensor([[-0.0373, -0.0050, -0.0053]], device='cuda:0') + ------------------------------- + +.. dropdown:: Code for imu_sensor.py + :icon: code + + .. literalinclude:: ../../../../../scripts/demos/sensors/imu_sensor.py + :language: python + :linenos: diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/index.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..1ecae8e3ccdfa5764c2ae9277422f4d03c236d03 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/index.rst @@ -0,0 +1,23 @@ +.. _overview_sensors: + +Sensors +========= + +In this section, we will overview the various sensor APIs provided by Isaac Lab. + +Every sensor in Isaac Lab inherits from the ``SensorBase`` abstract class that provides the core functionality inherent to all sensors, which is to provide access to "measurements" of the scene. These measurements can take many forms such as ray-casting results, camera rendered images, or even simply ground truth data queried directly from the simulation (such as poses). Whatever the data may be, we can think of the sensor as having a buffer that is periodically updated with measurements by querying the scene. This ``update_period`` is defined in "simulated" seconds, meaning that even if the flow of time in the simulation is dilated relative to the real world, the sensor will update at the appropriate rate. The ``SensorBase`` is also designed with vectorizability in mind, holding the buffers for all copies of the sensor across cloned environments. + +Updating the buffers is done by overriding the ``_update_buffers_impl`` abstract method of the ``SensorBase`` class. On every time-step of the simulation, ``dt``, all sensors are queried for an update. During this query, the total time since the last update is incremented by ``dt`` for every buffer managed by that particular sensor. If the total time is greater than or equal to the ``update_period`` for a buffer, then that buffer is flagged to be updated on the next query. + +The following pages describe the available sensors in more detail: + +.. toctree:: + :maxdepth: 1 + + camera + contact_sensor + frame_transformer + imu + pva + joint_wrench_sensor + ray_caster diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/joint_wrench_sensor.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/joint_wrench_sensor.rst new file mode 100644 index 0000000000000000000000000000000000000000..d1357645ddc158f6aaec5df4bff493b85d1b4620 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/joint_wrench_sensor.rst @@ -0,0 +1,42 @@ +.. _overview_sensors_joint_wrench: + +.. currentmodule:: isaaclab + +Joint Wrench Sensor +=================== + +The joint wrench sensor reports incoming joint reaction wrenches for selected +articulation bodies. It exposes force [N] and torque [N·m] buffers separately, +with entries ordered by the sensor's :attr:`~isaaclab.sensors.JointWrenchSensor.body_names`. +The default convention is ``incoming_joint_frame``, which expresses each wrench +in the child-side joint frame at the child-side joint anchor. + +The sensor is configured on an articulation prim and can then be used directly +or through manager terms such as :func:`~isaaclab.envs.mdp.body_incoming_wrench`. +For example, the Ant environment adds a joint wrench sensor to the scene: + +.. literalinclude:: ../../../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/ant/ant_env_cfg.py + :language: python + :lines: 91-95 + +The same environment uses :class:`~isaaclab.managers.SceneEntityCfg` to select +the reported foot bodies for an observation term: + +.. literalinclude:: ../../../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/ant/ant_env_cfg.py + :language: python + :lines: 133-142 + +Direct access to the sensor data follows the usual scene lookup pattern. + +.. code-block:: python + + joint_wrench = scene["joint_wrench"] + foot_ids, _ = joint_wrench.find_bodies([".*foot"]) + + force = joint_wrench.data.force.torch[:, foot_ids] + torque = joint_wrench.data.torque.torch[:, foot_ids] + wrench = torch.cat((force, torque), dim=-1) + +The resulting ``wrench`` tensor has shape ``(num_envs, num_selected_bodies, 6)`` +and stores the force components followed by the torque components for each +selected body. diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/pva.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/pva.rst new file mode 100644 index 0000000000000000000000000000000000000000..aa522984bd511ffea107e6f8d105f15d101b901b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/pva.rst @@ -0,0 +1,53 @@ +.. _overview_sensors_pva: + +.. currentmodule:: isaaclab + +Pose Velocity Acceleration (PVA) Sensor +======================================= + +The Pose Velocity Acceleration (PVA) sensor is a ground-truth sensor for reading +the kinematic state of a frame in the simulation. It reports the sensor pose in +the world frame, projected gravity, linear and angular velocities in the sensor +frame, and coordinate accelerations in the sensor frame. Unlike +:class:`~isaaclab.sensors.Imu`, the PVA sensor does not model proper +acceleration from an accelerometer. Use the IMU sensor when the observation +should include accelerometer-like gravity bias behavior. + +The sensor can be attached to a rigid body or to a child prim under a rigid-body +ancestor. If the configured prim is not itself rigid, Isaac Lab queries the +closest rigid ancestor and composes the fixed transform to the requested prim +with the configured sensor offset. + +Consider a simple environment with an Anymal Quadruped equipped with PVA sensors +on its front feet. + +.. literalinclude:: ../../../../../scripts/demos/sensors/pva_sensor.py + :language: python + :lines: 43-59 + +Retrieving values from the sensor follows the same pattern as the other Isaac +Lab sensors. The data fields are exposed as :class:`~isaaclab.utils.warp.ProxyArray` +buffers and can be converted to Torch tensors with the ``torch`` property. + +.. code-block:: python + + pva_data = scene["pva_LF"].data + print("Pose in world frame: ", pva_data.pose_w.torch) + print("Linear velocity in PVA frame: ", pva_data.lin_vel_b.torch) + print("Angular velocity in PVA frame: ", pva_data.ang_vel_b.torch) + print("Linear acceleration in PVA frame: ", pva_data.lin_acc_b.torch) + print("Angular acceleration in PVA frame: ", pva_data.ang_acc_b.torch) + print("Projected gravity in PVA frame: ", pva_data.projected_gravity_b.torch) + +The complete demo can be run with: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/demos/sensors/pva_sensor.py + +.. dropdown:: Code for pva_sensor.py + :icon: code + + .. literalinclude:: ../../../../../scripts/demos/sensors/pva_sensor.py + :language: python + :linenos: diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/ray_caster.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/ray_caster.rst new file mode 100644 index 0000000000000000000000000000000000000000..9b6ce1a313732d4270824c72a41e5f264461842f --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/sensors/ray_caster.rst @@ -0,0 +1,77 @@ +.. _overview_sensors_ray_caster: + +.. currentmodule:: isaaclab + +Ray Caster +============= + +.. figure:: ../../../_static/overview/sensors/raycaster_patterns.jpg + :align: center + :figwidth: 100% + :alt: A diagram outlining the basic geometry of frame transformations + +The Ray Caster sensor (and the ray caster camera) are similar to RTX based rendering in that they both involve casting rays. The difference here is that the rays cast by the Ray Caster sensor return strictly collision information along the cast, and the direction of each individual ray can be specified. They do not bounce, nor are they affected by things like materials or opacity. For each ray specified by the sensor, a line is traced along the path of the ray and the location of first collision with the specified mesh is returned. This is the method used by some of our quadruped examples to measure the local height field. + +To keep the sensor performant when there are many cloned environments, the line tracing is done directly in `Warp `_. This is the reason why specific meshes need to be identified to cast against: that mesh data is loaded onto the device by warp when the sensor is initialized. As a consequence, the current iteration of this sensor only works for literally static meshes (meshes that *are not changed from the defaults specified in their USD file*). This constraint will be removed in future releases. + +Using a ray caster sensor requires a **pattern** and a parent xform to be attached to. The pattern defines how the rays are cast, while the prim properties defines the orientation and position of the sensor (additional offsets can be specified for more exact placement). Isaac Lab supports a number of ray casting pattern configurations, including a generic LIDAR and grid pattern. + +.. literalinclude:: ../../../../../scripts/demos/sensors/raycaster_sensor.py + :language: python + :lines: 40-71 + +Notice that the units on the pattern config is in degrees! Also, we enable visualization here to explicitly show the pattern in the rendering, but this is not required and should be disabled for performance tuning. + +.. figure:: ../../../_static/overview/sensors/raycaster_visualizer.jpg + :align: center + :figwidth: 100% + :alt: Lidar Pattern visualized + +Querying the sensor for data can be done at simulation run time like any other sensor. + +.. code-block:: python + + def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + . + . + . + # Simulate physics + while simulation_app.is_running(): + . + . + . + # print information from the sensors + print("-------------------------------") + print(scene["ray_caster"]) + print("Ray cast hit results: ", scene["ray_caster"].data.ray_hits_w) + + +.. code-block:: bash + + ------------------------------- + Ray-caster @ '/World/envs/env_.*/Robot/base/lidar_cage': + view type : + update period (s) : 0.016666666666666666 + number of meshes : 1 + number of sensors : 1 + number of rays/sensor: 18000 + total number of rays : 18000 + Ray cast hit results: tensor([[[-0.3698, 0.0357, 0.0000], + [-0.3698, 0.0357, 0.0000], + [-0.3698, 0.0357, 0.0000], + ..., + [ inf, inf, inf], + [ inf, inf, inf], + [ inf, inf, inf]]], device='cuda:0') + ------------------------------- + +Here we can see the data returned by the sensor itself. Notice first that there are 3 closed brackets at the beginning and the end: this is because the data returned is batched by the number of sensors. The ray cast pattern itself has also been flattened, and so the dimensions of the array are ``[N, B, 3]`` where ``N`` is the number of sensors, ``B`` is the number of cast rays in the pattern, and 3 is the dimension of the casting space. Finally, notice that the first several values in this casting pattern are the same: this is because the lidar pattern is spherical and we have specified our FOV to be hemispherical, which includes the poles. In this configuration, the "flattening pattern" becomes apparent: the first 180 entries will be the same because it's the bottom pole of this hemisphere, and there will be 180 of them because our horizontal FOV is 180 degrees with a resolution of 1 degree. + +You can use this script to experiment with pattern configurations and build an intuition about how the data is stored by altering the ``triggered`` variable on line 81. + +.. dropdown:: Code for raycaster_sensor.py + :icon: code + + .. literalinclude:: ../../../../../scripts/demos/sensors/raycaster_sensor.py + :language: python + :linenos: diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/task_workflows.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/task_workflows.rst new file mode 100644 index 0000000000000000000000000000000000000000..18bd0f93b66a1b8fb434f03d49f4083f490a716e --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/task_workflows.rst @@ -0,0 +1,118 @@ +.. _feature-workflows: + + +Task Design Workflows +===================== + +.. currentmodule:: isaaclab + +A **Task** is defined by an environment with specific interfaces for observations to and actions from a specific agent (robot). The environment is what provides an agent with the current observations and executes that agent's actions by updating the simulation forward in time. There are many common components of simulating a robot in an environment, regardless of what you might want that robot to do or how it might be trained to do it. + +This is especially true of Reinforcement Learning (RL), where managing the actions, observations, rewards, etc... across a vectorized GPU simulation can be daunting to even think about! To meet this need, Isaac Lab provides the ability to build your RL environments within our **Manager-based** system, allowing you to trust various minutia of the appropriate manager classes. However, we also recognize the need to exert granular control over an environment, especially during development. For this need, we also provide a **Direct** interface into the simulation, giving you full control! + +* **Manager-based**: The environment is decomposed into individual components (or managers) that handle different + aspects of the environment (such as computing observations, applying actions, and applying randomization). The + user defines configuration classes for each component and the environment is responsible for coordinating the + managers and calling their functions. + +* **Direct**: The user defines a single class that implements the entire environment directly without the need for + separate managers. This class is responsible for computing observations, applying actions, and computing rewards. + +Both workflows have their own advantages and disadvantages. The manager-based workflow is more modular and allows +different components of the environment to be swapped out easily. This is useful when prototyping the environment +and experimenting with different configurations. On the other hand, the direct workflow is more efficient and allows +for more fine-grained control over the environment logic. This is useful when optimizing the environment for performance +or when implementing complex logic that is difficult to decompose into separate components. + + +Manager-Based Environments +-------------------------- + +.. image:: ../../_static/task-workflows/manager-based-light.svg + :class: only-light + :align: center + :alt: Manager-based Task Workflow + +.. image:: ../../_static/task-workflows/manager-based-dark.svg + :class: only-dark + :align: center + :alt: Manager-based Task Workflow + +Manager-based environments promote modular implementations of tasks by decomposing it into individually managed components. Each component of the task, such as calculating rewards, observations, etc... can be specified as configurations for a corresponding manager. These managers define configurable functions that are responsible for executing the specific computations as needed. Coordinating a collection of different managers is handled by an Environment class that inherits from :class:`envs.ManagerBasedEnv`. Configurations likewise must all inherit from :class:`envs.ManagerBasedEnvCfg`. + +When developing new training environments, it is often beneficial to break the environment into independent components. This can be highly effective for collaboration, as it lets individual developers focus on different aspects of the environment, while allowing those disparate efforts to be joined back together into a single runnable task. For example, you may have multiple robots with differing sensoriums, requiring different observation managers to process those sensory data into a form that's useful for downstream components. You might have multiple members on the team with different ideas about what the reward should be to achieve your goals, and by having each one develop their own reward manager, you can swap and test as you see fit. The modular nature of the manager workflow is essential for more complex projects! + +For reinforcement learning, much of this has been done for you already! In most cases, it will be enough to write your environment to inherit from +:class:`envs.ManagerBasedRLEnv` and and your configuration from :class:`envs.ManagerBasedRLEnvCfg`. + +.. dropdown:: Example for defining the reward function for the Cartpole task using the manager-style + :icon: plus + + The following class is a part of the Cartpole environment configuration class. The :class:`RewardsCfg` class + defines individual terms that compose the reward function. Each reward term is defined by its function + implementation, weight and additional parameters to be passed to the function. Users can define multiple + reward terms and their weights to be used in the reward function. + + .. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py + :language: python + :pyobject: RewardsCfg + +.. seealso:: + + We provide a more detailed tutorial for setting up an environment using the manager-based workflow at + :ref:`tutorial-create-manager-rl-env`. + + +Direct Environments +------------------- + +.. image:: ../../_static/task-workflows/direct-based-light.svg + :class: only-light + :align: center + :alt: Direct-based Task Workflow + +.. image:: ../../_static/task-workflows/direct-based-dark.svg + :class: only-dark + :align: center + :alt: Direct-based Task Workflow + +The direct-style environment aligns more closely with traditional implementations of environments from other libraries. +A single class implements the reward function, observation function, resets, and all the other components +of the environment. This approach does not require the manager classes. Instead, users are provided the complete freedom +to implement their task through the APIs of either :class:`envs.DirectRLEnv` or :class:`envs.DirectMARLEnv`. All direct task environments must inherit from one of these two classes. +Direct environments still require configurations to be defined, specifically by inheriting from either :class:`envs.DirectRLEnvCfg` or :class:`envs.DirectMARLEnvCfg`. +This workflow may be the most familiar for users migrating from the `IsaacGymEnvs`_ and `OmniIsaacGymEnvs`_ frameworks. + +.. dropdown:: Example for defining the reward function for the Cartpole task using the direct-style + :icon: plus + + The following function is a part of the Cartpole environment class and is responsible for computing the rewards. + + .. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py + :language: python + :pyobject: CartpoleEnv._get_rewards + :dedent: 4 + + It calls the :meth:`compute_rewards` function which is Torch JIT compiled for performance benefits. + + .. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py + :language: python + :pyobject: compute_rewards + +This approach provides more transparency in the implementations of the environments, as logic is defined within the task +class instead of abstracted with the use of managers. This may be beneficial when implementing complex logic that is +difficult to decompose into separate components. Additionally, the direct-style implementation may bring more performance +benefits for the environment, as it allows implementing large chunks of logic with optimized frameworks such as +`PyTorch JIT`_ or `Warp`_. This may be valuable when scaling up training tremendously which requires optimizing individual +operations in the environment. + +.. seealso:: + + We provide a more detailed tutorial for setting up a RL environment using the direct workflow at + :ref:`tutorial-create-direct-rl-env`. + + +.. _IsaacGymEnvs: https://github.com/isaac-sim/IsaacGymEnvs +.. _OmniIsaacGymEnvs: https://github.com/isaac-sim/OmniIsaacGymEnvs +.. _Pytorch JIT: https://pytorch.org/docs/stable/jit.html +.. _Warp: https://github.com/NVIDIA/warp diff --git a/simulation/modules/IsaacLab/docs/source/overview/core-concepts/visualization.rst b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/visualization.rst new file mode 100644 index 0000000000000000000000000000000000000000..defc678e26fc3397506ba4bfe1f8a0a929b42f61 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/core-concepts/visualization.rst @@ -0,0 +1,684 @@ +Visualization +============= + +.. currentmodule:: isaaclab + +Isaac Lab offers several lightweight visualizers for real-time simulation +inspection and debugging. Unlike renderers that process sensor data, +visualizers are meant for fast, interactive feedback. + +Most visualizers can be combined with any physics engine or rendering backend. +The exception is the Kit visualizer with kit-less OV backends: +``--visualizer kit`` cannot be used with ``presets=ovphysx`` or +``ovrtx_renderer`` in the same process. Use ``--visualizer newton``, +``--visualizer rerun``, ``--visualizer viser``, or omit ``--visualizer`` +for headless execution. + + +Overview +-------- + +Isaac Lab supports four visualizer backends, each optimized for different use cases: + +.. list-table:: Visualizer Comparison + :widths: 15 35 50 + :header-rows: 1 + + * - Visualizer + - Best For + - Key Features + * - **Omniverse** + - High-fidelity, Isaac Sim integration + - USD, visualization markers, live plots, tiled camera panel + * - **Newton** + - Fast iteration + - Low overhead, visualization markers, tiled camera panel + * - **Rerun** + - Remote viewing, replay + - Webviewer, time scrubbing, recording export, visualization markers + * - **Viser** + - Web-based remote visualization, sharing, recording + - Warp-based rendering, browser-based, share URL, visualization markers + + +*The following visualizers are shown training the Isaac-Velocity-Flat-Anymal-D-v0 environment.* + +.. figure:: ../../_static/visualizers/ov_viz.jpg + :width: 100% + :alt: Omniverse Visualizer + + Omniverse Visualizer + +.. figure:: ../../_static/visualizers/newton_viz.jpg + :width: 100% + :alt: Newton Visualizer + + Newton Visualizer + +.. figure:: ../../_static/visualizers/rerun_viz.jpg + :width: 100% + :alt: Rerun Visualizer + + Rerun Visualizer + + +Quick Start +----------- + +Launch visualizers from the command line with ``--visualizer`` (or ``--viz`` alias): + +.. code-block:: bash + + # Launch all visualizers (comma-delimited list, no spaces) + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-v0 --viz kit,newton,rerun + + # Launch only the Newton visualizer + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-v0 --viz newton + + # Launch the Viser web-based visualizer + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-v0 --viz viser + + +To run in headless mode, omit the ``--viz`` argument: + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-v0 + +.. note:: + + The ``--headless`` argument is deprecated. + For compatibility, ``--headless`` still takes precedence and disables all visualizers. + + +.. _visualization-configuration: + +Configuration +~~~~~~~~~~~~~ + +Launching visualizers with the command line will use default visualizer configurations. Visualizer backends live in the ``isaaclab_visualizers`` package (e.g. ``source/isaaclab_visualizers/isaaclab_visualizers/kit``, ``newton``, ``rerun``, ``viser``). + +You can also configure custom visualizers in the code by defining ``VisualizerCfg`` instances for the ``SimulationCfg``, for example: + +.. code-block:: python + + from isaaclab.sim import SimulationCfg + from isaaclab_visualizers.kit import KitVisualizerCfg + from isaaclab_visualizers.newton import NewtonVisualizerCfg + from isaaclab_visualizers.rerun import RerunVisualizerCfg + from isaaclab_visualizers.viser import ViserVisualizerCfg + + sim_cfg = SimulationCfg( + visualizer_cfgs=[ + KitVisualizerCfg( + # Omit create_viewport (default False) to use the active viewport; set + # create_viewport=True and optionally viewport_name to add a dedicated window. + eye=(0.0, 0.0, 20.0), # high top down view + lookat=(0.0, 0.0, 0.0), + ), + NewtonVisualizerCfg( + eye=(5.0, 5.0, 5.0), # closer quarter view + lookat=(0.0, 0.0, 0.0), + show_joints=True, + ), + RerunVisualizerCfg( + keep_historical_data=True, + keep_scalar_history=True, + record_to_rrd="my_training.rrd", + ), + ViserVisualizerCfg( + port=8080, + bind_address="0.0.0.0", + display_address="localhost", + share=False, + ), + ] + ) + +Resolution Rules (CLI + Config) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The effective visualizer mode is resolved from both CLI and ``SimulationCfg.visualizer_cfgs``: + +- ``--viz`` (alias: ``--visualizer``) uses comma-separated values (for example ``--viz kit,newton``). +- If ``--viz`` is omitted, Isaac Lab falls back to ``SimulationCfg.visualizer_cfgs`` (see :ref:`visualization-configuration`). +- ``--viz none`` explicitly disables all visualizers. +- If ``--headless`` is passed, it overrides ``--viz`` and disables visualizers. + +For the migration-focused summary and deprecation context, see +:doc:`/source/migration/migrating_to_isaaclab_3-0`. + +Partial Visualization +~~~~~~~~~~~~~~~~~~~~~ + +Visualizers can be configured to visualize just a subset of environments. +This is called partial visualization. + +There are 3 fields exposed in the ``VisualizerCfg`` for selecting environments for partial visualization: + +- ``max_visible_envs`` caps how many envs are shown. +- ``visible_env_indices`` explicitly selects the envs to visualize. +- ``randomly_sample_visible_envs`` (default ``True``): when ``visible_env_indices`` is unset and ``max_visible_envs`` is set, + enables randomly sampling the selected envs. If disabled, the first ``max_visible_envs`` envs are selected. + +Also, there is a CLI arg ``--max_visible_envs`` that overrides ``VisualizerCfg.max_visible_envs`` for the run. + +.. _visualization-common-modes: + +.. list-table:: Common modes + :header-rows: 1 + :widths: 30 35 35 + + * - CLI args + - visualizer configs + - Effective behavior + * - no ``--viz`` + - ``[]`` + - Run headless. + * - ``--viz kit,newton`` + - ``[]`` + - Launch default Kit and default Newton visualizers. + * - ``--viz kit,newton`` + - ``[NewtonVisualizerCfg(...), RerunVisualizerCfg(...)]`` + - Launch default Kit and custom Newton; Rerun is not launched. + * - no ``--viz`` + - ``[NewtonVisualizerCfg(...), RerunVisualizerCfg(...)]`` + - Launch custom Newton and custom Rerun visualizers from config. + * - ``--viz none`` + - ``[NewtonVisualizerCfg(...), RerunVisualizerCfg(...)]`` + - Run headless with all visualizers disabled. + * - ``--headless`` + - any + - Run headless with deprecation warning. + * - ``--headless --viz `` + - any + - Run headless; ``--headless`` takes precedence. + +Camera Modes +~~~~~~~~~~~~ + +To configure camera modes, including launching a tiled camera view, edit the fields described below in the +``VisualizerCfg`` config class. + +For runnable Kit and Newton examples that use generated and existing tiled cameras, +see :doc:`/source/how-to/visualizer_tiled_camera`. + +The default visualizer camera mode is interactive, with ``eye`` and ``lookat`` specifying the initial pose. +Kit and Newton visualizers can also run additional tiled camera image panels. + +If ``tiled_cam_view=True`` is set, another window is launched in the visualizer which shows +a non-interactive tiled camera image view. Number of tiles is capped at 100. + +Note, Kit tiled camera views require launching with ``--enable_cameras``. + +.. list-table:: Camera Modes + :header-rows: 1 + :widths: 24 30 46 + + * - Mode + - Key fields + - Behavior + * - **Default interactive** + - ``tiled_cam_view=False``, ``eye=(4, -4, 3)``, ``lookat=(0, 0, 0)`` + - Interactive visualizer camera starts at ``eye`` and looks at the fixed ``lookat`` coordinate. + * - Generated tiled camera + - ``tiled_cam_view=True``, ``tiled_cam_prim_path=None``, ``tiled_cam_target_prim_path="/World/envs/*/Robot"`` + - The visualizer creates per-env cameras. Each camera looks at the matched target prim, with ``tiled_cam_eye`` as an offset from that target. + Note that the ``tiled_cam_target_prim_path`` has a default value, but different environments may require different paths. + * - Existing tiled camera sensors + - ``tiled_cam_view=True``, ``tiled_cam_prim_path="/World/envs/*/Camera"`` + - The visualizer displays existing Isaac Lab ``Camera`` sensor output. Generated-camera fields such as ``tiled_cam_eye`` and + ``tiled_cam_target_prim_path`` are ignored. Note that the ``tiled_cam_prim_path`` has a default value, but different + environments may require different paths. This mode requires an environment that registers Isaac Lab ``Camera`` sensors + in ``scene.sensors``. For Cartpole, use a camera task such as ``Isaac-Cartpole-Camera-Presets-Direct-v0``. The plain ``Isaac-Cartpole-v0`` + task has no ``/World/envs/*/Camera`` sensor, so leave ``tiled_cam_prim_path=None`` to use generated visualizer cameras. + +**How to Access the Tiled Camera View in the UI** + +- **Kit Visualizer:** + To display the tiled camera panel, select the "Visualizer Tiled Camera" viewport from the viewport selection menu. + +- **Newton Visualizer:** + To enable or disable the tiled camera panel, use the "Visualizer Tiled Camera" option found in the Tiled Camera View dropdown menu on the left sidebar. + + +Video Recording +--------------- + +Video recording is enabled with the ``--video`` flag. When combined with ``--visualizer``, +the visualizer selection also determines which backend captures the video frames: + +- ``--visualizer kit`` enables ``--video`` capture through the Isaac RTX renderer (Omniverse Replicator). +- ``--visualizer newton`` enables ``--video`` capture through the Newton OpenGL renderer. +- ``--visualizer rerun`` does not produce ``--video`` clips; it records Rerun ``.rrd`` data for replay + through the Rerun visualizer. +- ``--visualizer viser`` does not currently provide a ``--video`` recording backend. + +When both Kit and Newton visualizers are active, Isaac Lab records a single ``--video`` stream and +Kit takes precedence. To record from the renderer/physics stack instead of the active visualizer, +set ``VideoRecorderCfg.backend_source = "renderer"`` in the task configuration. + +.. list-table:: ``--video`` compatibility: visualizer × renderer preset + :header-rows: 1 + :widths: 28 36 36 + + * - Renderer preset + - ``--visualizer kit --video`` + - ``--visualizer newton --video`` + * - ``isaacsim_rtx_renderer`` + - ✅ Kit RTX captures video *(default, no change)* + - ✅ Newton GL captures video *(overrides RTX backend)* + * - ``newton_renderer`` + - ✅ Kit RTX captures video *(overrides Newton backend)* + - ✅ Newton GL captures video *(default, no change)* + * - ``ovrtx_renderer`` + - ❌ **Raises an error** — see note below + - ✅ Newton GL captures video; ovrtx provides camera sensor data + +.. note:: + + ``--visualizer kit`` combined with ``ovrtx_renderer`` raises a ``ValueError`` at startup. + Both Kit (Isaac Sim) and ovrtx ship conflicting RTX hydra libraries compiled against + different USD namespaces (``pxrInternal_v0_25_11`` vs ``ovInternal_v0_25_11``), which + causes a dynamic-linker crash when loaded into the same process. + Use ``--visualizer newton`` instead — it is compatible with all renderer presets. + +**Record video with the ovrtx renderer preset** + +.. code-block:: bash + + ./isaaclab.sh -p scripts/benchmarks/benchmark_rsl_rl.py \ + --task=Isaac-Repose-Cube-Shadow-Vision-Direct-v0 \ + --enable_cameras \ + --visualizer newton \ + --video \ + --video_length=300 \ + --video_interval=2000 \ + --max_iterations=5 \ + --num_envs=1024 \ + --benchmark_backend=summary \ + physics=newton_mjwarp renderer=ovrtx_renderer presets=rgb + +**Record video with the Isaac RTX renderer preset using the Newton video backend** + +.. code-block:: bash + + ./isaaclab.sh -p scripts/benchmarks/benchmark_rsl_rl.py \ + --task=Isaac-Repose-Cube-Shadow-Vision-Direct-v0 \ + --enable_cameras \ + --visualizer newton \ + --video \ + --video_length=300 \ + --video_interval=2000 \ + --max_iterations=5 \ + --num_envs=1024 \ + --benchmark_backend=summary \ + physics=physx renderer=isaacsim_rtx_renderer presets=rgb + +**Record video with the Isaac RTX renderer preset using the Kit video backend** + +.. code-block:: bash + + ./isaaclab.sh -p scripts/benchmarks/benchmark_rsl_rl.py \ + --task=Isaac-Repose-Cube-Shadow-Vision-Direct-v0 \ + --enable_cameras \ + --visualizer kit \ + --video \ + --video_length=300 \ + --video_interval=2000 \ + --max_iterations=5 \ + --num_envs=1024 \ + --benchmark_backend=summary \ + physics=physx renderer=isaacsim_rtx_renderer presets=rgb + + +Visualizer Backends +------------------- + +Omniverse Visualizer +~~~~~~~~~~~~~~~~~~~~ + +**Main Features:** + +- Native USD stage integration +- Live plots for monitoring training metrics +- Full Isaac Sim rendering capabilities and tooling +- Visualization markers for debugging (arrows, frames, object targets, etc.) +- Tiled camera views which can track multiple robots + +**Core Configuration:** + +.. code-block:: python + + from isaaclab_visualizers.kit import KitVisualizerCfg + + visualizer_cfg = KitVisualizerCfg( + # Viewport: default is create_viewport=False (use active viewport). + # Set create_viewport=True to create a docked window; viewport_name=None uses the default name. + create_viewport=False, + dock_position="SAME", + window_width=1280, + window_height=720, + + eye=(8.0, 8.0, 3.0), + lookat=(0.0, 0.0, 0.0), + + enable_markers=True, + enable_live_plots=True, + ) + +Newton Visualizer +~~~~~~~~~~~~~~~~~ + +**Main Features:** + +- Lightweight OpenGL rendering with low overhead +- Simulation and rendering pause controls +- Adjustable update frequency for performance tuning +- Some customizable rendering options (shadows, sky, wireframe) +- Visualization markers (joints, contacts, springs, COM, debug markers) +- Tiled camera views which can track multiple robots + + +**Interactive Controls:** + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Key/Input + - Action + * - **W, A, S, D** or **Arrow Keys** + - Forward / Left / Back / Right + * - **Q, E** + - Down / Up + * - **Left Click + Drag** + - Look around + * - **Mouse Scroll** + - Zoom in/out + * - **H** + - Toggle UI sidebar + * - **ESC** + - Exit viewer + +**Core Configuration:** + +.. code-block:: python + + from isaaclab_visualizers.newton import NewtonVisualizerCfg + + visualizer_cfg = NewtonVisualizerCfg( + # Window settings + window_width=1920, # Window width in pixels + window_height=1080, # Window height in pixels + + # Camera settings + eye=(8.0, 8.0, 3.0), # Initial camera position (x, y, z) + lookat=(0.0, 0.0, 0.0), # Camera look-at target + focal_length=12.0, # Camera focal length in millimeters + + # Tiled camera view settings + tiled_cam_view=True, # Enable non-interactive tiled camera image view + tiled_cam_num=16, # Number of generated camera tiles to display + tiled_cam_env_indices=None, # Optional explicit env ids to show in the tiled view + tiled_cam_prim_path=None, # Existing Camera sensor prim path, e.g. "/World/envs/*/Camera" + tiled_cam_eye=(4.0, -4.0, 3.0), # Eye offset for generated tiled cameras + tiled_cam_target_prim_path=( # Prim that generated cameras follow/look at + "/World/envs/*/Robot" # This is the default value, but different environments + ), # may require a different paths. + + # Performance tuning + update_frequency=1, # Update every N frames (1=every frame) + + # Physics debug visualization + show_joints=False, # Show joint visualizations + show_contacts=False, # Show contact points and normals + show_springs=False, # Show spring constraints + show_com=False, # Show center of mass markers + + # Rendering options + enable_shadows=True, # Enable shadow rendering + enable_sky=True, # Enable sky rendering + enable_wireframe=False, # Enable wireframe mode + + # Color customization + background_color=(0.53, 0.81, 0.92), # Sky/background color (RGB [0,1]) + ground_color=(0.18, 0.20, 0.25), # Ground plane color (RGB [0,1]) + light_color=(1.0, 1.0, 1.0), # Directional light color (RGB [0,1]) + ) + + +Rerun Visualizer +~~~~~~~~~~~~~~~~ + +**Main Features:** + +- Web viewer interface accessible from local or remote browser +- Metadata logging and filtering +- Recording to .rrd files for offline replay (.rrd files can be opened with ctrl+O from the web viewer) +- Timeline scrubbing and playback controls of recordings +- Visualization debug markers + +.. important:: + + A highlighted Rerun browser URL is printed in the logs before the main simulation or training loop begins. + Ctrl-click the printed URL in supported terminals/IDEs to open it. Set ``open_browser=True`` to automatically + open the browser tab instead. + + Example: + + .. code-block:: text + + ╭─────────────────────────── rerun (listening *:9090) ───────────────────────────╮ + │ ╷ │ + │ URL │ http://127.0.0.1:9090/?url=rerun%2Bhttp://127.0.0.1:9876/proxy │ + │ ╵ │ + ╰────────────────────────────────────────────────────────────────────────────────╯ + +**Core Configuration:** + +.. code-block:: python + + from isaaclab_visualizers.rerun import RerunVisualizerCfg + + visualizer_cfg = RerunVisualizerCfg( + # Server settings + app_id="isaaclab-simulation", # Application identifier for viewer + grpc_port=9876, # gRPC endpoint for logging SDK connection + web_port=9090, # Port for local web viewer URL printed in logs + bind_address="0.0.0.0", # Endpoint host formatting/reuse checks + open_browser=False, # Set True to auto-launch the browser + + # Camera settings + eye=(8.0, 8.0, 3.0), # Initial camera position (x, y, z) + lookat=(0.0, 0.0, 0.0), # Camera look-at target + + # History settings + keep_historical_data=False, # Keep transforms for time scrubbing + keep_scalar_history=False, # Keep scalar/plot history + + # Recording + record_to_rrd="recording.rrd", # Path to save .rrd file (None = no recording) + ) + +Rerun startup uses the Python SDK through ``newton.viewer.ViewerRerun`` (no external ``rerun`` CLI process +management). If ``grpc_port`` is already active, Isaac Lab reuses that server. If ``web_port`` is occupied while +starting a new server, initialization fails with a clear port-conflict error. + +To save a replay, set ``record_to_rrd`` to the output ``.rrd`` path. Enable +``keep_historical_data`` and ``keep_scalar_history`` when you want transform and scalar history to be available +for timeline scrubbing. After the run, open the Rerun web viewer and press ``Ctrl+O`` to load the saved ``.rrd`` file. + +Note, the timeline UI elements are for .rrd recording playback timeline scrubbing. + +Viser Visualizer +~~~~~~~~~~~~~~~~ + +The `Viser `_ visualizer provides a **web-based** 3D viewer for Isaac Lab +simulations powered by the Newton Warp renderer. It streams the simulation state to a local web +server, allowing you to view and interact with the scene from any browser. + +**Main Features:** + +- Browser-based visualization accessible at ``http://localhost:8080`` by default +- Optional public share URL for remote viewing +- Recording to ``.viser`` format for replay +- Environment filtering to control which environments are rendered +- Visualization debug markers + +.. important:: + + A highlighted Viser browser URL is printed in the logs before the main simulation or training loop begins. + Ctrl-click the printed URL in supported terminals/IDEs to open it. Set ``open_browser=True`` to automatically + open the browser tab instead. For remote access, keep ``bind_address="0.0.0.0"`` and set + ``display_address`` to the hostname or IP address reachable from your browser. + + Example: + + .. code-block:: text + + ╭────── viser (listening *:8080) ───────╮ + │ ╷ │ + │ URL │ http://localhost:8080 │ + │ ╵ │ + ╰───────────────────────────────────────╯ + +**Core Configuration:** + +.. code-block:: python + + from isaaclab_visualizers.viser import ViserVisualizerCfg + + visualizer_cfg = ViserVisualizerCfg( + # Server settings + port=8080, # Port for local Viser web server + bind_address="0.0.0.0", # Interface to listen on; use 0.0.0.0 for remote access + display_address="localhost", # Host/IP shown in the printed browser URL + open_browser=False, # Set True to auto-launch the browser + label="Isaac Lab Simulation", # Page title shown in the viewer + share=False, # Request a public share URL for remote viewing + verbose=True, # Print viewer server startup information + + # Camera settings + eye=(8.0, 8.0, 3.0), # Initial camera position (x, y, z) + lookat=(0.0, 0.0, 0.0), # Camera look-at target + + # Environment filtering + max_visible_envs=16, # Maximum number of environments to visualize + + # Recording + record_to_viser="recording.viser", # Path to save .viser file (None = no recording) + ) + +Viser uses an in-process ``viser.ViserServer`` through ``newton.viewer.ViewerViser``. ``bind_address`` +controls the network interface that the server listens on, while ``display_address`` controls only the +URL printed by Isaac Lab. On a remote machine, set ``display_address`` to the machine hostname/IP and +ensure the configured ``port`` is reachable from your browser. Set ``share=True`` to request Viser's +public share/tunnel URL when that service is available. + +.. note:: + + The Viser visualizer does not currently support live plots. + + +Performance Note +---------------- + +When visualizing large-scale environments, consider: + +- Using Newton instead of Omniverse or Rerun +- Reducing window sizes +- Lower update frequencies +- Pausing visualizers while they are not being used + + +Limitations +----------- + +**Rerun Visualizer Performance** + +The Rerun web-based visualizer may experience performance issues or crashes when visualizing large-scale +environments. For large-scale simulations, the Newton visualizer is recommended. Alternatively, to reduce load, +the num of environments can be overwritten and decreased using ``--num_envs``: + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-v0 --viz rerun --num_envs 512 + + +**Rerun Visualizer FPS Control** + +The FPS control in the Rerun visualizer UI may not affect the visualization frame rate in all configurations. + + +**Live Plots** + +Currently, live plots are only available in the Kit Visualizer. + + +**Newton Contact Visualization** + +Newton's native ``Show Contacts`` view can show all contacts from the Newton physics contact buffer. When running +with PhysX, the Newton visualizer can only show contacts reported by configured Isaac Lab contact sensors, so +currently the set of displayed contacts may differ across backends. + + +**Viser Visualizer Renderer Requirement** + +The Viser visualizer requires a Newton model, which is provided automatically by +:class:`~isaaclab.scene_data.SceneDataProvider` regardless of the active physics +backend or renderer. It is compatible with all rendering backends (RTX, Newton Warp, OVRTX). + + +**Newton Visualizer CUDA/OpenGL Interoperability Warnings** + +On some system configurations, the Newton visualizer may display warnings about CUDA/OpenGL interoperability: + +.. code-block:: text + + Warning: Could not get MSAA config, falling back to non-AA. + Warp CUDA error 999: unknown error (in function wp_cuda_graphics_register_gl_buffer) + Warp UserWarning: Could not register GL buffer since CUDA/OpenGL interoperability + is not available. Falling back to copy operations between the Warp array and the + OpenGL buffer. + +The visualizer will still function correctly but may experience reduced performance due to falling back to +CPU copy operations instead of direct GPU memory sharing. + + +**Newton Visualizer OpenGL Context Failures** + +The Newton visualizer is an OpenGL window. If pyglet reports that +``glCreateShader`` is not exported or that OpenGL 2.0 is required, the Python +process did not receive a usable OpenGL 2.0+ context from the active Windows or +Linux display session. This usually means the process is running in a +non-interactive/service session, through a remote desktop path without GPU +OpenGL acceleration, or with a software/basic OpenGL provider instead of the +NVIDIA driver. Run from a GPU-backed interactive display session, or omit +``--visualizer newton`` for headless inference. + + +**Newton Visualizer on Spark with Conda** + +When running the Newton visualizer on Spark inside a conda environment, conda-installed X11 libraries +may conflict with the system libraries required by pyglet, causing the following error: + +.. code-block:: text + + pyglet.window.xlib.XlibException: Could not create UTF8 text property + +To resolve this, remove the conflicting conda packages so that the system-provided libraries are used +instead: + +.. code-block:: bash + + conda remove --force xorg-libx11 libxcb + + +See Also +-------- + +- :doc:`/source/overview/core-concepts/renderers` — renderer backends (RTX, Newton Warp, OVRTX) +- :doc:`/source/overview/core-concepts/scene_data_providers` — how scene data flows from physics to visualizers +- :doc:`/source/overview/core-concepts/physical-backends/newton/index` — Newton backend guide +- :doc:`/source/migration/migrating_to_isaaclab_3-0` — migration guide with ``--headless`` deprecation details diff --git a/simulation/modules/IsaacLab/docs/source/overview/developer-guide/development.rst b/simulation/modules/IsaacLab/docs/source/overview/developer-guide/development.rst new file mode 100644 index 0000000000000000000000000000000000000000..2f789ac01acd14e32f8ab1a366ff6cad739e5e4c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/developer-guide/development.rst @@ -0,0 +1,179 @@ +Extension Development +======================= + +Everything in Omniverse is either an extension or a collection of extensions (an application). They are +modularized packages that form the atoms of 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 `__. + +Each extension in Isaac Lab is written as a python package and follows the following structure: + +.. code:: bash + + + ├── config + │   └── extension.toml + ├── docs + │   ├── CHANGELOG.md + │   └── README.md + ├── + │ ├── __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 the Omniverse API 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 ```` directory contains the main python package for the extension. +It may also contain the ``scripts`` directory for keeping python-based applications +that are loaded into Omniverse when the extension is enabled using the +`Extension Manager `__. + +More specifically, when an extension is enabled, the python module specified in the +``config/extension.toml`` file is loaded and scripts that contain 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 +avoid the need to understand the `premake `__ +build system used by Omniverse, we directly use the `setuptools `__ +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 `__. + +Lastly, the ``tests`` directory contains the unit tests for the extension. These are written +using the `unittest `__ framework. It is +important to note that Omniverse also provides a similar +`testing framework `__. +However, it requires going through the build process and does not support testing of the python module in +standalone applications. + +Custom Extension Dependency Management +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Certain extensions may have dependencies which require the installation of additional packages before the extension +can be used. Python dependencies are handled by the `setuptools `__ +package and specified in the ``setup.py`` file. Non-Python dependencies such as +`ROS `__ packages or `apt `__ +packages are not handled by setuptools. Handling these kinds of dependencies requires an additional procedure. + +There are three types of dependencies that can be specified in the ``extension.toml`` file +under the ``isaac_lab_settings`` section: + +1. **apt_deps**: A list of apt packages that need to be installed. These are installed using the + `apt `__ package manager. +2. **ros_ws**: The path to the ROS workspace that contains the ROS packages. These are installed using + the `rosdep `__ dependency manager. +3. **pip_upgrade_dependencies**: A list of ``install_requires`` dependency names that should be explicitly + upgraded after installing the extension with ``./isaaclab.sh --install``. List package names only. Version + ranges, extras, and platform markers are read from the installed extension metadata generated from ``setup.py``. + +As an example, the following ``extension.toml`` file specifies the dependencies for the extension: + +.. code-block:: toml + + [isaac_lab_settings] + # apt dependencies + apt_deps = ["libboost-all-dev"] + + # ROS workspace + # note: if this path is relative, it is relative to the extension directory's root + ros_ws = "/home/user/catkin_ws" + + # Python dependency names to upgrade after installing this extension + pip_upgrade_dependencies = ["example_package"] + +The ``apt_deps`` and ``ros_ws`` dependencies are installed using the ``install_deps.py`` script provided in the +``tools`` directory. To install all apt and ROS dependencies for all extensions, run the following command: + +.. code-block:: bash + + # execute from the root of the repository + # the script expects the type of dependencies to install and the path to the extensions directory + # available types are: 'apt', 'rosdep' and 'all' + python tools/install_deps.py all ${ISAACLAB_PATH}/source + +.. note:: + Currently, this script is automatically executed during the build process of the ``Dockerfile.base`` + and ``Dockerfile.ros2``. This ensures that all the 'apt' and 'rosdep' dependencies are installed + before building the extensions respectively. + +The ``pip_upgrade_dependencies`` entries are handled by ``./isaaclab.sh --install`` after the extension's editable +pip install completes. + + +Standalone applications +~~~~~~~~~~~~~~~~~~~~~~~ + +In a typical Omniverse workflow, the simulator is launched first and then the extensions are +enabled. The loading of python modules and other python applications happens automagically, under the hood, and while this is the recommended +workflow, it is not always possible. + +For example, consider robot reinforcement learning. It is essential to have complete control over the simulation step +and when things update instead of asynchronously waiting for the result. In +such cases, we require direct control of the simulation, and so it is necessary to write a standalone application. These applications are functionally similar in that they launch the simulator using the :class:`~isaaclab.app.AppLauncher` and +then control the simulation directly through the :class:`~isaaclab.sim.SimulationContext`. In these cases, python modules from extensions **must** be imported after the app is launched. Doing so before the app is launched will cause missing module errors. + +The following snippet shows how to write a standalone application: + +.. code:: python + + """Launch Isaac Sim Simulator first.""" + + from isaaclab.app import AppLauncher + + # launch omniverse app + app_launcher = AppLauncher(headless=False) + simulation_app = app_launcher.app + + + """Rest everything follows.""" + + from isaaclab.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() + + +It is necessary to launch the simulator before running any other code because extensions are hot-loaded +when the simulator starts. Many Omniverse modules become available only after the simulator is launched. +For further details, we recommend exploring the Isaac Lab :ref:`tutorials`. diff --git a/simulation/modules/IsaacLab/docs/source/overview/developer-guide/index.rst b/simulation/modules/IsaacLab/docs/source/overview/developer-guide/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..59f603fbfad2361551328a2821a307a693fb34d7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/developer-guide/index.rst @@ -0,0 +1,15 @@ +Developer's Guide +================= + +For development, we suggest using `Microsoft Visual Studio Code +(VSCode) `__. This is also suggested by +NVIDIA Omniverse and there exists tutorials on how to `debug Omniverse +extensions `__ +using VSCode. + +.. toctree:: + :maxdepth: 1 + + VS Code + repo_structure + development diff --git a/simulation/modules/IsaacLab/docs/source/overview/developer-guide/repo_structure.rst b/simulation/modules/IsaacLab/docs/source/overview/developer-guide/repo_structure.rst new file mode 100644 index 0000000000000000000000000000000000000000..92fd0f90dcddf76c438c8941bbca67011a983386 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/developer-guide/repo_structure.rst @@ -0,0 +1,127 @@ +Repository organization +----------------------- + +.. code-block:: bash + + IsaacLab + ├── .vscode + ├── CONTRIBUTING.md + ├── CONTRIBUTORS.md + ├── LICENSE + ├── isaaclab.bat + ├── isaaclab.sh + ├── pyproject.toml + ├── README.md + ├── docs + ├── docker + ├── source + │ ├── isaaclab # core framework + │ ├── isaaclab_physx # PhysX backend (requires Isaac Sim) + │ ├── isaaclab_ovphysx # standalone PhysX backend (requires ovphysx) + │ ├── isaaclab_ov # OVRTX renderer backend (requires ovrtx) + │ ├── isaaclab_newton # Newton backend (kit-less) + │ ├── isaaclab_assets # pre-configured robot & sensor assets + │ ├── isaaclab_tasks # pre-built RL/IL environments + │ ├── isaaclab_tasks_experimental # Warp-accelerated environments + │ ├── isaaclab_rl # RL library wrappers + │ ├── isaaclab_mimic # imitation learning & data generation + │ ├── isaaclab_teleop # teleoperation & XR + │ ├── isaaclab_visualizers # external visualizer backends + │ ├── isaaclab_contrib # community-contributed extensions + │ ├── isaaclab_experimental # Warp-accelerated manager and environment variants + │ ├── extensions # legacy Omniverse extension wrappers + │ └── standalone # standalone tutorials & workflows + ├── scripts + │ ├── benchmarks + │ ├── demos + │ ├── environments + │ ├── imitation_learning + │ ├── reinforcement_learning + │ ├── sim2sim_transfer + │ ├── tools + │ └── tutorials + ├── tools + └── VERSION + +Isaac Lab supports the **PhysX** and **Newton** physics engines through backend packages. The +default PhysX path runs through Isaac Sim, while ``ovphysx`` supports standalone PhysX workflows +without launching Isaac Sim and Newton provides a Warp-native kit-less backend. The ``source`` +directory contains all packages that compose Isaac Lab, while ``scripts`` contains standalone +Python applications for training, evaluation, and tooling. +See :doc:`/source/overview/core-concepts/multi_backend_architecture` for details on the backend +system, and :doc:`/source/setup/ecosystem` for a full package-layer overview. + +Submodules +~~~~~~~~~~ + +The packages under ``source/`` are installed as Python packages using +`setuptools `__. They are organized into three +groups: + +**Core, physics backends, and renderers** + +* **isaaclab**: The core framework. Provides :mod:`~isaaclab.sim` (simulation context and + configuration), :class:`~isaaclab.scene.InteractiveScene`, asset and sensor base classes and + factory interfaces (:mod:`~isaaclab.assets`, :mod:`~isaaclab.sensors`), environment base + classes (:mod:`~isaaclab.envs`), the manager system (:mod:`~isaaclab.managers`), composable + MDP term library (:mod:`~isaaclab.envs.mdp`), actuator models (:mod:`~isaaclab.actuators`), + low-level controllers (:mod:`~isaaclab.controllers`), procedural terrain generation + (:mod:`~isaaclab.terrains`), and human-input device support (:mod:`~isaaclab.devices`). +* **isaaclab_physx**: PhysX-backed implementations of articulations, rigid bodies, deformable + objects, Fabric views, the Isaac RTX renderer, and USD spawners. Requires Isaac Sim. +* **isaaclab_ovphysx**: Standalone PhysX backend variant using ``ovphysx`` and the + TensorBindingsAPI. Requires the ``ovphysx`` package and can run without launching Isaac Sim. +* **isaaclab_ov**: OVRTX renderer backend for RTX-based tiled camera rendering. Requires the + ``ovrtx`` package and can run without Isaac Sim. +* **isaaclab_newton**: Newton-backed implementations of articulations, rigid bodies, rigid + object collections, cameras, USD spawners, and the Warp renderer. Supports + :ref:`kit-less installation ` without Isaac Sim. + +**Tasks and assets** + +* **isaaclab_assets**: Pre-configured :class:`~isaaclab.utils.configclass` dataclasses for a + wide range of robots (Franka, Unitree, ANYmal, Spot, Allegro, humanoids, quadcopters, and + more) and sensors (Velodyne, GelSight). +* **isaaclab_tasks**: Registered `gymnasium `__ environments for + reinforcement and imitation learning, organized as *manager-based* and *direct* tasks across + locomotion, manipulation, navigation, and classic control domains. +* **isaaclab_tasks_experimental**: Experimental task implementations under active development, + not yet part of the stable task suite. + +**Optional Additions** + +* **isaaclab_rl**: Thin wrappers that adapt Isaac Lab environments to the interfaces expected + by `RSL-RL `__, + `skrl `__, + `Stable Baselines 3 `__, and + `RL Games `__. +* **isaaclab_mimic**: APIs and pre-configured environments for data generation and imitation + learning, including cuRobo-based motion planners and a dataset-generation pipeline. +* **isaaclab_teleop**: Teleoperation session orchestration with OpenXR / CloudXR support, + device retargeters for manipulators and humanoids, and gamepad / spacemouse / keyboard input. +* **isaaclab_visualizers**: Supplementary visualizer backends (Isaac Sim Kit, Newton, Rerun, Viser) that + work with any physics backend. +* **isaaclab_contrib**: Community-contributed features: multirotor assets, TacSL + visuo-tactile sensors, drone thrust controllers, and more. +* **isaaclab_experimental**: Pre-production core experiments including Warp-accelerated manager + and environment variants. + + +Standalone +~~~~~~~~~~ + +The ``scripts`` directory contains standalone Python applications. +They are structured as follows: + +* **benchmarks**: Scripts for benchmarking different framework components. +* **demos**: Demo applications that showcase the core framework :mod:`isaaclab`. +* **environments**: Scripts for running environments defined in :mod:`isaaclab_tasks` with + different agents (random policy, zero-action policy, teleoperation, scripted state machines). +* **imitation_learning**: Applications for training and evaluating policies with imitation + learning libraries (e.g. robomimic). +* **reinforcement_learning**: Applications for training and evaluating policies with RL + libraries (e.g. rsl_rl, rl_games, sb3, skrl). +* **sim2sim_transfer**: Scripts for transferring policies trained in one simulator to another. +* **tools**: Applications for using framework tools such as converting assets and generating + datasets. +* **tutorials**: Step-by-step tutorials for using the APIs provided by the framework. diff --git a/simulation/modules/IsaacLab/docs/source/overview/developer-guide/vs_code.rst b/simulation/modules/IsaacLab/docs/source/overview/developer-guide/vs_code.rst new file mode 100644 index 0000000000000000000000000000000000000000..11946a71c7695d6c202b05a8c5a3b4ec93d807a3 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/developer-guide/vs_code.rst @@ -0,0 +1,111 @@ +.. _setup-vs-code: + +Setting up Visual Studio Code +----------------------------- + +**This is optional. You do not need to use VScode to use Isaac Lab** + +`Visual Studio Code `_ has proven an invaluable tool for the development of Isaac Lab. The Isaac Lab repository includes the VSCode files for 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 + + +.. attention:: + + The following instructions on setting up Visual Studio Code only work with + :ref:`Isaac Sim Binaries Installation ` and not with + :ref:`Pip Installation `. + + +To setup the IDE, please follow these instructions: + +1. Open the ``IsaacLab`` 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. + + .. image:: ../../_static/vscode_tasks.png + :width: 600px + :align: center + :alt: VSCode Tasks + + +.. note:: + If this is your first time running tasks in VS Code, you may be prompted to select how to handle warnings. Simply follow + the prompts until the task window closes. + +If everything executes correctly, it should create the following files: + +* ``.vscode/launch.json``: Contains the launch configurations for debugging python code. +* ``.vscode/settings.json``: Contains the settings for the python interpreter and the python environment. + +For more information on VSCode support for Omniverse, please refer to the +following links: + +* `Isaac Sim VSCode support `__ + + +Attach to a Running ``debugpy`` Session +--------------------------------------- + +The generated ``.vscode/launch.json`` includes a ``Python: Debugger Attach`` +configuration that starts to listen on port ``localhost:3000`` for the debugpy session. + +To use it: + +1. Set your breakpoints. +2. Run your code under debugpy like so: + + .. code-block:: bash + + ./isaaclab.sh -p -m debugpy --listen 3000 --wait-for-client -c "from isaaclab.cli import cli; cli()" [cli_args] + +3. In VS Code, select the ``Python: Debugger Attach`` configuration from the Run and Debug panel + and press the green play button or ``F5``. VS Code will connect to the debugpy server + running on ``localhost:3000``. + +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/python.sh", + } + +If you want to use a different python interpreter (for instance, from your conda or uv 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 `_. + + +Setting up formatting and linting +--------------------------------- + +We use `ruff `_ as a formatter and linter. +These are configured in the ``.vscode/settings.json`` file: + +.. code-block:: json + + { + "ruff.configuration": "${workspaceFolder}/pyproject.toml", + } + +The ruff linter will show warnings and errors in your code to help you follow Python best practices and the project's coding standards. diff --git a/simulation/modules/IsaacLab/docs/source/overview/environments.rst b/simulation/modules/IsaacLab/docs/source/overview/environments.rst new file mode 100644 index 0000000000000000000000000000000000000000..a5326519f4f9ffdba9217d9aa75415e815176e44 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/environments.rst @@ -0,0 +1,1701 @@ +.. _environments: + +Available Environments +====================== + +The following lists comprises of all the RL and IL tasks implementations that are available in Isaac Lab. +While we try to keep this list up-to-date, you can always get the latest list of environments by +running the following command: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. note:: + Use ``--keyword `` (optional) to filter environments by keyword. + + .. code:: bash + + ./isaaclab.sh -p scripts/environments/list_envs.py --keyword + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. note:: + Use ``--keyword `` (optional) to filter environments by keyword. + + .. code:: batch + + isaaclab.bat -p scripts\environments\list_envs.py --keyword + + +To also see the available presets for each environment, pass ``--show_presets``: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/environments/list_envs.py --show_presets + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\environments\list_envs.py --show_presets + + +The **RL Library** and **Presets** columns in the :ref:`comprehensive-environment-list` below are +generated automatically from the Gym registry. + +We are actively working on adding more environments to the list. If you have any environments that +you would like to add to Isaac Lab, please feel free to open a pull request! + + +Preset Selectors +---------------- + +Many environments support multiple physics backends, rendering backends, and observation +modes. The **Presets** column in each table below is divided into three labeled groups: + +* **physics=** — physics-backend name passed as ``physics=NAME`` + (e.g. ``physx``, ``newton_mjwarp``, ``newton_kamino``, ``ovphysx``, + ``newton_mjwarp_vbd``) +* **renderer=** — renderer-backend name passed as ``renderer=NAME`` + (e.g. ``isaacsim_rtx_renderer``, ``newton_renderer``, ``ovrtx_renderer``) +* **presets=** — environment-specific (domain) preset name passed as + ``presets=NAME[,NAME,...]`` + (e.g. ``rgb``, ``depth``, ``single_camera``, ``duo_camera``) + +Pass ``--task= --help`` to a training script to see all available +preset names grouped by selector type at the command line, or run +``./isaaclab.sh -p scripts/environments/list_envs.py --show_presets`` +to list presets for every registered environment. + +See :doc:`/source/features/hydra` for the full preset system documentation, +including all available backend names and how the typed selectors work. + + +Single-agent +------------ + +Classic +~~~~~~~ + +Classic environments that are based on IsaacGymEnvs implementation of MuJoCo-style environments. + +.. table:: + :widths: 25 30 25 20 + + +------------------+-----------------------------+-------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +==================+=============================+=========================================================================+==============================+ + | |humanoid| | |humanoid-link| | Move towards a direction with the MuJoCo humanoid robot | **physics=** | + | | | | ``physx``, | + | | |humanoid-direct-link| | | ``newton_mjwarp``, | + | | | | ``ovphysx`` (direct only) | + +------------------+-----------------------------+-------------------------------------------------------------------------+------------------------------+ + | |ant| | |ant-link| | Move towards a direction with the MuJoCo ant robot | **physics=** | + | | | | ``physx``, | + | | |ant-direct-link| | | ``newton_mjwarp``, | + | | | | ``newton_kamino``, | + | | | | ``ovphysx`` (direct only) | + +------------------+-----------------------------+-------------------------------------------------------------------------+------------------------------+ + | |cartpole| | |cartpole-link| | Move the cart to keep the pole upwards in the classic cartpole control | **physics=** | + | | | | ``physx``, | + | | |cartpole-direct-link| | | ``newton_mjwarp``, | + | | | | ``newton_kamino``, | + | | | | ``ovphysx`` (direct only) | + +------------------+-----------------------------+-------------------------------------------------------------------------+------------------------------+ + | |cartpole| | |cartpole-camera-presets| | Move the cart to keep the pole upwards in the classic cartpole control | **physics=** | + | | | and perceptive inputs. Select data type via ``presets=``. Requires | ``physx``, | + | | | running with ``--enable_cameras``. | ``newton_mjwarp``, | + | | | | ``ovphysx`` (direct only) | + | | | | **renderer=** | + | | | | ``isaacsim_rtx_renderer``, | + | | | | ``newton_renderer``, | + | | | | ``ovrtx_renderer`` | + | | | | **presets=** ``rgb``, | + | | | | ``depth``, ``albedo``, | + | | | | ``semantic_segmentation``, | + | | | | ``simple_shading_*`` | + +------------------+-----------------------------+-------------------------------------------------------------------------+------------------------------+ + | |cartpole| | |cartpole-resnet-link| | Move the cart to keep the pole upwards in the classic cartpole control | **physics=** | + | | | based off of features extracted from perceptive inputs with pre-trained | ``physx``, | + | | |cartpole-theia-link| | frozen vision encoders. Requires running with ``--enable_cameras``. | ``newton_mjwarp`` | + +------------------+-----------------------------+-------------------------------------------------------------------------+------------------------------+ + +.. |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 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/humanoid/humanoid_env_cfg.py>`__ +.. |ant-link| replace:: `Isaac-Ant-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/ant/ant_env_cfg.py>`__ +.. |cartpole-link| replace:: `Isaac-Cartpole-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py>`__ +.. |cartpole-camera-presets| replace:: `Isaac-Cartpole-Camera-Presets-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_presets_env_cfg.py>`__ +.. |cartpole-resnet-link| replace:: `Isaac-Cartpole-RGB-ResNet18-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_camera_env_cfg.py>`__ +.. |cartpole-theia-link| replace:: `Isaac-Cartpole-RGB-TheiaTiny-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_camera_env_cfg.py>`__ + + +.. |humanoid-direct-link| replace:: `Isaac-Humanoid-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/humanoid/humanoid_env.py>`__ +.. |ant-direct-link| replace:: `Isaac-Ant-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/ant/ant_env.py>`__ +.. |cartpole-direct-link| replace:: `Isaac-Cartpole-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py>`__ + +Manipulation +~~~~~~~~~~~~ + +Environments based on fixed-arm manipulation tasks. + +For many of these tasks, we include configurations with different arm action spaces. For example, +for the lift-cube 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: 25 30 25 20 + + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +=========================+==============================+=============================================================================+==============================+ + | |reach-franka| | |reach-franka-link| | Move the end-effector to a sampled target pose with the Franka robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |reach-ur10| | |reach-ur10-link| | Move the end-effector to a sampled target pose with the UR10 robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |deploy-reach-ur10e| | |deploy-reach-ur10e-link| | Move the end-effector to a sampled target pose with the UR10e robot | | + | | | This policy has been deployed to a real robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |lift-cube| | |lift-cube-link| | Pick a cube and bring it to a sampled target position with the Franka robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |lift-soft-franka| | |lift-soft-franka-link| | Pick a deformable soft body and bring it to a sampled target position with | **physics=** ``physx``, | + | | | the Franka robot | ``newton_mjwarp_vbd`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |stack-cube| | |stack-cube-link| | Stack three cubes (bottom to top: blue, red, green) with the Franka robot. | | + | | | Blueprint env used for the NVIDIA Isaac GR00T blueprint for synthetic | | + | | |stack-cube-bp-link| | manipulation motion generation | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |surface-gripper| | |long-suction-link| | Stack three cubes (bottom to top: blue, red, green) | | + | | | with the UR10 arm and long surface gripper | | + | | |short-suction-link| | or short surface gripper (cpu only). | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |cabi-franka| | |cabi-franka-link| | Grasp the handle of a cabinet's drawer and open it with the Franka robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + | | |franka-direct-link| | | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |cube-allegro| | |cube-allegro-link| | In-hand reorientation of a cube using Allegro hand | **physics=** ``physx``, | + | | | | ``newton_mjwarp``, | + | | |allegro-direct-link| | | ``ovphysx`` (direct only) | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |cube-shadow| | |cube-shadow-link| | In-hand reorientation of a cube using Shadow hand | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + | | |cube-shadow-ff-link| | | | + | | | | | + | | |cube-shadow-lstm-link| | | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |cube-shadow| | |cube-shadow-vis-link| | In-hand reorientation of a cube using Shadow hand using perceptive inputs. | **physics=** ``physx``, | + | | | Requires running with ``--enable_cameras``. | ``newton_mjwarp`` | + | | | | **renderer=** | + | | | | ``isaacsim_rtx_renderer``, | + | | | | ``newton_renderer``, | + | | | | ``ovrtx_renderer`` | + | | | | **presets=** ``rgb``, | + | | | | ``depth``, ``albedo``, | + | | | | ``full``, | + | | | | ``semantic_segmentation``, | + | | | | ``simple_shading_*`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |gr1_pick_place| | |gr1_pick_place-link| | Pick up and place an object in a basket with a GR-1 humanoid robot | **physics=** ``physx`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |gr1_pp_waist| | |gr1_pp_waist-link| | Pick up and place an object in a basket with a GR-1 humanoid robot | **physics=** ``physx`` | + | | | with waist degrees-of-freedom enables that provides a wider reach space. | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |g1_pick_place| | |g1_pick_place-link| | Pick up and place an object in a basket with a Unitree G1 humanoid robot | **physics=** ``physx`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |g1_pick_place_fixed| | |g1_pick_place_fixed-link| | Pick up and place an object in a basket with a Unitree G1 humanoid robot | **physics=** ``physx`` | + | | | with three-fingered hands. Robot is set up with the base fixed in place. | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |g1_pick_place_lm| | |g1_pick_place_lm-link| | Pick up and place an object in a basket with a Unitree G1 humanoid robot | **physics=** ``physx`` | + | | | with three-fingered hands and in-place locomanipulation capabilities | | + | | | enabled (i.e. Robot lower body balances in-place while upper body is | | + | | | controlled via Inverse Kinematics). | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |kuka-allegro-lift| | |kuka-allegro-lift-link| | Pick up a primitive shape on the table and lift it to target position. | **physics=** ``physx``, | + | | | Supports state, single-camera, and dual-camera observation modes via | ``newton_mjwarp`` | + | | | ``presets=single_camera`` / ``presets=duo_camera`` (see RL table below). | **renderer=** | + | | | | ``isaacsim_rtx_renderer``, | + | | | | ``newton_renderer``, | + | | | | ``ovrtx_renderer`` | + | | | | **presets=** ``state``, | + | | | | ``single_camera``, | + | | | | ``duo_camera``, | + | | | | ``rgb{64,128,256}``, | + | | | | ``depth/albedo{..}``, | + | | | | ``simple_shading_*{..}`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |kuka-allegro-reorient| | |kuka-allegro-reorient-link| | Pick up a primitive shape on the table and orient it to target pose. | **physics=** ``physx``, | + | | | Supports state, single-camera, and dual-camera observation modes via | ``newton_mjwarp`` | + | | | ``presets=single_camera`` / ``presets=duo_camera`` (see RL table below). | **renderer=** | + | | | | ``isaacsim_rtx_renderer``, | + | | | | ``newton_renderer``, | + | | | | ``ovrtx_renderer`` | + | | | | **presets=** ``state``, | + | | | | ``single_camera``, | + | | | | ``duo_camera``, | + | | | | ``rgb{64,128,256}``, | + | | | | ``depth/albedo{..}``, | + | | | | ``simple_shading_*{..}`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |galbot_stack| | |galbot_stack-link| | Stack three cubes (bottom to top: blue, red, green) with the left arm of | **physics=** ``physx`` | + | | | a Galbot humanoid robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |agibot_place_mug| | |agibot_place_mug-link| | Pick up and place a mug upright with a Agibot A2D humanoid robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |agibot_place_toy| | |agibot_place_toy-link| | Pick up and place an object in a box with a Agibot A2D humanoid robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |reach_openarm_bi| | |reach_openarm_bi-link| | Move the end-effector to sampled target poses with the OpenArm robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |reach_openarm_uni| | |reach_openarm_uni-link| | Move the end-effector to a sampled target pose with the OpenArm robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |lift_openarm_uni| | |lift_openarm_uni-link| | Pick a cube and bring it to a sampled target position with the OpenArm robot| | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |cabi_openarm_uni| | |cabi_openarm_uni-link| | Grasp the handle of a cabinet's drawer and open it with the OpenArm robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |g1_assemble_trocar| | |g1_assemble_trocar-link| | Assemble trocar with a Unitree G1 humanoid robot with Dex3 hands | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + +.. |reach-franka| image:: ../_static/tasks/manipulation/franka_reach.jpg +.. |reach-ur10| image:: ../_static/tasks/manipulation/ur10_reach.jpg +.. |deploy-reach-ur10e| image:: ../_static/tasks/manipulation/ur10e_reach.jpg +.. |lift-cube| image:: ../_static/tasks/manipulation/franka_lift.jpg +.. |lift-soft-franka| image:: ../_static/newton/franka-mjwarp-vbd-coupling.png +.. |cabi-franka| image:: ../_static/tasks/manipulation/franka_open_drawer.jpg +.. |cube-allegro| image:: ../_static/tasks/manipulation/allegro_cube.jpg +.. |cube-shadow| image:: ../_static/tasks/manipulation/shadow_cube.jpg +.. |stack-cube| image:: ../_static/tasks/manipulation/franka_stack.jpg +.. |gr1_pick_place| image:: ../_static/tasks/manipulation/gr-1_pick_place.jpg +.. |g1_pick_place| image:: ../_static/tasks/manipulation/g1_pick_place.jpg +.. |g1_pick_place_fixed| image:: ../_static/tasks/manipulation/g1_pick_place_fixed_base.jpg +.. |g1_pick_place_lm| image:: ../_static/tasks/manipulation/g1_pick_place_locomanipulation.jpg +.. |surface-gripper| image:: ../_static/tasks/manipulation/ur10_stack_surface_gripper.jpg +.. |gr1_pp_waist| image:: ../_static/tasks/manipulation/gr-1_pick_place_waist.jpg +.. |galbot_stack| image:: ../_static/tasks/manipulation/galbot_stack_cube.jpg +.. |agibot_place_mug| image:: ../_static/tasks/manipulation/agibot_place_mug.jpg +.. |agibot_place_toy| image:: ../_static/tasks/manipulation/agibot_place_toy.jpg +.. |kuka-allegro-lift| image:: ../_static/tasks/manipulation/kuka_allegro_lift.jpg +.. |kuka-allegro-reorient| image:: ../_static/tasks/manipulation/kuka_allegro_reorient.jpg +.. |reach_openarm_bi| image:: ../_static/tasks/manipulation/openarm_bi_reach.jpg +.. |reach_openarm_uni| image:: ../_static/tasks/manipulation/openarm_uni_reach.jpg +.. |lift_openarm_uni| image:: ../_static/tasks/manipulation/openarm_uni_lift.jpg +.. |cabi_openarm_uni| image:: ../_static/tasks/manipulation/openarm_uni_open_drawer.jpg +.. |g1_assemble_trocar| image:: ../_static/tasks/manipulation/g1_assemble_trocar.jpg + +.. |reach-franka-link| replace:: `Isaac-Reach-Franka-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/config/franka/joint_pos_env_cfg.py>`__ +.. |reach-ur10-link| replace:: `Isaac-Reach-UR10-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/config/ur_10/joint_pos_env_cfg.py>`__ +.. |deploy-reach-ur10e-link| replace:: `Isaac-Deploy-Reach-UR10e-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/ur_10e/joint_pos_env_cfg.py>`__ +.. |lift-cube-link| replace:: `Isaac-Lift-Cube-Franka-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/config/franka/joint_pos_env_cfg.py>`__ +.. |lift-cube-ik-abs-link| replace:: `Isaac-Lift-Cube-Franka-IK-Abs-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/config/franka/ik_abs_env_cfg.py>`__ +.. |lift-cube-ik-rel-link| replace:: `Isaac-Lift-Cube-Franka-IK-Rel-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/config/franka/ik_rel_env_cfg.py>`__ +.. |lift-soft-franka-link| replace:: `Isaac-Lift-Soft-Franka-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift_franka_soft/franka_soft_env_cfg.py>`__ +.. |cabi-franka-link| replace:: `Isaac-Open-Drawer-Franka-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/config/franka/joint_pos_env_cfg.py>`__ +.. |franka-direct-link| replace:: `Isaac-Franka-Cabinet-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/franka_cabinet/franka_cabinet_env.py>`__ +.. |cube-allegro-link| replace:: `Isaac-Repose-Cube-Allegro-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/config/allegro_hand/allegro_env_cfg.py>`__ +.. |allegro-direct-link| replace:: `Isaac-Repose-Cube-Allegro-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/allegro_hand/allegro_hand_env_cfg.py>`__ +.. |stack-cube-link| replace:: `Isaac-Stack-Cube-Franka-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_joint_pos_env_cfg.py>`__ +.. |stack-cube-bp-link| replace:: `Isaac-Stack-Cube-Franka-IK-Rel-Blueprint-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_ik_rel_blueprint_env_cfg.py>`__ +.. |gr1_pick_place-link| replace:: `Isaac-PickPlace-GR1T2-Abs-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/pickplace_gr1t2_env_cfg.py>`__ +.. |g1_pick_place-link| replace:: `Isaac-PickPlace-G1-InspireFTP-Abs-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/pickplace_unitree_g1_inspire_hand_env_cfg.py>`__ +.. |g1_pick_place_fixed-link| replace:: `Isaac-PickPlace-FixedBaseUpperBodyIK-G1-Abs-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/fixed_base_upper_body_ik_g1_env_cfg.py>`__ +.. |g1_pick_place_lm-link| replace:: `Isaac-PickPlace-Locomanipulation-G1-Abs-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/locomanipulation_g1_env_cfg.py>`__ +.. |long-suction-link| replace:: `Isaac-Stack-Cube-UR10-Long-Suction-IK-Rel-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/ur10_gripper/stack_ik_rel_env_cfg.py>`__ +.. |short-suction-link| replace:: `Isaac-Stack-Cube-UR10-Short-Suction-IK-Rel-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/ur10_gripper/stack_ik_rel_env_cfg.py>`__ +.. |gr1_pp_waist-link| replace:: `Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/pickplace_gr1t2_waist_enabled_env_cfg.py>`__ +.. |galbot_stack-link| replace:: `Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-RmpFlow-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/galbot/stack_rmp_rel_env_cfg.py>`__ +.. |kuka-allegro-lift-link| replace:: `Isaac-Dexsuite-Kuka-Allegro-Lift-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/dexsuite_kuka_allegro_env_cfg.py>`__ +.. |kuka-allegro-reorient-link| replace:: `Isaac-Dexsuite-Kuka-Allegro-Reorient-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/dexsuite_kuka_allegro_env_cfg.py>`__ +.. |cube-shadow-link| replace:: `Isaac-Repose-Cube-Shadow-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_env_cfg.py>`__ +.. |cube-shadow-ff-link| replace:: `Isaac-Repose-Cube-Shadow-OpenAI-FF-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_env_cfg.py>`__ +.. |cube-shadow-lstm-link| replace:: `Isaac-Repose-Cube-Shadow-OpenAI-LSTM-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_env_cfg.py>`__ +.. |cube-shadow-vis-link| replace:: `Isaac-Repose-Cube-Shadow-Vision-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_vision_env.py>`__ +.. |agibot_place_mug-link| replace:: `Isaac-Place-Mug-Agibot-Left-Arm-RmpFlow-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/place/config/agibot/place_upright_mug_rmp_rel_env_cfg.py>`__ +.. |agibot_place_toy-link| replace:: `Isaac-Place-Toy2Box-Agibot-Right-Arm-RmpFlow-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/place/config/agibot/place_toy2box_rmp_rel_env_cfg.py>`__ +.. |reach_openarm_bi-link| replace:: `Isaac-Reach-OpenArm-Bi-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/config/openarm/bimanual/joint_pos_env_cfg.py>`__ +.. |reach_openarm_uni-link| replace:: `Isaac-Reach-OpenArm-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/config/openarm/unimanual/joint_pos_env_cfg.py>`__ +.. |lift_openarm_uni-link| replace:: `Isaac-Lift-Cube-OpenArm-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/config/openarm/joint_pos_env_cfg.py>`__ +.. |cabi_openarm_uni-link| replace:: `Isaac-Open-Drawer-OpenArm-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/config/openarm/joint_pos_env_cfg.py>`__ +.. |g1_assemble_trocar-link| replace:: `Isaac-Assemble-Trocar-G129-Dex3-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/assemble_trocar/g129_dex3_env_cfg.py>`__ + + +Contact-rich Manipulation +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Environments based on contact-rich manipulation tasks such as peg insertion, gear meshing and nut-bolt fastening. + +These tasks share the same task configurations and control options. You can switch between them by specifying the task name. +For example: + +* |factory-peg-link|: Peg insertion with the Franka arm +* |factory-gear-link|: Gear meshing with the Franka arm +* |factory-nut-link|: Nut-Bolt fastening with the Franka arm + +.. table:: + :widths: 25 30 25 20 + + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +====================+=========================+=============================================================================+==============================+ + | |factory-peg| | |factory-peg-link| | Insert peg into the socket with the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |factory-gear| | |factory-gear-link| | Insert and mesh gear into the base with other gears, using the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |factory-nut| | |factory-nut-link| | Thread the nut onto the first 2 threads of the bolt, using the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + +.. |factory-peg| image:: ../_static/tasks/factory/peg_insert.jpg +.. |factory-gear| image:: ../_static/tasks/factory/gear_mesh.jpg +.. |factory-nut| image:: ../_static/tasks/factory/nut_thread.jpg + +.. |factory-peg-link| replace:: `Isaac-Factory-PegInsert-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/factory/factory_env_cfg.py>`__ +.. |factory-gear-link| replace:: `Isaac-Factory-GearMesh-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/factory/factory_env_cfg.py>`__ +.. |factory-nut-link| replace:: `Isaac-Factory-NutThread-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/factory/factory_env_cfg.py>`__ + +AutoMate +~~~~~~~~ + +Environments based on 100 diverse assembly tasks, each involving the insertion of a plug into a socket. These tasks share a common configuration and differ by th geometry and properties of the parts. + +You can switch between tasks by specifying the corresponding asset ID. Available asset IDs include: + +'00004', '00007', '00014', '00015', '00016', '00021', '00028', '00030', '00032', '00042', '00062', '00074', '00077', '00078', '00081', '00083', '00103', '00110', '00117', '00133', '00138', '00141', '00143', '00163', '00175', '00186', '00187', '00190', '00192', '00210', '00211', '00213', '00255', '00256', '00271', '00293', '00296', '00301', '00308', '00318', '00319', '00320', '00329', '00340', '00345', '00346', '00360', '00388', '00410', '00417', '00422', '00426', '00437', '00444', '00446', '00470', '00471', '00480', '00486', '00499', '00506', '00514', '00537', '00553', '00559', '00581', '00597', '00614', '00615', '00638', '00648', '00649', '00652', '00659', '00681', '00686', '00700', '00703', '00726', '00731', '00741', '00755', '00768', '00783', '00831', '00855', '00860', '00863', '01026', '01029', '01036', '01041', '01053', '01079', '01092', '01102', '01125', '01129', '01132', '01136'. + +We provide environments for both disassembly and assembly. + +.. attention:: + + CUDA is recommended for running the AutoMate environments. If running with Nvidia driver 570 on Linux with architecture x86_64, we follow the below steps to install CUDA 12.8. This allows for computing rewards in AutoMate environments with CUDA. If you have a different operation system or architecture, please refer to the `CUDA installation page `_ for additional instruction. + + .. code-block:: bash + + wget https://developer.download.nvidia.com/compute/cuda/12.8.0/local_installers/cuda_12.8.0_570.86.10_linux.run + sudo sh cuda_12.8.0_570.86.10_linux.run --toolkit + + When using conda, cuda toolkit can be installed with: + + .. code-block:: bash + + conda install cudatoolkit + + With 580 drivers on Linux with architecture x86_64, we install CUDA 13 and additionally install several packages. Please ensure that the pytorch version is compatible with the CUDA version. + + .. code-block:: bash + + wget https://developer.download.nvidia.com/compute/cuda/13.0.2/local_installers/cuda_13.0.2_580.95.05_linux.run + sudo sh cuda_13.0.2_580.95.05_linux.run --toolkit + pip install numba-cuda[cu13] coverage==7.6.1 + + +* |disassembly-link|: The plug starts inserted in the socket. A low-level controller lifts the plug out and moves it to a random position. This process is purely scripted and does not involve any learned policy. Therefore, it does not require policy training or evaluation. The resulting trajectories serve as demonstrations for the reverse process, i.e., learning to assemble. To run disassembly for a specific task: ``python source/isaaclab_tasks/isaaclab_tasks/direct/automate/run_disassembly_w_id.py --assembly_id=ASSEMBLY_ID --disassembly_dir=DISASSEMBLY_DIR``. All generated trajectories are saved to a local directory ``DISASSEMBLY_DIR``. +* |assembly-link|: The goal is to insert the plug into the socket. You can use this environment to train a policy via reinforcement learning or evaluate a pre-trained checkpoint. + + * To train an assembly policy, we run the command ``python source/isaaclab_tasks/isaaclab_tasks/direct/automate/run_w_id.py --assembly_id=ASSEMBLY_ID --train``. We can customize the training process using the optional flags: ``--max_iterations=MAX_ITERATIONS`` to set the number of training iterations, ``--num_envs=NUM_ENVS`` to set the number of parallel environments during training, ``--seed=SEED`` to assign the random seed. The policy checkpoints will be saved automatically during training in the directory ``logs/rl_games/Assembly/test``. + * To evaluate an assembly policy, we run the command ``python source/isaaclab_tasks/isaaclab_tasks/direct/automate/run_w_id.py --assembly_id=ASSEMBLY_ID --checkpoint=CHECKPOINT --log_eval``. The evaluation results are stored in ``evaluation_{ASSEMBLY_ID}.h5``. + +.. table:: + :widths: 25 30 25 20 + + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +====================+=========================+=============================================================================+==============================+ + | |disassembly| | |disassembly-link| | Lift a plug out of the socket with the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |assembly| | |assembly-link| | Insert a plug into its corresponding socket with the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + +.. |assembly| image:: ../_static/tasks/automate/00004.jpg +.. |disassembly| image:: ../_static/tasks/automate/01053_disassembly.jpg + +.. |assembly-link| replace:: `Isaac-AutoMate-Assembly-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/automate/assembly_env_cfg.py>`__ +.. |disassembly-link| replace:: `Isaac-AutoMate-Disassembly-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/automate/disassembly_env_cfg.py>`__ + +FORGE +~~~~~~~~ + +FORGE environments extend Factory environments with: + +* Force sensing: Add observations for force experienced by the end-effector. +* Excessive force penalty: Add an option to penalize the agent for excessive contact forces. +* Dynamics randomization: Randomize controller gains, asset properties (friction, mass), and dead-zone. +* Success prediction: Add an extra action that predicts task success. + +These tasks share the same task configurations and control options. You can switch between them by specifying the task name. + +* |forge-peg-link|: Peg insertion with the Franka arm +* |forge-gear-link|: Gear meshing with the Franka arm +* |forge-nut-link|: Nut-Bolt fastening with the Franka arm + +.. table:: + :widths: 25 30 25 20 + + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +====================+=========================+=============================================================================+==============================+ + | |forge-peg| | |forge-peg-link| | Insert peg into the socket with the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |forge-gear| | |forge-gear-link| | Insert and mesh gear into the base with other gears, using the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |forge-nut| | |forge-nut-link| | Thread the nut onto the first 2 threads of the bolt, using the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + +.. |forge-peg| image:: ../_static/tasks/factory/peg_insert.jpg +.. |forge-gear| image:: ../_static/tasks/factory/gear_mesh.jpg +.. |forge-nut| image:: ../_static/tasks/factory/nut_thread.jpg + +.. |forge-peg-link| replace:: `Isaac-Forge-PegInsert-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/forge/forge_env_cfg.py>`__ +.. |forge-gear-link| replace:: `Isaac-Forge-GearMesh-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/forge/forge_env_cfg.py>`__ +.. |forge-nut-link| replace:: `Isaac-Forge-NutThread-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/forge/forge_env_cfg.py>`__ + + +Locomotion +~~~~~~~~~~ + +Environments based on legged locomotion tasks. + +.. table:: + :widths: 25 30 25 20 + + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +==============================+==============================================+==============================================================================+==============================+ + | |velocity-flat-anymal-b| | |velocity-flat-anymal-b-link| | Track a velocity command on flat terrain with the Anymal B robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-anymal-b| | |velocity-rough-anymal-b-link| | Track a velocity command on rough terrain with the Anymal B robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-anymal-c| | |velocity-flat-anymal-c-link| | Track a velocity command on flat terrain with the Anymal C robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + | | | | (Manager-based only) | + | | |velocity-flat-anymal-c-direct-link| | | | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-anymal-c| | |velocity-rough-anymal-c-link| | Track a velocity command on rough terrain with the Anymal C robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + | | | | (Manager-based only) | + | | |velocity-rough-anymal-c-direct-link| | | | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-anymal-d| | |velocity-flat-anymal-d-link| | Track a velocity command on flat terrain with the Anymal D robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp``, | + | | | | ``ovphysx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-anymal-d| | |velocity-rough-anymal-d-link| | Track a velocity command on rough terrain with the Anymal D robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-unitree-a1| | |velocity-flat-unitree-a1-link| | Track a velocity command on flat terrain with the Unitree A1 robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-unitree-a1| | |velocity-rough-unitree-a1-link| | Track a velocity command on rough terrain with the Unitree A1 robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-unitree-go1| | |velocity-flat-unitree-go1-link| | Track a velocity command on flat terrain with the Unitree Go1 robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-unitree-go1| | |velocity-rough-unitree-go1-link| | Track a velocity command on rough terrain with the Unitree Go1 robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-unitree-go2| | |velocity-flat-unitree-go2-link| | Track a velocity command on flat terrain with the Unitree Go2 robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-unitree-go2| | |velocity-rough-unitree-go2-link| | Track a velocity command on rough terrain with the Unitree Go2 robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-spot| | |velocity-flat-spot-link| | Track a velocity command on flat terrain with the Boston Dynamics Spot robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-h1| | |velocity-flat-h1-link| | Track a velocity command on flat terrain with the Unitree H1 robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-h1| | |velocity-rough-h1-link| | Track a velocity command on rough terrain with the Unitree H1 robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-g1| | |velocity-flat-g1-link| | Track a velocity command on flat terrain with the Unitree G1 robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-g1| | |velocity-rough-g1-link| | Track a velocity command on rough terrain with the Unitree G1 robot | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-digit| | |velocity-flat-digit-link| | Track a velocity command on flat terrain with the Agility Digit robot | **physics=** ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-digit| | |velocity-rough-digit-link| | Track a velocity command on rough terrain with the Agility Digit robot | **physics=** ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |tracking-loco-manip-digit| | |tracking-loco-manip-digit-link| | Track a root velocity and hand pose command with the Agility Digit robot | **physics=** ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + +.. |velocity-flat-anymal-b-link| replace:: `Isaac-Velocity-Flat-Anymal-B-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py>`__ +.. |velocity-rough-anymal-b-link| replace:: `Isaac-Velocity-Rough-Anymal-B-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py>`__ + +.. |velocity-flat-anymal-c-link| replace:: `Isaac-Velocity-Flat-Anymal-C-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py>`__ +.. |velocity-rough-anymal-c-link| replace:: `Isaac-Velocity-Rough-Anymal-C-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py>`__ + +.. |velocity-flat-anymal-c-direct-link| replace:: `Isaac-Velocity-Flat-Anymal-C-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/anymal_c/anymal_c_env.py>`__ +.. |velocity-rough-anymal-c-direct-link| replace:: `Isaac-Velocity-Rough-Anymal-C-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/anymal_c/anymal_c_env.py>`__ + +.. |velocity-flat-anymal-d-link| replace:: `Isaac-Velocity-Flat-Anymal-D-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py>`__ +.. |velocity-rough-anymal-d-link| replace:: `Isaac-Velocity-Rough-Anymal-D-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py>`__ + +.. |velocity-flat-unitree-a1-link| replace:: `Isaac-Velocity-Flat-Unitree-A1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py>`__ +.. |velocity-rough-unitree-a1-link| replace:: `Isaac-Velocity-Rough-Unitree-A1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py>`__ + +.. |velocity-flat-unitree-go1-link| replace:: `Isaac-Velocity-Flat-Unitree-Go1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py>`__ +.. |velocity-rough-unitree-go1-link| replace:: `Isaac-Velocity-Rough-Unitree-Go1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py>`__ + +.. |velocity-flat-unitree-go2-link| replace:: `Isaac-Velocity-Flat-Unitree-Go2-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py>`__ +.. |velocity-rough-unitree-go2-link| replace:: `Isaac-Velocity-Rough-Unitree-Go2-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py>`__ + +.. |velocity-flat-spot-link| replace:: `Isaac-Velocity-Flat-Spot-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/spot/flat_env_cfg.py>`__ + +.. |velocity-flat-h1-link| replace:: `Isaac-Velocity-Flat-H1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py>`__ +.. |velocity-rough-h1-link| replace:: `Isaac-Velocity-Rough-H1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py>`__ + +.. |velocity-flat-g1-link| replace:: `Isaac-Velocity-Flat-G1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py>`__ +.. |velocity-rough-g1-link| replace:: `Isaac-Velocity-Rough-G1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py>`__ + +.. |velocity-flat-digit-link| replace:: `Isaac-Velocity-Flat-Digit-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/digit/flat_env_cfg.py>`__ +.. |velocity-rough-digit-link| replace:: `Isaac-Velocity-Rough-Digit-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/digit/rough_env_cfg.py>`__ +.. |tracking-loco-manip-digit-link| replace:: `Isaac-Tracking-LocoManip-Digit-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/tracking/config/digit/loco_manip_env_cfg.py>`__ + +.. |velocity-flat-anymal-b| image:: ../_static/tasks/locomotion/anymal_b_flat.jpg +.. |velocity-rough-anymal-b| image:: ../_static/tasks/locomotion/anymal_b_rough.jpg +.. |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 +.. |velocity-flat-spot| image:: ../_static/tasks/locomotion/spot_flat.jpg +.. |velocity-flat-h1| image:: ../_static/tasks/locomotion/h1_flat.jpg +.. |velocity-rough-h1| image:: ../_static/tasks/locomotion/h1_rough.jpg +.. |velocity-flat-g1| image:: ../_static/tasks/locomotion/g1_flat.jpg +.. |velocity-rough-g1| image:: ../_static/tasks/locomotion/g1_rough.jpg +.. |velocity-flat-digit| image:: ../_static/tasks/locomotion/agility_digit_flat.jpg +.. |velocity-rough-digit| image:: ../_static/tasks/locomotion/agility_digit_rough.jpg +.. |tracking-loco-manip-digit| image:: ../_static/tasks/locomotion/agility_digit_loco_manip.jpg + +.. note:: + + Agility Digit environments use closed-loop articulations (achilles rod, toe + push-rods) that do not run correctly on ``newton_mjwarp``. Use ``physx`` for + Digit-based tasks; see :ref:`known-issues-closed-loop-newton` for details. + +Navigation +~~~~~~~~~~ + +.. table:: + :widths: 25 30 25 20 + + +----------------+---------------------+-----------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +================+=====================+=============================================================================+==============================+ + | |anymal_c_nav| | |anymal_c_nav-link| | Navigate towards a target x-y position and heading with the ANYmal C robot. | **physics=** ``physx``, | + | | | | ``newton_mjwarp`` | + +----------------+---------------------+-----------------------------------------------------------------------------+------------------------------+ + +.. |anymal_c_nav-link| replace:: `Isaac-Navigation-Flat-Anymal-C-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/navigation/config/anymal_c/navigation_env_cfg.py>`__ + +.. |anymal_c_nav| image:: ../_static/tasks/navigation/anymal_c_nav.jpg + + +Multirotor +~~~~~~~~~~ + +.. note:: + The multirotor entry provides an environment configuration for flying the ARL robot. + See the `drone_arl` folder and the ARL robot config + (`ARL_ROBOT_1_CFG`) in the codebase for details. + +.. |arl_robot_track_position_state_based-link| replace:: `Isaac-TrackPositionNoObstacles-ARL-Robot-1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/drone_arl/track_position_state_based/config/arl_robot_1/track_position_state_based_env_cfg.py>`__ + +.. |arl_robot_track_position_state_based| image:: ../_static/tasks/drone_arl/arl_robot_1_track_position_state_based.jpg + +.. |arl_robot_navigation-link| replace:: `Isaac-Navigation-3DObstacles-ARL-Robot-1-v0 `__ + +.. |arl_robot_navigation| image:: ../_static/tasks/drone_arl/arl_robot_1_navigation.jpg + +.. table:: + :widths: 25 30 25 20 + + +----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------+-----------------------+ + | World | Environment ID | Description | Presets | + +========================================+=============================================+========================================================================================+=======================+ + | |arl_robot_track_position_state_based| | |arl_robot_track_position_state_based-link| | Setpoint position control for the ARL robot using the track_position_state_based task. | | + +----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------+-----------------------+ + | |arl_robot_navigation| | |arl_robot_navigation-link| | Navigate through 3D obstacles with the ARL robot using depth camera sensing. | | + +----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------+-----------------------+ + + +Others +~~~~~~ + +.. note:: + + Adversarial Motion Priors (AMP) training is only available with the `skrl` library, as it is the only one of the currently + integrated libraries that supports it out-of-the-box (for the other libraries, it is necessary to implement the algorithm and architectures). + See the `skrl's AMP Documentation `_ for more information. + The AMP algorithm can be activated by adding the command line input ``--algorithm AMP`` to the train/play script. + + For evaluation, the play script's command line input ``--real-time`` allows the interaction loop between the environment and the agent to run in real time, if possible. + +.. table:: + :widths: 25 30 25 20 + + +----------------+---------------------------+-----------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +================+===========================+=============================================================================+==============================+ + | |quadcopter| | |quadcopter-link| | Fly and hover the Crazyflie copter at a goal point by applying thrust. | | + +----------------+---------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |humanoid_amp| | |humanoid_amp_dance-link| | Move a humanoid robot by imitating different pre-recorded human animations | | + | | | (Adversarial Motion Priors). | | + | | |humanoid_amp_run-link| | | | + | | | | | + | | |humanoid_amp_walk-link| | | | + +----------------+---------------------------+-----------------------------------------------------------------------------+------------------------------+ + +.. |quadcopter-link| replace:: `Isaac-Quadcopter-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/quadcopter/quadcopter_env.py>`__ +.. |humanoid_amp_dance-link| replace:: `Isaac-Humanoid-AMP-Dance-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/humanoid_amp_env_cfg.py>`__ +.. |humanoid_amp_run-link| replace:: `Isaac-Humanoid-AMP-Run-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/humanoid_amp_env_cfg.py>`__ +.. |humanoid_amp_walk-link| replace:: `Isaac-Humanoid-AMP-Walk-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/humanoid_amp_env_cfg.py>`__ + +.. |quadcopter| image:: ../_static/tasks/others/quadcopter.jpg +.. |humanoid_amp| image:: ../_static/tasks/others/humanoid_amp.jpg + +Spaces showcase +~~~~~~~~~~~~~~~ + +The |cartpole_showcase| folder contains showcase tasks (based on the *Cartpole* and *Cartpole-Camera* Direct tasks) +for the definition/use of the various Gymnasium observation and action spaces supported in Isaac Lab. + +.. |cartpole_showcase| replace:: `cartpole_showcase `__ + +.. note:: + + Currently, only Isaac Lab's Direct workflow supports the definition of observation and action spaces other than ``Box``. + See Direct workflow's :py:obj:`~isaaclab.envs.DirectRLEnvCfg.observation_space` / :py:obj:`~isaaclab.envs.DirectRLEnvCfg.action_space` + documentation for more details. + +The following tables summarize the different pairs of showcased spaces for the *Cartpole* and *Cartpole-Camera* tasks. +Replace ```` and ```` with the observation and action spaces to be explored in the task names for training and evaluation. + +.. raw:: html + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

Showcase spaces for the Cartpole task

+

Isaac-Cartpole-Showcase-<OBSERVATION>-<ACTION>-Direct-v0

+
action space
 Box Discrete MultiDiscrete

observation

space

 Boxxxx
 Discretexxx
 MultiDiscretexxx
 Dictxxx
 Tuplexxx
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

Showcase spaces for the Cartpole-Camera task

+

Isaac-Cartpole-Camera-Showcase-<OBSERVATION>-<ACTION>-Direct-v0

+
action space
 Box Discrete MultiDiscrete

observation

space

 Boxxxx
 Discrete---
 MultiDiscrete---
 Dictxxx
 Tuplexxx
+ +Multi-agent +------------ + +.. note:: + + True mutli-agent training is only available with the `skrl` library, see the `Multi-Agents Documentation `_ for more information. + It supports the `IPPO` and `MAPPO` algorithms, which can be activated by adding the command line input ``--algorithm IPPO`` or ``--algorithm MAPPO`` to the train/play script. + If these environments are run with other libraries or without the `IPPO` or `MAPPO` flags, they will be converted to single-agent environments under the hood. + + +Classic +~~~~~~~ + +.. table:: + :widths: 25 30 25 20 + + +------------------------+------------------------------------+-----------------------------------------------------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +========================+====================================+=======================================================================================================================+==============================+ + | |cart-double-pendulum| | |cart-double-pendulum-direct-link| | Move the cart and the pendulum to keep the last one upwards in the classic inverted double pendulum on a cart control | | + +------------------------+------------------------------------+-----------------------------------------------------------------------------------------------------------------------+------------------------------+ + +.. |cart-double-pendulum| image:: ../_static/tasks/classic/cart_double_pendulum.jpg + +.. |cart-double-pendulum-direct-link| replace:: `Isaac-Cart-Double-Pendulum-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/cart_double_pendulum/cart_double_pendulum_env.py>`__ + +Manipulation +~~~~~~~~~~~~ + +Environments based on fixed-arm manipulation tasks. + +.. table:: + :widths: 25 30 25 20 + + +----------------------+--------------------------------+--------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +======================+================================+========================================================+==============================+ + | |shadow-hand-over| | |shadow-hand-over-direct-link| | Passing an object from one hand over to the other hand | | + +----------------------+--------------------------------+--------------------------------------------------------+------------------------------+ + +.. |shadow-hand-over| image:: ../_static/tasks/manipulation/shadow_hand_over.jpg + +.. |shadow-hand-over-direct-link| replace:: `Isaac-Shadow-Hand-Over-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/shadow_hand_over_env.py>`__ + +| + +.. _comprehensive-environment-list: + +Comprehensive List of Environments +================================== + +For environments that have a different task name listed under ``Inference Task Name``, please use the Inference Task Name +provided when running ``play.py`` or any inferencing workflows. These tasks provide more suitable configurations for +inferencing, including reading from an already trained checkpoint and disabling runtime perturbations used for training. + +.. START-AUTO-GENERATED: comprehensive-environment-list + +.. list-table:: + :widths: 18 17 10 22 33 + + * - **Task Name** + - **Inference Task Name** + - **Workflow** + - **RL Library** + - **Presets** + * - Isaac-Ant-Direct-Warp-v0 + - + - Direct + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Ant-Direct-v0 + - + - Direct + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Ant-Warp-v0 + - + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - + * - Isaac-Ant-v0 + - + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``physx`` + * - Isaac-Assemble-Trocar-G129-Dex3-v0 + - Isaac-Assemble-Trocar-G129-Dex3-Eval-v0 + - Manager Based + - **rlinf** (PPO) + - + * - Isaac-AutoMate-Assembly-Direct-v0 + - + - Direct + - **rl_games** (PPO) + - + * - Isaac-AutoMate-Disassembly-Direct-v0 + - + - Direct + - **rl_games** (PPO) + - + * - Isaac-Cart-Double-Pendulum-Direct-v0 + - + - Direct + - **rl_games** (PPO), **skrl** (PPO, IPPO, MAPPO) + - + * - Isaac-Cartpole-Albedo-Camera-Direct-v0 + - + - Direct + - **rl_games** (PPO), **skrl** (PPO) + - + * - Isaac-Cartpole-Camera-Presets-Direct-v0 + - + - Direct + - **rl_games** (PPO), **skrl** (PPO) + - | **physics=** ``newton_mjwarp``, ``ovphysx``, ``physx`` + | **renderer=** ``isaacsim_rtx_renderer``, ``newton_renderer``, ``ovrtx_renderer`` + | **presets=** ``albedo``, ``depth``, ``rgb``, ``semantic_segmentation``, ``simple_shading_constant_diffuse``, ``simple_shading_diffuse_mdl``, ``simple_shading_full_mdl`` + * - Isaac-Cartpole-Camera-Showcase-Box-Box-Direct-v0 + - + - Direct + - **skrl** (PPO) + - + * - Isaac-Cartpole-Camera-Showcase-Box-Discrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - + * - Isaac-Cartpole-Camera-Showcase-Box-MultiDiscrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - + * - Isaac-Cartpole-Camera-Showcase-Dict-Box-Direct-v0 + - + - Direct + - **skrl** (PPO) + - + * - Isaac-Cartpole-Camera-Showcase-Dict-Discrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - + * - Isaac-Cartpole-Camera-Showcase-Dict-MultiDiscrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - + * - Isaac-Cartpole-Camera-Showcase-Tuple-Box-Direct-v0 + - + - Direct + - **skrl** (PPO) + - + * - Isaac-Cartpole-Camera-Showcase-Tuple-Discrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - + * - Isaac-Cartpole-Camera-Showcase-Tuple-MultiDiscrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - + * - Isaac-Cartpole-Depth-Camera-Direct-v0 + - + - Direct + - **rl_games** (PPO), **skrl** (PPO) + - + * - Isaac-Cartpole-Depth-v0 + - + - Manager Based + - **rl_games** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``physx`` + * - Isaac-Cartpole-Direct-Warp-v0 + - + - Direct + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - + * - Isaac-Cartpole-Direct-v0 + - + - Direct + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-RGB-Camera-Direct-v0 + - + - Direct + - **rl_games** (PPO), **skrl** (PPO) + - **renderer=** ``isaacsim_rtx_renderer``, ``newton_renderer``, ``ovrtx_renderer`` + * - Isaac-Cartpole-RGB-ResNet18-v0 + - + - Manager Based + - **rl_games** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``physx`` + * - Isaac-Cartpole-RGB-TheiaTiny-v0 + - + - Manager Based + - **rl_games** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``physx`` + * - Isaac-Cartpole-RGB-v0 + - + - Manager Based + - **rl_games** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``physx`` + * - Isaac-Cartpole-Showcase-Box-Box-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-Showcase-Box-Discrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-Showcase-Box-MultiDiscrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-Showcase-Dict-Box-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-Showcase-Dict-Discrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-Showcase-Dict-MultiDiscrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-Showcase-Discrete-Box-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-Showcase-Discrete-Discrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-Showcase-Discrete-MultiDiscrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-Showcase-MultiDiscrete-Box-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-Showcase-MultiDiscrete-Discrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-Showcase-MultiDiscrete-MultiDiscrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-Showcase-Tuple-Box-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-Showcase-Tuple-Discrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-Showcase-Tuple-MultiDiscrete-Direct-v0 + - + - Direct + - **skrl** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Cartpole-SimpleShading-Constant-Camera-Direct-v0 + - + - Direct + - **rl_games** (PPO), **skrl** (PPO) + - + * - Isaac-Cartpole-SimpleShading-Diffuse-Camera-Direct-v0 + - + - Direct + - **rl_games** (PPO), **skrl** (PPO) + - + * - Isaac-Cartpole-SimpleShading-Full-Camera-Direct-v0 + - + - Direct + - **rl_games** (PPO), **skrl** (PPO) + - + * - Isaac-Cartpole-Warp-v0 + - + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - + * - Isaac-Cartpole-v0 + - + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``physx`` + * - Isaac-Deploy-GearAssembly-Rizon4s-Grav-ROS-Inference-v0 + - + - Manager Based + - **rsl_rl** (PPO) + - + * - Isaac-Deploy-GearAssembly-Rizon4s-Grav-v0 + - Isaac-Deploy-GearAssembly-Rizon4s-Grav-Play-v0 + - Manager Based + - **rsl_rl** (PPO) + - + * - Isaac-Deploy-GearAssembly-UR10e-2F140-ROS-Inference-v0 + - + - Manager Based + - **rsl_rl** (PPO) + - + * - Isaac-Deploy-GearAssembly-UR10e-2F140-v0 + - Isaac-Deploy-GearAssembly-UR10e-2F140-Play-v0 + - Manager Based + - **rsl_rl** (PPO) + - + * - Isaac-Deploy-GearAssembly-UR10e-2F85-ROS-Inference-v0 + - + - Manager Based + - **rsl_rl** (PPO) + - + * - Isaac-Deploy-GearAssembly-UR10e-2F85-v0 + - Isaac-Deploy-GearAssembly-UR10e-2F85-Play-v0 + - Manager Based + - **rsl_rl** (PPO) + - + * - Isaac-Deploy-Reach-Rizon4s-ROS-Inference-v0 + - + - Manager Based + - **rsl_rl** (PPO) + - + * - Isaac-Deploy-Reach-Rizon4s-v0 + - Isaac-Deploy-Reach-Rizon4s-Play-v0 + - Manager Based + - **rsl_rl** (PPO) + - + * - Isaac-Deploy-Reach-UR10e-ROS-Inference-v0 + - + - Manager Based + - **rsl_rl** (PPO) + - + * - Isaac-Deploy-Reach-UR10e-v0 + - Isaac-Deploy-Reach-UR10e-Play-v0 + - Manager Based + - **rsl_rl** (PPO) + - + * - Isaac-Dexsuite-Kuka-Allegro-Lift-v0 + - Isaac-Dexsuite-Kuka-Allegro-Lift-Play-v0 + - Manager Based + - **rsl_rl** (PPO) + - | **physics=** ``newton_mjwarp``, ``physx`` + | **renderer=** ``isaacsim_rtx_renderer``, ``newton_renderer``, ``ovrtx_renderer`` + | **presets=** ``albedo128``, ``albedo256``, ``albedo64``, ``cube``, ``depth128``, ``depth256``, ``depth64``, ``duo_camera``, ``raycaster_depth128``, ``raycaster_depth256``, ``raycaster_depth64``, ``rgb128``, ``rgb256``, ``rgb64``, ``semantic_segmentation128``, ``semantic_segmentation256``, ``semantic_segmentation64``, ``shapes``, ``simple_shading_constant_diffuse128``, ``simple_shading_constant_diffuse256``, ``simple_shading_constant_diffuse64``, ``simple_shading_diffuse_mdl128``, ``simple_shading_diffuse_mdl256``, ``simple_shading_diffuse_mdl64``, ``simple_shading_full_mdl128``, ``simple_shading_full_mdl256``, ``simple_shading_full_mdl64``, ``single_camera``, ``state`` + * - Isaac-Dexsuite-Kuka-Allegro-Reorient-v0 + - Isaac-Dexsuite-Kuka-Allegro-Reorient-Play-v0 + - Manager Based + - **rsl_rl** (PPO) + - | **physics=** ``newton_mjwarp``, ``physx`` + | **renderer=** ``isaacsim_rtx_renderer``, ``newton_renderer``, ``ovrtx_renderer`` + | **presets=** ``albedo128``, ``albedo256``, ``albedo64``, ``cube``, ``depth128``, ``depth256``, ``depth64``, ``duo_camera``, ``raycaster_depth128``, ``raycaster_depth256``, ``raycaster_depth64``, ``rgb128``, ``rgb256``, ``rgb64``, ``semantic_segmentation128``, ``semantic_segmentation256``, ``semantic_segmentation64``, ``shapes``, ``simple_shading_constant_diffuse128``, ``simple_shading_constant_diffuse256``, ``simple_shading_constant_diffuse64``, ``simple_shading_diffuse_mdl128``, ``simple_shading_diffuse_mdl256``, ``simple_shading_diffuse_mdl64``, ``simple_shading_full_mdl128``, ``simple_shading_full_mdl256``, ``simple_shading_full_mdl64``, ``single_camera``, ``state`` + * - Isaac-ExhaustPipe-GR1T2-Pink-IK-Abs-v0 + - + - Manager Based + - + - + * - Isaac-Factory-GearMesh-Direct-v0 + - + - Direct + - **rl_games** (PPO) + - + * - Isaac-Factory-NutThread-Direct-v0 + - + - Direct + - **rl_games** (PPO) + - + * - Isaac-Factory-PegInsert-Direct-v0 + - + - Direct + - **rl_games** (PPO) + - + * - Isaac-Forge-GearMesh-Direct-v0 + - + - Direct + - **rl_games** (PPO) + - + * - Isaac-Forge-NutThread-Direct-v0 + - + - Direct + - **rl_games** (PPO) + - + * - Isaac-Forge-PegInsert-Direct-v0 + - + - Direct + - **rl_games** (PPO) + - + * - Isaac-Franka-Cabinet-Direct-v0 + - + - Direct + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Humanoid-AMP-Dance-Direct-v0 + - + - Direct + - **skrl** (AMP) + - + * - Isaac-Humanoid-AMP-Run-Direct-v0 + - + - Direct + - **skrl** (AMP) + - + * - Isaac-Humanoid-AMP-Walk-Direct-v0 + - + - Direct + - **skrl** (AMP) + - + * - Isaac-Humanoid-Direct-Warp-v0 + - + - Direct + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Humanoid-Direct-v0 + - + - Direct + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Humanoid-Warp-v0 + - + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - + * - Isaac-Humanoid-v0 + - + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Lift-Cloth-Franka-v0 + - + - Manager Based + - **rsl_rl** (PPO) + - **physics=** ``newton_mjwarp_vdb`` + * - Isaac-Lift-Cube-Franka-IK-Abs-v0 + - + - Manager Based + - + - + * - Isaac-Lift-Cube-Franka-IK-Rel-v0 + - + - Manager Based + - + - + * - Isaac-Lift-Cube-Franka-v0 + - Isaac-Lift-Cube-Franka-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - + * - Isaac-Lift-Cube-OpenArm-v0 + - Isaac-Lift-Cube-OpenArm-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO) + - + * - Isaac-Lift-Soft-Franka-v0 + - + - Manager Based + - **rsl_rl** (PPO) + - **physics=** ``newton_mjwarp_vbd``, ``physx`` + * - Isaac-Lift-Teddy-Bear-Franka-IK-Abs-v0 + - + - Manager Based + - + - + * - Isaac-Navigation-3DObstacles-ARL-Robot-1-v0 + - Isaac-Navigation-3DObstacles-ARL-Robot-1-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Navigation-Flat-Anymal-C-v0 + - Isaac-Navigation-Flat-Anymal-C-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-NutPour-GR1T2-Pink-IK-Abs-v0 + - + - Manager Based + - + - + * - Isaac-Open-Drawer-Franka-IK-Abs-v0 + - + - Manager Based + - + - + * - Isaac-Open-Drawer-Franka-IK-Rel-v0 + - + - Manager Based + - + - + * - Isaac-Open-Drawer-Franka-v0 + - Isaac-Open-Drawer-Franka-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Open-Drawer-OpenArm-v0 + - Isaac-Open-Drawer-OpenArm-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO) + - + * - Isaac-PickPlace-FixedBaseUpperBodyIK-G1-Abs-v0 + - + - Manager Based + - + - + * - Isaac-PickPlace-G1-InspireFTP-Abs-v0 + - + - Manager Based + - + - + * - Isaac-PickPlace-GR1T2-Abs-v0 + - + - Manager Based + - + - + * - Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 + - + - Manager Based + - + - + * - Isaac-PickPlace-Locomanipulation-G1-Abs-v0 + - + - Manager Based + - + - + * - Isaac-Place-Mug-Agibot-Left-Arm-RmpFlow-v0 + - + - Manager Based + - + - + * - Isaac-Place-Toy2Box-Agibot-Right-Arm-RmpFlow-v0 + - + - Manager Based + - + - + * - Isaac-Quadcopter-Direct-v0 + - + - Direct + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Reach-Franka-IK-Abs-v0 + - + - Manager Based + - + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Reach-Franka-IK-Rel-v0 + - + - Manager Based + - + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Reach-Franka-OSC-v0 + - Isaac-Reach-Franka-OSC-Play-v0 + - Manager Based + - **rsl_rl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Reach-Franka-Warp-v0 + - Isaac-Reach-Franka-Warp-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Reach-Franka-v0 + - Isaac-Reach-Franka-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Reach-OpenArm-Bi-v0 + - Isaac-Reach-OpenArm-Bi-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO) + - + * - Isaac-Reach-OpenArm-v0 + - Isaac-Reach-OpenArm-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Reach-UR10-v0 + - Isaac-Reach-UR10-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Repose-Cube-Allegro-Direct-Warp-v0 + - + - Direct + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Repose-Cube-Allegro-Direct-v0 + - + - Direct + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Repose-Cube-Allegro-NoVelObs-v0 + - Isaac-Repose-Cube-Allegro-NoVelObs-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Repose-Cube-Allegro-v0 + - Isaac-Repose-Cube-Allegro-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Repose-Cube-Shadow-Direct-v0 + - + - Direct + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Repose-Cube-Shadow-OpenAI-FF-Direct-v0 + - + - Direct + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Repose-Cube-Shadow-OpenAI-LSTM-Direct-v0 + - + - Direct + - **rl_games** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Repose-Cube-Shadow-Vision-Direct-v0 + - Isaac-Repose-Cube-Shadow-Vision-Direct-Play-v0 + - Direct + - **rl_games** (VISION), **rsl_rl** (PPO) + - | **physics=** ``newton_mjwarp``, ``physx`` + | **renderer=** ``isaacsim_rtx_renderer``, ``newton_renderer``, ``ovrtx_renderer`` + | **presets=** ``albedo``, ``depth``, ``full``, ``rgb``, ``semantic_segmentation``, ``simple_shading_constant_diffuse``, ``simple_shading_diffuse_mdl``, ``simple_shading_full_mdl`` + * - Isaac-Shadow-Hand-Over-Direct-v0 + - + - Direct + - **rl_games** (PPO), **skrl** (PPO, IPPO, MAPPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Stack-Cube-Bin-Franka-IK-Rel-Mimic-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-BlueGreen-Franka-IK-Rel-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-BlueGreenRed-Franka-IK-Rel-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-Franka-IK-Abs-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-Franka-IK-Rel-Blueprint-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-Franka-IK-Rel-Skillgen-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Cosmos-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-Franka-IK-Rel-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-Franka-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-RmpFlow-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-Galbot-Right-Arm-Suction-RmpFlow-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-Instance-Randomize-Franka-IK-Rel-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-Instance-Randomize-Franka-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-RedGreen-Franka-IK-Rel-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-RedGreenBlue-Franka-IK-Rel-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-UR10-Long-Suction-IK-Rel-v0 + - + - Manager Based + - + - + * - Isaac-Stack-Cube-UR10-Short-Suction-IK-Rel-v0 + - + - Manager Based + - + - + * - Isaac-TrackPositionNoObstacles-ARL-Robot-1-v0 + - Isaac-TrackPositionNoObstacles-ARL-Robot-1-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Tracking-LocoManip-Digit-v0 + - Isaac-Tracking-LocoManip-Digit-Play-v0 + - Manager Based + - **rsl_rl** (PPO) + - **physics=** ``physx`` + * - Isaac-Velocity-Flat-Anymal-B-Warp-v0 + - Isaac-Velocity-Flat-Anymal-B-Warp-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Velocity-Flat-Anymal-B-v0 + - Isaac-Velocity-Flat-Anymal-B-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Flat-Anymal-C-Direct-v0 + - + - Direct + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Velocity-Flat-Anymal-C-Warp-v0 + - Isaac-Velocity-Flat-Anymal-C-Warp-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Velocity-Flat-Anymal-C-v0 + - Isaac-Velocity-Flat-Anymal-C-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Flat-Anymal-D-Warp-v0 + - Isaac-Velocity-Flat-Anymal-D-Warp-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Velocity-Flat-Anymal-D-v0 + - Isaac-Velocity-Flat-Anymal-D-Play-v0 + - Manager Based + - **rsl_rl** (PPO, DISTILLATION, DISTILLATION_RECURRENT, RECURRENT), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``ovphysx``, ``physx`` + * - Isaac-Velocity-Flat-Cassie-Warp-v0 + - Isaac-Velocity-Flat-Cassie-Warp-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Velocity-Flat-Cassie-v0 + - Isaac-Velocity-Flat-Cassie-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Flat-Digit-v0 + - Isaac-Velocity-Flat-Digit-Play-v0 + - Manager Based + - **rsl_rl** (PPO) + - **physics=** ``physx`` + * - Isaac-Velocity-Flat-G1-Warp-v0 + - Isaac-Velocity-Flat-G1-Warp-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Velocity-Flat-G1-v0 + - Isaac-Velocity-Flat-G1-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Flat-H1-Warp-v0 + - Isaac-Velocity-Flat-H1-Warp-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Velocity-Flat-H1-v0 + - Isaac-Velocity-Flat-H1-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Flat-Spot-v0 + - Isaac-Velocity-Flat-Spot-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Flat-Unitree-A1-Warp-v0 + - Isaac-Velocity-Flat-Unitree-A1-Warp-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - + * - Isaac-Velocity-Flat-Unitree-A1-v0 + - Isaac-Velocity-Flat-Unitree-A1-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Flat-Unitree-Go1-Warp-v0 + - Isaac-Velocity-Flat-Unitree-Go1-Warp-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Velocity-Flat-Unitree-Go1-v0 + - Isaac-Velocity-Flat-Unitree-Go1-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Flat-Unitree-Go2-Warp-v0 + - Isaac-Velocity-Flat-Unitree-Go2-Warp-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Velocity-Flat-Unitree-Go2-v0 + - Isaac-Velocity-Flat-Unitree-Go2-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Rough-Anymal-B-v0 + - Isaac-Velocity-Rough-Anymal-B-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Rough-Anymal-C-Direct-v0 + - + - Direct + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - + * - Isaac-Velocity-Rough-Anymal-C-v0 + - Isaac-Velocity-Rough-Anymal-C-Play-v0 + - Manager Based + - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Rough-Anymal-D-v0 + - Isaac-Velocity-Rough-Anymal-D-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Rough-Cassie-v0 + - Isaac-Velocity-Rough-Cassie-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Rough-Digit-v0 + - Isaac-Velocity-Rough-Digit-Play-v0 + - Manager Based + - **rsl_rl** (PPO) + - **physics=** ``physx`` + * - Isaac-Velocity-Rough-G1-v0 + - Isaac-Velocity-Rough-G1-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Rough-H1-v0 + - Isaac-Velocity-Rough-H1-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Rough-Unitree-A1-v0 + - Isaac-Velocity-Rough-Unitree-A1-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Rough-Unitree-Go1-v0 + - Isaac-Velocity-Rough-Unitree-Go1-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + * - Isaac-Velocity-Rough-Unitree-Go2-v0 + - Isaac-Velocity-Rough-Unitree-Go2-Play-v0 + - Manager Based + - **rsl_rl** (PPO), **skrl** (PPO) + - **physics=** ``newton_mjwarp``, ``physx`` + +.. END-AUTO-GENERATED: comprehensive-environment-list diff --git a/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/augmented_imitation.rst b/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/augmented_imitation.rst new file mode 100644 index 0000000000000000000000000000000000000000..56a3ae91841d54ce864dab70e678e41c0b89efb8 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/augmented_imitation.rst @@ -0,0 +1,441 @@ +.. _augmented-imitation-learning: + +Augmented Imitation Learning +============================ + +This section describes how to use Isaac Lab's imitation learning capabilities with the visual augmentation capabilities of `Cosmos `_ models to generate demonstrations at scale to train visuomotor policies robust against visual variations. + + +.. important:: + The `Cosmos Transfer1 `_ model used in this tutorial is `supported `_ on Ampere and Hopper GPUs. + +Generating Demonstrations +~~~~~~~~~~~~~~~~~~~~~~~~~ + +We use the Isaac Lab Mimic feature that allows the generation of additional demonstrations automatically from a handful of annotated demonstrations. + +.. note:: + This section assumes you already have an annotated dataset of collected demonstrations. If you don't, you can follow the instructions in :ref:`teleoperation-imitation-learning` to collect and annotate your own demonstrations. + +In the following example, we will show you how to use Isaac Lab Mimic to generate additional demonstrations that can be used to train a visuomotor policy directly or can be augmented with visual variations using Cosmos (using the ``Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Cosmos-Mimic-v0`` environment). + +.. note:: + The ``Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Cosmos-Mimic-v0`` environment is similar to the standard visuomotor environment (``Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Mimic-v0``), but with the addition of segmentation masks, depth maps, and normal maps in the generated dataset. These additional modalities are required to get the best results from the visual augmentation done using Cosmos. + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ + --device cpu --enable_cameras --num_envs 10 --generation_num_trials 1000 \ + --input_file ./datasets/annotated_dataset.hdf5 --output_file ./datasets/mimic_dataset_1k.hdf5 \ + --task Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Cosmos-Mimic-v0 \ + --rendering_mode performance + +The number of demonstrations can be increased or decreased, 1000 demonstrations have been shown to provide good training results for this task. + +Additionally, the number of environments in the ``--num_envs`` parameter can be adjusted to speed up data generation. +The suggested number of 10 can be executed on a moderate laptop CPU. +On a more powerful desktop machine, use a larger number of environments for a significant speedup of this step. + +Cosmos Augmentation +~~~~~~~~~~~~~~~~~~~ + +HDF5 to MP4 Conversion +^^^^^^^^^^^^^^^^^^^^^^ + +The ``hdf5_to_mp4.py`` script converts camera frames stored in HDF5 demonstration files to MP4 videos. It supports multiple camera modalities including RGB, segmentation, depth and normal maps. This conversion is necessary for visual augmentation using Cosmos as it only works with video files rather than HDF5 data. + +.. rubric:: Required Arguments + +.. list-table:: + :widths: 30 70 + :header-rows: 0 + + * - ``--input_file`` + - Path to the input HDF5 file. + * - ``--output_dir`` + - Directory to save the output MP4 files. + +.. rubric:: Optional Arguments + +.. list-table:: + :widths: 30 70 + :header-rows: 0 + + * - ``--input_keys`` + - List of input keys to process from the HDF5 file. (default: ["table_cam", "wrist_cam", "table_cam_segmentation", "table_cam_normals", "table_cam_shaded_segmentation", "table_cam_depth"]) + * - ``--video_height`` + - Height of the output video in pixels. (default: 704) + * - ``--video_width`` + - Width of the output video in pixels. (default: 1280) + * - ``--framerate`` + - Frames per second for the output video. (default: 30) + +.. note:: + The default input keys cover all camera modalities as per the naming convention followed in the ``Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Cosmos-Mimic-v0`` environment. We include an additional modality "table_cam_shaded_segmentation" which is not a part of the generated modalities from simulation in the HDF5 data file. Instead, it is automatically generated by this script using a combination of the segmentation and normal maps to get a pseudo-textured segmentation video for better controlling the Cosmos augmentation. + +.. note:: + We recommend using the default values given above for the output video height, width and framerate for the best results with Cosmos augmentation. + +Example usage for the cube stacking task: + +.. code:: bash + + python scripts/tools/hdf5_to_mp4.py \ + --input_file datasets/mimic_dataset_1k.hdf5 \ + --output_dir datasets/mimic_dataset_1k_mp4 + +.. _running-cosmos: + +Running Cosmos for Visual Augmentation +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +After converting the demonstrations to MP4 format, you can use a `Cosmos`_ model to visually augment the videos. Follow the Cosmos documentation for details on the augmentation process. Visual augmentation can include changes to lighting, textures, backgrounds, and other visual elements while preserving the essential task-relevant features. + +We use the RGB, depth and shaded segmentation videos from the previous step as input to the Cosmos model as seen below: + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/cosmos_inputs.gif + :width: 100% + :align: center + :alt: RGB, depth and segmentation control inputs to Cosmos + +We provide an example augmentation output from `Cosmos Transfer1 `_ below: + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/cosmos_output.gif + :width: 100% + :align: center + :alt: Cosmos Transfer1 augmentation output + +We recommend using the `Cosmos Transfer1 `_ model for visual augmentation as we found it to produce the best results in the form of a highly diverse dataset with a wide range of visual variations. You can refer to the `installation instructions `_, the `checkpoint download instructions `_ and `this example `_ for reference on how to use Transfer1 for this usecase. We further recommend the following settings to be used with the Transfer1 model for this task: + +.. note:: + This workflow has been tested with commit ``e4055e39ee9c53165e85275bdab84ed20909714a`` of the Cosmos Transfer1 repository, and it is the recommended version to use. After cloning the Cosmos Transfer1 repository, checkout to this specific commit by running ``git checkout e4055e39ee9c53165e85275bdab84ed20909714a``. + +.. rubric:: Hyperparameters + +.. list-table:: + :widths: 30 70 + :header-rows: 0 + + * - ``negative_prompt`` + - "The video captures a game playing, with bad crappy graphics and cartoonish frames. It represents a recording of old outdated games. The images are very pixelated and of poor CG quality. There are many subtitles in the footage. Overall, the video is unrealistic and appears cg. Plane background." + * - ``sigma_max`` + - 50 + * - ``control_weight`` + - "0.3,0.3,0.6,0.7" + * - ``hint_key`` + - "blur,canny,depth,segmentation" + +Another crucial aspect to get good augmentations is the set of prompts used to control the Cosmos generation. We provide a script, ``cosmos_prompt_gen.py``, to construct prompts from a set of carefully chosen templates that handle various aspects of the augmentation process. + +.. rubric:: Required Arguments + +.. list-table:: + :widths: 30 70 + :header-rows: 0 + + * - ``--templates_path`` + - Path to the file containing templates for the prompts. + +.. rubric:: Optional Arguments + +.. list-table:: + :widths: 30 70 + :header-rows: 0 + + * - ``--num_prompts`` + - Number of prompts to generate (default: 1). + * - ``--output_path`` + - Path to the output file to write generated prompts. (default: prompts.txt) + +.. code:: bash + + python scripts/tools/cosmos/cosmos_prompt_gen.py \ + --templates_path scripts/tools/cosmos/transfer1_templates.json \ + --num_prompts 10 --output_path prompts.txt + +In case you want to create your own prompts, we suggest you refer to the following guidelines: + +1. Keep the prompts as detailed as possible. It is best to have some instruction on how the generation should handle each visible object/region of interest. For instance, the prompts that we provide cover explicit details for the table, lighting, background, robot arm, cubes, and the general setting. + +2. Try to keep the augmentation instructions as realistic and coherent as possible. The more unrealistic or unconventional the prompt is, the worse the model does at retaining key features of the input control video(s). + +3. Keep the augmentation instructions in-sync for each aspect. What we mean by this is that the augmentation for all the objects/regions of interest should be coherent and conventional with respect to each other. For example, it is better to have a prompt such as "The table is of old dark wood with faded polish and food stains and the background consists of a suburban home" instead of something like "The table is of old dark wood with faded polish and food stains and the background consists of a spaceship hurtling through space". + +4. It is vital to include details on key aspects of the input control video(s) that should be retained or left unchanged. In our prompts, we very clearly mention that the cube colors should be left unchanged such that the bottom cube is blue, the middle is red and the top is green. Note that we not only mention what should be left unchanged but also give details on what form that aspect currently has. + +Example command to use the Cosmos Transfer1 model for this usecase: + +.. code:: bash + + export CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:=0}" + export CHECKPOINT_DIR="${CHECKPOINT_DIR:=./checkpoints}" + export NUM_GPU="${NUM_GPU:=1}" + PYTHONPATH=$(pwd) torchrun --nproc_per_node=$NUM_GPU --nnodes=1 --node_rank=0 cosmos_transfer1/diffusion/inference/transfer.py \ + --checkpoint_dir $CHECKPOINT_DIR \ + --video_save_folder outputs/cosmos_dataset_1k_mp4 \ + --controlnet_specs ./controlnet_specs/demo_0.json \ + --offload_text_encoder_model \ + --offload_guardrail_models \ + --num_gpus $NUM_GPU + +Example ``./controlnet_specs/demo_0.json`` json file to use with the above command: + +.. code:: json + + { + "prompt": "A robotic arm is picking up and stacking cubes inside a foggy industrial scrapyard at dawn, surrounded by piles of old robotic parts and twisted metal. The background includes large magnetic cranes, rusted conveyor belts, and flickering yellow floodlights struggling to penetrate the fog. The robot arm is bright teal with a glossy surface and silver stripes on the outer edges; the joints rotate smoothly and the pistons reflect a pale cyan hue. The robot arm is mounted on a table that is light oak wood with a natural grain pattern and a glossy varnish that reflects overhead lights softly; small burn marks dot one corner. The arm is connected to the base mounted on the table. The bottom cube is deep blue, the second cube is bright red, and the top cube is vivid green, maintaining their correct order after stacking. Sunlight pouring in from a large, open window bathes the table and robotic arm in a warm golden light. The shadows are soft, and the scene feels natural and inviting with a slight contrast between light and shadow.", + "negative_prompt": "The video captures a game playing, with bad crappy graphics and cartoonish frames. It represents a recording of old outdated games. The images are very pixelated and of poor CG quality. There are many subtitles in the footage. Overall, the video is unrealistic and appears cg. Plane background.", + "input_video_path" : "mimic_dataset_1k_mp4/demo_0_table_cam.mp4", + "sigma_max": 50, + "vis": { + "input_control": "mimic_dataset_1k_mp4/demo_0_table_cam.mp4", + "control_weight": 0.3 + }, + "edge": { + "control_weight": 0.3 + }, + "depth": { + "input_control": "mimic_dataset_1k_mp4/demo_0_table_cam_depth.mp4", + "control_weight": 0.6 + }, + "seg": { + "input_control": "mimic_dataset_1k_mp4/demo_0_table_cam_shaded_segmentation.mp4", + "control_weight": 0.7 + } + } + +MP4 to HDF5 Conversion +^^^^^^^^^^^^^^^^^^^^^^ + +The ``mp4_to_hdf5.py`` script converts the visually augmented MP4 videos back to HDF5 format for training. This step is crucial as it ensures the augmented visual data is in the correct format for training visuomotor policies in Isaac Lab and pairs the videos with the corresponding demonstration data from the original dataset. + +.. rubric:: Required Arguments + +.. list-table:: + :widths: 30 70 + :header-rows: 0 + + * - ``--input_file`` + - Path to the input HDF5 file containing the original demonstrations. + * - ``--videos_dir`` + - Directory containing the visually augmented MP4 videos. + * - ``--output_file`` + - Path to save the new HDF5 file with augmented videos. + +.. note:: + The input HDF5 file is used to preserve the non-visual data (such as robot states and actions) while replacing the visual data with the augmented versions. + +.. important:: + The visually augmented MP4 files must follow the naming convention ``demo_{demo_id}_*.mp4``, where: + + - ``demo_id`` matches the demonstration ID from the original MP4 file + + - ``*`` signifies that the file name can be as per user preference starting from this point + + This naming convention is required for the script to correctly pair the augmented videos with their corresponding demonstrations. + +Example usage for the cube stacking task: + +.. code:: bash + + python scripts/tools/mp4_to_hdf5.py \ + --input_file datasets/mimic_dataset_1k.hdf5 \ + --videos_dir datasets/cosmos_dataset_1k_mp4 \ + --output_file datasets/cosmos_dataset_1k.hdf5 + +Pre-generated Dataset +^^^^^^^^^^^^^^^^^^^^^ + +We provide a pre-generated dataset in HDF5 format containing visually augmented demonstrations for the cube stacking task. This dataset can be used if you do not wish to run Cosmos locally to generate your own augmented data. The dataset is available on `Hugging Face `_ and contains both (as separate dataset files), original and augmented demonstrations, that can be used for training visuomotor policies. + +Merging Datasets +^^^^^^^^^^^^^^^^ + +The ``merge_hdf5_datasets.py`` script combines multiple HDF5 datasets into a single file. This is useful when you want to combine the original demonstrations with the augmented ones to create a larger, more diverse training dataset. + +.. rubric:: Required Arguments + +.. list-table:: + :widths: 30 70 + :header-rows: 0 + + * - ``--input_files`` + - A list of paths to HDF5 files to merge. + +.. rubric:: Optional Arguments + +.. list-table:: + :widths: 30 70 + :header-rows: 0 + + * - ``--output_file`` + - File path to merged output. (default: merged_dataset.hdf5) + +.. tip:: + Merging datasets can help improve policy robustness by exposing the model to both original and augmented visual conditions during training. + +Example usage for the cube stacking task: + +.. code:: bash + + python scripts/tools/merge_hdf5_datasets.py \ + --input_files datasets/mimic_dataset_1k.hdf5 datasets/cosmos_dataset_1k.hdf5 \ + --output_file datasets/mimic_cosmos_dataset.hdf5 + +Model Training and Evaluation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Robomimic Setup +^^^^^^^^^^^^^^^ + +As an example, we will train a BC agent implemented in `Robomimic `__ to train a policy. Any other framework or training method could be used. + +To install the robomimic framework, use the following commands: + +.. code:: bash + + # install the dependencies + sudo apt install cmake build-essential + # install python module (for robomimic) + ./isaaclab.sh -i robomimic + +Training an agent +^^^^^^^^^^^^^^^^^ + +Using the generated data, we can now train a visuomotor BC agent for ``Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Cosmos-v0``: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/robomimic/train.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Cosmos-v0 --algo bc \ + --dataset ./datasets/mimic_cosmos_dataset.hdf5 \ + --name bc_rnn_image_franka_stack_mimic_cosmos + +.. note:: + By default the trained models and logs will be saved to ``IsaacLab/logs/robomimic``. + +Evaluation +^^^^^^^^^^ + +The ``robust_eval.py`` script evaluates trained visuomotor policies in simulation. This evaluation helps assess how well the policy generalizes to different visual variations and whether the visually augmented data has improved the policy's robustness. + +Below is an explanation of the different settings used for evaluation: + +.. rubric:: Evaluation Settings + +.. list-table:: + :widths: 30 70 + :header-rows: 0 + + * - ``Vanilla`` + - Exact same setting as that used during Mimic data generation. + * - ``Light Intensity`` + - Light intensity/brightness is varied, all other aspects remain the same. + * - ``Light Color`` + - Light color is varied, all other aspects remain the same. + * - ``Light Texture (Background)`` + - Light texture/background is varied, all other aspects remain the same. + * - ``Table Texture`` + - Table's visual texture is varied, all other aspects remain the same. + * - ``Robot Arm Texture`` + - Robot arm's visual texture is varied, all other aspects remain the same. + +.. rubric:: Required Arguments + +.. list-table:: + :widths: 30 70 + :header-rows: 0 + + * - ``--task`` + - Name of the environment. + * - ``--input_dir`` + - Directory containing the model checkpoints to evaluate. + +.. rubric:: Optional Arguments + +.. list-table:: + :widths: 30 70 + :header-rows: 0 + + * - ``--start_epoch`` + - Epoch of the checkpoint to start the evaluation from. (default: 100) + * - ``--horizon`` + - Step horizon of each rollout. (default: 400) + * - ``--num_rollouts`` + - Number of rollouts per model per setting. (default: 15) + * - ``--num_seeds`` + - Number of random seeds to evaluate. (default: 3) + * - ``--seeds`` + - List of specific seeds to use instead of random ones. + * - ``--log_dir`` + - Directory to write results to. (default: /tmp/policy_evaluation_results) + * - ``--log_file`` + - Name of the output file. (default: results) + * - ``--norm_factor_min`` + - Minimum value of the action space normalization factor. + * - ``--norm_factor_max`` + - Maximum value of the action space normalization factor. + * - ``--disable_fabric`` + - Whether to disable fabric and use USD I/O operations. + +.. note:: + The evaluation results will help you understand if the visual augmentation has improved the policy's performance and robustness. Compare these results with evaluations on the original dataset to measure the impact of augmentation. + +Example usage for the cube stacking task: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/robomimic/robust_eval.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Cosmos-v0 \ + --input_dir logs/robomimic/Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Cosmos-v0/bc_rnn_image_franka_stack_mimic_cosmos/*/models \ + --log_dir robust_results/bc_rnn_image_franka_stack_mimic_cosmos \ + --log_file result \ + --enable_cameras \ + --seeds 0 \ + --num_rollouts 15 \ + --rendering_mode performance + +.. tip:: + Verify that the models directory is not empty. By default, the training script saves models every 20 epochs starting from epoch 100. + +.. note:: + This script can take over a day or even longer to run (depending on the hardware being used). This behavior is expected. + +We use the above script to compare models trained with 1000 Mimic-generated demonstrations, 2000 Mimic-generated demonstrations and 2000 Cosmos-Mimic-generated demonstrations (1000 original mimic + 1000 Cosmos augmented) respectively. We use the same seeds (0, 1000 and 5000) for all three models and provide the metrics (averaged across best checkpoints for each seed) below: + +.. rubric:: Model Comparison + +.. list-table:: + :widths: 25 25 25 25 + :header-rows: 0 + + * - **Evaluation Setting** + - **Mimic 1k Baseline** + - **Mimic 2k Baseline** + - **Cosmos-Mimic 2k** + * - ``Vanilla`` + - 62% + - 96.6% + - 86.6% + * - ``Light Intensity`` + - 11.1% + - 20% + - 62.2% + * - ``Light Color`` + - 24.6% + - 30% + - 77.7% + * - ``Light Texture (Background)`` + - 16.6% + - 20% + - 68.8% + * - ``Table Texture`` + - 0% + - 0% + - 20% + * - ``Robot Arm Texture`` + - 0% + - 0% + - 4.4% + +The above trained models' checkpoints can be accessed `here `_ in case you wish to use the models directly. diff --git a/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/humanoids_imitation.rst b/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/humanoids_imitation.rst new file mode 100644 index 0000000000000000000000000000000000000000..44dc7d19cf4475742b14c7aff8eff0bf5024af70 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/humanoids_imitation.rst @@ -0,0 +1,906 @@ +.. _data-generation-imitation-learning-humanoids: + +Examples: Data Generation and Imitation Learning for Humanoids +============================================================== + +This page covers data generation and imitation learning workflows for humanoid robots (GR-1, G1) with Isaac Lab Mimic: + +* **Demo 1:** Data generation and policy training for a humanoid robot (GR-1 pick and place) +* **Demo 2:** Visuomotor policy for a humanoid robot (GR-1 nut pouring) +* **Demo 3:** Data generation and policy training for humanoid robot locomanipulation (Unitree G1) + +.. important:: + + Complete the tutorial in :ref:`Synthetic Data Generation and Imitation Learning with Isaac Lab Mimic ` + before proceeding with the following demonstrations to + understand the data collection, annotation, and generation steps of Isaac Lab Mimic. + + +Demo 1: Data Generation and Policy Training for a Humanoid Robot +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/gr-1_steering_wheel_pick_place.gif + :width: 100% + :align: center + :alt: GR-1 humanoid robot performing a pick and place task + :figclass: align-center + + +Isaac Lab Mimic supports data generation for robots with multiple end effectors. In the following demonstration, we will show how to generate data +to train a Fourier GR-1 humanoid robot to perform a pick and place task. + +Optional: Collect and annotate demonstrations +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Collect human demonstrations +"""""""""""""""""""""""""""" +.. note:: + + Data collection for the GR-1 humanoid robot environment requires use of an Apple Vision Pro headset. If you do not have access to + an Apple Vision Pro, you may skip this step and continue on to the next step: :ref:`Generate the dataset `. + A pre-recorded annotated dataset is provided in the next step. + +.. tip:: + The GR1 scene utilizes the wrist poses from the Apple Vision Pro (AVP) as setpoints for a differential IK controller (Pink-IK). + The differential IK controller requires the user's wrist pose to be close to the robot's initial or current pose for optimal performance. + Rapid movements of the user's wrist may cause it to deviate significantly from the goal state, which could prevent the IK controller from finding the optimal solution. + This may result in a mismatch between the user's wrist and the robot's wrist. + You can increase the gain of all the `Pink-IK controller's FrameTasks `__ to track the AVP wrist poses with lower latency. + However, this may lead to more jerky motion. + Separately, the finger joints of the robot are retargeted to the user's finger joints using the `dex-retargeting `_ library. + +Set up the CloudXR Runtime and Apple Vision Pro for teleoperation by following the steps in :ref:`cloudxr-teleoperation`. +CPU simulation is used in the following steps for better XR performance when running a single environment. + +Collect a set of human demonstrations. +A success demo requires the object to be placed in the bin and for the robot's right arm to be retracted to the starting position. + +The Isaac Lab Mimic Env GR-1 humanoid robot is set up such that the left hand has a single subtask, while the right hand has two subtasks. +The first subtask involves the right hand remaining idle while the left hand picks up and moves the object to the position where the right hand will grasp it. +This setup allows Isaac Lab Mimic to interpolate the right hand's trajectory accurately by using the object's pose, especially when poses are randomized during data generation. +Therefore, avoid moving the right hand while the left hand picks up the object and brings it to a stable position. + + +.. |good_demo| image:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/gr-1_steering_wheel_pick_place_good_demo.gif + :width: 49% + :alt: GR-1 humanoid robot performing a good pick and place demonstration + +.. |bad_demo| image:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/gr-1_steering_wheel_pick_place_bad_demo.gif + :width: 49% + :alt: GR-1 humanoid robot performing a bad pick and place demonstration + +|good_demo| |bad_demo| + +.. centered:: Left: A good human demonstration with smooth and steady motion. Right: A bad demonstration with jerky and exaggerated motion. + + +Collect five demonstrations by running the following command: + +.. code:: bash + + ./isaaclab.sh -p scripts/tools/record_demos.py \ + --task Isaac-PickPlace-GR1T2-Abs-v0 \ + --visualizer kit \ + --xr \ + --device cpu \ + --num_demos 5 \ + --dataset_file ./datasets/dataset_gr1.hdf5 + + +.. note:: + We also provide a GR-1 pick and place task with waist degrees-of-freedom enabled ``Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0`` (see :ref:`environments` for details on the available environments, including the GR1 Waist Enabled variant). The same command above applies but with the task name changed to ``Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0``. + +.. tip:: + If a demo fails during data collection, the environment can be reset using the teleoperation controls panel in the XR teleop client + on the Apple Vision Pro or via voice control by saying "reset". See :ref:`teleoperate-apple-vision-pro` for more details. + + The robot uses simplified collision meshes for physics calculations that differ from the detailed visual meshes displayed in the simulation. Due to this difference, you may occasionally observe visual artifacts where parts of the robot appear to penetrate other objects or itself, even though proper collision handling is occurring in the physics simulation. + +You can replay the collected demonstrations by running the following command: + +.. code:: bash + + ./isaaclab.sh -p scripts/tools/replay_demos.py \ + --task Isaac-PickPlace-GR1T2-Abs-v0 \ + --visualizer kit \ + --device cpu \ + --dataset_file ./datasets/dataset_gr1.hdf5 + +.. note:: + Non-determinism may be observed during replay as physics in IsaacLab are not deterministically reproducible when using ``env.reset``. + + +Annotate the demonstrations +""""""""""""""""""""""""""" + +Unlike the :ref:`Franka stacking task `, the GR-1 pick and place task uses manual annotation to define subtasks. + +The pick and place task has one subtask for the left arm (pick) and two subtasks for the right arm (idle, place). +Annotations denote the end of a subtask. For the pick and place task, this means there are no annotations for the left arm and one annotation for the right arm (the end of the final subtask is always implicit). + +Each demo requires a single annotation between the first and second subtask of the right arm. This annotation ("S" button press) should be done when the right robot arm finishes the "idle" subtask and begins to +move towards the target object. An example of a correct annotation is shown below: + +.. figure:: ../../_static/tasks/manipulation/gr-1_pick_place_annotation.jpg + :width: 100% + :align: center + +Annotate the demonstrations by running the following command: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/annotate_demos.py \ + --task Isaac-PickPlace-GR1T2-Abs-Mimic-v0 \ + --visualizer kit \ + --device cpu \ + --input_file ./datasets/dataset_gr1.hdf5 \ + --output_file ./datasets/dataset_annotated_gr1.hdf5 + +.. note:: + + The script prints the keyboard commands for manual annotation and the current subtask being annotated: + + .. code:: text + + Annotating episode #0 (demo_0) + Playing the episode for subtask annotations for eef "right". + Subtask signals to annotate: + - Termination: ['idle_right'] + + Press "N" to begin. + Press "B" to pause. + Press "S" to annotate subtask signals. + Press "Q" to skip the episode. + +.. tip:: + + If the object does not get placed in the bin during annotation, you can press "N" to replay the episode and annotate again. Or you can press "Q" to skip the episode and annotate the next one. + +.. _generate-the-dataset: + +Generate the dataset +^^^^^^^^^^^^^^^^^^^^ + +If you skipped the prior collection and annotation step, download the pre-recorded annotated dataset ``dataset_annotated_gr1.hdf5`` from +here: `[Annotated GR1 Dataset] `_. +Place the file under ``IsaacLab/datasets`` and run the following command to generate a new dataset with 1000 demonstrations. + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ + --device cpu \ + --num_envs 20 \ + --generation_num_trials 1000 \ + --input_file ./datasets/dataset_annotated_gr1.hdf5 \ + --output_file ./datasets/generated_dataset_gr1.hdf5 + +Train a policy +^^^^^^^^^^^^^^ + +Use `Robomimic `__ to train a policy for the generated dataset. + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/robomimic/train.py \ + --task Isaac-PickPlace-GR1T2-Abs-v0 \ + --algo bc \ + --normalize_training_actions \ + --dataset ./datasets/generated_dataset_gr1.hdf5 + +The training script will normalize the actions in the dataset to the range [-1, 1]. +The normalization parameters are saved in the model directory under ``PATH_TO_MODEL_DIRECTORY/logs/normalization_params.txt``. +Record the normalization parameters for later use in the visualization step. + +.. note:: + By default the trained models and logs will be saved to ``IsaacLab/logs/robomimic``. + +Visualize the results +^^^^^^^^^^^^^^^^^^^^^ + +Visualize the results of the trained policy by running the following command, using the normalization parameters recorded in the prior training step: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/robomimic/play.py \ + --task Isaac-PickPlace-GR1T2-Abs-v0 \ + --visualizer kit \ + --device cpu \ + --num_rollouts 50 \ + --horizon 400 \ + --norm_factor_min \ + --norm_factor_max \ + --checkpoint /PATH/TO/desired_model_checkpoint.pth + +.. note:: + Change the ``NORM_FACTOR`` in the above command with the values generated in the training step. + +.. tip:: + + **If you don't see expected performance results:** It is critical to test policies from various checkpoint epochs. + Performance can vary significantly between epochs, and the best-performing checkpoint is often not the final one. + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/gr-1_steering_wheel_pick_place_policy.gif + :width: 100% + :align: center + :alt: GR-1 humanoid robot performing a pick and place task + :figclass: align-center + + The trained policy performing the pick and place task in Isaac Lab. + +.. note:: + + **Expected Success Rates and Timings for Pick and Place GR1T2 Task** + + * Success rate for data generation depends on the quality of human demonstrations (how well the user performs them) and dataset annotation quality. Both data generation and downstream policy success are sensitive to these factors and can show high variance. See :ref:`Common Pitfalls when Generating Data ` for tips to improve your dataset. + * Data generation success for this task is typically 65-80% over 1000 demonstrations, taking 18-40 minutes depending on GPU hardware and success rate (19 minutes on a RTX ADA 6000 @ 80% success rate). + * Behavior Cloning (BC) policy success is typically 75-86% (evaluated on 50 rollouts) when trained on 1000 generated demonstrations for 2000 epochs (default), depending on demonstration quality. Training takes approximately 29 minutes on a RTX ADA 6000. + * **Recommendation:** Train for 2000 epochs with 1000 generated demonstrations, and **evaluate multiple checkpoints saved between the 1000th and 2000th epochs** to select the best-performing policy. Testing various epochs is essential for finding optimal performance. + + +Demo 2: Visuomotor Policy for a Humanoid Robot +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/gr-1_nut_pouring_policy.gif + :width: 100% + :align: center + :alt: GR-1 humanoid robot performing a pouring task + :figclass: align-center + +Download the Dataset +^^^^^^^^^^^^^^^^^^^^ + +Download the pre-generated dataset from `here `__ and place it under ``IsaacLab/datasets/generated_dataset_gr1_nut_pouring.hdf5`` +(**Note: The dataset size is approximately 15GB**). The dataset contains 1000 demonstrations of a humanoid robot performing a pouring/placing task that was +generated using Isaac Lab Mimic for the ``Isaac-NutPour-GR1T2-Pink-IK-Abs-Mimic-v0`` task. + +.. hint:: + + If desired, data collection, annotation, and generation can be done using the same commands as the prior examples. + + The robot first picks up the red beaker and pours the contents into the yellow bowl. + Then, it drops the red beaker into the blue bin. Lastly, it places the yellow bowl onto the white scale. + See the video in the :ref:`visualize-results-demo-2` section below for a visual demonstration of the task. + + **The success criteria for this task requires the red beaker to be placed in the blue bin, the green nut to be in the yellow bowl, + and the yellow bowl to be placed on top of the white scale.** + + .. attention:: + **The following commands are only for your reference and are not required for this demo.** + + To collect demonstrations: + + .. code:: bash + + ./isaaclab.sh -p scripts/tools/record_demos.py \ + --task Isaac-NutPour-GR1T2-Pink-IK-Abs-v0 \ + --visualizer kit \ + --device cpu \ + --xr \ + --num_demos 5 \ + --dataset_file ./datasets/dataset_gr1_nut_pouring.hdf5 + + To annotate the demonstrations: + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/annotate_demos.py \ + --task Isaac-NutPour-GR1T2-Pink-IK-Abs-Mimic-v0 \ + --visualizer kit \ + --enable_cameras \ + --device cpu \ + --input_file ./datasets/dataset_gr1_nut_pouring.hdf5 \ + --output_file ./datasets/dataset_annotated_gr1_nut_pouring.hdf5 + + .. warning:: + There are multiple right eef annotations for this task. Annotations for subtasks for the same eef cannot have the same action index. + Make sure to annotate the right eef subtasks with different action indices. + + + To generate the dataset: + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ + --task Isaac-NutPour-GR1T2-Pink-IK-Abs-Mimic-v0 \ + --visualizer kit \ + --enable_cameras \ + --device cpu \ + --generation_num_trials 1000 \ + --num_envs 5 \ + --input_file ./datasets/dataset_annotated_gr1_nut_pouring.hdf5 \ + --output_file ./datasets/generated_dataset_gr1_nut_pouring.hdf5 + + +Train a policy +^^^^^^^^^^^^^^ + +Use `Robomimic `__ to train a visuomotor BC agent for the task. + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/robomimic/train.py \ + --task Isaac-NutPour-GR1T2-Pink-IK-Abs-v0 \ + --algo bc \ + --normalize_training_actions \ + --dataset ./datasets/generated_dataset_gr1_nut_pouring.hdf5 + +The training script will normalize the actions in the dataset to the range [-1, 1]. +The normalization parameters are saved in the model directory under ``PATH_TO_MODEL_DIRECTORY/logs/normalization_params.txt``. +Record the normalization parameters for later use in the visualization step. + +.. note:: + By default the trained models and logs will be saved to ``IsaacLab/logs/robomimic``. + +You can also post-train a `GR00T `__ foundation model to deploy a Vision-Language-Action policy for the task. + +Please refer to the `IsaacLabEvalTasks `__ repository for more details. + +.. _visualize-results-demo-2: + +Visualize the results +^^^^^^^^^^^^^^^^^^^^^ + +Visualize the results of the trained policy by running the following command, using the normalization parameters recorded in the prior training step: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/robomimic/play.py \ + --task Isaac-NutPour-GR1T2-Pink-IK-Abs-v0 \ + --visualizer kit \ + --device cpu \ + --enable_cameras \ + --num_rollouts 50 \ + --horizon 350 \ + --norm_factor_min \ + --norm_factor_max \ + --checkpoint /PATH/TO/desired_model_checkpoint.pth + +.. note:: + Change the ``NORM_FACTOR`` in the above command with the values generated in the training step. + +.. tip:: + + **If you don't see expected performance results:** Test policies from various checkpoint epochs, not just the final one. + Policy performance can vary substantially across training, and intermediate checkpoints often yield better results. + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/gr-1_nut_pouring_policy.gif + :width: 100% + :align: center + :alt: GR-1 humanoid robot performing a pouring task + :figclass: align-center + + The trained visuomotor policy performing the pouring task in Isaac Lab. + +.. note:: + + **Expected Success Rates and Timings for Visuomotor Nut Pour GR1T2 Task** + + * Success rate for data generation depends on the quality of human demonstrations (how well the user performs them) and dataset annotation quality. Both data generation and downstream policy success are sensitive to these factors and can show high variance. See :ref:`Common Pitfalls when Generating Data ` for tips to improve your dataset. + * Data generation for 1000 demonstrations takes approximately 10 hours on a RTX ADA 6000. + * Behavior Cloning (BC) policy success is typically 50-60% (evaluated on 50 rollouts) when trained on 1000 generated demonstrations for 600 epochs (default). Training takes approximately 15 hours on a RTX ADA 6000. + * **Recommendation:** Train for 600 epochs with 1000 generated demonstrations, and **evaluate multiple checkpoints saved between the 300th and 600th epochs** to select the best-performing policy. Testing various epochs is critical for achieving optimal performance. + + +Demo 3: Data Generation and Policy Training for Humanoid Robot Locomanipulation with Unitree G1 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In this demo, we showcase the integration of locomotion and manipulation capabilities within a single humanoid robot system. +This locomanipulation environment enables data collection for complex tasks that combine navigation and object manipulation. +The demonstration follows a multi-step process: first, it generates pick and place tasks similar to Demo 1, then introduces +a navigation component that uses specialized scripts to generate scenes where the humanoid robot must move from point A to point B. +The robot picks up an object at the initial location (point A) and places it at the target destination (point B). + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/locomanipulation-g-1_steering_wheel_pick_place.gif + :width: 100% + :align: center + :alt: G1 humanoid robot with locomanipulation performing a pick and place task + :figclass: align-center + +.. note:: + **Locomotion policy training** + + The locomotion policy used in this integration example was trained using the `AGILE `__ framework. + AGILE is an officially supported humanoid control training pipeline that leverages the manager based environment in Isaac Lab. It will also be + seamlessly integrated with other evaluation and deployment tools across Isaac products. This allows teams to rely on a single, maintained stack + covering all necessary infrastructure and tooling for policy training, with easy export to real-world deployment. The AGILE repository contains + updated pre-trained policies with separate upper and lower body policies for flexibility. They have been verified in the real world and can be + directly deployed. Users can also train their own locomotion or whole-body control policies using the AGILE framework. + +.. _generate-the-manipulation-dataset: + +Generate the manipulation dataset +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The same data generation and policy training steps from Demo 1 can be applied to the G1 humanoid robot with locomanipulation capabilities. +This demonstration shows how to train a G1 robot to perform pick and place tasks with full-body locomotion and manipulation. + +The process follows the same workflow as Demo 1, but uses the ``Isaac-PickPlace-Locomanipulation-G1-Abs-v0`` task environment. + +Follow the same data collection, annotation, and generation process as demonstrated in Demo 1, but adapted for the G1 locomanipulation task. + +.. hint:: + + If desired, data collection and annotation can be done using the same commands as the prior examples for validation of the dataset. + + The G1 robot with locomanipulation capabilities combines full-body locomotion with manipulation to perform pick and place tasks. + + **Note that the following commands are only for your reference and dataset validation purposes - they are not required for this demo.** + + To collect demonstrations: + + .. code:: bash + + ./isaaclab.sh -p scripts/tools/record_demos.py \ + --device cpu \ + --xr \ + --visualizer kit \ + --task Isaac-PickPlace-Locomanipulation-G1-Abs-v0 \ + --dataset_file ./datasets/dataset_g1_locomanip.hdf5 \ + --num_demos 5 + + .. note:: + + Depending on how the Apple Vision Pro app was initialized, the hands of the operator might be very far up or far down compared to the hands of the G1 robot. If this is the case, you can click **Stop XR** in the XR tab in Isaac Lab, and move the AR Anchor prim. Adjust it down to bring the hands of the operator lower, and up to bring them higher. Click **Start XR** to resume teleoperation session. Make sure to match the hands of the robot before clicking **Play** in the Apple Vision Pro, otherwise there will be an undesired large force generated initially. + + You can replay the collected demonstrations by running: + + .. code:: bash + + ./isaaclab.sh -p scripts/tools/replay_demos.py \ + --device cpu \ + --visualizer kit \ + --task Isaac-PickPlace-Locomanipulation-G1-Abs-v0 \ + --dataset_file ./datasets/dataset_g1_locomanip.hdf5 + + To annotate the demonstrations: + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/annotate_demos.py \ + --device cpu \ + --visualizer kit \ + --task Isaac-Locomanipulation-G1-Abs-Mimic-v0 \ + --input_file ./datasets/dataset_g1_locomanip.hdf5 \ + --output_file ./datasets/dataset_annotated_g1_locomanip.hdf5 + + +If you skipped the prior collection and annotation step, download the pre-recorded annotated dataset ``dataset_annotated_g1_locomanip.hdf5`` from +here: `[Annotated G1 Dataset] `_. +Place the file under ``IsaacLab/datasets`` and run the following command to generate a new dataset with 1000 demonstrations. + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ + --device cpu --num_envs 20 --generation_num_trials 1000 \ + --input_file ./datasets/dataset_annotated_g1_locomanip.hdf5 --output_file ./datasets/generated_dataset_g1_locomanip.hdf5 + + +Train a manipulation-only policy +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +At this point you can train a policy that only performs manipulation tasks using the generated dataset: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/robomimic/train.py \ + --task Isaac-PickPlace-Locomanipulation-G1-Abs-v0 --algo bc \ + --normalize_training_actions \ + --dataset ./datasets/generated_dataset_g1_locomanip.hdf5 + +Visualize the results +^^^^^^^^^^^^^^^^^^^^^ + +Visualize the trained policy performance: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/robomimic/play.py \ + --device cpu \ + --visualizer kit \ + --task Isaac-PickPlace-Locomanipulation-G1-Abs-v0 \ + --num_rollouts 50 \ + --horizon 400 \ + --norm_factor_min \ + --norm_factor_max \ + --checkpoint /PATH/TO/desired_model_checkpoint.pth + +.. note:: + Change the ``NORM_FACTOR`` in the above command with the values generated in the training step. + +.. tip:: + + **If you don't see expected performance results:** Always test policies from various checkpoint epochs. + Different epochs can produce significantly different results, so evaluate multiple checkpoints to find the optimal model. + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/locomanipulation-g-1_steering_wheel_pick_place.gif + :width: 100% + :align: center + :alt: G1 humanoid robot performing a pick and place task + :figclass: align-center + + The trained policy performing the pick and place task in Isaac Lab. + +.. note:: + + **Expected Success Rates and Timings for Locomanipulation Pick and Place Task** + + * Success rate for data generation depends on the quality of human demonstrations (how well the user performs them) and dataset annotation quality. Both data generation and downstream policy success are sensitive to these factors and can show high variance. See :ref:`Common Pitfalls when Generating Data ` for tips to improve your dataset. + * Data generation success for this task is typically 65-82% over 1000 demonstrations, taking 18-40 minutes depending on GPU hardware and success rate (18 minutes on a RTX ADA 6000 @ 82% success rate). + * Behavior Cloning (BC) policy success is typically 75-85% (evaluated on 50 rollouts) when trained on 1000 generated demonstrations for 2000 epochs (default), depending on demonstration quality. Training takes approximately 40 minutes on a RTX ADA 6000. + * **Recommendation:** Train for 2000 epochs with 1000 generated demonstrations, and **evaluate multiple checkpoints saved between the 1000th and 2000th epochs** to select the best-performing policy. Testing various epochs is essential for finding optimal performance. + +.. _generate-the-dataset-with-manipulation-and-point-to-point-navigation: + +Generate the dataset with manipulation and point-to-point navigation +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To create a comprehensive locomanipulation dataset that combines both manipulation and navigation capabilities, you can generate a navigation dataset using the manipulation dataset from the previous step as input. + +.. tip:: + + **Skip data generation:** A pre-made locomanipulation dataset in LeRobot format is available on + Hugging Face at `nvidia/g1_locomanip_dataset `__. + Downloading it lets you skip this section and the dataset conversion step, proceeding directly to + **Finetune the policy** below. + + Download and unzip the dataset: + + .. code:: bash + + huggingface-cli download nvidia/g1_locomanip_dataset --repo-type dataset --local-dir ./datasets/g1_locomanip_hf + unzip ./datasets/g1_locomanip_hf/*.zip -d ./datasets/ + + The archive extracts to ``./datasets/g1_simple_high_var_lerobot/``. + Use this path as the ``--dataset-path`` in the finetuning step. + Policies trained on this dataset require ``--policy_quat_format wxyz`` at rollout time. + +.. list-table:: + :widths: 50 50 + :header-rows: 0 + + * - .. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/g1_locomanip_no_obstacles.gif + :height: 260px + :align: center + :alt: G1 locomanipulation data generation without obstacles + + Default: no obstacles (open scene). + - .. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/g1_locomanip_with_obstacles.gif + :height: 260px + :align: center + :alt: G1 locomanipulation data generation with forklift obstacles + + With 8 forklift obstacles and ``--randomize_placement`` enabled. + +The locomanipulation dataset generation process takes the previously generated manipulation dataset and creates scenarios where the robot must navigate from one location to another while performing manipulation tasks. This creates a more complex dataset that includes both locomotion and manipulation behaviors. + +To generate the locomanipulation dataset, use the following command: + +.. code:: bash + + ./isaaclab.sh -p \ + scripts/imitation_learning/locomanipulation_sdg/generate_data.py \ + --device cpu \ + --kit_args="--enable isaacsim.replicator.experimental.mobility_gen" \ + --task="Isaac-G1-SteeringWheel-Locomanipulation" \ + --dataset ./datasets/generated_dataset_g1_locomanip.hdf5 \ + --num_runs 1 \ + --lift_step 60 \ + --navigate_step 130 \ + --output_file ./datasets/generated_dataset_g1_locomanipulation_sdg.hdf5 \ + --enable_cameras \ + --randomize_placement \ + --visualizer kit + +.. note:: + + The input dataset (``--dataset``) should be the manipulation dataset generated in the previous step. You can specify any output filename using the ``--output_file_name`` parameter. + +The key parameters for locomanipulation dataset generation are: + +* ``--lift_step 60``: Number of steps for the lifting phase of the manipulation task. This should mark the point immediately after the robot has grasped the object. +* ``--navigate_step 130``: Number of steps for the navigation phase between locations. This should mark the point where the robot has lifted the object and is ready to walk. +* ``--output_file``: Name of the output dataset file + +.. note:: + + You can change the number of obstacles (forklifts and boxes) in the scene by editing the locomanipulation SDG environment configuration. In ``source/isaaclab_mimic/isaaclab_mimic/locomanipulation_sdg/envs/g1_locomanipulation_sdg_env.py``, set the module-level constants ``NUM_FORKLIFTS`` and ``NUM_BOXES`` to the desired counts. Use ``--randomize_placement`` when running :file:`generate_data.py` to randomize obstacle and fixture positions each run. + +This process creates a dataset where the robot performs the manipulation task at different locations, requiring it to navigate between points while maintaining the learned manipulation behaviors. The resulting dataset can be used to train policies that combine both locomotion and manipulation capabilities. + +.. note:: + + You can visualize the robot trajectory results with the following script command: + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/locomanipulation_sdg/plot_navigation_trajectory.py --input_file datasets/generated_dataset_g1_locomanipulation_sdg.hdf5 --output_dir /PATH/TO/DESIRED_OUTPUT_DIR + +The data generated from this locomanipulation pipeline can also be used to finetune an imitation learning policy using GR00T N1.5. +The following steps describe how to install GR00T, convert the dataset to LeRobot format, finetune the policy, and run rollouts in Isaac Lab. + +.. _finetune-groot-n15-for-locomanipulation: + +Finetune GR00T N1.5 policy for locomanipulation +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**Prerequisites:** Generate the locomanipulation dataset using the command in the previous section (e.g. ``generated_dataset_g1_locomanipulation_sdg.hdf5``). +The conversion step accepts a directory of SDG HDF5 files, so you may group multiple ``generate_data.py`` outputs together — but the directory must contain **only** SDG outputs, not other HDF5 files from earlier steps (e.g. ``dataset_annotated_g1_locomanip.hdf5`` or ``generated_dataset_g1_locomanip.hdf5``). + +Install GR00T with Isaac Lab (uv) +""""""""""""""""""""""""""""""""" + +Clone the Isaac-GR00T repository and install GR00T N1.5 in the same uv environment used for Isaac Lab. From a parent directory that contains both repositories (or adjust paths accordingly), run: + +.. code:: bash + + git clone -b n1.5-release https://github.com/NVIDIA/Isaac-GR00T + +Copy the G1 locomanipulation data config from Isaac Lab into the GR00T experiment data config: + +.. code:: bash + + cp IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/data_config.py Isaac-GR00T/gr00t/experiment/data_config.py + +Then, from the **Isaac-GR00T** directory, install GR00T N1.5 and its dependencies: + +.. code:: bash + + cd Isaac-GR00T + uv pip install -e . + uv pip install wheel + MAX_JOBS=4 uv pip install --no-build-isolation flash-attn==2.7.1.post4 + MAX_JOBS=4 uv pip install --no-build-isolation 'git+https://github.com/facebookresearch/pytorch3d.git@v0.7.9' + uv pip install diffusers decord zmq + +.. note:: + + **If you cannot install or use flash-attn**, an optional patch is provided that switches the + bundled Eagle 2.5 VL model to PyTorch SDPA. Use this if ``flash-attn`` fails to build for your + environment, or if it installs but raises a runtime error such as + ``RuntimeError: FlashAttention only supports Ampere GPUs or newer`` (for example on Blackwell + GPUs, which ``flash-attn==2.7.1.post4`` does not have prebuilt kernels for). After the patch, + finetune and rollout run on any CUDA arch supported by your PyTorch build, at the cost of + flash-attn's training speedup. Skip the ``flash-attn`` install line above, then apply the + patch from the **Isaac-GR00T** directory (the sibling layout above means the IsaacLab + checkout is at ``../IsaacLab``): + + .. code:: bash + + git apply ../IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/no_flash_attn.patch + +Convert dataset to LeRobot format +""""""""""""""""""""""""""""""""" + +GR00T N1.5 expects data in LeRobot format. From the **IsaacLab** repository root, run the conversion script. ```` is a directory containing one or more SDG ``.hdf5`` files produced by ``generate_data.py`` (and **no other HDF5 files**). ```` is the LeRobot-format output directory (e.g. ``./datasets/datasets_train_200_lerobot``). Episodes with very low object displacement are skipped. + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/locomanipulation_sdg/gr00t/convert_dataset.py + +Example — move the SDG output into its own directory first so the converter only sees SDG files: + +.. code:: bash + + mkdir -p ./datasets/locomanip_sdg + mv ./datasets/generated_dataset_g1_locomanipulation_sdg.hdf5 ./datasets/locomanip_sdg/ + ./isaaclab.sh -p scripts/imitation_learning/locomanipulation_sdg/gr00t/convert_dataset.py ./datasets/locomanip_sdg ./datasets/datasets_train_200_lerobot + +Finetune the policy +""""""""""""""""""" + +Run finetuning from the **Isaac-GR00T** repository root. Use the LeRobot-format output path from the previous step as ``--dataset-path`` and choose an ``--output-dir`` for checkpoints. The ``--data-config g1_locomanipulation_sdg`` and ``--embodiment-tag new_embodiment`` options are required for the G1 locomanipulation task. + +.. code:: bash + + cd Isaac-GR00T + python scripts/gr00t_finetune.py \ + --dataset-path \ + --output-dir \ + --data-config g1_locomanipulation_sdg \ + --embodiment-tag new_embodiment \ + --num-gpus 1 \ + --max-steps 10000 \ + --save-steps 1000 \ + --video-backend decord \ + --report-to tensorboard + +See the GR00T N1.5 repository documentation for additional training options. + +.. tip:: + + **Skip finetuning:** A pre-trained GR00T N1.5 checkpoint for this task is available on + Hugging Face at `nvidia/g1_locomanip_finetune `__. + Downloading it lets you skip the finetuning step and proceed directly to rollout. + + Download and unzip the checkpoint: + + .. code:: bash + + huggingface-cli download nvidia/g1_locomanip_finetune --local-dir ./checkpoints/g1_locomanip_finetune_hf + unzip ./checkpoints/g1_locomanip_finetune_hf/*.zip -d ./checkpoints/ + + The archive extracts to ``./checkpoints/g1_locomanip_finetune_20260129_231610/``. + Use ``./checkpoints/g1_locomanip_finetune_20260129_231610/checkpoint-20000`` as the ``--model_path`` + in the rollout command below. This checkpoint requires ``--policy_quat_format wxyz``. + +Rollout the policy in Isaac Lab +""""""""""""""""""""""""""""""" + +From the **IsaacLab** repository root, run the rollout script with the path to your finetuned checkpoint, the static manipulation dataset (used for scene/demo setup), and the task name: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/locomanipulation_sdg/gr00t/rollout_policy.py \ + --model_path \ + --embodiment_tag new_embodiment \ + --dataset ./datasets/generated_dataset_g1_locomanip.hdf5 \ + --demo demo_0 \ + --output_file ./datasets/rollout_output.hdf5 \ + --task Isaac-G1-SteeringWheel-Locomanipulation \ + --device cpu \ + --enable_cameras \ + --visualizer kit + +Optional arguments include ``--randomize_placement`` and ``--policy_quat_format wxyz`` (use if your checkpoint was trained with wxyz quaternion format). + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/locomanipulation_sdg_disjoint_nav_groot_policy_4x.gif + :width: 100% + :align: center + :alt: Simulation rollout of GR00T N1.5 policy finetuned for locomanipulation + :figclass: align-center + + Simulation rollout of GR00T N1.5 policy finetuned for locomanipulation. + +The policy shown above uses the camera image, hand poses, hand joint positions, object pose, and base goal pose as inputs. +The output of the model is the target base velocity, hand poses, and hand joint positions for the next several timesteps. + +Integrating 3D Gaussian Splatting into SDG +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +This section extends +:ref:`locomanipulation SDG ` +by replacing the synthetic background with a 3D Gaussian Splatting (NuRec) scene. As in the +base pipeline, the workflow takes a manipulation dataset as input and produces a combined +navigation and manipulation dataset as an HDF5 file — but here the robot navigates and +manipulates objects inside a neurally-rendered environment, and an ego-centric camera +captures the result, producing more realistic training data than a purely synthetic scene. +NVIDIA Isaac Sim renders 3DGS models stored as USD assets; see +`Neural Volume Rendering `__ +for details. + +.. note:: + + This section focuses on data generation with a 3DGS background. To train a policy on the + generated data, see :ref:`Finetune GR00T N1.5 policy for locomanipulation `. + +.. note:: + + The locomanipulation SDG pipeline currently runs a single environment. Parallel environment + support is not yet available for this workflow. + +Setup: downloading example assets +""""""""""""""""""""""""""""""""" + +We provide a sample asset, ``hand_hold-voyager-babyboom``, on +`Hugging Face `__. + +Log in to Hugging Face: + +.. code:: bash + + hf auth login --token + +Download the required USDZ stage files and occupancy maps: + +.. code:: bash + + hf download nvidia/PhysicalAI-Robotics-NuRec \ + hand_hold-voyager-babyboom/stage_volume.usdz \ + hand_hold-voyager-babyboom/stage_particle.usdz \ + hand_hold-voyager-babyboom/occupancy_map.png \ + hand_hold-voyager-babyboom/occupancy_map.yaml \ + --repo-type dataset \ + --local-dir + +The sample includes both a volume-based USD (``stage_volume.usdz``) and a particle-field USD +(``stage_particle.usdz``). Either can be used as the background asset. + +Asset requirements +"""""""""""""""""" + +If you are using custom 3D Gaussian assets, ensure they meet these specifications to be +compatible with the SDG pipeline: + +- The scene has sufficient free space (e.g. 5m x 5m) for asset placement and robot navigation. +- The ground surface is aligned with the z=0 plane, as the pipeline assumes this elevation for + object placement. +- An occupancy map is required for path planning. + + - If your scene was reconstructed using the `Stereo Workflow `__, + the occupancy map is generated via ``nvblox``. + - If your background includes a mesh, use the `Occupancy Map Generator `__ + to create a map via physical simulation. + +Generating the dataset +"""""""""""""""""""""" + +Before proceeding, ensure you have generated a manipulation dataset or downloaded the sample +dataset provided in the +:ref:`Generate the manipulation dataset ` section. + +Once you have gathered: + +- A manipulation dataset +- A background USD asset +- A matched occupancy map + +you can run the generation command. At runtime, the script adds a ground plane at ``z=0`` to +the scene. It then proceeds through four stages: + +1. **Pick**: The robot picks up an object at the start location by replaying the manipulation + trajectory. ``--lift_step`` marks the end of this stage (immediately after grasp). +2. **Navigate**: The robot travels to the target location using occupancy-map path planning and + its locomotion policy. ``--navigate_step`` marks the end of this stage (when the robot is in + place to release the object). +3. **Place**: The robot places the object at the target location, completing the trajectory. +4. **Record**: Joint states, poses, and the ego-centric video are saved to the HDF5 file + specified by ``--output_file``. + +Run the generation command: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/locomanipulation_sdg/generate_data.py \ + --device cpu \ + --kit_args="--enable isaacsim.replicator.experimental.mobility_gen" \ + --task="Isaac-G1-SteeringWheel-Locomanipulation" \ + --dataset /dataset_annotated_g1_locomanip.hdf5 \ + --num_runs 1 \ + --lift_step 60 \ + --navigate_step 130 \ + --output_file /generated_dataset_g1_locomanipulation_sdg_gaussian_background.hdf5 \ + --enable_cameras \ + --visualizer kit \ + --background_usd_path /stage_particle.usdz \ + --background_occupancy_yaml_file /occupancy_map.yaml \ + --randomize_placement \ + --high_res_video + +The key parameters are: + +- ``--background_usd_path``: Path to the 3D Gaussian background USD asset. +- ``--background_occupancy_yaml_file``: Path to the occupancy map file. +- ``--high_res_video``: Capture the ego-centric camera at 960×540 instead of the default + 256×160. + +When the run completes successfully, an HDF5 dataset is generated containing camera +observations. You can convert the ego-centric camera view to MP4: + +.. code:: bash + + ./isaaclab.sh -p scripts/tools/hdf5_to_mp4.py \ + --input_file /generated_dataset_g1_locomanipulation_sdg_gaussian_background.hdf5 \ + --output_dir / \ + --input_keys robot_pov_cam \ + --video_width 960 \ + --video_height 540 + +Set ``--video_width`` and ``--video_height`` to match the resolution captured during +generation: 960×540 with ``--high_res_video``, or 256×160 without it. + +To play the generated MP4 video on Ubuntu, install the following multimedia packages: + +.. code:: bash + + sudo apt update + sudo apt install libavcodec-extra gstreamer1.0-libav gstreamer1.0-plugins-ugly + + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/locomanipulation_sdg_gaussian_background_2x.webp + :width: 100% + :align: center + :alt: locomanipulation SDG with a 3D Gaussian background + :figclass: align-center + +The figure above shows recorded ego-centric camera views in the 3D Gaussian background +when the robot replays the pick and place trajectory and navigates to the target location. diff --git a/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/index.rst b/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..769b259185f8b0a8050333ca4a6c2adf5dd5822a --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/index.rst @@ -0,0 +1,13 @@ +Imitation Learning +================== + +In this section, we show existing scripts for running imitation learning +with Isaac Lab. + +.. toctree:: + :maxdepth: 1 + + teleop_imitation + humanoids_imitation + augmented_imitation + skillgen diff --git a/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/skillgen.rst b/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/skillgen.rst new file mode 100644 index 0000000000000000000000000000000000000000..54c4a1ca0eb51efc8a871e9560e966232bbddcb0 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/skillgen.rst @@ -0,0 +1,549 @@ +.. _skillgen: + +SkillGen for Automated Demonstration Generation +=============================================== + +SkillGen is an advanced demonstration generation system that enhances Isaac Lab Mimic by integrating motion planning. It generates high-quality, adaptive, collision-free robot demonstrations by combining human-provided subtask segments with automated motion planning. + +What is SkillGen? +~~~~~~~~~~~~~~~~~ + +SkillGen addresses key limitations in traditional demonstration generation: + +* **Motion Quality**: Uses cuRobo's GPU-accelerated motion planner to generate smooth, collision-free trajectories +* **Validity**: Generates kinematically feasible plans between skill segments +* **Diversity**: Generates varied demonstrations through configurable sampling and planning parameters +* **Adaptability**: Generates demonstrations that can be adapted to new object placements and scene configurations during data generation + +The system works by taking manually annotated human demonstrations, extracting localized subtask skills (see `Subtasks in SkillGen`_), and using cuRobo to plan feasible motions between these skill segments while respecting robot kinematics and collision constraints. + +Prerequisites +~~~~~~~~~~~~~ + +Before using SkillGen, you must understand: + +1. **Teleoperation**: How to control robots and record demonstrations using keyboard, SpaceMouse, or hand tracking +2. **Isaac Lab Mimic**: The complete workflow including data collection, annotation, generation, and policy training + +.. important:: + + Review the :ref:`teleoperation-imitation-learning` documentation thoroughly before proceeding with SkillGen. + +.. _skillgen-installation: + +Installation +~~~~~~~~~~~~ + +SkillGen requires Isaac Lab, Isaac Sim, and cuRobo. Follow these steps in your Isaac Lab conda environment. + +Step 1: Install and verify Isaac Sim and Isaac Lab +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Follow the official Isaac Sim and Isaac Lab installation guide :doc:`here `. + +Step 2: Install cuRobo +^^^^^^^^^^^^^^^^^^^^^^ + +cuRobo provides the motion planning capabilities for SkillGen. This installation is tested to work with Isaac Lab's PyTorch and CUDA requirements: + +.. code:: bash + + # One line installation of cuRobo (formatted for readability) + conda install -c nvidia cuda-toolkit=12.8 -y && \ + export CUDA_HOME="$CONDA_PREFIX" && \ + export PATH="$CUDA_HOME/bin:$PATH" && \ + export LD_LIBRARY_PATH="$CUDA_HOME/lib:$LD_LIBRARY_PATH" && \ + export TORCH_CUDA_ARCH_LIST="8.0+PTX" && \ + pip install -e "git+https://github.com/NVlabs/curobo.git@ebb71702f3f70e767f40fd8e050674af0288abe8#egg=nvidia-curobo" --no-build-isolation + +.. note:: + * The commit hash ``ebb71702f3f70e767f40fd8e050674af0288abe8`` is tested with Isaac Lab - using other versions may cause compatibility issues. This commit has the support for quad face mesh triangulation, required for cuRobo to parse usds as collision objects. + + * cuRobo is installed from source and is editable installed. This means that the cuRobo source code will be cloned in the current directory under ``src/nvidia-curobo``. Users can choose their working directory to install cuRobo. + + * ``TORCH_CUDA_ARCH_LIST`` in the above command should match your GPU's CUDA compute capability (e.g., ``8.0`` for A100, ``8.6`` for many RTX 30‑series, ``8.9`` for RTX 4090); the ``+PTX`` suffix embeds PTX for forward compatibility so newer GPUs can JIT‑compile when native SASS isn’t included. + +.. warning:: + + **cuRobo installation may fail if Isaac Sim environment scripts are sourced** + + Sourcing Omniverse Kit/Isaac Sim environment scripts (for example, ``setup_conda_env.sh``) exports ``PYTHONHOME`` and ``PYTHONPATH`` to the Kit runtime and its pre-bundled Python packages. During cuRobo installation this can cause ``conda`` to import Omniverse's bundled libraries (e.g., ``requests``/``urllib3``) before initialization, resulting in a crash (often seen as a ``TypeError`` referencing ``omni.kit.pip_archive``). + + Do one of the following: + + - Install cuRobo from a clean shell that has not sourced any Omniverse/Isaac Sim scripts. + - Temporarily reset or ignore inherited Python environment variables (notably ``PYTHONPATH`` and ``PYTHONHOME``) before invoking Conda, so Kit's Python does not shadow your Conda environment. + - Use Conda mechanisms that do not rely on shell activation and avoid inheriting the current shell's Python variables. + + After installation completes, you may source Isaac Lab/Isaac Sim scripts again for normal use. + + + +Step 3: Install Rerun +^^^^^^^^^^^^^^^^^^^^^ + +For trajectory visualization during development: + +.. code:: bash + + pip install rerun-sdk==0.23 + +.. note:: + + **Rerun Visualization Setup:** + + * Rerun is optional but highly recommended for debugging and validating planned trajectories during development + * Enable trajectory visualization by setting ``visualize_plan = True`` in the cuRobo planner configuration + * When enabled, cuRobo planner interface will stream planned end-effector trajectories, waypoints, and collision data to Rerun for interactive inspection + * Visualization helps identify planning issues, collision problems, and trajectory smoothness before full dataset generation + * Can also run without Isaac Sim visualization while still visualizing and debugging end-effector trajectories + +Step 4: Verify Installation +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Test that cuRobo works with Isaac Lab: + +.. code:: bash + + # This should run without import errors + python -c "import curobo; print('cuRobo installed successfully')" + +.. tip:: + + If you run into ``libstdc++.so.6: version 'GLIBCXX_3.4.30' not found`` error, you can try these commands to fix it: + + .. code:: bash + + conda config --env --set channel_priority strict + conda config --env --add channels conda-forge + conda install -y -c conda-forge "libstdcxx-ng>=12" "libgcc-ng>=12" + +Download the SkillGen Dataset +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We provide a pre-annotated dataset to help you get started quickly with SkillGen. + +Dataset Contents +^^^^^^^^^^^^^^^^ + +The dataset contains: + +* Human demonstrations of Franka arm cube stacking +* Manually annotated subtask boundaries for each demonstration +* Compatible with both basic cube stacking and adaptive bin cube stacking tasks + +Download and Setup +^^^^^^^^^^^^^^^^^^ + +1. Download the pre-annotated dataset by clicking `here `__. + +2. Prepare the datasets directory and move the downloaded file: + +.. code:: bash + + # Make sure you are in the root directory of your Isaac Lab workspace + cd /path/to/your/IsaacLab + + # Create the datasets directory if it does not exist + mkdir -p datasets + + # Move the downloaded dataset into the datasets directory + mv /path/to/annotated_dataset_skillgen.hdf5 datasets/annotated_dataset_skillgen.hdf5 + +.. tip:: + + A major advantage of SkillGen is that the same annotated dataset can be reused across multiple related tasks (e.g., basic stacking and adaptive bin stacking). This avoids collecting and annotating new data per variant. + +.. admonition:: {Optional for the tasks in this tutorial} Collect a fresh dataset (source + annotated) + + If you want to collect a fresh source dataset and then create an annotated dataset for SkillGen, follow these commands. The user is expected to have knowledge of the Isaac Lab Mimic workflow. + + **Important pointers before you begin** + + * Using the provided annotated dataset is the fastest path to get started with SkillGen tasks in this tutorial. + * If you create your own dataset, SkillGen requires manual annotation of both subtask start and termination boundaries (no auto-annotation). + * Start boundary signals are mandatory for SkillGen; use ``--annotate_subtask_start_signals`` during annotation or data generation will fail. + * Keep your subtask definitions (``object_ref``, ``subtask_term_signal``) consistent with the SkillGen environment config. + + **Record demonstrations** (any teleop device is supported; replace ``spacemouse`` if needed): + + .. code:: bash + + ./isaaclab.sh -p scripts/tools/record_demos.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-Skillgen-v0 \ + --teleop_device spacemouse \ + --dataset_file ./datasets/dataset_skillgen.hdf5 \ + --num_demos 10 \ + --visualizer kit + + **Annotate demonstrations for SkillGen** (writes both term and start boundaries): + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/annotate_demos.py \ + --device cpu \ + --task Isaac-Stack-Cube-Franka-IK-Rel-Skillgen-v0 \ + --input_file ./datasets/dataset_skillgen.hdf5 \ + --output_file ./datasets/annotated_dataset_skillgen.hdf5 \ + --annotate_subtask_start_signals \ + --visualizer kit + +Understanding Dataset Annotation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +SkillGen requires datasets with annotated subtask start and termination boundaries. Auto-annotation is not supported. + +Subtasks in SkillGen +^^^^^^^^^^^^^^^^^^^^ + +**Technical definition:** A subtask is a contiguous demo segment that achieves a manipulation objective, defined via ``SubTaskConfig``: + +* ``object_ref``: the object (or ``None``) used as the spatial reference for this subtask +* ``subtask_term_signal``: the binary termination signal name (transitions 0 to 1 when the subtask completes) +* ``subtask_start_signal``: the binary start signal name (transitions 0 to 1 when the subtask begins; required for SkillGen) + +The subtask localization process performs: + +* detection of signal transition points (0 to 1) to identify subtask boundaries ``[t_start, t_end]``; +* extraction of the subtask segment between boundaries; +* computation of end-effector trajectories and key poses in an object- or task-relative frame (using ``object_ref`` if provided); + +This converts absolute, scene-specific motions into object-relative skill segments that can be adapted to new object placements and scene configurations during data generation. + +Manual Annotation Workflow +^^^^^^^^^^^^^^^^^^^^^^^^^^ +Contrary to the Isaac Lab Mimic workflow, SkillGen requires manual annotation of subtask start and termination boundaries. For example, for grasping a cube, the start signal is right before the gripper closes and the termination signal is right after the object is grasped. You can adjust the start and termination signals to fit your subtask definition. + +.. tip:: + + **Manual Annotation Controls:** + + * Press ``N`` to start/continue playback + * Press ``B`` to pause + * Press ``S`` to mark subtask boundary + * Press ``Q`` to skip current demonstration + + When annotating the start and end signals for a skill segment (e.g., grasp, stack, etc.), pause the playback using ``B`` a few steps before the skill, annotate the start signal using ``S``, and then resume playback using ``N``. After the skill is completed, pause again a few steps later to annotate the end signal using ``S``. + +Data Generation with SkillGen +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +SkillGen transforms annotated demonstrations into diverse, high-quality datasets using motion planning. + +How SkillGen Works +^^^^^^^^^^^^^^^^^^ + +The SkillGen pipeline uses your annotated dataset and the environment's Mimic API to synthesize new demonstrations: + +1. **Subtask boundary use**: Reads per-subtask start and termination indices from the annotated dataset +2. **Goal sampling**: Samples target poses per subtask according to task constraints and datagen config +3. **Trajectory planning**: Plans collision-free motions between subtask segments using cuRobo (when ``--use_skillgen``) +4. **Trajectory stitching**: Stitches skill segments and planned trajectories into complete demonstrations. +5. **Success evaluation**: Validates task success terms; only successful trials are written to the output dataset + +Usage Parameters +^^^^^^^^^^^^^^^^ + +Key parameters for SkillGen data generation: + +* ``--use_skillgen``: Enables SkillGen planner (required) +* ``--generation_num_trials``: Number of demonstrations to generate +* ``--num_envs``: Parallel environments (tune based on GPU memory) +* ``--device``: Computation device (cpu/cuda). Use cpu for stable physics + +.. _task-basic-cube-stacking: + +Task 1: Basic Cube Stacking +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Generate demonstrations for the standard Isaac Lab Mimic cube stacking task. In this task, the Franka robot must: + +1. Pick up the red cube and place it on the blue cube +2. Pick up the green cube and place it on the red cube +3. Final stack order: blue (bottom), red (middle), green (top). + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/cube_stack_data_gen_skillgen.gif + :width: 75% + :align: center + :alt: Cube stacking task generated with SkillGen + :figclass: align-center + + Cube stacking dataset example. + +Small-Scale Generation +^^^^^^^^^^^^^^^^^^^^^^ + +Start with a small dataset to verify everything works: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ + --device cpu \ + --num_envs 1 \ + --generation_num_trials 10 \ + --input_file ./datasets/annotated_dataset_skillgen.hdf5 \ + --output_file ./datasets/generated_dataset_small_skillgen_cube_stack.hdf5 \ + --task Isaac-Stack-Cube-Franka-IK-Rel-Skillgen-v0 \ + --use_skillgen --visualizer kit + +Full-Scale Generation +^^^^^^^^^^^^^^^^^^^^^ + +Once satisfied with small-scale results, generate a full training dataset: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ + --device cpu \ + --num_envs 1 \ + --generation_num_trials 1000 \ + --input_file ./datasets/annotated_dataset_skillgen.hdf5 \ + --output_file ./datasets/generated_dataset_skillgen_cube_stack.hdf5 \ + --task Isaac-Stack-Cube-Franka-IK-Rel-Skillgen-v0 \ + --use_skillgen + +.. note:: + + * Rerun visualization can be enabled by setting ``visualize_plan = True`` in the cuRobo planner configuration for debugging. + * Adjust ``--num_envs`` based on your GPU memory (start with 1, increase gradually). The performance gain is not very significant when num_envs is greater than 1. A value of 5 seems to be a sweet spot for most GPUs to balance performance and memory usage between cuRobo instances and simulation environments. + * Generation time: ~90 to 120 minutes for one environment for 1000 demonstrations on a RTX 6000 Ada GPU. Time depends on the GPU, the number of environments, and the success rate of the demonstrations (which depends on quality of the annotated dataset). + * cuRobo planner interface and configurations are described in :ref:`cuRobo-interface-features`. + +.. _task-bin-cube-stacking: + +Task 2: Adaptive Cube Stacking in a Bin +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +SkillGen can also be used to generate datasets for adaptive tasks. In this example, we generate a dataset for adaptive cube stacking in a narrow bin. The bin is placed at a fixed position and orientation in the workspace and a blue cube is placed at the center of the bin. The robot must generate successful demonstrations for stacking the red and green cubes on the blue cube without colliding with the bin. + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/bin_cube_stack_data_gen_skillgen.gif + :width: 75% + :align: center + :alt: Adaptive bin cube stacking task generated with SkillGen + :figclass: align-center + + Adaptive bin stacking data generation example. + +Small-Scale Generation +^^^^^^^^^^^^^^^^^^^^^^ + +Test the adaptive stacking setup: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ + --device cpu \ + --num_envs 1 \ + --generation_num_trials 10 \ + --input_file ./datasets/annotated_dataset_skillgen.hdf5 \ + --output_file ./datasets/generated_dataset_small_skillgen_bin_cube_stack.hdf5 \ + --task Isaac-Stack-Cube-Bin-Franka-IK-Rel-Mimic-v0 \ + --use_skillgen --visualizer kit + +Full-Scale Generation +^^^^^^^^^^^^^^^^^^^^^ + +Generate the complete adaptive stacking dataset: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ + --device cpu \ + --num_envs 1 \ + --generation_num_trials 1000 \ + --input_file ./datasets/annotated_dataset_skillgen.hdf5 \ + --output_file ./datasets/generated_dataset_skillgen_bin_cube_stack.hdf5 \ + --task Isaac-Stack-Cube-Bin-Franka-IK-Rel-Mimic-v0 \ + --use_skillgen + +.. warning:: + + Adaptive tasks typically have lower success rates and higher data generation time due to increased complexity. The time taken to generate the dataset is also longer due to lower success rates than vanilla cube stacking and difficult planning problems. + +.. note:: + + If the pre-annotated dataset is used, the generation time is typically around ~220 minutes for 1000 demonstrations for a single environment on a RTX 6000 Ada GPU. + +.. note:: + + **VRAM usage and GPU recommendations** + + Figures measured over 10 generated demonstrations on an RTX 6000 Ada. + * Vanilla Cube Stacking: 1 env ~9.3–9.6 GB steady; 5 envs ~21.8–22.2 GB steady (briefly higher during initialization). + * Adaptive Bin Cube Stacking: 1 env ~9.3–9.6 GB steady; 5 envs ~22.0–22.3 GB steady (briefly higher during initialization). + * Minimum recommended GPU: ≥24 GB VRAM for ``--num_envs`` 1–2; ≥48 GB VRAM for ``--num_envs`` up to ~5. + * To reduce VRAM, keep ``--num_envs`` modest. Numbers can vary with scene assets and number of demonstrations. + +Learning Policies from SkillGen Data +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Similar to the Isaac Lab Mimic workflow, you can train imitation learning policies using the generated SkillGen datasets with Robomimic. + +Basic Cube Stacking Policy +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Train a state-based policy for the basic cube stacking task: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/robomimic/train.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-Skillgen-v0 \ + --algo bc \ + --dataset ./datasets/generated_dataset_skillgen_cube_stack.hdf5 + +Adaptive Bin Cube Stacking Policy +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Train a policy for the more complex adaptive bin stacking: + +.. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/robomimic/train.py \ + --task Isaac-Stack-Cube-Bin-Franka-IK-Rel-Mimic-v0 \ + --algo bc \ + --dataset ./datasets/generated_dataset_skillgen_bin_cube_stack.hdf5 + +.. note:: + + The training script will save the model checkpoints in the model directory under ``IsaacLab/logs/robomimic``. + +Evaluating Trained Policies +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Test your trained policies: + +.. code:: bash + + # Basic cube stacking evaluation + ./isaaclab.sh -p scripts/imitation_learning/robomimic/play.py \ + --device cpu \ + --task Isaac-Stack-Cube-Franka-IK-Rel-Skillgen-v0 \ + --num_rollouts 50 \ + --checkpoint /path/to/model_checkpoint.pth \ + --visualizer kit + +.. code:: bash + + # Adaptive bin cube stacking evaluation + ./isaaclab.sh -p scripts/imitation_learning/robomimic/play.py \ + --device cpu \ + --task Isaac-Stack-Cube-Bin-Franka-IK-Rel-Mimic-v0 \ + --num_rollouts 50 \ + --checkpoint /path/to/model_checkpoint.pth \ + --visualizer kit + +.. note:: + + **Expected Success Rates and Recommendations for Cube Stacking and Bin Cube Stacking Tasks** + + * SkillGen data generation and downstream policy success are sensitive to the task and the quality of dataset annotation, and can show high variance. + * For cube stacking and bin cube stacking, data generation success is typically 40% to 70% when the dataset is properly annotated per the instructions. + * Behavior Cloning (BC) policy success from 1000 generated demonstrations trained for 2000 epochs (default) is typically 40% to 85% for these tasks, depending on data quality. + * Training the policy with 1000 demonstrations and for 2000 epochs takes about 30 to 35 minutes on a RTX 6000 Ada GPU. Training time increases with the number of demonstrations and epochs. + * For dataset generation time, see :ref:`task-basic-cube-stacking` and :ref:`task-bin-cube-stacking`. + * Recommendation: Train for the default 2000 epochs with about 1000 generated demonstrations, and evaluate multiple checkpoints saved after the 1000th epoch to select the best-performing policy. + +.. _cuRobo-interface-features: + +cuRobo Interface Features +~~~~~~~~~~~~~~~~~~~~~~~~~ + +This section summarizes the cuRobo planner interface and features. The SkillGen pipeline uses the cuRobo planner to generate collision-free motions between subtask segments. However, the user can use cuRobo as a standalone motion planner for your own tasks. The user can also implement their own motion planner by subclassing the base motion planner and implementing the same API. + +Base Motion Planner (Extensible) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +* Location: ``isaaclab_mimic/motion_planners/base_motion_planner.py`` +* Purpose: Uniform interface for all motion planners used by SkillGen +* Extensibility: New planners can be added by subclassing and implementing the same API; SkillGen consumes the API without code changes + +cuRobo Planner (GPU, collision-aware) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +* Location: ``isaaclab_mimic/motion_planners/curobo`` +* Multi-phase planning: + + * Retreat → Contact → Approach phases per subtask + * Configurable collision filtering in contact phases + * For SkillGen, retreat and approach phases are collision-free. The transit phase is collision-checked. + +* World synchronization: + + * Updates robot state, attached objects, and collision spheres from the Isaac Lab scene each trial + * Dynamic attach/detach of objects during grasp/place + +* Collision representation: + + * Contact-aware sphere sets with per-phase enables/filters + +* Outputs: + + * Time-parameterized, collision-checked trajectories for stitching + +* Tests: + + * ``source/isaaclab_mimic/test/test_curobo_planner_cube_stack.py`` + * ``source/isaaclab_mimic/test/test_curobo_planner_franka.py`` + * ``source/isaaclab_mimic/test/test_generate_dataset_skillgen.py`` + +.. list-table:: + :widths: 50 50 + :header-rows: 0 + + * - .. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/cube_stack_end_to_end_curobo.gif + :height: 260px + :align: center + :alt: cuRobo planner test on cube stack using Franka Panda robot + + Cube stack planner test. + - .. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/obstacle_avoidance_curobo.gif + :height: 260px + :align: center + :alt: cuRobo planner test on obstacle avoidance using Franka Panda robot + + Franka planner test. + +These tests can also serve as a reference for how to use cuRobo as a standalone motion planner. + +.. note:: + + For detailed cuRobo config creation and parameters, please see the file ``isaaclab_mimic/motion_planners/curobo/curobo_planner_config.py``. + +Generation Pipeline Integration +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +When ``--use_skillgen`` is enabled in ``generate_dataset.py``, the following pipeline is executed: + +1. **Randomize subtask boundaries**: Randomize per-demo start and termination indices for each subtask using task-configured offset ranges. + +2. **Build per-subtask trajectories**: + For each end-effector and subtask: + + - Select a source demonstration segment (strategy-driven; respects coordination/sequential constraints) + - Transform the segment to the current scene (object-relative or coordination delta; optional first-pose interpolation) + - Wrap the transformed segment into a waypoint trajectory + +3. **Transition between subtasks**: + - Plan a collision-aware transition with cuRobo to the subtask's first waypoint (world sync, optional attach/detach), execute the planned waypoints, then resume the subtask trajectory + +4. **Execute with constraints**: + - Execute waypoints step-by-step across end-effectors while enforcing subtask constraints (sequential, coordination with synchronous steps); optionally update planner visualization if enabled + +5. **Record and export**: + - Accumulate states/observations/actions, set the episode success flag, and export the episode (the outer pipeline filters/consumes successes) + +Visualization and Debugging +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Users can visualize the planned trajectories and debug for collisions using Rerun-based plan visualizer. This can be enabled by setting ``visualize_plan = True`` in the cuRobo planner configuration. Note that rerun needs to be installed to visualize the planned trajectories. Refer to Step 3 in :ref:`skillgen-installation` for installation instructions. + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/rerun_cube_stack.gif + :width: 80% + :align: center + :alt: Rerun visualization of planned trajectories and collisions + :figclass: align-center + + Rerun integration: planned trajectories with collision spheres. + +.. note:: + + Check cuRobo usage license in ``docs/licenses/dependencies/cuRobo-license.txt`` diff --git a/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/teleop_imitation.rst b/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/teleop_imitation.rst new file mode 100644 index 0000000000000000000000000000000000000000..6f9e337df5e2bd6e51db5661e947d653a246c463 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/imitation-learning/teleop_imitation.rst @@ -0,0 +1,775 @@ +.. _teleoperation-imitation-learning: + +Synthetic Data Generation and Imitation Learning with Isaac Lab Mimic +===================================================================== + +.. important:: + Isaac Lab Mimic is only supported on Linux. + +What is Isaac Lab Mimic? +~~~~~~~~~~~~~~~~~~~~~~~~ + +.. figure:: ../../_static/mimic/franka_mimic_imitation_learning.jpg + :width: 100% + :align: center + :alt: Franka robot performing a stacking task + :figclass: align-center + +Isaac Lab Mimic (Mimic) is a trajectory data generation tool that can be used to +augment human demonstrations by generating new synthetic data. Given a set of human demonstrations, +Mimic can automatically generate new demonstrations involving the same task but with different spatial configurations. +The generated data can be used to train imitation learning policies that are more robust to spatial variations +even if just a handful of manual demonstrations are available. + +Mimic works by taking a set of human demonstrations and splitting each demonstration into a sequence of subtasks. +Subtasks are defined based on reference objects that dictate the motion of the robot's end-effectors (eefs). Each subtask +is a contiguous segment of the demonstration where the eef's motion is dictated by a single reference object. A new subtask begins +when the reference object changes. Annotations mark points in the demonstration where a subtask is completed. + +During data generation, Mimic takes the human demonstration subtask segments and applies rigid body transformations to the robot's actions +to transform them into new demonstrations involving the same task but with different spatial configurations. +The new demonstrations are evaluated to determine if they are successful, and if so, are added to the output dataset. + +Mimic is compatible with a variety of embodiments including single-eef (e.g. manipulator robots) and multi-eef (e.g. humanoid robots). +The use of rigid body transformations requires that the embodiment's action space is defined in **task space**. If +the embodiment's action is in joint space, then the action must be converted to task space using forward kinematics. + +In the following sections, we will show how to collect a small batch of human demonstrations for a stacking task +with the Franka robot, increase the size of the dataset by generating new synthetic data using Isaac Lab Mimic, and +lastly train a policy to perform the stacking task. + + + +.. _teleop-imitation-step-1-human-data-collection: + +Step 1: Human Data Collection +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. note:: + You may skip this step and proceed directly to :ref:`Step 2: Synthetic Data Generation using Isaac Lab Mimic ` + if you do not wish to collect your own demonstrations. + + + +Environment Introduction +^^^^^^^^^^^^^^^^^^^^^^^^ + +The environment we will be using in this tutorial is ``Isaac-Stack-Cube-Franka-IK-Rel-v0`` and its variations. +This environment contains a Franka robot attached to a table with three cubes. +The task is to stack the cubes in the following order: blue (bottom), red (middle), green (top). As you proceed through +the rest of this tutorial, you will encounter variations of this environment with different observation spaces +(e.g. state-based, visuomotor, etc.). + +Run the following command to spin up and visualize the environment using the ``zero_agent.py`` +script provided by Isaac Lab. This script create and step through the environment in a loop with zero tensor actions. +You will see the robot remain stationary while the environment is running. Use the scroll wheel to zoom in and out of the scene. +Press and hold the alt key while clicking and dragging to pan around the scene. + +.. code:: bash + + ./isaaclab.sh -p scripts/environments/zero_agent.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --viz kit \ + --num_envs 1 + + + +Next, use the ``random_agent.py`` script to spin up the environment and perform random actions. The script will create +and step through the environment in a loop with random tensor actions. You will see the robot move in random +directions. + +.. code:: bash + + ./isaaclab.sh -p scripts/environments/random_agent.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --viz kit \ + --num_envs 1 + +.. figure:: ../../_static/mimic/franka_cube_stacking_env.jpg + :width: 100% + :align: center + :alt: Franka cube stacking environment + :figclass: align-center + + Franka cube stacking environment + + + +Teleoperation +^^^^^^^^^^^^^ + +Isaac Lab supports teleoperation of robots through a variety of input devices including keyboard, SpaceMouse, and XR headsets. + +Run the following command to spin up the environment and teleoperate the robot using the keyboard. Familiarize yourself +with the controls and perform the stacking task. The order of the stacked cubes should be blue (bottom), red (middle), green (top). +Once you feel sufficiently comfortable with the controls, you may shutdown +the environment by quitting the script with Ctrl+C. + +.. code:: bash + + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --viz kit \ + --num_envs 1 \ + --sensitivity 4 \ + --teleop_device keyboard + + +The script will print a helper message with key bindings. For keyboard, +the key bindings are: + +.. code:: text + + Keyboard Controller for SE(3): Se3Keyboard + Reset all commands: R + 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 + +For smoother and simultaneous multi-axis operation, we recommend using a SpaceMouse as the input device. +Providing smoother demonstrations will make it easier for the policy to clone the behavior. +Isaac Lab supports the 3Dconnexion `SpaceMouse Compact `__ +and `SpaceMouse Wireless `__. +To use a SpaceMouse, simply change ``--teleop_device`` accordingly: + +.. code:: bash + + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --viz kit \ + --num_envs 1 \ + --sensitivity 4 \ + --teleop_device spacemouse + +The script will print a helper message with key bindings. For SpaceMouse, +the key bindings are: + +.. code:: text + + SpaceMouse Controller for SE(3): Se3SpaceMouse + Reset all commands: Right click + Toggle gripper (open/close): Click the left button on the SpaceMouse + Move arm along x/y-axis: Tilt the SpaceMouse + Move arm along z-axis: Push or pull the SpaceMouse + Rotate arm: Twist the SpaceMouse + +.. tip:: + + If the SpaceMouse is not detected, you may need to grant additional user permissions by running ``sudo chmod 666 /dev/hidraw<#>`` where ``<#>`` corresponds to the device index + of the connected SpaceMouse. + + To determine the device index, list all ``hidraw`` devices by running ``ls -l /dev/hidraw*``. + Identify the device corresponding to the SpaceMouse by running ``cat /sys/class/hidraw/hidraw<#>/device/uevent`` on each of the devices listed + from the prior step. + + We recommend using local deployment of Isaac Lab to use the SpaceMouse. If using container deployment (:ref:`deployment-docker`), you must manually mount the SpaceMouse to the ``isaac-lab-base`` container by + adding a ``devices`` attribute with the path to the device in your ``docker-compose.yaml`` file: + + .. code:: yaml + + devices: + - /dev/hidraw<#>:/dev/hidraw<#> + + where ``<#>`` is the device index of the connected SpaceMouse. + + Isaac Lab is only compatible with the SpaceMouse Wireless and SpaceMouse Compact models from 3Dconnexion. + + + +(Optional) Teleoperation with XR Headsets +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +For tasks that benefit from the use of an extended reality (XR) device with hand tracking, +Isaac Lab supports using `Isaac Teleop `_ with NVIDIA CloudXR +to immersively stream the scene to compatible XR devices for teleoperation. + +Follow the steps in :ref:`cloudxr-teleoperation` to learn how to install Isaac Teleop and set up CloudXR for +teleoperation. Once you have set it up, you can launch the cube stacking environment with the follow command to try it out +with an XR headset. Note that when using hand tracking, we recommend using the absolute action space +variant of the task (``Isaac-Stack-Cube-Franka-IK-Abs-v0``): + +.. code:: bash + + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-Stack-Cube-Franka-IK-Abs-v0 \ + --viz kit \ + --xr + +.. tip:: + + For more information on teleoperation devices in Isaac Lab, see :ref:`isaac-teleop-feature` for a comprehensive + overview of the teleop framework. See :ref:`isaac-teleop-supported-devices` for a list of supported XR devices + and :ref:`isaac-teleop-new-device` for information on adding new devices. + + + +Collect a Dataset of Human Demonstrations +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Make a new folder in the ``IsaacLab`` root directory to store datasets: + +.. code:: bash + + mkdir -p datasets + +Run the record demos script to collect a set of 10 human demonstrations for the cube stacking task. +Select the tab that matches your input device: + +.. tab-set:: + + .. tab-item:: Keyboard + + .. code:: bash + + ./isaaclab.sh -p scripts/tools/record_demos.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --viz kit \ + --dataset_file ./datasets/dataset.hdf5 \ + --num_demos 10 \ + --teleop_device keyboard + + .. tab-item:: SpaceMouse + + .. code:: bash + + ./isaaclab.sh -p scripts/tools/record_demos.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --viz kit \ + --dataset_file ./datasets/dataset.hdf5 \ + --num_demos 10 \ + --teleop_device spacemouse + + .. tab-item:: XR Headset (Meta Quest / Pico) + + When using hand tracking via an XR headset, use the absolute action space + variant of the task and omit ``--teleop_device``. The IsaacTeleop pipeline + is activated automatically via the ``--xr`` flag. + + .. code:: bash + + ./isaaclab.sh -p scripts/tools/record_demos.py \ + --task Isaac-Stack-Cube-Franka-IK-Abs-v0 \ + --viz kit \ + --dataset_file ./datasets/dataset.hdf5 \ + --num_demos 10 \ + --xr + + .. note:: + + Ensure CloudXR is configured and the headset is connected before running. + See :ref:`cloudxr-teleoperation` for setup instructions. + +.. important:: + The order of the stacked cubes should be blue (bottom), red (middle), green (top). + +Tips for collecting good demonstrations: + +* Keep demonstrations short. Shorter demonstrations mean fewer decisions for the policy, making training easier. +* Take a direct path and move efficiently toward the goal. +* Do not have extended pauses. Instead, perform smooth, continuous motions. It is not obvious for a policy why and when to pause, hence continuous motions are easier to learn. + +If a mistake is made while performing a demonstration, press the ``R`` key (if using a keyboard) or the +right button (if using a SpaceMouse) to discard the current demonstration and reset to a new starting position. + +You can replay the collected demonstrations by running: + +.. code:: bash + + ./isaaclab.sh -p scripts/tools/replay_demos.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --viz kit \ + --num_envs 1 \ + --reset_sim_buffer_each_episode \ + --dataset_file ./datasets/dataset.hdf5 + +**Collect 10 successful demonstrations before proceeding to the next step.** + + + +.. _teleop-imitation-step-2-synthetic-data: + +Step 2: Synthetic Data Generation using Isaac Lab Mimic +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +(Optional) Download Pre-recorded Human Demonstrations +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +We provide a pre-recorded HDF5 dataset containing 10 human demonstrations for the cube stacking task +here: `[Cube Stacking Human Dataset] `__. +If you skipped :ref:`Step 1: Human Data Collection `, you can download this dataset and use it in the remaining tutorial steps. + +Place the dataset in the ``IsaacLab/datasets`` folder. You may need to create the folder if you skipped Step 1 and +have not created it yet. + + + +.. _generate-additional-demonstrations: + +Generate Additional Synthetic Demonstrations +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In the following example, we will show how to use Isaac Lab Mimic to generate additional demonstrations that can be used to train either a state-based policy +(using the ``Isaac-Stack-Cube-Franka-IK-Rel-Mimic-v0`` environment) or visuomotor policy (using the ``Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Mimic-v0`` environment) +to teach a Franka robot to stack cubes. + +Before generating additional demonstrations, the human demonstrations must first be annotated to define the boundary of each subtask. +Subtasks are defined for each end-effector (eef) and are segments in the demonstrations where the eef is performing an action relative to a specific object. +Any time the target object of the eef changes, a new subtask begins. For example, in the stacking task, the first subtask is to grasp the red cube +(eef motion is dictated by the red cube), while the second subtask is to stack the red cube on top of the blue cube (eef motion is dictated by the blue cube). +Subtasks can be annotated manually or (if the environment supports it) automatically using heuristics. For this tutorial, our environment +supports automatic annotation which will be used in the following step. + +.. important:: + + All commands in the following sections must keep a consistent policy type. For example, if choosing to use a state-based policy, then all commands used should be from the "State-based policy" tab. + +Annotate the subtasks in the recording: + +.. tab-set:: + :sync-group: policy_type + + .. tab-item:: State-based policy + :sync: state + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/annotate_demos.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-Mimic-v0 \ + --viz kit \ + --auto \ + --input_file ./datasets/dataset.hdf5 \ + --output_file ./datasets/annotated_dataset.hdf5 + + .. tab-item:: Visuomotor policy + :sync: visuomotor + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/annotate_demos.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Mimic-v0 \ + --viz kit \ + --enable_cameras \ + --auto \ + --input_file ./datasets/dataset.hdf5 \ + --output_file ./datasets/annotated_dataset.hdf5 + + +Next, use Isaac Lab Mimic to generate some additional demonstrations: + +.. tab-set:: + :sync-group: policy_type + + .. tab-item:: State-based policy + :sync: state + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ + --viz kit \ + --num_envs 20 \ + --generation_num_trials 10 \ + --input_file ./datasets/annotated_dataset.hdf5 \ + --output_file ./datasets/generated_dataset_small.hdf5 + + .. tab-item:: Visuomotor policy + :sync: visuomotor + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ + --viz kit \ + --enable_cameras \ + --num_envs 20 \ + --generation_num_trials 10 \ + --input_file ./datasets/annotated_dataset.hdf5 \ + --output_file ./datasets/generated_dataset_small.hdf5 + +.. tip:: + + The output_file of ``annotate_demos.py`` is the input_file to ``generate_dataset.py``. + +.. figure:: ../../_static/mimic/franka_datagen.jpg + :width: 100% + :align: center + :alt: Franka robot performing a stacking task + :figclass: align-center + + Parallel data generation for the Franka cube stacking task + +Inspect the generated data (``generated_dataset_small.hdf5``) and if satisfactory, generate the full dataset: + +.. tab-set:: + :sync-group: policy_type + + .. tab-item:: State-based policy + :sync: state + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ + --num_envs 1000 \ + --generation_num_trials 1000 \ + --input_file ./datasets/annotated_dataset.hdf5 \ + --output_file ./datasets/generated_dataset.hdf5 + + .. tab-item:: Visuomotor policy + :sync: visuomotor + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ + --enable_cameras \ + --num_envs 300 \ + --generation_num_trials 1000 \ + --input_file ./datasets/annotated_dataset.hdf5 \ + --output_file ./datasets/generated_dataset.hdf5 + + +The number of demonstrations ``--generation_num_trials`` can be adjusted to your policy needs. +1000 demonstrations have been shown to provide good training results for the BC RNN policy used in this tutorial. + +The number of environments in the ``--num_envs`` parameter can be adjusted to speed up or slow down data generation. +The suggested values assume an RTX PRO 6000 Blackwell GPU. +You may need to adjust the number of environments to fit your VRAM if you are using a different GPU. + +.. note:: + + **Expected Data Generation Success Rate and Time** + + * Data generation success rate: ~40% for both state and visuomotor + * Data generation time: ~15 mins for state, ~1 hour for visuomotor + + *Numbers are based on using an RTX PRO 6000 Blackwell GPU with the provided commands.* + + + +Step 3: Policy Training +~~~~~~~~~~~~~~~~~~~~~~~ + +Install Robomimic +^^^^^^^^^^^^^^^^^ + +In this step, we will train a Behavior Cloning (BC) RNN agent using `Robomimic `__ +to demonstrate a policy for the cube stacking task using the synthetic data generated in the previous step. + +Install the Robomimic framework using the following command: + +.. code:: bash + + # install the dependencies + sudo apt install cmake build-essential + # install python module (for robomimic) + ./isaaclab.sh -i robomimic + + + +Train an Agent +^^^^^^^^^^^^^^ + +Using the Isaac Lab Mimic generated data we can now train a state-based BC RNN agent for +``Isaac-Stack-Cube-Franka-IK-Rel-v0``, or a visuomotor BC RNN agent for +``Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-v0``: + +.. tab-set:: + :sync-group: policy_type + + .. tab-item:: State-based policy + :sync: state + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/robomimic/train.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --algo bc \ + --dataset ./datasets/generated_dataset.hdf5 + + .. tab-item:: Visuomotor policy + :sync: visuomotor + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/robomimic/train.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-v0 \ + --algo bc \ + --dataset ./datasets/generated_dataset.hdf5 + +.. important:: + The trained models and logs are saved to ``IsaacLab/logs/robomimic``. + + + +Visualize the Results +^^^^^^^^^^^^^^^^^^^^^ + +Run the trained policy to visualize the results: + +.. tab-set:: + :sync-group: policy_type + + .. tab-item:: State-based policy + :sync: state + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/robomimic/play.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --viz kit \ + --num_rollouts 50 \ + --checkpoint /PATH/TO/desired_model_checkpoint.pth + + .. tab-item:: Visuomotor policy + :sync: visuomotor + + .. code:: bash + + ./isaaclab.sh -p scripts/imitation_learning/robomimic/play.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-v0 \ + --viz kit \ + --enable_cameras \ + --num_rollouts 50 \ + --checkpoint /PATH/TO/desired_model_checkpoint.pth + +When evaluating policy performance, it is common for different training epochs to yield different results. +If you don't see the expected performance, **always test policies from various epochs** (not just the final checkpoint) +to find the best-performing model. Model performance can vary substantially across training, and the final epoch +is not always optimal. + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/franka_cube_stack_robomimic_mimic_bcrnn.gif + :width: 100% + :align: center + :alt: Robomimic BCRNN policy performing the cube stacking task + :figclass: align-center + + Robomimic BC RNN policy performing the cube stacking task + +.. note:: + + **Expected Policy Training Time and Success Rate** + + * BC RNN training time: ~30 mins for state (1000 epochs), ~6 hours for visuomotor (600 epochs) + * BC RNN policy success rate: ~40-60% for both state and visuomotor + * **Recommendation:** Evaluate checkpoints from various epochs throughout training to identify the best-performing model + + *Numbers are based on using an RTX PRO 6000 Blackwell GPU with the provided commands.* + + +**You have now completed the introductory tutorial on synthetic data generation and policy training with Isaac Lab Mimic. +In the sections below, you can explore examples with other robot embodiments (e.g. humanoids) and how to create your +own Isaac Lab Mimic compatible environments.** + + + +Humanoid Examples +~~~~~~~~~~~~~~~~~ + +For examples of data generation and policy training with humanoid robots (GR-1, G1), +see the page: :ref:`Examples: Data Generation and Imitation Learning for Humanoids `. + + + +Creating Your Own Isaac Lab Mimic Compatible Environments +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. figure:: ../../_static/mimic/mimic_env_architecture.jpg + :align: center + :figwidth: 100% + :alt: Mimic compatible environment class and config hierarchy + + Mimic compatible environment class and config hierarchy + + +How it works +^^^^^^^^^^^^ + +Isaac Lab Mimic works by splitting the input demonstrations into subtasks. Subtasks are user-defined segments in the demonstrations that are common to all demonstrations. Examples for subtasks are "grasp an object", "move end effector to some pre-defined position", "release object" etc.. Note that most subtasks are defined with respect to some object that the robot interacts with. + +Subtasks need to be defined, and then annotated for each input demonstration. Annotation can either happen algorithmically by defining heuristics for subtask detection, as was done in the example above, or it can be done manually. + +With subtasks defined and annotated, Isaac Lab Mimic utilizes a small number of helper methods to then transform the subtask segments, and generate new demonstrations by stitching them together to match the new task at hand. + +For each thusly generated candidate demonstration, Isaac Lab Mimic uses a boolean success criteria to determine whether the demonstration succeeded in performing the task, and if so, add it to the output dataset. Success rate of candidate demonstrations can be as high as 70% in simple cases, and as low as <1%, depending on the difficulty of the task, and the complexity of the robot itself. + +Configuration and subtask definition +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Subtasks, among other configuration settings for Isaac Lab Mimic, are defined in a Mimic compatible environment configuration class that is created by extending the existing environment config with additional Mimic required parameters. + +All Mimic required config parameters are specified in the :class:`~isaaclab.envs.MimicEnvCfg` class. + +The config class :class:`~isaaclab_mimic.envs.FrankaCubeStackIKRelMimicEnvCfg` serves as an example of creating a Mimic compatible environment config class for the Franka stacking task that was used in the examples above. + +The ``DataGenConfig`` member contains various parameters that influence how data is generated. It is initially sufficient to just set the ``name`` parameter, and revise the rest later. + +Subtasks are a list of :class:`~isaaclab.envs.SubTaskConfig` objects, of which the most important members are: + +* ``object_ref`` is the object that is being interacted with. This will be used to adjust motions relative to this object during data generation. Can be ``None`` if the current subtask does not involve any object. +* ``subtask_term_signal`` is the ID of the signal indicating whether the subtask is active or not. + +For multi end-effector environments, subtask ordering between end-effectors can be enforced by specifying subtask constraints. These constraints are defined in the :class:`~isaaclab.envs.SubTaskConstraintConfig` class. + +Subtask annotation +^^^^^^^^^^^^^^^^^^ + +Once the subtasks are defined, they need to be annotated in the source data. There are two methods to annotate source demonstrations for subtask boundaries: Manual annotation or using heuristics. + +It is often easiest to perform manual annotations, since the number of input demonstrations is usually very small. To perform manual annotations, use the ``annotate_demos.py`` script without the ``--auto`` flag. Then press ``B`` to pause, ``N`` to continue, and ``S`` to annotate a subtask boundary. + +For more accurate boundaries, or to speed up repeated processing of a given task for experiments, heuristics can be implemented to perform the same task. Heuristics are observations in the environment. An example how to add subtask terms can be found in ``source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/stack_env_cfg.py``, where they are added as an observation group called ``SubtaskCfg``. This example is using prebuilt heuristics, but custom heuristics are easily implemented. + + +Helpers for demonstration generation +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Helpers needed for Isaac Lab Mimic are defined in the environment. All tasks that are to be used with Isaac Lab Mimic are derived from the :class:`~isaaclab.envs.ManagerBasedRLMimicEnv` base class, and must implement the following functions: + +* ``get_robot_eef_pose``: Returns the current robot end effector pose in the same frame as used by the robot end effector controller. + +* ``target_eef_pose_to_action``: Takes a target pose and a gripper action for the end effector controller and returns an action which achieves the target pose. + +* ``action_to_target_eef_pose``: Takes an action and returns a target pose for the end effector controller. + +* ``actions_to_gripper_actions``: Takes a sequence of actions and returns the gripper actuation part of the actions. + +* ``get_object_poses``: Returns the pose of each object in the scene that is used for data generation. + +* ``get_subtask_term_signals``: Returns a dictionary of binary flags for each subtask in a task. The flag of true is set when the subtask has been completed and false otherwise. + +The class :class:`~isaaclab_mimic.envs.FrankaCubeStackIKRelMimicEnv` shows an example of creating a Mimic compatible environment from an existing Isaac Lab environment. + +Registering the environment +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Once both Mimic compatible environment and environment config classes have been created, a new Mimic compatible environment can be registered using ``gym.register``. For the Franka stacking task in the examples above, the Mimic environment is registered as ``Isaac-Stack-Cube-Franka-IK-Rel-Mimic-v0``. + +The registered environment is now ready to be used with Isaac Lab Mimic. + + +Tips for Successful Data Generation with Isaac Lab Mimic +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Splitting subtasks +^^^^^^^^^^^^^^^^^^ + +A general rule of thumb is to split the task into as few subtasks as possible, while still being able to complete the task. Isaac Lab Mimic data generation uses linear interpolation to bridge and stitch together subtask segments. +More subtasks result in more stitching of trajectories which can result in less smooth motions and more failed demonstrations. For this reason, it is often best to annoatate subtask boundaries where the robot's motion is unlikely to collide with other objects. + +For example, in the scenario below, there is a subtask partition after the robot's left arm grasps the object. On the left, the subtask annotation is marked immediately after the grasp, while on the right, the annotation is marked after the robot has grasped and lifted the object. +In the left case, the interpolation causes the robot's left arm to collide with the table and it's motion lags while on the right the motion is continuous and smooth. + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/lagging_subtask.gif + :width: 99% + :align: center + :alt: Subtask splitting example + :figclass: align-center + +.. centered:: Motion lag/collision caused by poor subtask splitting (left) + + +Selecting number of interpolation steps +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The number of interpolation steps between subtask segments can be specified in the :class:`~isaaclab.envs.SubTaskConfig` class. Once transformed, the subtask segments don't start/end at the same spot, thus to create a continuous motion, Isaac Lab Mimic +will apply linear interpolation between the last point of the previous subtask and the first point of the next subtask. + +The number of interpolation steps can be tuned to control the smoothness of the generated demonstrations during this stitching process. +The appropriate number of interpolation steps depends on the speed of the robot and the complexity of the task. A complex task with a large object reset distribution will have larger gaps between subtask segments and require more interpolation steps to create a smooth motion. +Alternatively, a task with small gaps between subtask segments should use a small number of interpolation steps to avoid unnecessary motion lag caused by too many steps. + +An example of how the number of interpolation steps can affect the generated demonstrations is shown below. +In the example, an interpolation is applied to the right arm of the robot to bridge the gap between the left arm's grasp and the right arm's placement. With 0 steps, the right arm exhibits a jerky jump in motion while with 20 steps, the motion is laggy. With 5 steps, the motion is +smooth and natural. + +.. |0_interp_steps| image:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/0_interpolation_steps.gif + :width: 32% + :alt: GR-1 robot with 0 interpolation steps + +.. |5_interp_steps| image:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/5_interpolation_steps.gif + :width: 32% + :alt: GR-1 robot with 5 interpolation steps + +.. |20_interp_steps| image:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/20_interpolation_steps.gif + :width: 32% + :alt: GR-1 robot with 20 interpolation steps + +|0_interp_steps| |5_interp_steps| |20_interp_steps| + +.. centered:: Left: 0 steps. Middle: 5 steps. Right: 20 steps. + + + +.. _common-pitfalls-generating-data: + +Common Pitfalls when Generating Data +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Demonstrations are too long:** + +* Longer time horizon is harder to learn for a policy +* Start close to the first object and minimize motions + +**Demonstrations are not smooth:** + +* Irregular motion is hard for policy to decipher +* Better teleop devices result in better data (i.e. SpaceMouse is better than Keyboard) + +**Pauses in demonstrations:** + +* Pauses are difficult to learn +* Keep the human motions smooth and fluid + +**Excessive number of subtasks:** + +* Minimize the number of defined subtasks for completing a given task +* Less subtacks results in less stitching of trajectories, yielding higher data generation success rate + +**Lack of action noise:** + +* Action noise makes policies more robust + +**Recording cropped too tight:** + +* If recording stops on the frame the success term triggers, it may not re-trigger during replay +* Allow for some buffer at the end of recording + +**Non-deterministic replay:** + +* Physics in IsaacLab are not deterministically reproducible when using ``env.reset`` so demonstrations may fail on replay +* Collect more human demos than needed, use the ones that succeed during annotation +* All data in Isaac Lab Mimic generated HDF5 file represent a successful demo and can be used for training (even if non-determinism causes failure when replayed) + + + +.. _glossary-mimic-terminology: + +Glossary +~~~~~~~~ + +.. glossary:: + + Isaac Lab Mimic (Mimic) + Tool for generating spatially new robot demonstrations from a small number of human demonstrations. + + Subtask + A contiguous segment of a human demonstration where the robot's end-effector action is dictated by a single rigid object. + + Annotated Dataset + An HDF5 dataset with human demonstrations marked with subtask completion boundaries. + + IK + Inverse kinematics. + + FK + Forward kinematics. + + Task Space Action + A robot action defined in the robot's end-effector space given by spatial translation (XYZ) and orientation (quaternion or euler). + + State-based Policy + A policy that takes state vectors as input and outputs a robot action. + + Visuomotor Policy: + A policy that takes camera images as input and outputs a robot action. diff --git a/simulation/modules/IsaacLab/docs/source/overview/own-project/index.rst b/simulation/modules/IsaacLab/docs/source/overview/own-project/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..36ef4443f5b124f53c85679692ebb1a7aa476e0c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/own-project/index.rst @@ -0,0 +1,14 @@ +.. _own-project: + +Build your Own Project or Task +============================== + +To get started, first create a new project or task with the template generator :ref:`template-generator`. +For more detailed information on how your project is structured, see :ref:`project-structure`. + +.. toctree:: + :maxdepth: 1 + :titlesonly: + + template + project_structure diff --git a/simulation/modules/IsaacLab/docs/source/overview/own-project/project_structure.rst b/simulation/modules/IsaacLab/docs/source/overview/own-project/project_structure.rst new file mode 100644 index 0000000000000000000000000000000000000000..a0e17f0344d42665c287b02cc2f4dfef208d631e --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/own-project/project_structure.rst @@ -0,0 +1,44 @@ +.. _project-structure: + + +Project Structure +================= + +There are four nested structures you need to be aware of when working in the direct workflow with an Isaac Lab template +project: the **Project**, the **Extension**, the **Modules**, and the **Task**. + +.. figure:: ../../_static/setup/walkthrough_project_setup.svg + :align: center + :figwidth: 100% + :alt: The structure of the isaac lab template project. + +The **Project** is the root directory of the generated template. It contains the source and scripts directories, as well as +a ``README.md`` file. When we created the template, we named the project *IsaacLabTutorial* and this defined the root directory +of a git repository. If you examine the project root with hidden files visible you will see a number of files defining +the behavior of the project with respect to git. The ``scripts`` directory contains the ``train.py`` and ``play.py`` scripts for the +various RL libraries you chose when generating the template, while the source directory contains the python packages for the project. + +The **Extension** is the name of the python package we installed via pip. By default, the template generates a project +with a single extension of the same name. A project can have multiple extensions, and so they are kept in a common ``source`` +directory. Traditional python packages are defined by the presence of a ``pyproject.toml`` file that describes the package +metadata, but packages using Isaac Lab must also be Isaac Sim extensions and so require a ``config`` directory and an accompanying +``extension.toml`` file that describes the metadata needed by the Isaac Sim extension manager. Finally, because the template +is intended to be installed via pip, it needs a ``setup.py`` file to complete the setup procedure using the ``extension.toml`` +config. A project can have multiple extensions, as evidenced by the Isaac Lab repository itself! + +The **Modules** are what actually gets loaded by Isaac Lab to run training (the meat of the code). By default, the template +generates an extension with a single module that is named the same as the project. The structure of the various sub-modules +in the extension is what determines the ``entry_point`` for an environment in Isaac Lab. This is why our template project needed +to be installed before we could call ``train.py``: the path to the necessary components to run the task needed to be exposed +to python for Isaac Lab to find them. + +Finally, the **Task** is the heart of the direct workflow. By default, the template generates a single task with the same name +as the project. The environment and configuration files are stored here, as well as placeholder, RL library dependent ``agents``. +Critically, note the contents of the ``__init__.py``! Specifically, the ``gym.register`` function needs to be called at least once +before an environment and task can be used with the Isaac Lab ``train.py`` and ``play.py`` scripts. +This function should be included in one of the module ``__init__.py`` files so it is called at installation. The path to +this init file is what defines the entry point for the task! + +For the template, ``gym.register`` is called within ``isaac_lab_tutorial/source/isaac_lab_tutorial/isaac_lab_tutorial/tasks/direct/isaac_lab_tutorial/__init__.py``. +The repeated name is a consequence of needing default names for the template, but now we can see the structure of the project. +**Project**/source/**Extension**/**Module**/tasks/direct/**Task**/__init__.py diff --git a/simulation/modules/IsaacLab/docs/source/overview/own-project/template.rst b/simulation/modules/IsaacLab/docs/source/overview/own-project/template.rst new file mode 100644 index 0000000000000000000000000000000000000000..d2408e9e4fefe591afcf0dac9d2a490ae43baf1a --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/own-project/template.rst @@ -0,0 +1,230 @@ +.. _template-generator: + + +Create new project or task +========================== + +Traditionally, building new projects that utilize Isaac Lab's features required creating your own +extensions within the Isaac Lab repository. However, this approach can obscure project visibility and +complicate updates from one version of Isaac Lab to another. To circumvent these challenges, +we now provide a command-line tool (**template generator**) for creating Isaac Lab-based projects and tasks. + +The template generator enables you to create an: + +* **External project** (recommended): An isolated project that is not part of the Isaac Lab repository. This approach + works outside of the core Isaac Lab repository, ensuring that your development efforts remain self-contained. Also, + it allows your code to be run as an extension in Omniverse. + + .. hint:: + + For the external project, the template generator will initialize a new Git repository in the specified directory. + You can push the generated content to your own remote repository (e.g. GitHub) and share it with others. + +* **Internal task**: A task that is part of the Isaac Lab repository. This approach should only be used to create + new tasks within the Isaac Lab repository in order to contribute to it. + + .. warning:: + + Pip installations of Isaac Lab do not support *Internal* templates. + If ``isaaclab`` is loaded from ``site-packages`` or ``dist-packages``, the *Internal* option is disabled + and the *External* template will be used instead. + +Running the template generator +------------------------------ + +Install Isaac Lab by following the `installation guide <../../setup/installation/index.html>`_. +We recommend using conda or uv installation as it simplifies calling Python scripts from the terminal. + +Then, run the following command to generate a new external project or internal task: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + ./isaaclab.sh --new # or "./isaaclab.sh -n" + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + isaaclab.bat --new :: or "isaaclab.bat -n" + +The generator will guide you in setting up the project/task for your needs by asking you the following questions: + +* Type of project/task (external or internal), and project/task path or names according to the selected type. +* Isaac Lab workflows (see :ref:`feature-workflows`). +* Reinforcement learning libraries (see :ref:`rl-frameworks`), and algorithms (if the selected libraries support multiple algorithms). + +External project usage (once generated) +--------------------------------------- + +Once the external project is generated, a ``README.md`` file will be created in the specified directory. +This file will contain instructions on how to install the project and run the tasks. + +Here are some general commands to get started with it: + +.. note:: + + If Isaac Lab is not installed in a conda environment or in a (virtual) Python environment, use ``FULL_PATH_TO_ISAACLAB/isaaclab.sh -p`` + (or ``FULL_PATH_TO_ISAACLAB\isaaclab.bat -p`` on Windows) instead of ``python`` to run the commands below. + +* Install the project (in editable mode). + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + python -m pip install -e source/ + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + python -m pip install -e source\ + +* List the tasks available in the project. + + .. warning:: + + If the task names change, it may be necessary to update the search pattern ``"Template-"`` + (in the ``scripts/list_envs.py`` file) so that they can be listed. + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + python scripts/list_envs.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + python scripts\list_envs.py + +* Run a task. + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + python scripts//train.py --task= + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + python scripts\\train.py --task= + +For more details, please follow the instructions in the generated project's ``README.md`` file. + +Internal task usage (once generated) +--------------------------------------- + +Once the internal task is generated, it will be available along with the rest of the Isaac Lab tasks. + +Here are some general commands to get started with it: + +.. note:: + + If Isaac Lab is not installed in a conda environment or in a (virtual) Python environment, use ``./isaaclab.sh -p`` + (or ``isaaclab.bat -p`` on Windows) instead of ``python`` to run the commands below. + +* List the tasks available in Isaac Lab. + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + python scripts/environments/list_envs.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + python scripts\environments\list_envs.py + +* Run a task. + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + ./isaaclab.sh train --rl_library --task= + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + isaaclab.bat train --rl_library --task= + +* Run a task with dummy agents. + + These include dummy agents that output zero or random agents. They are useful to ensure that the environments are configured correctly. + + * Zero-action agent + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + python scripts/zero_agent.py --task= + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + python scripts\zero_agent.py --task= + + * Random-action agent + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + python scripts/random_agent.py --task= + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + python scripts\random_agent.py --task= diff --git a/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/index.rst b/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..730b0751f82a531e737f3b3e2acce62cd21bc2d1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/index.rst @@ -0,0 +1,15 @@ +Reinforcement Learning +====================== + +Isaac Lab supports multiple reinforcement learning frameworks. +In this section, we show existing scripts for running reinforcement learning +with supported RL libraries and provide a comparison of the supported +learning frameworks. + +.. toctree:: + :maxdepth: 1 + + rl_existing_scripts + rl_frameworks + performance_benchmarks + training_guide diff --git a/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/performance_benchmarks.rst b/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/performance_benchmarks.rst new file mode 100644 index 0000000000000000000000000000000000000000..d7303a6e91b11e9b0f760525bb08d85dc39367f2 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/performance_benchmarks.rst @@ -0,0 +1,152 @@ +Performance Benchmarks +====================== + +Isaac Lab leverages end-to-end GPU training for reinforcement learning workflows, +allowing for fast parallel training across thousands of environments. +In this section, we provide runtime performance benchmark results for reinforcement learning +training of various example environments on different GPU setups. +Multi-GPU and multi-node training performance results are also outlined. + + +Benchmark Results +----------------- + +All benchmarking results were performed with the RL Games library on Ubuntu 22.04. +``Isaac-Velocity-Rough-G1-v0`` environment benchmarks were performed with the RSL RL library. +The PhysX backend was used for all benchmarks. + + +Memory Consumption +^^^^^^^^^^^^^^^^^^ + ++------------------------------------+----------------+-------------------+----------+-----------+ +| Environment Name | | # of Environments | RAM (GB) | VRAM (GB) | ++====================================+================+===================+==========+===========+ +| Isaac-Cartpole-Direct-v0 | |cartpole| | 4096 | 3.7 | 3.3 | ++------------------------------------+----------------+-------------------+----------+-----------+ +| Isaac-Cartpole-RGB-Camera-Direct-v0| |cartpole-cam| | 1024 | 7.5 | 16.7 | ++------------------------------------+----------------+-------------------+----------+-----------+ +| Isaac-Velocity-Rough-G1-v0 | |g1| | 4096 | 6.5 | 6.1 | ++------------------------------------+----------------+-------------------+----------+-----------+ +| Isaac-Repose-Cube-Shadow-Direct-v0 | |shadow| | 8192 | 6.7 | 6.4 | ++------------------------------------+----------------+-------------------+----------+-----------+ + +.. |cartpole| image:: ../../_static/benchmarks/cartpole.jpg + :width: 80 + :height: 45 +.. |cartpole-cam| image:: ../../_static/benchmarks/cartpole_camera.jpg + :width: 80 + :height: 45 +.. |g1| image:: ../../_static/benchmarks/g1_rough.jpg + :width: 80 + :height: 45 +.. |shadow| image:: ../../_static/benchmarks/shadow.jpg + :width: 80 + :height: 45 + + +Single GPU - RTX 4090 +^^^^^^^^^^^^^^^^^^^^^ + +CPU: AMD Ryzen 9 7950X 16-Core Processor + ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Environment Name | # of Environments | Environment | Environment Step | Environment Step, | +| | | Step FPS | and | Inference, | +| | | | Inference FPS | and Train FPS | ++=====================================+===================+==============+===================+====================+ +| Isaac-Cartpole-Direct-v0 | 4096 | 1100000 | 910000 | 510000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Isaac-Cartpole-RGB-Camera-Direct-v0 | 1024 | 50000 | 45000 | 32000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Isaac-Velocity-Rough-G1-v0 | 4096 | 94000 | 88000 | 82000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Isaac-Repose-Cube-Shadow-Direct-v0 | 8192 | 200000 | 190000 | 170000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ + + +Single GPU - L40 +^^^^^^^^^^^^^^^^ + +CPU: Intel(R) Xeon(R) Platinum 8362 CPU @ 2.80GHz + ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Environment Name | # of Environments | Environment | Environment Step | Environment Step, | +| | | Step FPS | and | Inference, | +| | | | Inference FPS | and Train FPS | ++=====================================+===================+==============+===================+====================+ +| Isaac-Cartpole-Direct-v0 | 4096 | 620000 | 490000 | 260000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Isaac-Cartpole-RGB-Camera-Direct-v0 | 1024 | 30000 | 28000 | 21000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Isaac-Velocity-Rough-G1-v0 | 4096 | 72000 | 64000 | 62000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Isaac-Repose-Cube-Shadow-Direct-v0 | 8192 | 170000 | 140000 | 120000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ + + +Single-Node, 4 x L40 GPUs +^^^^^^^^^^^^^^^^^^^^^^^^^ + +CPU: Intel(R) Xeon(R) Platinum 8362 CPU @ 2.80GHz + ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Environment Name | # of Environments | Environment | Environment Step | Environment Step, | +| | | Step FPS | and | Inference, | +| | | | Inference FPS | and Train FPS | ++=====================================+===================+==============+===================+====================+ +| Isaac-Cartpole-Direct-v0 | 4096 | 2700000 | 2100000 | 950000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Isaac-Cartpole-RGB-Camera-Direct-v0 | 1024 | 130000 | 120000 | 90000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Isaac-Velocity-Rough-G1-v0 | 4096 | 290000 | 270000 | 250000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Isaac-Repose-Cube-Shadow-Direct-v0 | 8192 | 440000 | 420000 | 390000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ + + +4 Nodes, 4 x L40 GPUs per node +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +CPU: Intel(R) Xeon(R) Platinum 8362 CPU @ 2.80GHz + ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Environment Name | # of Environments | Environment | Environment Step | Environment Step, | +| | | Step FPS | and | Inference, | +| | | | Inference FPS | and Train FPS | ++=====================================+===================+==============+===================+====================+ +| Isaac-Cartpole-Direct-v0 | 4096 | 10200000 | 8200000 | 3500000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Isaac-Cartpole-RGB-Camera-Direct-v0 | 1024 | 530000 | 490000 | 260000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Isaac-Velocity-Rough-G1-v0 | 4096 | 1200000 | 1100000 | 960000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ +| Isaac-Repose-Cube-Shadow-Direct-v0 | 8192 | 2400000 | 2300000 | 1800000 | ++-------------------------------------+-------------------+--------------+-------------------+--------------------+ + + +Benchmark Scripts +----------------- + +For ease of reproducibility, we provide benchmarking scripts available at ``scripts/benchmarks``. +This folder contains individual benchmark scripts that resemble the ``train.py`` script for RL-Games +and RSL RL. In addition, we also provide a benchmarking script that runs only the environment implementation +without any reinforcement learning library. + +Example scripts can be run similarly to training scripts: + +.. code-block:: bash + + # benchmark with RSL RL + python scripts/benchmarks/benchmark_rsl_rl.py --task=Isaac-Cartpole-v0 + + # benchmark with RL Games + python scripts/benchmarks/benchmark_rlgames.py --task=Isaac-Cartpole-v0 + + # benchmark without RL libraries + python scripts/benchmarks/benchmark_non_rl.py --task=Isaac-Cartpole-v0 + +Each script will generate a set of KPI files at the end of the run, which includes data on the +startup times, runtime statistics, such as the time taken for each simulation or rendering step, +as well as overall environment FPS for stepping the environment, performing inference during +rollout, as well as training. diff --git a/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/rl_existing_scripts.rst b/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/rl_existing_scripts.rst new file mode 100644 index 0000000000000000000000000000000000000000..aaf6904dafb47819f69e716a48d196990b777edc --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/rl_existing_scripts.rst @@ -0,0 +1,422 @@ +Reinforcement Learning Workflows +================================ + +We provide wrappers to different reinforcement libraries. These wrappers convert the data +from the environments into the respective libraries function argument and return types. + +Preset Selectors +---------------- + +All training and play commands accept ``physics=NAME``, ``renderer=NAME``, and +``presets=NAME[,NAME,...]`` tokens appended directly to the command (no leading dashes). +See :doc:`/source/features/hydra` for all available names and how the selectors work. + +.. code:: bash + + # Switch physics backend + ./isaaclab.sh train --rl_library \ + --task physics=newton_mjwarp + + # Switch renderer (camera environments) + ./isaaclab.sh train --rl_library rl_games \ + --task Isaac-Cartpole-Camera-Presets-Direct-v0 \ + --enable_cameras renderer=newton_renderer + + # Combine selectors freely + ./isaaclab.sh train --rl_library rl_games \ + --task Isaac-Cartpole-Camera-Presets-Direct-v0 \ + --enable_cameras physics=newton_mjwarp renderer=newton_renderer presets=rgb + +.. note:: + + **Not all environments support the Newton backend yet.** Using ``physics=newton_mjwarp`` with an + environment that has not been configured for Newton will raise an error at launch. See + :doc:`/source/overview/core-concepts/physical-backends/newton/index` + for more details, and the :ref:`migrating-to-isaaclab-3-0` + guide for how to add Newton support to your own environments. + +Newton does not require Isaac Sim (kit-less mode). See :ref:`kitless-installation` for setup. + + +Observation-mode Presets +------------------------ + +Some environments support multiple observation modes selectable via ``presets=``. +Unlike physics or renderer presets, **observation-mode presets affect the checkpoint +structure**: you must pass the same preset to both the training and play commands. +Using a different preset (or none) at play time will cause a model-architecture +mismatch when loading the checkpoint. + +For example, ``Isaac-Repose-Cube-Shadow-Vision-Direct-v0`` defaults to RGB + depth ++ segmentation inputs but can be switched to RGB-only with ``presets=rgb``: + +.. code:: bash + + # Train with RGB-only observations + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Repose-Cube-Shadow-Vision-Direct-v0 \ + --enable_cameras presets=rgb + + # Play — must use the same preset to load the matching checkpoint + ./isaaclab.sh play --rl_library rsl_rl \ + --task Isaac-Repose-Cube-Shadow-Vision-Direct-Play-v0 \ + --enable_cameras presets=rgb + +Other available presets for this environment: ``albedo``, +``simple_shading_constant_diffuse``, ``simple_shading_diffuse_mdl``, +``simple_shading_full_mdl``. The ``depth`` preset is intended for +benchmarking only (see the environment's config for details). + + +RL-Games +-------- + +.. attention:: + + When using RL-Games with the Ray workflow for distributed training or hyperparameter tuning, + please be aware that due to security risks associated with Ray, this workflow is not intended + for use outside of a strictly controlled network environment. + +- Training an agent with + `RL-Games `__ on ``Isaac-Ant-v0``: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + # install python module (for rl-games) + ./isaaclab.sh -i rl_games + # run command for training + ./isaaclab.sh train --rl_library rl_games --task Isaac-Ant-v0 + # run command for training with Newton backend + ./isaaclab.sh train --rl_library rl_games --task Isaac-Ant-v0 physics=newton_mjwarp + # run command for playing with 32 environments + ./isaaclab.sh play --rl_library rl_games --task Isaac-Ant-v0 --num_envs 32 --checkpoint /PATH/TO/model.pth + # run command for recording video of a trained agent (requires installing `ffmpeg`) + ./isaaclab.sh play --rl_library rl_games --task Isaac-Ant-v0 --video --video_length 200 + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: install python module (for rl-games) + isaaclab.bat -i rl_games + :: run command for training + isaaclab.bat train --rl_library rl_games --task Isaac-Ant-v0 + :: run command for training with Newton backend + isaaclab.bat train --rl_library rl_games --task Isaac-Ant-v0 physics=newton_mjwarp + :: run command for playing with 32 environments + isaaclab.bat play --rl_library rl_games --task Isaac-Ant-v0 --num_envs 32 --checkpoint /PATH/TO/model.pth + :: run command for recording video of a trained agent (requires installing `ffmpeg`) + isaaclab.bat play --rl_library rl_games --task Isaac-Ant-v0 --video --video_length 200 + +RSL-RL +------ + +- Training an agent with + `RSL-RL `__ on ``Isaac-Reach-Franka-v0``: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + # install python module (for rsl-rl) + ./isaaclab.sh -i rsl_rl + # run command for training + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Reach-Franka-v0 + # run command for training with Newton backend + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Reach-Franka-v0 physics=newton_mjwarp + # run command for playing with 32 environments + ./isaaclab.sh play --rl_library rsl_rl --task Isaac-Reach-Franka-v0 --num_envs 32 --load_run run_folder_name --checkpoint /PATH/TO/model.pt + # run command for recording video of a trained agent (requires installing `ffmpeg`) + ./isaaclab.sh play --rl_library rsl_rl --task Isaac-Reach-Franka-v0 --video --video_length 200 + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: install python module (for rsl-rl) + isaaclab.bat -i rsl_rl + :: run command for training + isaaclab.bat train --rl_library rsl_rl --task Isaac-Reach-Franka-v0 + :: run command for training with Newton backend + isaaclab.bat train --rl_library rsl_rl --task Isaac-Reach-Franka-v0 physics=newton_mjwarp + :: run command for playing with 32 environments + isaaclab.bat play --rl_library rsl_rl --task Isaac-Reach-Franka-v0 --num_envs 32 --load_run run_folder_name --checkpoint /PATH/TO/model.pt + :: run command for recording video of a trained agent (requires installing `ffmpeg`) + isaaclab.bat play --rl_library rsl_rl --task Isaac-Reach-Franka-v0 --video --video_length 200 + +- Training and distilling an agent with + `RSL-RL `__ on ``Isaac-Velocity-Flat-Anymal-D-v0``: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + # install python module (for rsl-rl) + ./isaaclab.sh -i rsl_rl + # run command for rl training of the teacher agent + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Velocity-Flat-Anymal-D-v0 + # run command for rl training of the teacher agent with Newton backend + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Velocity-Flat-Anymal-D-v0 physics=newton_mjwarp + # run command for distilling the teacher agent into a student agent + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Velocity-Flat-Anymal-D-v0 --agent rsl_rl_distillation_cfg_entry_point --load_run teacher_run_folder_name + # run command for playing the student with 64 environments + ./isaaclab.sh play --rl_library rsl_rl --task Isaac-Velocity-Flat-Anymal-D-v0 --num_envs 64 --agent rsl_rl_distillation_cfg_entry_point + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: install python module (for rsl-rl) + isaaclab.bat -i rsl_rl + :: run command for rl training of the teacher agent + isaaclab.bat train --rl_library rsl_rl --task Isaac-Velocity-Flat-Anymal-D-v0 + :: run command for rl training of the teacher agent with Newton backend + isaaclab.bat train --rl_library rsl_rl --task Isaac-Velocity-Flat-Anymal-D-v0 physics=newton_mjwarp + :: run command for distilling the teacher agent into a student agent + isaaclab.bat train --rl_library rsl_rl --task Isaac-Velocity-Flat-Anymal-D-v0 --agent rsl_rl_distillation_cfg_entry_point --load_run teacher_run_folder_name + :: run command for playing the student with 64 environments + isaaclab.bat play --rl_library rsl_rl --task Isaac-Velocity-Flat-Anymal-D-v0 --num_envs 64 --agent rsl_rl_distillation_cfg_entry_point + +SKRL +---- + +- Training an agent with + `SKRL `__ on ``Isaac-Reach-Franka-v0``: + + .. tab-set:: + + .. tab-item:: PyTorch + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + # install python module (for skrl) + ./isaaclab.sh -i skrl + # run command for training + ./isaaclab.sh train --rl_library skrl --task Isaac-Reach-Franka-v0 + # run command for training with Newton backend + ./isaaclab.sh train --rl_library skrl --task Isaac-Reach-Franka-v0 physics=newton_mjwarp + # run command for playing with 32 environments + ./isaaclab.sh play --rl_library skrl --task Isaac-Reach-Franka-v0 --num_envs 32 --checkpoint /PATH/TO/model.pt + # run command for recording video of a trained agent (requires installing `ffmpeg`) + ./isaaclab.sh play --rl_library skrl --task Isaac-Reach-Franka-v0 --video --video_length 200 + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: install python module (for skrl) + isaaclab.bat -i skrl + :: run command for training + isaaclab.bat train --rl_library skrl --task Isaac-Reach-Franka-v0 + :: run command for training with Newton backend + isaaclab.bat train --rl_library skrl --task Isaac-Reach-Franka-v0 physics=newton_mjwarp + :: run command for playing with 32 environments + isaaclab.bat play --rl_library skrl --task Isaac-Reach-Franka-v0 --num_envs 32 --checkpoint /PATH/TO/model.pt + :: run command for recording video of a trained agent (requires installing `ffmpeg`) + isaaclab.bat play --rl_library skrl --task Isaac-Reach-Franka-v0 --video --video_length 200 + + .. tab-item:: JAX + + .. warning:: + + It is recommended to `install JAX `_ manually before proceeding to install skrl and its dependencies, as JAX installs its CPU version by default. + Visit the **skrl** `installation `_ page for more details. + Note that JAX GPU support is only available on Linux x86_64 and Linux aarch64. + Use the CUDA 12 wheel on Linux x86_64 and the CUDA 13 wheel on Linux aarch64 systems such as DGX Spark. + + .. hint:: + + When using JAX its default behavior is to pre-allocate 75% of the GPU memory for its own computations. If you run into memory issues, + you can set the ``XLA_PYTHON_CLIENT_PREALLOCATE=false`` environment variable to disable this behavior, or reduce the amount of + pre-allocated memory by setting ``export XLA_PYTHON_CLIENT_MEM_FRACTION=0.5`` which will allocate 50% of the GPU memory for JAX. + Any value between 0 and 1 can be set, where 0 will allocate no memory for JAX and 1 will allocate 100% of the GPU memory for JAX. + + .. tab-set:: + :sync-group: jax-cuda + + .. tab-item:: :icon:`fa-brands fa-linux` Linux (x86_64, CUDA 12) + :sync: linux-x86_64-jax-cuda12 + + .. code:: bash + + # install python module (for skrl) + ./isaaclab.sh -i skrl + # install JAX for CUDA 12 + ./isaaclab.sh -p -m pip install -U "jax[cuda12]" + # install skrl dependencies for JAX + ./isaaclab.sh -p -m pip install "skrl[jax]" + + .. tab-item:: :icon:`fa-brands fa-linux` Linux (aarch64, CUDA 13) + :sync: linux-aarch64-jax-cuda13 + + .. code:: bash + + # install python module (for skrl) + ./isaaclab.sh -i skrl + # install JAX for CUDA 13 + ./isaaclab.sh -p -m pip install -U "jax[cuda13]" + # install skrl dependencies for JAX + ./isaaclab.sh -p -m pip install "skrl[jax]" + + .. code:: bash + + # run command for training + ./isaaclab.sh train --rl_library skrl --task Isaac-Reach-Franka-v0 --ml_framework jax + # run command for training with Newton backend + ./isaaclab.sh train --rl_library skrl --task Isaac-Reach-Franka-v0 --ml_framework jax presets=newton_mjwarp + # run command for playing with 32 environments + ./isaaclab.sh play --rl_library skrl --task Isaac-Reach-Franka-v0 --num_envs 32 --ml_framework jax --checkpoint /PATH/TO/model.pt + # run command for recording video of a trained agent (requires installing `ffmpeg`) + ./isaaclab.sh play --rl_library skrl --task Isaac-Reach-Franka-v0 --ml_framework jax --video --video_length 200 + + - Training the multi-agent environment ``Isaac-Shadow-Hand-Over-Direct-v0`` with skrl: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + # install python module (for skrl) + ./isaaclab.sh -i skrl + # run command for training with the MAPPO algorithm (IPPO is also supported) + ./isaaclab.sh train --rl_library skrl --task Isaac-Shadow-Hand-Over-Direct-v0 --algorithm MAPPO + # run command for playing with 32 environments with the MAPPO algorithm (IPPO is also supported) + ./isaaclab.sh play --rl_library skrl --task Isaac-Shadow-Hand-Over-Direct-v0 --num_envs 32 --algorithm MAPPO --checkpoint /PATH/TO/model.pt + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: install python module (for skrl) + isaaclab.bat -i skrl + :: run command for training with the MAPPO algorithm (IPPO is also supported) + isaaclab.bat train --rl_library skrl --task Isaac-Shadow-Hand-Over-Direct-v0 --algorithm MAPPO + :: run command for playing with 32 environments with the MAPPO algorithm (IPPO is also supported) + isaaclab.bat play --rl_library skrl --task Isaac-Shadow-Hand-Over-Direct-v0 --num_envs 32 --algorithm MAPPO --checkpoint /PATH/TO/model.pt + +Stable-Baselines3 +----------------- + +- Training an agent with + `Stable-Baselines3 `__ + on ``Isaac-Velocity-Flat-Unitree-A1-v0``: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + # install python module (for stable-baselines3) + ./isaaclab.sh -i sb3 + # run command for training + ./isaaclab.sh train --rl_library sb3 --task Isaac-Velocity-Flat-Unitree-A1-v0 + # run command for training with Newton backend + ./isaaclab.sh train --rl_library sb3 --task Isaac-Velocity-Flat-Unitree-A1-v0 physics=newton_mjwarp + # run command for playing with 32 environments + ./isaaclab.sh play --rl_library sb3 --task Isaac-Velocity-Flat-Unitree-A1-v0 --num_envs 32 --checkpoint /PATH/TO/model.zip + # run command for recording video of a trained agent (requires installing `ffmpeg`) + ./isaaclab.sh play --rl_library sb3 --task Isaac-Velocity-Flat-Unitree-A1-v0 --video --video_length 200 + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: install python module (for stable-baselines3) + isaaclab.bat -i sb3 + :: run command for training + isaaclab.bat train --rl_library sb3 --task Isaac-Velocity-Flat-Unitree-A1-v0 + :: run command for training with Newton backend + isaaclab.bat train --rl_library sb3 --task Isaac-Velocity-Flat-Unitree-A1-v0 physics=newton_mjwarp + :: run command for playing with 32 environments + isaaclab.bat play --rl_library sb3 --task Isaac-Velocity-Flat-Unitree-A1-v0 --num_envs 32 --checkpoint /PATH/TO/model.zip + :: run command for recording video of a trained agent (requires installing `ffmpeg`) + isaaclab.bat play --rl_library sb3 --task Isaac-Velocity-Flat-Unitree-A1-v0 --video --video_length 200 + +RLinf +----- + +`RLinf `__ is a distributed RL infrastructure for fine-tuning +Vision-Language-Action (VLA) models such as `GR00T `__. +It uses Ray for distributed computing and FSDP for model parallelism, enabling RL training of +large VLA models that don't fit on a single GPU. + +For installation instructions, see :ref:`rlinf-post-training`. + +- Training a VLA agent with RLinf: + + .. code:: bash + + # Train with a specific config + ./isaaclab.sh train --rl_library rlinf \ + --config_name isaaclab_ppo_gr00t_assemble_trocar \ + --model_path /path/to/checkpoint + +- Evaluating a trained VLA agent: + + .. code:: bash + + # Evaluate with video recording + ./isaaclab.sh play --rl_library rlinf \ + --config_name isaaclab_ppo_gr00t_assemble_trocar \ + --model_path /path/to/checkpoint --video + + +All the commands above log the training progress to `Tensorboard`_ in the ``logs`` directory in the root of +the repository. The logs directory follows the pattern ``logs///``, where ```` +is the name of the learning framework, ```` is the task name, and ```` is the timestamp at +which the training command was executed. + +To view the logs, run: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + # execute from the root directory of the repository + ./isaaclab.sh -p -m tensorboard.main --logdir=logs + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: execute from the root directory of the repository + isaaclab.bat -p -m tensorboard.main --logdir=logs + +.. _Tensorboard: https://www.tensorflow.org/tensorboard diff --git a/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/rl_frameworks.rst b/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/rl_frameworks.rst new file mode 100644 index 0000000000000000000000000000000000000000..abd57829747eabdd4e148f14466b36b63b280e3b --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/rl_frameworks.rst @@ -0,0 +1,112 @@ +.. _rl-frameworks: + +Reinforcement Learning Library Comparison +========================================= + +In this section, we provide an overview of the supported reinforcement learning libraries in Isaac Lab, +along with performance benchmarks across the libraries. + +The supported libraries are: + +- `SKRL `__ +- `RSL-RL `__ +- `RL-Games `__ +- `Stable-Baselines3 `__ +- `RLinf `__ (for VLA model fine-tuning) + +Feature Comparison +------------------ + +.. list-table:: + :widths: 16 16 16 16 16 20 + :header-rows: 1 + + * - Feature + - RL-Games + - RSL RL + - SKRL + - Stable Baselines3 + - RLinf + * - Algorithms Included + - PPO, SAC, A2C + - PPO, Distillation + - `Extensive List `__ + - `Extensive List `__ + - PPO, Actor-Critic, SAC + * - Vectorized Training + - Yes + - Yes + - Yes + - No + - Yes + * - Distributed Training + - Yes + - Yes + - Yes + - No + - Yes (Ray + FSDP) + * - ML Frameworks Supported + - PyTorch + - PyTorch + - PyTorch, JAX + - PyTorch + - PyTorch + * - VLA Model Support + - No + - No + - No + - No + - GR00T, OpenVLA + * - Multi-Agent Support + - PPO + - PPO + - PPO + Multi-Agent algorithms + - External projects support + - No + * - Documentation + - Low + - Low + - Comprehensive + - Extensive + - Low + * - Community Support + - Small Community + - Small Community + - Small Community + - Large Community + - Small Community + * - Available Examples in Isaac Lab + - Large + - Large + - Large + - Small + - Small + + +Training Performance +-------------------- + +We performed training with each RL library on the same ``Isaac-Humanoid-v0`` environment +on a single NVIDIA GeForce RTX 4090 and logged the total training time for 65.5M steps +(4096 environments x 32 rollout steps x 500 iterations). + ++--------------------+-----------------+ +| RL Library | Time in seconds | ++====================+=================+ +| RL-Games | 201 | ++--------------------+-----------------+ +| SKRL | 201 | ++--------------------+-----------------+ +| RSL RL | 198 | ++--------------------+-----------------+ +| Stable-Baselines3 | 287 | ++--------------------+-----------------+ + +Training commands (check for the *'Training time: XXX seconds'* line in the terminal output): + +.. code:: bash + + ./isaaclab.sh train --rl_library rl_games --task Isaac-Humanoid-v0 --max_iterations 500 + ./isaaclab.sh train --rl_library skrl --task Isaac-Humanoid-v0 --max_iterations 500 + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Humanoid-v0 --max_iterations 500 + ./isaaclab.sh train --rl_library sb3 --task Isaac-Humanoid-v0 --max_iterations 500 diff --git a/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/training_guide.rst b/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/training_guide.rst new file mode 100644 index 0000000000000000000000000000000000000000..9a220a52003b6c69d79f3cc097258991f1a91777 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/reinforcement-learning/training_guide.rst @@ -0,0 +1,163 @@ +Debugging and Training Guide +============================ + +In this tutorial, we'll guide developers working with Isaac Lab to understand the +impact of various parameters on training time, GPU utilization, and memory usage. +This is especially helpful for addressing Out of Memory (OOM) errors that commonly +occur during reinforcement learning (RL) training. We will touch on common errors seen +during RL training in Isaac Lab and provide some guidance on troubleshooting steps. + + +Training with Parallel Environments +----------------------------------- + +The key RL paradigm of Isaac Lab is to train with many environments in parallel. +Here, we define an environment as an instance of a robot or multiple robots interacting with other robots or objects in simulation. +By creating multiple environments in parallel, we generate multiple copies of the environment such that the robots in each environment can explore the world independently of other environments. +The number of environments thus becomes an important hyperparameter for training. +In general, the more environments we have running in parallel, +the more data we can collect during rollout, which in turn, provides more data +for RL training and allows for faster training since the RL agent can learn from parallel experiences. + +However, the number of environments can also be bounded by other factors. +Memory can often be a hard constraint on the number of environments we can run in parallel. +When more environments are added to the world, the simulation also requires more memory to represent and simulate each object in the scene. +The number of environments we can simulate in parallel thus often depend on the amount of memory resources available on the machine. +In addition, different forms of simulation can also consume various amounts of memory. +For example, objects with high fidelity visual and collision meshes will consume more memory than simple primitive shapes. +Deformable simulation will also likely require more memory to simulate than rigid bodies. + +Training with rendering often consumes much higher memory than running with only physics simulation. This is especially true when rendering at relatively large resolutions. Additionally, when training RL policies with image observations, we often also require more memory to hold the rollout trajectories of image buffers and larger networks for the policies. Both of these components will also impact the amount of memory available for the simulation. + +To reduce memory consumption, one method is to simplify collision meshes of the assets where possible to keep only bare minimum collision shapes required for correct simulation of contacts. +Additionally, we recommend only running with the viewport when debugging with a small number of environments. +When training with larger number of environments in parallel, it is recommended to run in headless mode to avoid any rendering overhead. +If the RL pipeline requires rendering in the loop, make sure to reduce the number of environments, taking into consideration for the dimensions of the image buffers and the size of the policy networks. When hitting out of memory errors, the simplest solution may be to reduce the number of environments. + + +Hyperparameter Tuning +--------------------- + +Although in many cases, simulating more environments in parallel can yield faster training and better results, there are also cases where diminishing returns are observed when the number of environments reaches certain thresholds. +This threshold will vary depending on the complexity of the environment, task, policy setup, and RL algorithm. +When more environments are simulated in parallel, each simulation step requires more time to simulate, which will impact the overall training time. +When the number of environments is small, this increase in per-step simulation time is often insignificant compared to the increase in training performance from more experiences collected. +However, when the number of environments reaches a point, the benefits from having even more experiences for the RL algorithm may start to saturate, and the amount of increased simulation time can outweigh the benefits in training performance. + +In contrast to diminishing returns on number of environments that are too large, training with low number of environments can also be challenging. +This is often due to the RL policies not getting enough experiences to learn from. +To address this issue, it may be helpful to increase the batch size or the horizon length to accommodate for the smaller amount of data collected from lower number of parallel environments. +When the number of environments is constrained by available resources, running with parallel GPUs or training across multiple nodes can also help alleviate issues due to limited rollouts. + + +Debugging NaNs during Training +------------------------------ + +One common error seen during RL training is the appearance of NaNs in the observation buffers, which often get propagated into the policy networks and cause crashes in the downstream training pipeline. +In most cases, the appearance of NaNs occur when the simulation becomes unstable. +This could be due to drastic actions being applied to the robots that exceed the limits of the simulation, or resets of the assets into invalid states. +Some helpful tips to reduce the occurrence of NaNs include proper tuning of the physics parameters for the assets to ensure that joint, velocity, and force limits are within reasonable ranges and the gains are correctly tuned for the robot. +It is also a good idea to check that actions applied to the robots are reasonable and will not impose large forces or impulses on the objects. +Reducing the timestep of the physics simulation can also help improve accuracy and stability of the simulation, in addition to increasing the solver iterations. + + +Understanding Training Outputs +------------------------------ + +Each RL library produces its own output data during training. +Some libraries are more verbose and generate logs that contain more detailed information on the training process, while others are more compact. +In this section, we will explain the common outputs from the RL libraries. + + +RL-Games +^^^^^^^^ + +For each iteration, RL-Games prints statistics of the data collection, inference, and training performance. + +.. code:: bash + + fps step: 112918 fps step and policy inference: 104337 fps total: 78179 epoch: 1/150 frames: 0 + +``fps step`` refers to the environment step FPS, which includes the applying actions, computing observations, rewards, dones, and resets, as well as stepping simulation. + +``step and policy inference`` measure everything in ``fps step`` along with the time it takes for the policy inference to compute the actions. + +``fps total`` measure the above and the time it takes for the training iteration. + +At specified intervals, it will also log the current best reward and the path of the intermmediate checkpoints saved to file. + +.. code:: bash + + => saving checkpoint 'IsaacLab/logs/rl_games/cartpole_direct/2024-12-28_20-23-06/nn/last_cartpole_direct_ep_150_rew_294.18793.pth' + saving next best rewards: [294.18793] + + +RSL RL +^^^^^^ + +For each iteration, RSL RL provides the following output: + +.. code:: bash + + Learning iteration 0/150 + + Computation: 50355 steps/s (collection: 1.106s, learning 0.195s) + Value function loss: 22.0539 + Surrogate loss: -0.0086 + Mean action noise std: 1.00 + Mean reward: -5.49 + Mean episode length: 15.79 + -------------------------------------------------------------------------------- + Total timesteps: 65536 + Iteration time: 1.30s + Total time: 1.30s + ETA: 195.2s + + +This output encapsulates the total FPS for data collection, inference, and learning, along with the per-step breakdown for collection and learning time per step. +In addition, statistics for the training losses are provided, along with the current average reward and episode length. + +In the bottom section, it logs the total number of steps completed so far, the total ieration time for the current ieration, the total overall training time, and the estimated training time to complete the full number of iterations. + + +SKRL +^^^^ + +SKRL provides a very simplistic output showing the training progress as a percentage of the total number of timesteps (divided by the number of environments). It also includes the total elapsed time so far and the estimated time to complete training. + +.. code:: bash + + 0%| | 2/4800 [00:00<10:02, 7.96it/s] + + +Stable-Baselines3 +^^^^^^^^^^^^^^^^^ + +Stable-Baselines3 provides a detailed output, outlining the rollout statistics, timing, and policy data. + +.. code:: bash + + ------------------------------------------ + | rollout/ | | + | ep_len_mean | 30.8 | + | ep_rew_mean | 2.87 | + | time/ | | + | fps | 8824 | + | iterations | 2 | + | time_elapsed | 14 | + | total_timesteps | 131072 | + | train/ | | + | approx_kl | 0.0079056695 | + | clip_fraction | 0.0842 | + | clip_range | 0.2 | + | entropy_loss | -1.42 | + | explained_variance | 0.0344 | + | learning_rate | 0.0003 | + | loss | 10.4 | + | n_updates | 20 | + | policy_gradient_loss | -0.0119 | + | std | 1 | + | value_loss | 17 | + ------------------------------------------ + +Under the ``rollout/`` section, average episode length and reward are logged for the iteration. Under ``time/``, data for the total FPS, number of iterations, total time elapsed, and the total number of timesteps are provided. Finally, under ``train/``, statistics of the training parameters are logged, such as KL, losses, learning rates, and more. diff --git a/simulation/modules/IsaacLab/docs/source/overview/showroom.rst b/simulation/modules/IsaacLab/docs/source/overview/showroom.rst new file mode 100644 index 0000000000000000000000000000000000000000..358a310e9e1e20e3ce7318862d3c2ab599515b78 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/showroom.rst @@ -0,0 +1,387 @@ +Showroom Demos +============== + +The main core interface extension in Isaac Lab ``isaaclab`` 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 arms and apply random joint position commands: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/demos/arms.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\demos\arms.py + + .. image:: ../_static/demos/arms.jpg + :width: 100% + :alt: Arms in Isaac Lab + + +- Spawn different biped robots: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/demos/bipeds.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\demos\bipeds.py + + .. image:: ../_static/demos/bipeds.jpg + :width: 100% + :alt: Biped robots in Isaac Lab + + +- Spawn different deformable objects and let them fall from a height: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/demos/deformables.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\demos\deformables.py + + Add ``--backend newton`` to run the same demo with the experimental Newton + deformable backend. + + .. image:: ../_static/demos/deformables.jpg + :width: 100% + :alt: Deformable primitive-shaped objects in Isaac Lab + + +- Interactive inference of trained H1 rough terrain locomotion policy: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/demos/h1_locomotion.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\demos\h1_locomotion.py + + .. image:: ../_static/demos/h1_locomotion.jpg + :width: 100% + :alt: H1 locomotion in Isaac Lab + + This is an interactive demo that can be run using the mouse and keyboard. + To enter third-person perspective, click on a humanoid character in the scene. + Once entered into third-person view, the humanoid can be controlled by keyboard using: + + * ``UP``: go forward + * ``LEFT``: turn left + * ``RIGHT``: turn right + * ``DOWN``: stop + * ``C``: switch between third-person and perspective views + * ``ESC``: exit current third-person view + + If a misclick happens outside of the humanoid bodies when selecting a humanoid, + a message is printed to console indicating the error, such as + ``The selected prim was not a H1 robot`` or + ``Multiple prims are selected. Please only select one!``. + + +- Spawn different hands and command them to open and close: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/demos/hands.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\demos\hands.py + + .. image:: ../_static/demos/hands.jpg + :width: 100% + :alt: Dexterous hands in Isaac Lab + + +- Define multiple markers that are useful for visualizations: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/demos/markers.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\demos\markers.py + + .. image:: ../_static/demos/markers.jpg + :width: 100% + :alt: Markers in Isaac Lab + + +- Use the interactive scene and spawn varying assets in individual environments: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/demos/multi_asset.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\demos\multi_asset.py + + .. image:: ../_static/demos/multi_asset.jpg + :width: 100% + :alt: Multiple assets managed through the same simulation handles + + +- Use the RigidObjectCollection spawn and view manipulation to demonstrate bin-packing example: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/demos/bin_packing.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\demos\bin_packing.py + + .. image:: ../_static/demos/bin_packing.jpg + :width: 100% + :alt: Spawning random number of random asset per env_id using combination of MultiAssetSpawner and RigidObjectCollection + + + +- Use the interactive scene and spawn a simple parallel robot for pick and place: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/demos/pick_and_place.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\demos\pick_and_place.py + + .. image:: ../_static/demos/pick_and_place.jpg + :width: 100% + :alt: User controlled pick and place with a parallel robot + + This is an interactive demo that can be run using the mouse and keyboard. + Your goal is pick up the purple cube and to drop it on the red sphere! + Use the following controls to interact with the simulation: + + * Hold the ``A`` key to have the gripper track the cube position. + * Hold the ``D`` key to have the gripper track the target position + * Press the ``W`` or ``S`` keys to move the gantry UP or DOWN respectively + * Press ``Q`` or ``E`` to OPEN or CLOSE the gripper respectively + + + +- Teleoperate a Franka Panda robot using Haply haptic device with force feedback: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/demos/haply_teleoperation.py --websocket_uri ws://localhost:10001 --pos_sensitivity 1.65 + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\demos\haply_teleoperation.py --websocket_uri ws://localhost:10001 --pos_sensitivity 1.65 + + .. image:: ../_static/demos/haply_teleop_franka.jpg + :width: 100% + :alt: Haply teleoperation with force feedback + + This demo requires Haply Inverse3 and VerseGrip devices. + The goal of this demo is to pick up the cube or touch it with the end-effector. + The Haply devices provide: + + * 3 dimensional position tracking for end-effector control + * Directional force feedback for contact sensing + * Button inputs for gripper and end-effector rotation control + + See :ref:`haply-teleoperation` for detailed setup instructions. + + + +- Create and spawn procedurally generated terrains with different configurations: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/demos/procedural_terrain.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\demos\procedural_terrain.py + + .. image:: ../_static/demos/procedural_terrain.jpg + :width: 100% + :alt: Procedural Terrains in Isaac Lab + + + +- Spawn a quadcopter in the default environment: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/demos/quadcopter.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\demos\quadcopter.py + + .. image:: ../_static/demos/quadcopter.jpg + :width: 100% + :alt: Quadcopter in Isaac Lab + + +- Spawn different quadrupeds and make robots stand using position commands: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/demos/quadrupeds.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\demos\quadrupeds.py + + .. image:: ../_static/demos/quadrupeds.jpg + :width: 100% + :alt: Quadrupeds in Isaac Lab + + +- Spawn a multi-mesh ray caster that uses Warp kernels for raycasting + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/demos/sensors/multi_mesh_raycaster.py --num_envs 16 --asset_type objects + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\demos\sensors\multi_mesh_raycaster.py --num_envs 16 --asset_type objects + + .. image:: ../_static/demos/multi-mesh-raycast.jpg + :width: 100% + :alt: Multi-mesh raycaster in Isaac Lab diff --git a/simulation/modules/IsaacLab/docs/source/overview/simple_agents.rst b/simulation/modules/IsaacLab/docs/source/overview/simple_agents.rst new file mode 100644 index 0000000000000000000000000000000000000000..86d26ee46c047545fdfed09a01f4646fdf920274 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/overview/simple_agents.rst @@ -0,0 +1,120 @@ +Simple Agents +============= + +Workflows +--------- + +With Isaac Lab, we also provide a suite of benchmark environments included +in the ``isaaclab_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: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/environments/list_envs.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\environments\list_envs.py + +Dummy agents +~~~~~~~~~~~~ + +These include dummy 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 + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/environments/zero_agent.py --task Isaac-Cartpole-v0 --num_envs 32 + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\environments\zero_agent.py --task Isaac-Cartpole-v0 --num_envs 32 + +- Random-action agent on the Cart-pole example: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/environments/random_agent.py --task Isaac-Cartpole-v0 --num_envs 32 + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\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 `__ which +allows efficient execution for large number of environments using CUDA kernels. + +- Picking up a cube and placing it at a desired pose with a robotic arm: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/environments/state_machine/lift_cube_sm.py --num_envs 32 --viz kit + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\environments\state_machine\lift_cube_sm.py --num_envs 32 --viz kit + +- Picking up a deformable teddy bear and placing it at a desired pose with a robotic arm: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -p scripts/environments/state_machine/lift_teddy_bear.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -p scripts\environments\state_machine\lift_teddy_bear.py diff --git a/simulation/modules/IsaacLab/docs/source/policy_deployment/01_io_descriptors/io_descriptors_101.rst b/simulation/modules/IsaacLab/docs/source/policy_deployment/01_io_descriptors/io_descriptors_101.rst new file mode 100644 index 0000000000000000000000000000000000000000..1559153bea905d0439693999922d5b26e88e2b37 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/policy_deployment/01_io_descriptors/io_descriptors_101.rst @@ -0,0 +1,281 @@ +IO Descriptors 101 +================== + +.. currentmodule:: isaaclab + +In this tutorial, we will learn about IO descriptors, what they are, how to export them, and how to add them to +your environments. We will use the Anymal-D robot as an example to demonstrate how to export IO descriptors from +an environment, and use our own terms to demonstrate how to attach IO descriptors to custom action and observation terms. + + +What are IO Descriptors? +------------------------ + +Before we dive into IO descriptors, let's first understand what they are and how they can be useful. + +IO descriptors are a way to describe the inputs and outputs of a policy trained using the ManagerBasedRLEnv in Isaac +Lab. In other words, they describe the action and observation terms of a policy. This description is used to generate +a YAML file that can be loaded in an external tool to run the policies without having to manually input the +configuration of the action and observation terms. + +In addition to this the IO Descriptors provide the following information: +- The parameters of all the joints in the articulation. +- Some simulation parameters including the simulation time step, and the policy time step. +- For some action and observation terms, it provides the joint names or body names in the same order as they appear in the action/observation terms. +- For both the observation and action terms, it provides the terms in the exact same order as they appear in the managers. Making it easy to reconstruct them from the YAML file. + +Here is an example of what the action part of the YAML generated from the IO descriptors looks like for the Anymal-D robot: + +.. literalinclude:: ../../_static/policy_deployment/01_io_descriptors/isaac_velocity_flat_anymal_d_v0_IO_descriptors.yaml + :language: yaml + :lines: 1-39 + +Here is an example of what a portion of the observation part of the YAML generated from the IO descriptors looks like for the Anymal-D robot: + +.. literalinclude:: ../../_static/policy_deployment/01_io_descriptors/isaac_velocity_flat_anymal_d_v0_IO_descriptors.yaml + :language: yaml + :lines: 158-199 + +.. literalinclude:: ../../_static/policy_deployment/01_io_descriptors/isaac_velocity_flat_anymal_d_v0_IO_descriptors.yaml + :language: yaml + :lines: 236-279 + +Something to note here is that both the action and observation terms are returned as list of dictionaries, and not a dictionary of dictionaries. +This is done to ensure the order of the terms is preserved. Hence, to retrieve the action or observation term, the users need to look for the +``name`` key in the dictionaries. + +For example, in the following snippet, we are looking at the ``projected_gravity`` observation term. The ``name`` key is used to identify the term. +The ``full_path`` key is used to provide an explicit path to the function in Isaac Lab's source code that is used to compute this term. Some flags +like ``mdp_type`` and ``observation_type`` are also provided, these don't have any functional impact. They are here to inform the user that this is the +category this term belongs to. + +.. literalinclude:: ../../_static/policy_deployment/01_io_descriptors/isaac_velocity_flat_anymal_d_v0_IO_descriptors.yaml + :language: yaml + :lines: 200-219 + :emphasize-lines: 9, 11 + + +Exporting IO Descriptors from an Environment +-------------------------------------------- + +In this section, we will cover how to export IO descriptors from an environment. +Keep in mind that this feature is only available to the manager based RL environments. + +If a policy has already been trained using a given configuration, then the IO descriptors can be exported using: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/export_io_descriptors.py --task --output_dir + +For example, if we want to export the IO descriptors for the Anymal-D robot, we can run: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/export_io_descriptors.py --task Isaac-Velocity-Flat-Anymal-D-v0 --output_dir ./io_descriptors + +When training a policy, it is also possible to request the IO descriptors to be exported at the beginning of the training. +This can be done by setting the ``export_io_descriptors`` flag in the command line. + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Velocity-Flat-Anymal-D-v0 --export_io_descriptors + ./isaaclab.sh train --rl_library sb3 --task Isaac-Velocity-Flat-Anymal-D-v0 --export_io_descriptors + ./isaaclab.sh train --rl_library rl_games --task Isaac-Velocity-Flat-Anymal-D-v0 --export_io_descriptors + ./isaaclab.sh train --rl_library skrl --task Isaac-Velocity-Flat-Anymal-D-v0 --export_io_descriptors + + +Attaching IO Descriptors to Custom Observation Terms +---------------------------------------------------- + +In this section, we will cover how to attach IO descriptors to custom observation terms. + +Let's take a look at how we can attach an IO descriptor to a simple observation term: + +.. code-block:: python + + @generic_io_descriptor( + units="m/s", axes=["X", "Y", "Z"], observation_type="RootState", on_inspect=[record_shape, record_dtype] + ) + def base_lin_vel(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: + """Root linear velocity in the asset's root frame.""" + # extract the used quantities (to enable type-hinting) + asset: RigidObject = env.scene[asset_cfg.name] + return asset.data.root_lin_vel_b + +Here, we are defining a custom observation term called ``base_lin_vel`` that computes the root linear velocity of the robot. +We are also attaching an IO descriptor to this term. The IO descriptor is defined using the ``@generic_io_descriptor`` decorator. + +The ``@generic_io_descriptor`` decorator is a special decorator that is used to attach an IO descriptor to a custom observation term. +It takes arbitrary arguments that are used to describe the observation term, in this case we provide extra information that could be +useful for the end user: + +- ``units``: The units of the observation term. +- ``axes``: The axes of the observation term. +- ``observation_type``: The type of the observation term. + +You'll also notice that there is an ``on_inspect`` argument that is provided. This is a list of functions that are used to inspect the observation term. +In this case, we are using the ``record_shape`` and ``record_dtype`` functions to record the shape and dtype of the output of the observation term. + +These functions are defined like so: + +.. code-block:: python + + def record_shape(output: torch.Tensor, descriptor: GenericObservationIODescriptor, **kwargs) -> None: + """Record the shape of the output tensor. + + Args: + output: The output tensor. + descriptor: The descriptor to record the shape to. + **kwargs: Additional keyword arguments. + """ + descriptor.shape = (output.shape[-1],) + + + def record_dtype(output: torch.Tensor, descriptor: GenericObservationIODescriptor, **kwargs) -> None: + """Record the dtype of the output tensor. + + Args: + output: The output tensor. + descriptor: The descriptor to record the dtype to. + **kwargs: Additional keyword arguments. + """ + descriptor.dtype = str(output.dtype) + +They always take the output tensor of the observation term as the first argument, and the descriptor as the second argument. +In the ``kwargs`` all the inputs of the observation term are provided. In addition to the ``on_inspect`` functions, the decorator +will also call call some functions in the background to collect the ``name``, the ``description``, and the ``full_path`` of the +observation term. Note that adding this decorator does not change the signature of the observation term, so it can be used safely +with the observation manager! + +Let us now take a look at a more complex example: getting the relative joint positions of the robot. + +.. code-block:: python + + @generic_io_descriptor( + observation_type="JointState", + on_inspect=[record_joint_names, record_dtype, record_shape, record_joint_pos_offsets], + units="rad", + ) + def joint_pos_rel(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: + """The joint positions of the asset w.r.t. the default joint positions. + + Note: Only the joints configured in :attr:`asset_cfg.joint_ids` will have their positions returned. + """ + # extract the used quantities (to enable type-hinting) + asset: Articulation = env.scene[asset_cfg.name] + return asset.data.joint_pos[:, asset_cfg.joint_ids] - asset.data.default_joint_pos[:, asset_cfg.joint_ids] + +Similarly to the previous example, we are adding an IO descriptor to a custom observation term with a set of functions that probe the observation term. + +To get the name of the joints we can write the following function: + +.. code-block:: python + + def record_joint_names(output: torch.Tensor, descriptor: GenericObservationIODescriptor, **kwargs) -> None: + """Record the joint names of the output tensor. + + Expects the `asset_cfg` keyword argument to be set. + + Args: + output: The output tensor. + descriptor: The descriptor to record the joint names to. + **kwargs: Additional keyword arguments. + """ + asset: Articulation = kwargs["env"].scene[kwargs["asset_cfg"].name] + joint_ids = kwargs["asset_cfg"].joint_ids + if joint_ids == slice(None, None, None): + joint_ids = list(range(len(asset.joint_names))) + descriptor.joint_names = [asset.joint_names[i] for i in joint_ids] + +Note that we can access all the inputs of the observation term in the ``kwargs`` dictionary. Hence we can access the ``asset_cfg``, which contains the +configuration of the articulation that the observation term is computed on. + +To get the offsets, we can write the following function: + +.. code-block:: python + + def record_joint_pos_offsets(output: torch.Tensor, descriptor: GenericObservationIODescriptor, **kwargs): + """Record the joint position offsets of the output tensor. + + Expects the `asset_cfg` keyword argument to be set. + + Args: + output: The output tensor. + descriptor: The descriptor to record the joint position offsets to. + **kwargs: Additional keyword arguments. + """ + asset: Articulation = kwargs["env"].scene[kwargs["asset_cfg"].name] + ids = kwargs["asset_cfg"].joint_ids + # Get the offsets of the joints for the first robot in the scene. + # This assumes that all robots have the same joint offsets. + descriptor.joint_pos_offsets = asset.data.default_joint_pos[:, ids][0] + +With this in mind, you should now be able to attach an IO descriptor to your own custom observation terms! However, before +we close this tutorial, let's take a look at how we can attach an IO descriptor to a custom action term. + + +Attaching IO Descriptors to Custom Action Terms +----------------------------------------------- + +In this section, we will cover how to attach IO descriptors to custom action terms. Action terms are classes that +inherit from the :class:`managers.ActionTerm` class. To add an IO descriptor to an action term, we need to expand +upon its :meth:`~managers.ActionTerm.IO_descriptor` property. + +By default, the :meth:`~managers.ActionTerm.IO_descriptor` property returns the base descriptor and fills the following fields: +- ``name``: The name of the action term. +- ``full_path``: The full path of the action term. +- ``description``: The description of the action term. +- ``export``: Whether to export the action term. + +.. code-block:: python + + @property + def IO_descriptor(self) -> GenericActionIODescriptor: + """The IO descriptor for the action term.""" + self._IO_descriptor.name = re.sub(r"([a-z])([A-Z])", r"\1_\2", self.__class__.__name__).lower() + self._IO_descriptor.full_path = f"{self.__class__.__module__}.{self.__class__.__name__}" + self._IO_descriptor.description = " ".join(self.__class__.__doc__.split()) + self._IO_descriptor.export = self.export_IO_descriptor + return self._IO_descriptor + +To add more information to the descriptor, we need to override the :meth:`~managers.ActionTerm.IO_descriptor` property. +Let's take a look at an example on how to add the joint names, scale, offset, and clip to the descriptor. + +.. code-block:: python + + @property + def IO_descriptor(self) -> GenericActionIODescriptor: + """The IO descriptor of the action term. + + This descriptor is used to describe the action term of the joint action. + It adds the following information to the base descriptor: + - joint_names: The names of the joints. + - scale: The scale of the action term. + - offset: The offset of the action term. + - clip: The clip of the action term. + + Returns: + The IO descriptor of the action term. + """ + super().IO_descriptor + self._IO_descriptor.shape = (self.action_dim,) + self._IO_descriptor.dtype = str(self.raw_actions.dtype) + self._IO_descriptor.action_type = "JointAction" + self._IO_descriptor.joint_names = self._joint_names + self._IO_descriptor.scale = self._scale + # This seems to be always [4xNum_joints] IDK why. Need to check. + if isinstance(self._offset, torch.Tensor): + self._IO_descriptor.offset = self._offset[0].detach().cpu().numpy().tolist() + else: + self._IO_descriptor.offset = self._offset + # FIXME: This is not correct. Add list support. + if self.cfg.clip is not None: + if isinstance(self._clip, torch.Tensor): + self._IO_descriptor.clip = self._clip[0].detach().cpu().numpy().tolist() + else: + self._IO_descriptor.clip = self._clip + else: + self._IO_descriptor.clip = None + return self._IO_descriptor + +This is it! You should now be able to attach an IO descriptor to your own custom action terms which concludes this tutorial. diff --git a/simulation/modules/IsaacLab/docs/source/policy_deployment/02_gear_assembly/gear_assembly_policy.rst b/simulation/modules/IsaacLab/docs/source/policy_deployment/02_gear_assembly/gear_assembly_policy.rst new file mode 100644 index 0000000000000000000000000000000000000000..93bba03ab6ac9ffb184b17be0f3c47ff22fb7b20 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/policy_deployment/02_gear_assembly/gear_assembly_policy.rst @@ -0,0 +1,912 @@ +.. _walkthrough_sim_to_real: + +Training a Gear Insertion Policy and ROS Deployment +==================================================== + +This tutorial walks you through how to train a gear insertion reinforcement learning (RL) policy that transfers from simulation to a real robot. The workflow consists of two main stages: + +1. **Simulation Training in Isaac Lab**: Train the policy in a high-fidelity physics simulation with domain randomization +2. **Real Robot Deployment with Isaac ROS**: Deploy the trained policy on real hardware using Isaac ROS and a custom ROS inference node + +This walkthrough covers the key principles and best practices for sim-to-real transfer using Isaac Lab. + +**Supported Robots:** + +- **Universal Robots UR10e**: 6-DOF industrial robot arm with Robotiq 2F-140 or 2F-85 gripper +- **Flexiv Rizon 4s**: 7-DOF collaborative robot arm with Grav parallel gripper + +**Task Details:** + +The gear assembly policy operates as follows: + +1. **Initial State**: The policy assumes the gear is already grasped by the gripper at the start of the episode +2. **Input Observations**: The policy receives the pose of the gear shaft (position and orientation) in which the gear should be inserted, obtained from a separate perception pipeline +3. **Policy Output**: The policy outputs delta joint positions (incremental changes to joint angles) to control the robot arm and perform the insertion +4. **Generalization**: The trained policy generalizes across 3 different gear sizes without requiring retraining for each size + + +.. figure:: ../../_static/policy_deployment/02_gear_assembly/gear_assembly_sim_real.webm + :align: center + :figwidth: 100% + :alt: Comparison of gear assembly in simulation versus real hardware + + Sim-to-real transfer: Gear assembly policy trained in Isaac Lab (left) successfully deployed on real UR10e robot (right). + +This environment has been successfully deployed on real UR10e and Flexiv Rizon 4s robots without an IsaacLab dependency. + +**Scope of This Tutorial:** + +This tutorial focuses exclusively on the **training part** of the sim-to-real transfer workflow in Isaac Lab. For the complete deployment workflow on the real robot, including the exact steps to set up the vision pipeline, robot interface and the ROS inference node to run your trained policy on real hardware, please refer to the `Isaac ROS Documentation `_. + +Overview +-------- + +Successful sim-to-real transfer requires addressing three fundamental aspects: + +1. **Input Consistency**: Ensuring the observations your policy receives in simulation match those available on the real robot +2. **System Response Consistency**: Ensuring the robot and environment respond to actions in simulation the same way they do in reality +3. **Output Consistency**: Ensuring any post-processing applied to policy outputs in Isaac Lab is also applied during real-world inference + +When all three aspects are properly addressed, policies trained purely in simulation can achieve robust performance on real hardware without any real-world training data. + +**Debugging Tip**: When your policy fails on the real robot, the best approach to debug is to set up the real robot with the same initial observations as in simulation, then compare how the controller/system respond. This isolates whether the problem is from observation mismatch (Input Consistency) or physics/controller mismatch (System Response Consistency). + +Part 1: Input Consistency +-------------------------- + +The observations your policy receives must be consistent between simulation and reality. This means: + +1. The observation space should only include information available from real sensors +2. Sensor noise and delays should be modeled appropriately + +Using Real-Robot-Available Observations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Your simulation environment should only use observations that are available on the real robot and not use "privileged" information that wouldn't be available in deployment. + + +Observation Specification +^^^^^^^^^^^^^^^^^^^^^^^^^ + +The Gear Assembly environment uses both proprioceptive and exteroceptive (vision) observations: + +.. list-table:: Gear Assembly Environment Observations + :widths: 20 10 10 20 20 20 + :header-rows: 1 + + * - Observation + - UR10e Dim + - Rizon 4s Dim + - Real-World Source + - UR10e Noise + - Rizon 4s Noise + * - ``joint_pos`` + - 6 + - 7 + - Robot controller + - None + - None + * - ``joint_vel`` + - 6 + - 7 + - Robot controller + - None + - None + * - ``gear_shaft_pos`` + - 3 + - 3 + - FoundationPose + RealSense depth + - ±5mm + - ±10mm + * - ``gear_shaft_quat`` + - 4 + - 4 + - FoundationPose + RealSense depth + - None + - ±2° + +**Total observation dimension:** 19 (UR10e) or 21 (Rizon 4s) + +.. note:: + + The Rizon 4s uses higher observation noise than the UR10e. The position noise is doubled (±10mm vs ±5mm) and quaternion noise (±2° per axis via quaternion multiplication) is added to the gear shaft orientation. These noise levels are set in the Rizon4s-specific config (``joint_pos_env_cfg.py``) rather than the shared base class, so they do not affect UR10e environments. The higher noise trains a more robust policy for the Rizon 4s perception pipeline. + +**Implementation (base class, shared by all robots):** + +.. code-block:: python + + @configclass + class PolicyCfg(ObsGroup): + """Observations for policy group.""" + + # Robot joint states - NO noise for proprioceptive observations + joint_pos = ObsTerm( + func=mdp.joint_pos, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*"])}, + ) + joint_vel = ObsTerm( + func=mdp.joint_vel, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*"])}, + ) + + # Vision-based observations with noise calibrated to FoundationPose + RealSense D435 error + gear_shaft_pos = ObsTerm( + func=mdp.gear_shaft_pos_w, + params={}, + noise=ResetSampledConstantNoiseModelCfg( + noise_cfg=UniformNoiseCfg(n_min=-0.005, n_max=0.005, operation="add") # ±5mm + ), + ) + gear_shaft_quat = ObsTerm(func=mdp.gear_shaft_quat_w) + + def __post_init__(self): + self.enable_corruption = True # Enable for perception observations only + self.concatenate_terms = True + +**Rizon 4s overrides** (in ``joint_pos_env_cfg.py``): + +.. code-block:: python + + # Higher noise for Rizon 4s perception pipeline + self.observations.policy.gear_shaft_pos.noise = ResetSampledConstantNoiseModelCfg( + noise_cfg=UniformNoiseCfg(n_min=-0.01, n_max=0.01, operation="add") # ±10mm + ) + self.observations.policy.gear_shaft_quat.noise = ResetSampledQuaternionNoiseModelCfg( + roll_range=(-0.03491, 0.03491), # ±2 degrees + pitch_range=(-0.03491, 0.03491), + yaw_range=(-0.03491, 0.03491), + ) + +**Why No Noise for Proprioceptive Observations?** + +Empirically, we found that policies trained without noise on proprioceptive observations (joint positions and velocities) transfer well to real hardware. The UR10e controller provides sufficiently accurate joint state feedback that modeling sensor noise doesn't improve sim-to-real transfer for these tasks. + + +Part 2: System Response Consistency +------------------------------------ + +Once your observations are consistent, you need to ensure the simulated robot and environment respond to actions the same way the real system does. In this use case, this involves three main aspects: + +1. Physics simulation parameters (friction, contact properties) +2. Actuator modeling (PD controller gains, effort limits) +3. Domain randomization + +Physics Parameter Tuning +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Accurate physics simulation is critical for contact-rich tasks. Key parameters include: + +- Friction coefficients (static and dynamic) +- Contact solver parameters +- Material properties +- Rigid body properties + +**Example: Gear Assembly Physics Configuration** + +The Gear Assembly task requires accurate contact modeling for insertion. Here's how friction is configured: + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: python + + # From config/ur_10e/joint_pos_env_cfg.py + + small_gear_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("factory_gear_small", body_names=".*"), + "static_friction_range": (0.75, 0.75), + "dynamic_friction_range": (0.75, 0.75), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + robot_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*finger"), + "static_friction_range": (0.75, 0.75), + "dynamic_friction_range": (0.75, 0.75), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: python + + # From config/rizon_4s/joint_pos_env_cfg.py + + small_gear_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("factory_gear_small", body_names=".*"), + "static_friction_range": (0.75, 0.75), + "dynamic_friction_range": (0.75, 0.75), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + robot_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*finger.*"), + "static_friction_range": (3.0, 3.0), + "dynamic_friction_range": (3.0, 3.0), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + +These friction values were determined through iterative visual comparison: + +1. Record videos of the gear being grasped and manipulated on real hardware +2. Start training in simulation and observe the live simulation viewer +3. Look for physics issues (penetration, unrealistic slipping, poor contact) +4. Adjust friction coefficients and solver parameters and retry +5. Compare the gear's behavior in the gripper visually between sim and real +6. Repeat adjustments until behavior matches (no need to wait for full policy training) +7. Once physics looks good, train in headless mode with video recording: + + .. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-GearAssembly-UR10e-2F140-v0 \ + --video --video_length 800 --video_interval 5000 + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-GearAssembly-Rizon4s-Grav-ROS-Inference-v0 \ + --video --video_length 800 --video_interval 5000 + +8. Review the recorded videos and compare with real hardware videos to verify physics behavior + +**Contact Solver Configuration** + +Contact-rich manipulation requires careful solver tuning. These parameters were calibrated through the same iterative visual comparison process as the friction coefficients: + +.. code-block:: python + + # Robot rigid body properties + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=True, # Robot is mounted, no gravity + max_depenetration_velocity=5.0, # Control interpenetration resolution + linear_damping=0.0, # No artificial damping + angular_damping=0.0, + max_linear_velocity=1000.0, + max_angular_velocity=3666.0, + enable_gyroscopic_forces=True, # Important for accurate dynamics + solver_position_iteration_count=4, # Balance accuracy vs performance + solver_velocity_iteration_count=1, + max_contact_impulse=1e32, # Allow large contact forces + ), + +**Important**: The ``solver_position_iteration_count`` is a critical parameter for contact-rich tasks. Increasing this value improves collision simulation stability and reduces penetration issues, but it also increases simulation and training time. For the gear assembly task, we use ``solver_position_iteration_count=4`` as a balance between physics accuracy and computational performance. If you observe penetration or unstable contacts, try increasing to 8 or 16, but expect slower training. + +.. code-block:: python + + # Articulation properties + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=False, + solver_position_iteration_count=4, + solver_velocity_iteration_count=1, + ), + + # Contact properties + collision_props=sim_utils.CollisionPropertiesCfg( + contact_offset=0.005, # 5mm contact detection distance + rest_offset=0.0, # Objects touch at 0 distance + ), + +Actuator Modeling +~~~~~~~~~~~~~~~~~ + +Accurate actuator modeling ensures the simulated robot moves like the real one. This includes: + +- PD controller gains (stiffness and damping) +- Effort and velocity limits +- Joint friction + +**Controller Choice: Impedance Control** + +For the UR10e and Flexiv Rizon 4s deployments, we use an impedance controller interface. Using a simpler controller like impedance control reduces the chances of variation between simulation and reality compared to more complex controllers (e.g., operational space control, hybrid force-position control). Simpler controllers: + +- Have fewer parameters that can mismatch between sim and real +- Are easier to model accurately in simulation +- Have more predictable behavior that's easier to replicate +- Reduce the controller complexity as a source of sim-real gap + +**Actuator Configurations:** + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: python + + # Default UR10e actuator configuration + actuators = { + "arm": ImplicitActuatorCfg( + joint_names_expr=["shoulder_pan_joint", "shoulder_lift_joint", + "elbow_joint", "wrist_1_joint", "wrist_2_joint", "wrist_3_joint"], + effort_limit=87.0, # From UR10e specifications + velocity_limit=2.0, # From UR10e specifications + stiffness=800.0, # Calibrated to match real behavior + damping=40.0, # Calibrated to match real behavior + ), + } + + .. tab-item:: Flexiv Rizon 4s + Grav Gripper + + The Rizon 4s uses ``ImplicitActuatorCfg`` with per-joint-group tuning, plus actuators for the Grav parallel gripper: + + .. code-block:: python + + actuators = { + "shoulder": ImplicitActuatorCfg( + joint_names_expr=["joint[1-2]"], + effort_limit=123.0, velocity_limit=2.094, + stiffness=6000.0, damping=108.4, + ), + "elbow": ImplicitActuatorCfg( + joint_names_expr=["joint[3-4]"], + effort_limit=64.0, velocity_limit=2.443, + stiffness=4200.0, damping=90.7, + ), + "wrist": ImplicitActuatorCfg( + joint_names_expr=["joint[5-7]"], + effort_limit=39.0, velocity_limit=4.887, + stiffness=1500.0, damping=54.2, + ), + "gripper_drive": ImplicitActuatorCfg( + joint_names_expr=["finger_joint"], + effort_limit=2.0, velocity_limit=1.0, + stiffness=2e3, damping=1e1, + ), + "gripper_passive": ImplicitActuatorCfg( + joint_names_expr=[".*_knuckle_joint"], + effort_limit=1.0, velocity_limit=1.0, + stiffness=0.0, damping=0.0, + ), + } + +**Domain Randomization of Actuator Parameters (UR10e only)** + +To account for variations in real robot behavior, the UR10e configuration randomizes actuator gains during training: + +.. code-block:: python + + # From EventCfg in config/ur_10e/joint_pos_env_cfg.py + robot_joint_stiffness_and_damping = EventTerm( + func=mdp.randomize_actuator_gains, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=["shoulder_.*", "elbow_.*", "wrist_.*"]), + "stiffness_distribution_params": (0.75, 1.5), # 75% to 150% of nominal + "damping_distribution_params": (0.3, 3.0), # 30% to 300% of nominal + "operation": "scale", + "distribution": "log_uniform", + }, + ) + + +**Joint Friction Randomization (UR10e only)** + +Real robots have friction in their joints that varies with position, velocity, and temperature. For the UR10e with impedance controller interface, we observed significant stiction (static friction) causing the controller to not reach target joint positions. + +**Characterizing Real Robot Behavior:** + +To quantify this behavior, we plotted the step response of the impedance controller on the real robot and observed contact offsets of approximately 0.25 degrees from the commanded setpoint. This steady-state error is caused by joint friction opposing the controller's commanded motion. Based on these measurements, we added joint friction modeling in simulation to replicate this behavior: + +.. code-block:: python + + # From EventCfg in config/ur_10e/joint_pos_env_cfg.py + joint_friction = EventTerm( + func=mdp.randomize_joint_parameters, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=["shoulder_.*", "elbow_.*", "wrist_.*"]), + "friction_distribution_params": (0.3, 0.7), # Add 0.3 to 0.7 Nm friction + "operation": "add", + "distribution": "uniform", + }, + ) + +**Why Joint Friction Matters**: Without modeling joint friction in simulation, the policy learns to expect that commanded joint positions are always reached. On the real robot, stiction prevents small movements and causes steady-state errors. By adding friction during training, the policy learns to account for these effects and commands appropriately larger motions to overcome friction. + +.. note:: + + **Flexiv Rizon 4s**: Domain randomization for actuator gains and joint friction is not included in the Rizon 4s ``EventCfg`` (``config/rizon_4s/joint_pos_env_cfg.py``). We found the Rizon 4s real-world controller is more stable and precise than the UR10e's, with negligible stiction and steady-state error. As a result, the simulation policy transfers well to the real robot without needing these additional randomizations. + +**Compensating for Stiction with Action Scaling:** + +To help the policy overcome stiction on the real robot, we also increased the output action scaling. The Isaac ROS documentation notes that a higher action scale (0.0325 vs 0.025) is needed to overcome the higher static friction (stiction) compared to the 2F-85 gripper. This increased scaling ensures the policy commands are large enough to overcome the friction forces observed in the step response analysis. + +Action Space Design +~~~~~~~~~~~~~~~~~~~ + +Your action space should match what the real robot controller can execute. For this task we found that **incremental joint position control** is the most reliable approach. + +**Action Configuration:** + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: python + + self.joint_action_scale = 0.025 # ±1.4 degrees per step + + self.actions.arm_action = mdp.RelativeJointPositionActionCfg( + asset_name="robot", + joint_names=["shoulder_pan_joint", "shoulder_lift_joint", "elbow_joint", + "wrist_1_joint", "wrist_2_joint", "wrist_3_joint"], + scale=self.joint_action_scale, + use_zero_offset=True, + ) + + **Action dimension:** 6 + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: python + + self.joint_action_scale = 0.025 # ±1.4 degrees per step + + self.actions.arm_action = mdp.RelativeJointPositionActionCfg( + asset_name="robot", + joint_names=["joint1", "joint2", "joint3", "joint4", + "joint5", "joint6", "joint7"], + scale=self.joint_action_scale, + use_zero_offset=True, + ) + + **Action dimension:** 7 + +The action scale is a critical hyperparameter that should be tuned based on: + +- Task precision requirements (smaller for contact-rich tasks) +- Control frequency (higher frequency allows larger steps) + +Domain Randomization Strategy +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Domain randomization should cover the range of conditions in which you want the real robot to perform. Increasing randomization ranges makes it harder for the policy to learn, but allows for larger variations in inputs and system parameters. The key is to balance training difficulty with robustness: randomize enough to cover real-world variations, but not so much that the policy cannot learn effectively. + +**Pose Randomization** + +For manipulation tasks, randomize object poses to ensure the policy works across the workspace. Both robots use the same gear and base pose randomization: + +.. code-block:: python + + # Shared by both UR10e and Rizon 4s EventCfg + randomize_gears_and_base_pose = EventTerm( + func=gear_assembly_events.randomize_gears_and_base_pose, + mode="reset", + params={ + "pose_range": { + "x": [-0.1, 0.1], # ±10cm + "y": [-0.25, 0.25], # ±25cm + "z": [-0.1, 0.1], # ±10cm + "roll": [-math.pi/90, math.pi/90], # ±2 degrees + "pitch": [-math.pi/90, math.pi/90], # ±2 degrees + "yaw": [-math.pi/6, math.pi/6], # ±30 degrees + }, + "gear_pos_range": { + "x": [-0.02, 0.02], # ±2cm relative to base + "y": [-0.02, 0.02], + "z": [0.0575, 0.0775], # 5.75-7.75cm above base + }, + "velocity_range": {}, + }, + ) + +**Initial State Randomization** + +Randomizing the robot's initial configuration helps the policy handle different starting conditions: + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: python + + set_robot_to_grasp_pose = EventTerm( + func=gear_assembly_events.set_robot_to_grasp_pose, + mode="reset", + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "pos_randomization_range": { + "x": [-0.0, 0.0], + "y": [-0.005, 0.005], # ±5mm variation + "z": [-0.003, 0.003], # ±3mm variation + }, + }, + ) + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: python + + set_robot_to_grasp_pose = EventTerm( + func=gear_assembly_events.set_robot_to_grasp_pose, + mode="reset", + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "pos_randomization_range": { + "x": [-0.0, 0.0], + "y": [-0.0, 0.0], + "z": [-0.0, 0.0], + }, + }, + ) + +Reward Shaping +~~~~~~~~~~~~~~ + +The gear assembly environment uses keypoint-based rewards that measure the distance between keypoints on the gear and corresponding keypoints on the gear shaft. Both robots share a base set of reward terms defined in ``gear_assembly_env_cfg.py``: + +- **Keypoint tracking** (``keypoint_entity_error``): Penalizes the L2 distance between gear and shaft keypoints, encouraging the gear to approach the shaft. +- **Exponential keypoint tracking** (``keypoint_entity_error_exp``): Provides a dense exponential reward that grows sharply as keypoints align, helping the policy refine fine-grained insertion. +- **Action rate** (``action_rate_l2``): Penalizes large changes in actions between timesteps, promoting smooth motions. + +**Rizon 4s additional reward terms:** + +The Rizon 4s configuration adds two reward terms that measure the distance between the robot's end effector and the grasp-corrected pose computed from the active gear. For each gear, the code applies ``grasp_rot_offset`` and per-gear-size ``gear_offsets_grasp`` to compute where the EE should be if properly grasping that gear, then measures keypoint distance between the actual EE pose and that target. This acts as a grasp quality metric. These terms are defined only in the Rizon4s config (``joint_pos_env_cfg.py``) so they do not affect UR10e training: + +.. code-block:: python + + # Penalizes distance between EE and grasp-corrected pose + self.rewards.end_effector_grasp_keypoint_tracking = RewTerm( + func=mdp.keypoint_ee_grasp_error, + weight=-0.5, + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "keypoint_scale": 0.15, + "ee_grasp_threshold": 0.00, + "weight_ramp_start": 0.0, + "weight_ramp_steps": 250_000, + "end_effector_body_name": self.end_effector_body_name, + "grasp_rot_offset": self.grasp_rot_offset, + "gear_offsets_grasp": self.gear_offsets_grasp, + }, + ) + + # Exponential version for dense reward near alignment + self.rewards.end_effector_grasp_keypoint_tracking_exp = RewTerm( + func=mdp.keypoint_ee_grasp_error_exp, + weight=0.5, + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "kp_exp_coeffs": [(50, 0.0001), (300, 0.0001)], + "kp_use_sum_of_exps": False, + "keypoint_scale": 0.15, + "ee_grasp_threshold": 0.00, + "weight_ramp_start": 0.0, + "weight_ramp_steps": 250_000, + "end_effector_body_name": self.end_effector_body_name, + "grasp_rot_offset": self.grasp_rot_offset, + "gear_offsets_grasp": self.gear_offsets_grasp, + }, + ) + +These terms encourage the Rizon 4s policy to keep the gripper properly aligned with the gear during insertion. The distance is ~0 when the EE is correctly grasping the gear, and increases when the gripper drifts away. The ``weight_ramp_steps`` parameter linearly ramps the reward weight from zero over the first 512k environment steps, allowing the policy to first learn coarse approach/insertion behavior before the grasp quality reward becomes active. + +.. list-table:: Reward Terms Comparison + :widths: 40 15 15 + :header-rows: 1 + + * - Reward Term + - UR10e + - Rizon 4s + * - ``keypoint_entity_error`` (gear-shaft distance) + - Yes + - Yes + * - ``keypoint_entity_error_exp`` (exponential gear-shaft) + - Yes + - Yes + * - ``action_rate_l2`` (smooth actions) + - Yes + - Yes + * - ``keypoint_ee_grasp_error`` (EE vs grasp-corrected gear) + - No + - Yes + * - ``keypoint_ee_grasp_error_exp`` (exponential EE vs gear) + - No + - Yes + + +Part 3: Training the Policy in Isaac Lab +----------------------------------------- + +Now that we've covered the key principles for sim-to-real transfer, let's train the gear assembly policy in Isaac Lab. + +Step 1: Visualize the Environment +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +First, launch the training with a small number of environments and visualization enabled to verify that the environment is set up correctly: + +.. tab-set:: + + .. tab-item:: UR10e (2F-140) + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-GearAssembly-UR10e-2F140-ROS-Inference-v0 \ + --num_envs 4 \ + --visualizer kit + + .. tab-item:: UR10e (2F-85) + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-GearAssembly-UR10e-2F85-ROS-Inference-v0 \ + --num_envs 4 \ + --visualizer kit + + .. tab-item:: Flexiv Rizon 4s + Grav + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-GearAssembly-Rizon4s-Grav-ROS-Inference-v0 \ + --num_envs 4 \ + --visualizer kit + +This will open the Isaac Sim viewer where you can observe the training process in real-time. + +.. figure:: ../../_static/policy_deployment/02_gear_assembly/sim_real_gear_assembly_train.jpg + :align: center + :figwidth: 100% + :alt: Gear assembly training visualization in Isaac Lab + + Training visualization showing multiple parallel environments with robots grasping gears. + +**What to Expect:** + +In the early stages of training, you should see the robots moving around with the gears grasped by the grippers, but they won't be successfully inserting the gears yet. This is expected behavior as the policy is still learning. The robots will move the grasped gear in various directions. Once you've verified the environment looks correct, stop the training (Ctrl+C) and proceed to full-scale training. + +Step 2: Full-Scale Training with Video Recording +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Now launch the full training run with more parallel environments in headless mode for faster training. We'll also enable video recording to monitor progress: + +.. tab-set:: + + .. tab-item:: UR10e (2F-140) + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-GearAssembly-UR10e-2F140-ROS-Inference-v0 \ + --num_envs 256 \ + --video --video_length 200 --video_interval 76800 + + .. tab-item:: UR10e (2F-85) + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-GearAssembly-UR10e-2F85-ROS-Inference-v0 \ + --num_envs 256 \ + --video --video_length 200 --video_interval 76800 + + .. tab-item:: Flexiv Rizon 4s + Grav + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-GearAssembly-Rizon4s-Grav-ROS-Inference-v0 \ + --num_envs 256 \ + --video --video_length 200 --video_interval 76800 + +**Command breakdown:** + +- ``--num_envs 256``: Runs 256 parallel environments for efficient training +- ``--video_length 200``: Each video captures approximately one full episode (``episode_length_s / (sim.dt * decimation)`` = ``6.66 / (1/1000 * 33)`` ≈ 200 steps) +- ``--video_interval 76800``: Records a video every 76,800 environment steps (~every 150 iterations), producing ~10 videos over full training + +Training typically takes ~12-24 hours for a robust insertion policy. The videos will be saved in the ``logs`` directory and can be reviewed to assess policy performance during training. + +.. note:: + + **GPU Memory Considerations**: The default configuration uses 256 parallel environments, which should work on most modern GPUs (e.g., RTX 3090, RTX 4090, A100). For better sim-to-real transfer performance, you can increase ``solver_position_iteration_count`` from 4 to 196 in ``gear_assembly_env_cfg.py`` and ``joint_pos_env_cfg.py`` for more realistic contact simulation, but this requires a larger GPU (e.g., RTX PRO 6000 with 40GB+ VRAM). Higher solver iteration counts reduce penetration and improve contact stability but significantly increase GPU memory usage. + + +**Monitoring Training Progress with TensorBoard:** + +You can monitor training metrics in real-time using TensorBoard. Open a new terminal and run: + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: bash + + ./isaaclab.sh -p -m tensorboard.main --logdir logs/rsl_rl/gear_assembly_ur10e + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: bash + + ./isaaclab.sh -p -m tensorboard.main --logdir logs/rsl_rl/gear_assembly_rizon4s_grav + +Replace the log directory path with your actual training log location if different. TensorBoard will display plots showing rewards, episode lengths, and other metrics. Verify that the rewards are increasing over iterations to ensure the policy is learning successfully. + + +Step 3: Deploy on Real Robot +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Once training is complete, follow the `Isaac ROS inference documentation `_ to deploy your policy. + +The Isaac ROS deployment pipeline directly uses the trained model checkpoint (``.pt`` file) along with the ``agent.yaml`` and ``env.yaml`` configuration files generated during training. No additional export step is required. + +The deployment pipeline uses Isaac ROS and a custom ROS inference node to run the policy on real hardware. The pipeline includes: + +1. **Perception**: Camera-based pose estimation (FoundationPose, Segment Anything) +2. **Motion Planning**: cuMotion for collision-free trajectories +3. **Policy Inference**: Your trained policy running at control frequency in a custom ROS inference node +4. **Robot Control**: Low-level controller executing commands + + +Troubleshooting +--------------- + +This section covers common errors you may encounter during training and their solutions. + +PhysX Collision Stack Overflow +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Error Message:** + +.. code-block:: text + + PhysX error: PxGpuDynamicsMemoryConfig::collisionStackSize buffer overflow detected, + please increase its size to at least 269452544 in the scene desc! + Contacts have been dropped. + +**Cause:** This error occurs when the GPU collision detection buffer is too small for the number of contacts being simulated. This is common in contact-rich environments like gear assembly. + +**Solution:** Increase the ``gpu_collision_stack_size`` parameter in ``gear_assembly_env_cfg.py``: + +.. code-block:: python + + # In GearAssemblyEnvCfg class + sim: SimulationCfg = SimulationCfg( + physx=PhysxCfg( + gpu_collision_stack_size=2**31, # Increase this value if you see overflow errors + gpu_max_rigid_contact_count=2**23, + gpu_max_rigid_patch_count=2**23, + ), + ) + +The error message will suggest a minimum size. Set ``gpu_collision_stack_size`` to at least the recommended value (e.g., if the error says "at least 269452544", set it to ``2**28`` or ``2**29``). Note that increasing this value increases GPU memory usage. + +CUDA Out of Memory +~~~~~~~~~~~~~~~~~~ + +**Error Message:** + +.. code-block:: text + + torch.OutOfMemoryError: CUDA out of memory. + +**Cause:** The GPU does not have enough memory to run the requested number of parallel environments with the current simulation parameters. + +**Solutions (in order of preference):** + +1. **Reduce the number of parallel environments:** + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-GearAssembly-UR10e-2F140-v0 \ + --num_envs 128 # Reduce from 256 to 128, 64, etc. + + **Trade-off:** Using fewer environments will reduce sample diversity per training iteration and may slow down training convergence. You may need to train for more iterations to achieve the same performance. However, the final policy quality should be similar. + +2. **If using increased solver iteration counts** (values higher than the default 4): + + In both ``gear_assembly_env_cfg.py`` and ``joint_pos_env_cfg.py``, reduce ``solver_position_iteration_count`` back to the default value of 4, or use intermediate values like 8 or 16: + + .. code-block:: python + + rigid_props=sim_utils.RigidBodyPropertiesCfg( + solver_position_iteration_count=4, # Use default value + # ... other parameters + ), + + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + solver_position_iteration_count=4, # Use default value + # ... other parameters + ), + + **Trade-off:** Lower solver iteration counts may result in less realistic contact dynamics and more penetration issues. The default value of 4 provides a good balance for most use cases. + +3. **Disable video recording during training:** + + Remove the ``--video`` flags to save GPU memory: + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-GearAssembly-UR10e-2F140-v0 \ + --num_envs 256 + + You can always evaluate the trained policy later with visualization. + + +Deterministic Debugging (Play Environment) +------------------------------------------- + +The ``Isaac-Deploy-GearAssembly-Rizon4s-Grav-Play-v0`` environment provides a fully +deterministic setup for debugging policy behavior against a specific real-world scenario. +All randomization is disabled and observation noise is turned off, so the simulation is +identical on every reset. + +To use it, run the standard play command: + +.. code-block:: bash + + ./isaaclab.sh play --rl_library rsl_rl \ + --task Isaac-Deploy-GearAssembly-Rizon4s-Grav-Play-v0 \ + --num_envs 1 \ + --checkpoint + +To match a specific real-world setup, edit the constants at the top of the +``Rizon4sGearAssemblyEnvCfg_PLAY`` class in +``isaaclab_tasks/.../gear_assembly/config/rizon_4s/ros_inference_env_cfg.py``: + +.. code-block:: python + + @configclass + class Rizon4sGearAssemblyEnvCfg_PLAY(Rizon4sGearAssemblyROSInferenceEnvCfg): + # ── Scene setup ── + GEAR_TYPE: str = "gear_large" # which gear to grasp + GEAR_BASE_POS: tuple = (0.481, -0.073, -0.005) # (x, y, z) meters + GEAR_BASE_ROT: tuple = (0.0, 0.0, 0.70711, -0.70711) # quaternion (x,y,z,w) + GEAR_Z_OFFSET: float = 0.0675 # gear height above base + + # ── Observation overrides (None = use simulated values) ── + OBS_SHAFT_POS: tuple | None = None # e.g. (0.481, -0.073, -0.005) + OBS_SHAFT_QUAT: tuple | None = None # e.g. (0.0, 0.0, 0.70711, -0.70711) + +When ``OBS_SHAFT_POS`` or ``OBS_SHAFT_QUAT`` are set (not ``None``), the +play command automatically overwrites the corresponding portions of the +policy's observation tensor every step, regardless of simulation state. This +lets you test what the policy does when given a specific observation (e.g. a +pose captured from the real robot). + +This environment is particularly useful for: + +- Comparing simulated and real-world policy behavior at a known pose +- Injecting real-world observations to verify policy actions match expectations +- Debugging insertion failures at a specific gear base position/orientation + + +Further Resources +----------------- + +- `IndustReal: Transferring Contact-Rich Assembly Tasks from Simulation to Reality `_ +- `FORGE: Force-Guided Exploration for Robust Contact-Rich Manipulation under Uncertainty `_ +- `Isaac ROS Manipulation Documentation `_ +- `Isaac ROS Gear Assembly Tutorial `_ +- RL Training Tutorial: :ref:`tutorial-run-rl-training` diff --git a/simulation/modules/IsaacLab/docs/source/policy_deployment/03_compass_with_NuRec/compass_navigation_policy_with_NuRec.rst b/simulation/modules/IsaacLab/docs/source/policy_deployment/03_compass_with_NuRec/compass_navigation_policy_with_NuRec.rst new file mode 100644 index 0000000000000000000000000000000000000000..2b989cb7024e19e37e99faef58ab04e3904000eb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/policy_deployment/03_compass_with_NuRec/compass_navigation_policy_with_NuRec.rst @@ -0,0 +1,110 @@ +Training and Deploying COMPASS Policies with NuRec Assets +========================================================= + +`COMPASS `_ (Cross-embodiment Mobility Policy via Residual RL and +Skill Synthesis) trains navigation policies that can transfer across robot embodiments. Isaac Lab supports +COMPASS training with NuRec scene assets, so policies can be developed in reconstructed real-world +environments instead of relying only on hand-authored simulation scenes. + +This page gives a short overview of the supported NuRec assets and example COMPASS training clips. For +installation, asset registration, training, evaluation, export, and ROS 2 deployment instructions, see the +`COMPASS handbook `_. + +NuRec Assets for COMPASS +------------------------ + +NuRec assets matter for COMPASS because they allow navigation policies to train in simulation on realistic +geometry, visual appearance, and obstacle layouts. This, in turn, should reduce the sim-to-real gap between +training scenes and real operating environments and improve zero-shot transfer. They also make it possible +to evaluate policies in reconstructed simulation scenes that better reflect target deployment spaces. + +Some sample assets compatible with COMPASS training are available in the +`PhysicalAI-Robotics-NuRec dataset on Hugging Face `_. + +Real2Sim Assets +~~~~~~~~~~~~~~~ + +`NVIDIA Neural Reconstruction (NuRec) `_ converts real-world +sensor data into digital simulation-ready assets for training and testing Physical AI agents. The Real2Sim +workflow converts stereo RGB captures into Isaac Sim-ready assets with aligned geometry, collision meshes, +and simulation-ready scene augmentation. The PhysicalAI-Robotics-NuRec dataset includes several robotics +scenes produced with this workflow; two examples are shown below. + +.. list-table:: + :widths: 50 50 + :class: nurec-gif-grid + + * - .. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/nurec_real2sim_galileo.gif + :alt: Galileo Real2Sim NuRec asset + :class: nurec-gif-cover + :align: center + + **Galileo** + + | Embodiment: `Nova Carter [wheeled robot] `_ + | Sensor Rig: 4 x `Stereo Camera `_ + - .. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/nurec_real2sim_living_room.gif + :alt: Living Room Real2Sim NuRec asset + :class: nurec-gif-cover + :align: center + + **Living Room** + + | Embodiment: Hand-Held + | Sensor Rig: 1 x `Stereo Camera `_ + +XGRIDS Assets +~~~~~~~~~~~~~ + +COMPASS also supports compatible assets reconstructed with XGRIDS. These assets are post-processed into the +NuRec format used by the COMPASS workflow, including mesh alignment and augmentation with simulation-ready +assets available in Isaac Sim. + +.. list-table:: + :widths: 100 + :class: nurec-gif-grid nurec-gif-grid-single + + * - .. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/xgrid_wormhole_with_sim_objects.gif + :alt: Wormhole XGRIDS reconstruction + :class: nurec-gif-cover + :align: center + + **Wormhole** + + | Embodiment: Hand-Held + | Sensor Rig: `XGRIDS PortalCam `_ [2 x fish-eye cameras, 2 x front cameras, 1 x LiDAR] + +COMPASS Workflow +---------------- + +The complete COMPASS workflow is maintained in the COMPASS repository: + +- **Repository:** `NVlabs/COMPASS `_ +- **Branch:** ``real2sim/isaaclab_3.0`` +- **Guide:** `NuRec asset workflow `_ + +The guide covers the COMPASS code path for training with NuRec assets generated by the Real2Sim workflow, +including Isaac Sim and Isaac Lab setup, COMPASS installation, asset download and registration, residual RL +specialist training, evaluation, ONNX and TensorRT export, and ROS 2 sim-to-real deployment. + +Training Examples +----------------- + +The following clips show COMPASS training with different robot embodiments in NuRec scenes. + +.. list-table:: + :widths: 50 50 + :class: nurec-gif-grid + + * - .. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/compass_galileo_g1_training.gif + :alt: COMPASS training with a G1 robot in the Galileo scene + :class: nurec-gif-contain + :align: center + + **Galileo** with G1 + - .. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/compass_xgrid_wormhole_carter_training.gif + :alt: COMPASS training with a Carter robot in the XGRIDS Wormhole scene + :class: nurec-gif-contain + :align: center + + **Wormhole** with Carter diff --git a/simulation/modules/IsaacLab/docs/source/policy_deployment/04_reach/reach_policy.rst b/simulation/modules/IsaacLab/docs/source/policy_deployment/04_reach/reach_policy.rst new file mode 100644 index 0000000000000000000000000000000000000000..32efe0b7b7daf73c704b5918b4acca322ca3840e --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/policy_deployment/04_reach/reach_policy.rst @@ -0,0 +1,675 @@ +.. _walkthrough_reach_sim_to_real: + +Training a Reach Policy for Real Robot Deployment +================================================= + +This tutorial walks you through training an end-effector pose tracking (reach) reinforcement learning (RL) policy that transfers from simulation to a real robot. By the end of this guide, you will have a trained policy capable of controlling a robot arm to reach arbitrary target end-effector poses within its workspace. + +**Supported Robots:** + +- **Universal Robots UR10e**: 6-DOF industrial robot arm +- **Flexiv Rizon 4s**: 7-DOF collaborative robot arm + +**Scope of This Tutorial:** + +This tutorial focuses on the **training** portion of the sim-to-real workflow. For deployment on real hardware, including robot interface setup and ROS inference node configuration, refer to the `Isaac ROS Documentation `_. + +**Prerequisites:** + +Before starting this tutorial, ensure you have Isaac Lab installed and configured. Follow the :ref:`installation guide ` if you haven't already set up your environment. + + +Task Overview +------------- + +The reach task trains a policy to track randomly sampled end-effector poses within the robot's workspace. + +**How It Works:** + +1. A target pose (position and orientation) is randomly sampled within a defined workspace +2. The policy receives the current joint states and the target pose as observations +3. The policy outputs incremental joint position commands to move the end-effector toward the target +4. The target is resampled periodically during training to ensure the policy generalizes across the workspace + + +Key Concepts for Sim-to-Real Transfer +------------------------------------- + +Successful sim-to-real transfer requires consistency across three areas: + +1. **Input Consistency**: Observations available in simulation must match those available on the real robot +2. **System Response Consistency**: The simulated robot must respond to actions similarly to the real robot +3. **Output Consistency**: Any post-processing on policy outputs must be replicated during deployment + +When these are properly addressed, policies trained purely in simulation can transfer to real hardware without any real-world training data. + + +Observation Space +----------------- + +The policy receives only proprioceptive observations, which are reliably available from the robot controller: + +.. list-table:: Reach Environment Observations + :widths: 25 20 20 35 + :header-rows: 1 + + * - Observation + - UR10e Dim + - Rizon 4s Dim + - Source + * - ``joint_pos`` + - 6 + - 7 + - Robot joint encoders + * - ``joint_vel`` + - 6 + - 7 + - Robot joint encoders + * - ``pose_command`` + - 7 + - 7 + - Target pose (3D position + quaternion) + +**Total observation dimension:** 19 (UR10e) or 21 (Rizon 4s) + +**Implementation:** + +.. code-block:: python + + @configclass + class PolicyCfg(ObsGroup): + """Observations for policy group.""" + + joint_pos = ObsTerm(func=mdp.joint_pos, noise=Unoise(n_min=-0.0, n_max=0.0)) + joint_vel = ObsTerm(func=mdp.joint_vel, noise=Unoise(n_min=-0.0, n_max=0.0)) + pose_command = ObsTerm(func=mdp.generated_commands, params={"command_name": "ee_pose"}) + + def __post_init__(self): + self.enable_corruption = True + self.concatenate_terms = True + +.. note:: + + The noise terms are set to zero by default (``Unoise(n_min=-0.0, n_max=0.0)``), meaning no observation noise is applied. This can be adjusted if noise modeling is desired for additional robustness. Modern robot controllers provide sufficiently accurate joint state feedback that adding noise during training is not required for sim-to-real transfer of this task. + + +Action Space +------------ + +The policy outputs **incremental joint position commands**. Each action specifies a delta (change) to apply to the current joint positions: + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: python + + self.actions.arm_action = mdp.RelativeJointPositionActionCfg( + asset_name="robot", + joint_names=[".*"], + scale=0.0625, # ~3.6 degrees per action step + use_zero_offset=True, + ) + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: python + + self.actions.arm_action = mdp.RelativeJointPositionActionCfg( + asset_name="robot", + joint_names=["joint[1-7]"], + scale=0.0625, # ~3.6 degrees per action step + use_zero_offset=True, + ) + +The action scale of 0.0625 radians (~3.6 degrees) per step provides a balance between responsiveness and smooth motion. The UR10e uses ``[".*"]`` to match all joints, while the Rizon 4s explicitly specifies ``["joint[1-7]"]`` to match its 7 arm joints. + +**Action dimension:** 6 (UR10e) or 7 (Rizon 4s) + + +Robot Configurations +-------------------- + +Each robot has specific actuator configurations and workspace definitions. + +.. tab-set:: + + .. tab-item:: UR10e + + The UR10e is a 6-DOF industrial robot with the following actuator configuration: + + .. code-block:: python + + actuators = { + "shoulder": ImplicitActuatorCfg( + joint_names_expr=["shoulder_.*"], + stiffness=1320.0, + damping=72.66, + friction=0.0, + armature=0.0, + ), + "elbow": ImplicitActuatorCfg( + joint_names_expr=["elbow_joint"], + stiffness=600.0, + damping=34.64, + friction=0.0, + armature=0.0, + ), + "wrist": ImplicitActuatorCfg( + joint_names_expr=["wrist_.*"], + stiffness=216.0, + damping=29.39, + friction=0.0, + armature=0.0, + ), + } + + **End-Effector:** + + - Link: ``wrist_3_link`` + - Default orientation: End-effector facing down (roll = pi, yaw = -pi/2) + + **Target Workspace:** + + .. code-block:: python + + # Position (meters, relative to robot base) + pos_center = (0.8875, -0.225, 0.2) + pos_range = (0.25, 0.125, 0.1) # ±25cm x, ±12.5cm y, ±10cm z + + # Orientation (radians) + rot_center = (pi, 0.0, -pi/2) + rot_range = (pi/6, pi/6, pi*2/3) # ±30 deg roll/pitch, ±120 deg yaw + + .. tab-item:: Flexiv Rizon 4s + + The Rizon 4s is a 7-DOF collaborative robot with different torque, speed, and stiffness characteristics per joint group: + + .. code-block:: python + + actuators = { + # Joints 1-2: Higher torque (123 Nm), lower speed + "shoulder": ImplicitActuatorCfg( + joint_names_expr=["joint[1-2]"], + effort_limit_sim=123.0, + velocity_limit_sim=2.094, # 120 deg/s + stiffness=6000.0, + damping=108.5, + friction=0.0, + armature=0.0, + ), + # Joints 3-4: Medium torque (64 Nm), medium speed + "elbow": ImplicitActuatorCfg( + joint_names_expr=["joint[3-4]"], + effort_limit_sim=64.0, + velocity_limit_sim=2.443, # 140 deg/s + stiffness=4200.0, + damping=90.7, + friction=0.0, + armature=0.0, + ), + # Joints 5-7: Lower torque (39 Nm), higher speed + "wrist": ImplicitActuatorCfg( + joint_names_expr=["joint[5-7]"], + effort_limit_sim=39.0, + velocity_limit_sim=4.887, # 280 deg/s + stiffness=1500.0, + damping=54.2, + friction=0.0, + armature=0.0, + ), + } + + **End-Effector:** + + - Link: ``flange`` + - Default orientation: End-effector facing down (roll = pi) + + **Target Workspace:** + + .. code-block:: python + + # Position (meters, relative to robot base) + pos_center = (0.4, 0.0, 0.4) + pos_range = (0.4, 0.4, 0.35) # ±40cm x, ±40cm y, ±35cm z + + # Orientation (radians) + rot_center = (pi, 0.0, 0.0) + rot_range = (pi/2, pi/2, pi) # ±90 deg roll/pitch, ±180 deg yaw + + +Customizing the Workspace +------------------------- + +You may need to modify the target workspace to match your deployment scenario. Key parameters you can adjust: + +**Target Position Range** + +Modify ``target_pos_centre`` and ``target_pos_range`` in the robot-specific config file (e.g., ``joint_pos_env_cfg.py``): + +.. code-block:: python + + # Center of the target workspace (meters, relative to robot base) + self.target_pos_centre = (0.5, 0.0, 0.4) + + # Half-extents of the workspace in each dimension + self.target_pos_range = (0.2, 0.2, 0.15) # ±20cm x, ±20cm y, ±15cm z + +**Effects:** + +- Larger ranges increase task difficulty but improve generalization +- Ensure all target positions are reachable by the robot (within kinematic limits) +- Targets outside reachable workspace will cause the policy to fail + +**Target Orientation Range** + +Modify ``target_rot_centre`` and ``target_rot_range``: + +.. code-block:: python + + # Center orientation (roll, pitch, yaw in radians) + self.target_rot_centre = (math.pi, 0.0, 0.0) + + # Range of rotation variation around the center + self.target_rot_range = (math.pi/6, math.pi/6, math.pi) # ±30 deg, ±30 deg, ±180 deg + +**Effects:** + +- Wider orientation ranges train more versatile policies but may slow convergence +- Very wide ranges (e.g., full rotation) significantly increase training difficulty + +**Action Scale** + +Modify the ``scale`` parameter in the action configuration: + +.. code-block:: python + + self.actions.arm_action = mdp.RelativeJointPositionActionCfg( + asset_name="robot", + joint_names=[".*"], + scale=0.0625, # Decrease for finer control, increase for faster motion + use_zero_offset=True, + ) + +**Effects:** + +- Smaller scale: Finer control, smoother motion, but slower reaching +- Larger scale: Faster motion, but potentially jerky or overshooting targets +- The same scale must be used during deployment on the real robot + +**Target Resampling Interval** + +Modify ``resampling_time_range`` in the commands configuration: + +.. code-block:: python + + self.commands.ee_pose.resampling_time_range = (4.0, 4.0) # Resample every 4 seconds + +**Effects:** + +- Shorter intervals: More diverse targets per episode, but less time to converge to each target +- Longer intervals: More time to refine tracking, but fewer targets seen during training + + +Domain Randomization +-------------------- + +Domain randomization helps the policy generalize across variations in real robot behavior. + +**Actuator Gain Randomization:** + +.. code-block:: python + + robot_joint_stiffness_and_damping = EventTerm( + func=mdp.randomize_actuator_gains, + min_step_count_between_reset=200, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot"), + "stiffness_distribution_params": (0.9, 1.1), # 90-110% of nominal + "damping_distribution_params": (0.75, 1.5), # 75-150% of nominal + "operation": "scale", + "distribution": "uniform", + }, + ) + +The ``min_step_count_between_reset=200`` ensures that actuator gains are not re-randomized too frequently, giving the policy time to adapt to each set of parameters before they change. + +**Joint Friction Randomization:** + +.. code-block:: python + + joint_friction = EventTerm( + func=mdp.randomize_joint_parameters, + min_step_count_between_reset=200, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot"), + "friction_distribution_params": (0.0, 0.1), # Add 0-0.1 Nm friction + "operation": "add", + "distribution": "uniform", + }, + ) + +**Initial Joint Position Randomization:** + +.. code-block:: python + + reset_robot_joints = EventTerm( + func=mdp.reset_joints_by_offset, + mode="reset", + params={ + "position_range": (-0.125, 0.125), # ±7 degrees + "velocity_range": (0.0, 0.0), + }, + ) + + +Reward Structure +---------------- + +The policy is trained using a keypoint-based reward that captures both position and orientation accuracy: + +.. code-block:: python + + @configclass + class RewardsCfg: + """Reward terms for the MDP.""" + + # Linear penalty for keypoint tracking error + end_effector_keypoint_tracking = RewTerm( + func=mdp.keypoint_command_error, + weight=-1.5, + params={ + "asset_cfg": SceneEntityCfg("ee_frame"), + "command_name": "ee_pose", + "keypoint_scale": 0.45, + }, + ) + + # Exponential reward for fine precision + end_effector_keypoint_tracking_exp = RewTerm( + func=mdp.keypoint_command_error_exp, + weight=1.5, + params={ + "asset_cfg": SceneEntityCfg("ee_frame"), + "command_name": "ee_pose", + "kp_exp_coeffs": [(50, 0.0001), (300, 0.0001), (5000, 0.0001)], + "kp_use_sum_of_exps": False, + "keypoint_scale": 0.45, + }, + ) + + # Penalties for smooth motion + action_rate = RewTerm(func=mdp.action_rate_l2, weight=-0.005) + action = RewTerm(func=mdp.action_l2, weight=-0.005) + +The keypoint-based reward places virtual markers on the end-effector frame and measures the distance to corresponding markers on the target frame. This provides a robust metric that naturally captures both position and orientation errors. + + +Training the Policy +------------------- + +Step 1: Verify the Environment +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Before starting full training, launch a quick visualization run to verify the environment is set up correctly: + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-Reach-UR10e-ROS-Inference-v0 \ + --num_envs 4 \ + --visualizer kit + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-Reach-Rizon4s-ROS-Inference-v0 \ + --num_envs 4 \ + --visualizer kit + +This opens the Isaac Sim viewer where you can observe the training in real-time. + +.. figure:: ../../_static/policy_deployment/04_reach/reach_train.png + :align: center + :figwidth: 100% + :alt: Reach policy training visualization in Isaac Lab + + Training visualization showing multiple parallel environments with robots reaching toward target poses. + +**What to look for:** + +- The robot should be moving its arm attempting to reach different poses +- Early on, motion will be erratic as the policy explores; this is expected +- For **Rizon 4s**: Target pose markers appear as coordinate frames in the scene +- For **UR10e**: Target visualization is disabled (``debug_vis = False``) because commands are generated in the ``base`` frame, which is 180 degrees offset from the ``base_link`` frame used for rendering. The robot will still track targets, but markers won't be visible. + +Once you confirm the environment looks correct, stop training with ``Ctrl+C`` and proceed to full-scale training. + + +Step 2: Full-Scale Training +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Launch full training with many parallel environments: + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-Reach-UR10e-ROS-Inference-v0 \ + --num_envs 4096 \ + --video --video_length 720 --video_interval 72000 + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Deploy-Reach-Rizon4s-ROS-Inference-v0 \ + --num_envs 4096 \ + --video --video_length 720 --video_interval 72000 + +**Command breakdown:** + +- ``--num_envs 4096``: Runs 4096 parallel environments for efficient data collection +- ``--video``: Records videos to monitor training progress +- ``--video_length 720``: Each video captures exactly one full episode (``episode_length_s / (sim.dt * decimation)`` = ``12.0 / (1/120 * 2)`` = 720 steps) +- ``--video_interval 72000``: Records a video every 72000 environment steps (~every 100 training iterations). + +**Training Configuration:** + +The training hyperparameters are the same for both robots: + +.. code-block:: python + + num_steps_per_env = 512 + max_iterations = 1500 + save_interval = 50 + obs_groups = {"actor": ["policy"], "critic": ["policy"]} + + actor = RslRlMLPModelCfg( + hidden_dims=[256, 128, 64], + activation="elu", + obs_normalization=True, + distribution_cfg=RslRlMLPModelCfg.GaussianDistributionCfg(init_std=1.0), + ) + critic = RslRlMLPModelCfg( + hidden_dims=[256, 128, 64], + activation="elu", + obs_normalization=True, + ) + + algorithm = RslRlPpoAlgorithmCfg( + value_loss_coef=1.0, + use_clipped_value_loss=True, + clip_param=0.2, + entropy_coef=0.0, + num_learning_epochs=8, + num_mini_batches=8, + learning_rate=5.0e-4, + schedule="adaptive", + gamma=0.99, + lam=0.95, + desired_kl=0.008, + max_grad_norm=1.0, + ) + +The ``experiment_name`` is ``"reach_ur10e"`` for UR10e and ``"reach_rizon4s"`` for Rizon 4s. Training typically takes 1-3 hours depending on your GPU. + + +Step 3: Monitor Training Progress +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Use TensorBoard to monitor training metrics: + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: bash + + ./isaaclab.sh -p -m tensorboard.main --logdir logs/rsl_rl/reach_ur10e + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: bash + + ./isaaclab.sh -p -m tensorboard.main --logdir logs/rsl_rl/reach_rizon4s + +Replace the log directory path with your actual training log location if different. + +**Key metrics to watch:** + +- **Mean reward**: Should increase steadily and plateau once the policy converges +- **Reward terms**: Monitor individual reward components to understand policy behavior: + + - ``end_effector_keypoint_tracking``: Linear keypoint tracking penalty -- should become less negative as the policy improves + - ``end_effector_keypoint_tracking_exp``: Exponential precision reward -- should increase as the policy achieves finer tracking + - ``action_rate`` and ``action``: Motion smoothness penalties -- these are small in magnitude but should increase (become less negative) over training, indicating the policy is converging toward smoother motion + +- **Position error**: Tracks the Euclidean distance (in meters) between the end-effector and target position -- should decrease over training +- **Orientation error**: Tracks the angular difference between the end-effector and target orientation -- should decrease over training + + +Step 4: Evaluate the Trained Policy +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Once training completes, evaluate the policy in the play environment: + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: bash + + ./isaaclab.sh play --rl_library rsl_rl \ + --task Isaac-Deploy-Reach-UR10e-Play-v0 \ + --num_envs 50 \ + --visualizer kit + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: bash + + ./isaaclab.sh play --rl_library rsl_rl \ + --task Isaac-Deploy-Reach-Rizon4s-Play-v0 \ + --num_envs 50 \ + --visualizer kit + +The play environments disable observation corruption for cleaner evaluation and use fewer environments for better visualization. + +**Checkpoint Loading:** + +By default, the play command automatically loads the most recent checkpoint from the most recent training run. +It searches in ``logs/rsl_rl//`` and selects the latest run folder and checkpoint file +(sorted alphabetically). + +To load a specific checkpoint, use these arguments: + +.. code-block:: bash + + # Load from a specific run folder + ./isaaclab.sh play --rl_library rsl_rl \ + --task Isaac-Deploy-Reach-UR10e-Play-v0 \ + --load_run 2025-01-15_14-30-00 + + # Load a specific checkpoint file + ./isaaclab.sh play --rl_library rsl_rl \ + --task Isaac-Deploy-Reach-UR10e-Play-v0 \ + --checkpoint /path/to/model_1500.pt + + +Step 5: Deploy on Real Robot +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Once satisfied with the trained policy, deploy it on real hardware using the Isaac ROS deployment pipeline. The pipeline uses: + +- The trained model checkpoint (``.pt`` file) +- The ``agent.yaml`` and ``env.yaml`` configuration files generated during training + +No additional export step is required. + +For detailed deployment instructions, see the `Isaac ROS Documentation `_. + + +Troubleshooting +--------------- + +CUDA Out of Memory +~~~~~~~~~~~~~~~~~~ + +**Error:** + +.. code-block:: text + + torch.OutOfMemoryError: CUDA out of memory. + +**Solutions:** + +1. **Reduce parallel environments:** + + .. code-block:: bash + + --num_envs 2048 # or 1024, 512, etc. + +2. **Disable video recording:** + + Remove the ``--video`` flags to free GPU memory. + +Policy Does Not Converge +~~~~~~~~~~~~~~~~~~~~~~~~ + +If rewards do not improve after many iterations: + +1. **Check target workspace ranges**: Ensure all target poses are reachable by the robot +2. **Verify joint names**: Confirm joint ordering matches between simulation and configuration +3. **Reduce domain randomization**: Temporarily disable randomization to verify the base task works + +Jerky Motion on Real Robot +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If the deployed policy produces jerky or unstable motion: + +1. **Reduce action scale**: Lower the ``scale`` parameter in ``RelativeJointPositionActionCfg`` +2. **Verify control frequency**: Ensure the real robot runs at the same frequency as simulation (60 Hz by default) +3. **Check joint ordering**: Verify joint names and ordering match between simulation and real robot + + +Further Resources +----------------- + +- `IndustReal: Transferring Contact-Rich Assembly Tasks from Simulation to Reality `_ +- `FORGE: Force-Guided Exploration for Robust Contact-Rich Manipulation under Uncertainty `_ +- `Isaac ROS Manipulation Documentation `_ +- Gear Assembly Sim-to-Real Tutorial: :ref:`walkthrough_sim_to_real` +- RL Training Tutorial: :ref:`tutorial-run-rl-training` diff --git a/simulation/modules/IsaacLab/docs/source/policy_deployment/05_leapp/exporting_policies_with_leapp.rst b/simulation/modules/IsaacLab/docs/source/policy_deployment/05_leapp/exporting_policies_with_leapp.rst new file mode 100644 index 0000000000000000000000000000000000000000..22825daad6eb110581c80bb2c6eba5b4f0ac8fc9 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/policy_deployment/05_leapp/exporting_policies_with_leapp.rst @@ -0,0 +1,323 @@ +Exporting Policies with LEAPP +============================= + +.. currentmodule:: isaaclab + +This guide covers how to export trained reinforcement learning policies from Isaac Lab using +`LEAPP `__ (Lightweight Export Annotations for Policy Pipelines). +The main goal of the LEAPP export path is to package the policy together with the input and +output semantics needed for deployment, so downstream users do not need to reimplement Isaac Lab +observation preprocessing, action postprocessing, or recurrent-state handling by hand. + +In practice, this makes the exported policy a much better fit for Isaac deployment libraries. +Isaac Lab can already consume these exports through :class:`~envs.LeappDeploymentEnv`, and Isaac +ROS will add direct support for running LEAPP-exported policies in a future release. + +.. note:: + + This export path currently supports **manager-based RL environments** (``ManagerBasedRLEnv``) + trained with **RSL-RL** only. Other environments are not yet supported. + + +Prerequisites +------------- + +This export flow requires ``leapp>=0.5.2``, Python >= 3.8, and PyTorch >= 2.6. Install +LEAPP with: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + ./isaaclab.sh -p -m pip install leapp + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + isaaclab.bat -p -m pip install leapp + +Ensure you have a trained RSL-RL checkpoint before proceeding. The standard Isaac Lab +training workflow produces checkpoints under ``logs/rsl_rl//``. + + +Why Export with LEAPP +--------------------- + +Running the export script generates a self-contained export directory alongside your +checkpoint (or at a custom path). The directory contains: + +- **Exported model files** — ``.onnx`` (default) or ``.pt`` depending on the chosen backend. +- **Export metadata** — LEAPP records the semantic information and wiring needed by downstream + deployment runtimes. +- **Initial values** — a ``.safetensors`` file for any feedback state, such as recurrent hidden + state or last action. +- **A graph visualization** — a ``.png`` diagram of the pipeline (can be disabled). + +The important outcome for Isaac deployment workflows is that the exported artifact preserves the +same dataflow that was used during training and inference inside Isaac Lab. That means downstream +consumers can run the policy without reconstructing observation ordering, command wiring, actuator +targets, or policy feedback loops themselves. + +For a detailed description of LEAPP's generated artifacts and APIs, refer to the +`LEAPP documentation `_. + + +Exporting a Policy +------------------ + +Use the RSL-RL export script to export a trained checkpoint: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/leapp/rsl_rl/export.py \ + --task \ + --checkpoint + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + isaaclab.bat -p scripts\reinforcement_learning\leapp\rsl_rl\export.py ^ + --task ^ + --checkpoint + +For example, to export a UR10 reach policy: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/leapp/rsl_rl/export.py \ + --task Isaac-Reach-UR10-v0 \ + --checkpoint logs/rsl_rl/ur10_reach/< date timestamp >/model_4999.pt + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + isaaclab.bat -p scripts\reinforcement_learning\leapp\rsl_rl\export.py ^ + --task Isaac-Reach-UR10-v0 ^ + --checkpoint logs\rsl_rl\ur10_reach\\model_4999.pt + +By default, the export artifacts are saved in the same directory as the checkpoint. The +exported graph is named after the task. + + +CLI Options +^^^^^^^^^^^ + +The export script accepts the following LEAPP-specific arguments in addition to the standard +RSL-RL and AppLauncher arguments: + +.. list-table:: + :widths: 30 15 55 + :header-rows: 1 + + * - Argument + - Default + - Description + * - ``--export_task_name`` + - Task name + - Name for the exported graph and output directory. + * - ``--export_method`` + - ``onnx-dynamo`` + - Export backend. Choices: ``onnx-dynamo``, ``onnx-torchscript``, ``jit-script``, + ``jit-trace``. + * - ``--export_save_path`` + - Checkpoint dir + - Base directory for export output. + * - ``--validation_steps`` + - ``5`` + - Number of environment steps to run during the traced rollout. Set to ``0`` to skip + validation. + * - ``--disable_graph_visualization`` + - ``False`` + - Skip generating the pipeline graph PNG. + +The script also accepts the standard ``--checkpoint``, ``--load_run``, ``--load_checkpoint``, +and ``--use_pretrained_checkpoint`` arguments for locating the trained model. + + +How It Works (High Level) +^^^^^^^^^^^^^^^^^^^^^^^^^ + +The export script performs the following steps: + +1. **Creates the environment** with ``num_envs=1`` and loads the trained checkpoint. +2. **Patches the environment** for export. This step injects annotations into the environment + so that tensor i/o to the pipeline are identified by LEAPP during execution. +3. **Runs a short rollout** (controlled by ``--validation_steps``) with LEAPP tracing + active. During this rollout, LEAPP traces all tensor operations in the pipeline and automatically + builds an onnx file. +4. **Compiles the graph** so the exported model and deployment metadata can be consumed by + downstream runtimes, and optionally validates that the exported model reproduces the traced + outputs. + +The patching is transparent to the policy — no changes to your training code or environment +configuration are needed. + +.. warning:: + + LEAPP is designed to support a broad range of model architectures, but the current + implementation has a few important limitations: + + - **Dynamic control flow** is not supported when the condition depends on runtime tensor + values, such as tensor-dependent ``if``, ``for``, or ``while`` logic. + - **Complex slicing** is not fully supported. Examples include dynamic masked indexing + using multiple traced tensors such as ``tensor[traced1, traced2]``. Slicing with constant values + or with a single traced tensor is supported such as ``tensor[mask]`` or ``tensor[1:5]``. + - **Critical traced operations must be written in PyTorch.** For this release, Warp and + NumPy operations cannot be traced by LEAPP. + + +Verifying an Export +------------------- + +After export, we recommend validating the result in three ways. + +1. **Use LEAPP's automatic verification on seen traced data.** +2. **Inspect the generated graph visualization.** +3. **Read the LEAPP log carefully, especially when the export fails or emits warnings.** + +Automatic Verification on Seen Data +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +By default, Isaac Lab asks LEAPP to validate the exported model after compilation. LEAPP does +this by replaying the data it already saw during the traced rollout and checking that the +exported artifact reproduces the same outputs. + +This is a strong first-line check because it is good at catching export-time issues such as: + +- backend conversion problems +- unsupported or incorrectly lowered operators +- output shape or dtype mismatches +- numerical discrepancies between the original policy and the exported artifact +- recurrent or feedback-state handling mistakes that show up during replay + +This validation is controlled by ``--validation_steps``. Setting it to a positive value gives +LEAPP rollout data to validate against. Setting it to ``0`` skips this automatic check, which +is useful for debugging but not recommended for normal export workflows. + +Inspect the Graph Visualization +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +LEAPP can generate a diagram of the exported pipeline as part of ``compile_graph()``. Even when +automatic verification passes, it is still worth opening the diagram and doing a quick visual +inspection. + +This is especially useful for catching structural issues such as: + +- missing inputs or outputs +- unexpected extra nodes +- incorrect feedback edges +- naming mistakes that make deployment harder to reason about + +You can disable the diagram with ``--disable_graph_visualization``, but we recommend keeping it +enabled while developing and validating a new export path. + +Inspect the LEAPP Log +^^^^^^^^^^^^^^^^^^^^^ + +If something breaks, the LEAPP-generated log is usually the best place to determine exactly what +happened. Read it closely and pay attention to both hard errors and warnings. + +The log is useful for diagnosing issues such as: + +- export backend failures +- warnings about graph construction or validation +- missing metadata +- unsupported model patterns +- file generation problems + +In practice, this should be your first stop when the export does not complete or when the output +artifacts do not look correct. + + +Export Backends +^^^^^^^^^^^^^^^ + +The ``--export_method`` argument controls how the policy network is serialized: + +- **onnx-dynamo** (default) — Uses ``torch.onnx.dynamo_export``. Best compatibility with + modern PyTorch features. +- **onnx-torchscript** — Uses the legacy ``torch.onnx.export`` path. May be needed for + certain model architectures. +- **jit-script** / **jit-trace** — Produces TorchScript ``.pt`` files instead of ONNX. + + +Recurrent Policies +^^^^^^^^^^^^^^^^^^ + +Recurrent policies (e.g., using GRU or LSTM memory) are supported automatically. The export +script detects recurrent hidden state in the RSL-RL policy, registers it as LEAPP feedback +state, and ensures it appears in the ``feedback_flow`` section of the output YAML. The +initial hidden state values are saved in the ``.safetensors`` file. + + +Running the Exported Policy in Simulation +----------------------------------------- + +Isaac Lab provides :class:`~envs.LeappDeploymentEnv` for running exported policies back in +simulation without the training infrastructure. This is the Isaac Lab deployment path for +LEAPP-exported policies and is useful for validating that the packaged policy still behaves +correctly when driven through the deployment stack instead of the training stack. + +Run the deployment script with the task name and the exported LEAPP ``.yaml`` file. + +By default, Isaac Lab launches headless when no visualization option is selected. If you expect +to see the policy running in a viewport, pass a visualization option such as ``--viz kit``: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/leapp/deploy.py \ + --task \ + --leapp_model \ + --viz kit + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + isaaclab.bat -p scripts\reinforcement_learning\leapp\deploy.py ^ + --task ^ + --leapp_model ^ + --viz kit + +For Direct workflow policies, see the +:doc:`Direct workflow LEAPP export tutorial `. +That guide shows how to add LEAPP annotations to a direct RL environment so it can be +exported with ``scripts/reinforcement_learning/leapp/rsl_rl/export.py``. Direct +workflow policies are not currently supported by ``scripts/reinforcement_learning/leapp/deploy.py``. + + +Further Reading +--------------- + +- `LEAPP documentation `__ +- `LEAPP API reference `__ +- :class:`~envs.LeappDeploymentEnv` API reference diff --git a/simulation/modules/IsaacLab/docs/source/policy_deployment/index.rst b/simulation/modules/IsaacLab/docs/source/policy_deployment/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..cd89350c1773b34e2b92b3d609536fbd73c0a0dd --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/policy_deployment/index.rst @@ -0,0 +1,15 @@ +Sim2Real Deployment of Policies Trained in Isaac Lab +==================================================== + +Welcome to the Policy Deployment Guide! This section provides examples of training policies in Isaac Lab and deploying them to both simulation and real robots. + +Below, you'll find detailed examples of various policies for training and deploying them, along with essential configuration details. + +.. toctree:: + :maxdepth: 1 + + 01_io_descriptors/io_descriptors_101 + 02_gear_assembly/gear_assembly_policy + 03_compass_with_NuRec/compass_navigation_policy_with_NuRec + 04_reach/reach_policy + 05_leapp/exporting_policies_with_leapp diff --git a/simulation/modules/IsaacLab/docs/source/refs/additional_resources.rst b/simulation/modules/IsaacLab/docs/source/refs/additional_resources.rst new file mode 100644 index 0000000000000000000000000000000000000000..16913b36d2eea2ced9413ccca2a38a6e327080e9 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/refs/additional_resources.rst @@ -0,0 +1,36 @@ +Additional Resources +==================== + +Here we provide external links to tools and various resources that you may also find useful. + + +Sim-to-Real Resources +--------------------- + +One of the core goals of the broader Isaac project is to bring real robots to life through the power of NVIDIA technology. There are many ways to do this, and thus, many tools that you could use. These resources are dedicated to helping you navigate these possibilities by providing examples and discussions about closing the Sim-to-Real gap and deploying policies to actual real robots. + +* `Closing the Sim-to-Real Gap: Training Spot Quadruped Locomotion with NVIDIA Isaac Lab `_ is a detailed guide for training a quadruped locomotion policy for the Spot Quadruped from Boston Dynamics, and deploying it to the real robot. + + +LLM Generated Reward Functions +------------------------------ + +Our research endeavor, ``Eureka!``, has resulted in a pipeline for generating and tuning Reinforcement Learning (RL) reward functions using an LLM. These resources are dedicated to helping you utilize this pipeline to create RL based solutions to tasks that were once thought impossible! + +* `Isaac Lab Eureka `_ is a github repository where you can setup your own LLM reward generation pipeline for your direct RL environments built in Isaac Lab! + +* `Eureka! NVIDIA Research Breakthrough Puts New Spin on Robot Learning `_ is a blog post that covers the broad idea of this reward generation process. + + +Simulation Features +------------------- + +At the heart of Isaac Lab is Isaac Sim, which is itself a feature rich tool that is useful for robotics in general, and not only for RL. The stronger your understanding of the simulation, the readily you will be able to exploit its capabilities for your own projects and applications. These resources are dedicated to informing you about the other features of the simulation that may be useful to you given your specific interest in Isaac Lab! + +* `Simulation Performance Guide `_ is a best practice guide for obtaining the best simulation performance from OmniPhysics. + +* `Deploying Policies in Isaac Sim `_ is an Isaac Sim tutorial on how to use trained policies within the simulation. + +* `Supercharge Robotics Workflows with AI and Simulation Using NVIDIA Isaac Sim 4.0 and NVIDIA Isaac Lab `_ is a blog post covering the newest features of Isaac Sim 4.0, including ``pip install``, a more advanced physics engine, updated sensor simulations, and more! + +* `Fast-Track Robot Learning in Simulation Using NVIDIA Isaac Lab `_ is a blog post covering the gamut of features for accelerated robot learning through Isaac Lab. diff --git a/simulation/modules/IsaacLab/docs/source/refs/bibliography.rst b/simulation/modules/IsaacLab/docs/source/refs/bibliography.rst new file mode 100644 index 0000000000000000000000000000000000000000..0d21440d01c35639698c298f9415e74db4134ecc --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/refs/bibliography.rst @@ -0,0 +1,4 @@ +Bibliography +============ + +.. bibliography:: diff --git a/simulation/modules/IsaacLab/docs/source/refs/changelog.rst b/simulation/modules/IsaacLab/docs/source/refs/changelog.rst new file mode 100644 index 0000000000000000000000000000000000000000..1fb156e6d444a93d0d3b3b8271c1af7c414b5b32 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/refs/changelog.rst @@ -0,0 +1,38 @@ +Extensions Changelog +==================== + +All notable changes to this project are documented in this file. The format is based on +`Keep a Changelog `__ and this project adheres to +`Semantic Versioning `__. For a broader information +about the changes in the framework, please refer to the +`release notes `__. + +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. + +isaaclab +-------------- + +Extension containing the core framework of Isaac Lab. + +.. include:: ../../../source/isaaclab/docs/CHANGELOG.rst + :start-line: 3 + + +isaaclab_assets +--------------------- + +Extension for configurations of various assets and sensors for Isaac Lab. + +.. include:: ../../../source/isaaclab_assets/docs/CHANGELOG.rst + :start-line: 3 + + +isaaclab_tasks +-------------------- + +Extension containing the environments built using Isaac Lab. + +.. include:: ../../../source/isaaclab_tasks/docs/CHANGELOG.rst + :start-line: 3 diff --git a/simulation/modules/IsaacLab/docs/source/refs/contributing.rst b/simulation/modules/IsaacLab/docs/source/refs/contributing.rst new file mode 100644 index 0000000000000000000000000000000000000000..a49f742140502383534fd16b6214568acc4301d3 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/refs/contributing.rst @@ -0,0 +1,751 @@ +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 `__. +* Feature requests: Please suggest new features you would like to see in the `discussions `__. +* Code contributions: Please submit a `pull request `__. + + * Bug fixes + * New features + * Documentation improvements + * Tutorials and tutorial improvements + +We prefer GitHub `discussions `_ for discussing ideas, +asking questions, conversations and requests for new features. + +Please use the +`issue tracker `_ 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 +----------------- + +.. attention:: + + Please refer to the `Google Style Guide `__ + for the coding style before contributing to the codebase. In the coding style section, + we outline the specific deviations from the style guide that we follow in the codebase. + +We use `GitHub `__ for code hosting. Please +follow the following steps to contribute code: + +1. Create an issue in the `issue tracker `__ 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 `__. +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. + + +More details on the code style and testing can be found in the `Coding Style`_ and `Unit Testing`_ sections. + + +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 ``IsaacLab/docs`` directory. The documentation is written in +`reStructuredText `__ format. + +We use `Sphinx `__ with the +`Book Theme `__ +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 `__ + to install the dependencies. This can also be a `conda environment `__. + + +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 + + ./isaaclab.sh --docs # or "./isaaclab.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/current/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 && ./isaaclab.sh --docs + + +Contributing assets +------------------- + +Currently, we host the assets for the extensions on `NVIDIA Nucleus Server `__. +Nucleus is a cloud-based storage service that allows users to store and share large files. It is +integrated with the `NVIDIA Omniverse Platform `__. + +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. + +Please checkout the `Isaac Sim Assets `__ +for more information on what is presently available. + +.. 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 and extension.toml +------------------------------------------ + +Each extension maintains a changelog in the ``CHANGELOG.rst`` file in the ``docs`` directory, +as well as a ``extension.toml`` file in the ``config`` directory. + +The ``extension.toml`` file contains the metadata for the extension. It is used to describe the +name, version, description, and other metadata of the extension. + +The ``CHANGELOG.rst`` is a file that contains the curated, chronologically ordered list of notable changes +for each version of the extension. + +.. note:: + + ``CHANGELOG.rst`` and ``extension.toml`` are compiled by CI from per-PR **fragment + files** — contributors do not edit them directly. For every package your PR touches + in ``source//`` (outside ``changelog.d/``), add one fragment under + ``source//changelog.d/..rst``: + + * ``.rst`` — patch bump + * ``.minor.rst`` — minor bump (new public API) + * ``.major.rst`` — major bump (breaking change) + * ``.skip`` — no entry, no bump (CI / docs / test-only PRs) + + ```` is any short, unique name; your branch name with ``/`` replaced by ``-`` + is the recommended default. Within a batch the highest tier wins for the package. + The version on ``extension.toml`` is bumped by CI according to + `Semantic Versioning `__. + +The changelog file is written in `reStructuredText `__ format. +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 each fragment, please follow the following guidelines: + +* Each fragment 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**. + + * This means that the change is described as if it has already happened. + * The bullet points should be concise and to the point. They should not be verbose. + * The bullet point should also include the reason for the change, if applicable. + + +.. tip:: + + When in doubt, please check the style in the existing changelog files and follow the same style. + +For example, ``source/isaaclab/changelog.d/.minor.rst``: + +.. code:: rst + + Added + ^^^^^ + + * Added a new feature that helps in a 10x speedup. + + Changed + ^^^^^^^ + + * Changed an existing feature. Earlier, we were using :meth:`torch.bmm` to perform the matrix multiplication. + However, this was slow for large matrices. We have now switched to using :meth:`torch.einsum` which is + significantly faster. + + Deprecated + ^^^^^^^^^^ + + * Deprecated an existing feature in favor of a new feature. + + Removed + ^^^^^^^ + + * Removed an existing feature. This was done to simplify the codebase and reduce the complexity. + + Fixed + ^^^^^ + + * Fixed crashing of the :meth:`my_function` when the input was too large. + We now use :meth:`torch.einsum` that is able to handle larger inputs. + + +Coding Style +------------ + +We follow the `Google Style +Guides `__ for the +codebase. For Python code, the PEP guidelines are followed. Most +important ones are `PEP-8 `__ +for code comments and layout, +`PEP-484 `__ and +`PEP-585 `__ for +type-hinting. + +For documentation, we adopt the `Google Style Guide `__ +for docstrings. We use `Sphinx `__ for generating the documentation. +Please make sure that your code is well-documented and follows the guidelines. + +Code Structure +^^^^^^^^^^^^^^ + +We follow a specific structure for the codebase. This helps in maintaining the codebase and makes it easier to +understand. + +In a Python file, we follow the following structure: + +.. code:: python + + # Imports: These are sorted by the pre-commit hooks. + # Constants + # Functions (public) + # Classes (public) + # _Functions (private) + # _Classes (private) + +Imports are sorted by the pre-commit hooks. Unless there is a good reason to do otherwise, please do not +import the modules inside functions or classes. To deal with circular imports, we use the +:obj:`typing.TYPE_CHECKING` variable. Please refer to the `Circular Imports`_ section for more details. + +Note that ``__init__.py`` files are an exception to the above: they use +:func:`~isaaclab.utils.module.lazy_export` instead of traditional imports. +See the `Lazy Loading & Module Exports`_ section for details. + +Python does not have a concept of private and public classes and functions. However, we follow the +convention of prefixing the private functions and classes with an underscore. +The public functions and classes are the ones that are intended to be used by the users. The private +functions and classes are the ones that are intended to be used internally in that file. +Irrespective of the public or private nature of the functions and classes, we follow the Style Guide +for the code and make sure that the code and documentation are consistent. + +Similarly, within Python classes, we follow the following structure: + +.. code:: python + + # Constants + # Class variables (public or private): Must have the type hint ClassVar[type] + # Dunder methods: __init__, __del__ + # Representation: __repr__, __str__ + # Properties: @property + # Instance methods (public) + # Class methods (public) + # Static methods (public) + # _Instance methods (private) + # _Class methods (private) + # _Static methods (private) + +The rule of thumb is that the functions within the classes are ordered in the way a user would +expect to use them. For instance, if the class contains the method :meth:`initialize`, :meth:`reset`, +:meth:`update`, and :meth:`close`, then they should be listed in the order of their usage. +The same applies for private functions in the class. Their order is based on the order of call inside the +class. + +.. dropdown:: Code skeleton + :icon: code + + .. literalinclude:: snippets/code_skeleton.py + :language: python + +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 `__. + +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 this, we use two complementary techniques: + +1. **Resolvable strings** — Store ``class_type`` and ``func`` as ``{DIR}``-based strings + (e.g. ``"{DIR}.sensor:Sensor"``) so the implementation module is never imported at config + construction time. The string is resolved to the actual class (via :class:`~isaaclab.utils.string.ResolvableString`) + after ``SimulationApp`` launches. +2. **TYPE_CHECKING guards** — Import the implementation class under `typing.TYPE_CHECKING + `_ so that IDEs and type + checkers can provide autocomplete on the type annotation without triggering a runtime import. + +See the `Resolvable Strings`_ and `Lazy Loading & Module Exports`_ sections for full +examples of both patterns. + +Lazy Loading & Module Exports +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Every ``__init__.py`` in Isaac Lab uses **lazy loading** so that importing a top-level package +(e.g. ``import isaaclab.sensors``) does not eagerly pull in heavyweight dependencies like +``pxr``, ``omni``, or ``scipy``. This is critical because config classes must be constructable +*before* ``SimulationApp`` is launched. + +We follow `SPEC 1 — Lazy Loading of Submodules and Functions +`__ and use the `lazy_loader +`__ library (endorsed by NumPy, SciPy, scikit-image, +scikit-learn, NetworkX) with ``.pyi`` type-stub files. The stub is the **single source of +truth** for both IDE autocomplete and runtime lazy loading. + +**Standard pattern** — the vast majority of ``__init__.py`` files: + +.. code:: python + + # mypackage/__init__.py + from isaaclab.utils.module import lazy_export + + lazy_export() + +With a corresponding type stub adjacent to it: + +.. code:: python + + # mypackage/__init__.pyi + __all__ = ["MyClass", "MyOtherClass", "my_function"] + + from .my_module import MyClass, MyOtherClass + from .my_other_module import my_function + +Key rules for ``.pyi`` stubs: + +* The ``__all__`` list at the top marks names as public re-exports (per `PEP 484 + `__). +* Group imports from the same submodule on one line. Use parenthesized multi-line + imports if the line exceeds 100 characters. +* Use **relative imports** (``from .something import ...``) for local submodule + symbols. Absolute wildcard imports (``from pkg import *``) are only used for + cross-package fallbacks (see below). +* Include the standard Isaac Lab license header. + +**Cross-package fallback** — for modules that re-export names from another package +(e.g. task MDP modules that delegate to ``isaaclab.envs.mdp``), add a wildcard +import for the external package in the ``.pyi`` stub: + +.. code:: python + + # isaaclab_tasks/.../mdp/__init__.pyi + __all__ = ["MyReward", "MyObservation"] + + from .rewards import MyReward + from .observations import MyObservation + + from isaaclab.envs.mdp import * + +The ``__init__.py`` stays the same as the standard pattern — just ``lazy_export()`` +with no arguments: + +.. code:: python + + # isaaclab_tasks/.../mdp/__init__.py + from isaaclab.utils.module import lazy_export + + lazy_export() + +At runtime, ``lazy_export`` parses the ``.pyi`` stub and uses the absolute wildcard +import (``from isaaclab.envs.mdp import *``) as a fallback: any name not found in +the local submodules is looked up in the specified package. This also gives type +checkers and IDEs full visibility into the re-exported symbols. + +**Relative wildcard re-exports** — the stub can also use ``from .submodule import *`` +to eagerly export all public names from a local submodule. This is resolved at +import time (not lazily) and is useful when a submodule's public API is large or +changes frequently. + +.. note:: + + Relative wildcard re-exports bypass lazy loading and eagerly import every public + name from the submodule at package init time. In general, we advise against using + them unless absolutely necessary. Prefer listing explicit named imports in the stub + so that the public API surface is clear, reviewable, and remains lazily loaded. + +.. code:: python + + # isaaclab_tasks/.../mdp/__init__.pyi + from .rewards import * + from .observations import * + + from isaaclab.envs.mdp import * + +**Ensuring .pyi stubs are distributed** + +The ``setup.py`` for each package includes ``package_data={"": ["*.pyi"]}`` so that stub +files are included in sdist and wheel distributions. The pre-commit ``insert-license`` hook +is configured to add license headers to ``.pyi`` files automatically (``\.(pyi?|ya?ml)$``). + +Resolvable Strings +^^^^^^^^^^^^^^^^^^ + +When a config field needs to reference a class or callable that depends on the simulator +runtime, store it as a :class:`~isaaclab.utils.string.ResolvableString` rather than a +direct reference. This avoids eagerly importing heavyweight modules (``omni``, ``pxr``, +etc.) at config construction time — the string is resolved to the actual callable only +after ``SimulationApp`` has been initialized. + +You can use either the ``{DIR}`` shorthand or a fully-qualified module path: + +.. code:: python + + # Good — {DIR} shorthand (resolved to the current package at runtime) + class_type: type[Sensor] | str = "{DIR}.sensor:Sensor" + + # Good — fully-qualified path (useful for cross-package references) + class_type: type[Sensor] | str = "isaaclab.sensors.my_sensor.sensor:Sensor" + + # Bad — eagerly imports the implementation module + from .sensor import Sensor + class_type: type = Sensor + +The ``{DIR}`` placeholder is resolved at runtime to the fully-qualified package name of the +directory containing the config file (e.g. ``isaaclab.sensors.my_sensor``). Prefer ``{DIR}`` +for references within the same package since it stays correct across renames and moves. + +For the type annotation (``type[Sensor]``), import the class under a ``TYPE_CHECKING`` guard +so that the IDE can still provide autocomplete without triggering a runtime import: + +.. code:: python + + from __future__ import annotations + import typing + + if typing.TYPE_CHECKING: + from .sensor import Sensor + +Config + Implementation File Split +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Classes and their configuration objects live in separate files. This keeps config classes +free of heavy runtime imports: + +.. code:: text + + my_sensor/ + ├── __init__.py # lazy_export() + ├── __init__.pyi # re-exports: SensorCfg, Sensor + ├── sensor_cfg.py # pure data — no runtime deps + └── sensor.py # implementation — may import omni, pxr, etc. + +``__init__.py`` — uses ``lazy_export()`` to lazily load names from the stub: + +.. code:: python + + # my_sensor/__init__.py + from isaaclab.utils.module import lazy_export + + lazy_export() + +``__init__.pyi`` — declares the public API for both IDE autocomplete and lazy loading: + +.. code:: python + + # my_sensor/__init__.pyi + __all__ = ["SensorCfg", "Sensor"] + + from .sensor_cfg import SensorCfg + from .sensor import Sensor + +``sensor_cfg.py`` — pure data; references the implementation class by resolvable string +to avoid importing it: + +.. code:: python + + # my_sensor/sensor_cfg.py + from __future__ import annotations + import typing + + from isaaclab.utils.configclass import configclass + + if typing.TYPE_CHECKING: + from .sensor import Sensor + + @configclass + class SensorCfg: + class_type: type[Sensor] | str = "{DIR}.sensor:Sensor" + +``sensor.py`` — the implementation; may freely import heavyweight dependencies: + +.. code:: python + + # my_sensor/sensor.py + import omni.isaac.core # heavy — only loaded when this module is accessed + + from .sensor_cfg import SensorCfg + + class Sensor: + def __init__(self, cfg: SensorCfg): + ... + +Type-hinting +^^^^^^^^^^^^ + +To make the code more readable, we use `type hints `__ 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 `__. + +**Type-hinting only in the function signature** + +To avoid duplication of efforts, we do not specify type hints for the arguments and return values in the docstrings. + +For instance, the following are bad examples for various reasons: + +.. code:: python + + def my_function(a, b): + """Adds two numbers. + + This function is a bad example. Reason: No type hints anywhere. + + Args: + a: The first argument. + b: The second argument. + + Returns: + The sum of the two arguments. + """ + return a + b + +.. code:: python + + def my_function(a, b): + """Adds two numbers. + + This function is a bad example. Reason: Type hints in the docstring and not in the + function signature. + + Args: + a (int): The first argument. + b (int): The second argument. + + Returns: + int: The sum of the two arguments. + """ + return a + b + +.. code:: python + + def my_function(a: int, b: int) -> int: + """Adds two numbers. + + This function is a bad example. Reason: Type hints in the docstring and in the function + signature. Redundancy. + + Args: + a (int): The first argument. + b (int): The second argument. + + Returns: + int: The sum of the two arguments. + """ + return a + b + +The following is how we expect you to write the docstrings and type hints: + +.. code:: python + + def my_function(a: int, b: int) -> int: + """Adds two numbers. + + This function is a good example. Reason: Type hints in the function signature and not in the + docstring. + + Args: + a: The first argument. + b: The second argument. + + Returns: + The sum of the two arguments. + """ + return a + b + +**No type-hinting for None** + +We do not specify the return type of :obj:`None` in the docstrings. This is because +it is not necessary and can be inferred from the function signature. + +For instance, the following is a bad example: + +.. code:: python + + def my_function(x: int | None) -> None: + pass + +Instead, we recommend the following: + +.. code:: python + + def my_function(x: int | None): + pass + +Documenting the code +^^^^^^^^^^^^^^^^^^^^ + +The code documentation is as important as the code itself. It helps in understanding the code and makes +it easier to maintain. However, more often than not, the documentation is an afterthought or gets rushed +to keep up with the development pace. + +**What is considered as a bad documentation?** + +* If someone else wants to use the code, they cannot understand the code just by reading the documentation. + + What this means is that the documentation is not complete or is not written in a way that is easy to understand. + The next time someone wants to use the code, they will have to spend time understanding the code (in the best + case scenario), or scrap the code and start from scratch (in the worst case scenario). + +* Certain design subtleties are not documented and are only apparent from the code. + + Often certain design decisions are made to address specific use cases. These use cases are not + obvious to someone who wants to use the code. They may change the code in a way that is not intuitive + and unintentionally break the code. + +* The documentation is not updated when the code is updated. + + This means that the documentation is not kept up to date with the code. It is important to update the + documentation when the code is updated. This helps in keeping the documentation up to date and in sync + with the code. + +**What is considered good documentation?** + +We recommend thinking of the code documentation as a living document that helps the reader understand +the *what, why and how* of the code. Often we see documentation that only explains the +what but not the how or why. This is not helpful in the long run. + +We suggest always thinking of the documentation from a new user's perspective. They should be able to directly +check the documentation and have a good understanding of the code. + +For information on how to write good documentation, please check the notes on +`Dart's effective documentation `__ +and `technical writing `__. +We summarize the key points below: + +* Inform (educate the reader) and persuade (convince the reader). + * Have a clear aim in mind, and make sure everything you write is towards that aim alone. + * Use examples and analogies before introducing abstract concepts. +* Use the right tone for the audience. +* Compose simple sentences in active voice. +* Avoid unnecessary jargon and repetition. Use plain English. +* Avoid ambiguous phrases such as 'kind of', 'sort of', 'a bit', etc. +* State important information at the beginning of the sentence. +* Say exactly what you mean. Don't avoid writing the uncomfortable truth. + + +Unit Testing +------------ + +We use `pytest `__ for unit testing. +Good tests not only cover the basic functionality of the code but also the edge cases. +They should be able to catch regressions and ensure that the code is working as expected. +Please make sure that you add tests for your changes. + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + # Run all tests + ./isaaclab.sh --test # or "./isaaclab.sh -t" + + # Run all tests in a particular file + ./isaaclab.sh -p -m pytest source/isaaclab/test/deps/test_torch.py + + # Run a particular test + ./isaaclab.sh -p -m pytest source/isaaclab/test/deps/test_torch.py::test_array_slicing + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: bash + + # Run all tests + isaaclab.bat --test # or "isaaclab.bat -t" + + # Run all tests in a particular file + isaaclab.bat -p -m pytest source/isaaclab/test/deps/test_torch.py + + # Run a particular test + isaaclab.bat -p -m pytest source/isaaclab/test/deps/test_torch.py::test_array_slicing + + +Tools +----- + +We use the following tools for maintaining code quality: + +* `pre-commit `__: Runs a list of formatters and linters over the codebase. +* `ruff `__: An extremely fast Python linter and formatter. + +Please check `here `__ for instructions +to set these up. To run over the entire repository, please execute the +following command in the terminal: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + ./isaaclab.sh --format # or "./isaaclab.sh -f" + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: bash + + isaaclab.bat --format # or "isaaclab.bat -f" diff --git a/simulation/modules/IsaacLab/docs/source/refs/issues.rst b/simulation/modules/IsaacLab/docs/source/refs/issues.rst new file mode 100644 index 0000000000000000000000000000000000000000..46d8e41b5ffc0e98a68a41656cd5483c96e1d3c0 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/refs/issues.rst @@ -0,0 +1,140 @@ +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. + +.. note:: + With Isaac Lab 1.2, we have introduced a PhysX kinematic update call inside the + :attr:`~isaaclab.assets.ArticulationData.body_state_w` attribute. This workaround + ensures that the states of the links are updated when the root state or joint state + of an articulation is set. + + +Blank initial frames from the camera +------------------------------------ + +When using the :class:`~isaaclab.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 isaaclab.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.isaacsim.omniverse.nvidia.com/latest/isaac_lab_tutorials/tutorial_instanceable_assets.html +.. _Omniverse Isaac Sim documentation: https://docs.isaacsim.omniverse.nvidia.com/latest/overview/known_issues.html# + + +Exiting the process +------------------- + +When exiting a process with ``Ctrl+C``, occasionally the below error may appear: + +.. code-block:: bash + + [Error] [omni.physx.plugin] Subscription cannot be changed during the event call. + +This is due to the termination occurring in the middle of a physics event call and +should not affect the functionality of Isaac Lab. It is safe to ignore the error +message and continue with terminating the process. On Windows systems, please use +``Ctrl+Break`` or ``Ctrl+fn+B`` to terminate the process. + + +.. _known-issues-closed-loop-newton: + +Closed-loop articulations on Newton (e.g. Agility Digit) +-------------------------------------------------------- + +Robots whose USD encodes a closed kinematic loop -- such as the achilles rod and +toe push-rods on the Agility Digit -- do not currently run correctly on the +``newton_mjwarp`` physics preset, even though they work on ``physx``. This affects: + +* ``Isaac-Velocity-Flat-Digit-v0`` / ``Isaac-Velocity-Flat-Digit-Play-v0`` +* ``Isaac-Velocity-Rough-Digit-v0`` / ``Isaac-Velocity-Rough-Digit-Play-v0`` +* ``Isaac-Tracking-LocoManip-Digit-v0`` / ``Isaac-Tracking-LocoManip-Digit-Play-v0`` + +The root cause sits inside Newton's :class:`~newton.selection.ArticulationView`. When +it builds its per-link axis it walks each joint in the articulation's joint range and +appends ``model.joint_child[joint_id]`` without deduplicating. A body that is the +child of multiple joints (the standard closed-loop encoding) therefore occupies +multiple slots on that axis, so ``view.link_count`` is larger than the number of +unique physical bodies in the model. On Digit this is 49 link slots versus 43 actual +bodies (the four loop-closed bodies -- left/right ``tarsus`` and left/right +``toe_roll`` -- account for the six extra slots). + +Until the upstream fix lands in Newton, please use the ``physx`` preset for +Digit-based environments. + + +URDF Importer: Unresolved references for fixed joints +----------------------------------------------------- + +Starting with Isaac Sim 5.1, links connected through ``fixed_joint`` elements are no longer merged when +their URDF link entries specify mass and inertia even if ``merge-joint`` set to True. +This is expected behaviour—those links are treated as full bodies rather than zero-mass reference frames. +However, the USD importer currently raises ``ReportError`` warnings showing unresolved references for such links +when they lack visuals or colliders. This is a known bug in the importer; it creates references to visuals +that do not exist. The warnings can be safely ignored until the importer is updated. + + +GLIBCXX errors in Conda +----------------------- + +In Isaac Sim 5.0, we have observed some workflows exiting with an ``OSError`` indicating +``version 'GLIBCXX_3.4.30' not found`` when running from a conda environment. +The issue apperas to be stemming from importing torch or torch-related packages, such as tensorboard, +prior to launching ``AppLauncher``. As a workaround, ensure that all torch imports happen after +the ``AppLauncher`` instance has been created, which should resolve the error. diff --git a/simulation/modules/IsaacLab/docs/source/refs/license.rst b/simulation/modules/IsaacLab/docs/source/refs/license.rst new file mode 100644 index 0000000000000000000000000000000000000000..4e1a296587332f7cd9c571a7981ddd8214c21937 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/refs/license.rst @@ -0,0 +1,46 @@ +.. _license: + +License +======== + +NVIDIA Isaac Sim is licensed under Apache 2.0. For more information +about its license terms, please check `here `_. +The license files for all its dependencies and included assets are available in its +`documentation `_. + + +The Isaac Lab framework is open-sourced under the +`BSD-3-Clause license `_, with some dependencies licensed under other terms. + + +.. code-block:: text + + Copyright (c) 2022-2025, The Isaac Lab 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. diff --git a/simulation/modules/IsaacLab/docs/source/refs/migration.rst b/simulation/modules/IsaacLab/docs/source/refs/migration.rst new file mode 100644 index 0000000000000000000000000000000000000000..11db227bc142139dbdb65e2dfd2eb2389c59d7df --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/refs/migration.rst @@ -0,0 +1,203 @@ +.. _migration_guide: + +Migration Guide (Isaac Sim) +=========================== + +Moving from Isaac Sim 4.2 to 4.5 and later brings in a number of changes to the +APIs and Isaac Sim extensions and classes. This document outlines the changes +and how to migrate your code to the new APIs. + + +Renaming of Isaac Sim Extensions +-------------------------------- + +Previously, Isaac Sim extensions have been following the convention of ``omni.isaac.*``, +such as ``omni.isaac.core``. In Isaac Sim 4.5, Isaac Sim extensions have been renamed +to use the prefix ``isaacsim``, replacing ``omni.isaac``. In addition, many extensions +have been renamed and split into multiple extensions to prepare for a more modular +framework that can be customized by users through the use of app templates. + +Notably, the following commonly used Isaac Sim extensions in Isaac Lab are renamed as follow: + +* ``omni.isaac.cloner`` --> ``isaacsim.core.cloner`` +* ``omni.isaac.core.prims`` --> ``isaacsim.core.prims`` +* ``omni.isaac.core.simulation_context`` --> ``isaacsim.core.api.simulation_context`` +* ``omni.isaac.core.utils`` --> ``isaacsim.core.utils`` +* ``omni.isaac.core.world`` --> ``isaacsim.core.api.world`` +* ``omni.isaac.kit.SimulationApp`` --> ``isaacsim.SimulationApp`` +* ``omni.isaac.ui`` --> ``isaacsim.gui.components`` + + +Renaming of the URDF and MJCF Importers +--------------------------------------- + +Starting from Isaac Sim 4.5, the URDF and MJCF importers have been renamed to be more consistent +with the other extensions in Isaac Sim. The importers are available on isaac-sim GitHub +as open source projects. + +Due to the extension name change, the Python module names have also been changed: + +* URDF Importer: :mod:`isaacsim.asset.importer.urdf` (previously :mod:`omni.importer.urdf`) +* MJCF Importer: :mod:`isaacsim.asset.importer.mjcf` (previously :mod:`omni.importer.mjcf`) + +From the Isaac Sim UI, both URDF and MJCF importers can now be accessed directly from the File > Import +menu when selecting a corresponding .urdf or .xml file in the file browser. + + +Changes in URDF Importer +------------------------ + +Isaac Sim 4.5 brings some updates to the URDF Importer, with a fresh UI to allow for better configurations +when importing robots from URDF. As a result, the Isaac Lab URDF Converter has also been updated to +reflect these changes. The :class:`UrdfConverterCfg` includes some new settings, such as :class:`PDGainsCfg` +and :class:`NaturalFrequencyGainsCfg` classes for configuring the gains of the drives. + +One breaking change to note is that the :attr:`UrdfConverterCfg.JointDriveCfg.gains` attribute must +be of class type :class:`PDGainsCfg` or :class:`NaturalFrequencyGainsCfg`. + +The stiffness of the :class:`PDGainsCfg` must be specified, as such: + +.. code::python + + joint_drive=sim_utils.UrdfConverterCfg.JointDriveCfg( + gains=sim_utils.UrdfConverterCfg.JointDriveCfg.PDGainsCfg(stiffness=None, damping=None) + ) + +The :attr:`natural_frequency` must be specified for :class:`NaturalFrequencyGainsCfg`. + + +Renaming of omni.isaac.core Classes +----------------------------------- + +Isaac Sim 4.5 introduced some naming changes to the core prim classes that are commonly +used in Isaac Lab. These affect the single and ``View`` variations of the prim classes, including +Articulation, RigidPrim, XFormPrim, and others. Single-object classes are now prefixed with +``Single``, such as ``SingleArticulation``, while tensorized View classes now have the ``View`` +suffix removed. + +The exact renaming of the classes are as follow: + +* ``Articulation`` --> ``SingleArticulation`` +* ``ArticulationView`` --> ``Articulation`` +* ``ClothPrim`` --> ``SingleClothPrim`` +* ``ClothPrimView`` --> ``ClothPrim`` +* ``DeformablePrim`` --> ``SingleDeformablePrim`` +* ``DeformablePrimView`` --> ``DeformablePrim`` +* ``GeometryPrim`` --> ``SingleGeometryPrim`` +* ``GeometryPrimView`` --> ``GeometryPrim`` +* ``ParticleSystem`` --> ``SingleParticleSystem`` +* ``ParticleSystemView`` --> ``ParticleSystem`` +* ``RigidPrim`` --> ``SingleRigidPrim`` +* ``RigidPrimView`` --> ``RigidPrim`` +* ``XFormPrim`` --> ``SingleXFormPrim`` +* ``XFormPrimView`` --> ``XFormPrim`` + + +Renaming of Isaac Lab Extensions and Folders +-------------------------------------------- + +Corresponding to Isaac Sim 4.5 changes, we have also made some updates to the Isaac Lab directories and extensions. +All extensions that were previously under ``source/extensions`` are now under the ``source/`` directory directly. +The ``source/apps`` and ``source/standalone`` folders have been moved to the root directory and are now called +``apps/`` and ``scripts/``. + +Isaac Lab extensions have been renamed to: + +* ``omni.isaac.lab`` --> ``isaaclab`` +* ``omni.isaac.lab_assets`` --> ``isaaclab_assets`` +* ``omni.isaac.lab_tasks`` --> ``isaaclab_tasks`` + +In addition, we have split up the previous ``source/standalone/workflows`` directory into ``scripts/imitation_learning`` +and ``scripts/reinforcement_learning`` directories. The RSL RL, Stable-Baselines, RL_Games, SKRL, and Ray directories +are under ``scripts/reinforcement_learning``, while Robomimic and the new Isaac Lab Mimic directories are under +``scripts/imitation_learning``. + +To assist with the renaming of Isaac Lab extensions in your project, we have provided a `simple script`_ that will traverse +through the ``source`` and ``docs`` directories in your local Isaac Lab project and replace any instance of the renamed +directories and imports. **Please use the script at your own risk as it will overwrite source files directly.** + + +Restructuring of Isaac Lab Extensions +------------------------------------- + +With the introduction of ``isaaclab_mimic``, designed for supporting data generation workflows for imitation learning, +we have also split out the previous ``wrappers`` folder under ``isaaclab_tasks`` to its own module, named ``isaaclab_rl``. +This new extension will contain reinforcement learning specific wrappers for the various RL libraries supported by Isaac Lab. + +The new ``isaaclab_mimic`` extension will also replace the previous imitation learning scripts under the ``robomimic`` folder. +We have removed the old scripts for data collection and dataset preparation in favor of the new mimic workflow. For users +who prefer to use the previous scripts, they will be available in previous release branches. + +Additionally, we have also restructured the ``isaaclab_assets`` extension to be split into ``robots`` and ``sensors`` +subdirectories. This allows for clearer separation between the pre-defined configurations provided in the extension. +For any existing imports such as ``from omni.isaac.lab_assets.anymal import ANYMAL_C_CFG``, please replace it with +``from isaaclab.robots.anymal import ANYMAL_C_CFG``. + + +Lazy Exporting and Resolvable Strings +-------------------------------------- + +Isaac Lab now uses **lazy exporting** throughout all packages so that importing a top-level +module (e.g. ``import isaaclab.sensors``) no longer eagerly pulls in heavyweight +dependencies such as ``pxr``, ``omni``, or ``scipy``. This is critical because Kit and the +Isaac Sim viewer do **not** tolerate imports of ``pxr``, ``omni``, or ``scipy`` before the +application is launched — doing so will cause crashes or undefined behavior. With lazy +exporting, config objects can be constructed *before* ``SimulationApp`` is launched, which +enables automatic physics-backend selection without requiring flags like +``--enable_cameras``. + +Two key patterns support this: + +1. **Lazy exports** — Every ``__init__.py`` uses :func:`~isaaclab.utils.module.lazy_export` + together with an adjacent ``.pyi`` stub to defer submodule and symbol imports until + first access. +2. **Resolvable strings** — Config fields such as ``class_type`` store implementation + references as strings (e.g. ``"{DIR}.sensor:Sensor"``) instead of direct class imports. + The string is resolved to the actual class only after ``SimulationApp`` has been + initialized. + +For full details, examples, and the ``{DIR}`` placeholder convention, see the +:doc:`contributing` guide — in particular the +`Lazy Loading & Module Exports `__, +`Resolvable Strings `__, and +`Config + Implementation File Split `__ +sections. + +Lazy Exporting in User Code +---------------------------- + +If your own project imports Isaac Lab symbols eagerly (i.e. via normal ``from ... import`` +statements in ``__init__.py``), those imports may trigger heavyweight modules before the +simulation app is ready. This prevents automatic backend selection and may require you to +pass explicit flags like ``--enable_cameras`` or ``--kit``. + +To fix this, adopt the same lazy-exporting pattern used throughout Isaac Lab: + +1. Rename your existing ``__init__.py`` to ``__init__.pyi`` (this becomes the type stub). +2. Create a new ``__init__.py`` that calls ``lazy_export()``: + +.. code:: python + + # my_package/__init__.py + from isaaclab.utils.module import lazy_export + + lazy_export() + +3. Ensure the ``.pyi`` stub uses **relative imports** and declares ``__all__``: + +.. code:: python + + # my_package/__init__.pyi + __all__ = ["MyCfg", "MyClass"] + + from .my_cfg import MyCfg + from .my_class import MyClass + +With this in place, ``import my_package`` will not eagerly import any submodules. Symbols +are loaded on first access, giving ``SimulationApp`` time to initialize and auto-detect the +correct backend. + +For more details, refer to the :doc:`contributing` guide. + + +.. _simple script: https://gist.github.com/kellyguo11/3e8f73f739b1c013b1069ad372277a85 diff --git a/simulation/modules/IsaacLab/docs/source/refs/reference_architecture/index.rst b/simulation/modules/IsaacLab/docs/source/refs/reference_architecture/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..c875c964e26c21260dcc11a116bcd948bf469b5e --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/refs/reference_architecture/index.rst @@ -0,0 +1,378 @@ +.. _ref_arch: + +Reference Architecture +====================== + +This document presents an overview of the end-to-end robot learning process with +Isaac Lab and Isaac Sim. This is demonstrated using a reference architecture that highlights +the major building blocks for training and deployment workflows. It provides a comprehensive, +user-friendly guide on the entire process of developing applications from training to deploying +the trained model in the real world, including links to demos, working examples, and documentation. + +Who is this document for? +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This document is designed to assist robotics developers and researchers working with NVIDIA Isaac Lab +in the robot learning field, including those at research labs, Original Equipment Manufacturers (OEM), +Solutions Providers, Solutions Integrators (SI), and independent software vendors (ISV). It offers +guidance on utilizing Isaac Lab’s robot training framework and workflows as a foundational starting +point for environment configuration, task design, and policy training and testing. + + + +.. image:: ../../_static/reference-architecture/isaac-lab-ra-light.svg + :class: only-light + :align: center + :alt: Isaac Lab Reference Architecture + +.. image:: ../../_static/reference-architecture/isaac-lab-ra-dark.svg + :class: only-dark + :align: center + :alt: Isaac Lab Reference Architecture + + +| + +The reference architecture for Isaac Lab comprises the following components: + +1. :ref:`Asset Input` +2. :ref:`Configuration - Assets & Scene` +3. :ref:`Robot Learning Task Design` +4. :ref:`Register with Gymnasium` +5. :ref:`Environment Wrapping` +6. :ref:`Run Training` +7. :ref:`Run Testing` + + + + +Components +~~~~~~~~~~~ +In this section, we will briefly discuss the individual blocks for creating a +sample reference application in Isaac Lab. + + +.. _ra-asset-input: + +Component 1 - Asset Input +--------------------------- +Isaac Lab accepts URDF, MJCF XML or USD files for the assets. The first step to training using Isaac Lab is to +have the USD file of your asset and the USD or URDF file of your robot. This can be achieved in +the following ways: + + +1. Design your assets or robot in Isaac Sim and export the USD file. + +2. Design your assets or robot in any software of your choice and export it to USD using Isaac Sim converters. Isaac Sim supports the different converters/importers to USD such as the `CAD Converter`_, `URDF Importer`_, `MJCF Importer`_, `Onshape Importer`_, etc. More details are found in the `Importing Assets section`_ in the `Isaac Sim Reference Architecture`_. + +3. If you already have the URDF or MJCF file of your robot, you do not need to convert to USD as Isaac Lab takes URDF and MJCF XML. + + +.. _ra-configuration: + +Component 2 - Configuration (Assets and Scene) +------------------------------------------------------ + +Asset Configuration +^^^^^^^^^^^^^^^^^^^^^^^^ + +Given that you have the asset file for your robot and other assets such as environment objects based on the task, the next step is to import them into Isaac Lab. Isaac Lab uses asset configuration classes to spawn various objects (or prims) into the scene using Python. The first step is to write a configuration class to define the properties for the assets needed to complete the task. For example, a simple go-to-goal task for a mobile robot will include the robot asset, an object like cubes to signify the goal pose visually, lights, ground plane, etc. Isaac Lab understands these assets using the configuration classes. Isaac Lab provides various sim-ready assets such as physically accurate +3D objects that encompass accurate physical properties and behavior. It also provides connected data streams to represent the real world in simulated digital worlds such as `robots `__ +like ANYbotics Anymal, Unitree H1 Humanoid, etc. as well as `sensors `__. We provide these assets configuration classes. Users can also define their own assets using the configuration classes. + +Follow the tutorial on `how to write an Articulation and ArticulationCfg class `__. + +Scene Configuration +^^^^^^^^^^^^^^^^^^^^^^^^ + +Given the individual asset configurations, the next step is to put all the assets together into a +scene. The scene configuration is a simple config class that initializes all the assets in the +scene that are needed for the task and for visualization. This is an example for the +`Cartpole example scene configuration `__, +which includes the cartpole, ground plane, and dome light. + + +.. _ra-robot-learning-task-design: + +Component 3 - Robot Learning Task Design +------------------------------------------------------ +Now, we have the scene for the task, but we need to define the robot learning task. We will focus on +`reinforcement learning (RL) `__ algorithm here. We define the RL task +that the agent is going to do. RL tasks are defined as a Markov Decision Process (MDP), +which is a stochastic decision-making process where optional decisions are made for the agents +considering their current state and environment they interact with. The environment provides the +agents’ current state or observations, and executes the actions provided by the agent. +The environment responds to the agents by providing the next states, reward of taking the +action, done flag and information about the current episode. Therefore, different components +of the MDP formulation (the environment) – states, actions, rewards, reset, done, etc. — must +be defined by the user for the agent to perform the given task. + +In Isaac Lab, we provide two different workflows for designing environments. + +Manager-based +^^^^^^^^^^^^^^^^^ +.. image:: ../../_static/task-workflows/manager-based-light.svg + :class: only-light + :align: center + :alt: Manager-based Task Workflow + +.. image:: ../../_static/task-workflows/manager-based-dark.svg + :class: only-dark + :align: center + :alt: Manager-based Task Workflow + +This workflow is modular, and the environment is decomposed into individual components (or managers) +that handle the different aspects of the environment, such as computing observations, +applying actions, and applying randomization. As a user, you define different configuration classes +for each component. + +- An RL task should have the following configuration classes: + + - Observations Config: Defines the agents’ observations for the task. + - Actions Config: Defines the agent’s action type, i.e. how the output of the agent are mapped to + the robot's control inputs. + - Rewards Config: Defines the reward function for the task + - Terminations Config: Defines the conditions for termination of an episode or when the task + is completed. + +- You can add other optional configuration classes such as Event Config which defines the set of randomizations and noisification for the agent and environment, Curriculum Config for tasks that require `curriculum learning`_ and Commands Config for tasks where the input is from a controller/setpoint controls e.g. a gamepad controller. + +.. tip:: + + To learn more on how you can design your own manager-based environment, see :ref:`tutorial-create-manager-rl-env`. + + + +Direct +^^^^^^^^ +.. image:: ../../_static/task-workflows/direct-based-light.svg + :class: only-light + :align: center + :alt: Direct-based Task Workflow + +.. image:: ../../_static/task-workflows/direct-based-dark.svg + :class: only-dark + :align: center + :alt: Direct-based Task Workflow + +In this workflow, you implement a single class that is responsible for computing observations, applying actions, and computing rewards. This workflow allows for direct control of the environment logic. + +.. tip:: + To learn more on how you can design your own direct environment, see :ref:`tutorial-create-direct-rl-env`. + +Users can choose from Isaac Lab’s large suite of pre-configured environments or users can define +their own environments. For more technical information about the two workflows, please see the +`documentation `__. + + +In addition to designing the RL task, you will need to design your agent’s model, the neural +network policy and value function. To train the RL agent to solve the task, you need to define +the hyperparameters such as number of epochs, learning rate, etc. for training and the +policy/value model architecture. This is defined in the training configuration file specific +to the RL library you want to use. Examples are created under the agent's folder in each task directory. +See an example of `RSL-RL `__ for Anymal-B. + + +.. _ra-register-gym: + +Component 4 - Register with Gymnasium +------------------------------------------------------ + +The next step is to register the environments with the gymnasium registry to allow you to create the environment using the unique environment name. +Registration is a way to make the environment accessible and reusable across different +RL algorithms and experiments. This is common in the RL community. Follow the tutorial on +`Registering an Environment `__ to learn more about how to register in your own environment. + +.. _ra-env-wrap: + +Component 5 - Environment Wrapping +------------------------------------------------------ +In running your RL task, you might want to change the behavior of your environment without +changing the environment itself. For example, you might want to create functions to modify +observations or rewards, record videos, or enforce time limits. Isaac Lab utilizes the API +available in the `gymnasium.Wrapper `__ class to create interfaces to the simulated environments. + +Some wrappers include: + +* `Video Wrappers `__ +* `RL Libraries Wrappers `__ + +.. currentmodule:: isaaclab_rl + +Most RL libraries expect their own variation of an environment interface. This means the +data types needed by each library differs. Isaac Lab provides its own wrappers to convert +the environment into the expected interface by the RL library a user wants to use. These are +specified in :class:`isaaclab_rl` + +See the `full list `__ of other wrappers APIs. For more information on how these wrappers work, +please refer to the `Wrapping environments `__ documentation. + +Adding your own wrappers +^^^^^^^^^^^^^^^^^^^^^^^^ + +You can define your own wrappers by adding them to the Isaac Lab utils wrapper module. More information is available `on the GitHub page for wrapping environments `__. + +.. _ra-run-training: + +Component 6 - Run Training +--------------------------- + +Finally, the last step is to run the training of the RL agent. Isaac Lab provides scripts which utilizes four popular RL libraries for training the models (GPU-based training): + +* `StableBaselines3 `__ +* `RSL-RL `__ +* `RL-Games `__ +* `SKRL `__ + + +.. note:: + + Isaac Lab does not provide the implementation of these RL libraries. They are already implemented by different authors. We provide the environments and framework wrappers for the RL libraries. + + + +If you want to integrate a different version of the provided algorithms or your learning library, you can follow +`these instructions `__. + + + +Single GPU Training +^^^^^^^^^^^^^^^^^^^^^^^^ +.. image:: ../../_static/reference-architecture/single-gpu-training-light.svg + :class: only-light + :align: center + :alt: Single GPU Training Data Flow + +.. image:: ../../_static/reference-architecture/single-gpu-training-dark.svg + :class: only-dark + :align: center + :alt: Single GPU Training Data Flow + +Isaac Lab supports training massively parallel environments to speed up RL training and provides rich data for the model to train. +For single GPU training, the following steps show how training works in Isaac Sim and Isaac Lab: + +1. **In Isaac Sim** + +* Isaac Sim provides the asset states such as robot and sensor states, including the observations defined in the task observation config class. + +2. **In Isaac Lab** + +* Randomizations are added to the states defined in the event configuration class to obtain the observation for the task. Randomizations are however optional. If not defined, the states are the observations. +* The observations are computed as PyTorch tensors, and it can optionally include the action provided by the trained model based on the task. + +3. **In the RL library** + +* The observation is passed to the policy. +* The policy is trained to output the right actions for the robot using RL library algorithms such as PPO, TRPO, etc. +* The actions can serve either as a setpoint for a controller that generates the action to the robot or used directly as the action to the robot based on the task. +* Action types such as joint position for a quadruped is an input to a joint controller, velocity of 1 or 0 is used to control the cart directly in the cartpole task, etc. +* In addition, based on how the task is defined, the previous action can be part of the next set of observations that is sent. + +4. **In Isaac Sim** + +* The actions from the policy are sent back to Isaac Sim to control the agent that is learning i.e. the robot. This is the physics simulation (sim) step. This generates the next states in Isaac Sim and the rewards are calculated in Isaac Lab. + +5. **Rendering** + +* The scene can be rendered to produce the cameras' images. + + +The next state is then passed in the flow till the training reaches the specified training steps or epochs. The final product is the trained model/agent. + + + +Multi-GPU and Multi-Node Training +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +.. image:: ../../_static/reference-architecture/multi-gpu-training-light.svg + :class: only-light + :align: center + :alt: Multi GPU Training Data Flow + +.. image:: ../../_static/reference-architecture/multi-gpu-training-dark.svg + :class: only-dark + :align: center + :alt: Multi GPU Training Data Flow + + +Isaac Lab supports scaling up training by taking advantage of multi-GPU and multi-node training on Linux. Follow the tutorial on `Multi-GPU training `__ and `Multi-Node training `__ to get started. + + +Cloud-Based Training +^^^^^^^^^^^^^^^^^^^^^^^^ +Isaac Lab can be deployed alongside Isaac Sim onto the public clouds with `Isaac Automator `__. AWS, GCP, Azure, and Alibaba Cloud are currently supported. Follow the tutorial on `how to run Isaac Lab in the cloud `__. + +.. note:: + + Both multi-GPU and multi-node jobs can be easily scaled across heterogeneous environments with `OSMO `__, a cloud-native, orchestration platform for scheduling complex multi-stage and multi-container heterogeneous computing workflows. Isaac Lab also provides the tools to run your RL task in Docker. See more details on `container deployment `__. + +.. _ra-run-testing: + +Component 7: Run Testing +----------------------------- +Isaac Lab provides scripts for `testing/playing the trained policy `__ on the environment and functions for converting the trained model from .pt to +.jit and .onnx for deployment. + + +Deployment on Physical Robots +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. image:: ../../_static/reference-architecture/deployment-light.svg + :class: only-light + :align: center + :alt: Isaac Lab Trained Policy Deployment + +.. image:: ../../_static/reference-architecture/deployment-dark.svg + :class: only-dark + :align: center + :alt: Isaac Lab Trained Policy Deployment + + +To deploy your trained model on a real robot, you would need what is shown in the flow diagram. Note, this is a sample reference architecture, hence it can be tweaked for a different application. +First, you need a robot with the required sensors and processing computer such as `NVIDIA Jetson `__ to deploy on. Next, you need a state estimator for your robot. The state estimator should be able to deliver the list of observations used for training. + +Once the observations are extracted, they are passed into the model which delivers the action using the model inferencing runtime. The commanded action from the model serves as setpoints for the action controller. The action controller outputs scaled actions which are then used to control the robot to get to the next state, and this continues till the task is done. + +NVIDIA Isaac platform provides some tools for state estimation, including visual slam and inferencing engines such as `TensorRT `__. Other inferencing runtime includes `OnnxRuntime `__, direct inferencing on the PyTorch model, etc. + + + + +Summary +~~~~~~~~~~~ + +This document presents a reference architecture for Isaac Lab that has undergone SQA testing. We have provided a user-friendly guide to end-to-end robot learning with Isaac Lab and Isaac Sim from training to real-world deployment, including demos, examples, and documentation links. + + +How to Get Started +~~~~~~~~~~~~~~~~~~~~~~ +Check out our resources on using Isaac Lab with your robots. + +Review Our Documentation & Samples Resources + +* :ref:`Isaac Lab Tutorials ` +* `Fast-Track Robot Learning in Simulation Using NVIDIA Isaac Lab`_ +* `Supercharge Robotics Workflows with AI and Simulation Using NVIDIA Isaac Sim 4.0 and NVIDIA Isaac Lab`_ +* `Closing the Sim-to-Real Gap: Training Spot Quadruped Locomotion with NVIDIA Isaac Lab `__ +* `Additional Resources`_ + +Learn More About Featured NVIDIA Solutions + +* `Scale AI-Enabled Robotics Development Workloads with NVIDIA OSMO`_ +* `Parkour and More: How Simulation-Based RL Helps to Push the Boundaries in Legged Locomotion (GTC session) `__ +* `Isaac Perceptor`_ +* `Isaac Manipulator`_ + +.. _curriculum learning: https://arxiv.org/abs/2109.11978 +.. _CAD Converter: https://docs.omniverse.nvidia.com/extensions/latest/ext_cad-converter.html +.. _URDF Importer: https://docs.isaacsim.omniverse.nvidia.com/latest/importer_exporter/ext_isaacsim_asset_importer_urdf.html +.. _MJCF Importer: https://docs.isaacsim.omniverse.nvidia.com/latest/importer_exporter/ext_isaacsim_asset_importer_mjcf.html +.. _Onshape Importer: https://docs.omniverse.nvidia.com/extensions/latest/ext_onshape.html +.. _Isaac Sim Reference Architecture: https://docs.isaacsim.omniverse.nvidia.com/latest/introduction/reference_architecture.html +.. _Importing Assets section: https://docs.isaacsim.omniverse.nvidia.com/latest/importer_exporter/importers_exporters.html + +.. _Scale AI-Enabled Robotics Development Workloads with NVIDIA OSMO: https://developer.nvidia.com/blog/scale-ai-enabled-robotics-development-workloads-with-nvidia-osmo/ +.. _Isaac Perceptor: https://developer.nvidia.com/isaac/perceptor +.. _Isaac Manipulator: https://developer.nvidia.com/isaac/manipulator +.. _Additional Resources: https://isaac-sim.github.io/IsaacLab/main/source/refs/additional_resources.html +.. _Fast-Track Robot Learning in Simulation Using NVIDIA Isaac Lab: https://developer.nvidia.com/blog/fast-track-robot-learning-in-simulation-using-nvidia-isaac-lab/ +.. _Supercharge Robotics Workflows with AI and Simulation Using NVIDIA Isaac Sim 4.0 and NVIDIA Isaac Lab: https://developer.nvidia.com/blog/supercharge-robotics-workflows-with-ai-and-simulation-using-nvidia-isaac-sim-4-0-and-nvidia-isaac-lab/ diff --git a/simulation/modules/IsaacLab/docs/source/refs/release_notes.rst b/simulation/modules/IsaacLab/docs/source/refs/release_notes.rst new file mode 100644 index 0000000000000000000000000000000000000000..e0f388a04ad8ef3257b485253d5cb6c256aaa790 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/refs/release_notes.rst @@ -0,0 +1,1981 @@ +Release Notes +############# + +The release notes are now available in the `Isaac Lab GitHub repository `_. +We summarize the release notes here for convenience. + +v2.3.2 +====== + +What's Changed +-------------- + +This release focuses on stability, infrastructure improvements, workflow refinements, and incremental feature expansions, along with some significant new features, including **Multirotor and thruster support for drones**, **Multi-mesh RayCaster**, **Visual-based tactile sensor**, **Haply device integration**, and new **OpenArm environments**. It includes improvements to training workflows, teleoperation and Mimic pipelines, Ray integration, simulation utilities, and developer tooling, along with a large number of robustness and quality-of-life fixes. + +This will be our final release on the current **main** branch as we shift our development focus towards the **develop** branch. We anticipate large restructuring changes to happen on **develop**. While we hope to continue taking in contributions from the community, we will focus more time on our development towards Isaac Lab 3.0. For existing PRs, please re-target the target branch to **develop** to stay up-to-date with the latest changes. + +New Features +------------ + +Core & Simulation +~~~~~~~~~~~~~~~~~ + +* Adds Raycaster with tracking support for dynamic meshes by @renezurbruegg in https://github.com/isaac-sim/IsaacLab/pull/3298 +* Adds visual-based tactile sensor with shape sensing example by @JuanaDd in https://github.com/isaac-sim/IsaacLab/pull/3420 +* Adds wrench composers allowing the composition of multiple wrenches on the same bodies by @AntoineRichard in https://github.com/isaac-sim/IsaacLab/pull/3287 +* Adds multirotor/thruster actuator, multirotor asset and manager-based ARL drone task https://github.com/isaac-sim/IsaacLab/pull/3760 by @mihirk284 @grzemal @Zwoelf12 +* Adds automatic transform discovery for IMU sensors to find valid parent bodies by @bmccann-bdai in https://github.com/isaac-sim/IsaacLab/pull/3864 +* Adds friction force reporting to ContactSensor by @gattra-rai in https://github.com/isaac-sim/IsaacLab/pull/3563 +* Adds MJCF spawner for importing MJCF-based assets by @KyleM73 in https://github.com/isaac-sim/IsaacLab/pull/1672 + +Learning & Environments +~~~~~~~~~~~~~~~~~~~~~~~ + +* Adds OpenArm environments by @JinnnK in https://github.com/isaac-sim/IsaacLab/pull/4089 + +Mimic & Teleoperation +~~~~~~~~~~~~~~~~~~~~~ + +* Adds Haply device API with force feedback and teleoperation demo by @mingxueg-nv in https://github.com/isaac-sim/IsaacLab/pull/3873 +* Refactors retargeters and adds Quest retargeters for G1 tasks by @rwiltz in https://github.com/isaac-sim/IsaacLab/pull/3950 +* Adds Arena G1 locomanipulation retargeters by @rwiltz in https://github.com/isaac-sim/IsaacLab/pull/4140 +* Adds APIs to Isaac Lab Mimic for loco-manipulation data generation by @peterd-NV in https://github.com/isaac-sim/IsaacLab/pull/3992 + +Improvements +------------ + +Core & Simulation +~~~~~~~~~~~~~~~~~ + +* Adds preserve-order flag to JointPositionToLimitsAction by @renezurbruegg in https://github.com/isaac-sim/IsaacLab/pull/3716 +* Adds parsing of instanced meshes to prim fetching utilities by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/3367 +* Adds configurable logdir parameter to environments by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3391 +* Exposes PhysX flag solveArticulationContactLast via PhysxCfg by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3502 +* Removes pickle dependency for config load and dump by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3709 +* Improves recorder manager to support custom demo indices by @rebeccazhang0707 in https://github.com/isaac-sim/IsaacLab/pull/3552 +* Normalizes Python logging by replacing remaining omni.log usage by @pascal-roth in https://github.com/isaac-sim/IsaacLab/pull/3912 +* Replaces Isaac Sim stage_utils, prim_utils, and nucleus_utils with Isaac Lab implementations by @pascal-roth in https://github.com/isaac-sim/IsaacLab/pull/3921, https://github.com/isaac-sim/IsaacLab/pull/3923, https://github.com/isaac-sim/IsaacLab/pull/3924 +* Breaks actuator configuration into multiple files to avoid circular imports by @bmccann-bdai in https://github.com/isaac-sim/IsaacLab/pull/3994 +* Moves logging configuration into shared utilities by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/4298 +* Caches Isaac Sim package version for faster lookup by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/4299 +* Simplifies imports of stage and prim utilities by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/4286 +* Randomizes viscous and dynamic joint friction consistent with Isaac Sim 5.0 by @GiulioRomualdi in https://github.com/isaac-sim/IsaacLab/pull/3318 +* Prevents randomization of rigid body mass to zero or negative values by @jtigue-bdai in https://github.com/isaac-sim/IsaacLab/pull/4060 +* Improves image plotting normalization and colorization by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/4302 +* Adds Fabric backend support to isaaclab.sim.views.XformPrimView by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/4374 + +Learning & Environments +~~~~~~~~~~~~~~~~~~~~~~~ + +* Enhances PBT usability with small workflow improvements by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3449 +* Supports vectorized environments for pick-and-place demo by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3996 +* Registers direct environments to Gymnasium using string-style imports by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3803 +* Updates Gymnasium dependency to version 1.2.1 by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/3696 +* Updates SB3 PPO configuration to reduce excessive training time by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3726 +* Adds support for validating replay success using task termination conditions by @yami007007 in https://github.com/isaac-sim/IsaacLab/pull/4170 +* Adds early stopping support for Ray-based training by @ozhanozen in https://github.com/isaac-sim/IsaacLab/pull/3276 +* Adds support for custom ProgressReporter implementations in Ray integration by @ozhanozen in https://github.com/isaac-sim/IsaacLab/pull/3269 +* Updates rsl_rl to version 3.1.2 to support state-dependent standard deviation by @ashwinvkNV in https://github.com/isaac-sim/IsaacLab/pull/3867 + +Infrastructure +~~~~~~~~~~~~~~ + +* Switches linting and import sorting to Ruff by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/4329, https://github.com/isaac-sim/IsaacLab/pull/4377 +* Moves flake8 and pytest configuration into pyproject.toml by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/4335, https://github.com/isaac-sim/IsaacLab/pull/4376 +* Removes dependency on XformPrim for create_prim by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/4307 +* Updates copyright year to 2026 by @ashwinvkNV in https://github.com/isaac-sim/IsaacLab/pull/4311 +* Restricts .gitignore dataset rule to top-level directory only by @louislelay in https://github.com/isaac-sim/IsaacLab/pull/3400 +* Adds uv as an alternative to conda in isaaclab.sh by @KyleM73 in https://github.com/isaac-sim/IsaacLab/pull/3172 +* Fixes transformers dependency for theia issue and failing tests by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/4484 + +Bug Fixes +--------- + +Core & Simulation +~~~~~~~~~~~~~~~~~ + +* Fixes missing actuator indices variable in joint randomization by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3447 +* Fixes ViewportCameraController numpy array missing datatype by @T-K-233 in https://github.com/isaac-sim/IsaacLab/pull/3375 +* Fixes PDActuator docstring mismatch with implementation by @lorenwel in https://github.com/isaac-sim/IsaacLab/pull/3493 +* Fixes rail difficulty-based height computation in mesh terrains by @KyleM73 in https://github.com/isaac-sim/IsaacLab/pull/3254 +* Fixes contact threshold handling when activating contact sensors by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3498 +* Fixes indexing errors in joint parameter randomization by @GiulioRomualdi in https://github.com/isaac-sim/IsaacLab/pull/4051 +* Fixes noisy velocities near joint limits by @AntoineRichard in https://github.com/isaac-sim/IsaacLab/pull/3989 +* Fixes mesh converter not setting collision approximation attributes by @Soappyooo in https://github.com/isaac-sim/IsaacLab/pull/4082 +* Fixes returned normal tensor shape in TiledCamera by @Rabbit-Hu in https://github.com/isaac-sim/IsaacLab/pull/4241 +* Fixes advanced indexing shape mismatch in JointPositionToLimitsAction by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3865 +* Fixes teleoperation crash when using DirectRL environments by @emmanuel-ferdman in https://github.com/isaac-sim/IsaacLab/pull/4364 +* Fixes lidar pattern horizontal resolution bug by @pascal-roth in https://github.com/isaac-sim/IsaacLab/pull/4452 + +Learning & Environments +~~~~~~~~~~~~~~~~~~~~~~~ + +* Fixes CUDA version parsing for AutoMate environments by @yijieg in https://github.com/isaac-sim/IsaacLab/pull/3795 + +Infrastructure & Tooling +~~~~~~~~~~~~~~~~~~~~~~~~ + +* Fixes CI behavior to correctly fail fork PRs when general tests fail by @nv-apoddubny in https://github.com/isaac-sim/IsaacLab/pull/3412 +* Fixes docker availability check in isaaclab.sh on systems without Docker by @klakhi in https://github.com/isaac-sim/IsaacLab/pull/4180 +* Forces CRLF line endings for .bat files to avoid Windows execution errors by @jiang131072 in https://github.com/isaac-sim/IsaacLab/pull/3624 +* Fixes environment test failures and disables unstable tests by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3413 +* Fixes vulnerability in eval usage for Ray resource parsing by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/4425 +* Fixes curobo dockerfile for CI runs by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/4462 + +Documentation +------------- + +* Improves contribution guidelines for Isaac Lab by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/3403 +* Abstracts common installation steps in documentation by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/3445 +* Updates SkillGen documentation with data generation commands and success rates by @njawale42 in https://github.com/isaac-sim/IsaacLab/pull/3702 +* Adds Newton Beta documentation updates and visualizer guidance by @kellyguo11 and @Milad-Rakhsha-NV in https://github.com/isaac-sim/IsaacLab/pull/3518, https://github.com/isaac-sim/IsaacLab/pull/3551 +* Adds automated checks for broken documentation links and fixes existing ones by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3888 +* Updates technical report link for Isaac Lab by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/4074 +* Adds clarification on missing pip in uv virtual environments by @DBinK in https://github.com/isaac-sim/IsaacLab/pull/4055 +* Adds keyword filtering documentation for list_envs.py by @louislelay in https://github.com/isaac-sim/IsaacLab/pull/3384 +* Adds documentation for Multirotor feature by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/4400 +* Adds documentation for PVD and OVD comparison by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/4409 + +Migration Guide +--------------- + +External Force and Torque Application - Wrench Composers +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +The ``set_external_force_and_torque()`` method on articulations, rigid bodies, and rigid body collections has been deprecated in favor of a new composable wrench system. + +Related PR: https://github.com/isaac-sim/IsaacLab/pull/3287 + +**New Features:** +- **Permanent Wrench Composer**: Applies forces/torques that persist across simulation steps until explicitly changed +- **Instantaneous Wrench Composer**: Applies forces/torques for a single simulation step, then automatically resets +- **Composability**: Multiple forces and torques can now be added together on the same body +- **Mixed Frame Support**: Seamlessly compose local and global frame wrenches + +**Migration Guide:** + +**Old API (Deprecated):** + +.. code-block:: python + + # Old method - overwrites previous forces + asset.set_external_force_and_torque( + forces=torch.ones(1, 1, 3), + torques=torch.ones(1, 1, 3), + body_ids=[0], + env_ids=[0], + is_global=False, + ) + +**New API:** + +.. code-block:: python + + # Set initial permanent forces (replaces previous) + asset.permanent_wrench_composer.set_forces_and_torques( + forces=torch.ones(1, 1, 3), + env_ids=[0], + body_ids=[0], + ) + + # Compose additional forces on the same body + asset.permanent_wrench_composer.add_forces_and_torques( + forces=torch.ones(1, 1, 3), + env_ids=[0], + body_ids=[0], + is_global=True, # Mix local and global frames + ) + + # Add torques independently + asset.permanent_wrench_composer.add_forces_and_torques( + torques=torch.ones(1, 1, 3), + env_ids=[0], + body_ids=[0], + ) + + # Apply forces and torques together with custom application points + asset.permanent_wrench_composer.add_forces_and_torques( + forces=torch.ones(1, 1, 3), + torques=torch.ones(1, 1, 3), + positions=torch.ones(1, 1, 3), + env_ids=[0], + body_ids=[0], + ) + +**Instantaneous Wrenches (New):** + +.. code-block:: python + + # Apply forces for a single simulation step only + asset.instantaneous_wrench_composer.add_forces_and_torques( + forces=torch.ones(1, 1, 3), + env_ids=[0], + body_ids=[0], + ) + + # Multiple instantaneous wrenches compose automatically + asset.instantaneous_wrench_composer.add_forces_and_torques( + forces=torch.ones(1, 2, 3), # Add more forces + env_ids=[0], + body_ids=[0, 1], + ) + # These are automatically reset after write_data_to_sim() + +**Key Differences:** + +- ``set_forces_and_torques()`` replaces existing wrenches +- ``add_forces_and_torques()`` composes with existing wrenches +- Permanent and instantaneous wrenches compose automatically +- Instantaneous wrenches auto-clear after each simulation step + +**Use Cases:** +- **Drones**: Compose thrust forces with aerodynamic drag and wind disturbances +- **Boats**: Apply buoyancy forces with wave-induced motions + + +Formatting and Linting - Migration to Ruff +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The project has migrated from multiple tools (``flake8`` for linting, ``black`` for formatting, ``isort`` for import sorting) to a unified toolchain using ``ruff`` for all formatting and linting tasks. + +Related PRs: https://github.com/isaac-sim/IsaacLab/pull/4329, https://github.com/isaac-sim/IsaacLab/pull/4377, https://github.com/isaac-sim/IsaacLab/pull/4335, https://github.com/isaac-sim/IsaacLab/pull/4376 + + +**Why:** + +- Faster performance (10-100x speedup) +- Unified configuration in ``pyproject.toml`` +- More consistent formatting and linting rules +- Simplified developer workflow + +**Migration Steps:** + +1. **Update configuration files:** + + .. code-block:: bash + + # Copy the updated configuration from the main branch + # Files to update: pyproject.toml, .pre-commit-config.yaml + +2. **Apply new formatting:** + + .. code-block:: bash + + ./isaaclab.sh --format + +3. **Resolve merge conflicts:** + If you encounter merge conflicts after updating, they likely originate from formatting differences. After copying the new configuration files, rerun the formatting command and commit the changes. + +.. note:: + + Pre-commit hooks will automatically run ``ruff`` on staged files. Ensure your code is formatted + before committing to avoid CI failures. + + +USD Utilities - Unified ``isaaclab.sim.utils`` Module +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Isaac Lab now provides its own comprehensive USD utility module (``isaaclab.sim.utils``) instead of relying on scattered utilities from Isaac Sim's ``isaacsim.core.utils`` packages. + +Related PR: https://github.com/isaac-sim/IsaacLab/pull/4286 + +**Why:** + +- **Better Organization**: All USD operations grouped into logical submodules (stage, prims, queries, transforms, semantics) +- **Type Hints**: Full type annotations for better IDE support and code safety +- **Version Compatibility**: Handles differences between Isaac Sim versions automatically + +**Old API (Isaac Sim utilities):** + +.. code-block:: python + + import isaac.core.utils.stage as stage_utils + import isaac.core.utils.prims as prim_utils + + # Stage operations + stage_utils.create_new_stage() + current_stage = stage_utils.get_current_stage() + + # Prim operations + prim_utils.create_prim("/World/Cube", "Cube") + prim_utils.delete_prim("/World/OldObject") + +**New API (Isaac Lab utilities):** + +.. code-block:: python + + import isaaclab.sim as sim_utils + + # Stage operations + sim_utils.create_new_stage() + current_stage = sim_utils.get_current_stage() + + # Prim operations + sim_utils.create_prim("/World/Cube", "Cube", attributes={"size": 1.0}) + sim_utils.delete_prim("/World/OldObject") + +**Legacy Support:** + +For backward compatibility, legacy functions are still available in ``isaaclab.sim.utils.legacy``, but it's recommended to migrate to the new APIs or use USD directly. + +**Full Changelog**: https://github.com/isaac-sim/IsaacLab/compare/v2.3.1...v2.3.2 + +v2.3.1 +====== + +What's Changed +-------------- + +This is a small patch release with a few critical fixes that impacted user workflows. + +Key fixes include: +* The behavior of termination logging has changed in the manager-based workflow, where ``get_done_term`` now returns the current step value instead of the last episode value. +* Additionally, a breaking change in the URDF importer was introduced in Isaac Sim 5.1, where the merge joints flag is no longer supported. We have now introduced a patch in the importer to return the behavior. Moving forward, we plan to deprecate this flag in favor of preserving asset definitions from URDFs directly without performing additional processing during the import process. + +Bug Fixes +--------- + +* Updates URDF importer to 2.4.31 to continue support for merge-joints by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/4000 +* Separates per-step termination and last-episode termination bookkeeping by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3745 +* Uses effort_limit from USD if not specified in actuator cfg by @JuanaDd in https://github.com/isaac-sim/IsaacLab/pull/3522 +* Fixes type name for tendon properties in from_files config by @KyleM73 in https://github.com/isaac-sim/IsaacLab/pull/3941 +* Fixes duplicated text in pip installation docs by @shryt in https://github.com/isaac-sim/IsaacLab/pull/3969 +* Pins python version of pre-commmit.yaml workflow by @hhansen-bdai in https://github.com/isaac-sim/IsaacLab/pull/3929 + +Documentation +------------- + +* Updates the mimic teleop doc to link to the locomotion policy training by @huihuaNvidia2023 in https://github.com/isaac-sim/IsaacLab/pull/4053 + +**Full Changelog**: https://github.com/isaac-sim/IsaacLab/compare/v2.3.0...v2.3.1 + +v2.3.0 +====== + +What's Changed +-------------- + +The Isaac Lab 2.3.0 release, built on Isaac Sim 5.1, delivers enhancements across dexterous manipulation, +teleoperation, and learning workflows. It introduces new dexterous environments with advanced training capabilities, +expands surface gripper and teleoperation support for a wider range of robots and devices, +and integrates SkillGen with the Mimic imitation learning pipeline to enable GPU-accelerated motion planning +and skill-based data generation with cuRobo integration. + +Key highlights of this release include: + +* **Dexterous RL (DexSuite)**: Introduction of two new dexterous manipulation environments using the Kuka arm and + Allegro hand setup, with addition of support for Automatic Domain Randomization (ADR) and PBT (Population-Based Training). +* **Surface gripper updates**: Surface gripper has been extended to support Manager-based workflows, + including the addition of ``SurfaceGripperAction`` and ``SurfaceGripperActionCfg``, along with several new environments + demonstrating teleoperation examples with surface grippers and the RMPFlow controller. + New robots and variations are introduced, including Franka and UR10 with robotiq grippers and suction cups, + and Galbot and Agibot robots. +* **Mimic - SkillGen**: SkillGen support has been added for the Mimic Imitation Learning pipeline, + introducing cuRobo integration, integrating GPU motion planning with skill-segmented data generation. + Note that cuRobo has proprietary licensing terms, please review the + `cuRobo license `_ + carefully before use. +* **Mimic - Locomanipulation**: Added a new G1 humanoid environment combining RL-based locomotion with IK-based + manipulation. A full robot navigation stack is integrated to augment demonstrations with randomization of + tabletop pick/place locations, destination and ground obstacles. By segmenting tasks into pick-navigate-place + phases, this method enables generation of large-scale loco-manipulation datasets from manipulation-only + demonstrations. +* **Teleoperation**: Upper body inverse kinematics controller is improved by adding a null space posture task that + helps enable waist movement on humanoid tasks while regularizing redundant degrees-of-freedom to a preferred + upright posture. Additionally, support for Vive and Manus Glove are introduced, providing more options for + teleoperation devices. + +**Full Changelog**: https://github.com/isaac-sim/IsaacLab/compare/v2.2.1...v2.3.0 + +Isaac Sim 5.1 Updates +---------------------- + +* Introduced support for `DGX Spark `_, + including multi-architecture Docker images with support for ARM platforms. +* PhysX now offers a new joint parameter tuning `tutorial `_ + for robotic grippers, along with a new feature for solving articulation collision contacts last to improve on + gripper penetration issues, especially for cases with sub-optimally tuned joints. +* Surface grippers has been optimized for better performance. Although support continues to be CPU-only, + performance has improved by several orders of magnitude compared to previous releases. +* Windows 10 support ended on October 14, 2025. Microsoft will no longer provide free security, feature, or technical + updates for Windows 10. As a result, we will be dropping support for Windows 10 in future releases of Isaac Sim and Lab + to ensure the security and functionality of our software. + +New Features +------------ + +Core +~~~~ + +* Supports rl games wrapper with dictionary observation by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3340 +* Adds surface gripper support in manager-based workflow by @rebeccazhang0707 in https://github.com/isaac-sim/IsaacLab/pull/3174 +* Adds two new robots with grippers by @rebeccazhang0707 in https://github.com/isaac-sim/IsaacLab/pull/3229 +* Adds new Collision Mesh Schema properties by @hapatel-bdai in https://github.com/isaac-sim/IsaacLab/pull/2249 +* Adds PBT algorithm to rl games by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3399 + +Mimic and Teleoperation +~~~~~~~~~~~~~~~~~~~~~~~ + +* Adds SkillGen framework to Isaac Lab with cuRobo support by @njawale42 in https://github.com/isaac-sim/IsaacLab/pull/3303 +* Adds locomanipulation data generation via. disjoint navigation by @jaybdub in https://github.com/isaac-sim/IsaacLab/pull/3259 +* Adds support for manus and vive by @cathyliyuanchen in https://github.com/isaac-sim/IsaacLab/pull/3357 +* Adds notification widgets at IK error status and Teleop task completion by @lotusl-code in https://github.com/isaac-sim/IsaacLab/pull/3356 + +Environments +~~~~~~~~~~~~ + +* Adds dexterous lift and reorientation manipulation environments by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3378 +* Adds task Reach-UR10e, an end-effector tracking environment by @ashwinvkNV in https://github.com/isaac-sim/IsaacLab/pull/3147 +* Adds a configuration example for Student-Teacher Distillation by @ClemensSchwarke in https://github.com/isaac-sim/IsaacLab/pull/3100 +* Adds Locomanipulation Environment with G1 for Mimic workflow by @michaellin6 in https://github.com/isaac-sim/IsaacLab/pull/3150 +* Adds teleop support for Unitree G1 with Inspire 5-finger hand, take PickPlace task as an example by @yami007007 in https://github.com/isaac-sim/IsaacLab/pull/3242 +* Adds galbot stack cube tasks, with left_arm_gripper and right_arm_suction, using RMPFlow controller by @rebeccazhang0707 in https://github.com/isaac-sim/IsaacLab/pull/3210 +* Adds AVP teleop support for Galbot stack tasks by @rwiltz in https://github.com/isaac-sim/IsaacLab/pull/3669 +* Adds camera to G1 Steering Wheel environment by @jaybdub in https://github.com/isaac-sim/IsaacLab/pull/3549 + +Infrastructure +~~~~~~~~~~~~~~ + +* Adds YAML Resource Specification To Ray Integration by @binw666 in https://github.com/isaac-sim/IsaacLab/pull/2847 +* Installs cuda13 on arm builds for Spark by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3396 +* Adds arm64 platform for Pink IK setup by @michaellin6 in https://github.com/isaac-sim/IsaacLab/pull/3686 +* Updates torch installation version to 2.9 for Linux-aarch, and updates opset version from 11 to 18. by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3706 + + +Improvements +------------ + +Core and Infrastructure +~~~~~~~~~~~~~~~~~~~~~~~ + +* Adds changes for rsl_rl 3.0.1 by @ClemensSchwarke in https://github.com/isaac-sim/IsaacLab/pull/2962 +* Simplifies cross platform installation setup.py by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3294 +* Updated image build logic and details by @nv-apoddubny in https://github.com/isaac-sim/IsaacLab/pull/3649 +* Applies the pre-merge CI failure control to the tasks by @nv-apoddubny in https://github.com/isaac-sim/IsaacLab/pull/3457 +* Updates Isaac Sim 5.1 staging server to production by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3691 +* Removes scikit-learn dependency by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3799 +* Removes extra calls to write simulation after reset_idx by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3446 +* Exposes render parameter ``/rtx/domeLight/upperLowerStrategy`` for dome light by @shauryadNv in https://github.com/isaac-sim/IsaacLab/pull/3694 +* Adds onnxscript dependency to isaaclab_rl module by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3722 +* Configures mesh collision schemas in ``convert_mesh.py`` by @zehao-wang in https://github.com/isaac-sim/IsaacLab/pull/3558 + +Mimic and Teleoperation +~~~~~~~~~~~~~~~~~~~~~~~ + +* Improves recorder performance and add additional recording capability by @peterd-NV in https://github.com/isaac-sim/IsaacLab/pull/3302 +* Optimizes Kit XR Teleop CPU time by @hougantc-nvda in https://github.com/isaac-sim/IsaacLab/pull/3487 +* Improves dataset file names and low success rate for trained model on g1 locomanipulation dataset by @michaellin6 in https://github.com/isaac-sim/IsaacLab/pull/3503 +* Updates the teleop_se3 and record_demos scripts with more helpful description for teleop_device parameter by @rwiltz in https://github.com/isaac-sim/IsaacLab/pull/3642 + + +Documentation +------------- + +Core +~~~~ + +* Updates documentation to explain known issue of missing references when uses URDF importer by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3729 +* Fixes symbol in training_jetbot_reward_exploration.rst by @dougfulop in https://github.com/isaac-sim/IsaacLab/pull/2722 +* Clarifies asset classes' default_inertia tensor coordinate frame by @preist-nvidia in https://github.com/isaac-sim/IsaacLab/pull/3405 +* Adds limitation note in docs for Multi Node Training on DGX Spark by @matthewtrepte in https://github.com/isaac-sim/IsaacLab/pull/3806 +* Updates locomanip task name and link in docs by @fan-ziqi in https://github.com/isaac-sim/IsaacLab/pull/3342 + +Mimic and Teleoperation +~~~~~~~~~~~~~~~~~~~~~~~ + +* Fixes G1 dataset link in teleop_imitation tutorial by @michaellin6 in https://github.com/isaac-sim/IsaacLab/pull/3463 +* Updates dataset instruction in ``teleop_imitation.rst`` (#3462) by @peterd-NV in https://github.com/isaac-sim/IsaacLab/pull/3489 +* Fixes teleop doc in Isaac Lab by @tifchen-nvda in https://github.com/isaac-sim/IsaacLab/pull/3539 +* Updates cloudxr teleop doc in Isaac Lab by @tifchen-nvda in https://github.com/isaac-sim/IsaacLab/pull/3540 +* Adds instructions on how to position the lighthouse for manus+vive by @cathyliyuanchen in https://github.com/isaac-sim/IsaacLab/pull/3548 +* Corrects versions for the cloudxr teleop doc by @tifchen-nvda in https://github.com/isaac-sim/IsaacLab/pull/3580 +* Adds link to IsaacLabEvalTasks repo from mimic section in doc (#3621) by @xyao-nv in https://github.com/isaac-sim/IsaacLab/pull/3627 +* Fixes ordering of docs for imitation learning by @shauryadNv in https://github.com/isaac-sim/IsaacLab/pull/3634 +* Updates documentation for manus teleop by @rwiltz in https://github.com/isaac-sim/IsaacLab/pull/3605 +* Updates SkillGen documentation for data gen command and success rates by @njawale42 in https://github.com/isaac-sim/IsaacLab/pull/3703 +* Fixes typo in mimic teleop documentation for locomanipulation by @michaellin6 in https://github.com/isaac-sim/IsaacLab/pull/3704 +* Updates dataset paths in teleop documentation and adds note in documentation to adjusting AR Anchors by @michaellin6 in https://github.com/isaac-sim/IsaacLab/pull/3707 +* Adds pysurvive installation instructions by @rwiltz in https://github.com/isaac-sim/IsaacLab/pull/3747 +* Adds to mimic documentation expected generation and training timings and success rates by @michaellin6 in https://github.com/isaac-sim/IsaacLab/pull/3742 +* Adds data gen and policy learning times in SkillGen documentation by @njawale42 in https://github.com/isaac-sim/IsaacLab/pull/3774 +* Updates doc to describe ways to clean up orphaned container and check connectivity for teleop by @yanziz-nvidia in https://github.com/isaac-sim/IsaacLab/pull/3787 +* Updates cloudxr teleop doc to explain openxr plugin by @tifchen-nvda in https://github.com/isaac-sim/IsaacLab/pull/3786 +* Updates Mimic docs to clarify CPU mode usage and DGX Spark support by @peterd-NV in https://github.com/isaac-sim/IsaacLab/pull/3794 +* Updates cuRobo installation instructions and added VRAM baseline perf to SkillGen docs by @njawale42 in https://github.com/isaac-sim/IsaacLab/pull/3797 +* Adds dgx spark limitations link to teleop docs by @lotusl-code in https://github.com/isaac-sim/IsaacLab/pull/3805 +* Adds Cosmos Transfer1 limitation for DGX spark by @shauryadNv in https://github.com/isaac-sim/IsaacLab/pull/3817 +* Updates DGX spark limitations for SkillGen in the documentation by @njawale42 in https://github.com/isaac-sim/IsaacLab/pull/3748 +* Adds the Isaac-PickPlace-G1-InspireFTP-Abs-v0 Task into Envs Docs by @yami007007 in https://github.com/isaac-sim/IsaacLab/pull/3479 + +Infrastructure +~~~~~~~~~~~~~~ + +* Change GLIBC version requirement to 2.35 for pip by @GiulioRomualdi in https://github.com/isaac-sim/IsaacLab/pull/3360 +* Updates Isaac Sim license by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3393 +* Updates jax installation instructions by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3561 +* Adds section for the DGX spark limitations by @mpgussert in https://github.com/isaac-sim/IsaacLab/pull/3652 +* Fixes broken links in the documentation by @mpgussert in https://github.com/isaac-sim/IsaacLab/pull/3721 +* Adds windows pip installation instruction in local pip installation documentation by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3723 +* Adds note about potential security risks with Ray by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3711 +* Fixes errors while building the docs by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/3370 + + +Bug Fixes +--------- + +Core +~~~~ + +* Fixes missing visible attribute in spawn_ground_plane by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3304 +* Moves parameter ``platform_height`` to the correct mesh terrain configuration by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/3316 +* Fixes invalid callbacks for debug vis when simulation is restarted by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3338 +* Deletes unused asset.py in isaaclab by @fan-ziqi in https://github.com/isaac-sim/IsaacLab/pull/3389 +* Moves location of serve file check to the correct module by @Mayankm96 in https://github.com/isaac-sim/IsaacLab/pull/3368 +* Fixes SurfaceGripper API to accommodate for Isaac Sim 5.1 changes by @AntoineRichard in https://github.com/isaac-sim/IsaacLab/pull/3528 +* Fixes keyboard unsubscribe carb call by @rwiltz in https://github.com/isaac-sim/IsaacLab/pull/3662 +* Fixes GCC error for raycaster demo when running in conda by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3712 +* Corrects materials and objects imports in ``check_terrain_importer.py`` by @PeterL-NV in https://github.com/isaac-sim/IsaacLab/pull/3411 +* Fixes tensor construction warning in ``events.py`` by @louislelay in https://github.com/isaac-sim/IsaacLab/pull/3251 +* Fixes skrl train/play script configurations when using the ``--agent`` argument and rename agent configuration variable by @Toni-SM in https://github.com/isaac-sim/IsaacLab/pull/3643 +* Fixes TiledCamera data types and rlgames training on CPU by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3808 + +Mimic and Teleoperation +~~~~~~~~~~~~~~~~~~~~~~~ + +* Updates the Path to Isaaclab Dir in SkillGen Documentation by @njawale42 in https://github.com/isaac-sim/IsaacLab/pull/3483 +* Fixes the reach task regression with teleop devices returning the gripper by @rwiltz in https://github.com/isaac-sim/IsaacLab/pull/3327 +* Fixes teleop G1 with Inspire hand issues by @yami007007 in https://github.com/isaac-sim/IsaacLab/pull/3440 +* Updates default viewer pose to see the whole scene for Agibot environment by @rebeccazhang0707 in https://github.com/isaac-sim/IsaacLab/pull/3525 +* Fixes XR UI when used with teleop devices other than "handtracking" by @rwiltz in https://github.com/isaac-sim/IsaacLab/pull/3566 +* Fixes manus joint indices mapping for teleoperation by @rwiltz in https://github.com/isaac-sim/IsaacLab/pull/3592 +* Updates gr1t2 dex pilot hand scaling by @rwiltz in https://github.com/isaac-sim/IsaacLab/pull/3607 +* Fixes unreal surface_gripper behavior by @rebeccazhang0707 in https://github.com/isaac-sim/IsaacLab/pull/3679 +* Fixes G1 finger PD gains configs for locomanipulation by @michaellin6 in https://github.com/isaac-sim/IsaacLab/pull/3749 +* Fixes the bug of right_arm suction cup passing through cubes by @rebeccazhang0707 in https://github.com/isaac-sim/IsaacLab/pull/3764 +* Updates the xr anchor for g1 tasks to me more natural for standing teleop by @rwiltz in https://github.com/isaac-sim/IsaacLab/pull/3775 +* Suppresses dex_retargeting::yourdfpy warnings for G1 by @rwiltz in https://github.com/isaac-sim/IsaacLab/pull/3798 +* Refines height of xr view for G1 envs by @rwiltz in https://github.com/isaac-sim/IsaacLab/pull/3813 + +Infrastructure +~~~~~~~~~~~~~~ + +* Fixes the missing Ray initialization by @ozhanozen in https://github.com/isaac-sim/IsaacLab/pull/3350 +* Fixes torch nightly version install in arm system by @ooctipus in https://github.com/isaac-sim/IsaacLab/pull/3464 +* Fixes unintentional removal of '=' from command by @ndahile-nvidia in https://github.com/isaac-sim/IsaacLab/pull/3600 +* Updates installation script for aarch64 to fix LD_PRELOAD issues by @matthewtrepte in https://github.com/isaac-sim/IsaacLab/pull/3708 +* Fixes hanging issue in test_manager_based_rl_env_obs_spaces.py by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3717 +* Fixes for missing desktop icon when running scripts on DGX Spark by @matthewtrepte in https://github.com/isaac-sim/IsaacLab/pull/3804 + + +Breaking Changes +---------------- + +* Removes unused 'relevant_link_name' parameter in nutpour and exhaust pipe envs by @michaellin6 in https://github.com/isaac-sim/IsaacLab/pull/3651 +* Moves IO descriptor log dir to logs by @kellyguo11 in https://github.com/isaac-sim/IsaacLab/pull/3434 + +Known Issues +~~~~~~~~~~~~ + +* The ROS2 docker image is not currently expected to work due to the update to Python 3.11. We are actively working on + a fix to resolve this. +* We have received reports of performance regressions in the previous Isaac Sim release for both physics and rendering + workflows. We are still working on addressing some of these, but have also found some workarounds. + For viewport regressions, Omniverse settings can be set by adding + ``--kit_args="--/app/usdrt/hierarchy/partialGpuUpdate=1 --/rtx/post/dlss/execMode=0 --/app/runLoops/main/rateLimitEnabled=false --/app/runLoops/main/manualModeEnabled=true --enable omni.kit.loop-isaac"``. Additionally, Isaac Sim 5.0 + introduced new actuator models for PhysX, including drive model and friction model improvements. + These improvements also introduced a small performance regression. We have observed up to ~20% slowdown in some + state-based environments. + +v2.2.1 +====== + +Overview +-------- + +This is a minor patch release with some improvements and bug fixes. + +Full Changelog: https://github.com/isaac-sim/IsaacLab/compare/v2.2.0...v2.2.1 + +New Features +------------ + +- Adds contact point location reporting to ContactSensor by @jtigue-bdai +- Adds environments actions/observations descriptors for export by @AntoineRichard +- Adds RSL-RL symmetry example for cartpole and ANYmal locomotion by @Mayankm96 + +Improvements +------------ + +Core API +~~~~~~~~ + +- Enhances Pink IK controller with null-space posture control and improvements by @michaellin6 +- Adds periodic logging when checking USD path on Nucleus server by @matthewtrepte +- Disallows string value written in sb3_ppo_cfg.yaml from being evaluated in process_sb3_cfg by @ooctipus + +Infrastructure +~~~~~~~~~~~~~~ + +* **Application Settings** + - Disables rate limit for headless and headless rendering app by @matthewtrepte, @kellyguo11 + - Disables ``rtx.indirrectDiffuse.enabled`` in render preset balanced and performance modes by @matthewtrepte + - Sets profiler backend to NVTX by default by @soowanpNV, @rwiltz +* **Dependencies** + - Adds hf-xet license by @hhansen-bdai + - Fixes new typing-inspection dependency license by @kellyguo11 +* **Testing & Benchmarking** + - Adds basic validation tests for scale-based randomization ranges by @louislelay + - Adds ``SensorBase`` tests by @jtigue-bdai +* **Repository Utilities** + - Adds improved readout from install_deps.py by @hhansen-bdai + - Fixes isaaclab.sh to detect isaacsim_version accurately 4.5 or >= 5.0 by @ooctipus + - Disables verbose printing in conftest.py by @ooctipus + - Updates pytest flags for isaacsim integration testing by @ben-johnston-nv + - Updates CodeOwners to be more fine-grained by @pascal-roth + - Fixes minor issues in CI by @nv-apoddubny + +Bug Fixes +--------- + +Core API +~~~~~~~~ + +* **Asset Interfaces** + - Fixes setting friction coefficients into PhysX in the articulation classes by @ossamaAhmed + - Sets joint_friction_coeff only for selected physx_env_ids by @ashwinvkNV +* **Manager Interfaces** + - Fixes observation space Dict for non-concatenated groups only keeping the last term by @CSCSX +* **MDP Terms** + - Fixes termination term effort limit check logic by @moribots + - Broadcasts environment ids inside ``mdp.randomize_rigid_body_com`` by @Foruck + - Fixes IndexError in reset_joints_by_scale and reset_joints_by_offset by @Creampelt + - Fixes ``terrain_out_of_bounds`` to return tensor instead of bool by @fan-ziqi + +Infrastructure +~~~~~~~~~~~~~~ + +- Fixes distributed training hanging issue by @kellyguo11 +- Disables generation of internal template when detecting isaaclab install via pip by @ooctipus +- Fixes typo in isaaclab.bat by @ooctipus +- Updates app pathing for user-provided rendering preset mode by @matthewtrepte + +Documentation +------------- + +- Adds documentation for Newton integration by @mpgussert +- Adapts FAQ section in docs with Isaac Sim open-sourcing by @Mayankm96 +- Changes checkpoint path in rsl-rl to an absolute path in documentation by @fan-ziqi +- Fixes MuJoCo link in docs by @fan-ziqi +- Adds client version direction to XR document by @lotusl-code +- Fixes broken link in doc by @kellyguo11 +- Fixes typo in list_envs.py script path by @fbeltrao +- Fixes Franka blueprint env ID in docs by @louislelay + +Breaking Changes +---------------- + +- Improves termination manager logging to report aggregated percentage of environments done due to each term by @ooctipus + + +v2.2.0 +====== + +Overview +-------- + +**Isaac Lab 2.2** brings major upgrades across simulation capabilities, tooling, and developer experience. It expands support for advanced physics features, new environments, and improved testing and documentation workflows. This release includes full compatibility with **Isaac Sim 5.0** as well as backwards compatibility with **Isaac Sim 4.5**. + +Key highlights of this release include: + +- **Enhanced Physics Support**: Updated `joint friction modeling using the latest PhysX APIs `_, added support for `spatial tendons `_, and improved surface gripper interactions. +- **New Environments for Imitation Learning**: Introduction of two new GR1 mimic environments, with domain randomization and visual robustness evaluation, and improved pick-and-place tasks. +- **New Contact-Rich Manipulation Tasks**: Integration of `FORGE `_ and `AutoMate `_ tasks for learning fine-grained contact interactions in simulation. +- **Teleoperation Improvements**: Teleoperation tools have been enhanced with configurable parameters and CloudXR runtime updates, including head tracking and hand tracking. +- **Performance & Usability Improvements**: Includes support for Stage in Memory and Cloning in Fabric for faster scene creation, new OVD recorder for large-scene GPU-based animation recording, and FSD (Fabric Scene Delegate) for improved rendering speed. +- **Improved Documentation**: The documentation has been extended and updated to cover new features, resolve common issues, and streamline setup, including updates to teleop system requirements, VS Code integration, and Python environment management. + +**Full Changelog**: https://github.com/isaac-sim/IsaacLab/compare/v2.1.1...v2.2.0 + + +Isaac Sim 5.0 Updates +--------------------- + +* Fixes rendering issues on Blackwell GPUs that previously resulted in overly noisy renders +* Updates Python version from 3.10 to 3.11 +* Updates PyTorch version to torch 2.7.0+cu128, which will include Blackwell support +* Drops official support for Ubuntu 20.04, we now officially support Ubuntu 22.04 and 24.04 Linux platforms +* Isaac Sim 5.0 no longer sets ``/app/player/useFixedTimeStepping=False`` by default. We now do this in Isaac Lab. +* :attr:`~isaaclab.sim.spawners.PhysicsMaterialCfg.improve_patch_friction` is now removed. The simulation will always behave as if this attribute is set to true. +* Native Livestreaming support has been removed. ``LIVESTREAM=1`` can now be used for WebRTC streaming over public networks and + ``LIVESTREAM=2`` for private and local networks with WebRTC streaming. +* Some assets in Isaac Sim have been reworked and restructured. Notably, the following asset paths were updated: + + * ``Robots/Ant/ant_instanceable.usd`` --> ``Robots/IsaacSim/Ant/ant_instanceable.usd`` + * ``Robots/Humanoid/humanoid_instanceable.usd`` --> ``Robots/IsaacSim/Humanoid/humanoid_instanceable.usd`` + * ``Robots/ANYbotics/anymal_instanceable.usd`` --> ``Robots/ANYbotics/anymal_c/anymal_c.usd`` + * ``Robots/ANYbotics/anymal_c.usd`` --> ``Robots/ANYbotics/anymal_c/anymal_c.usd`` + * ``Robots/Franka/franka.usd`` --> ``Robots/FrankaRobotics/FrankaPanda/franka.usd`` + * ``Robots/AllegroHand/allegro_hand_instanceable.usd`` --> ``Robots/WonikRobotics/AllegroHand/allegro_hand_instanceable.usd`` + * ``Robots/Crazyflie/cf2x.usd`` --> ``Robots/Bitcraze/Crazyflie/cf2x.usd`` + * ``Robots/RethinkRobotics/sawyer_instanceable.usd`` --> ``Robots/RethinkRobotics/Sawyer/sawyer_instanceable.usd`` + * ``Robots/ShadowHand/shadow_hand_instanceable.usd`` --> ``Robots/ShadowRobot/ShadowHand/shadow_hand_instanceable.usd`` + + +New Features +------------ + +* Adds FORGE tasks for contact-rich manipulation with force sensing to IsaacLab by @noseworm in #2968 +* Adds two new GR1 environments for IsaacLab Mimic by @peterd-NV +* Adds stack environment, scripts for Cosmos, and visual robustness evaluation by @shauryadNv +* Updates Joint Friction Parameters to Isaac Sim 5.0 PhysX APIs by @ossamaAhmed +* Adds support for spatial tendons by @ossamaAhmed +* Adds support and example for SurfaceGrippers by @AntoineRichard +* Adds support for stage in memory by @matthewtrepte +* Adds OVD animation recording feature by @matthewtrepte + +Improvements +------------ + +* Enables FSD for faster rendering by @nv-mm +* Sets rtx.indirectDiffuse.enabled to True for performance & balanced rendering presets by @matthewtrepte +* Changes runner for post-merge pipeline on self-hosted runners by @nv-apoddubny +* Fixes and improvements for CI pipeline by @nv-apoddubny +* Adds flaky annotation for tests by @kellyguo11 +* Updates Mimic test cases to pytest format by @peterd-NV +* Updates cosmos test files to use pytest by @shauryadNv +* Updates onnx and protobuf version due to vulnerabilities by @kellyguo11 +* Updates minimum skrl version to 1.4.3 by @Toni-SM +* Updates to Isaac Sim 5.0 by @kellyguo11 +* Updates docker CloudXR runtime version by @lotusl-code +* Removes xr rendering mode by @rwiltz +* Migrates OpenXRDevice from isaacsim.xr.openxr to omni.xr.kitxr by @rwiltz +* Implements teleop config parameters and device factory by @rwiltz +* Updates pick place env to use steering wheel asset by @peterd-NV +* Adds a CLI argument to set epochs for Robomimic training script by @peterd-NV + +Bug Fixes +--------- + +* Fixes operational space unit test to avoid pi rotation error by @ooctipus +* Fixes GLIBC errors with importing torch before AppLauncher by @kellyguo11 +* Fixes rendering preset by @matthewtrepte in cc0dab6cd50778507efc3c9c2d74a28919ab2092 +* Fixes callbacks with stage in memory and organize environment tests by @matthewtrepte +* Fixes XR and external camera bug with async rendering by @rwiltz +* Disables selection for rl_games when marl is selected for template generator by @ooctipus +* Adds check for .gitignore when generating template by @kellyguo11 +* Fixes camera obs errors in stack instance randomize envs by @peterd-NV +* Fixes parsing for play envs by @matthewtrepte +* Fixes issues with consecutive python exe calls in isaaclab.bat by @kellyguo11 +* Fixes spacemouse add callback function by @peterd-NV +* Fixes humanoid training with new velocity_limit_sim by @AntoineRichard + +Documentation +------------- + +* Adds note to mimic cosmos pipeline doc for eval by @shauryadNv +* Updates teleop docs for 2.2 release by @rwiltz +* Fixes outdated dofbot path in tutorial scripts by @mpgussert +* Updates docs for VS Code IntelliSense setup and JAX installation by @Toni-SM +* Updates Jax doc to overwrite version < 0.6.0 for torch by @kellyguo11 +* Adds docs for fabric cloning & stage in memory by @matthewtrepte +* Updates driver requirements to point to our official technical docs by @mpgussert +* Adds warning for ovd recording warning logs spam by @matthewtrepte +* Adds documentation to specify HOVER version and known GLIBCXX error by @kellyguo11 +* Updates teleop system requirements doc by @lotusl-code +* Add network requirements to cloudxr teleop doc by @lotusl-code + + +v2.1.1 +====== + +Overview +-------- + +This release has been in development over the past few months and includes a significant number of updates, +enhancements, and new features across the entire codebase. Given the volume of changes, we've grouped them +into relevant categories to improve readability. This version is compatible with +`NVIDIA Isaac Sim 4.5 `__. + +We appreciate the community's patience and contributions in ensuring quality and stability throughout. +We're aiming for more frequent patch releases moving forward to improve the developer experience. + +**Note:** This minor release does not include a Docker image or pip package. + +**Full Changelog:** https://github.com/isaac-sim/IsaacLab/compare/v2.1.0...v2.1.1 + +New Features +------------ + +* **Asset Interfaces** + * Adds ``position`` argument to set external forces and torques at different locations on the rigid body by @AntoineRichard + * Adds ``body_incoming_joint_wrench_b`` to ArticulationData field by @jtigue-bdai + * Allows selecting articulation root prim explicitly by @lgulich +* **Sensor Interfaces** + * Draws connection lines for FrameTransformer visualization by @Mayankm96 + * Uses visualization marker for connecting lines inside FrameTransformer by @bikcrum +* **MDP Terms** + * Adds ``body_pose_w`` and ``body_projected_gravity_b`` observations by @jtigue-bdai + * Adds joint effort observation by @jtigue-bdai + * Adds CoM randomization term to manager-based events by @shendredm + * Adds time-based mdp (observation) functions by @TheIndoorDad + * Adds curriculum mdp term to modify any environment parameters by @ooctipus +* **New Example Tasks** + * Adds assembly tasks from the Automate project by @yijieg + * Adds digit locomotion examples by @lgulich + +Improvements +------------ + +Core API +~~~~~~~~ + +* **Actuator Interfaces** + * Fixes implicit actuator limits configs for assets by @ooctipus + * Updates actuator configs for Franka arm by @reeceomahoney +* **Asset Interfaces** + * Optimizes getters of data inside asset classes by @Mayankm96 + * Adds method to set the visibility of the Asset's prims by @Mayankm96 +* **Sensor Interfaces** + * Updates to ray caster ray alignment and customizable drift sampling by @jsmith-bdai + * Extends ``ContactSensorData`` by ``force_matrix_w_history`` attribute by @bikcrum + * Adds IMU ``projected_gravity_b`` and optimizations by @jtigue-bdai +* **Manager Interfaces** + * Adds serialization to observation and action managers by @jsmith-bdai + * Adds concatenation dimension to ``ObservationManager`` by @pascal-roth + * Supports composite observation space with min/max by @ooctipus + * Changes counter update in ``CommandManager`` by @pascal-roth + * Integrates ``NoiseModel`` to manager-based workflows by @ozhanozen + * Updates ``NoiseModelWithAdditiveBias`` to apply per-feature bias by @ozhanozen + * Fixes :meth:`isaaclab.scene.reset_to` to accept ``None`` by @ooctipus + * Resets step reward buffer properly by @bikcrum +* **Terrain Generation** + * Custom ``TerrainGenerator`` support by @pascal-roth + * Adds terrain border options by @pascal-roth + * Platform height independent of object height by @jtigue-bdai + * Adds noise to ``MeshRepeatedObjectsTerrain`` by @jtigue-bdai +* **Simulation** + * Raises exceptions from SimContext init callbacks + * Applies ``semantic_tags`` to ground by @KumoLiu + * Sets ``enable_stabilization`` to false by default by @AntoineRichard + * Fixes deprecation for ``pxr.Semantics`` by @kellyguo11 +* **Math Utilities** + * Improves ``euler_xyz_from_quat`` by @ShaoshuSu + * Optimizes ``yaw_quat`` by @hapatel-bdai + * Changes ``quat_apply`` and ``quat_apply_inverse`` by @jtigue-bdai + * Changes ``quat_box_minus`` by @jtigue-bdai + * Adds ``quat_box_plus`` and ``rigid_body_twist_transform`` by @jtigue-bdai + * Adds math tests for transforms by @jtigue-bdai +* **General Utilities** + * Simplifies buffer validation for ``CircularBuffer`` by @Mayankm96 + * Modifies ``update_class_from_dict()`` by @ozhanozen + * Allows slicing from list values in dicts by @LinghengMeng @kellyguo11 + +Tasks API +~~~~~~~~~ + +* Adds support for ``module:task`` and gymnasium >=1.0 by @kellyguo11 +* Adds RL library error hints by @Toni-SM +* Enables hydra for ``play.py`` scripts by @ooctipus +* Fixes ray metric reporting and hangs by @ozhanozen +* Adds gradient clipping for distillation (RSL-RL) by @alessandroassirelli98 +* GRU-based RNNs ONNX export in RSL RL by @WT-MM +* Adds wandb support in rl_games by @ooctipus +* Optimizes SB3 wrapper by @araffin +* Enables SB3 checkpoint loading by @ooctipus +* Pre-processes SB3 env image obs-space for CNN pipeline by @ooctipus + +Infrastructure +~~~~~~~~~~~~~~ + +* **Dependencies** + * Updates torch to 2.7.0 with CUDA 12.8 by @kellyguo11 + * Updates gymnasium to 1.2.0 by @kellyguo11 + * Fixes numpy version to <2 by @ooctipus + * Adds license file for OSS by @kellyguo11 + * Sets robomimic to v0.4.0 by @masoudmoghani + * Upgrades pillow for Kit 107.3.1 by @ooctipus + * Removes protobuf upper pin by @kwlzn +* **Docker** + * Uses ``--gpus`` instead of Nvidia runtime by @yanziz-nvidia + * Adds docker name suffix parameter by @zoemcc + * Adds bash history support in docker by @AntoineRichard +* **Testing & Benchmarking** + * Switches unittest to pytest by @kellyguo11 @pascal-roth + * Adds training benchmark unit tests by @matthewtrepte + * Fixes env and IK test failures by @kellyguo11 +* **Repository Utilities** + * Adds URDF to USD batch conversion script by @hapatel-bdai + * Adds repository citation link by @kellyguo11 + * Adds pip install warning for internal templates by @ooctipus + +Bug Fixes +--------- + +Core API +~~~~~~~~ + +* **Actuator Interfaces** + * Fixes DCMotor clipping for negative power by @jtigue-bdai +* **Asset Interfaces** + * Fixes inconsistent data reads for body/link/com by @ooctipus +* **Sensor Interfaces** + * Fixes pose update in ``Camera`` and ``TiledCamera`` by @pascal-roth + * Fixes CPU fallback in camera.py by @renaudponcelet + * Fixes camera intrinsics logic by @jtigue-bdai +* **Manager Interfaces** + * Fixes ``ObservationManager`` buffer overwrite by @patrickhaoy + * Fixes term check in event manager by @miguelalonsojr + * Fixes ``Modifiers`` and history buffer bug by @ZiwenZhuang + * Fixes re-init check in ``ManagerBase`` by @Mayankm96 + * Fixes CPU collision filtering by @kellyguo11 + * Fixes imports in InteractiveScene/LiveVisualizer by @Mayankm96 + * Fixes image plot import in Live Visualizer by @pascal-roth +* **MDP Terms** + * Fixes CoM randomization shape mismatch by @shendredm + * Fixes visual prim handling in texture randomization by @KumoLiu + * Resets joint targets in ``reset_scene_to_default`` by @wghou + * Fixes joint limit terminations by @GiulioRomualdi + * Fixes joint reset scope in ``SceneEntityCfg`` by @ooctipus +* **Math Utilities** + * Fixes ``quat_inv()`` implementation by @ozhanozen + +Tasks API +~~~~~~~~~ + +* Fixes LSTM to ONNX export by @jtigue-bdai + +Example Tasks +~~~~~~~~~~~~~ + +* Removes contact termination redundancy by @louislelay +* Fixes memory leak in SDF by @leondavi +* Changes ``randomization`` to ``events`` in Digit envs by @fan-ziqi + +Documentation +------------- + +* Adds Isaac Sim version section to README by @kellyguo11 +* Adds physics performance guide by @kellyguo11 +* Adds jetbot tutorial to walkthrough docs by @mpgussert +* Changes quickstart install to conda by @mpgussert +* Fixes typo in library docs by @norbertcygiert +* Updates docs for conda, fabric, inference by @kellyguo11 +* Adds license/contributing updates with DCO by @kellyguo11 +* Updates pytest docs and help by @louislelay +* Adds actuator reference docs by @AntoineRichard +* Updates multi-GPU PyTorch setup docs by @Alex-Omar-Nvidia +* Removes deprecated env var in docs by @Kyu3224 + + +v2.1.0 +====== + +Overview +-------- + +This release introduces the official support for teleoperation using the Apple Vision Pro for collecting high-quality +and dexterous hand data, including the addition of bi-manual teleoperation and imitation learning workflows through Isaac Lab Mimic. + +We have also introduced new randomization methods for USD attributes, including the randomization of +scale, color, and textures. In this release, we updated RSL RL to v2.3.1, which introduces many additional features +including distributed training, student-teacher distillation, and recurrent student-teacher distillation. + +Additionally, we revamped the `Extension Template `_ +to include an automatic template generator tool from within the Isaac Lab repo. The extension template is +a powerful method for users to develop new projects in user-hosted repos, allowing for isolation from the core +Isaac Lab repo and changes. The previous IsaacLabExtensionTemplate repo showed a limited example pertaining only +to the Manager-based workflow and RSL RL. In the new template generator, users can choose from any supported +workflow and RL library, along with the desired RL algorithm. We will be deprecating the standalone +`IsaacLabExtensionTemplate `_ in the near future. + +NVIDIA has also released `HOVER `_ as an independent repo, hosting a neural whole body +controller for humanoids built on top of Isaac Lab. HOVER includes sim-to-real workflows for deployment on the Unitree +H1 robot, which we have also added a tutorial guide for the deployment process in the Isaac Lab documentation. + +**Full Changelog**: https://github.com/isaac-sim/IsaacLab/compare/v2.0.2...v2.1.0 + +New Features +------------ + +* Adds new external project / internal task template generator by @Toni-SM +* Adds dummy agents to the external task template generator by @louislelay +* Adds USD-level randomization mode to event manager by @Mayankm96 +* Adds texture and scale randomization event terms by @hapatel-bdai +* Adds replicator event for randomizing colors by @Mayankm96 +* Adds interactive demo script for H1 locomotion by @kellyguo11 +* Adds blueprint environment for Franka stacking mimic by @chengronglai +* Adds action clipping to rsl-rl wrapper by @Mayankm96 +* Adds Gymnasium spaces showcase tasks by @Toni-SM +* Add configs and adapt exporter for RSL-RL distillation by @ClemensSchwarke +* Adds support for head pose for Open XR device by @rwiltz +* Adds handtracking joints and retargetting pipeline by @rwiltz +* Adds documentation for openxr device and retargeters by @rwiltz +* Adds tutorial for training & validating HOVER policy using Isaac Lab by @pulkitg01 +* Adds rendering mode presets by @matthewtrepte +* Adds GR1 scene with Pink IK + Groot Mimic data generation and training by @ashwinvkNV +* Adds absolute pose franka cube stacking environment for mimic by @rwiltz +* Enables CloudXR OpenXR runtime container by @jaczhangnv +* Adds a quick start guide for quick installation and introduction by @mpgussert + +Improvements +------------ + +* Clarifies the default parameters in ArticulationData by @Mayankm96 +* Removes storage of meshes inside the TerrainImporter class by @Mayankm96 +* Adds more details about state in InteractiveScene by @Mayankm96 +* Mounts scripts to docker container by @Mayankm96 +* Initializes manager term classes only when sim starts by @Mayankm96 +* Updates to latest RSL-RL v2.3.0 release by @Mayankm96 +* Skips dependency installation for directories with no extension.toml by @jsmith-bdai +* Clarifies layer instructions in animation docs by @tylerlum +* Lowers the default number of environments for camera envs by @kellyguo11 +* Updates Rendering Mode guide in documentation by @matthewtrepte +* Adds task instruction UI support for mimic by @chengronglai +* Adds ExplicitAction class to track argument usage in AppLauncher by @nv-mhaselton +* Allows physics reset during simulation by @oahmednv +* Updates mimic to support multi-eef (DexMimicGen) data generation by @nvcyc + +Bug Fixes +--------- + +* Fixes default effort limit behavior for implicit actuators by @jtigue-bdai +* Fixes docstrings inconsistencies the code by @Bardreamaster +* Fixes missing stage recorder extension for animation recorder by @kellyguo11 +* Fixes ground height in factory environment by @louislelay +* Removes double definition of render settings by @pascal-roth +* Fixes device settings in env tutorials by @Mayankm96 +* Changes default ground color back to dark grey by @Mayankm96 +* Initializes extras dict before loading managers by @kousheekc +* Fixes typos in development.rst by @vi3itor +* Fixes SE gamepad omniverse subscription API by @PinkPanther-ny +* Fixes modify_action_space in RslRlVecEnvWrapper by @felipemohr +* Fixes distributed setup in benchmarking scripts by @kellyguo11 +* Fixes typo ``RF_FOOT`` to ``RH_FOOT`` in tutorials by @likecanyon +* Checks if success term exists before recording in RecorderManager by @peterd-NV +* Unsubscribes from debug vis handle when timeline is stopped by @jsmith-bdai +* Fixes wait time in ``play.py`` by using ``env.step_dt`` by @tylerlum +* Fixes 50 series installation instruction to include torchvision by @kellyguo11 +* Fixes importing MotionViewer from external scripts by @T-K-233 +* Resets cuda device after each app.update call by @kellyguo11 +* Fixes resume flag in rsl-rl cli args by @Mayankm96 + + +v2.0.2 +====== + +Overview +-------- + +This patch release focuses on improving actuator configuration and fixing key bugs while reverting unintended +behavioral changes from v2.0.1. **We strongly recommend switching** to this new version if you're migrating +from a pre-2.0 release of Isaac Lab. + +**Key Changes:** + +* **Actuator Limit Handling**: Introduced :attr:`~isaaclab.actuators.ActuatorBaseCfg.velocity_limit_sim` + and :attr:`~isaaclab.actuators.ActuatorBaseCfg.effort_limit_sim` to clearly distinguish + simulation solver limits from actuator model constraints. Reverted implicit actuator velocity limits + to pre-v2.0 behavior +* **Simulation configuration update**: Removed :attr:`~isaaclab.sim.SimulationCfg.disable_contact_processing` + flag to simplify behavior +* **Rendering configuration update**: Reverted to pre-2.0 configuration to improve the quality of the + render product +* **Tiled camera fixes**: Fixed motion vector processing and added a hotfix for retrieving semantic + images from the :class:`~isaaclab.sensors.TiledCamera` +* **WebRTC Support**: Added IP specification for live-streaming + +**Full Changelog**: https://github.com/isaac-sim/IsaacLab/compare/v2.0.1...v2.0.2 + +New Features +------------ + +* Adds :attr:`~isaaclab.actuators.ActuatorBaseCfg.velocity_limit_sim` and + :attr:`~isaaclab.actuators.ActuatorBaseCfg.effort_limit_sim` to actuator. +* Adds WebRTC livestreaming support with IP specification. + +Improvements +------------ + +* Adds guidelines and examples for code contribution +* Separates joint state setters inside Articulation class +* Implements deterministic evaluation for skrl's multi-agent algorithms +* Adds new extensions to ``pyproject.toml`` +* Updates docs on Isaac Sim binary installation path and VSCode integration +* Removes remaining deprecation warning in RigidObject deprecation +* Adds security and show&tell notes to documentation +* Updates docs for segmentation and 50 series GPUs +* Adds workaround for semantic segmentation issue with tiled camera + +Bug Fixes +--------- + +* Fixes offset from object obs for Franka stacking env when using parallel envs +* Adds scene update to ManagerBasedEnv, DirectRLEnv, and MARL envs initialization +* Loads actuator networks in eval() mode to prevent gradients +* Fixes instructions on importing ANYmal URDF in docs +* Fixes setting of root velocities in the event term :func:`~isaaclab.mdp.reset_root_state_from_terrain` +* Fixes ``activate_contact_sensors`` when using :class:`~isaaclab.sim.MultiUsdFileCfg` +* Fixes misalignment in motion vectors from :class:`~isaaclab.sim.TiledCamera` +* Sets default tensor device to CPU for Camera rot buffer + +Breaking Changes +---------------- + +* Reverts the setting of joint velocity limits for implicit actuators +* Removes ``disable_contact_processing`` flag from SimulationContext +* Reverts to old render settings in kit experience files + +Migration Guide +--------------- + +.. attention:: + + We strongly recommend reviewing the details to fully understand the change in behavior, + as it may impact the deployment of learned policies. Please open an issue on GitHub if + you face any problems. + + +Introduction of simulation's effort and velocity limits parameters in ActuatorBaseCfg +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We have introduced the configuration variables :attr:`~isaaclab.actuators.ActuatorBaseCfg.velocity_limit_sim` +and :attr:`~isaaclab.actuators.ActuatorBaseCfg.effort_limit_sim` to the +:class:`isaaclab.actuators.ActuatorBaseCfg` to allow users to set the **simulation** joint velocity +and effort limits through the actuator configuration class. + +Previously, we were overusing the attributes :attr:`~isaaclab.actuators.ActuatorBaseCfg.velocity_limit` +and :attr:`~isaaclab.actuators.ActuatorBaseCfg.effort_limit` inside the actuator configuration. A series +of changes in-between led to a regression from v1.4.0 to v2.0.1 release of IsaacLab. To make this +clearer to understand, we note the change in their behavior in a tabular form: + ++---------------+-------------------------+--------------------------------------------------------------------+----------------------------------------------------------------+ +| Actuator Type | Attribute | v1.4.0 Behavior | v2.0.1 Behavior | ++---------------+-------------------------+--------------------------------------------------------------------+----------------------------------------------------------------+ +| Implicit | :attr:`velocity_limit` | Ignored, not set into simulation | Set into simulation | +| Implicit | :attr:`effort_limit` | Set into simulation | Set into simulation | +| Explicit | :attr:`velocity_limit` | Used by actuator models (e.g., DC Motor), not set into simulation | Used by actuator models (e.g., DC Motor), set into simulation | +| Explicit | :attr:`effort_limit` | Used by actuator models, not set into simulation | Used by actuator models, set into simulation | ++---------------+-------------------------+--------------------------------------------------------------------+----------------------------------------------------------------+ + +Setting the limits from the configuration into the simulation directly affects the behavior +of the underlying physics engine solver. This impact is particularly noticeable when velocity +limits are too restrictive, especially in joints with high stiffness, where it becomes easier +to reach these limits. As a result, the change in behavior caused previously trained policies +to not function correctly in IsaacLab v2.0.1. + +Consequently, we have reverted back to the prior behavior and added :attr:`velocity_limit_sim` and +:attr:`effort_limit_sim` attributes to make it clear that setting those parameters means +changing solver's configuration. The new behavior is as follows: + ++----------------------------+--------------------------------------------------------+-------------------------------------------------------------+ +| Attribute | Implicit Actuator | Explicit Actuator | ++============================+========================================================+=============================================================+ +| :attr:`velocity_limit` | Ignored, not set into simulation | Used by the model (e.g., DC Motor), not set into simulation | +| :attr:`effort_limit` | Set into simulation (same as :attr:`effort_limit_sim`) | Used by the models, not set into simulation | +| :attr:`velocity_limit_sim` | Set into simulation | Set into simulation | +| :attr:`effort_limit_sim` | Set into simulation (same as :attr:`effort_limit`) | Set into simulation | ++----------------------------+--------------------------------------------------------+-------------------------------------------------------------+ + +Users are advised to use the ``xxx_sim`` flag if they want to directly modify the solver limits. + +Removal of ``disable_contact_processing`` flag in ``SimulationCfg`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We have now removed the ``disable_contact_processing`` flag from the :class:`isaaclab.sim.SimulationCfg` +to not have the user worry about these intricacies of the simulator. The flag is always True by +default unless a contact sensor is created (which will internally set this flag to False). + +Previously, the flag ``disable_contact_processing`` led to confusion about its +behavior. As the name suggests, the flag controls the contact reporting from the +underlying physics engine, PhysX. Disabling this flag (note the double negation) +means that PhysX collects the contact information from its solver and allows +reporting them to the user. Enabling this flag means this operation is not performed and +the overhead of it is avoided. + +Many of our examples (for instance, the locomotion environments) were setting this +flag to True which meant the contacts should **not** get reported. However, this issue +was not noticed earlier since GPU simulation bypasses this flag, and only CPU simulation +gets affected. Running the same examples on CPU device led to different behaviors +because of this reason. + +Existing users, who currently set this flag themselves, should receive a deprecated +warning mentioning the removal of this flag and the switch to the new default behavior. + +Switch to older rendering settings to improve render quality +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +With the IsaacLab 2.0.0 release, we switched to new render settings aimed at improving +tiled-rendering performance, but at the cost of reduced rendering quality. This change +particularly affected dome lighting in the scene, which is the default in many of our examples. + +As reported by several users, this change negatively impacted render quality, even in +cases where it wasn't necessary (such as when recording videos of the simulation). In +response to this feedback, we have reverted to the previous render settings by default +to restore the quality users expected. + +For users looking to trade render quality for speed, we will provide guidelines in the future. + + +v2.0.1 +====== + +Overview +-------- + +This release contains a small set of fixes and improvements. + +The main change was to maintain combability with the updated library name for RSL RL, which breaks the previous +installation methods for Isaac Lab. This release provides the necessary fixes and updates in Isaac Lab to accommodate +for the name change and maintain compatibility with installation for RSL RL. + +**Full Changelog**: https://github.com/isaac-sim/IsaacLab/compare/v2.0.0...v2.0.1 + +Improvements +------------ + +* Switches to RSL-RL install from PyPI by @Mayankm96 +* Updates the script path in the document by @fan-ziqi +* Disables extension auto-reload when saving files by @kellyguo11 +* Updates documentation for v2.0.1 installation by @kellyguo11 + +Bug Fixes +--------- + +* Fixes timestamp of com and link buffers when writing articulation pose to sim by @Jackkert +* Fixes incorrect local documentation preview path in xdg-open command by @louislelay +* Fixes no matching distribution found for rsl-rl (unavailable) by @samibouziri +* Fixes reset of sensor drift inside the RayCaster sensor by @zoctipus + +v2.0.0 +====== + +Overview +-------- + +Isaac Lab 2.0 brings some exciting new features, including a new addition to the Imitation Learning workflow with +the **Isaac Lab Mimic** extension. + +Isaac Lab Mimic provides the ability to automatically generate additional trajectories based on just a few human +collected demonstrations, allowing for larger training datasets with less human effort. This work is based on the +`MimicGen `_ work for Scalable Robot Learning using Human Demonstrations. + +Additionally, we introduced a new set of AMP tasks based on +`Adversarial Motion Priors `_, training humanoid robots to walk, run, +and dance. + +Along with Isaac Lab 2.0, Isaac Sim 4.5 brings several new and breaking changes, including a full refactor of the +Isaac Sim extensions, an improved URDF importer, an update to the PyTorch dependency to version 2.5.1, and many +fixes for tiled rendering that now supports multiple tiled cameras at different resolutions. + +To follow the refactoring in Isaac Sim, we made similar refactoring and restructuring changes to Isaac Lab. +These breaking changes will no longer be compatible with previous Isaac Sim versions. + +.. attention:: + + Please make sure to update to Isaac Sim 4.5 when using the Isaac Lab 2.0 release. + +**Full Changelog**: https://github.com/isaac-sim/IsaacLab/compare/v1.4.1...v2.0.0 + +Highlights from the Isaac Sim 4.5 release +----------------------------------------- + +* Support for multiple ``TiledCamera`` instances and varying resolutions +* Improved rendering performance by up to 1.2x +* Faster startup time through optimizations in the Cloner class that improves startup time by 30% +* Enhanced OmniPVD for debugging physics simulation, enabling capturing reinforcement learning simulation +* Physics simulation performance optimizations improving throughput of up to 70% +* Physics support for dedicated cylinder and cone geometry designed for robot wheels that is fully GPU accelerated +* A new physics GPU filtering mechanism allowing co-location of reinforcement learning environments at the + origin with minimal performance loss for scenes with limited collider counts +* Improvements in simulation stability for mimic joints at high joint gains + +New Features +------------ + +* Adds humanoid AMP tasks for direct workflow by @Toni-SM +* Adds Isaac Lab Mimic based on MimicGen data generation for Imitation Learning by @peterd-NV @nvcyc @ashwinvkNV @karsten-nvidia +* Adds consolidated demo script for showcasing recording and mimic dataset generation in real-time in one simulation script by @nvcyc +* Adds Franka stacking environment for GR00T mimic by @peterd-NV @nvcyc +* Adds option to filter collisions and real-time playback by @kellyguo11 + +Improvements +------------ + +* Adds a tutorial for policy inference in a prebuilt USD scene by @oahmednv +* Adds unit tests for multi-tiled cameras by @matthewtrepte +* Updates render setting defaults for better quality by @kellyguo11 +* Adds a flag to wait for texture loading completion when reset by @oahmednv +* Adds pre-trained checkpoints and tools for generating and uploading checkpoints by @nv-cupright +* Adds new denoiser optimization flags for rendering by @kellyguo11 +* Updates torch to 2.5.1 by @kellyguo11 + +Bug Fixes +--------- + +* Fixes external force buffers to set to zero when no forces/torques are applied by @matthewtrepte +* Fixes RSL-RL package name in ``setup.py`` according to PyPI installation by @samibouziri + +Breaking Changes +---------------- + +* Updates the URDF and MJCF importers for Isaac Sim 4.5 by @Dhoeller19 +* Renames Isaac Lab extensions and folders by @kellyguo11 +* Restructures extension folders and removes old imitation learning scripts by @kellyguo11 +* Renames default conda and venv Python environment from ``isaaclab`` to ``env_isaaclab`` by @Toni-SM + +.. attention:: + + We have identified a breaking feature for semantic segmentation and instance segmentation when using + ``Camera`` and ``TiledCamera`` with instanceable assets. Since the Isaac Sim 4.5 / Isaac Lab 2.0 release, semantic and instance + segmentation outputs only render the first tile correctly and produces blank outputs for the remaining tiles. + We will be introducing a workaround for this fix to remove scene instancing if semantic segmentation or instance + segmentation is required for ``Camera`` and ``TiledCamera`` until we receive a proper fix from Omniverse as part of the next Isaac Sim release. + +Migration Guide +--------------- + +Renaming of Isaac Sim Extensions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Previously, Isaac Sim extensions have been following the convention of ``omni.isaac.*``, +such as ``omni.isaac.core``. In Isaac Sim 4.5, Isaac Sim extensions have been renamed +to use the prefix ``isaacsim``, replacing ``omni.isaac``. In addition, many extensions +have been renamed and split into multiple extensions to prepare for a more modular +framework that can be customized by users through the use of app templates. + +Notably, the following commonly used Isaac Sim extensions in Isaac Lab are renamed as follow: + +* ``omni.isaac.cloner`` --> :mod:`isaacsim.core.cloner` +* ``omni.isaac.core.prims`` --> :mod:`isaacsim.core.prims` +* ``omni.isaac.core.simulation_context`` --> :mod:`isaacsim.core.api.simulation_context` +* ``omni.isaac.core.utils`` --> :mod:`isaacsim.core.utils` +* ``omni.isaac.core.world`` --> :mod:`isaacsim.core.api.world` +* ``omni.isaac.kit.SimulationApp`` --> :mod:`isaacsim.SimulationApp` +* ``omni.isaac.ui`` --> :mod:`isaacsim.gui.components` + +Renaming of the URDF and MJCF Importers +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Starting from Isaac Sim 4.5, the URDF and MJCF importers have been renamed to be more consistent +with the other extensions in Isaac Sim. The importers are available on isaac-sim GitHub +as open source projects. + +Due to the extension name change, the Python module names have also been changed: + +* URDF Importer: :mod:`isaacsim.asset.importer.urdf` (previously :mod:`omni.importer.urdf`) +* MJCF Importer: :mod:`isaacsim.asset.importer.mjcf` (previously :mod:`omni.importer.mjcf`) + +From the Isaac Sim UI, both URDF and MJCF importers can now be accessed directly from the File > Import +menu when selecting a corresponding .urdf or .xml file in the file browser. + +Changes in URDF Importer +~~~~~~~~~~~~~~~~~~~~~~~~ + +Isaac Sim 4.5 brings some updates to the URDF Importer, with a fresh UI to allow for better configurations +when importing robots from URDF. As a result, the Isaac Lab URDF Converter has also been updated to +reflect these changes. The :class:`isaaclab.sim.converters.UrdfConverterCfg` includes some new settings, +such as :class:`~isaaclab.sim.converters.JointDriveCfg.PDGainsCfg` +and :class:`~isaaclab.sim.converters.JointDriveCfg.NaturalFrequencyGainsCfg` classes for configuring +the gains of the drives. + +One breaking change to note is that the :attr:`~isaaclab.sim.converters.UrdfConverterCfg.JointDriveCfg.gains` +attribute must be of class type :class:`~isaaclab.sim.converters.JointDriveCfg.PDGainsCfg` or +:class:`~isaaclab.sim.converters.JointDriveCfg.NaturalFrequencyGainsCfg`. + +The stiffness of the :class:`~isaaclab.sim.converters.JointDriveCfg.PDGainsCfg` must be specified, as such: + +.. code-block:: python + + joint_drive=sim_utils.UrdfConverterCfg.JointDriveCfg( + gains=sim_utils.UrdfConverterCfg.JointDriveCfg.PDGainsCfg(stiffness=None, damping=None) + ) + + +The :attr:`~isaaclab.sim.converters.JointDriveCfg.NaturalFrequencyGainsCfg.natural_frequency` attribute must +be specified for :class:`~isaaclab.sim.converters.JointDriveCfg.NaturalFrequencyGainsCfg`. + + +Renaming of Isaac Lab Extensions and Folders +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Corresponding to Isaac Sim 4.5 changes, we have also made some updates to the Isaac Lab directories and extensions. +All extensions that were previously under ``source/extensions`` are now under the ``source/`` directory directly. +The ``source/apps`` and ``source/standalone`` folders have been moved to the root directory and are now called +``apps/`` and ``scripts/``. + +Isaac Lab extensions have been renamed to: + +* ``omni.isaac.lab`` --> :mod:`isaaclab` +* ``omni.isaac.lab_assets`` --> :mod:`isaaclab_assets` +* ``omni.isaac.lab_tasks`` --> :mod:`isaaclab_tasks` + +In addition, we have split up the previous ``source/standalone/workflows`` directory into ``scripts/imitation_learning`` +and ``scripts/reinforcement_learning`` directories. The RSL RL, Stable-Baselines, RL_Games, SKRL, and Ray directories +are under ``scripts/reinforcement_learning``, while Robomimic and the new Isaac Lab Mimic directories are under +``scripts/imitation_learning``. + +To assist with the renaming of Isaac Lab extensions in your project, we have provided a +`simple script `_ that will traverse +through the ``source`` and ``docs`` directories in your local Isaac Lab project and replace any instance of the renamed +directories and imports. **Please use the script at your own risk as it will overwrite source files directly.** + + +Restructuring of Isaac Lab Extensions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +With the introduction of :mod:`isaaclab_mimic`, designed for supporting data generation workflows for imitation learning, +we have also split out the previous ``wrappers`` folder under ``isaaclab_tasks`` to its own module, named :mod:`isaaclab_rl`. +This new extension will contain reinforcement learning specific wrappers for the various RL libraries supported by Isaac Lab. + +The new :mod:`isaaclab_mimic` extension will also replace the previous imitation learning scripts under the ``robomimic`` folder. +We have removed the old scripts for data collection and dataset preparation in favor of the new mimic workflow. For users +who prefer to use the previous scripts, they will be available in previous release branches. + +Additionally, we have also restructured the :mod:`isaaclab_assets` extension to be split into ``robots`` and ``sensors`` +subdirectories. This allows for clearer separation between the pre-defined configurations provided in the extension. + +As an example, the following import: + +.. code-block:: python + + from omni.isaac.lab_assets.anymal import ANYMAL_C_CFG + +should be replaced with: + +.. code-block:: python + + from isaaclab_assets.robots.anymal import ANYMAL_C_CFG + + +v1.4.1 +====== + +Overview +-------- + +This release contains a set of improvements and bug fixes. + +Most importantly, we reverted one of the `changes from the previous release `_ +to ensure the training throughput performance remains the same. + +**Full Changelog**: https://github.com/isaac-sim/IsaacLab/compare/v1.4.0...v1.4.1 + +This is the **final release compatible with Isaac Sim 4.2**. The next release will target Isaac Sim 4.5, +which introduces breaking changes that will make Isaac Lab incompatible with earlier versions of Isaac Sim. + +New Features +------------ + +* Adds documentation and demo script for IMU sensor by @mpgussert + +Improvements +------------ + +* Removes deprecation for root_state_w properties and setters by @jtigue-bdai +* Fixes MARL workflows for recording videos during training/inferencing by @Rishi-V +* Adds body tracking option to ViewerCfg by @KyleM73 +* Fixes the ``joint_parameter_lookup`` type in ``RemotizedPDActuatorCfg`` to support list format by @fan-ziqi +* Updates pip installation documentation to clarify options by @steple +* Fixes docstrings in Articulation Data that report wrong return dimension by @zoctipus +* Fixes documentation error for PD Actuator by @kellyguo11 +* Clarifies ray documentation and fixes minor issues by @garylvov +* Updates code snippets in documentation to reference scripts by @mpgussert +* Adds dict conversion test for ActuatorBase configs by @mschweig + +Bug Fixes +--------- + +* Fixes JointAction not preserving order when using all joints by @T-K-233 +* Fixes event term for pushing root by setting velocity by @Mayankm96 +* Fixes error in Articulation where ``default_joint_stiffness`` and ``default_joint_damping`` are not correctly set for implicit actuator by @zoctipus +* Fixes action reset of ``pre_trained_policy_action`` in navigation environment by @nicolaloi +* Fixes rigid object's root com velocities timestamp check by @ori-gadot +* Adds interval resampling on event manager's reset call by @Mayankm96 +* Corrects calculation of target height adjustment based on sensor data by @fan-ziqi +* Fixes infinite loop in ``repeated_objects_terrain`` method by @nicolaloi +* Fixes issue where the indices were not created correctly for articulation setters by @AntoineRichard + + +v1.4.0 +====== + +Overview +-------- + +Due to a great amount of amazing updates, we are putting out one more Isaac Lab release based off of Isaac Sim 4.2. +This release contains many great new additions and bug fixes, including several new environments, distributed training +and hyperparameter support with Ray, new live plot feature for Manager-based environments, and more. + +We will now spend more focus on the next Isaac Lab release geared towards the new Isaac Sim 4.5 release coming +soon. The upcoming release will contain breaking changes in both Isaac Lab and Isaac Sim and breaks backwards +compatibility, but will come with many great fixes and improvements. + +**Full Changelog**: https://github.com/isaac-sim/IsaacLab/compare/v1.3.0...v1.4.0 + +New Features +------------ + +* Adds Factory contact-rich manipulation tasks to IsaacLab by @noseworm +* Adds a Franka stacking ManagerBasedRLEnv by @peterd-NV +* Adds recorder manager in manager-based environments by @nvcyc +* Adds Ray Workflow: Multiple Run Support, Distributed Hyperparameter Tuning, and Consistent Setup Across Local/Cloud by @glvov-bdai +* Adds ``OperationSpaceController`` to docs and tests and implement corresponding action/action_cfg classes by @ozhanozen +* Adds null-space control option within ``OperationSpaceController`` by @ozhanozen +* Adds observation term history support to Observation Manager by @jtigue-bdai +* Adds live plots to managers by @pascal-roth + +Improvements +------------ + +* Adds documentation and example scripts for sensors by @mpgussert +* Removes duplicated ``TerminationsCfg`` code in G1 and H1 RoughEnvCfg by @fan-ziqi +* Adds option to change the clipping behavior for all Cameras and unifies the default by @pascal-roth +* Adds check that no articulation root API is applied on rigid bodies by @lgulich +* Adds RayCaster rough terrain base height to reward by @Andy-xiong6 +* Adds position threshold check for state transitions by @DorsaRoh +* Adds clip range for JointAction by @fan-ziqi + +Bug Fixes +--------- + +* Fixes noise_model initialized in direct_marl_env by @NoneJou072 +* Fixes entry_point and kwargs in isaaclab_tasks README by @fan-ziqi +* Fixes syntax for checking if pre-commit is installed in isaaclab.sh by @louislelay +* Corrects fisheye camera projection types in spawner configuration by @command-z-z +* Fixes actuator velocity limits propagation down the articulation root_physx_view by @jtigue-bdai +* Computes Jacobian in the root frame inside the ``DifferentialInverseKinematicsAction`` class by @zoctipus +* Adds transform for mesh_prim of ray caster sensor by @clearsky-mio +* Fixes configclass dict conversion for torch tensors by @lgulich +* Fixes error in apply_actions method in ``NonHolonomicAction`` action term. by @KyleM73 +* Fixes outdated sensor data after reset by @kellyguo11 +* Fixes order of logging metrics and sampling commands in command manager by @Mayankm96 + +Breaking Changes +---------------- + +* Refactors pose and velocities to link frame and COM frame APIs by @jtigue-bdai + + +v1.3.0 +====== + +Overview +-------- + +This release will be a final release based on Isaac Sim 4.2 before the transition to Isaac Sim 4.5, which will +likely contain breaking changes and no longer backwards compatible with Isaac Sim 4.2 and earlier. In this release, +we introduce many features, improvements, and bug fixes, including IMU sensors, support for various types of +gymnasium spaces, manager-based perception environments, and more. + +**Full Changelog**: https://github.com/isaac-sim/IsaacLab/compare/v1.2.0...v1.3.0 + +New Features +------------ + +* Adds ``IMU`` sensor by @pascal-roth +* Add Camera Benchmark Tool and Allow Correct Unprojection of distance_to_camera depth image by @glvov-bdai +* Creates Manager Based Cartpole Vision Example Environments by @glvov-bdai +* Adds image extracted features observation term and cartpole examples for it by @glvov-bdai +* Supports other gymnasium spaces in Direct workflow by @Toni-SM +* Adds configuration classes for spawning different assets at prim paths by @Mayankm96 +* Adds a rigid body collection class by @Dhoeller19 +* Adds option to scale/translate/rotate meshes in the ``mesh_converter`` by @pascal-roth +* Adds event term to randomize gains of explicit actuators by @MoreTore +* Adds Isaac Lab Reference Architecture documentation by @OOmotuyi + +Improvements +------------ + +* Expands functionality of FrameTransformer to allow multi-body transforms by @jsmith-bdai +* Inverts SE-2 keyboard device actions (Z, X) for yaw command by @riccardorancan +* Disables backward pass compilation of warp kernels by @Mayankm96 +* Replaces TensorDict with native dictionary by @Toni-SM +* Improves omni.isaac.lab_tasks loading time by @Toni-SM +* Caches PhysX view's joint paths when processing fixed articulation tendons by @Toni-SM +* Replaces hardcoded module paths with ``__name__`` dunder by @Mayankm96 +* Expands observation term scaling to support list of floats by @pascal-roth +* Removes extension startup messages from the Simulation App by @Mayankm96 +* Adds a render config to the simulation and tiledCamera limitations to the docs by @kellyguo11 +* Adds Kit command line argument support by @kellyguo11 +* Modifies workflow scripts to generate random seed when seed=-1 by @kellyguo11 +* Adds benchmark script to measure robot loading by @Mayankm96 +* Switches from ``carb`` to ``omni.log`` for logging by @Mayankm96 +* Excludes cache files from vscode explorer by @Divelix +* Adds versioning to the docs by @sheikh-nv +* Adds better error message for invalid actuator parameters by @lgulich +* Updates tested docker and apptainer versions for cluster deployment by @pascal-roth +* Removes ``ml_archive`` as a dependency of ``omni.isaac.lab`` extension by @fan-ziqi +* Adds a validity check for configclasses by @Dhoeller19 +* Ensures mesh name is compatible with USD convention in mesh converter by @fan-ziqi +* Adds sanity check for the term type inside the command manager by @command-z-z +* Allows configclass ``to_dict`` operation to handle a list of configclasses by @jtigue-bdai + +Bug Fixes +--------- + +* Disables replicate physics for deformable teddy lift environment by @Mayankm96 +* Fixes Jacobian joint indices for floating base articulations by @lorenwel +* Fixes setting the seed from CLI for RSL-RL by @kaixi287 +* Fixes camera MDP term name and reprojection docstrings by @Mayankm96 +* Fixes deprecation notice for using ``pxr.Semantics`` by @Mayankm96 +* Fixes scaling of default ground plane by @kellyguo11 +* Fixes Isaac Sim executable on pip installation by @Toni-SM +* Passes device from CLI args to simulation config in standalone scripts by @Mayankm96 +* Fixes the event for randomizing rigid body material by @pascal-roth +* Fixes the ray_caster_camera tutorial script when saving the data by @mpgussert +* Fixes running the docker container when the DISPLAY env variable is not defined by @GiulioRomualdi +* Fixes default joint pos when setting joint limits by @kellyguo11 +* Fixes device propagation for noise and adds noise tests by @jtigue-bdai +* Removes additional sbatch and fixes default profile in cluster deployment by @pascal-roth +* Fixes the checkpoint loading error in RSL-RL training script by @bearpaw +* Fixes pytorch broadcasting issue in ``EMAJointPositionToLimitsAction`` by @bearpaw +* Fixes body IDs selection when computing ``feet_slide`` reward for locomotion-velocity task by @dtc103 +* Fixes broken URLs in markdown files by @DorsaRoh +* Fixes ``net_arch`` in ``sb3_ppo_cfg.yaml`` for Isaac-Lift-Cube-Franka-v0 task by @LinghengMeng + + +v1.2.0 +====== + +Overview +-------- + +We leverage the new release of Isaac Sim, 4.2.0, and bring RTX-based tiled rendering, support for multi-agent +environments, and introduce many bug fixes and improvements. + +Additionally, we have published an example for generating rewards using an LLM based on +`Eureka `_, available here: https://github.com/isaac-sim/IsaacLabEureka + +**Full Changelog**: https://github.com/isaac-sim/IsaacLab/compare/v1.1.0...v1.2.0 + +New Features +------------ + +* Adds RTX-based tiled rendering. This improves the overall rendering speed and quality. +* Adds the direct workflow perceptive Shadowhand Cube Repose environment ``Isaac-Repose-Cube-Shadow-Vision-Direct-v0`` by @kellyguo11. +* Adds support for multi-agent environments with the Direct workflow, with support for MAPPO and IPPO in SKRL by @Toni-SM +* Adds the direct workflow multi-agent environments ``Isaac-Cart-Double-Pendulum-Direct-v0`` and ``Isaac-Shadow-Hand-Over-Direct-v0`` by @Toni-SM +* Adds throughput benchmarking scripts for the different learning workflows by @kellyguo11 +* Adds results for the benchmarks in the documentation + `here `__ + for different types of hardware by @kellyguo11 +* Adds the direct workflow Allegro hand environment by @kellyguo11 +* Adds video recording to the play scripts in RL workflows by @j3soon +* Adds comparison tables for the supported RL libraries + `here `__ by @kellyguo11 +* Add APIs for deformable asset by @masoudmoghani +* Adds support for MJCF converter by @qqqwan +* Adds a function to define camera configs through intrinsic matrix by @pascal-roth +* Adds configurable modifiers to observation manager by @jtigue-bdai +* Adds the Hydra configuration system for RL training by @Dhoeller19 + +Improvements +------------ + +* Uses PhysX accelerations for rigid body acceleration data by @Mayankm96 +* Adds documentation on the frames for asset data by @Mayankm96 +* Renames Unitree configs in locomotion tasks to match properly by @Mayankm96 +* Adds option to set the height of the border in the ``TerrainGenerator`` by @pascal-roth +* Adds a cli arg to ``run_all_tests.py`` for testing a selected extension by @jsmith-bdai +* Decouples rigid object and articulation asset classes by @Mayankm96 +* Adds performance optimizations for domain randomization by @kellyguo11 +* Allows having hybrid dimensional terms inside an observation group by @Mayankm96 +* Adds a flag to preserve joint order inside ``JointActionCfg`` action term by @xav-nal +* Adds the ability to resume training from a checkpoint with rl_games by @sizsJEon +* Adds windows configuration to VS code tasks by @johnBuffer +* Adapts A and D button bindings in the keyboard device by @zoctipus +* Uses ``torch.einsum`` for quat_rotate and quat_rotate_inverse operations by @dxyy1 +* Expands on articulation test for multiple instances and devices by @jsmith-bdai +* Adds setting of environment seed at initialization by @Mayankm96 +* Disables default viewport when headless but cameras are enabled by @kellyguo11 +* Simplifies the return type for ``parse_env_cfg`` method by @Mayankm96 +* Simplifies the if-elses inside the event manager apply method by @Mayankm96 + +Bug Fixes +--------- + +* Fixes rendering frame delays. Rendered images now faithfully represent the latest state of the physics scene. + We added the flag ``rerender_on_reset`` in the environment configs to toggle an additional render step when a + reset happens. When activated, the images/observation always represent the latest state of the environment, but + this also reduces performance. +* Fixes ``wrap_to_pi`` function in math utilities by @Mayankm96 +* Fixes setting of pose when spawning a mesh by @masoudmoghani +* Fixes caching of the terrain using the terrain generator by @Mayankm96 +* Fixes running train scripts when rsl_rl is not installed by @Dhoeller19 +* Adds flag to recompute inertia when randomizing the mass of a rigid body by @Mayankm96 +* Fixes support for ``classmethod`` when defining a configclass by @Mayankm96 +* Fixes ``Sb3VecEnvWrapper`` to clear buffer on reset by @EricJin2002 +* Fixes venv and conda pip installation on windows by @kellyguo11 +* Sets native livestream extensions to Isaac Sim 4.1-4.0 defaults by @jtigue-bdai +* Defaults the gym video recorder fps to match episode decimation by @ozhanozen +* Fixes the event manager's apply method by @kellyguo11 +* Updates camera docs with world units and introduces new test for intrinsics by @pascal-roth +* Adds the ability to resume training from a checkpoint with rl_games by @sizsJEon + +Breaking Changes +---------------- + +* Simplifies device setting in SimulationCfg and AppLauncher by @Dhoeller19 +* Fixes conflict in teleop-device command line argument in scripts by @Dhoeller19 +* Converts container.sh into Python utilities by @hhansen-bdai +* Drops support for ``TiledCamera`` for Isaac Sim 4.1 + +Migration Guide +--------------- + +Setting the simulation device into the simulation context +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Previously, changing the simulation device to CPU required users to set other simulation parameters +(such as disabling GPU physics and GPU pipelines). This made setting up the device appear complex. +We now simplify the checks for device directly inside the simulation context, so users only need to +specify the device through the configuration object. + +Before: + +.. code:: python + + sim_utils.SimulationCfg(device="cpu", use_gpu_pipeline=False, dt=0.01, physx=sim_utils.PhysxCfg(use_gpu=False)) + +Now: + +.. code:: python + + sim_utils.SimulationCfg(device="cpu", dt=0.01, physx=sim_utils.PhysxCfg()) + +Setting the simulation device from CLI +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Previously, users could specify the device through the command line argument ``--device_id``. However, +this made it ambiguous when users wanted to set the device to CPU. Thus, instead of the device ID, +users need to specify the device explicitly through the argument ``--device``. +The valid options for the device name are: + +* "cpu": runs simulation on CPU +* "cuda": runs simulation on GPU with device ID at default index +* "cuda:N": runs simulation on GPU with device ID at ``N``. For instance, "cuda:0" will use device at index "0". + +Due to the above change, the command line interaction with some of the scripts has changed. + +Before: + +.. code:: bash + + ./isaaclab.sh -p source/standalone/workflows/sb3/train.py --task Isaac-Cartpole-v0 --cpu + +Now: + +.. code:: bash + + ./isaaclab.sh -p source/standalone/workflows/sb3/train.py --task Isaac-Cartpole-v0 --device cpu + +Renaming of teleoperation device CLI in standalone scripts +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Since ``--device`` is now an argument provided by the AppLauncher, it conflicted with the command-line +argument used for specifying the teleoperation-device in some of the standalone scripts. Thus, to fix +this conflict, the teleoperation-device now needs to be specified through ``--teleop_device`` argument. + +Before: + +.. code:: bash + + ./isaaclab.sh -p source/standalone/environments/teleoperation/teleop_se3_agent.py --task Isaac-Lift-Cube-Franka-IK-Rel-v0 --num_envs 1 --device keyboard + +Now: + +.. code:: bash + + ./isaaclab.sh -p source/standalone/environments/teleoperation/teleop_se3_agent.py --task Isaac-Lift-Cube-Franka-IK-Rel-v0 --num_envs 1 --teleop_device keyboard + + +Using Python-version of container utility script +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The prior `container.sh `_ became quite +complex as it had many different use cases in one script. For instance, building a docker image for "base" or "ros2", +as well as cluster deployment. As more users wanted to have the flexibility to overlay their own docker settings, +maintaining this bash script became cumbersome. Hence, we migrated its features into a Python script in this release. +Additionally, we split the cluster-related utilities into their own script inside the ``docker/cluster`` directory. + +We still maintain backward compatibility for ``container.sh``. Internally, it calls the Python script ``container.py``. +We request users to use the Python script directly. + +Before: + +.. code:: bash + + ./docker/container.sh start + + +Now: + +.. code:: bash + + ./docker/container.py start + + +Using separate directories for logging videos in RL workflows +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Previously, users could record videos during the RL training by specifying the ``--video`` flag to the +``train.py`` script. The videos would be saved inside the ``videos`` directory in the corresponding log +directory of the run. + +Since many users requested to also be able to record videos while inferencing the policy, recording +videos have also been added to the ``play.py`` script. Since changing the prefix of the video file +names is not possible, the videos from the train and play scripts are saved inside the ``videos/train`` +and ``videos/play`` directories, respectively. + +Drops support for the tiled camera with Isaac Sim 4.1 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Various fixes have been made to the tiled camera rendering pipeline in Isaac Sim 4.2. This made +supporting the tiled camera with Isaac Sim 4.1 difficult. Hence, for the best experience, we advice +switching to Isaac Sim 4.2 with this release of Isaac Lab. + + +v1.1.0 +====== + +Overview +-------- + +With the release of Isaac Sim 4.0 and 4.1, support for Isaac Sim 2023.1.1 has been discontinued. +We strongly encourage all users to upgrade to Isaac Sim 4.1 to take advantage of the latest features +and improvements. For detailed information on this upgrade, please refer to the release notes available +`here `__. + +Besides the above, the Isaac Lab release brings new features and improvements, as detailed below. We thank +all our contributors for their continued support. + +**Full Changelog**: https://github.com/isaac-sim/IsaacLab/compare/v1.0.0...v1.1.0 + +New Features +------------ + +* Adds distributed multi-GPU learning support for skrl by @Toni-SM +* Updates skrl integration to support training/evaluation using JAX by @Toni-SM +* Adds lidar pattern for raycaster sensor by @pascal-roth +* Adds support for PBS job scheduler-based clusters by @shafeef901 +* Adds APIs for spawning deformable meshes by @Mayankm96 + +Improvements +------------ + +* Changes documentation color to the green theme by @Mayankm96 +* Fixes sphinx tabs to make them work in dark theme by @Mayankm96 +* Fixes VSCode settings to work with pip installation of Isaac Sim by @Mayankm96 +* Fixes ``isaaclab`` scripts to deal with Isaac Sim pip installation by @Mayankm96 +* Optimizes interactive scene for homogeneous cloning by @kellyguo11 +* Improves docker X11 forwarding documentation by @j3soon + +Bug Fixes +--------- + +* Reads gravity direction from simulation inside ``RigidObjectData`` by @Mayankm96 +* Fixes reference count in asset instances due to circular references by @Mayankm96 +* Fixes issue with asset deinitialization due to torch > 2.1 by @Mayankm96 +* Fixes the rendering logic regression in environments by @Dhoeller19 +* Fixes the check for action-space inside Stable-Baselines3 wrapper by @Mayankm96 +* Fixes warning message in Articulation config processing by @locoxsoco +* Fixes action term in the reach environment by @masoudmoghani +* Fixes training UR10 reach with RL_GAMES and SKRL by @sudhirpratapyadav +* Adds event manager call to simple manage-based env by @Mayankm96 + +Breaking Changes +---------------- + +* Drops official support for Isaac Sim 2023.1.1 +* Removes the use of body view inside the asset classes by @Mayankm96 +* Renames ``SimulationCfg.substeps`` to ``SimulationCfg.render_interval`` by @Dhoeller19 + +Migration Guide +--------------- + +Renaming of ``SimulationCfg.substeps`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Previously, the users set both ``omni.isaac.lab.sim.SimulationCfg.dt`` and +``omni.isaac.lab.sim.SimulationCfg.substeps``, which marked the physics insulation time-step and sub-steps, +respectively. It was unclear whether sub-steps meant the number of integration steps inside the physics time-step +``dt`` or the number of physics steps inside a rendering step. + +Since in the code base, the attribute was used as the latter, it has been renamed to ``render_interval`` for clarity. + +Removal of Deprecated Attributes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +As notified in previous releases, we removed the classes and attributes marked as deprecated. These are as follows: + +* The ``mdp.add_body_mass`` method in the events. Please use the ``mdp.randomize_rigid_body_mass`` instead. +* The classes ``managers.RandomizationManager`` and ``managers.RandomizationTermCfg``. Please use the + ``managers.EventManager`` and ``managers.EventTermCfg`` classes instead. +* The following properties in ``omni.isaac.lab.sensors.FrameTransformerData``: + * ``target_rot_source`` --> ``target_quat_w`` + * ``target_rot_w`` --> ``target_quat_source`` + * ``source_rot_w`` --> ``source_quat_w`` + +* The attribute ``body_physx_view`` from the ``omni.isaac.lab.assets.Articulation`` and + ``omni.isaac.lab.assets.RigidObject`` classes. These caused confusion when used with the articulation view + since the body names did not follow the same ordering. + +v1.0.0 +====== + +Overview +-------- + +Welcome to the first official release of Isaac Lab! + +Building upon the foundation of the `Orbit `_ framework, we have integrated +the RL environment designing workflow from `OmniIsaacGymEnvs `_. +This allows users to choose a suitable :ref:`task-design approach ` +for their applications. + +While we maintain backward compatibility with Isaac Sim 2023.1.1, we highly recommend using Isaac Lab with +Isaac Sim 4.0.0 version for the latest features and improvements. + +**Full Changelog**: https://github.com/isaac-sim/IsaacLab/compare/v0.3.1...v1.0.0 + +New Features +------------ + +* Integrated CI/CD pipeline, which is triggered on pull requests and publishes the results publicly +* Extended support for Windows OS platforms +* Added tiled render based Camera + sensor implementation. This provides optimized RGB-D rendering throughputs of up to 10k frames per second. +* Added support for multi-GPU and multi-node training for the RL-Games library +* Integrated APIs for environment designing (direct workflow) without relying on managers +* Added implementation of delayed PD actuator model +* Added various new learning environments: + * Cartpole balancing using images + * Shadow hand cube reorientation + * Boston Dynamics Spot locomotion + * Unitree H1 and G1 locomotion + * ANYmal-C navigation + * Quadcopter target reaching + +Improvements +------------ + +* Reduced start-up time for scripts (inherited from Isaac Sim 4.0 improvements) +* Added lazy buffer implementation for rigid object and articulation data. Instead of updating all the quantities + at every step call, the lazy buffers are updated only when the user queries them +* Added SKRL support to more environments + +Breaking Changes +---------------- + +For users coming from Orbit, this release brings certain breaking changes. Please check the migration guide for more information. + +Migration Guide +--------------- + +Please find detailed migration guides as follows: + +* :doc:`From Orbit to IsaacLab <../migration/migrating_from_orbit>` +* :doc:`From OmniIsaacGymEnvs to IsaacLab <../migration/migrating_from_omniisaacgymenvs>` + +.. _simple script: https://gist.github.com/kellyguo11/3e8f73f739b1c013b1069ad372277a85 diff --git a/simulation/modules/IsaacLab/docs/source/refs/snippets/code_skeleton.py b/simulation/modules/IsaacLab/docs/source/refs/snippets/code_skeleton.py new file mode 100644 index 0000000000000000000000000000000000000000..759ca38ae0f96d2f2e8d72e653fd8ca530c9cb20 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/refs/snippets/code_skeleton.py @@ -0,0 +1,152 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from typing import ClassVar + +DEFAULT_TIMEOUT: int = 30 +"""Default timeout for the task.""" + +_MAX_RETRIES: int = 3 # private constant (note the underscore) +"""Maximum number of retries for the task.""" + + +def run_task(task_name: str): + """Run a task by name. + + Args: + task_name: The name of the task to run. + """ + print(f"Running task: {task_name}") + + +class TaskRunner: + """Runs and manages tasks.""" + + DEFAULT_NAME: ClassVar[str] = "runner" + """Default name for the runner.""" + + _registry: ClassVar[dict] = {} + """Registry of runners.""" + + def __init__(self, name: str): + """Initialize the runner. + + Args: + name: The name of the runner. + """ + self.name = name + self._tasks = [] # private instance variable + + def __del__(self): + """Clean up the runner.""" + print(f"Cleaning up {self.name}") + + def __repr__(self) -> str: + return f"TaskRunner(name={self.name!r})" + + def __str__(self) -> str: + return f"TaskRunner: {self.name}" + + """ + Properties. + """ + + @property + def task_count(self) -> int: + return len(self._tasks) + + """ + Operations. + """ + + def initialize(self): + """Initialize the runner.""" + print("Initializing runner...") + + def update(self, task: str): + """Update the runner with a new task. + + Args: + task: The task to add. + """ + self._tasks.append(task) + print(f"Added task: {task}") + + def close(self): + """Close the runner.""" + print("Closing runner...") + + """ + Operations: Registration. + """ + + @classmethod + def register(cls, name: str, runner: "TaskRunner"): + """Register a runner. + + Args: + name: The name of the runner. + runner: The runner to register. + """ + if name in cls._registry: + _log_error(f"Runner {name} already registered. Skipping registration.") + return + cls._registry[name] = runner + + @staticmethod + def validate_task(task: str) -> bool: + """Validate a task. + + Args: + task: The task to validate. + + Returns: + True if the task is valid, False otherwise. + """ + return bool(task and task.strip()) + + """ + Internal operations. + """ + + def _reset(self): + """Reset the runner.""" + self._tasks.clear() + + @classmethod + def _get_registry(cls) -> dict: + """Get the registry.""" + return cls._registry + + @staticmethod + def _internal_helper(): + """Internal helper.""" + print("Internal helper called.") + + +""" +Helper operations. +""" + + +def _log_error(message: str): + """Internal helper to log errors. + + Args: + message: The message to log. + """ + print(f"[ERROR] {message}") + + +class _TaskHelper: + """Private utility class for internal task logic.""" + + def compute(self) -> int: + """Compute the result. + + Returns: + The result of the computation. + """ + return 42 diff --git a/simulation/modules/IsaacLab/docs/source/refs/snippets/tutorial_modify_direct_rl_env.py b/simulation/modules/IsaacLab/docs/source/refs/snippets/tutorial_modify_direct_rl_env.py new file mode 100644 index 0000000000000000000000000000000000000000..e839abf20099bb878f288af7797f9431f7eda62d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/refs/snippets/tutorial_modify_direct_rl_env.py @@ -0,0 +1,61 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# ruff: noqa +# fmt: off + +# [start-init-import] +from .h1_env import H1Env, H1EnvCfg +# [end-init-import] + +# [start-init-register] +gym.register( + id="Isaac-H1-Direct-v0", + entry_point="isaaclab_tasks.direct.humanoid:H1Env", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": H1EnvCfg, + "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:HumanoidPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", + }, +) +# [end-init-register] + +# [start-h1_env-import] +from isaaclab_assets import H1_CFG +# [end-h1_env-import] + +# [start-h1_env-spaces] +action_space = 19 +observation_space = 69 +# [end-h1_env-spaces] + +# [start-h1_env-robot] +robot: ArticulationCfg = H1_CFG.replace(prim_path="/World/envs/env_.*/Robot") +joint_gears: list = [ + 50.0, # left_hip_yaw + 50.0, # right_hip_yaw + 50.0, # torso + 50.0, # left_hip_roll + 50.0, # right_hip_roll + 50.0, # left_shoulder_pitch + 50.0, # right_shoulder_pitch + 50.0, # left_hip_pitch + 50.0, # right_hip_pitch + 50.0, # left_shoulder_roll + 50.0, # right_shoulder_roll + 50.0, # left_knee + 50.0, # right_knee + 50.0, # left_shoulder_yaw + 50.0, # right_shoulder_yaw + 50.0, # left_ankle + 50.0, # right_ankle + 50.0, # left_elbow + 50.0, # right_elbow +] +# [end-h1_env-robot] + +# fmt: on diff --git a/simulation/modules/IsaacLab/docs/source/refs/troubleshooting.rst b/simulation/modules/IsaacLab/docs/source/refs/troubleshooting.rst new file mode 100644 index 0000000000000000000000000000000000000000..8fc69767c37c812bd2747f354d955a2b7a010202 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/refs/troubleshooting.rst @@ -0,0 +1,387 @@ +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 + `__ for more + assistance. + + +Installation Troubleshooting +---------------------------- + +``ModuleNotFoundError: No module named 'pip'`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Your venv was created without pip. The install system auto-detects and uses +``uv pip`` when pip is absent, so this error should no longer occur with the +latest Isaac Lab. + +``ModuleNotFoundError: No module named 'isaacsim'`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You are running a script that requires Isaac Sim, but it is not installed. +Either: + +- Install Isaac Sim: ``./isaaclab.sh -i isaacsim``, or +- Use a Newton-based task with ``physics=newton_mjwarp --visualizer newton`` (Kit-less path) + +``ModuleNotFoundError: No module named 'isaaclab_physx'`` or ``'isaaclab_ov'`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +These config packages are auto-installed by ``./isaaclab.sh -i``. If using a +selective install, re-run with the default ``./isaaclab.sh -i`` to get all +packages. + +``ModuleNotFoundError: No module named 'isaaclab_assets'`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Include ``assets`` in your install command, or use ``./isaaclab.sh -i`` to install +everything. + +``ModuleNotFoundError: No module named 'rsl_rl'`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Include the RL framework: ``./isaaclab.sh -i rsl_rl``, or use +``./isaaclab.sh -i`` to install all frameworks. + +Crash in ``libusd_tf`` / USD Symbol Collision with OVRTX +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you see a crash involving ``libusd_tf-*.so`` and conflicting USD versions +(e.g. ``pxrInternal_v0_25_5`` vs ``pxrInternal_v0_25_11``): + +1. Ensure ``LD_PRELOAD`` is set to ovrtx's ``libcarb.so`` and install the OVRTX + runtime with ``./isaaclab.sh -i 'ov[ovrtx]'`` (see :ref:`installation-selective-install`) +2. Ensure ``isaacsim`` / ``omniverse-kit`` is **not** installed in the same + environment — their bundled USD libraries conflict with ovrtx's + +Visualizer Not Appearing +~~~~~~~~~~~~~~~~~~~~~~~~ + +If ``--visualizer newton`` shows no window, you may be missing ``imgui-bundle``: + +.. code-block:: bash + + uv pip install imgui-bundle + +For ``viser``, check the terminal for a URL (e.g. ``http://localhost:8012``). + +``GLIBC Version Too Old`` +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Isaac Sim pip packages require GLIBC 2.35+. Check with ``ldd --version``. +Ubuntu 22.04+ satisfies this. For older distributions, use the +`binary installation `_ +method for Isaac Sim. + +Troubleshooting distributed training NCCL errors +------------------------------------------------ + +On some Linux multi-GPU systems, distributed training may fail with +``CUDA error: an illegal memory access was encountered`` reported by ``ProcessGroupNCCL``. +For documented NCCL workarounds, see :ref:`multi-gpu-nccl-troubleshooting`. + + +Debugging physics simulation stability issues +--------------------------------------------- + +When importing new robots into Isaac Lab or setting up a new environment, simulation instability +can often appear if the assets have not been tuned with reasonable simulation parameters. +In reinforcement learning scenarios, this will often result in NaNs propagating into the learning pipeline +due to invalid states in the simulation. + +If this happens, we recommend consulting the +`Articulation and Robot Simulation Stability Guide `_ +which recommends various simulation parameters and best practices to achieve better stability in robot simulations. + +Additionally, `Omniverse PhysX Visual Debugger `_ +allows for recording of data of PhysX simulations, which can often help simulation issues and aid the debugging process. + +To enable OmniPVD capture in Isaac Lab, add the relevant kit arguments to the command line prompt when launching an Isaac Lab process + +.. code:: bash + + ./isaaclab.sh -p scripts/demos/bipeds.py --kit_args "--/persistent/physics/omniPvdOvdRecordingDirectory=/tmp/ --/physics/omniPvdOutputEnabled=true" + + +Joints actuate in PhysX but not in a Newton-based backend +--------------------------------------------------------- + +If your robot's joints move under PhysX but appear unactuated under one of the +Newton-based backends (MuJoCo Warp, XPBD, Featherstone, Semi-implicit) — even +though you have authored an :class:`~isaaclab.actuators.ImplicitActuatorCfg` +with non-zero ``stiffness`` and ``damping`` — the cause is almost always that +the USD asset ships with zero authored drive gains. + +Newton's USD importer only materialises a solver actuator when the authored +``PhysicsDriveAPI`` reports a non-zero stiffness *or* damping. Many existing +assets leave both at ``0`` on purpose, expecting the actuator gains to come from +an :class:`~isaaclab.actuators.ImplicitActuatorCfg` at runtime. PhysX creates +the actuator regardless and lets the runtime gain writes take effect, so the +asset works there; Newton drops the actuator before the runtime writes can +attach to it. + +The fix is to set +:attr:`~isaaclab.sim.schemas.JointDrivePropertiesCfg.ensure_drives_exist` to +``True`` on the spawn config. This writes a minimal placeholder stiffness +(``1e-3``) to any drive whose authored stiffness *and* damping are both zero, +which is enough for Newton's importer to create the actuator. The actual gains +are then overwritten by the actuator model at runtime, so the placeholder has +no effect on the simulated dynamics. + +.. code:: python + + from isaaclab.actuators import ImplicitActuatorCfg + from isaaclab.assets import ArticulationCfg + import isaaclab.sim as sim_utils + + ROBOT_CFG = ArticulationCfg( + spawn=sim_utils.UsdFileCfg( + usd_path="...", + joint_drive_props=sim_utils.JointDrivePropertiesCfg(ensure_drives_exist=True), + ), + actuators={ + "legs": ImplicitActuatorCfg( + joint_names_expr=[".*HAA", ".*HFE", ".*KFE"], + effort_limit_sim=120.0, + velocity_limit_sim=7.5, + stiffness={".*": 40.0}, + damping={".*": 5.0}, + ), + }, + ) + +See :ref:`import-new-asset-ensure-drives-exist` for the underlying USD-import +details and the equivalent fix when authoring a new asset. + + +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 `_. + +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/IsaacLab/_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. + +Changing logging channel levels for the simulator +------------------------------------------------- + +By default, the simulator logs messages at the ``WARN`` level and above on the terminal. You can change the logging +channel levels to get more detailed logs. The logging channel levels can be set through Omniverse's logging system. + +To obtain more detailed logs, you can run your application with the following flags: + +* ``--info``: This flag logs messages at the ``INFO`` level and above. +* ``--verbose``: This flag logs messages at the ``VERBOSE`` level and above. + +For instance, to run a standalone script with verbose logging, you can use the following command: + +.. code-block:: bash + + # Run the standalone script with info logging + ./isaaclab.sh -p scripts/tutorials/00_sim/create_empty.py --info + +For more fine-grained control, you can modify the logging channels through the ``logger`` module. +For more information, please refer to its `documentation `__. + + +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:`~isaaclab.sim.SimulationContext` class. The size of the buffers can be increased by setting +the :attr:`~isaaclab.sim.PhysxCfg.gpu_found_lost_pairs_capacity` parameter in the +:class:`~isaaclab.sim.PhysxCfg` class. For example, to increase the size of the buffers to +4096, you can use the following code: + +.. code:: python + + import isaaclab.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:`~isaaclab.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 `_ +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 "scripts/imitation_learning/robomimic/collect_demonstrations.py", line 166, in + main() + File "scripts/imitation_learning/robomimic/collect_demonstrations.py", line 126, in main + actions = pre_process_actions(delta_pose, gripper_command) + File "scripts/imitation_learning/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: ._Registry.__del__ at 0x7f94ac097f80> + Traceback (most recent call last): + File "../IsaacLab/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 103, in __del__ + File "../IsaacLab/_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: ._Registry.__del__ at 0x7f94ac097f80> + Traceback (most recent call last): + File "../IsaacLab/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 103, in __del__ + File "../IsaacLab/_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: + Traceback (most recent call last): + File "../IsaacLab/_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: + Traceback (most recent call last): + File "../IsaacLab/_isaac_sim/extscache/omni.kit.viewport.menubar.lighting-104.0.7/omni/kit/viewport/menubar/lighting/actions.py", line 345, in __del__ + File "../IsaacLab/_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 + ../IsaacLab/_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 "scripts/imitation_learning/robomimic/tools/collect_demonstrations.py", line 166, in + main() + File "scripts/imitation_learning/robomimic/tools/collect_demonstrations.py", line 126, in main + actions = pre_process_actions(delta_pose, gripper_command) + File "scripts/imitation_learning/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 diff --git a/simulation/modules/IsaacLab/docs/source/setup/ecosystem.rst b/simulation/modules/IsaacLab/docs/source/setup/ecosystem.rst new file mode 100644 index 0000000000000000000000000000000000000000..4ce71497b59b7543c695be8e2de034babb7db9bb --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/ecosystem.rst @@ -0,0 +1,217 @@ +.. _isaac-lab-ecosystem: + +Isaac Lab Ecosystem +=================== + +Isaac Lab is a modular, extensible framework for robot learning built on top of `Isaac Sim`_ and +`Newton`_. It provides a unified interface for the most common workflows in robotics research — +reinforcement learning, learning from demonstrations, and motion planning — while staying easy to +use and easy to extend. + +Isaac Lab supports two physics engines through multiple backend packages: + +* **PhysX** — the default backend through `Isaac Sim`_, with access to GPU-accelerated + rigid-body simulation, deformable objects, Fabric views, tiled RTX rendering, ROS/ROS2, + URDF/MJCF importers, and the full Omniverse toolchain. PhysX can also be used through the + standalone ``ovphysx`` runtime for kit-less workflows that do not launch Isaac Sim. +* **Newton** — a Warp-native backend that can run in kit-less mode, enabling lightweight + deployments and GPU-parallel simulation using `Warp`_. + +.. note:: + + Isaac Lab 3.0 supports a **kit-less installation** mode: you can install Isaac Lab and use the + Newton physics backend without installing Isaac Sim at all. + See :ref:`isaaclab-installation-root` for details. + +A factory pattern dispatches every asset and sensor instantiation to the correct backend at +runtime, so user code stays unchanged regardless of which backend is active. See +:doc:`/source/overview/core-concepts/multi_backend_architecture` for details. + +.. image:: ../_static/setup/ecosystem-light.svg + :class: only-light + :align: center + :alt: The Isaac Lab package ecosystem layered on the NVIDIA GPU platform + +.. image:: ../_static/setup/ecosystem-dark.svg + :class: only-dark + :align: center + :alt: The Isaac Lab package ecosystem layered on the NVIDIA GPU platform + + +Package structure +----------------- + +Isaac Lab is organized into a set of focused packages that can be used independently or together. + +**Core** + +* ``isaaclab`` — the core library. Contains simulation context and configuration + (:mod:`~isaaclab.sim`), the :class:`~isaaclab.scene.InteractiveScene` that aggregates all + assets, sensors, and terrain for a vectorized set of environments, asset interfaces + (:mod:`~isaaclab.assets`), sensor interfaces (:mod:`~isaaclab.sensors`), environment base + classes (:mod:`~isaaclab.envs`), the manager system (:mod:`~isaaclab.managers`), + composable MDP term functions (:mod:`~isaaclab.envs.mdp`), actuator models + (:mod:`~isaaclab.actuators`), low-level controllers (:mod:`~isaaclab.controllers`), + procedural terrain generation (:mod:`~isaaclab.terrains`), and human-input device support + (:mod:`~isaaclab.devices`). + +**Physics and renderer backends** + +* ``isaaclab_physx`` — PhysX-backed implementations of articulations, + rigid bodies, deformable objects, Fabric views, the Isaac RTX renderer, and USD spawners. + Requires Isaac Sim. +* ``isaaclab_ovphysx`` — standalone PhysX-backed implementations built on ``ovphysx`` and + TensorBindingsAPI. Requires the ``ovphysx`` package and can run without launching Isaac Sim. +* ``isaaclab_ov`` — Omniverse renderer package that provides the OVRTX renderer for + RTX-based tiled camera rendering. Requires the ``ovrtx`` package and can be used in + kit-less workflows without Isaac Sim. +* ``isaaclab_newton`` — Newton-backed implementations of articulations, rigid bodies, and the + Warp renderer. Supports kit-less installation without Isaac Sim. + +**Extensions** + +* ``isaaclab_assets`` — pre-configured robot and sensor :class:`~isaaclab.utils.configclass` + dataclasses for a wide range of robots (Franka, Unitree, ANYmal, Spot, Allegro, humanoids, + quadcopters, and more) and sensors (Velodyne, GelSight). +* ``isaaclab_tasks`` — registered `gymnasium`_ environments organized into two authoring patterns: + + * *Manager-based* — behavior is fully specified through composable manager configurations + (observations, rewards, terminations, events, commands, actions). Well-suited for research + that requires clean separation between task specification and environment logic. + * *Direct* — a single Python class implements the full step/reset/obs/reward loop, similar + in style to Isaac Gym. Convenient for rapid prototyping and tasks with complex custom logic. + +* ``isaaclab_rl`` — thin wrappers that adapt Isaac Lab environments to the vectorized + environment interfaces expected by `RSL-RL`_, `skrl`_, `Stable Baselines 3`_, and + `RL Games`_. +* ``isaaclab_mimic`` — APIs and pre-configured environments for data generation and imitation + learning, including cuRobo-based motion planners and a full dataset-generation pipeline. +* ``isaaclab_teleop`` — teleoperation session orchestration with XR (OpenXR / CloudXR) support, + device retargeters for manipulators and humanoids, and gamepad/spacemouse/keyboard input. +* ``isaaclab_visualizers`` — supplementary visualizer backends (Isaac Kit, Rerun, Viser) that + work with any physics backend. +* ``isaaclab_contrib`` — community-contributed features: multirotor assets, TacSL visuo-tactile + sensors, drone thrust controllers, and more. +* ``isaaclab_experimental`` — pre-production experiments, including Warp-accelerated manager and + environment variants. + + +Where does Isaac Lab fit in the Isaac ecosystem? +------------------------------------------------ + +Over the years, NVIDIA has developed a number of tools for robotics and AI. These tools leverage +the power of GPUs to accelerate simulation both in terms of speed and realism. + +`Isaac Gym`_ :cite:`makoviychuk2021isaac` provided a high-performance GPU-based physics simulation +for robot learning built on top of `PhysX`_. Its end-to-end GPU pipeline enabled frame rates +far beyond what CPU-based physics engines could achieve. The tool proved successful across a +number of research projects, including legged locomotion :cite:`rudin2022learning` +:cite:`rudin2022advanced`, in-hand manipulation :cite:`handa2022dextreme` +:cite:`allshire2022transferring`, and industrial assembly :cite:`narang2022factory`. + +`Isaac Sim`_ is a general-purpose robot simulation toolkit built on top of `Omniverse`_. It +integrates the capabilities of Isaac Gym while adding high-fidelity rendering, ROS/ROS2, +deformable-object simulation, synthetic data generation, domain randomization, tiled rendering +for vectorized observations, and cloud support via `Isaac Automator`_. With the Isaac Gym legacy +API absorbed into Isaac Sim, NVIDIA also released open-sourced environment collections +`IsaacGymEnvs`_ and `OmniIsaacGymEnvs`_ to showcase the capabilities of these simulators. +Those environment collections are now deprecated in favor of Isaac Lab. + +Isaac Lab supersedes `IsaacGymEnvs`_, `OmniIsaacGymEnvs`_, and `Orbit`_ as the single robot +learning framework for Isaac Sim. It retains full access to the PhysX/Isaac Sim stack while +adding the Newton physics backend for kit-less deployments, an expanded sensor suite, imitation +learning tooling, XR teleoperation, and a rich set of pre-built tasks. + + +Is Isaac Lab a simulator? +------------------------- + +At its core, Isaac Lab is **not** a robotics simulator; it is a framework for building robot +learning applications on top of a simulator. An analogous example is `RoboSuite`_, which is +built on top of `MuJoCo`_ for fixed-base manipulation. Other examples include +`MuJoCo Playground`_ (built on `MJX`_) and Isaac Gym (built on `PhysX`_). + +Isaac Lab supports both `PhysX`_ and `Newton`_ as physics backends and is deliberately +agnostic to the underlying engine — user environments and tasks do not import backend-specific +modules directly. + +The framework addresses a recurring problem with standalone task implementations: because each +task reimplements the observation, reward, termination, and randomization logic from scratch, +large projects accumulate significant code duplication. Isaac Lab solves this with two +complementary patterns: + +* **Manager-based** environments defer every behavioral concern to typed, composable + *manager* objects (``ObservationManager``, ``RewardManager``, ``TerminationManager``, + ``EventManager``, ``CurriculumManager``, ``CommandManager``, ``ActionManager``, + ``RecorderManager``). Each manager is driven by small, reusable MDP term functions that live + in :mod:`isaaclab.envs.mdp`. This makes it easy to mix and match terms across tasks and to + test individual components in isolation. + +* **Direct** environments implement ``_get_observations``, ``_get_rewards``, + ``_get_dones``, and ``_reset_idx`` directly in a subclass, similar to the Isaac Gym style. + They sacrifice some modularity for simplicity and are a natural starting point for rapid + prototyping. + +Both patterns expose a standard `gymnasium`_ ``Env`` interface with vectorized semantics, +so the same environment works unmodified with any of the supported RL libraries. +Configuration management uses `Hydra`_ with a preset system that allows selecting physics +backends and hyperparameter sweeps from the command line. + + +Why should I use Isaac Lab? +--------------------------- + +Isaac Lab provides an open-sourced platform for the community to build benchmarks and robot +learning systems together. Sharing a common infrastructure lets teams reuse existing components, +compare results on the same tasks, and focus on the research problems that matter rather than +rebuilding simulation scaffolding from scratch. + +Concretely, Isaac Lab offers: + +* **Two authoring patterns** — manager-based for modular research and direct for rapid + prototyping — with a shared :class:`~isaaclab.scene.InteractiveScene` and sensor stack. +* **Multi-backend simulation** — switch between PhysX and Newton from the command line; the + same environment code runs on both. +* **Rich sensor suite** — cameras (tiled and standard), ray-casters, contact sensors, IMU, + frame transformers, joint-wrench sensors, and visuo-tactile sensors. +* **Imitation learning tooling** — ``isaaclab_mimic`` provides cuRobo-based planners and a + full dataset-generation pipeline for human demonstration collection. +* **Teleoperation and XR** — ``isaaclab_teleop`` supports OpenXR, CloudXR, gamepads, + spacemouses, and Haply devices with retargeters for manipulators and humanoids. +* **Hydra configuration management** — hierarchical configs with command-line overrides and a + preset system for multi-backend environment variants. +* **RL library integrations** — wrappers for RSL-RL, skrl, Stable Baselines 3, and RL Games + ship in ``isaaclab_rl``. +* **Kit-less deployment** — run policies and simulations using the Newton backend without a + full Isaac Sim installation. + +We are working with labs in universities and research institutions to integrate their work into +Isaac Lab and hope that others in the community will join us. If you are interested in +contributing, please reach out to us. + + +.. _PhysX: https://developer.nvidia.com/physx-sdk +.. _Newton: https://github.com/newton-physics/newton +.. _Warp: https://github.com/NVIDIA/warp +.. _Isaac Sim: https://developer.nvidia.com/isaac-sim +.. _Omniverse: https://www.nvidia.com/en-us/omniverse/ +.. _Isaac Gym: https://developer.nvidia.com/isaac-gym +.. _IsaacGymEnvs: https://github.com/isaac-sim/IsaacGymEnvs +.. _OmniIsaacGymEnvs: https://github.com/isaac-sim/OmniIsaacGymEnvs +.. _Orbit: https://isaac-orbit.github.io/ +.. _Isaac Automator: https://github.com/isaac-sim/IsaacAutomator +.. _gymnasium: https://gymnasium.farama.org/ +.. _Hydra: https://hydra.cc/ +.. _RSL-RL: https://github.com/leggedrobotics/rsl_rl +.. _skrl: https://skrl.readthedocs.io/ +.. _Stable Baselines 3: https://stable-baselines3.readthedocs.io/ +.. _RL Games: https://github.com/Denys88/rl_games +.. _AirSim: https://microsoft.github.io/AirSim/ +.. _DoorGym: https://github.com/PSVL/DoorGym/ +.. _ManiSkill: https://github.com/haosulab/ManiSkill +.. _RoboSuite: https://github.com/ARISE-Initiative/robosuite +.. _MuJoCo: https://mujoco.org/ +.. _MuJoCo Playground: https://playground.mujoco.org/ +.. _MJX: https://mujoco.readthedocs.io/en/stable/mjx.html +.. _Bullet: https://github.com/bulletphysics/bullet3 +.. _Flex: https://developer.nvidia.com/flex diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/asset_caching.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/asset_caching.rst new file mode 100644 index 0000000000000000000000000000000000000000..5cee207fae36bb5346b3514852b184a53ab12ce5 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/asset_caching.rst @@ -0,0 +1,58 @@ +Asset Caching +============= + +Assets used in Isaac Lab are hosted on AWS S3 buckets on the cloud. +Asset loading time can depend on your network connection and geographical location. +In some cases, it is possible that asset loading times can be long when assets are pulled from the AWS servers. + +If you run into cases where assets take a few minutes to load for each run, +we recommend enabling asset caching following the below steps. + +First, launch the Isaac Sim application: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh -s + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat -s + +On the top right of the Isaac Lab or Isaac Sim app, look for the icon labeled ``CACHE:``. +You may see a message such as ``HUB NOT DETECTED`` or ``NEW VERSION DETECTED``. + +Click the message to enable `Hub `_. +Hub automatically manages local caching for Isaac Lab assets, so subsequent runs will use cached files instead of +downloading from AWS each time. + +.. figure:: /source/_static/setup/asset_caching.jpg + :align: center + :figwidth: 100% + :alt: Simulator with cache messaging. + +Hub provides better control and management of cached assets, making workflows faster and more reliable, especially +in environments with limited or intermittent internet access. + +.. note:: + The first time you run Isaac Lab, assets will still need to be pulled from the cloud, which could lead + to longer loading times. Once cached, loading times will be significantly reduced on subsequent runs. + +Nucleus +------- + + +Before Isaac Sim 4.5, assets were accessed via the Omniverse Nucleus server, including setups with local Nucleus instances. + +.. warning:: + Starting with Isaac Sim 4.5, the Omniverse Nucleus server and Omniverse Launcher are deprecated. + Existing Nucleus setups will continue to work, so if you have a local Nucleus server already configured, + you may continue to use it. diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/binaries_installation.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/binaries_installation.rst new file mode 100644 index 0000000000000000000000000000000000000000..7bd130187284117b5d20bf7bff60596e9532f7a4 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/binaries_installation.rst @@ -0,0 +1,87 @@ +.. _isaaclab-binaries-installation: + +Installation using Isaac Sim Pre-built Binaries +=============================================== + +The following steps first installs Isaac Sim from its pre-built binaries, then Isaac Lab from source code. + +.. caution:: + + Combining an Isaac Sim **binary** installation with a conda, uv, or venv virtual environment + is **no longer supported**. Use Isaac Sim's bundled Python via ``./isaaclab.sh -p`` (or + ``isaaclab.bat -p`` on Windows) instead. + + If you need a dedicated virtual environment, install Isaac Sim via pip and follow the + :doc:`pip_installation` guide. + +Installing Isaac Sim +-------------------- + +Downloading pre-built binaries +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Isaac Sim binaries can be downloaded directly as a zip file from +`here `__. +If you wish to use the older Isaac Sim 4.5 release, please check the older download page +`here `__. + +Once the zip file is downloaded, you can unzip it to the desired directory. +As an example set of instructions for unzipping the Isaac Sim binaries, +please refer to the `Isaac Sim documentation `__. + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + On Linux systems, we assume the Isaac Sim directory is named ``${HOME}/isaacsim``. + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + On Windows systems, we assume the Isaac Sim directory is named ``C:\isaacsim``. + +Verifying the Isaac Sim installation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +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: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + # Isaac Sim root directory + export ISAACSIM_PATH="${HOME}/isaacsim" + # Isaac Sim python executable + export ISAACSIM_PYTHON_EXE="${ISAACSIM_PATH}/python.sh" + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: Isaac Sim root directory + set ISAACSIM_PATH="C:\isaacsim" + :: Isaac Sim python executable + set ISAACSIM_PYTHON_EXE="%ISAACSIM_PATH:"=%\python.bat" + + +.. include:: include/bin_verify_isaacsim.rst + +Installing Isaac Lab +-------------------- + +.. include:: include/src_clone_isaaclab.rst + +.. include:: include/src_symlink_isaacsim.rst + +.. include:: include/src_build_isaaclab.rst + +.. include:: include/src_verify_isaaclab.rst diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/cloud_installation.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/cloud_installation.rst new file mode 100644 index 0000000000000000000000000000000000000000..1cda016ae07395d55831eaefb05ebdbf3560fa44 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/cloud_installation.rst @@ -0,0 +1,204 @@ +Cloud Deployment +================ + +Isaac Lab can be run in various cloud infrastructures with the use of +`Isaac Automator `__ (v4). + +Isaac Automator allows quick deployment of Isaac Sim, Isaac Lab, and Isaac Lab Arena +onto public clouds (AWS, GCP, Azure, and Alibaba Cloud are currently supported). +The result is a fully configured remote desktop cloud workstation (Isaac Workstation), +which can be used for development and testing of Isaac Lab within minutes and on a budget. +Isaac Automator supports a variety of GPU instances and stop/start functionality +to save on cloud costs, and provides tools to aid the workflow +(uploading and downloading data, autorun scripts, deployment management, etc.). + + +System Requirements +------------------- + +Isaac Automator requires having ``docker`` pre-installed on the system. + +* To install Docker, please follow the instructions for your operating system on the + `Docker website`_. +* Follow the post-installation steps for Docker on the `post-installation steps`_ page. + These steps allow you to run Docker without using ``sudo``. + + +Installing Isaac Automator +--------------------------- + +For the most up-to-date and complete installation instructions, please refer to +the `Isaac Automator README `__. + +To use Isaac Automator, first clone the repo: + +.. tab-set:: + + .. tab-item:: HTTPS + + .. code-block:: bash + + git clone https://github.com/isaac-sim/IsaacAutomator.git + + .. tab-item:: SSH + + .. code-block:: bash + + git clone git@github.com:isaac-sim/IsaacAutomator.git + + +Building the Container +---------------------- + +Build the Isaac Automator container: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux / macOS + :sync: linux + + .. code-block:: bash + + ./build + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + docker build --platform linux/x86_64 -t isaac_automator . + +This will build the Isaac Automator container and tag it as ``isaac_automator``. + + +Deploying an Isaac Workstation +------------------------------ + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux / macOS + :sync: linux + + Enter the Automator container and run the deployment command: + + .. code-block:: bash + + ./run + # inside container: + ./deploy-aws + + Alternatively, run it in one step: + + .. code-block:: bash + + ./run ./deploy-aws + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + docker run --platform linux/x86_64 -it --rm -v .:/app isaac_automator bash + :: inside container: + ./deploy-aws + +Replace ``deploy-aws`` with ``deploy-gcp``, ``deploy-azure``, or ``deploy-alicloud`` +for other cloud providers. + +.. note:: + + The ``--isaaclab`` and ``--isaacsim`` flags accept any valid Git reference + to specify the version to deploy. Use ``--isaaclab no`` or ``--isaacsim no`` + to skip installation of the respective component. + + .. code-block:: bash + + ./deploy-aws --isaaclab v3.0.0 --isaacsim main + +On the first run (or when credentials expire), you will be prompted to enter +your cloud credentials. Credentials are stored in ``state/`` and persist +across container restarts. Run ``./deploy- --help`` to see all available +options. + +Key deployment options: + +- ``--instance-type`` -- Cloud VM instance type. +- ``--isaacsim`` / ``--isaaclab`` / ``--isaaclab-arena`` -- Git ref for the version + to install, or ``no`` to skip. +- ``--existing`` -- What to do if a deployment already exists: ``ask`` (default), + ``repair``, ``modify``, ``replace``, or ``run_ansible``. +- ``--from-image`` -- Deploy from a pre-built VM image for faster provisioning + (AWS only at this time). + +Connecting to the Isaac Workstation +----------------------------------- + +Deployed Isaac Workstations can be accessed via: + +- **SSH**: ``./ssh `` +- **noVNC** (browser-based): ``./novnc `` +- **NoMachine** (remote desktop client) + +Connection instructions are displayed at the end of the deployment command +output and saved in ``state//info.txt``. + + +Running Isaac Lab on the Cloud +------------------------------ + +Isaac Lab is installed from source on the deployed workstation at ``~/IsaacLab``. +To run Isaac Lab commands, open a terminal on the workstation: + +.. code-block:: bash + + ~/IsaacLab/isaaclab.sh train --rl_library rsl_rl \ + --task=Isaac-Cartpole-Direct-v0 + + +Pausing and Resuming +-------------------- + +You can stop and restart instances to save on cloud costs: + +.. code-block:: bash + + # inside the Automator container: + ./stop + ./start + +Use ``./start --quick`` to skip full Ansible provisioning +and only run the autorun script. + + +Uploading and Downloading Data +------------------------------ + +.. code-block:: bash + + # upload local uploads/ folder to the instance + ./upload + + # download results from the instance to local results/ folder + ./download + + +Destroying a Deployment +----------------------- + +To save costs, destroy deployments when no longer needed: + +.. code-block:: bash + + # inside the Automator container: + ./destroy + +.. note:: + + Deployment metadata is stored in the ``state/`` directory. Do not delete this + directory, as it is required for managing deployments. + + +.. _`Docker website`: https://docs.docker.com/engine/install/ +.. _`post-installation steps`: https://docs.docker.com/engine/install/linux-postinstall/ diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/include/bin_verify_isaacsim.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/include/bin_verify_isaacsim.rst new file mode 100644 index 0000000000000000000000000000000000000000..4d5bbd1f5a0d4d3090c8227d3edaa4643c377244 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/include/bin_verify_isaacsim.rst @@ -0,0 +1,74 @@ +Check that the simulator runs as expected: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + # note: you can pass the argument "--help" to see all arguments possible. + ${ISAACSIM_PATH}/isaac-sim.sh + + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: note: you can pass the argument "--help" to see all arguments possible. + %ISAACSIM_PATH%\isaac-sim.bat + + +Check that the simulator runs from a standalone python script: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. 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/isaacsim.core.experimental.api/add_cubes.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: checks that python path is set correctly + %ISAACSIM_PYTHON_EXE% -c "print('Isaac Sim configuration is now complete.')" + :: checks that Isaac Sim can be launched from python + %ISAACSIM_PYTHON_EXE% %ISAACSIM_PATH%\standalone_examples\api\isaacsim.core.experimental.api\add_cubes.py + +.. caution:: + + 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: + + .. tab-set:: + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + + .. code:: bash + + ${ISAACSIM_PATH}/isaac-sim.sh --reset-user + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + + .. code:: batch + + %ISAACSIM_PATH%\isaac-sim.bat --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 `__ +and the +`Isaac Sim Forums `_. diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/include/pip_extras_note.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/include/pip_extras_note.rst new file mode 100644 index 0000000000000000000000000000000000000000..e6b3bd919b87dee7387468dfeec6c13f29244a81 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/include/pip_extras_note.rst @@ -0,0 +1,4 @@ +.. note:: + + The ``isaaclab`` pip wheel bundles all Isaac Lab extensions. Install with + ``[isaacsim,all]`` for the full Isaac Sim workflow. diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/include/pip_python_virtual_env.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/include/pip_python_virtual_env.rst new file mode 100644 index 0000000000000000000000000000000000000000..c85846c9d1dd1f7dcde956b6b3f5002bccfabb89 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/include/pip_python_virtual_env.rst @@ -0,0 +1,100 @@ +Preparing a Python Environment +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Creating a dedicated Python environment is **strongly recommended**. It helps: + +- **Avoid conflicts with system Python** or other projects installed on your machine. +- **Keep dependencies isolated**, so that package upgrades or experiments in other projects + do not break Isaac Sim. +- **Easily manage multiple environments** for setups with different versions of dependencies. +- **Simplify reproducibility** — the environment contains only the packages needed for the current project, + making it easier to share setups with colleagues or run on different machines. + +We recommend **uv** as the package manager — it is significantly faster than pip and conda +for creating environments and resolving dependencies. + +.. caution:: + + The Python version of the virtual environment must match the Python version of Isaac Sim. + + - For Isaac Sim 6.X, the required Python version is 3.12. + + Using a different Python version will result in errors when running Isaac Lab. + +The following instructions are for Isaac Sim 6.X, which requires Python 3.12. + +- Create a virtual environment using one of the package managers: + + .. tab-set:: + + .. tab-item:: UV Environment (Recommended) + + **uv** is the fastest and recommended way to create a Python environment for Isaac Lab. + To install ``uv``, please follow the instructions `here `__. + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + # create a virtual environment named env_isaaclab with python3.12 and pip + uv venv --python 3.12 --seed env_isaaclab + # activate the virtual environment + source env_isaaclab/bin/activate + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + :: create a virtual environment named env_isaaclab with python3.12 and pip + uv venv --python 3.12 --seed env_isaaclab + :: activate the virtual environment + env_isaaclab\Scripts\activate + + .. note:: + + The ``--seed`` flag ensures ``pip`` is available inside the ``uv`` virtual environment, + which is required by the Isaac Lab installer. + + .. tab-item:: Conda Environment + + To install conda, please follow the instructions `here `__. + You can create the Isaac Lab environment using the following commands. + + We recommend using `Miniconda `_, + since it is light-weight and resource-efficient environment management system. + + .. code-block:: bash + + conda create -n env_isaaclab python=3.12 + conda activate env_isaaclab + + +- Ensure the latest pip version is installed. To update pip, run the following command + from inside the virtual environment: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + uv pip install --upgrade pip + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + uv pip install --upgrade pip + + .. note:: + + If you are using ``pip`` directly instead of ``uv pip``, replace ``uv pip`` with ``pip`` + (or ``python -m pip`` on Windows) in the commands above and throughout this guide. diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/include/pip_verify_isaacsim.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/include/pip_verify_isaacsim.rst new file mode 100644 index 0000000000000000000000000000000000000000..111b47d271bb41e142eaf673c93349cf364f6507 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/include/pip_verify_isaacsim.rst @@ -0,0 +1,46 @@ + +Verifying the Isaac Sim installation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Make sure that your virtual environment is activated (if applicable) + +- Check that the simulator runs as expected: + + .. code:: bash + + # note: you can pass the argument "--help" to see all arguments possible. + isaacsim + +- It's also possible to run with a specific experience file, run: + + .. code:: bash + + # experience files can be absolute path, or relative path searched in isaacsim/apps or omni/apps + isaacsim isaacsim.exp.full.kit + + +.. note:: + + When running Isaac Sim for the first time, all dependent extensions will be pulled from the registry. + This process can take upwards of 10 minutes and is required on the first run of each experience file. + Once the extensions are pulled, consecutive runs using the same experience file will use the cached extensions. + +.. attention:: + + The first run will prompt users to accept the Nvidia Omniverse License Agreement. + To accept the EULA, reply ``Yes`` when prompted with the below message: + + .. code:: bash + + By installing or using Isaac Sim, I agree to the terms of NVIDIA OMNIVERSE LICENSE AGREEMENT (EULA) + in https://docs.isaacsim.omniverse.nvidia.com/latest/common/NVIDIA_Omniverse_License_Agreement.html + + Do you accept the EULA? (Yes/No): Yes + + +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 `__ +and the +`Isaac Sim Forums `_. diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/include/selective_install.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/include/selective_install.rst new file mode 100644 index 0000000000000000000000000000000000000000..7b1a86f6d3eff3e1d89ddd66ded362f5c1c88207 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/include/selective_install.rst @@ -0,0 +1,104 @@ +Modularized Installation +~~~~~~~~~~~~~~~~~~~~~~~~ + +``./isaaclab.sh -i`` (or ``isaaclab.bat -i``) **always** installs all core +source packages. Additional arguments can control which **optional** submodules and +**extra feature dependencies** are installed. + +**Default behavior:** ``./isaaclab.sh --install`` or ``./isaaclab.sh -i`` +are equivalent to ``./isaaclab.sh -i all``. +That installs optional submodules (``mimic``, ``teleop``) and automatic extra +features (``newton``, ``rl``, ``visualizer``) on top of the core set. It does +**not** install ``contrib`` or ``ov`` runtime wheels or the Isaac Sim pip +package—request those explicitly when needed. + +**Special values:** + +- ``all`` — same as the default behavior above. +- ``core`` — core packages only; no optional submodules, no extra feature + dependencies. + +**Optional submodules** (installed only when requested or with ``all``): + +.. list-table:: + :header-rows: 1 + + * - Token + - What it installs + * - ``mimic`` + - ``isaaclab_teleop`` and ``isaaclab_mimic`` (imitation-learning tools) + * - ``teleop`` + - ``isaaclab_teleop`` only (Linux x86_64) + +**Extra feature sets** (optional heavy dependencies on core packages): + +.. list-table:: + :header-rows: 1 + + * - Token + - What it installs + * - ``newton`` + - Newton physics dependencies on ``isaaclab_newton``, ``isaaclab_physx``, + and ``isaaclab_visualizers`` (selectors are not supported) + * - ``rl[]`` + - RL framework extras on ``isaaclab_rl``. Selectors: ``rsl-rl``, ``skrl``, + ``sb3``, ``rl-games``. Omit the selector to install all frameworks. + * - ``visualizer[]`` + - Visualizer backend extras on ``isaaclab_visualizers``. Selectors: + ``rerun``, ``viser``, ``newton``, ``kit``. Omit the selector for all + backends. + * - ``contrib[]`` + - Contrib runtime extras. Selector: ``rlinf``. Bare ``contrib`` installs + no additional dependencies (the source package is already in core). + * - ``ov[]`` + - OV runtime wheels. Selectors: ``ovrtx``, ``ovphysx``, ``all``. Bare + ``ov`` installs no additional dependencies (the source packages are + already in core). + * - ``isaacsim`` + - Isaac Sim pip package (via the install script; use only when Isaac Sim + is not already installed) + +``contrib`` and ``ov`` are **not** part of the default ``all`` install. Request +them explicitly when you need rlinf, OVRTX, or OVPhysX runtimes. + +Pass a comma-separated list to combine tokens (commas inside ``[...]`` are +preserved). Unknown tokens emit a warning and are skipped. + +Examples: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + # Default: core + optional submodules + newton/rl/visualizer extras + ./isaaclab.sh -i + + # Newton physics + RSL-RL (common kit-less setup) + ./isaaclab.sh -i 'newton,rl[rsl-rl]' + + # Newton + OVRTX renderer + RSL-RL + Newton visualizer + ./isaaclab.sh -i 'newton,ov[ovrtx],rl[rsl-rl],visualizer[newton]' + + # Contrib rlinf runtime dependencies + ./isaaclab.sh -i 'contrib[rlinf]' + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + :: Default: core + optional submodules + newton/rl/visualizer extras + isaaclab.bat -i + + :: Newton physics + RSL-RL + isaaclab.bat -i "newton,rl[rsl-rl]" + + :: Newton + OVRTX + RSL-RL + Newton visualizer + isaaclab.bat -i "newton,ov[ovrtx],rl[rsl-rl],visualizer[newton]" + + :: Contrib rlinf runtime dependencies + isaaclab.bat -i "contrib[rlinf]" diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_build_isaaclab.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_build_isaaclab.rst new file mode 100644 index 0000000000000000000000000000000000000000..0b2b042bc6212dba2ed497b1c29418a348d16a9e --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_build_isaaclab.rst @@ -0,0 +1,41 @@ +Installation +~~~~~~~~~~~~ + +- Install dependencies using ``apt`` (on Linux only): + + .. code:: bash + + # these dependencies are needed by robomimic which is not available on Windows + sudo apt install cmake build-essential + + On **aarch64** systems (e.g., DGX Spark), Python, OpenGL and X11 development packages are also required. + The ``imgui-bundle`` and ``quadprog`` dependencies do not provide pre-built wheels for aarch64 and must be + compiled from source, which needs these headers and libraries: + + .. code:: bash + + sudo apt install python3.12-dev libgl1-mesa-dev libx11-dev libxcursor-dev libxi-dev libxinerama-dev libxrandr-dev + +- Install Isaac Lab from the repository root: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh --install # or ./isaaclab.sh -i + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat --install :: or isaaclab.bat -i + + By default this installs core packages plus optional submodules (``mimic``, + ``teleop``) and the automatic extra features (``newton``, ``rl``, + ``visualizer``). For the full token reference and examples, see + :ref:`installation-selective-install`. diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_clone_isaaclab.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_clone_isaaclab.rst new file mode 100644 index 0000000000000000000000000000000000000000..f051166788d54b513b3dc29205b9c95cae527ae1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_clone_isaaclab.rst @@ -0,0 +1,97 @@ +Cloning Isaac Lab +~~~~~~~~~~~~~~~~~ + +.. note:: + + We recommend making a `fork `_ of the Isaac Lab repository to contribute + to the project but this is not mandatory to use the framework. If you + make a fork, please replace ``isaac-sim`` with your username + in the following instructions. + +Clone the Isaac Lab repository into your project's workspace: + +.. isaaclab-clone-commands:: + +We provide helper executables at the repository root — ``./isaaclab.sh`` (Linux) and +``isaaclab.bat`` (Windows) — that provide utilities to manage extensions. + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: text + + ./isaaclab.sh --help + + usage: isaaclab.sh [-h] [-i [INSTALL]] [-f] [-p ...] [-s ...] [-t ...] [-o ...] [-v] [-d] [-n ...] [-c [CONDA]] [-u [UV]] + + Isaac Lab CLI + + options: + -h, --help show this help message and exit + -i [INSTALL], --install [INSTALL] + Install Isaac Lab submodules and RL frameworks. + Accepts a comma-separated list of submodule names, one of the RL frameworks, or a special value. + + Isaac Lab Submodules: assets, physx, contrib, mimic, newton, ov, rl, tasks, teleop, visualizers. + Any submodule accepts an editable selector, e.g. visualizers[all|kit|newton|rerun|viser], rl[rsl_rl|skrl]. + RL frameworks: rl_games, rsl_rl, sb3, skrl, robomimic. + + Passing an RL framework name installs all Isaac Lab submodules + that framework. + + Special values: + - all - Install all Isaac Lab submodules + all RL frameworks (default). + - none - Install only the core 'isaaclab' package. + - (-i or --install without value) - Install all Isaac Lab submodules + all RL frameworks. + -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 pytest 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. + -n ..., --new ... Create a new external project or internal task from template. + -c [CONDA], --conda [CONDA] + Create a new conda environment for Isaac Lab. Default name is 'env_isaaclab'. + -u [UV], --uv [UV] Create a new uv environment for Isaac Lab. Default name is 'env_isaaclab'. + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: text + + isaaclab.bat --help + + usage: isaaclab.bat [-h] [-i [INSTALL]] [-f] [-p ...] [-s ...] [-t ...] [-o ...] [-v] [-d] [-n ...] [-c [CONDA]] [-u [UV]] + + Isaac Lab CLI + + options: + -h, --help show this help message and exit + -i [INSTALL], --install [INSTALL] + Install Isaac Lab submodules and RL frameworks. + Accepts a comma-separated list of submodule names, one of the RL frameworks, or a special value. + + Isaac Lab Submodules: assets, physx, contrib, mimic, newton, ov, rl, tasks, teleop, visualizers. + Any submodule accepts an editable selector, e.g. visualizers[all|kit|newton|rerun|viser], rl[rsl_rl|skrl]. + RL frameworks: rl_games, rsl_rl, sb3, skrl, robomimic. + + Passing an RL framework name installs all Isaac Lab submodules + that framework. + + Special values: + - all - Install all Isaac Lab submodules + all RL frameworks (default). + - none - Install only the core 'isaaclab' package. + - (-i or --install without value) - Install all Isaac Lab submodules + all RL frameworks. + -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.bat) provided by Isaac Sim. + -t ..., --test ... Run all python pytest 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. + -n ..., --new ... Create a new external project or internal task from template. + -c [CONDA], --conda [CONDA] + Create a new conda environment for Isaac Lab. Default name is 'env_isaaclab'. + -u [UV], --uv [UV] Create a new uv environment for Isaac Lab. Default name is 'env_isaaclab'. diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_python_virtual_env.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_python_virtual_env.rst new file mode 100644 index 0000000000000000000000000000000000000000..6826397f6223866fe5ba9e390061432e27817263 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_python_virtual_env.rst @@ -0,0 +1,136 @@ +Setting up a Python Environment (optional) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. attention:: + This step is optional. If you are using the bundled Python with Isaac Sim, you can skip this step. + +Creating a dedicated Python environment for Isaac Lab is **strongly recommended**, even though +it is optional. Using a virtual environment helps: + +- **Avoid conflicts with system Python** or other projects installed on your machine. +- **Keep dependencies isolated**, so that package upgrades or experiments in other projects + do not break Isaac Sim. +- **Easily manage multiple environments** for setups with different versions of dependencies. +- **Simplify reproducibility** — the environment contains only the packages needed for the current project, + making it easier to share setups with colleagues or run on different machines. + + +You can choose different package managers to create a virtual environment. + +- **UV**: A modern, fast, and secure package manager for Python. +- **Conda**: A cross-platform, language-agnostic package manager for Python. + +Once created, you can use the default Python in the virtual environment (*python* or *python3*) +instead of *./isaaclab.sh -p* or *isaaclab.bat -p*. + +.. caution:: + + The Python version of the virtual environment must match the Python version of Isaac Sim. + + - For Isaac Sim 6.X, the required Python version is 3.12. + + Using a different Python version will result in errors when running Isaac Lab. + + +.. tab-set:: + + .. tab-item:: UV Environment (Recommended) + + To install ``uv``, please follow the instructions `here `__. + You can create the Isaac Lab environment using the following commands: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + # Option 1: Default environment name 'env_isaaclab' + ./isaaclab.sh --uv # or "./isaaclab.sh -u" + # Option 2: Custom name + ./isaaclab.sh --uv my_env # or "./isaaclab.sh -u my_env" + + .. code:: bash + + # Activate environment + source ./env_isaaclab/bin/activate # or "source ./my_env/bin/activate" + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: Option 1: Default environment name 'env_isaaclab' + isaaclab.bat --uv :: or "isaaclab.bat -u" + :: Option 2: Custom name + isaaclab.bat --uv my_env :: or "isaaclab.bat -u my_env" + + .. code:: batch + + :: Activate environment + env_isaaclab\Scripts\activate :: or "my_env\Scripts\activate" + + .. note:: + + You can also create the environment manually with ``uv venv --python 3.12 --seed env_isaaclab``. + The ``--seed`` flag ensures ``pip`` is available inside the venv, which the Isaac Lab installer + requires. + + .. tab-item:: Conda Environment + + To install conda, please follow the instructions `here `__. + You can create the Isaac Lab environment using the following commands. + + We recommend using `Miniconda `_, + since it is light-weight and resource-efficient environment management system. + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + # Option 1: Default environment name 'env_isaaclab' + ./isaaclab.sh --conda # or "./isaaclab.sh -c" + # Option 2: Custom name + ./isaaclab.sh --conda my_env # or "./isaaclab.sh -c my_env" + + .. code:: bash + + # Activate environment + conda activate env_isaaclab # or "conda activate my_env" + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: Option 1: Default environment name 'env_isaaclab' + isaaclab.bat --conda :: or "isaaclab.bat -c" + :: Option 2: Custom name + isaaclab.bat --conda my_env :: or "isaaclab.bat -c my_env" + + .. code:: batch + + :: Activate environment + conda activate env_isaaclab :: or "conda activate my_env" + + .. note:: + + On Windows, ``isaaclab.bat`` sources ``_isaac_sim\setup_conda_env.bat`` to + export the Isaac Sim environment variables. Some Isaac Sim binary zips do + not ship this file; in that case, ``isaaclab.bat`` prints a non-fatal warning + and Isaac Sim env vars are not exported, which later surfaces as an + ``Isaac Sim is not installed or not found on PYTHONPATH`` error at script + launch. Re-extract a build that includes ``setup_conda_env.bat``, or set + the Isaac Sim environment variables yourself before running ``isaaclab.bat``. + +Once you are in the virtual environment, you do not need to use ``./isaaclab.sh -p`` or +``isaaclab.bat -p`` to run python scripts. You can use the default python executable in your +environment by running ``python`` or ``python3``. Updated how-to guides use ``python`` directly; +older pages may still show ``./isaaclab.sh -p`` or ``isaaclab.bat -p``, which are equivalent when +your virtual environment is active. diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_symlink_isaacsim.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_symlink_isaacsim.rst new file mode 100644 index 0000000000000000000000000000000000000000..be8ae17cdbd2825150b5dec7c47321193c5aec85 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_symlink_isaacsim.rst @@ -0,0 +1,43 @@ +Creating the Isaac Sim Symbolic Link +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Set up a symbolic link between the installed Isaac Sim root folder +and ``_isaac_sim`` in the Isaac Lab directory. This makes it convenient +to index the python modules and look for extensions shipped with Isaac Sim. + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + # enter the cloned repository + cd IsaacLab + # create a symbolic link + ln -s ${ISAACSIM_PATH} _isaac_sim + + # For example: + # Option 1: If pre-built binaries were installed: + # ln -s ${HOME}/isaacsim _isaac_sim + # + # Option 2: If Isaac Sim was built from source: + # ln -s ${HOME}/IsaacSim/_build/linux-x86_64/release _isaac_sim + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: enter the cloned repository + cd IsaacLab + :: create a symbolic link - requires launching Command Prompt with Administrator access + mklink /D _isaac_sim %ISAACSIM_PATH% + + :: For example: + :: Option 1: If pre-built binaries were installed: + :: mklink /D _isaac_sim C:\isaacsim + :: + :: Option 2: If Isaac Sim was built from source: + :: mklink /D _isaac_sim C:\IsaacSim\_build\windows-x86_64\release diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_verify_isaaclab.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_verify_isaaclab.rst new file mode 100644 index 0000000000000000000000000000000000000000..267fd7e5e3553f13e69defcde08e2a7c94002c5c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/include/src_verify_isaaclab.rst @@ -0,0 +1,101 @@ +Verifying the Isaac Lab installation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To verify that the installation was successful, run the following command from the +top of the repository: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + # Option 1: Using the isaaclab.sh executable + # note: this works for both the bundled python and the virtual environment + ./isaaclab.sh -p scripts/tutorials/00_sim/create_empty.py --viz kit + + # Option 2: Using python in your virtual environment + python scripts/tutorials/00_sim/create_empty.py --viz kit + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: Option 1: Using the isaaclab.bat executable + :: note: this works for both the bundled python and the virtual environment + isaaclab.bat -p scripts\tutorials\00_sim\create_empty.py --viz kit + + :: Option 2: Using python in your virtual environment + python scripts\tutorials\00_sim\create_empty.py --viz kit + + +The above command should launch the simulator and display a window with a black +viewport. You can exit the script by pressing ``Ctrl+C`` on your terminal. +On Windows machines, please terminate the process from Command Prompt using +``Ctrl+Break`` or ``Ctrl+fn+B``. + +.. figure:: /source/_static/setup/verify_install.jpg + :align: center + :figwidth: 100% + :alt: Simulator with a black window. + + +If you see this, then the installation was successful! |:tada:| + +.. note:: + + If you see an error ``ModuleNotFoundError: No module named 'isaacsim'``, please ensure that the virtual + environment is activated and ``source _isaac_sim/setup_conda_env.sh`` has been executed (for uv as well). + + +Train a robot! +~~~~~~~~~~~~~~ + +You can now use Isaac Lab to train a robot through Reinforcement Learning! The quickest way to use Isaac Lab is through the predefined workflows using one of our **Batteries-included** robot tasks. Execute the following command to quickly train an ant to walk! + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh train --rl_library rsl_rl --task=Isaac-Ant-v0 + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat train --rl_library rsl_rl --task=Isaac-Ant-v0 + +... Or a robot dog! + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + ./isaaclab.sh train --rl_library rsl_rl --task=Isaac-Velocity-Rough-Anymal-C-v0 + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + isaaclab.bat train --rl_library rsl_rl --task=Isaac-Velocity-Rough-Anymal-C-v0 + +Isaac Lab provides the tools you'll need to create your own **Tasks** and **Workflows** for whatever your project needs may be. +Take a look at our :ref:`how-to` like :ref:`Adding your own learning Library ` or :ref:`Wrapping Environments ` for details. + +.. figure:: /source/_static/setup/isaac_ants_example.jpg + :align: center + :figwidth: 100% + :alt: Idle hands... diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/index.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..99ba2e45dbbfa9873f1159c16935e7c3ffb2264a --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/index.rst @@ -0,0 +1,239 @@ +.. _isaaclab-installation-root: + +Local Installation +================== + +.. image:: https://img.shields.io/badge/IsaacSim-6.0.1-silver.svg + :target: https://developer.nvidia.com/isaac-sim + :alt: IsaacSim 6.0.1 + +.. image:: https://img.shields.io/badge/python-3.12-blue.svg + :target: https://www.python.org/downloads/release/python-3120/ + :alt: Python 3.12 + +.. image:: https://img.shields.io/badge/platform-linux--64-orange.svg + :target: https://releases.ubuntu.com/22.04/ + :alt: Ubuntu 22.04 + +.. image:: https://img.shields.io/badge/platform-windows--64-orange.svg + :target: https://www.microsoft.com/en-ca/windows/windows-11 + :alt: Windows 11 + + + +.. note:: + + **Isaac Lab 3.0 supports kit-less installation.** You can install and use Isaac Lab with the + Newton physics backend *without* installing Isaac Sim. Clone Isaac Lab and run: + + .. isaaclab-kitless-install-snippet:: + + This installs the core Isaac Lab packages and the Newton physics backend. Isaac Sim is **not** + required for this mode. See :doc:`kitless_installation` for which features are available + without Isaac Sim. + + When you need full simulation features — including PhysX, ROS, URDF/MJCF + importers — install Isaac Sim via pip (see the + :doc:`pip_installation` guide). + +.. caution:: + + We have dropped support for Isaac Sim versions 5.1.0 and below. We recommend using the latest + Isaac Sim 6.0.1 release to benefit from the latest features and improvements. + + For more information, please refer to the + `Isaac Sim release notes `__. + + +System Requirements +------------------- + +.. warning:: + + Windows support is still being completed, so some workflows may not work as expected. + For the most reliable installation and runtime experience, we recommend using Ubuntu 24.04. + +General Requirements +~~~~~~~~~~~~~~~~~~~~ + +For detailed requirements, please see the +`Isaac Sim system requirements `_. +The basic requirements are: + +- **OS:** Ubuntu 22.04 (Linux x64) or Windows 11 (x64) +- **RAM:** 32 GB or more +- **GPU VRAM:** 16 GB or more (additional VRAM may be required for rendering workflows) + +**Isaac Sim is built against a specific Python version**, making +it essential to use the same Python version when installing Isaac Lab. +The required Python version is as follows: + +- For Isaac Sim 6.X, the required Python version is 3.12. + + +Driver Requirements +~~~~~~~~~~~~~~~~~~~ + +Drivers other than those recommended on `Omniverse Technical Requirements `_ +may work but have not been validated against all Omniverse tests. + +- Use the **latest NVIDIA production branch driver**. +- On Linux (x86_64 and aarch64), version ``580.95.05`` or later is recommended. +- On Spark (Linux aarch64), version ``580.142`` is recommended. +- On Windows, version ``581.42.00`` is recommended. +- If you are using a new GPU or encounter driver issues, install the latest production branch + driver from the `Unix Driver Archive `_ + using the ``.run`` installer. + +.. _dgx-spark-limitations: + +DGX Spark: details and limitations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The DGX spark is a standalone machine learning device with aarch64 architecture. As a consequence, some +features of Isaac Lab are not currently supported on the DGX spark. The most noteworthy is that the architecture *requires* CUDA ≥ 13, and thus the cu13 build of PyTorch or newer. +Other notable limitations with respect to Isaac Lab include... + +#. :doc:`SkillGen ` is not supported out of the box. This + is because cuRobo builds native CUDA/C++ extensions that requires specific tooling and library versions which are not validated for use with DGX spark. + +#. Extended reality teleoperation tools such as :class:`OpenXR ` is not supported. This is due + to encoding performance limitations that have not yet been fully investigated. + +#. Livestream and Hub Workstation Cache are not supported on the DGX spark. + +#. :ref:`Running Cosmos Transfer1 ` is not currently supported on the DGX Spark. + +#. Newton VBD deformable support is limited on DGX Spark because no pre-built + ``pytetwild`` wheel is available for ARM (aarch64). ``pytetwild`` is required for + automatic tetrahedral mesh generation of volume deformables. + +#. RLinf support has not been verified on DGX Spark. + +.. note:: + + **Build prerequisites on aarch64:** Some Python packages (notably ``imgui-bundle`` and ``quadprog``) do not ship + pre-built wheels for aarch64 and are compiled from source during installation. This requires + Python 3.12, OpenGL, and X11 development headers to be installed on the system: + + .. code-block:: bash + + sudo apt install python3.12-dev libgl1-mesa-dev libx11-dev libxcursor-dev libxi-dev libxinerama-dev libxrandr-dev + + Without these packages, the build will fail with a CMake error about missing ``OPENGL_opengl_LIBRARY``, + ``OPENGL_glx_LIBRARY``, and ``OPENGL_INCLUDE_DIR``. + +Troubleshooting +~~~~~~~~~~~~~~~ + +Please refer to the `Linux Troubleshooting `_ +to resolve installation issues in Linux. + +You can use `Isaac Sim Compatibility Checker `_ +to automatically check if the above requirements are met for running Isaac Sim on your system. + +Isaac Sim Installation +---------------------- + +For most users, the simplest and fastest way to install Isaac Lab with full Isaac Sim support +is by following the :doc:`pip_installation` guide. We recommend using **uv** as the package +manager for the fastest and most reliable installation experience. + +This method installs Isaac Sim via pip and Isaac Lab from source. +If you are new to Isaac Lab, start here. + + +Choosing an Installation Method +-------------------------------- + +Different workflows require different installation methods. +Use this table to decide: + ++---------------------+------------------------------+------------------------------+-------------------------------+------------+ +| Method | Isaac Sim | Isaac Lab | Best For | Difficulty | ++=====================+==============================+==============================+===============================+============+ +| **Kit-less (beta)** | |:x:| not required | |:floppy_disk:| source (git) | Newton-only, fastest start | Easiest | ++---------------------+------------------------------+------------------------------+-------------------------------+------------+ +| **Pip (uv)** | |:package:| pip install | |:floppy_disk:| source (git) | Most users, full features | Easy | +| **(Recommended)** | | | | | ++---------------------+------------------------------+------------------------------+-------------------------------+------------+ +| Binary + Source | |:inbox_tray:| binary | |:floppy_disk:| source (git) | Users preferring binary | Easy | +| | download | | install of Isaac Sim | | +| | | | *(conda/uv/venv unsupported; | | +| | | | use bundled Python or pip)* | | ++---------------------+------------------------------+------------------------------+-------------------------------+------------+ +| Full Source Build | |:floppy_disk:| source (git) | |:floppy_disk:| source (git) | Developers modifying both | Advanced | ++---------------------+------------------------------+------------------------------+-------------------------------+------------+ +| Pip Only | |:package:| pip install | |:package:| pip install | External extensions only | Special | +| | | | (no training/examples). | case | +| | | | Use ``[isaacsim,all]``. | | ++---------------------+------------------------------+------------------------------+-------------------------------+------------+ +| Docker | |:whale:| Docker | |:floppy_disk:| source (git) | Docker users | Advanced | ++---------------------+------------------------------+------------------------------+-------------------------------+------------+ + +Next Steps +---------- + +Once you've reviewed the installation methods, continue with the guide that matches your workflow: + +- |:rocket:| :doc:`kitless_installation` + + - Install Isaac Lab without Isaac Sim. + - Uses the Newton physics backend. + - Best for getting started immediately or when Isaac Sim is not needed. + +- |:smiley:| :doc:`pip_installation` **(Recommended for full features)** + + - Install Isaac Sim via pip (preferably with **uv**) and Isaac Lab from source. + - Best for most users who need full simulation capabilities. + +- :doc:`binaries_installation` + + - Install Isaac Sim from its binary package (website download). + - Install Isaac Lab from its source code. + - Choose this if you prefer not to use pip for Isaac Sim (for instance, on Ubuntu 20.04). + +- :doc:`source_installation` + + - Build Isaac Sim from source. + - Install Isaac Lab from its source code. + - Recommended only if you plan to modify Isaac Sim itself. + +- :doc:`isaaclab_pip_installation` + + - Install Isaac Sim and Isaac Lab as pip packages with ``isaaclab[isaacsim,all]``. + - Best for advanced users building **external extensions** with custom runner scripts. + - Note: This does **not** include training or example scripts. + +- :ref:`container-deployment` + + - Install Isaac Sim and Isaac Lab in a Docker container. + - Best for users who want to use Isaac Lab in a containerized environment. + + +Asset Caching +------------- + +Isaac Lab assets are hosted on **AWS S3 cloud storage**. Loading times can vary +depending on your **network connection** and **geographical location**, and in some cases, +assets may take several minutes to load for each run. To improve performance or support +**offline workflows**, we recommend enabling **asset caching**. + +- Cached assets are stored locally, reducing repeated downloads. +- This is especially useful if you have a slow or intermittent internet connection, + or if your deployment environment is offline. + +Please follow the steps :doc:`asset_caching` to enable asset caching and speed up your workflow. + + +.. toctree:: + :maxdepth: 1 + :hidden: + + kitless_installation + pip_installation + binaries_installation + source_installation + isaaclab_pip_installation + asset_caching + uv run (experimental) diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/isaaclab_pip_installation.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/isaaclab_pip_installation.rst new file mode 100644 index 0000000000000000000000000000000000000000..fe815b148afa563c8d4e2208b15063a3568bef52 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/isaaclab_pip_installation.rst @@ -0,0 +1,170 @@ +Installation using Isaac Lab Pip Packages +========================================= + +From Isaac Lab 2.0, pip packages are provided to install both Isaac Sim and Isaac Lab extensions from pip. +Note that this installation process is only recommended for advanced users working on additional extension projects +that are built on top of Isaac Lab. Isaac Lab pip packages **does not** include any standalone python scripts for +training, inferencing, or running standalone workflows such as demos and examples. Therefore, users are required +to define their own runner scripts when installing Isaac Lab from pip. + +To learn about how to set up your own project on top of Isaac Lab, please see :ref:`template-generator`. + +.. note:: + + Currently, we only provide pip packages for every major release of Isaac Lab. + For example, we provide the pip package for release 2.1.0 and 2.2.0, but not 2.1.1. + In the future, we will provide pip packages for every minor release of Isaac Lab. + +.. include:: include/pip_python_virtual_env.rst + +Installing Isaac Lab +~~~~~~~~~~~~~~~~~~~~ + +The ``isaaclab`` pip wheel bundles all Isaac Lab extensions. Common optional +pip extras include: + +.. list-table:: + :header-rows: 1 + :widths: 18 52 + + * - Extra + - What it installs + * - ``isaacsim`` + - Isaac Sim (``isaacsim[all,extscache]==6.0.1.0``) from `pypi.nvidia.com `_ + * - ``all`` + - RL frameworks (SB3, SKRL, RSL-RL). Combine with ``isaacsim`` for a full install. + +Install with ``isaaclab[isaacsim,all]`` for the full workflow. + +.. tab-set:: + + .. tab-item:: uv + + .. code-block:: bash + + uv pip install "isaaclab[isaacsim,all]" --extra-index-url https://pypi.nvidia.com --index-strategy unsafe-best-match --prerelease=allow + + .. tab-item:: pip + + .. code-block:: bash + + pip install "isaaclab[isaacsim,all]" --extra-index-url https://pypi.nvidia.com --pre + +.. note:: + + ``rl_games`` is not included in the Isaac Lab pip wheel extras. If your workflow requires + ``rl_games``, install it manually from the Isaac Lab-compatible branch: + + .. code-block:: bash + + pip install "rl-games @ git+https://github.com/isaac-sim/rl_games.git@python3.11" gym standard-distutils + +Installing dependencies +~~~~~~~~~~~~~~~~~~~~~~~ + +- Install a CUDA-enabled PyTorch 2.10.0 build that matches your system architecture: + + .. tab-set:: + :sync-group: pip-platform + + .. tab-item:: :icon:`fa-brands fa-linux` Linux (x86_64) + :sync: linux-x86_64 + + .. code-block:: bash + + pip install -U torch==2.10.0 torchvision==0.25.0 --index-url https://download.pytorch.org/whl/cu128 + + .. tab-item:: :icon:`fa-brands fa-windows` Windows (x86_64) + :sync: windows-x86_64 + + .. code-block:: bash + + pip install -U torch==2.10.0 torchvision==0.25.0 --index-url https://download.pytorch.org/whl/cu128 + + .. tab-item:: :icon:`fa-brands fa-linux` Linux (aarch64) + :sync: linux-aarch64 + + .. code-block:: bash + + pip install -U torch==2.10.0 torchvision==0.25.0 --index-url https://download.pytorch.org/whl/cu130 + + .. note:: + + On aarch64 (e.g., DGX Spark), ``imgui-bundle`` and ``quadprog`` must be compiled from source because no + pre-built wheel is available. Install the required Python, OpenGL, and X11 development packages + **before** installing Isaac Lab: + + .. code-block:: bash + + sudo apt install python3.12-dev libgl1-mesa-dev libx11-dev libxcursor-dev libxi-dev libxinerama-dev libxrandr-dev + + .. note:: + + After installing Isaac Lab on aarch64, you may encounter warnings such as: + + .. code-block:: none + + ERROR: ld.so: object '...torch.libs/libgomp-XXXX.so.1.0.0' cannot be preloaded: ignored. + + This occurs when both the system and PyTorch ``libgomp`` (GNU OpenMP) libraries are preloaded. + Isaac Sim expects the **system** OpenMP runtime, while PyTorch sometimes bundles its own. + + To fix this, unset any existing ``LD_PRELOAD`` and set it to use the system library only: + + .. code-block:: bash + + unset LD_PRELOAD + export LD_PRELOAD=/lib/aarch64-linux-gnu/libgomp.so.1 + + This ensures the correct ``libgomp`` library is preloaded for both Isaac Sim and Isaac Lab, + removing the preload warnings during runtime. + + .. note:: + + On aarch64, you may encounter the following error when importing ``omni.client`` or ``torch``: + + .. code-block:: none + + ImportError: .../libcarb.so: cannot allocate memory in static TLS block + + This happens because ``libcarb.so`` uses the *initial-exec* TLS model, and + the dynamic linker's fixed-size TLS surplus is exhausted by the time it is loaded. + To fix this, preload ``libcarb.so`` before launching Python: + + .. code-block:: bash + + export LD_PRELOAD=$(python -c "import sys,os;[print(os.path.join(p,'omni','client','libcarb.so')) for p in sys.path if os.path.isfile(os.path.join(p,'omni','client','libcarb.so'))]" 2>/dev/null | head -1)${LD_PRELOAD:+:$LD_PRELOAD} + + When using ``./isaaclab.sh -p``, this is handled automatically. + When using a conda environment, + the preload is set up via the conda activation hook. + +.. include:: include/pip_verify_isaacsim.rst + +Running Isaac Lab Scripts +~~~~~~~~~~~~~~~~~~~~~~~~~ + +By following the above scripts, your Python environment should now have access to all of the Isaac Lab extensions. +To run a user-defined script for Isaac Lab, simply run + +.. code:: bash + + python my_awesome_script.py + +Generating VS Code Settings +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Due to the structure resulting from the installation, VS Code IntelliSense (code completion, parameter info +and member lists, etc.) will not work by default. To set it up (define the search paths for import resolution, +the path to the default Python interpreter, and other settings), for a given workspace folder, +run the following command: + +.. code-block:: bash + + python -m isaaclab --generate-vscode-settings + + +.. warning:: + + The command will generate a ``.vscode/settings.json`` file in the workspace folder. + If the file already exists, it will be overwritten (a confirmation prompt will be shown first). diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/kitless_installation.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/kitless_installation.rst new file mode 100644 index 0000000000000000000000000000000000000000..6f68a4a364297fd02f16fdf8aae2e250fe7c6066 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/kitless_installation.rst @@ -0,0 +1,79 @@ +.. _kitless-installation: + +Kit-less Installation +===================== + +Isaac Lab can be installed and used **without Isaac Sim** using the kit-less mode. This is the +fastest way to get started and is ideal for users who only need the Newton physics backend. + +Cloning Isaac Lab +----------------- + +Clone the repository: + +.. isaaclab-clone-commands:: + +.. include:: include/pip_python_virtual_env.rst + +Installing Isaac Lab +-------------------- + +With the virtual environment activated, install Isaac Lab (Newton backend, no Isaac Sim required) +and kickoff training with MJWarp physics and the Newton visualizer: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + # Install Isaac Lab (Newton backend, no Isaac Sim required) + ./isaaclab.sh --install # or ./isaaclab.sh -i + + # Kickoff training with MJWarp physics and Newton visualizer + ./isaaclab.sh train --rl_library rsl_rl \ + --task=Isaac-Cartpole-Direct-v0 \ + --num_envs=16 --max_iterations=10 \ + physics=newton_mjwarp --visualizer newton + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + :: Install Isaac Lab (Newton backend, no Isaac Sim required) + :: or: isaaclab.bat -i + isaaclab.bat --install + + :: Kickoff training with MJWarp physics and Newton visualizer + isaaclab.bat train --rl_library rsl_rl ^ + --task=Isaac-Cartpole-Direct-v0 ^ + --num_envs=16 --max_iterations=10 ^ + physics=newton_mjwarp --visualizer newton + + +**Features available in kit-less mode (Newton backend, no Isaac Sim):** + +- Newton physics simulation (GPU-accelerated, including MuJoCo-Warp solver) +- All manager-based and direct RL environments that support Newton +- RL training with SKRL, RSL-RL, and other frameworks +- Robot assets compatible with Newton +- ovphysx and ovrtx backends + +**Features that require Isaac Sim:** + +- Isaac Sim PhysX physics backend (not ovphysx) +- Isaac Sim RTX rendering (not ovrtx) +- Kit visualizer +- URDF and MJCF importers (GUI-based) +- Surface gripper (Isaac Sim PhysX-only) +- PhysX Deformable simulation (Isaac Sim PhysX-only) +- Teleoperation and imitation learning workflows + +To install Isaac Sim, use the pip method described in :doc:`pip_installation`. + +.. _installation-selective-install: + +.. include:: include/selective_install.rst diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/pip_installation.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/pip_installation.rst new file mode 100644 index 0000000000000000000000000000000000000000..6f0a413cdd76647d9ad41780f7e47cdcae37ca56 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/pip_installation.rst @@ -0,0 +1,132 @@ +.. _isaaclab-pip-installation: + +Installation using Isaac Sim Pip Package +======================================== + +The following steps first installs Isaac Sim from pip, then Isaac Lab from source code. + +.. attention:: + + Installing Isaac Sim with pip requires GLIBC 2.35+ version compatibility. + To check the GLIBC version on your system, use command ``ldd --version``. + + This may pose compatibility issues with some Linux distributions. For instance, Ubuntu 20.04 LTS + has GLIBC 2.31 by default. If you encounter compatibility issues, we recommend following the + :ref:`Isaac Sim Binaries Installation ` approach. + +.. note:: + + If you plan to :ref:`Set up Visual Studio Code ` later, we recommend following the + :ref:`Isaac Sim Binaries Installation ` approach. + +Installing Isaac Sim +-------------------- + +From Isaac Sim 4.0 onwards, it is possible to install Isaac Sim using pip. +This approach makes it easier to install Isaac Sim without requiring to download the Isaac Sim binaries. +If you encounter any issues, please report them to the +`Isaac Sim Forums `_. + +.. attention:: + + On Windows, it may be necessary to `enable long path support `_ + to avoid installation errors due to OS limitations. + +.. include:: include/pip_python_virtual_env.rst + +Installing dependencies +~~~~~~~~~~~~~~~~~~~~~~~ + +.. note:: + + On aarch64 (e.g., DGX Spark), ``imgui-bundle`` and ``quadprog`` must be compiled from source because no + pre-built wheel is available. Install the required Python, OpenGL, and X11 development packages + **before** installing Isaac Lab: + + .. code-block:: bash + + sudo apt install python3.12-dev libgl1-mesa-dev libx11-dev libxcursor-dev libxi-dev libxinerama-dev libxrandr-dev + +- Install Isaac Sim pip packages: + + .. code-block:: bash + + uv pip install "isaacsim[all,extscache]==6.0.1.0" --extra-index-url https://pypi.nvidia.com --index-strategy unsafe-best-match --prerelease=allow + +- Install a CUDA-enabled PyTorch build that matches your system architecture: + + .. tab-set:: + :sync-group: pip-platform + + .. tab-item:: :icon:`fa-brands fa-linux` Linux (x86_64) + :sync: linux-x86_64 + + .. code-block:: bash + + uv pip install -U torch==2.10.0 torchvision==0.25.0 --index-url https://download.pytorch.org/whl/cu128 + + .. tab-item:: :icon:`fa-brands fa-windows` Windows (x86_64) + :sync: windows-x86_64 + + .. code-block:: bash + + uv pip install -U torch==2.10.0 torchvision==0.25.0 --index-url https://download.pytorch.org/whl/cu128 + + .. tab-item:: :icon:`fa-brands fa-linux` Linux (aarch64) + :sync: linux-aarch64 + + .. code-block:: bash + + uv pip install -U torch==2.10.0 torchvision==0.25.0 --index-url https://download.pytorch.org/whl/cu130 + + .. note:: + + After installing Isaac Lab on aarch64, you may encounter warnings such as: + + .. code-block:: none + + ERROR: ld.so: object '...torch.libs/libgomp-XXXX.so.1.0.0' cannot be preloaded: ignored. + + This occurs when both the system and PyTorch ``libgomp`` (GNU OpenMP) libraries are preloaded. + Isaac Sim expects the **system** OpenMP runtime, while PyTorch sometimes bundles its own. + + To fix this, unset any existing ``LD_PRELOAD`` and set it to use the system library only: + + .. code-block:: bash + + unset LD_PRELOAD + export LD_PRELOAD=/lib/aarch64-linux-gnu/libgomp.so.1 + + This ensures the correct ``libgomp`` library is preloaded for both Isaac Sim and Isaac Lab, + removing the preload warnings during runtime. + + .. note:: + + On aarch64, you may encounter the following error when importing ``omni.client`` or ``torch``: + + .. code-block:: none + + ImportError: .../libcarb.so: cannot allocate memory in static TLS block + + This happens because ``libcarb.so`` uses the *initial-exec* TLS model, and + the dynamic linker's fixed-size TLS surplus is exhausted by the time it is loaded. + To fix this, preload ``libcarb.so`` before launching Python: + + .. code-block:: bash + + export LD_PRELOAD=$(python -c "import sys,os;[print(os.path.join(p,'omni','client','libcarb.so')) for p in sys.path if os.path.isfile(os.path.join(p,'omni','client','libcarb.so'))]" 2>/dev/null | head -1)${LD_PRELOAD:+:$LD_PRELOAD} + + When using ``./isaaclab.sh -p``, this is handled automatically. + When using a conda environment, + the preload is set up via the conda activation hook. + +.. include:: include/pip_verify_isaacsim.rst + +Installing Isaac Lab +-------------------- + +.. include:: include/src_clone_isaaclab.rst + +.. include:: include/src_build_isaaclab.rst + +.. include:: include/src_verify_isaaclab.rst diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/source_installation.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/source_installation.rst new file mode 100644 index 0000000000000000000000000000000000000000..50add4cdba2305d39c908c3169ab6f9e180de5a9 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/source_installation.rst @@ -0,0 +1,107 @@ +.. _isaaclab-source-installation: + +Installation using Isaac Sim Source Code +======================================== + +The following steps first installs Isaac Sim from source, then Isaac Lab from source code. + +.. note:: + + This is a more advanced installation method and is not recommended for most users. Only follow this method + if you wish to modify the source code of Isaac Sim as well. + +Installing Isaac Sim +-------------------- + +Building from source +~~~~~~~~~~~~~~~~~~~~ + +From Isaac Sim 5.0 release, it is possible to build Isaac Sim from its source code. +This approach is meant for users who wish to modify the source code of Isaac Sim as well, +or want to test Isaac Lab with the nightly version of Isaac Sim. + +The following instructions are adapted from the `Isaac Sim documentation `_ +for the convenience of users. + +.. attention:: + + Building Isaac Sim from source requires Ubuntu 22.04 LTS or higher. + +.. attention:: + + For details on driver requirements, please see the `Technical Requirements `_ guide! + + On Windows, it may be necessary to `enable long path support `_ to avoid installation errors due to OS limitations. + + +- Clone the Isaac Sim repository into your workspace: + + .. code:: bash + + git clone https://github.com/isaac-sim/IsaacSim.git + +- Build Isaac Sim from source: + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + cd IsaacSim + ./build.sh + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + cd IsaacSim + build.bat + + +Verifying the Isaac Sim installation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +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: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code:: bash + + # Isaac Sim root directory + export ISAACSIM_PATH="${PWD}/_build/linux-x86_64/release" + # Isaac Sim python executable + export ISAACSIM_PYTHON_EXE="${ISAACSIM_PATH}/python.sh" + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code:: batch + + :: Isaac Sim root directory + set ISAACSIM_PATH="%cd%\_build\windows-x86_64\release" + :: Isaac Sim python executable + set ISAACSIM_PYTHON_EXE="%ISAACSIM_PATH:"=%\python.bat" + +.. include:: include/bin_verify_isaacsim.rst + + +Installing Isaac Lab +-------------------- + +.. include:: include/src_clone_isaaclab.rst + +.. include:: include/src_symlink_isaacsim.rst + +.. include:: include/src_build_isaaclab.rst + +.. include:: include/src_verify_isaaclab.rst diff --git a/simulation/modules/IsaacLab/docs/source/setup/installation/uv_run.rst b/simulation/modules/IsaacLab/docs/source/setup/installation/uv_run.rst new file mode 100644 index 0000000000000000000000000000000000000000..ea0314b9c2a5d40d7dfb092a928547f2cfda3f01 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/installation/uv_run.rst @@ -0,0 +1,38 @@ +.. _uv-run-training: + +``uv run`` Training and Play (Experimental) +============================================ + +.. warning:: + + This feature is experimental and subject to change in future releases. + +Install ``uv`` if you do not have it already: + +.. code-block:: bash + + curl -LsSf https://astral.sh/uv/install.sh | sh + +Clone the repo and start training immediately — no virtual environment setup required: + +.. isaaclab-clone-commands:: + +.. code-block:: bash + + # Newton backend training without Isaac Sim + uv run train --rl_library rsl_rl \ + --task Isaac-Cartpole-Direct-v0 physics=newton_mjwarp + + # Add OVRTX/OVPhysX extras only when the workflow needs them + uv run --extra ov --extra rtx train --rl_library rsl_rl \ + --task Isaac-Cartpole-Direct-v0 physics=newton_mjwarp + +``uv`` resolves and manages the environment automatically on each invocation. Supported +libraries for ``--rl_library`` are: ``rsl_rl``, ``rl_games``, ``skrl``, ``sb3``, and ``rlinf``. + +Play / Evaluation +----------------- + +.. code-block:: bash + + uv run play --rl_library rsl_rl --task diff --git a/simulation/modules/IsaacLab/docs/source/setup/quickstart.rst b/simulation/modules/IsaacLab/docs/source/setup/quickstart.rst new file mode 100644 index 0000000000000000000000000000000000000000..60fa578b9492fc4606990829b526aed91c74a302 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/quickstart.rst @@ -0,0 +1,142 @@ +.. _isaac-lab-quickstart: + +Quickstart +========== + +Isaac Lab is a GPU-accelerated framework for robot learning built on vectorized simulation. +Environments run thousands of parallel copies on the GPU, and a modular manager design lets you +swap robots, sensors, and controllers without rewriting task logic. + +This page gets you installed and running a first training job in minutes. For deeper topics +(configurations, project scaffolding, standalone apps, preset catalogs), see +:doc:`quickstart_details`. + +Install +------- + +Clone Isaac Lab, create a Python 3.12 environment, and install. Choose the path that matches +your workflow: + +.. tab-set:: + + .. tab-item:: Kit-less (no Isaac Sim) + + Fastest start — Newton physics only, no Isaac Sim download required. + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. isaaclab-quickstart-install:: + :kitless: + :platform: linux + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. isaaclab-quickstart-install:: + :kitless: + :platform: windows + + See :ref:`installation-selective-install` for install tokens and + :doc:`/source/setup/installation/kitless_installation` for feature + availability without Isaac Sim. + + .. tab-item:: With Isaac Sim (full features) + + Recommended for PhysX, RTX rendering, ROS, URDF/MJCF importers, and the Kit visualizer. + + .. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. isaaclab-quickstart-install:: + :isaacsim: + :platform: linux + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. isaaclab-quickstart-install:: + :isaacsim: + :platform: windows + + On Linux aarch64 (DGX Spark), use ``cu130`` for PyTorch and see + :ref:`isaaclab-installation-root` for additional setup notes. + + For conda, binary installs, Docker, and troubleshooting, see + :ref:`isaaclab-installation-root`. + + +Run Training +------------ + +Use the reinforcement learning training command with a **task name** and +``physics=``, ``renderer=``, and ``presets=`` to select backends and task-specific options: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + # Kit-less: Newton MJWarp physics + Newton visualizer + ./isaaclab.sh train --rl_library rsl_rl \ + --task=Isaac-Cartpole-Direct-v0 \ + --num_envs=16 --max_iterations=10 \ + physics=newton_mjwarp --visualizer newton + + # With Isaac Sim: PhysX physics (default renderer) + ./isaaclab.sh train --rl_library rsl_rl \ + --task=Isaac-Cartpole-Direct-v0 \ + --num_envs=4096 \ + physics=physx + + # Camera task: typed physics + renderer + domain preset + ./isaaclab.sh train --rl_library rl_games \ + --task=Isaac-Cartpole-RGB-Camera-Direct-v0 \ + physics=newton_mjwarp renderer=newton_renderer presets=rgb + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + isaaclab.bat train --rl_library rsl_rl ^ + --task=Isaac-Cartpole-Direct-v0 ^ + --num_envs=16 --max_iterations=10 ^ + physics=newton_mjwarp --visualizer newton + + isaaclab.bat train --rl_library rsl_rl ^ + --task=Isaac-Cartpole-Direct-v0 ^ + --num_envs=4096 ^ + physics=physx + +Use ``--help`` on any script to see task-specific ``physics=``, ``renderer=``, and ``presets=`` options. + +.. seealso:: + + - :doc:`/source/features/hydra` — preset system and Hydra overrides + - :doc:`quickstart_details` — preset catalog, environments, project generator, and more + + +Next Steps +---------- + +- List registered environments: ``python scripts/environments/list_envs.py`` +- Scaffold a new project: ``./isaaclab.sh --new`` (Linux) or ``isaaclab.bat --new`` (Windows) +- Walk through tutorials: :doc:`/source/tutorials/index` +- Browse all environments: :doc:`/source/overview/environments` + + +.. toctree:: + :maxdepth: 1 + :hidden: + + quickstart_details diff --git a/simulation/modules/IsaacLab/docs/source/setup/quickstart_details.rst b/simulation/modules/IsaacLab/docs/source/setup/quickstart_details.rst new file mode 100644 index 0000000000000000000000000000000000000000..202024c8c0e34a1b428c471aa7fea3f9efb35c40 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/quickstart_details.rst @@ -0,0 +1,212 @@ +.. _isaac-lab-quickstart-details: + +Quickstart Details +================== + +Extended reference for topics introduced in :doc:`quickstart`. + + +Quick Start Using Isaac Launchable +---------------------------------- + +For users first learning Isaac Lab without sufficient local compute, the +`Isaac Launchable `_ project provides a +browser-based Isaac Sim and Isaac Lab environment via `NVIDIA Brev `_. + +.. image:: https://brev-assets.s3.us-west-1.amazonaws.com/nv-lb-dark.svg + :target: https://brev.nvidia.com/launchable/deploy/now?launchableID=env-35JP2ywERLgqtD0b0MIeK1HnF46 + :alt: Click here to deploy + + +Running Tasks +------------- + +Use ``physics=`` and ``renderer=`` for backend selection and ``presets=`` for task-specific +options (observation modes, camera configs, etc.). They fold into Hydra overrides automatically. + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + # Kit-less: Newton MJWarp + Newton visualizer + ./isaaclab.sh train --rl_library rsl_rl \ + --task=Isaac-Cartpole-Direct-v0 \ + --num_envs=4096 \ + physics=newton_mjwarp --visualizer newton + + # With Isaac Sim: PhysX + ./isaaclab.sh train --rl_library rsl_rl \ + --task=Isaac-Cartpole-Direct-v0 \ + --num_envs=4096 \ + physics=physx + + # Camera task: physics + renderer + domain preset + ./isaaclab.sh train --rl_library rl_games \ + --task=Isaac-Cartpole-Camera-Presets-Direct-v0 \ + physics=newton_mjwarp renderer=newton_renderer presets=rgb + + # OVRTX rendering (kit-less, no Kit visualizer) + ./isaaclab.sh train --rl_library rsl_rl \ + --task=Isaac-Repose-Cube-Shadow-Vision-Benchmark-Direct-v0 \ + --enable_cameras --num_envs=16 --max_iterations=10 \ + physics=newton_mjwarp renderer=ovrtx_renderer presets=simple_shading_diffuse_mdl + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + isaaclab.bat train --rl_library rsl_rl ^ + --task=Isaac-Cartpole-Direct-v0 ^ + --num_envs=4096 ^ + physics=newton_mjwarp --visualizer newton + +Kit-less visualizer options: ``newton``, ``rerun``, ``viser``. Combine with commas: +``--visualizer newton,rerun``. + + +Available Presets +^^^^^^^^^^^^^^^^^ + +**Physics backends** (``physics=NAME``): + +- ``physx`` — PhysX via Isaac Sim (default when no selector is given) +- ``newton_mjwarp`` — Newton with the MuJoCo-Warp solver +- ``newton_kamino`` — Newton with the Kamino solver (beta, limited tasks) +- ``ovphysx`` — OV PhysX (kit-less; incompatible with ``--visualizer kit``) + +**Renderer backends** (``renderer=NAME``): + +- ``isaacsim_rtx_renderer`` — Isaac Sim RTX (default with Isaac Sim) +- ``newton_renderer`` — Newton Warp renderer +- ``ovrtx_renderer`` — OV RTX renderer (kit-less) + +**Domain presets** (``presets=NAME[,NAME,...]``) are task-specific — run +``--task= --help`` to list them. + +Common combinations: + +.. code-block:: bash + + physics=newton_mjwarp renderer=newton_renderer presets=rgb + physics=newton_mjwarp renderer=newton_renderer presets=depth + physics=physx renderer=isaacsim_rtx_renderer presets=rgb + physics=physx renderer=isaacsim_rtx_renderer presets=depth + physics=physx renderer=isaacsim_rtx_renderer presets=albedo + physics=newton_mjwarp renderer=ovrtx_renderer presets=rgb + physics=newton_mjwarp renderer=ovrtx_renderer presets=simple_shading_diffuse_mdl + +Legacy ``presets=newton_mjwarp,newton_renderer,rgb`` form still works; prefer typed selectors +for clarity. See :doc:`/source/features/hydra` for the full preset system. + + +List Available Environments +--------------------------- + +Task names are registered with the `Gymnasium API `_. +List them with: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/list_envs.py + +Example output: + +.. code-block:: bash + + +--------+----------------------+--------------------------------------------+... + | 2 | Isaac-Ant-Direct-v0 | isaaclab_tasks.direct.ant.ant_env:AntEnv |... + | 48 | Isaac-Ant-v0 | isaaclab.envs:ManagerBasedRLEnv |... + +Each task may appear in **Direct** and **ManagerBased** variants — see +:ref:`feature-workflows` for the two primary workflows. + + +Generate Your Own Project +------------------------- + +Scaffold a new project with the template generator: + +.. code-block:: bash + + ./isaaclab.sh --new + +Choose **External vs Internal**, **Direct vs Manager**, and RL **Framework** options, then install: + +.. code-block:: bash + + uv pip install -e source/ + +The generated ``__init__.py`` registers the environment with Gymnasium: + +.. code-block:: python + + gym.register( + id="Template-isaaclabtutorial_env-v0", + entry_point=f"{__name__}.isaaclabtutorial_env:IsaaclabtutorialEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.isaaclabtutorial_env_cfg:IsaaclabtutorialEnvCfg", + "skrl_cfg_entry_point": f"{agents.__name__}.skrl_ppo_cfg:PPORunnerCfg", + }, + ) + + +Configurations +-------------- + +Configurations use the ``@configclass`` decorator and contain no ``__init__``. Example from +the :ref:`cartpole environment `: + +.. code-block:: python + + @configclass + class CartpoleEnvCfg(DirectRLEnvCfg): + decimation = 2 + episode_length_s = 5.0 + action_scale = 100.0 + action_space = 1 + observation_space = 4 + + sim: SimulationCfg = SimulationCfg(dt=1 / 120, render_interval=decimation) + robot_cfg: ArticulationCfg = CARTPOLE_CFG.replace(prim_path="/World/envs/env_.*/Robot") + scene: InteractiveSceneCfg = InteractiveSceneCfg(num_envs=4096, env_spacing=4.0, replicate_physics=True) + + rew_scale_alive = 1.0 + rew_scale_terminated = -2.0 + +CLI arguments such as ``--num_envs`` override matching config fields at launch time. + + +Robots +------ + +Robots are defined as configuration instances. See :doc:`/source/how-to/robots` for a full +example. + + +Apps and Sims +------------- + +PhysX workflows require launching the Isaac Sim app. Newton workflows do not. For standalone +scripts outside the standard task runners, use :class:`~isaaclab.app.AppLauncher`: + +.. code-block:: python + + from isaaclab.app import AppLauncher + + parser = argparse.ArgumentParser() + parser.add_argument("--num_envs", type=int, default=1) + AppLauncher.add_app_launcher_args(parser) + args_cli = parser.parse_args() + + app_launcher = AppLauncher(args_cli) + simulation_app = app_launcher.app + +Many Isaac Lab modules cannot be imported until the app is launched. See the +`Isaac Sim documentation `_ for +standalone app development. diff --git a/simulation/modules/IsaacLab/docs/source/setup/walkthrough/api_env_design.rst b/simulation/modules/IsaacLab/docs/source/setup/walkthrough/api_env_design.rst new file mode 100644 index 0000000000000000000000000000000000000000..a669bc47fa1ca2527c50c23ea60f26575124f7c2 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/walkthrough/api_env_design.rst @@ -0,0 +1,158 @@ +.. _walkthrough_api_env_design: + +Classes and Configs +==================================== + +To begin, navigate to the task: ``source/isaac_lab_tutorial/isaac_lab_tutorial/tasks/direct/isaac_lab_tutorial``, and take a look +and the contents of ``isaac_lab_tutorial_env_cfg.py``. You should see something that looks like the following + +.. code-block:: python + + from isaaclab_assets.robots.cartpole import CARTPOLE_CFG + + from isaaclab.assets import ArticulationCfg + from isaaclab.envs import DirectRLEnvCfg + from isaaclab.scene import InteractiveSceneCfg + from isaaclab.sim import SimulationCfg + from isaaclab.utils.configclass import configclass + + + @configclass + class IsaacLabTutorialEnvCfg(DirectRLEnvCfg): + + # Some useful fields + . + . + . + + # simulation + sim: SimulationCfg = SimulationCfg(dt=1 / 120, render_interval=2) + + # robot(s) + robot_cfg: ArticulationCfg = CARTPOLE_CFG.replace(prim_path="/World/envs/env_.*/Robot") + + # scene + scene: InteractiveSceneCfg = InteractiveSceneCfg(num_envs=4096, env_spacing=4.0, replicate_physics=True) + + # Some more useful fields + . + . + . + +This is the default configuration for a simple cartpole environment that comes with the template and defines the ``self`` scope +for anything you do within the corresponding environment. + +.. currentmodule:: isaaclab.envs + +The first thing to note is the presence of the ``@configclass`` decorator. This defines a class as a configuration class, which holds +a special place in Isaac Lab. Configuration classes are part of how Isaac Lab determines what to "care" about when it comes to cloning +the environment to scale up training. Isaac Lab provides different base configuration classes depending on your goals, and in this +case we are using the :class:`DirectRLEnvCfg` class because we are interested in performing reinforcement learning in the direct workflow. + +.. currentmodule:: isaaclab.sim + +The second thing to note is the content of the configuration class. As the author, you can specify any fields you desire but, generally speaking, there are three things you +will always define here: The **sim**, the **scene**, and the **robot**. Notice that these fields are also configuration classes! Configuration classes +are compositional in this way as a solution for cloning arbitrarily complex environments. + +The **sim** is an instance of :class:`SimulationCfg`, and this is the config that controls the nature of the simulated reality we are building. This field is a member +of the base class, ``DirecRLEnvCfg``, but has a default sim configuration, so it's *technically* optional. The ``SimulationCfg`` dictates +how finely to step through time (dt), the direction of gravity, and even how physics should be simulated. In this case we only specify the time step and the render interval, with the +former indicating that each step through time should simulate :math:`1/120` th of a second, and the latter being how many steps we should take before we render a frame (a value of 2 means +render every other frame). + +.. currentmodule:: isaaclab.scene + +The **scene** is an instance of :class:`InteractiveSceneCfg`. The scene describes what goes "on the stage" and manages those simulation entities to be cloned across environments. +The scene is also a member of the base class ``DirectRLEnvCfg``, but unlike the sim it has no default and must be defined in every ``DirectRLEnvCfg``. The ``InteractiveSceneCfg`` +describes how many copies of the scene we want to create for training purposes, as well as how far apart they should be spaced on the stage. + +.. currentmodule:: isaaclab.assets + +Finally we have the **robot** definition, which is an instance of :class:`ArticulationCfg`. An environment could have multiple articulations, and so the presence of +an ``ArticulationCfg`` is not strictly required in order to define a ``DirectRLEnv``. Instead, the usual workflow is to define a regex path to the robot, and replace +the ``prim_path`` attribute in the base configuration. In this case, ``CARTPOLE_CFG`` is a configuration defined in ``isaaclab_assets.robots.cartpole`` and by replacing +the prim path with ``/World/envs/env_.*/Robot`` we are implicitly saying that every copy of the scene will have a robot named ``Robot``. + + +The Environment +----------------- + +Next, let's take a look at the contents of the other python file in our task directory: ``isaac_lab_tutorial_env.py`` + +.. code-block:: python + + # imports + . + . + . + from .isaac_lab_tutorial_env_cfg import IsaacLabTutorialEnvCfg + + class IsaacLabTutorialEnv(DirectRLEnv): + cfg: IsaacLabTutorialEnvCfg + + def __init__(self, cfg: IsaacLabTutorialEnvCfg, render_mode: str | None = None, **kwargs): + super().__init__(cfg, render_mode, **kwargs) + . . . + + def _setup_scene(self): + self.robot = Articulation(self.cfg.robot_cfg) + # add ground plane + spawn_ground_plane(prim_path="/World/ground", cfg=GroundPlaneCfg()) + # add articulation to scene + self.scene.articulations["robot"] = self.robot + # clone and replicate + self.scene.clone_environments(copy_from_source=False) + # add lights + light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) + light_cfg.func("/World/Light", light_cfg) + + def _pre_physics_step(self, actions: torch.Tensor) -> None: + . . . + + def _apply_action(self) -> None: + . . . + + def _get_observations(self) -> dict: + . . . + + def _get_rewards(self) -> torch.Tensor: + total_reward = compute_rewards(...) + return total_reward + + def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: + . . . + + def _reset_idx(self, env_ids: Sequence[int] | None): + . . . + + @torch.jit.script + def compute_rewards(...): + . . . + return total_reward + + +.. currentmodule:: isaaclab.envs + +Some of the code has been omitted for clarity, in order to aid in discussion. This is where the actual "meat" of the +direct workflow exists and where most of our modifications will take place as we tweak the template to suit our needs. +Currently, all of the member functions of ``IsaacLabTutorialEnv`` are directly inherited from the :class:`DirectRLEnv`. This +known interface is how Isaac Lab and its supported RL frameworks interact with the environment. + +When the environment is initialized, it receives its own config as an argument, which is then immediately passed to super in order +to initialize the ``DirectRLEnv``. This super call also calls ``_setup_scene``, which actually constructs the scene and clones +it appropriately. Notably is how the robot is created and registered to the scene in ``_setup_scene``. First, the robot articulation +is created by using the ``robot_config`` we defined in ``IsaacLabTutorialEnvCfg``: it doesn't exist before this point! When the +articulation is created, the robot exists on the stage at ``/World/envs/env_0/Robot``. The call to ``scene.clone_environments`` then +copies ``env_0`` appropriately. At this point the robot exists as many copies on the stage, so all that's left is to notify the ``scene`` +object of the existence of this articulation to be tracked. The articulations of the scene are kept as a dictionary, so ``scene.articulations["robot"] = self.robot`` +creates a new ``robot`` element of the ``articulations`` dictionary and sets the value to be ``self.robot``. + +Notice also that the remaining functions do not take additional arguments except ``_reset_idx``. This is because the environment only manages the application of +actions to the agent being simulated, and then updating the sim. This is what the ``_pre_physics_step`` and ``_apply_action`` steps are for: we set the drive commands +to the robot so that when the simulation steps forward, the actions are applied and the joints are driven to new targets. This process is broken into steps like this +in order to ensure systematic control over how the environment is executed, and is especially important in the manager workflow. A similar relationship exists between the +``_get_dones`` function and ``_reset_idx``. The former, ``_get_dones`` determines if each of the environments is in a terminal state, and populates tensors of boolean +values to indicate which environments terminated due to entering a terminal state vs time out (the two returned tensors of the function). The latter, ``_reset_idx`` takes a +list environment index values (integers) and then actually resets those environments. It is important that things like updating drive targets or resetting environments +do not happen **during** the physics or rendering steps, and breaking up the interface in this way helps prevent that. diff --git a/simulation/modules/IsaacLab/docs/source/setup/walkthrough/concepts_env_design.rst b/simulation/modules/IsaacLab/docs/source/setup/walkthrough/concepts_env_design.rst new file mode 100644 index 0000000000000000000000000000000000000000..d446820a1472d96d22f726c687f45efee462b355 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/walkthrough/concepts_env_design.rst @@ -0,0 +1,70 @@ +.. _walkthrough_concepts_env_design: + +Environment Design Background +============================== + +Now that we have our project installed, we can start designing the environment. In the traditional description +of a reinforcement learning (RL) problem, the environment is responsible for using the actions produced by the agent to +update the state of the "world", and finally compute and return the observations and the reward signal. However, there are +some additional concepts that are unique to Isaac Sim and Lab regarding the mechanics of the simulation itself. +The traditional description of a reinforcement learning problem presumes a "world", but we get no such luxury; we must define +the world ourselves, and success depends on understanding on how to construct that world and how it will fit into the simulation. + +App, Sim, World, Stage, and Scene +---------------------------------- + +.. figure:: ../../_static/setup/walkthrough_sim_stage_scene.svg + :align: center + :figwidth: 100% + :alt: How the sim is organized. + +The **World** is defined by the origin of a cartesian coordinate system and the units that define it. How big or how small? How +near or how far? The answers to questions like these can only be defined *relative* to some contextual reference frame, and that +reference frame is what defines the world. + +"Above" the world in structure is the **Sim**\ ulation and the **App**\ lication. The **Application** is "the thing responsible for +everything else": It governs all resource management as well as launching and destroying the simulation when we are done with it. +When we :ref:`launched training with the template`, the window that appears with the viewport of cartpoles +training is the Application window. The application is not defined by the GUI however, and even when running in headless mode all +simulations have an application that governs them. + +The **Simulation** controls the "rules" of the world. It defines the laws of physics, such as how time and gravity should work, and how frequently to perform +rendering. If the application holds the sim, then the sim holds the world. The simulation governs a single step through time by dividing it into many different +sub-steps, each devoted to a specific aspect of updating the world into a state. Many of the APIs in Isaac Lab are written to specifically hook into +these various steps and you will often see functions named like ``_pre_XYZ_step`` and ``_post_XYZ_step`` where ``XYZ_step`` is the name of one of these sub-steps of +the simulation, such as the ``physics_step`` or the ``render_step``. + +"Below" the world in structure is the **Stage** and the **Scene**. If the world provides spatial context to the sim, then +the **Stage** provides the *compositional context* for the world. Suppose we want to simulate a table set for a meal in a room: +the room is the "world" in this case, and we choose the origin of the world to be one of the corners of the room. The position of the +table in the room is defined as a vector from the origin of the world to some point on the table that we choose to be the origin of a *new* coordinate +system, fixed to the table. It's not useful to us, *the agent*\ , to talk about the location of the food and the utensils on the table with respect to the +corner of the room: instead it is preferable to use the coordinates defined with respect to the table. However, the simulation needs to know +these global coordinates in order to properly simulate the next time step, so we must define how these two coordinate systems are *composed* together. + +This is what the stage accomplishes: everything in the simulation is a `USD primitive `_ and the +stage represents the relationships between these primitives as a tree, with the context being defined by the relative path in the tree. Every prim on the stage +has a name and therefore a path in this tree, such as ``/room/table/food`` or ``room/table/utensils``. Relationships are defined by the "parents" and "children" +of a given node in this tree: the ``table`` is a child of the ``room`` but a parent of ``food``. Compositional properties of the parent are applied to all of its +children, but child prims have the ability to override parent properties if necessary, as is often the case for materials. + +.. figure:: ../../_static/setup/walkthrough_stage_context.svg + :align: center + :figwidth: 100% + :alt: How the stage organizes context + +Armed with this vocabulary, we can finally talk about the **Scene**, one of the most critical elements to understand about Isaac Lab. Deep learning, in +all its forms, is rooted in the analysis of data. This is true even in robot learning, where data is acquired through the sensors of the robot being trained. +The time required to setup the robot, collect data, and reset the robot to collect more, is a fundamental bottleneck in teaching robots to do *anything*, with any method. +Isaac Sim gives us access to robots without the need for literal physical robots, but Isaac Lab gives us access to *vectorization*: the ability to simulate many copies +of a training procedure efficiently, thus multiplying the rate of data generation and accelerating training proportionally. The scene governs those primitives on the stage +that matter to this vectorization process, known as **simulation entities**. + +Suppose the reason why you want to simulate a table set for a meal is because you would like to train a robot to place the table settings for you! The robot, the table, +and all the things on it can be registered to the scene of an environment. We can then specify how many copies we want and the scene will automatically +construct and run those copies on the stage. These copies are placed at new coordinates on the stage, defining a new reference frame from which observations +and rewards can be computed. Every copy of the scene exists on the stage and is being simulated by the same world. This is much more efficient +than running unique simulations for each copy, but it does open up the possibility of unwanted interactions between copies of the scene, so it's important +to keep this in mind while debugging. + +Now that we have a grasp on the mechanics, we can take a look at the code generated for our template project! diff --git a/simulation/modules/IsaacLab/docs/source/setup/walkthrough/index.rst b/simulation/modules/IsaacLab/docs/source/setup/walkthrough/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..2ba226625583b310ade151eabfadb516c9af44f8 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/walkthrough/index.rst @@ -0,0 +1,24 @@ +.. _walkthrough: + +Walkthrough +======================== + +So you finished installing Isaac Sim and Isaac Lab, and you verified that everything is working as expected... + +Now what? + +The following walkthrough will guide you through setting up an Isaac Lab extension project, adding a new robot to lab, designing an environment, and training a policy for that robot. +For this walkthrough, we will be starting with the Jetbot, a simple two wheeled differential base robot with a camera mounted on top, but the intent is for these guides to be general enough that you can use them to add your own robots and environments to Isaac Lab! + +The end result of this walkthrough can be found in our tutorial project repository `here `_. Each branch of this repository +represents a different stage of modifying the default template project to achieve our goals. + +.. toctree:: + :maxdepth: 1 + :titlesonly: + + concepts_env_design + api_env_design + technical_env_design + training_jetbot_gt + training_jetbot_reward_exploration diff --git a/simulation/modules/IsaacLab/docs/source/setup/walkthrough/technical_env_design.rst b/simulation/modules/IsaacLab/docs/source/setup/walkthrough/technical_env_design.rst new file mode 100644 index 0000000000000000000000000000000000000000..41b99445c135eee49a8a00a571e6b84db7e77089 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/walkthrough/technical_env_design.rst @@ -0,0 +1,204 @@ +.. _walkthrough_technical_env_design: + +Environment Design +==================== + +Armed with our understanding of the project and its structure, we are ready to start modifying the code to suit our Jetbot training needs. +Our template is set up for the **direct** workflow, which means the environment class will manage all of these details +centrally. We will need to write the code that will... + +#. Define the robot +#. Define the training simulation and manage cloning +#. Apply the actions from the agent to the robot +#. Calculate and return the rewards and observations +#. Manage resetting and terminal states + +As a first step, our goal will be to get the environment training pipeline to load and run. We will use a dummy reward signal +for the purposes of this part of the walkthrough. You can find the code for these modifications `here `_! + +Define the Robot +------------------ + +As our project grows, we may have many robots that we want to train. With malice aforethought we will add a new ``module`` to our +tutorial ``extension`` named ``robots`` where we will keep the definitions for robots as individual python scripts. Navigate +to ``isaac_lab_tutorial/source/isaac_lab_tutorial/isaac_lab_tutorial`` and create a new folder called ``robots``. Within this folder +create two files: ``__init__.py`` and ``jetbot.py``. The ``__init__.py`` file marks this directory as a python module and we will +be able to import the contents of ``jetbot.py`` in the usual way. + +The contents of ``jetbot.py`` is fairly minimal + +.. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab.assets import ArticulationCfg + from isaaclab.actuators import ImplicitActuatorCfg + from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR + + JETBOT_CONFIG = ArticulationCfg( + spawn=sim_utils.UsdFileCfg(usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/NVIDIA/Jetbot/jetbot.usd"), + actuators={"wheel_acts": ImplicitActuatorCfg(joint_names_expr=[".*"], damping=None, stiffness=None)}, + ) + +The only purpose of this file is to define a unique scope in which to save our configurations. The details of robot configurations +can be explored in :ref:`this tutorial ` but most noteworthy for this walkthrough is the ``usd_path`` for the ``spawn`` +argument of this ``ArticulationCfg``. The Jetbot asset is available to the public via a hosted nucleus server, and that path is defined by +``ISAAC_NUCLEUS_DIR``, however any path to a USD file is valid, including local ones! + +Environment Configuration +--------------------------- + +Navigate to the environment configuration, ``isaac_lab_tutorial/source/isaac_lab_tutorial/isaac_lab_tutorial/tasks/direct/isaac_lab_tutorial/isaac_lab_tutorial_env_cfg.py``, and +replace its contents with the following + +.. code-block:: python + + from isaac_lab_tutorial.robots.jetbot import JETBOT_CONFIG + + from isaaclab.assets import ArticulationCfg + from isaaclab.envs import DirectRLEnvCfg + from isaaclab.scene import InteractiveSceneCfg + from isaaclab.sim import SimulationCfg + from isaaclab.utils.configclass import configclass + + @configclass + class IsaacLabTutorialEnvCfg(DirectRLEnvCfg): + # env + decimation = 2 + episode_length_s = 5.0 + # - spaces definition + action_space = 2 + observation_space = 3 + state_space = 0 + # simulation + sim: SimulationCfg = SimulationCfg(dt=1 / 120, render_interval=decimation) + # robot(s) + robot_cfg: ArticulationCfg = JETBOT_CONFIG.replace(prim_path="/World/envs/env_.*/Robot") + # scene + scene: InteractiveSceneCfg = InteractiveSceneCfg(num_envs=100, env_spacing=4.0, replicate_physics=True) + dof_names = ["left_wheel_joint", "right_wheel_joint"] + +Here we have, effectively, the same environment configuration as before, but with the Jetbot instead of the cartpole. The +parameters ``decimation``, ``episode_length_s``, ``action_space``, ``observation_space``, and ``state_space`` are members of +the base class, ``DirectRLEnvCfg``, and must be defined for every ``DirectRLEnv``. The space parameters are interpreted as vectors of +the given integer dimension, but they can also be defined as `gymnasium spaces `_! + +Notice the difference in the action and observation spaces. As the designers of the environment, we get to choose these. For the Jetbot, we want to +directly control the joints of the robot, of which only two are actuated (hence the action space of two). The observation space is *chosen* to be +3 because we are just going to feed the agent the linear velocity of the Jetbot, for now. We will change these later as we develop the environment. Our policy isn't going +to need an internal state maintained, so our state space is zero. + +Attack of the clones +--------------------- + +With the config defined, it's time to fill in the details of the environment, starting with the initialization and setup. +Navigate to the environment definition, ``isaac_lab_tutorial/source/isaac_lab_tutorial/isaac_lab_tutorial/tasks/direct/isaac_lab_tutorial/isaac_lab_tutorial_env.py``, and +replace the contents of the ``__init__`` and ``_setup_scene`` methods with the following. + +.. code-block:: python + + class IsaacLabTutorialEnv(DirectRLEnv): + cfg: IsaacLabTutorialEnvCfg + + def __init__(self, cfg: IsaacLabTutorialEnvCfg, render_mode: str | None = None, **kwargs): + super().__init__(cfg, render_mode, **kwargs) + + self.dof_idx, _ = self.robot.find_joints(self.cfg.dof_names) + + def _setup_scene(self): + self.robot = Articulation(self.cfg.robot_cfg) + # add ground plane + spawn_ground_plane(prim_path="/World/ground", cfg=GroundPlaneCfg()) + # clone and replicate + self.scene.clone_environments(copy_from_source=False) + # add articulation to scene + self.scene.articulations["robot"] = self.robot + # add lights + light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) + light_cfg.func("/World/Light", light_cfg) + +Notice that the ``_setup_scene`` method doesn't change and the ``_init__`` method is simply grabbing the joint indices from the robot (remember, setup is called in super). + +The next thing our environment needs is the definitions for how to handle actions, observations, and rewards. First, replace the contents of ``_pre_physics_step`` and +``_apply_action`` with the following. + +.. code-block:: python + + def _pre_physics_step(self, actions: torch.Tensor) -> None: + self.actions = actions.clone() + + def _apply_action(self) -> None: + self.robot.set_joint_velocity_target(self.actions, joint_ids=self.dof_idx) + +Here the act of applying actions to the robot in the environment is broken into two steps: ``_pre_physics_step`` and ``_apply_action``. The physics +simulation is decimated with respect to querying the policy for actions, meaning that multiple physics steps may occur per action taken by the policy. +The ``_pre_physics_step`` method is called just before this simulation step takes place and lets us detach the process of getting data from the +policy being trained and applying updates to the physics simulation. The ``_apply_action`` method is where those actions are actually applied to the robots +on the stage, after which the simulation is actually stepped forward in time. + +Next is the observations and rewards, which is just going to depend on the linear velocity of the Jetbot in the body frame of the robot. Replace the contents of ``_get_observations`` +and ``_get_rewards`` with the following. + +.. code-block:: python + + def _get_observations(self) -> dict: + self.velocity = self.robot.data.root_com_lin_vel_b + observations = {"policy": self.velocity} + return observations + + def _get_rewards(self) -> torch.Tensor: + total_reward = torch.linalg.norm(self.velocity, dim=-1, keepdim=True) + return total_reward + +The robot exists as an Articulation object within the Isaac Lab API. That object carries a data class, the ``ArticulationData``, which contains all the data for **specific** robots on the stage. +When we talk about a scene entity like the robot, we can either be talking about the robot broadly, as an entity that exists in every scene, or we can be describing a specific, singular clone +of the robot on the stage. The ``ArticulationData`` contains the data for those individual clones. This includes things like various kinematic vectors (like ``root_com_lin_vel_b``) and reference +vectors (like ``robot.data.FORWARD_VEC_B``). + +Notice how in the ``_apply_action`` method, we are calling a method of ``self.robot`` which is a method of ``Articulation``. The actions being applied are in the form of a 2D tensor +of shape ``[num_envs, num_actions]``. We are applying actions to **all** robots on the stage at once! Here, when we need to get the observations, we need the body frame velocity for all robots on the +stage, and so access ``self.robot.data`` to get that information. The ``root_com_lin_vel_b`` is a property of the ``ArticulationData`` that handles the conversion of the center-of-mass linear velocity from the world frame +to the body frame for us. Finally, Isaac Lab expects the observations to be returned as a dictionary, with ``policy`` defining those observations for the policy model and ``critic`` defining those observations for +the critic model (in the case of asymmetric actor critic training). Since we are not doing asymmetric actor critic, we only need to define ``policy``. + +The rewards are more straightforward. For each clone of the scene, we need to compute a reward value and return it as a tensor of shape ``[num_envs, 1]``. As a place holder, we will make the reward the +magnitude of the linear velocity of the Jetbot in the body frame. With this reward and observation space, the agent should learn to drive the Jetbot forward or backward, with the direction determined at random +shortly after training starts. + +Finally, we can write the parts of the environment to handle termination and resetting. Replace the contents of ``_get_dones`` and ``_reset_idx`` with the following. + +.. code-block:: python + + def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: + time_out = self.episode_length_buf >= self.max_episode_length - 1 + + return False, time_out + + def _reset_idx(self, env_ids: Sequence[int] | None): + if env_ids is None: + env_ids = self.robot._ALL_INDICES + super()._reset_idx(env_ids) + + default_root_state = self.robot.data.default_root_state[env_ids] + default_root_state[:, :3] += self.scene.env_origins[env_ids] + + self.robot.write_root_state_to_sim(default_root_state, env_ids) + +Like the actions, termination and resetting are handled in two parts. First is the ``_get_dones`` method, the goal of which is simply to mark which environments need to be reset and why. +Traditionally in reinforcement learning, an "episode" ends in one of two ways: either the agent reaches a terminal state, or the episode reaches a maximum duration. +Isaac Lab is kind to us, because it manages all of this episode duration tracking behind the scenes. The configuration parameter ``episode_length_s`` defines this maximum episode length in +seconds and the parameters ``episode_length_buff`` and ``max_episode_length`` contain the number of steps taken by individual scenes (allowing for asynchronous running of the environment) and the +maximum length of the episode as converted from ``episode_length_s``. The boolean operation computing ``time_out`` just compares the current buffer size to the max and returns true if it's greater, thus +indicating which scenes are at the episode length limit. Since our current environment is a dummy, we don't define terminal states and so just return ``False`` for the first tensor (this gets projected automatically +to the correct shape through the power of pytorch). + +Finally, the ``_reset_idx`` method accepts a tensor of booleans indicating which scenes need to be reset, and resets them. Notice that this is the only other method of ``DirectRLEnv`` that directly calls +``super``, which is done so here to manage the internal buffers related to episode length. For those environments indicated by ``env_ids`` we retrieve the root default state, and reset the robot to that state while +also offsetting the position of each robot according to the origin of the corresponding scene. This is a consequence of the cloning procedure, which starts with a single robot and a single default state defined in the world +frame. Don't forget this step for your own custom environments! + +With these changes complete, you should see the Jetbot slowly learn to drive forward when you launch the task with the template ``train.py`` script. + +.. figure:: ../../_static/setup/walkthrough_1_1_result.jpg + :align: center + :figwidth: 100% + :alt: The Jetbot invasion begins! diff --git a/simulation/modules/IsaacLab/docs/source/setup/walkthrough/training_jetbot_gt.rst b/simulation/modules/IsaacLab/docs/source/setup/walkthrough/training_jetbot_gt.rst new file mode 100644 index 0000000000000000000000000000000000000000..05e89ef4564463d7361a7c7767ac10a9d5d6d0ed --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/walkthrough/training_jetbot_gt.rst @@ -0,0 +1,221 @@ +.. _walkthrough_training_jetbot_gt: + +Training the Jetbot: Ground Truth +====================================== + +With the environment defined, we can now start modifying our observations and rewards in order to train a policy +to act as a controller for the Jetbot. As a user, we would like to be able to specify the desired direction for the Jetbot to drive, +and have the wheels turn such that the robot drives in that specified direction as fast as possible. How do we achieve this with +Reinforcement Learning (RL)? If you want to cut to the end and checkout the result of this stage of the walk through, checkout +`this branch of the tutorial repository `_! + +Expanding the Environment +-------------------------- + +The very first thing we need to do is create the logic for setting commands for each Jetbot on the stage. Each command will be a unit vector, and +we need one for every clone of the robot on the stage, which means a tensor of shape ``[num_envs, 3]``. Even though the Jetbot only navigates in the +2D plane, by working with 3D vectors we get to make use of all the math utilities provided by Isaac Lab. + +It would also be a good idea to setup visualizations, so we can more easily tell what the policy is doing during training and inference. +In this case, we will define two arrow ``VisualizationMarkers``: one to represent the "forward" direction of the robot, and one to +represent the command direction. When the policy is fully trained, these arrows should be aligned! Having these visualizations in place +early helps us avoid "silent bugs": issues in the code that do not cause it to crash. + +To begin, we need to define the marker config and then instantiate the markers with that config. Add the following to the global scope of ``isaac_lab_tutorial_env.py`` + +.. code-block:: python + + from isaaclab.markers import VisualizationMarkers, VisualizationMarkersCfg + from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR + import isaaclab.utils.math as math_utils + + def define_markers() -> VisualizationMarkers: + """Define markers with various different shapes.""" + marker_cfg = VisualizationMarkersCfg( + prim_path="/Visuals/myMarkers", + markers={ + "forward": sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/arrow_x.usd", + scale=(0.25, 0.25, 0.5), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 1.0)), + ), + "command": sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/arrow_x.usd", + scale=(0.25, 0.25, 0.5), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)), + ), + }, + ) + return VisualizationMarkers(cfg=marker_cfg) + +The ``VisualizationMarkersCfg`` defines USD prims to serve as the "marker". Any prim will do, but generally you want to keep markers as simple as possible because the cloning of markers occurs at runtime on every time step. +This is because the purpose of these markers is for *debug visualization only* and not to be a part of the simulation: the user has full control over how many markers to draw when and where. +NVIDIA provides several simple meshes on our public nucleus server, located at ``ISAAC_NUCLEUS_DIR``, and for obvious reasons we choose to use ``arrow_x.usd``. + +For a more detailed example of using ``VisualizationMarkers`` checkout the ``markers.py`` demo! + +.. dropdown:: Code for the markers.py demo + :icon: code + + .. literalinclude:: ../../../../scripts/demos/markers.py + :language: python + :linenos: + +Next, we need to expand the initialization and setup steps to construct the data we need for tracking the commands as well as the marker positions and rotations. Replace the contents of +``_setup_scene`` with the following + +.. code-block:: python + + def _setup_scene(self): + self.robot = Articulation(self.cfg.robot_cfg) + # add ground plane + spawn_ground_plane(prim_path="/World/ground", cfg=GroundPlaneCfg()) + # clone and replicate + self.scene.clone_environments(copy_from_source=False) + # add articulation to scene + self.scene.articulations["robot"] = self.robot + # add lights + light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) + light_cfg.func("/World/Light", light_cfg) + + self.visualization_markers = define_markers() + + # setting aside useful variables for later + self.up_dir = torch.tensor([0.0, 0.0, 1.0]).cuda() + self.yaws = torch.zeros((self.cfg.scene.num_envs, 1)).cuda() + self.commands = torch.randn((self.cfg.scene.num_envs, 3)).cuda() + self.commands[:,-1] = 0.0 + self.commands = self.commands/torch.linalg.norm(self.commands, dim=1, keepdim=True) + + # offsets to account for atan range and keep things on [-pi, pi] + ratio = self.commands[:,1]/(self.commands[:,0]+1E-8) + gzero = torch.where(self.commands > 0, True, False) + lzero = torch.where(self.commands < 0, True, False) + plus = lzero[:,0]*gzero[:,1] + minus = lzero[:,0]*lzero[:,1] + offsets = torch.pi*plus - torch.pi*minus + self.yaws = torch.atan(ratio).reshape(-1,1) + offsets.reshape(-1,1) + + self.marker_locations = torch.zeros((self.cfg.scene.num_envs, 3)).cuda() + self.marker_offset = torch.zeros((self.cfg.scene.num_envs, 3)).cuda() + self.marker_offset[:,-1] = 0.5 + self.forward_marker_orientations = torch.zeros((self.cfg.scene.num_envs, 4)).cuda() + self.command_marker_orientations = torch.zeros((self.cfg.scene.num_envs, 4)).cuda() + +Most of this is setting up the book keeping for the commands and markers, but the command initialization and the yaw calculations are worth diving into. The commands +are sampled from a multivariate normal distribution via ``torch.randn`` with the z component fixed to zero and then normalized to unit length. In order to point our +command markers along these vectors, we need to rotate the base arrow mesh appropriately. This means we need to define a `quaternion `_ that will rotate the arrow +prim about the z axis by some angle defined by the command. By convention, rotations about the z axis are called a "yaw" rotation (akin to roll and pitch). + +Luckily for us, Isaac Lab provides a utility to generate a quaternion from an axis of rotation and an angle: :func:`isaaclab.utils.math.quat_from_axis_angle`, so the only +tricky part now is determining that angle. + +.. figure:: ../../_static/setup/walkthrough_training_vectors.svg + :align: center + :figwidth: 100% + :alt: Useful vector definitions for training + +The yaw is defined about the z axis, with a yaw of 0 aligning with the x axis and positive angles opening counterclockwise. The x and y components of the command vector +define the tangent of this angle, and so we need the *arctangent* of that ratio to get the yaw. + +Now, consider two commands: Command A is in quadrant 2 at (-x, y), while command B is in quadrant 4 at (x, -y). The ratio of the +y component to the x component is identical for both A and B. If we do not account for this, then some of our command arrows will be +pointing in the opposite direction of the command! Essentially, our commands are defined on ``[-pi, pi]`` but ``arctangent`` is +only defined on ``[-pi/2, pi/2]``. + +To remedy this, we add or subtract ``pi`` from the yaw depending on the quadrant of the command. + +.. code-block:: python + + ratio = self.commands[:,1]/(self.commands[:,0]+1E-8) #in case the x component is zero + gzero = torch.where(self.commands > 0, True, False) + lzero = torch.where(self.commands < 0, True, False) + plus = lzero[:,0]*gzero[:,1] + minus = lzero[:,0]*lzero[:,1] + offsets = torch.pi*plus - torch.pi*minus + self.yaws = torch.atan(ratio).reshape(-1,1) + offsets.reshape(-1,1) + +Boolean expressions involving tensors can have ambiguous definitions and pytorch will throw errors regarding this. Pytorch provides +various methods to make the definitions explicit. The method ``torch.where`` produces a tensor with the same shape as the input +with each element of the output is determined by the evaluation of that expression on only that element. A reliable way to handle +boolean operations with tensors is to simply produce boolean indexing tensors and then represent the operation algebraically, with ``AND`` +as multiplication and ``OR`` as addition, which is what we do above. This is equivalent to the pseudocode: + +.. code-block:: python + + yaws = torch.atan(ratio) + yaws[commands[:,0] < 0 and commands[:,1] > 0] += torch.pi + yaws[commands[:,0] < 0 and commands[:,1] < 0] -= torch.pi + +Next we have the method for actually visualizing the markers. Remember, these markers aren't scene entities! We need to "draw" them whenever we +want to see them. + +.. code-block:: python + + def _visualize_markers(self): + # get marker locations and orientations + self.marker_locations = self.robot.data.root_pos_w + self.forward_marker_orientations = self.robot.data.root_quat_w + self.command_marker_orientations = math_utils.quat_from_angle_axis(self.yaws, self.up_dir).squeeze() + + # offset markers so they are above the jetbot + loc = self.marker_locations + self.marker_offset + loc = torch.vstack((loc, loc)) + rots = torch.vstack((self.forward_marker_orientations, self.command_marker_orientations)) + + # render the markers + all_envs = torch.arange(self.cfg.scene.num_envs) + indices = torch.hstack((torch.zeros_like(all_envs), torch.ones_like(all_envs))) + self.visualization_markers.visualize(loc, rots, marker_indices=indices) + +The ``visualize`` method of ``VisualizationMarkers`` is like this "draw" function. It accepts tensors for the spatial +transformations of the markers, and a ``marker_indices`` tensor to specify which marker prototype to use for each marker. So +long as the first dimension of all of these tensors match, this function will draw those markers with the specified transformations. +This is why we stack the locations, rotations, and indices. + +Now we just need to call ``_visualize_markers`` on the pre physics step to make the arrows visible. Replace ``_pre_physics_step`` with the following + +.. code-block:: python + + def _pre_physics_step(self, actions: torch.Tensor) -> None: + self.actions = actions.clone() + self._visualize_markers() + +The last major modification before we dig into the RL training is to update the ``_reset_idx`` method to account for the commands and markers. Whenever we reset an environment, +we need to generate a new command and reset the markers. The logic for this is already covered above. Replace the contents of ``_reset_idx`` with the following: + +.. code-block:: python + + def _reset_idx(self, env_ids: Sequence[int] | None): + if env_ids is None: + env_ids = self.robot._ALL_INDICES + super()._reset_idx(env_ids) + + # pick new commands for reset envs + self.commands[env_ids] = torch.randn((len(env_ids), 3)).cuda() + self.commands[env_ids,-1] = 0.0 + self.commands[env_ids] = self.commands[env_ids]/torch.linalg.norm(self.commands[env_ids], dim=1, keepdim=True) + + # recalculate the orientations for the command markers with the new commands + ratio = self.commands[env_ids][:,1]/(self.commands[env_ids][:,0]+1E-8) + gzero = torch.where(self.commands[env_ids] > 0, True, False) + lzero = torch.where(self.commands[env_ids]< 0, True, False) + plus = lzero[:,0]*gzero[:,1] + minus = lzero[:,0]*lzero[:,1] + offsets = torch.pi*plus - torch.pi*minus + self.yaws[env_ids] = torch.atan(ratio).reshape(-1,1) + offsets.reshape(-1,1) + + # set the root state for the reset envs + default_root_state = self.robot.data.default_root_state[env_ids] + default_root_state[:, :3] += self.scene.env_origins[env_ids] + + self.robot.write_root_state_to_sim(default_root_state, env_ids) + self._visualize_markers() + + +And that's it! We now generate commands and can visualize it the heading of the Jetbot. We are ready to start tinkering with the observations and rewards. + +.. figure:: ../../_static/setup/walkthrough_1_2_arrows.jpg + :align: center + :figwidth: 100% + :alt: Visualization of the command markers diff --git a/simulation/modules/IsaacLab/docs/source/setup/walkthrough/training_jetbot_reward_exploration.rst b/simulation/modules/IsaacLab/docs/source/setup/walkthrough/training_jetbot_reward_exploration.rst new file mode 100644 index 0000000000000000000000000000000000000000..cd7414e3d99eb820de97e7679801bbd414a2199c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/setup/walkthrough/training_jetbot_reward_exploration.rst @@ -0,0 +1,146 @@ +.. _walkthrough_training_jetbot_reward_exploration: + +Exploring the RL problem +========================= + +The command to the Jetbot is a unit vector in specifying the desired drive direction and we must make the agent aware of this somehow +so it can adjust its actions accordingly. There are many possible ways to do this, with the "zeroth order" approach to simply change the observation space to include +this command. To start, **edit the ``IsaacLabTutorialEnvCfg`` to set the observation space to 9**: the world velocity vector contains the linear and angular velocities +of the robot, which is 6 dimensions and if we append the command to this vector, that's 9 dimensions for the observation space in total. + +Next, we just need to do that appending when we get the observations. We also need to calculate our forward vectors for later use. The forward vector for the Jetbot is +the x axis, so we apply the ``root_link_quat_w`` to ``[1,0,0]`` to get the forward vector in the world frame. Replace the ``_get_observations`` method with the following: + +.. code-block:: python + + def _get_observations(self) -> dict: + self.velocity = self.robot.data.root_com_vel_w + self.forwards = math_utils.quat_apply(self.robot.data.root_link_quat_w, self.robot.data.FORWARD_VEC_B) + obs = torch.hstack((self.velocity, self.commands)) + observations = {"policy": obs} + return observations + +So now what should the reward be? + +When the robot is behaving as desired, it will be driving at full speed in the direction of the command. If we reward both +"driving forward" and "alignment to the command", then maximizing that combined signal should result in driving to the command... right? + +Let's give it a try! Replace the ``_get_rewards`` method with the following: + +.. code-block:: python + + def _get_rewards(self) -> torch.Tensor: + forward_reward = self.robot.data.root_com_lin_vel_b[:,0].reshape(-1,1) + alignment_reward = torch.sum(self.forwards * self.commands, dim=-1, keepdim=True) + total_reward = forward_reward + alignment_reward + return total_reward + +The ``forward_reward`` is the x component of the linear center of mass velocity of the robot in the body frame. We know that +the x direction is the forward direction for the asset, so this should be equivalent to inner product between the forward vector and +the linear velocity in the world frame. The alignment term is the inner product between the forward vector and the command vector: when they are +pointing in the same direction this term will be 1, but in the opposite direction it will be -1. We add them together to get the combined reward and +we can finally run training! Let's see what happens! + +.. code-block:: bash + + ./isaaclab.sh train --rl_library skrl --task=Template-Isaac-Lab-Tutorial-Direct-v0 + + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/walkthrough_naive_webp.webp + :align: center + :figwidth: 100% + :alt: Naive results + +Surely we can do better! + +Reward and Observation Tuning +------------------------------- + +When tuning an environment for training, as a rule of thumb, you want to keep the observation space as small as possible. This is to +reduce the number parameters in the model (the literal interpretation of Occam's razor) and thus improve training time. In this case we +need to somehow encode our alignment to the command and our forward speed. One way to do this is to exploit the dot and cross products +from linear algebra! Replace the contents of ``_get_observations`` with the following: + +.. code-block:: python + + def _get_observations(self) -> dict: + self.velocity = self.robot.data.root_com_vel_w + self.forwards = math_utils.quat_apply(self.robot.data.root_link_quat_w, self.robot.data.FORWARD_VEC_B) + + dot = torch.sum(self.forwards * self.commands, dim=-1, keepdim=True) + cross = torch.cross(self.forwards, self.commands, dim=-1)[:,-1].reshape(-1,1) + forward_speed = self.robot.data.root_com_lin_vel_b[:,0].reshape(-1,1) + obs = torch.hstack((dot, cross, forward_speed)) + + observations = {"policy": obs} + return observations + +We also need to **edit the ``IsaacLabTutorialEnvCfg`` to set the observation space back to 3** which includes the dot product, the z component of the cross product, and the forward speed. + +The dot or inner product tells us how aligned two vectors are as a single scalar quantity. If they are very aligned and pointed in the same direction, then the inner +product will be large and positive, but if they are aligned and in opposite directions, it will be large and negative. If two vectors are +perpendicular, the inner product is zero. This means that the inner product between the forward vector and the command vector can tell us +how much we are facing towards or away from the command, but not which direction we need to turn to improve alignment. + +The cross product also tells us how aligned two vectors are, but it expresses this relationship as a vector. The cross product between any +two vectors defines an axis that is perpendicular to the plane containing the two argument vectors, where the direction of the result vector along this axis is +determined by the chirality (dimension ordering, or handedness) of the coordinate system. In our case, we can exploit the fact that we are operating in 2D to only +examine the z component of the result of :math:`\vec{forward} \times \vec{command}`. This component will be zero if the vectors are colinear, positive if the +command vector is to the left of forward, and negative if it's to the right. + +Finally, the x component of the center of mass linear velocity tells us our forward speed, with positive being forward and negative being backwards. We stack these together +"horizontally" (along dim 1) to generate the observations for each Jetbot. This alone improves performance! + + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/walkthrough_improved_webp.webp + :align: center + :figwidth: 100% + :alt: Improved results + +It seems to qualitatively train better, and the Jetbots are somewhat inching forward... Surely we can do better still! + +Another rule of thumb for training is to reduce and simplify the reward function as much as possible. Terms in the reward behave similarly to +the logical "OR" operation. In our case, we are rewarding driving forward and being aligned to the command by adding them together, so our agent +can be reward for driving forward OR being aligned to the command. To force the agent to learn to drive in the direction of the command, we should only +reward the agent driving forward AND being aligned. Logical AND suggests multiplication and therefore the following reward function: + +.. code-block:: python + + def _get_rewards(self) -> torch.Tensor: + forward_reward = self.robot.data.root_com_lin_vel_b[:,0].reshape(-1,1) + alignment_reward = torch.sum(self.forwards * self.commands, dim=-1, keepdim=True) + total_reward = forward_reward*alignment_reward + return total_reward + +Now we will only get rewarded for driving forward if our alignment reward is non zero. Let's see what kind of result this produces! + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/walkthrough_tuned_webp.webp + :align: center + :figwidth: 100% + :alt: Tuned results + +It definitely trains faster, but the Jetbots have learned to drive in reverse if the command is pointed behind them. This may be desirable in our +case, but it shows just how dependent the policy behavior is on the reward function. In this case, there are **degenerate solutions** to our +reward function: The reward is maximized for driving forward and aligned to the command, but if the Jetbot drives in reverse, then the forward +term is negative, and if its driving in reverse towards the command, then the alignment term is **also negative**, meaning hat the reward is positive! +When you design your own environments, you will run into degenerate solutions like this and a significant amount of reward engineering is devoted to +suppressing or supporting these behaviors by modifying the reward function. + +Let's say, in our case, we don't want this behavior. In our case, the alignment term has a domain of ``[-1, 1]``, but we would much prefer it to be mapped +only to positive values. We don't want to *eliminate* the sign on the alignment term, rather, we would like large negative values to be near zero, so if we +are misaligned, we don't get rewarded. The exponential function accomplishes this! + +.. code-block:: python + + def _get_rewards(self) -> torch.Tensor: + forward_reward = self.robot.data.root_com_lin_vel_b[:,0].reshape(-1,1) + alignment_reward = torch.sum(self.forwards * self.commands, dim=-1, keepdim=True) + total_reward = forward_reward*torch.exp(alignment_reward) + return total_reward + +Now when we train, the Jetbots will turn to always drive towards the command in the forward direction! + +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/walkthrough_directed_webp.webp + :align: center + :figwidth: 100% + :alt: Directed results diff --git a/simulation/modules/IsaacLab/docs/source/testing/benchmarks.rst b/simulation/modules/IsaacLab/docs/source/testing/benchmarks.rst new file mode 100644 index 0000000000000000000000000000000000000000..e78a78ec6467ac965a572b4fae729ff6dec6be4c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/testing/benchmarks.rst @@ -0,0 +1,696 @@ +.. _testing_benchmarks: + +Benchmarking Framework +====================== + +Isaac Lab provides a comprehensive benchmarking framework for measuring the performance +of simulations, training workflows, and system resources. The framework is designed to +work without depending on Isaac Sim's benchmark services, enabling standalone benchmarking +with pluggable output backends. + +Overview +-------- + +The benchmarking framework consists of several key components: + +.. code-block:: text + + ┌─────────────────────────────────┐ + │ BaseIsaacLabBenchmark │ + │ (benchmark_core.py) │ + └───────────────┬─────────────────┘ + │ + ┌───────────┼───────────┐ + │ │ │ + ▼ ▼ ▼ + ┌───────┐ ┌─────────┐ ┌──────────┐ + │Phases │ │Recorders│ │ Backends │ + └───────┘ └─────────┘ └──────────┘ + +**Key Components:** + +- **BaseIsaacLabBenchmark**: Main class for orchestrating benchmark execution +- **Measurements**: Data classes for recording metrics (timing, counts, statistics) +- **Metadata**: Data classes for recording context (hardware, versions, parameters) +- **TestPhase**: Container for organizing measurements into logical groups +- **Recorders**: System information collectors (CPU, GPU, memory, versions) +- **Backends**: Output formatters (JSON, Osmo, OmniPerf, Summary) + +.. seealso:: + + For method-level micro-benchmarks that measure asset setter/writer and property + performance using mock interfaces (without running full simulations), see + :ref:`testing_micro_benchmarks`. + +Quick Start +----------- + +Basic usage with :class:`~isaaclab.test.benchmark.BaseIsaacLabBenchmark`: + +.. code-block:: python + + from isaaclab.test.benchmark import ( + BaseIsaacLabBenchmark, + SingleMeasurement, + StatisticalMeasurement, + StringMetadata, + ) + + # Initialize benchmark + benchmark = BaseIsaacLabBenchmark( + benchmark_name="MyBenchmark", + backend_type="json", + output_path="./results", + ) + + # Record measurements + benchmark.add_measurement( + phase_name="simulation", + measurement=SingleMeasurement( + name="fps", + value=1234.5, + unit="frames/sec" + ), + ) + + benchmark.add_measurement( + phase_name="simulation", + measurement=StatisticalMeasurement( + name="step_time", + mean=0.82, + std=0.05, + n=1000, + unit="ms" + ), + ) + + # Add metadata + benchmark.add_measurement( + phase_name="simulation", + metadata=StringMetadata(name="task", data="Isaac-Cartpole-v0"), + ) + + # Finalize and write output + benchmark._finalize_impl() + +Running Benchmark Scripts +------------------------- + +Isaac Lab provides shell scripts for running benchmark suites: + +Non-RL Benchmarks +~~~~~~~~~~~~~~~~~ + +Measure environment stepping performance without training: + +.. code-block:: bash + + # Run all non-RL benchmarks + ./scripts/benchmarks/run_non_rl_benchmarks.sh ./output_dir + + # Run a single benchmark manually + ./isaaclab.sh -p scripts/benchmarks/benchmark_non_rl.py \ + --task Isaac-Cartpole-v0 \ + --num_envs 4096 \ + --num_frames 100 \ + --benchmark_backend json \ + --output_path ./results + +RL Training Benchmarks +~~~~~~~~~~~~~~~~~~~~~~ + +Measure training performance with RSL-RL: + +.. code-block:: bash + + # Run training benchmarks + ./scripts/benchmarks/run_training_benchmarks.sh ./output_dir + + # Run manually with RSL-RL + ./isaaclab.sh -p scripts/benchmarks/benchmark_rsl_rl.py \ + --task Isaac-Cartpole-v0 \ + --num_envs 4096 \ + --max_iterations 500 \ + --benchmark_backend json \ + --output_path ./results + +PhysX Micro-Benchmarks +~~~~~~~~~~~~~~~~~~~~~~ + +Measure asset method and property performance using mock interfaces: + +.. code-block:: bash + + # Run PhysX micro-benchmarks + ./scripts/benchmarks/run_physx_benchmarks.sh ./output_dir + + # Run articulation benchmarks manually + ./isaaclab.sh -p source/isaaclab_physx/benchmark/assets/benchmark_articulation.py \ + --num_iterations 1000 \ + --num_instances 4096 + +For detailed documentation on micro-benchmarks, including available benchmark files, +input modes, and how to add new benchmarks, see :ref:`testing_micro_benchmarks`. + +Startup Profiling Benchmark +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Profile the startup sequence of an IsaacLab environment using ``cProfile``. Each +startup stage is wrapped in its own profiling session and the top functions by +own-time are reported. This is useful for investigating startup regressions and +understanding where time is spent during initialization. + +.. code-block:: bash + + # Basic usage — reports top 30 functions per phase + ./isaaclab.sh -p scripts/benchmarks/benchmark_startup.py \ + --task Isaac-Ant-v0 \ + --num_envs 4096 \ + --benchmark_backend summary + +The script profiles five phases independently: + +- **app_launch**: ``launch_simulation()`` context entry (Kit/USD/PhysX init) +- **python_imports**: importing gymnasium, torch, isaaclab_tasks, etc. +- **task_config**: ``resolve_task_config()`` (Hydra config resolution) +- **env_creation**: ``gym.make()`` + ``env.reset()`` (scene creation, sim start) +- **first_step**: a single ``env.step()`` call + +Each phase records a wall-clock time plus per-function own-time and cumulative +time as ``SingleMeasurement`` entries. Only IsaacLab functions and first-level +calls into external libraries are included (deep internals of torch, USD, etc. +are filtered out). + +**Whitelist mode** — For dashboard time-series comparisons across runs, use a +YAML whitelist config to report a fixed set of functions instead of top-N. +Patterns use ``fnmatch`` syntax (``*`` and ``?`` wildcards): + +.. code-block:: yaml + + # Example whitelist config + app_launch: + - "isaaclab.utils.configclass:_custom_post_init" + - "isaaclab.sim.*:__init__" + env_creation: + - "isaaclab.cloner.*:usd_replicate" + - "isaaclab.cloner.*:filter_collisions" + - "isaaclab.scene.*:_init_scene" + first_step: + - "isaaclab.actuators.*:compute" + - "warp.*:launch" + +.. code-block:: bash + + ./isaaclab.sh -p scripts/benchmarks/benchmark_startup.py \ + --task Isaac-Ant-v0 \ + --num_envs 4096 \ + --benchmark_backend omniperf \ + --whitelist_config scripts/benchmarks/startup_whitelist.yaml + +Phases listed in the YAML use the whitelist; phases not listed fall back to +``--top_n`` (default: 5 in whitelist mode, 30 otherwise). Patterns that match +no profiled function emit ``0.0`` placeholders so the output always contains +the same keys. + +A default whitelist is provided at ``scripts/benchmarks/startup_whitelist.yaml``. + +.. list-table:: + :header-rows: 1 + :widths: 25 15 60 + + * - Argument + - Default + - Description + * - ``--task`` + - required + - Environment task name + * - ``--num_envs`` + - from config + - Number of parallel environments + * - ``--top_n`` + - 30 (5 with whitelist) + - Max functions per non-whitelisted phase + * - ``--whitelist_config`` + - None + - Path to YAML whitelist file + * - ``--benchmark_backend`` + - ``omniperf`` + - Output backend (``json``, ``osmo``, ``omniperf``, ``summary``) + * - ``--output_path`` + - ``.`` + - Directory for output files + +Command Line Arguments +---------------------- + +Common Arguments +~~~~~~~~~~~~~~~~ + +.. list-table:: + :header-rows: 1 + :widths: 25 15 60 + + * - Argument + - Default + - Description + * - ``--benchmark_backend`` + - ``json`` + - Output backend: ``json``, ``osmo``, ``omniperf``, or ``summary`` + * - ``--output_path`` + - ``./`` + - Directory for output files + +Non-RL Benchmark Arguments +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :header-rows: 1 + :widths: 25 15 60 + + * - Argument + - Default + - Description + * - ``--task`` + - required + - Environment task name (e.g., ``Isaac-Cartpole-v0``) + * - ``--num_envs`` + - ``4096`` + - Number of parallel environments + * - ``--num_frames`` + - ``100`` + - Number of simulation frames to run + * - ``--enable_cameras`` + - ``false`` + - Enable camera rendering (for RGB/depth tasks) + +RL Training Arguments +~~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :header-rows: 1 + :widths: 25 15 60 + + * - Argument + - Default + - Description + * - ``--task`` + - required + - Environment task name + * - ``--num_envs`` + - ``4096`` + - Number of parallel environments + * - ``--max_iterations`` + - ``500`` + - Number of training iterations + +Measurement Types +----------------- + +The framework provides several measurement types for different data: + +SingleMeasurement +~~~~~~~~~~~~~~~~~ + +For single numeric values: + +.. code-block:: python + + from isaaclab.test.benchmark import SingleMeasurement + + measurement = SingleMeasurement( + name="total_frames", + value=100000, + unit="frames" + ) + +StatisticalMeasurement +~~~~~~~~~~~~~~~~~~~~~~ + +For statistical summaries: + +.. code-block:: python + + from isaaclab.test.benchmark import StatisticalMeasurement + + measurement = StatisticalMeasurement( + name="step_time", + mean=0.82, + std=0.05, + n=1000, + unit="ms" + ) + +BooleanMeasurement +~~~~~~~~~~~~~~~~~~ + +For pass/fail status: + +.. code-block:: python + + from isaaclab.test.benchmark import BooleanMeasurement + + measurement = BooleanMeasurement( + name="converged", + bvalue=True + ) + +DictMeasurement +~~~~~~~~~~~~~~~ + +For structured data: + +.. code-block:: python + + from isaaclab.test.benchmark import DictMeasurement + + measurement = DictMeasurement( + name="config", + value={"learning_rate": 0.001, "batch_size": 64} + ) + +ListMeasurement +~~~~~~~~~~~~~~~ + +For sequences of values: + +.. code-block:: python + + from isaaclab.test.benchmark import ListMeasurement + + measurement = ListMeasurement( + name="rewards_per_episode", + value=[100.5, 102.3, 98.7, 105.1] + ) + +Test Phases +----------- + +:class:`~isaaclab.test.benchmark.TestPhase` organizes measurements and metadata +into logical groups. Common phases include: + +- ``benchmark_info``: Workflow name, timestamp, configuration +- ``hardware_info``: CPU, GPU, memory information +- ``version_info``: Software versions (Isaac Sim, PyTorch, etc.) +- ``simulation``: Environment stepping metrics +- ``training``: RL training metrics +- ``runtime``: Execution time and resource usage + +Example: + +.. code-block:: python + + # Measurements are automatically grouped by phase + benchmark.add_measurement("simulation", measurement=fps_measurement) + benchmark.add_measurement("simulation", metadata=task_metadata) + benchmark.add_measurement("training", measurement=reward_measurement) + +Output Backends +--------------- + +JSON Backend +~~~~~~~~~~~~ + +Full output with all phases, measurements, and metadata: + +.. code-block:: bash + + ./isaaclab.sh -p ... --benchmark_backend json --output_path ./results + +Output structure: + +.. code-block:: json + + [ + { + "phase_name": "simulation", + "measurements": [ + { + "name": "MyBenchmark simulation fps", + "value": 1234.5, + "unit": "frames/sec", + "type": "single" + } + ], + "metadata": [ + {"name": "MyBenchmark simulation task", "data": "Isaac-Cartpole-v0", "type": "string"} + ] + } + ] + +Osmo Backend +~~~~~~~~~~~~ + +Simplified key-value format for CI/CD integration: + +.. code-block:: bash + + ./isaaclab.sh -p ... --benchmark_backend osmo --output_path ./results + +Output structure: + +.. code-block:: json + + { + "workflow_name": "MyBenchmark", + "phase": "simulation", + "fps": 1234.5, + "task": "Isaac-Cartpole-v0" + } + +OmniPerf Backend +~~~~~~~~~~~~~~~~ + +Format for database upload and performance tracking: + +.. code-block:: bash + + ./isaaclab.sh -p ... --benchmark_backend omniperf --output_path ./results + +Output structure: + +.. code-block:: json + + { + "simulation": { + "workflow_name": "MyBenchmark", + "fps": 1234.5, + "step_time_mean": 0.82, + "step_time_std": 0.05 + } + } + +Summary Backend +~~~~~~~~~~~~~~~ + +Human-readable console report plus JSON file. Prints a formatted summary to the +terminal while also writing the same data as JSON. Standard phases (runtime, +startup, train, frametime, system info) are rendered with specialized formatting; +any additional phases (e.g., from the startup profiling benchmark) are rendered +automatically with their ``SingleMeasurement`` and ``StatisticalMeasurement`` +entries. Use when you want a quick readout without opening the JSON: + +.. code-block:: bash + + ./isaaclab.sh -p ... --benchmark_backend summary --output_path ./results + +When ``summary`` is selected, frametime recorders are enabled automatically when +running with Isaac Sim (Kit). + +BenchmarkMonitor +---------------- + +:class:`~isaaclab.test.benchmark.BenchmarkMonitor` enables continuous system +monitoring during blocking operations like RL training loops: + +.. code-block:: python + + from isaaclab.test.benchmark import BaseIsaacLabBenchmark, BenchmarkMonitor + + benchmark = BaseIsaacLabBenchmark( + benchmark_name="TrainingBenchmark", + backend_type="json", + output_path="./results", + ) + + # Monitor system resources during blocking training call + with BenchmarkMonitor(benchmark, interval=1.0): + runner.learn(num_learning_iterations=1000) # Blocking call + + benchmark._finalize_impl() + +The monitor runs in a background thread and periodically calls +``update_manual_recorders()`` to capture CPU, GPU, and memory usage samples. + +System Recorders +---------------- + +The framework includes built-in recorders for system information: + +CPUInfoRecorder +~~~~~~~~~~~~~~~ + +Captures CPU model, core count, and usage statistics. + +GPUInfoRecorder +~~~~~~~~~~~~~~~ + +Captures GPU model, memory, and utilization via ``nvidia-smi``. + +MemoryInfoRecorder +~~~~~~~~~~~~~~~~~~ + +Captures system and GPU memory usage over time. + +VersionInfoRecorder +~~~~~~~~~~~~~~~~~~~ + +Captures software versions: + +- Isaac Sim version +- Isaac Lab version +- PyTorch version +- CUDA version +- Python version + +Creating Custom Benchmarks +-------------------------- + +Step 1: Initialize Benchmark +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: python + + import argparse + from isaaclab.test.benchmark import BaseIsaacLabBenchmark + + parser = argparse.ArgumentParser() + parser.add_argument("--benchmark_backend", default="json") + parser.add_argument("--output_path", default="./") + args = parser.parse_args() + + benchmark = BaseIsaacLabBenchmark( + benchmark_name="CustomBenchmark", + backend_type=args.benchmark_backend, + output_path=args.output_path, + ) + +Step 2: Run Your Workload +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: python + + import time + + start_time = time.time() + + # Your workload here + for i in range(num_iterations): + env.step(actions) + + elapsed = time.time() - start_time + +Step 3: Record Measurements +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: python + + from isaaclab.test.benchmark import SingleMeasurement, StringMetadata + + benchmark.add_measurement( + phase_name="runtime", + measurement=SingleMeasurement( + name="total_time", + value=elapsed, + unit="seconds" + ), + ) + + benchmark.add_measurement( + phase_name="runtime", + metadata=StringMetadata(name="num_iterations", data=str(num_iterations)), + ) + +Step 4: Finalize +~~~~~~~~~~~~~~~~ + +.. code-block:: python + + benchmark._finalize_impl() + +Integration with CI/CD +---------------------- + +The shell scripts in ``scripts/benchmarks/`` are designed for CI/CD integration: + +.. code-block:: bash + + # GitHub Actions / GitLab CI example + - name: Run Benchmarks + run: | + ./scripts/benchmarks/run_non_rl_benchmarks.sh ./benchmark_results + + - name: Upload Results + uses: actions/upload-artifact@v3 + with: + name: benchmark-results + path: ./benchmark_results/ + +For Osmo integration, use the ``osmo`` backend: + +.. code-block:: bash + + ./scripts/benchmarks/run_non_rl_benchmarks.sh ./results + # Results are in Osmo-compatible JSON format + +Troubleshooting +--------------- + +Import Errors +~~~~~~~~~~~~~ + +Ensure you're running through the Isaac Lab launcher: + +.. code-block:: bash + + ./isaaclab.sh -p your_benchmark.py + +Not: + +.. code-block:: bash + + python your_benchmark.py # Missing environment setup + +Missing GPU Metrics +~~~~~~~~~~~~~~~~~~~ + +Verify ``nvidia-smi`` is available and CUDA is configured: + +.. code-block:: bash + + nvidia-smi # Should show GPU info + +Empty Output Files +~~~~~~~~~~~~~~~~~~ + +Ensure ``_finalize_impl()`` is called before the script exits: + +.. code-block:: python + + try: + # Your benchmark code + pass + finally: + benchmark._finalize_impl() + +Backend Not Recognized +~~~~~~~~~~~~~~~~~~~~~~ + +Valid backend types are: ``json``, ``osmo``, ``omniperf``, ``summary`` + +.. code-block:: bash + + # Correct + --benchmark_backend json + + # Incorrect + --benchmark_backend JSON # Case sensitive diff --git a/simulation/modules/IsaacLab/docs/source/testing/index.rst b/simulation/modules/IsaacLab/docs/source/testing/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..4d875d98279710e0d8a924d3e193e828a072eaa7 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/testing/index.rst @@ -0,0 +1,13 @@ +.. _testing: + +Testing +======== + +This section covers testing utilities and patterns for Isaac Lab development. + +.. toctree:: + :maxdepth: 2 + + mock_interfaces + micro_benchmarks + benchmarks diff --git a/simulation/modules/IsaacLab/docs/source/testing/micro_benchmarks.rst b/simulation/modules/IsaacLab/docs/source/testing/micro_benchmarks.rst new file mode 100644 index 0000000000000000000000000000000000000000..d4d9ce82f6487b9c3397f09fa9645f900499d120 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/testing/micro_benchmarks.rst @@ -0,0 +1,366 @@ +.. _testing_micro_benchmarks: + +Micro-Benchmarks for Performance Testing +======================================== + +Isaac Lab provides micro-benchmarking tools to measure the performance of asset +setter/writer methods and data property accessors without requiring Isaac Sim. + +.. seealso:: + + For full-simulation benchmarks (environment stepping, RL training), see + :ref:`testing_benchmarks`. This page covers method-level micro-benchmarks + that use mock interfaces. + +Overview +-------- + +The benchmarks use **mock interfaces** to simulate PhysX views, allowing performance +measurement of Python-level overhead in isolation. This is useful for: + +- Comparing list vs tensor index performance +- Identifying bottlenecks in hot code paths +- Tracking performance regressions +- Optimizing custom methods + +Quick Start +----------- + +Run benchmarks using the Isaac Lab launcher: + +.. code-block:: bash + + # Run Articulation method benchmarks + ./isaaclab.sh -p source/isaaclab_physx/benchmark/assets/benchmark_articulation.py + + # With custom parameters + ./isaaclab.sh -p source/isaaclab_physx/benchmark/assets/benchmark_articulation.py \ + --num_iterations 1000 \ + --num_instances 64 \ + --num_bodies 5 \ + --num_joints 4 + +Available Benchmarks +-------------------- + +Asset Method Benchmarks +~~~~~~~~~~~~~~~~~~~~~~~ + +These benchmark setter and writer methods on asset classes: + +.. list-table:: + :header-rows: 1 + :widths: 35 25 40 + + * - Benchmark File + - Asset Class + - Methods Covered + * - ``benchmark_articulation.py`` + - ``Articulation`` + - 24 methods (root/joint state, mass props, forces) + * - ``benchmark_rigid_object.py`` + - ``RigidObject`` + - 13 methods (root state, mass props, forces) + * - ``benchmark_rigid_object_collection.py`` + - ``RigidObjectCollection`` + - 13 methods (body state, mass props, forces) + +Data Property Benchmarks +~~~~~~~~~~~~~~~~~~~~~~~~ + +These benchmark property accessors on data classes: + +.. list-table:: + :header-rows: 1 + :widths: 40 30 30 + + * - Benchmark File + - Data Class + - Properties + * - ``benchmark_articulation_data.py`` + - ``ArticulationData`` + - 59 properties + * - ``benchmark_rigid_object_data.py`` + - ``RigidObjectData`` + - 40 properties + * - ``benchmark_rigid_object_collection_data.py`` + - ``RigidObjectCollectionData`` + - 40 properties + +All benchmarks are located in ``source/isaaclab_physx/benchmark/assets/``. + +Command Line Arguments +---------------------- + +Common Arguments +~~~~~~~~~~~~~~~~ + +.. list-table:: + :header-rows: 1 + :widths: 20 15 65 + + * - Argument + - Default + - Description + * - ``--num_iterations`` + - 1000 + - Number of timed iterations + * - ``--warmup_steps`` + - 10 + - Warmup iterations (not timed) + * - ``--num_instances`` + - 4096 + - Number of asset instances + * - ``--device`` + - ``cuda:0`` + - Device for tensors + * - ``--mode`` + - ``all`` + - ``all``, ``torch_list``, or ``torch_tensor`` + * - ``--output`` + - auto + - Output JSON filename + * - ``--no_csv`` + - false + - Disable CSV output + +Asset-Specific Arguments +~~~~~~~~~~~~~~~~~~~~~~~~ + +**Articulation benchmarks:** + +- ``--num_bodies``: Number of links (default: 13) +- ``--num_joints``: Number of DOFs (default: 12) + +**RigidObjectCollection benchmarks:** + +- ``--num_bodies``: Number of bodies in collection (default: 5) + +Benchmark Modes +--------------- + +Each method is benchmarked under two input scenarios: + +**torch_list** + Environment/body IDs passed as Python lists. Measures the overhead of + list-to-tensor conversion, which is common in user code. + +**torch_tensor** + Environment/body IDs passed as pre-allocated tensors. Represents the + optimal baseline with minimal overhead. + +Example output: + +.. code-block:: text + + [1/24] [TORCH_LIST] write_root_state_to_sim... 132.02 ± 6.79 µs + [1/24] [TORCH_TENSOR] write_root_state_to_sim... 65.44 ± 3.06 µs + +The comparison shows tensor indices are ~2x faster than list indices. + +Output Format +------------- + +Console Output +~~~~~~~~~~~~~~ + +.. code-block:: text + + Benchmarking Articulation (PhysX) with 64 instances, 5 bodies, 4 joints... + Device: cuda:0 + Iterations: 100, Warmup: 10 + + Benchmarking 24 methods... + [1/24] [TORCH_LIST] write_root_state_to_sim... 132.02 ± 6.79 µs + [1/24] [TORCH_TENSOR] write_root_state_to_sim... 65.44 ± 3.06 µs + ... + + ================================================================================ + COMPARISON: Torch_list vs Torch_tensor + ================================================================================ + Method Name Torch_list Torch_tensor Speedup + ------------------------------------------------------------------------ + write_root_state_to_sim 132.02 65.44 2.02x + +Export Files +~~~~~~~~~~~~ + +Results are automatically exported to: + +- ``{benchmark_name}_{timestamp}.json`` - Full results with hardware info +- ``{benchmark_name}_{timestamp}.csv`` - Tabular results for analysis + +JSON Structure +~~~~~~~~~~~~~~ + +.. code-block:: json + + { + "config": { + "num_iterations": 100, + "num_instances": 64, + "device": "cuda:0" + }, + "hardware": { + "cpu": "Intel Core i9-13950HX", + "gpu": "NVIDIA RTX 5000", + "pytorch": "2.7.0", + "cuda": "12.8" + }, + "results": [ + { + "name": "write_root_state_to_sim", + "mode": "torch_list", + "mean_us": 132.02, + "std_us": 6.79, + "iterations": 100 + } + ] + } + +Architecture +------------ + +The benchmarks use mock interfaces to simulate PhysX views without Isaac Sim: + +.. code-block:: text + + ┌─────────────────────┐ ┌──────────────────────┐ + │ Asset Class │────>│ MockArticulationView│ + │ (Articulation) │ │ (mock_interfaces) │ + └─────────────────────┘ └──────────────────────┘ + │ + v + ┌───────────────────────────┐ + │ MethodBenchmarkRunner │ + │ (extends BaseIsaacLab- │ + │ Benchmark) │ + └───────────────────────────┘ + │ + v + ┌───────────────────────────┐ + │ Output Backends │ + │ (json, osmo, omniperf) │ + └───────────────────────────┘ + +Key Components +~~~~~~~~~~~~~~ + +1. **Mock Views** (``isaaclab_physx/test/mock_interfaces/``) + + - ``MockArticulationView`` - Mimics PhysX ArticulationView + - ``MockRigidBodyView`` - Mimics PhysX RigidBodyView + +2. **Benchmark Framework** (``isaaclab/test/benchmark/``) + + - :class:`~isaaclab.test.benchmark.MethodBenchmarkRunner` - Runner extending + :class:`~isaaclab.test.benchmark.BaseIsaacLabBenchmark` for method-level benchmarks + - :class:`~isaaclab.test.benchmark.MethodBenchmarkRunnerConfig` - Configuration dataclass + - :class:`~isaaclab.test.benchmark.MethodBenchmarkDefinition` - Benchmark definition + - Multiple output backends (JSON, Osmo, OmniPerf) + +3. **Module Mocking** + + Each benchmark file mocks Isaac Sim dependencies (``isaacsim``, ``omni``, ``pxr``) + to allow the asset classes to be instantiated without simulation. + +Adding New Benchmarks +--------------------- + +Adding a Method Benchmark +~~~~~~~~~~~~~~~~~~~~~~~~~ + +1. Create input generator functions: + +.. code-block:: python + + from isaaclab.test.benchmark import MethodBenchmarkRunnerConfig + + def gen_my_method_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "param1": torch.rand(config.num_instances, 3, device=config.device), + "env_ids": list(range(config.num_instances)), + } + + def gen_my_method_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "param1": torch.rand(config.num_instances, 3, device=config.device), + "env_ids": torch.arange(config.num_instances, device=config.device), + } + +2. Add to the ``BENCHMARKS`` list: + +.. code-block:: python + + from isaaclab.test.benchmark import MethodBenchmarkDefinition + + MethodBenchmarkDefinition( + name="my_method", + method_name="my_method", + input_generators={ + "torch_list": gen_my_method_torch_list, + "torch_tensor": gen_my_method_torch_tensor, + }, + category="my_category", + ), + +Adding a Property Benchmark +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +For data class properties, add to the ``PROPERTIES`` list: + +.. code-block:: python + + ("my_property", {"derived_from": ["dependency1", "dependency2"]}), + +The ``derived_from`` key indicates dependencies that should be pre-computed +before timing the property access. + +Performance Tips +---------------- + +Based on benchmark results: + +1. **Use tensor indices** instead of lists for 30-50% speedup +2. **Pre-allocate index tensors** and reuse them across calls +3. **Batch operations** where possible (e.g., set all joint positions at once) +4. **Mass properties are CPU-bound** - PhysX requires CPU tensors for these + +Example optimization: + +.. code-block:: python + + # Slow: Create new list each call + for _ in range(1000): + robot.write_joint_state_to_sim(state, env_ids=list(range(64))) + + # Fast: Pre-allocate tensor and reuse + env_ids = torch.arange(64, device="cuda:0") + for _ in range(1000): + robot.write_joint_state_to_sim(state, env_ids=env_ids) + +Troubleshooting +--------------- + +Import Errors +~~~~~~~~~~~~~ + +Ensure you're running through ``isaaclab.sh``: + +.. code-block:: bash + + ./isaaclab.sh -p source/isaaclab_physx/benchmark/assets/benchmark_articulation.py + +CUDA Out of Memory +~~~~~~~~~~~~~~~~~~ + +Reduce ``--num_instances``: + +.. code-block:: bash + + ./isaaclab.sh -p ... --num_instances 1024 + +Slow First Run +~~~~~~~~~~~~~~ + +The first run compiles Warp kernels. Subsequent runs will be faster. diff --git a/simulation/modules/IsaacLab/docs/source/testing/mock_interfaces.rst b/simulation/modules/IsaacLab/docs/source/testing/mock_interfaces.rst new file mode 100644 index 0000000000000000000000000000000000000000..63c9a2477db7efca740411bb6bd2a885fd05af6c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/testing/mock_interfaces.rst @@ -0,0 +1,470 @@ +.. _testing_mock_interfaces: + +Mock Interfaces for Unit Testing +================================ + +Isaac Lab provides mock implementations of sensor, asset, and PhysX view classes +for unit testing without requiring Isaac Sim or GPU simulation. + +Overview +-------- + +Two levels of mock interfaces are available: + +1. **High-level mocks** (``isaaclab.test.mock_interfaces``) - Mock sensors and assets +2. **Low-level PhysX mocks** (``isaaclab_physx.test.mock_interfaces``) - Mock PhysX TensorAPI views + +High-Level Mock Interfaces +-------------------------- + +Located in ``isaaclab.test.mock_interfaces``, these mock the public API of sensor +and asset base classes. + +Available Mocks +~~~~~~~~~~~~~~~ + +**Sensors:** + +.. list-table:: + :header-rows: 1 + :widths: 25 25 50 + + * - Mock Class + - Real Class + - Description + * - ``MockImu`` + - ``BaseImu`` + - IMU sensor (accelerometer + gyroscope) + * - ``MockContactSensor`` + - ``BaseContactSensor`` + - Contact force sensor + * - ``MockFrameTransformer`` + - ``BaseFrameTransformer`` + - Frame tracking sensor + +**Assets:** + +.. list-table:: + :header-rows: 1 + :widths: 25 25 50 + + * - Mock Class + - Real Class + - Description + * - ``MockArticulation`` + - ``BaseArticulation`` + - Articulated robot (joints + bodies) + * - ``MockRigidObject`` + - ``BaseRigidObject`` + - Single rigid body + * - ``MockRigidObjectCollection`` + - ``BaseRigidObjectCollection`` + - Collection of rigid bodies + +Quick Start +~~~~~~~~~~~ + +.. code-block:: python + + import torch + from isaaclab.test.mock_interfaces import MockArticulation, MockContactSensor + + # Create a mock quadruped robot + robot = MockArticulation( + num_instances=4, + num_joints=12, + num_bodies=13, + joint_names=[f"joint_{i}" for i in range(12)], + device="cpu" + ) + + # Set joint states + robot.data.set_mock_data( + joint_pos=torch.zeros(4, 12), + joint_vel=torch.randn(4, 12) * 0.1 + ) + + # Access data like the real asset + positions = robot.data.joint_pos # Shape: (4, 12) + + # Create a mock contact sensor + sensor = MockContactSensor(num_instances=4, num_bodies=4, device="cpu") + sensor.data.set_net_forces_w(torch.randn(4, 4, 3)) + +Factory Functions +~~~~~~~~~~~~~~~~~ + +Pre-configured factories for common use cases: + +.. code-block:: python + + from isaaclab.test.mock_interfaces import ( + create_mock_quadruped, + create_mock_humanoid, + create_mock_foot_contact_sensor, + ) + + # Pre-configured quadruped (12 joints, 13 bodies) + robot = create_mock_quadruped(num_instances=4) + + # Pre-configured humanoid (21 joints, 22 bodies) + humanoid = create_mock_humanoid(num_instances=2) + + # Foot contact sensor for quadruped + foot_contact = create_mock_foot_contact_sensor(num_instances=4, num_feet=4) + +Patching Utilities +~~~~~~~~~~~~~~~~~~ + +Use context managers or decorators to inject mocks into tests: + +**Context Managers:** + +.. code-block:: python + + from isaaclab.test.mock_interfaces.utils import patch_articulation, patch_sensor + + with patch_articulation("my_module.Articulation", num_joints=12) as MockRobot: + robot = my_function_that_creates_robot() + robot.data.set_joint_pos(torch.zeros(1, 12)) + + with patch_sensor("my_module.ContactSensor", "contact", num_bodies=4): + sensor = my_function_that_creates_sensor() + +**Decorators:** + +.. code-block:: python + + from isaaclab.test.mock_interfaces.utils import mock_articulation, mock_sensor + + @mock_articulation(num_joints=12, num_bodies=13) + def test_observation_function(mock_robot): + mock_robot.data.set_joint_pos(torch.zeros(1, 12)) + obs = compute_observation(mock_robot) + assert obs.shape == (1, 24) + + @mock_sensor("contact", num_instances=4, num_bodies=4) + def test_contact_reward(mock_contact): + mock_contact.data.set_net_forces_w(torch.randn(4, 4, 3)) + reward = compute_contact_reward(mock_contact) + +Low-Level PhysX Mock Interfaces +------------------------------- + +Located in ``isaaclab_physx.test.mock_interfaces``, these mock the PhysX TensorAPI +views used internally by assets and sensors. + +Available Mocks +~~~~~~~~~~~~~~~ + +.. list-table:: + :header-rows: 1 + :widths: 25 25 50 + + * - Mock Class + - PhysX Class + - Used By + * - ``MockRigidBodyView`` + - ``physx.RigidBodyView`` + - ``RigidObject`` + * - ``MockArticulationView`` + - ``physx.ArticulationView`` + - ``Articulation`` + * - ``MockRigidContactView`` + - ``physx.RigidContactView`` + - ``ContactSensor`` + +Quick Start +~~~~~~~~~~~ + +.. code-block:: python + + from isaaclab_physx.test.mock_interfaces import ( + MockRigidBodyView, + MockArticulationView, + MockRigidContactView, + ) + + # Create a mock rigid body view + view = MockRigidBodyView(count=4, device="cpu") + transforms = view.get_transforms() # Shape: (4, 7) + + # Set mock data + view.set_mock_transforms(torch.randn(4, 7)) + + # Create a mock articulation view + art_view = MockArticulationView( + count=4, + num_dofs=12, + num_links=13, + device="cpu" + ) + positions = art_view.get_dof_positions() # Shape: (4, 12) + +Factory Functions +~~~~~~~~~~~~~~~~~ + +.. code-block:: python + + from isaaclab_physx.test.mock_interfaces import ( + create_mock_rigid_body_view, + create_mock_articulation_view, + create_mock_quadruped_view, + create_mock_rigid_contact_view, + ) + + # Pre-configured quadruped view (12 DOFs, 13 links) + view = create_mock_quadruped_view(count=4) + + # Pre-configured humanoid view (21 DOFs, 22 links) + humanoid = create_mock_humanoid_view(count=2) + +Patching Utilities +~~~~~~~~~~~~~~~~~~ + +.. code-block:: python + + from isaaclab_physx.test.mock_interfaces.utils import ( + patch_rigid_body_view, + patch_articulation_view, + mock_articulation_view, + ) + + # Context manager + with patch_rigid_body_view("my_module.physx.RigidBodyView", count=4): + view = create_rigid_body() + + # Decorator + @mock_articulation_view(count=4, num_dofs=12, num_links=13) + def test_my_function(mock_view): + positions = mock_view.get_dof_positions() + assert positions.shape == (4, 12) + +Data Shapes Reference +--------------------- + +High-Level Mocks +~~~~~~~~~~~~~~~~ + +**IMU Data:** + +.. list-table:: + :header-rows: 1 + :widths: 25 20 55 + + * - Property + - Shape + - Description + * - ``pos_w`` + - ``(N, 3)`` + - Position in world frame + * - ``quat_w`` + - ``(N, 4)`` + - Orientation (w,x,y,z) in world frame + * - ``lin_vel_b`` + - ``(N, 3)`` + - Linear velocity in body frame + * - ``ang_vel_b`` + - ``(N, 3)`` + - Angular velocity in body frame + * - ``projected_gravity_b`` + - ``(N, 3)`` + - Gravity in body frame + +**Contact Sensor Data:** + +.. list-table:: + :header-rows: 1 + :widths: 25 20 55 + + * - Property + - Shape + - Description + * - ``net_forces_w`` + - ``(N, B, 3)`` + - Net contact forces + * - ``force_matrix_w`` + - ``(N, B, M, 3)`` + - Filtered forces + * - ``current_contact_time`` + - ``(N, B)`` + - Time in contact + * - ``current_air_time`` + - ``(N, B)`` + - Time in air + +Where N = instances, B = bodies, M = filter bodies + +**Articulation Data:** + +.. list-table:: + :header-rows: 1 + :widths: 25 20 55 + + * - Property + - Shape + - Description + * - ``joint_pos`` + - ``(N, J)`` + - Joint positions + * - ``joint_vel`` + - ``(N, J)`` + - Joint velocities + * - ``root_link_pose_w`` + - ``(N, 7)`` + - Root pose in world + * - ``body_link_pose_w`` + - ``(N, B, 7)`` + - Body poses in world + +Where N = instances, J = joints, B = bodies + +PhysX View Mocks +~~~~~~~~~~~~~~~~ + +**RigidBodyView:** + +.. list-table:: + :header-rows: 1 + :widths: 30 20 50 + + * - Method + - Shape + - Description + * - ``get_transforms()`` + - ``(N, 7)`` + - [pos(3), quat_xyzw(4)] + * - ``get_velocities()`` + - ``(N, 6)`` + - [lin_vel(3), ang_vel(3)] + * - ``get_masses()`` + - ``(N, 1, 1)`` + - mass per body + * - ``get_inertias()`` + - ``(N, 1, 3, 3)`` + - 3x3 inertia matrix + +**ArticulationView:** + +.. list-table:: + :header-rows: 1 + :widths: 35 20 45 + + * - Method + - Shape + - Description + * - ``get_root_transforms()`` + - ``(N, 7)`` + - Root pose + * - ``get_link_transforms()`` + - ``(N, L, 7)`` + - Link poses + * - ``get_dof_positions()`` + - ``(N, J)`` + - Joint positions + * - ``get_dof_limits()`` + - ``(N, J, 2)`` + - [lower, upper] + +**RigidContactView:** + +.. list-table:: + :header-rows: 1 + :widths: 40 20 40 + + * - Method + - Shape + - Description + * - ``get_net_contact_forces(dt)`` + - ``(N*B, 3)`` + - Flat net forces + * - ``get_contact_force_matrix(dt)`` + - ``(N*B, F, 3)`` + - Per-filter forces + +Design Patterns +--------------- + +All mock interfaces follow these patterns: + +1. **Lazy Initialization** - Tensors created on first access with correct shapes +2. **Device Transfer** - All setters call ``.to(device)`` +3. **Identity Quaternion Defaults** - Quaternions default to identity +4. **Clone on Getters** - Return ``.clone()`` to prevent mutation +5. **No-op Actions** - Simulation operations (reset, update, write_to_sim) do nothing +6. **Mock Setters** - Direct ``set_mock_*`` methods for test setup + +Example: Testing an Observation Function +---------------------------------------- + +.. code-block:: python + + import pytest + import torch + from isaaclab.test.mock_interfaces import MockArticulation + + @pytest.fixture + def robot(): + return MockArticulation( + num_instances=4, + num_joints=12, + num_bodies=13, + device="cpu" + ) + + def test_joint_observation(robot): + # Setup + joint_pos = torch.randn(4, 12) + robot.data.set_joint_pos(joint_pos) + + # Test your observation function + obs = compute_joint_observation(robot) + + # Verify + assert obs.shape == (4, 24) # pos + vel + assert torch.allclose(obs[:, :12], joint_pos) + + def test_body_observation(robot): + # Setup + body_poses = torch.randn(4, 13, 7) + robot.data.set_body_link_pose_w(body_poses) + + # Test + obs = compute_body_observation(robot) + assert obs.shape == (4, 13, 7) + +Example: Testing with PhysX View Mocks +-------------------------------------- + +.. code-block:: python + + import pytest + import torch + from isaaclab_physx.test.mock_interfaces import create_mock_quadruped_view + from isaaclab_physx.test.mock_interfaces.utils import mock_articulation_view + + def test_quadruped_joint_limits(): + """Test quadruped joint limit handling.""" + view = create_mock_quadruped_view(count=4) + + # Set custom joint limits + limits = torch.zeros(4, 12, 2) + limits[:, :, 0] = -1.5 # lower limit + limits[:, :, 1] = 1.5 # upper limit + view.set_mock_dof_limits(limits) + + # Verify limits + result = view.get_dof_limits() + assert torch.allclose(result[:, :, 0], torch.full((4, 12), -1.5)) + assert torch.allclose(result[:, :, 1], torch.full((4, 12), 1.5)) + + @mock_articulation_view(count=4, num_dofs=12, num_links=13) + def test_articulation_with_decorator(mock_view): + """Test using the decorator pattern.""" + # Set some initial positions + positions = torch.randn(4, 12) + mock_view.set_mock_dof_positions(positions) + + # Verify + result = mock_view.get_dof_positions() + assert torch.allclose(result, positions) diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/00_sim/create_empty.rst b/simulation/modules/IsaacLab/docs/source/tutorials/00_sim/create_empty.rst new file mode 100644 index 0000000000000000000000000000000000000000..e2b9788d7f86f43dc00c4554ef44baa9e3b41ee8 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/00_sim/create_empty.rst @@ -0,0 +1,166 @@ +Creating an empty scene +======================= + +.. currentmodule:: isaaclab + +This tutorial shows how to launch and control Isaac Sim simulator from a standalone Python script. It sets up an +empty scene in Isaac Lab and introduces the two main classes used in the framework, :class:`app.AppLauncher` and +:class:`sim.SimulationContext`. + +Please review `Isaac Sim Workflows`_ prior to beginning this tutorial to get +an initial understanding of working with the simulator. + + +The Code +~~~~~~~~ + +The tutorial corresponds to the ``create_empty.py`` script in the ``scripts/tutorials/00_sim`` directory. + +.. dropdown:: Code for create_empty.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/00_sim/create_empty.py + :language: python + :emphasize-lines: 18-30,34,40-44,46-47,51-54,60-61 + :linenos: + + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +Launching the simulator +----------------------- + +The first step when working with standalone Python scripts is to launch the simulation application. +This is necessary to do at the start since various dependency modules of Isaac Sim are only available +after the simulation app is running. + +This can be done by importing the :class:`app.AppLauncher` class. This utility class wraps around +:class:`isaacsim.SimulationApp` class to launch the simulator. It provides mechanisms to +configure the simulator using command-line arguments and environment variables. + +For this tutorial, we mainly look at adding the command-line options to a user-defined +:class:`argparse.ArgumentParser`. This is done by passing the parser instance to the +:meth:`app.AppLauncher.add_app_launcher_args` method, which appends different parameters +to it. These include launching the app headless, configuring different Livestream options, +and enabling off-screen rendering. + +.. literalinclude:: ../../../../scripts/tutorials/00_sim/create_empty.py + :language: python + :start-at: import argparse + :end-at: simulation_app = app_launcher.app + +Importing python modules +------------------------ + +Once the simulation app is running, it is possible to import different Python modules from +Isaac Sim and other libraries. Here we import the following module: + +* :mod:`isaaclab.sim`: A sub-package in Isaac Lab for all the core simulator-related operations. + +.. literalinclude:: ../../../../scripts/tutorials/00_sim/create_empty.py + :language: python + :start-at: from isaaclab.sim import SimulationCfg, SimulationContext + :end-at: from isaaclab.sim import SimulationCfg, SimulationContext + + +Configuring the simulation context +---------------------------------- + +When launching the simulator from a standalone script, the user has complete control over playing, +pausing and stepping the simulator. All these operations are handled through the **simulation +context**. It takes care of various timeline events and also configures the physics scene for +simulation. + +In Isaac Lab, the :class:`sim.SimulationContext` class wraps Isaac Sim's simulation stack +to allow configuring the simulation +through Python's ``dataclass`` object and handle certain intricacies of the simulation stepping. + +For this tutorial, we set the physics and rendering time step to 0.01 seconds. This is done +by passing these quantities to the :class:`sim.SimulationCfg`, which is then used to create an +instance of the simulation context. + +.. literalinclude:: ../../../../scripts/tutorials/00_sim/create_empty.py + :language: python + :start-at: # Initialize the simulation context + :end-at: sim.set_camera_view([2.5, 2.5, 2.5], [0.0, 0.0, 0.0]) + + +Following the creation of the simulation context, we have only configured the physics acting on the +simulated scene. This includes the device to use for simulation, the gravity vector, and other advanced +solver parameters. There are now two main steps remaining to run the simulation: + +1. Designing the simulation scene: Adding sensors, robots and other simulated objects +2. Running the simulation loop: Stepping the simulator, and setting and getting data from the simulator + +In this tutorial, we look at Step 2 first for an empty scene to focus on the simulation control first. +In the following tutorials, we will look into Step 1 and working with simulation handles for interacting +with the simulator. + +Running the simulation +---------------------- + +The first thing, after setting up the simulation scene, is to call the :meth:`sim.SimulationContext.reset` +method. This method plays the timeline and initializes the physics handles in the simulator. It must always +be called the first time before stepping the simulator. Otherwise, the simulation handles are not initialized +properly. + +.. note:: + + :meth:`sim.SimulationContext.reset` is different from :meth:`sim.SimulationContext.play` method as the latter + only plays the timeline and does not initializes the physics handles. + +After playing the simulation timeline, we set up a simple simulation loop where the simulator is stepped repeatedly +while the simulation app is running. The method :meth:`sim.SimulationContext.step` takes in as argument :attr:`render`, +which dictates whether the step includes updating the rendering-related events or not. By default, this flag is +set to True. + +.. literalinclude:: ../../../../scripts/tutorials/00_sim/create_empty.py + :language: python + :start-at: # Play the simulator + :end-at: sim.step() + +Exiting the simulation +---------------------- + +Lastly, the simulation application is stopped and its window is closed by calling +:meth:`isaacsim.SimulationApp.close` method. + +.. literalinclude:: ../../../../scripts/tutorials/00_sim/create_empty.py + :language: python + :start-at: # close sim app + :end-at: simulation_app.close() + + +The Code Execution +~~~~~~~~~~~~~~~~~~ + +Now that we have gone through the code, let's run the script and see the result: + +.. code-block:: bash + + python scripts/tutorials/00_sim/create_empty.py --viz kit + + +The simulation should be playing, and the stage should be rendering. To stop the simulation, +you can either close the window, or press ``Ctrl+C`` in the terminal. + +.. figure:: ../../_static/tutorials/tutorial_create_empty.jpg + :align: center + :figwidth: 100% + :alt: result of create_empty.py + +Passing ``--help`` to the above script will show the different command-line arguments added +earlier by the :class:`app.AppLauncher` class. To run the script headless, you can execute the +following: + +.. code-block:: bash + + python scripts/tutorials/00_sim/create_empty.py --viz none + + +Now that we have a basic understanding of how to run a simulation, let's move on to the +following tutorial where we will learn how to add assets to the stage. + +.. _`Isaac Sim Workflows`: https://docs.isaacsim.omniverse.nvidia.com/latest/introduction/workflows.html +.. _carb: https://docs.omniverse.nvidia.com/kit/docs/carbonite/latest/index.html diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/00_sim/launch_app.rst b/simulation/modules/IsaacLab/docs/source/tutorials/00_sim/launch_app.rst new file mode 100644 index 0000000000000000000000000000000000000000..9c215b11d9d1423067fa21f9b26b8a656221cc1d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/00_sim/launch_app.rst @@ -0,0 +1,181 @@ +Deep-dive into AppLauncher +========================== + +.. currentmodule:: isaaclab + +In this tutorial, we will dive into the :class:`app.AppLauncher` class to configure the simulator using +CLI arguments and environment variables (envars). Particularly, we will demonstrate how to use +:class:`~app.AppLauncher` to enable livestreaming and configure the :class:`isaacsim.simulation_app.SimulationApp` +instance it wraps, while also allowing user-provided options. + +The :class:`~app.AppLauncher` is a wrapper for :class:`~isaacsim.simulation_app.SimulationApp` to simplify +its configuration. The :class:`~isaacsim.simulation_app.SimulationApp` has many extensions that must be +loaded to enable different capabilities, and some of these extensions are order- and inter-dependent. +Additionally, there are startup options such as ``headless`` which must be set at instantiation time, +and which have an implied relationship with some extensions, e.g. the livestreaming extensions. +The :class:`~app.AppLauncher` presents an interface that can handle these extensions and startup +options in a portable manner across a variety of use cases. To achieve this, we offer CLI and envar +flags which can be merged with user-defined CLI args, while passing forward arguments intended +for :class:`~isaacsim.simulation_app.SimulationApp`. + + +The Code +-------- + +The tutorial corresponds to the ``launch_app.py`` script in the +``scripts/tutorials/00_sim`` directory. + +.. dropdown:: Code for launch_app.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/00_sim/launch_app.py + :language: python + :emphasize-lines: 18-40 + :linenos: + +The Code Explained +------------------ + +Adding arguments to the argparser +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:class:`~app.AppLauncher` is designed to be compatible with custom CLI args that users need for +their own scripts, while still providing a portable CLI interface. + +In this tutorial, a standard :class:`argparse.ArgumentParser` is instantiated and given the +script-specific ``--size`` argument, as well as the arguments ``--height`` and ``--width``. +The latter are ingested by :class:`~isaacsim.simulation_app.SimulationApp`. + +The argument ``--size`` is not used by :class:`~app.AppLauncher`, but will merge seamlessly +with the :class:`~app.AppLauncher` interface. In-script arguments can be merged with the +:class:`~app.AppLauncher` interface via the :meth:`~app.AppLauncher.add_app_launcher_args` method, +which will return a modified :class:`~argparse.ArgumentParser` with the :class:`~app.AppLauncher` +arguments appended. This can then be processed into an :class:`argparse.Namespace` using the +standard :meth:`argparse.ArgumentParser.parse_args` method and passed directly to +:class:`~app.AppLauncher` for instantiation. + +.. literalinclude:: ../../../../scripts/tutorials/00_sim/launch_app.py + :language: python + :start-at: import argparse + :end-at: simulation_app = app_launcher.app + +The above illustrates one of several ways of passing arguments to :class:`~app.AppLauncher`. +Please consult its documentation page to see further options. + +Understanding the output of --help +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +While executing the script, we can pass the ``--help`` argument and see the combined outputs of the +custom arguments and those from :class:`~app.AppLauncher`. + +.. code-block:: console + + ./isaaclab.sh -p scripts/tutorials/00_sim/launch_app.py --help + + [INFO] Using python from: /isaac-sim/python.sh + [INFO][AppLauncher]: The argument 'width' will be used to configure the SimulationApp. + [INFO][AppLauncher]: The argument 'height' will be used to configure the SimulationApp. + usage: launch_app.py [-h] [--size SIZE] [--width WIDTH] [--height HEIGHT] [--livestream {0,1,2}] + [--enable_cameras] [--visualizer VISUALIZER] [--verbose] [--experience EXPERIENCE] + + Tutorial on running IsaacSim via the AppLauncher. + + options: + -h, --help show this help message and exit + --size SIZE Side-length of cuboid + --width WIDTH Width of the viewport and generated images. Defaults to 1280 + --height HEIGHT Height of the viewport and generated images. Defaults to 720 + + app_launcher arguments: + [DEPRECATED] Disable visualizers and force headless mode (display off). + --livestream {0,1,2} + Force enable livestreaming. Mapping corresponds to that for the "LIVESTREAM" environment variable. + --enable_cameras Enable cameras when running without a GUI. + --visualizer VISUALIZER, --viz VISUALIZER + Visualizer backends as CSV (e.g., kit,newton,rerun,viser) or none. + --verbose Enable verbose terminal logging from the SimulationApp. + --experience EXPERIENCE + The experience file to load when launching the SimulationApp. + + * If an empty string is provided, the experience file is determined based on the headless flag. + * If a relative path is provided, it is resolved relative to the `apps` folder in Isaac Sim and + Isaac Lab (in that order). + +This readout details the ``--size``, ``--height``, and ``--width`` arguments defined in the script directly, +as well as the :class:`~app.AppLauncher` arguments. + +The ``[INFO]`` messages preceding the help output also reads out which of these arguments are going +to be interpreted as arguments to the :class:`~isaacsim.simulation_app.SimulationApp` instance which the +:class:`~app.AppLauncher` class wraps. In this case, it is ``--height`` and ``--width``. These +are classified as such because they match the name and type of an argument which can be processed +by :class:`~isaacsim.simulation_app.SimulationApp`. Please refer to the `specification`_ for such arguments +for more examples. + +Using environment variables +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +As noted in the help message, the :class:`~app.AppLauncher` arguments (for example ``--livestream``) +have corresponding environment variables (envar) as well. These are detailed in :mod:`isaaclab.app` +documentation. Providing any of these arguments through CLI is equivalent to running the script in a shell +environment where the corresponding envar is set. + +The support for :class:`~app.AppLauncher` envars are simply a convenience to provide session-persistent +configurations, and can be set in the user's ``${HOME}/.bashrc`` for persistent settings between sessions. +In the case where these arguments are provided from the CLI, they will override their corresponding envar, +as we will demonstrate later in this tutorial. + +These arguments can be used with any script that starts the simulation using :class:`~app.AppLauncher`, +with one exception, ``--enable_cameras``. This setting sets the rendering pipeline to use the +offscreen renderer. However, this setting is only compatible with the :class:`isaaclab.sim.SimulationContext`. +It will not work with Isaac Sim's legacy ``SimulationContext`` from deprecated Isaac Sim core extensions. +For more information on this flag, please see the :class:`~app.AppLauncher` API documentation. + + +The Code Execution +------------------ + +We will now run the example script: + +.. code-block:: console + + LIVESTREAM=2 ./isaaclab.sh -p scripts/tutorials/00_sim/launch_app.py --size 0.5 + +This will spawn a 0.5m\ :sup:`3` volume cuboid in the simulation. No GUI will appear, equivalent +to omitting ``--visualizer`` in this setup because headlessness is implied by our ``LIVESTREAM`` +envar. If a visualization is desired, we could get one via Isaac's `WebRTC Livestreaming`_. Streaming +is currently the only supported method of visualization from within the container. The +process can be killed by pressing ``Ctrl+C`` in the launching terminal. + +.. figure:: ../../_static/tutorials/tutorial_launch_app.jpg + :align: center + :figwidth: 100% + :alt: result of launch_app.py + +Now, let's look at how :class:`~app.AppLauncher` handles conflicting commands: + +.. code-block:: console + + LIVESTREAM=0 ./isaaclab.sh -p scripts/tutorials/00_sim/launch_app.py --size 0.5 --livestream 2 + +This will cause the same behavior as in the previous run, because although we have set ``LIVESTREAM=0`` +in our envars, CLI args such as ``--livestream`` take precedence in determining behavior. The process can +be killed by pressing ``Ctrl+C`` in the launching terminal. + +Finally, we will examine passing arguments to :class:`~isaacsim.simulation_app.SimulationApp` through +:class:`~app.AppLauncher`: + +.. code-block:: console + + LIVESTREAM=2 ./isaaclab.sh -p scripts/tutorials/00_sim/launch_app.py --size 0.5 --width 1920 --height 1080 + +This will cause the same behavior as before, but now the viewport will be rendered at 1920x1080p resolution. +This can be useful when we want to gather high-resolution video, or we can specify a lower resolution if we +want our simulation to be more performant. The process can be killed by pressing ``Ctrl+C`` in the launching +terminal. + +For more details on headless mode and launching visualizers, see +:doc:`/source/migration/migrating_to_isaaclab_3-0`. + + +.. _specification: https://docs.isaacsim.omniverse.nvidia.com/latest/py/source/extensions/isaacsim.simulation_app/docs/api.html#isaacsim.simulation_app.SimulationApp.DEFAULT_LAUNCHER_CONFIG +.. _WebRTC Livestreaming: https://docs.isaacsim.omniverse.nvidia.com/latest/installation/manual_livestream_clients.html#isaac-sim-short-webrtc-streaming-client diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/00_sim/spawn_prims.rst b/simulation/modules/IsaacLab/docs/source/tutorials/00_sim/spawn_prims.rst new file mode 100644 index 0000000000000000000000000000000000000000..86672091b2f74ce0fd7472016ae0646c83f2f414 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/00_sim/spawn_prims.rst @@ -0,0 +1,193 @@ +.. _tutorial-spawn-prims: + + +Spawning prims into the scene +============================= + +.. currentmodule:: isaaclab + +This tutorial explores how to spawn various objects (or prims) into the scene in Isaac Lab from Python. +It builds on the previous tutorial on running the simulator from a standalone script and +demonstrates how to spawn a ground plane, lights, primitive shapes, and meshes from USD files. + + +The Code +~~~~~~~~ + +The tutorial corresponds to the ``spawn_prims.py`` script in the ``scripts/tutorials/00_sim`` directory. +Let's take a look at the Python script: + +.. dropdown:: Code for spawn_prims.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/00_sim/spawn_prims.py + :language: python + :emphasize-lines: 40-88, 100-101 + :linenos: + + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +Scene designing in Omniverse is built around a software system and file format called USD (Universal Scene Description). +It allows describing 3D scenes in a hierarchical manner, similar to a file system. Since USD is a comprehensive framework, +we recommend reading the `USD documentation`_ to learn more about it. + +For completeness, we introduce the must know concepts of USD in this tutorial. + +* **Primitives (Prims)**: These are the basic building blocks of a USD scene. They can be thought of as nodes in a scene + graph. Each node can be a mesh, a light, a camera, or a transform. It can also be a group of other prims under it. +* **Attributes**: These are the properties of a prim. They can be thought of as key-value pairs. For example, a prim can + have an attribute called ``color`` with a value of ``red``. +* **Relationships**: These are the connections between prims. They can be thought of as pointers to other prims. For + example, a mesh prim can have a relationship to a material prim for shading. + +A collection of these prims, with their attributes and relationships, is called a **USD stage**. It can be thought of +as a container for all prims in a scene. When we say we are designing a scene, we are actually designing a USD stage. + +While working with direct USD APIs provides a lot of flexibility, it can be cumbersome to learn and use. To make it +easier to design scenes, Isaac Lab builds on top of the USD APIs to provide a configuration-driven interface to spawn prims +into a scene. These are included in the :mod:`sim.spawners` module. + +When spawning prims into the scene, each prim requires a configuration class instance that defines the prim's attributes +and relationships (through material and shading information). The configuration class is then passed to its respective +function where the prim name and transformation are specified. The function then spawns the prim into the scene. + +At a high-level, this is how it works: + +.. code-block:: python + + # Create a configuration class instance + cfg = MyPrimCfg() + prim_path = "/path/to/prim" + + # Spawn the prim into the scene using the corresponding spawner function + spawn_my_prim(prim_path, cfg, translation=[0, 0, 0], orientation=[1, 0, 0, 0], scale=[1, 1, 1]) + # OR + # Use the spawner function directly from the configuration class + cfg.func(prim_path, cfg, translation=[0, 0, 0], orientation=[1, 0, 0, 0], scale=[1, 1, 1]) + + +In this tutorial, we demonstrate the spawning of various different prims into the scene. For more +information on the available spawners, please refer to the :mod:`sim.spawners` module in Isaac Lab. + +.. attention:: + + All the scene designing must happen before the simulation starts. Once the simulation starts, we recommend keeping + the scene frozen and only altering the properties of the prim. This is particularly important for GPU simulation + as adding new prims during simulation may alter the physics simulation buffers on GPU and lead to unexpected + behaviors. + + +Spawning a ground plane +----------------------- + +The :class:`~sim.spawners.from_files.GroundPlaneCfg` configures a grid-like ground plane with +modifiable properties such as its appearance and size. + +.. literalinclude:: ../../../../scripts/tutorials/00_sim/spawn_prims.py + :language: python + :start-at: # Ground-plane + :end-at: cfg_ground.func("/World/defaultGroundPlane", cfg_ground) + + +Spawning lights +--------------- + +It is possible to spawn `different light prims`_ into the stage. These include distant lights, sphere lights, disk +lights, and cylinder lights. In this tutorial, we spawn a distant light which is a light that is infinitely far away +from the scene and shines in a single direction. + +.. literalinclude:: ../../../../scripts/tutorials/00_sim/spawn_prims.py + :language: python + :start-at: # spawn distant light + :end-at: cfg_light_distant.func("/World/lightDistant", cfg_light_distant, translation=(1, 0, 10)) + + +Spawning primitive shapes +------------------------- + +Before spawning primitive shapes, we introduce the concept of a transform prim or Xform. A transform prim is a prim that +contains only transformation properties. It is used to group other prims under it and to transform them as a group. +Here we make an Xform prim to group all the primitive shapes under it. + +.. literalinclude:: ../../../../scripts/tutorials/00_sim/spawn_prims.py + :language: python + :start-at: # create a new xform prim for all objects to be spawned under + :end-at: sim_utils.create_prim("/World/Objects", "Xform") + +Next, we spawn a cone using the :class:`~sim.spawners.shapes.ConeCfg` class. It is possible to specify +the radius, height, physics properties, and material properties of the cone. By default, the physics and material +properties are disabled. + +The first two cones we spawn ``Cone1`` and ``Cone2`` are visual elements and do not have physics enabled. + +.. literalinclude:: ../../../../scripts/tutorials/00_sim/spawn_prims.py + :language: python + :start-at: # spawn a red cone + :end-at: cfg_cone.func("/World/Objects/Cone2", cfg_cone, translation=(-1.0, -1.0, 1.0)) + +For the third cone ``ConeRigid``, we add rigid body physics to it by setting the attributes for that in the configuration +class. Through these attributes, we can specify the mass, friction, and restitution of the cone. If unspecified, they +default to the default values set by USD Physics. + +.. literalinclude:: ../../../../scripts/tutorials/00_sim/spawn_prims.py + :language: python + :start-at: # spawn a green cone with colliders and rigid body + :end-before: # spawn a blue cuboid with deformable body + +Lastly, we spawn a cuboid ``CuboidDeformable`` which contains deformable body physics properties. Unlike the +rigid body simulation, a deformable body can have relative motion between its vertices. This is useful for simulating +soft bodies like cloth, rubber, or jello. It is important to note that deformable bodies are only supported in +GPU simulation and require a mesh object to be spawned with deformable body physics properties and a deformable +physics material. This example uses the PhysX-specific deformable property and material cfgs. + +.. literalinclude:: ../../../../scripts/tutorials/00_sim/spawn_prims.py + :language: python + :start-at: # spawn a blue cuboid with deformable body + :end-before: # spawn a usd file of a table into the scene + +Spawning from another file +-------------------------- + +Lastly, it is possible to spawn prims from other file formats such as other USD, URDF, or OBJ files. In this tutorial, +we spawn a USD file of a table into the scene. The table is a mesh prim and has a material prim associated with it. +All of this information is stored in its USD file. + +.. literalinclude:: ../../../../scripts/tutorials/00_sim/spawn_prims.py + :language: python + :start-at: # spawn a usd file of a table into the scene + :end-at: cfg.func("/World/Objects/Table", cfg, translation=(0.0, 0.0, 1.05)) + +The table above is added as a reference to the scene. In layman terms, this means that the table is not actually added +to the scene, but a ``pointer`` to the table asset is added. This allows us to modify the table asset and have the changes +reflected in the scene in a non-destructive manner. For example, we can change the material of the table without +actually modifying the underlying file for the table asset directly. Only the changes are stored in the USD stage. + + +Executing the Script +~~~~~~~~~~~~~~~~~~~~ + +Similar to the tutorial before, to run the script, execute the following command: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tutorials/00_sim/spawn_prims.py + +Once the simulation starts, you should see a window with a ground plane, a light, some cones, and a table. +The green cone, which has rigid body physics enabled, should fall and collide with the table and the ground +plane. The other cones are visual elements and should not move. To stop the simulation, you can close the window, +or press ``Ctrl+C`` in the terminal. + +.. figure:: ../../_static/tutorials/tutorial_spawn_prims.jpg + :align: center + :figwidth: 100% + :alt: result of spawn_prims.py + +This tutorial provided a foundation for spawning various prims into the scene in Isaac Lab. Although simple, it +demonstrates the basic concepts of scene designing in Isaac Lab and how to use the spawners. In the coming tutorials, +we will now look at how to interact with the scene and the simulation. + + +.. _`USD documentation`: https://openusd.org/release/index.html +.. _`different light prims`: https://youtu.be/c7qyI8pZvF4?feature=shared diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/add_new_robot.rst b/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/add_new_robot.rst new file mode 100644 index 0000000000000000000000000000000000000000..a4d258f82c15a7dbc89ec9a99ad3ce0ea95586bc --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/add_new_robot.rst @@ -0,0 +1,113 @@ +.. _tutorial-add-new-robot: + +Adding a New Robot to Isaac Lab +=============================== + +.. currentmodule:: isaaclab + +Simulating and training a new robot is a multi-step process that starts with importing the robot into Isaac Sim. +This is covered in depth in the Isaac Sim documentation `here `_. +Once the robot is imported and tuned for simulation, we must define those interfaces necessary to clone the robot across multiple environments, drive its joints, +and properly reset it, regardless of the chosen workflow or training framework. + +In this tutorial, we will examine how to add a new robot to Isaac Lab. The key step is creating an ``AssetBaseCfg`` that defines +the interface between the USD articulation of the robot and the learning algorithms available through Isaac Lab. + +The Code +~~~~~~~~ + +The tutorial corresponds to the ``add_new_robot`` script in the ``scripts/tutorials/01_assets`` directory. + +.. dropdown:: Code for add_new_robot.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/01_assets/add_new_robot.py + :language: python + :linenos: + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +Fundamentally, a robot is an articulation with joint drives. To move a robot around in the simulation, we must apply +targets to its drives and step the sim forward in time. However, to control a robot strictly through joint drives is tedious, especially if +you want to control anything complex, and doubly so if you want to clone the robot across multiple environments. + +To facilitate this, Isaac Lab provides a collection of ``configuration`` classes that define which parts of the USD need +to be cloned, which parts are actuators to be controlled by an agent, how it should be reset, etc... There are many ways +you can configure a single robot asset for Isaac Lab depending on how much fine tuning the asset requires. To demonstrate, +the tutorial script imports two robots: The first robot, the ``Jetbot``, is configured minimally while the second robot, the ``Dofbot``, is configured with additional parameters. + +The Jetbot is a simple, two wheeled differential base with a camera on top. The asset is used for a number of demonstrations and +tutorials in Isaac Sim, so we know it's good to go! To bring it into Isaac lab, we must first define one of these configurations. +Because a robot is an articulation with joint drives, we define an ``ArticulationCfg`` that describes the robot. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/add_new_robot.py + :language: python + :lines: 27-38 + +This is the minimal configuration for a robot in Isaac Lab. There are only two required parameters: ``spawn`` and ``actuators``. + +The ``spawn`` parameter is looking for a ``SpawnerCfg``, and is used to specify the USD asset that defines the robot in the sim. +The Isaac Lab simulation utilities, ``isaaclab.sim``, provides us with a ``USDFileCfg`` class that consumes a path to our USD +asset, and generates the ``SpawnerCfg`` we need. In this case, the ``jetbot.usd`` is located +with the `Isaac Assets `_ under ``Robots/Jetbot/jetbot.usd``. + +The ``actuators`` parameter is a dictionary of Actuator Configs and defines what parts of the robot we intend to control with an agent. +There are many different ways to update the state of a joint in time towards some target. Isaac Lab provides a collection of actuator +classes that can be used to match common actuator models or even implement your own! In this case, we are using the ``ImplicitActuatorCfg`` class to specify +the actuators for the robot, because they are simple wheels and the defaults are fine. + +Specifying joint name keys for this dictionary can be done to varying levels of specificity. +The jetbot only has a few joints, and we are just going to use the defaults specified in the USD asset, so we can use a simple regex, ``.*`` to specify all joints. +Other regex can also be used to group joints and associated configurations. + +.. note:: + + Both stiffness and damping must be specified in the implicit actuator, but a value of ``None`` will use the defaults defined in the USD asset. + +While this is the minimal configuration, there are a number of other parameters we could specify + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/add_new_robot.py + :language: python + :lines: 39-82 + +This configuration can be used to add a Dofbot to the scene, and it contains some of those parameters. +The Dofbot is a hobbiest robot arm with several joints, and so we have more options available for configuration. +The two most notable differences though is the addition of configurations for physics properties, and the initial state of the robot, ``init_state``. + +The ``USDFileCfg`` has special parameters for rigid bodies and robots, among others. The ``rigid_props`` parameter expects +a ``RigidBodyPropertiesCfg`` that allows you to specify body link properties of the robot being spawned relating to its behavior +as a "physical object" in the simulation. The ``articulation_props`` meanwhile governs the properties relating to the solver +being used to step the joints through time, and so it expects an ``ArticulationRootPropertiesCfg`` to be configured. +There are many other physics properties and parameters that can be specified through configurations provided by :class:`isaaclab.sim.schemas`. + +The ``ArticulationCfg`` can optionally include the ``init_state`` parameter, that defines the initial state of the articulation. +The initial state of an articulation is a special, user defined state that is used when the robot is spawned or reset by Isaac Lab. +The initial joint state, ``joint_pos``, is specified by a dictionary of floats with the USD joint names as keys (**not** the actuator names). +Something else worth noting here is the coordinate system of the initial position, ``pos``, which is that of the environment. +In this case, by specifying a position of ``(0.25, -0.25, 0.0)`` we are offsetting the spawn position of the robot **from the origin of the environment**, and not the world. + +Armed with the configurations for these robots, we can now add them to the scene and interact with them in the usual way +for the direct workflow: by defining an ``InteractiveSceneCfg`` containing the articulation configs for the robots ... + + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/add_new_robot.py + :language: python + :lines: 85 - 99 + + +...and then stepping the simulation while updating the scene entities appropriately. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/add_new_robot.py + :language: python + :lines: 101 - 158 + + +.. note:: + + You may see a warning that not all actuators are configured! This is expected because we don't handle the gripper for this tutorial. + +.. figure:: ../../_static/tutorials/tutorial_add_new_robot_result.jpg + :align: center + :figwidth: 100% + :alt: The new robots say hi! diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/run_articulation.rst b/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/run_articulation.rst new file mode 100644 index 0000000000000000000000000000000000000000..6adf96d98d260ca1dcd543cdba0f6ae0d499a4da --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/run_articulation.rst @@ -0,0 +1,146 @@ +.. _tutorial-interact-articulation: + +Interacting with an articulation +================================ + +.. currentmodule:: isaaclab + + +This tutorial shows how to interact with an articulated robot in the simulation. It is a continuation of the +:ref:`tutorial-interact-rigid-object` tutorial, where we learned how to interact with a rigid object. +On top of setting the root state, we will see how to set the joint state and apply commands to the articulated +robot. + + +The Code +~~~~~~~~ + +The tutorial corresponds to the ``run_articulation.py`` script in the ``scripts/tutorials/01_assets`` +directory. + +.. dropdown:: Code for run_articulation.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/01_assets/run_articulation.py + :language: python + :emphasize-lines: 58-69, 91-104, 108-111, 116-117 + :linenos: + + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +Designing the scene +------------------- + +Similar to the previous tutorial, we populate the scene with a ground plane and a distant light. Instead of +spawning rigid objects, we now spawn a cart-pole articulation from its USD file. The cart-pole is a simple robot +consisting of a cart and a pole attached to it. The cart is free to move along the x-axis, and the pole is free to +rotate about the cart. The USD file for the cart-pole contains the robot's geometry, joints, and other physical +properties. + +For the cart-pole, we use its pre-defined configuration object, which is an instance of the +:class:`assets.ArticulationCfg` class. This class contains information about the articulation's spawning strategy, +default initial state, actuator models for different joints, and other meta-information. A deeper-dive into how to +create this configuration object is provided in the :ref:`how-to-write-articulation-config` tutorial. + +As seen in the previous tutorial, we can spawn the articulation into the scene in a similar fashion by creating +an instance of the :class:`assets.Articulation` class by passing the configuration object to its constructor. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_articulation.py + :language: python + :start-at: # Create separate groups called "Origin1", "Origin2" + :end-at: cartpole = Articulation(cfg=cartpole_cfg) + + +Running the simulation loop +--------------------------- + +Continuing from the previous tutorial, we reset the simulation at regular intervals, set commands to the articulation, +step the simulation, and update the articulation's internal buffers. + +Resetting the simulation +"""""""""""""""""""""""" + +Similar to a rigid object, an articulation also has a root state. This state corresponds to the root body in the +articulation tree. On top of the root state, an articulation also has joint states. These states correspond to the +joint positions and velocities. + +To reset the articulation, we first set the root state by calling the :meth:`Articulation.write_root_pose_to_sim` and :meth:`Articulation.write_root_velocity_to_sim` +methods. Similarly, we set the joint states by calling the :meth:`Articulation.write_joint_state_to_sim` method. +Finally, we call the :meth:`Articulation.reset` method to reset any internal buffers and caches. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_articulation.py + :language: python + :start-at: # reset the scene entities + :end-at: robot.reset() + +Stepping the simulation +""""""""""""""""""""""" + +Applying commands to the articulation involves two steps: + +1. *Setting the joint targets*: This sets the desired joint position, velocity, or effort targets for the articulation. +2. *Writing the data to the simulation*: Based on the articulation's configuration, this step handles any + :ref:`actuation conversions ` and writes the converted values to the PhysX buffer. + +In this tutorial, we control the articulation using joint effort commands. For this to work, we need to set the +articulation's stiffness and damping parameters to zero. This is done a-priori inside the cart-pole's pre-defined +configuration object. + +At every step, we randomly sample joint efforts and set them to the articulation by calling the +:meth:`Articulation.set_joint_effort_target` method. After setting the targets, we call the +:meth:`Articulation.write_data_to_sim` method to write the data to the PhysX buffer. Finally, we step +the simulation. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_articulation.py + :language: python + :start-at: # Apply random action + :end-at: robot.write_data_to_sim() + + +Updating the state +"""""""""""""""""" + +Every articulation class contains a :class:`assets.ArticulationData` object. This stores the state of the +articulation. To update the state inside the buffer, we call the :meth:`assets.Articulation.update` method. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_articulation.py + :language: python + :start-at: # Update buffers + :end-at: robot.update(sim_dt) + + +The Code Execution +~~~~~~~~~~~~~~~~~~ + + +To run the code and see the results, let's run the script from the terminal: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tutorials/01_assets/run_articulation.py + + +This command should open a stage with a ground plane, lights, and two cart-poles that are moving around randomly. +To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal. + +.. figure:: ../../_static/tutorials/tutorial_run_articulation.jpg + :align: center + :figwidth: 100% + :alt: result of run_articulation.py + +In this tutorial, we learned how to create and interact with a simple articulation. We saw how to set the state +of an articulation (its root and joint state) and how to apply commands to it. We also saw how to update its +buffers to read the latest state from the simulation. + +In addition to this tutorial, we also provide a few other scripts that spawn different robots. These are included +in the ``scripts/demos`` directory. You can run these scripts as: + +.. code-block:: bash + + # Spawn many different single-arm manipulators + ./isaaclab.sh -p scripts/demos/arms.py + + # Spawn many different quadrupeds + ./isaaclab.sh -p scripts/demos/quadrupeds.py diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/run_deformable_object.rst b/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/run_deformable_object.rst new file mode 100644 index 0000000000000000000000000000000000000000..bb2607a209491144d74ceab31baaac49ae32585c --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/run_deformable_object.rst @@ -0,0 +1,193 @@ +.. _tutorial-interact-deformable-object: + + +Interacting with a deformable object +==================================== + +.. currentmodule:: isaaclab + +While deformable objects sometimes refer to a broader class of objects, such as cloths, fluids and soft bodies, +Isaac Lab represents deformable objects as either surface or volume deformables. Unlike rigid objects, soft bodies can +deform under external forces and collisions. In this tutorial, we focus on volume deformable bodies. For an example of +surface deformables (cloth), see the deformable demo at ``scripts/demos/deformables.py``. + +The deformable object API and schema define/modify functions are shared across backends, while deformable +property and material configuration classes are backend-specific. PhysX simulates soft bodies using the Finite +Element Method (FEM); the Newton experimental backend uses VBD-based deformable support from +:mod:`isaaclab_contrib.deformable`. +The volume deformable comprises of two tetrahedral meshes -- a simulation mesh and a collision mesh. The simulation +mesh is used to simulate the deformations of the soft body, while the collision mesh is used to detect collisions +with other objects in the scene. For PhysX-specific details, please check the `PhysX documentation`_. + +This tutorial shows how to interact with a deformable object in the simulation. We will spawn a +set of soft cubes and see how to set their nodal positions and velocities, along with apply kinematic +commands to the mesh nodes to move the soft body. + + +The Code +~~~~~~~~ + +The tutorial corresponds to the ``run_deformable_object.py`` script in the ``scripts/tutorials/01_assets`` directory. + +.. dropdown:: Code for run_deformable_object.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/01_assets/run_deformable_object.py + :language: python + :emphasize-lines: 65-98, 119-124, 126-135, 140-148, 150-158 + :linenos: + + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +Designing the scene +------------------- + +Similar to the :ref:`tutorial-interact-rigid-object` tutorial, we populate the scene with a ground plane +and a light source. In addition, we add a deformable object to the scene using the :class:`assets.DeformableObject` +class. This class is responsible for spawning the prims at the input path and initializes their corresponding +deformable body physics handles. + +In this tutorial, we create a cubical soft object using the spawn configuration similar to the deformable cube +in the :ref:`Spawn Objects ` tutorial. The only difference is that now we wrap +the spawning configuration into the :class:`assets.DeformableObjectCfg` class. This class contains information about +the asset's spawning strategy and default initial state. When this class is passed to +the :class:`assets.DeformableObject` class, it spawns the object and initializes the corresponding physics handles +when the simulation is played. + +.. note:: + Deformable objects require a mesh object to be spawned with backend-specific deformable body physics + properties and a matching deformable physics material. + Use ``--backend physx`` for the PhysX implementation or ``--backend newton`` for the experimental Newton + implementation. + + +As seen in the rigid body tutorial, we can spawn the deformable object into the scene in a similar fashion by creating +an instance of the :class:`assets.DeformableObject` class by passing the configuration object to its constructor. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_deformable_object.py + :language: python + :start-at: # Create separate groups called "env_0", "env_1", ... + :end-at: cube_object = DeformableObject(cfg=cfg) + +Running the simulation loop +--------------------------- + +Continuing from the rigid body tutorial, we reset the simulation at regular intervals, apply kinematic commands +to the deformable body, step the simulation, and update the deformable object's internal buffers. + +Resetting the simulation state +"""""""""""""""""""""""""""""" + +Unlike rigid bodies and articulations, deformable objects have a different state representation. The state of a +deformable object is defined by the nodal positions and velocities of the mesh. The nodal positions and velocities +are defined in the **simulation world frame** and are stored in the :attr:`assets.DeformableObject.data` attribute. + +We use the :attr:`assets.DeformableObject.data.default_nodal_state_w` attribute to get the default nodal state of the +spawned object prims. This default state can be configured from the :attr:`assets.DeformableObjectCfg.init_state` +attribute, which we left as identity in this tutorial. + +.. attention:: + The initial state in the configuration :attr:`assets.DeformableObjectCfg` specifies the pose + of the deformable object at the time of spawning. Based on this initial state, the default nodal state is + obtained when the simulation is played for the first time. + +We apply transformations to the nodal positions to randomize the initial state of the deformable object. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_deformable_object.py + :language: python + :start-at: # reset the nodal state of the object + :end-at: nodal_state[..., :3] = cube_object.transform_nodal_pos(nodal_state[..., :3], pos_w, quat_w) + +To reset the deformable object, we first set the nodal state by calling the :meth:`assets.DeformableObject.write_nodal_state_to_sim` +method. This method writes the nodal state of the deformable object prim into the simulation buffer. +Additionally, we free all the kinematic targets set for the nodes in the previous simulation step by calling +the :meth:`assets.DeformableObject.write_nodal_kinematic_target_to_sim` method. We explain the +kinematic targets in the next section. + +Finally, we call the :meth:`assets.DeformableObject.reset` method to reset any internal buffers and caches. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_deformable_object.py + :language: python + :start-at: # write nodal state to simulation + :end-at: cube_object.reset() + +Stepping the simulation +""""""""""""""""""""""" + +Deformable bodies support user-driven kinematic control where a user can specify position targets for some of +the mesh nodes while the rest of the nodes are simulated by the active deformable solver. This `partial kinematic`_ +control is useful for applications where the user wants to interact with the deformable object in a controlled manner. + +In this tutorial, we apply kinematic commands to two out of the four cubes in the scene. We set the position +targets for the node at index 0 (bottom-left corner) to move the cube along the z-axis. + +At every step, we increment the kinematic position target for the node by a small value. Additionally, +we set the flag to indicate that the target is a kinematic target for that node in the simulation buffer. +These are set into the simulation buffer by calling the :meth:`assets.DeformableObject.write_nodal_kinematic_target_to_sim` +method. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_deformable_object.py + :language: python + :start-at: # update the kinematic target for cubes at index 0 and 3 + :end-at: cube_object.write_nodal_kinematic_target_to_sim_index(nodal_kinematic_target) + +Similar to the rigid object and articulation, we perform the :meth:`assets.DeformableObject.write_data_to_sim` method +before stepping the simulation. For deformable objects, this method does not apply any external forces to the object. +However, we keep this method for completeness and future extensions. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_deformable_object.py + :language: python + :start-at: # write internal data to simulation + :end-at: cube_object.write_data_to_sim() + +Updating the state +"""""""""""""""""" + +After stepping the simulation, we update the internal buffers of the deformable object prims to reflect their new state +inside the :class:`assets.DeformableObject.data` attribute. This is done using the :meth:`assets.DeformableObject.update` method. + +At a fixed interval, we print the root position of the deformable object to the terminal. As mentioned +earlier, there is no concept of a root state for deformable objects. However, we compute the root position as +the average position of all the nodes in the mesh. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_deformable_object.py + :language: python + :start-at: # update buffers + :end-at: cube_object.data.root_pos_w + + +The Code Execution +~~~~~~~~~~~~~~~~~~ + +Now that we have gone through the code, let's run the script and see the result: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tutorials/01_assets/run_deformable_object.py --visualizer kit + +To run the same tutorial with the experimental Newton deformable backend: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tutorials/01_assets/run_deformable_object.py --backend newton --visualizer kit + + +This should open a stage with a ground plane, lights, and several cubes. Two of the four cubes must be dropping +from a height and settling on to the ground. Meanwhile the other two cubes must be moving along the z-axis. You +should see a marker showing the kinematic target position for the nodes at the bottom-left corner of the cubes. +To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal + +.. figure:: ../../_static/tutorials/tutorial_run_deformable_object.jpg + :align: center + :figwidth: 100% + :alt: result of run_deformable_object.py + +This tutorial showed how to spawn deformable objects and wrap them in a :class:`DeformableObject` class to initialize their +physics handles which allows setting and obtaining their state. We also saw how to apply kinematic commands to the +deformable object to move the mesh nodes in a controlled manner. An advanced demo of deformable objects, including surface deformables and loading USD assets and applying deformable material on them, can be found in ``scripts/demos/deformables.py``. In the next tutorial, we will see how to create +a scene using the :class:`InteractiveScene` class. + +.. _PhysX documentation: https://nvidia-omniverse.github.io/PhysX/physx/5.4.1/docs/SoftBodies.html +.. _partial kinematic: https://nvidia-omniverse.github.io/PhysX/physx/5.4.1/docs/SoftBodies.html#kinematic-soft-bodies diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/run_rigid_object.rst b/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/run_rigid_object.rst new file mode 100644 index 0000000000000000000000000000000000000000..80232c76e7d5961f5fb0ce84a49d4d62b143ed1d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/run_rigid_object.rst @@ -0,0 +1,153 @@ +.. _tutorial-interact-rigid-object: + + +Interacting with a rigid object +=============================== + +.. currentmodule:: isaaclab + +In the previous tutorials, we learned the essential workings of the standalone script and how to +spawn different objects (or *prims*) into the simulation. This tutorial shows how to create and interact +with a rigid object. For this, we will use the :class:`assets.RigidObject` class provided in Isaac Lab. + +The Code +~~~~~~~~ + +The tutorial corresponds to the ``run_rigid_object.py`` script in the ``scripts/tutorials/01_assets`` directory. + +.. dropdown:: Code for run_rigid_object.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/01_assets/run_rigid_object.py + :language: python + :emphasize-lines: 55-74, 76-78, 98-108, 111-112, 118-119, 132-134, 139-140 + :linenos: + + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +In this script, we split the ``main`` function into two separate functions, which highlight the two main +steps of setting up any simulation in the simulator: + +1. **Design scene**: As the name suggests, this part is responsible for adding all the prims to the scene. +2. **Run simulation**: This part is responsible for stepping the simulator, interacting with the prims + in the scene, e.g., changing their poses, and applying any commands to them. + +A distinction between these two steps is necessary because the second step only happens after the first step +is complete and the simulator is reset. Once the simulator is reset (which automatically plays the simulation), +no new (physics-enabled) prims should be added to the scene as it may lead to unexpected behaviors. However, +the prims can be interacted with through their respective handles. + + +Designing the scene +------------------- + +Similar to the previous tutorial, we populate the scene with a ground plane and a light source. In addition, +we add a rigid object to the scene using the :class:`assets.RigidObject` class. This class is responsible for +spawning the prims at the input path and initializes their corresponding rigid body physics handles. + +In this tutorial, we create a conical rigid object using the spawn configuration similar to the rigid cone +in the :ref:`Spawn Objects ` tutorial. The only difference is that now we wrap +the spawning configuration into the :class:`assets.RigidObjectCfg` class. This class contains information about +the asset's spawning strategy, default initial state, and other meta-information. When this class is passed to +the :class:`assets.RigidObject` class, it spawns the object and initializes the corresponding physics handles +when the simulation is played. + +As an example on spawning the rigid object prim multiple times, we create its parent Xform prims, +``/World/Origin{i}``, that correspond to different spawn locations. When the regex expression +``/World/Origin.*/Cone`` is passed to the :class:`assets.RigidObject` class, it spawns the rigid object prim at +each of the ``/World/Origin{i}`` locations. For instance, if ``/World/Origin1`` and ``/World/Origin2`` are +present in the scene, the rigid object prims are spawned at the locations ``/World/Origin1/Cone`` and +``/World/Origin2/Cone`` respectively. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_rigid_object.py + :language: python + :start-at: # Create separate groups called "Origin1", "Origin2", "Origin3" + :end-at: cone_object = RigidObject(cfg=cone_cfg) + +Since we want to interact with the rigid object, we pass this entity back to the main function. This entity +is then used to interact with the rigid object in the simulation loop. In later tutorials, we will see a more +convenient way to handle multiple scene entities using the :class:`scene.InteractiveScene` class. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_rigid_object.py + :language: python + :start-at: # return the scene information + :end-at: return scene_entities, origins + + +Running the simulation loop +--------------------------- + +We modify the simulation loop to interact with the rigid object to include three steps -- resetting the +simulation state at fixed intervals, stepping the simulation, and updating the internal buffers of the +rigid object. For the convenience of this tutorial, we extract the rigid object's entity from the scene +dictionary and store it in a variable. + +Resetting the simulation state +"""""""""""""""""""""""""""""" + +To reset the simulation state of the spawned rigid object prims, we need to set their pose and velocity. +Together they define the root state of the spawned rigid objects. It is important to note that this state +is defined in the **simulation world frame**, and not of their parent Xform prim. This is because the physics +engine only understands the world frame and not the parent Xform prim's frame. Thus, we need to transform +desired state of the rigid object prim into the world frame before setting it. + +We use the :attr:`assets.RigidObject.data.default_root_state` attribute to get the default root state of the +spawned rigid object prims. This default state can be configured from the :attr:`assets.RigidObjectCfg.init_state` +attribute, which we left as identity in this tutorial. We then randomize the translation of the root state and +set the desired state of the rigid object prim using the :meth:`assets.RigidObject.write_root_pose_to_sim` and :meth:`assets.RigidObject.write_root_velocity_to_sim` methods. +As the name suggests, this method writes the root state of the rigid object prim into the simulation buffer. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_rigid_object.py + :language: python + :start-at: # reset root state + :end-at: cone_object.reset() + +Stepping the simulation +""""""""""""""""""""""" + +Before stepping the simulation, we perform the :meth:`assets.RigidObject.write_data_to_sim` method. This method +writes other data, such as external forces, into the simulation buffer. In this tutorial, we do not apply any +external forces to the rigid object, so this method is not necessary. However, it is included for completeness. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_rigid_object.py + :language: python + :start-at: # apply sim data + :end-at: cone_object.write_data_to_sim() + +Updating the state +"""""""""""""""""" + +After stepping the simulation, we update the internal buffers of the rigid object prims to reflect their new state +inside the :class:`assets.RigidObject.data` attribute. This is done using the :meth:`assets.RigidObject.update` method. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_rigid_object.py + :language: python + :start-at: # update buffers + :end-at: cone_object.update(sim_dt) + + +The Code Execution +~~~~~~~~~~~~~~~~~~ + +Now that we have gone through the code, let's run the script and see the result: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tutorials/01_assets/run_rigid_object.py + + +This should open a stage with a ground plane, lights, and several green cones. The cones must be dropping from +a random height and settling on to the ground. To stop the simulation, you can either close the window, or press +the ``STOP`` button in the UI, or press ``Ctrl+C`` in the terminal + +.. figure:: ../../_static/tutorials/tutorial_run_rigid_object.jpg + :align: center + :figwidth: 100% + :alt: result of run_rigid_object.py + + +This tutorial showed how to spawn rigid objects and wrap them in a :class:`RigidObject` class to initialize their +physics handles which allows setting and obtaining their state. In the next tutorial, we will see how to interact +with an articulated object which is a collection of rigid objects connected by joints. diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/run_surface_gripper.rst b/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/run_surface_gripper.rst new file mode 100644 index 0000000000000000000000000000000000000000..402d8e0847018b6acbd1620d94a463f5e8936cbd --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/01_assets/run_surface_gripper.rst @@ -0,0 +1,170 @@ +.. _tutorial-interact-surface-gripper: + +Interacting with a surface gripper +================================== + +.. currentmodule:: isaaclab + + +This tutorial shows how to interact with an articulated robot with a surface gripper attached to its end-effector in +the simulation. It is a continuation of the :ref:`tutorial-interact-articulation` tutorial, where we learned how to +interact with an articulated robot. Note that as of IsaacSim 5.0 the surface gripper are only supported on the cpu +backend. + + +The Code +~~~~~~~~ + +The tutorial corresponds to the ``run_surface_gripper.py`` script in the ``scripts/tutorials/01_assets`` +directory. + +.. dropdown:: Code for run_surface_gripper.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/01_assets/run_surface_gripper.py + :language: python + :emphasize-lines: 61-85, 124-125, 128-142, 147-150 + :linenos: + + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +Designing the scene +------------------- + +Similarly to the previous tutorial, we populate the scene with a ground plane and a distant light. Then, we spawn +an articulation from its USD file. This time a pick-and-place robot is spawned. The pick-and-place robot is a simple +robot with 3 driven axes, its gantry allows it to move along the x and y axes, as well as up and down along the z-axis. +Furthermore, the robot end-effector is outfitted with a surface gripper. +The USD file for the pick-and-place robot contains the robot's geometry, joints, and other physical properties +as well as the surface gripper. Before implementing a similar gripper on your own robot, we recommend to +check out the USD file for the gripper found on Isaaclab's Nucleus. + +For the pick-and-place robot, we use its pre-defined configuration object, you can find out more about it in the +:ref:`how-to-write-articulation-config` tutorial. For the surface gripper, we also need to create a configuration +object. This is done by instantiating a :class:`assets.SurfaceGripperCfg` object and passing it the relevant +parameters. + +The available parameters are: + +- ``max_grip_distance``: The maximum distance at which the gripper can grasp an object. +- ``shear_force_limit``: The maximum force the gripper can exert in the direction perpendicular to the gripper's axis. +- ``coaxial_force_limit``: The maximum force the gripper can exert in the direction of the gripper's axis. +- ``retry_interval``: The time the gripper will stay in a grasping state. + +As seen in the previous tutorial, we can spawn the articulation into the scene in a similar fashion by creating +an instance of the :class:`assets.Articulation` class by passing the configuration object to its constructor. The same +principle applies to the surface gripper. By passing the configuration object to the :class:`assets.SurfaceGripper` +constructor, the surface gripper is created and can be added to the scene. In practice, the object will only be +initialized when the play button is pressed. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_surface_gripper.py + :language: python + :start-at: # Create separate groups called "Origin1", "Origin2" + :end-at: surface_gripper = SurfaceGripper(cfg=surface_gripper_cfg) + + +Running the simulation loop +--------------------------- + +Continuing from the previous tutorial, we reset the simulation at regular intervals, set commands to the articulation, +step the simulation, and update the articulation's internal buffers. + +Resetting the simulation +"""""""""""""""""""""""" + +To reset the surface gripper, we only need to call the :meth:`SurfaceGripper.reset` method which will reset the +internal buffers and caches. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_surface_gripper.py + :language: python + :start-at: # Opens the gripper and makes sure the gripper is in the open state + :end-at: surface_gripper.reset() + +Stepping the simulation +""""""""""""""""""""""" + +Applying commands to the surface gripper involves two steps: + +1. *Setting the desired commands*: This sets the desired gripper commands (Open, Close, or Idle). +2. *Writing the data to the simulation*: Based on the surface gripper's configuration, this step handles writes the + converted values to the PhysX buffer. + +In this tutorial, we use a random command to set the gripper's command. The gripper behavior is as follows: + +- -1 < command < -0.3 --> Gripper is Opening +- -0.3 < command < 0.3 --> Gripper is Idle +- 0.3 < command < 1 --> Gripper is Closing + +At every step, we randomly sample commands and set them to the gripper by calling the +:meth:`SurfaceGripper.set_grippers_command` method. After setting the commands, we call the +:meth:`SurfaceGripper.write_data_to_sim` method to write the data to the PhysX buffer. Finally, we step +the simulation. + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_surface_gripper.py + :language: python + :start-at: # Sample a random command between -1 and 1. + :end-at: surface_gripper.write_data_to_sim() + + +Updating the state +"""""""""""""""""" + +To know the current state of the surface gripper, we can query the :meth:`assets.SurfaceGripper.state` property. +This property returns a tensor of size ``[num_envs]`` where each element is either ``-1``, ``0``, or ``1`` +corresponding to the gripper state. This property is updated every time the :meth:`assets.SurfaceGripper.update` method +is called. + +- ``-1`` --> Gripper is Open +- ``0`` --> Gripper is Closing +- ``1`` --> Gripper is Closed + +.. literalinclude:: ../../../../scripts/tutorials/01_assets/run_surface_gripper.py + :language: python + :start-at: # Read the gripper state from the simulation + :end-at: surface_gripper_state = surface_gripper.state + + +The Code Execution +~~~~~~~~~~~~~~~~~~ + + +To run the code and see the results, let's run the script from the terminal: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tutorials/01_assets/run_surface_gripper.py --device cpu + + +This command should open a stage with a ground plane, lights, and two pick-and-place robots. +In the terminal, you should see the gripper state and the command being printed. +To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal. + +.. figure:: ../../_static/tutorials/tutorial_run_surface_gripper.jpg + :align: center + :figwidth: 100% + :alt: result of run_surface_gripper.py + +In this tutorial, we learned how to create and interact with a surface gripper. We saw how to set commands and +query the gripper state. We also saw how to update its buffers to read the latest state from the simulation. + +In addition to this tutorial, we also provide a few other scripts that spawn different robots. These are included +in the ``scripts/demos`` directory. You can run these scripts as: + +.. code-block:: bash + + # Spawn many pick-and-place robots and perform a pick-and-place task + ./isaaclab.sh -p scripts/demos/pick_and_place.py + +Note that in practice, the users would be expected to register their :class:`assets.SurfaceGripper` instances inside +a :class:`isaaclab.InteractiveScene` object, which will automatically handle the calls to the +:meth:`assets.SurfaceGripper.write_data_to_sim` and :meth:`assets.SurfaceGripper.update` methods. + +.. code-block:: python + + # Create a scene + scene = InteractiveScene() + + # Register the surface gripper + scene.surface_grippers["gripper"] = surface_gripper diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/02_scene/create_scene.rst b/simulation/modules/IsaacLab/docs/source/tutorials/02_scene/create_scene.rst new file mode 100644 index 0000000000000000000000000000000000000000..a2d34cf57e78bed7f6d0e16c9466cfebf777c3d1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/02_scene/create_scene.rst @@ -0,0 +1,169 @@ +.. _tutorial-interactive-scene: + +Using the Interactive Scene +=========================== + +.. currentmodule:: isaaclab + +So far in the tutorials, we manually spawned assets into the simulation and created +object instances to interact with them. However, as the complexity of the scene +increases, it becomes tedious to perform these tasks manually. In this tutorial, +we will introduce the :class:`scene.InteractiveScene` class, which provides a convenient +interface for spawning prims and managing them in the simulation. + +At a high-level, the interactive scene is a collection of scene entities. Each entity +can be either a non-interactive prim (e.g. ground plane, light source), an interactive +prim (e.g. articulation, rigid object), or a sensor (e.g. camera, lidar). The interactive +scene provides a convenient interface for spawning these entities and managing them +in the simulation. + +Compared the manual approach, it provides the following benefits: + +* Alleviates the user needing to spawn each asset separately as this is handled implicitly. +* Enables user-friendly cloning of scene prims for multiple environments. +* Collects all the scene entities into a single object, which makes them easier to manage. + +In this tutorial, we take the cartpole example from the :ref:`tutorial-interact-articulation` +tutorial and replace the ``design_scene`` function with an :class:`scene.InteractiveScene` object. +While it may seem like overkill to use the interactive scene for this simple example, it will +become more useful in the future as more assets and sensors are added to the scene. + + +The Code +~~~~~~~~ + +This tutorial corresponds to the ``create_scene.py`` script within +``scripts/tutorials/02_scene``. + +.. dropdown:: Code for create_scene.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/02_scene/create_scene.py + :language: python + :emphasize-lines: 50-63, 68-70, 91-92, 99-100, 105-106, 116-118 + :linenos: + + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +While the code is similar to the previous tutorial, there are a few key differences +that we will go over in detail. + +Scene configuration +------------------- + +The scene is composed of a collection of entities, each with their own configuration. +These are specified in a configuration class that inherits from :class:`scene.InteractiveSceneCfg`. +The configuration class is then passed to the :class:`scene.InteractiveScene` constructor +to create the scene. + +For the cartpole example, we specify the same scene as in the previous tutorial, but list +them now in the configuration class :class:`CartpoleSceneCfg` instead of manually spawning them. + +.. literalinclude:: ../../../../scripts/tutorials/02_scene/create_scene.py + :language: python + :pyobject: CartpoleSceneCfg + +The variable names in the configuration class are used as keys to access the corresponding +entity from the :class:`scene.InteractiveScene` object. For example, the cartpole can +be accessed via ``scene["cartpole"]``. However, we will get to that later. First, let's +look at how individual scene entities are configured. + +Similar to how a rigid object and articulation were configured in the previous tutorials, +the configurations are specified using a configuration class. However, there is a key +difference between the configurations for the ground plane and light source and the +configuration for the cartpole. The ground plane and light source are non-interactive +prims, while the cartpole is an interactive prim. This distinction is reflected in the +configuration classes used to specify them. The configurations for the ground plane and +light source are specified using an instance of the :class:`assets.AssetBaseCfg` class +while the cartpole is configured using an instance of the :class:`assets.ArticulationCfg`. +Anything that is not an interactive prim (i.e., neither an asset nor a sensor) is not +*handled* by the scene during simulation steps. + +Another key difference to note is in the specification of the prim paths for the +different prims: + +* Ground plane: ``/World/defaultGroundPlane`` +* Light source: ``/World/Light`` +* Cartpole: ``{ENV_REGEX_NS}/Robot`` + +As we learned earlier, Omniverse creates a graph of prims in the USD stage. The prim +paths are used to specify the location of the prim in the graph. The ground plane and +light source are specified using absolute paths, while the cartpole is specified using +a relative path. The relative path is specified using the ``ENV_REGEX_NS`` variable, +which is a special variable that is replaced with the environment name during scene creation. +Any entity that has the ``ENV_REGEX_NS`` variable in its prim path will be cloned for each +environment. This path is replaced by the scene object with ``/World/envs/env_{i}`` where +``i`` is the environment index. + +Scene instantiation +------------------- + +Unlike before where we called the ``design_scene`` function to create the scene, we now +create an instance of the :class:`scene.InteractiveScene` class and pass in the configuration +object to its constructor. While creating the configuration instance of ``CartpoleSceneCfg`` +we specify how many environment copies we want to create using the ``num_envs`` argument. +This will be used to clone the scene for each environment. + +.. literalinclude:: ../../../../scripts/tutorials/02_scene/create_scene.py + :language: python + :start-at: # Design scene + :end-at: scene = InteractiveScene(scene_cfg) + +Accessing scene elements +------------------------ + +Similar to how entities were accessed from a dictionary in the previous tutorials, the +scene elements can be accessed from the :class:`InteractiveScene` object using the +``[]`` operator. The operator takes in a string key and returns the corresponding +entity. The key is specified through the configuration class for each entity. For example, +the cartpole is specified using the key ``"cartpole"`` in the configuration class. + +.. literalinclude:: ../../../../scripts/tutorials/02_scene/create_scene.py + :language: python + :start-at: # Extract scene entities + :end-at: robot = scene["cartpole"] + +Running the simulation loop +--------------------------- + +The rest of the script looks similar to previous scripts that interfaced with :class:`assets.Articulation`, +with a few small differences in the methods called: + +* :meth:`assets.Articulation.reset` ⟶ :meth:`scene.InteractiveScene.reset` +* :meth:`assets.Articulation.write_data_to_sim` ⟶ :meth:`scene.InteractiveScene.write_data_to_sim` +* :meth:`assets.Articulation.update` ⟶ :meth:`scene.InteractiveScene.update` + +Under the hood, the methods of :class:`scene.InteractiveScene` call the corresponding +methods of the entities in the scene. + + +The Code Execution +~~~~~~~~~~~~~~~~~~ + + + +Let's run the script to simulate 32 cartpoles in the scene. We can do this by passing +the ``--num_envs`` argument to the script. + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tutorials/02_scene/create_scene.py --num_envs 32 + +This should open a stage with 32 cartpoles swinging around randomly. You can use the +mouse to rotate the camera and the arrow keys to move around the scene. + + +.. figure:: ../../_static/tutorials/tutorial_creating_a_scene.jpg + :align: center + :figwidth: 100% + :alt: result of create_scene.py + +In this tutorial, we saw how to use :class:`scene.InteractiveScene` to create a +scene with multiple assets. We also saw how to use the ``num_envs`` argument +to clone the scene for multiple environments. + +There are many more example usages of the :class:`scene.InteractiveSceneCfg` in the tasks found +under the ``isaaclab_tasks`` extension. Please check out the source code to see +how they are used for more complex scenes. diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/configuring_rl_training.rst b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/configuring_rl_training.rst new file mode 100644 index 0000000000000000000000000000000000000000..ff2e8bef0be7301c51c374e3ac1482ceea064ca2 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/configuring_rl_training.rst @@ -0,0 +1,140 @@ +.. _tutorial-configure-rl-training: + +Configuring an RL Agent +======================= + +.. currentmodule:: isaaclab + +In the previous tutorial, we saw how to train an RL agent to solve the cartpole balancing task +using the `Stable-Baselines3`_ library. In this tutorial, we will see how to configure the +training process to use different RL libraries and different training algorithms. + +In the directory ``scripts/reinforcement_learning``, you will find the scripts for +different RL libraries. These are organized into subdirectories named after the library name. +Each subdirectory contains the training and playing scripts for the library. + +To configure a learning library with a specific task, you need to create a configuration file +for the learning agent. This configuration file is used to create an instance of the learning agent +and is used to configure the training process. Similar to the environment registration shown in +the :ref:`tutorial-register-rl-env-gym` tutorial, you can register the learning agent with the +``gymnasium.register`` method. + +The Code +-------- + +As an example, we will look at the configuration included for the task ``Isaac-Cartpole-v0`` +in the ``isaaclab_tasks`` package. This is the same task that we used in the +:ref:`tutorial-run-rl-training` tutorial. + +.. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/__init__.py + :language: python + :lines: 18-29 + +The Code Explained +------------------ + +Under the attribute ``kwargs``, we can see the configuration for the different learning libraries. +The key is the name of the library and the value is the path to the configuration instance. +This configuration instance can be a string, a class, or an instance of the class. +For example, the value of the key ``"rl_games_cfg_entry_point"`` is a string that points to the +configuration YAML file for the RL-Games library. Meanwhile, the value of the key +``"rsl_rl_cfg_entry_point"`` points to the configuration class for the RSL-RL library. + +The pattern used for specifying an agent configuration class follows closely to that used for +specifying the environment configuration entry point. This means that while the following +are equivalent: + + +.. dropdown:: Specifying the configuration entry point as a string + :icon: code + + .. code-block:: python + + from . import agents + + gym.register( + id="Isaac-Cartpole-v0", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.cartpole_env_cfg:CartpoleEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CartpolePPORunnerCfg", + }, + ) + +.. dropdown:: Specifying the configuration entry point as a class + :icon: code + + .. code-block:: python + + from . import agents + + gym.register( + id="Isaac-Cartpole-v0", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.cartpole_env_cfg:CartpoleEnvCfg", + "rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.CartpolePPORunnerCfg, + }, + ) + +The first code block is the preferred way to specify the configuration entry point. +The second code block is equivalent to the first one, but it leads to import of the configuration +class which slows down the import time. This is why we recommend using strings for the configuration +entry point. + +The reinforcement learning entrypoints are configured by default to read the +``_cfg_entry_point`` from the ``kwargs`` dictionary to retrieve the configuration instance. + +For instance, the following code block shows how the Stable-Baselines3 training implementation +reads the configuration instance: + +.. dropdown:: Code for train_sb3.py with SB3 + :icon: code + + .. literalinclude:: ../../../../scripts/reinforcement_learning/sb3/train_sb3.py + :language: python + :linenos: + :emphasize-lines: 56-60, 97-98 + +The argument ``--rl_library`` selects the reinforcement learning library. The ``--agent`` +argument selects the library-specific configuration entry point from the ``kwargs`` +dictionary, so you can manually specify alternate configuration instances. + +The Code Execution +------------------ + +Since for the cartpole balancing task, RSL-RL library offers two configuration instances, +we can use the ``--agent`` argument to specify the configuration instance to use. + +* Training with the standard PPO configuration: + + .. code-block:: bash + + # standard PPO training + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-v0 \ + --run_name ppo + +* Training with the PPO configuration with symmetry augmentation: + + .. code-block:: bash + + # PPO training with symmetry augmentation + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-v0 \ + --agent rsl_rl_with_symmetry_cfg_entry_point \ + --run_name ppo_with_symmetry_data_augmentation + + # you can use hydra to disable symmetry augmentation but enable mirror loss computation + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-v0 \ + --agent rsl_rl_with_symmetry_cfg_entry_point \ + --run_name ppo_without_symmetry_data_augmentation \ + agent.algorithm.symmetry_cfg.use_data_augmentation=false + +The ``--run_name`` argument is used to specify the name of the run. This is used to +create a directory for the run in the ``logs/rsl_rl/cartpole`` directory. + +.. _Stable-Baselines3: https://stable-baselines3.readthedocs.io/en/master/ +.. _RL-Games: https://github.com/Denys88/rl_games +.. _RSL-RL: https://github.com/leggedrobotics/rsl_rl +.. _SKRL: https://skrl.readthedocs.io diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/create_direct_rl_env.rst b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/create_direct_rl_env.rst new file mode 100644 index 0000000000000000000000000000000000000000..260f4095b41ae4ebbcb34c95713a13846437e06d --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/create_direct_rl_env.rst @@ -0,0 +1,339 @@ +.. _tutorial-create-direct-rl-env: + + +Creating a Direct Workflow RL Environment +========================================= + +.. currentmodule:: isaaclab + +In addition to the :class:`envs.ManagerBasedRLEnv` class, which encourages the use of configuration classes +for more modular environments, the :class:`~isaaclab.envs.DirectRLEnv` class allows for more direct control +in the scripting of environment. + +Instead of using Manager classes for defining rewards and observations, the direct workflow tasks +implement the full reward and observation functions directly in the task script. +This allows for more control in the implementation of the methods, such as using pytorch jit +features, and provides a less abstracted framework that makes it easier to find the various +pieces of code. + +In this tutorial, we will configure the cartpole environment using the direct workflow implementation to create a task +for balancing the pole upright. We will learn how to specify the task using by implementing functions +for scene creation, actions, resets, rewards and observations. + + +The Code +~~~~~~~~ + +For this tutorial, we use the cartpole environment defined in ``isaaclab_tasks.direct.cartpole`` module. + +.. dropdown:: Code for cartpole_env.py + :icon: code + + .. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py + :language: python + :linenos: + + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +Similar to the manager-based environments, a configuration class is defined for the task to hold settings +for the simulation parameters, the scene, the actors, and the task. With the direct workflow implementation, +the :class:`envs.DirectRLEnvCfg` class is used as the base class for configurations. +Since the direct workflow implementation does not use Action and Observation managers, the task +config should define the number of actions and observations for the environment. + +.. code-block:: python + + @configclass + class CartpoleEnvCfg(DirectRLEnvCfg): + ... + action_space = 1 + observation_space = 4 + state_space = 0 + +The config class can also be used to define task-specific attributes, such as scaling for reward terms +and thresholds for reset conditions. + +.. code-block:: python + + @configclass + class CartpoleEnvCfg(DirectRLEnvCfg): + ... + # reset + max_cart_pos = 3.0 + initial_pole_angle_range = [-0.25, 0.25] + + # reward scales + rew_scale_alive = 1.0 + rew_scale_terminated = -2.0 + rew_scale_pole_pos = -1.0 + rew_scale_cart_vel = -0.01 + rew_scale_pole_vel = -0.005 + +When creating a new environment, the code should define a new class that inherits from :class:`~isaaclab.envs.DirectRLEnv`. + +.. code-block:: python + + class CartpoleEnv(DirectRLEnv): + cfg: CartpoleEnvCfg + + def __init__(self, cfg: CartpoleEnvCfg, render_mode: str | None = None, **kwargs): + super().__init__(cfg, render_mode, **kwargs) + +The class can also hold class variables that are accessible by all functions in the class, +including functions for applying actions, computing resets, rewards, and observations. + +Scene Creation +-------------- + +In contrast to manager-based environments where the scene creation is taken care of by the framework, +the direct workflow implementation provides flexibility for users to implement their own scene creation +function. This includes adding actors into the stage, cloning the environments, filtering collisions +between the environments, adding the actors into the scene, and adding any additional props to the +scene, such as ground plane and lights. These operations should be implemented in the +``_setup_scene(self)`` method. + +.. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py + :language: python + :pyobject: CartpoleEnv._setup_scene + +Defining Rewards +---------------- + +Reward function should be defined in the ``_get_rewards(self)`` API, which returns the reward +buffer as a return value. Within this function, the task is free to implement the logic of +the reward function. In this example, we implement a Pytorch JIT function that computes +the various components of the reward function. + +.. code-block:: python + + def _get_rewards(self) -> torch.Tensor: + total_reward = compute_rewards( + self.cfg.rew_scale_alive, + self.cfg.rew_scale_terminated, + self.cfg.rew_scale_pole_pos, + self.cfg.rew_scale_cart_vel, + self.cfg.rew_scale_pole_vel, + self.joint_pos[:, self._pole_dof_idx[0]], + self.joint_vel[:, self._pole_dof_idx[0]], + self.joint_pos[:, self._cart_dof_idx[0]], + self.joint_vel[:, self._cart_dof_idx[0]], + self.reset_terminated, + ) + return total_reward + + @torch.jit.script + def compute_rewards( + rew_scale_alive: float, + rew_scale_terminated: float, + rew_scale_pole_pos: float, + rew_scale_cart_vel: float, + rew_scale_pole_vel: float, + pole_pos: torch.Tensor, + pole_vel: torch.Tensor, + cart_pos: torch.Tensor, + cart_vel: torch.Tensor, + reset_terminated: torch.Tensor, + ): + rew_alive = rew_scale_alive * (1.0 - reset_terminated.float()) + rew_termination = rew_scale_terminated * reset_terminated.float() + rew_pole_pos = rew_scale_pole_pos * torch.sum(torch.square(pole_pos), dim=-1) + rew_cart_vel = rew_scale_cart_vel * torch.sum(torch.abs(cart_vel), dim=-1) + rew_pole_vel = rew_scale_pole_vel * torch.sum(torch.abs(pole_vel), dim=-1) + total_reward = rew_alive + rew_termination + rew_pole_pos + rew_cart_vel + rew_pole_vel + return total_reward + + +Defining Observations +--------------------- + +The observation buffer should be computed in the ``_get_observations(self)`` function, +which constructs the observation buffer for the environment. At the end of this API, +a dictionary should be returned that contains ``policy`` as the key, and the full +observation buffer as the value. For asymmetric policies, the dictionary should also +include the key ``critic`` and the states buffer as the value. + +.. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py + :language: python + :pyobject: CartpoleEnv._get_observations + +Computing Dones and Performing Resets +------------------------------------- + +Populating the ``dones`` buffer should be done in the ``_get_dones(self)`` method. +This method is free to implement logic that computes which environments would need to be reset +and which environments have reached the episode length limit. Both results should be +returned by the ``_get_dones(self)`` function, in the form of a tuple of boolean tensors. + +.. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py + :language: python + :pyobject: CartpoleEnv._get_dones + +Once the indices for environments requiring reset have been computed, the ``_reset_idx(self, env_ids)`` +function performs the reset operations on those environments. Within this function, new states +for the environments requiring reset should be set directly into simulation. + +.. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py + :language: python + :pyobject: CartpoleEnv._reset_idx + +Applying Actions +---------------- + +There are two APIs that are designed for working with actions. The ``_pre_physics_step(self, actions)`` takes in actions +from the policy as an argument and is called once per RL step, prior to taking any physics steps. This function can +be used to process the actions buffer from the policy and cache the data in a class variable for the environment. + +.. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py + :language: python + :pyobject: CartpoleEnv._pre_physics_step + +The ``_apply_action(self)`` API is called ``decimation`` number of times for each RL step, prior to taking +each physics step. This provides more flexibility for environments where actions should be applied +for each physics step. + +.. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py + :language: python + :pyobject: CartpoleEnv._apply_action + + +The Code Execution +~~~~~~~~~~~~~~~~~~ + +To run training for the direct workflow Cartpole environment, we can use the following command: + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rl_games --task=Isaac-Cartpole-Direct-v0 + +.. figure:: ../../_static/tutorials/tutorial_create_direct_workflow.jpg + :align: center + :figwidth: 100% + :alt: result of train.py + +All direct workflow tasks have the suffix ``-Direct`` added to the task name to differentiate the implementation style. + + +Domain Randomization +~~~~~~~~~~~~~~~~~~~~ + +In the direct workflow, domain randomization configuration uses the :class:`~isaaclab.utils.configclass` module +to specify a configuration class consisting of :class:`~managers.EventTermCfg` variables. + +Below is an example of a configuration class for domain randomization: + +.. code-block:: python + + @configclass + class EventCfg: + robot_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*"), + "static_friction_range": (0.7, 1.3), + "dynamic_friction_range": (1.0, 1.0), + "restitution_range": (1.0, 1.0), + "num_buckets": 250, + }, + ) + robot_joint_stiffness_and_damping = EventTerm( + func=mdp.randomize_actuator_gains, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=".*"), + "stiffness_distribution_params": (0.75, 1.5), + "damping_distribution_params": (0.3, 3.0), + "operation": "scale", + "distribution": "log_uniform", + }, + ) + reset_gravity = EventTerm( + func=mdp.randomize_physics_scene_gravity, + mode="interval", + is_global_time=True, + interval_range_s=(36.0, 36.0), # time_s = num_steps * (decimation * dt) + params={ + "gravity_distribution_params": ([0.0, 0.0, 0.0], [0.0, 0.0, 0.4]), + "operation": "add", + "distribution": "gaussian", + }, + ) + +Each ``EventTerm`` object is of the :class:`~managers.EventTermCfg` class and takes in a ``func`` parameter +for specifying the function to call during randomization, a ``mode`` parameter, which can be ``startup``, +``reset`` or ``interval``. THe ``params`` dictionary should provide the necessary arguments to the +function that is specified in the ``func`` parameter. +Functions specified as ``func`` for the ``EventTerm`` can be found in the :class:`~envs.mdp.events` module. + +Note that as part of the ``"asset_cfg": SceneEntityCfg("robot", body_names=".*")`` parameter, the name of +the actor ``"robot"`` is provided, along with the body or joint names specified as a regex expression, +which will be the actors and bodies/joints that will have randomization applied. + +Once the ``configclass`` for the randomization terms have been set up, the class must be added +to the base config class for the task and be assigned to the variable ``events``. + +.. code-block:: python + + @configclass + class MyTaskConfig: + events: EventCfg = EventCfg() + + +Action and Observation Noise +---------------------------- + +Actions and observation noise can also be added using the :class:`~utils.configclass` module. +Action and observation noise configs must be added to the main task config using the +``action_noise_model`` and ``observation_noise_model`` variables: + +.. code-block:: python + + @configclass + class MyTaskConfig: + + # at every time-step add gaussian noise + bias. The bias is a gaussian sampled at reset + action_noise_model: NoiseModelWithAdditiveBiasCfg = NoiseModelWithAdditiveBiasCfg( + noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.05, operation="add"), + bias_noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.015, operation="abs"), + ) + + # at every time-step add gaussian noise + bias. The bias is a gaussian sampled at reset + observation_noise_model: NoiseModelWithAdditiveBiasCfg = NoiseModelWithAdditiveBiasCfg( + noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.002, operation="add"), + bias_noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.0001, operation="abs"), + ) + + +:class:`~.utils.noise.NoiseModelWithAdditiveBiasCfg` can be used to sample both uncorrelated noise +per step as well as correlated noise that is re-sampled at reset time. + +The ``noise_cfg`` term specifies the Gaussian distribution that will be sampled at each +step for all environments. This noise will be added to the corresponding actions and +observations buffers at every step. + +The ``bias_noise_cfg`` term specifies the Gaussian distribution for the correlated noise +that will be sampled at reset time for the environments being reset. The same noise +will be applied each step for the remaining of the episode for the environments and +resampled at the next reset. + +If only per-step noise is desired, :class:`~utils.noise.GaussianNoiseCfg` can be used +to specify an additive Gaussian distribution that adds the sampled noise to the input buffer. + +.. code-block:: python + + @configclass + class MyTaskConfig: + action_noise_model: GaussianNoiseCfg = GaussianNoiseCfg(mean=0.0, std=0.05, operation="add") + + + + +In this tutorial, we learnt how to create a direct workflow task environment for reinforcement learning. We do this +by extending the base environment to include the scene setup, actions, dones, reset, reward and observaion functions. + +While it is possible to manually create an instance of :class:`~isaaclab.envs.DirectRLEnv` class for a desired task, +this is not scalable as it requires specialized scripts for each task. Thus, we exploit the +:meth:`gymnasium.make` function to create the environment with the gym interface. We will learn how to do this +in the next tutorial. diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/create_manager_base_env.rst b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/create_manager_base_env.rst new file mode 100644 index 0000000000000000000000000000000000000000..e99a1d2eb589c5bf829000f8ca278cb3d76818c8 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/create_manager_base_env.rst @@ -0,0 +1,220 @@ +.. _tutorial-create-manager-base-env: + + +Creating a Manager-Based Base Environment +========================================= + +.. currentmodule:: isaaclab + +Environments bring together different aspects of the simulation such as +the scene, observations and actions spaces, reset events etc. to create a +coherent interface for various applications. In Isaac Lab, manager-based environments are +implemented as :class:`envs.ManagerBasedEnv` and :class:`envs.ManagerBasedRLEnv` classes. +The two classes are very similar, but :class:`envs.ManagerBasedRLEnv` is useful for +reinforcement learning tasks and contains rewards, terminations, curriculum +and command generation. The :class:`envs.ManagerBasedEnv` class is useful for +traditional robot control and doesn't contain rewards and terminations. + +In this tutorial, we will look at the base class :class:`envs.ManagerBasedEnv` and its +corresponding configuration class :class:`envs.ManagerBasedEnvCfg` for the manager-based workflow. +We will use the +cartpole environment from earlier to illustrate the different components +in creating a new :class:`envs.ManagerBasedEnv` environment. + + +The Code +~~~~~~~~ + +The tutorial corresponds to the ``create_cartpole_base_env`` script in the ``scripts/tutorials/03_envs`` +directory. + +.. dropdown:: Code for create_cartpole_base_env.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/03_envs/create_cartpole_base_env.py + :language: python + :emphasize-lines: 47-51, 54-71, 74-108, 111-130, 135-139, 144, 148, 153-154, 160-161 + :linenos: + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +The base class :class:`envs.ManagerBasedEnv` wraps around many intricacies of the simulation interaction +and provides a simple interface for the user to run the simulation and interact with it. It +is composed of the following components: + +* :class:`scene.InteractiveScene` - The scene that is used for the simulation. +* :class:`managers.ActionManager` - The manager that handles actions. +* :class:`managers.ObservationManager` - The manager that handles observations. +* :class:`managers.EventManager` - The manager that schedules operations (such as domain randomization) + at specified simulation events. For instance, at startup, on resets, or periodic intervals. + +By configuring these components, the user can create different variations of the same environment +with minimal effort. In this tutorial, we will go through the different components of the +:class:`envs.ManagerBasedEnv` class and how to configure them to create a new environment. + +Designing the scene +------------------- + +The first step in creating a new environment is to configure its scene. For the cartpole +environment, we will be using the scene from the previous tutorial. Thus, we omit the +scene configuration here. For more details on how to configure a scene, see +:ref:`tutorial-interactive-scene`. + +Defining actions +---------------- + +In the previous tutorial, we directly input the action to the cartpole using +the :meth:`assets.Articulation.set_joint_effort_target` method. In this tutorial, we will +use the :class:`managers.ActionManager` to handle the actions. + +The action manager can comprise of multiple :class:`managers.ActionTerm`. Each action term +is responsible for applying *control* over a specific aspect of the environment. For instance, +for robotic arm, we can have two action terms -- one for controlling the joints of the arm, +and the other for controlling the gripper. This composition allows the user to define +different control schemes for different aspects of the environment. + +In the cartpole environment, we want to control the force applied to the cart to balance the pole. +Thus, we will create an action term that controls the force applied to the cart. + +.. literalinclude:: ../../../../scripts/tutorials/03_envs/create_cartpole_base_env.py + :language: python + :pyobject: ActionsCfg + +Defining observations +--------------------- + +While the scene defines the state of the environment, the observations define the states +that are observable by the agent. These observations are used by the agent to make decisions +on what actions to take. In Isaac Lab, the observations are computed by the +:class:`managers.ObservationManager` class. + +Similar to the action manager, the observation manager can comprise of multiple observation terms. +These are further grouped into observation groups which are used to define different observation +spaces for the environment. For instance, for hierarchical control, we may want to define +two observation groups -- one for the low level controller and the other for the high level +controller. It is assumed that all the observation terms in a group have the same dimensions. + +For this tutorial, we will only define one observation group named ``"policy"``. While not completely +prescriptive, this group is a necessary requirement for various wrappers in Isaac Lab. +We define a group by inheriting from the :class:`managers.ObservationGroupCfg` class. This class +collects different observation terms and help define common properties for the group, such +as enabling noise corruption or concatenating the observations into a single tensor. + +The individual terms are defined by inheriting from the :class:`managers.ObservationTermCfg` class. +This class takes in the :attr:`managers.ObservationTermCfg.func` that specifies the function or +callable class that computes the observation for that term. It includes other parameters for +defining the noise model, clipping, scaling, etc. However, we leave these parameters to their +default values for this tutorial. + +.. literalinclude:: ../../../../scripts/tutorials/03_envs/create_cartpole_base_env.py + :language: python + :pyobject: ObservationsCfg + +Defining events +--------------- + +At this point, we have defined the scene, actions and observations for the cartpole environment. +The general idea for all these components is to define the configuration classes and then +pass them to the corresponding managers. The event manager is no different. + +The :class:`managers.EventManager` class is responsible for events corresponding to changes +in the simulation state. This includes resetting (or randomizing) the scene, randomizing physical +properties (such as mass, friction, etc.), and varying visual properties (such as colors, textures, etc.). +Each of these are specified through the :class:`managers.EventTermCfg` class, which +takes in the :attr:`managers.EventTermCfg.func` that specifies the function or callable +class that performs the event. + +Additionally, it expects the **mode** of the event. The mode specifies when the event term should be applied. +It is possible to specify your own mode. For this, you'll need to adapt the :class:`~envs.ManagerBasedEnv` class. +However, out of the box, Isaac Lab provides three commonly used modes: + +* ``"startup"`` - Event that takes place only once at environment startup. +* ``"reset"`` - Event that occurs on environment termination and reset. +* ``"interval"`` - Event that are executed at a given interval, i.e., periodically after a certain number of steps. + +For this example, we define events that randomize the pole's mass on startup. This is done only once since this +operation is expensive and we don't want to do it on every reset. We also create an event to randomize the initial +joint state of the cartpole and the pole at every reset. + +.. literalinclude:: ../../../../scripts/tutorials/03_envs/create_cartpole_base_env.py + :language: python + :pyobject: EventCfg + +Tying it all together +--------------------- + +Having defined the scene and manager configurations, we can now define the environment configuration +through the :class:`envs.ManagerBasedEnvCfg` class. This class takes in the scene, action, observation and +event configurations. + +In addition to these, it also takes in the :attr:`envs.ManagerBasedEnvCfg.sim` which defines the simulation +parameters such as the timestep, gravity, etc. This is initialized to the default values, but can +be modified as needed. We recommend doing so by defining the :meth:`__post_init__` method in the +:class:`envs.ManagerBasedEnvCfg` class, which is called after the configuration is initialized. + +.. literalinclude:: ../../../../scripts/tutorials/03_envs/create_cartpole_base_env.py + :language: python + :pyobject: CartpoleEnvCfg + +Running the simulation +---------------------- + +Lastly, we revisit the simulation execution loop. This is now much simpler since we have +abstracted away most of the details into the environment configuration. We only need to +call the :meth:`envs.ManagerBasedEnv.reset` method to reset the environment and :meth:`envs.ManagerBasedEnv.step` +method to step the environment. Both these functions return the observation and an info dictionary +which may contain additional information provided by the environment. These can be used by an +agent for decision-making. + +The :class:`envs.ManagerBasedEnv` class does not have any notion of terminations since that concept is +specific for episodic tasks. Thus, the user is responsible for defining the termination condition +for the environment. In this tutorial, we reset the simulation at regular intervals. + +.. literalinclude:: ../../../../scripts/tutorials/03_envs/create_cartpole_base_env.py + :language: python + :pyobject: main + +An important thing to note above is that the entire simulation loop is wrapped inside the +:meth:`torch.inference_mode` context manager. This is because the environment uses PyTorch +operations under-the-hood and we want to ensure that the simulation is not slowed down by +the overhead of PyTorch's autograd engine and gradients are not computed for the simulation +operations. + +The Code Execution +~~~~~~~~~~~~~~~~~~ + +To run the base environment made in this tutorial, you can use the following command: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tutorials/03_envs/create_cartpole_base_env.py --num_envs 32 --viz kit + +This should open a stage with a ground plane, light source, and cartpoles. The simulation should be +playing with random actions on the cartpole. Additionally, it opens a UI window on the bottom +right corner of the screen named ``"Isaac Lab"``. This window contains different UI elements that +can be used for debugging and visualization. + + +.. figure:: ../../_static/tutorials/tutorial_create_manager_rl_env.jpg + :align: center + :figwidth: 100% + :alt: result of create_cartpole_base_env.py + +To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal where you +started the simulation. + +In this tutorial, we learned about the different managers that help define a base environment. We +include more examples of defining the base environment in the ``scripts/tutorials/03_envs`` +directory. For completeness, they can be run using the following commands: + +.. code-block:: bash + + # Floating cube environment with custom action term for PD control + ./isaaclab.sh -p scripts/tutorials/03_envs/create_cube_base_env.py --num_envs 32 --viz kit + + # Quadrupedal locomotion environment with a policy that interacts with the environment + ./isaaclab.sh -p scripts/tutorials/03_envs/create_quadruped_base_env.py --num_envs 32 --viz kit + +In the following tutorial, we will look at the :class:`envs.ManagerBasedRLEnv` class and how to use it +to create a Markovian Decision Process (MDP). diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/create_manager_rl_env.rst b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/create_manager_rl_env.rst new file mode 100644 index 0000000000000000000000000000000000000000..a5b26675a30d9f065aa620127aecfdabdfd76853 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/create_manager_rl_env.rst @@ -0,0 +1,190 @@ +.. _tutorial-create-manager-rl-env: + + +Creating a Manager-Based RL Environment +======================================= + +.. currentmodule:: isaaclab + +Having learnt how to create a base environment in :ref:`tutorial-create-manager-base-env`, we will now look at how to create a manager-based +task environment for reinforcement learning. + +The base environment is designed as an sense-act environment where the agent can send commands to the environment +and receive observations from the environment. This minimal interface is sufficient for many applications such as +traditional motion planning and controls. However, many applications require a task-specification which often +serves as the learning objective for the agent. For instance, in a navigation task, the agent may be required to +reach a goal location. To this end, we use the :class:`envs.ManagerBasedRLEnv` class which extends the base environment +to include a task specification. + +Similar to other components in Isaac Lab, instead of directly modifying the base class :class:`envs.ManagerBasedRLEnv`, we +encourage users to simply implement a configuration :class:`envs.ManagerBasedRLEnvCfg` for their task environment. +This practice allows us to separate the task specification from the environment implementation, making it easier +to reuse components of the same environment for different tasks. + +In this tutorial, we will configure the cartpole environment using the :class:`envs.ManagerBasedRLEnvCfg` to create a manager-based task +for balancing the pole upright. We will learn how to specify the task using reward terms, termination criteria, +curriculum and commands. + + +The Code +~~~~~~~~ + +For this tutorial, we use the cartpole environment defined in ``isaaclab_tasks.manager_based.classic.cartpole`` module. + +.. dropdown:: Code for cartpole_env_cfg.py + :icon: code + + .. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py + :language: python + :emphasize-lines: 117-141, 144-154, 172-174 + :linenos: + +The script for running the environment ``run_cartpole_rl_env.py`` is present in the +``isaaclab/scripts/tutorials/03_envs`` directory. The script is similar to the +``cartpole_base_env.py`` script in the previous tutorial, except that it uses the +:class:`envs.ManagerBasedRLEnv` instead of the :class:`envs.ManagerBasedEnv`. + +.. dropdown:: Code for run_cartpole_rl_env.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/03_envs/run_cartpole_rl_env.py + :language: python + :emphasize-lines: 38-42, 56-57 + :linenos: + + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +We already went through parts of the above in the :ref:`tutorial-create-manager-base-env` tutorial to learn +about how to specify the scene, observations, actions and events. Thus, in this tutorial, we +will focus only on the RL components of the environment. + +In Isaac Lab, we provide various implementations of different terms in the :mod:`envs.mdp` module. We will use +some of these terms in this tutorial, but users are free to define their own terms as well. These +are usually placed in their task-specific sub-package +(for instance, in :mod:`isaaclab_tasks.manager_based.classic.cartpole.mdp`). + + +Defining rewards +---------------- + +The :class:`managers.RewardManager` is used to compute the reward terms for the agent. Similar to the other +managers, its terms are configured using the :class:`managers.RewardTermCfg` class. The +:class:`managers.RewardTermCfg` class specifies the function or callable class that computes the reward +as well as the weighting associated with it. It also takes in dictionary of arguments, ``"params"`` +that are passed to the reward function when it is called. + +For the cartpole task, we will use the following reward terms: + +* **Alive Reward**: Encourage the agent to stay alive for as long as possible. +* **Terminating Reward**: Similarly penalize the agent for terminating. +* **Pole Angle Reward**: Encourage the agent to keep the pole at the desired upright position. +* **Cart Velocity Reward**: Encourage the agent to keep the cart velocity as small as possible. +* **Pole Velocity Reward**: Encourage the agent to keep the pole velocity as small as possible. + +.. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py + :language: python + :pyobject: RewardsCfg + +Defining termination criteria +----------------------------- + +Most learning tasks happen over a finite number of steps that we call an episode. For instance, in the cartpole +task, we want the agent to balance the pole for as long as possible. However, if the agent reaches an unstable +or unsafe state, we want to terminate the episode. On the other hand, if the agent is able to balance the pole +for a long time, we want to terminate the episode and start a new one so that the agent can learn to balance the +pole from a different starting configuration. + +The :class:`managers.TerminationsCfg` configures what constitutes for an episode to terminate. In this example, +we want the task to terminate when either of the following conditions is met: + +* **Episode Length** The episode length is greater than the defined max_episode_length +* **Cart out of bounds** The cart goes outside of the bounds [-3, 3] + +The flag :attr:`managers.TerminationsCfg.time_out` specifies whether the term is a time-out (truncation) term +or terminated term. These are used to indicate the two types of terminations as described in `Gymnasium's documentation +`_. + +.. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py + :language: python + :pyobject: TerminationsCfg + +Defining commands +----------------- + +For various goal-conditioned tasks, it is useful to specify the goals or commands for the agent. These are +handled through the :class:`managers.CommandManager`. The command manager handles resampling and updating the +commands at each step. It can also be used to provide the commands as an observation to the agent. + +For this simple task, we do not use any commands. Hence, we leave this attribute as its default value, which is None. +You can see an example of how to define a command manager in the other locomotion or manipulation tasks. + +Defining curriculum +------------------- + +Often times when training a learning agent, it helps to start with a simple task and gradually increase the +tasks's difficulty as the agent training progresses. This is the idea behind curriculum learning. In Isaac Lab, +we provide a :class:`managers.CurriculumManager` class that can be used to define a curriculum for your environment. + +In this tutorial we don't implement a curriculum for simplicity, but you can see an example of a +curriculum definition in the other locomotion or manipulation tasks. + +Tying it all together +--------------------- + +With all the above components defined, we can now create the :class:`ManagerBasedRLEnvCfg` configuration for the +cartpole environment. This is similar to the :class:`ManagerBasedEnvCfg` defined in :ref:`tutorial-create-manager-base-env`, +only with the added RL components explained in the above sections. + +.. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py + :language: python + :pyobject: CartpoleEnvCfg + +Running the simulation loop +--------------------------- + +Coming back to the ``run_cartpole_rl_env.py`` script, the simulation loop is similar to the previous tutorial. +The only difference is that we create an instance of :class:`envs.ManagerBasedRLEnv` instead of the +:class:`envs.ManagerBasedEnv`. Consequently, now the :meth:`envs.ManagerBasedRLEnv.step` method returns additional signals +such as the reward and termination status. The information dictionary also maintains logging of quantities +such as the reward contribution from individual terms, the termination status of each term, the episode length etc. + +.. literalinclude:: ../../../../scripts/tutorials/03_envs/run_cartpole_rl_env.py + :language: python + :pyobject: main + + +The Code Execution +~~~~~~~~~~~~~~~~~~ + + +Similar to the previous tutorial, we can run the environment by executing the ``run_cartpole_rl_env.py`` script. + +.. code-block:: bash + + python scripts/tutorials/03_envs/run_cartpole_rl_env.py --num_envs 32 --viz kit + + +This should open a similar simulation as in the previous tutorial. However, this time, the environment +returns more signals that specify the reward and termination status. Additionally, the individual +environments reset themselves when they terminate based on the termination criteria specified in the +configuration. + +.. figure:: ../../_static/tutorials/tutorial_create_manager_rl_env.jpg + :align: center + :figwidth: 100% + :alt: result of run_cartpole_rl_env.py + +To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal +where you started the simulation. + +In this tutorial, we learnt how to create a task environment for reinforcement learning. We do this +by extending the base environment to include the rewards, terminations, commands and curriculum terms. +We also learnt how to use the :class:`envs.ManagerBasedRLEnv` class to run the environment and receive various +signals from it. + +While it is possible to manually create an instance of :class:`envs.ManagerBasedRLEnv` class for a desired task, +this is not scalable as it requires specialized scripts for each task. Thus, we exploit the +:meth:`gymnasium.make` function to create the environment with the gym interface. We will learn how to do this +in the next tutorial. diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/modify_direct_rl_env.rst b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/modify_direct_rl_env.rst new file mode 100644 index 0000000000000000000000000000000000000000..986a6a60b9692d55e6e6fc28f702fb5b41191259 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/modify_direct_rl_env.rst @@ -0,0 +1,133 @@ +.. _tutorial-modify-direct-rl-env: + + +Modifying an existing Direct RL Environment +=========================================== + +.. currentmodule:: isaaclab + +Having learnt how to create a task in :ref:`tutorial-create-direct-rl-env`, register it in :ref:`tutorial-register-rl-env-gym`, +and train it in :ref:`tutorial-run-rl-training`, we will now look at how to make minor modifications to an existing task. + +Sometimes it is necessary to create, due to complexity or variations from existing examples, tasks from scratch. However, in certain situations, +it is possible to start from the existing code and introduce minor changes, one by one, to transform them according to our needs. + +In this tutorial, we will make minor modifications to the direct workflow Humanoid task to change the simple +humanoid model to the Unitree H1 humanoid robot without affecting the original code. + + +The Base Code +~~~~~~~~~~~~~ + +For this tutorial, we start from the direct workflow Humanoid environment defined in ``isaaclab_tasks.direct.humanoid`` module. + +.. dropdown:: Code for humanoid_env.py + :icon: code + + .. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/direct/humanoid/humanoid_env.py + :language: python + :linenos: + + +The Changes Explained +~~~~~~~~~~~~~~~~~~~~~ + +Duplicating the file and registering a new task +----------------------------------------------- + +To avoid modifying the code of the existing task, we will make a copy of the file containing the Python +code and perform the modification on this copy. Then, in the Isaac Lab project +``source/isaaclab_tasks/isaaclab_tasks/direct/humanoid`` +folder we make a copy of the ``humanoid_env.py`` file and rename it to ``h1_env.py``. + +Open the ``h1_env.py`` file in a code editor and replace all the humanoid task name (``HumanoidEnv``) and its configuration +(``HumanoidEnvCfg``) instances to ``H1Env`` and ``H1EnvCfg`` respectively. +This is necessary to avoid name conflicts during import when registering the environment. + +Once the name change has been made, we proceed to add a new entry to register the task under the name ``Isaac-H1-Direct-v0``. +To do this, we modify the ``__init__.py`` file in the same working folder and add the following entry. +Refer to the :ref:`tutorial-register-rl-env-gym` tutorial for more details about environment registrations. + +.. hint:: + + If the changes in the task are minimal, it is very likely that the same RL library agent configurations can be used to train it successfully. + Otherwise, it is advisable to create new configuration files (adjusting their name during registration under the ``kwargs`` parameter) + to avoid altering the original configurations. + + +.. literalinclude:: ../../refs/snippets/tutorial_modify_direct_rl_env.py + :language: python + :start-after: [start-init-import] + :end-before: [end-init-import] + +.. literalinclude:: ../../refs/snippets/tutorial_modify_direct_rl_env.py + :language: python + :start-after: [start-init-register] + :end-before: [end-init-register] + +Changing the robot +------------------ + +The ``H1EnvCfg`` class (in the new created ``h1_env.py`` file) encapsulates the configuration values of the environment, +including the assets to be instantiated. Particularly in this example, the ``robot`` property holds the target articulation configuration. + +Since the Unitree H1 robot is included in the Isaac Lab assets extension (``isaaclab_assets``) we can just import it +and do the replacement directly (under the ``H1EnvCfg.robot`` property), as shown below. Note that we also need to modify the +``joint_gears`` property as it holds robot-specific configuration values. + +.. |franka-direct-link| replace:: `Isaac-Franka-Cabinet-Direct-v0 `__ + +.. hint:: + + If the target robot is not included in the Isaac Lab assets extension, it is possible to load and configure it, from a USD file, + by using the :class:`~isaaclab.assets.ArticulationCfg` class. + + * See the |franka-direct-link| source code for an example of loading and configuring a robot from a USD file. + * Refer to the `Importing a New Asset <../../how-to/import_new_asset.html>`_ tutorial for details on how to import an asset from URDF or MJCF file, and other formats. + +.. literalinclude:: ../../refs/snippets/tutorial_modify_direct_rl_env.py + :language: python + :start-after: [start-h1_env-import] + :end-before: [end-h1_env-import] + +.. literalinclude:: ../../refs/snippets/tutorial_modify_direct_rl_env.py + :language: python + :start-after: [start-h1_env-robot] + :end-before: [end-h1_env-robot] + +The robot changed, and with it the number of joints to control or the number of rigid bodies that compose the articulation, for example. +Therefore, it is also necessary to adjust other values in the environment configuration that depend on the characteristics of the robot, +such as the number of elements in the observation and action space. + +.. literalinclude:: ../../refs/snippets/tutorial_modify_direct_rl_env.py + :language: python + :start-after: [start-h1_env-spaces] + :end-before: [end-h1_env-spaces] + +The Code Execution +~~~~~~~~~~~~~~~~~~ + +After the minor modification has been done, and similar to the previous tutorial, we can train on the task using one of the available RL workflows for such task. + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rl_games --task Isaac-H1-Direct-v0 + +When the training is finished, we can visualize the result with the following command. +To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal +where you started the simulation. + +.. code-block:: bash + + ./isaaclab.sh play --rl_library rl_games --task Isaac-H1-Direct-v0 --num_envs 64 --viz kit + +.. figure:: ../../_static/tutorials/tutorial_modify_direct_rl_env.jpg + :align: center + :figwidth: 100% + :alt: result of training Isaac-H1-Direct-v0 task + +In this tutorial, we learnt how to make minor modifications to an existing environment without affecting the original code. + +It is important to note, however, that while the changes to be made may be small, they may not always work on the first try, +as there may be deeper dependencies on the original assets in the environment being modified. +In these cases, it is advisable to analyze the code of the available examples in detail in order to make an appropriate adjustment. diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/policy_inference_in_usd.rst b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/policy_inference_in_usd.rst new file mode 100644 index 0000000000000000000000000000000000000000..ac67bdc13f317f2d4baa30b753f7edd063c1d6e5 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/policy_inference_in_usd.rst @@ -0,0 +1,74 @@ +.. _tutorial-policy-inference-in-usd: + + +Policy Inference in USD Environment +=================================== + +.. currentmodule:: isaaclab + +Having learnt how to modify a task in :ref:`tutorial-modify-direct-rl-env`, we will now look at how to run a trained policy in a prebuilt USD scene. + +In this tutorial, we will use the RSL RL library and the trained policy from the Humanoid Rough Terrain ``Isaac-Velocity-Rough-H1-v0`` task in a simple warehouse USD. + + +The Tutorial Code +~~~~~~~~~~~~~~~~~ + +For this tutorial, we use the trained policy's checkpoint exported as jit (which is an offline version of the policy). + +The ``H1RoughEnvCfg_PLAY`` cfg encapsulates the configuration values of the inference environment, including the assets to +be instantiated. + +In order to use a prebuilt USD environment instead of the terrain generator specified, we make the +following changes to the config before passing it to the ``ManagerBasedRLEnv``. + +.. dropdown:: Code for policy_inference_in_usd.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/03_envs/policy_inference_in_usd.py + :language: python + :linenos: + :emphasize-lines: 60-69 + + +Note that we have set the device to ``CPU`` and disabled the use of Fabric for inferencing. +This is because when simulating a small number of environment, CPU simulation can often perform faster than GPU simulation. + + +The Code Execution +~~~~~~~~~~~~~~~~~~ + +First, we need to train the ``Isaac-Velocity-Rough-H1-v0`` task by running the following: + +.. code-block:: bash + + ./isaaclab.sh train --rl_library rsl_rl --task Isaac-Velocity-Rough-H1-v0 + +When the training is finished, we can visualize the result with the following command. +To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal +where you started the simulation. + +.. code-block:: bash + + ./isaaclab.sh play --rl_library rsl_rl --task Isaac-Velocity-Rough-H1-v0 --num_envs 64 --checkpoint logs/rsl_rl/h1_rough/EXPERIMENT_NAME/POLICY_FILE.pt --viz kit + + +After running the play script, the policy will be exported to jit and onnx files under the experiment logs directory. +Note that not all learning libraries support exporting the policy to a jit or onnx file. +For libraries that don't currently support this functionality, please refer to the corresponding ``play.py`` script for the library +to learn about how to initialize the policy. + +We can then load the warehouse asset and run inference on the H1 robot using the exported jit policy +(``policy.pt`` file in the ``exported/`` directory). + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tutorials/03_envs/policy_inference_in_usd.py --checkpoint logs/rsl_rl/h1_rough/EXPERIMENT_NAME/exported/policy.pt --viz kit + + +.. figure:: ../../_static/tutorials/tutorial_policy_inference_in_usd.jpg + :align: center + :figwidth: 100% + :alt: result of training Isaac-H1-Direct-v0 task + +In this tutorial, we learnt how to make minor modifications to an existing environment config to run policy inference in a prebuilt usd environment. diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/register_rl_env_gym.rst b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/register_rl_env_gym.rst new file mode 100644 index 0000000000000000000000000000000000000000..74deafe90d8592d9dadd51131f12e70f33c5b897 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/register_rl_env_gym.rst @@ -0,0 +1,172 @@ +.. _tutorial-register-rl-env-gym: + +Registering an Environment +========================== + +.. currentmodule:: isaaclab + +In the previous tutorial, we learned how to create a custom cartpole environment. We manually +created an instance of the environment by importing the environment class and its configuration +class. + +.. dropdown:: Environment creation in the previous tutorial + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/03_envs/run_cartpole_rl_env.py + :language: python + :start-at: # create environment configuration + :end-at: env = ManagerBasedRLEnv(cfg=env_cfg) + +While straightforward, this approach is not scalable as we have a large suite of environments. +In this tutorial, we will show how to use the :meth:`gymnasium.register` method to register +environments with the ``gymnasium`` registry. This allows us to create the environment through +the :meth:`gymnasium.make` function. + + +.. dropdown:: Environment creation in this tutorial + :icon: code + + .. literalinclude:: ../../../../scripts/environments/random_agent.py + :language: python + :lines: 36-47 + + +The Code +~~~~~~~~ + +The tutorial corresponds to the ``random_agent.py`` script in the ``scripts/environments`` directory. + +.. dropdown:: Code for random_agent.py + :icon: code + + .. literalinclude:: ../../../../scripts/environments/random_agent.py + :language: python + :emphasize-lines: 36-37, 42-47 + :linenos: + + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +The :class:`envs.ManagerBasedRLEnv` class inherits from the :class:`gymnasium.Env` class to follow +a standard interface. However, unlike the traditional Gym environments, the :class:`envs.ManagerBasedRLEnv` +implements a *vectorized* environment. This means that multiple environment instances +are running simultaneously in the same process, and all the data is returned in a batched +fashion. + +Similarly, the :class:`envs.DirectRLEnv` class also inherits from the :class:`gymnasium.Env` class +for the direct workflow. For :class:`envs.DirectMARLEnv`, although it does not inherit +from Gymnasium, it can be registered and created in the same way. + +Using the gym registry +---------------------- + +To register an environment, we use the :meth:`gymnasium.register` method. This method takes +in the environment name, the entry point to the environment class, and the entry point to the +environment configuration class. + +.. note:: + The :mod:`gymnasium` registry is a global registry. Hence, it is important to ensure that the + environment names are unique. Otherwise, the registry will throw an error when registering + the environment. + +Manager-Based Environments +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +For manager-based environments, the following shows the registration +call for the cartpole environment in the ``isaaclab_tasks.manager_based.classic.cartpole`` sub-package: + +.. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/__init__.py + :language: python + :lines: 10- + :emphasize-lines: 4, 11, 12, 15 + +The ``id`` argument is the name of the environment. As a convention, we name all the environments +with the prefix ``Isaac-`` to make it easier to search for them in the registry. The name of the +environment is typically followed by the name of the task, and then the name of the robot. +For instance, for legged locomotion with ANYmal C on flat terrain, the environment is called +``Isaac-Velocity-Flat-Anymal-C-v0``. The version number ``v`` is typically used to specify different +variations of the same environment. Otherwise, the names of the environments can become too long +and difficult to read. + +The ``entry_point`` argument is the entry point to the environment class. The entry point is a string +of the form ``:``. In the case of the cartpole environment, the entry point is +``isaaclab.envs:ManagerBasedRLEnv``. The entry point is used to import the environment class +when creating the environment instance. + +The ``env_cfg_entry_point`` argument specifies the default configuration for the environment. The default +configuration is loaded using the :meth:`isaaclab_tasks.utils.parse_env_cfg` function. +It is then passed to the :meth:`gymnasium.make` function to create the environment instance. +The configuration entry point can be both a YAML file or a python configuration class. + +Direct Environments +^^^^^^^^^^^^^^^^^^^ + +For direct-based environments, the environment registration follows a similar pattern. Instead of +registering the environment's entry point as the :class:`~isaaclab.envs.ManagerBasedRLEnv` class, +we register the environment's entry point as the implementation class of the environment. +Additionally, we add the suffix ``-Direct`` to the environment name to differentiate it from the +manager-based environments. + +As an example, the following shows the registration call for the cartpole environment in the +``isaaclab_tasks.direct.cartpole`` sub-package: + +.. literalinclude:: ../../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/__init__.py + :language: python + :lines: 10-31 + :emphasize-lines: 5, 12, 13, 16 + + +Creating the environment +------------------------ + +To inform the ``gym`` registry with all the environments provided by the ``isaaclab_tasks`` +extension, we must import the module at the start of the script. This will execute the ``__init__.py`` +file which iterates over all the sub-packages and registers their respective environments. + +.. literalinclude:: ../../../../scripts/environments/random_agent.py + :language: python + :start-at: import isaaclab_tasks # noqa: F401 + :end-at: import isaaclab_tasks # noqa: F401 + +In this tutorial, the task name is read from the command line. The task name is used to parse +the default configuration as well as to create the environment instance. In addition, other +parsed command line arguments such as the number of environments, the simulation device, +and whether to render, are used to override the default configuration. + +.. literalinclude:: ../../../../scripts/environments/random_agent.py + :language: python + :start-at: # parse configuration via Hydra + :end-at: env = gym.make(args_cli.task, cfg=env_cfg) + +Once creating the environment, the rest of the execution follows the standard resetting and stepping. + + +The Code Execution +~~~~~~~~~~~~~~~~~~ + +Now that we have gone through the code, let's run the script and see the result: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/random_agent.py --task Isaac-Cartpole-v0 --num_envs 32 --viz kit + + +This should open a stage with everything similar to the :ref:`tutorial-create-manager-rl-env` tutorial. +To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal. + + +.. figure:: ../../_static/tutorials/tutorial_register_environment.jpg + :align: center + :figwidth: 100% + :alt: result of random_agent.py + + +In addition, you can also change the simulation device from GPU to CPU by setting the value of the ``--device`` flag explicitly: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/random_agent.py --task Isaac-Cartpole-v0 --num_envs 32 --device cpu --viz kit + +With the ``--device cpu`` flag, the simulation will run on the CPU. This is useful for debugging the simulation. +However, the simulation will run much slower than on the GPU. diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/run_rl_training.rst b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/run_rl_training.rst new file mode 100644 index 0000000000000000000000000000000000000000..dd8e8f3bc28c35e58f70c2dec5a2c5133b1961b0 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/03_envs/run_rl_training.rst @@ -0,0 +1,155 @@ +.. _tutorial-run-rl-training: + +Training with an RL Agent +========================= + +.. currentmodule:: isaaclab + +In the previous tutorials, we covered how to define an RL task environment, register +it into the ``gym`` registry, and interact with it using a random agent. We now move +on to the next step: training an RL agent to solve the task. + +Although the :class:`envs.ManagerBasedRLEnv` conforms to the :class:`gymnasium.Env` interface, +it is not exactly a ``gym`` environment. The input and outputs of the environment are +not numpy arrays, but rather based on torch tensors with the first dimension being the +number of environment instances. + +Additionally, most RL libraries expect their own variation of an environment interface. +For example, `Stable-Baselines3`_ expects the environment to conform to its +`VecEnv API`_ which expects a list of numpy arrays instead of a single tensor. Similarly, +`RSL-RL`_, `RL-Games`_ and `SKRL`_ expect a different interface. Since there is no one-size-fits-all +solution, we do not base the :class:`envs.ManagerBasedRLEnv` on any particular learning library. +Instead, we implement wrappers to convert the environment into the expected interface. +These are specified in the :mod:`isaaclab_rl` module. + +In this tutorial, we will use `Stable-Baselines3`_ to train an RL agent to solve the +cartpole balancing task. + +.. caution:: + + Wrapping the environment with the respective learning framework's wrapper should happen in the end, + i.e. after all other wrappers have been applied. This is because the learning framework's wrapper + modifies the interpretation of environment's APIs which may no longer be compatible with :class:`gymnasium.Env`. + +The Code +-------- + +For this tutorial, we use the training implementation from `Stable-Baselines3`_ workflow in the +``scripts/reinforcement_learning/sb3`` directory. + +.. dropdown:: Code for train_sb3.py + :icon: code + + .. literalinclude:: ../../../../scripts/reinforcement_learning/sb3/train_sb3.py + :language: python + :linenos: + :emphasize-lines: 97-100, 104-109, 121-137, 145-157, 164-170 + +The Code Explained +------------------ + +.. currentmodule:: isaaclab_rl.utils + +Most of the code above is boilerplate code to create logging directories, saving the parsed configurations, +and setting up different Stable-Baselines3 components. For this tutorial, the important part is creating +the environment and wrapping it with the Stable-Baselines3 wrapper. + +There are three wrappers used in the code above: + +1. :class:`gymnasium.wrappers.RecordVideo`: This wrapper records a video of the environment + and saves it to the specified directory. This is useful for visualizing the agent's behavior + during training. +2. :class:`wrappers.sb3.Sb3VecEnvWrapper`: This wrapper converts the environment + into a Stable-Baselines3 compatible environment. +3. `stable_baselines3.common.vec_env.VecNormalize`_: This wrapper normalizes the + environment's observations and rewards. + +Each of these wrappers wrap around the previous wrapper by following ``env = wrapper(env, *args, **kwargs)`` +repeatedly. The final environment is then used to train the agent. For more information on how these +wrappers work, please refer to the :ref:`how-to-env-wrappers` documentation. + +The Code Execution +------------------ + +We train a PPO agent from Stable-Baselines3 to solve the cartpole balancing task. + +Training the agent +~~~~~~~~~~~~~~~~~~ + +There are three main ways to train the agent. Each of them has their own advantages and disadvantages. +It is up to you to decide which one you prefer based on your use case. + +Headless execution +"""""""""""""""""" + +When no visualizer is requested, no interactive visualizer window is opened during training. This is useful +when training on a remote server or when you do not need live visual feedback, which can add some compute cost. +Rendering can still be active for sensor/camera data capture when enabled by the workflow. + +.. code-block:: bash + + ./isaaclab.sh train --rl_library sb3 --task Isaac-Cartpole-v0 --num_envs 64 + + +Headless execution with off-screen render +""""""""""""""""""""""""""""""""""""""""" + +Since the above command does not open an interactive visualizer, it is not possible to monitor behavior +live in a viewport window. To capture visual output during training, enable camera/sensor rendering +in the workflow and pass ``--video`` to record the agent behavior. + +.. code-block:: bash + + ./isaaclab.sh train --rl_library sb3 --task Isaac-Cartpole-v0 --num_envs 64 --video + +The videos are saved to the ``logs/sb3/Isaac-Cartpole-v0//videos/train`` directory. You can open these videos +using any video player. + +Interactive execution +""""""""""""""""""""" + +.. currentmodule:: isaaclab + +While the above two methods are useful for training the agent, they don't allow you to interact with the +simulation to see what is happening. In this case, run the +training command as follows: + +.. code-block:: bash + + ./isaaclab.sh train --rl_library sb3 --task Isaac-Cartpole-v0 --num_envs 64 --viz kit + +This will open the Kit visualizer window and you can see the agent training in the environment. However, this +can slow down the training process because interactive visual feedback is enabled. As a workaround, you +can switch between different render modes in the ``"Isaac Lab"`` window that is docked on the bottom-right +corner of the screen. To learn more about these render modes, please check the +:class:`sim.SimulationContext.RenderMode` class. + +Viewing the logs +~~~~~~~~~~~~~~~~ + +On a separate terminal, you can monitor the training progress by executing the following command: + +.. code:: bash + + # execute from the root directory of the repository + ./isaaclab.sh -p -m tensorboard.main --logdir logs/sb3/Isaac-Cartpole-v0 + +Playing the trained agent +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Once the training is complete, you can visualize the trained agent by executing the following command: + +.. code:: bash + + # execute from the root directory of the repository + ./isaaclab.sh play --rl_library sb3 --task Isaac-Cartpole-v0 --num_envs 32 --viz kit + +The above command will load the latest checkpoint from the ``logs/sb3/Isaac-Cartpole-v0`` +directory. You can also specify a specific checkpoint by passing the ``--checkpoint`` flag. + +.. _Stable-Baselines3: https://stable-baselines3.readthedocs.io/en/master/ +.. _VecEnv API: https://stable-baselines3.readthedocs.io/en/master/guide/vec_envs.html#vecenv-api-vs-gym-api +.. _`stable_baselines3.common.vec_env.VecNormalize`: https://stable-baselines3.readthedocs.io/en/master/guide/vec_envs.html#vecnormalize +.. _RL-Games: https://github.com/Denys88/rl_games +.. _RSL-RL: https://github.com/leggedrobotics/rsl_rl +.. _SKRL: https://skrl.readthedocs.io diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/04_sensors/add_sensors_on_robot.rst b/simulation/modules/IsaacLab/docs/source/tutorials/04_sensors/add_sensors_on_robot.rst new file mode 100644 index 0000000000000000000000000000000000000000..da5d180545949dd46dca91c37fa369f0057cad57 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/04_sensors/add_sensors_on_robot.rst @@ -0,0 +1,210 @@ +.. _tutorial-add-sensors-on-robot: + +Adding sensors on a robot +========================= + +.. currentmodule:: isaaclab + + +While the asset classes allow us to create and simulate the physical embodiment of the robot, +sensors help in obtaining information about the environment. They typically update at a lower +frequency than the simulation and are useful for obtaining different proprioceptive and +exteroceptive information. For example, a camera sensor can be used to obtain the visual +information of the environment, and a contact sensor can be used to obtain the contact +information of the robot with the environment. + +In this tutorial, we will see how to add different sensors to a robot. We will use the +ANYmal-C robot for this tutorial. The ANYmal-C robot is a quadrupedal robot with 12 degrees +of freedom. It has 4 legs, each with 3 degrees of freedom. The robot has the following +sensors: + +- A camera sensor on the head of the robot which provides RGB-D images +- A height scanner sensor that provides terrain height information +- Contact sensors on the feet of the robot that provide contact information + +We continue this tutorial from the previous tutorial on :ref:`tutorial-interactive-scene`, +where we learned about the :class:`scene.InteractiveScene` class. + + +The Code +~~~~~~~~ + +The tutorial corresponds to the ``add_sensors_on_robot.py`` script in the +``scripts/tutorials/04_sensors`` directory. + +.. dropdown:: Code for add_sensors_on_robot.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/04_sensors/add_sensors_on_robot.py + :language: python + :emphasize-lines: 72-95, 143-153, 167-168 + :linenos: + + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +Similar to the previous tutorials, where we added assets to the scene, the sensors are also added +to the scene using the scene configuration. All sensors inherit from the :class:`sensors.SensorBase` class +and are configured through their respective config classes. Each sensor instance can define its own +update period, which is the frequency at which the sensor is updated. The update period is specified +in seconds through the :attr:`sensors.SensorBaseCfg.update_period` attribute. + +Depending on the specified path and the sensor type, the sensors are attached to the prims in the scene. +They may have an associated prim that is created in the scene or they may be attached to an existing prim. +For instance, the camera sensor has a corresponding prim that is created in the scene, whereas for the +contact sensor, activating the contact reporting is a property on a rigid body prim. + +In the following, we introduce the different sensors we use in this tutorial and how they are configured. +For more description about them, please check the :mod:`sensors` module. + +Camera sensor +------------- + +A camera is defined using the :class:`sensors.CameraCfg`. It is based on the USD Camera sensor and +the different data types are captured using Omniverse Replicator API. Since it has a corresponding prim +in the scene, the prims are created in the scene at the specified prim path. + +The configuration of the camera sensor includes the following parameters: + +* :attr:`~sensors.CameraCfg.spawn`: The type of USD camera to create. This can be either + :class:`~sim.spawners.sensors.PinholeCameraCfg` or :class:`~sim.spawners.sensors.FisheyeCameraCfg`. +* :attr:`~sensors.CameraCfg.offset`: The offset of the camera sensor from the parent prim. +* :attr:`~sensors.CameraCfg.data_types`: The data types to capture. This can be ``rgb``, + ``distance_to_image_plane``, ``normals``, or other types supported by the USD Camera sensor. + +To attach an RGB-D camera sensor to the head of the robot, we specify an offset relative to the base +frame of the robot. The offset is specified as a translation and rotation relative to the base frame, +and the :attr:`~sensors.CameraCfg.OffsetCfg.convention` in which the offset is specified. + +In the following, we show the configuration of the camera sensor used in this tutorial. We set the +update period to 0.1s, which means that the camera sensor is updated at 10Hz. The prim path expression is +set to ``{ENV_REGEX_NS}/Robot/base/front_cam`` where the ``{ENV_REGEX_NS}`` is the environment namespace, +``"Robot"`` is the name of the robot, ``"base"`` is the name of the prim to which the camera is attached, +and ``"front_cam"`` is the name of the prim associated with the camera sensor. + +.. literalinclude:: ../../../../scripts/tutorials/04_sensors/add_sensors_on_robot.py + :language: python + :start-at: camera = CameraCfg( + :end-before: height_scanner = RayCasterCfg( + +Height scanner +-------------- + +The height-scanner is implemented as a virtual sensor using the NVIDIA Warp ray-casting kernels. +Through the :class:`sensors.RayCasterCfg`, we can specify the pattern of rays to cast and the +meshes against which to cast the rays. By default, :attr:`~sensors.RayCasterCfg.spawn` creates +a plain USD Xform at :attr:`~sensors.RayCasterCfg.prim_path` to serve as the sensor's +attachment frame, similar to how :class:`sensors.CameraCfg` spawns a Camera prim. + +For this tutorial, the ray-cast based height scanner is attached under the base frame of the robot. +The pattern of rays is specified using the :attr:`~sensors.RayCasterCfg.pattern` attribute. For +a uniform grid pattern, we specify the pattern using :class:`~sensors.patterns.GridPatternCfg`. +Since we only care about the height information, we do not need to consider the roll and pitch +of the robot. Hence, we set the :attr:`~sensors.RayCasterCfg.ray_alignment` to "yaw". + +For the height-scanner, you can visualize the points where the rays hit the mesh. This is done +by setting the :attr:`~sensors.SensorBaseCfg.debug_vis` attribute to true. + +The entire configuration of the height-scanner is as follows: + +.. literalinclude:: ../../../../scripts/tutorials/04_sensors/add_sensors_on_robot.py + :language: python + :start-at: height_scanner = RayCasterCfg( + :end-before: contact_forces = ContactSensorCfg( + +Contact sensor +-------------- + +Contact sensors wrap around the PhysX contact reporting API to obtain the contact information of the robot +with the environment. Since it relies of PhysX, the contact sensor expects the contact reporting API +to be enabled on the rigid bodies of the robot. This can be done by setting the +:attr:`~sim.spawners.RigidObjectSpawnerCfg.activate_contact_sensors` to true in the asset configuration. + +Through the :class:`sensors.ContactSensorCfg`, it is possible to specify the prims for which we want to +obtain the contact information. Additional flags can be set to obtain more information about +the contact, such as the contact air time, contact forces between filtered prims, etc. + +In this tutorial, we attach the contact sensor to the feet of the robot. The feet of the robot are +named ``"LF_FOOT"``, ``"RF_FOOT"``, ``"LH_FOOT"``, and ``"RH_FOOT"``. We pass a Regex expression +``".*_FOOT"`` to simplify the prim path specification. This Regex expression matches all prims that +end with ``"_FOOT"``. + +We set the update period to 0 to update the sensor at the same frequency as the simulation. Additionally, +for contact sensors, we can specify the history length of the contact information to store. For this +tutorial, we set the history length to 6, which means that the contact information for the last 6 +simulation steps is stored. + +The entire configuration of the contact sensor is as follows: + +.. literalinclude:: ../../../../scripts/tutorials/04_sensors/add_sensors_on_robot.py + :language: python + :start-at: contact_forces = ContactSensorCfg( + :lines: 1-3 + +Running the simulation loop +--------------------------- + +Similar to when using assets, the buffers and physics handles for the sensors are initialized only +when the simulation is played, i.e., it is important to call ``sim.reset()`` after creating the scene. + +.. literalinclude:: ../../../../scripts/tutorials/04_sensors/add_sensors_on_robot.py + :language: python + :start-at: # Play the simulator + :end-at: sim.reset() + +Besides that, the simulation loop is similar to the previous tutorials. The sensors are updated as part +of the scene update and they internally handle the updating of their buffers based on their update +periods. + +The data from the sensors can be accessed through their ``data`` attribute. As an example, we show how +to access the data for the different sensors created in this tutorial: + +.. literalinclude:: ../../../../scripts/tutorials/04_sensors/add_sensors_on_robot.py + :language: python + :start-at: # print information from the sensors + :end-at: print("Received max contact force of: ", torch.max(scene["contact_forces"].data.net_forces_w).item()) + + +The Code Execution +~~~~~~~~~~~~~~~~~~ + + +Now that we have gone through the code, let's run the script and see the result: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tutorials/04_sensors/add_sensors_on_robot.py --num_envs 2 --enable_cameras --viz kit + + +This command should open a stage with a ground plane, lights, and two quadrupedal robots. +Around the robots, you should see red spheres that indicate the points where the rays hit the mesh. +Additionally, you can switch the viewport to the camera view to see the RGB image captured by the +camera sensor. Please check `here `_ for more information +on how to switch the viewport to the camera view. + +.. figure:: ../../_static/tutorials/tutorial_add_sensors. jpg + :align: center + :figwidth: 100% + :alt: result of add_sensors_on_robot.py + +To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal. + +While in this tutorial, we went over creating and using different sensors, there are many more sensors +available in the :mod:`sensors` module. We include minimal examples of using these sensors in the +``scripts/tutorials/04_sensors`` directory. For completeness, these scripts can be run using the +following commands: + +.. code-block:: bash + + # Frame Transformer + ./isaaclab.sh -p scripts/tutorials/04_sensors/run_frame_transformer.py --viz kit + + # Ray Caster + ./isaaclab.sh -p scripts/tutorials/04_sensors/run_ray_caster.py --viz kit + + # Ray Caster Camera + ./isaaclab.sh -p scripts/tutorials/04_sensors/run_ray_caster_camera.py --viz kit + + # USD Camera + ./isaaclab.sh -p scripts/tutorials/04_sensors/run_usd_camera.py --enable_cameras --viz kit diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/05_controllers/run_diff_ik.rst b/simulation/modules/IsaacLab/docs/source/tutorials/05_controllers/run_diff_ik.rst new file mode 100644 index 0000000000000000000000000000000000000000..dda5568c0f41d122b2431f73e132c3cdfbd085a1 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/05_controllers/run_diff_ik.rst @@ -0,0 +1,159 @@ +Using a task-space controller +============================= + +.. currentmodule:: isaaclab + +In the previous tutorials, we have joint-space controllers to control the robot. However, in many +cases, it is more intuitive to control the robot using a task-space controller. For example, if we +want to teleoperate the robot, it is easier to specify the desired end-effector pose rather than +the desired joint positions. + +In this tutorial, we will learn how to use a task-space controller to control the robot. +We will use the :class:`controllers.DifferentialIKController` class to track a desired +end-effector pose command. + + +The Code +~~~~~~~~ + +The tutorial corresponds to the ``run_diff_ik.py`` script in the +``scripts/tutorials/05_controllers`` directory. + + +.. dropdown:: Code for run_diff_ik.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/05_controllers/run_diff_ik.py + :language: python + :emphasize-lines: 98-100, 121-136, 155-157, 161-171 + :linenos: + + +The Code Explained +~~~~~~~~~~~~~~~~~~ + +While using any task-space controller, it is important to ensure that the provided +quantities are in the correct frames. When parallelizing environment instances, they are +all existing in the same unique simulation world frame. However, typically, we want each +environment itself to have its own local frame. This is accessible through the +:attr:`scene.InteractiveScene.env_origins` attribute. + +In our APIs, we use the following notation for frames: + +- The simulation world frame (denoted as ``w``), which is the frame of the entire simulation. +- The local environment frame (denoted as ``e``), which is the frame of the local environment. +- The robot's base frame (denoted as ``b``), which is the frame of the robot's base link. + +Since the asset instances are not "aware" of the local environment frame, they return +their states in the simulation world frame. Thus, we need to convert the obtained +quantities to the local environment frame. This is done by subtracting the local environment +origin from the obtained quantities. + + +Creating an IK controller +------------------------- + +The :class:`~controllers.DifferentialIKController` class computes the desired joint +positions for a robot to reach a desired end-effector pose. The included implementation +performs the computation in a batched format and uses PyTorch operations. It supports +different types of inverse kinematics solvers, including the damped least-squares method +and the pseudo-inverse method. These solvers can be specified using the +:attr:`~controllers.DifferentialIKControllerCfg.ik_method` argument. +Additionally, the controller can handle commands as both relative and absolute poses. + +In this tutorial, we will use the damped least-squares method to compute the desired +joint positions. Additionally, since we want to track desired end-effector poses, we +will use the absolute pose command mode. + +.. literalinclude:: ../../../../scripts/tutorials/05_controllers/run_diff_ik.py + :language: python + :start-at: # Create controller + :end-at: diff_ik_controller = DifferentialIKController(diff_ik_cfg, num_envs=scene.num_envs, device=sim.device) + +Obtaining the robot's joint and body indices +-------------------------------------------- + +The IK controller implementation is a computation-only class. Thus, it expects the +user to provide the necessary information about the robot. This includes the robot's +joint positions, current end-effector pose, and the Jacobian matrix. + +While the attribute :attr:`assets.ArticulationData.joint_pos` provides the joint positions, +we only want the joint positions of the robot's arm, and not the gripper. Similarly, while +the attribute :attr:`assets.ArticulationData.body_state_w` provides the state of all the +robot's bodies, we only want the state of the robot's end-effector. Thus, we need to +index into these arrays to obtain the desired quantities. + +For this, the articulation class provides the methods :meth:`~assets.Articulation.find_joints` +and :meth:`~assets.Articulation.find_bodies`. These methods take in the names of the joints +and bodies and return their corresponding indices. + +While you may directly use these methods to obtain the indices, we recommend using the +:attr:`~managers.SceneEntityCfg` class to resolve the indices. This class is used in various +places in the APIs to extract certain information from a scene entity. Internally, it +calls the above methods to obtain the indices. However, it also performs some additional +checks to ensure that the provided names are valid. Thus, it is a safer option to use +this class. + +.. literalinclude:: ../../../../scripts/tutorials/05_controllers/run_diff_ik.py + :language: python + :start-at: # Specify robot-specific parameters + :end-before: # Define simulation stepping + + +Computing robot command +----------------------- + +The IK controller separates the operation of setting the desired command and +computing the desired joint positions. This is done to allow for the user to +run the IK controller at a different frequency than the robot's control frequency. + +The :meth:`~controllers.DifferentialIKController.set_command` method takes in +the desired end-effector pose as a single batched array. The pose is specified in +the robot's base frame. + +.. literalinclude:: ../../../../scripts/tutorials/05_controllers/run_diff_ik.py + :language: python + :start-at: # reset controller + :end-at: diff_ik_controller.set_command(ik_commands) + +We can then compute the desired joint positions using the +:meth:`~controllers.DifferentialIKController.compute` method. +The method takes in the current end-effector pose (in base frame), Jacobian, and +current joint positions. We read the Jacobian matrix from the robot's data, which uses +its value computed from the physics engine. + + +.. literalinclude:: ../../../../scripts/tutorials/05_controllers/run_diff_ik.py + :language: python + :start-at: # obtain quantities from simulation + :end-at: joint_pos_des = diff_ik_controller.compute(ee_pos_b, ee_quat_b, jacobian, joint_pos) + +The computed joint position targets can then be applied on the robot, as done in the +previous tutorials. + +.. literalinclude:: ../../../../scripts/tutorials/05_controllers/run_diff_ik.py + :language: python + :start-at: # apply actions + :end-at: scene.write_data_to_sim() + + +The Code Execution +~~~~~~~~~~~~~~~~~~ + + +Now that we have gone through the code, let's run the script and see the result: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tutorials/05_controllers/run_diff_ik.py --robot franka_panda --num_envs 128 + +The script will start a simulation with 128 robots. The robots will be controlled using the IK controller. +The current and desired end-effector poses should be displayed using frame markers. When the robot reaches +the desired pose, the command should cycle through to the next pose specified in the script. + +.. figure:: ../../_static/tutorials/tutorial_task_space_controller.jpg + :align: center + :figwidth: 100% + :alt: result of run_diff_ik.py + +To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal. diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/05_controllers/run_osc.rst b/simulation/modules/IsaacLab/docs/source/tutorials/05_controllers/run_osc.rst new file mode 100644 index 0000000000000000000000000000000000000000..b8dbab6ae347b47c126143001634b2d6af6a2896 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/05_controllers/run_osc.rst @@ -0,0 +1,191 @@ +Using an operational space controller +===================================== + +.. currentmodule:: isaaclab + +Sometimes, controlling the end-effector pose of the robot using a differential IK controller is not sufficient. +For example, we might want to enforce a very specific pose tracking error dynamics in the task space, actuate the robot +with joint effort/torque commands, or apply a contact force at a specific direction while controlling the motion of +the other directions (e.g., washing the surface of the table with a cloth). In such tasks, we can use an +operational space controller (OSC). + +.. rubric:: References for the operational space control: + +1. O Khatib. A unified approach for motion and force control of robot manipulators: + The operational space formulation. IEEE Journal of Robotics and Automation, 3(1):43–53, 1987. URL http://dx.doi.org/10.1109/JRA.1987.1087068. + +2. Robot Dynamics Lecture Notes by Marco Hutter (ETH Zurich). URL https://ethz.ch/content/dam/ethz/special-interest/mavt/robotics-n-intelligent-systems/rsl-dam/documents/RobotDynamics2017/RD_HS2017script.pdf + +In this tutorial, we will learn how to use an OSC to control the robot. +We will use the :class:`controllers.OperationalSpaceController` class to apply a constant force perpendicular to a +tilted wall surface while tracking a desired end-effector pose in all the other directions. + +The Code +~~~~~~~~ + +The tutorial corresponds to the ``run_osc.py`` script in the +``scripts/tutorials/05_controllers`` directory. + + +.. dropdown:: Code for run_osc.py + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/05_controllers/run_osc.py + :language: python + :linenos: + + +Creating an Operational Space Controller +---------------------------------------- + +The :class:`~controllers.OperationalSpaceController` class computes the joint +efforts/torques for a robot to do simultaneous motion and force control in task space. + +The reference frame of this task space could be an arbitrary coordinate frame in Euclidean space. By default, +it is the robot's base frame. However, in certain cases, it could be easier to define target coordinates w.r.t. a +different frame. In such cases, the pose of this task reference frame, w.r.t. to the robot's base frame, should be +provided in the ``set_command`` method's ``current_task_frame_pose_b`` argument. For example, in this tutorial, it +makes sense to define the target commands w.r.t. a frame that is parallel to the wall surface, as the force control +direction would be then only nonzero in the z-axis of this frame. The target pose, which is set to have the same +orientation as the wall surface, is such a candidate and is used as the task frame in this tutorial. Therefore, all +the arguments to the :class:`~controllers.OperationalSpaceControllerCfg` should be set with this task reference frame +in mind. + +For the motion control, the task space targets could be given as absolute (i.e., defined w.r.t. the robot base, +``target_types: "pose_abs"``) or relative the the end-effector's current pose (i.e., ``target_types: "pose_rel"``). +For the force control, the task space targets could be given as absolute (i.e., defined w.r.t. the robot base, +``target_types: "force_abs"``). If it is desired to apply pose and force control simultaneously, the ``target_types`` +should be a list such as ``["pose_abs", "wrench_abs"]`` or ``["pose_rel", "wrench_abs"]``. + +The axes that the motion and force control will be applied can be specified using the ``motion_control_axes_task`` and +``force_control_axes_task`` arguments, respectively. These lists should consist of 0/1 for all six axes (position and +rotation) and be complementary to each other (e.g., for the x-axis, if the ``motion_control_axes_task`` is ``0``, the +``force_control_axes_task`` should be ``1``). + +For the motion control axes, desired stiffness, and damping ratio values can be specified using the +``motion_control_stiffness`` and ``motion_damping_ratio_task`` arguments, which can be a scalar (same value for all +axes) or a list of six scalars, one value corresponding to each axis. If desired, the stiffness and damping ratio +values could be a command parameter (e.g., to learn the values using RL or change them on the go). For this, +``impedance_mode`` should be either ``"variable_kp"`` to include the stiffness values within the command or +``"variable"`` to include both the stiffness and damping ratio values. In these cases, ``motion_stiffness_limits_task`` +and ``motion_damping_limits_task`` should be set as well, which puts bounds on the stiffness and damping ratio values. + +For contact force control, it is possible to apply an open-loop force control by not setting the +``contact_wrench_stiffness_task``, or apply a closed-loop force control (with the feed-forward term) by setting +the desired stiffness values using the ``contact_wrench_stiffness_task`` argument, which can be a scalar or a list +of six scalars. Please note that, currently, only the linear part of the contact wrench (hence the first three +elements of the ``contact_wrench_stiffness_task``) is considered in the closed-loop control, as the rotational part +cannot be measured with the contact sensors. + +For the motion control, ``inertial_dynamics_decoupling`` should be set to ``True`` to use the robot's inertia matrix +to decouple the desired accelerations in the task space. This is important for the motion control to be accurate, +especially for rapid movements. This inertial decoupling accounts for the coupling between all the six motion axes. +If desired, the inertial coupling between the translational and rotational axes could be ignored by setting the +``partial_inertial_dynamics_decoupling`` to ``True``. + +If it is desired to include the gravity compensation in the operational space command, the ``gravity_compensation`` +should be set to ``True``. + +A final consideration regarding the operational space control is what to do with the null-space of redundant robots. +The null-space is the subspace of the joint space that does not affect the task space coordinates. If nothing is done +to control the null-space, the robot joints will float without moving the end-effector. This might be undesired (e.g., +the robot joints might get close to their limits), and one might want to control the robot behaviour within its +null-space. One way to do is to set ``nullspace_control`` to ``"position"`` (by default it is ``"none"``) which +integrates a null-space PD controller to attract the robot joints to desired targets without affecting the task +space. The behaviour of this null-space controller can be defined using the ``nullspace_stiffness`` and +``nullspace_damping_ratio`` arguments. Please note that theoretical decoupling of the null-space and task space +accelerations is only possible when ``inertial_dynamics_decoupling`` is set to ``True`` and +``partial_inertial_dynamics_decoupling`` is set to ``False``. + +The included OSC implementation performs the computation in a batched format and uses PyTorch operations. + +In this tutorial, we will use ``"pose_abs"`` for controlling the motion in all axes except the z-axis and +``"wrench_abs"`` for controlling the force in the z-axis. Moreover, we will include the full inertia decoupling in +the motion control and not include the gravity compensation, as the gravity is disabled from the robot configuration. +We set the impedance mode to ``"variable_kp"`` to dynamically change the stiffness values +(``motion_damping_ratio_task`` is set to ``1``: the kd values adapt according to kp values to maintain a critically +damped response). Finally, ``nullspace_control`` is set to use ``"position"`` where the joint set points are provided +to be the center of the joint position limits. + +.. literalinclude:: ../../../../scripts/tutorials/05_controllers/run_osc.py + :language: python + :start-at: # Create the OSC + :end-at: osc = OperationalSpaceController(osc_cfg, num_envs=scene.num_envs, device=sim.device) + +Updating the states of the robot +-------------------------------------------- + +The OSC implementation is a computation-only class. Thus, it expects the user to provide the necessary information +about the robot. This includes the robot's Jacobian matrix, mass/inertia matrix, end-effector pose, velocity, contact +force (all in the root frame), and finally, the joint positions and velocities. Moreover, the user should provide +gravity compensation vector and null-space joint position targets if required. + +.. literalinclude:: ../../../../scripts/tutorials/05_controllers/run_osc.py + :language: python + :start-at: # Update robot states + :end-before: # Update the target commands + + +Computing robot command +----------------------- + +The OSC separates the operation of setting the desired command and computing the desired joint positions. +To set the desired command, the user should provide command vector, which includes the target commands +(i.e., in the order they appear in the ``target_types`` argument of the OSC configuration), +and the desired stiffness and damping ratio values if the impedance_mode is set to ``"variable_kp"`` or ``"variable"``. +They should be all in the same coordinate frame as the task frame (e.g., indicated with ``_task`` subscript) and +concatanated together. + +In this tutorial, the desired wrench is already defined w.r.t. the task frame, and the desired pose is transformed +to the task frame as the following: + +.. literalinclude:: ../../../../scripts/tutorials/05_controllers/run_osc.py + :language: python + :start-at: # Convert the target commands to the task frame + :end-at: return command, task_frame_pose_b + +The OSC command is set with the command vector in the task frame, the end-effector pose in the base frame, and the +task (reference) frame pose in the base frame as the following. This information is needed, as the internal +computations are done in the base frame. + +.. literalinclude:: ../../../../scripts/tutorials/05_controllers/run_osc.py + :language: python + :start-at: # set the osc command + :end-at: osc.set_command(command=command, current_ee_pose_b=ee_pose_b, current_task_frame_pose_b=task_frame_pose_b) + +The joint effort/torque values are computed using the provided robot states and the desired command as the following: + +.. literalinclude:: ../../../../scripts/tutorials/05_controllers/run_osc.py + :language: python + :start-at: # compute the joint commands + :end-at: ) + + +The computed joint effort/torque targets can then be applied on the robot. + +.. literalinclude:: ../../../../scripts/tutorials/05_controllers/run_osc.py + :language: python + :start-at: # apply actions + :end-at: robot.write_data_to_sim() + + +The Code Execution +~~~~~~~~~~~~~~~~~~ + +You can now run the script and see the result: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tutorials/05_controllers/run_osc.py --num_envs 128 + +The script will start a simulation with 128 robots. The robots will be controlled using the OSC. +The current and desired end-effector poses should be displayed using frame markers in addition to the red tilted wall. +You should see that the robot reaches the desired pose while applying a constant force perpendicular to the wall +surface. + +.. figure:: ../../_static/tutorials/tutorial_operational_space_controller.jpg + :align: center + :figwidth: 100% + :alt: result of run_osc.py + +To stop the simulation, you can either close the window or press ``Ctrl+C`` in the terminal. diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/06_exporting/exporting_direct_workflow_policies_with_leapp.rst b/simulation/modules/IsaacLab/docs/source/tutorials/06_exporting/exporting_direct_workflow_policies_with_leapp.rst new file mode 100644 index 0000000000000000000000000000000000000000..682f2cafdb407efcb24f2e15935a22788b09f845 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/06_exporting/exporting_direct_workflow_policies_with_leapp.rst @@ -0,0 +1,245 @@ +Exporting Direct Workflow Policies with LEAPP +============================================= + +.. currentmodule:: isaaclab + +This tutorial shows how to prepare a Direct workflow policy for export with +LEAPP. If your policy is manager-based, use the +:doc:`manager-based LEAPP export guide ` +instead. + +For background on LEAPP concepts, supported node patterns, state feedback, and +runtime validation, see the `LEAPP documentation `__. + + +Overview +~~~~~~~~ + +To export a Direct workflow policy with LEAPP, you add LEAPP annotations to the +environment code. During export, LEAPP traces the annotated tensors and builds an +intermediate representation of the full policy pipeline. These annotations remain +dormant during normal environment execution and only add a small amount of +overhead until export time. They are activated by +``scripts/reinforcement_learning/leapp/rsl_rl/export.py`` when you run the export flow. + +This tutorial uses ``scripts/tutorials/06_deploy/anymal_c_env.py`` as a concrete +example of adding LEAPP annotations to a Direct workflow environment. Apply the same +annotation pattern to your own Direct RL environment. + +This export flow requires ``leapp>=0.5.2``. Before exporting, install LEAPP into +the Isaac Lab Python environment: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + ./isaaclab.sh -p -m pip install leapp + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + isaaclab.bat -p -m pip install leapp + +If you want to run the exported example with the existing +``Isaac-Velocity-Rough-Anymal-C-Direct-v0`` task registration, copy the annotated +tutorial environment into the task package: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + cp scripts/tutorials/06_deploy/anymal_c_env.py \ + source/isaaclab_tasks/isaaclab_tasks/direct/anymal_c/anymal_c_env.py + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + copy scripts\tutorials\06_deploy\anymal_c_env.py ^ + source\isaaclab_tasks\isaaclab_tasks\direct\anymal_c\anymal_c_env.py + +After your environment includes the required LEAPP input, output, and state +annotations, export a trained policy with: + +.. tab-set:: + :sync-group: os + + .. tab-item:: :icon:`fa-brands fa-linux` Linux + :sync: linux + + .. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/leapp/rsl_rl/export.py \ + --task \ + --checkpoint \ + --export_save_path + + .. tab-item:: :icon:`fa-brands fa-windows` Windows + :sync: windows + + .. code-block:: batch + + isaaclab.bat -p scripts\reinforcement_learning\leapp\rsl_rl\export.py ^ + --task ^ + --checkpoint ^ + --export_save_path + +The ``--task`` argument is the registered task name, such as +``Isaac-Velocity-Rough-Anymal-C-Direct-v0``. The ``--checkpoint`` argument +points to the trained RSL-RL checkpoint to export. The optional +``--export_save_path`` argument selects the output directory for the exported +artifacts. If you omit it, the export is written next to the checkpoint. + +.. warning:: + + This tutorial covers exporting direct rl policies only. direct rl + policies are not currently supported by + ``scripts/reinforcement_learning/leapp/deploy.py``. + +For more information on the export arguments, see the +:doc:`manager-based LEAPP export guide `. + + +.. dropdown:: Full example script + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/06_deploy/anymal_c_env.py + :language: python + :emphasize-lines: 20, 75-77, 92-107 + :linenos: + + +How the Annotations Work +~~~~~~~~~~~~~~~~~~~~~~~~ + +The main task is to identify the inputs, outputs, and persistent state in the +environment and register them with LEAPP. In this example, the script uses four +annotation helpers: + +- :func:`annotate.input_tensors` marks tensors that enter the policy pipeline. +- :func:`annotate.output_tensors` marks tensors that leave the environment-side + part of the pipeline. +- :func:`annotate.state_tensors` marks tensors that behave like persistent state. +- :func:`annotate.update_state` updates that persistent state after each step. + + +Input Annotations +~~~~~~~~~~~~~~~~~ + +Input annotations usually belong in ``_get_observations()``, because that method +collects the tensors that are passed to the policy. + + +.. literalinclude:: ../../../../scripts/tutorials/06_deploy/anymal_c_env.py + :language: python + :start-at: # start LEAPP annotations for inputs + :end-at: # end LEAPP annotations for inputs + :dedent: 8 + +``annotate.input_tensors()`` wraps a tensor so LEAPP can trace all downstream +operations that depend on it. The function takes two important arguments: + +- ``self.spec.id`` identifies the node that owns the tensor. When you use + ``export.py``, this ID matches the exported policy node. +- The second argument is a dictionary that maps a unique tensor name to the + tensor itself. LEAPP uses these names in the exported metadata and for + debugging. + +In this example, the observation tensors are registered one by one for +readability, but ``annotate.input_tensors()`` can also register multiple tensors +in a single call. + +.. note:: + Any inputs not explicitly annotated will be automatically inlined as a constant. + This may be desired for certain values such as constant transforms or default values. + + +Output Annotations +~~~~~~~~~~~~~~~~~~ + +Output annotations should be placed where the environment has finished preparing +the command that will be applied to the robot. In this example, that happens in +``_pre_physics_step()``. + +.. literalinclude:: ../../../../scripts/tutorials/06_deploy/anymal_c_env.py + :language: python + :start-at: # start LEAPP annotations for outputs + :end-at: # end LEAPP annotations for outputs + :dedent: 8 + +``annotate.output_tensors()`` marks the tensors that leave the environment-side +part of the pipeline. As with input annotations, the call uses ``self.spec.id`` +together with a dictionary that maps tensor names to tensors. + +The ``export_with`` argument restricts an output annotation to specific +export backends. The supported backend names are ``onnx-dynamo``, ``onnx-torchscript``, +``jit-script``, and ``jit-trace``. This argument is needed to actually generate the IR +based on the tracing. + +Unlike ``annotate.input_tensors()``, output annotation should happen once for the +final outputs of the pipeline stage. In this example, ``processed_actions`` is +the tensor that should be exported. After calling +``annotate.output_tensors()``, you do not need to use a return value. + +.. note:: + All tensors passed to ``annotate.output_tensors()`` must be traced tensors. + These tensors are created from inputs or tensors derived from inputs. + +.. warning:: + + Do not place output annotations in ``_apply_action()``. That method may be + called multiple times per environment step, depending on the decimation + setting, which would make the traced pipeline incorrect. + + +State Annotations +~~~~~~~~~~~~~~~~~ + +If your policy depends on internal state or feedback loops, register that data +explicitly with ``annotate.state_tensors()`` and update it with +``annotate.update_state()``. + +In this example, the environment uses the previous action as part of the +observation. That makes ``previous_actions`` a feedback state: + +- ``annotate.state_tensors()`` is called in ``_get_observations()`` so the state + can participate in the traced observation pipeline. +- ``annotate.update_state()`` is called in ``_pre_physics_step()`` so the stored + value is updated for the next step. + +The state name must match across both calls. Here, both functions use the name +``previous_actions``, which lets LEAPP route the feedback tensor correctly. + + +Semantic Annotations +~~~~~~~~~~~~~~~~~~~~ + +This example covers the minimum annotations needed to trace the pipeline. In +more advanced export workflows, you may also want to attach semantic metadata +so downstream runtimes know what each tensor represents. + +For direct environments, semantic annotations are optional and should be +authored explicitly by the user. Unlike the manager-based export path, Isaac Lab +does not infer tensor semantics automatically for direct environments, instead it +is up to the user to provide this data. LEAPP provides this through +``TensorSemantics``. You can use it to describe the meaning of tensors more +precisely and make the exported pipeline easier to inspect, validate, and integrate +into deployment systems. + +.. note:: + + Refer to the `LEAPP semantic annotation guide + `_ + and `LEAPP API reference `_ + for details on authoring semantic annotations. diff --git a/simulation/modules/IsaacLab/docs/source/tutorials/index.rst b/simulation/modules/IsaacLab/docs/source/tutorials/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..41b606e1bf76c9572487be4449ea64414dd55e80 --- /dev/null +++ b/simulation/modules/IsaacLab/docs/source/tutorials/index.rst @@ -0,0 +1,121 @@ +.. _tutorials: + +Tutorials +========= + +Welcome to the Isaac Lab tutorials! These tutorials provide a step-by-step guide to help you understand +and use various features of the framework. All the tutorials are written as Python scripts. You can +find the source code for each tutorial in the ``scripts/tutorials`` directory of the Isaac Lab +repository. + +.. note:: + + We would love to extend the tutorials to cover more topics and use cases, so please let us know if + you have any suggestions. + +We recommend that you go through the tutorials in the order they are listed here. + + +Setting up a Simple Simulation +------------------------------- + +These tutorials show you how to launch the simulation with different settings and spawn objects in the +simulated scene. They cover the following APIs: :class:`~isaaclab.app.AppLauncher`, +:class:`~isaaclab.sim.SimulationContext`, and :class:`~isaaclab.sim.spawners`. + +.. toctree:: + :maxdepth: 1 + :titlesonly: + + 00_sim/create_empty + 00_sim/spawn_prims + 00_sim/launch_app + +Interacting with Assets +----------------------- + +Having spawned objects in the scene, these tutorials show you how to create physics handles for these +objects and interact with them. These revolve around the :class:`~isaaclab.assets.AssetBase` +class and its derivatives such as :class:`~isaaclab.assets.RigidObject`, +:class:`~isaaclab.assets.Articulation` and :class:`~isaaclab.assets.DeformableObject`. + +.. toctree:: + :maxdepth: 1 + :titlesonly: + + 01_assets/add_new_robot + 01_assets/run_rigid_object + 01_assets/run_articulation + 01_assets/run_deformable_object + 01_assets/run_surface_gripper + +Creating a Scene +---------------- + +With the basic concepts of the framework covered, the tutorials move to a more intuitive scene +interface that uses the :class:`~isaaclab.scene.InteractiveScene` class. This class +provides a higher level abstraction for creating scenes easily. + +.. toctree:: + :maxdepth: 1 + :titlesonly: + + 02_scene/create_scene + +Designing an Environment +------------------------ + +The following tutorials introduce the concept of manager-based environments: :class:`~isaaclab.envs.ManagerBasedEnv` +and its derivative :class:`~isaaclab.envs.ManagerBasedRLEnv`, as well as the direct workflow base class +:class:`~isaaclab.envs.DirectRLEnv`. These environments bring-in together +different aspects of the framework to create a simulation environment for agent interaction. + +.. toctree:: + :maxdepth: 1 + :titlesonly: + + 03_envs/create_manager_base_env + 03_envs/create_manager_rl_env + 03_envs/create_direct_rl_env + 03_envs/register_rl_env_gym + 03_envs/run_rl_training + 03_envs/configuring_rl_training + 03_envs/modify_direct_rl_env + 03_envs/policy_inference_in_usd + +Integrating Sensors +------------------- + +The following tutorial shows you how to integrate sensors into the simulation environment. The +tutorials introduce the :class:`~isaaclab.sensors.SensorBase` class and its derivatives +such as :class:`~isaaclab.sensors.Camera` and :class:`~isaaclab.sensors.RayCaster`. + +.. toctree:: + :maxdepth: 1 + :titlesonly: + + 04_sensors/add_sensors_on_robot + +Using motion generators +----------------------- + +While the robots in the simulation environment can be controlled at the joint-level, the following +tutorials show you how to use motion generators to control the robots at the task-level. + +.. toctree:: + :maxdepth: 1 + :titlesonly: + + 05_controllers/run_diff_ik + 05_controllers/run_osc + +Exporting Policies +------------------ + +The following tutorial shows how to prepare a Direct workflow policy for export with LEAPP. + +.. toctree:: + :maxdepth: 1 + :titlesonly: + + 06_exporting/exporting_direct_workflow_policies_with_leapp diff --git a/simulation/modules/IsaacLab/environment.yml b/simulation/modules/IsaacLab/environment.yml new file mode 100644 index 0000000000000000000000000000000000000000..98908d816e289d662af43a202cb05557c882162f --- /dev/null +++ b/simulation/modules/IsaacLab/environment.yml @@ -0,0 +1,12 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +channels: + - conda-forge + - defaults +dependencies: + - python=3.12 + - pip + - importlib_metadata diff --git a/simulation/modules/IsaacLab/greptile.json b/simulation/modules/IsaacLab/greptile.json new file mode 100644 index 0000000000000000000000000000000000000000..1f195339e5b77d1a2d75b8e1a2086c103a15b477 --- /dev/null +++ b/simulation/modules/IsaacLab/greptile.json @@ -0,0 +1,3 @@ +{ + "triggerOnUpdates": false +} diff --git a/simulation/modules/IsaacLab/isaaclab.bat b/simulation/modules/IsaacLab/isaaclab.bat new file mode 100644 index 0000000000000000000000000000000000000000..d977701da05ca494fdffdf21617d463b5171098f --- /dev/null +++ b/simulation/modules/IsaacLab/isaaclab.bat @@ -0,0 +1,49 @@ +@echo off +setlocal EnableExtensions EnableDelayedExpansion + +rem Copyright (c) 2022-2025, The Isaac Lab Project Developers +rem (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +rem All rights reserved. +rem +rem SPDX-License-Identifier: BSD-3-Clause + +set "ISAACLAB_PATH=%~dp0" +rem Remove trailing backslash. +if "%ISAACLAB_PATH:~-1%"=="\" set "ISAACLAB_PATH=%ISAACLAB_PATH:~0,-1%" + +rem Find python to run CLI. +if defined VIRTUAL_ENV ( + set "python_exe=%VIRTUAL_ENV%\Scripts\python.exe" +) else if defined CONDA_PREFIX ( + set "python_exe=%CONDA_PREFIX%\python.exe" +) else if exist "%ISAACLAB_PATH%\_isaac_sim\python.bat" ( + set "python_exe=%ISAACLAB_PATH%\_isaac_sim\python.bat" +) else ( + rem Fallback. + set "python_exe=python" +) + +rem Add source/isaaclab to PYTHONPATH so we can import isaaclab.cli. +set "PYTHONPATH=%ISAACLAB_PATH%\source\isaaclab;%PYTHONPATH%" + +rem Let Kit associate direct wrapper launches with the Isaac Sim desktop icon. +if "%RESOURCE_NAME%"=="" set "RESOURCE_NAME=IsaacSim" + +rem If a local Isaac Sim binary is present, source its env setup so that +rem PYTHONPATH/PATH/EXP_PATH are correct without depending on a conda +rem activate.d hook (those don't fire under e.g. `conda run` on Windows). +if exist "%ISAACLAB_PATH%\_isaac_sim\" ( + if exist "%ISAACLAB_PATH%\_isaac_sim\setup_conda_env.bat" ( + call "%ISAACLAB_PATH%\_isaac_sim\setup_conda_env.bat" >NUL + ) else ( + echo [WARNING] _isaac_sim is present but _isaac_sim\setup_conda_env.bat is missing; Isaac Sim env vars not exported. 1>&2 + echo [WARNING] Re-extract the Isaac Sim Windows zip if you intend to use the bundled binary. 1>&2 + ) +) + +rem Execute CLI. +"%python_exe%" -c "from isaaclab.cli import cli; cli()" %* + +if errorlevel 1 exit /b 1 +endlocal +exit /b 0 diff --git a/simulation/modules/IsaacLab/isaaclab.sh b/simulation/modules/IsaacLab/isaaclab.sh new file mode 100644 index 0000000000000000000000000000000000000000..3a9ca94eb75ecda1e1a4c6bb4228f69e67ecf4e6 --- /dev/null +++ b/simulation/modules/IsaacLab/isaaclab.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash + +# Copyright (c) 2022-2025, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# Exit on error. +set -e + +# Get repo directory. +export ISAACLAB_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" + +# Find python to run CLI. +if [ -n "$VIRTUAL_ENV" ]; then + python_exe="$VIRTUAL_ENV/bin/python" +elif [ -n "$CONDA_PREFIX" ]; then + python_exe="$CONDA_PREFIX/bin/python" +elif [ -f "$ISAACLAB_PATH/env_isaaclab/bin/python" ]; then + python_exe="$ISAACLAB_PATH/env_isaaclab/bin/python" +elif [ -f "$ISAACLAB_PATH/_isaac_sim/python.sh" ]; then + python_exe="$ISAACLAB_PATH/_isaac_sim/python.sh" +else + # Fallback to system python + python_exe="python3" +fi + +# Add source/isaaclab to PYTHONPATH so we can import isaaclab.cli. +export PYTHONPATH="$ISAACLAB_PATH/source/isaaclab:$PYTHONPATH" + +# Let Kit associate direct wrapper launches with the Isaac Sim desktop icon. +export RESOURCE_NAME="${RESOURCE_NAME:-IsaacSim}" + +# If a local Isaac Sim binary is present, source its env setup so that +# PYTHONPATH/PATH/EXP_PATH are correct without depending on a conda +# activate.d hook (those don't fire reliably under e.g. `conda run`). +if [ -d "$ISAACLAB_PATH/_isaac_sim" ]; then + if [ -f "$ISAACLAB_PATH/_isaac_sim/setup_conda_env.sh" ]; then + # shellcheck disable=SC1091 + . "$ISAACLAB_PATH/_isaac_sim/setup_conda_env.sh" >/dev/null 2>&1 || true + else + echo "[WARNING] _isaac_sim is present but _isaac_sim/setup_conda_env.sh is missing; Isaac Sim env vars not exported." >&2 + echo "[WARNING] Re-extract the Isaac Sim binary zip if you intend to use the bundled binary." >&2 + fi +fi + +# Execute CLI. +exec "$python_exe" -c "from isaaclab.cli import cli; cli()" "$@" diff --git a/simulation/modules/IsaacLab/pyproject.toml b/simulation/modules/IsaacLab/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..a0797f74d3ebaa502b29746c41becb9f9f83e7ff --- /dev/null +++ b/simulation/modules/IsaacLab/pyproject.toml @@ -0,0 +1,266 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +[project] +name = "isaaclab-dev" +version = "0.1.0" +description = "Isaac Lab source checkout development environment." +requires-python = ">=3.12,<3.13" +dependencies = [ + "isaaclab", + "isaaclab-assets", + "isaaclab-contrib", + "isaaclab-experimental", + "isaaclab-newton[all]", + "isaaclab-ov", + "isaaclab-ovphysx", + "isaaclab-physx[newton]", + "isaaclab-ppisp", + "isaaclab-rl[rsl-rl]", + "isaaclab-tasks", + "isaaclab-tasks-experimental", + "isaaclab-visualizers", + "torch==2.10.0", + "torchaudio==2.10.0", + "torchvision==0.25.0", +] + +[project.optional-dependencies] +contrib = [ + "isaaclab-contrib", +] +mimic = [ + "isaaclab-mimic", +] +newton = [ + "isaaclab-newton[all]", + "isaaclab-physx[newton]", + "isaaclab-visualizers[newton]", +] +ov = [ + "isaaclab-ovphysx[ovphysx]", +] +rl = [ + "isaaclab-rl[rsl-rl]", +] +rl-all = [ + "isaaclab-rl[all]", +] +rtx = [ + "isaaclab-ov[ovrtx]", +] +all = [ + "isaaclab-mimic", + "isaaclab-newton[all]", + "isaaclab-physx[newton]", + "isaaclab-rl[all]", + "isaaclab-visualizers[all]", +] + +[tool.ruff] +line-length = 120 +target-version = "py310" + +# Exclude directories +extend-exclude = [ + "logs", + "_isaac_sim", + ".vscode", + "_*", + ".git", +] + +[tool.ruff.lint] +# Enable flake8 rules and other useful ones +select = [ + "E", # pycodestyle errors + "W", # pycodestyle warnings + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "C90", # mccabe complexity + # "D", # pydocstyle + "SIM", # flake8-simplify + "RET", # flake8-return +] + +# Ignore specific rules (matching your flake8 config) +ignore = [ + "E402", # Module level import not at top of file + "D401", # First line should be in imperative mood + "RET504", # Unnecessary variable assignment before return statement + "RET505", # Unnecessary elif after return statement + "SIM102", # Use a single if-statement instead of nested if-statements + "SIM103", # Return the negated condition directly + "SIM108", # Use ternary operator instead of if-else statement + "SIM117", # Merge with statements for context managers + "SIM118", # Use {key} in {dict} instead of {key} in {dict}.keys() + "UP006", # Use 'dict' instead of 'Dict' type annotation + "UP018", # Unnecessary `float` call (rewrite as a literal) +] + +[tool.ruff.lint.per-file-ignores] +"__init__.py" = ["F401"] # Allow unused imports in __init__.py files + +[tool.ruff.lint.mccabe] +max-complexity = 30 + +[tool.ruff.lint.pydocstyle] +convention = "google" + +[tool.ruff.lint.isort] + +# Custom import sections with separate sections for each Isaac Lab extension +section-order = [ + "future", + "standard-library", + "third-party", + # Group omniverse extensions separately since they are run-time dependencies + # which are pulled in by Isaac Lab extensions + "omniverse-extensions", + # Group Isaac Lab extensions together since they are all part of the Isaac Lab project + "isaaclab", + "isaaclab-contrib", + "isaaclab-rl", + "isaaclab-mimic", + "isaaclab-tasks", + "isaaclab-assets", + # First-party is reserved for project templates + "first-party", + "local-folder", +] + +[tool.ruff.lint.isort.sections] +# Define what belongs in each custom section + +"omniverse-extensions" = [ + "isaacsim", + "omni", + "pxr", + "carb", + "usdrt", + "Semantics", + "curobo", +] + +"isaaclab" = ["isaaclab"] +"isaaclab-assets" = ["isaaclab_assets"] +"isaaclab-contrib" = ["isaaclab_contrib"] +"isaaclab-rl" = ["isaaclab_rl"] +"isaaclab-mimic" = ["isaaclab_mimic"] +"isaaclab-tasks" = ["isaaclab_tasks"] + +[tool.ruff.format] + +docstring-code-format = true + +[tool.pyright] + +include = ["source", "scripts"] +exclude = [ + "**/__pycache__", + "**/_isaac_sim", + "**/docs", + "**/logs", + ".git", + ".vscode", +] + +typeCheckingMode = "basic" +pythonVersion = "3.12" +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" + + +[tool.codespell] +skip = '*.usd,*.usda,*.usdz,*.svg,*.png,_isaac_sim*,*.bib,*.css,*/_build' +quiet-level = 0 +# the world list should always have words in lower case +ignore-words-list = "haa,slq,collapsable,buss,reacher,thirdparty,segway" + + +[tool.pytest.ini_options] + +markers = [ + "isaacsim_ci: mark test to run in isaacsim ci", +] + +# Add pypi.nvidia.com so that `uv pip install isaaclab[isaacsim]` works without --extra-index-url. +# Pip still needs "--extra-index-url https://pypi.nvidia.com". +[[tool.uv.index]] +url = "https://pypi.nvidia.com" +explicit = false + +[[tool.uv.index]] +name = "pytorch-cu128" +url = "https://download.pytorch.org/whl/cu128" +explicit = true + +[[tool.uv.index]] +name = "pytorch-cu130" +url = "https://download.pytorch.org/whl/cu130" +explicit = true + +# Some NVIDIA-hosted dependencies have mismatched versions across pypi.nvidia.com +# and PyPI. unsafe-best-match lets uv resolve the correct version from any index, +# and prerelease=allow covers packages that only publish pre-release wheels. +[tool.uv] +index-strategy = "unsafe-best-match" +prerelease = "allow" +override-dependencies = ["numpy>=2"] +python-preference = "only-managed" +package = false + +[tool.uv.sources] +isaaclab = { path = "source/isaaclab", editable = true } +"isaaclab-assets" = { path = "source/isaaclab_assets", editable = true } +"isaaclab-contrib" = { path = "source/isaaclab_contrib", editable = true } +"isaaclab-experimental" = { path = "source/isaaclab_experimental", editable = true } +"isaaclab-mimic" = { path = "source/isaaclab_mimic", editable = true } +"isaaclab-newton" = { path = "source/isaaclab_newton", editable = true } +"isaaclab-ov" = { path = "source/isaaclab_ov", editable = true } +"isaaclab-ovphysx" = { path = "source/isaaclab_ovphysx", editable = true } +"isaaclab-physx" = { path = "source/isaaclab_physx", editable = true } +"isaaclab-ppisp" = { path = "source/isaaclab_ppisp", editable = true } +"isaaclab-rl" = { path = "source/isaaclab_rl", editable = true } +"isaaclab-tasks" = { path = "source/isaaclab_tasks", editable = true } +"isaaclab-tasks-experimental" = { path = "source/isaaclab_tasks_experimental", editable = true } +"isaaclab-teleop" = { path = "source/isaaclab_teleop", editable = true } +"isaaclab-visualizers" = { path = "source/isaaclab_visualizers", editable = true } +torch = [ + { index = "pytorch-cu128", marker = "sys_platform == 'linux' and platform_machine == 'x86_64'" }, + { index = "pytorch-cu128", marker = "sys_platform == 'linux' and platform_machine == 'AMD64'" }, + { index = "pytorch-cu128", marker = "sys_platform == 'win32'" }, + { index = "pytorch-cu130", marker = "sys_platform == 'linux' and platform_machine == 'aarch64'" }, + { index = "pytorch-cu130", marker = "sys_platform == 'linux' and platform_machine == 'arm64'" }, +] +torchaudio = [ + { index = "pytorch-cu128", marker = "sys_platform == 'linux' and platform_machine == 'x86_64'" }, + { index = "pytorch-cu128", marker = "sys_platform == 'linux' and platform_machine == 'AMD64'" }, + { index = "pytorch-cu128", marker = "sys_platform == 'win32'" }, + { index = "pytorch-cu130", marker = "sys_platform == 'linux' and platform_machine == 'aarch64'" }, + { index = "pytorch-cu130", marker = "sys_platform == 'linux' and platform_machine == 'arm64'" }, +] +torchvision = [ + { index = "pytorch-cu128", marker = "sys_platform == 'linux' and platform_machine == 'x86_64'" }, + { index = "pytorch-cu128", marker = "sys_platform == 'linux' and platform_machine == 'AMD64'" }, + { index = "pytorch-cu128", marker = "sys_platform == 'win32'" }, + { index = "pytorch-cu130", marker = "sys_platform == 'linux' and platform_machine == 'aarch64'" }, + { index = "pytorch-cu130", marker = "sys_platform == 'linux' and platform_machine == 'arm64'" }, +] + +[tool.uv.pip] +index-strategy = "unsafe-best-match" +prerelease = "allow" diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_cameras.py b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_cameras.py new file mode 100644 index 0000000000000000000000000000000000000000..3d5359ce5d41be655d02d493f7208f16531f54b7 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_cameras.py @@ -0,0 +1,962 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script might help you determine how many cameras your system can realistically run +at different desired settings. + +You can supply different task environments to inject cameras into, or just test a sample scene. +Additionally, you can automatically find the maximum amount of cameras you can run a task with +through the auto-tune functionality. + +.. code-block:: bash + + # Usage with GUI + ./isaaclab.sh -p scripts/benchmarks/benchmark_cameras.py -h + + # Usage with headless + ./isaaclab.sh -p scripts/benchmarks/benchmark_cameras.py -h --headless + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +from collections.abc import Callable +from dataclasses import MISSING + +from isaaclab.app import AppLauncher + +# parse the arguments +args_cli = argparse.Namespace() + +parser = argparse.ArgumentParser(description="This script can help you benchmark how many cameras you could run.") + +""" +The following arguments only need to be supplied for when one wishes +to try injecting cameras into their environment, and automatically determining +the maximum camera count. +""" +parser.add_argument( + "--task", + type=str, + default=None, + required=False, + help="Supply this argument to spawn cameras within an known manager-based task environment.", +) + +parser.add_argument( + "--autotune", + default=False, + action="store_true", + help=( + "Autotuning is only supported for provided task environments." + " Supply this argument to increase the number of environments until a desired threshold is reached." + "Install pynvml in your environment; ./isaaclab.sh -m pip install pynvml" + ), +) + +parser.add_argument( + "--task_num_cameras_per_env", + type=int, + default=1, + help="The number of cameras per environment to use when using a known task.", +) + +parser.add_argument( + "--use_fabric", action="store_true", default=False, help="Enable fabric and use USD I/O operations." +) + +parser.add_argument( + "--autotune_max_percentage_util", + nargs="+", + type=float, + default=[100.0, 80.0, 80.0, 80.0], + required=False, + help=( + "The system utilization percentage thresholds to reach before an autotune is finished. " + "If any one of these limits are hit, the autotune stops." + "Thresholds are, in order, maximum CPU percentage utilization," + "maximum RAM percentage utilization, maximum GPU compute percent utilization, " + "amd maximum GPU memory utilization." + ), +) + +parser.add_argument( + "--autotune_max_camera_count", type=int, default=4096, help="The maximum amount of cameras allowed in an autotune." +) + +parser.add_argument( + "--autotune_camera_count_interval", + type=int, + default=25, + help=( + "The number of cameras to try to add to the environment if the current camera count" + " falls within permitted system resource utilization limits." + ), +) + +""" +The following arguments are shared for when injecting cameras into a task environment, +as well as when creating cameras independent of a task environment. +""" + +parser.add_argument( + "--num_tiled_cameras", + type=int, + default=0, + required=False, + help="Number of tiled cameras to create. For autotuning, this is how many cameras to start with.", +) + +parser.add_argument( + "--num_standard_cameras", + type=int, + default=0, + required=False, + help="Number of standard cameras to create. For autotuning, this is how many cameras to start with.", +) + +parser.add_argument( + "--num_ray_caster_cameras", + type=int, + default=0, + required=False, + help="Number of ray caster cameras to create. For autotuning, this is how many cameras to start with.", +) + +parser.add_argument( + "--tiled_camera_data_types", + nargs="+", + type=str, + default=["rgb", "depth"], + help="The data types rendered by the tiled camera", +) + +parser.add_argument( + "--standard_camera_data_types", + nargs="+", + type=str, + default=["rgb", "distance_to_image_plane", "distance_to_camera"], + help="The data types rendered by the standard camera", +) + +parser.add_argument( + "--ray_caster_camera_data_types", + nargs="+", + type=str, + default=["distance_to_image_plane"], + help="The data types rendered by the ray caster camera.", +) + +parser.add_argument( + "--ray_caster_visible_mesh_prim_paths", + nargs="+", + type=str, + default=["/World/ground"], + help="WARNING: Ray Caster can currently only cast against a single, static, object", +) + +parser.add_argument( + "--convert_depth_to_camera_to_image_plane", + action="store_true", + default=True, + help=( + "Enable undistorting from perspective view (distance to camera data_type)" + "to orthogonal view (distance to plane data_type) for depth." + "This is currently needed to create undisorted depth images/point cloud." + ), +) + +parser.add_argument( + "--keep_raw_depth", + dest="convert_depth_to_camera_to_image_plane", + action="store_false", + help=( + "Disable undistorting from perspective view (distance to camera)" + "to orthogonal view (distance to plane data_type) for depth." + ), +) + +parser.add_argument( + "--height", + type=int, + default=120, + required=False, + help="Height in pixels of cameras", +) + +parser.add_argument( + "--width", + type=int, + default=140, + required=False, + help="Width in pixels of cameras", +) + +parser.add_argument( + "--warm_start_length", + type=int, + default=3, + required=False, + help=( + "Number of steps to run the sim before starting benchmark." + "Needed to avoid blank images at the start of the simulation." + ), +) + +parser.add_argument( + "--experiment_length", + type=int, + default=15, + required=False, + help="Number of steps to average over", +) + +# This argument is only used when a task is not provided. +parser.add_argument( + "--num_objects", + type=int, + default=10, + required=False, + help="Number of objects to spawn into the scene when not using a known task.", +) + +# Benchmark arguments +parser.add_argument( + "--benchmark_backend", + type=str, + default="omniperf", + choices=["json", "osmo", "omniperf", "summary"], + help="Benchmarking backend options, defaults omniperf", +) +parser.add_argument("--output_path", type=str, default=".", help="Path to output benchmark results.") + + +AppLauncher.add_app_launcher_args(parser) +args_cli = parser.parse_args() +args_cli.enable_cameras = True + +if args_cli.autotune: + import pynvml + +if len(args_cli.ray_caster_visible_mesh_prim_paths) > 1: + print("[WARNING]: Ray Casting is only currently supported for a single, static object") +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import random +import time + +import gymnasium as gym +import numpy as np +import psutil +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import RigidObject, RigidObjectCfg +from isaaclab.scene.interactive_scene import InteractiveScene +from isaaclab.sensors import ( + Camera, + CameraCfg, + RayCasterCamera, + RayCasterCameraCfg, + patterns, +) +from isaaclab.test.benchmark import BaseIsaacLabBenchmark, DictMeasurement, SingleMeasurement +from isaaclab.utils.math import orthogonalize_perspective_depth, unproject_depth + +from isaaclab_tasks.utils import load_cfg_from_registry + +""" +Camera Creation +""" + + +def _get_camera_class_name(camera_cfg: type[CameraCfg]) -> str: + """Return the configured camera sensor class name.""" + class_type_field = camera_cfg.__dataclass_fields__["class_type"] + if class_type_field.default is not MISSING: + class_type = class_type_field.default + elif class_type_field.default_factory is not MISSING: + class_type = class_type_field.default_factory() + else: + raise AttributeError(f"{camera_cfg.__name__} has no default class_type.") + + if hasattr(class_type, "__name__"): + return class_type.__name__ + return str(class_type).rsplit(":", maxsplit=1)[-1] + + +def create_camera_base( + camera_cfg: type[CameraCfg], + num_cams: int, + data_types: list[str], + height: int, + width: int, + prim_path: str | None = None, + instantiate: bool = True, +) -> Camera | CameraCfg | None: + """Generalized function to create a camera or tiled camera sensor.""" + # If valid camera settings are provided, create the camera + if num_cams <= 0 or len(data_types) <= 0 or height <= 0 or width <= 0: + return None + + name = _get_camera_class_name(camera_cfg) + cfg = camera_cfg( + prim_path=prim_path if prim_path is not None else f"/World/{name}_.*/{name}", + update_period=0, + height=height, + width=width, + data_types=data_types, + spawn=sim_utils.PinholeCameraCfg( + focal_length=24, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 1e4) + ), + ) + if instantiate: + # Create the necessary prims + for idx in range(num_cams): + sim_utils.create_prim(f"/World/{name}_{idx:02d}", "Xform") + return cfg.class_type(cfg=cfg) + + return cfg + + +def create_tiled_cameras( + num_cams: int = 2, data_types: list[str] | None = None, height: int = 100, width: int = 120 +) -> Camera | None: + if data_types is None: + data_types = ["rgb", "depth"] + """Defines the camera sensor to add to the scene.""" + return create_camera_base( + camera_cfg=CameraCfg, + num_cams=num_cams, + data_types=data_types, + height=height, + width=width, + ) + + +def create_cameras( + num_cams: int = 2, data_types: list[str] | None = None, height: int = 100, width: int = 120 +) -> Camera | None: + """Defines the Standard cameras.""" + if data_types is None: + data_types = ["rgb", "depth"] + return create_camera_base( + camera_cfg=CameraCfg, num_cams=num_cams, data_types=data_types, height=height, width=width + ) + + +def create_ray_caster_cameras( + num_cams: int = 2, + data_types: list[str] = ["distance_to_image_plane"], + mesh_prim_paths: list[str] = ["/World/ground"], + height: int = 100, + width: int = 120, + prim_path: str = "/World/RayCasterCamera_.*/RayCaster", + instantiate: bool = True, +) -> RayCasterCamera | RayCasterCameraCfg | None: + """Create the raycaster cameras; different configuration than Standard/Tiled camera""" + for idx in range(num_cams): + sim_utils.create_prim(f"/World/RayCasterCamera_{idx:02d}/RayCaster", "Xform") + + if num_cams > 0 and len(data_types) > 0 and height > 0 and width > 0: + cam_cfg = RayCasterCameraCfg( + prim_path=prim_path, + mesh_prim_paths=mesh_prim_paths, + update_period=0, + offset=RayCasterCameraCfg.OffsetCfg(pos=(0.0, 0.0, 0.0), rot=(1.0, 0.0, 0.0, 0.0)), + data_types=data_types, + debug_vis=False, + pattern_cfg=patterns.PinholeCameraPatternCfg( + focal_length=24.0, + horizontal_aperture=20.955, + height=480, + width=640, + ), + ) + if instantiate: + return RayCasterCamera(cfg=cam_cfg) + else: + return cam_cfg + + else: + return None + + +def create_tiled_camera_cfg(prim_path: str) -> CameraCfg: + """Grab a simple camera config for injecting into task environments.""" + return create_camera_base( + CameraCfg, + num_cams=args_cli.num_tiled_cameras, + data_types=args_cli.tiled_camera_data_types, + width=args_cli.width, + height=args_cli.height, + prim_path="{ENV_REGEX_NS}/" + prim_path, + instantiate=False, + ) + + +def create_standard_camera_cfg(prim_path: str) -> CameraCfg: + """Grab a simple standard camera config for injecting into task environments.""" + return create_camera_base( + CameraCfg, + num_cams=args_cli.num_standard_cameras, + data_types=args_cli.standard_camera_data_types, + width=args_cli.width, + height=args_cli.height, + prim_path="{ENV_REGEX_NS}/" + prim_path, + instantiate=False, + ) + + +def create_ray_caster_camera_cfg(prim_path: str) -> RayCasterCameraCfg: + """Grab a simple ray caster config for injecting into task environments.""" + return create_ray_caster_cameras( + num_cams=args_cli.num_ray_caster_cameras, + data_types=args_cli.ray_caster_camera_data_types, + width=args_cli.width, + height=args_cli.height, + prim_path="{ENV_REGEX_NS}/" + prim_path, + ) + + +""" +Scene Creation +""" + + +def design_scene( + num_tiled_cams: int = 2, + num_standard_cams: int = 0, + num_ray_caster_cams: int = 0, + tiled_camera_data_types: list[str] | None = None, + standard_camera_data_types: list[str] | None = None, + ray_caster_camera_data_types: list[str] | None = None, + height: int = 100, + width: int = 200, + num_objects: int = 20, + mesh_prim_paths: list[str] = ["/World/ground"], +) -> dict: + """Design the scene.""" + if tiled_camera_data_types is None: + tiled_camera_data_types = ["rgb"] + if standard_camera_data_types is None: + standard_camera_data_types = ["rgb"] + if ray_caster_camera_data_types is None: + ray_caster_camera_data_types = ["distance_to_image_plane"] + + # Populate scene + # -- Ground-plane + cfg = sim_utils.GroundPlaneCfg() + cfg.func("/World/ground", cfg) + # -- Lights + cfg = sim_utils.DistantLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + cfg.func("/World/Light", cfg) + + # Create a dictionary for the scene entities + scene_entities = {} + + # Xform to hold objects + sim_utils.create_prim("/World/Objects", "Xform") + # Random objects + for i in range(num_objects): + # sample random position + position = np.random.rand(3) - np.asarray([0.05, 0.05, -1.0]) + position *= np.asarray([1.5, 1.5, 0.5]) + # sample random color + color = (random.random(), random.random(), random.random()) + # choose random prim type + prim_type = random.choice(["Cube", "Cone", "Cylinder"]) + common_properties = { + "rigid_props": sim_utils.RigidBodyPropertiesCfg(), + "mass_props": sim_utils.MassPropertiesCfg(mass=5.0), + "collision_props": sim_utils.CollisionPropertiesCfg(), + "visual_material": sim_utils.PreviewSurfaceCfg(diffuse_color=color, metallic=0.5), + "semantic_tags": [("class", prim_type)], + } + if prim_type == "Cube": + shape_cfg = sim_utils.CuboidCfg(size=(0.25, 0.25, 0.25), **common_properties) + elif prim_type == "Cone": + shape_cfg = sim_utils.ConeCfg(radius=0.1, height=0.25, **common_properties) + elif prim_type == "Cylinder": + shape_cfg = sim_utils.CylinderCfg(radius=0.25, height=0.25, **common_properties) + # Rigid Object + obj_cfg = RigidObjectCfg( + prim_path=f"/World/Objects/Obj_{i:02d}", + spawn=shape_cfg, + init_state=RigidObjectCfg.InitialStateCfg(pos=position), + ) + scene_entities[f"rigid_object{i}"] = RigidObject(cfg=obj_cfg) + + # Sensors + standard_camera = create_cameras( + num_cams=num_standard_cams, data_types=standard_camera_data_types, height=height, width=width + ) + tiled_camera = create_tiled_cameras( + num_cams=num_tiled_cams, data_types=tiled_camera_data_types, height=height, width=width + ) + ray_caster_camera = create_ray_caster_cameras( + num_cams=num_ray_caster_cams, + data_types=ray_caster_camera_data_types, + mesh_prim_paths=mesh_prim_paths, + height=height, + width=width, + ) + # return the scene information + if tiled_camera is not None: + scene_entities["tiled_camera"] = tiled_camera + if standard_camera is not None: + scene_entities["standard_camera"] = standard_camera + if ray_caster_camera is not None: + scene_entities["ray_caster_camera"] = ray_caster_camera + return scene_entities + + +def inject_cameras_into_task( + task: str, + num_cams: int, + camera_name_prefix: str, + camera_creation_callable: Callable, + num_cameras_per_env: int = 1, +) -> gym.Env: + """Loads the task, sticks cameras into the config, and creates the environment.""" + cfg = load_cfg_from_registry(task, "env_cfg_entry_point") + cfg.sim.device = args_cli.device + cfg.sim.use_fabric = args_cli.use_fabric + scene_cfg = cfg.scene + + num_envs = int(num_cams / num_cameras_per_env) + scene_cfg.num_envs = num_envs + + for idx in range(num_cameras_per_env): + suffix = "" if idx == 0 else str(idx) + name = camera_name_prefix + suffix + setattr(scene_cfg, name, camera_creation_callable(name)) + cfg.scene = scene_cfg + env = gym.make(task, cfg=cfg) + return env + + +""" +System diagnosis +""" + + +def get_utilization_percentages(reset: bool = False, max_values: list[float] = [0.0, 0.0, 0.0, 0.0]) -> list[float]: + """Get the maximum CPU, RAM, GPU utilization (processing), and + GPU memory usage percentages since the last time reset was true.""" + if reset: + max_values[:] = [0, 0, 0, 0] # Reset the max values + + # CPU utilization + cpu_usage = psutil.cpu_percent(interval=0.1) + max_values[0] = max(max_values[0], cpu_usage) + + # RAM utilization + memory_info = psutil.virtual_memory() + ram_usage = memory_info.percent + max_values[1] = max(max_values[1], ram_usage) + + # GPU utilization using pynvml + if torch.cuda.is_available(): + if args_cli.autotune: + pynvml.nvmlInit() # Initialize NVML + for i in range(torch.cuda.device_count()): + handle = pynvml.nvmlDeviceGetHandleByIndex(i) + + # GPU Utilization + gpu_utilization = pynvml.nvmlDeviceGetUtilizationRates(handle) + gpu_processing_utilization_percent = gpu_utilization.gpu # GPU core utilization + max_values[2] = max(max_values[2], gpu_processing_utilization_percent) + + # GPU Memory Usage + memory_info = pynvml.nvmlDeviceGetMemoryInfo(handle) + gpu_memory_total = memory_info.total + gpu_memory_used = memory_info.used + gpu_memory_utilization_percent = (gpu_memory_used / gpu_memory_total) * 100 + max_values[3] = max(max_values[3], gpu_memory_utilization_percent) + + pynvml.nvmlShutdown() # Shutdown NVML after usage + else: + gpu_processing_utilization_percent = None + gpu_memory_utilization_percent = None + return max_values + + +""" +Experiment +""" + + +def run_simulator( + sim: sim_utils.SimulationContext | None, + scene_entities: dict | InteractiveScene, + warm_start_length: int = 10, + experiment_length: int = 100, + tiled_camera_data_types: list[str] | None = None, + standard_camera_data_types: list[str] | None = None, + ray_caster_camera_data_types: list[str] | None = None, + depth_predicate: Callable = lambda x: "to" in x or x == "depth", + perspective_depth_predicate: Callable = lambda x: x == "distance_to_camera", + convert_depth_to_camera_to_image_plane: bool = True, + max_cameras_per_env: int = 1, + env: gym.Env | None = None, +) -> dict: + """Run the simulator with all cameras, and return timing analytics. Visualize if desired.""" + + if tiled_camera_data_types is None: + tiled_camera_data_types = ["rgb"] + if standard_camera_data_types is None: + standard_camera_data_types = ["rgb"] + if ray_caster_camera_data_types is None: + ray_caster_camera_data_types = ["distance_to_image_plane"] + + # Initialize camera lists + tiled_cameras = [] + standard_cameras = [] + ray_caster_cameras = [] + + # Dynamically extract cameras from the scene entities up to max_cameras_per_env + for i in range(max_cameras_per_env): + # Extract tiled cameras + tiled_camera_key = f"tiled_camera{i}" if i > 0 else "tiled_camera" + standard_camera_key = f"standard_camera{i}" if i > 0 else "standard_camera" + ray_caster_camera_key = f"ray_caster_camera{i}" if i > 0 else "ray_caster_camera" + + try: # if instead you checked ... if key is in scene_entities... # errors out always even if key present + tiled_cameras.append(scene_entities[tiled_camera_key]) + standard_cameras.append(scene_entities[standard_camera_key]) + ray_caster_cameras.append(scene_entities[ray_caster_camera_key]) + except KeyError: + break + + # Initialize camera counts + camera_lists = [tiled_cameras, standard_cameras, ray_caster_cameras] + camera_data_types = [tiled_camera_data_types, standard_camera_data_types, ray_caster_camera_data_types] + labels = ["tiled", "standard", "ray_caster"] + + if sim is not None: + # Set camera world poses + for camera_list in camera_lists: + for camera in camera_list: + num_cameras = camera.data.intrinsic_matrices.size(0) + positions = torch.tensor([[2.5, 2.5, 2.5]], device=sim.device).repeat(num_cameras, 1) + targets = torch.tensor([[0.0, 0.0, 0.0]], device=sim.device).repeat(num_cameras, 1) + camera.set_world_poses_from_view(positions, targets) + + # Initialize timing variables + timestep = 0 + total_time = 0.0 + valid_timesteps = 0 + sim_step_time = 0.0 + + while simulation_app.is_running() and timestep < experiment_length: + print(f"On timestep {timestep} of {experiment_length}, with warm start of {warm_start_length}") + get_utilization_percentages() + + # Measure the total simulation step time + step_start_time = time.time() + + if sim is not None: + sim.step() + + if env is not None: + with torch.inference_mode(): + # compute zero actions + actions = torch.zeros(env.action_space.shape, device=env.unwrapped.device) + # apply actions + env.step(actions) + + # Update cameras and process vision data within the simulation step + clouds = {} + images = {} + depth_images = {} + + # Loop through all camera lists and their data_types + for camera_list, data_types, label in zip(camera_lists, camera_data_types, labels): + for cam_idx, camera in enumerate(camera_list): + if env is None: # No env, need to step cams manually + # Only update the camera if it hasn't been updated as part of scene_entities.update ... + camera.update(dt=sim.get_physics_dt()) + + for data_type in data_types: + data_label = f"{label}_{cam_idx}_{data_type}" + + if depth_predicate(data_type): # is a depth image, want to create cloud + depth = camera.data.output[data_type] + depth_images[data_label + "_raw"] = depth + if perspective_depth_predicate(data_type) and convert_depth_to_camera_to_image_plane: + depth = orthogonalize_perspective_depth( + camera.data.output[data_type], camera.data.intrinsic_matrices + ) + depth_images[data_label + "_undistorted"] = depth + + pointcloud = unproject_depth(depth=depth, intrinsics=camera.data.intrinsic_matrices) + clouds[data_label] = pointcloud + else: # rgb image, just save it + image = camera.data.output[data_type] + images[data_label] = image + + # End timing for the step + step_end_time = time.time() + sim_step_time += step_end_time - step_start_time + + if timestep > warm_start_length: + get_utilization_percentages(reset=True) + total_time += step_end_time - step_start_time + valid_timesteps += 1 + + timestep += 1 + + # Calculate average timings + if valid_timesteps > 0: + avg_timestep_duration = total_time / valid_timesteps + avg_sim_step_duration = sim_step_time / experiment_length + else: + avg_timestep_duration = 0.0 + avg_sim_step_duration = 0.0 + + # Package timing analytics in a dictionary + timing_analytics = { + "average_timestep_duration": avg_timestep_duration, + "average_sim_step_duration": avg_sim_step_duration, + "total_simulation_time": sim_step_time, + "total_experiment_duration": sim_step_time, + } + + system_utilization_analytics = get_utilization_percentages() + + print("--- Benchmark Results ---") + print(f"Average timestep duration: {avg_timestep_duration:.6f} seconds") + print(f"Average simulation step duration: {avg_sim_step_duration:.6f} seconds") + print(f"Total simulation time: {sim_step_time:.6f} seconds") + print("\nSystem Utilization Statistics:") + print( + f"| CPU:{system_utilization_analytics[0]}% | " + f"RAM:{system_utilization_analytics[1]}% | " + f"GPU Compute:{system_utilization_analytics[2]}% | " + f" GPU Memory: {system_utilization_analytics[3]:.2f}% |" + ) + + return {"timing_analytics": timing_analytics, "system_utilization_analytics": system_utilization_analytics} + + +def main(): + """Main function.""" + # Load simulation context + if args_cli.num_tiled_cameras + args_cli.num_standard_cameras + args_cli.num_ray_caster_cameras <= 0: + raise ValueError("You must select at least one camera.") + if ( + (args_cli.num_tiled_cameras > 0 and args_cli.num_standard_cameras > 0) + or (args_cli.num_ray_caster_cameras > 0 and args_cli.num_standard_cameras > 0) + or (args_cli.num_ray_caster_cameras > 0 and args_cli.num_tiled_cameras > 0) + ): + print("[WARNING]: You have elected to use more than one camera type.") + print("[WARNING]: For a benchmark to be meaningful, use ONLY ONE camera type at a time.") + print( + "[WARNING]: For example, if num_tiled_cameras=100, for a meaningful benchmark," + "num_standard_cameras should be 0, and num_ray_caster_cameras should be 0" + ) + raise ValueError("Benchmark one camera at a time.") + + # Determine which camera type is being used + camera_type = "tiled" + num_cameras = args_cli.num_tiled_cameras + if args_cli.num_standard_cameras > 0: + camera_type = "standard" + num_cameras = args_cli.num_standard_cameras + elif args_cli.num_ray_caster_cameras > 0: + camera_type = "ray_caster" + num_cameras = args_cli.num_ray_caster_cameras + + # Create the benchmark + backend_type = args_cli.benchmark_backend + benchmark = BaseIsaacLabBenchmark( + benchmark_name="benchmark_cameras", + backend_type=backend_type, + output_path=args_cli.output_path, + use_recorders=True, + frametime_recorders=backend_type in ("summary", "omniperf"), + output_prefix="benchmark_cameras", + workflow_metadata={ + "metadata": [ + {"name": "task", "data": args_cli.task}, + {"name": "camera_type", "data": camera_type}, + {"name": "num_cameras", "data": num_cameras}, + {"name": "height", "data": args_cli.height}, + {"name": "width", "data": args_cli.width}, + {"name": "experiment_length", "data": args_cli.experiment_length}, + {"name": "autotune", "data": args_cli.autotune}, + ] + }, + ) + + print("[INFO]: Designing the scene") + final_analysis = None + + if args_cli.task is None: + print("[INFO]: No task environment provided, creating random scene.") + sim_cfg = sim_utils.SimulationCfg(device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.5, 2.5, 2.5], [0.0, 0.0, 0.0]) + scene_entities = design_scene( + num_tiled_cams=args_cli.num_tiled_cameras, + num_standard_cams=args_cli.num_standard_cameras, + num_ray_caster_cams=args_cli.num_ray_caster_cameras, + tiled_camera_data_types=args_cli.tiled_camera_data_types, + standard_camera_data_types=args_cli.standard_camera_data_types, + ray_caster_camera_data_types=args_cli.ray_caster_camera_data_types, + height=args_cli.height, + width=args_cli.width, + num_objects=args_cli.num_objects, + mesh_prim_paths=args_cli.ray_caster_visible_mesh_prim_paths, + ) + # Play simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run simulator + final_analysis = run_simulator( + sim=sim, + scene_entities=scene_entities, + warm_start_length=args_cli.warm_start_length, + experiment_length=args_cli.experiment_length, + tiled_camera_data_types=args_cli.tiled_camera_data_types, + standard_camera_data_types=args_cli.standard_camera_data_types, + ray_caster_camera_data_types=args_cli.ray_caster_camera_data_types, + convert_depth_to_camera_to_image_plane=args_cli.convert_depth_to_camera_to_image_plane, + ) + else: + print("[INFO]: Using known task environment, injecting cameras.") + autotune_iter = 0 + max_sys_util_thresh = [0.0, 0.0, 0.0] + max_num_cams = max(args_cli.num_tiled_cameras, args_cli.num_standard_cameras, args_cli.num_ray_caster_cameras) + cur_num_cams = max_num_cams + cur_sys_util = max_sys_util_thresh + interval = args_cli.autotune_camera_count_interval + + if args_cli.autotune: + max_sys_util_thresh = args_cli.autotune_max_percentage_util + max_num_cams = args_cli.autotune_max_camera_count + print("[INFO]: Auto tuning until any of the following threshold are met") + print(f"|CPU: {max_sys_util_thresh[0]}% | RAM {max_sys_util_thresh[1]}% | GPU: {max_sys_util_thresh[2]}% |") + print(f"[INFO]: Maximum number of cameras allowed: {max_num_cams}") + # Determine which camera is being tested... + tiled_camera_cfg = create_tiled_camera_cfg("tiled_camera") + standard_camera_cfg = create_standard_camera_cfg("standard_camera") + ray_caster_camera_cfg = create_ray_caster_camera_cfg("ray_caster_camera") + camera_name_prefix = "" + camera_creation_callable = None + num_cams = 0 + if tiled_camera_cfg is not None: + camera_name_prefix = "tiled_camera" + camera_creation_callable = create_tiled_camera_cfg + num_cams = args_cli.num_tiled_cameras + elif standard_camera_cfg is not None: + camera_name_prefix = "standard_camera" + camera_creation_callable = create_standard_camera_cfg + num_cams = args_cli.num_standard_cameras + elif ray_caster_camera_cfg is not None: + camera_name_prefix = "ray_caster_camera" + camera_creation_callable = create_ray_caster_camera_cfg + num_cams = args_cli.num_ray_caster_cameras + + while ( + all(cur <= max_thresh for cur, max_thresh in zip(cur_sys_util, max_sys_util_thresh)) + and cur_num_cams <= max_num_cams + ): + cur_num_cams = num_cams + interval * autotune_iter + autotune_iter += 1 + + env = inject_cameras_into_task( + task=args_cli.task, + num_cams=cur_num_cams, + camera_name_prefix=camera_name_prefix, + camera_creation_callable=camera_creation_callable, + num_cameras_per_env=args_cli.task_num_cameras_per_env, + ) + env.reset() + print(f"Testing with {cur_num_cams} {camera_name_prefix}") + analysis = run_simulator( + sim=None, + scene_entities=env.unwrapped.scene, + warm_start_length=args_cli.warm_start_length, + experiment_length=args_cli.experiment_length, + tiled_camera_data_types=args_cli.tiled_camera_data_types, + standard_camera_data_types=args_cli.standard_camera_data_types, + ray_caster_camera_data_types=args_cli.ray_caster_camera_data_types, + convert_depth_to_camera_to_image_plane=args_cli.convert_depth_to_camera_to_image_plane, + max_cameras_per_env=args_cli.task_num_cameras_per_env, + env=env, + ) + + cur_sys_util = analysis["system_utilization_analytics"] + final_analysis = analysis + print("Triggering reset...") + env.close() + sim_utils.create_new_stage() + print("[INFO]: DONE! Feel free to CTRL + C Me ") + print(f"[INFO]: If you've made it this far, you can likely simulate {cur_num_cams} {camera_name_prefix}") + print("Keep in mind, this is without any training running on the GPU.") + print("Set lower utilization thresholds to account for training.") + + if not args_cli.autotune: + print("[WARNING]: GPU Util Statistics only correct while autotuning, ignore above.") + + # Log benchmark measurements + if final_analysis is not None: + timing = final_analysis["timing_analytics"] + sys_util = final_analysis["system_utilization_analytics"] + + # Log timing measurements + benchmark.add_measurement( + "runtime", + measurement=SingleMeasurement( + name="Average Timestep Duration", value=timing["average_timestep_duration"] * 1000, unit="ms" + ), + ) + benchmark.add_measurement( + "runtime", + measurement=SingleMeasurement( + name="Average Simulation Step Duration", value=timing["average_sim_step_duration"] * 1000, unit="ms" + ), + ) + benchmark.add_measurement( + "runtime", + measurement=SingleMeasurement( + name="Total Simulation Time", value=timing["total_simulation_time"] * 1000, unit="ms" + ), + ) + + # Log system utilization + benchmark.add_measurement( + "runtime", + measurement=DictMeasurement( + name="System Utilization", + value={ + "cpu_percent": sys_util[0], + "ram_percent": sys_util[1], + "gpu_compute_percent": sys_util[2], + "gpu_memory_percent": sys_util[3], + }, + ), + ) + + # Finalize benchmark + benchmark.update_manual_recorders() + benchmark._finalize_impl() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_hydra_resolve.py b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_hydra_resolve.py new file mode 100644 index 0000000000000000000000000000000000000000..f3709c9de93594c2cdbf2e40e7451c1216b812ae --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_hydra_resolve.py @@ -0,0 +1,260 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Benchmark task config resolution through IsaacLab's Hydra preset layer. + +This measures the pre-Kit path used by training scripts to load an env cfg, +resolve ``PresetCfg`` selections, register the plain Hydra config, run Hydra +scalar overrides, and return the resolved env/agent cfg objects. + +The benchmark prints a local summary table and writes per-case measurements to +the standard Isaac Lab benchmark backend. It does not create environments and +does not require a GPU. + +Usage:: + + ./isaaclab.sh -p scripts/benchmarks/benchmark_hydra_resolve.py + ./isaaclab.sh -p scripts/benchmarks/benchmark_hydra_resolve.py --suite broad + ./isaaclab.sh -p scripts/benchmarks/benchmark_hydra_resolve.py --iterations 100 + ./isaaclab.sh -p scripts/benchmarks/benchmark_hydra_resolve.py \ + --case cartpole:Isaac-Cartpole-v0:: \ + --case anymal:Isaac-Velocity-Rough-Anymal-C-v0::env.scene.num_envs=256 + +Case format is ``name:task:agent_entry:arg[,arg...]``. Leave ``agent_entry`` or +``arg`` empty when not needed. +""" + +from __future__ import annotations + +import argparse +import contextlib +import io +import os +import statistics +import sys +import time +import warnings +from dataclasses import dataclass + +import gymnasium + +from isaaclab.test.benchmark import BaseIsaacLabBenchmark, SingleMeasurement + +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../..")) + +with warnings.catch_warnings(): + warnings.simplefilter("ignore") + import isaaclab_tasks # noqa: F401 + +from isaaclab_tasks.utils.hydra import resolve_task_config + +from scripts.benchmarks.utils import get_backend_type + + +@dataclass(frozen=True) +class Case: + name: str + task: str + agent_entry: str | None = None + args: tuple[str, ...] = () + + +QUICK_CASES = ( + Case("cartpole_manager", "Isaac-Cartpole-v0"), + Case("cartpole_camera_presets", "Isaac-Cartpole-Camera-Presets-Direct-v0", "rl_games_cfg_entry_point"), + Case("anymal_rough", "Isaac-Velocity-Rough-Anymal-C-v0"), + Case("franka_lift_cube", "Isaac-Lift-Cube-Franka-v0"), + Case( + "cartpole_camera_newton_ovrtx", + "Isaac-Cartpole-Camera-Presets-Direct-v0", + "rl_games_cfg_entry_point", + ("presets=newton_mjwarp,ovrtx_renderer",), + ), + Case("anymal_rough_scalar", "Isaac-Velocity-Rough-Anymal-C-v0", None, ("env.scene.num_envs=256",)), +) + + +BROAD_CASES = ( + *QUICK_CASES, + Case("cartpole_direct", "Isaac-Cartpole-Direct-v0"), + Case("cartpole_rgb_direct", "Isaac-Cartpole-RGB-Camera-Direct-v0"), + Case("ant_manager", "Isaac-Ant-v0"), + Case("humanoid_manager", "Isaac-Humanoid-v0", "rsl_rl_cfg_entry_point"), + Case("franka_reach", "Isaac-Reach-Franka-v0"), + Case("franka_lift_cube_agent", "Isaac-Lift-Cube-Franka-v0", "sb3_cfg_entry_point"), + Case("kuka_allegro_lift", "Isaac-Dexsuite-Kuka-Allegro-Lift-v0", "rsl_rl_cfg_entry_point"), + Case( + "kuka_allegro_lift_single_camera", + "Isaac-Dexsuite-Kuka-Allegro-Lift-v0", + "rsl_rl_cfg_entry_point", + ("presets=single_camera,rgb128",), + ), + Case( + "kuka_allegro_lift_duo_camera", + "Isaac-Dexsuite-Kuka-Allegro-Lift-v0", + "rsl_rl_cfg_entry_point", + ("presets=duo_camera,rgb128",), + ), + Case( + "kuka_allegro_lift_scalar", + "Isaac-Dexsuite-Kuka-Allegro-Lift-v0", + "rsl_rl_cfg_entry_point", + ("env.scene.num_envs=256",), + ), + Case( + "cartpole_camera_hydra_force", + "Isaac-Cartpole-Camera-Presets-Direct-v0", + "rl_games_cfg_entry_point", + ("++env.scene.num_envs=256",), + ), +) + +SUITES = {"quick": QUICK_CASES, "broad": BROAD_CASES} + + +def _parse_case(spec: str) -> Case: + parts = spec.split(":", 3) + if len(parts) != 4: + raise argparse.ArgumentTypeError("case must have format name:task:agent_entry:arg[,arg...]") + name, task, agent_entry, args = parts + if not name or not task: + raise argparse.ArgumentTypeError("case name and task must be non-empty") + return Case( + name=name, + task=task, + agent_entry=agent_entry or None, + args=tuple(arg for arg in args.split(",") if arg), + ) + + +def _resolve_once(case: Case, *, verbose: bool = False) -> None: + old_argv = sys.argv + try: + sys.argv = [old_argv[0], *case.args] + if verbose: + resolve_task_config(case.task, case.agent_entry) + else: + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + resolve_task_config(case.task, case.agent_entry) + finally: + sys.argv = old_argv + + +def _benchmark_case(case: Case, iterations: int, warmup: int, *, verbose: bool) -> list[float]: + for _ in range(warmup): + _resolve_once(case, verbose=verbose) + + times_ms = [] + for _ in range(iterations): + t0 = time.perf_counter_ns() + _resolve_once(case, verbose=verbose) + t1 = time.perf_counter_ns() + times_ms.append((t1 - t0) / 1_000_000) + return times_ms + + +def _print_results(results: dict[Case, list[float]]) -> None: + print(f"\n{'Case':<32} {'median ms':>10} {'mean ms':>10} {'stdev ms':>10} {'min ms':>10} {'max ms':>10} argv") + print(f"{'-' * 32} {'-' * 10} {'-' * 10} {'-' * 10} {'-' * 10} {'-' * 10} {'-' * 24}") + for case, times in results.items(): + stdev = statistics.stdev(times) if len(times) > 1 else 0.0 + argv = " ".join(case.args) if case.args else "(none)" + print( + f"{case.name:<32} {statistics.median(times):>10.2f} {statistics.mean(times):>10.2f}" + f" {stdev:>10.2f} {min(times):>10.2f} {max(times):>10.2f} {argv}" + ) + + +def _log_results(benchmark: BaseIsaacLabBenchmark, results: dict[Case, list[float]]) -> None: + for case, times in results.items(): + stats = { + "Median Resolve Task Config Time": statistics.median(times), + "Mean Resolve Task Config Time": statistics.mean(times), + "Stdev Resolve Task Config Time": statistics.stdev(times) if len(times) > 1 else 0.0, + "Min Resolve Task Config Time": min(times), + "Max Resolve Task Config Time": max(times), + } + for name, value in stats.items(): + benchmark.add_measurement( + "task_config", + measurement=SingleMeasurement(name=f"{case.name} {name}", value=value, unit="ms"), + ) + + benchmark.update_manual_recorders() + benchmark._finalize_impl() + + +def main() -> int: + parser = argparse.ArgumentParser(description="Benchmark env_cfg + Hydra preset resolution.") + parser.add_argument("--iterations", type=int, default=50, help="Timed iterations per case.") + parser.add_argument("--warmup", type=int, default=5, help="Warmup iterations per case.") + parser.add_argument( + "--suite", + choices=sorted(SUITES), + default="quick", + help="Named benchmark suite to run when --case is not provided.", + ) + parser.add_argument( + "--case", + action="append", + type=_parse_case, + default=None, + help="Benchmark case in format name:task:agent_entry:arg[,arg...]. May be repeated.", + ) + parser.add_argument( + "--benchmark_backend", + type=str, + default="summary", + choices=[ + "json", + "osmo", + "omniperf", + "summary", + "LocalLogMetrics", + "JSONFileMetrics", + "OsmoKPIFile", + "OmniPerfKPIFile", + ], + help="Benchmarking backend options, defaults summary.", + ) + parser.add_argument("--output_path", type=str, default=".", help="Path to output benchmark results.") + parser.add_argument("--verbose", action="store_true", help="Keep per-iteration resolver output.") + args = parser.parse_args() + + cases = tuple(args.case) if args.case else SUITES[args.suite] + valid_cases = tuple(case for case in cases if case.task in gymnasium.registry) + skipped = [case.task for case in cases if case.task not in gymnasium.registry] + if skipped: + print(f"[WARN] Skipping unregistered task(s): {skipped}") + if not valid_cases: + print("[ERROR] No valid benchmark cases.") + return 1 + + print("Benchmarking resolve_task_config()") + print(f"Iterations: {args.iterations}, warmup: {args.warmup}") + + results = {case: _benchmark_case(case, args.iterations, args.warmup, verbose=args.verbose) for case in valid_cases} + _print_results(results) + + benchmark = BaseIsaacLabBenchmark( + benchmark_name="benchmark_hydra_resolve", + backend_type=get_backend_type(args.benchmark_backend), + output_path=args.output_path, + use_recorders=True, + output_prefix="benchmark_hydra_resolve", + workflow_metadata={ + "metadata": [ + {"name": "suite", "data": args.suite if not args.case else "custom"}, + {"name": "iterations", "data": args.iterations}, + {"name": "warmup", "data": args.warmup}, + ] + }, + ) + _log_results(benchmark, results) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_lazy_export.py b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_lazy_export.py new file mode 100644 index 0000000000000000000000000000000000000000..999dc7b5e1f40787726acc6f0849ba51b6e21116 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_lazy_export.py @@ -0,0 +1,177 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Benchmark lazy_export import performance via parse_env_cfg. + +Measures the cold end-to-end time to construct environment configs — the real +user-facing cost that includes gym registry walking, lazy_export stub parsing, +fallback resolution, module imports, and config class instantiation. + +Each iteration fully purges task modules and the gym registration guard so +that the next ``import isaaclab_tasks`` re-walks every task package and +re-registers every gym environment, matching a fresh-process cold start. + +The report separates **package loading** (``import isaaclab_tasks`` — registry +walk + gym registrations) from **config construction** +(``load_cfg_from_registry`` — module import + class instantiation). + +This script does NOT require Isaac Sim or a GPU. + +Usage:: + + ./isaaclab.sh -p scripts/benchmarks/benchmark_lazy_export.py + ./isaaclab.sh -p scripts/benchmarks/benchmark_lazy_export.py --iterations 20 + ./isaaclab.sh -p scripts/benchmarks/benchmark_lazy_export.py --tasks Isaac-Velocity-Flat-Anymal-D-v0 +""" + +from __future__ import annotations + +import argparse +import builtins +import importlib +import io +import statistics +import sys +import time +import warnings + +import gymnasium + +with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + import isaaclab_tasks # noqa: F401 + +from isaaclab_tasks.utils.parse_cfg import load_cfg_from_registry + +_REPRESENTATIVE_TASKS = [ + "Isaac-Cartpole-v0", + "Isaac-Humanoid-v0", + "Isaac-Velocity-Flat-Anymal-D-v0", + "Isaac-Reach-Franka-v0", + "Isaac-Lift-Cube-Franka-v0", + "Isaac-Dexsuite-Kuka-Allegro-Reorient-v0", + "Isaac-Navigation-Flat-Anymal-C-v0", + "Isaac-Stack-Cube-Franka-v0", +] + + +def _purge_all() -> None: + """Fully purge task modules, gym registrations, and the registration guard.""" + to_delete = [k for k in sys.modules if k.startswith("isaaclab_tasks.")] + for k in to_delete: + del sys.modules[k] + del sys.modules["isaaclab_tasks"] + + builtins._isaaclab_tasks_registered = False + + isaac_ids = [name for name in gymnasium.registry if name.startswith("Isaac-")] + for name in isaac_ids: + del gymnasium.registry[name] + + +def _short_name(task: str) -> str: + return task.replace("Isaac-", "").replace("-v0", "") + + +def benchmark( + tasks: list[str], iterations: int +) -> tuple[dict[str, list[float]], dict[str, list[float]], dict[str, list[float]]]: + """Benchmark with package loading and config construction timed separately. + + Returns: + Three dicts keyed by task name, each mapping to a list of per-iteration + times in ms: (pkg_load_times, cfg_construct_times, total_times). + """ + pkg_results: dict[str, list[float]] = {t: [] for t in tasks} + cfg_results: dict[str, list[float]] = {t: [] for t in tasks} + total_results: dict[str, list[float]] = {t: [] for t in tasks} + + for _ in range(iterations): + for task in tasks: + _purge_all() + + old_stdout, old_stderr = sys.stdout, sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + try: + t0 = time.perf_counter_ns() + importlib.import_module("isaaclab_tasks") + t1 = time.perf_counter_ns() + load_cfg_from_registry(task, "env_cfg_entry_point") + t2 = time.perf_counter_ns() + finally: + sys.stdout = old_stdout + sys.stderr = old_stderr + + pkg_ms = (t1 - t0) / 1_000_000 + cfg_ms = (t2 - t1) / 1_000_000 + pkg_results[task].append(pkg_ms) + cfg_results[task].append(cfg_ms) + total_results[task].append(pkg_ms + cfg_ms) + + return pkg_results, cfg_results, total_results + + +def _print_table(title: str, results: dict[str, list[float]], unit: str = "ms") -> None: + print(f"\n{'=' * 80}") + print(f" {title}") + print(f"{'=' * 80}") + print(f" {'Task':<40} {'median':>10} {'mean':>10} {'stdev':>10} ({unit})") + print(f" {'-' * 40} {'-' * 10} {'-' * 10} {'-' * 10}") + + all_medians: list[float] = [] + for task, times in results.items(): + short = _short_name(task) + med = statistics.median(times) + avg = statistics.mean(times) + std = statistics.stdev(times) if len(times) > 1 else 0.0 + all_medians.append(med) + print(f" {short:<40} {med:>10.2f} {avg:>10.2f} {std:>10.2f}") + + total_med = sum(all_medians) + avg_med = total_med / len(all_medians) if all_medians else 0 + print(f" {'-' * 40} {'-' * 10} {'-' * 10} {'-' * 10}") + print(f" {'TOTAL (sum of medians)':<40} {total_med:>10.2f}") + print(f" {'AVERAGE (per task)':<40} {avg_med:>10.2f}") + print() + + +def main(): + parser = argparse.ArgumentParser(description="Benchmark lazy_export via cold parse_env_cfg.") + parser.add_argument("--iterations", type=int, default=20, help="Iterations per benchmark.") + parser.add_argument( + "--tasks", + nargs="*", + default=None, + help="Task IDs to benchmark. Defaults to a representative set.", + ) + args = parser.parse_args() + n = args.iterations + + tasks = args.tasks or _REPRESENTATIVE_TASKS + valid = [t for t in tasks if t in gymnasium.registry] + skipped = [t for t in tasks if t not in gymnasium.registry] + if skipped: + print(f"[WARN] Skipping unregistered tasks: {skipped}") + tasks = valid + + if not tasks: + print("[ERROR] No valid tasks found.") + return + + print(f"Benchmarking cold parse_env_cfg with {n} iterations") + print(f"Tasks ({len(tasks)}): {[_short_name(t) for t in tasks]}") + + pkg, cfg, total = benchmark(tasks, n) + + _print_table("Package loading (import isaaclab_tasks — registry walk)", pkg) + _print_table("Config construction (load_cfg_from_registry)", cfg) + _print_table("Total (package loading + config construction)", total) + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_load_robot.py b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_load_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..d10ac63653230f10398efa887d54a50be0b78e15 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_load_robot.py @@ -0,0 +1,232 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to benchmark loading multiple copies of a robot. + +.. code-block python + + ./isaaclab.sh -p scripts/benchmarks/benchmark_load_robot.py --num_envs 2048 --robot g1 --headless + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +import time + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Benchmark loading different robots.") +parser.add_argument("--num_envs", type=int, default=32, help="Number of robots to simulate.") +parser.add_argument( + "--robot", + type=str, + choices=["anymal_d", "h1", "g1"], + default="h1", + help="Choose which robot to load: anymal_d, h1, or g1.", +) +parser.add_argument( + "--benchmark_backend", + type=str, + default="omniperf", + choices=["json", "osmo", "omniperf", "summary"], + help="Benchmarking backend options, defaults omniperf", +) +parser.add_argument("--output_path", type=str, default=".", help="Path to output benchmark results.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli, _ = parser.parse_known_args() + +# Start the timer for app start +app_start_time_begin = time.perf_counter_ns() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +# End the timer for app start +app_start_time_end = time.perf_counter_ns() + +"""Rest everything follows.""" + +# Start the timer for imports +imports_time_begin = time.perf_counter_ns() + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg, AssetBaseCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sim import SimulationContext +from isaaclab.test.benchmark import BaseIsaacLabBenchmark, SingleMeasurement +from isaaclab.utils.configclass import configclass + +## +# Pre-defined configs +## +from isaaclab_assets import ANYMAL_D_CFG, G1_MINIMAL_CFG, H1_MINIMAL_CFG # isort:skip + + +# Stop the timer for imports +imports_time_end = time.perf_counter_ns() + +# Create the benchmark +backend_type = args_cli.benchmark_backend +benchmark = BaseIsaacLabBenchmark( + benchmark_name="benchmark_load_robot", + backend_type=backend_type, + output_path=args_cli.output_path, + use_recorders=True, + frametime_recorders=backend_type in ("summary", "omniperf"), + output_prefix="benchmark_load_robot", + workflow_metadata={ + "metadata": [ + {"name": "robot", "data": args_cli.robot}, + {"name": "num_envs", "data": args_cli.num_envs}, + ] + }, +) + + +@configclass +class RobotSceneCfg(InteractiveSceneCfg): + """Configuration for a simple scene with a robot.""" + + # ground plane + ground = AssetBaseCfg(prim_path="/World/defaultGroundPlane", spawn=sim_utils.GroundPlaneCfg()) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # articulation + if args_cli.robot == "h1": + robot: ArticulationCfg = H1_MINIMAL_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + elif args_cli.robot == "g1": + robot: ArticulationCfg = G1_MINIMAL_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + elif args_cli.robot == "anymal_d": + robot: ArticulationCfg = ANYMAL_D_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + else: + raise ValueError(f"Unsupported robot type: {args_cli.robot}.") + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Runs the simulation loop.""" + # Extract scene entities + # note: we only do this here for readability. + robot = scene["robot"] + # Define simulation stepping + sim_dt = sim.get_physics_dt() + + # Start the timer for creating the scene + step_time_begin = time.perf_counter_ns() + num_steps = 2000 + + # Simulation loop + for count in range(num_steps): + # Reset + if count % 500 == 0: + # reset the scene entities + # root state + # we offset the root state by the origin since the states are written in simulation world frame + # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world + root_pose = robot.data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + robot.write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = robot.data.default_root_vel.torch.clone() + robot.write_root_velocity_to_sim_index(root_velocity=root_vel) + # set joint positions with some noise + joint_pos, joint_vel = ( + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), + ) + joint_pos += torch.rand_like(joint_pos) * 0.1 + robot.write_joint_position_to_sim_index(position=joint_pos) + robot.write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + scene.reset() + # Apply random action + # -- generate random joint efforts + efforts = torch.randn_like(robot.data.joint_pos.torch) * 5.0 + # -- apply action to the robot + robot.set_joint_effort_target_index(target=efforts) + # -- write data to sim + scene.write_data_to_sim() + # Perform step + sim.step() + # Update buffers + scene.update(sim_dt) + + # Stop the timer for reset + step_time_end = time.perf_counter_ns() + per_step_time_ms = (step_time_end - step_time_begin) / num_steps / 1e6 + + # Log per step time to benchmark + benchmark.add_measurement( + "runtime", measurement=SingleMeasurement(name="Per Step Time", value=per_step_time_ms, unit="ms") + ) + + +def main(): + """Main function.""" + # Load kit helper + sim_cfg = sim_utils.SimulationCfg(device="cuda:0") + sim = SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.5, 0.0, 4.0], [0.0, 0.0, 2.0]) + + # Start the timer for creating the scene + setup_time_begin = time.perf_counter_ns() + # Design scene + scene_cfg = RobotSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0) + scene = InteractiveScene(scene_cfg) + # Stop the timer for creating the scene + setup_time_end = time.perf_counter_ns() + + # Log scene creation time + scene_creation_time_ms = (setup_time_end - setup_time_begin) / 1e6 + benchmark.add_measurement( + "startup", measurement=SingleMeasurement(name="Scene Creation Time", value=scene_creation_time_ms, unit="ms") + ) + + # Start the timer for reset + reset_time_begin = time.perf_counter_ns() + # Play the simulator + sim.reset() + # Stop the timer for reset + reset_time_end = time.perf_counter_ns() + + # Log simulation start time + sim_start_time_ms = (reset_time_end - reset_time_begin) / 1e6 + benchmark.add_measurement( + "startup", measurement=SingleMeasurement(name="Simulation Start Time", value=sim_start_time_ms, unit="ms") + ) + + # Log app start and imports time + app_start_time_ms = (app_start_time_end - app_start_time_begin) / 1e6 + imports_time_ms = (imports_time_end - imports_time_begin) / 1e6 + benchmark.add_measurement( + "startup", measurement=SingleMeasurement(name="App Launch Time", value=app_start_time_ms, unit="ms") + ) + benchmark.add_measurement( + "startup", measurement=SingleMeasurement(name="Imports Time", value=imports_time_ms, unit="ms") + ) + + # Run the simulator + run_simulator(sim, scene) + + # Finalize benchmark + benchmark.update_manual_recorders() + benchmark._finalize_impl() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_non_rl.py b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_non_rl.py new file mode 100644 index 0000000000000000000000000000000000000000..9a6ce134f96df051411e15d7e32e2d9656066307 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_non_rl.py @@ -0,0 +1,230 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to benchmark non-RL environment.""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +import contextlib +import os +import sys +import time + +from isaaclab.app import AppLauncher + +from isaaclab_tasks.utils import setup_preset_cli + +# add argparse arguments +parser = argparse.ArgumentParser(description="Train an RL agent with RL-Games.") +parser.add_argument("--video", action="store_true", default=False, help="Record videos during training.") +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("--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") +parser.add_argument( + "--distributed", action="store_true", default=False, help="Run training with multiple GPUs or nodes." +) +parser.add_argument("--num_frames", type=int, default=100, help="Number of environment frames to run benchmark for.") +parser.add_argument( + "--benchmark_backend", + type=str, + default="omniperf", + choices=[ + "json", + "osmo", + "omniperf", + "summary", + "LocalLogMetrics", + "JSONFileMetrics", + "OsmoKPIFile", + "OmniPerfKPIFile", + ], + help="Benchmarking backend options, defaults omniperf", +) +parser.add_argument("--output_path", type=str, default=".", help="Path to output benchmark results.") + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args +if args_cli.video: + args_cli.enable_cameras = True + +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../..")) + +from isaaclab.test.benchmark import BaseIsaacLabBenchmark, BenchmarkMonitor +from isaaclab.utils.timer import Timer + +from scripts.benchmarks.utils import ( + get_backend_type, + get_preset_string, + log_app_start_time, + log_python_imports_time, + log_runtime_step_times, + log_scene_creation_time, + log_simulation_start_time, + log_task_start_time, + log_total_start_time, +) + +imports_time_begin = time.perf_counter_ns() + +import os +from datetime import datetime + +import gymnasium as gym +import numpy as np +import torch + +from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg +from isaaclab.utils.dict import print_dict + +import isaaclab_tasks # noqa: F401 + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 +from isaaclab_tasks.utils import launch_simulation, resolve_task_config + +imports_time_end = time.perf_counter_ns() + + +# Create the benchmark +backend_type = get_backend_type(args_cli.benchmark_backend) +benchmark = BaseIsaacLabBenchmark( + benchmark_name="benchmark_non_rl", + backend_type=backend_type, + output_path=args_cli.output_path, + use_recorders=True, + frametime_recorders=backend_type in ("summary", "omniperf"), + output_prefix=f"benchmark_non_rl_{args_cli.task}", + workflow_metadata={ + "metadata": [ + {"name": "task", "data": args_cli.task}, + {"name": "seed", "data": args_cli.seed}, + {"name": "num_envs", "data": args_cli.num_envs}, + {"name": "num_frames", "data": args_cli.num_frames}, + {"name": "presets", "data": get_preset_string(hydra_args)}, + ] + }, +) + + +def main( + env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, + app_start_time_begin: int, + app_start_time_end: int, +): + """Benchmark without RL in the loop.""" + + # override configurations with non-hydra CLI arguments + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + # For distributed training, launch_simulation() already resolved the + # correct per-rank device; only apply a CLI --device override for + # non-distributed runs (the default "cuda:0" would clobber the + # per-rank device otherwise). + if not args_cli.distributed: + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + env_cfg.seed = args_cli.seed + + # check for invalid combination of CPU device with distributed training + if args_cli.distributed and args_cli.device is not None and "cpu" in args_cli.device: + raise ValueError( + "Distributed training is not supported when using CPU device. " + "Please use GPU device (e.g., --device cuda) for distributed training." + ) + + # process distributed + # env_cfg.sim.device is already resolved by launch_simulation(). + world_size = 1 + world_rank = 0 + if args_cli.distributed: + world_size = int(os.getenv("WORLD_SIZE", 1)) + world_rank = int(os.getenv("RANK", "0")) + + task_startup_time_begin = time.perf_counter_ns() + + # 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: + log_root_path = os.path.abspath(f"benchmark/{args_cli.task}") + log_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + video_kwargs = { + "video_folder": os.path.join(log_root_path, 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) + + task_startup_time_end = time.perf_counter_ns() + + env.reset() + + # counter for number of frames to run for + num_frames = 0 + # log frame times + step_times = [] + + # Run with continuous benchmark monitoring + with BenchmarkMonitor(benchmark, interval=1.0): + while num_frames < args_cli.num_frames: + # get upper and lower bounds of action space, sample actions randomly on this interval + action_high = 1 + action_low = -1 + actions = (action_high - action_low) * torch.rand( + env.unwrapped.num_envs, env.unwrapped.single_action_space.shape[0], device=env.unwrapped.device + ) - action_high + + # env stepping + env_step_time_begin = time.perf_counter_ns() + _ = env.step(actions) + end_step_time_end = time.perf_counter_ns() + step_times.append(end_step_time_end - env_step_time_begin) + + num_frames += 1 + + if world_rank == 0: + # Final update after loop completes + benchmark.update_manual_recorders() + + # compute stats + step_times = np.array(step_times) / 1e6 # ns to ms + fps = 1.0 / (step_times / 1000) + effective_fps = fps * env.unwrapped.num_envs * world_size + + # prepare step timing dict + environment_step_times = { + "Environment step times": step_times.tolist(), + "Environment step FPS": fps.tolist(), + "Environment step effective FPS": effective_fps.tolist(), + } + + log_app_start_time(benchmark, (app_start_time_end - app_start_time_begin) / 1e6) + log_python_imports_time(benchmark, (imports_time_end - imports_time_begin) / 1e6) + log_task_start_time(benchmark, (task_startup_time_end - task_startup_time_begin) / 1e6) + log_scene_creation_time(benchmark, Timer.get_timer_info("scene_creation") * 1000) + log_simulation_start_time(benchmark, Timer.get_timer_info("simulation_start") * 1000) + log_total_start_time(benchmark, (task_startup_time_end - app_start_time_begin) / 1e6) + log_runtime_step_times(benchmark, environment_step_times, compute_stats=True) + + benchmark._finalize_impl() + + # close the simulator + env.close() + + +if __name__ == "__main__": + env_cfg, _agent_cfg = resolve_task_config(args_cli.task, None) + + app_start_time_begin = time.perf_counter_ns() + with launch_simulation(env_cfg, args_cli): + app_start_time_end = time.perf_counter_ns() + main(env_cfg, app_start_time_begin, app_start_time_end) diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_rlgames.py b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_rlgames.py new file mode 100644 index 0000000000000000000000000000000000000000..be59baada24b59fb672727e697c316c802e25bf5 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_rlgames.py @@ -0,0 +1,317 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to benchmark RL agent with RL-Games.""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +import contextlib +import os +import sys +import time + +from isaaclab.app import AppLauncher + +from isaaclab_tasks.utils import setup_preset_cli + +from scripts.benchmarks.early_stop import ( + RlGamesEarlyStopObserver, + add_success_cli_args, + build_success_kwargs, + get_success_tracker, +) + +# add argparse arguments +parser = argparse.ArgumentParser(description="Train an RL agent with RL-Games.") +parser.add_argument("--video", action="store_true", default=False, help="Record videos during training.") +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("--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") +parser.add_argument( + "--distributed", action="store_true", default=False, help="Run training with multiple GPUs or nodes." +) +parser.add_argument("--max_iterations", type=int, default=10, help="RL Policy training iterations.") +parser.add_argument( + "--benchmark_backend", + type=str, + default="omniperf", + choices=[ + "json", + "osmo", + "omniperf", + "summary", + "LocalLogMetrics", + "JSONFileMetrics", + "OsmoKPIFile", + "OmniPerfKPIFile", + ], + help="Benchmarking backend options, defaults omniperf", +) +parser.add_argument("--output_path", type=str, default=".", help="Path to output benchmark results.") +parser.add_argument( + "--reward_threshold", type=float, default=None, help="Reward threshold for convergence (overrides config)." +) +parser.add_argument( + "--check_convergence", action="store_true", help="Check reward convergence using thresholds from configs.yaml." +) +parser.add_argument( + "--convergence_config", type=str, default="full", help="Config mode for convergence thresholds (default: full)." +) +add_success_cli_args(parser) + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args +if args_cli.video: + args_cli.enable_cameras = True + +imports_time_begin = time.perf_counter_ns() + +import math +import random +from datetime import datetime + +import gymnasium as gym +import torch +from rl_games.common import env_configurations, vecenv +from rl_games.common.algo_observer import IsaacAlgoObserver +from rl_games.torch_runner import Runner + +from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg +from isaaclab.utils.dict import print_dict +from isaaclab.utils.io import dump_yaml + +from isaaclab_rl.rl_games import RlGamesGpuEnv, RlGamesVecEnvWrapper + +import isaaclab_tasks # noqa: F401 + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 +from isaaclab_tasks.utils import launch_simulation, resolve_task_config + +imports_time_end = time.perf_counter_ns() + +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../..")) + +from isaaclab.test.benchmark import BaseIsaacLabBenchmark, BenchmarkMonitor +from isaaclab.utils.timer import Timer + +from scripts.benchmarks.utils import ( + get_backend_type, + get_preset_string, + log_app_start_time, + log_python_imports_time, + log_rl_training_metrics, + log_runtime_step_times, + log_scene_creation_time, + log_simulation_start_time, + log_success, + log_task_start_time, + log_total_start_time, + parse_tf_logs, +) + +torch.backends.cuda.matmul.allow_tf32 = True +torch.backends.cudnn.allow_tf32 = True +torch.backends.cudnn.deterministic = False +torch.backends.cudnn.benchmark = False + + +# Create the benchmark +backend_type = get_backend_type(args_cli.benchmark_backend) +benchmark = BaseIsaacLabBenchmark( + benchmark_name="benchmark_rlgames_train", + backend_type=backend_type, + output_path=args_cli.output_path, + use_recorders=True, + frametime_recorders=backend_type in ("summary", "omniperf"), + output_prefix=f"benchmark_rlgames_train_{args_cli.task}", + workflow_metadata={ + "metadata": [ + {"name": "task", "data": args_cli.task}, + {"name": "seed", "data": args_cli.seed}, + {"name": "num_envs", "data": args_cli.num_envs}, + {"name": "max_iterations", "data": args_cli.max_iterations}, + {"name": "presets", "data": get_preset_string(hydra_args)}, + ] + }, +) + + +def main( + env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, + agent_cfg: dict, + app_start_time_begin: int, + app_start_time_end: int, +): + """Train with RL-Games agent.""" + + # override configurations with non-hydra CLI arguments + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + # For distributed training, launch_simulation() already resolved the + # correct per-rank device; only apply a CLI --device override for + # non-distributed runs (the default "cuda:0" would clobber the + # per-rank device otherwise). + if not args_cli.distributed: + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + # check for invalid combination of CPU device with distributed training + if args_cli.distributed and args_cli.device is not None and "cpu" in args_cli.device: + raise ValueError( + "Distributed training is not supported when using CPU device. " + "Please use GPU device (e.g., --device cuda) for distributed training." + ) + + # update agent device to match simulation device (skip for distributed — + # the per-rank device is resolved by launch_simulation) + if args_cli.device is not None and not args_cli.distributed: + agent_cfg["params"]["config"]["device"] = args_cli.device + agent_cfg["params"]["config"]["device_name"] = args_cli.device + + # randomly sample a seed if seed = -1 + if args_cli.seed == -1: + args_cli.seed = random.randint(0, 10000) + agent_cfg["params"]["seed"] = args_cli.seed if args_cli.seed is not None else agent_cfg["params"]["seed"] + + # process distributed + # env_cfg.sim.device is already resolved by launch_simulation(). + world_rank = 0 + if args_cli.distributed: + agent_cfg["params"]["config"]["device"] = env_cfg.sim.device + world_rank = int(os.getenv("RANK", "0")) + + # specify directory for logging experiments + log_root_path = os.path.join("logs", "rl_games", agent_cfg["params"]["config"]["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 + log_dir = agent_cfg["params"]["config"].get("full_experiment_name", datetime.now().strftime("%Y-%m-%d_%H-%M-%S")) + # set directory into agent config + # logging directory path: / + agent_cfg["params"]["config"]["train_dir"] = log_root_path + agent_cfg["params"]["config"]["full_experiment_name"] = log_dir + + # multi-gpu training config + if args_cli.distributed: + agent_cfg["params"]["seed"] += int(os.getenv("RANK", "0")) + agent_cfg["params"]["config"]["device"] = env_cfg.sim.device + agent_cfg["params"]["config"]["device_name"] = env_cfg.sim.device + agent_cfg["params"]["config"]["multi_gpu"] = True + + # max iterations + if args_cli.max_iterations: + agent_cfg["params"]["config"]["max_epochs"] = args_cli.max_iterations + + # dump the configuration into log-directory + dump_yaml(os.path.join(log_root_path, log_dir, "params", "env.yaml"), env_cfg) + dump_yaml(os.path.join(log_root_path, log_dir, "params", "agent.yaml"), agent_cfg) + + # read configurations about the agent-training + rl_device = agent_cfg["params"]["config"]["device"] + clip_obs = agent_cfg["params"]["env"].get("clip_observations", math.inf) + clip_actions = agent_cfg["params"]["env"].get("clip_actions", math.inf) + + task_startup_time_begin = time.perf_counter_ns() + + # 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_root_path, 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 rl-games + env = RlGamesVecEnvWrapper(env, rl_device, clip_obs, clip_actions) + + task_startup_time_end = time.perf_counter_ns() + + # register the environment to rl-games registry + # note: in agents configuration: environment name must be "rlgpu" + vecenv.register( + "IsaacRlgWrapper", lambda config_name, num_actors, **kwargs: RlGamesGpuEnv(config_name, num_actors, **kwargs) + ) + env_configurations.register("rlgpu", {"vecenv_type": "IsaacRlgWrapper", "env_creator": lambda **kwargs: env}) + + # set number of actors into agent config + agent_cfg["params"]["config"]["num_actors"] = env.unwrapped.num_envs + # always track the success metric; early-stop only if --check_success + observer = RlGamesEarlyStopObserver(IsaacAlgoObserver(), **build_success_kwargs(args_cli)) + runner = Runner(observer) + runner.load(agent_cfg) + + # set seed of the env + env.seed(agent_cfg["params"]["seed"]) + # reset the agent and env + runner.reset() + + # train the agent with continuous benchmark monitoring + with BenchmarkMonitor(benchmark, interval=1.0): + runner.run({"train": True, "play": False, "sigma": None}) + + if world_rank == 0: + # Final update after training completes + benchmark.update_manual_recorders() + + # parse tensorboard file stats + tensorboard_log_dir = os.path.join(log_root_path, log_dir, "summaries") + log_data = parse_tf_logs(tensorboard_log_dir) + + # prepare RL timing dict + rl_training_times = { + "Environment only step time": log_data["performance/step_time"], + "Environment + Inference step time": log_data["performance/step_inference_time"], + "Environment + Inference + Policy update time": log_data["performance/rl_update_time"], + "Environment only FPS": log_data["performance/step_fps"], + "Environment + Inference FPS": log_data["performance/step_inference_fps"], + "Environment + Inference + Policy update FPS": log_data["performance/step_inference_rl_update_fps"], + } + + # log additional metrics to benchmark services + log_app_start_time(benchmark, (app_start_time_end - app_start_time_begin) / 1e6) + log_python_imports_time(benchmark, (imports_time_end - imports_time_begin) / 1e6) + log_task_start_time(benchmark, (task_startup_time_end - task_startup_time_begin) / 1e6) + log_scene_creation_time(benchmark, Timer.get_timer_info("scene_creation") * 1000) + log_simulation_start_time(benchmark, Timer.get_timer_info("simulation_start") * 1000) + log_total_start_time(benchmark, (task_startup_time_end - app_start_time_begin) / 1e6) + log_runtime_step_times(benchmark, rl_training_times, compute_stats=True) + log_rl_training_metrics( + benchmark, + log_data, + reward_tag="rewards/iter", + episode_length_tag="episode_lengths/iter", + task=args_cli.task, + workflow="rl_games", + should_check_convergence=args_cli.check_convergence, + reward_threshold=args_cli.reward_threshold, + convergence_config=args_cli.convergence_config, + ) + + tracker = get_success_tracker(args_cli, observer.tracker, log_data) + log_success(benchmark, tracker, framework_iteration_count=observer.framework_iteration_count) + + benchmark._finalize_impl() + + # close the simulator + env.close() + + +if __name__ == "__main__": + env_cfg, agent_cfg = resolve_task_config(args_cli.task, "rl_games_cfg_entry_point") + + app_start_time_begin = time.perf_counter_ns() + with launch_simulation(env_cfg, args_cli): + app_start_time_end = time.perf_counter_ns() + main(env_cfg, agent_cfg, app_start_time_begin, app_start_time_end) diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_rsl_rl.py b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_rsl_rl.py new file mode 100644 index 0000000000000000000000000000000000000000..3b72524acbc1ae0e1bcb16aab35a0faeb35c12b3 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_rsl_rl.py @@ -0,0 +1,315 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to benchmark RL agent with RSL-RL.""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +import contextlib +import os +import sys +import time + +from isaaclab.app import AppLauncher + +from isaaclab_tasks.utils import setup_preset_cli + +from scripts.benchmarks.early_stop import ( + RslRlEarlyStopWrapper, + add_success_cli_args, + build_success_kwargs, + get_success_tracker, +) + +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../..")) +import scripts.reinforcement_learning.rsl_rl.cli_args as cli_args # isort: skip + +# 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("--num_envs", type=int, default=4096, 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=42, help="Seed used for the environment") +parser.add_argument("--max_iterations", type=int, default=10, help="RL Policy training iterations.") +parser.add_argument( + "--distributed", action="store_true", default=False, help="Run training with multiple GPUs or nodes." +) +parser.add_argument( + "--benchmark_backend", + type=str, + default="omniperf", + choices=[ + "json", + "osmo", + "omniperf", + "summary", + "LocalLogMetrics", + "JSONFileMetrics", + "OsmoKPIFile", + "OmniPerfKPIFile", + ], + help="Benchmarking backend options, defaults omniperf", +) +parser.add_argument("--output_path", type=str, default=".", help="Path to output benchmark results.") +parser.add_argument( + "--reward_threshold", type=float, default=None, help="Reward threshold for convergence (overrides config)." +) +parser.add_argument( + "--check_convergence", action="store_true", help="Check reward convergence using thresholds from configs.yaml." +) +parser.add_argument( + "--convergence_config", type=str, default="full", help="Config mode for convergence thresholds (default: full)." +) +add_success_cli_args(parser) + +# append RSL-RL cli arguments +cli_args.add_rsl_rl_args(parser) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args +if args_cli.video: + args_cli.enable_cameras = True + +imports_time_begin = time.perf_counter_ns() + +import importlib.metadata as metadata +from datetime import datetime + +import gymnasium as gym +import numpy as np +import torch +from rsl_rl.runners import OnPolicyRunner + +from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg +from isaaclab.utils.dict import print_dict +from isaaclab.utils.io import dump_yaml + +from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper, handle_deprecated_rsl_rl_cfg + +import isaaclab_tasks # noqa: F401 + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 +from isaaclab_tasks.utils import get_checkpoint_path, launch_simulation, resolve_task_config + +imports_time_end = time.perf_counter_ns() + +from isaaclab.test.benchmark import BaseIsaacLabBenchmark, BenchmarkMonitor +from isaaclab.utils.timer import Timer + +from scripts.benchmarks.utils import ( + get_backend_type, + get_preset_string, + log_app_start_time, + log_python_imports_time, + log_rl_training_metrics, + log_runtime_step_times, + log_scene_creation_time, + log_simulation_start_time, + log_success, + log_task_start_time, + log_total_start_time, + parse_tf_logs, +) + +torch.backends.cuda.matmul.allow_tf32 = True +torch.backends.cudnn.allow_tf32 = True +torch.backends.cudnn.deterministic = False +torch.backends.cudnn.benchmark = False + +# Create the benchmark +backend_type = get_backend_type(args_cli.benchmark_backend) +benchmark = BaseIsaacLabBenchmark( + benchmark_name="benchmark_rsl_rl_train", + backend_type=backend_type, + output_path=args_cli.output_path, + use_recorders=True, + frametime_recorders=backend_type in ("summary", "omniperf"), + output_prefix=f"benchmark_rsl_rl_train_{args_cli.task}", + workflow_metadata={ + "metadata": [ + {"name": "task", "data": args_cli.task}, + {"name": "seed", "data": args_cli.seed}, + {"name": "num_envs", "data": args_cli.num_envs}, + {"name": "max_iterations", "data": args_cli.max_iterations}, + {"name": "presets", "data": get_preset_string(hydra_args)}, + ] + }, +) + + +def main( + env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, + agent_cfg: RslRlOnPolicyRunnerCfg, + app_start_time_begin: int, + app_start_time_end: int, +): + """Train with RSL-RL agent.""" + # parse configuration + # override configurations with non-hydra CLI arguments + agent_cfg = cli_args.update_rsl_rl_cfg(agent_cfg, args_cli) + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + agent_cfg.max_iterations = ( + args_cli.max_iterations if args_cli.max_iterations is not None else agent_cfg.max_iterations + ) + + # set the environment seed + # note: certain randomizations occur in the environment initialization so we set the seed here + env_cfg.seed = agent_cfg.seed + # For distributed training, launch_simulation() already resolved the + # correct per-rank device; only apply a CLI --device override for + # non-distributed runs (the default "cuda:0" would clobber the + # per-rank device otherwise). + if not args_cli.distributed: + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + # check for invalid combination of CPU device with distributed training + if args_cli.distributed and args_cli.device is not None and "cpu" in args_cli.device: + raise ValueError( + "Distributed training is not supported when using CPU device. " + "Please use GPU device (e.g., --device cuda) for distributed training." + ) + + # multi-gpu training configuration + # env_cfg.sim.device is already resolved by launch_simulation(). + world_rank = 0 + world_size = 1 + if args_cli.distributed: + agent_cfg.device = env_cfg.sim.device + + # use global rank for seed diversity across all nodes + world_rank = int(os.getenv("RANK", "0")) + seed = agent_cfg.seed + world_rank + env_cfg.seed = seed + agent_cfg.seed = seed + world_size = int(os.getenv("WORLD_SIZE", 1)) + + # 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) + + # max iterations for training + if args_cli.max_iterations: + agent_cfg.max_iterations = args_cli.max_iterations + + task_startup_time_begin = time.perf_counter_ns() + + # 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) + + task_startup_time_end = time.perf_counter_ns() + + # handle deprecated configurations (e.g. legacy policy -> actor/critic migration) + agent_cfg = handle_deprecated_rsl_rl_cfg(agent_cfg, metadata.version("rsl-rl-lib")) + + # 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) + + # always track the success metric; early-stop only if --check_success + early_stop_ctx = RslRlEarlyStopWrapper( + env, runner, num_steps_per_env=agent_cfg.num_steps_per_env, **build_success_kwargs(args_cli) + ) + + # run training with continuous benchmark monitoring + with early_stop_ctx, BenchmarkMonitor(benchmark, interval=1.0): + runner.learn(num_learning_iterations=agent_cfg.max_iterations, init_at_random_ep_len=True) + + if world_rank == 0: + # Final update after training completes + benchmark.update_manual_recorders() + + # parse tensorboard file stats + log_data = parse_tf_logs(log_dir) + + # prepare RL timing dict + collection_fps = ( + 1 + / (np.array(log_data["Perf/collection_time"])) + * env.unwrapped.num_envs + * agent_cfg.num_steps_per_env + * world_size + ) + rl_training_times = { + "Collection Time": (np.array(log_data["Perf/collection_time"]) / 1000).tolist(), + "Learning Time": (np.array(log_data["Perf/learning_time"]) / 1000).tolist(), + "Collection FPS": collection_fps.tolist(), + "Total FPS": log_data["Perf/total_fps"] * world_size, + } + + # log additional metrics to benchmark services + log_app_start_time(benchmark, (app_start_time_end - app_start_time_begin) / 1e6) + log_python_imports_time(benchmark, (imports_time_end - imports_time_begin) / 1e6) + log_task_start_time(benchmark, (task_startup_time_end - task_startup_time_begin) / 1e6) + log_scene_creation_time(benchmark, Timer.get_timer_info("scene_creation") * 1000) + log_simulation_start_time(benchmark, Timer.get_timer_info("simulation_start") * 1000) + log_total_start_time(benchmark, (task_startup_time_end - app_start_time_begin) / 1e6) + log_runtime_step_times(benchmark, rl_training_times, compute_stats=True) + log_rl_training_metrics( + benchmark, + log_data, + reward_tag="Train/mean_reward", + episode_length_tag="Train/mean_episode_length", + task=args_cli.task, + workflow="rsl_rl", + should_check_convergence=args_cli.check_convergence, + reward_threshold=args_cli.reward_threshold, + convergence_config=args_cli.convergence_config, + ) + + tracker = get_success_tracker(args_cli, early_stop_ctx.tracker, log_data) + log_success(benchmark, tracker, framework_iteration_count=early_stop_ctx.framework_iteration_count) + + benchmark._finalize_impl() + + # close the simulator + env.close() + + +if __name__ == "__main__": + env_cfg, agent_cfg = resolve_task_config(args_cli.task, "rsl_rl_cfg_entry_point") + + app_start_time_begin = time.perf_counter_ns() + with launch_simulation(env_cfg, args_cli): + app_start_time_end = time.perf_counter_ns() + main(env_cfg, agent_cfg, app_start_time_begin, app_start_time_end) diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_startup.py b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_startup.py new file mode 100644 index 0000000000000000000000000000000000000000..4e5b7b0055b14c107d8d66203c70c9241f4f6e9c --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_startup.py @@ -0,0 +1,352 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to profile IsaacLab startup phases with cProfile. + +Each startup stage (app launch, python imports, env creation, first step) is +wrapped in its own cProfile session. The top functions by own-time are emitted +as SingleMeasurement entries (both own-time and cumulative time) via the +standard benchmark backend. +""" + +import argparse +import cProfile +import os +import sys +import time + +from isaaclab.app import AppLauncher + +from isaaclab_tasks.utils import setup_preset_cli + +# -- CLI arguments ----------------------------------------------------------- + +parser = argparse.ArgumentParser(description="Profile IsaacLab startup phases.") +parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") +parser.add_argument("--task", type=str, required=True, help="Name of the task.") +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument( + "--top_n", + type=int, + default=None, + help="Number of top functions per phase (default: 30, or 5 with --whitelist_config).", +) +parser.add_argument( + "--benchmark_backend", + type=str, + default="omniperf", + choices=[ + "json", + "osmo", + "omniperf", + "summary", + "LocalLogMetrics", + "JSONFileMetrics", + "OsmoKPIFile", + "OmniPerfKPIFile", + ], + help="Benchmarking backend options, defaults omniperf", +) +parser.add_argument("--output_path", type=str, default=".", help="Path to output benchmark results.") +parser.add_argument( + "--whitelist_config", + type=str, + default=None, + help="Path to YAML file with per-phase function whitelist patterns. Overrides --top_n for listed phases.", +) + +# append AppLauncher cli args (provides --device, --headless, etc.) +AppLauncher.add_app_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args + +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../..")) + +from isaaclab.test.benchmark import BaseIsaacLabBenchmark, SingleMeasurement +from isaaclab.utils.timer import Timer, TimerError + +from scripts.benchmarks.utils import ( + get_backend_type, + get_preset_string, + parse_cprofile_stats, +) + +# -- Python imports (profiled) ------------------------------------------------ + +imports_profile = cProfile.Profile() +imports_time_begin = time.perf_counter_ns() +imports_profile.enable() + +import gymnasium as gym # noqa: E402 +import numpy as np # noqa: E402 +import torch # noqa: E402 + +from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg # noqa: E402 + +from isaaclab_tasks.utils import launch_simulation, resolve_task_config # noqa: E402 + +imports_profile.disable() + +if torch.cuda.is_available() and torch.cuda.is_initialized(): + torch.cuda.synchronize() +imports_time_end = time.perf_counter_ns() + +# -- Resolve task config (profiled) ------------------------------------------ + +task_config_profile = cProfile.Profile() +task_config_time_begin = time.perf_counter_ns() +task_config_profile.enable() + +env_cfg, _agent_cfg = resolve_task_config(args_cli.task, None) + +task_config_profile.disable() +task_config_time_end = time.perf_counter_ns() + +# -- Detect IsaacLab source prefixes for filtering --------------------------- + +_REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")) +_source_dir = os.path.join(_REPO_ROOT, "source") +if os.path.isdir(_source_dir): + _ISAACLAB_PREFIXES = [ + os.path.join(_source_dir, d) for d in os.listdir(_source_dir) if os.path.isdir(os.path.join(_source_dir, d)) + ] +else: + print(f"[WARNING] IsaacLab source directory not found at '{_source_dir}'. Function-level profiling will be empty.") + _ISAACLAB_PREFIXES = [] + +# -- Load whitelist config if provided --------------------------------------- + +_WHITELIST: dict[str, list[str]] = {} +if args_cli.whitelist_config is not None: + import yaml + + try: + with open(args_cli.whitelist_config) as f: + raw = yaml.safe_load(f) + except OSError as e: + print(f"[ERROR] Cannot read whitelist config '{args_cli.whitelist_config}': {e}") + sys.exit(1) + except yaml.YAMLError as e: + print(f"[ERROR] Invalid YAML in whitelist config '{args_cli.whitelist_config}': {e}") + sys.exit(1) + + if raw is None: + _WHITELIST = {} + elif not isinstance(raw, dict): + print( + f"[ERROR] Whitelist config must be a YAML mapping (got {type(raw).__name__})." + " Expected format: phase_name: [pattern, ...]" + ) + sys.exit(1) + else: + _VALID_PHASES = {"app_launch", "python_imports", "task_config", "env_creation", "first_step"} + unknown_phases = set(raw.keys()) - _VALID_PHASES + if unknown_phases: + print( + f"[WARNING] Whitelist config contains unknown phase(s): {unknown_phases}. " + f"Valid phases: {_VALID_PHASES}. Check for typos." + ) + for phase_name, patterns in raw.items(): + if not isinstance(patterns, list) or not all(isinstance(p, str) for p in patterns): + print( + f"[ERROR] Whitelist phase '{phase_name}' must be a list of strings, " + f"got {type(patterns).__name__}. Check YAML formatting (use '- pattern' syntax)." + ) + sys.exit(1) + _WHITELIST = raw + +# Resolve top_n default: 5 when using whitelist (fallback phases stay compact), 30 otherwise +if args_cli.top_n is None: + args_cli.top_n = 5 if _WHITELIST else 30 + +# -- Create the benchmark instance ------------------------------------------ + +env_cfg.seed = args_cli.seed if args_cli.seed is not None else env_cfg.seed + +backend_type = get_backend_type(args_cli.benchmark_backend) +benchmark = BaseIsaacLabBenchmark( + benchmark_name="benchmark_startup", + backend_type=backend_type, + output_path=args_cli.output_path, + use_recorders=True, + output_prefix=f"benchmark_startup_{args_cli.task}", + workflow_metadata={ + "metadata": [ + {"name": "task", "data": args_cli.task}, + {"name": "seed", "data": args_cli.seed}, + {"name": "num_envs", "data": args_cli.num_envs}, + {"name": "top_n", "data": args_cli.top_n}, + {"name": "presets", "data": get_preset_string(hydra_args)}, + ] + }, +) + + +# -- Main profiling logic --------------------------------------------------- + + +def main( + env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, + app_launch_profile: cProfile.Profile, + app_launch_wall_ms: float, +): + """Profile env creation and first step, then log all phase measurements. + + Args: + env_cfg: Resolved environment configuration for the task. + app_launch_profile: cProfile session from the app-launch phase. + app_launch_wall_ms: Wall-clock duration of the app-launch phase [ms]. + """ + + # Override config with CLI args + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + env_cfg.seed = args_cli.seed if args_cli.seed is not None else env_cfg.seed + + # -- Env creation (gym.make + env.reset) profiled --------------------------- + + env = None + env_creation_profile = cProfile.Profile() + env_creation_time_begin = time.perf_counter_ns() + env_creation_profile.enable() + try: + env = gym.make(args_cli.task, cfg=env_cfg) + env.reset() + finally: + env_creation_profile.disable() + + try: + if torch.cuda.is_available() and torch.cuda.is_initialized(): + torch.cuda.synchronize() + env_creation_time_end = time.perf_counter_ns() + # -- First step profiled ------------------------------------------------ + + # Sample random actions from the action space directly to support + # Box, Discrete, MultiDiscrete, and Dict spaces. + np_actions = np.stack([env.unwrapped.single_action_space.sample() for _ in range(env.unwrapped.num_envs)]) + actions = torch.as_tensor(np_actions, dtype=torch.float32, device=env.unwrapped.device) + + first_step_profile = cProfile.Profile() + first_step_time_begin = time.perf_counter_ns() + first_step_profile.enable() + try: + with torch.inference_mode(): + env.step(actions) + finally: + first_step_profile.disable() + + if torch.cuda.is_available() and torch.cuda.is_initialized(): + torch.cuda.synchronize() + first_step_time_end = time.perf_counter_ns() + + # -- Parse all profiles and log measurements ---------------------------- + + imports_wall_ms = (imports_time_end - imports_time_begin) / 1e6 + task_config_wall_ms = (task_config_time_end - task_config_time_begin) / 1e6 + env_creation_wall_ms = (env_creation_time_end - env_creation_time_begin) / 1e6 + first_step_wall_ms = (first_step_time_end - first_step_time_begin) / 1e6 + + # Collect Timer-based sub-timings for env_creation phase (may not exist for all environment types) + scene_creation_ms = None + try: + scene_creation_ms = Timer.get_timer_info("scene_creation") * 1000 + except TimerError: + print("[INFO] Timer 'scene_creation' not available; sub-timing will be omitted.") + + simulation_start_ms = None + try: + simulation_start_ms = Timer.get_timer_info("simulation_start") * 1000 + except TimerError: + print("[INFO] Timer 'simulation_start' not available; sub-timing will be omitted.") + + phases = { + "app_launch": { + "profile": app_launch_profile, + "wall_clock_ms": app_launch_wall_ms, + "extra_measurements": [], + }, + "python_imports": { + "profile": imports_profile, + "wall_clock_ms": imports_wall_ms, + "extra_measurements": [], + }, + "task_config": { + "profile": task_config_profile, + "wall_clock_ms": task_config_wall_ms, + "extra_measurements": [], + }, + "env_creation": { + "profile": env_creation_profile, + "wall_clock_ms": env_creation_wall_ms, + "extra_measurements": [ + (name, val) + for name, val in [ + ("Scene Creation Time", scene_creation_ms), + ("Simulation Start Time", simulation_start_ms), + ] + if val is not None + ], + }, + "first_step": { + "profile": first_step_profile, + "wall_clock_ms": first_step_wall_ms, + "extra_measurements": [], + }, + } + + # Parse profiles and log measurements to benchmark + for phase_name, phase_data in phases.items(): + phase_whitelist = _WHITELIST.get(phase_name) + functions = parse_cprofile_stats( + phase_data["profile"], _ISAACLAB_PREFIXES, top_n=args_cli.top_n, whitelist=phase_whitelist + ) + wall_ms = phase_data["wall_clock_ms"] + extras = phase_data["extra_measurements"] + + # Log wall-clock time + benchmark.add_measurement( + phase_name, measurement=SingleMeasurement(name="Wall Clock Time", value=wall_ms, unit="ms") + ) + + # Log extra sub-timings + for extra_name, extra_val in extras: + benchmark.add_measurement( + phase_name, measurement=SingleMeasurement(name=extra_name, value=extra_val, unit="ms") + ) + + # Log per-function measurements (tottime + cumtime) + for label, tottime_ms, cumtime_ms in functions: + benchmark.add_measurement( + phase_name, measurement=SingleMeasurement(name=label, value=round(tottime_ms, 2), unit="ms") + ) + benchmark.add_measurement( + phase_name, + measurement=SingleMeasurement(name=f"{label} (cumtime)", value=round(cumtime_ms, 2), unit="ms"), + ) + + # Finalize benchmark output + benchmark.update_manual_recorders() + benchmark._finalize_impl() + finally: + if env is not None: + env.close() + + +if __name__ == "__main__": + # -- App launch (profiled) -------------------------------------------------- + + app_launch_profile = cProfile.Profile() + app_launch_time_begin = time.perf_counter_ns() + app_launch_profile.enable() + + with launch_simulation(env_cfg, args_cli): + app_launch_profile.disable() + + if torch.cuda.is_available() and torch.cuda.is_initialized(): + torch.cuda.synchronize() + app_launch_time_end = time.perf_counter_ns() + + app_launch_wall_ms = (app_launch_time_end - app_launch_time_begin) / 1e6 + main(env_cfg, app_launch_profile, app_launch_wall_ms) diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_view_comparison.py b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_view_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..aa5927e10b6ab3eef8324c67823cd1a3f3f110c4 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_view_comparison.py @@ -0,0 +1,448 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Benchmark script comparing FrameView backends and PhysX RigidBodyView. + +Compares batched transform operation performance across: + +- **USD** (baseline): Isaac Lab's FrameView via USD XformCache +- **Fabric**: Isaac Lab's FrameView via Fabric GPU arrays +- **Newton**: Isaac Lab's Newton FrameView via Warp site kernels +- **PhysX**: PhysX RigidBodyView via PhysX tensor API (reference) + +Usage: + # All backends + ./isaaclab.sh -p scripts/benchmarks/benchmark_view_comparison.py --num_envs 1024 --device cuda:0 --headless + + # Select specific backends + ./isaaclab.sh -p scripts/benchmarks/benchmark_view_comparison.py --backends usd fabric newton --headless + + # With profiling + ./isaaclab.sh -p scripts/benchmarks/benchmark_view_comparison.py --num_envs 1024 --profile --headless +""" + +from __future__ import annotations + +import argparse + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser(description="Benchmark FrameView backends and PhysX RigidBodyView.") + +parser.add_argument("--num_envs", type=int, default=1000, help="Number of environments to simulate.") +parser.add_argument("--num_iterations", type=int, default=50, help="Number of iterations for each test.") +parser.add_argument( + "--backends", + nargs="+", + default=["usd", "fabric", "newton", "physx"], + choices=["usd", "fabric", "newton", "physx"], + help="Backends to benchmark. Default: all four.", +) +parser.add_argument( + "--profile", + action="store_true", + help="Enable profiling with cProfile. Results saved as .prof files for snakeviz visualization.", +) +parser.add_argument( + "--profile_dir", + type=str, + default="./profile_results", + help="Directory to save profile results. Default: ./profile_results", +) + +AppLauncher.add_app_launcher_args(parser) +args_cli = parser.parse_args() + +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import cProfile +import time + +import torch +import warp as wp + +from pxr import Gf + +import isaaclab.sim as sim_utils +from isaaclab.sim.views import FrameView + +try: + from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + from isaaclab_newton.sim.views import NewtonSiteFrameView + + HAS_NEWTON = True +except ImportError: + HAS_NEWTON = False + + +# ------------------------------------------------------------------ +# Benchmark functions +# ------------------------------------------------------------------ + + +@torch.no_grad() +def benchmark_usd_or_fabric(view_type: str, num_iterations: int) -> dict[str, float]: + """Benchmark USD or Fabric FrameView.""" + timing_results = {} + + print(" Setting up scene") + sim_utils.create_new_stage() + start_time = time.perf_counter() + sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device, use_fabric=(view_type == "fabric")) + sim = sim_utils.SimulationContext(sim_cfg) + stage = sim_utils.get_current_stage() + print(f" SimulationContext: {time.perf_counter() - start_time:.4f}s") + + object_cfg = sim_utils.ConeCfg( + radius=0.15, + height=0.5, + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)), + ) + for i in range(args_cli.num_envs): + sim_utils.create_prim(f"/World/Env_{i}", "Xform", stage=stage, translation=(i * 2.0, 0.0, 0.0)) + object_cfg.func(f"/World/Env_{i}/Object", object_cfg, translation=(0.0, 0.0, 1.0)) + prim = stage.DefinePrim(f"/World/Env_{i}/Object/Sensor", "Xform") + sim_utils.standardize_xform_ops(prim) + prim.GetAttribute("xformOp:translate").Set(Gf.Vec3d(0.1, 0.0, 0.05)) + prim.GetAttribute("xformOp:orient").Set(Gf.Quatd(1.0, 0.0, 0.0, 0.0)) + + sim.reset() + + pattern = "/World/Env_.*/Object/Sensor" + + start_time = time.perf_counter() + if view_type == "fabric" and "cuda" not in args_cli.device: + raise ValueError("Fabric backend requires CUDA.") + view = FrameView(pattern, device=args_cli.device, validate_xform_ops=False) + num_prims = view.count + timing_results["init"] = time.perf_counter() - start_time + + print(f" FrameView ({view_type.upper()}) managing {num_prims} prims") + + positions, orientations = view.get_world_poses() + + _run_pose_benchmarks(view, num_prims, num_iterations, timing_results, positions, orientations) + + sim.clear_instance() + return timing_results + + +@torch.no_grad() +def benchmark_newton(num_iterations: int) -> dict[str, float]: + """Benchmark Newton FrameView.""" + from isaaclab.assets import RigidObjectCfg + from isaaclab.scene import InteractiveScene, InteractiveSceneCfg + from isaaclab.sim import SimulationCfg, build_simulation_context + from isaaclab.utils.configclass import configclass + + timing_results = {} + + @configclass + class _SceneCfg(InteractiveSceneCfg): + cube: RigidObjectCfg = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.2, 0.2, 0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 1.0)), + ) + + print(" Setting up Newton scene") + newton_cfg = SimulationCfg(physics=NewtonCfg(solver_cfg=MJWarpSolverCfg()), device=args_cli.device) + start_time = time.perf_counter() + ctx = build_simulation_context(device=args_cli.device, sim_cfg=newton_cfg, add_ground_plane=True) + sim = ctx.__enter__() + sim._app_control_on_stop_handle = None + InteractiveScene(_SceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0)) + + stage = sim_utils.get_current_stage() + for i in range(args_cli.num_envs): + prim = stage.DefinePrim(f"/World/envs/env_{i}/Cube/Sensor", "Xform") + sim_utils.standardize_xform_ops(prim) + prim.GetAttribute("xformOp:translate").Set(Gf.Vec3d(0.1, 0.0, 0.05)) + prim.GetAttribute("xformOp:orient").Set(Gf.Quatd(1.0, 0.0, 0.0, 0.0)) + + sim.reset() + print(f" Newton scene setup: {time.perf_counter() - start_time:.4f}s") + + start_time = time.perf_counter() + view = NewtonSiteFrameView("/World/envs/env_.*/Cube/Sensor", device=args_cli.device) + num_prims = view.count + timing_results["init"] = time.perf_counter() - start_time + + print(f" Newton FrameView managing {num_prims} prims") + + positions, orientations = view.get_world_poses() + + _run_pose_benchmarks(view, num_prims, num_iterations, timing_results, positions, orientations) + + ctx.__exit__(None, None, None) + return timing_results + + +@torch.no_grad() +def benchmark_physx(num_iterations: int) -> dict[str, float]: + """Benchmark PhysX RigidBodyView.""" + timing_results = {} + + print(" Setting up scene") + sim_utils.create_new_stage() + start_time = time.perf_counter() + sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device, use_fabric=False) + sim = sim_utils.SimulationContext(sim_cfg) + stage = sim_utils.get_current_stage() + print(f" SimulationContext: {time.perf_counter() - start_time:.4f}s") + + object_cfg = sim_utils.ConeCfg( + radius=0.15, + height=0.5, + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)), + ) + for i in range(args_cli.num_envs): + sim_utils.create_prim(f"/World/Env_{i}", "Xform", stage=stage, translation=(i * 2.0, 0.0, 0.0)) + object_cfg.func(f"/World/Env_{i}/Object", object_cfg, translation=(0.0, 0.0, 1.0)) + + sim.reset() + + pattern = "/World/Env_*/Object" + start_time = time.perf_counter() + physics_sim_view = sim.physics_manager.get_physics_sim_view() + view = physics_sim_view.create_rigid_body_view(pattern) + num_prims = view.count + timing_results["init"] = time.perf_counter() - start_time + + print(f" PhysX RigidBodyView managing {num_prims} prims") + + all_indices = wp.from_torch(torch.arange(num_prims, dtype=torch.int32, device=args_cli.device)) + + transforms = view.get_transforms() + transforms_t = wp.to_torch(transforms) if isinstance(transforms, wp.array) else transforms + positions_t = transforms_t[:, :3] + orientations_t = transforms_t[:, 3:7] + + start_time = time.perf_counter() + for _ in range(num_iterations): + transforms = view.get_transforms() + timing_results["get_world_poses"] = (time.perf_counter() - start_time) / num_iterations + + new_positions = positions_t.clone() + new_positions[:, 2] += 0.5 + expected_positions = new_positions.clone() + new_transforms = wp.from_torch(torch.cat([new_positions, orientations_t], dim=-1).contiguous()) + start_time = time.perf_counter() + for _ in range(num_iterations): + view.set_transforms(new_transforms, indices=all_indices) + timing_results["set_world_poses"] = (time.perf_counter() - start_time) / num_iterations + + transforms_after = view.get_transforms() + ta = wp.to_torch(transforms_after) if isinstance(transforms_after, wp.array) else transforms_after + pos_ok = torch.allclose(ta[:, :3], expected_positions, atol=1e-4, rtol=0) + quat_ok = torch.allclose(ta[:, 3:7], orientations_t, atol=1e-4, rtol=0) + if pos_ok and quat_ok: + print(" Round-trip verification: PASS") + else: + pos_diff = (ta[:, :3] - expected_positions).abs().max().item() + quat_diff = (ta[:, 3:7] - orientations_t).abs().max().item() + print(f" Round-trip verification: FAIL (pos max_diff={pos_diff:.6e}, quat max_diff={quat_diff:.6e})") + + sim.clear_instance() + return timing_results + + +def _run_pose_benchmarks( + view, + num_prims: int, + num_iterations: int, + timing_results: dict, + positions: wp.array, + orientations: wp.array, +): + """Shared benchmark loop for get/set world poses on any FrameView.""" + start_time = time.perf_counter() + for _ in range(num_iterations): + view.get_world_poses() + timing_results["get_world_poses"] = (time.perf_counter() - start_time) / num_iterations + + new_positions = wp.clone(positions) + new_positions_t = wp.to_torch(new_positions) + new_positions_t[:, 2] += 0.5 + expected_positions = new_positions_t.clone() + + start_time = time.perf_counter() + for _ in range(num_iterations): + view.set_world_poses(new_positions, orientations) + timing_results["set_world_poses"] = (time.perf_counter() - start_time) / num_iterations + + ret_pos, ret_quat = view.get_world_poses() + ret_pos_t = wp.to_torch(ret_pos) + ret_quat_t = wp.to_torch(ret_quat) + ori_t = wp.to_torch(orientations) + + pos_ok = torch.allclose(ret_pos_t, expected_positions, atol=1e-4, rtol=0) + quat_ok = torch.allclose(ret_quat_t, ori_t, atol=1e-4, rtol=0) + if pos_ok and quat_ok: + print(" Round-trip verification: PASS") + else: + pos_diff = (ret_pos_t - expected_positions).abs().max().item() + quat_diff = (ret_quat_t - ori_t).abs().max().item() + print(f" Round-trip verification: FAIL (pos max_diff={pos_diff:.6e}, quat max_diff={quat_diff:.6e})") + + +# ------------------------------------------------------------------ +# Reporting +# ------------------------------------------------------------------ + + +def print_results(results_dict: dict[str, dict[str, float]], num_prims: int, num_iterations: int): + """Print benchmark results in a formatted table.""" + print("\n" + "=" * 120) + print(f"BENCHMARK RESULTS: {num_prims} prims, {num_iterations} iterations") + print("=" * 120) + + impl_names = list(results_dict.keys()) + display_names = {n: n.replace("_", " ").title() for n in impl_names} + col_width = 22 + + header = f"{'Operation':<25}" + for name in impl_names: + header += f" {display_names[name] + ' (ms)':>{col_width}}" + print(header) + print("-" * 120) + + operations = [ + ("Initialization", "init"), + ("Get World Poses", "get_world_poses"), + ("Set World Poses", "set_world_poses"), + ] + + for op_name, op_key in operations: + row = f"{op_name:<25}" + for name in impl_names: + val = results_dict[name].get(op_key, 0) * 1000 + row += f" {val:>{col_width}.4f}" + print(row) + + print("=" * 120) + + total_row = f"{'Total':<25}" + for name in impl_names: + total = sum(results_dict[name].values()) * 1000 + total_row += f" {total:>{col_width}.4f}" + print(total_row) + + baseline = "usd" + if baseline in results_dict and len(impl_names) > 1: + print("\n" + "=" * 120) + print(f"SPEEDUP vs {display_names[baseline]}") + print("=" * 120) + header = f"{'Operation':<25}" + for name in impl_names: + if name != baseline: + header += f" {display_names[name]:>{col_width}}" + print(header) + print("-" * 120) + + base = results_dict[baseline] + for op_name, op_key in operations: + row = f"{op_name:<25}" + base_t = base.get(op_key, 0) + for name in impl_names: + if name != baseline: + impl_t = results_dict[name].get(op_key, 0) + if base_t > 0 and impl_t > 0: + row += f" {base_t / impl_t:>{col_width}.2f}x" + else: + row += f" {'N/A':>{col_width}}" + print(row) + print("=" * 120) + + print("\nNotes:") + print(" - Times are averaged over all iterations") + print(" - Speedup > 1.0 means faster than USD baseline") + print(" - PhysX RigidBodyView requires rigid body physics; FrameView works with any Xformable prim") + print() + + +# ------------------------------------------------------------------ +# Main +# ------------------------------------------------------------------ + + +def main(): + print("=" * 120) + print("FrameView Benchmark: USD vs Fabric vs Newton vs PhysX") + print("=" * 120) + print(f" Environments: {args_cli.num_envs}") + print(f" Iterations: {args_cli.num_iterations}") + print(f" Device: {args_cli.device}") + print(f" Backends: {', '.join(args_cli.backends)}") + print() + + if args_cli.profile: + import os + + os.makedirs(args_cli.profile_dir, exist_ok=True) + + all_timing = {} + profile_files = {} + + dispatch = { + "usd": ("usd", "FrameView (USD)", lambda n: benchmark_usd_or_fabric("usd", n)), + "fabric": ("fabric", "FrameView (Fabric)", lambda n: benchmark_usd_or_fabric("fabric", n)), + "newton": ("newton", "FrameView (Newton)", lambda n: benchmark_newton(n)), + "physx": ("physx", "PhysX RigidBodyView", lambda n: benchmark_physx(n)), + } + + for backend in args_cli.backends: + if backend == "newton" and not HAS_NEWTON: + print(f"Skipping {backend}: isaaclab_newton not installed") + continue + + key, display_name, bench_fn = dispatch[backend] + print(f"Benchmarking {display_name}...") + + if args_cli.profile: + profiler = cProfile.Profile() + profiler.enable() + + timing = bench_fn(args_cli.num_iterations) + + if args_cli.profile: + profiler.disable() + pf = f"{args_cli.profile_dir}/{key}_benchmark.prof" + profiler.dump_stats(pf) + profile_files[key] = pf + print(f" Profile saved to: {pf}") + + all_timing[key] = timing + print(" Done!\n") + + print_results(all_timing, args_cli.num_envs, args_cli.num_iterations) + + if args_cli.profile: + print("\n" + "=" * 100) + print("PROFILING RESULTS") + print("=" * 100) + for key, pf in profile_files.items(): + print(f" snakeviz {pf}") + print() + + sim_utils.SimulationContext.clear_instance() + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_xform_prim_view.py b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_xform_prim_view.py new file mode 100644 index 0000000000000000000000000000000000000000..fee3b9642c79b2738db6a3e291e18864b7b4080e --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/benchmark_xform_prim_view.py @@ -0,0 +1,394 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Benchmark script comparing FrameView implementations across backends. + +Compares batched transform operation performance across: +- Isaac Lab FrameView (USD backend) -- baseline +- Isaac Lab FrameView (Fabric backend) +- Isaac Lab FrameView (Newton backend) + +Usage: + ./isaaclab.sh -p scripts/benchmarks/benchmark_xform_prim_view.py --num_envs 1024 --device cuda:0 --headless + + # With profiling + ./isaaclab.sh -p scripts/benchmarks/benchmark_xform_prim_view.py --num_envs 1024 --profile --headless +""" + +from __future__ import annotations + +import argparse + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser(description="Benchmark FrameView performance across backends.") +parser.add_argument("--num_envs", type=int, default=100, help="Number of environments to simulate.") +parser.add_argument("--num_iterations", type=int, default=50, help="Number of iterations for each test.") +parser.add_argument("--profile", action="store_true", help="Enable cProfile profiling.") +parser.add_argument("--profile_dir", type=str, default="./profile_results", help="Directory for .prof files.") + +AppLauncher.add_app_launcher_args(parser) +args_cli = parser.parse_args() + +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import cProfile +import time +from typing import Literal + +import torch +import warp as wp +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +from isaaclab_newton.sim.views import NewtonSiteFrameView +from isaaclab_physx.sim.views import FabricFrameView + +from pxr import Gf + +import isaaclab.sim as sim_utils +from isaaclab.assets import RigidObjectCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sim import SimulationCfg, build_simulation_context +from isaaclab.sim.views import UsdFrameView +from isaaclab.utils.configclass import configclass + + +@configclass +class _NewtonSceneCfg(InteractiveSceneCfg): + cube: RigidObjectCfg = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Object", + spawn=sim_utils.CuboidCfg( + size=(0.2, 0.2, 0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 1.0)), + ) + + +# ------------------------------------------------------------------ +# Benchmark +# ------------------------------------------------------------------ + + +@torch.no_grad() +def benchmark_frame_view( # noqa: C901 + api: Literal["isaaclab-usd", "isaaclab-fabric", "isaaclab-newton-site"], + num_iterations: int, +) -> tuple[dict[str, float], dict[str, torch.Tensor]]: + """Benchmark get/set world/local poses for the given FrameView backend.""" + timing_results: dict[str, float] = {} + computed_results: dict[str, torch.Tensor] = {} + device = args_cli.device + num_envs = args_cli.num_envs + + # -- Scene setup (backend-specific) -------------------------------- + + print(" Setting up scene") + cleanup = None + + if api == "isaaclab-newton-site": + newton_cfg = SimulationCfg(device=device, physics=NewtonCfg(solver_cfg=MJWarpSolverCfg())) + ctx = build_simulation_context(device=device, sim_cfg=newton_cfg, add_ground_plane=True) + sim = ctx.__enter__() + sim._app_control_on_stop_handle = None + InteractiveScene(_NewtonSceneCfg(num_envs=num_envs, env_spacing=2.0)) + + stage = sim_utils.get_current_stage() + for i in range(num_envs): + prim = stage.DefinePrim(f"/World/envs/env_{i}/Object/Sensor", "Xform") + sim_utils.standardize_xform_ops(prim) + prim.GetAttribute("xformOp:translate").Set(Gf.Vec3d(0.1, 0.0, 0.05)) + prim.GetAttribute("xformOp:orient").Set(Gf.Quatd(1.0, 0.0, 0.0, 0.0)) + + sim.reset() + + start_time = time.perf_counter() + xform_view = NewtonSiteFrameView("/World/envs/env_.*/Object/Sensor", device=device) + timing_results["init"] = time.perf_counter() - start_time + cleanup = lambda: ctx.__exit__(None, None, None) # noqa: E731 + + else: + sim_utils.create_new_stage() + start_time = time.perf_counter() + use_fabric = api == "isaaclab-fabric" + sim = sim_utils.SimulationContext(sim_utils.SimulationCfg(dt=0.01, device=device, use_fabric=use_fabric)) + stage = sim_utils.get_current_stage() + + for i in range(num_envs): + sim_utils.create_prim(f"/World/Env_{i}", "Xform", stage=stage, translation=(i * 2.0, 0.0, 1.0)) + sim_utils.create_prim(f"/World/Env_{i}/Object", "Xform", stage=stage, translation=(0.0, 0.0, 0.0)) + + sim.reset() + + pattern = "/World/Env_.*/Object" + start_time = time.perf_counter() + ViewClass = FabricFrameView if use_fabric else UsdFrameView + xform_view = ViewClass(pattern, device=device, validate_xform_ops=False) + timing_results["init"] = time.perf_counter() - start_time + cleanup = lambda: sim.clear_instance() # noqa: E731 + + num_prims = xform_view.count + print(f" {api} managing {num_prims} prims") + + is_newton = api == "isaaclab-newton-site" + + def to_torch(a): + return wp.to_torch(a) if isinstance(a, wp.array) else a + + try: + # -- Warmup -------------------------------------------------------- + xform_view.get_world_poses() + + # -- get_world_poses ----------------------------------------------- + if is_newton: + torch.cuda.synchronize() + start_time = time.perf_counter() + for _ in range(num_iterations): + positions, orientations = xform_view.get_world_poses() + if is_newton: + torch.cuda.synchronize() + timing_results["get_world_poses"] = (time.perf_counter() - start_time) / num_iterations + + positions_t = to_torch(positions) + orientations_t = to_torch(orientations) + computed_results["initial_world_positions"] = positions_t.clone() + computed_results["initial_world_orientations"] = orientations_t.clone() + + # -- set_world_poses ----------------------------------------------- + if is_newton: + new_positions = wp.clone(positions) + wp.to_torch(new_positions)[:, 2] += 0.1 + else: + new_positions = positions_t.clone() + new_positions[:, 2] += 0.1 + + if is_newton: + torch.cuda.synchronize() + start_time = time.perf_counter() + for _ in range(num_iterations): + xform_view.set_world_poses(new_positions, orientations) + if is_newton: + torch.cuda.synchronize() + timing_results["set_world_poses"] = (time.perf_counter() - start_time) / num_iterations + + pa, oa = xform_view.get_world_poses() + computed_results["world_positions_after_set"] = to_torch(pa).clone() + computed_results["world_orientations_after_set"] = to_torch(oa).clone() + + # -- get_local_poses ----------------------------------------------- + if is_newton: + torch.cuda.synchronize() + start_time = time.perf_counter() + for _ in range(num_iterations): + translations, orientations_local = xform_view.get_local_poses() + if is_newton: + torch.cuda.synchronize() + timing_results["get_local_poses"] = (time.perf_counter() - start_time) / num_iterations + + translations_t = to_torch(translations) + orientations_local_t = to_torch(orientations_local) + computed_results["initial_local_translations"] = translations_t.clone() + computed_results["initial_local_orientations"] = orientations_local_t.clone() + + # -- set_local_poses ----------------------------------------------- + if is_newton: + new_translations = wp.clone(translations) + wp.to_torch(new_translations)[:, 2] += 0.1 + else: + new_translations = translations_t.clone() + new_translations[:, 2] += 0.1 + + if is_newton: + torch.cuda.synchronize() + start_time = time.perf_counter() + for _ in range(num_iterations): + xform_view.set_local_poses(new_translations, orientations_local) + if is_newton: + torch.cuda.synchronize() + timing_results["set_local_poses"] = (time.perf_counter() - start_time) / num_iterations + + ta, ola = xform_view.get_local_poses() + computed_results["local_translations_after_set"] = to_torch(ta).clone() + computed_results["local_orientations_after_set"] = to_torch(ola).clone() + + # -- get_both (world + local) -------------------------------------- + if is_newton: + torch.cuda.synchronize() + start_time = time.perf_counter() + for _ in range(num_iterations): + xform_view.get_world_poses() + xform_view.get_local_poses() + if is_newton: + torch.cuda.synchronize() + timing_results["get_both"] = (time.perf_counter() - start_time) / num_iterations + + # -- interleaved set -> get ---------------------------------------- + if is_newton: + torch.cuda.synchronize() + start_time = time.perf_counter() + for _ in range(num_iterations): + xform_view.set_world_poses(new_positions, orientations) + xform_view.get_world_poses() + if is_newton: + torch.cuda.synchronize() + timing_results["interleaved_world_set_get"] = (time.perf_counter() - start_time) / num_iterations + + finally: + if cleanup: + cleanup() + + return timing_results, computed_results + + +# ------------------------------------------------------------------ +# Reporting +# ------------------------------------------------------------------ + + +def print_results(results_dict: dict[str, dict[str, float]], num_prims: int, num_iterations: int): + """Print benchmark results in a formatted table.""" + print("\n" + "=" * 120) + print(f"BENCHMARK RESULTS: {num_prims} prims, {num_iterations} iterations") + print("=" * 120) + + api_names = list(results_dict.keys()) + display_names = [name.replace("-", " ").title() for name in api_names] + col_width = 22 + + header = f"{'Operation':<28}" + for dn in display_names: + header += f" {dn + ' (ms)':>{col_width}}" + print(header) + print("-" * 120) + + operations = [ + ("Initialization", "init"), + ("Get World Poses", "get_world_poses"), + ("Set World Poses", "set_world_poses"), + ("Get Local Poses", "get_local_poses"), + ("Set Local Poses", "set_local_poses"), + ("Get Both (World+Local)", "get_both"), + ("Interleaved World Set->Get", "interleaved_world_set_get"), + ] + + for op_name, op_key in operations: + row = f"{op_name:<28}" + for name in api_names: + val = results_dict[name].get(op_key, 0) * 1000 + row += f" {val:>{col_width}.4f}" + print(row) + + print("=" * 120) + + total_row = f"{'Total':<28}" + for name in api_names: + total_row += f" {sum(results_dict[name].values()) * 1000:>{col_width}.4f}" + print(f"\n{total_row}") + + baseline = "isaaclab-usd" + if baseline in results_dict and len(api_names) > 1: + print("\n" + "=" * 120) + print(f"SPEEDUP vs {baseline.replace('-', ' ').title()}") + print("=" * 120) + header = f"{'Operation':<28}" + for name in api_names: + if name != baseline: + header += f" {name.replace('-', ' ').title():>{col_width}}" + print(header) + print("-" * 120) + + base = results_dict[baseline] + for op_name, op_key in operations: + row = f"{op_name:<28}" + base_t = base.get(op_key, 0) + for name in api_names: + if name != baseline: + impl_t = results_dict[name].get(op_key, 0) + if base_t > 0 and impl_t > 0: + row += f" {base_t / impl_t:>{col_width}.2f}x" + else: + row += f" {'N/A':>{col_width}}" + print(row) + + print("=" * 120) + print(f"{'Overall':>28}", end="") + total_base = sum(base.values()) + for name in api_names: + if name != baseline: + total_impl = sum(results_dict[name].values()) + if total_base > 0 and total_impl > 0: + print(f" {total_base / total_impl:>{col_width}.2f}x", end="") + else: + print(f" {'N/A':>{col_width}}", end="") + print() + + print("\n" + "=" * 120) + print("\nNotes:") + print(" - Times are averaged over all iterations") + print(" - Speedup > 1.0 means faster than USD baseline") + print() + + +def main(): + print("=" * 120) + print("FrameView Benchmark") + print("=" * 120) + print(f" Environments: {args_cli.num_envs}") + print(f" Iterations: {args_cli.num_iterations}") + print(f" Device: {args_cli.device}") + print() + + if args_cli.profile: + import os + + os.makedirs(args_cli.profile_dir, exist_ok=True) + + all_timing = {} + all_computed = {} + profile_files = {} + + apis = [ + ("isaaclab-usd", "Isaac Lab FrameView (USD)"), + ("isaaclab-fabric", "Isaac Lab FrameView (Fabric)"), + ("isaaclab-newton-site", "Isaac Lab FrameView (Newton Site)"), + ] + + for api_key, api_name in apis: + print(f"Benchmarking {api_name}...") + + if args_cli.profile: + profiler = cProfile.Profile() + profiler.enable() + + timing, computed = benchmark_frame_view(api=api_key, num_iterations=args_cli.num_iterations) + + if args_cli.profile: + profiler.disable() + pf = f"{args_cli.profile_dir}/{api_key.replace('-', '_')}_benchmark.prof" + profiler.dump_stats(pf) + profile_files[api_key] = pf + print(f" Profile saved to: {pf}") + + all_timing[api_key] = timing + all_computed[api_key] = computed + print(" Done!\n") + + print_results(all_timing, args_cli.num_envs, args_cli.num_iterations) + + if args_cli.profile: + print("\nProfile files:") + for key, pf in profile_files.items(): + print(f" snakeviz {pf}") + print() + + sim_utils.SimulationContext.clear_instance() + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/early_stop.py b/simulation/modules/IsaacLab/scripts/benchmarks/early_stop.py new file mode 100644 index 0000000000000000000000000000000000000000..38dabe3b67cd138a16e681de911754df5a2057fb --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/early_stop.py @@ -0,0 +1,321 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Early stopping for benchmark training based on a success metric. + +Framework-specific implementations that monitor a metric from ``extras["log"]`` +and stop training when it stabilizes above a threshold: + +- **rsl_rl**: ``env.step`` wrapper + exception (no callback API in rsl_rl). +- **rl_games**: ``AlgoObserver`` subclass, sets ``max_epochs`` for clean exit. +""" + +from __future__ import annotations + +import argparse +import os +import statistics +from typing import TYPE_CHECKING + +from scripts.benchmarks.utils import get_success_rate_log + +if TYPE_CHECKING: + from rl_games.common.algo_observer import AlgoObserver + from rsl_rl.runners import OnPolicyRunner + + from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper + +DEFAULT_SUCCESS_THRESHOLD = 0.3 +DEFAULT_SUCCESS_WINDOW = 20 + + +class EarlyStopConverged(Exception): + """Raised by :class:`RslRlEarlyStopWrapper` when the metric has converged.""" + + +class SuccessRateTracker: + """Accumulates a per-iteration success-rate metric and checks trailing-window convergence. + + Args: + threshold: Minimum value to consider a pass. + window: Consecutive iterations above *threshold* to trigger convergence. + num_steps_per_env: Steps per RL iteration (for boundary detection). + """ + + def __init__(self, threshold: float, window: int, num_steps_per_env: int): + self.threshold = threshold + self.window = window + self.num_steps_per_env = num_steps_per_env + + self.history: list[float] = [] + self._step_count = 0 + self._iter_sum = 0.0 + self._iter_count = 0 + + def record_step(self, extras: dict) -> None: + """Record one env step.""" + val = get_success_rate_log(extras.get("log", {})) + if val is not None: + self._iter_sum += val.item() if hasattr(val, "item") else float(val) + self._iter_count += 1 + self._step_count += 1 + + def end_iteration(self) -> float | None: + """Finalize the current iteration. Returns mean metric, or ``None`` if no data.""" + if self._iter_count == 0: + return None + mean = self._iter_sum / self._iter_count + self.history.append(mean) + self._iter_sum = 0.0 + self._iter_count = 0 + return mean + + @property + def at_iteration_boundary(self) -> bool: + """Whether the tracker has seen exactly a full iteration's worth of steps. + + Assumes :meth:`record_step` is called exactly once per env step. This holds for + all current framework integrations (rsl_rl's patched ``env.step`` and rl_games' + ``AlgoObserver.process_infos``) — both pair a single step with a single record. + Integrations that call :meth:`record_step` more or fewer times per env step will + break iteration accounting. + """ + return self.num_steps_per_env > 0 and self._step_count % self.num_steps_per_env == 0 + + @property + def converged(self) -> bool: + if len(self.history) < self.window: + return False + return all(v >= self.threshold for v in self.history[-self.window :]) + + @property + def current_iteration(self) -> int: + return len(self.history) + + @property + def tail_mean(self) -> float: + if not self.history: + return 0.0 + tail = self.history[-self.window :] if len(self.history) >= self.window else self.history + return statistics.mean(tail) + + +class RslRlEarlyStopWrapper: + """Context manager that wraps ``env.step`` to track a success metric during rsl_rl training. + + Always records the metric into :attr:`tracker` so the caller can log the tail mean / converged-at + iteration regardless of whether early stopping is enabled. When ``stop_on_convergence=True``, the + wrapper also raises :class:`EarlyStopConverged` on the first iteration where the trailing window + is above threshold, performs runner cleanup (checkpoint save + logger flush), and suppresses the + exception so the caller sees a normal return from :meth:`rsl_rl.runners.OnPolicyRunner.learn`. + + Args: + env: ``RslRlVecEnvWrapper`` instance. + runner: ``OnPolicyRunner`` instance. + threshold: Minimum metric value to pass. + window: Consecutive iterations above threshold to trigger stop. + num_steps_per_env: Steps per RL iteration. + stop_on_convergence: If ``True``, raise :class:`EarlyStopConverged` when the metric converges. + If ``False``, only track the metric without interrupting training. + """ + + def __init__( + self, + env: RslRlVecEnvWrapper, + runner: OnPolicyRunner, + threshold: float, + window: int, + num_steps_per_env: int, + stop_on_convergence: bool = True, + ): + self.env = env + self.runner = runner + self.tracker = SuccessRateTracker(threshold, window, num_steps_per_env) + self.stop_on_convergence = stop_on_convergence + self._orig_step = env.step + + def __enter__(self): + self.env.step = self._step + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.env.step = self._orig_step + if exc_type is EarlyStopConverged: + self._runner_cleanup() + print( + f"[INFO] Early stop: success rate converged at iteration " + f"{self.tracker.current_iteration} (tail mean {self.tracker.tail_mean:.4f})" + ) + return True + return False + + def _step(self, actions): + result = self._orig_step(actions) + self.tracker.record_step(result[3]) # rsl_rl: (obs, rew, dones, extras) + if self.tracker.at_iteration_boundary: + self.tracker.end_iteration() + if self.stop_on_convergence and self.tracker.converged: + # relies on rsl_rl's rollout loop not catching arbitrary exceptions; if upstream + # ever wraps env.step in a broad except, this exception will be swallowed + raise EarlyStopConverged() + return result + + def _runner_cleanup(self): + """Save final checkpoint and flush the TensorBoard writer.""" + if self.runner.logger.writer is not None: + it = self.runner.current_learning_iteration + self.runner.save(os.path.join(self.runner.logger.log_dir, f"model_{it}.pt")) + self.runner.logger.stop_logging_writer() + + @property + def framework_iteration_count(self) -> int: + """Number of training iterations the rsl_rl runner has recorded as completed. + + Note: ``current_learning_iteration`` is set AFTER rollout + policy update, so mid-rollout + (including the instant our early-stop exception fires) this counter lags :attr:`tracker` + by 1 iteration. + """ + return self.runner.current_learning_iteration + 1 + + +class RlGamesEarlyStopObserver: + """``AlgoObserver`` that tracks a success metric during rl_games training. + + Always records the metric into :attr:`tracker` so the caller can log the tail mean / converged-at + iteration regardless of whether early stopping is enabled. When ``stop_on_convergence=True``, the + observer also sets ``algo.max_epochs`` on the first iteration where the trailing window is above + threshold, which forces a clean exit from :meth:`rl_games.torch_runner.Runner.run`. All other + observer calls are delegated to *base_observer*. + + Args: + base_observer: Original ``AlgoObserver`` to delegate to. + threshold: Minimum metric value to pass. + window: Consecutive iterations above threshold to trigger stop. + stop_on_convergence: If ``True``, set ``algo.max_epochs`` when the metric converges. + If ``False``, only track the metric without interrupting training. + """ + + def __init__( + self, + base_observer: AlgoObserver, + threshold: float, + window: int, + stop_on_convergence: bool = True, + ): + self._base = base_observer + self.threshold = threshold + self.window = window + self.stop_on_convergence = stop_on_convergence + self.algo = None + self.tracker: SuccessRateTracker | None = None + + def before_init(self, base_name, config, experiment_name): + self._base.before_init(base_name, config, experiment_name) + + def after_init(self, algo): + self._base.after_init(algo) + self.algo = algo + num_steps = getattr(algo, "horizon_length", algo.config.get("horizon_length", 16)) + self.tracker = SuccessRateTracker(self.threshold, self.window, num_steps) + + def process_infos(self, infos, done_indices): + self._base.process_infos(infos, done_indices) + if self.tracker is not None and isinstance(infos, dict) and "episode" in infos: + # rl_games remaps extras["log"] → extras["episode"] + self.tracker.record_step({"log": infos["episode"]}) + + def after_steps(self): + self._base.after_steps() + if self.tracker is None: + return + self.tracker.end_iteration() + if self.stop_on_convergence and self.tracker.converged and self.algo is not None: + print( + f"[INFO] Early stop: success rate converged at iteration " + f"{self.tracker.current_iteration} (tail mean {self.tracker.tail_mean:.4f})" + ) + self.algo.max_epochs = self.tracker.current_iteration + + def after_clear_stats(self): + self._base.after_clear_stats() + + def after_print_stats(self, frame, epoch_num, total_time): + self._base.after_print_stats(frame, epoch_num, total_time) + + @property + def framework_iteration_count(self) -> int | None: + """Number of training iterations the rl_games algo has recorded. + + rl_games increments ``algo.epoch_num`` at the start of each iteration, so after iter N + completes this value equals N (matching :attr:`tracker`'s count exactly). Returns + ``None`` before :meth:`after_init` has attached to an algo. + """ + return None if self.algo is None else self.algo.epoch_num + + +def add_success_cli_args(parser: argparse.ArgumentParser) -> None: + """Register the success-metric CLI args on *parser*. + + Adds ``--check_success``, ``--success_threshold``, and ``--success_window``. Use + :func:`build_success_kwargs` to resolve the parsed values into a kwargs dict for + the wrapper constructors. + """ + parser.add_argument( + "--check_success", action="store_true", help="Early-stop when the normalized success metric converges." + ) + parser.add_argument( + "--success_threshold", + type=float, + default=None, + help=f"Override the success threshold (default: {DEFAULT_SUCCESS_THRESHOLD}).", + ) + parser.add_argument( + "--success_window", + type=int, + default=None, + help=f"Override the convergence window (default: {DEFAULT_SUCCESS_WINDOW}).", + ) + + +def build_success_kwargs(args_cli: argparse.Namespace) -> dict: + """Resolve success-metric CLI args into kwargs for the wrapper constructors. + + Returns a dict with ``threshold``, ``window``, and ``stop_on_convergence``, suitable + to splat into :class:`RslRlEarlyStopWrapper` or :class:`RlGamesEarlyStopObserver`. + """ + return { + "threshold": ( + args_cli.success_threshold if args_cli.success_threshold is not None else DEFAULT_SUCCESS_THRESHOLD + ), + "window": args_cli.success_window if args_cli.success_window is not None else DEFAULT_SUCCESS_WINDOW, + "stop_on_convergence": args_cli.check_success, + } + + +def get_success_tracker( + args_cli: argparse.Namespace, + live_tracker: SuccessRateTracker | None, + log_data: dict[str, list[float]], +) -> SuccessRateTracker | None: + """Return a tracker with recorded history, or ``None`` if neither source has data. + + Prefers *live_tracker* (from the training wrapper/observer). If it never ran or recorded + no iterations, falls back to building a post-hoc tracker by replaying the success metric + series out of TensorBoard *log_data* (from :func:`scripts.benchmarks.utils.parse_tf_logs`). + + Args: + args_cli: Parsed arg namespace with the ``--success_*`` flags. + live_tracker: Tracker attached to the early-stop wrapper/observer (or ``None``). + log_data: Mapping of TB tag -> list of scalars for the current run. + """ + if live_tracker is not None and live_tracker.history: + return live_tracker + history = get_success_rate_log(log_data) + if not history: + return None + kwargs = build_success_kwargs(args_cli) + tracker = SuccessRateTracker(kwargs["threshold"], kwargs["window"], num_steps_per_env=0) + tracker.history = list(history) + return tracker diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/nsys_trace.json b/simulation/modules/IsaacLab/scripts/benchmarks/nsys_trace.json new file mode 100644 index 0000000000000000000000000000000000000000..0d04fd1b85463e3e648009d82ff3c52b5a26c55f --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/nsys_trace.json @@ -0,0 +1,166 @@ +[ + { + "_comment": "=== PYTHON IMPORTS (tracks module loading) ===", + "domain": "Python-Imports", + "color": "0x9E9E9E", + "module": "importlib", + "functions": ["import_module"] + }, + { + "domain": "Python-Imports", + "color": "0x9E9E9E", + "module": "importlib._bootstrap", + "functions": ["_find_and_load", "_load_unlocked"] + }, + { + "_comment": "=== WARP (verified working) ===", + "domain": "Warp", + "color": "0xF44336", + "module": "warp", + "functions": ["launch", "synchronize", "copy", "zeros", "empty"] + }, + { + "_comment": "=== PYTORCH (verified working) ===", + "domain": "PyTorch", + "color": "0x3F51B5", + "module": "torch.autograd", + "functions": ["backward"] + }, + { + "_comment": "=== USD (verified working) ===", + "domain": "USD", + "color": "0x795548", + "module": "pxr.UsdGeom", + "functions": ["Xform", "Mesh", "Sphere", "Cube"] + }, + { + "_comment": "=== ISAACLAB ENVIRONMENTS ===", + "domain": "IsaacLab-Env", + "color": "0x9C27B0", + "module": "isaaclab.envs.manager_based_rl_env", + "functions": [ + {"function": "ManagerBasedRLEnv.__init__", "color": "0x9C27B0"}, + {"function": "ManagerBasedRLEnv.step", "color": "0xAB47BC"} + ] + }, + { + "domain": "IsaacLab-Env", + "color": "0x9C27B0", + "module": "isaaclab.envs.manager_based_env", + "functions": [ + {"function": "ManagerBasedEnv.__init__", "color": "0x9C27B0"}, + {"function": "ManagerBasedEnv.step", "color": "0xAB47BC"}, + {"function": "ManagerBasedEnv.reset", "color": "0xBA68C8"}, + {"function": "ManagerBasedEnv._reset_idx", "color": "0xCE93D8"} + ] + }, + { + "_comment": "=== ISAACLAB SIMULATION ===", + "domain": "IsaacLab-Sim", + "color": "0x4CAF50", + "module": "isaaclab.sim.simulation_context", + "functions": [ + {"function": "SimulationContext.__init__", "color": "0x4CAF50"}, + {"function": "SimulationContext.reset", "color": "0x66BB6A"}, + {"function": "SimulationContext.step", "color": "0x81C784"} + ] + }, + { + "_comment": "=== ISAACLAB SCENE ===", + "domain": "IsaacLab-Scene", + "color": "0x2196F3", + "module": "isaaclab.scene.interactive_scene", + "functions": [ + {"function": "InteractiveScene.__init__", "color": "0x2196F3"}, + {"function": "InteractiveScene.reset", "color": "0x42A5F5"}, + {"function": "InteractiveScene.write_data_to_sim", "color": "0x64B5F6"}, + {"function": "InteractiveScene.update", "color": "0x90CAF9"} + ] + }, + { + "_comment": "=== ISAACLAB MANAGERS ===", + "domain": "IsaacLab-Managers", + "color": "0xFF9800", + "module": "isaaclab.managers.observation_manager", + "functions": [ + {"function": "ObservationManager.__init__", "color": "0xFF9800"}, + {"function": "ObservationManager.reset", "color": "0xFFA726"}, + {"function": "ObservationManager.compute", "color": "0xFFB74D"} + ] + }, + { + "domain": "IsaacLab-Managers", + "color": "0xFF9800", + "module": "isaaclab.managers.action_manager", + "functions": [ + {"function": "ActionManager.__init__", "color": "0xFF9800"}, + {"function": "ActionManager.reset", "color": "0xFFA726"}, + {"function": "ActionManager.process_action", "color": "0xFFB74D"}, + {"function": "ActionManager.apply_action", "color": "0xFFCC80"} + ] + }, + { + "domain": "IsaacLab-Managers", + "color": "0xFF9800", + "module": "isaaclab.managers.reward_manager", + "functions": [ + {"function": "RewardManager.__init__", "color": "0xFF9800"}, + {"function": "RewardManager.reset", "color": "0xFFA726"}, + {"function": "RewardManager.compute", "color": "0xFFB74D"} + ] + }, + { + "_comment": "=== ISAACLAB ASSETS ===", + "domain": "IsaacLab-Assets", + "color": "0x607D8B", + "module": "isaaclab.assets.articulation.articulation", + "functions": [ + {"function": "Articulation.__init__", "color": "0x607D8B"}, + {"function": "Articulation.reset", "color": "0x78909C"}, + {"function": "Articulation.write_data_to_sim", "color": "0x90A4AE"}, + {"function": "Articulation.update", "color": "0xB0BEC5"} + ] + }, + { + "_comment": "=== ISAACLAB SENSORS ===", + "domain": "IsaacLab-Sensors", + "color": "0x00BCD4", + "module": "isaaclab.sensors.camera.camera", + "functions": [ + {"function": "Camera.__init__", "color": "0x00BCD4"}, + {"function": "Camera.reset", "color": "0x26C6DA"}, + {"function": "Camera.update", "color": "0x4DD0E1"} + ] + }, + { + "_comment": "=== RSL-RL ===", + "domain": "RSL-RL", + "color": "0x673AB7", + "module": "rsl_rl.runners.on_policy_runner", + "functions": [ + {"function": "OnPolicyRunner.__init__", "color": "0x673AB7"}, + {"function": "OnPolicyRunner.learn", "color": "0x7E57C2"} + ] + }, + { + "domain": "RSL-RL", + "color": "0x673AB7", + "module": "rsl_rl.algorithms.ppo", + "functions": [ + {"function": "PPO.__init__", "color": "0x673AB7"}, + {"function": "PPO.act", "color": "0x7E57C2"}, + {"function": "PPO.update", "color": "0x9575CD"} + ] + }, + { + "_comment": "=== NEWTON WARP RENDERER ===", + "domain": "NewtonWarpRenderer", + "color": "0xE91E63", + "module": "isaaclab_newton.renderers.newton_warp_renderer", + "functions": [ + {"function": "NewtonWarpRenderer.update_transforms", "color": "0x2196F3"}, + {"function": "NewtonWarpRenderer.render", "color": "0x4CAF50"}, + {"function": "NewtonWarpRenderer.read_output", "color": "0xFF9800"} + ] + } +] diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/run_non_rl_benchmarks.sh b/simulation/modules/IsaacLab/scripts/benchmarks/run_non_rl_benchmarks.sh new file mode 100644 index 0000000000000000000000000000000000000000..b62781461b664cc164d1022b7679b3a66a6ff37b --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/run_non_rl_benchmarks.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash + +#!/usr/bin/env bash + +ROOT_DIR="${1:-./benchmarks}" +OUTPUT_DIR="${ROOT_DIR}/isaaclab_non_rl" +TASKS="Isaac-Repose-Cube-Allegro-Direct-v0 Isaac-Ant-Direct-v0 Isaac-Cartpole-Direct-v0 Isaac-Humanoid-Direct-v0 Isaac-Ant-v0 Isaac-Cartpole-v0 Isaac-Humanoid-v0 Isaac-Velocity-Flat-Unitree-A1-v0 Isaac-Velocity-Flat-Anymal-B-v0 Isaac-Velocity-Flat-Anymal-C-v0 Isaac-Velocity-Flat-Anymal-D-v0 Isaac-Velocity-Flat-Cassie-v0 Isaac-Velocity-Flat-G1-v0 Isaac-Velocity-Flat-G1-v1 Isaac-Velocity-Flat-Unitree-Go1-v0 Isaac-Velocity-Flat-Unitree-Go2-v0 Isaac-Velocity-Flat-H1-v0 Isaac-Reach-Franka-v0 Isaac-Reach-UR10-v0" +NUM_ENVS="4096 8192 16384" +NUM_FRAMES="100" + +for TASK in $TASKS; do + for NUM_ENV in $NUM_ENVS; do + if [[ $TASK == *"RGB-Camera"* ]] || [[ $TASK == *"Depth-Camera"* ]]; then + ./isaaclab.sh -p scripts/benchmarks/benchmark_non_rl.py --benchmark_backend omniperf --output_path "$OUTPUT_DIR" --task "$TASK" --num_envs "$NUM_ENV" --headless --num_frames "$NUM_FRAMES" --enable_cameras + else + ./isaaclab.sh -p scripts/benchmarks/benchmark_non_rl.py --benchmark_backend omniperf --output_path "$OUTPUT_DIR" --task "$TASK" --num_envs "$NUM_ENV" --headless --num_frames "$NUM_FRAMES" + fi + done +done diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/run_physx_benchmarks.sh b/simulation/modules/IsaacLab/scripts/benchmarks/run_physx_benchmarks.sh new file mode 100644 index 0000000000000000000000000000000000000000..adb743b46434d01d12fd36ea118106fe013ece47 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/run_physx_benchmarks.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +# Set output directory from argument or use default +ROOT_DIR="${1:-./benchmarks}" +OUTPUT_DIR="${ROOT_DIR}/isaaclab_physx" + +./isaaclab.sh -p source/isaaclab_physx/benchmark/assets/benchmark_articulation.py --backend omniperf --output_dir "$OUTPUT_DIR" +./isaaclab.sh -p source/isaaclab_physx/benchmark/assets/benchmark_rigid_object.py --backend omniperf --output_dir "$OUTPUT_DIR" +./isaaclab.sh -p source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_collection.py --backend omniperf --output_dir "$OUTPUT_DIR" +./isaaclab.sh -p source/isaaclab_physx/benchmark/assets/benchmark_articulation_data.py --backend omniperf --output_dir "$OUTPUT_DIR" +./isaaclab.sh -p source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_data.py --backend omniperf --output_dir "$OUTPUT_DIR" +./isaaclab.sh -p source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_collection_data.py --backend omniperf --output_dir "$OUTPUT_DIR" diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/run_training_benchmarks.sh b/simulation/modules/IsaacLab/scripts/benchmarks/run_training_benchmarks.sh new file mode 100644 index 0000000000000000000000000000000000000000..7bc05ddd45aee87cac4297187b28f9f256c41573 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/run_training_benchmarks.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +ROOT_DIR="${1:-./benchmarks}" +OUTPUT_DIR="${ROOT_DIR}/isaaclab_rsl_rl_training" +TASKS="Isaac-Repose-Cube-Allegro-Direct-v0 Isaac-Ant-Direct-v0 Isaac-Cartpole-Direct-v0 Isaac-Humanoid-Direct-v0 Isaac-Ant-v0 Isaac-Cartpole-v0 Isaac-Humanoid-v0 Isaac-Velocity-Flat-Unitree-A1-v0 Isaac-Velocity-Flat-Anymal-B-v0 Isaac-Velocity-Flat-Anymal-C-v0 Isaac-Velocity-Flat-Anymal-D-v0 Isaac-Velocity-Flat-Cassie-v0 Isaac-Velocity-Flat-G1-v0 Isaac-Velocity-Flat-G1-v1 Isaac-Velocity-Flat-Unitree-Go1-v0 Isaac-Velocity-Flat-Unitree-Go2-v0 Isaac-Velocity-Flat-H1-v0 Isaac-Reach-Franka-v0 Isaac-Reach-UR10-v0" +NUM_ENV="4096" +ITERATIONS="500" + +for TASK in $TASKS; do + if [[ $TASK == *"RGB-Camera"* ]] || [[ $TASK == *"Depth-Camera"* ]]; then + ./isaaclab.sh -p scripts/benchmarks/benchmark_rsl_rl.py --benchmark_backend omniperf --output_path "$OUTPUT_DIR" --task "$TASK" --num_envs "$NUM_ENV" --headless --max_iterations "$ITERATIONS" --enable_cameras + else + ./isaaclab.sh -p scripts/benchmarks/benchmark_rsl_rl.py --benchmark_backend omniperf --output_path "$OUTPUT_DIR" --task "$TASK" --num_envs "$NUM_ENV" --headless --max_iterations "$ITERATIONS" + fi +done diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/startup_whitelist.yaml b/simulation/modules/IsaacLab/scripts/benchmarks/startup_whitelist.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3aef4a7297230dc100128905babf38e8fd834545 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/startup_whitelist.yaml @@ -0,0 +1,25 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +app_launch: + - "isaaclab.utils.configclass:_wrap_resolvable_strings" + - "isaaclab.utils.configclass:_custom_post_init" + - "isaaclab.utils.configclass:_field_module_dir" + +env_creation: + - "isaaclab.cloner.*:usd_replicate" + - "isaaclab.cloner.*:filter_collisions" + - "isaaclab_physx.cloner.*:attach_end_fn" + - "isaaclab.scene.*:_init_scene" + - "isaaclab.envs.mdp.observations:*" + - "isaaclab.utils.assets:_find_asset_dependencies" + +first_step: + - "isaaclab.envs.mdp.rewards:*" + - "isaaclab.envs.mdp.terminations:*" + - "isaaclab.envs.mdp.observations:*" + - "isaaclab.actuators.*:compute" + - "warp.*:launch" + - "warp.*:to_torch" diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/test/test_early_stop.py b/simulation/modules/IsaacLab/scripts/benchmarks/test/test_early_stop.py new file mode 100644 index 0000000000000000000000000000000000000000..b11231481da33f269ae7cdd38e5209ebad02ea64 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/test/test_early_stop.py @@ -0,0 +1,706 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for the benchmark success-metric early-stopping helpers.""" + +from __future__ import annotations + +import argparse + +import pytest + +from scripts.benchmarks.early_stop import ( + DEFAULT_SUCCESS_THRESHOLD, + DEFAULT_SUCCESS_WINDOW, + RlGamesEarlyStopObserver, + RslRlEarlyStopWrapper, + SuccessRateTracker, + add_success_cli_args, + build_success_kwargs, + get_success_tracker, +) +from scripts.benchmarks.utils import SUCCESS_RATE_LOG_TAGS, log_success + +DEFAULT_SUCCESS_TAG = SUCCESS_RATE_LOG_TAGS[0] + +# -- fakes ------------------------------------------------------------------ + + +class _FakeTensor: + """Stand-in for ``torch.Tensor`` with only the ``.item()`` path exercised.""" + + def __init__(self, value: float): + self._value = value + + def item(self) -> float: + return self._value + + +class _FakeBenchmark: + def __init__(self): + self.measurements: list[tuple[str, str, object, str]] = [] + + def add_measurement(self, phase, measurement): + self.measurements.append((phase, measurement.name, measurement.value, measurement.unit)) + + def by_name(self, name: str): + return next(m for m in self.measurements if m[1] == name) + + +class _FakeLogger: + def __init__(self, has_writer: bool = True): + self.writer = object() if has_writer else None + self.log_dir = "/tmp/fake_log_dir" + self.stopped = False + + def stop_logging_writer(self): + self.stopped = True + + +class _FakeRunner: + def __init__(self, has_writer: bool = True): + self.logger = _FakeLogger(has_writer=has_writer) + self.current_learning_iteration = 7 + self.saved: list[str] = [] + + def save(self, path: str): + self.saved.append(path) + + +class _FakeEnv: + def __init__(self, extras_sequence): + self._seq = list(extras_sequence) + self.step_calls = 0 + + def step(self, actions): + extras = self._seq[self.step_calls] if self.step_calls < len(self._seq) else self._seq[-1] + self.step_calls += 1 + return (None, None, None, extras) + + +class _FakeBaseObserver: + def __init__(self): + self.calls: list[str] = [] + + def before_init(self, base_name, config, experiment_name): + self.calls.append("before_init") + + def after_init(self, algo): + self.calls.append("after_init") + + def process_infos(self, infos, done_indices): + self.calls.append("process_infos") + + def after_steps(self): + self.calls.append("after_steps") + + def after_clear_stats(self): + self.calls.append("after_clear_stats") + + def after_print_stats(self, frame, epoch_num, total_time): + self.calls.append("after_print_stats") + + +class _FakeAlgo: + def __init__(self, horizon_length: int | None = None, config_horizon: int | None = 16, epoch_num: int = 0): + self.max_epochs = 999 + self.epoch_num = epoch_num + if horizon_length is not None: + self.horizon_length = horizon_length + self.config = {"horizon_length": config_horizon} if config_horizon is not None else {} + + +def _parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser() + add_success_cli_args(p) + return p + + +# -- SuccessRateTracker ----------------------------------------------------- + + +class TestSuccessRateTracker: + """Test cases for the per-iteration metric accumulator and convergence check.""" + + def test_records_metric_from_extras_log(self): + """Test that a present metric is accumulated into the iteration sum.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.record_step({"log": {DEFAULT_SUCCESS_TAG: 0.9}}) + assert t._iter_sum == pytest.approx(0.9) + assert t._iter_count == 1 + + def test_ignores_missing_metric_key(self): + """Test that a foreign key in extras["log"] is ignored.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.record_step({"log": {"other": 1.0}}) + assert t._iter_count == 0 + + def test_missing_log_subdict_does_not_raise(self): + """Test that an extras dict without a "log" sub-dict is handled gracefully.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.record_step({}) + assert t._iter_count == 0 + assert t._step_count == 1 + + def test_tensor_value_uses_item_method(self): + """Test that tensor-like values are extracted via ``.item()``.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.record_step({"log": {DEFAULT_SUCCESS_TAG: _FakeTensor(0.7)}}) + assert t._iter_sum == pytest.approx(0.7) + + def test_step_count_increments_even_without_metric(self): + """Test that ``_step_count`` tracks every call regardless of metric presence.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.record_step({}) + t.record_step({"log": {"other": 1.0}}) + assert t._step_count == 2 + assert t._iter_count == 0 + + def test_end_iteration_averages_and_resets(self): + """Test that ``end_iteration`` averages recorded values and resets counters.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.record_step({"log": {DEFAULT_SUCCESS_TAG: 0.4}}) + t.record_step({"log": {DEFAULT_SUCCESS_TAG: 0.6}}) + assert t.end_iteration() == pytest.approx(0.5) + assert t.history == [pytest.approx(0.5)] + assert t._iter_sum == 0.0 + assert t._iter_count == 0 + + def test_end_iteration_no_data_returns_none_without_recording(self): + """Test that ``end_iteration`` returns None and skips history append when no data was seen.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + assert t.end_iteration() is None + assert t.history == [] + + def test_at_iteration_boundary_respects_num_steps_per_env(self): + """Test that the boundary flag fires only after exactly ``num_steps_per_env`` calls.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + for _ in range(3): + t.record_step({"log": {DEFAULT_SUCCESS_TAG: 0.1}}) + assert t.at_iteration_boundary is False + t.record_step({"log": {DEFAULT_SUCCESS_TAG: 0.1}}) + assert t.at_iteration_boundary is True + + def test_at_iteration_boundary_false_when_num_steps_zero(self): + """Test that a post-hoc tracker (``num_steps_per_env=0``) never reports a boundary.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=0) + t.record_step({"log": {DEFAULT_SUCCESS_TAG: 0.1}}) + assert t.at_iteration_boundary is False + + def test_not_converged_when_history_shorter_than_window(self): + """Test that convergence is False when there aren't yet enough history entries.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.9, 0.9] + assert t.converged is False + + def test_not_converged_when_history_empty(self): + """Test that convergence is False on a freshly-created tracker.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + assert t.history == [] + assert t.converged is False + + def test_converged_when_window_all_above_threshold(self): + """Test that convergence is True when the trailing window is all above threshold.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.1, 0.9, 0.9, 0.9] + assert t.converged is True + + def test_converged_when_history_length_equals_window(self): + """Test the window boundary: history length == window (minimum qualifying case).""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.9, 0.9, 0.9] + assert t.converged is True + + def test_converged_at_exact_threshold(self): + """Test the threshold boundary: values equal to the threshold satisfy ``>= threshold``.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.5, 0.5, 0.5] + assert t.converged is True + + def test_not_converged_when_any_window_value_below(self): + """Test that a single sub-threshold value in the trailing window blocks convergence.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.9, 0.9, 0.4] + assert t.converged is False + + def test_converged_with_window_of_one(self): + """Test the degenerate ``window=1`` case: only the last value matters.""" + t = SuccessRateTracker(0.5, 1, num_steps_per_env=4) + t.history = [0.1, 0.2, 0.9] + assert t.converged is True + t.history = [0.9, 0.9, 0.1] + assert t.converged is False + + def test_tail_mean_empty_history_is_zero(self): + """Test that ``tail_mean`` returns 0.0 for an empty history.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + assert t.tail_mean == 0.0 + + def test_tail_mean_shorter_than_window_uses_all_values(self): + """Test that ``tail_mean`` averages the full history when it's shorter than the window.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.2, 0.4] + assert t.tail_mean == pytest.approx(0.3) + + def test_tail_mean_longer_than_window_uses_tail(self): + """Test that ``tail_mean`` averages only the last ``window`` entries.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.9, 0.9, 0.1, 0.2, 0.3] + assert t.tail_mean == pytest.approx(0.2) + + def test_current_iteration_equals_history_length(self): + """Test that ``current_iteration`` reports the history length.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.1, 0.2, 0.3] + assert t.current_iteration == 3 + + +# -- CLI helpers ------------------------------------------------------------ + + +class TestCliHelpers: + """Test cases for the ``--success_*`` CLI registration and kwargs resolution.""" + + def test_defaults_parse_to_none_and_false(self): + """Test that unset args resolve to None / False.""" + args = _parser().parse_args([]) + assert args.check_success is False + assert args.success_threshold is None + assert args.success_window is None + + def test_overrides_parse(self): + """Test that explicit ``--success_*`` values round-trip through argparse.""" + args = _parser().parse_args( + [ + "--check_success", + "--success_threshold", + "0.75", + "--success_window", + "50", + ] + ) + assert args.check_success is True + assert args.success_threshold == 0.75 + assert args.success_window == 50 + + def test_build_success_kwargs_uses_defaults_when_unset(self): + """Test that ``build_success_kwargs`` substitutes library defaults for unset args.""" + kwargs = build_success_kwargs(_parser().parse_args([])) + assert kwargs == { + "threshold": DEFAULT_SUCCESS_THRESHOLD, + "window": DEFAULT_SUCCESS_WINDOW, + "stop_on_convergence": False, + } + + def test_build_success_kwargs_applies_overrides(self): + """Test that CLI overrides flow through into the kwargs dict.""" + args = _parser().parse_args( + [ + "--check_success", + "--success_threshold", + "0.1", + "--success_window", + "5", + ] + ) + kwargs = build_success_kwargs(args) + assert kwargs["threshold"] == pytest.approx(0.1) + assert kwargs["window"] == 5 + assert kwargs["stop_on_convergence"] is True + + def test_zero_threshold_is_respected_not_treated_as_unset(self): + """Test that ``--success_threshold 0`` is preserved (``is not None`` check, not truthy).""" + args = _parser().parse_args(["--success_threshold", "0"]) + assert build_success_kwargs(args)["threshold"] == 0.0 + + +# -- get_success_tracker ---------------------------------------------------- + + +class TestGetSuccessTracker: + """Test cases for the live-vs-post-hoc tracker resolution helper.""" + + def test_prefers_live_tracker_with_history(self): + """Test that a non-empty live tracker is returned as-is.""" + live = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + live.history = [0.9, 0.9] + assert get_success_tracker(_parser().parse_args([]), live, {}) is live + + def test_falls_back_to_post_hoc_when_live_tracker_empty(self): + """Test that an empty live tracker falls back to TensorBoard replay.""" + live = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + log_data = {DEFAULT_SUCCESS_TAG: [0.1, 0.2, 0.3]} + result = get_success_tracker(_parser().parse_args([]), live, log_data) + assert result is not live + assert result.history == [pytest.approx(0.1), pytest.approx(0.2), pytest.approx(0.3)] + + def test_falls_back_to_post_hoc_when_live_tracker_none(self): + """Test that a missing live tracker falls back to TensorBoard replay.""" + log_data = {DEFAULT_SUCCESS_TAG: [0.5, 0.6, 0.7]} + result = get_success_tracker(_parser().parse_args([]), None, log_data) + assert result is not None + assert result.history == [pytest.approx(0.5), pytest.approx(0.6), pytest.approx(0.7)] + + def test_returns_none_when_no_data_anywhere(self): + """Test that both sources missing resolves to ``None``.""" + assert get_success_tracker(_parser().parse_args([]), None, {}) is None + + def test_returns_none_when_tag_absent_from_log_data(self): + """Test that unrelated TensorBoard tags don't satisfy the fallback.""" + assert get_success_tracker(_parser().parse_args([]), None, {"Metrics/other": [1.0]}) is None + + def test_post_hoc_honors_override_threshold_and_window(self): + """Test that CLI threshold/window overrides are applied to the post-hoc tracker.""" + args = _parser().parse_args(["--success_threshold", "0.2", "--success_window", "2"]) + log_data = {DEFAULT_SUCCESS_TAG: [0.3, 0.3]} + result = get_success_tracker(args, None, log_data) + assert result.threshold == pytest.approx(0.2) + assert result.window == 2 + assert result.converged is True + + def test_post_hoc_tracker_has_no_iteration_boundary(self): + """Test that post-hoc trackers use ``num_steps_per_env=0`` so ``at_iteration_boundary`` never fires.""" + result = get_success_tracker(_parser().parse_args([]), None, {DEFAULT_SUCCESS_TAG: [0.9]}) + assert result.num_steps_per_env == 0 + assert result.at_iteration_boundary is False + + +# -- RslRlEarlyStopWrapper -------------------------------------------------- + + +class TestRslRlEarlyStopWrapper: + """Test cases for the rsl_rl env.step monkey-patch context manager.""" + + def test_records_every_step_and_restores_on_exit(self): + """Test that wrapped env.step records, and original step is restored on normal exit.""" + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.9}}] * 5) + runner = _FakeRunner() + with RslRlEarlyStopWrapper(env, runner, 0.5, 3, num_steps_per_env=2) as ctx: + env.step(None) + assert ctx.tracker._iter_sum == pytest.approx(0.9) + # after exit, env.step no longer routes through the tracker + env.step(None) + assert ctx.tracker._iter_sum == pytest.approx(0.9) + assert env.step_calls == 2 + + def test_raises_and_cleans_up_on_convergence_by_default(self): + """Test that convergence triggers cleanup (checkpoint + flush) and suppresses the exception.""" + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.9}}] * 100) + runner = _FakeRunner() + # num_steps_per_env=2, window=2 -> converges on step 4 (iter 2) + with RslRlEarlyStopWrapper(env, runner, 0.5, 2, num_steps_per_env=2) as ctx: + for _ in range(10): + env.step(None) + assert ctx.tracker.converged is True + assert env.step_calls == 4 + assert len(runner.saved) == 1 + assert runner.logger.stopped is True + + def test_does_not_raise_when_stop_on_convergence_false(self): + """Test that ``stop_on_convergence=False`` lets training run past convergence.""" + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.9}}] * 100) + runner = _FakeRunner() + with RslRlEarlyStopWrapper( + env, + runner, + 0.5, + 2, + num_steps_per_env=2, + stop_on_convergence=False, + ) as ctx: + for _ in range(10): + env.step(None) + assert env.step_calls == 10 + assert ctx.tracker.converged is True + assert runner.saved == [] + assert runner.logger.stopped is False + + def test_does_not_suppress_other_exceptions(self): + """Test that non-EarlyStopConverged exceptions propagate out of the ``with`` block.""" + env = _FakeEnv([{"log": {}}]) + runner = _FakeRunner() + with pytest.raises(ValueError): + with RslRlEarlyStopWrapper(env, runner, 0.5, 2, num_steps_per_env=2): + raise ValueError("not an early stop") + + def test_env_step_restored_after_early_stop_exception(self): + """Test that env.step is unwrapped after an early-stop exception suppressed by __exit__.""" + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.9}}] * 100) + runner = _FakeRunner() + with RslRlEarlyStopWrapper(env, runner, 0.5, 2, num_steps_per_env=2) as ctx: + for _ in range(10): + env.step(None) # converges & raises at step 4, suppressed + sum_at_exit = ctx.tracker._iter_sum + env.step(None) + assert ctx.tracker._iter_sum == sum_at_exit # post-exit step bypassed the tracker + + def test_env_step_restored_after_unrelated_exception(self): + """Test that env.step is unwrapped even when a non-EarlyStopConverged exception propagates.""" + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.9}}] * 10) + runner = _FakeRunner() + try: + with RslRlEarlyStopWrapper(env, runner, 0.5, 2, num_steps_per_env=2) as ctx: + env.step(None) + raise ValueError("boom") + except ValueError: + pass + sum_at_exit = ctx.tracker._iter_sum + env.step(None) + assert ctx.tracker._iter_sum == sum_at_exit + + def test_cleanup_not_called_on_unrelated_exceptions(self): + """Test that only EarlyStopConverged triggers checkpoint save + logger flush.""" + env = _FakeEnv([{"log": {}}]) + runner = _FakeRunner() + try: + with RslRlEarlyStopWrapper(env, runner, 0.5, 2, num_steps_per_env=2): + raise ValueError("boom") + except ValueError: + pass + assert runner.saved == [] + assert runner.logger.stopped is False + + def test_cleanup_skipped_when_runner_has_no_writer(self): + """Test that cleanup skips both save and flush when ``runner.logger.writer`` is ``None``.""" + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.9}}] * 100) + runner = _FakeRunner(has_writer=False) + with RslRlEarlyStopWrapper(env, runner, 0.5, 2, num_steps_per_env=2): + for _ in range(10): + env.step(None) + assert runner.saved == [] + assert runner.logger.stopped is False + + def test_framework_iteration_count_reflects_runner(self): + """Test that the framework-counter property reports ``current_learning_iteration + 1``.""" + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.0}}]) + runner = _FakeRunner() + runner.current_learning_iteration = 42 + wrapper = RslRlEarlyStopWrapper(env, runner, 0.5, 3, num_steps_per_env=2) + assert wrapper.framework_iteration_count == 43 + + +# -- RlGamesEarlyStopObserver ----------------------------------------------- + + +class TestRlGamesEarlyStopObserver: + """Test cases for the rl_games AlgoObserver that tracks success and forces max_epochs.""" + + def test_delegates_every_call_to_base(self): + """Test that all observer lifecycle calls are forwarded to the wrapped base observer.""" + base = _FakeBaseObserver() + obs = RlGamesEarlyStopObserver(base, 0.5, 3) + obs.before_init("name", {}, "exp") + obs.after_init(_FakeAlgo(horizon_length=8)) + obs.process_infos({"episode": {}}, []) + obs.after_steps() + obs.after_clear_stats() + obs.after_print_stats(0, 0, 0) + assert base.calls == [ + "before_init", + "after_init", + "process_infos", + "after_steps", + "after_clear_stats", + "after_print_stats", + ] + + def test_tracker_uses_horizon_length_attribute(self): + """Test that the tracker pulls ``num_steps_per_env`` from ``algo.horizon_length`` when present.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 3) + obs.after_init(_FakeAlgo(horizon_length=24)) + assert obs.tracker.num_steps_per_env == 24 + + def test_tracker_falls_back_to_config_horizon_length(self): + """Test that the tracker falls back to ``algo.config['horizon_length']`` when the attr is missing.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 3) + obs.after_init(_FakeAlgo(horizon_length=None, config_horizon=32)) + assert obs.tracker.num_steps_per_env == 32 + + def test_process_infos_records_from_episode_key(self): + """Test that ``infos["episode"]`` is remapped to the tracker's extras["log"] shape.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 3) + obs.after_init(_FakeAlgo(horizon_length=2)) + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.8}}, []) + assert obs.tracker._iter_sum == pytest.approx(0.8) + + def test_process_infos_is_noop_before_after_init(self): + """Test that ``process_infos`` before ``after_init`` does not raise (tracker is None).""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 3) + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.8}}, []) + assert obs.tracker is None + + def test_process_infos_ignores_non_dict_infos(self): + """Test that non-dict ``infos`` are skipped gracefully without mutating the tracker.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 3) + obs.after_init(_FakeAlgo(horizon_length=2)) + obs.process_infos([], []) + assert obs.tracker._iter_sum == 0.0 + + def test_after_steps_sets_max_epochs_on_convergence(self): + """Test that convergence on iteration N sets ``algo.max_epochs = N`` for clean exit.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 2) + algo = _FakeAlgo(horizon_length=1) + obs.after_init(algo) + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.9}}, []) + obs.after_steps() + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.9}}, []) + obs.after_steps() + assert algo.max_epochs == 2 + + def test_after_steps_leaves_max_epochs_alone_when_stop_disabled(self): + """Test that ``stop_on_convergence=False`` preserves the caller's ``algo.max_epochs``.""" + obs = RlGamesEarlyStopObserver( + _FakeBaseObserver(), + 0.5, + 2, + stop_on_convergence=False, + ) + algo = _FakeAlgo(horizon_length=1) + original_max_epochs = algo.max_epochs + obs.after_init(algo) + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.9}}, []) + obs.after_steps() + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.9}}, []) + obs.after_steps() + assert algo.max_epochs == original_max_epochs + + def test_after_steps_noop_before_after_init(self): + """Test that ``after_steps`` before ``after_init`` does not raise (tracker is None).""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 2) + obs.after_steps() + assert obs.tracker is None + + def test_each_after_steps_appends_one_iteration(self): + """Test that each ``after_steps`` call finalizes exactly one iteration in the tracker.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 5) + obs.after_init(_FakeAlgo(horizon_length=1)) + for i in range(4): + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.9}}, []) + obs.after_steps() + assert obs.tracker.current_iteration == i + 1 + + def test_after_steps_does_not_converge_with_insufficient_history(self): + """Test that a trailing window shorter than ``window`` does not trigger early stop.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 5) + algo = _FakeAlgo(horizon_length=1) + obs.after_init(algo) + for _ in range(4): + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.9}}, []) + obs.after_steps() + assert algo.max_epochs == 999 # unchanged: tracker.converged is still False + + def test_framework_iteration_count_returns_none_before_after_init(self): + """Test that the framework-counter property returns ``None`` before an algo is attached.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 2) + assert obs.framework_iteration_count is None + + def test_framework_iteration_count_reflects_algo_epoch_num(self): + """Test that the framework-counter property mirrors ``algo.epoch_num``.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 2) + obs.after_init(_FakeAlgo(horizon_length=1, epoch_num=7)) + assert obs.framework_iteration_count == 7 + + +# -- log_success (scripts.benchmarks.utils) --------------------------------- + + +class TestLogSuccess: + """Test cases for the benchmark-side success-metric logging helper.""" + + def _tracker_with(self, history: list[float]) -> SuccessRateTracker: + """Build a tracker with a pre-populated history for testing.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = history + return t + + def test_noop_when_tracker_is_none(self): + """Test that ``log_success`` emits nothing when no tracker is supplied.""" + bench = _FakeBenchmark() + log_success(bench, None) + assert bench.measurements == [] + + def test_noop_when_history_empty(self): + """Test that an empty tracker history is a silent no-op.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([])) + assert bench.measurements == [] + + def test_logs_full_measurement_set(self): + """Test that a populated tracker produces the full measurement set.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([0.9, 0.9, 0.9])) + names = {m[1] for m in bench.measurements} + assert names == {"Success Rate (tail mean)", "Success Converged At Iter", "Success Passed"} + + def test_converged_path(self): + """Test that a converged run reports ``Passed=1`` with the true converged iter + tail mean.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([0.9, 0.9, 0.9])) + assert bench.by_name("Success Passed")[2] == 1 + assert bench.by_name("Success Converged At Iter")[2] == 3 + assert bench.by_name("Success Rate (tail mean)")[2] == pytest.approx(0.9) + + def test_failed_path(self): + """Test that a non-converged run reports ``Passed=0`` and ``Converged At Iter=-1``.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([0.1, 0.2, 0.3])) + assert bench.by_name("Success Passed")[2] == 0 + assert bench.by_name("Success Converged At Iter")[2] == -1 + + def test_cadence_warning_fires_on_cadence_violation(self, capsys): + """Test that a 2x tracker/framework ratio triggers the cadence warning.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([0.5] * 100), framework_iteration_count=50) + captured = capsys.readouterr().out + assert "[WARN]" in captured + assert "check record_step cadence" in captured + + def test_no_cadence_warning_on_exact_agreement(self, capsys): + """Test that an exact tracker-vs-framework match (rl_games case) is silent.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([0.5] * 50), framework_iteration_count=50) + assert "[WARN]" not in capsys.readouterr().out + + def test_no_cadence_warning_on_rsl_rl_early_stop_offset(self, capsys): + """Test that the rsl_rl early-stop +1 offset (tracker=51, framework=50) is within slack.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([0.5] * 51), framework_iteration_count=50) + assert "[WARN]" not in capsys.readouterr().out + + def test_no_cadence_warning_when_framework_count_not_provided(self, capsys): + """Test that the cadence check is skipped entirely when no framework count is supplied.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([0.5] * 999)) + assert "[WARN]" not in capsys.readouterr().out + + def test_cadence_violation_end_to_end_via_wrapper(self, capsys): + """Test that a simulated 2x env.step bug manifests as an overcounted tracker and is caught. + + The wrapper can't distinguish "2 env.step calls that should have been 1" from normal + traffic — but the tracker overcounts iterations by 2x, and comparing against the + runner's independent counter catches the discrepancy. + """ + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.5}}] * 100) + runner = _FakeRunner() + runner.current_learning_iteration = 9 # rsl_rl thinks 10 iterations completed + with RslRlEarlyStopWrapper( + env, + runner, + 0.5, + 3, + num_steps_per_env=2, + stop_on_convergence=False, + ) as ctx: + # simulate the bug: upstream calls env.step 2x per real rollout step + for _ in range(10 * 2 * 2): # 10 iters * 2 steps/iter * 2x-bug + env.step(None) + # 40 calls with num_steps_per_env=2 => tracker.current_iteration = 20 + assert ctx.tracker.current_iteration == 20 + # framework's counter is independent: reports 10 iterations actually ran + assert ctx.framework_iteration_count == 10 + bench = _FakeBenchmark() + log_success(bench, ctx.tracker, framework_iteration_count=ctx.framework_iteration_count) + captured = capsys.readouterr().out + assert "[WARN]" in captured diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/test/test_nsys_trace.py b/simulation/modules/IsaacLab/scripts/benchmarks/test/test_nsys_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..e39f372da3804746893bf719124938e673efd00f --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/test/test_nsys_trace.py @@ -0,0 +1,153 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sync tests for ``scripts/benchmarks/nsys_trace.json``. + +The JSON lists Python functions that nsys annotates during profiling via the +``--python-functions-trace`` flag. Entries reference IsaacLab (and adjacent) +source by dotted paths. These tests catch two kinds of drift: + +* Referenced functions that no longer resolve (hard failure) +* Covered classes that have public methods not listed in the JSON (warning — + signals that new coverage may need to be added) +""" + +from isaaclab.app import AppLauncher + +simulation_app = AppLauncher(headless=True).app + +"""Rest everything follows.""" + +import importlib +import inspect +import json +import warnings +from collections import defaultdict +from pathlib import Path + +import pytest + +TRACE_JSON_PATH = Path(__file__).resolve().parents[1] / "nsys_trace.json" + + +def _load_trace_entries() -> list[dict]: + """Return the parsed JSON entries from the trace file.""" + if not TRACE_JSON_PATH.exists(): + raise RuntimeError(f"nsys trace JSON not found at {TRACE_JSON_PATH}") + try: + with TRACE_JSON_PATH.open() as f: + return json.load(f) + except json.JSONDecodeError as exc: + raise RuntimeError(f"nsys trace JSON at {TRACE_JSON_PATH} is malformed: {exc}") from exc + + +def _function_name_and_module(entry_module: str, func_spec) -> tuple[str, str]: + """Normalize a function spec to ``(module, dotted_name)``. + + ``func_spec`` may be a bare string or a dict that optionally overrides + ``module`` (per the nsys --python-functions-trace schema). + """ + if isinstance(func_spec, str): + return entry_module, func_spec + return func_spec.get("module", entry_module), func_spec["function"] + + +def _iter_function_pairs(entries: list[dict]) -> list[tuple[str, str]]: + """Yield ``(module, dotted_function_path)`` for every function in the JSON.""" + pairs: list[tuple[str, str]] = [] + for entry in entries: + entry_module = entry["module"] + for func_spec in entry["functions"]: + pairs.append(_function_name_and_module(entry_module, func_spec)) + return pairs + + +def _resolve(module_name: str, dotted_path: str): + """Import ``module_name`` and walk ``dotted_path`` via getattr.""" + obj = importlib.import_module(module_name) + for attr in dotted_path.split("."): + obj = getattr(obj, attr) + return obj + + +def _group_methods_by_class(pairs: list[tuple[str, str]]) -> dict[tuple[str, str], set[str]]: + """Group referenced method names by ``(module, class_name)``. + + Top-level functions (paths without a dot) are skipped — no class context. + """ + grouped: dict[tuple[str, str], set[str]] = defaultdict(set) + for module_name, dotted_path in pairs: + parts = dotted_path.split(".") + if len(parts) >= 2: + class_name, method_name = parts[0], parts[-1] + grouped[(module_name, class_name)].add(method_name) + return grouped + + +def _is_own_public_method(cls: type, name: str, member: object) -> bool: + """True if ``member`` is a public method defined directly on ``cls``.""" + if not inspect.isfunction(member): + return False + if name not in cls.__dict__: + return False + # Skip dunders and private helpers from the unreferenced-method check; the JSON curates inclusions explicitly. + if name.startswith("_"): + return False + return True + + +_FUNCTION_PAIRS = _iter_function_pairs(_load_trace_entries()) + + +@pytest.mark.parametrize( + "module_name, dotted_path", + _FUNCTION_PAIRS, + ids=[f"{m}:{p}" for m, p in _FUNCTION_PAIRS], +) +def test_function_resolves(module_name: str, dotted_path: str): + """Every function referenced in the trace JSON must resolve to a callable. + + A missing reference silently loses profiling coverage, so this fails loudly. + Modules that aren't importable in the current environment (e.g. optional + RL frameworks) are skipped rather than failed. + """ + try: + importlib.import_module(module_name) + except ImportError as exc: + pytest.skip(f"Module '{module_name}' not importable here: {exc}") + + try: + resolved = _resolve(module_name, dotted_path) + except AttributeError as exc: + pytest.fail(f"'{module_name}.{dotted_path}' not found: {exc}") + + assert callable(resolved), f"'{module_name}.{dotted_path}' resolved but is not callable" + + +def test_warn_unreferenced_methods_on_covered_classes(): + """Emit a warning for each public method that isn't listed in the JSON. + + Scope: classes that already have at least one method referenced. If the + class gained a new public method since the JSON was last updated, it shows + up here as a nudge to add (or intentionally omit) it. Inherited, dunder, + and private methods are excluded to keep the signal actionable. + """ + grouped = _group_methods_by_class(_FUNCTION_PAIRS) + + for (module_name, class_name), referenced in sorted(grouped.items()): + try: + cls = _resolve(module_name, class_name) + except (ImportError, AttributeError): + continue + if not inspect.isclass(cls): + continue + + own_public = {name for name, member in inspect.getmembers(cls) if _is_own_public_method(cls, name, member)} + unreferenced = own_public - referenced + if unreferenced: + warnings.warn( + f"{module_name}.{class_name} has public methods not listed in nsys_trace.json: {sorted(unreferenced)}", + stacklevel=2, + ) diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/test/test_training_metrics.py b/simulation/modules/IsaacLab/scripts/benchmarks/test/test_training_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..a3187fb15cc9dd2a05673dd8b97ad1ae85176709 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/test/test_training_metrics.py @@ -0,0 +1,90 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for benchmark training-metric logging helpers.""" + +from __future__ import annotations + +import pytest + +from scripts.benchmarks.utils import SUCCESS_RATE_LOG_TAGS, log_rl_training_metrics + + +class _FakeBenchmark: + """Collect benchmark measurements without initializing benchmark backends.""" + + def __init__(self): + self.measurements: list[tuple[str, str, object, str]] = [] + + def add_measurement(self, phase, measurement): + self.measurements.append((phase, measurement.name, measurement.value, getattr(measurement, "unit", ""))) + + def measurement_by_name(self, name: str): + return next(m for m in self.measurements if m[1] == name) + + +@pytest.mark.parametrize( + "workflow,reward_tag,episode_length_tag", + [ + ("rl_games", "rewards/iter", "episode_lengths/iter"), + ("rsl_rl", "Train/mean_reward", "Train/mean_episode_length"), + ], +) +def test_log_rl_training_metrics_skips_missing_short_run_scalars( + workflow: str, reward_tag: str, episode_length_tag: str, capsys: pytest.CaptureFixture[str] +): + """Short benchmark runs may finish before reward and episode-length scalars are emitted.""" + benchmark = _FakeBenchmark() + + log_rl_training_metrics( + benchmark, + log_data={}, + reward_tag=reward_tag, + episode_length_tag=episode_length_tag, + task="Isaac-Ant-v0", + workflow=workflow, + should_check_convergence=True, + ) + + assert benchmark.measurements == [] + output = capsys.readouterr().out + assert f"TensorBoard log is missing '{reward_tag}'" in output + assert f"TensorBoard log is missing '{episode_length_tag}'" in output + assert f"Cannot check convergence because '{reward_tag}' was not logged" in output + + +@pytest.mark.parametrize( + "workflow,reward_tag,episode_length_tag", + [ + ("rl_games", "rewards/iter", "episode_lengths/iter"), + ("rsl_rl", "Train/mean_reward", "Train/mean_episode_length"), + ], +) +def test_log_rl_training_metrics_logs_present_normal_run_scalars( + workflow: str, reward_tag: str, episode_length_tag: str, capsys: pytest.CaptureFixture[str] +): + """Normal runs with reward and episode-length scalars should log train metrics.""" + benchmark = _FakeBenchmark() + + log_rl_training_metrics( + benchmark, + log_data={ + reward_tag: [1.0, 2.0, 3.0], + episode_length_tag: [10.0, 11.0], + SUCCESS_RATE_LOG_TAGS[0]: [0.25, 0.5], + }, + reward_tag=reward_tag, + episode_length_tag=episode_length_tag, + task="Isaac-Ant-v0", + workflow=workflow, + ) + + assert benchmark.measurement_by_name("Rewards")[2] == [1.0, 2.0, 3.0] + assert benchmark.measurement_by_name("Max Rewards")[2] == 3.0 + assert benchmark.measurement_by_name("Episode Lengths")[2] == [10.0, 11.0] + assert benchmark.measurement_by_name("Max Episode Lengths")[2] == 11.0 + assert benchmark.measurement_by_name("Success Rates")[2] == [0.25, 0.5] + assert benchmark.measurement_by_name("success_rate")[2] == 0.5 + assert "TensorBoard log is missing" not in capsys.readouterr().out diff --git a/simulation/modules/IsaacLab/scripts/benchmarks/utils.py b/simulation/modules/IsaacLab/scripts/benchmarks/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..05effa5241726aeddcb3f984e4a7b077fc5e1a25 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/benchmarks/utils.py @@ -0,0 +1,453 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + + +import cProfile +import glob +import os +import statistics +import sys + +from tensorboard.backend.event_processing import event_accumulator + +from isaaclab.test.benchmark import BaseIsaacLabBenchmark, DictMeasurement, ListMeasurement, SingleMeasurement + +# Path to configs.yaml and the config loader. +_BENCHMARKING_DIR = os.path.join( + os.path.dirname(__file__), "..", "..", "source", "isaaclab_tasks", "test", "benchmarking" +) +_CONFIGS_YAML = os.path.join(_BENCHMARKING_DIR, "configs.yaml") +SUCCESS_RATE_LOG_TAGS = ("Metrics/success_rate", "Episode/Metrics/success_rate") + + +def get_backend_type(cli_backend: str) -> str: + """Map old CLI backend names to new backend types. + + Args: + cli_backend: The backend name from CLI arguments. + + Returns: + The new backend type string. + """ + mapping = { + "OmniPerfKPIFile": "omniperf", + "JSONFileMetrics": "json", + "OsmoKPIFile": "osmo", + "LocalLogMetrics": "json", + "omniperf": "omniperf", + "json": "json", + "osmo": "osmo", + "summary": "summary", + } + return mapping.get(cli_backend, "omniperf") + + +def parse_tf_logs(log_dir: str): + """Search for the latest tfevents file in log_dir folder and returns + the tensorboard logs in a dictionary. + + Args: + log_dir: directory used to search for tfevents files + """ + + # search log directory for latest log file + list_of_files = glob.glob(f"{log_dir}/events*") # * means all if need specific format then *.csv + latest_file = max(list_of_files, key=os.path.getctime) + + log_data = {} + ea = event_accumulator.EventAccumulator(latest_file) + ea.Reload() + tags = ea.Tags()["scalars"] + for tag in tags: + log_data[tag] = [] + for event in ea.Scalars(tag): + log_data[tag].append(event.value) + + return log_data + + +############################# +# logging benchmark metrics # +############################# + + +def log_min_max_mean_stats(benchmark: BaseIsaacLabBenchmark, values: dict): + for k, v in values.items(): + unit = "FPS" if "FPS" in k else "ms" if "Time" in k or "time" in k else "" + measurement = SingleMeasurement(name=f"Min {k}", value=min(v), unit=unit) + benchmark.add_measurement("runtime", measurement=measurement) + measurement = SingleMeasurement(name=f"Max {k}", value=max(v), unit=unit) + benchmark.add_measurement("runtime", measurement=measurement) + measurement = SingleMeasurement(name=f"Mean {k}", value=sum(v) / len(v), unit=unit) + benchmark.add_measurement("runtime", measurement=measurement) + + +def log_app_start_time(benchmark: BaseIsaacLabBenchmark, value: float): + measurement = SingleMeasurement(name="App Launch Time", value=value, unit="ms") + benchmark.add_measurement("startup", measurement=measurement) + + +def log_python_imports_time(benchmark: BaseIsaacLabBenchmark, value: float): + measurement = SingleMeasurement(name="Python Imports Time", value=value, unit="ms") + benchmark.add_measurement("startup", measurement=measurement) + + +def log_task_start_time(benchmark: BaseIsaacLabBenchmark, value: float): + measurement = SingleMeasurement(name="Task Creation and Start Time", value=value, unit="ms") + benchmark.add_measurement("startup", measurement=measurement) + + +def log_scene_creation_time(benchmark: BaseIsaacLabBenchmark, value: float): + measurement = SingleMeasurement(name="Scene Creation Time", value=value, unit="ms") + benchmark.add_measurement("startup", measurement=measurement) + + +def log_simulation_start_time(benchmark: BaseIsaacLabBenchmark, value: float): + measurement = SingleMeasurement(name="Simulation Start Time", value=value, unit="ms") + benchmark.add_measurement("startup", measurement=measurement) + + +def log_total_start_time(benchmark: BaseIsaacLabBenchmark, value: float): + measurement = SingleMeasurement(name="Total Start Time (Launch to Train)", value=value, unit="ms") + benchmark.add_measurement("startup", measurement=measurement) + + +def log_runtime_step_times(benchmark: BaseIsaacLabBenchmark, value: dict, compute_stats=True): + measurement = DictMeasurement(name="Step Frametimes", value=value) + benchmark.add_measurement("runtime", measurement=measurement) + if compute_stats: + log_min_max_mean_stats(benchmark, value) + + +def get_preset_string(hydra_args: list[str]) -> str: + """Extract the active preset string from CLI hydra args or an environment variable. + + Checks (in order): + 1. ``presets=...`` in *hydra_args* (e.g. ``presets=physx,ovrtx_renderer,rgb``) + 2. ``ISAACLAB_BENCHMARK_PRESET`` environment variable + 3. Falls back to ``"default"`` + """ + for arg in hydra_args: + if arg.startswith("presets="): + value = arg.split("=", 1)[1] + return value if value else "default" + return os.environ.get("ISAACLAB_BENCHMARK_PRESET", "") or "default" + + +def log_rl_policy_rewards(benchmark: BaseIsaacLabBenchmark, value: list): + measurement = ListMeasurement(name="Rewards", value=value) + benchmark.add_measurement("train", measurement=measurement) + # log max reward + measurement = SingleMeasurement(name="Max Rewards", value=max(value), unit="float") + benchmark.add_measurement("train", measurement=measurement) + + +def log_rl_policy_episode_lengths(benchmark: BaseIsaacLabBenchmark, value: list): + measurement = ListMeasurement(name="Episode Lengths", value=value) + benchmark.add_measurement("train", measurement=measurement) + # log max episode length + measurement = SingleMeasurement(name="Max Episode Lengths", value=max(value), unit="float") + benchmark.add_measurement("train", measurement=measurement) + + +def log_rl_policy_success_rates(benchmark: BaseIsaacLabBenchmark, value: list): + if not value: + return + measurement = ListMeasurement(name="Success Rates", value=value) + benchmark.add_measurement("train", measurement=measurement) + # Log the best observed success rate as a scalar for benchmark JSON backends. + measurement = SingleMeasurement(name="success_rate", value=max(value), unit="float") + benchmark.add_measurement("train", measurement=measurement) + + +def get_success_rate_log(log_data: dict) -> list | None: + for tag in SUCCESS_RATE_LOG_TAGS: + if tag in log_data: + return log_data[tag] + return None + + +def check_convergence( + rewards: list[float], + threshold: float, + window_pct: float = 0.2, + cv_threshold: float = 20.0, +) -> dict: + """Check whether training rewards have converged. + + Passes when the trailing window mean exceeds *threshold* and the + coefficient of variation (CV) is below *cv_threshold*. + + Args: + rewards: Per-iteration mean reward values. + threshold: Minimum reward to pass. + window_pct: Fraction of iterations for the trailing window. + cv_threshold: Maximum CV (%) for stable convergence. + + Returns: + Dict with ``tail_mean``, ``cv``, and ``passed``. + """ + if not rewards: + return {"tail_mean": 0.0, "cv": 999.9, "passed": False} + window = max(1, int(len(rewards) * window_pct)) + tail = rewards[-window:] + tail_mean = statistics.mean(tail) + tail_std = statistics.stdev(tail) if len(tail) > 1 else 0.0 + cv = (tail_std / abs(tail_mean) * 100) if tail_mean != 0 else 999.9 + passed = tail_mean >= threshold and cv <= cv_threshold + return {"tail_mean": round(tail_mean, 2), "cv": round(cv, 1), "passed": passed} + + +def log_convergence( + benchmark: BaseIsaacLabBenchmark, + rewards: list[float], + task: str, + workflow: str = "", + should_check_convergence: bool = False, + reward_threshold: float | None = None, + convergence_config: str = "full", +): + """Check reward convergence and log results to the benchmark backend. + + No-op unless *check_convergence* is True. When enabled, the threshold + is loaded from ``configs.yaml``. *reward_threshold* overrides the config. + + Args: + benchmark: Benchmark instance to log measurements to. + rewards: Per-iteration mean reward values. + task: Task name for config lookup. + workflow: RL workflow name (``rsl_rl``, ``rl_games``, etc.). + should_check_convergence: Whether ``--check_convergence`` was passed. + reward_threshold: Explicit threshold override. + convergence_config: Config section for threshold lookup (default: ``full``). + """ + if not should_check_convergence: + return + + threshold = reward_threshold + if threshold is None and os.path.exists(_CONFIGS_YAML): + if _BENCHMARKING_DIR not in sys.path: + sys.path.insert(0, _BENCHMARKING_DIR) + try: + from env_benchmark_test_utils import get_env_config, get_env_configs + + entry = get_env_config(get_env_configs(_CONFIGS_YAML), convergence_config, workflow, task) + except (ImportError, ValueError): + entry = None + if entry: + threshold = entry.get("lower_thresholds", {}).get("reward") + + if threshold is None: + print( + f"[WARNING] No reward threshold found for '{task}'" + f" in configs.yaml [{convergence_config}]. Skipping convergence check." + ) + return + + result = check_convergence(rewards, threshold) + benchmark.add_measurement( + "train", SingleMeasurement(name="Mean Reward (Converged)", value=result["tail_mean"], unit="float") + ) + benchmark.add_measurement("train", SingleMeasurement(name="Reward CV %", value=result["cv"], unit="%")) + benchmark.add_measurement( + "train", SingleMeasurement(name="Convergence Passed", value=int(result["passed"]), unit="bool") + ) + + +def log_success(benchmark, tracker, framework_iteration_count: int | None = None): + """Log success-metric results to the benchmark backend. + + Always logs the tag, tail mean, converged-at-iter, and pass/fail whenever the tracker holds + data (useful for historical comparison across runs). No-op when the tracker is ``None`` or + never recorded anything. + + Args: + benchmark: Benchmark instance. + tracker: :class:`SuccessRateTracker` from early_stop (or ``None`` if no tracker ran). + framework_iteration_count: Iterations the RL framework actually ran. When provided, emits a warning + if the tracker's count exceeds the framework's by more than 1. + """ + if tracker is None or not tracker.history: + return + + converged = tracker.converged + benchmark.add_measurement( + "train", SingleMeasurement(name="Success Rate (tail mean)", value=round(tracker.tail_mean, 4), unit="float") + ) + benchmark.add_measurement( + "train", + SingleMeasurement( + name="Success Converged At Iter", + value=tracker.current_iteration if converged else -1, + unit="int", + ), + ) + benchmark.add_measurement("train", SingleMeasurement(name="Success Passed", value=int(converged), unit="bool")) + + # +1 slack handles counters that lag behind during early-stop. + # Anything larger signals a broken record_step cadence (see SuccessRateTracker.at_iteration_boundary). + if framework_iteration_count is not None and tracker.current_iteration > framework_iteration_count + 1: + print( + f"[WARN] Success tracker logged {tracker.current_iteration} iterations vs framework's " + f"{framework_iteration_count}; check record_step cadence assumption." + ) + + +def log_rl_training_metrics( + benchmark: BaseIsaacLabBenchmark, + log_data: dict[str, list[float]], + reward_tag: str, + episode_length_tag: str, + task: str, + workflow: str, + should_check_convergence: bool = False, + reward_threshold: float | None = None, + convergence_config: str = "full", +) -> None: + """Log optional RL training metrics from TensorBoard data. + + Short smoke-test runs can finish before the RL framework emits reward or + episode-length scalars. Missing tags should skip those measurements instead + of failing the whole benchmark. + """ + rewards = log_data.get(reward_tag) + episode_lengths = log_data.get(episode_length_tag) + if rewards: + log_rl_policy_rewards(benchmark, rewards) + else: + print(f"[WARNING] TensorBoard log is missing '{reward_tag}'; skipping reward benchmark metrics.") + if episode_lengths: + log_rl_policy_episode_lengths(benchmark, episode_lengths) + else: + print(f"[WARNING] TensorBoard log is missing '{episode_length_tag}'; skipping episode-length metrics.") + + success_rates = get_success_rate_log(log_data) + if success_rates is not None: + log_rl_policy_success_rates(benchmark, success_rates) + + if rewards: + log_convergence( + benchmark, + rewards, + task, + workflow=workflow, + should_check_convergence=should_check_convergence, + reward_threshold=reward_threshold, + convergence_config=convergence_config, + ) + elif should_check_convergence: + print(f"[WARNING] Cannot check convergence because '{reward_tag}' was not logged.") + + +def parse_cprofile_stats( + profile: cProfile.Profile, + isaaclab_prefixes: list[str], + top_n: int = 30, + whitelist: list[str] | None = None, +) -> list[tuple[str, float, float]]: + """Parse cProfile stats, filtering to IsaacLab + first-level external calls. + + Walks the pstats data and keeps functions that are either (a) inside an + IsaacLab source directory, or (b) directly called by an IsaacLab function. + Results are sorted by own-time (tottime) descending. + + When *whitelist* is provided, only functions whose labels match at least one + ``fnmatch`` pattern are returned. Patterns that match no profiled function + emit a ``(pattern, 0.0, 0.0)`` placeholder so dashboards always receive + consistent keys. The *top_n* parameter is ignored in whitelist mode. + + Args: + profile: A completed cProfile.Profile instance (after .disable()). + isaaclab_prefixes: Absolute file path prefixes identifying IsaacLab source + (e.g. ["/home/user/IsaacLab/source/isaaclab", ...]). + top_n: Maximum number of functions to return. Ignored when + *whitelist* is provided. + whitelist: Optional list of ``fnmatch`` patterns to select specific + functions (e.g. ``["isaaclab.cloner.*:usd_replicate"]``). + + Returns: + List of (function_label, tottime_ms, cumtime_ms) tuples sorted by + tottime descending. + """ + import fnmatch + import io + import pstats + + stats = pstats.Stats(profile, stream=io.StringIO()) + + def _is_isaaclab(filename: str) -> bool: + return any(filename.startswith(prefix) for prefix in isaaclab_prefixes) + + def _make_label(filename: str, funcname: str) -> str: + # For builtins/C-extensions the filename is something like "~" or "" + if not filename or filename.startswith("<") or filename == "~": + return funcname + # Convert absolute path to dotted module-style label + for prefix in isaaclab_prefixes: + if filename.startswith(prefix): + rel = os.path.relpath(filename, prefix) + # Strip .py, replace os.sep with dot + rel = rel.replace(os.sep, ".").removesuffix(".py") + return f"{rel}:{funcname}" + # External function — try to find the top-level package name + # e.g. ".../site-packages/torch/nn/modules/linear.py" -> "torch.nn.modules.linear" + parts = filename.replace(os.sep, "/").removesuffix(".py").split("/") + # Find "site-packages" anchor or fall back to last 3 components + try: + sp_idx = parts.index("site-packages") + short = ".".join(parts[sp_idx + 1 :]) + except ValueError: + short = ".".join(parts[-3:]) if len(parts) >= 3 else ".".join(parts) + return f"{short}:{funcname}" + + # NOTE: stats.stats is an internal CPython dict, not part of the public pstats API. + # The public get_stats_profile() (Python 3.9+) doesn't expose caller info, which + # we need for the first-level external call filter. If a future Python release + # breaks this, switch to get_stats_profile() and drop the caller-based filtering. + # stats.stats: dict[(filename, lineno, funcname)] -> (pcalls, ncalls, tottime, cumtime, callers) + # callers: dict[(filename, lineno, funcname)] -> (pcalls, ncalls, tottime, cumtime) + results = [] + for func_key, (_, _, tottime, cumtime, callers) in stats.stats.items(): + filename, _, funcname = func_key + if _is_isaaclab(filename): + label = _make_label(filename, funcname) + results.append((label, tottime * 1000.0, cumtime * 1000.0)) + else: + # Check if any direct caller is an IsaacLab function + for caller_key in callers: + caller_filename = caller_key[0] + if _is_isaaclab(caller_filename): + label = _make_label(filename, funcname) + results.append((label, tottime * 1000.0, cumtime * 1000.0)) + break + + # Sort by tottime (own-time) descending + results.sort(key=lambda x: x[1], reverse=True) + + if whitelist is None: + return results[:top_n] + + # Whitelist mode: filter by fnmatch patterns, emit placeholders for unmatched patterns + matched: dict[str, tuple[str, float, float]] = {} + matched_patterns: set[str] = set() + for label, tottime, cumtime in results: + for pattern in whitelist: + if fnmatch.fnmatch(label, pattern): + if label not in matched: + matched[label] = (label, tottime, cumtime) + matched_patterns.add(pattern) + + # Add 0.0 placeholders for patterns that matched nothing + for pattern in whitelist: + if pattern not in matched_patterns: + print( + f"[WARNING] Whitelist pattern '{pattern}' matched no profiled functions. " + "Check for typos or verify the function ran during this phase." + ) + matched[pattern] = (pattern, 0.0, 0.0) + + filtered = list(matched.values()) + filtered.sort(key=lambda x: x[1], reverse=True) + return filtered diff --git a/simulation/modules/IsaacLab/scripts/demos/arl_robot_1.py b/simulation/modules/IsaacLab/scripts/demos/arl_robot_1.py new file mode 100644 index 0000000000000000000000000000000000000000..987e6be6b2ecc223d7db241ed4f3188b0ec1cf8e --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/arl_robot_1.py @@ -0,0 +1,114 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Script to view ARL Robot 1. + +Launch Isaac Sim Simulator first. +""" + +# Create argparser +import argparse + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser(description="View ARL Robot 1 with Lee Position Controller.") +# 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 torch + +import omni.usd +from pxr import Gf, UsdLux + +import isaaclab.sim as sim_utils +from isaaclab.sim import SimulationContext + +from isaaclab_contrib.assets import Multirotor +from isaaclab_contrib.controllers.lee_position_control import LeePosController +from isaaclab_contrib.controllers.lee_position_control_cfg import LeePosControllerCfg + +from isaaclab_assets.robots.arl_robot_1 import ARL_ROBOT_1_CFG + + +def main(): + """Main function to spawn arl_robot_1.""" + + # Create simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.01) + sim = SimulationContext(sim_cfg) + + # Create a dome light with light blue color + stage = omni.usd.get_context().get_stage() + dome_light = UsdLux.DomeLight.Define(stage, "/World/DomeLight") + dome_light.CreateColorAttr(Gf.Vec3f(0.53, 0.81, 0.92)) # Light blue + dome_light.CreateIntensityAttr(1000.0) + + # Spawn ground plane + cfg = sim_utils.GroundPlaneCfg() + cfg.func("/World/defaultGroundPlane", cfg) + + # Spawn robot + robot_cfg = ARL_ROBOT_1_CFG.replace(prim_path="/World/Robot") + robot_cfg.actuators["thrusters"].dt = sim_cfg.dt + robot = Multirotor(robot_cfg) + + # Play the simulator + sim.reset() + + # Create Lee position controller + controller_cfg = LeePosControllerCfg( + K_pos_range=((2.5, 2.5, 1.5), (3.5, 3.5, 2.0)), + K_vel_range=((2.5, 2.5, 1.5), (3.5, 3.5, 2.0)), + K_rot_range=((1.6, 1.6, 0.25), (1.85, 1.85, 0.4)), + K_angvel_range=((0.4, 0.4, 0.075), (0.5, 0.5, 0.09)), + max_inclination_angle_rad=1.0471975511965976, + max_yaw_rate=1.0471975511965976, + ) + controller = LeePosController(controller_cfg, robot, num_envs=1, device=str(sim.device)) + + # Get allocation matrix and compute pseudoinverse + allocation_matrix = torch.tensor(robot_cfg.allocation_matrix, device=sim.device, dtype=torch.float32) + # allocation_matrix is (6, num_thrusters), we need pseudoinverse for wrench -> thrust + alloc_pinv = torch.linalg.pinv(allocation_matrix) # Shape: (num_thrusters, 6) + + # Position command: hover in place (zero position, zero yaw) + pos_command = torch.zeros((1, 4), device=sim.device) # [x, y, z, yaw] + pos_command[0, 2] = 1.0 # Hover at 1 meter height + + # Simulation loop + print("[INFO] Starting demo with Lee Position Controller. Press Ctrl+C to stop.") + + while simulation_app.is_running(): + # Compute wrench from velocity controller + wrench = controller.compute(pos_command) # Shape: (1, 6) + + # Allocate wrench to thrusters: thrust = pinv(A) @ wrench + thrust_cmd = torch.matmul(wrench, alloc_pinv.T) # Shape: (1, num_thrusters) + thrust_cmd = thrust_cmd.clamp(min=0.0) # Ensure non-negative thrust + + # Apply thrust + robot.set_thrust_target(thrust_cmd) + + # Step simulation + robot.write_data_to_sim() + sim.step() + + # Update robot + robot.update(sim_cfg.dt) + + # Cleanup + simulation_app.close() + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/demos/arms.py b/simulation/modules/IsaacLab/scripts/demos/arms.py new file mode 100644 index 0000000000000000000000000000000000000000..b08686a8e52cb41fa7e433ae5a2921e0a77ad3d2 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/arms.py @@ -0,0 +1,237 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates different single-arm manipulators. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/demos/arms.py + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="This script demonstrates different single-arm manipulators.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import numpy as np +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import Articulation +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR + +## +# Pre-defined configs +## +# isort: off +from isaaclab_assets import ( + FRANKA_PANDA_CFG, + UR10_CFG, + KINOVA_JACO2_N7S300_CFG, + KINOVA_JACO2_N6S300_CFG, + KINOVA_GEN3_N7_CFG, + SAWYER_CFG, +) + +# isort: on + + +def define_origins(num_origins: int, spacing: float) -> list[list[float]]: + """Defines the origins of the the scene.""" + # create tensor based on number of environments + env_origins = torch.zeros(num_origins, 3) + # create a grid of origins + num_rows = np.floor(np.sqrt(num_origins)) + num_cols = np.ceil(num_origins / num_rows) + xx, yy = torch.meshgrid(torch.arange(num_rows), torch.arange(num_cols), indexing="xy") + env_origins[:, 0] = spacing * xx.flatten()[:num_origins] - spacing * (num_rows - 1) / 2 + env_origins[:, 1] = spacing * yy.flatten()[:num_origins] - spacing * (num_cols - 1) / 2 + env_origins[:, 2] = 0.0 + # return the origins + return env_origins.tolist() + + +def design_scene() -> tuple[dict, list[list[float]]]: + """Designs the scene.""" + # Ground-plane + cfg = sim_utils.GroundPlaneCfg() + cfg.func("/World/defaultGroundPlane", cfg) + # Lights + cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) + cfg.func("/World/Light", cfg) + + # Create separate groups called "Origin1", "Origin2", "Origin3" + # Each group will have a mount and a robot on top of it + origins = define_origins(num_origins=6, spacing=2.0) + + # Origin 1 with Franka Panda + sim_utils.create_prim("/World/Origin1", "Xform", translation=origins[0]) + # -- Table + cfg = sim_utils.UsdFileCfg(usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Mounts/SeattleLabTable/table_instanceable.usd") + cfg.func("/World/Origin1/Table", cfg, translation=(0.55, 0.0, 1.05)) + # -- Robot + franka_arm_cfg = FRANKA_PANDA_CFG.replace(prim_path="/World/Origin1/Robot") + franka_arm_cfg.init_state.pos = (0.0, 0.0, 1.05) + franka_panda = Articulation(cfg=franka_arm_cfg) + + # Origin 2 with UR10 + sim_utils.create_prim("/World/Origin2", "Xform", translation=origins[1]) + # -- Table + cfg = sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Mounts/Stand/stand_instanceable.usd", scale=(2.0, 2.0, 2.0) + ) + cfg.func("/World/Origin2/Table", cfg, translation=(0.0, 0.0, 1.03)) + # -- Robot + ur10_cfg = UR10_CFG.replace(prim_path="/World/Origin2/Robot") + ur10_cfg.init_state.pos = (0.0, 0.0, 1.03) + ur10 = Articulation(cfg=ur10_cfg) + + # Origin 3 with Kinova JACO2 (7-Dof) arm + sim_utils.create_prim("/World/Origin3", "Xform", translation=origins[2]) + # -- Table + cfg = sim_utils.UsdFileCfg(usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Mounts/ThorlabsTable/table_instanceable.usd") + cfg.func("/World/Origin3/Table", cfg, translation=(0.0, 0.0, 0.8)) + # -- Robot + kinova_arm_cfg = KINOVA_JACO2_N7S300_CFG.replace(prim_path="/World/Origin3/Robot") + kinova_arm_cfg.init_state.pos = (0.0, 0.0, 0.8) + kinova_j2n7s300 = Articulation(cfg=kinova_arm_cfg) + + # Origin 4 with Kinova JACO2 (6-Dof) arm + sim_utils.create_prim("/World/Origin4", "Xform", translation=origins[3]) + # -- Table + cfg = sim_utils.UsdFileCfg(usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Mounts/ThorlabsTable/table_instanceable.usd") + cfg.func("/World/Origin4/Table", cfg, translation=(0.0, 0.0, 0.8)) + # -- Robot + kinova_arm_cfg = KINOVA_JACO2_N6S300_CFG.replace(prim_path="/World/Origin4/Robot") + kinova_arm_cfg.init_state.pos = (0.0, 0.0, 0.8) + kinova_j2n6s300 = Articulation(cfg=kinova_arm_cfg) + + # Origin 5 with Sawyer + sim_utils.create_prim("/World/Origin5", "Xform", translation=origins[4]) + # -- Table + cfg = sim_utils.UsdFileCfg(usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Mounts/SeattleLabTable/table_instanceable.usd") + cfg.func("/World/Origin5/Table", cfg, translation=(0.55, 0.0, 1.05)) + # -- Robot + kinova_arm_cfg = KINOVA_GEN3_N7_CFG.replace(prim_path="/World/Origin5/Robot") + kinova_arm_cfg.init_state.pos = (0.0, 0.0, 1.05) + kinova_gen3n7 = Articulation(cfg=kinova_arm_cfg) + + # Origin 6 with Kinova Gen3 (7-Dof) arm + sim_utils.create_prim("/World/Origin6", "Xform", translation=origins[5]) + # -- Table + cfg = sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Mounts/Stand/stand_instanceable.usd", scale=(2.0, 2.0, 2.0) + ) + cfg.func("/World/Origin6/Table", cfg, translation=(0.0, 0.0, 1.03)) + # -- Robot + sawyer_arm_cfg = SAWYER_CFG.replace(prim_path="/World/Origin6/Robot") + sawyer_arm_cfg.init_state.pos = (0.0, 0.0, 1.03) + sawyer = Articulation(cfg=sawyer_arm_cfg) + + # return the scene information + scene_entities = { + "franka_panda": franka_panda, + "ur10": ur10, + "kinova_j2n7s300": kinova_j2n7s300, + "kinova_j2n6s300": kinova_j2n6s300, + "kinova_gen3n7": kinova_gen3n7, + "sawyer": sawyer, + } + return scene_entities, origins + + +def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articulation], origins: torch.Tensor): + """Runs the simulation loop.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + # Simulate physics + while simulation_app.is_running(): + # reset + if count % 200 == 0: + # reset counters + sim_time = 0.0 + count = 0 + # reset the scene entities + for index, robot in enumerate(entities.values()): + # root state + root_pose = robot.data.default_root_pose.torch.clone() + root_pose[:, :3] += origins[index] + robot.write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = robot.data.default_root_vel.torch.clone() + robot.write_root_velocity_to_sim_index(root_velocity=root_vel) + # set joint positions + joint_pos, joint_vel = ( + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), + ) + robot.write_joint_position_to_sim_index(position=joint_pos) + robot.write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + robot.reset() + print("[INFO]: Resetting robots state...") + # apply random actions to the robots + for robot in entities.values(): + # generate random joint positions + joint_pos_target = robot.data.default_joint_pos.torch + torch.randn_like(robot.data.joint_pos.torch) * 0.1 + soft_limits = robot.data.soft_joint_pos_limits.torch + joint_pos_target = joint_pos_target.clamp_(soft_limits[..., 0], soft_limits[..., 1]) + # apply action to the robot + robot.set_joint_position_target_index(target=joint_pos_target) + # write data to sim + robot.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + for robot in entities.values(): + robot.update(sim_dt) + + +def main(): + """Main function.""" + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([3.5, 0.0, 3.2], [0.0, 0.0, 0.5]) + # design scene + scene_entities, scene_origins = design_scene() + scene_origins = torch.tensor(scene_origins, device=sim.device) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene_entities, scene_origins) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/bin_packing.py b/simulation/modules/IsaacLab/scripts/demos/bin_packing.py new file mode 100644 index 0000000000000000000000000000000000000000..989c71554285991add69b0ef4ffdcc13f39945f2 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/bin_packing.py @@ -0,0 +1,369 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Demonstration of randomized bin-packing with Isaac Lab. + +This script tiles multiple environments, spawns a configurable set of grocery +objects, and continuously randomizes their poses, velocities, mass properties, +and active/cached state to mimic a bin filling workflow. It showcases how to +use ``RigidObjectCollection`` utilities for bulk pose resets, cache management, +and out-of-bounds recovery inside an interactive simulation loop. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/demos/bin_packing.py --num_envs 32 + +""" + +from __future__ import annotations + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Demo usage of RigidObjectCollection through bin packing example") +parser.add_argument("--num_envs", type=int, default=16, help="Number of environments to spawn.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import math + +import torch + +import isaaclab.sim as sim_utils +import isaaclab.utils.math as math_utils +from isaaclab.assets import AssetBaseCfg, RigidObjectCfg, RigidObjectCollection, RigidObjectCollectionCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sim import SimulationContext +from isaaclab.utils import Timer +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR +from isaaclab.utils.configclass import configclass + +## +# Scene Configuration +## + +# Layout and spawn counts. +MAX_NUM_OBJECTS = 24 # Hard cap on objects managed per environment (active + cached). +MAX_OBJECTS_PER_BIN = 24 # Maximum active objects we plan to fit inside the bin. +MIN_OBJECTS_PER_BIN = 1 # Lower bound for randomized active object count. +NUM_OBJECTS_PER_LAYER = 4 # Number of groceries spawned on each layer of the active stack. + +# Cached staging area and grid spacing. +CACHE_HEIGHT = 2.5 # Height (m) at which inactive groceries wait out of view. +ACTIVE_LAYER_SPACING = 0.1 # Vertical spacing (m) between layers inside the bin. +CACHE_SPACING = 0.25 # XY spacing (m) between cached groceries. + +# Bin dimensions and bounds. +BIN_DIMENSIONS = (0.2, 0.3, 0.15) # Physical size (m) of the storage bin. +BIN_XY_BOUND = ((-0.2, -0.3), (0.2, 0.3)) # Valid XY region (min/max) for active groceries. + +# Randomization ranges (radians for rotations, m/s and rad/s for velocities). +POSE_RANGE = {"roll": (-3.14, 3.14), "pitch": (-3.14, 3.14), "yaw": (-3.14, 3.14)} +VELOCITY_RANGE = {"roll": (-0.2, 1.0), "pitch": (-0.2, 1.0), "yaw": (-0.2, 1.0)} + +# Object layout configuration + +GROCERIES = { + "OBJECT_A": sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/YCB/Axis_Aligned_Physics/004_sugar_box.usd", + rigid_props=sim_utils.RigidBodyPropertiesCfg(solver_position_iteration_count=4), + ), + "OBJECT_B": sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/YCB/Axis_Aligned_Physics/003_cracker_box.usd", + rigid_props=sim_utils.RigidBodyPropertiesCfg(solver_position_iteration_count=4), + ), + "OBJECT_C": sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/YCB/Axis_Aligned_Physics/005_tomato_soup_can.usd", + rigid_props=sim_utils.RigidBodyPropertiesCfg(solver_position_iteration_count=4), + ), + "OBJECT_D": sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/YCB/Axis_Aligned_Physics/006_mustard_bottle.usd", + rigid_props=sim_utils.RigidBodyPropertiesCfg(solver_position_iteration_count=4), + ), +} + + +@configclass +class MultiObjectSceneCfg(InteractiveSceneCfg): + """Configuration for a multi-object scene.""" + + # ground plane + ground = AssetBaseCfg(prim_path="/World/defaultGroundPlane", spawn=sim_utils.GroundPlaneCfg()) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # rigid object + object: RigidObjectCfg = RigidObjectCfg( + prim_path="/World/envs/env_.*/Object", + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/KLT_Bin/small_KLT.usd", + scale=(2.0, 2.0, 2.0), + rigid_props=sim_utils.RigidBodyPropertiesCfg( + solver_position_iteration_count=4, solver_velocity_iteration_count=0, kinematic_enabled=True + ), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 0.15)), + ) + + groceries: RigidObjectCollectionCfg = RigidObjectCollectionCfg( + # Instantiate four grocery variants per layer and replicate across all layers in each environment. + rigid_objects={ + f"Object_{label}_Layer{layer}": RigidObjectCfg( + prim_path=f"/World/envs/env_.*/Object_{label}_Layer{layer}", + init_state=RigidObjectCfg.InitialStateCfg(pos=(x, y, 0.2 + (layer) * 0.2)), + spawn=GROCERIES.get(f"OBJECT_{label}"), + ) + for layer in range(MAX_NUM_OBJECTS // NUM_OBJECTS_PER_LAYER) + for label, (x, y) in zip(["A", "B", "C", "D"], [(-0.035, -0.1), (-0.035, 0.1), (0.035, 0.1), (0.035, -0.1)]) + } + ) + + +def reset_object_collections( + scene: InteractiveScene, + asset_name: str, + poses: torch.Tensor, + vels: torch.Tensor, + view_ids: torch.Tensor, + noise: bool = False, +) -> None: + """Apply poses and velocities to a subset of a collection, with optional noise. + + Updates ``poses`` and ``vels`` in-place for ``view_ids`` and writes them + to the PhysX view for the collection ``asset_name``. When ``noise`` is True, adds + uniform perturbations to pose (XYZ + Euler) and velocities using ``POSE_RANGE`` and + ``VELOCITY_RANGE``. + + Args: + scene: Interactive scene containing the collection. + asset_name: Key in the scene (e.g., ``"groceries"``) for the RigidObjectCollection. + poses: Env-major body poses [m, rad], shape ``(num_envs, num_bodies, 7)``. + vels: Env-major body velocities [m/s, rad/s], shape ``(num_envs, num_bodies, 6)``. + view_ids: 1D tensor of env-major flattened indices into ``poses`` and ``vels`` to update. + noise: If True, apply pose and velocity noise before writing. + + Returns: + None: This function updates ``poses``, ``vels``, and the underlying PhysX view in-place. + """ + rigid_object_collection: RigidObjectCollection = scene[asset_name] + flat_poses = poses.view(-1, poses.shape[-1]) + flat_velocities = vels.view(-1, vels.shape[-1]) + selected_poses = flat_poses[view_ids] + positions = selected_poses[:, :3] + orientations = selected_poses[:, 3:7] + # poses + if noise: + range_list = [POSE_RANGE.get(key, (0.0, 0.0)) for key in ["x", "y", "z", "roll", "pitch", "yaw"]] + ranges = torch.tensor(range_list, device=scene.device) + samples = math_utils.sample_uniform(ranges[:, 0], ranges[:, 1], (len(view_ids), 6), device=scene.device) + positions += samples[..., 0:3] + + # Compose new orientations by applying the sampled euler noise in quaternion space. + orientations_delta = math_utils.quat_from_euler_xyz(samples[..., 3], samples[..., 4], samples[..., 5]) + orientations = math_utils.quat_mul(orientations, orientations_delta) + + # velocities + new_velocities = flat_velocities[view_ids] + if noise: + range_list = [VELOCITY_RANGE.get(key, (0.0, 0.0)) for key in ["x", "y", "z", "roll", "pitch", "yaw"]] + ranges = torch.tensor(range_list, device=scene.device) + samples = math_utils.sample_uniform(ranges[:, 0], ranges[:, 1], (len(view_ids), 6), device=scene.device) + new_velocities += samples + else: + new_velocities[:] = 0.0 + + flat_poses[view_ids, :3] = positions + flat_poses[view_ids, 3:7] = orientations + flat_velocities[view_ids] = new_velocities + + rigid_object_collection.write_body_link_pose_to_sim_index(body_poses=poses) + rigid_object_collection.write_body_com_velocity_to_sim_index(body_velocities=vels) + + +def build_grocery_defaults( + num_envs: int, + device: str = "cpu", +) -> tuple[torch.Tensor, torch.Tensor]: + """Create default active/cached spawn poses for all environments. + + - Active poses: stacked 3D grid over the bin with ``ACTIVE_LAYER_SPACING`` per layer. + - Cached poses: 2D grid at ``CACHE_HEIGHT`` to park inactive objects out of view. + + Args: + num_envs: Number of environments to tile the poses for. + device: Torch device for allocation (e.g., ``"cuda:0"`` or ``"cpu"``). + + Returns: + tuple[torch.Tensor, torch.Tensor]: Active and cached spawn poses, each shaped + ``(num_envs, M, 7)`` with ``[x, y, z, qx, qy, qz, qw]`` where ``M`` equals + ``MAX_NUM_OBJECTS``. + """ + + # The bin has a size of 0.2 x 0.3 x 0.15 m + bin_x_dim, bin_y_dim, bin_z_dim = BIN_DIMENSIONS + # First, we calculate the number of layers and objects per layer + num_layers = math.ceil(MAX_OBJECTS_PER_BIN / NUM_OBJECTS_PER_LAYER) + num_x_objects = math.ceil(math.sqrt(NUM_OBJECTS_PER_LAYER)) + num_y_objects = math.ceil(NUM_OBJECTS_PER_LAYER / num_x_objects) + total_objects = num_x_objects * num_y_objects * num_layers + # Then, we create a 3D grid that allows for IxJxN objects to be placed on top of the bin. + x = torch.linspace(-bin_x_dim * (2 / 6), bin_x_dim * (2 / 6), num_x_objects, device=device) + y = torch.linspace(-bin_y_dim * (2 / 6), bin_y_dim * (2 / 6), num_y_objects, device=device) + z = torch.linspace(0, ACTIVE_LAYER_SPACING * (num_layers - 1), num_layers, device=device) + bin_z_dim * 2 + grid_z, grid_y, grid_x = torch.meshgrid(z, y, x, indexing="ij") # Note Z first, this stacks the layers. + # Using this grid plus a reference quaternion, create the poses for the groceries to be spawned above the bin. + ref_quat = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device).repeat(total_objects, 1) + positions = torch.stack((grid_x.flatten(), grid_y.flatten(), grid_z.flatten()), dim=-1) + poses = torch.cat((positions, ref_quat), dim=-1) + # Duplicate across environments, cap at max_num_objects + active_spawn_poses = poses.unsqueeze(0).repeat(num_envs, 1, 1)[:, :MAX_NUM_OBJECTS, :] + + # We'll also create a buffer for the cached groceries. They'll be spawned below the bin so they can't be seen. + num_x_objects = math.ceil(math.sqrt(MAX_NUM_OBJECTS)) + num_y_objects = math.ceil(MAX_NUM_OBJECTS / num_x_objects) + # We create a XY grid only and fix the Z height for the cache. + x = CACHE_SPACING * torch.arange(num_x_objects, device=device) + y = CACHE_SPACING * torch.arange(num_y_objects, device=device) + grid_y, grid_x = torch.meshgrid(y, x, indexing="ij") + grid_z = CACHE_HEIGHT * torch.ones_like(grid_x) + # We can then create the poses for the cached groceries. + ref_quat = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device).repeat(num_x_objects * num_y_objects, 1) + positions = torch.stack((grid_x.flatten(), grid_y.flatten(), grid_z.flatten()), dim=-1) + poses = torch.cat((positions, ref_quat), dim=-1) + # Duplicate across environments, cap at max_num_objects + cached_spawn_poses = poses.unsqueeze(0).repeat(num_envs, 1, 1)[:, :MAX_NUM_OBJECTS, :] + + return active_spawn_poses, cached_spawn_poses + + +## +# Simulation Loop +## + + +def run_simulator(sim: SimulationContext, scene: InteractiveScene) -> None: + """Runs the simulation loop that coordinates spawn randomization and stepping. + + Returns: + None: The simulator side-effects are applied through ``scene`` and ``sim``. + """ + # Extract scene entities + # note: we only do this here for readability. + groceries: RigidObjectCollection = scene["groceries"] + num_objects = groceries.num_bodies + num_envs = scene.num_envs + device = scene.device + view_indices = torch.arange(num_envs * num_objects, device=device) + default_pose_w = groceries.data.default_body_pose.torch.clone() + default_pose_w[..., :3] = default_pose_w[..., :3] + scene.env_origins.unsqueeze(1) + default_vel_w = groceries.data.default_body_vel.torch.clone() + # Define simulation stepping + sim_dt = sim.get_physics_dt() + count = 0 + + # Pre-compute canonical spawn poses for each object both inside the bin and in the cache. + active_spawn_poses, cached_spawn_poses = build_grocery_defaults(num_envs, device) + # Offset poses into each environment's world frame. + active_spawn_poses[..., :3] += scene.env_origins.view(-1, 1, 3) + cached_spawn_poses[..., :3] += scene.env_origins.view(-1, 1, 3) + spawn_poses_w = default_pose_w.clone() + spawn_vel_w = default_vel_w.clone() + + groceries_mask_helper = torch.arange(num_objects * num_envs, device=device) % num_objects + # Precompute a helper mask to toggle objects between active and cached sets. + # Precompute XY bounds [[x_min,y_min],[x_max,y_max]] + bounds_xy = torch.as_tensor(BIN_XY_BOUND, device=device, dtype=spawn_poses_w.dtype) + # Simulation loop + while simulation_app.is_running(): + # Reset + if count % 250 == 0: + # reset counter + count = 0 + # Randomly choose how many groceries stay active in each environment. + num_active_groceries = torch.randint(MIN_OBJECTS_PER_BIN, num_objects, (num_envs, 1), device=device) + groceries_mask = (groceries_mask_helper.view(num_envs, -1) < num_active_groceries).unsqueeze(-1) + spawn_poses_w[:] = cached_spawn_poses * (~groceries_mask) + active_spawn_poses * groceries_mask + # Retrieve positions + with Timer("[INFO] Time to reset scene: "): + active_indices = view_indices[~groceries_mask.view(-1)] + reset_object_collections(scene, "groceries", spawn_poses_w, spawn_vel_w, active_indices) + cached_indices = view_indices[groceries_mask.view(-1)] + reset_object_collections(scene, "groceries", spawn_poses_w, spawn_vel_w, cached_indices, noise=True) + # Vary the mass and gravity settings so cached objects stay parked. + random_masses = torch.rand((groceries.num_instances, num_objects), device=device) * 0.2 + 0.2 + groceries.set_masses_index(masses=random_masses) + scene.reset() + + # Write data to sim + scene.write_data_to_sim() + # Perform step + sim.step() + + # Bring out-of-bounds objects back to the bin in one pass. + xy = (groceries.data.body_link_pos_w.torch - scene.env_origins.unsqueeze(1))[..., :2] + out_bound = torch.nonzero((~((xy >= bounds_xy[0]) & (xy <= bounds_xy[1])).all(dim=-1)).view(-1)).flatten() + if out_bound.numel(): + # Teleport stray objects back into the active stack to keep the bin tidy. + body_pose_w = groceries.data.body_link_pose_w.torch.clone() + body_vel_w = groceries.data.body_com_vel_w.torch.clone() + body_pose_w.view(-1, 7)[out_bound] = spawn_poses_w.view(-1, 7)[out_bound] + body_vel_w.view(-1, 6)[out_bound] = spawn_vel_w.view(-1, 6)[out_bound] + reset_object_collections(scene, "groceries", body_pose_w, body_vel_w, out_bound) + # Increment counter + count += 1 + # Update buffers + scene.update(sim_dt) + + +def main() -> None: + """Main function. + + Returns: + None: The function drives the simulation for its side-effects. + """ + # Load kit helper + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device) + sim = SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view((2.5, 0.0, 4.0), (0.0, 0.0, 2.0)) + + # Design scene + scene_cfg = MultiObjectSceneCfg(num_envs=args_cli.num_envs, env_spacing=1.0, replicate_physics=True) + with Timer("[INFO] Time to create scene: "): + scene = InteractiveScene(scene_cfg) + + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main execution + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/bipeds.py b/simulation/modules/IsaacLab/scripts/demos/bipeds.py new file mode 100644 index 0000000000000000000000000000000000000000..68f79db14fcbc3bd26bffaea8bcf2ca437a01363 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/bipeds.py @@ -0,0 +1,146 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates how to simulate bipedal robots. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/demos/bipeds.py + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="This script demonstrates how to simulate bipedal robots.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import Articulation +from isaaclab.sim import SimulationContext + +## +# Pre-defined configs +## +from isaaclab_assets.robots.cassie import CASSIE_CFG # isort:skip +from isaaclab_assets import H1_CFG # isort:skip +from isaaclab_assets import G1_CFG # isort:skip + + +def design_scene(sim: sim_utils.SimulationContext) -> tuple[list, torch.Tensor]: + """Designs the scene.""" + # Ground-plane + cfg = sim_utils.GroundPlaneCfg() + cfg.func("/World/defaultGroundPlane", cfg) + # Lights + cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) + cfg.func("/World/Light", cfg) + + # Define origins + origins = torch.tensor( + [ + [0.0, -1.0, 0.0], + [0.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + ] + ).to(device=sim.device) + + # Robots + cassie = Articulation(CASSIE_CFG.replace(prim_path="/World/Cassie")) + h1 = Articulation(H1_CFG.replace(prim_path="/World/H1")) + g1 = Articulation(G1_CFG.replace(prim_path="/World/G1")) + robots = [cassie, h1, g1] + + return robots, origins + + +def run_simulator(sim: sim_utils.SimulationContext, robots: list[Articulation], origins: torch.Tensor): + """Runs the simulation loop.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + # Simulate physics + while simulation_app.is_running(): + # reset + if count % 200 == 0: + # reset counters + sim_time = 0.0 + count = 0 + for index, robot in enumerate(robots): + # reset dof state + joint_pos, joint_vel = ( + robot.data.default_joint_pos.torch, + robot.data.default_joint_vel.torch, + ) + robot.write_joint_position_to_sim_index(position=joint_pos) + robot.write_joint_velocity_to_sim_index(velocity=joint_vel) + root_pose = robot.data.default_root_pose.torch.clone() + root_pose[:, :3] += origins[index] + robot.write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = robot.data.default_root_vel.torch.clone() + robot.write_root_velocity_to_sim_index(root_velocity=root_vel) + robot.reset() + # reset command + print(">>>>>>>> Reset!") + # apply action to the robot + for robot in robots: + robot.set_joint_position_target_index(target=robot.data.default_joint_pos.torch.clone()) + robot.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + for robot in robots: + robot.update(sim_dt) + + +def main(): + """Main function.""" + # Load kit helper + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device) + sim = SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[3.0, 0.0, 2.25], target=[0.0, 0.0, 1.0]) + + # design scene + robots, origins = design_scene(sim) + + # Play the simulator + sim.reset() + + # Now we are ready! + print("[INFO]: Setup complete...") + + # Run the simulator + run_simulator(sim, robots, origins) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/deformables.py b/simulation/modules/IsaacLab/scripts/demos/deformables.py new file mode 100644 index 0000000000000000000000000000000000000000..1da56e1df004a27e42aec0e8a747c0a632cdbaeb --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/deformables.py @@ -0,0 +1,277 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""This script demonstrates how to spawn deformable prims into the scene. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/demos/deformables.py + +""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# create argparser +parser = argparse.ArgumentParser(description="This script demonstrates how to spawn deformable prims into the scene.") +parser.add_argument("--backend", type=str, default="physx", choices=["physx", "newton"], help="Physics backend.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import random + +import numpy as np +import torch +import tqdm + +import isaaclab.sim as sim_utils +from isaaclab.assets import DeformableObject, DeformableObjectCfg +from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR + +if args_cli.backend == "newton": + from isaaclab_newton.sim.schemas import NewtonDeformableBodyPropertiesCfg as DeformableBodyPropertiesCfg + from isaaclab_newton.sim.spawners.materials import ( + NewtonDeformableBodyMaterialCfg as VolumeDeformableMaterialCfg, + ) + from isaaclab_newton.sim.spawners.materials import ( + NewtonSurfaceDeformableBodyMaterialCfg as SurfaceDeformableMaterialCfg, + ) +else: + from isaaclab_physx.sim.schemas import PhysxDeformableBodyPropertiesCfg as DeformableBodyPropertiesCfg + from isaaclab_physx.sim.spawners.materials import ( + PhysxDeformableBodyMaterialCfg as VolumeDeformableMaterialCfg, + ) + from isaaclab_physx.sim.spawners.materials import ( + PhysxSurfaceDeformableBodyMaterialCfg as SurfaceDeformableMaterialCfg, + ) + + +def define_origins(num_origins: int, radius: float = 2.0, center_height: float = 3.0) -> list[list[float]]: + """Defines origins distributed on the surface of a sphere, sampled according to a Fibonacci lattice. + + Args: + num_origins: Number of points to place. + radius: Radius of the sphere [m]. + center_height: Height of the sphere center above ground [m]. + """ + golden_ratio = (1 + np.sqrt(5)) / 2 + env_origins = torch.zeros(num_origins, 3) + for i in range(num_origins): + theta = 2 * np.pi * i / golden_ratio + phi = np.arccos(1 - 2 * (i + 0.5) / num_origins) + env_origins[i, 0] = radius * np.cos(theta) * np.sin(phi) + env_origins[i, 1] = radius * np.sin(theta) * np.sin(phi) + env_origins[i, 2] = radius * np.cos(phi) + center_height + return env_origins.tolist() + + +def design_scene() -> tuple[dict, list[list[float]]]: + """Designs the scene.""" + # Ground-plane + cfg_ground = sim_utils.GroundPlaneCfg() + cfg_ground.func("/World/defaultGroundPlane", cfg_ground) + + # spawn distant light + cfg_light = sim_utils.DomeLightCfg( + intensity=3000.0, + color=(0.75, 0.75, 0.75), + ) + cfg_light.func("/World/light", cfg_light) + + # spawn a red cone + cfg_sphere = sim_utils.MeshSphereCfg( + radius=0.4, + deformable_props=DeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=VolumeDeformableMaterialCfg(), + ) + cfg_cuboid = sim_utils.MeshCuboidCfg( + size=(0.6, 0.6, 0.6), + deformable_props=DeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=VolumeDeformableMaterialCfg(), + ) + cfg_cylinder = sim_utils.MeshCylinderCfg( + radius=0.25, + height=0.5, + deformable_props=DeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=VolumeDeformableMaterialCfg(), + ) + cfg_capsule = sim_utils.MeshCapsuleCfg( + radius=0.35, + height=0.5, + deformable_props=DeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=VolumeDeformableMaterialCfg(), + ) + cfg_cone = sim_utils.MeshConeCfg( + radius=0.35, + height=0.75, + deformable_props=DeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=VolumeDeformableMaterialCfg(), + ) + cfg_cloth = sim_utils.MeshRectangleCfg( + size=(1.5, 1.0), + resolution=(21, 21), + deformable_props=DeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=SurfaceDeformableMaterialCfg(), + ) + cfg_usd = sim_utils.UsdFileCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Objects/Teddy_Bear/teddy_bear.usd", + deformable_props=DeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=VolumeDeformableMaterialCfg(), + scale=[0.05, 0.05, 0.05], + ) + # create a dictionary of all the objects to be spawned + objects_cfg = { + "sphere": cfg_sphere, + "cuboid": cfg_cuboid, + "cylinder": cfg_cylinder, + "capsule": cfg_capsule, + "cone": cfg_cone, + "cloth": cfg_cloth, + "usd": cfg_usd, + } + + # Create separate groups of deformable objects + origins = define_origins(num_origins=12, radius=1.5, center_height=2.0) + print("[INFO]: Spawning objects...") + # Iterate over all the origins, spawn objects, and create a view for all the deformables + # note: since we manually spawned random deformable meshes above, we don't need to + # specify the spawn configuration for the deformable object + scene_entities = {} + for idx, origin in tqdm.tqdm(enumerate(origins), total=len(origins)): + # randomly select an object to spawn + obj_name = random.choice(list(objects_cfg.keys())) + obj_cfg = objects_cfg[obj_name] + # randomize the deformable material stiffness + if args_cli.backend == "newton" and obj_name == "cloth": + obj_cfg.physics_material.tri_ke = random.uniform(5e3, 5e4) + obj_cfg.physics_material.tri_ka = random.uniform(5e3, 5e4) + else: + youngs_modulus = random.uniform(5e5, 1e8) + poissons_ratio = random.uniform(0.25, 0.45) + if args_cli.backend == "newton": + obj_cfg.physics_material.k_mu = youngs_modulus / (2.0 * (1.0 + poissons_ratio)) + obj_cfg.physics_material.k_lambda = ( + youngs_modulus * poissons_ratio / ((1.0 + poissons_ratio) * (1.0 - 2.0 * poissons_ratio)) + ) + else: + obj_cfg.physics_material.youngs_modulus = youngs_modulus + obj_cfg.physics_material.poissons_ratio = poissons_ratio + # randomize the color + obj_cfg.visual_material.diffuse_color = (random.random(), random.random(), random.random()) + # spawn the object, separate groups for surface and volume deformables + if obj_name in ["cloth"]: + prim_path = f"/World/Origin/Surface{idx:02d}" + cfg = DeformableObjectCfg( + prim_path=prim_path, + spawn=obj_cfg, + init_state=DeformableObjectCfg.InitialStateCfg(pos=origin), + ) + scene_entities[f"Surface{idx:02d}"] = DeformableObject(cfg=cfg) + else: + prim_path = f"/World/Origin/Volume{idx:02d}" + cfg = DeformableObjectCfg( + prim_path=prim_path, + spawn=obj_cfg, + init_state=DeformableObjectCfg.InitialStateCfg(pos=origin), + ) + scene_entities[f"Volume{idx:02d}"] = DeformableObject(cfg=cfg) + + # return the scene information + return scene_entities, origins + + +def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, DeformableObject]): + """Runs the simulation loop.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + # Simulate physics + while simulation_app.is_running(): + # reset + if count % int(3.0 / sim_dt) == 0: + # reset counters + count = 0 + # reset deformable object state + for _, deform_body in enumerate(entities.values()): + # root state + nodal_state = deform_body.data.default_nodal_state_w.torch.clone() + deform_body.write_nodal_state_to_sim_index(nodal_state) + # reset the internal state + deform_body.reset() + print("[INFO]: Resetting deformable object state...") + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + for deform_body in entities.values(): + deform_body.update(sim_dt) + + +def main(): + """Main function.""" + # Initialize the simulation context + if args_cli.backend == "newton": + from isaaclab_newton.physics import NewtonCfg + + from isaaclab_contrib.deformable.newton_manager_cfg import VBDSolverCfg + + physics_cfg = NewtonCfg( + solver_cfg=VBDSolverCfg( + iterations=5, + particle_enable_self_contact=True, + particle_self_contact_radius=0.0001, + particle_self_contact_margin=0.1, + ), + num_substeps=4, + ) + else: + from isaaclab_physx.physics import PhysxCfg + + physics_cfg = PhysxCfg() + sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device, physics=physics_cfg) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([4.0, 4.0, 3.0], [0.5, 0.5, 0.0]) + + # Design scene by adding assets to it + scene_entities, _ = design_scene() + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + run_simulator(sim, scene_entities) + print("[INFO]: Simulation complete...") + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/h1_locomotion.py b/simulation/modules/IsaacLab/scripts/demos/h1_locomotion.py new file mode 100644 index 0000000000000000000000000000000000000000..2c166a00bed4a2964aab3ce479663f83e05869de --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/h1_locomotion.py @@ -0,0 +1,233 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates an interactive demo with the H1 rough terrain environment. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/demos/h1_locomotion.py + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +import os +import sys +from importlib import metadata + +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../..")) +import scripts.reinforcement_learning.rsl_rl.cli_args as cli_args # isort: skip + + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser( + description="This script demonstrates an interactive demo with the H1 rough terrain environment." +) +# append RSL-RL cli arguments +cli_args.add_rsl_rl_args(parser) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch +from rsl_rl.runners import OnPolicyRunner + +import carb +import omni +from omni.kit.viewport.utility import get_viewport_from_window_name +from omni.kit.viewport.utility.camera_state import ViewportCameraState +from pxr import Gf, Sdf + +from isaaclab.envs import ManagerBasedRLEnv +from isaaclab.sim.utils.stage import get_current_stage +from isaaclab.utils.math import quat_apply + +from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper, handle_deprecated_rsl_rl_cfg +from isaaclab_rl.utils.pretrained_checkpoint import get_published_pretrained_checkpoint + +from isaaclab_tasks.manager_based.locomotion.velocity.config.h1.rough_env_cfg import H1RoughEnvCfg_PLAY + +TASK = "Isaac-Velocity-Rough-H1-v0" +RL_LIBRARY = "rsl_rl" + + +class H1RoughDemo: + """This class provides an interactive demo for the H1 rough terrain environment. + It loads a pre-trained checkpoint for the Isaac-Velocity-Rough-H1-v0 task, trained with RSL RL + and defines a set of keyboard commands for directing motion of selected robots. + + A robot can be selected from the scene through a mouse click. Once selected, the following + keyboard controls can be used to control the robot: + + * UP: go forward + * LEFT: turn left + * RIGHT: turn right + * DOWN: stop + * C: switch between third-person and perspective views + * ESC: exit current third-person view""" + + def __init__(self): + """Initializes environment config designed for the interactive model and sets up the environment, + loads pre-trained checkpoints, and registers keyboard events.""" + agent_cfg: RslRlOnPolicyRunnerCfg = cli_args.parse_rsl_rl_cfg(TASK, args_cli) + agent_cfg = handle_deprecated_rsl_rl_cfg(agent_cfg, metadata.version("rsl-rl-lib")) + # load the trained jit policy + checkpoint = get_published_pretrained_checkpoint(RL_LIBRARY, TASK) + # create envionrment + env_cfg = H1RoughEnvCfg_PLAY() + env_cfg.scene.num_envs = 25 + env_cfg.episode_length_s = 1000000 + env_cfg.curriculum = None + env_cfg.commands.base_velocity.ranges.lin_vel_x = (0.0, 1.0) + env_cfg.commands.base_velocity.ranges.heading = (-1.0, 1.0) + # wrap around environment for rsl-rl + self.env = RslRlVecEnvWrapper(ManagerBasedRLEnv(cfg=env_cfg)) + self.device = self.env.unwrapped.device + # load previously trained model + ppo_runner = OnPolicyRunner(self.env, agent_cfg.to_dict(), log_dir=None, device=self.device) + ppo_runner.load(checkpoint) + # obtain the trained policy for inference + self.policy = ppo_runner.get_inference_policy(device=self.device) + + self.create_camera() + self.commands = torch.zeros(env_cfg.scene.num_envs, 4, device=self.device) + self.commands[:, 0:3] = self.env.unwrapped.command_manager.get_command("base_velocity") + self.set_up_keyboard() + self._prim_selection = omni.usd.get_context().get_selection() + self._selected_id = None + self._previous_selected_id = None + self._camera_local_transform = torch.tensor([-2.5, 0.0, 0.8], device=self.device) + + def create_camera(self): + """Creates a camera to be used for third-person view.""" + stage = get_current_stage() + self.viewport = get_viewport_from_window_name("Viewport") + # Create camera + self.camera_path = "/World/Camera" + self.perspective_path = "/OmniverseKit_Persp" + camera_prim = stage.DefinePrim(self.camera_path, "Camera") + camera_prim.GetAttribute("focalLength").Set(8.5) + coi_prop = camera_prim.GetProperty("omni:kit:centerOfInterest") + if not coi_prop or not coi_prop.IsValid(): + camera_prim.CreateAttribute( + "omni:kit:centerOfInterest", Sdf.ValueTypeNames.Vector3d, True, Sdf.VariabilityUniform + ).Set(Gf.Vec3d(0, 0, -10)) + self.viewport.set_active_camera(self.perspective_path) + + def set_up_keyboard(self): + """Sets up interface for keyboard input and registers the desired keys for control.""" + self._input = carb.input.acquire_input_interface() + self._keyboard = omni.appwindow.get_default_app_window().get_keyboard() + self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._on_keyboard_event) + T = 1 + R = 0.5 + self._key_to_control = { + "UP": torch.tensor([T, 0.0, 0.0, 0.0], device=self.device), + "DOWN": torch.tensor([0.0, 0.0, 0.0, 0.0], device=self.device), + "LEFT": torch.tensor([T, 0.0, 0.0, -R], device=self.device), + "RIGHT": torch.tensor([T, 0.0, 0.0, R], device=self.device), + "ZEROS": torch.tensor([0.0, 0.0, 0.0, 0.0], device=self.device), + } + + def _on_keyboard_event(self, event): + """Checks for a keyboard event and assign the corresponding command control depending on key pressed.""" + if event.type == carb.input.KeyboardEventType.KEY_PRESS: + # Arrow keys map to pre-defined command vectors to control navigation of robot + if event.input.name in self._key_to_control: + if self._selected_id is not None: + self.commands[self._selected_id] = self._key_to_control[event.input.name] + # Escape key exits out of the current selected robot view + elif event.input.name == "ESCAPE": + self._prim_selection.clear_selected_prim_paths() + # C key swaps between third-person and perspective views + elif event.input.name == "C": + if self._selected_id is not None: + if self.viewport.get_active_camera() == self.camera_path: + self.viewport.set_active_camera(self.perspective_path) + else: + self.viewport.set_active_camera(self.camera_path) + # On key release, the robot stops moving + elif event.type == carb.input.KeyboardEventType.KEY_RELEASE: + if self._selected_id is not None: + self.commands[self._selected_id] = self._key_to_control["ZEROS"] + + def update_selected_object(self): + """Determines which robot is currently selected and whether it is a valid H1 robot. + For valid robots, we enter the third-person view for that robot. + When a new robot is selected, we reset the command of the previously selected + to continue random commands.""" + + self._previous_selected_id = self._selected_id + selected_prim_paths = self._prim_selection.get_selected_prim_paths() + if len(selected_prim_paths) == 0: + self._selected_id = None + self.viewport.set_active_camera(self.perspective_path) + elif len(selected_prim_paths) > 1: + print("Multiple prims are selected. Please only select one!") + else: + prim_splitted_path = selected_prim_paths[0].split("/") + # a valid robot was selected, update the camera to go into third-person view + if len(prim_splitted_path) >= 4 and prim_splitted_path[3][0:4] == "env_": + self._selected_id = int(prim_splitted_path[3][4:]) + if self._previous_selected_id != self._selected_id: + self.viewport.set_active_camera(self.camera_path) + self._update_camera() + else: + print("The selected prim was not a H1 robot") + + # Reset commands for previously selected robot if a new one is selected + if self._previous_selected_id is not None and self._previous_selected_id != self._selected_id: + self.env.unwrapped.command_manager.reset([self._previous_selected_id]) + self.commands[:, 0:3] = self.env.unwrapped.command_manager.get_command("base_velocity") + + def _update_camera(self): + """Updates the per-frame transform of the third-person view camera to follow + the selected robot's torso transform.""" + + base_pos = self.env.unwrapped.scene["robot"].data.root_pos_w.torch[ + self._selected_id, : + ] # - env.scene.env_origins + base_quat = self.env.unwrapped.scene["robot"].data.root_quat_w.torch[self._selected_id, :] + + camera_pos = quat_apply(base_quat, self._camera_local_transform) + base_pos + + camera_state = ViewportCameraState(self.camera_path, self.viewport) + eye = Gf.Vec3d(camera_pos[0].item(), camera_pos[1].item(), camera_pos[2].item()) + target = Gf.Vec3d(base_pos[0].item(), base_pos[1].item(), base_pos[2].item() + 0.6) + camera_state.set_position_world(eye, True) + camera_state.set_target_world(target, True) + + +def main(): + """Main function.""" + demo_h1 = H1RoughDemo() + obs, _ = demo_h1.env.reset() + while simulation_app.is_running(): + # check for selected robots + demo_h1.update_selected_object() + with torch.inference_mode(): + action = demo_h1.policy(obs) + obs, _, _, _ = demo_h1.env.step(action) + # overwrite command based on keyboard input + obs[:, 9:13] = demo_h1.commands + + +if __name__ == "__main__": + main() + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/hands.py b/simulation/modules/IsaacLab/scripts/demos/hands.py new file mode 100644 index 0000000000000000000000000000000000000000..4b9a12d7b433a990653c9736b14e18458c9f3c94 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/hands.py @@ -0,0 +1,172 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates different dexterous hands. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/demos/hands.py + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="This script demonstrates different dexterous hands.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import numpy as np +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import Articulation + +## +# Pre-defined configs +## +from isaaclab_assets.robots.allegro import ALLEGRO_HAND_CFG # isort:skip +from isaaclab_assets.robots.shadow_hand import SHADOW_HAND_CFG # isort:skip + + +def define_origins(num_origins: int, spacing: float) -> list[list[float]]: + """Defines the origins of the the scene.""" + # create tensor based on number of environments + env_origins = torch.zeros(num_origins, 3) + # create a grid of origins + num_cols = np.floor(np.sqrt(num_origins)) + num_rows = np.ceil(num_origins / num_cols) + xx, yy = torch.meshgrid(torch.arange(num_rows), torch.arange(num_cols), indexing="xy") + env_origins[:, 0] = spacing * xx.flatten()[:num_origins] - spacing * (num_rows - 1) / 2 + env_origins[:, 1] = spacing * yy.flatten()[:num_origins] - spacing * (num_cols - 1) / 2 + env_origins[:, 2] = 0.0 + # return the origins + return env_origins.tolist() + + +def design_scene() -> tuple[dict, list[list[float]]]: + """Designs the scene.""" + # Ground-plane + cfg = sim_utils.GroundPlaneCfg() + cfg.func("/World/defaultGroundPlane", cfg) + # Lights + cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) + cfg.func("/World/Light", cfg) + + # Create separate groups called "Origin1", "Origin2", "Origin3" + # Each group will have a mount and a robot on top of it + origins = define_origins(num_origins=2, spacing=0.5) + + # Origin 1 with Allegro Hand + sim_utils.create_prim("/World/Origin1", "Xform", translation=origins[0]) + # -- Robot + allegro = Articulation(ALLEGRO_HAND_CFG.replace(prim_path="/World/Origin1/Robot")) + + # Origin 2 with Shadow Hand + sim_utils.create_prim("/World/Origin2", "Xform", translation=origins[1]) + # -- Robot + shadow_hand = Articulation(SHADOW_HAND_CFG.replace(prim_path="/World/Origin2/Robot")) + + # return the scene information + scene_entities = { + "allegro": allegro, + "shadow_hand": shadow_hand, + } + return scene_entities, origins + + +def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articulation], origins: torch.Tensor): + """Runs the simulation loop.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + # Start with hand open + grasp_mode = 0 + # Simulate physics + while simulation_app.is_running(): + # reset + if count % 1000 == 0: + # reset counters + sim_time = 0.0 + count = 0 + # reset robots + for index, robot in enumerate(entities.values()): + # root state + root_pose = robot.data.default_root_pose.torch.clone() + root_pose[:, :3] += origins[index] + robot.write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = robot.data.default_root_vel.torch.clone() + robot.write_root_velocity_to_sim_index(root_velocity=root_vel) + # joint state + joint_pos, joint_vel = ( + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), + ) + robot.write_joint_position_to_sim_index(position=joint_pos) + robot.write_joint_velocity_to_sim_index(velocity=joint_vel) + # reset the internal state + robot.reset() + print("[INFO]: Resetting robots state...") + # toggle grasp mode + if count % 100 == 0: + grasp_mode = 1 - grasp_mode + # apply default actions to the hands robots + for robot in entities.values(): + # generate joint positions + joint_pos_target = robot.data.soft_joint_pos_limits.torch[..., grasp_mode] + # apply action to the robot + robot.set_joint_position_target_index(target=joint_pos_target) + # write data to sim + robot.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + for robot in entities.values(): + robot.update(sim_dt) + + +def main(): + """Main function.""" + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[0.0, -0.5, 1.5], target=[0.0, -0.2, 0.5]) + # design scene + scene_entities, scene_origins = design_scene() + scene_origins = torch.tensor(scene_origins, device=sim.device) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene_entities, scene_origins) + + +if __name__ == "__main__": + # run the main execution + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/haply_teleoperation.py b/simulation/modules/IsaacLab/scripts/demos/haply_teleoperation.py new file mode 100644 index 0000000000000000000000000000000000000000..9880cae46f2e766b8268cdff5a8c175aa13ebbac --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/haply_teleoperation.py @@ -0,0 +1,372 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Demonstration of Haply device teleoperation with a robotic arm. + +This script demonstrates how to use a Haply device (Inverse3 + VerseGrip) to +teleoperate a robotic arm in Isaac Lab. The Haply provides: +- Position tracking from the Inverse3 device +- Orientation and button inputs from the VerseGrip device +- Force feedback + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/demos/haply_teleoperation.py + + # With custom WebSocket URI + ./isaaclab.sh -p scripts/demos/haply_teleoperation.py --websocket_uri ws://localhost:10001 + + # With sensitivity adjustment + ./isaaclab.sh -p scripts/demos/haply_teleoperation.py --pos_sensitivity 2.0 + +Prerequisites: + 1. Install websockets package: pip install websockets + 2. Have Haply SDK running and accessible via WebSocket + 3. Connect Inverse3 and VerseGrip devices +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Demonstration of Haply device teleoperation with Isaac Lab.") +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to spawn.") +parser.add_argument( + "--websocket_uri", + type=str, + default="ws://localhost:10001", + help="WebSocket URI for Haply SDK connection.", +) +parser.add_argument( + "--pos_sensitivity", + type=float, + default=1.0, + help="Position sensitivity scaling factor.", +) + +AppLauncher.add_app_launcher_args(parser) +parser.set_defaults(visualizer=["kit"]) +args_cli = parser.parse_args() +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +import numpy as np +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import Articulation, AssetBaseCfg, RigidObject, RigidObjectCfg +from isaaclab.controllers import DifferentialIKController, DifferentialIKControllerCfg +from isaaclab.devices import HaplyDevice, HaplyDeviceCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors import ContactSensor, ContactSensorCfg +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR +from isaaclab.utils.configclass import configclass + +from isaaclab_assets import FRANKA_PANDA_HIGH_PD_CFG # isort: skip + +# Workspace mapping constants +HAPLY_Z_OFFSET = 0.35 +WORKSPACE_LIMITS = { + "x": (0.1, 0.9), + "y": (-0.50, 0.50), + "z": (1.05, 1.85), +} + + +def apply_haply_to_robot_mapping( + haply_pos: np.ndarray | torch.Tensor, + haply_initial_pos: np.ndarray | list, + robot_initial_pos: np.ndarray | torch.Tensor, +) -> np.ndarray: + """Apply coordinate mapping from Haply workspace to Franka Panda end-effector. + + Uses absolute position control: robot position = robot_initial_pos + haply_pos (transformed) + + Args: + haply_pos: Current Haply absolute position [x, y, z] in meters + haply_initial_pos: Haply's zero reference position [x, y, z] + robot_initial_pos: Base offset for robot end-effector + + Returns: + robot_pos: Target position for robot EE in world frame [x, y, z] + + """ + # Convert to numpy + if isinstance(haply_pos, torch.Tensor): + haply_pos = haply_pos.cpu().numpy() + if isinstance(robot_initial_pos, torch.Tensor): + robot_initial_pos = robot_initial_pos.cpu().numpy() + + haply_delta = haply_pos - haply_initial_pos + + # Coordinate system mapping: Haply (X, Y, Z) -> Robot (-Y, X, Z-offset) + robot_offset = np.array([-haply_delta[1], haply_delta[0], haply_delta[2] - HAPLY_Z_OFFSET]) + robot_pos = robot_initial_pos + robot_offset + + # Apply workspace limits for safety + robot_pos[0] = np.clip(robot_pos[0], WORKSPACE_LIMITS["x"][0], WORKSPACE_LIMITS["x"][1]) + robot_pos[1] = np.clip(robot_pos[1], WORKSPACE_LIMITS["y"][0], WORKSPACE_LIMITS["y"][1]) + robot_pos[2] = np.clip(robot_pos[2], WORKSPACE_LIMITS["z"][0], WORKSPACE_LIMITS["z"][1]) + + return robot_pos + + +@configclass +class FrankaHaplySceneCfg(InteractiveSceneCfg): + """Configuration for Franka scene with Haply teleoperation and contact sensors.""" + + ground = AssetBaseCfg( + prim_path="/World/defaultGroundPlane", + spawn=sim_utils.GroundPlaneCfg(), + ) + + dome_light = AssetBaseCfg( + prim_path="/World/Light", + spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)), + ) + + table = AssetBaseCfg( + prim_path="{ENV_REGEX_NS}/Table", + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Mounts/SeattleLabTable/table_instanceable.usd", + scale=(1.0, 1.0, 1.0), + ), + init_state=AssetBaseCfg.InitialStateCfg(pos=(0.50, 0.0, 1.05), rot=(0.707, 0, 0, 0.707)), + ) + + robot: Articulation = FRANKA_PANDA_HIGH_PD_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + robot.init_state.pos = (-0.02, 0.0, 1.05) + robot.spawn.activate_contact_sensors = True + + cube = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.06, 0.06, 0.06), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=0.5), + collision_props=sim_utils.CollisionPropertiesCfg(), + physics_material=sim_utils.RigidBodyMaterialCfg(static_friction=0.5, dynamic_friction=0.5), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.2, 0.8, 0.2), metallic=0.2), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.60, 0.00, 1.15)), + ) + + left_finger_contact_sensor = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/panda_leftfinger", + update_period=0.0, + history_length=3, + debug_vis=True, + track_pose=True, + ) + + right_finger_contact_sensor = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/panda_rightfinger", + update_period=0.0, + history_length=3, + debug_vis=True, + track_pose=True, + ) + + +def run_simulator( + sim: sim_utils.SimulationContext, + scene: InteractiveScene, + haply_device: HaplyDevice, +): + """Runs the simulation loop with Haply teleoperation.""" + sim_dt = sim.get_physics_dt() + count = 1 + + robot: Articulation = scene["robot"] + cube: RigidObject = scene["cube"] + left_finger_sensor: ContactSensor = scene["left_finger_contact_sensor"] + right_finger_sensor: ContactSensor = scene["right_finger_contact_sensor"] + + ee_body_name = "panda_hand" + ee_body_idx = robot.body_names.index(ee_body_name) + # ``body_link_jacobian_w`` drops the fixed-root body row for fixed-base assets, + # so the Jacobian-axis body index is ``body_idx - 1`` in that case. + ee_jacobi_body_idx = ee_body_idx - 1 if robot.is_fixed_base else ee_body_idx + + joint_pos = robot.data.default_joint_pos.torch.clone() + joint_pos[0, :7] = torch.tensor([0.0, -0.569, 0.0, -2.81, 0.0, 3.037, 0.741], device=robot.device) + joint_vel = robot.data.default_joint_vel.torch.clone() + robot.write_joint_position_to_sim_index(position=joint_pos) + robot.write_joint_velocity_to_sim_index(velocity=joint_vel) + + for _ in range(10): + scene.write_data_to_sim() + sim.step() + scene.update(sim_dt) + + # Initialize the position of franka + robot_initial_pos = robot.data.body_pos_w.torch[0, ee_body_idx].cpu().numpy() + haply_initial_pos = np.array([0.0, 0.0, 0.0], dtype=np.float32) + + ik_controller_cfg = DifferentialIKControllerCfg( + command_type="position", + use_relative_mode=False, + ik_method="dls", + ik_params={"lambda_val": 0.05}, + ) + + # IK joints control arms, buttons control ee rotation and gripper open/close + arm_joint_names = [ + "panda_joint1", + "panda_joint2", + "panda_joint3", + "panda_joint4", + "panda_joint5", + "panda_joint6", + ] + arm_joint_indices = [robot.joint_names.index(name) for name in arm_joint_names] + + # Initialize IK controller + ik_controller = DifferentialIKController(cfg=ik_controller_cfg, num_envs=scene.num_envs, device=sim.device) + initial_ee_quat = robot.data.body_quat_w.torch[:, ee_body_idx] + ik_controller.set_command(command=torch.zeros(scene.num_envs, 3, device=sim.device), ee_quat=initial_ee_quat) + + prev_button_a = False + prev_button_b = False + prev_button_c = False + gripper_target = 0.04 + + # Initialize the rotation of franka end-effector + ee_rotation_angle = robot.data.joint_pos.torch[0, 6].item() + rotation_step = np.pi / 3 + + print("\n[INFO] Teleoperation ready!") + print(" Move handler: Control pose of the end-effector") + print(" Button A: Open | Button B: Close | Button C: Rotate EE (60°)\n") + + while simulation_app.is_running(): + if count % 10000 == 0: + count = 1 + root_pose = robot.data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + robot.write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = robot.data.default_root_vel.torch.clone() + robot.write_root_velocity_to_sim_index(root_velocity=root_vel) + + joint_pos = robot.data.default_joint_pos.torch.clone() + joint_pos[0, :7] = torch.tensor([0.0, -0.569, 0.0, -2.81, 0.0, 3.037, 0.741], device=robot.device) + joint_vel = robot.data.default_joint_vel.torch.clone() + robot.write_joint_position_to_sim_index(position=joint_pos) + robot.write_joint_velocity_to_sim_index(velocity=joint_vel) + + cube_pose = cube.data.default_root_pose.torch.clone() + cube_pose[:, :3] += scene.env_origins + cube.write_root_pose_to_sim_index(root_pose=cube_pose) + cube_vel = cube.data.default_root_vel.torch.clone() + cube.write_root_velocity_to_sim_index(root_velocity=cube_vel) + + scene.reset() + haply_device.reset() + ik_controller.reset() + print("[INFO]: Resetting robot state...") + + # Get the data from Haply device + haply_data = haply_device.advance() + + haply_pos = haply_data[:3] + button_a = haply_data[7].item() > 0.5 + button_b = haply_data[8].item() > 0.5 + button_c = haply_data[9].item() > 0.5 + + if button_a and not prev_button_a: + gripper_target = 0.04 # Open gripper + if button_b and not prev_button_b: + gripper_target = 0.0 # Close gripper + if button_c and not prev_button_c: + joint_7_limit = 3.0 + ee_rotation_angle += rotation_step + + if ee_rotation_angle > joint_7_limit: + ee_rotation_angle = -joint_7_limit + (ee_rotation_angle - joint_7_limit) + elif ee_rotation_angle < -joint_7_limit: + ee_rotation_angle = joint_7_limit + (ee_rotation_angle + joint_7_limit) + + prev_button_a = button_a + prev_button_b = button_b + prev_button_c = button_c + + # Compute IK + target_pos = apply_haply_to_robot_mapping( + haply_pos, + haply_initial_pos, + robot_initial_pos, + ) + + target_pos_tensor = torch.tensor(target_pos, dtype=torch.float32, device=sim.device).unsqueeze(0) + + current_joint_pos = robot.data.joint_pos.torch[:, arm_joint_indices] + ee_pos_w = robot.data.body_pos_w.torch[:, ee_body_idx] + ee_quat_w = robot.data.body_quat_w.torch[:, ee_body_idx] + + # get jacobian to IK controller. The DoF axis prepends ``num_base_dofs`` + # floating-base columns (0 for fixed-base, 6 for floating-base); shift the + # actuated-joint ids by ``num_base_dofs`` to address the actuated columns. + jacobi_joint_ids = [j + robot.num_base_dofs for j in arm_joint_indices] + jacobian = robot.data.body_link_jacobian_w.torch[:, ee_jacobi_body_idx, :, jacobi_joint_ids] + ik_controller.set_command(command=target_pos_tensor, ee_quat=ee_quat_w) + joint_pos_des = ik_controller.compute(ee_pos_w, ee_quat_w, jacobian, current_joint_pos) + + joint_pos_target = robot.data.joint_pos.torch[0].clone() + + # Update joints: 6 from IK + 1 from button control (correct by design) + joint_pos_target[arm_joint_indices] = joint_pos_des[0] # panda_joint1-6 from IK + joint_pos_target[6] = ee_rotation_angle # panda_joint7 - end-effector rotation (button C) + joint_pos_target[[-2, -1]] = gripper_target # gripper + + robot.set_joint_position_target_index(target=joint_pos_target.unsqueeze(0)) + + for _ in range(5): + scene.write_data_to_sim() + sim.step() + + scene.update(sim_dt) + count += 1 + + # get contact forces and apply force feedback + left_finger_forces = left_finger_sensor.data.net_forces_w[0, 0] + right_finger_forces = right_finger_sensor.data.net_forces_w[0, 0] + total_contact_force = (left_finger_forces + right_finger_forces) * 0.5 + haply_device.push_force(forces=total_contact_force.unsqueeze(0), position=torch.tensor([0])) + + +def main(): + """Main function to set up and run the Haply teleoperation demo.""" + sim_cfg = sim_utils.SimulationCfg(device=args_cli.device, dt=1 / 200) + sim = sim_utils.SimulationContext(sim_cfg) + + # set the simulation view + sim.set_camera_view([1.6, 1.0, 1.70], [0.4, 0.0, 1.0]) + + scene_cfg = FrankaHaplySceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0) + scene = InteractiveScene(scene_cfg) + + # Create Haply device + haply_cfg = HaplyDeviceCfg( + websocket_uri=args_cli.websocket_uri, + pos_sensitivity=args_cli.pos_sensitivity, + sim_device=args_cli.device, + limit_force=2.0, + ) + haply_device = HaplyDevice(cfg=haply_cfg) + print(f"[INFO] Haply connected: {args_cli.websocket_uri}") + + sim.reset() + + run_simulator(sim, scene, haply_device) + + +if __name__ == "__main__": + main() + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/markers.py b/simulation/modules/IsaacLab/scripts/demos/markers.py new file mode 100644 index 0000000000000000000000000000000000000000..bd44a887d3eda3765531ed13b7fad2444070b433 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/markers.py @@ -0,0 +1,156 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""This script demonstrates different types of markers. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/demos/markers.py + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="This script demonstrates different types of markers.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.markers import VisualizationMarkers, VisualizationMarkersCfg +from isaaclab.sim import SimulationContext +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, ISAACLAB_NUCLEUS_DIR +from isaaclab.utils.math import quat_from_angle_axis + + +def define_markers() -> VisualizationMarkers: + """Define markers with various different shapes.""" + marker_cfg = VisualizationMarkersCfg( + prim_path="/Visuals/myMarkers", + markers={ + "frame": sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/frame_prim.usd", + scale=(0.5, 0.5, 0.5), + ), + "arrow_x": sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/arrow_x.usd", + scale=(1.0, 0.5, 0.5), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 1.0)), + ), + "cube": sim_utils.CuboidCfg( + size=(1.0, 1.0, 1.0), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)), + ), + "sphere": sim_utils.SphereCfg( + radius=0.5, + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)), + ), + "cylinder": sim_utils.CylinderCfg( + radius=0.5, + height=1.0, + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 1.0)), + ), + "cone": sim_utils.ConeCfg( + radius=0.5, + height=1.0, + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 1.0, 0.0)), + ), + "mesh": sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/DexCube/dex_cube_instanceable.usd", + scale=(10.0, 10.0, 10.0), + ), + "mesh_recolored": sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/DexCube/dex_cube_instanceable.usd", + scale=(10.0, 10.0, 10.0), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.25, 0.0)), + ), + "robot_mesh": sim_utils.UsdFileCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Robots/ANYbotics/ANYmal-C/anymal_c.usd", + scale=(2.0, 2.0, 2.0), + visual_material=sim_utils.GlassMdlCfg(glass_color=(0.0, 0.1, 0.0)), + ), + }, + ) + return VisualizationMarkers(marker_cfg) + + +def main(): + """Main function.""" + # Load kit helper + sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device) + sim = SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([0.0, 18.0, 12.0], [0.0, 3.0, 0.0]) + + # Spawn things into stage + # Lights + cfg = sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + cfg.func("/World/Light", cfg) + + # create markers + my_visualizer = define_markers() + + # define a grid of positions where the markers should be placed + num_markers_per_type = 5 + grid_spacing = 2.0 + # Calculate the half-width and half-height + half_width = (num_markers_per_type - 1) / 2.0 + half_height = (my_visualizer.num_prototypes - 1) / 2.0 + # Create the x and y ranges centered around the origin + x_range = torch.arange(-half_width * grid_spacing, (half_width + 1) * grid_spacing, grid_spacing) + y_range = torch.arange(-half_height * grid_spacing, (half_height + 1) * grid_spacing, grid_spacing) + # Create the grid + x_grid, y_grid = torch.meshgrid(x_range, y_range, indexing="ij") + x_grid = x_grid.reshape(-1) + y_grid = y_grid.reshape(-1) + z_grid = torch.zeros_like(x_grid) + # marker locations + marker_locations = torch.stack([x_grid, y_grid, z_grid], dim=1) + marker_indices = torch.arange(my_visualizer.num_prototypes).repeat(num_markers_per_type) + + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + + # Yaw angle + yaw = torch.zeros_like(marker_locations[:, 0]) + # Simulate physics + while simulation_app.is_running(): + # rotate the markers around the z-axis for visualization + marker_orientations = quat_from_angle_axis(yaw, torch.tensor([0.0, 0.0, 1.0])) + # visualize + my_visualizer.visualize(marker_locations, marker_orientations, marker_indices=marker_indices) + # roll corresponding indices to show how marker prototype can be changed + if yaw[0].item() % (0.5 * torch.pi) < 0.01: + marker_indices = torch.roll(marker_indices, 1) + # perform step + sim.step() + # increment yaw + yaw += 0.01 + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/multi_asset.py b/simulation/modules/IsaacLab/scripts/demos/multi_asset.py new file mode 100644 index 0000000000000000000000000000000000000000..907c993e95495fffc2aaa6662c5193384718a494 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/multi_asset.py @@ -0,0 +1,316 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""This script demonstrates how to spawn multiple objects in multiple environments. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/demos/multi_asset.py --num_envs 2048 + +""" + +from __future__ import annotations + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Demo on spawning different objects in multiple environments.") +parser.add_argument("--num_envs", type=int, default=512, help="Number of environments to spawn.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import random + +from pxr import Gf, Sdf + +import isaaclab.sim as sim_utils +from isaaclab.assets import ( + Articulation, + ArticulationCfg, + AssetBaseCfg, + RigidObject, + RigidObjectCfg, + RigidObjectCollection, + RigidObjectCollectionCfg, +) +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sim import SimulationContext +from isaaclab.sim.utils.stage import get_current_stage +from isaaclab.utils import Timer +from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR +from isaaclab.utils.configclass import configclass + +## +# Pre-defined Configuration +## + +from isaaclab_assets.robots.anymal import ANYDRIVE_3_LSTM_ACTUATOR_CFG # isort: skip + + +## +# Randomization events. +## + + +def randomize_shape_color(prim_path_expr: str): + """Randomize the color of the geometry.""" + # get stage handle + stage = get_current_stage() + # resolve prim paths for spawning and cloning + prim_paths = sim_utils.find_matching_prim_paths(prim_path_expr) + # manually clone prims if the source prim path is a regex expression + with Sdf.ChangeBlock(): + for prim_path in prim_paths: + # spawn single instance + prim_spec = Sdf.CreatePrimInLayer(stage.GetRootLayer(), prim_path) + + # DO YOUR OWN OTHER KIND OF RANDOMIZATION HERE! + # Note: Just need to acquire the right attribute about the property you want to set + # Here is an example on setting color randomly + color_spec = prim_spec.GetAttributeAtPath(prim_path + "/geometry/material/Shader.inputs:diffuseColor") + color_spec.default = Gf.Vec3f(random.random(), random.random(), random.random()) + + +## +# Scene Configuration +## + + +@configclass +class MultiObjectSceneCfg(InteractiveSceneCfg): + """Configuration for a multi-object scene.""" + + # ground plane + ground = AssetBaseCfg(prim_path="/World/defaultGroundPlane", spawn=sim_utils.GroundPlaneCfg()) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # rigid object + object: RigidObjectCfg = RigidObjectCfg( + prim_path="/World/envs/env_.*/Object", + spawn=sim_utils.MultiAssetSpawnerCfg( + assets_cfg=[ + sim_utils.ConeCfg( + radius=0.3, + height=0.6, + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0), metallic=0.2), + ), + sim_utils.CuboidCfg( + size=(0.3, 0.3, 0.3), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0), metallic=0.2), + ), + sim_utils.SphereCfg( + radius=0.3, + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 1.0), metallic=0.2), + ), + ], + random_choice=True, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + solver_position_iteration_count=4, solver_velocity_iteration_count=0 + ), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 2.0)), + ) + + # object collection + object_collection: RigidObjectCollectionCfg = RigidObjectCollectionCfg( + rigid_objects={ + "object_A": RigidObjectCfg( + prim_path="/World/envs/env_.*/Object_A", + spawn=sim_utils.SphereCfg( + radius=0.1, + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0), metallic=0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg( + solver_position_iteration_count=4, solver_velocity_iteration_count=0 + ), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, -0.5, 2.0)), + ), + "object_B": RigidObjectCfg( + prim_path="/World/envs/env_.*/Object_B", + spawn=sim_utils.CuboidCfg( + size=(0.1, 0.1, 0.1), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0), metallic=0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg( + solver_position_iteration_count=4, solver_velocity_iteration_count=0 + ), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.5, 2.0)), + ), + "object_C": RigidObjectCfg( + prim_path="/World/envs/env_.*/Object_C", + spawn=sim_utils.ConeCfg( + radius=0.1, + height=0.3, + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0), metallic=0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg( + solver_position_iteration_count=4, solver_velocity_iteration_count=0 + ), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.5, 0.0, 2.0)), + ), + } + ) + + # articulation + robot: ArticulationCfg = ArticulationCfg( + prim_path="/World/envs/env_.*/Robot", + spawn=sim_utils.MultiUsdFileCfg( + usd_path=[ + f"{ISAACLAB_NUCLEUS_DIR}/Robots/ANYbotics/ANYmal-C/anymal_c.usd", + f"{ISAACLAB_NUCLEUS_DIR}/Robots/ANYbotics/ANYmal-D/anymal_d.usd", + ], + random_choice=True, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=False, + retain_accelerations=False, + linear_damping=0.0, + angular_damping=0.0, + max_linear_velocity=1000.0, + max_angular_velocity=1000.0, + max_depenetration_velocity=1.0, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=True, solver_position_iteration_count=4, solver_velocity_iteration_count=0 + ), + activate_contact_sensors=True, + ), + init_state=ArticulationCfg.InitialStateCfg( + pos=(0.0, 0.0, 0.6), + joint_pos={ + ".*HAA": 0.0, # all HAA + ".*F_HFE": 0.4, # both front HFE + ".*H_HFE": -0.4, # both hind HFE + ".*F_KFE": -0.8, # both front KFE + ".*H_KFE": 0.8, # both hind KFE + }, + ), + actuators={"legs": ANYDRIVE_3_LSTM_ACTUATOR_CFG}, + ) + + +## +# Simulation Loop +## + + +def run_simulator(sim: SimulationContext, scene: InteractiveScene): + """Runs the simulation loop.""" + # Extract scene entities + # note: we only do this here for readability. + rigid_object: RigidObject = scene["object"] + rigid_object_collection: RigidObjectCollection = scene["object_collection"] + robot: Articulation = scene["robot"] + # Define simulation stepping + sim_dt = sim.get_physics_dt() + count = 0 + # Simulation loop + while simulation_app.is_running(): + # Reset + if count % 250 == 0: + # reset counter + count = 0 + # reset the scene entities + # object + root_pose = rigid_object.data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + rigid_object.write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = rigid_object.data.default_root_vel.torch.clone() + rigid_object.write_root_velocity_to_sim_index(root_velocity=root_vel) + # object collection + default_pose_w = rigid_object_collection.data.default_body_pose.torch.clone() + default_pose_w[..., :3] += scene.env_origins.unsqueeze(1) + rigid_object_collection.write_body_pose_to_sim_index(body_poses=default_pose_w) + default_vel_w = rigid_object_collection.data.default_body_vel.torch.clone() + rigid_object_collection.write_body_com_velocity_to_sim_index(body_velocities=default_vel_w) + # robot + # -- root state + root_pose = robot.data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + robot.write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = robot.data.default_root_vel.torch.clone() + robot.write_root_velocity_to_sim_index(root_velocity=root_vel) + # -- joint state + joint_pos, joint_vel = ( + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), + ) + robot.write_joint_position_to_sim_index(position=joint_pos) + robot.write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + scene.reset() + print("[INFO]: Resetting scene state...") + + # Apply action to robot + robot.set_joint_position_target_index(target=robot.data.default_joint_pos.torch) + # Write data to sim + scene.write_data_to_sim() + # Perform step + sim.step() + # Increment counter + count += 1 + # Update buffers + scene.update(sim_dt) + + +def main(): + """Main function.""" + # Load kit helper + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device) + sim = SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.5, 0.0, 4.0], [0.0, 0.0, 2.0]) + + # Design scene + scene_cfg = MultiObjectSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0, replicate_physics=True) + with Timer("[INFO] Time to create scene: "): + scene = InteractiveScene(scene_cfg) + + with Timer("[INFO] Time to randomize scene: "): + # DO YOUR OWN OTHER KIND OF RANDOMIZATION HERE! + # Note: Just need to acquire the right attribute about the property you want to set + # Here is an example on setting color randomly + randomize_shape_color(scene_cfg.object.prim_path) + + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main execution + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/pick_and_place.py b/simulation/modules/IsaacLab/scripts/demos/pick_and_place.py new file mode 100644 index 0000000000000000000000000000000000000000..d5e77aa4a12acde9191b06430a42f22f2627a0b9 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/pick_and_place.py @@ -0,0 +1,435 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Keyboard control for Isaac Lab Pick and Place.") +parser.add_argument("--num_envs", type=int, default=32, help="Number of environments to spawn.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +from collections.abc import Sequence + +import torch +import warp as wp +from isaaclab_physx.assets import SurfaceGripper, SurfaceGripperCfg + +import carb +import omni + +import isaaclab.sim as sim_utils +from isaaclab.assets import ( + Articulation, + ArticulationCfg, + RigidObject, + RigidObjectCfg, +) +from isaaclab.envs import DirectRLEnv, DirectRLEnvCfg +from isaaclab.markers import SPHERE_MARKER_CFG, VisualizationMarkers +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sim import SimulationCfg +from isaaclab.sim.spawners.from_files import GroundPlaneCfg, spawn_ground_plane +from isaaclab.utils.configclass import configclass +from isaaclab.utils.math import sample_uniform + +from isaaclab_assets.robots.pick_and_place import PICK_AND_PLACE_CFG + + +@configclass +class PickAndPlaceEnvCfg(DirectRLEnvCfg): + """Example configuration for a PickAndPlace robot using suction-cups. + + This example follows what would be typically done in a DirectRL pipeline. + """ + + # env + decimation = 4 + episode_length_s = 240.0 + action_space = 4 + observation_space = 6 + state_space = 0 + + # Simulation cfg. Surface grippers are currently only supported on CPU. + # Surface grippers also require scene query support to function. + sim: SimulationCfg = SimulationCfg( + dt=1 / 60, + device="cpu", + render_interval=decimation, + use_fabric=True, + enable_scene_query_support=True, + ) + debug_vis = True + + # robot + robot_cfg: ArticulationCfg = PICK_AND_PLACE_CFG.replace(prim_path="/World/envs/env_.*/Robot") + x_dof_name = "x_axis" + y_dof_name = "y_axis" + z_dof_name = "z_axis" + + # We add a cube to pick-up + cube_cfg: RigidObjectCfg = RigidObjectCfg( + prim_path="/World/envs/env_.*/Robot/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.4, 0.4, 0.4), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.8, 0.0, 0.8)), + ), + init_state=RigidObjectCfg.InitialStateCfg(), + ) + + # Surface Gripper, the prim_expr need to point to a unique surface gripper per environment. + gripper = SurfaceGripperCfg( + prim_path="/World/envs/env_.*/Robot/picker_head/SurfaceGripper", + max_grip_distance=0.1, + shear_force_limit=500.0, + coaxial_force_limit=500.0, + retry_interval=0.2, + ) + + # scene + scene: InteractiveSceneCfg = InteractiveSceneCfg(num_envs=1, env_spacing=12.0, replicate_physics=True) + + # reset logic + # Initial position of the robot + initial_x_pos_range = [-2.0, 2.0] + initial_y_pos_range = [-2.0, 2.0] + initial_z_pos_range = [0.0, 0.5] + + # Initial position of the cube + initial_object_x_pos_range = [-2.0, 2.0] + initial_object_y_pos_range = [-2.0, -0.5] + initial_object_z_pos = 0.2 + + # Target position of the cube + target_x_pos_range = [-2.0, 2.0] + target_y_pos_range = [2.0, 0.5] + target_z_pos = 0.2 + + +class PickAndPlaceEnv(DirectRLEnv): + """Example environment for a PickAndPlace robot using suction-cups. + + This example follows what would be typically done in a DirectRL pipeline. + Here we substitute the policy by keyboard inputs. + """ + + cfg: PickAndPlaceEnvCfg + + def __init__(self, cfg: PickAndPlaceEnvCfg, render_mode: str | None = None, **kwargs): + super().__init__(cfg, render_mode, **kwargs) + + # Indices used to control the different axes of the gantry + self._x_dof_idx, _ = self.pick_and_place.find_joints(self.cfg.x_dof_name) + self._y_dof_idx, _ = self.pick_and_place.find_joints(self.cfg.y_dof_name) + self._z_dof_idx, _ = self.pick_and_place.find_joints(self.cfg.z_dof_name) + + # joints info + self.joint_pos = self.pick_and_place.data.joint_pos.torch + self.joint_vel = self.pick_and_place.data.joint_vel.torch + + # Buffers + self.go_to_cube = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device) + self.go_to_target = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device) + self.target_pos = torch.zeros((self.num_envs, 3), device=self.device, dtype=torch.float32) + self.instant_controls = torch.zeros((self.num_envs, 3), device=self.device, dtype=torch.float32) + self.permanent_controls = torch.zeros((self.num_envs, 1), device=self.device, dtype=torch.float32) + + # Visual marker for the target + self.set_debug_vis(self.cfg.debug_vis) + + # Sets up the keyboard callback and settings + self.set_up_keyboard() + + def set_up_keyboard(self): + """Sets up interface for keyboard input and registers the desired keys for control.""" + # Acquire keyboard interface + self._input = carb.input.acquire_input_interface() + self._keyboard = omni.appwindow.get_default_app_window().get_keyboard() + self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._on_keyboard_event) + # Open / Close / Idle commands for gripper + self._instant_key_controls = { + "Q": torch.tensor([0, 0, -1]), + "E": torch.tensor([0, 0, 1]), + "ZEROS": torch.tensor([0, 0, 0]), + } + # Move up or down + self._permanent_key_controls = { + "W": torch.tensor([-200.0], device=self.device), + "S": torch.tensor([100.0], device=self.device), + } + # Aiming manually is painful we can automate this. + self._auto_aim_cube = "A" + self._auto_aim_target = "D" + + # Task description: + print("Keyboard set up!") + print("The simulation is ready for you to try it out!") + print("Your goal is pick up the purple cube and to drop it on the red sphere!") + print(f"Number of environments: {self.num_envs}") + print("Use the following controls to interact with ALL environments simultaneously:") + print("Press the 'A' key to have all grippers track the cube position.") + print("Press the 'D' key to have all grippers track the target position") + print("Press the 'W' or 'S' keys to move all gantries UP or DOWN respectively") + print("Press 'Q' or 'E' to OPEN or CLOSE all grippers respectively") + + def _on_keyboard_event(self, event): + """Checks for a keyboard event and assign the corresponding command control depending on key pressed.""" + if event.type == carb.input.KeyboardEventType.KEY_PRESS: + # Logic on key press - apply to ALL environments + if event.input.name == self._auto_aim_target: + self.go_to_target[:] = True + self.go_to_cube[:] = False + if event.input.name == self._auto_aim_cube: + self.go_to_cube[:] = True + self.go_to_target[:] = False + if event.input.name in self._instant_key_controls: + self.go_to_cube[:] = False + self.go_to_target[:] = False + self.instant_controls[:] = self._instant_key_controls[event.input.name] + if event.input.name in self._permanent_key_controls: + self.go_to_cube[:] = False + self.go_to_target[:] = False + self.permanent_controls[:] = self._permanent_key_controls[event.input.name] + # On key release, all robots stop moving + elif event.type == carb.input.KeyboardEventType.KEY_RELEASE: + self.go_to_cube[:] = False + self.go_to_target[:] = False + self.instant_controls[:] = self._instant_key_controls["ZEROS"] + + def _setup_scene(self): + self.pick_and_place = Articulation(self.cfg.robot_cfg) + self.cube = RigidObject(self.cfg.cube_cfg) + self.gripper = SurfaceGripper(self.cfg.gripper) + # add ground plane + spawn_ground_plane(prim_path="/World/ground", cfg=GroundPlaneCfg()) + # clone and replicate + self.scene.clone_environments(copy_from_source=False) + # add articulation to scene + self.scene.articulations["pick_and_place"] = self.pick_and_place + self.scene.rigid_objects["cube"] = self.cube + self.scene.surface_grippers["gripper"] = self.gripper + # add lights + light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) + light_cfg.func("/World/Light", light_cfg) + + def _pre_physics_step(self, actions: torch.Tensor) -> None: + # Store the actions + self.actions = actions.clone() + + def _apply_action(self) -> None: + # We use the keyboard outputs as an action. + # Process each environment independently + if self.go_to_cube.any(): + # Effort based proportional controller to track the cube position + head_pos_x = self.pick_and_place.data.joint_pos.torch[self.go_to_cube, self._x_dof_idx[0]] + head_pos_y = self.pick_and_place.data.joint_pos.torch[self.go_to_cube, self._y_dof_idx[0]] + cube_pos_x = ( + self.cube.data.root_pos_w.torch[self.go_to_cube, 0] - self.scene.env_origins[self.go_to_cube, 0] + ) + cube_pos_y = ( + self.cube.data.root_pos_w.torch[self.go_to_cube, 1] - self.scene.env_origins[self.go_to_cube, 1] + ) + d_cube_robot_x = cube_pos_x - head_pos_x + d_cube_robot_y = cube_pos_y - head_pos_y + self.instant_controls[self.go_to_cube] = torch.stack( + [d_cube_robot_x * 5.0, d_cube_robot_y * 5.0, torch.zeros_like(d_cube_robot_x)], dim=1 + ) + if self.go_to_target.any(): + # Effort based proportional controller to track the target position + head_pos_x = self.pick_and_place.data.joint_pos.torch[self.go_to_target, self._x_dof_idx[0]] + head_pos_y = self.pick_and_place.data.joint_pos.torch[self.go_to_target, self._y_dof_idx[0]] + target_pos_x = self.target_pos[self.go_to_target, 0] + target_pos_y = self.target_pos[self.go_to_target, 1] + d_target_robot_x = target_pos_x - head_pos_x + d_target_robot_y = target_pos_y - head_pos_y + self.instant_controls[self.go_to_target] = torch.stack( + [d_target_robot_x * 5.0, d_target_robot_y * 5.0, torch.zeros_like(d_target_robot_x)], dim=1 + ) + + # Set the joint effort targets for the picker + self.pick_and_place.set_joint_effort_target_index( + target=self.instant_controls[:, 0].unsqueeze(dim=1), joint_ids=self._x_dof_idx + ) + self.pick_and_place.set_joint_effort_target_index( + target=self.instant_controls[:, 1].unsqueeze(dim=1), joint_ids=self._y_dof_idx + ) + self.pick_and_place.set_joint_effort_target_index( + target=self.permanent_controls[:, 0].unsqueeze(dim=1), joint_ids=self._z_dof_idx + ) + # Set the gripper command + self.gripper.set_grippers_command(self.instant_controls[:, 2]) + + def _get_observations(self) -> dict: + # Get the observations + gripper_state = wp.to_torch(self.gripper.state).clone() + obs = torch.cat( + ( + self.joint_pos[:, self._x_dof_idx[0]].unsqueeze(dim=1), + self.joint_vel[:, self._x_dof_idx[0]].unsqueeze(dim=1), + self.joint_pos[:, self._y_dof_idx[0]].unsqueeze(dim=1), + self.joint_vel[:, self._y_dof_idx[0]].unsqueeze(dim=1), + self.joint_pos[:, self._z_dof_idx[0]].unsqueeze(dim=1), + self.joint_vel[:, self._z_dof_idx[0]].unsqueeze(dim=1), + self.target_pos[:, 0].unsqueeze(dim=1), + self.target_pos[:, 1].unsqueeze(dim=1), + gripper_state.unsqueeze(dim=1), + ), + dim=-1, + ) + + observations = {"policy": obs} + return observations + + def _get_rewards(self) -> torch.Tensor: + return torch.zeros_like(self.reset_terminated, dtype=torch.float32) + + def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: + # Dones + self.joint_pos = self.pick_and_place.data.joint_pos.torch + self.joint_vel = self.pick_and_place.data.joint_vel.torch + # Check for time out + time_out = self.episode_length_buf >= self.max_episode_length - 1 + # Check if the cube reached the target + cube_root_pos_w = self.cube.data.root_pos_w.torch + cube_to_target_x_dist = cube_root_pos_w[:, 0] - self.target_pos[:, 0] - self.scene.env_origins[:, 0] + cube_to_target_y_dist = cube_root_pos_w[:, 1] - self.target_pos[:, 1] - self.scene.env_origins[:, 1] + cube_to_target_z_dist = cube_root_pos_w[:, 2] - self.target_pos[:, 2] - self.scene.env_origins[:, 2] + cube_to_target_distance = torch.linalg.norm( + torch.stack((cube_to_target_x_dist, cube_to_target_y_dist, cube_to_target_z_dist), dim=1), dim=1 + ) + self.target_reached = cube_to_target_distance < 0.3 + # Check if the cube is out of bounds (that is outside of the picking area) + cube_to_origin_xy_diff = cube_root_pos_w[:, :2] - self.scene.env_origins[:, :2] + cube_to_origin_x_dist = torch.abs(cube_to_origin_xy_diff[:, 0]) + cube_to_origin_y_dist = torch.abs(cube_to_origin_xy_diff[:, 1]) + self.cube_out_of_bounds = (cube_to_origin_x_dist > 2.5) | (cube_to_origin_y_dist > 2.5) + + time_out = time_out | self.target_reached + return self.cube_out_of_bounds, time_out + + def _reset_idx(self, env_ids: Sequence[int] | None): + if env_ids is None: + env_ids = self.pick_and_place._ALL_INDICES + # Reset the environment, this must be done first! As it releases the objects held by the grippers. + # (And that's an operation that should be done before the gripper or the gripped objects are moved) + super()._reset_idx(env_ids) + num_resets = len(env_ids) + + # Set a target position for the cube + self.target_pos[env_ids, 0] = sample_uniform( + self.cfg.target_x_pos_range[0], + self.cfg.target_x_pos_range[1], + num_resets, + self.device, + ) + self.target_pos[env_ids, 1] = sample_uniform( + self.cfg.target_y_pos_range[0], + self.cfg.target_y_pos_range[1], + num_resets, + self.device, + ) + self.target_pos[env_ids, 2] = self.cfg.target_z_pos + + # Set the initial position of the cube + cube_pos = self.cube.data.default_root_pose.torch[env_ids] + cube_pos[:, 0] = sample_uniform( + self.cfg.initial_object_x_pos_range[0], + self.cfg.initial_object_x_pos_range[1], + cube_pos[:, 0].shape, + self.device, + ) + cube_pos[:, 1] = sample_uniform( + self.cfg.initial_object_y_pos_range[0], + self.cfg.initial_object_y_pos_range[1], + cube_pos[:, 1].shape, + self.device, + ) + cube_pos[:, 2] = self.cfg.initial_object_z_pos + cube_pos[:, :3] += self.scene.env_origins[env_ids] + self.cube.write_root_pose_to_sim_index(root_pose=cube_pos, env_ids=env_ids) + + # Set the initial position of the robot + joint_pos = self.pick_and_place.data.default_joint_pos.torch[env_ids] + joint_pos[:, self._x_dof_idx] += sample_uniform( + self.cfg.initial_x_pos_range[0], + self.cfg.initial_x_pos_range[1], + joint_pos[:, self._x_dof_idx].shape, + self.device, + ) + joint_pos[:, self._y_dof_idx] += sample_uniform( + self.cfg.initial_y_pos_range[0], + self.cfg.initial_y_pos_range[1], + joint_pos[:, self._y_dof_idx].shape, + self.device, + ) + joint_pos[:, self._z_dof_idx] += sample_uniform( + self.cfg.initial_z_pos_range[0], + self.cfg.initial_z_pos_range[1], + joint_pos[:, self._z_dof_idx].shape, + self.device, + ) + joint_vel = self.pick_and_place.data.default_joint_vel.torch[env_ids] + + self.joint_pos[env_ids] = joint_pos + self.joint_vel[env_ids] = joint_vel + + self.pick_and_place.write_joint_position_to_sim_index(position=joint_pos, env_ids=env_ids) + self.pick_and_place.write_joint_velocity_to_sim_index(velocity=joint_vel, env_ids=env_ids) + + def _set_debug_vis_impl(self, debug_vis: bool): + # create markers if necessary for the first tome + if debug_vis: + if not hasattr(self, "goal_pos_visualizer"): + marker_cfg = SPHERE_MARKER_CFG.copy() + marker_cfg.markers["sphere"].radius = 0.25 + # -- goal pose + marker_cfg.prim_path = "/Visuals/Command/goal_position" + self.goal_pos_visualizer = VisualizationMarkers(marker_cfg) + # set their visibility to true + self.goal_pos_visualizer.set_visibility(True) + else: + if hasattr(self, "goal_pos_visualizer"): + self.goal_pos_visualizer.set_visibility(False) + + def _debug_vis_callback(self, event): + # update the markers + self.goal_pos_visualizer.visualize(self.target_pos + self.scene.env_origins) + + +def main(): + """Main function.""" + # create environment configuration + env_cfg = PickAndPlaceEnvCfg() + env_cfg.scene.num_envs = args_cli.num_envs + # create environment + pick_and_place = PickAndPlaceEnv(env_cfg) + obs, _ = pick_and_place.reset() + while simulation_app.is_running(): + # check for selected robots + with torch.inference_mode(): + actions = torch.zeros((pick_and_place.num_envs, 4), device=pick_and_place.device, dtype=torch.float32) + pick_and_place.step(actions) + + +if __name__ == "__main__": + main() + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/procedural_terrain.py b/simulation/modules/IsaacLab/scripts/demos/procedural_terrain.py new file mode 100644 index 0000000000000000000000000000000000000000..98bcd0276789f3958e68fc963c99a2964fd7c019 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/procedural_terrain.py @@ -0,0 +1,177 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates procedural terrains with flat patches. + +Example usage: + +.. code-block:: bash + + # Generate terrain with height color scheme + ./isaaclab.sh -p scripts/demos/procedural_terrain.py --color_scheme height + + # Generate terrain with random color scheme + ./isaaclab.sh -p scripts/demos/procedural_terrain.py --color_scheme random + + # Generate terrain with no color scheme + ./isaaclab.sh -p scripts/demos/procedural_terrain.py --color_scheme none + + # Generate terrain with curriculum + ./isaaclab.sh -p scripts/demos/procedural_terrain.py --use_curriculum + + # Generate terrain with curriculum along with flat patches + ./isaaclab.sh -p scripts/demos/procedural_terrain.py --use_curriculum --show_flat_patches + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="This script demonstrates procedural terrain generation.") +parser.add_argument( + "--color_scheme", + type=str, + default="none", + choices=["height", "random", "none"], + help="Color scheme to use for the terrain generation.", +) +parser.add_argument( + "--use_curriculum", + action="store_true", + default=False, + help="Whether to use the curriculum for the terrain generation.", +) +parser.add_argument( + "--show_flat_patches", + action="store_true", + default=False, + help="Whether to show the flat patches computed during the terrain generation.", +) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import random + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBase +from isaaclab.markers import VisualizationMarkers, VisualizationMarkersCfg +from isaaclab.terrains import FlatPatchSamplingCfg, TerrainImporter, TerrainImporterCfg + +## +# Pre-defined configs +## +from isaaclab.terrains.config.rough import ROUGH_TERRAINS_CFG # isort:skip + + +def design_scene() -> tuple[dict, torch.Tensor]: + """Designs the scene.""" + # Lights + cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) + cfg.func("/World/Light", cfg) + + # Parse terrain generation + terrain_gen_cfg = ROUGH_TERRAINS_CFG.replace(curriculum=args_cli.use_curriculum, color_scheme=args_cli.color_scheme) + + # Add flat patch configuration + # Note: To have separate colors for each sub-terrain type, we set the flat patch sampling configuration name + # to the sub-terrain name. However, this is not how it should be used in practice. The key name should be + # the intention of the flat patch. For instance, "source" or "target" for spawn and command related flat patches. + if args_cli.show_flat_patches: + for sub_terrain_name, sub_terrain_cfg in terrain_gen_cfg.sub_terrains.items(): + sub_terrain_cfg.flat_patch_sampling = { + sub_terrain_name: FlatPatchSamplingCfg(num_patches=10, patch_radius=0.5, max_height_diff=0.05) + } + + # Handler for terrains importing + terrain_importer_cfg = TerrainImporterCfg( + num_envs=2048, + env_spacing=3.0, + prim_path="/World/ground", + max_init_terrain_level=None, + terrain_type="generator", + terrain_generator=terrain_gen_cfg, + debug_vis=True, + ) + # Remove visual material for height and random color schemes to use the default material + if args_cli.color_scheme in ["height", "random"]: + terrain_importer_cfg.visual_material = None + # Create terrain importer + terrain_importer = TerrainImporter(terrain_importer_cfg) + + # Show the flat patches computed + if args_cli.show_flat_patches: + # Configure the flat patches + vis_cfg = VisualizationMarkersCfg(prim_path="/Visuals/TerrainFlatPatches", markers={}) + for name in terrain_importer.flat_patches: + vis_cfg.markers[name] = sim_utils.CylinderCfg( + radius=0.5, # note: manually set to the patch radius for visualization + height=0.1, + visual_material=sim_utils.GlassMdlCfg(glass_color=(random.random(), random.random(), random.random())), + ) + flat_patches_visualizer = VisualizationMarkers(vis_cfg) + + # Visualize the flat patches + all_patch_locations = [] + all_patch_indices = [] + for i, patch_locations in enumerate(terrain_importer.flat_patches.values()): + num_patch_locations = patch_locations.view(-1, 3).shape[0] + # store the patch locations and indices + all_patch_locations.append(patch_locations.view(-1, 3)) + all_patch_indices += [i] * num_patch_locations + # combine the patch locations and indices + flat_patches_visualizer.visualize(torch.cat(all_patch_locations), marker_indices=all_patch_indices) + + # return the scene information + scene_entities = {"terrain": terrain_importer} + return scene_entities, terrain_importer.env_origins + + +def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, AssetBase], origins: torch.Tensor): + """Runs the simulation loop.""" + # Simulate physics + while simulation_app.is_running(): + # perform step + sim.step() + + +def main(): + """Main function.""" + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[5.0, 5.0, 5.0], target=[0.0, 0.0, 0.0]) + # design scene + scene_entities, scene_origins = design_scene() + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene_entities, scene_origins) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/quadcopter.py b/simulation/modules/IsaacLab/scripts/demos/quadcopter.py new file mode 100644 index 0000000000000000000000000000000000000000..f3e15ff899d23d53c8cf4e6dc6f4b8fadc8f1438 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/quadcopter.py @@ -0,0 +1,128 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates how to simulate a quadcopter. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/demos/quadcopter.py + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="This script demonstrates how to simulate a quadcopter.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import Articulation +from isaaclab.sim import SimulationContext + +## +# Pre-defined configs +## +from isaaclab_assets import CRAZYFLIE_CFG # isort:skip + + +def main(): + """Main function.""" + # Load kit helper + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device) + sim = SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[0.5, 0.5, 1.0], target=[0.0, 0.0, 0.5]) + + # Spawn things into stage + # Ground-plane + cfg = sim_utils.GroundPlaneCfg() + cfg.func("/World/defaultGroundPlane", cfg) + # Lights + cfg = sim_utils.DistantLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + cfg.func("/World/Light", cfg) + + # Robots + robot_cfg = CRAZYFLIE_CFG.replace(prim_path="/World/Crazyflie") + robot_cfg.spawn.func("/World/Crazyflie", robot_cfg.spawn, translation=robot_cfg.init_state.pos) + + # create handles for the robots + robot = Articulation(robot_cfg) + + # Play the simulator + sim.reset() + + # Fetch relevant parameters to make the quadcopter hover in place + prop_body_ids = robot.find_bodies("m.*_prop")[0] + robot_mass = robot.data.body_mass.torch[0].sum() + gravity = torch.tensor(sim.cfg.gravity, device=sim.device).norm() + + # Now we are ready! + print("[INFO]: Setup complete...") + + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + # Simulate physics + while simulation_app.is_running(): + # reset + if count % 2000 == 0: + # reset counters + sim_time = 0.0 + count = 0 + # reset dof state + joint_pos, joint_vel = robot.data.default_joint_pos.torch, robot.data.default_joint_vel.torch + robot.write_joint_position_to_sim_index(position=joint_pos) + robot.write_joint_velocity_to_sim_index(velocity=joint_vel) + default_root_pose = robot.data.default_root_pose.torch + robot.write_root_pose_to_sim_index(root_pose=default_root_pose) + default_root_vel = robot.data.default_root_vel.torch + robot.write_root_velocity_to_sim_index(root_velocity=default_root_vel) + robot.reset() + # reset command + print(">>>>>>>> Reset!") + # apply action to the robot (make the robot float in place) + forces = torch.zeros(robot.num_instances, 4, 3, device=sim.device) + torques = torch.zeros_like(forces) + forces[..., 2] = robot_mass * gravity / 4.0 + robot.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + body_ids=prop_body_ids, + ) + robot.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + robot.update(sim_dt) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/quadrupeds.py b/simulation/modules/IsaacLab/scripts/demos/quadrupeds.py new file mode 100644 index 0000000000000000000000000000000000000000..59551a3738a266954e03712c2a232eda57aacdf3 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/quadrupeds.py @@ -0,0 +1,198 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates different legged robots. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/demos/quadrupeds.py + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="This script demonstrates different legged robots.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import numpy as np +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import Articulation + +## +# Pre-defined configs +## +from isaaclab_assets.robots.anymal import ANYMAL_B_CFG, ANYMAL_C_CFG, ANYMAL_D_CFG # isort:skip +from isaaclab_assets.robots.spot import SPOT_CFG # isort:skip +from isaaclab_assets.robots.unitree import UNITREE_A1_CFG, UNITREE_GO1_CFG, UNITREE_GO2_CFG # isort:skip + + +def define_origins(num_origins: int, spacing: float) -> list[list[float]]: + """Defines the origins of the scene.""" + # create tensor based on number of environments + env_origins = torch.zeros(num_origins, 3) + # create a grid of origins + num_cols = np.floor(np.sqrt(num_origins)) + num_rows = np.ceil(num_origins / num_cols) + xx, yy = torch.meshgrid(torch.arange(num_rows), torch.arange(num_cols), indexing="xy") + env_origins[:, 0] = spacing * xx.flatten()[:num_origins] - spacing * (num_rows - 1) / 2 + env_origins[:, 1] = spacing * yy.flatten()[:num_origins] - spacing * (num_cols - 1) / 2 + env_origins[:, 2] = 0.0 + # return the origins + return env_origins.tolist() + + +def design_scene() -> tuple[dict, list[list[float]]]: + """Designs the scene.""" + # Ground-plane + cfg = sim_utils.GroundPlaneCfg() + cfg.func("/World/defaultGroundPlane", cfg) + # Lights + cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) + cfg.func("/World/Light", cfg) + + # Create separate groups called "Origin1", "Origin2", "Origin3" + # Each group will have a mount and a robot on top of it + origins = define_origins(num_origins=7, spacing=1.25) + + # Origin 1 with Anymal B + sim_utils.create_prim("/World/Origin1", "Xform", translation=origins[0]) + # -- Robot + anymal_b = Articulation(ANYMAL_B_CFG.replace(prim_path="/World/Origin1/Robot")) + + # Origin 2 with Anymal C + sim_utils.create_prim("/World/Origin2", "Xform", translation=origins[1]) + # -- Robot + anymal_c = Articulation(ANYMAL_C_CFG.replace(prim_path="/World/Origin2/Robot")) + + # Origin 3 with Anymal D + sim_utils.create_prim("/World/Origin3", "Xform", translation=origins[2]) + # -- Robot + anymal_d = Articulation(ANYMAL_D_CFG.replace(prim_path="/World/Origin3/Robot")) + + # Origin 4 with Unitree A1 + sim_utils.create_prim("/World/Origin4", "Xform", translation=origins[3]) + # -- Robot + unitree_a1 = Articulation(UNITREE_A1_CFG.replace(prim_path="/World/Origin4/Robot")) + + # Origin 5 with Unitree Go1 + sim_utils.create_prim("/World/Origin5", "Xform", translation=origins[4]) + # -- Robot + unitree_go1 = Articulation(UNITREE_GO1_CFG.replace(prim_path="/World/Origin5/Robot")) + + # Origin 6 with Unitree Go2 + sim_utils.create_prim("/World/Origin6", "Xform", translation=origins[5]) + # -- Robot + unitree_go2 = Articulation(UNITREE_GO2_CFG.replace(prim_path="/World/Origin6/Robot")) + + # Origin 7 with Boston Dynamics Spot + sim_utils.create_prim("/World/Origin7", "Xform", translation=origins[6]) + # -- Robot + spot = Articulation(SPOT_CFG.replace(prim_path="/World/Origin7/Robot")) + + # return the scene information + scene_entities = { + "anymal_b": anymal_b, + "anymal_c": anymal_c, + "anymal_d": anymal_d, + "unitree_a1": unitree_a1, + "unitree_go1": unitree_go1, + "unitree_go2": unitree_go2, + "spot": spot, + } + return scene_entities, origins + + +def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articulation], origins: torch.Tensor): + """Runs the simulation loop.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + # Simulate physics + while simulation_app.is_running(): + # reset + if count % 200 == 0: + # reset counters + sim_time = 0.0 + count = 0 + # reset robots + for index, robot in enumerate(entities.values()): + # root state + root_pose = robot.data.default_root_pose.torch.clone() + root_pose[:, :3] += origins[index] + robot.write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = robot.data.default_root_vel.torch.clone() + robot.write_root_velocity_to_sim_index(root_velocity=root_vel) + # joint state + joint_pos, joint_vel = ( + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), + ) + robot.write_joint_position_to_sim_index(position=joint_pos) + robot.write_joint_velocity_to_sim_index(velocity=joint_vel) + # reset the internal state + robot.reset() + print("[INFO]: Resetting robots state...") + # apply default actions to the quadrupedal robots + for robot in entities.values(): + # generate random joint positions + joint_pos_target = robot.data.default_joint_pos.torch + torch.randn_like(robot.data.joint_pos.torch) * 0.1 + # apply action to the robot + robot.set_joint_position_target_index(target=joint_pos_target) + # write data to sim + robot.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + for robot in entities.values(): + robot.update(sim_dt) + + +def main(): + """Main function.""" + + # Initialize the simulation context + sim = sim_utils.SimulationContext(sim_utils.SimulationCfg(dt=0.01)) + # Set main camera + sim.set_camera_view(eye=[2.5, 2.5, 2.5], target=[0.0, 0.0, 0.0]) + # design scene + scene_entities, scene_origins = design_scene() + scene_origins = torch.tensor(scene_origins, device=sim.device) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene_entities, scene_origins) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/sensors/cameras.py b/simulation/modules/IsaacLab/scripts/demos/sensors/cameras.py new file mode 100644 index 0000000000000000000000000000000000000000..a501201afb6d5ff4dd59fce5f072d8cde61a355b --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/sensors/cameras.py @@ -0,0 +1,306 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates the different camera sensors that can be attached to a robot. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/demos/sensors/cameras.py --enable_cameras + + # Usage in headless mode + ./isaaclab.sh -p scripts/demos/sensors/cameras.py --headless --enable_cameras + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Example on using the different camera sensor implementations.") +parser.add_argument("--num_envs", type=int, default=4, help="Number of environments to spawn.") +parser.add_argument("--disable_fabric", action="store_true", help="Disable Fabric API and use USD instead.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import os + +import matplotlib.pyplot as plt +import numpy as np +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg, AssetBaseCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors import CameraCfg, RayCasterCameraCfg +from isaaclab.sensors.ray_caster import patterns +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils.configclass import configclass + +## +# Pre-defined configs +## +from isaaclab.terrains.config.rough import ROUGH_TERRAINS_CFG # isort:skip +from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip + + +@configclass +class SensorsSceneCfg(InteractiveSceneCfg): + """Design the scene with sensors on the robot.""" + + # ground plane + ground = TerrainImporterCfg( + prim_path="/World/ground", + max_init_terrain_level=None, + terrain_type="generator", + terrain_generator=ROUGH_TERRAINS_CFG.replace(color_scheme="random"), + visual_material=None, + debug_vis=False, + ) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) + ) + + # robot + robot: ArticulationCfg = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + # sensors + camera = CameraCfg( + prim_path="{ENV_REGEX_NS}/Robot/base/front_cam", + update_period=0.1, + height=480, + width=640, + data_types=["rgb", "distance_to_image_plane"], + spawn=sim_utils.PinholeCameraCfg( + focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 1.0e5) + ), + offset=CameraCfg.OffsetCfg(pos=(0.510, 0.0, 0.015), rot=(0.5, -0.5, 0.5, -0.5), convention="ros"), + ) + tiled_camera = CameraCfg( + prim_path="{ENV_REGEX_NS}/Robot/base/front_cam", + update_period=0.1, + height=480, + width=640, + data_types=["rgb", "distance_to_image_plane"], + spawn=None, # the camera is already spawned in the scene + offset=CameraCfg.OffsetCfg(pos=(0.510, 0.0, 0.015), rot=(0.5, -0.5, 0.5, -0.5), convention="ros"), + ) + raycast_camera = RayCasterCameraCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + mesh_prim_paths=["/World/ground"], + update_period=0.1, + offset=RayCasterCameraCfg.OffsetCfg(pos=(0.510, 0.0, 0.015), rot=(0.5, -0.5, 0.5, -0.5), convention="ros"), + data_types=["distance_to_image_plane", "normals"], + pattern_cfg=patterns.PinholeCameraPatternCfg( + focal_length=24.0, + horizontal_aperture=20.955, + height=480, + width=640, + ), + ) + + +def save_images_grid( + images: list[torch.Tensor], + cmap: str | None = None, + nrow: int = 1, + subtitles: list[str] | None = None, + title: str | None = None, + filename: str | None = None, +): + """Save images in a grid with optional subtitles and title. + + Args: + images: A list of images to be plotted. Shape of each image should be (H, W, C). + cmap: Colormap to be used for plotting. Defaults to None, in which case the default colormap is used. + nrows: Number of rows in the grid. Defaults to 1. + subtitles: A list of subtitles for each image. Defaults to None, in which case no subtitles are shown. + title: Title of the grid. Defaults to None, in which case no title is shown. + filename: Path to save the figure. Defaults to None, in which case the figure is not saved. + """ + # show images in a grid + n_images = len(images) + ncol = int(np.ceil(n_images / nrow)) + + fig, axes = plt.subplots(nrow, ncol, figsize=(ncol * 2, nrow * 2)) + if isinstance(axes, np.ndarray): + axes = axes.flatten() + else: + axes = np.array([axes]) + + # plot images + for idx, (img, ax) in enumerate(zip(images, axes)): + img = img.detach().cpu().numpy() + ax.imshow(img, cmap=cmap) + ax.axis("off") + if subtitles: + ax.set_title(subtitles[idx]) + # remove extra axes if any + for ax in axes[n_images:]: + fig.delaxes(ax) + # set title + if title: + plt.suptitle(title) + + # adjust layout to fit the title + plt.tight_layout() + # save the figure + if filename: + os.makedirs(os.path.dirname(filename), exist_ok=True) + plt.savefig(filename) + # close the figure + plt.close() + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Run the simulator.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + # Create output directory to save images + output_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output") + os.makedirs(output_dir, exist_ok=True) + + # Simulate physics + while simulation_app.is_running(): + # Reset + if count % 500 == 0: + # reset counter + count = 0 + # reset the scene entities + # root state + # we offset the root state by the origin since the states are written in simulation world frame + # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world + root_pose = scene["robot"].data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + scene["robot"].write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = scene["robot"].data.default_root_vel.torch.clone() + scene["robot"].write_root_velocity_to_sim_index(root_velocity=root_vel) + # set joint positions with some noise + joint_pos, joint_vel = ( + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), + ) + joint_pos += torch.rand_like(joint_pos) * 0.1 + scene["robot"].write_joint_position_to_sim_index(position=joint_pos) + scene["robot"].write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + scene.reset() + print("[INFO]: Resetting robot state...") + # Apply default actions to the robot + # -- generate actions/commands + targets = scene["robot"].data.default_joint_pos.torch + # -- apply action to the robot + scene["robot"].set_joint_position_target_index(target=targets) + # -- write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + scene.update(sim_dt) + + # print information from the sensors + print("-------------------------------") + print(scene["camera"]) + print("Received shape of rgb image: ", scene["camera"].data.output["rgb"].shape) + print("Received shape of depth image: ", scene["camera"].data.output["distance_to_image_plane"].shape) + print("-------------------------------") + print(scene["tiled_camera"]) + print("Received shape of rgb image: ", scene["tiled_camera"].data.output["rgb"].shape) + print("Received shape of depth image: ", scene["tiled_camera"].data.output["distance_to_image_plane"].shape) + print("-------------------------------") + print(scene["raycast_camera"]) + print("Received shape of depth: ", scene["raycast_camera"].data.output["distance_to_image_plane"].shape) + print("Received shape of normals: ", scene["raycast_camera"].data.output["normals"].shape) + + # save every 10th image (for visualization purposes only) + # note: saving images will slow down the simulation + if count % 10 == 0: + # compare generated RGB images across different cameras + rgb_images = [scene["camera"].data.output["rgb"][0, ..., :3], scene["tiled_camera"].data.output["rgb"][0]] + save_images_grid( + rgb_images, + subtitles=["Camera", "TiledCamera"], + title="RGB Image: Cam0", + filename=os.path.join(output_dir, "rgb", f"{count:04d}.jpg"), + ) + + # compare generated Depth images across different cameras + depth_images = [ + scene["camera"].data.output["distance_to_image_plane"][0], + scene["tiled_camera"].data.output["distance_to_image_plane"][0, ..., 0], + scene["raycast_camera"].data.output["distance_to_image_plane"][0], + ] + save_images_grid( + depth_images, + cmap="turbo", + subtitles=["Camera", "TiledCamera", "RaycasterCamera"], + title="Depth Image: Cam0", + filename=os.path.join(output_dir, "distance_to_camera", f"{count:04d}.jpg"), + ) + + # save all tiled RGB images + tiled_images = scene["tiled_camera"].data.output["rgb"] + save_images_grid( + tiled_images, + subtitles=[f"Cam{i}" for i in range(tiled_images.shape[0])], + title="Tiled RGB Image", + filename=os.path.join(output_dir, "tiled_rgb", f"{count:04d}.jpg"), + ) + + # save all camera RGB images + cam_images = scene["camera"].data.output["rgb"][..., :3] + save_images_grid( + cam_images, + subtitles=[f"Cam{i}" for i in range(cam_images.shape[0])], + title="Camera RGB Image", + filename=os.path.join(output_dir, "cam_rgb", f"{count:04d}.jpg"), + ) + + +def main(): + """Main function.""" + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device, use_fabric=not args_cli.disable_fabric) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[3.5, 3.5, 3.5], target=[0.0, 0.0, 0.0]) + # design scene + scene_cfg = SensorsSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0) + scene = InteractiveScene(scene_cfg) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/sensors/contact_sensor.py b/simulation/modules/IsaacLab/scripts/demos/sensors/contact_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..a8cc37aeff932e2b0e26bb8928405ab601159978 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/sensors/contact_sensor.py @@ -0,0 +1,180 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Example on using the contact sensor.") +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to spawn.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg, RigidObjectCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors import ContactSensorCfg +from isaaclab.utils.configclass import configclass + +## +# Pre-defined configs +## +from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip + + +@configclass +class ContactSensorSceneCfg(InteractiveSceneCfg): + """Design the scene with sensors on the robot.""" + + # ground plane + ground = AssetBaseCfg(prim_path="/World/defaultGroundPlane", spawn=sim_utils.GroundPlaneCfg()) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # robot + robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + # Rigid Object + cube = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.5, 0.5, 0.1), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=100.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + physics_material=sim_utils.RigidBodyMaterialCfg(static_friction=1.0), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0), metallic=0.2), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.5, 0.5, 0.05)), + ) + + contact_forces_LF = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/LF_FOOT", + update_period=0.0, + history_length=6, + debug_vis=True, + filter_prim_paths_expr=["{ENV_REGEX_NS}/Cube"], + ) + + contact_forces_RF = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/RF_FOOT", + update_period=0.0, + history_length=6, + debug_vis=True, + filter_prim_paths_expr=["{ENV_REGEX_NS}/Cube"], + ) + + contact_forces_H = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/.*H_FOOT", + update_period=0.0, + history_length=6, + debug_vis=True, + ) + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Run the simulator.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + # Simulate physics + while simulation_app.is_running(): + if count % 500 == 0: + # reset counter + count = 0 + # reset the scene entities + # root state + # we offset the root state by the origin since the states are written in simulation world frame + # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world + root_pose = scene["robot"].data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + scene["robot"].write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = scene["robot"].data.default_root_vel.torch.clone() + scene["robot"].write_root_velocity_to_sim_index(root_velocity=root_vel) + # set joint positions with some noise + joint_pos, joint_vel = ( + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), + ) + joint_pos += torch.rand_like(joint_pos) * 0.1 + scene["robot"].write_joint_position_to_sim_index(position=joint_pos) + scene["robot"].write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + scene.reset() + print("[INFO]: Resetting robot state...") + # Apply default actions to the robot + # -- generate actions/commands + targets = scene["robot"].data.default_joint_pos.torch + # -- apply action to the robot + scene["robot"].set_joint_position_target_index(target=targets) + # -- write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + scene.update(sim_dt) + + # print information from the sensors + print("-------------------------------") + print(scene["contact_forces_LF"]) + print("Received force matrix of: ", scene["contact_forces_LF"].data.force_matrix_w) + print("Received contact force of: ", scene["contact_forces_LF"].data.net_forces_w) + print("-------------------------------") + print(scene["contact_forces_RF"]) + print("Received force matrix of: ", scene["contact_forces_RF"].data.force_matrix_w) + print("Received contact force of: ", scene["contact_forces_RF"].data.net_forces_w) + print("-------------------------------") + print(scene["contact_forces_H"]) + print("Received force matrix of: ", scene["contact_forces_H"].data.force_matrix_w) + print("Received contact force of: ", scene["contact_forces_H"].data.net_forces_w) + + +def main(): + """Main function.""" + + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[3.5, 3.5, 3.5], target=[0.0, 0.0, 0.0]) + # design scene + scene_cfg = ContactSensorSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0) + scene = InteractiveScene(scene_cfg) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/sensors/frame_transformer_sensor.py b/simulation/modules/IsaacLab/scripts/demos/sensors/frame_transformer_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..99e5cab6636d80120c0f41ec548dbb9cdefdd0d1 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/sensors/frame_transformer_sensor.py @@ -0,0 +1,174 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Example on using the frame transformer sensor.") +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to spawn.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg, RigidObjectCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors import FrameTransformerCfg +from isaaclab.utils.configclass import configclass + +## +# Pre-defined configs +## +from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip + + +@configclass +class FrameTransformerSensorSceneCfg(InteractiveSceneCfg): + """Design the scene with sensors on the robot.""" + + # ground plane + ground = AssetBaseCfg(prim_path="/World/defaultGroundPlane", spawn=sim_utils.GroundPlaneCfg()) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # robot + robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + # Rigid Object + cube = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(1, 1, 1), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=100.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + physics_material=sim_utils.RigidBodyMaterialCfg(static_friction=1.0), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0), metallic=0.2), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(5, 0, 0.5)), + ) + + specific_transforms = FrameTransformerCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + target_frames=[ + FrameTransformerCfg.FrameCfg(prim_path="{ENV_REGEX_NS}/Robot/LF_FOOT"), + FrameTransformerCfg.FrameCfg(prim_path="{ENV_REGEX_NS}/Robot/RF_FOOT"), + ], + debug_vis=True, + ) + + cube_transform = FrameTransformerCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + target_frames=[FrameTransformerCfg.FrameCfg(prim_path="{ENV_REGEX_NS}/Cube")], + debug_vis=False, + ) + + robot_transforms = FrameTransformerCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + target_frames=[FrameTransformerCfg.FrameCfg(prim_path="{ENV_REGEX_NS}/Robot/.*")], + debug_vis=False, + ) + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Run the simulator.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + # Simulate physics + while simulation_app.is_running(): + if count % 500 == 0: + # reset counter + count = 0 + # reset the scene entities + # root state + # we offset the root state by the origin since the states are written in simulation world frame + # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world + root_pose = scene["robot"].data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + scene["robot"].write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = scene["robot"].data.default_root_vel.torch.clone() + scene["robot"].write_root_velocity_to_sim_index(root_velocity=root_vel) + # set joint positions with some noise + joint_pos, joint_vel = ( + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), + ) + joint_pos += torch.rand_like(joint_pos) * 0.1 + scene["robot"].write_joint_position_to_sim_index(position=joint_pos) + scene["robot"].write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + scene.reset() + print("[INFO]: Resetting robot state...") + # Apply default actions to the robot + # -- generate actions/commands + targets = scene["robot"].data.default_joint_pos.torch + # -- apply action to the robot + scene["robot"].set_joint_position_target_index(target=targets) + # -- write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + scene.update(sim_dt) + + # print information from the sensors + print("-------------------------------") + print(scene["specific_transforms"]) + print("relative transforms:", scene["specific_transforms"].data.target_pos_source) + print("relative orientations:", scene["specific_transforms"].data.target_quat_source) + print("-------------------------------") + print(scene["cube_transform"]) + print("relative transform:", scene["cube_transform"].data.target_pos_source) + print("-------------------------------") + print(scene["robot_transforms"]) + print("relative transforms:", scene["robot_transforms"].data.target_pos_source) + + +def main(): + """Main function.""" + + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[3.5, 3.5, 3.5], target=[0.0, 0.0, 0.0]) + # design scene + scene_cfg = FrameTransformerSensorSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0) + scene = InteractiveScene(scene_cfg) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/sensors/imu_sensor.py b/simulation/modules/IsaacLab/scripts/demos/sensors/imu_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..22eb1729e75be794087b69855c9099626d367654 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/sensors/imu_sensor.py @@ -0,0 +1,137 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Example on using the IMU sensor.") +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to spawn.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors import ImuCfg +from isaaclab.utils.configclass import configclass + +## +# Pre-defined configs +## +from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip + + +@configclass +class ImuSensorSceneCfg(InteractiveSceneCfg): + """Design the scene with IMU sensors on the robot.""" + + # ground plane + ground = AssetBaseCfg(prim_path="/World/defaultGroundPlane", spawn=sim_utils.GroundPlaneCfg()) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # robot + robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + imu_RF = ImuCfg(prim_path="{ENV_REGEX_NS}/Robot/LF_FOOT") + + imu_LF = ImuCfg(prim_path="{ENV_REGEX_NS}/Robot/RF_FOOT") + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Run the simulator.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + # Simulate physics + while simulation_app.is_running(): + if count % 500 == 0: + # reset counter + count = 0 + # reset the scene entities + root_pose = scene["robot"].data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + scene["robot"].write_root_link_pose_to_sim_index(root_pose=root_pose) + root_vel = scene["robot"].data.default_root_vel.torch.clone() + scene["robot"].write_root_com_velocity_to_sim_index(root_velocity=root_vel) + # set joint positions with some noise + joint_pos, joint_vel = ( + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), + ) + joint_pos += torch.rand_like(joint_pos) * 0.1 + scene["robot"].write_joint_position_to_sim_index(position=joint_pos) + scene["robot"].write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + scene.reset() + print("[INFO]: Resetting robot state...") + # Apply default actions to the robot + targets = scene["robot"].data.default_joint_pos.torch + scene["robot"].set_joint_position_target_index(target=targets) + scene.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + scene.update(sim_dt) + + # print information from the sensors + print("-------------------------------") + print(scene["imu_LF"]) + print("Received angular velocity: ", scene["imu_LF"].data.ang_vel_b) + print("Received linear acceleration: ", scene["imu_LF"].data.lin_acc_b) + print("-------------------------------") + print(scene["imu_RF"]) + print("Received angular velocity: ", scene["imu_RF"].data.ang_vel_b) + print("Received linear acceleration: ", scene["imu_RF"].data.lin_acc_b) + + +def main(): + """Main function.""" + + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[3.5, 3.5, 3.5], target=[0.0, 0.0, 0.0]) + # design scene + scene_cfg = ImuSensorSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0) + scene = InteractiveScene(scene_cfg) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/sensors/multi_mesh_raycaster.py b/simulation/modules/IsaacLab/scripts/demos/sensors/multi_mesh_raycaster.py new file mode 100644 index 0000000000000000000000000000000000000000..6ff142f680aff3dc705e8e9929a81fd61665ff82 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/sensors/multi_mesh_raycaster.py @@ -0,0 +1,304 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + + +"""Example on using the Multi-Mesh Raycaster sensor. + +.. code-block:: bash + + # with allegro hand + python scripts/demos/sensors/multi_mesh_raycaster.py --num_envs 16 --asset_type allegro_hand + + # with anymal-D bodies + python scripts/demos/sensors/multi_mesh_raycaster.py --num_envs 16 --asset_type anymal_d + + # with random multiple objects + python scripts/demos/sensors/multi_mesh_raycaster.py --num_envs 16 --asset_type objects + +""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Example on using the multi-mesh raycaster sensor.") +parser.add_argument("--num_envs", type=int, default=16, help="Number of environments to spawn.") +parser.add_argument( + "--asset_type", + type=str, + default="allegro_hand", + help="Asset type to use.", + choices=["allegro_hand", "anymal_d", "objects"], +) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import random + +import torch + +from pxr import Gf, Sdf + +import isaaclab.sim as sim_utils +from isaaclab.assets import Articulation, AssetBaseCfg, RigidObjectCfg +from isaaclab.markers.config import VisualizationMarkersCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors.ray_caster import MultiMeshRayCasterCfg, patterns +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR +from isaaclab.utils.configclass import configclass + +## +# Pre-defined configs +## +from isaaclab_assets.robots.allegro import ALLEGRO_HAND_CFG +from isaaclab_assets.robots.anymal import ANYMAL_D_CFG + +RAY_CASTER_MARKER_CFG = VisualizationMarkersCfg( + markers={ + "hit": sim_utils.SphereCfg( + radius=0.01, + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)), + ), + }, +) + + +if args_cli.asset_type == "allegro_hand": + asset_cfg = ALLEGRO_HAND_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + ray_caster_cfg = MultiMeshRayCasterCfg( + prim_path="{ENV_REGEX_NS}/Robot", + update_period=1 / 60, + offset=MultiMeshRayCasterCfg.OffsetCfg(pos=(0, -0.1, 0.3)), + mesh_prim_paths=[ + "/World/Ground", + MultiMeshRayCasterCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/thumb_link_.*/visuals_xform"), + MultiMeshRayCasterCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/index_link.*/visuals_xform"), + MultiMeshRayCasterCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/middle_link_.*/visuals_xform"), + MultiMeshRayCasterCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/ring_link_.*/visuals_xform"), + MultiMeshRayCasterCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/palm_link/visuals_xform"), + MultiMeshRayCasterCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/allegro_mount/visuals_xform"), + ], + ray_alignment="world", + pattern_cfg=patterns.GridPatternCfg(resolution=0.005, size=(0.4, 0.4), direction=(0, 0, -1)), + debug_vis=not args_cli.headless, + visualizer_cfg=RAY_CASTER_MARKER_CFG.replace(prim_path="/Visuals/RayCaster"), + ) + +elif args_cli.asset_type == "anymal_d": + asset_cfg = ANYMAL_D_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + ray_caster_cfg = MultiMeshRayCasterCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + update_period=1 / 60, + offset=MultiMeshRayCasterCfg.OffsetCfg(pos=(0, -0.1, 0.3)), + mesh_prim_paths=[ + "/World/Ground", + MultiMeshRayCasterCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/LF_.*/visuals"), + MultiMeshRayCasterCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/RF_.*/visuals"), + MultiMeshRayCasterCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/LH_.*/visuals"), + MultiMeshRayCasterCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/RH_.*/visuals"), + MultiMeshRayCasterCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/base/visuals"), + ], + ray_alignment="world", + pattern_cfg=patterns.GridPatternCfg(resolution=0.02, size=(2.5, 2.5), direction=(0, 0, -1)), + debug_vis=not args_cli.headless, + visualizer_cfg=RAY_CASTER_MARKER_CFG.replace(prim_path="/Visuals/RayCaster"), + ) + +elif args_cli.asset_type == "objects": + asset_cfg = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Object", + spawn=sim_utils.MultiAssetSpawnerCfg( + assets_cfg=[ + sim_utils.CuboidCfg( + size=(0.3, 0.3, 0.3), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0), metallic=0.2), + ), + sim_utils.SphereCfg( + radius=0.3, + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 1.0), metallic=0.2), + ), + sim_utils.CylinderCfg( + radius=0.2, + height=0.5, + axis="Y", + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0), metallic=0.2), + ), + sim_utils.CapsuleCfg( + radius=0.15, + height=0.5, + axis="Z", + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 1.0, 0.0), metallic=0.2), + ), + sim_utils.ConeCfg( + radius=0.2, + height=0.5, + axis="Z", + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 1.0), metallic=0.2), + ), + ], + random_choice=True, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + solver_position_iteration_count=4, solver_velocity_iteration_count=0 + ), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 2.0)), + ) + ray_caster_cfg = MultiMeshRayCasterCfg( + prim_path="{ENV_REGEX_NS}/Object", + update_period=1 / 60, + offset=MultiMeshRayCasterCfg.OffsetCfg(pos=(0, 0.0, 0.6)), + mesh_prim_paths=[ + "/World/Ground", + MultiMeshRayCasterCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Object"), + ], + ray_alignment="world", + pattern_cfg=patterns.GridPatternCfg(resolution=0.01, size=(0.6, 0.6), direction=(0, 0, -1)), + debug_vis=not args_cli.headless, + visualizer_cfg=RAY_CASTER_MARKER_CFG.replace(prim_path="/Visuals/RayCaster"), + ) +else: + raise ValueError(f"Unknown asset type: {args_cli.asset_type}") + + +@configclass +class RaycasterSensorSceneCfg(InteractiveSceneCfg): + """Design the scene with sensors on the asset.""" + + # ground plane + ground = AssetBaseCfg( + prim_path="/World/Ground", + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Environments/Terrains/rough_plane.usd", + scale=(1, 1, 1), + ), + ) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # asset + asset = asset_cfg + # ray caster + ray_caster = ray_caster_cfg + + +def randomize_shape_color(prim_path_expr: str): + """Randomize the color of the geometry.""" + + stage = sim_utils.get_current_stage() + # resolve prim paths for spawning and cloning + prim_paths = sim_utils.find_matching_prim_paths(prim_path_expr) + # manually clone prims if the source prim path is a regex expression + + with Sdf.ChangeBlock(): + for prim_path in prim_paths: + print("Applying prim scale to:", prim_path) + # spawn single instance + prim_spec = Sdf.CreatePrimInLayer(stage.GetRootLayer(), prim_path) + + # DO YOUR OWN OTHER KIND OF RANDOMIZATION HERE! + # Note: Just need to acquire the right attribute about the property you want to set + # Here is an example on setting color randomly + color_spec = prim_spec.GetAttributeAtPath(prim_path + "/geometry/material/Shader.inputs:diffuseColor") + color_spec.default = Gf.Vec3f(random.random(), random.random(), random.random()) + + # randomize scale + scale_spec = prim_spec.GetAttributeAtPath(prim_path + ".xformOp:scale") + scale_spec.default = Gf.Vec3f(random.uniform(0.5, 1.5), random.uniform(0.5, 1.5), random.uniform(0.5, 1.5)) + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Run the simulator.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + # Simulate physics + while simulation_app.is_running(): + if count % 500 == 0: + # reset counter + count = 0 + # reset the scene entities + # root state + root_pose = scene["asset"].data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + scene["asset"].write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = scene["asset"].data.default_root_vel.torch.clone() + scene["asset"].write_root_velocity_to_sim_index(root_velocity=root_vel) + + if isinstance(scene["asset"], Articulation): + # set joint positions with some noise + joint_pos, joint_vel = ( + scene["asset"].data.default_joint_pos.torch.clone(), + scene["asset"].data.default_joint_vel.torch.clone(), + ) + joint_pos += torch.rand_like(joint_pos) * 0.1 + scene["asset"].write_joint_position_to_sim_index(position=joint_pos) + scene["asset"].write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + scene.reset() + print("[INFO]: Resetting Asset state...") + + if isinstance(scene["asset"], Articulation): + # -- generate actions/commands + default_joint_pos = scene["asset"].data.default_joint_pos.torch + targets = default_joint_pos + 5 * (torch.rand_like(default_joint_pos) - 0.5) + # -- apply action to the asset + scene["asset"].set_joint_position_target_index(target=targets) + # -- write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + scene.update(sim_dt) + + +def main(): + """Main function.""" + + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[3.5, 3.5, 3.5], target=[0.0, 0.0, 0.0]) + # design scene + scene_cfg = RaycasterSensorSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0, replicate_physics=True) + scene = InteractiveScene(scene_cfg) + + if args_cli.asset_type == "objects": + randomize_shape_color(scene_cfg.asset.prim_path.format(ENV_REGEX_NS="/World/envs/env_.*")) + + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/sensors/multi_mesh_raycaster_camera.py b/simulation/modules/IsaacLab/scripts/demos/sensors/multi_mesh_raycaster_camera.py new file mode 100644 index 0000000000000000000000000000000000000000..4bbc0769e6ba69ac199e1c37ab7ea8337d5f26bd --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/sensors/multi_mesh_raycaster_camera.py @@ -0,0 +1,330 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + + +"""Example on using the Multi-Mesh Raycaster Camera sensor. + +.. code-block:: bash + + # with allegro hand + python scripts/demos/sensors/multi_mesh_raycaster.py --num_envs 16 --asset_type allegro_hand + + # with anymal-D bodies + python scripts/demos/sensors/multi_mesh_raycaster.py --num_envs 16 --asset_type anymal_d + + # with random multiple objects + python scripts/demos/sensors/multi_mesh_raycaster.py --num_envs 16 --asset_type objects + +""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Example on using the multi-mesh raycaster sensor.") +parser.add_argument("--num_envs", type=int, default=16, help="Number of environments to spawn.") +parser.add_argument( + "--asset_type", + type=str, + default="allegro_hand", + help="Asset type to use.", + choices=["allegro_hand", "anymal_d", "objects"], +) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import random + +import torch + +from pxr import Gf, Sdf + +import isaaclab.sim as sim_utils +from isaaclab.assets import Articulation, AssetBaseCfg, RigidObjectCfg +from isaaclab.markers.config import VisualizationMarkersCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors.ray_caster import MultiMeshRayCasterCameraCfg, patterns +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR +from isaaclab.utils.configclass import configclass + +## +# Pre-defined configs +## +from isaaclab_assets.robots.allegro import ALLEGRO_HAND_CFG +from isaaclab_assets.robots.anymal import ANYMAL_D_CFG + +RAY_CASTER_MARKER_CFG = VisualizationMarkersCfg( + markers={ + "hit": sim_utils.SphereCfg( + radius=0.01, + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)), + ), + }, +) + +if args_cli.asset_type == "allegro_hand": + asset_cfg = ALLEGRO_HAND_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + ray_caster_cfg = MultiMeshRayCasterCameraCfg( + prim_path="{ENV_REGEX_NS}/Robot", + update_period=1 / 60, + offset=MultiMeshRayCasterCameraCfg.OffsetCfg( + pos=(-0.70, -0.7, -0.25), rot=(0.268976, 0.268976, 0.653951, 0.653951) + ), + mesh_prim_paths=[ + "/World/Ground", + MultiMeshRayCasterCameraCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/thumb_link_.*/visuals_xform"), + MultiMeshRayCasterCameraCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/index_link.*/visuals_xform"), + MultiMeshRayCasterCameraCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/middle_link_.*/visuals_xform"), + MultiMeshRayCasterCameraCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/ring_link_.*/visuals_xform"), + MultiMeshRayCasterCameraCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/palm_link/visuals_xform"), + MultiMeshRayCasterCameraCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/allegro_mount/visuals_xform"), + ], + pattern_cfg=patterns.PinholeCameraPatternCfg( + focal_length=24.0, + horizontal_aperture=20.955, + height=120, + width=240, + ), + debug_vis=not args_cli.headless, + visualizer_cfg=RAY_CASTER_MARKER_CFG.replace(prim_path="/Visuals/RayCaster"), + ) + +elif args_cli.asset_type == "anymal_d": + asset_cfg = ANYMAL_D_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + ray_caster_cfg = MultiMeshRayCasterCameraCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + update_period=1 / 60, + offset=MultiMeshRayCasterCameraCfg.OffsetCfg(pos=(0, -0.1, 1.5), rot=(0.0, 1.0, 0.0, 0.0)), + mesh_prim_paths=[ + "/World/Ground", + MultiMeshRayCasterCameraCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/LF_.*/visuals"), + MultiMeshRayCasterCameraCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/RF_.*/visuals"), + MultiMeshRayCasterCameraCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/LH_.*/visuals"), + MultiMeshRayCasterCameraCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/RH_.*/visuals"), + MultiMeshRayCasterCameraCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Robot/base/visuals"), + ], + pattern_cfg=patterns.PinholeCameraPatternCfg( + focal_length=24.0, + horizontal_aperture=20.955, + height=120, + width=240, + ), + debug_vis=not args_cli.headless, + visualizer_cfg=RAY_CASTER_MARKER_CFG.replace(prim_path="/Visuals/RayCaster"), + ) + +elif args_cli.asset_type == "objects": + asset_cfg = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Object", + spawn=sim_utils.MultiAssetSpawnerCfg( + assets_cfg=[ + sim_utils.CuboidCfg( + size=(0.3, 0.3, 0.3), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0), metallic=0.2), + ), + sim_utils.SphereCfg( + radius=0.3, + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 1.0), metallic=0.2), + ), + sim_utils.CylinderCfg( + radius=0.2, + height=0.5, + axis="Y", + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0), metallic=0.2), + ), + sim_utils.CapsuleCfg( + radius=0.15, + height=0.5, + axis="Z", + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 1.0, 0.0), metallic=0.2), + ), + sim_utils.ConeCfg( + radius=0.2, + height=0.5, + axis="Z", + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 1.0), metallic=0.2), + ), + ], + random_choice=True, + rigid_props=sim_utils.RigidBodyPropertiesCfg( + solver_position_iteration_count=4, solver_velocity_iteration_count=0 + ), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 2.0)), + ) + ray_caster_cfg = MultiMeshRayCasterCameraCfg( + prim_path="{ENV_REGEX_NS}/Object", + update_period=1 / 60, + offset=MultiMeshRayCasterCameraCfg.OffsetCfg(pos=(0, 0.0, 1.5), rot=(0.0, 1.0, 0.0, 0.0)), + mesh_prim_paths=[ + "/World/Ground", + MultiMeshRayCasterCameraCfg.RaycastTargetCfg(prim_expr="{ENV_REGEX_NS}/Object"), + ], + pattern_cfg=patterns.PinholeCameraPatternCfg( + focal_length=24.0, + horizontal_aperture=20.955, + height=120, + width=240, + ), + debug_vis=not args_cli.headless, + visualizer_cfg=RAY_CASTER_MARKER_CFG.replace(prim_path="/Visuals/RayCaster"), + ) +else: + raise ValueError(f"Unknown asset type: {args_cli.asset_type}") + + +@configclass +class RaycasterSensorSceneCfg(InteractiveSceneCfg): + """Design the scene with sensors on the asset.""" + + # ground plane + ground = AssetBaseCfg( + prim_path="/World/Ground", + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Environments/Terrains/rough_plane.usd", + scale=(1, 1, 1), + ), + ) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # asset + asset = asset_cfg + # ray caster + ray_caster = ray_caster_cfg + + +def randomize_shape_color(prim_path_expr: str): + """Randomize the color of the geometry.""" + + stage = sim_utils.get_current_stage() + # resolve prim paths for spawning and cloning + prim_paths = sim_utils.find_matching_prim_paths(prim_path_expr) + # manually clone prims if the source prim path is a regex expression + + with Sdf.ChangeBlock(): + for prim_path in prim_paths: + print("Applying prim scale to:", prim_path) + # spawn single instance + prim_spec = Sdf.CreatePrimInLayer(stage.GetRootLayer(), prim_path) + + # DO YOUR OWN OTHER KIND OF RANDOMIZATION HERE! + # Note: Just need to acquire the right attribute about the property you want to set + # Here is an example on setting color randomly + color_spec = prim_spec.GetAttributeAtPath(prim_path + "/geometry/material/Shader.inputs:diffuseColor") + color_spec.default = Gf.Vec3f(random.random(), random.random(), random.random()) + + # randomize scale + scale_spec = prim_spec.GetAttributeAtPath(prim_path + ".xformOp:scale") + scale_spec.default = Gf.Vec3f(random.uniform(0.5, 1.5), random.uniform(0.5, 1.5), random.uniform(0.5, 1.5)) + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Run the simulator.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + triggered = True + countdown = 42 + + # Simulate physics + while simulation_app.is_running(): + if count % 500 == 0: + # reset counter + count = 0 + # reset the scene entities + # root state + root_pose = scene["asset"].data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + scene["asset"].write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = scene["asset"].data.default_root_vel.torch.clone() + scene["asset"].write_root_velocity_to_sim_index(root_velocity=root_vel) + + if isinstance(scene["asset"], Articulation): + # set joint positions with some noise + joint_pos, joint_vel = ( + scene["asset"].data.default_joint_pos.torch.clone(), + scene["asset"].data.default_joint_vel.torch.clone(), + ) + joint_pos += torch.rand_like(joint_pos) * 0.1 + scene["asset"].write_joint_position_to_sim_index(position=joint_pos) + scene["asset"].write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + scene.reset() + print("[INFO]: Resetting Asset state...") + + if isinstance(scene["asset"], Articulation): + # -- generate actions/commands + default_joint_pos = scene["asset"].data.default_joint_pos.torch + targets = default_joint_pos + 5 * (torch.rand_like(default_joint_pos) - 0.5) + # -- apply action to the asset + scene["asset"].set_joint_position_target_index(target=targets) + # -- write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + scene.update(sim_dt) + + if not triggered: + if countdown > 0: + countdown -= 1 + continue + + data = scene["ray_caster"].data.ray_hits_w.torch.cpu().numpy() # noqa: F841 + triggered = True + else: + continue + + +def main(): + """Main function.""" + + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[3.5, 3.5, 3.5], target=[0.0, 0.0, 0.0]) + # design scene + scene_cfg = RaycasterSensorSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0, replicate_physics=True) + scene = InteractiveScene(scene_cfg) + + if args_cli.asset_type == "objects": + randomize_shape_color(scene_cfg.asset.prim_path.format(ENV_REGEX_NS="/World/envs/env_.*")) + + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/sensors/ppisp_camera.py b/simulation/modules/IsaacLab/scripts/demos/sensors/ppisp_camera.py new file mode 100644 index 0000000000000000000000000000000000000000..04a21dc6c1fefbe6f9f72e1cf455cb3739852d08 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/sensors/ppisp_camera.py @@ -0,0 +1,601 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates USD-authored PPISP on a Gaussian scene through the Isaac Lab camera sensor with +the Newton Warp or Isaac RTX renderer. + +.. code-block:: bash + + # Run a finite smoke with the default Newton Warp renderer and save comparison images. + ./isaaclab.sh -p scripts/demos/sensors/ppisp_camera.py \ + --input_scene /path/to/scene.usd --renderer newton --visualizer none --max_steps 60 + + # Run the same saved-image workflow with Isaac RTX. + ./isaaclab.sh -p scripts/demos/sensors/ppisp_camera.py \ + --input_scene /path/to/scene.usd --renderer isaac_rtx --visualizer none --max_steps 60 + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +import os +from typing import Any + +from isaaclab.app import AppLauncher +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR + +# add argparse arguments +DEFAULT_INPUT_SCENE = f"{ISAAC_NUCLEUS_DIR}/Samples/Scene_ParticleField/valiant_auto.usdz" + +parser = argparse.ArgumentParser(description="Example of a USD-authored PPISP effect on camera RGB output.") +parser.add_argument( + "--input_scene", + type=str, + default=DEFAULT_INPUT_SCENE, + help="USD or USDZ scene containing the Gaussian PPISP setup.", +) +parser.add_argument( + "--camera_prim_path", + type=str, + default=None, + help="Optional camera prim path override. Omit to auto-select the first PPISP-bound camera.", +) +parser.add_argument( + "--camera_time_code", + type=float, + default=0.0, + help="USD time code used to bake the selected camera pose into duplicated env cameras for Newton.", +) +parser.add_argument( + "--num_envs", + type=int, + default=1, + help="Number of duplicated input-scene envs to render in the tiled camera batch.", +) +parser.add_argument("--env_spacing", type=float, default=20.0, help="Spacing between duplicated input-scene envs.") +parser.add_argument("--image_width", type=int, default=320, help="Output image width.") +parser.add_argument( + "--image_height", + type=int, + default=None, + help="Output image height. Defaults to preserving the selected USD RenderProduct aspect ratio.", +) +parser.add_argument("--disable_fabric", action="store_true", help="Disable Fabric API and use USD instead.") +parser.add_argument( + "--renderer", + type=str, + choices=["newton", "isaac_rtx"], + default="newton", + help="Camera renderer backend to use. Newton Warp is the default for this PPISP smoke.", +) +parser.add_argument( + "--warmup_steps", + type=int, + default=None, + help="Simulation/render steps to run before saving images. Defaults to 32 for Isaac RTX and 0 for Newton.", +) +parser.add_argument("--max_steps", type=int, default=120, help="Maximum simulation steps before exiting.") +parser.add_argument("--save_interval", type=int, default=20, help="Interval, in steps, for saving comparison images.") +parser.add_argument( + "--ppisp_responsivity", + type=float, + default=None, + help="Override the USD-authored PPISP responsivity. If omitted, the scene-authored value is used.", +) +parser.add_argument( + "--output_dir", + type=str, + default=None, + help="Directory to write comparison images. Defaults to scripts/demos/sensors/output/ppisp_camera.", +) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# enable cameras by default; the QA workflow validates saved camera outputs and does not require a visualizer. +parser.set_defaults(enable_cameras=True) +# parse the arguments +args_cli = parser.parse_args() +if "://" not in args_cli.input_scene: + args_cli.input_scene = os.path.abspath(os.path.expanduser(args_cli.input_scene)) + if not os.path.exists(args_cli.input_scene): + parser.error(f"--input_scene does not exist: {args_cli.input_scene}") +if args_cli.num_envs < 1: + parser.error("--num_envs must be at least 1.") +if args_cli.image_width < 1: + parser.error("--image_width must be at least 1.") +if args_cli.image_height is not None and args_cli.image_height < 1: + parser.error("--image_height must be at least 1.") +if args_cli.warmup_steps is None: + args_cli.warmup_steps = 32 if args_cli.renderer == "isaac_rtx" else 0 +if args_cli.warmup_steps < 0: + parser.error("--warmup_steps must be non-negative.") +if args_cli.max_steps < 1: + parser.error("--max_steps must be at least 1.") +if args_cli.save_interval < 1: + parser.error("--save_interval must be at least 1.") + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import matplotlib.pyplot as plt +import numpy as np +import torch +from isaaclab_ppisp.cfg import PpispCfg, ppisp_cfg_from_usd_shader + +from pxr import Usd, UsdGeom, UsdShade + +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg, RigidObjectCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors import Camera, CameraCfg +from isaaclab.utils.configclass import configclass + + +@configclass +class PpispCameraSceneCfg(InteractiveSceneCfg): + """Minimal scene cfg that references the input USD under each env.""" + + env_spacing: float = 20.0 + + input_scene = AssetBaseCfg( + prim_path="{ENV_REGEX_NS}/Scene", + spawn=sim_utils.UsdFileCfg(usd_path=""), + ) + + anchor = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Anchor", + spawn=sim_utils.CuboidCfg( + size=(0.01, 0.01, 0.01), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=0.001), + collision_props=sim_utils.CollisionPropertiesCfg(), + physics_material=sim_utils.RigidBodyMaterialCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 0.0)), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, -100.0)), + ) + + +def make_renderer_cfg() -> Any: + """Create the selected camera renderer cfg.""" + if args_cli.renderer == "newton": + from isaaclab_newton.renderers import NewtonWarpRendererCfg + + return NewtonWarpRendererCfg() + else: + from isaaclab_physx.renderers import IsaacRtxRendererCfg + + return IsaacRtxRendererCfg() + + +def make_sim_cfg() -> sim_utils.SimulationCfg: + """Create the simulation cfg matching the selected renderer.""" + physics_cfg = None + if args_cli.renderer == "newton": + from isaaclab_newton.physics.mjwarp_manager_cfg import MJWarpSolverCfg + from isaaclab_newton.physics.newton_manager_cfg import NewtonCfg + + physics_cfg = NewtonCfg(solver_cfg=MJWarpSolverCfg(), num_substeps=1) + + return sim_utils.SimulationCfg( + dt=0.005, + device=args_cli.device, + physics=physics_cfg, + use_fabric=not args_cli.disable_fabric, + ) + + +def find_ppisp_camera_bindings(stage: Usd.Stage) -> list[tuple[str, Usd.Prim, Usd.Prim]]: + """Return camera, RenderProduct, and PPISP shader bindings from a source stage.""" + bindings = [] + for prim in stage.Traverse(): + if prim.GetTypeName() != "RenderProduct": + continue + shader_prim = stage.GetPrimAtPath(prim.GetPath().AppendChild("PPISP")) + if not shader_prim or not shader_prim.IsValid(): + continue + camera_rel = prim.GetRelationship("camera") + if not camera_rel: + continue + for target in camera_rel.GetTargets(): + camera_prim = stage.GetPrimAtPath(target) + if camera_prim and camera_prim.IsValid(): + bindings.append((str(target), prim, shader_prim)) + return bindings + + +def order_ppisp_bindings_by_camera( + stage: Usd.Stage, ppisp_bindings: list[tuple[str, Usd.Prim, Usd.Prim]] +) -> list[tuple[str, Usd.Prim, Usd.Prim]]: + """Return PPISP bindings ordered by source Camera prim traversal.""" + binding_by_camera_path = {} + for binding in ppisp_bindings: + binding_by_camera_path.setdefault(binding[0], binding) + + ordered_bindings = [] + seen_paths = set() + for prim in stage.Traverse(): + if prim.GetTypeName() != "Camera": + continue + camera_path = str(prim.GetPath()) + binding = binding_by_camera_path.get(camera_path) + if binding is not None: + ordered_bindings.append(binding) + seen_paths.add(camera_path) + + for binding in ppisp_bindings: + if binding[0] not in seen_paths: + ordered_bindings.append(binding) + seen_paths.add(binding[0]) + return ordered_bindings + + +def format_available_ppisp_cameras(ppisp_bindings: list[tuple[str, Usd.Prim, Usd.Prim]]) -> str: + """Format PPISP-bound camera paths for CLI error messages.""" + return "\n ".join(dict.fromkeys(binding[0] for binding in ppisp_bindings)) + + +def resolve_source_camera_binding(source_stage: Usd.Stage) -> tuple[str, Usd.Prim, Usd.Prim]: + """Resolve the source camera and PPISP shader binding from CLI or source stage metadata.""" + ppisp_bindings = order_ppisp_bindings_by_camera(source_stage, find_ppisp_camera_bindings(source_stage)) + if not ppisp_bindings: + raise RuntimeError("No PPISP RenderProduct bindings found in input scene.") + + if args_cli.camera_prim_path is not None: + camera_prim_path = args_cli.camera_prim_path + if not camera_prim_path.startswith("/"): + camera_prim_path = f"/{camera_prim_path}" + else: + camera_prim_path = ppisp_bindings[0][0] + print(f"[INFO] Auto-selected camera prim: {camera_prim_path}", flush=True) + + camera_prim = source_stage.GetPrimAtPath(camera_prim_path) + if not camera_prim or not camera_prim.IsValid(): + available = format_available_ppisp_cameras(ppisp_bindings) + raise RuntimeError( + f"Camera prim not found: {camera_prim_path}\n" + "Omit --camera_prim_path to auto-select a PPISP-bound camera, or use one of:\n" + f" {available}" + ) + if camera_prim.GetTypeName() != "Camera": + available = format_available_ppisp_cameras(ppisp_bindings) + raise RuntimeError( + f"Prim is not a Camera: {camera_prim_path} ({camera_prim.GetTypeName()})\n" + "Omit --camera_prim_path to auto-select a PPISP-bound camera, or use one of:\n" + f" {available}" + ) + + for binding in ppisp_bindings: + if binding[0] == camera_prim_path: + return binding + + available = format_available_ppisp_cameras(ppisp_bindings) + raise RuntimeError( + f"Selected camera has no PPISP RenderProduct binding: {camera_prim_path}\n" + "Omit --camera_prim_path to auto-select a PPISP-bound camera, or use one of:\n" + f" {available}" + ) + + +def source_camera_path_to_default_rel_path(source_stage: Usd.Stage, source_camera_prim_path: str) -> str: + """Return the source camera path relative to the source defaultPrim.""" + default_prim = source_stage.GetDefaultPrim() + if not default_prim: + raise RuntimeError("Input scene must have a defaultPrim so it can be referenced under each env.") + + default_prim_path = default_prim.GetPath().pathString + default_prefix = f"{default_prim_path}/" + if not source_camera_prim_path.startswith(default_prefix): + raise RuntimeError( + f"Camera path {source_camera_prim_path} is not under source defaultPrim {default_prim_path}." + ) + return source_camera_prim_path[len(default_prefix) :] + + +def source_camera_path_to_env_regex(source_stage: Usd.Stage, source_camera_prim_path: str) -> str: + """Map a source camera path to the duplicated-env camera regex.""" + camera_rel_path = source_camera_path_to_default_rel_path(source_stage, source_camera_prim_path) + return f"/World/envs/env_.*/Scene/{camera_rel_path}" + + +def bake_source_camera_pose_to_envs(source_stage: Usd.Stage, source_camera_prim_path: str) -> None: + """Bake the selected USD camera pose at ``camera_time_code`` into duplicated env camera prims.""" + default_prim = source_stage.GetDefaultPrim() + if not default_prim: + raise RuntimeError("Input scene must have a defaultPrim so it can be referenced under each env.") + + source_camera_prim = source_stage.GetPrimAtPath(source_camera_prim_path) + if not source_camera_prim or not source_camera_prim.IsValid(): + raise RuntimeError(f"Camera prim not found: {source_camera_prim_path}") + + time_code = Usd.TimeCode(args_cli.camera_time_code) + source_cache = UsdGeom.XformCache(time_code) + source_default_world = source_cache.GetLocalToWorldTransform(default_prim) + source_camera_world = source_cache.GetLocalToWorldTransform(source_camera_prim) + source_camera_in_default = source_camera_world * source_default_world.GetInverse() + + stage = sim_utils.get_current_stage() + target_cache = UsdGeom.XformCache(Usd.TimeCode.Default()) + camera_rel_path = source_camera_path_to_default_rel_path(source_stage, source_camera_prim_path) + authored_count = 0 + for env_id in range(args_cli.num_envs): + scene_path = f"/World/envs/env_{env_id}/Scene" + target_camera_path = f"{scene_path}/{camera_rel_path}" + scene_prim = stage.GetPrimAtPath(scene_path) + target_camera_prim = stage.GetPrimAtPath(target_camera_path) + if not scene_prim or not scene_prim.IsValid(): + raise RuntimeError(f"Duplicated scene prim not found: {scene_path}") + if not target_camera_prim or not target_camera_prim.IsValid(): + raise RuntimeError(f"Duplicated camera prim not found: {target_camera_path}") + + target_scene_world = target_cache.GetLocalToWorldTransform(scene_prim) + target_parent_world = target_cache.GetLocalToWorldTransform(target_camera_prim.GetParent()) + target_camera_world = source_camera_in_default * target_scene_world + target_camera_local = target_camera_world * target_parent_world.GetInverse() + target_camera_local.Orthonormalize() + + xformable = UsdGeom.Xformable(target_camera_prim) + xformable.ClearXformOpOrder() + xform_op = xformable.AddTransformOp(UsdGeom.XformOp.PrecisionDouble, "ppispCameraPose") + xform_op.Set(target_camera_local, Usd.TimeCode.Default()) + xformable.SetXformOpOrder([xform_op]) + authored_count += 1 + + print( + f"[INFO] Baked camera pose at USD time {args_cli.camera_time_code:g} into {authored_count} env camera(s).", + flush=True, + ) + + +def get_render_product_resolution(render_product_prim: Usd.Prim) -> tuple[int, int] | None: + """Return ``(width, height)`` from a RenderProduct ``resolution`` attribute.""" + resolution_attr = render_product_prim.GetAttribute("resolution") + if not resolution_attr: + return None + resolution = resolution_attr.Get() + if resolution is None or len(resolution) != 2: + return None + return int(resolution[0]), int(resolution[1]) + + +def resolve_image_shape(render_product_prim: Usd.Prim) -> tuple[int, int]: + """Resolve demo output ``(width, height)`` preserving source aspect when height is omitted.""" + width = args_cli.image_width + height = args_cli.image_height + if height is not None: + return width, height + + source_resolution = get_render_product_resolution(render_product_prim) + if source_resolution is None: + return width, width + + source_width, source_height = source_resolution + height = max(1, round(width * source_height / source_width)) + return width, height + + +def make_ppisp_cfg(shader_prim: Usd.Prim, num_ppisp_bindings: int) -> PpispCfg: + """Parse the selected source PPISP shader into an explicit cfg for duplicated envs.""" + ppisp_cfg = ppisp_cfg_from_usd_shader(UsdShade.Shader(shader_prim)) + # The duplicated stage does not carry the source /Render scope; keep the + # parsed inputs as explicit values instead of resolving this source path later. + ppisp_cfg.shader_prim_path = None + if args_cli.ppisp_responsivity is None: + print(f"[INFO] Using USD-authored PPISP values from {num_ppisp_bindings} PPISP shader(s).", flush=True) + else: + ppisp_cfg.inputs["responsivity"] = float(args_cli.ppisp_responsivity) + print( + f"[INFO] Applied PPISP responsivity={args_cli.ppisp_responsivity:g} to duplicated env PPISP cfg.", + flush=True, + ) + return ppisp_cfg + + +def create_duplicated_env_scene() -> InteractiveScene: + """Create a production-style duplicated-env scene for tiled camera rendering.""" + scene_cfg = PpispCameraSceneCfg(num_envs=args_cli.num_envs, env_spacing=args_cli.env_spacing) + scene_cfg.input_scene.spawn = sim_utils.UsdFileCfg(usd_path=args_cli.input_scene) + scene = InteractiveScene(scene_cfg) + print(f"[INFO] Referenced input scene into {args_cli.num_envs} env(s).", flush=True) + return scene + + +def make_camera(camera_prim_path: str, *, ppisp_cfg: PpispCfg | None, width: int, height: int) -> Camera: + """Create a baseline or PPISP camera sensor for the duplicated-env camera batch.""" + return Camera( + CameraCfg( + prim_path=camera_prim_path, + update_period=0.0, + height=height, + width=width, + data_types=["rgb"], + spawn=None, + isp_cfg=ppisp_cfg, + renderer_cfg=make_renderer_cfg(), + ) + ) + + +def save_images_grid( + images: list[torch.Tensor], + nrow: int = 1, + subtitles: list[str] | None = None, + title: str | None = None, + filename: str | None = None, +) -> None: + """Save images in a grid with optional subtitles and title.""" + n_images = len(images) + ncol = int(np.ceil(n_images / nrow)) + + fig, axes = plt.subplots(nrow, ncol, figsize=(ncol * 3, nrow * 3)) + if isinstance(axes, np.ndarray): + axes = axes.flatten() + else: + axes = np.array([axes]) + + for idx, (img, ax) in enumerate(zip(images, axes)): + ax.imshow(img.detach().cpu().clamp(0.0, 1.0).numpy()) + ax.axis("off") + if subtitles: + ax.set_title(subtitles[idx]) + for ax in axes[n_images:]: + fig.delaxes(ax) + if title: + plt.suptitle(title) + plt.tight_layout() + if filename: + os.makedirs(os.path.dirname(filename), exist_ok=True) + plt.savefig(filename) + plt.close() + + +def make_tiled_image(images: torch.Tensor) -> torch.Tensor: + """Stack a camera batch vertically into one image.""" + return torch.cat([image for image in images], dim=0) + + +def save_tensor_image(image: torch.Tensor, filename: str) -> None: + """Save a tensor image in [0, 1] without axes, titles, or layout scaling.""" + os.makedirs(os.path.dirname(filename), exist_ok=True) + plt.imsave(filename, image.detach().cpu().clamp(0.0, 1.0).numpy()) + + +def corner_center_ratio(rgb: torch.Tensor) -> float: + """Return the average corner brightness divided by center brightness for one RGB image.""" + h, w = rgb.shape[:2] + patch = max(4, min(h, w) // 8) + cy, cx = h // 2 - patch // 2, w // 2 - patch // 2 + center = rgb[cy : cy + patch, cx : cx + patch, :3].float().mean() + corners = torch.stack( + [ + rgb[:patch, :patch, :3].float().mean(), + rgb[:patch, -patch:, :3].float().mean(), + rgb[-patch:, :patch, :3].float().mean(), + rgb[-patch:, -patch:, :3].float().mean(), + ] + ).mean() + return (corners / center.clamp_min(1.0)).item() + + +def run_simulator(sim: sim_utils.SimulationContext, baseline_camera: Camera, ppisp_camera: Camera) -> None: + """Run the simulator and periodically save baseline-vs-PPISP images.""" + sim_dt = sim.get_physics_dt() + output_dir = args_cli.output_dir + if output_dir is None: + output_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output", "ppisp_camera") + os.makedirs(output_dir, exist_ok=True) + + if args_cli.warmup_steps > 0: + print(f"[INFO] Running {args_cli.warmup_steps} warmup step(s) before saving images.", flush=True) + for _ in range(args_cli.warmup_steps): + sim.step() + baseline_camera.update(sim_dt) + ppisp_camera.update(sim_dt) + + count = 0 + reported_shape = False + while simulation_app.is_running(): + sim.step() + baseline_camera.update(sim_dt) + ppisp_camera.update(sim_dt) + count += 1 + + if count % args_cli.save_interval == 0: + baseline = baseline_camera.data.output["rgb"][..., :3] + ppisp = ppisp_camera.data.output["rgb"][..., :3] + diff = (ppisp.float() - baseline.float()).abs() / 255.0 + if not reported_shape: + print(f"[INFO] camera batch rgb shape={tuple(ppisp.shape)}", flush=True) + reported_shape = True + mean_abs_delta = diff.mean().item() * 255.0 + ratios = [corner_center_ratio(ppisp[i]) for i in range(ppisp.shape[0])] + ratio = sum(ratios) / len(ratios) + per_env_delta = diff.mean(dim=(1, 2, 3)) * 255.0 + per_env_ppisp_mean = ppisp.float().mean(dim=(1, 2, 3)) + print( + f"[INFO] step={count} mean_abs_delta={mean_abs_delta:.2f} mean_ppisp_corner_center_ratio={ratio:.3f}", + flush=True, + ) + print( + "[INFO] per-env mean_abs_delta=" + + ", ".join(f"{value:.2f}" for value in per_env_delta.detach().cpu().tolist()), + flush=True, + ) + print( + "[INFO] per-env ppisp_mean=" + + ", ".join(f"{value:.2f}" for value in per_env_ppisp_mean.detach().cpu().tolist()), + flush=True, + ) + images = [] + subtitles = [] + for env_id in range(ppisp.shape[0]): + images.extend( + [ + baseline[env_id].float() / 255.0, + ppisp[env_id].float() / 255.0, + diff[env_id], + ] + ) + subtitles.extend([f"env {env_id} baseline", f"env {env_id} PPISP", f"env {env_id} diff"]) + save_images_grid( + images, + nrow=ppisp.shape[0], + subtitles=subtitles, + title="USD-authored PPISP on duplicated Gaussian scene envs", + filename=os.path.join(output_dir, f"ppisp_camera_{count:04d}.png"), + ) + save_tensor_image( + make_tiled_image(baseline.float() / 255.0), + os.path.join(output_dir, f"ppisp_camera_{count:04d}_baseline_tiled.png"), + ) + save_tensor_image( + make_tiled_image(ppisp.float() / 255.0), + os.path.join(output_dir, f"ppisp_camera_{count:04d}_ppisp_tiled.png"), + ) + save_tensor_image( + make_tiled_image(diff), + os.path.join(output_dir, f"ppisp_camera_{count:04d}_diff_tiled.png"), + ) + + if args_cli.max_steps is not None and count >= args_cli.max_steps: + break + + +def main() -> None: + """Main function.""" + source_stage = Usd.Stage.Open(args_cli.input_scene) + if source_stage is None: + raise RuntimeError(f"Failed to open input scene: {args_cli.input_scene}") + source_camera_prim_path, render_product_prim, shader_prim = resolve_source_camera_binding(source_stage) + ppisp_cfg = make_ppisp_cfg(shader_prim, len(find_ppisp_camera_bindings(source_stage))) + camera_prim_path = source_camera_path_to_env_regex(source_stage, source_camera_prim_path) + width, height = resolve_image_shape(render_product_prim) + + sim_utils.create_new_stage() + sim_cfg = make_sim_cfg() + sim = sim_utils.SimulationContext(sim_cfg) + sim.set_camera_view(eye=[2.5, 2.5, 2.5], target=[0.0, 0.0, 0.0]) + + scene = create_duplicated_env_scene() + if args_cli.renderer == "newton": + bake_source_camera_pose_to_envs(source_stage, source_camera_prim_path) + baseline_camera = make_camera(camera_prim_path, ppisp_cfg=None, width=width, height=height) + ppisp_camera = make_camera(camera_prim_path, ppisp_cfg=ppisp_cfg, width=width, height=height) + print(f"[INFO] Duplicated-env camera regex: {camera_prim_path}", flush=True) + print(f"[INFO] Rendering {width}x{height} from source camera {source_camera_prim_path}.", flush=True) + + sim.reset() + print("[INFO]: Setup complete. Saving comparison images during simulation.", flush=True) + run_simulator(sim, baseline_camera, ppisp_camera) + del scene + + +if __name__ == "__main__": + main() + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/sensors/pva_sensor.py b/simulation/modules/IsaacLab/scripts/demos/sensors/pva_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..746bd1bc8452106834895cf1450298b973408515 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/sensors/pva_sensor.py @@ -0,0 +1,147 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Example on using the PVA sensor.") +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to spawn.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors import PvaCfg +from isaaclab.utils.configclass import configclass + +## +# Pre-defined configs +## +from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip + + +@configclass +class PvaSensorSceneCfg(InteractiveSceneCfg): + """Design the scene with sensors on the robot.""" + + # ground plane + ground = AssetBaseCfg(prim_path="/World/defaultGroundPlane", spawn=sim_utils.GroundPlaneCfg()) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # robot + robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + pva_LF = PvaCfg(prim_path="{ENV_REGEX_NS}/Robot/LF_FOOT", debug_vis=True) + + pva_RF = PvaCfg(prim_path="{ENV_REGEX_NS}/Robot/RF_FOOT", debug_vis=True) + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Run the simulator.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + # Simulate physics + while simulation_app.is_running(): + if count % 500 == 0: + # reset counter + count = 0 + # reset the scene entities + # root state + # we offset the root state by the origin since the states are written in simulation world frame + # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world + root_pose = scene["robot"].data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + scene["robot"].write_root_link_pose_to_sim_index(root_pose=root_pose) + root_vel = scene["robot"].data.default_root_vel.torch.clone() + scene["robot"].write_root_com_velocity_to_sim_index(root_velocity=root_vel) + # set joint positions with some noise + joint_pos, joint_vel = ( + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), + ) + joint_pos += torch.rand_like(joint_pos) * 0.1 + scene["robot"].write_joint_position_to_sim_index(position=joint_pos) + scene["robot"].write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + scene.reset() + print("[INFO]: Resetting robot state...") + # Apply default actions to the robot + # -- generate actions/commands + targets = scene["robot"].data.default_joint_pos.torch + # -- apply action to the robot + scene["robot"].set_joint_position_target_index(target=targets) + # -- write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + scene.update(sim_dt) + + # print information from the sensors + print("-------------------------------") + print(scene["pva_LF"]) + print("Received linear velocity: ", scene["pva_LF"].data.lin_vel_b) + print("Received angular velocity: ", scene["pva_LF"].data.ang_vel_b) + print("Received linear acceleration: ", scene["pva_LF"].data.lin_acc_b) + print("Received angular acceleration: ", scene["pva_LF"].data.ang_acc_b) + print("-------------------------------") + print(scene["pva_RF"]) + print("Received linear velocity: ", scene["pva_RF"].data.lin_vel_b) + print("Received angular velocity: ", scene["pva_RF"].data.ang_vel_b) + print("Received linear acceleration: ", scene["pva_RF"].data.lin_acc_b) + print("Received angular acceleration: ", scene["pva_RF"].data.ang_acc_b) + + +def main(): + """Main function.""" + + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[3.5, 3.5, 3.5], target=[0.0, 0.0, 0.0]) + # design scene + scene_cfg = PvaSensorSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0) + scene = InteractiveScene(scene_cfg) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/sensors/raycaster_sensor.py b/simulation/modules/IsaacLab/scripts/demos/sensors/raycaster_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..2ae95f85e64d2db26e059dad946aec4dce0cc0e9 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/sensors/raycaster_sensor.py @@ -0,0 +1,165 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Example on using the raycaster sensor.") +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to spawn.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import numpy as np +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors.ray_caster import RayCasterCfg, patterns +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR +from isaaclab.utils.configclass import configclass + +## +# Pre-defined configs +## +from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip + + +@configclass +class RaycasterSensorSceneCfg(InteractiveSceneCfg): + """Design the scene with sensors on the robot.""" + + # ground plane + ground = AssetBaseCfg( + prim_path="/World/Ground", + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Environments/Terrains/rough_plane.usd", + scale=(1, 1, 1), + ), + ) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # robot + robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + ray_caster = RayCasterCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + update_period=1 / 60, + offset=RayCasterCfg.OffsetCfg(pos=(0, 0, 0.5)), + mesh_prim_paths=["/World/Ground"], + ray_alignment="yaw", + pattern_cfg=patterns.LidarPatternCfg( + channels=100, vertical_fov_range=[-90, 90], horizontal_fov_range=[-90, 90], horizontal_res=1.0 + ), + debug_vis=not args_cli.headless, + ) + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Run the simulator.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + triggered = True + countdown = 42 + + # Simulate physics + while simulation_app.is_running(): + if count % 500 == 0: + # reset counter + count = 0 + # reset the scene entities + # root state + # we offset the root state by the origin since the states are written in simulation world frame + # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world + root_pose = scene["robot"].data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + scene["robot"].write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = scene["robot"].data.default_root_vel.torch.clone() + scene["robot"].write_root_velocity_to_sim_index(root_velocity=root_vel) + # set joint positions with some noise + joint_pos, joint_vel = ( + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), + ) + joint_pos += torch.rand_like(joint_pos) * 0.1 + scene["robot"].write_joint_position_to_sim_index(position=joint_pos) + scene["robot"].write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + scene.reset() + print("[INFO]: Resetting robot state...") + # Apply default actions to the robot + # -- generate actions/commands + targets = scene["robot"].data.default_joint_pos.torch + # -- apply action to the robot + scene["robot"].set_joint_position_target_index(target=targets) + # -- write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + scene.update(sim_dt) + + # print information from the sensors + print("-------------------------------") + print(scene["ray_caster"]) + print("Ray cast hit results: ", scene["ray_caster"].data.ray_hits_w.torch) + + if not triggered: + if countdown > 0: + countdown -= 1 + continue + data = scene["ray_caster"].data.ray_hits_w.torch.cpu().numpy() + np.save("cast_data.npy", data) + triggered = True + else: + continue + + +def main(): + """Main function.""" + + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[3.5, 3.5, 3.5], target=[0.0, 0.0, 0.0]) + # design scene + scene_cfg = RaycasterSensorSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0) + scene = InteractiveScene(scene_cfg) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/demos/sensors/tacsl_sensor.py b/simulation/modules/IsaacLab/scripts/demos/sensors/tacsl_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..a3332ed6f7e9280c5a06e437304a58cdb12e3483 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/demos/sensors/tacsl_sensor.py @@ -0,0 +1,431 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Example script demonstrating the TacSL tactile sensor implementation in IsaacLab. + +This script shows how to use the TactileSensor for both camera-based and force field +tactile sensing with the GelSight finger setup. + +.. code-block:: bash + + # Usage + python scripts/demos/sensors/tacsl_sensor.py \ + --use_tactile_rgb \ + --use_tactile_ff \ + --tactile_compliance_stiffness 100.0 \ + --num_envs 16 \ + --contact_object_type nut \ + --save_viz \ + --enable_cameras \ + --viz kit/newton + +""" + +import argparse +import math +import os + +import cv2 +import numpy as np +import torch + +from isaaclab.app import AppLauncher + +# Add argparse arguments +parser = argparse.ArgumentParser(description="TacSL tactile sensor example.") +parser.add_argument("--num_envs", type=int, default=2, help="Number of environments to spawn.") +parser.add_argument("--normal_contact_stiffness", type=float, default=1.0, help="Tactile normal stiffness.") +parser.add_argument("--tangential_stiffness", type=float, default=0.1, help="Tactile tangential stiffness.") +parser.add_argument("--friction_coefficient", type=float, default=2.0, help="Tactile friction coefficient.") +parser.add_argument( + "--tactile_compliance_stiffness", + type=float, + default=None, + help="Optional: Override compliant contact stiffness (default: use USD asset values)", +) +parser.add_argument( + "--tactile_compliant_damping", + type=float, + default=None, + help="Optional: Override compliant contact damping (default: use USD asset values)", +) +parser.add_argument("--save_viz", action="store_true", help="Visualize tactile data.") +parser.add_argument("--save_viz_dir", type=str, default="tactile_record", help="Directory to save tactile data.") +parser.add_argument("--use_tactile_rgb", action="store_true", help="Use tactile RGB sensor data collection.") +parser.add_argument("--use_tactile_ff", action="store_true", help="Use tactile force field sensor data collection.") +parser.add_argument("--debug_sdf_closest_pts", action="store_true", help="Visualize closest SDF points.") +parser.add_argument("--debug_tactile_sensor_pts", action="store_true", help="Visualize tactile sensor points.") +parser.add_argument("--trimesh_vis_tactile_points", action="store_true", help="Visualize tactile points using trimesh.") +parser.add_argument( + "--contact_object_type", + type=str, + default="nut", + choices=["none", "cube", "nut"], + help="Type of contact object to use.", +) + +# Append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# Parse the arguments +args_cli = parser.parse_args() + +# Launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +from isaaclab_physx.sim.schemas import ( + PhysxArticulationRootPropertiesCfg, + PhysxCollisionPropertiesCfg, + PhysxRigidBodyPropertiesCfg, +) +from isaaclab_physx.sim.spawners.materials import PhysxRigidBodyMaterialCfg + +import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg, AssetBaseCfg, RigidObjectCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors import CameraCfg +from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR +from isaaclab.utils.configclass import configclass + +from isaaclab_contrib.sensors.tacsl_sensor import VisuoTactileSensorCfg +from isaaclab_contrib.sensors.tacsl_sensor.visuotactile_render import compute_tactile_shear_image +from isaaclab_contrib.sensors.tacsl_sensor.visuotactile_sensor_data import VisuoTactileSensorData + +from isaaclab_assets.sensors import GELSIGHT_R15_CFG + + +@configclass +class TactileSensorsSceneCfg(InteractiveSceneCfg): + """Design the scene with tactile sensors on the robot.""" + + # Ground plane + ground = AssetBaseCfg(prim_path="/World/defaultGroundPlane", spawn=sim_utils.GroundPlaneCfg()) + + # Lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # Robot with tactile sensor + robot = ArticulationCfg( + prim_path="{ENV_REGEX_NS}/Robot", + spawn=sim_utils.UsdFileWithCompliantContactCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/TacSL/gelsight_r15_finger/gelsight_r15_finger.usd", + rigid_props=PhysxRigidBodyPropertiesCfg( + disable_gravity=True, + max_depenetration_velocity=5.0, + ), + compliant_contact_stiffness=args_cli.tactile_compliance_stiffness, + compliant_contact_damping=args_cli.tactile_compliant_damping, + physics_material_prim_path="elastomer", + articulation_props=PhysxArticulationRootPropertiesCfg( + enabled_self_collisions=False, + solver_position_iteration_count=12, + solver_velocity_iteration_count=1, + ), + collision_props=PhysxCollisionPropertiesCfg(contact_offset=0.001, rest_offset=-0.0005), + ), + init_state=ArticulationCfg.InitialStateCfg( + pos=(0.0, 0.0, 0.5), + rot=(-math.sqrt(2) / 2, 0.0, 0.0, math.sqrt(2) / 2), # 90° rotation + joint_pos={}, + joint_vel={}, + ), + actuators={}, + ) + + # Camera configuration for tactile sensing + + # TacSL Tactile Sensor + tactile_sensor = VisuoTactileSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/elastomer/tactile_sensor", + debug_vis=args_cli.debug_tactile_sensor_pts or args_cli.debug_sdf_closest_pts, + # Sensor configuration + render_cfg=GELSIGHT_R15_CFG, + enable_camera_tactile=args_cli.use_tactile_rgb, + enable_force_field=args_cli.use_tactile_ff, + # Elastomer configuration + tactile_array_size=(20, 25), + tactile_margin=0.003, + # Contact object configuration + contact_object_prim_path_expr="{ENV_REGEX_NS}/contact_object", + # Force field physics parameters + normal_contact_stiffness=args_cli.normal_contact_stiffness, + friction_coefficient=args_cli.friction_coefficient, + tangential_stiffness=args_cli.tangential_stiffness, + # Camera configuration + # Note: the camera is already spawned in the scene, properties are set in the + # 'gelsight_r15_finger.usd' USD file + camera_cfg=CameraCfg( + prim_path="{ENV_REGEX_NS}/Robot/elastomer_tip/cam", + height=GELSIGHT_R15_CFG.image_height, + width=GELSIGHT_R15_CFG.image_width, + data_types=["distance_to_image_plane"], + spawn=None, + ), + # Debug Visualization + trimesh_vis_tactile_points=args_cli.trimesh_vis_tactile_points, + visualize_sdf_closest_pts=args_cli.debug_sdf_closest_pts, + ) + + +@configclass +class CubeTactileSceneCfg(TactileSensorsSceneCfg): + """Scene with cube contact object.""" + + # Cube contact object + contact_object = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/contact_object", + spawn=sim_utils.CuboidCfg( + size=(0.01, 0.01, 0.01), + rigid_props=PhysxRigidBodyPropertiesCfg(disable_gravity=True), + mass_props=sim_utils.MassPropertiesCfg(mass=0.00327211), + collision_props=PhysxCollisionPropertiesCfg(), + physics_material=PhysxRigidBodyMaterialCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.1, 0.1)), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0 + 0.06776, 0.51), rot=(0.0, 0.0, 0.0, 1.0)), + ) + + +@configclass +class NutTactileSceneCfg(TactileSensorsSceneCfg): + """Scene with nut contact object.""" + + # Nut contact object + contact_object = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/contact_object", + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Factory/factory_nut_m16.usd", + rigid_props=PhysxRigidBodyPropertiesCfg( + disable_gravity=True, + solver_position_iteration_count=12, + solver_velocity_iteration_count=1, + max_angular_velocity=180.0, + ), + mass_props=sim_utils.MassPropertiesCfg(mass=0.1), + collision_props=PhysxCollisionPropertiesCfg(contact_offset=0.005, rest_offset=0), + articulation_props=PhysxArticulationRootPropertiesCfg(articulation_enabled=False), + ), + init_state=RigidObjectCfg.InitialStateCfg( + pos=(0.0, 0.0 + 0.06776, 0.498), + rot=(0.0, 0.0, 0.0, 1.0), + ), + ) + + +def mkdir_helper(dir_path: str) -> tuple[str, str]: + """Create directories for saving tactile sensor visualizations. + + Args: + dir_path: The base directory path where visualizations will be saved. + + Returns: + A tuple containing paths to the force field directory and RGB image directory. + """ + tactile_img_folder = dir_path + os.makedirs(tactile_img_folder, exist_ok=True) + # create a subdirectory for the force field data + tactile_force_field_dir = os.path.join(tactile_img_folder, "tactile_force_field") + os.makedirs(tactile_force_field_dir, exist_ok=True) + # create a subdirectory for the RGB image data + tactile_rgb_image_dir = os.path.join(tactile_img_folder, "tactile_rgb_image") + os.makedirs(tactile_rgb_image_dir, exist_ok=True) + + return tactile_force_field_dir, tactile_rgb_image_dir + + +def save_viz_helper( + dir_path_list: tuple[str, str], + count: int, + tactile_data: VisuoTactileSensorData, + num_envs: int, + nrows: int, + ncols: int, +): + """Save visualization of tactile sensor data. + + Args: + dir_path_list: A tuple containing paths to the force field directory and RGB image directory. + count: The current simulation step count, used for naming saved files. + tactile_data: The data object containing tactile sensor readings (forces, images). + num_envs: Number of environments in the simulation. + nrows: Number of rows in the tactile array. + ncols: Number of columns in the tactile array. + """ + # Only save the first 2 environments + + tactile_force_field_dir, tactile_rgb_image_dir = dir_path_list + + if tactile_data.tactile_shear_force is not None and tactile_data.tactile_normal_force is not None: + # visualize tactile forces + tactile_normal_force = tactile_data.tactile_normal_force.view((num_envs, nrows, ncols)) + tactile_shear_force = tactile_data.tactile_shear_force.view((num_envs, nrows, ncols, 2)) + + tactile_image = compute_tactile_shear_image( + tactile_normal_force[0, :, :].detach().cpu().numpy(), tactile_shear_force[0, :, :].detach().cpu().numpy() + ) + + if tactile_normal_force.shape[0] > 1: + tactile_image_1 = compute_tactile_shear_image( + tactile_normal_force[1, :, :].detach().cpu().numpy(), + tactile_shear_force[1, :, :].detach().cpu().numpy(), + ) + combined_image = np.vstack([tactile_image, tactile_image_1]) + cv2.imwrite( + os.path.join(tactile_force_field_dir, f"{count:04d}.png"), (combined_image * 255).astype(np.uint8) + ) + else: + cv2.imwrite( + os.path.join(tactile_force_field_dir, f"{count:04d}.png"), (tactile_image * 255).astype(np.uint8) + ) + + if tactile_data.tactile_rgb_image is not None: + tactile_rgb_data = tactile_data.tactile_rgb_image.cpu().numpy() + tactile_rgb_data = np.transpose(tactile_rgb_data, axes=(0, 2, 1, 3)) + tactile_rgb_data_first_2 = tactile_rgb_data[:2] if len(tactile_rgb_data) >= 2 else tactile_rgb_data + tactile_rgb_tiled = np.concatenate(tactile_rgb_data_first_2, axis=0) + # Convert to uint8 if not already + if tactile_rgb_tiled.dtype != np.uint8: + tactile_rgb_tiled = ( + (tactile_rgb_tiled * 255).astype(np.uint8) + if tactile_rgb_tiled.max() <= 1.0 + else tactile_rgb_tiled.astype(np.uint8) + ) + cv2.imwrite(os.path.join(tactile_rgb_image_dir, f"{count:04d}.png"), tactile_rgb_tiled) + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Run the simulator.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + # Assign different masses to contact objects in different environments + num_envs = scene.num_envs + + if args_cli.save_viz: + # Create output directories for tactile data + print(f"[INFO]: Saving tactile data to: {args_cli.save_viz_dir}...") + dir_path_list = mkdir_helper(args_cli.save_viz_dir) + + # Create constant downward force + force_tensor = torch.zeros(scene.num_envs, 1, 3, device=sim.device) + torque_tensor = torch.zeros(scene.num_envs, 1, 3, device=sim.device) + force_tensor[:, 0, 2] = -1.0 + + nrows = scene["tactile_sensor"].cfg.tactile_array_size[0] + ncols = scene["tactile_sensor"].cfg.tactile_array_size[1] + + entity_list = ["robot"] + if "contact_object" in scene.keys(): + entity_list.append("contact_object") + + while simulation_app.is_running(): + if count == 122: + # Reset robot and contact object positions + count = 0 + for entity in entity_list: + root_pose = scene[entity].data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + scene[entity].write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = scene[entity].data.default_root_vel.torch.clone() + scene[entity].write_root_velocity_to_sim_index(root_velocity=root_vel) + + scene.reset() + print("[INFO]: Resetting robot and contact object state...") + + if "contact_object" in scene.keys(): + # rotation + if count > 20: + env_indices = torch.arange(scene.num_envs, device=sim.device) + odd_mask = env_indices % 2 == 1 + even_mask = env_indices % 2 == 0 + torque_tensor[odd_mask, 0, 2] = 10 # rotation for odd environments + torque_tensor[even_mask, 0, 2] = -10 # rotation for even environments + scene["contact_object"].permanent_wrench_composer.set_forces_and_torques_index( + forces=force_tensor, torques=torque_tensor + ) + + # Step simulation + scene.write_data_to_sim() + sim.step() + sim_time += sim_dt + count += 1 + scene.update(sim_dt) + + # Access tactile sensor data + tactile_data = scene["tactile_sensor"].data + + if args_cli.save_viz: + save_viz_helper(dir_path_list, count, tactile_data, num_envs, nrows, ncols) + + +def main(): + """Main function.""" + from isaaclab_physx.physics import PhysxCfg + + # Initialize simulation + # Note: We set the gpu_collision_stack_size to prevent buffer overflow in contact-rich environments. + sim_cfg = sim_utils.SimulationCfg( + dt=0.005, + device=args_cli.device, + physics=PhysxCfg(gpu_collision_stack_size=2**30), + ) + sim = sim_utils.SimulationContext(sim_cfg) + + # Set main camera + sim.set_camera_view(eye=(0.5, 0.6, 1.0), target=(-0.1, 0.1, 0.5)) + + # Create scene based on contact object type + if args_cli.contact_object_type == "cube": + scene_cfg = CubeTactileSceneCfg(num_envs=args_cli.num_envs, env_spacing=0.2) + # disabled force field for cube contact object because a SDF collision mesh cannot + # be created for the Shape Prims + scene_cfg.tactile_sensor.enable_force_field = False + elif args_cli.contact_object_type == "nut": + scene_cfg = NutTactileSceneCfg(num_envs=args_cli.num_envs, env_spacing=0.2) + elif args_cli.contact_object_type == "none": + scene_cfg = TactileSensorsSceneCfg(num_envs=args_cli.num_envs, env_spacing=0.2) + scene_cfg.tactile_sensor.contact_object_prim_path_expr = None + # this flag is to visualize the tactile sensor points + scene_cfg.tactile_sensor.debug_vis = True + else: + raise ValueError( + f"Invalid contact object type: '{args_cli.contact_object_type}'. Must be 'none', 'cube', or 'nut'." + ) + + scene = InteractiveScene(scene_cfg) + + # Initialize simulation + sim.reset() + + # The tactile RGB path internally uses an RTX camera that may request only non-color render products. + # Isaac RTX can disable color rendering for that case, which makes the Kit viewport black even though + # the sensor images are produced correctly. Keep color rendering enabled when a Kit viewport is active. + visualizers = args_cli.visualizer + if isinstance(visualizers, str): + visualizers = [token.strip() for token in visualizers.split(",")] + if args_cli.use_tactile_rgb and "kit" in visualizers: + print("[INFO]: Keeping RTX color rendering enabled for Kit viewport visualization.") + sim.set_setting("/rtx/sdg/force/disableColorRender", False) + + print("[INFO]: Setup complete...") + + # Get initial render + scene["tactile_sensor"].get_initial_render() + # Run simulation + run_simulator(sim, scene) + + +if __name__ == "__main__": + # Run the main function + main() + # Close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/environments/export_IODescriptors.py b/simulation/modules/IsaacLab/scripts/environments/export_IODescriptors.py new file mode 100644 index 0000000000000000000000000000000000000000..2db02f1cc3e8b1e845ffcf9e5601dc736bee595f --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/environments/export_IODescriptors.py @@ -0,0 +1,105 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to an environment with random action agent.""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +import contextlib +import os + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Random agent for Isaac Lab environments.") +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument("--output_dir", type=str, default=None, help="Path to the output directory.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() +args_cli.headless = True + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import gymnasium as gym +import torch + +import isaaclab_tasks # noqa: F401 + +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 +from isaaclab_tasks.utils import parse_env_cfg + +# PLACEHOLDER: Extension template (do not remove this comment) + + +def main(): + """Random actions agent with Isaac Lab environment.""" + # create environment configuration + env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=1, use_fabric=True) + # create environment + env = gym.make(args_cli.task, cfg=env_cfg) + + # print info (this is vectorized environment) + print(f"[INFO]: Gym observation space: {env.observation_space}") + print(f"[INFO]: Gym action space: {env.action_space}") + # reset environment + env.reset() + + outs = env.unwrapped.get_IO_descriptors + out_observations = outs["observations"] + out_actions = outs["actions"] + out_articulations = outs["articulations"] + out_scene = outs["scene"] + # Make a yaml file with the output + import yaml + + name = args_cli.task.lower().replace("-", "_") + name = name.replace(" ", "_") + + if not os.path.exists(args_cli.output_dir): + os.makedirs(args_cli.output_dir) + + with open(os.path.join(args_cli.output_dir, f"{name}_IO_descriptors.yaml"), "w") as f: + print(f"[INFO]: Exporting IO descriptors to {os.path.join(args_cli.output_dir, f'{name}_IO_descriptors.yaml')}") + yaml.safe_dump(outs, f) + + for k in out_actions: + print(f"--- Action term: {k['name']} ---") + k.pop("name") + for k1, v1 in k.items(): + print(f"{k1}: {v1}") + + for obs_group_name, obs_group in out_observations.items(): + print(f"--- Obs group: {obs_group_name} ---") + for k in obs_group: + print(f"--- Obs term: {k['name']} ---") + k.pop("name") + for k1, v1 in k.items(): + print(f"{k1}: {v1}") + + for articulation_name, articulation_data in out_articulations.items(): + print(f"--- Articulation: {articulation_name} ---") + for k1, v1 in articulation_data.items(): + print(f"{k1}: {v1}") + + for k1, v1 in out_scene.items(): + print(f"{k1}: {v1}") + + env.step(torch.zeros(env.action_space.shape, device=env.unwrapped.device)) + env.close() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/environments/list_envs.py b/simulation/modules/IsaacLab/scripts/environments/list_envs.py new file mode 100644 index 0000000000000000000000000000000000000000..0bbcf8cf6d6f7661f06820618eb41b5a1adc1699 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/environments/list_envs.py @@ -0,0 +1,135 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Script to print all the available environments in Isaac Lab. + +The script iterates over all registered environments and stores the details in a table. +It prints the name of the environment, the entry point and the config file. + +All the environments are registered in the `isaaclab_tasks` extension. They start +with `Isaac` in their name. +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +import contextlib + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="List Isaac Lab environments.") +parser.add_argument("--keyword", type=str, default=None, help="Keyword to filter environments.") +parser.add_argument( + "--show_presets", + action="store_true", + default=False, + help=( + "Show available preset selectors for each environment. " + "Presets are grouped by selector type: physics (physics=NAME), " + "renderer (renderer=NAME), and domain (presets=NAME)." + ), +) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(headless=True) +simulation_app = app_launcher.app + + +"""Rest everything follows.""" + +import gymnasium as gym +from prettytable import PrettyTable + +import isaaclab_tasks # noqa: F401 + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + + +def _format_presets(preset_map: dict | None) -> str: + """Format a preset map returned by :func:`enumerate_task_presets` into a human-readable string. + + Args: + preset_map: Mapping of :class:`~isaaclab_tasks.utils.preset_target.PresetTarget` + to sorted preset name lists, or ``None`` when the env cfg could not be loaded. + + Returns: + A multi-line string with one line per non-empty selector category, or a + short placeholder when no presets are available or the cfg failed to load. + """ + if preset_map is None: + return "(unavailable)" + from isaaclab_tasks.utils.preset_target import PresetTarget + + lines = [] + labels = { + PresetTarget.PHYSICS: "physics", + PresetTarget.RENDERER: "renderer", + PresetTarget.DOMAIN: "domain", + } + for target, label in labels.items(): + names = preset_map.get(target, []) + if names: + lines.append(f"{label}: {', '.join(names)}") + return "\n".join(lines) if lines else "(none)" + + +def main(): + """Print all environments registered in `isaaclab_tasks` extension.""" + # Collect matching task specs first so we can enumerate presets in one pass. + task_specs = [ + spec + for spec in gym.registry.values() + if "Isaac" in spec.id and (args_cli.keyword is None or args_cli.keyword in spec.id) + ] + + if args_cli.show_presets: + from isaaclab_tasks.utils.preset_cli import enumerate_task_presets + + table = PrettyTable(["S. No.", "Task Name", "Entry Point", "Config", "Presets"]) + table.title = "Available Environments in Isaac Lab" + table.align["Task Name"] = "l" + table.align["Entry Point"] = "l" + table.align["Config"] = "l" + table.align["Presets"] = "l" + + for index, spec in enumerate(task_specs): + preset_map = enumerate_task_presets(spec.id) + table.add_row( + [ + index + 1, + spec.id, + spec.entry_point, + spec.kwargs["env_cfg_entry_point"], + _format_presets(preset_map), + ] + ) + else: + table = PrettyTable(["S. No.", "Task Name", "Entry Point", "Config"]) + table.title = "Available Environments in Isaac Lab" + table.align["Task Name"] = "l" + table.align["Entry Point"] = "l" + table.align["Config"] = "l" + + for index, spec in enumerate(task_specs): + table.add_row([index + 1, spec.id, spec.entry_point, spec.kwargs["env_cfg_entry_point"]]) + + print(table) + + +if __name__ == "__main__": + try: + # run the main function + main() + except Exception as e: + raise e + finally: + # close the app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/environments/random_agent.py b/simulation/modules/IsaacLab/scripts/environments/random_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..2303b6bd9274b3cc04677a356ad328f02289ac18 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/environments/random_agent.py @@ -0,0 +1,86 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to an environment with random action agent.""" + +import argparse +import contextlib +import sys + +import gymnasium as gym +import torch + +import isaaclab_tasks # noqa: F401 + +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + launch_simulation, + resolve_task_config, + setup_preset_cli, +) + +# add argparse arguments +parser = argparse.ArgumentParser(description="Random agent for Isaac Lab environments.") +parser.add_argument( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +# append AppLauncher cli args +add_launcher_args(parser) +# simple agents should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args + +# PLACEHOLDER: Extension template (do not remove this comment) + + +def main(): + """Random actions agent with Isaac Lab environment.""" + + torch.manual_seed(42) + + # parse configuration via Hydra (supports preset selection, e.g. env.sim.physics=newton_mjwarp) + env_cfg, _ = resolve_task_config(args_cli.task, "") + + with launch_simulation(env_cfg, args_cli): + # override with CLI arguments + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + if args_cli.disable_fabric: + env_cfg.sim.use_fabric = False + + # create environment + env = gym.make(args_cli.task, cfg=env_cfg) + + # print info (this is vectorized environment) + print(f"[INFO]: Gym observation space: {env.observation_space}") + print(f"[INFO]: Gym action space: {env.action_space}") + # reset environment + env.reset() + # simulate environment + sim = env.unwrapped.sim + while True: + if sim.visualizers: + # visualizer mode: run until the visualizer window is closed + if not any(v.is_running() and not v.is_closed for v in sim.visualizers): + break + # run everything in inference mode + with torch.inference_mode(): + # sample actions from -1 to 1 + actions = 2 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1 + # apply actions + env.step(actions) + + # close the simulator + env.close() + + +if __name__ == "__main__": + # run the main function + main() diff --git a/simulation/modules/IsaacLab/scripts/environments/state_machine/lift_cube_sm.py b/simulation/modules/IsaacLab/scripts/environments/state_machine/lift_cube_sm.py new file mode 100644 index 0000000000000000000000000000000000000000..895991461ee89c5e6e2a8a663ae38bb557622383 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/environments/state_machine/lift_cube_sm.py @@ -0,0 +1,315 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Script to run an environment with a pick and lift state machine. + +The state machine is implemented in the kernel function `infer_state_machine`. +It uses the `warp` library to run the state machine in parallel on the GPU. + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/state_machine/lift_cube_sm.py --num_envs 32 --viz kit + +""" + +"""Launch Omniverse Toolkit first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Pick and lift state machine for lift environments.") +parser.add_argument( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything else.""" + +from collections.abc import Sequence + +import gymnasium as gym +import torch +import warp as wp + +from isaaclab.assets.rigid_object.rigid_object_data import RigidObjectData + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.manager_based.manipulation.lift.lift_env_cfg import LiftEnvCfg +from isaaclab_tasks.utils.parse_cfg import parse_env_cfg + +# initialize warp +wp.init() + + +class GripperState: + """States for the gripper.""" + + OPEN = wp.constant(1.0) + CLOSE = wp.constant(-1.0) + + +class PickSmState: + """States for the pick state machine.""" + + REST = wp.constant(0) + APPROACH_ABOVE_OBJECT = wp.constant(1) + APPROACH_OBJECT = wp.constant(2) + GRASP_OBJECT = wp.constant(3) + LIFT_OBJECT = wp.constant(4) + + +class PickSmWaitTime: + """Additional wait times (in s) for states for before switching.""" + + REST = wp.constant(0.2) + APPROACH_ABOVE_OBJECT = wp.constant(0.5) + APPROACH_OBJECT = wp.constant(0.6) + GRASP_OBJECT = wp.constant(0.3) + LIFT_OBJECT = wp.constant(1.0) + + +@wp.func +def distance_below_threshold(current_pos: wp.vec3, desired_pos: wp.vec3, threshold: float) -> bool: + return wp.length(current_pos - desired_pos) < threshold + + +@wp.kernel +def infer_state_machine( + dt: wp.array(dtype=float), + sm_state: wp.array(dtype=int), + sm_wait_time: wp.array(dtype=float), + ee_pose: wp.array(dtype=wp.transform), + object_pose: wp.array(dtype=wp.transform), + des_object_pose: wp.array(dtype=wp.transform), + des_ee_pose: wp.array(dtype=wp.transform), + gripper_state: wp.array(dtype=float), + offset: wp.array(dtype=wp.transform), + position_threshold: float, +): + # retrieve thread id + tid = wp.tid() + # retrieve state machine state + state = sm_state[tid] + # decide next state + if state == PickSmState.REST: + des_ee_pose[tid] = ee_pose[tid] + gripper_state[tid] = GripperState.OPEN + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.REST: + # move to next state and reset wait time + sm_state[tid] = PickSmState.APPROACH_ABOVE_OBJECT + sm_wait_time[tid] = 0.0 + elif state == PickSmState.APPROACH_ABOVE_OBJECT: + des_ee_pose[tid] = wp.transform_multiply(offset[tid], object_pose[tid]) + gripper_state[tid] = GripperState.OPEN + if distance_below_threshold( + wp.transform_get_translation(ee_pose[tid]), + wp.transform_get_translation(des_ee_pose[tid]), + position_threshold, + ): + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.APPROACH_OBJECT: + # move to next state and reset wait time + sm_state[tid] = PickSmState.APPROACH_OBJECT + sm_wait_time[tid] = 0.0 + elif state == PickSmState.APPROACH_OBJECT: + des_ee_pose[tid] = object_pose[tid] + gripper_state[tid] = GripperState.OPEN + if distance_below_threshold( + wp.transform_get_translation(ee_pose[tid]), + wp.transform_get_translation(des_ee_pose[tid]), + position_threshold, + ): + if sm_wait_time[tid] >= PickSmWaitTime.APPROACH_OBJECT: + # move to next state and reset wait time + sm_state[tid] = PickSmState.GRASP_OBJECT + sm_wait_time[tid] = 0.0 + elif state == PickSmState.GRASP_OBJECT: + des_ee_pose[tid] = object_pose[tid] + gripper_state[tid] = GripperState.CLOSE + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.GRASP_OBJECT: + # move to next state and reset wait time + sm_state[tid] = PickSmState.LIFT_OBJECT + sm_wait_time[tid] = 0.0 + elif state == PickSmState.LIFT_OBJECT: + des_ee_pose[tid] = des_object_pose[tid] + gripper_state[tid] = GripperState.CLOSE + if distance_below_threshold( + wp.transform_get_translation(ee_pose[tid]), + wp.transform_get_translation(des_ee_pose[tid]), + position_threshold, + ): + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.LIFT_OBJECT: + # move to next state and reset wait time + sm_state[tid] = PickSmState.LIFT_OBJECT + sm_wait_time[tid] = 0.0 + # increment wait time + sm_wait_time[tid] = sm_wait_time[tid] + dt[tid] + + +class PickAndLiftSm: + """A simple state machine in a robot's task space to pick and lift an object. + + The state machine is implemented as a warp kernel. It takes in the current state of + the robot's end-effector and the object, and outputs the desired state of the robot's + end-effector and the gripper. The state machine is implemented as a finite state + machine with the following states: + + 1. REST: The robot is at rest. + 2. APPROACH_ABOVE_OBJECT: The robot moves above the object. + 3. APPROACH_OBJECT: The robot moves to the object. + 4. GRASP_OBJECT: The robot grasps the object. + 5. LIFT_OBJECT: The robot lifts the object to the desired pose. This is the final state. + """ + + def __init__(self, dt: float, num_envs: int, device: torch.device | str = "cpu", position_threshold=0.01): + """Initialize the state machine. + + Args: + dt: The environment time step. + num_envs: The number of environments to simulate. + device: The device to run the state machine on. + """ + # save parameters + self.dt = float(dt) + self.num_envs = num_envs + self.device = device + self.position_threshold = position_threshold + # initialize state machine + self.sm_dt = torch.full((self.num_envs,), self.dt, device=self.device) + self.sm_state = torch.full((self.num_envs,), 0, dtype=torch.int32, device=self.device) + self.sm_wait_time = torch.zeros((self.num_envs,), device=self.device) + + # desired state + self.des_ee_pose = torch.zeros((self.num_envs, 7), device=self.device) + self.des_gripper_state = torch.full((self.num_envs,), 0.0, device=self.device) + + # approach above object offset + self.offset = torch.zeros((self.num_envs, 7), device=self.device) + self.offset[:, 2] = 0.1 + self.offset[:, -1] = 1.0 # warp expects quaternion as (x, y, z, w) + + # convert to warp + self.sm_dt_wp = wp.from_torch(self.sm_dt, wp.float32) + self.sm_state_wp = wp.from_torch(self.sm_state, wp.int32) + self.sm_wait_time_wp = wp.from_torch(self.sm_wait_time, wp.float32) + self.des_ee_pose_wp = wp.from_torch(self.des_ee_pose, wp.transform) + self.des_gripper_state_wp = wp.from_torch(self.des_gripper_state, wp.float32) + self.offset_wp = wp.from_torch(self.offset, wp.transform) + + def reset_idx(self, env_ids: Sequence[int] = None): + """Reset the state machine.""" + if env_ids is None: + env_ids = slice(None) + self.sm_state[env_ids] = 0 + self.sm_wait_time[env_ids] = 0.0 + + def compute(self, ee_pose: torch.Tensor, object_pose: torch.Tensor, des_object_pose: torch.Tensor) -> torch.Tensor: + """Compute the desired state of the robot's end-effector and the gripper.""" + + # convert to warp + ee_pose_wp = wp.from_torch(ee_pose.contiguous(), wp.transform) + object_pose_wp = wp.from_torch(object_pose.contiguous(), wp.transform) + des_object_pose_wp = wp.from_torch(des_object_pose.contiguous(), wp.transform) + + # run state machine + wp.launch( + kernel=infer_state_machine, + dim=self.num_envs, + inputs=[ + self.sm_dt_wp, + self.sm_state_wp, + self.sm_wait_time_wp, + ee_pose_wp, + object_pose_wp, + des_object_pose_wp, + self.des_ee_pose_wp, + self.des_gripper_state_wp, + self.offset_wp, + self.position_threshold, + ], + device=self.device, + ) + + # convert to torch + return torch.cat([self.des_ee_pose, self.des_gripper_state.unsqueeze(-1)], dim=-1) + + +def main(): + # parse configuration + env_cfg: LiftEnvCfg = parse_env_cfg( + "Isaac-Lift-Cube-Franka-IK-Abs-v0", + device=args_cli.device, + num_envs=args_cli.num_envs, + use_fabric=not args_cli.disable_fabric, + ) + # create environment + env = gym.make("Isaac-Lift-Cube-Franka-IK-Abs-v0", cfg=env_cfg) + # reset environment at start + env.reset() + + # create action buffers (position + quaternion) + actions = torch.zeros(env.unwrapped.action_space.shape, device=env.unwrapped.device) + actions[:, 3] = 1.0 + # desired object orientation (we only do position control of object) + desired_orientation = torch.zeros((env.unwrapped.num_envs, 4), device=env.unwrapped.device) + desired_orientation[:, 1] = 1.0 + # create state machine + pick_sm = PickAndLiftSm( + env_cfg.sim.dt * env_cfg.decimation, env.unwrapped.num_envs, env.unwrapped.device, position_threshold=0.01 + ) + + while simulation_app.is_running(): + # run everything in inference mode + with torch.inference_mode(): + # step environment + dones = env.step(actions)[-2] + + # observations + # -- end-effector frame + ee_frame_sensor = env.unwrapped.scene["ee_frame"] + tcp_rest_position = ( + ee_frame_sensor.data.target_pos_w.torch[..., 0, :].clone() - env.unwrapped.scene.env_origins + ) + tcp_rest_orientation = ee_frame_sensor.data.target_quat_w.torch[..., 0, :].clone() + # -- object frame + object_data: RigidObjectData = env.unwrapped.scene["object"].data + object_position = object_data.root_pos_w.torch - env.unwrapped.scene.env_origins + # -- target object frame + desired_position = env.unwrapped.command_manager.get_command("object_pose")[..., :3] + + # advance state machine + actions = pick_sm.compute( + torch.cat([tcp_rest_position, tcp_rest_orientation], dim=-1), + torch.cat([object_position, desired_orientation], dim=-1), + torch.cat([desired_position, desired_orientation], dim=-1), + ) + + # reset state machine + if dones.any(): + pick_sm.reset_idx(dones.nonzero(as_tuple=False).squeeze(-1)) + + # close the environment + env.close() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/environments/state_machine/lift_franka_soft.py b/simulation/modules/IsaacLab/scripts/environments/state_machine/lift_franka_soft.py new file mode 100644 index 0000000000000000000000000000000000000000..a9561718a5918d18d30057078cb784af544b1ca9 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/environments/state_machine/lift_franka_soft.py @@ -0,0 +1,382 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Script to demonstrate lifting a deformable object with a robotic arm. + +The state machine is implemented in the kernel function `infer_state_machine`. +It uses the `warp` library to run the state machine in parallel on the GPU. + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/state_machine/lift_franka_soft.py + +""" + +"""Launch Omniverse Toolkit first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Pick and lift a deformable with a robotic arm.") +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to simulate.") +parser.add_argument("--task", type=str, default="Isaac-Lift-Soft-Franka-v0", help="The task to run.") +parser.add_argument("--video", action="store_true", default=False, help="Record a video of the rollout.") +parser.add_argument("--video_length", type=int, default=500, help="Length of the recorded video (in env steps).") +parser.add_argument( + "--video_folder", + type=str, + default="videos/lift_franka_soft", + help="Directory to write recorded videos into.", +) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# RecordVideo needs an rgb_array render mode, which in turn requires cameras to be enabled. +if args_cli.video: + args_cli.enable_cameras = True + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +# disable metrics assembler due to scene graph instancing +from isaacsim.core.experimental.utils.app import enable_extension + +enable_extension("omni.usd.metrics.assembler.ui", enabled=False) + +"""Rest everything else.""" + +import os +from collections.abc import Sequence + +import gymnasium as gym +import torch +import warp as wp + +from isaaclab.assets.deformable_object.deformable_object_data import DeformableObjectData + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.manager_based.manipulation.lift_franka_soft.franka_cloth_env_cfg import FrankaClothEnvCfg +from isaaclab_tasks.manager_based.manipulation.lift_franka_soft.franka_soft_env_cfg import FrankaSoftEnvCfg +from isaaclab_tasks.utils.parse_cfg import parse_env_cfg + +# initialize warp +wp.init() + + +class GripperState: + """States for the gripper.""" + + OPEN = wp.constant(1.0) + CLOSE = wp.constant(-1.0) + + +class PickSmState: + """States for the pick state machine.""" + + REST = wp.constant(0) + APPROACH_ABOVE_OBJECT = wp.constant(1) + APPROACH_OBJECT = wp.constant(2) + GRASP_OBJECT = wp.constant(3) + LIFT_OBJECT = wp.constant(4) + OPEN_GRIPPER = wp.constant(5) + + +@wp.func +def distance_below_threshold(current_pos: wp.vec3, desired_pos: wp.vec3, threshold: float) -> bool: + return wp.length(current_pos - desired_pos) < threshold + + +@wp.kernel +def infer_state_machine( + dt: wp.array(dtype=float), + sm_state: wp.array(dtype=int), + sm_wait_time: wp.array(dtype=float), + ee_pose: wp.array(dtype=wp.transform), + object_pose: wp.array(dtype=wp.transform), + des_object_pose: wp.array(dtype=wp.transform), + des_ee_pose: wp.array(dtype=wp.transform), + gripper_state: wp.array(dtype=float), + offset: wp.array(dtype=wp.transform), + position_threshold: float, +): + # retrieve thread id + tid = wp.tid() + # retrieve state machine state + state = sm_state[tid] + # decide next state + if state == PickSmState.REST: + des_ee_pose[tid] = ee_pose[tid] + gripper_state[tid] = GripperState.OPEN + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.REST: + # move to next state and reset wait time + sm_state[tid] = PickSmState.APPROACH_ABOVE_OBJECT + sm_wait_time[tid] = 0.0 + elif state == PickSmState.APPROACH_ABOVE_OBJECT: + des_ee_pose[tid] = wp.transform_multiply(offset[tid], object_pose[tid]) + gripper_state[tid] = GripperState.OPEN + if distance_below_threshold( + wp.transform_get_translation(ee_pose[tid]), + wp.transform_get_translation(des_ee_pose[tid]), + position_threshold, + ): + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.APPROACH_OBJECT: + # move to next state and reset wait time + sm_state[tid] = PickSmState.APPROACH_OBJECT + sm_wait_time[tid] = 0.0 + elif state == PickSmState.APPROACH_OBJECT: + des_ee_pose[tid] = object_pose[tid] + gripper_state[tid] = GripperState.OPEN + if distance_below_threshold( + wp.transform_get_translation(ee_pose[tid]), + wp.transform_get_translation(des_ee_pose[tid]), + position_threshold, + ): + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.APPROACH_OBJECT: + # move to next state and reset wait time + sm_state[tid] = PickSmState.GRASP_OBJECT + sm_wait_time[tid] = 0.0 + elif state == PickSmState.GRASP_OBJECT: + des_ee_pose[tid] = object_pose[tid] + gripper_state[tid] = GripperState.CLOSE + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.GRASP_OBJECT: + # move to next state and reset wait time + sm_state[tid] = PickSmState.LIFT_OBJECT + sm_wait_time[tid] = 0.0 + elif state == PickSmState.LIFT_OBJECT: + des_ee_pose[tid] = des_object_pose[tid] + gripper_state[tid] = GripperState.CLOSE + if distance_below_threshold( + wp.transform_get_translation(ee_pose[tid]), + wp.transform_get_translation(des_ee_pose[tid]), + position_threshold, + ): + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.LIFT_OBJECT: + # move to next state and reset wait time + sm_state[tid] = PickSmState.OPEN_GRIPPER + sm_wait_time[tid] = 0.0 + elif state == PickSmState.OPEN_GRIPPER: + # des_ee_pose[tid] = object_pose[tid] + gripper_state[tid] = GripperState.OPEN + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.OPEN_GRIPPER: + # move to next state and reset wait time + sm_state[tid] = PickSmState.OPEN_GRIPPER + sm_wait_time[tid] = 0.0 + # increment wait time + sm_wait_time[tid] = sm_wait_time[tid] + dt[tid] + + +class PickSmWaitTime: + """Additional wait times (in s) for states for before switching. + + Wait times are generous because the low-PD Franka takes a while to settle on each IK target. + """ + + REST = wp.constant(0.2) + APPROACH_ABOVE_OBJECT = wp.constant(1.0) + APPROACH_OBJECT = wp.constant(1.0) + GRASP_OBJECT = wp.constant(1.0) + LIFT_OBJECT = wp.constant(1.5) + OPEN_GRIPPER = wp.constant(0.0) + + +class PickAndLiftSm: + """A simple state machine in a robot's task space to pick and lift an object. + + The state machine is implemented as a warp kernel. It takes in the current state of + the robot's end-effector and the object, and outputs the desired state of the robot's + end-effector and the gripper. The state machine is implemented as a finite state + machine with the following states: + + 1. REST: The robot is at rest. + 2. APPROACH_ABOVE_OBJECT: The robot moves above the object. + 3. APPROACH_OBJECT: The robot moves to the object. + 4. GRASP_OBJECT: The robot grasps the object. + 5. LIFT_OBJECT: The robot lifts the object to the desired pose. This is the final state. + """ + + def __init__(self, dt: float, num_envs: int, device: torch.device | str = "cpu", position_threshold=0.03): + """Initialize the state machine. + + Args: + dt: The environment time step. + num_envs: The number of environments to simulate. + device: The device to run the state machine on. + """ + # save parameters + self.dt = float(dt) + self.num_envs = num_envs + self.device = device + self.position_threshold = position_threshold + # initialize state machine + self.sm_dt = torch.full((self.num_envs,), self.dt, device=self.device) + self.sm_state = torch.full((self.num_envs,), 0, dtype=torch.int32, device=self.device) + self.sm_wait_time = torch.zeros((self.num_envs,), device=self.device) + + # desired state + self.des_ee_pose = torch.zeros((self.num_envs, 7), device=self.device) + self.des_gripper_state = torch.full((self.num_envs,), 0.0, device=self.device) + + # approach above object offset + self.offset = torch.zeros((self.num_envs, 7), device=self.device) + self.offset[:, 2] = 0.1 + self.offset[:, -1] = 1.0 # warp expects quaternion as (x, y, z, w) + + # convert to warp + self.sm_dt_wp = wp.from_torch(self.sm_dt, wp.float32) + self.sm_state_wp = wp.from_torch(self.sm_state, wp.int32) + self.sm_wait_time_wp = wp.from_torch(self.sm_wait_time, wp.float32) + self.des_ee_pose_wp = wp.from_torch(self.des_ee_pose, wp.transform) + self.des_gripper_state_wp = wp.from_torch(self.des_gripper_state, wp.float32) + self.offset_wp = wp.from_torch(self.offset, wp.transform) + + def reset_idx(self, env_ids: Sequence[int] = None): + """Reset the state machine.""" + if env_ids is None: + env_ids = slice(None) + self.sm_state[env_ids] = 0 + self.sm_wait_time[env_ids] = 0.0 + + def compute(self, ee_pose: torch.Tensor, object_pose: torch.Tensor, des_object_pose: torch.Tensor): + """Compute the desired state of the robot's end-effector and the gripper.""" + + # convert to warp + ee_pose_wp = wp.from_torch(ee_pose.contiguous(), wp.transform) + object_pose_wp = wp.from_torch(object_pose.contiguous(), wp.transform) + des_object_pose_wp = wp.from_torch(des_object_pose.contiguous(), wp.transform) + + # run state machine + wp.launch( + kernel=infer_state_machine, + dim=self.num_envs, + inputs=[ + self.sm_dt_wp, + self.sm_state_wp, + self.sm_wait_time_wp, + ee_pose_wp, + object_pose_wp, + des_object_pose_wp, + self.des_ee_pose_wp, + self.des_gripper_state_wp, + self.offset_wp, + self.position_threshold, + ], + device=self.device, + ) + + # convert to torch + return torch.cat([self.des_ee_pose, self.des_gripper_state.unsqueeze(-1)], dim=-1) + + +def main(): + # create environment + render_mode = "rgb_array" if args_cli.video else None + if args_cli.task == "Isaac-Lift-Soft-Franka-v0": + # parse configuration + env_cfg: FrankaSoftEnvCfg = parse_env_cfg( + "Isaac-Lift-Soft-Franka-v0", + device=args_cli.device, + num_envs=args_cli.num_envs, + ) + env_cfg.viewer.eye = (2.1, 1.0, 1.3) + env = gym.make("Isaac-Lift-Soft-Franka-v0", cfg=env_cfg, render_mode=render_mode) + elif args_cli.task == "Isaac-Lift-Soft-Franka-Cloth-v0": + # parse configuration + env_cfg: FrankaClothEnvCfg = parse_env_cfg( + "Isaac-Lift-Cloth-Franka-v0", + device=args_cli.device, + num_envs=args_cli.num_envs, + ) + env_cfg.viewer.eye = (2.1, 1.0, 1.3) + env = gym.make("Isaac-Lift-Cloth-Franka-v0", cfg=FrankaClothEnvCfg(), render_mode=render_mode) + else: + raise ValueError(f"Unknown task: {args_cli.task}") + + # wrap for video recording + if args_cli.video: + video_folder = os.path.abspath(args_cli.video_folder) + os.makedirs(video_folder, exist_ok=True) + env = gym.wrappers.RecordVideo( + env, + video_folder=video_folder, + step_trigger=lambda step: step == 0, + video_length=args_cli.video_length, + disable_logger=True, + ) + print(f"[INFO] Recording video to {video_folder} (length={args_cli.video_length} steps)") + + # reset environment at start + env.reset() + + # create action buffers (position + quaternion) + actions = torch.zeros(env.unwrapped.action_space.shape, device=env.unwrapped.device) + actions[:, 3] = 1.0 + # desired rotation after grasping + desired_orientation = torch.zeros((env.unwrapped.num_envs, 4), device=env.unwrapped.device) + desired_orientation[:, 0] = 1.0 + + # Top-down approach: identity quaternion (wxyz, w=1) aligns panda_hand with the Franka root, + # giving the canonical top-down grasp pose. The bar lies along world-X, so the gripper + # closes across its short side without any wrist twist. + object_grasp_orientation = torch.zeros((env.unwrapped.num_envs, 4), device=env.unwrapped.device) + object_grasp_orientation[:, 0] = 1.0 + # Grasp at the deformable's centre of mass. + object_local_grasp_position = torch.tensor([0.0, 0.0, 0.0], device=env.unwrapped.device) + + # create state machine + pick_sm = PickAndLiftSm(env_cfg.sim.dt * env_cfg.decimation, env.unwrapped.num_envs, env.unwrapped.device) + + while simulation_app.is_running(): + # run everything in inference mode + with torch.inference_mode(): + # step environment + dones = env.step(actions)[-2] + + # observations + # -- end-effector frame + ee_frame_sensor = env.unwrapped.scene["ee_frame"] + tcp_rest_position = ( + ee_frame_sensor.data.target_pos_w.torch[..., 0, :].clone() - env.unwrapped.scene.env_origins + ) + tcp_rest_orientation = ee_frame_sensor.data.target_quat_w.torch[..., 0, :].clone() + # -- object frame + object_data: DeformableObjectData = env.unwrapped.scene["deformable"].data + object_position = object_data.root_pos_w.torch - env.unwrapped.scene.env_origins + object_position += object_local_grasp_position + + # -- target object frame + desired_position = env.unwrapped.command_manager.get_command("deformable_pose")[..., :3] + + # advance state machine + actions = pick_sm.compute( + torch.cat([tcp_rest_position, tcp_rest_orientation], dim=-1), + torch.cat([object_position, object_grasp_orientation], dim=-1), + torch.cat([desired_position, desired_orientation], dim=-1), + ) + + # reset state machine + if dones.any(): + pick_sm.reset_idx(dones.nonzero(as_tuple=False).squeeze(-1)) + + # close the environment + env.close() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/environments/state_machine/lift_teddy_bear.py b/simulation/modules/IsaacLab/scripts/environments/state_machine/lift_teddy_bear.py new file mode 100644 index 0000000000000000000000000000000000000000..0aa8e0c33504133b62cae312b0fed50dd5ad506b --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/environments/state_machine/lift_teddy_bear.py @@ -0,0 +1,337 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Script to demonstrate lifting a deformable object with a robotic arm. + +The state machine is implemented in the kernel function `infer_state_machine`. +It uses the `warp` library to run the state machine in parallel on the GPU. + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/state_machine/lift_teddy_bear.py + +""" + +"""Launch Omniverse Toolkit first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Pick and lift a teddy bear with a robotic arm.") +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to simulate.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(headless=args_cli.headless) +simulation_app = app_launcher.app + +# disable metrics assembler due to scene graph instancing +from isaacsim.core.experimental.utils.app import enable_extension + +enable_extension("omni.usd.metrics.assembler.ui", enabled=False) + +"""Rest everything else.""" + +from collections.abc import Sequence + +import gymnasium as gym +import torch +import warp as wp + +from isaaclab.assets.rigid_object.rigid_object_data import RigidObjectData + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.manager_based.manipulation.lift.lift_env_cfg import LiftEnvCfg +from isaaclab_tasks.utils.parse_cfg import parse_env_cfg + +# initialize warp +wp.init() + + +class GripperState: + """States for the gripper.""" + + OPEN = wp.constant(1.0) + CLOSE = wp.constant(-1.0) + + +class PickSmState: + """States for the pick state machine.""" + + REST = wp.constant(0) + APPROACH_ABOVE_OBJECT = wp.constant(1) + APPROACH_OBJECT = wp.constant(2) + GRASP_OBJECT = wp.constant(3) + LIFT_OBJECT = wp.constant(4) + OPEN_GRIPPER = wp.constant(5) + + +class PickSmWaitTime: + """Additional wait times (in s) for states for before switching.""" + + REST = wp.constant(0.2) + APPROACH_ABOVE_OBJECT = wp.constant(0.5) + APPROACH_OBJECT = wp.constant(0.6) + GRASP_OBJECT = wp.constant(0.6) + LIFT_OBJECT = wp.constant(1.0) + OPEN_GRIPPER = wp.constant(0.0) + + +@wp.func +def distance_below_threshold(current_pos: wp.vec3, desired_pos: wp.vec3, threshold: float) -> bool: + return wp.length(current_pos - desired_pos) < threshold + + +@wp.kernel +def infer_state_machine( + dt: wp.array(dtype=float), + sm_state: wp.array(dtype=int), + sm_wait_time: wp.array(dtype=float), + ee_pose: wp.array(dtype=wp.transform), + object_pose: wp.array(dtype=wp.transform), + des_object_pose: wp.array(dtype=wp.transform), + des_ee_pose: wp.array(dtype=wp.transform), + gripper_state: wp.array(dtype=float), + offset: wp.array(dtype=wp.transform), + position_threshold: float, +): + # retrieve thread id + tid = wp.tid() + # retrieve state machine state + state = sm_state[tid] + # decide next state + if state == PickSmState.REST: + des_ee_pose[tid] = ee_pose[tid] + gripper_state[tid] = GripperState.OPEN + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.REST: + # move to next state and reset wait time + sm_state[tid] = PickSmState.APPROACH_ABOVE_OBJECT + sm_wait_time[tid] = 0.0 + elif state == PickSmState.APPROACH_ABOVE_OBJECT: + des_ee_pose[tid] = wp.transform_multiply(offset[tid], object_pose[tid]) + gripper_state[tid] = GripperState.OPEN + if distance_below_threshold( + wp.transform_get_translation(ee_pose[tid]), + wp.transform_get_translation(des_ee_pose[tid]), + position_threshold, + ): + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.APPROACH_OBJECT: + # move to next state and reset wait time + sm_state[tid] = PickSmState.APPROACH_OBJECT + sm_wait_time[tid] = 0.0 + elif state == PickSmState.APPROACH_OBJECT: + des_ee_pose[tid] = object_pose[tid] + gripper_state[tid] = GripperState.OPEN + if distance_below_threshold( + wp.transform_get_translation(ee_pose[tid]), + wp.transform_get_translation(des_ee_pose[tid]), + position_threshold, + ): + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.APPROACH_OBJECT: + # move to next state and reset wait time + sm_state[tid] = PickSmState.GRASP_OBJECT + sm_wait_time[tid] = 0.0 + elif state == PickSmState.GRASP_OBJECT: + des_ee_pose[tid] = object_pose[tid] + gripper_state[tid] = GripperState.CLOSE + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.GRASP_OBJECT: + # move to next state and reset wait time + sm_state[tid] = PickSmState.LIFT_OBJECT + sm_wait_time[tid] = 0.0 + elif state == PickSmState.LIFT_OBJECT: + des_ee_pose[tid] = des_object_pose[tid] + gripper_state[tid] = GripperState.CLOSE + if distance_below_threshold( + wp.transform_get_translation(ee_pose[tid]), + wp.transform_get_translation(des_ee_pose[tid]), + position_threshold, + ): + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.LIFT_OBJECT: + # move to next state and reset wait time + sm_state[tid] = PickSmState.OPEN_GRIPPER + sm_wait_time[tid] = 0.0 + elif state == PickSmState.OPEN_GRIPPER: + # des_ee_pose[tid] = object_pose[tid] + gripper_state[tid] = GripperState.OPEN + # wait for a while + if sm_wait_time[tid] >= PickSmWaitTime.OPEN_GRIPPER: + # move to next state and reset wait time + sm_state[tid] = PickSmState.OPEN_GRIPPER + sm_wait_time[tid] = 0.0 + # increment wait time + sm_wait_time[tid] = sm_wait_time[tid] + dt[tid] + + +class PickAndLiftSm: + """A simple state machine in a robot's task space to pick and lift an object. + + The state machine is implemented as a warp kernel. It takes in the current state of + the robot's end-effector and the object, and outputs the desired state of the robot's + end-effector and the gripper. The state machine is implemented as a finite state + machine with the following states: + + 1. REST: The robot is at rest. + 2. APPROACH_ABOVE_OBJECT: The robot moves above the object. + 3. APPROACH_OBJECT: The robot moves to the object. + 4. GRASP_OBJECT: The robot grasps the object. + 5. LIFT_OBJECT: The robot lifts the object to the desired pose. This is the final state. + """ + + def __init__(self, dt: float, num_envs: int, device: torch.device | str = "cpu", position_threshold=0.01): + """Initialize the state machine. + + Args: + dt: The environment time step. + num_envs: The number of environments to simulate. + device: The device to run the state machine on. + """ + # save parameters + self.dt = float(dt) + self.num_envs = num_envs + self.device = device + self.position_threshold = position_threshold + # initialize state machine + self.sm_dt = torch.full((self.num_envs,), self.dt, device=self.device) + self.sm_state = torch.full((self.num_envs,), 0, dtype=torch.int32, device=self.device) + self.sm_wait_time = torch.zeros((self.num_envs,), device=self.device) + + # desired state + self.des_ee_pose = torch.zeros((self.num_envs, 7), device=self.device) + self.des_gripper_state = torch.full((self.num_envs,), 0.0, device=self.device) + + # approach above object offset + self.offset = torch.zeros((self.num_envs, 7), device=self.device) + self.offset[:, 2] = 0.2 + self.offset[:, -1] = 1.0 # warp expects quaternion as (x, y, z, w) + + # convert to warp + self.sm_dt_wp = wp.from_torch(self.sm_dt, wp.float32) + self.sm_state_wp = wp.from_torch(self.sm_state, wp.int32) + self.sm_wait_time_wp = wp.from_torch(self.sm_wait_time, wp.float32) + self.des_ee_pose_wp = wp.from_torch(self.des_ee_pose, wp.transform) + self.des_gripper_state_wp = wp.from_torch(self.des_gripper_state, wp.float32) + self.offset_wp = wp.from_torch(self.offset, wp.transform) + + def reset_idx(self, env_ids: Sequence[int] = None): + """Reset the state machine.""" + if env_ids is None: + env_ids = slice(None) + self.sm_state[env_ids] = 0 + self.sm_wait_time[env_ids] = 0.0 + + def compute(self, ee_pose: torch.Tensor, object_pose: torch.Tensor, des_object_pose: torch.Tensor): + """Compute the desired state of the robot's end-effector and the gripper.""" + + # convert to warp + ee_pose_wp = wp.from_torch(ee_pose.contiguous(), wp.transform) + object_pose_wp = wp.from_torch(object_pose.contiguous(), wp.transform) + des_object_pose_wp = wp.from_torch(des_object_pose.contiguous(), wp.transform) + + # run state machine + wp.launch( + kernel=infer_state_machine, + dim=self.num_envs, + inputs=[ + self.sm_dt_wp, + self.sm_state_wp, + self.sm_wait_time_wp, + ee_pose_wp, + object_pose_wp, + des_object_pose_wp, + self.des_ee_pose_wp, + self.des_gripper_state_wp, + self.offset_wp, + self.position_threshold, + ], + device=self.device, + ) + + # convert to torch + return torch.cat([self.des_ee_pose, self.des_gripper_state.unsqueeze(-1)], dim=-1) + + +def main(): + # parse configuration + env_cfg: LiftEnvCfg = parse_env_cfg( + "Isaac-Lift-Teddy-Bear-Franka-IK-Abs-v0", + device=args_cli.device, + num_envs=args_cli.num_envs, + ) + + env_cfg.viewer.eye = (2.1, 1.0, 1.3) + + # create environment + env = gym.make("Isaac-Lift-Teddy-Bear-Franka-IK-Abs-v0", cfg=env_cfg) + # reset environment at start + env.reset() + + # create action buffers (position + quaternion) + actions = torch.zeros(env.unwrapped.action_space.shape, device=env.unwrapped.device) + actions[:, 3] = 1.0 + # desired rotation after grasping + desired_orientation = torch.zeros((env.unwrapped.num_envs, 4), device=env.unwrapped.device) + desired_orientation[:, 1] = 1.0 + + object_grasp_orientation = torch.zeros((env.unwrapped.num_envs, 4), device=env.unwrapped.device) + # z-axis pointing down and 45 degrees rotation + object_grasp_orientation[:, 1] = 0.9238795 + object_grasp_orientation[:, 2] = -0.3826834 + object_local_grasp_position = torch.tensor([0.02, -0.08, 0.0], device=env.unwrapped.device) + + # create state machine + pick_sm = PickAndLiftSm(env_cfg.sim.dt * env_cfg.decimation, env.unwrapped.num_envs, env.unwrapped.device) + + while simulation_app.is_running(): + # run everything in inference mode + with torch.inference_mode(): + # step environment + dones = env.step(actions)[-2] + + # observations + # -- end-effector frame + ee_frame_sensor = env.unwrapped.scene["ee_frame"] + tcp_rest_position = ( + ee_frame_sensor.data.target_pos_w.torch[..., 0, :].clone() - env.unwrapped.scene.env_origins + ) + tcp_rest_orientation = ee_frame_sensor.data.target_quat_w.torch[..., 0, :].clone() + # -- object frame + object_data: RigidObjectData = env.unwrapped.scene["object"].data + object_position = object_data.root_pos_w.torch - env.unwrapped.scene.env_origins + object_position += object_local_grasp_position + + # -- target object frame + desired_position = env.unwrapped.command_manager.get_command("object_pose")[..., :3] + + # advance state machine + actions = pick_sm.compute( + torch.cat([tcp_rest_position, tcp_rest_orientation], dim=-1), + torch.cat([object_position, object_grasp_orientation], dim=-1), + torch.cat([desired_position, desired_orientation], dim=-1), + ) + + # reset state machine + if dones.any(): + pick_sm.reset_idx(dones.nonzero(as_tuple=False).squeeze(-1)) + + # close the environment + env.close() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/environments/state_machine/open_cabinet_sm.py b/simulation/modules/IsaacLab/scripts/environments/state_machine/open_cabinet_sm.py new file mode 100644 index 0000000000000000000000000000000000000000..b94bbd58f7b7fa528db5913fb6f6f6daab6e62ad --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/environments/state_machine/open_cabinet_sm.py @@ -0,0 +1,330 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Script to run an environment with a cabinet opening state machine. + +The state machine is implemented in the kernel function `infer_state_machine`. +It uses the `warp` library to run the state machine in parallel on the GPU. + +.. code-block:: bash + + ./isaaclab.sh -p scripts/environments/state_machine/open_cabinet_sm.py --num_envs 32 --viz kit + +""" + +"""Launch Omniverse Toolkit first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Pick and lift state machine for cabinet environments.") +parser.add_argument( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything else.""" + +from collections.abc import Sequence + +import gymnasium as gym +import torch +import warp as wp + +from isaaclab.sensors import FrameTransformer + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.manager_based.manipulation.cabinet.cabinet_env_cfg import CabinetEnvCfg +from isaaclab_tasks.utils.parse_cfg import parse_env_cfg + +# initialize warp +wp.init() + + +class GripperState: + """States for the gripper.""" + + OPEN = wp.constant(1.0) + CLOSE = wp.constant(-1.0) + + +class OpenDrawerSmState: + """States for the cabinet drawer opening state machine.""" + + REST = wp.constant(0) + APPROACH_INFRONT_HANDLE = wp.constant(1) + APPROACH_HANDLE = wp.constant(2) + GRASP_HANDLE = wp.constant(3) + OPEN_DRAWER = wp.constant(4) + RELEASE_HANDLE = wp.constant(5) + + +class OpenDrawerSmWaitTime: + """Additional wait times (in s) for states for before switching.""" + + REST = wp.constant(0.5) + APPROACH_INFRONT_HANDLE = wp.constant(1.25) + APPROACH_HANDLE = wp.constant(1.0) + GRASP_HANDLE = wp.constant(1.0) + OPEN_DRAWER = wp.constant(3.0) + RELEASE_HANDLE = wp.constant(0.2) + + +@wp.func +def distance_below_threshold(current_pos: wp.vec3, desired_pos: wp.vec3, threshold: float) -> bool: + return wp.length(current_pos - desired_pos) < threshold + + +@wp.kernel +def infer_state_machine( + dt: wp.array(dtype=float), + sm_state: wp.array(dtype=int), + sm_wait_time: wp.array(dtype=float), + ee_pose: wp.array(dtype=wp.transform), + handle_pose: wp.array(dtype=wp.transform), + des_ee_pose: wp.array(dtype=wp.transform), + gripper_state: wp.array(dtype=float), + handle_approach_offset: wp.array(dtype=wp.transform), + handle_grasp_offset: wp.array(dtype=wp.transform), + drawer_opening_rate: wp.array(dtype=wp.transform), + position_threshold: float, +): + # retrieve thread id + tid = wp.tid() + # retrieve state machine state + state = sm_state[tid] + # decide next state + if state == OpenDrawerSmState.REST: + des_ee_pose[tid] = ee_pose[tid] + gripper_state[tid] = GripperState.OPEN + # wait for a while + if sm_wait_time[tid] >= OpenDrawerSmWaitTime.REST: + # move to next state and reset wait time + sm_state[tid] = OpenDrawerSmState.APPROACH_INFRONT_HANDLE + sm_wait_time[tid] = 0.0 + elif state == OpenDrawerSmState.APPROACH_INFRONT_HANDLE: + des_ee_pose[tid] = wp.transform_multiply(handle_approach_offset[tid], handle_pose[tid]) + gripper_state[tid] = GripperState.OPEN + if distance_below_threshold( + wp.transform_get_translation(ee_pose[tid]), + wp.transform_get_translation(des_ee_pose[tid]), + position_threshold, + ): + # wait for a while + if sm_wait_time[tid] >= OpenDrawerSmWaitTime.APPROACH_INFRONT_HANDLE: + # move to next state and reset wait time + sm_state[tid] = OpenDrawerSmState.APPROACH_HANDLE + sm_wait_time[tid] = 0.0 + elif state == OpenDrawerSmState.APPROACH_HANDLE: + des_ee_pose[tid] = handle_pose[tid] + gripper_state[tid] = GripperState.OPEN + if distance_below_threshold( + wp.transform_get_translation(ee_pose[tid]), + wp.transform_get_translation(des_ee_pose[tid]), + position_threshold, + ): + # wait for a while + if sm_wait_time[tid] >= OpenDrawerSmWaitTime.APPROACH_HANDLE: + # move to next state and reset wait time + sm_state[tid] = OpenDrawerSmState.GRASP_HANDLE + sm_wait_time[tid] = 0.0 + elif state == OpenDrawerSmState.GRASP_HANDLE: + des_ee_pose[tid] = wp.transform_multiply(handle_grasp_offset[tid], handle_pose[tid]) + gripper_state[tid] = GripperState.CLOSE + # wait for a while + if sm_wait_time[tid] >= OpenDrawerSmWaitTime.GRASP_HANDLE: + # move to next state and reset wait time + sm_state[tid] = OpenDrawerSmState.OPEN_DRAWER + sm_wait_time[tid] = 0.0 + elif state == OpenDrawerSmState.OPEN_DRAWER: + des_ee_pose[tid] = wp.transform_multiply(drawer_opening_rate[tid], handle_pose[tid]) + gripper_state[tid] = GripperState.CLOSE + # wait for a while + if sm_wait_time[tid] >= OpenDrawerSmWaitTime.OPEN_DRAWER: + # move to next state and reset wait time + sm_state[tid] = OpenDrawerSmState.RELEASE_HANDLE + sm_wait_time[tid] = 0.0 + elif state == OpenDrawerSmState.RELEASE_HANDLE: + des_ee_pose[tid] = ee_pose[tid] + gripper_state[tid] = GripperState.CLOSE + # wait for a while + if sm_wait_time[tid] >= OpenDrawerSmWaitTime.RELEASE_HANDLE: + # move to next state and reset wait time + sm_state[tid] = OpenDrawerSmState.RELEASE_HANDLE + sm_wait_time[tid] = 0.0 + # increment wait time + sm_wait_time[tid] = sm_wait_time[tid] + dt[tid] + + +class OpenDrawerSm: + """A simple state machine in a robot's task space to open a drawer in the cabinet. + + The state machine is implemented as a warp kernel. It takes in the current state of + the robot's end-effector and the object, and outputs the desired state of the robot's + end-effector and the gripper. The state machine is implemented as a finite state + machine with the following states: + + 1. REST: The robot is at rest. + 2. APPROACH_HANDLE: The robot moves towards the handle of the drawer. + 3. GRASP_HANDLE: The robot grasps the handle of the drawer. + 4. OPEN_DRAWER: The robot opens the drawer. + 5. RELEASE_HANDLE: The robot releases the handle of the drawer. This is the final state. + """ + + def __init__(self, dt: float, num_envs: int, device: torch.device | str = "cpu", position_threshold=0.01): + """Initialize the state machine. + + Args: + dt: The environment time step. + num_envs: The number of environments to simulate. + device: The device to run the state machine on. + """ + # save parameters + self.dt = float(dt) + self.num_envs = num_envs + self.device = device + self.position_threshold = position_threshold + # initialize state machine + self.sm_dt = torch.full((self.num_envs,), self.dt, device=self.device) + self.sm_state = torch.full((self.num_envs,), 0, dtype=torch.int32, device=self.device) + self.sm_wait_time = torch.zeros((self.num_envs,), device=self.device) + + # desired state + self.des_ee_pose = torch.zeros((self.num_envs, 7), device=self.device) + self.des_gripper_state = torch.full((self.num_envs,), 0.0, device=self.device) + + # approach in front of the handle + self.handle_approach_offset = torch.zeros((self.num_envs, 7), device=self.device) + self.handle_approach_offset[:, 0] = -0.1 + self.handle_approach_offset[:, -1] = 1.0 # warp expects quaternion as (x, y, z, w) + + # handle grasp offset + self.handle_grasp_offset = torch.zeros((self.num_envs, 7), device=self.device) + self.handle_grasp_offset[:, 0] = 0.025 + self.handle_grasp_offset[:, -1] = 1.0 # warp expects quaternion as (x, y, z, w) + + # drawer opening rate + self.drawer_opening_rate = torch.zeros((self.num_envs, 7), device=self.device) + self.drawer_opening_rate[:, 0] = -0.015 + self.drawer_opening_rate[:, -1] = 1.0 # warp expects quaternion as (x, y, z, w) + + # convert to warp + self.sm_dt_wp = wp.from_torch(self.sm_dt, wp.float32) + self.sm_state_wp = wp.from_torch(self.sm_state, wp.int32) + self.sm_wait_time_wp = wp.from_torch(self.sm_wait_time, wp.float32) + self.des_ee_pose_wp = wp.from_torch(self.des_ee_pose, wp.transform) + self.des_gripper_state_wp = wp.from_torch(self.des_gripper_state, wp.float32) + self.handle_approach_offset_wp = wp.from_torch(self.handle_approach_offset, wp.transform) + self.handle_grasp_offset_wp = wp.from_torch(self.handle_grasp_offset, wp.transform) + self.drawer_opening_rate_wp = wp.from_torch(self.drawer_opening_rate, wp.transform) + + def reset_idx(self, env_ids: Sequence[int] | None = None): + """Reset the state machine.""" + if env_ids is None: + env_ids = slice(None) + # reset state machine + self.sm_state[env_ids] = 0 + self.sm_wait_time[env_ids] = 0.0 + + def compute(self, ee_pose: torch.Tensor, handle_pose: torch.Tensor): + """Compute the desired state of the robot's end-effector and the gripper.""" + # convert to warp + ee_pose_wp = wp.from_torch(ee_pose.contiguous(), wp.transform) + handle_pose_wp = wp.from_torch(handle_pose.contiguous(), wp.transform) + + # run state machine + wp.launch( + kernel=infer_state_machine, + dim=self.num_envs, + inputs=[ + self.sm_dt_wp, + self.sm_state_wp, + self.sm_wait_time_wp, + ee_pose_wp, + handle_pose_wp, + self.des_ee_pose_wp, + self.des_gripper_state_wp, + self.handle_approach_offset_wp, + self.handle_grasp_offset_wp, + self.drawer_opening_rate_wp, + self.position_threshold, + ], + device=self.device, + ) + + # convert to torch + return torch.cat([self.des_ee_pose, self.des_gripper_state.unsqueeze(-1)], dim=-1) + + +def main(): + # parse configuration + env_cfg: CabinetEnvCfg = parse_env_cfg( + "Isaac-Open-Drawer-Franka-IK-Abs-v0", + device=args_cli.device, + num_envs=args_cli.num_envs, + use_fabric=not args_cli.disable_fabric, + ) + # create environment + env = gym.make("Isaac-Open-Drawer-Franka-IK-Abs-v0", cfg=env_cfg) + # reset environment at start + env.reset() + + # create action buffers (position + quaternion) + actions = torch.zeros(env.unwrapped.action_space.shape, device=env.unwrapped.device) + actions[:, 3] = 1.0 + # desired object orientation (we only do position control of object) + desired_orientation = torch.zeros((env.unwrapped.num_envs, 4), device=env.unwrapped.device) + desired_orientation[:, 1] = 1.0 + # create state machine + open_sm = OpenDrawerSm(env_cfg.sim.dt * env_cfg.decimation, env.unwrapped.num_envs, env.unwrapped.device) + + while simulation_app.is_running(): + # run everything in inference mode + with torch.inference_mode(): + # step environment + dones = env.step(actions)[-2] + + # observations + # -- end-effector frame + ee_frame_tf: FrameTransformer = env.unwrapped.scene["ee_frame"] + tcp_rest_position = ee_frame_tf.data.target_pos_w.torch[..., 0, :].clone() - env.unwrapped.scene.env_origins + tcp_rest_orientation = ee_frame_tf.data.target_quat_w.torch[..., 0, :].clone() + # -- handle frame + cabinet_frame_tf: FrameTransformer = env.unwrapped.scene["cabinet_frame"] + cabinet_position = ( + cabinet_frame_tf.data.target_pos_w.torch[..., 0, :].clone() - env.unwrapped.scene.env_origins + ) + cabinet_orientation = cabinet_frame_tf.data.target_quat_w.torch[..., 0, :].clone() + + # advance state machine + actions = open_sm.compute( + torch.cat([tcp_rest_position, tcp_rest_orientation], dim=-1), + torch.cat([cabinet_position, cabinet_orientation], dim=-1), + ) + + # reset state machine + if dones.any(): + open_sm.reset_idx(dones.nonzero(as_tuple=False).squeeze(-1)) + + # close the environment + env.close() + + +if __name__ == "__main__": + # run the main execution + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/environments/teleoperation/teleop_replay_agent.py b/simulation/modules/IsaacLab/scripts/environments/teleoperation/teleop_replay_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..2b8ffe51d63da48c33e38cbf1741cc18d108bb78 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/environments/teleoperation/teleop_replay_agent.py @@ -0,0 +1,1401 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""CI/automation entry point for replaying captured Isaac Teleop sessions. + +This is the non-interactive counterpart to ``teleop_se3_agent.py``. It builds +a teleop environment, attaches an :class:`~isaaclab_teleop.IsaacTeleopDevice` +configured in :class:`isacteleop.teleop_session_manager.SessionMode.REPLAY`, +and pumps the simulation loop until the recorded operator presses STOP (or +``--max_replay_duration_s`` elapses, or Kit is closed). The user-journey +teleop script remains ``teleop_se3_agent.py``. + +Inputs: + ``--replay_file`` is an MCAP capture produced by Isaac Teleop's + ``McapRecordingConfig`` path (typically written by ``record_demos.py + --mcap_record_path``). The recorder lays down per-tracker flatbuffer + messages (head / hands / controllers) plus the ``_teleop_control`` + ``MessageChannelTracker`` that captured the operator's START / STOP / + RESET gestures. TeleopCore's + :class:`~isacteleop.deviceio_session.ReplaySession` re-emits all of + them on the same monotonic-time cadence they were recorded on, so + :func:`~isaaclab_teleop.poll_control_events` returns the same edges + here that ``record_demos.py``'s loop saw at recording time. + +Gating: + The env-step loop mirrors ``teleop_se3_agent.py``: each iteration + calls :meth:`IsaacTeleopDevice.advance` and + :func:`~isaaclab_teleop.poll_control_events`, gates ``env.step()`` on + ``ctrl.is_active`` (so pre-START operator setup frames are rendered + without stepping), and handles mid-demo ``ctrl.should_reset`` events + by running the full sim/env/teleop reset cycle. + +End-of-replay termination: + Four distinct signals end the current run by breaking out of the + inner loop. ``_run_single_replay`` returns its populated + :class:`_RunStats`, and the outer batch driver in :func:`main` + moves on to the next replay (or returns from ``main`` when the + batch is done; ``__main__`` then calls ``simulation_app.close()``). + The signals are: + + 1. **The recorded operator STOP**, replayed via the + ``_teleop_control`` ``MessageChannelTracker`` at the same + recording-frame index it was captured at -- ``ctrl.is_active`` + transitions True->False on that frame. + 2. **The env's success condition firing for + ``--num_success_steps`` consecutive steps**, the natural end of + a ``record_demos.py``-style capture. Post-success MCAP frames + are operator wind-down (releases, idle drift) that we have no + use for in replay, so we skip the ``_handle_reset`` cycle the + live agent would do. + 3. **A task-specific failure term** (``terminated`` or ``truncated`` + from ``env.step``) -- the recorded trajectory did not reproduce; + the operator has no agency to recover during replay. + 4. **Wall-clock ``--max_replay_duration_s`` safety cap**, for + recordings that produce neither a STOP, a success, nor a failure + within the configured window. + + With ``--num_replays N > 1`` each run is independently terminated by + one of the four signals above; the agent then rebuilds the + :class:`IsaacTeleopDevice` (reopening the MCAP at frame 0) and runs + again. The USD stage is loaded only once. + +Stats output: + Every iteration where ``env.step()`` actually ran contributes one + CPU frame-time sample (``time.perf_counter()`` delta in ms). Pre- + START render-only frames, warmup ticks, and post-quit render-only + spin-down are excluded so the resulting numbers reflect the + steady-state replay workload rather than agent bookkeeping + overhead. Per-run samples are summarised into mean / p50 / p90 / + p95 / p99 / min / max / stddev (under ``cpu_frame_time_ms``) plus + derived FPS metrics (under ``fps``). The two blocks measure the + same ``env.step`` event and stay self-consistent: ``fps.mean`` + equals ``1000 / cpu_frame_time_ms.mean`` (harmonic mean of FPS + = total frames / total step time). Kit's HUD displays the render + rate, which is this FPS multiplied by ``decimation / + render_interval`` (Kit pumps multiple frames per ``env.step``); + derive that from the env config if you need it. + + Each active iteration also emits one ``GpuStatsProvider.sample()`` + call. The default :class:`NvmlGpuStatsProvider` snapshots GPU + utilization (%) and used memory (MB) via ``pynvml``, summarised + under ``gpu_stats`` with the same percentile shape as + ``cpu_frame_time_ms``. It soft-fails when ``nvidia-ml-py`` is + missing or the driver is unreachable (``gpu_stats.available = + false`` + reason). Renderer-specific providers (Kit viewport + telemetry, Newton, ...) can be slotted in by implementing the + :class:`GpuStatsProvider` Protocol. + + A multi-run batch aggregates by taking the mean-of-means, + mean-of-p90s, etc. across runs. + + A one-line-per-run stdout summary is always printed at the end of + the batch. Pass ``--stats_output_file `` to additionally + persist the report as JSON. Schema (schema_version 1):: + + { + "schema_version": 1, + "task": "Isaac-PickPlace-GR1T2-Abs-v0", + "replay_file": "/tmp/pickplace_gr1t2.mcap", + "num_replays": 5, + "outcomes": {"success": 4, "failure": 1, "incomplete": 0, "timeout": 0}, + "success_rate": 0.8, + "runs": [ + { + "run_index": 0, + "outcome": "success", + "active_iterations": 322, + "active_duration_s": 21.503, + "success_step_count": 1, + "cpu_frame_time_ms": { + "mean": ..., "p50": ..., "p90": ..., "p95": ..., "p99": ..., + "min": ..., "max": ..., "stddev": ..., "n": ... + }, + "fps": {"mean": ..., "min_instantaneous": ..., "max_instantaneous": ...}, + "gpu_stats": { + "backend": "nvml", "available": True, + "device_index": 0, "device_name": ..., "memory_total_mb": ..., + "utilization_percent": {}, + "memory_used_mb": {} + } + } + ], + "aggregate": { + "cpu_frame_time_ms": {"mean_of_means": ..., "mean_of_p90s": ..., + "mean_of_p99s": ..., "min_overall": ..., + "max_overall": ...}, + "fps": {"mean_of_means": ...} + } + } + +Exit codes: + The process exits with a status code that CI can branch on. With + ``--num_replays N`` the worst-of-N outcome wins (precedence + ``timeout > failure > incomplete > success``): + + * ``0`` -- every run reproduced the recording (``success_term`` + fired on each run). + * ``1`` -- one or more runs terminated/truncated mid-trajectory, + or finished without any explicit terminator firing. + * ``2`` -- one or more runs hit ``--max_replay_duration_s``. + +Warmup: + Before stepping the env, the agent waits deterministically for Kit + to finish loading the USD stage by polling + ``omni.usd.UsdContext.get_stage_loading_status()`` until no assets + are pending (bounded by ``--max_stage_load_wait_s`` as a safety net). + It then pumps a fixed number of additional renderer-settle frames so + shaders / articulation views finish warming up before any action + lands. ``--replay_start_delay_s`` is available as an optional + wall-clock buffer on top of the deterministic wait for hardware + that needs more grace. During warmup the agent does not call + :meth:`IsaacTeleopDevice.advance`, so ``ReplaySession.update()`` + does not advance through the MCAP. + +XR-active replay: + Pass ``--cloudxr_env `` (and optionally + ``--no-auto_launch_cloudxr``) to auto-spawn the CloudXR runtime and + engage Kit's XR pipeline during replay. ``--cloudxr_env`` mirrors + the flag on ``record_demos.py`` and accepts the same ``cloudxrjs`` + / ``avp`` shorthands. This is required (not optional) for two + distinct reasons: + + A. **Performance parity with live teleop.** A pure-replay run (no + XR, no CloudXR) skips the entire Kit XR rendering pipeline, + so frame timings, render load, GPU/CPU contention, and any + XR-side bottlenecks do not appear -- a captured trajectory + that replayed at 90Hz under those conditions could easily run + at 30Hz once XR is actually active. For perf regression or + benchmarking the replay loop must reproduce the same Kit + configuration the original recording ran under. + + B. **Correct ``world_T_anchor`` for playback.** The recorded + tracker stream (head / hands / controllers) lives in + OpenXR-local space; the world-frame poses the env consumes + come from ``world_T_anchor @ oxr_pose``. With XR active, + :class:`~isaaclab_teleop.XrAnchorManager` resolves + ``world_T_anchor`` through ``XrAnchorSynchronizer`` (the same + path used at record time), so the live anchor semantics -- + including any dynamic-anchor following of a prim and runtime + recentering -- are reproduced. Without XR active, the manager + falls back to the static :class:`~isaaclab_teleop.XrCfg` + values, which only happen to match record-time semantics when + the anchor never moved. + + The full incantation also needs ``AppLauncher``'s ``--xr`` flag + plus a few Kit-side carb settings to flip the AR profile and load + the teleop XR bridge (the replay path skips both for the + headless-CI default; we have not yet promoted them to a single + ``--xr_active`` knob):: + + ./isaaclab.sh -p teleop_replay_agent.py \\ + --task --replay_file \\ + --xr --device cuda:0 \\ + --cloudxr_env cloudxrjs \\ + --kit_args="--/xr/profile/ar/enabled=true \\ + --enable isaacsim.kit.xr.teleop.bridge \\ + --/persistent/xr/openxr/disableInputBindings=true" + + The headset is purely a viewer / anchor source -- the recorded MCAP + remains the sole source of action; live controller input from the + spectator's headset does not displace the replayed trajectory. + + Multi-run note: ``--num_replays > 1`` IS supported in XR-active + mode. The CloudXR runtime is launched once at the agent (batch) + scope and shared across runs (``_maybe_launch_cloudxr``); each + per-run :class:`~isaaclab_teleop.IsaacTeleopDevice` is constructed + with ``auto_launch_cloudxr=False`` so the per-run lifecycle does + not stop the runtime on teardown. Only the per-run + ``TeleopSession`` is torn down between replays; Kit's OpenXR + instance/session stay alive. +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser( + description=( + "Replay a captured Isaac Teleop MCAP session against an Isaac Lab environment. " + "CI/automation entry point; for interactive teleoperation see teleop_se3_agent.py." + ) +) +parser.add_argument("--task", type=str, required=True, help="Name of the task.") +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to simulate.") +parser.add_argument( + "--replay_file", + type=str, + required=True, + help="Absolute path to the Isaac Teleop MCAP capture to replay.", +) +parser.add_argument( + "--num_success_steps", + type=int, + default=1, + help=( + "Number of consecutive steps the task success term must hold before declaring success and" + " resetting the env. Mirrors the equivalent flag in record_demos.py." + ), +) +parser.add_argument( + "--max_replay_duration_s", + type=float, + default=600.0, + help=( + "Maximum wall-clock seconds to keep a single replay running before ending it with the" + " ``timeout`` outcome, measured from the end of the warmup window. Safety net for" + " malformed MCAPs that omit the operator's STOP gesture -- with a clean recording the" + " agent ends the run on the replayed STOP edge well before this cap. Applies per run when" + " ``--num_replays > 1``. Default is 600s (10 min)." + ), +) +parser.add_argument( + "--num_replays", + type=int, + default=1, + help=( + "Number of times to replay the MCAP back-to-back. Each replay rebuilds the IsaacTeleopDevice" + " (re-opens the MCAP at frame 0) and resets the env in place without reloading Kit; the" + " CloudXR runtime and Kit's OpenXR session stay alive across runs so subsequent replays" + " start ~instantly. Per-run and aggregated success/failure rates are reported in the stats" + " summary; the exit code reflects the worst outcome across runs. Default 1." + ), +) +parser.add_argument( + "--stats_output_file", + type=str, + default=None, + help=( + "Optional path to write a JSON stats report (CPU frame time, FPS, outcome) to after the" + " run(s) complete. When omitted only a stdout summary is printed. Schema is documented" + " in the 'Stats output' section of the script's module docstring." + ), +) +parser.add_argument( + "--replay_start_delay_s", + type=float, + default=0.0, + help=( + "Optional wall-clock buffer added on top of the deterministic stage-load wait." + " The agent always blocks until omni.usd reports no assets pending and then renders a" + " fixed number of settle frames before consuming MCAP frames; this flag inserts an" + " additional render-only window after that if the deterministic check is not enough" + " for a given hardware/asset combination. Default is 0s -- bump it if you still see" + " a race after the deterministic wait." + ), +) +parser.add_argument( + "--max_stage_load_wait_s", + type=float, + default=300.0, + help=( + "Safety cap on how long to wait for omni.usd to finish loading the stage before" + " proceeding anyway. Hit only when something is misconfigured (missing asset, slow" + " Nucleus, etc.); a warning is logged and replay continues. Default is 300s." + ), +) +parser.add_argument( + "--cloudxr_env", + type=str, + default=None, + help=( + "Path to a CloudXR ``.env`` file, or a shorthand: 'cloudxrjs' (Quest/Pico) or 'avp'" + " (Apple Vision Pro). Default is None -- CloudXR is not launched. Pair with" + " AppLauncher's ``--xr`` and Kit-side AR-profile settings for spectate-on-headset" + " replay; see the script docstring for the full command." + ), +) +parser.add_argument( + "--auto_launch_cloudxr", + action=argparse.BooleanOptionalAction, + default=True, + help=( + "Auto-launch the CloudXR runtime when ``--cloudxr_env`` is set. Use" + " ``--no-auto_launch_cloudxr`` to skip the launch (e.g. when running the" + " runtime externally). Ignored when ``--cloudxr_env`` is omitted." + ), +) +AppLauncher.add_app_launcher_args(parser) +args_cli = parser.parse_args() + +app_launcher_args = vars(args_cli) +app_launcher = AppLauncher(app_launcher_args) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + + +import json +import logging +import os +import statistics +import sys +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Protocol, runtime_checkable + +import gymnasium as gym +import torch +from isaaclab_teleop import IsaacTeleopDevice, create_isaac_teleop_device, poll_control_events + +from isaaclab.devices.openxr import remove_camera_configs +from isaaclab.envs import ManagerBasedRLEnvCfg + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import parse_env_cfg + +logger = logging.getLogger(__name__) + +_CLOUDXR_ENV_SHORTHANDS: dict[str, str] = {} + + +# ---------------------------------------------------------------------- +# Perf stats: per-run collection + multi-run reporting +# ---------------------------------------------------------------------- + +_STATS_SCHEMA_VERSION = 1 +"""Bump when the JSON shape produced by :func:`_build_report` changes in a +non-additive way (renamed / removed keys). Additive changes (new optional +keys) do not require a bump.""" + + +@dataclass +class _RunStats: + """Per-replay performance + outcome record. + + ``active_frame_times_ms`` is sampled only on iterations where + ``env.step()`` actually ran (post-START, pre-terminator). Pre-START + render-only frames, warmup ticks, and post-quit render-only spin-down + are intentionally excluded so the resulting stats reflect the steady- + state replay workload rather than the agent's bookkeeping overhead. + """ + + outcome: str = "incomplete" # "success" | "failure" | "incomplete" | "timeout" + active_frame_times_ms: list[float] = field(default_factory=list) + active_duration_s: float = 0.0 + success_step_count: int = 0 # final consecutive-success counter at terminator + # Filled in at run end from ``GpuStatsProvider.summary()``. + # Defaults to ``{}`` so a run that never reached the active loop + # produces a missing-but-not-None ``"gpu_stats"`` slot. + gpu_stats: dict = field(default_factory=dict) + + def to_dict(self, run_index: int) -> dict: + cpu_stats = _compute_frame_stats(self.active_frame_times_ms) + fps_stats = _compute_fps_stats(self.active_frame_times_ms) + return { + "run_index": run_index, + "outcome": self.outcome, + "active_iterations": len(self.active_frame_times_ms), + "active_duration_s": round(self.active_duration_s, 6), + "success_step_count": self.success_step_count, + "cpu_frame_time_ms": cpu_stats, + "fps": fps_stats, + "gpu_stats": self.gpu_stats, + } + + +def _compute_frame_stats(samples_ms: list[float]) -> dict: + """Compute summary stats for a list of per-frame CPU times (in ms). + + Uses :func:`statistics.quantiles` with ``n=100, method="inclusive"`` so + the result is a stable in-process measurement with no numpy dependency. + The 99 quantile cut-points returned by ``quantiles`` are interpreted as + p1..p99; we sample p50 / p90 / p95 / p99 plus mean / min / max / + stddev / n. Handles empty (``n=0``, all numeric fields ``None``) and + single-sample (``n=1``, all numeric fields equal to the single sample, + ``stddev=0.0``) inputs without raising. + """ + n = len(samples_ms) + if n == 0: + return { + "mean": None, + "p50": None, + "p90": None, + "p95": None, + "p99": None, + "min": None, + "max": None, + "stddev": None, + "n": 0, + } + sample_min = min(samples_ms) + sample_max = max(samples_ms) + sample_mean = statistics.fmean(samples_ms) + if n == 1: + return { + "mean": sample_mean, + "p50": samples_ms[0], + "p90": samples_ms[0], + "p95": samples_ms[0], + "p99": samples_ms[0], + "min": sample_min, + "max": sample_max, + "stddev": 0.0, + "n": 1, + } + # quantiles(n=100) returns 99 cut points; cuts[i] is the (i+1)-th percentile. + cuts = statistics.quantiles(samples_ms, n=100, method="inclusive") + return { + "mean": sample_mean, + "p50": cuts[49], + "p90": cuts[89], + "p95": cuts[94], + "p99": cuts[98], + "min": sample_min, + "max": sample_max, + "stddev": statistics.stdev(samples_ms), + "n": n, + } + + +def _compute_fps_stats(samples_ms: list[float]) -> dict: + """Compute env.step-throughput FPS stats from per-step CPU times. + + All three fields are derived from the same ``samples_ms`` series + that feeds ``cpu_frame_time_ms`` and stay self-consistent with it: + ``mean == 1000 / cpu_frame_time_ms.mean`` (harmonic mean of FPS = + total frames / total step time). The harmonic mean is what + Devdeep's "use harmonic mean for FPS and it will agree with the + arithmetic mean of frame time" prescription expects -- it avoids + the upward bias of arithmetic-mean-of-instantaneous-FPS + (dominated by the fastest frames) and the downward bias of + ``n / active_duration_s`` (dragged down by inter-step + bookkeeping). + + Note that this is the ``env.step`` rate, not Kit's render rate: + Kit pumps ``cfg.decimation / cfg.sim.render_interval`` frames per + ``env.step`` call, so the HUD shows a higher number than what is + reported here. Compute the render rate as + ``fps.mean * decimation / render_interval`` from the env config + if needed. + + ``min_instantaneous`` and ``max_instantaneous`` are derived from + the slowest / fastest individual step respectively. + """ + n = len(samples_ms) + if n == 0: + return {"mean": None, "min_instantaneous": None, "max_instantaneous": None} + sample_mean_ms = statistics.fmean(samples_ms) + sample_max_ms = max(samples_ms) + sample_min_ms = min(samples_ms) + return { + "mean": 1000.0 / sample_mean_ms if sample_mean_ms > 0 else None, + "min_instantaneous": 1000.0 / sample_max_ms if sample_max_ms > 0 else None, + "max_instantaneous": 1000.0 / sample_min_ms if sample_min_ms > 0 else None, + } + + +# ============================================================================= +# GPU statistics +# ============================================================================= +# +# ``GpuStatsProvider`` is the modularity seam. The agent constructs a +# provider at the start of each run, calls :meth:`sample` once per +# active iteration, and consumes :meth:`summary` at run end to embed +# the resulting dict under ``"gpu_stats"`` in the per-run report. +# +# ``NvmlGpuStatsProvider`` (default) is renderer-agnostic: it queries +# NVML directly via ``pynvml`` and works wherever an NVIDIA driver is +# installed -- no Kit dependency, no CUDA context needed. If you swap +# the renderer out (e.g. move to a non-Kit visualization), this +# provider still works. +# +# To add a renderer-specific provider in the future (Kit viewport +# telemetry, Newton, etc.), define a class with the same +# ``sample`` / ``summary`` signature and instantiate it inside +# ``_run_single_replay`` in place of ``NvmlGpuStatsProvider``. + + +@runtime_checkable +class GpuStatsProvider(Protocol): + """Per-run GPU telemetry source. + + Renderer-agnostic interface for sampling GPU state during a + replay. Implementations are expected to be cheap on + :meth:`sample` (<<1 ms; the agent calls it once per active + iteration in the hot path) and to return a JSON-serializable + dict from :meth:`summary` matching the shape documented on the + concrete impl. + """ + + def sample(self) -> None: + """Snapshot current GPU state. Called once per active iteration.""" + ... + + def summary(self) -> dict: + """Return the aggregated stats fragment for the run, embedded + as the ``"gpu_stats"`` value in the run's report dict.""" + ... + + +class NvmlGpuStatsProvider: + """NVML-backed :class:`GpuStatsProvider`. + + Snapshots GPU utilization (%) and used memory (MB) for one + device per :meth:`sample` call via ``pynvml``. Per-call cost is + <100 us so per-frame sampling is fine at any realistic frame + rate. Soft-fails when ``pynvml`` is missing or initialization + fails (no NVIDIA driver, etc.); :meth:`sample` is then a no-op + and :meth:`summary` reports the failure reason. + + Args: + device_index: NVML device index (typically 0 for the + workstation's primary GPU). Defaults to 0. + + Summary shape on success:: + + { + "backend": "nvml", + "available": True, + "device_index": 0, + "device_name": "NVIDIA GeForce RTX 4090", + "memory_total_mb": 24564.0, + "utilization_percent": {}, + "memory_used_mb": {} + } + + On failure the ``"backend"`` / ``"available"`` fields are still + present plus a ``"reason"`` string. + """ + + def __init__(self, device_index: int = 0): + self._device_index = device_index + self._available = False + self._reason: str | None = None + self._device_name: str | None = None + self._memory_total_mb: float | None = None + self._util_samples: list[float] = [] + self._mem_used_samples_mb: list[float] = [] + try: + import pynvml + + self._pynvml = pynvml + pynvml.nvmlInit() + self._handle = pynvml.nvmlDeviceGetHandleByIndex(device_index) + self._memory_total_mb = pynvml.nvmlDeviceGetMemoryInfo(self._handle).total / (1024 * 1024) + # nvmlDeviceGetName returns bytes on older bindings and str on newer ones; coerce both. + name = pynvml.nvmlDeviceGetName(self._handle) + self._device_name = name.decode("utf-8") if isinstance(name, bytes) else str(name) + self._available = True + except ImportError: + self._reason = "pynvml not installed (`pip install nvidia-ml-py` to enable)" + except Exception as exc: + self._reason = f"NVML init failed: {exc}" + + def sample(self) -> None: + if not self._available: + return + try: + util = self._pynvml.nvmlDeviceGetUtilizationRates(self._handle) + mem = self._pynvml.nvmlDeviceGetMemoryInfo(self._handle) + self._util_samples.append(float(util.gpu)) + self._mem_used_samples_mb.append(mem.used / (1024 * 1024)) + except Exception: + # Transient NVML query failures shouldn't kill the replay loop; + # missing samples are reflected in the final ``n`` count. + pass + + def summary(self) -> dict: + if not self._available: + return {"backend": "nvml", "available": False, "reason": self._reason} + return { + "backend": "nvml", + "available": True, + "device_index": self._device_index, + "device_name": self._device_name, + "memory_total_mb": round(self._memory_total_mb, 1) if self._memory_total_mb is not None else None, + "utilization_percent": _compute_frame_stats(self._util_samples), + "memory_used_mb": _compute_frame_stats(self._mem_used_samples_mb), + } + + +def _build_report(args, all_runs: list[_RunStats]) -> dict: + """Build the structured JSON report dict from a list of completed runs.""" + outcomes_count = {"success": 0, "failure": 0, "incomplete": 0, "timeout": 0} + for r in all_runs: + outcomes_count[r.outcome] = outcomes_count.get(r.outcome, 0) + 1 + + total = max(len(all_runs), 1) + success_rate = outcomes_count.get("success", 0) / total + + run_dicts = [r.to_dict(i) for i, r in enumerate(all_runs)] + + return { + "schema_version": _STATS_SCHEMA_VERSION, + "task": args.task, + "replay_file": args.replay_file, + "num_replays": len(all_runs), + "outcomes": outcomes_count, + "success_rate": success_rate, + "runs": run_dicts, + "aggregate": _aggregate_runs(run_dicts), + } + + +def _aggregate_runs(run_dicts: list[dict]) -> dict: + """Aggregate per-run CPU / FPS stats across a multi-run batch. + + Returns ``mean_of_means``, ``p90_of_p90s``, etc. so reviewers can scan + a one-line summary without recomputing from individual runs. Runs that + produced no active frames (e.g. the recording never reached START) + contribute no samples and are skipped for that field; if no run had + samples the aggregate value is ``None``. + """ + + def _gather(key_path: list[str]) -> list[float]: + out: list[float] = [] + for run in run_dicts: + value = run + for key in key_path: + if value is None: + break + value = value.get(key) if isinstance(value, dict) else None + if isinstance(value, (int, float)): + out.append(float(value)) + return out + + def _mean_or_none(values: list[float]) -> float | None: + return statistics.fmean(values) if values else None + + def _min_or_none(values: list[float]) -> float | None: + return min(values) if values else None + + def _max_or_none(values: list[float]) -> float | None: + return max(values) if values else None + + return { + "cpu_frame_time_ms": { + "mean_of_means": _mean_or_none(_gather(["cpu_frame_time_ms", "mean"])), + "mean_of_p90s": _mean_or_none(_gather(["cpu_frame_time_ms", "p90"])), + "mean_of_p99s": _mean_or_none(_gather(["cpu_frame_time_ms", "p99"])), + "min_overall": _min_or_none(_gather(["cpu_frame_time_ms", "min"])), + "max_overall": _max_or_none(_gather(["cpu_frame_time_ms", "max"])), + }, + "fps": { + "mean_of_means": _mean_or_none(_gather(["fps", "mean"])), + }, + "gpu_stats": { + "utilization_percent": { + "mean_of_means": _mean_or_none(_gather(["gpu_stats", "utilization_percent", "mean"])), + "mean_of_p90s": _mean_or_none(_gather(["gpu_stats", "utilization_percent", "p90"])), + "max_overall": _max_or_none(_gather(["gpu_stats", "utilization_percent", "max"])), + }, + "memory_used_mb": { + "mean_of_means": _mean_or_none(_gather(["gpu_stats", "memory_used_mb", "mean"])), + "mean_of_p90s": _mean_or_none(_gather(["gpu_stats", "memory_used_mb", "p90"])), + "max_overall": _max_or_none(_gather(["gpu_stats", "memory_used_mb", "max"])), + }, + }, + } + + +def _print_stdout_summary(report: dict) -> None: + """Print a one-line-per-run summary plus an aggregate line to stdout.""" + runs = report.get("runs", []) + total = report.get("num_replays", len(runs)) + + def _fmt(value: float | None, suffix: str = "") -> str: + return f"{value:.2f}{suffix}" if isinstance(value, (int, float)) else "n/a" + + def _gpu_segment(gpu_stats: dict) -> str: + """Render a compact GPU summary suffix, or empty when unavailable.""" + if not isinstance(gpu_stats, dict) or not gpu_stats.get("available"): + return "" + util = gpu_stats.get("utilization_percent") or {} + mem = gpu_stats.get("memory_used_mb") or {} + return f" | gpu={_fmt(util.get('mean'), '%')} mem={_fmt(mem.get('max'), 'MB')}" + + print("--- Replay stats ---") + for run in runs: + idx = run["run_index"] + 1 + cpu = run["cpu_frame_time_ms"] + fps = run["fps"] + print( + f"Replay {idx}/{total}: outcome={run['outcome']}" + f" | frames={run['active_iterations']}" + f" | active={run['active_duration_s']:.2f}s" + f" | mean={_fmt(cpu['mean'], 'ms')}" + f" p90={_fmt(cpu['p90'], 'ms')}" + f" p99={_fmt(cpu['p99'], 'ms')}" + f" | mean_fps={_fmt(fps['mean'])}" + f"{_gpu_segment(run.get('gpu_stats', {}))}" + ) + + succ = report["outcomes"].get("success", 0) + agg = report["aggregate"] + agg_gpu = agg.get("gpu_stats", {}) + agg_util = agg_gpu.get("utilization_percent", {}) if isinstance(agg_gpu, dict) else {} + agg_mem = agg_gpu.get("memory_used_mb", {}) if isinstance(agg_gpu, dict) else {} + print( + f"Aggregate: success_rate={succ}/{total} ({report['success_rate']:.2f})" + f" | mean_fps={_fmt(agg['fps']['mean_of_means'])}" + f" | mean_p90={_fmt(agg['cpu_frame_time_ms']['mean_of_p90s'], 'ms')}" + f" | mean_gpu={_fmt(agg_util.get('mean_of_means'), '%')}" + f" | max_mem={_fmt(agg_mem.get('max_overall'), 'MB')}" + ) + + +def _write_json_report(path: str, report: dict) -> None: + """Persist the report to ``path`` as a UTF-8 JSON file (pretty-printed).""" + with open(path, "w", encoding="utf-8") as fh: + json.dump(report, fh, indent=2, sort_keys=False) + fh.write("\n") + print(f"Stats report written to {path}") + + +def _exit_code_for_outcomes(all_runs: list[_RunStats]) -> int: + """Map the worst-of-N replay outcome to a CI-friendly exit code. + + Precedence: ``timeout`` > ``failure`` > ``incomplete`` > ``success``. + Any single bad run fails the whole batch; timeouts get their own code + so CI can distinguish a perf cliff from a broken trajectory. + """ + if not all_runs: + return 1 + outcomes = {r.outcome for r in all_runs} + if outcomes <= {"success"}: + return 0 + if "timeout" in outcomes: + return 2 + return 1 # any "failure" or "incomplete" + + +def _resolve_cloudxr_env(value: str | None) -> str | None: + """Resolve ``--cloudxr_env`` shorthands to absolute ``.env`` file paths. + + Mirrors :func:`scripts.tools.record_demos._resolve_cloudxr_env` so the same + short names (``"cloudxrjs"``, ``"avp"``) behave identically on the + recording and replay sides. Accepts ``"none"`` / empty / ``None`` to mean + "no CloudXR" and otherwise returns the value unchanged. + """ + if value is None or value.strip() == "" or value.lower() == "none": + return None + if not _CLOUDXR_ENV_SHORTHANDS: + from isaaclab_teleop import CLOUDXR_AVP_ENV, CLOUDXR_JS_ENV + + _CLOUDXR_ENV_SHORTHANDS["cloudxrjs"] = CLOUDXR_JS_ENV + _CLOUDXR_ENV_SHORTHANDS["avp"] = CLOUDXR_AVP_ENV + return _CLOUDXR_ENV_SHORTHANDS.get(value.lower(), value) + + +def _maybe_launch_cloudxr(cloudxr_env_path: str | None, auto_launch: bool): + """Launch a CloudXR runtime owned at the agent (batch) scope. + + The CloudXR runtime is process-scoped, not session-scoped: tearing it + down between teleop sessions in the same Kit process severs Kit's + OpenXR runtime IPC, so the next session's ``xrCreateInstance`` fails + with ``XR_ERROR_RUNTIME_UNAVAILABLE`` and the XR pipeline hangs. To + support multi-run XR replay we hoist CloudXR ownership out of the + per-run :class:`~isaaclab_teleop.session_lifecycle.TeleopSessionLifecycle` + (which would otherwise stop it on every device teardown) into the + agent. Each replay's ``IsaacTeleopDevice`` is constructed with + ``auto_launch_cloudxr=False`` so the lifecycle leaves the runtime + alone; the agent terminates the launcher in its ``finally`` block. + + Mirrors the gating in :meth:`TeleopSessionLifecycle._ensure_cloudxr_runtime` + (``--cloudxr_env`` set, ``--auto_launch_cloudxr`` enabled, + ``ISAACLAB_CXR_SKIP_AUTOLAUNCH=1`` env var not set) so behavior parity + is preserved. + + Args: + cloudxr_env_path: Resolved CloudXR ``.env`` file path, or ``None`` + to skip launching. + auto_launch: Whether to honor the request (mirrors + ``--auto_launch_cloudxr``). + + Returns: + The launched ``CloudXRLauncher`` instance, or ``None`` when + nothing should be launched. Caller is responsible for calling + ``.stop()`` at the end of the batch. + """ + if cloudxr_env_path is None or not auto_launch: + return None + + if os.environ.get("ISAACLAB_CXR_SKIP_AUTOLAUNCH", "").strip() == "1": + logger.info("CloudXR auto-launch skipped (ISAACLAB_CXR_SKIP_AUTOLAUNCH=1)") + return None + + from isaacteleop.cloudxr import CloudXRLauncher + + launcher = CloudXRLauncher( + install_dir=str(Path.home() / ".cloudxr"), + env_config=cloudxr_env_path, + accept_eula=False, + ) + logger.info("CloudXR runtime launched (process-scoped, shared across replays)") + return launcher + + +def _prepare_env_cfg(task: str, num_envs: int, device: str) -> tuple[ManagerBasedRLEnvCfg, object | None]: + """Build and tweak an env config suitable for non-interactive replay. + + Mirrors the env-config mutations performed by ``record_demos.py``'s + :func:`create_environment_config`: + + * The ``success`` term is extracted and cleared from the env config so the + script can drive success detection (and the matching reset cycle) + explicitly via :func:`_process_success_condition`, gated by + ``--num_success_steps``. This matches record_demos.py's pattern of + manually counting consecutive success steps before resetting. + * The ``time_out`` term is cleared for the same reason it is cleared in + :file:`scripts/tools/record_demos.py` and + :file:`scripts/imitation_learning/robomimic/play.py`: a recorded + trajectory often exceeds ``episode_length_s`` (pick-place is 20s by + default; a successful operator demo can easily run 25-30s). With the + term active, the env auto-truncates partway through the MCAP, resets + to the default pose, and the remainder of the recorded actions get + retargeted against the freshly-reset robot -- which manifests as + "robot moves correctly for a bit, then snaps back / acts wrong." + The recorder itself did not run with ``time_out`` enabled, so + reproducing record-time semantics requires clearing it here too. + * Other failure terms (e.g. ``object_dropping``, ``object_too_far``) + are left active. ``env.step`` then auto-invokes ``_reset_idx`` for any + env whose termination fires; the main loop detects this via the + returned ``terminated``/``truncated`` tensors and completes the reset + cycle (sim reinit + teleop device reset) so Pink IK starts the next + attempt with fresh articulation views. + + Returns: + Tuple ``(env_cfg, success_term)``. ``success_term`` is ``None`` when + the env doesn't define a ``success`` termination term. + """ + env_cfg = parse_env_cfg(task, device=device, num_envs=num_envs) + env_cfg.env_name = task.split(":")[-1] + if not isinstance(env_cfg, ManagerBasedRLEnvCfg): + raise ValueError( + "teleop_replay_agent only supports ManagerBasedRLEnv environments. " + f"Received environment config type: {type(env_cfg).__name__}" + ) + success_term: object | None = None + if hasattr(env_cfg.terminations, "success"): + success_term = env_cfg.terminations.success + env_cfg.terminations.success = None + else: + logger.warning( + "No success termination term was found in the environment;" + " success-driven resets will not fire during replay." + ) + if hasattr(env_cfg.terminations, "time_out"): + env_cfg.terminations.time_out = None + env_cfg = remove_camera_configs(env_cfg) + env_cfg.sim.render.antialiasing_mode = "DLSS" + return env_cfg, success_term + + +def _handle_reset(env: gym.Env, teleop_interface: IsaacTeleopDevice) -> None: + """Run the full env+teleop reset cycle used by ``record_demos.py``. + + Mirrors :func:`scripts.tools.record_demos.handle_reset` (sans the + instruction-display update, which the headless replay agent doesn't + own). ``env.sim.reset()`` does the hard physics reinit that keeps Pink + IK seeded against fresh articulation views; see the initial-reset note + in :func:`main`. ``env.recorder_manager.reset()`` is a no-op when no + recorders are configured (the default for this script), but kept for + parity with record_demos.py so future recorder additions don't have to + re-derive the call sequence. + """ + print("Resetting environment...") + env.sim.reset() + env.recorder_manager.reset() + env.reset() + teleop_interface.reset() + + +def _process_success_condition( + env: gym.Env, + success_term: object | None, + success_step_count: int, + num_success_steps: int, +) -> tuple[int, bool]: + """Track consecutive success steps and decide whether to reset. + + Mirrors :func:`scripts.tools.record_demos.process_success_condition` + minus the recorder-export side effects, which this script does not own. + + Returns: + Tuple ``(updated_success_step_count, reset_due_to_success)``. + """ + if success_term is None: + return success_step_count, False + + if bool(success_term.func(env, **success_term.params)[0]): + success_step_count += 1 + if success_step_count >= num_success_steps: + print(f"Success condition met after {success_step_count} consecutive steps; resetting env.") + return success_step_count, True + else: + success_step_count = 0 + + return success_step_count, False + + +_RENDERER_SETTLE_FRAMES: int = 30 +"""Number of additional render frames pumped after the USD stage finishes loading. + +Kit's stage-load status flips to ``count_loading == 0`` as soon as every referenced asset +has been resolved, but the renderer pipeline (shader compilation, articulation-view +binding, material warm-up) typically needs a few more event-loop ticks to converge. Thirty +frames at the default Kit render cadence is ~0.5 s on most machines and is deterministic +per-machine -- unlike a wall-clock delay it does not have to be tuned for hardware. +""" + + +def _wait_for_stage_load(simulation_app, max_wait_s: float) -> None: + """Block until the USD stage finishes resolving every referenced asset. + + Polls :meth:`omni.usd.UsdContext.get_stage_loading_status`. The third element of + the returned tuple is the count of assets Kit still has pending; when it reaches + zero the stage is fully streamed in and the renderer pipeline is ready to draw + against it. After the count reaches zero this function pumps an additional + :data:`_RENDERER_SETTLE_FRAMES` ``simulation_app.update()`` calls so shaders, + materials, and articulation views finish warming up before the caller begins + consuming MCAP frames or stepping the env. + + Args: + simulation_app: The :class:`isaaclab.app.SimulationApp` instance whose + event loop to pump while waiting. + max_wait_s: Upper bound on how long to spin on a non-zero loading count + before warning and returning. Acts as a safety net for misconfigured + scenes (missing assets, slow Nucleus); a successful run typically + completes well within this bound. + + The function is best-effort: when ``omni.usd`` is unavailable (e.g. when + running outside a Kit context) it returns immediately so callers do not + need a separate code path. + """ + try: + import omni.usd + except (ImportError, ModuleNotFoundError): + logger.warning("omni.usd not available; skipping deterministic stage-load wait") + return + + print("Waiting for USD stage to finish loading...") + start_s = time.monotonic() + last_progress_log_s = start_s + while simulation_app.is_running(): + context = omni.usd.get_context() + if context is None: + break + # get_stage_loading_status -> (message, count_loaded, count_loading) + _, _, count_loading = context.get_stage_loading_status() + if count_loading == 0: + break + elapsed_s = time.monotonic() - start_s + if elapsed_s >= max_wait_s: + logger.warning( + "Stage still reports %d assets pending after %.1fs; proceeding anyway. Replay may race the renderer.", + count_loading, + max_wait_s, + ) + break + if time.monotonic() - last_progress_log_s >= 5.0: + print(f" stage loading: {count_loading} assets pending (elapsed {elapsed_s:.1f}s)") + last_progress_log_s = time.monotonic() + simulation_app.update() + + elapsed_s = time.monotonic() - start_s + print(f"Stage load complete after {elapsed_s:.1f}s; settling renderer for {_RENDERER_SETTLE_FRAMES} frames...") + for _ in range(_RENDERER_SETTLE_FRAMES): + if not simulation_app.is_running(): + return + simulation_app.update() + + +def _run_single_replay( + env: gym.Env, + isaac_teleop_cfg, + success_term: object | None, + run_index: int, + total_runs: int, +) -> _RunStats: + """Run a single replay pass against ``env`` and return the per-run stats. + + Builds a fresh :class:`IsaacTeleopDevice` so each call re-opens the MCAP + reader at frame 0 -- exiting and re-entering the device's context manager + tears down the previous ``TeleopSession`` and constructs a new one. The + USD stage is left untouched; the caller (``main``) is responsible for + building / closing ``env`` once across the full multi-run batch. + + Per-frame sampling is restricted to iterations where ``env.step()`` + actually ran (post-START, pre-terminator). Pre-START render-only + frames, warmup ticks, and reset cycles do not contribute to the + returned stats so the numbers reflect the steady-state replay + workload rather than agent bookkeeping overhead. + + Args: + env: The (already built) Isaac Lab environment, shared across runs. + isaac_teleop_cfg: The :class:`IsaacTeleopCfg` extracted from + ``env_cfg.isaac_teleop``. + success_term: The original ``success`` termination term (or ``None``); + forwarded to :func:`_process_success_condition` each frame. + run_index: Zero-indexed run number within the multi-run batch. + Used to gate one-time work (the deterministic stage-load wait + only runs on ``run_index == 0``). + total_runs: Total number of runs in the batch; used only for log + framing ("Replay 1/5: ..."). + """ + stats = _RunStats() + + # Default NVML-backed provider samples GPU utilization + used + # memory once per active iteration. ``NvmlGpuStatsProvider`` + # soft-fails (the summary dict carries ``available: False`` and a + # reason) when ``nvidia-ml-py`` is missing or the driver is + # unreachable, so a missing GPU never blocks the replay. To swap + # in a renderer-specific provider (Kit viewport telemetry, Newton, + # ...) implement the :class:`GpuStatsProvider` Protocol and + # construct it here in place of :class:`NvmlGpuStatsProvider`. + gpu_stats_provider: GpuStatsProvider = NvmlGpuStatsProvider() + if run_index == 0 and not getattr(gpu_stats_provider, "_available", False): + print(f"[GPU stats] disabled: {getattr(gpu_stats_provider, '_reason', 'unknown reason')}") + + # CloudXR is owned by the agent (see ``_maybe_launch_cloudxr`` in + # ``main``), so the per-run lifecycle must not try to launch -- or + # stop -- it. ``cloudxr_env_file=None`` + ``auto_launch_cloudxr=False`` + # short-circuits ``TeleopSessionLifecycle._ensure_cloudxr_runtime`` so + # the runtime survives across replays and Kit's OpenXR session keeps + # its IPC connection. + teleop_interface = create_isaac_teleop_device( + isaac_teleop_cfg, + sim_device=args_cli.device, + callbacks={}, + cloudxr_env_file=None, + auto_launch_cloudxr=False, + mcap_replay_path=args_cli.replay_file, + ) + if run_index == 0: + print(f"Using teleop device: {teleop_interface}") + + with teleop_interface: + # Mirror the reset sequence used by ``record_demos.py``: ``sim.reset()`` + # does a hard physics reinit (re-binds articulation views, plays the + # timeline) that ``env.reset()`` alone does not perform. Pink IK reads + # ``data.joint_pos.torch`` every step to seed Pinocchio's configuration + # and to compute ``target = curr + delta``; if the articulation view is + # stale, every IK call produces zero-delta arm targets while the + # hand-finger path (which bypasses IK) keeps tracking. See PR #5507. + env.sim.reset() + env.reset() + teleop_interface.reset() + + # Deterministic warmup is only required on the first run -- once the + # stage has been streamed in and the renderer settled, subsequent + # runs share the same stage and only need the per-run ``env.sim.reset`` + # above. Skipping it on later runs saves the renderer-settle frames + # at the cost of doing nothing measurable (the wait returns + # immediately on a fully-loaded stage anyway). + if run_index == 0: + _wait_for_stage_load(simulation_app, args_cli.max_stage_load_wait_s) + + # Optional extra wall-clock buffer on top of the deterministic + # wait. Useful as an escape hatch when the deterministic check + # is not enough (e.g. very slow shader compilation paths). + if args_cli.replay_start_delay_s > 0: + print( + f"Additional warmup buffer: rendering for {args_cli.replay_start_delay_s:.1f}s" + " before consuming MCAP frames." + ) + buffer_start_s = time.monotonic() + while simulation_app.is_running() and time.monotonic() - buffer_start_s < args_cli.replay_start_delay_s: + env.sim.render() + + print( + f"Replay {run_index + 1}/{total_runs} started; replaying MCAP from {args_cli.replay_file}" + f" (max_replay_duration_s={args_cli.max_replay_duration_s:.1f})." + ) + teleop_active = False + teleop_was_active = False # only terminate on STOP after a real START + success_step_count = 0 + replay_start_s = time.monotonic() + # First time we run env.step on this replay; used to bound the + # active duration that drives mean-FPS. Stays None until a sample + # is recorded so render-only / pre-START frames don't widen the + # window. + active_start_s: float | None = None + # End-of-active-window timestamp. Updated each sampled iteration + # so the active duration is always "first active iter -> last + # active iter" even when a terminator fires mid-loop and the + # subsequent renders are excluded. + last_active_end_s: float | None = None + + while simulation_app.is_running(): + try: + with torch.inference_mode(): + # Wall-clock safety cap. Only hit when the recording + # never reaches a natural terminator -- e.g. it omits + # an operator STOP AND the env's success/failure + # terms never fire within the configured window. A + # clean ``record_demos.py``-style capture exits on + # the success edge well before this triggers. + elapsed_s = time.monotonic() - replay_start_s + if elapsed_s >= args_cli.max_replay_duration_s: + print(f"Replay reached max_replay_duration_s={args_cli.max_replay_duration_s:.1f}; ending run.") + stats.outcome = "timeout" + break + + action = teleop_interface.advance() + ctrl = poll_control_events(teleop_interface) + + # Track active state from the replayed _teleop_control + # channel. ``ctrl.is_active`` follows the same shape + # that ``record_demos.py`` and ``teleop_se3_agent.py`` + # consume; None means "no transition this frame." + prev_active = teleop_active + if ctrl.is_active is not None: + teleop_active = ctrl.is_active + if teleop_active: + teleop_was_active = True + + # End-of-run on the first STOP edge after a real + # START -- the operator pressed Stop during + # recording, and ``ReplayMessageChannelTrackerImpl`` + # surfaces that payload at the same recording-frame + # index it was captured at. Per-frame tracker EOF on + # its own does NOT trigger this branch: + # :class:`TeleopMessageProcessor` keeps emitting + # valid False booleans for KILL / RUN_TOGGLE / RESET + # after the message-channel MCAP exhausts, so the + # state manager stays in its last state and + # ``ctrl.is_active`` does not flip. Recordings + # without an operator STOP are terminated instead by + # the success / failure / wall-clock terminators + # below. + if prev_active and not teleop_active and teleop_was_active: + print("Replay end observed (STOP edge); ending run.") + break + + if ctrl.should_reset: + _handle_reset(env, teleop_interface) + success_step_count = 0 + continue + + # Gate stepping on the active state (mirrors + # teleop_se3_agent.py:309-328). Pre-START operator + # setup frames render only; the recorded START flips + # us into the stepping branch. + if action is None or not teleop_active: + env.sim.render() + continue + + # Sample CPU frame time across the env.step call only + # (the active-frame window the stats report covers). + iter_start_s = time.perf_counter() + if active_start_s is None: + active_start_s = iter_start_s + actions = action.repeat(env.num_envs, 1) + _, _, terminated, truncated, _ = env.step(actions) + iter_end_s = time.perf_counter() + stats.active_frame_times_ms.append((iter_end_s - iter_start_s) * 1000.0) + last_active_end_s = iter_end_s + + # Snapshot GPU state right after env.step so the + # sample reflects the active workload (post-render + # for that frame). Provider is cheap (~50 us for + # NVML, no-op when disabled). + gpu_stats_provider.sample() + + # Failure path: ``env.step`` already invoked + # ``_reset_idx`` for any env whose task-specific + # failure term fired (``time_out`` was cleared by + # ``_prepare_env_cfg``; ``success`` is handled + # below). + # + # Replay-specific behavior: a failure mid-trajectory + # means the recorded demo did not reproduce -- the + # operator has no agency to recover here, so the + # rest of the MCAP would just feed retargeted + # actions to a freshly-reset env, which is not + # meaningful replay. End the run with a failure + # outcome so the batch's exit code reflects it. + if bool(terminated.any().item()) or bool(truncated.any().item()): + print("Replay failure: env terminated/truncated mid-trajectory; ending run.") + stats.outcome = "failure" + break + + # Success path: ``success_term`` was cleared from the + # env cfg so ``env.step`` does not auto-reset on it. + # ``_process_success_condition`` consults the original + # success term and reports when it has held for + # ``--num_success_steps`` consecutive steps. + # + # Replay-specific behavior: success is the natural + # end-of-replay for ``record_demos.py``-style single + # episode captures, so end the run here instead of + # invoking ``_handle_reset`` like the live agent + # does. The alternative -- resetting and continuing + # into the post-success MCAP tail -- would just + # replay operator wind-down frames (controller + # releases, idle motion before they hit Stop on + # recording), which is not meaningful demo data and + # quickly exhausts the per-frame tracker streams + # anyway. + success_step_count, reset_on_success = _process_success_condition( + env, success_term, success_step_count, args_cli.num_success_steps + ) + if reset_on_success: + print("Recorded demo succeeded; ending run.") + stats.outcome = "success" + break + except Exception: + # ``logger.exception`` preserves the full traceback; bare + # ``logger.error`` would only log the message. Classify as + # ``failure`` so the per-run outcome and the batch exit + # code reflect that the recorded trajectory did not + # complete -- staying at the default ``incomplete`` would + # silently mask a crash mid-replay in CI reports. + logger.exception("Error during simulation step") + stats.outcome = "failure" + break + + # Stamp the active window duration. Falls back to 0.0 when no env + # step ever ran (recording never reached START, or terminated before + # the first active frame). + if active_start_s is not None and last_active_end_s is not None: + stats.active_duration_s = last_active_end_s - active_start_s + stats.success_step_count = success_step_count + stats.gpu_stats = gpu_stats_provider.summary() + return stats + + +def main() -> int: + """Replay a captured Isaac Teleop session against an Isaac Lab environment. + + Builds the env once, then loops :func:`_run_single_replay` for + ``--num_replays`` iterations. Each iteration builds a fresh + :class:`IsaacTeleopDevice` (so the MCAP reader reopens at frame 0) and + resets the env in place; the USD stage stays loaded between runs so + multi-run batches start essentially instantly. + + Per-replay control flow (see :func:`_run_single_replay` for details): + * Pre-loop warmup: ``_wait_for_stage_load`` polls + ``omni.usd.UsdContext.get_stage_loading_status`` until Kit + reports zero pending assets, then renders a fixed number of + settle frames (only on ``run_index == 0``). An optional + ``--replay_start_delay_s`` buffer can be appended for hardware + that needs more grace. ``advance()`` is not called during + warmup so ``ReplaySession.update`` does not consume MCAP + frames yet. + * Main loop: :meth:`IsaacTeleopDevice.advance` returns an action + tensor derived from the MCAP-replayed tracker stream and + :func:`poll_control_events` returns the START / STOP / RESET + edges replayed from the ``_teleop_control`` channel. The env + steps only when ``ctrl.is_active`` is True, mirroring + ``teleop_se3_agent.py`` and ``record_demos.py`` exactly -- + pre-START operator-setup frames render only. + * End-of-replay terminators (any of these breaks the inner + loop and sets ``_RunStats.outcome`` accordingly; the function + returns and the outer batch driver moves to the next replay): + 1. Replayed STOP edge from ``_teleop_control`` -- the + operator pressed Stop during recording. Does not + overwrite ``outcome``: if success fired earlier in this + run, the outcome stays ``"success"``; otherwise it stays + ``"incomplete"``, since stopping without reaching + success is not a successful reproduction. + 2. Success condition met for ``--num_success_steps`` + consecutive steps -- the natural end of a + ``record_demos.py`` single-episode capture. Sets + outcome ``"success"``. ``_handle_reset`` is intentionally + skipped here because the post-success MCAP tail is + operator wind-down, not demo data. + 3. ``env.step`` ``terminated`` / ``truncated`` -- a task- + specific failure term fired during the recorded + trajectory. Sets outcome ``"failure"``. + 4. Wall-clock ``--max_replay_duration_s`` safety cap. Sets + outcome ``"timeout"``. + + Kit itself is left running between replays so a fresh + :class:`IsaacTeleopDevice` can be constructed without reloading + the USD stage; ``__main__`` calls ``simulation_app.close()`` + after the whole batch finishes. + + Stats output: + Each iteration where ``env.step()`` ran contributes one CPU + frame-time sample (``perf_counter`` delta in ms). At the end of + the run the samples are summarised into mean / p50 / p90 / p95 / + p99 / min / max / stddev + a mean / instantaneous-min / max FPS + triple, then serialised into the ``runs[]`` array of the report + dict. ``--stats_output_file`` controls whether the dict is + persisted to disk; a one-line-per-run stdout summary is always + printed. See the module docstring for the full JSON schema. + + Resource cleanup is wrapped in a ``try/finally`` so that ``env.close()`` + always runs, even when device construction or any subsequent setup + raises -- otherwise the USD stage would leak across CI runs. + + Returns: + The host process exit code, mapped from the worst-of-N outcome + across the multi-run batch: ``0`` if every run's + ``success_term`` fired, ``2`` if any run hit + ``--max_replay_duration_s``, otherwise ``1`` (any failure or + incomplete run). + """ + env: gym.Env | None = None + cloudxr_launcher = None + all_runs: list[_RunStats] = [] + + if args_cli.num_replays < 1: + raise ValueError(f"--num_replays must be >= 1; got {args_cli.num_replays}") + + try: + # CloudXR launch is hoisted to the agent (batch scope) so it + # survives across per-run device teardown; per-run lifecycles + # are explicitly told not to launch / stop it (see the + # ``cloudxr_env_file=None, auto_launch_cloudxr=False`` call in + # ``_run_single_replay``). This is what lets ``--num_replays > 1`` + # work in XR-active mode without losing Kit's OpenXR runtime + # IPC between runs. + cloudxr_launcher = _maybe_launch_cloudxr( + _resolve_cloudxr_env(args_cli.cloudxr_env), args_cli.auto_launch_cloudxr + ) + + env_cfg, success_term = _prepare_env_cfg(args_cli.task, args_cli.num_envs, args_cli.device) + + if not hasattr(env_cfg, "isaac_teleop") or env_cfg.isaac_teleop is None: + raise ValueError( + f"Task '{args_cli.task}' does not configure an IsaacTeleop pipeline. " + "MCAP replay requires env_cfg.isaac_teleop to be set." + ) + + env = gym.make(args_cli.task, cfg=env_cfg).unwrapped + + for run_idx in range(args_cli.num_replays): + run_stats = _run_single_replay( + env=env, + isaac_teleop_cfg=env_cfg.isaac_teleop, + success_term=success_term, + run_index=run_idx, + total_runs=args_cli.num_replays, + ) + all_runs.append(run_stats) + print(f"Replay {run_idx + 1}/{args_cli.num_replays} outcome: {run_stats.outcome}") + if not simulation_app.is_running(): + # Kit was closed externally mid-batch; stop the outer loop + # rather than spawning a fresh device against a dead app. + break + finally: + if env is not None: + env.close() + print("Environment closed") + if cloudxr_launcher is not None: + try: + cloudxr_launcher.stop() + logger.info("CloudXR runtime stopped (end of batch)") + except Exception: + logger.exception("Failed to stop CloudXR launcher cleanly") + + report = _build_report(args_cli, all_runs) + _print_stdout_summary(report) + if args_cli.stats_output_file is not None: + _write_json_report(args_cli.stats_output_file, report) + return _exit_code_for_outcomes(all_runs) + + +if __name__ == "__main__": + exit_code = main() + simulation_app.update() + simulation_app.close() + sys.exit(exit_code) diff --git a/simulation/modules/IsaacLab/scripts/environments/teleoperation/teleop_se3_agent.py b/simulation/modules/IsaacLab/scripts/environments/teleoperation/teleop_se3_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..80ba2a7895c1b984f77cf9cb9b8f185470a3bebd --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/environments/teleoperation/teleop_se3_agent.py @@ -0,0 +1,376 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to run teleoperation with Isaac Lab manipulation environments. + +Supports multiple input devices (e.g., keyboard, spacemouse, gamepad) and devices +configured within the environment (including OpenXR-based hand tracking or motion +controllers). + +This script supports two teleoperation stacks: +1. Native Isaac Lab teleop stack (via teleop_devices in env_cfg) +2. IsaacTeleop-based stack (via isaac_teleop in env_cfg) + +The script automatically detects which stack to use based on the environment config. +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +from collections.abc import Callable + +from isaaclab.app import AppLauncher +from isaaclab.utils.string import list_intersection, string_to_callable + +# add argparse arguments +parser = argparse.ArgumentParser(description="Teleoperation for Isaac Lab environments.") +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to simulate.") +parser.add_argument( + "--teleop_device", + type=str, + default=None, + help=( + "Legacy teleop device name. When omitted, the IsaacTeleop pipeline is used if configured in the env," + " otherwise keyboard is used as fallback. When explicitly provided, the script uses the legacy" + " teleop_devices path and looks up this name in env_cfg.teleop_devices.devices." + ), +) +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument("--sensitivity", type=float, default=1.0, help="Sensitivity factor.") +parser.add_argument( + "--cloudxr_env", + type=str, + default="cloudxrjs", + help=( + "Path to a CloudXR .env file, or a shorthand: 'cloudxrjs' (Quest/Pico, default) or 'avp' (Apple Vision Pro)." + " Set to 'none' to disable CloudXR auto-launch entirely." + ), +) +parser.add_argument( + "--auto_launch_cloudxr", + action=argparse.BooleanOptionalAction, + default=True, + help="Auto-launch the CloudXR runtime when --cloudxr_env is set. Use --no-auto_launch_cloudxr to disable.", +) +parser.add_argument( + "--external_callback", + default=None, + help="Fully qualified path to an externally defined callback.", +) + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli, remaining_args = parser.parse_known_args() + +app_launcher_args = vars(args_cli) + +# launch omniverse app +app_launcher = AppLauncher(app_launcher_args) +simulation_app = app_launcher.app + +# Call an external callback if requested. +remaining_args_env_registration = None +if args_cli.external_callback: + external_callback_function = string_to_callable(args_cli.external_callback, separator=".") + remaining_args_env_registration = external_callback_function() + +# Error on unrecognized arguments. +unrecognized_args = list_intersection(remaining_args, remaining_args_env_registration) +if unrecognized_args: + parser.error(f"unrecognized arguments: {' '.join(unrecognized_args)}") + +"""Rest everything follows.""" + + +import logging + +import gymnasium as gym +import torch + +from isaaclab.devices import Se3Gamepad, Se3GamepadCfg, Se3Keyboard, Se3KeyboardCfg, Se3SpaceMouse, Se3SpaceMouseCfg +from isaaclab.devices.openxr import remove_camera_configs +from isaaclab.devices.teleop_device_factory import create_teleop_device +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.managers import TerminationTermCfg as DoneTerm + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.manager_based.manipulation.lift import mdp +from isaaclab_tasks.utils import parse_env_cfg + +logger = logging.getLogger(__name__) + +_CLOUDXR_ENV_SHORTHANDS: dict[str, str] = {} + + +def _resolve_cloudxr_env(value: str | None) -> str | None: + """Resolve ``--cloudxr_env`` shorthands to absolute ``.env`` file paths. + + Accepts ``"cloudxrjs"`` (Quest/Pico), ``"avp"`` (Apple Vision Pro), + ``"none"`` / ``None`` (disable), or an arbitrary file path. + """ + if value is None or value.strip() == "" or value.lower() == "none": + return None + if not _CLOUDXR_ENV_SHORTHANDS: + from isaaclab_teleop import CLOUDXR_AVP_ENV, CLOUDXR_JS_ENV + + _CLOUDXR_ENV_SHORTHANDS["cloudxrjs"] = CLOUDXR_JS_ENV + _CLOUDXR_ENV_SHORTHANDS["avp"] = CLOUDXR_AVP_ENV + return _CLOUDXR_ENV_SHORTHANDS.get(value.lower(), value) + + +def _create_builtin_device(device_name: str, sensitivity: float) -> object | None: + """Create a built-in teleop device by name, or return None if unrecognized.""" + name = device_name.lower() + if name == "keyboard": + return Se3Keyboard(Se3KeyboardCfg(pos_sensitivity=0.05 * sensitivity, rot_sensitivity=0.05 * sensitivity)) + elif name == "spacemouse": + return Se3SpaceMouse(Se3SpaceMouseCfg(pos_sensitivity=0.05 * sensitivity, rot_sensitivity=0.05 * sensitivity)) + elif name == "gamepad": + return Se3Gamepad(Se3GamepadCfg(pos_sensitivity=0.1 * sensitivity, rot_sensitivity=0.1 * sensitivity)) + return None + + +def main() -> None: + """ + Run teleoperation with an Isaac Lab manipulation environment. + + Creates the environment, sets up teleoperation interfaces and callbacks, + and runs the main simulation loop until the application is closed. + + Returns: + None + """ + # parse configuration + env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=args_cli.num_envs) + env_cfg.env_name = args_cli.task + if not isinstance(env_cfg, ManagerBasedRLEnvCfg): + raise ValueError( + "Teleoperation is only supported for ManagerBasedRLEnv environments. " + f"Received environment config type: {type(env_cfg).__name__}" + ) + # modify configuration + env_cfg.terminations.time_out = None + if "Lift" in args_cli.task: + # set the resampling time range to large number to avoid resampling + env_cfg.commands.object_pose.resampling_time_range = (1.0e9, 1.0e9) + # add termination condition for reaching the goal otherwise the environment won't reset + env_cfg.terminations.object_reached_goal = DoneTerm(func=mdp.object_reached_goal) + + # When --teleop_device is explicitly provided, use the legacy teleop_devices path + # even if isaac_teleop is configured. Otherwise prefer isaac_teleop when available. + teleop_device_explicitly_set = args_cli.teleop_device is not None + use_isaac_teleop = ( + not teleop_device_explicitly_set and hasattr(env_cfg, "isaac_teleop") and env_cfg.isaac_teleop is not None + ) + + if use_isaac_teleop or args_cli.xr: + env_cfg = remove_camera_configs(env_cfg) + env_cfg.sim.render.antialiasing_mode = "DLSS" + + try: + # create environment + env = gym.make(args_cli.task, cfg=env_cfg).unwrapped + # check environment name (for reach , we don't allow the gripper) + if "Reach" in args_cli.task: + logger.warning( + f"The environment '{args_cli.task}' does not support gripper control. The device command will be" + " ignored." + ) + except Exception as e: + logger.error(f"Failed to create environment: {e}") + simulation_app.close() + return + + # Flags for controlling teleoperation flow + should_reset_recording_instance = False + teleoperation_active = True + + # Callback handlers + def reset_recording_instance() -> None: + """ + Reset the environment to its initial state. + + Sets a flag to reset the environment on the next simulation step. + + Returns: + None + """ + nonlocal should_reset_recording_instance + should_reset_recording_instance = True + print("Reset triggered - Environment will reset on next step") + + def start_teleoperation() -> None: + """ + Activate teleoperation control of the robot. + + Enables the application of teleoperation commands to the environment. + + Returns: + None + """ + nonlocal teleoperation_active + teleoperation_active = True + print("Teleoperation activated") + + def stop_teleoperation() -> None: + """ + Deactivate teleoperation control of the robot. + + Disables the application of teleoperation commands to the environment. + + Returns: + None + """ + nonlocal teleoperation_active + teleoperation_active = False + print("Teleoperation deactivated") + + # Create device config if not already in env_cfg + teleoperation_callbacks: dict[str, Callable[[], None]] = { + "R": reset_recording_instance, + "START": start_teleoperation, + "STOP": stop_teleoperation, + "RESET": reset_recording_instance, + } + + # For XR devices (hand tracking or IsaacTeleop), default to inactive + if use_isaac_teleop or args_cli.xr: + teleoperation_active = env_cfg.isaac_teleop.teleoperation_active_default if use_isaac_teleop else False + else: + # Always active for other devices + teleoperation_active = True + + # Create teleop device based on configuration + teleop_interface = None + + try: + if use_isaac_teleop: + from isaaclab_teleop import create_isaac_teleop_device, poll_control_events + + teleop_interface = create_isaac_teleop_device( + env_cfg.isaac_teleop, + sim_device=args_cli.device, + callbacks=teleoperation_callbacks, + cloudxr_env_file=_resolve_cloudxr_env(args_cli.cloudxr_env), + auto_launch_cloudxr=args_cli.auto_launch_cloudxr, + ) + + elif teleop_device_explicitly_set: + device_name = args_cli.teleop_device + if hasattr(env_cfg, "teleop_devices") and device_name in env_cfg.teleop_devices.devices: + teleop_interface = create_teleop_device( + device_name, env_cfg.teleop_devices.devices, teleoperation_callbacks + ) + else: + teleop_interface = _create_builtin_device(device_name, args_cli.sensitivity) + if teleop_interface is None: + logger.error( + f"--teleop_device={device_name} was passed but no matching entry exists in" + " env_cfg.teleop_devices and it is not a built-in device name. Either remove" + " --teleop_device to use the IsaacTeleop pipeline, or add a" + f" '{device_name}' entry under teleop_devices in the environment config." + " Built-in devices: keyboard, spacemouse, gamepad." + ) + env.close() + simulation_app.close() + return + for key, callback in teleoperation_callbacks.items(): + try: + teleop_interface.add_callback(key, callback) + except (ValueError, TypeError) as e: + logger.warning(f"Failed to add callback for key {key}: {e}") + else: + # No --teleop_device and no isaac_teleop: fall back to keyboard + sensitivity = args_cli.sensitivity + teleop_interface = Se3Keyboard( + Se3KeyboardCfg(pos_sensitivity=0.05 * sensitivity, rot_sensitivity=0.05 * sensitivity) + ) + for key, callback in teleoperation_callbacks.items(): + try: + teleop_interface.add_callback(key, callback) + except (ValueError, TypeError) as e: + logger.warning(f"Failed to add callback for key {key}: {e}") + except Exception as e: + logger.error(f"Failed to create teleop device: {e}") + env.close() + simulation_app.close() + return + + if teleop_interface is None: + logger.error("Failed to create teleop interface") + env.close() + simulation_app.close() + return + + print(f"Using teleop device: {teleop_interface}") + + def run_loop(): + """Inner function to run the teleop loop with access to nonlocal variables.""" + nonlocal should_reset_recording_instance, teleoperation_active + + # reset environment + env.reset() + teleop_interface.reset() + + stack_name = "IsaacTeleop" if use_isaac_teleop else "native" + print(f"{stack_name} teleoperation started. Press 'R' to reset the environment.") + + # simulate environment + while simulation_app.is_running(): + try: + # run everything in inference mode + with torch.inference_mode(): + # get device command + action = teleop_interface.advance() + + if use_isaac_teleop: + ctrl = poll_control_events(teleop_interface) + if ctrl.is_active is not None: + teleoperation_active = ctrl.is_active + if ctrl.should_reset: + should_reset_recording_instance = True + + # action is None when IsaacTeleop session hasn't started yet + # (e.g. waiting for user to click "Start AR") + if action is None: + env.sim.render() + elif teleoperation_active: + # process actions + actions = action.repeat(env.num_envs, 1) + # apply actions + env.step(actions) + else: + env.sim.render() + + if should_reset_recording_instance: + env.reset() + teleop_interface.reset() + should_reset_recording_instance = False + print("Environment reset complete") + except Exception as e: + logger.error(f"Error during simulation step: {e}") + break + + # Run the teleoperation loop + # IsaacTeleop requires a context manager, native devices don't + if use_isaac_teleop: + with teleop_interface: + run_loop() + else: + run_loop() + + # close the simulator + env.close() + print("Environment closed") + + +if __name__ == "__main__": + # run the main function + main() + # env.close() already closes the USD stage via sim.clear_instance(). + # Pump the event loop so the viewport processes closure, then close the app. + simulation_app.update() + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/environments/zero_agent.py b/simulation/modules/IsaacLab/scripts/environments/zero_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..11a6135be7131d933c03f01656a5d6a06889fac4 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/environments/zero_agent.py @@ -0,0 +1,86 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to run an environment with zero action agent.""" + +import argparse +import contextlib +import sys + +import gymnasium as gym +import torch + +import isaaclab_tasks # noqa: F401 + +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + launch_simulation, + resolve_task_config, + setup_preset_cli, +) + +# add argparse arguments +parser = argparse.ArgumentParser(description="Zero agent for Isaac Lab environments.") +parser.add_argument( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +# append AppLauncher cli args +add_launcher_args(parser) +# simple agents should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args + +# PLACEHOLDER: Extension template (do not remove this comment) +MAX_STEPS = 100 + + +def main(): + """Zero actions agent with Isaac Lab environment.""" + + torch.manual_seed(42) + + # parse configuration via Hydra (supports preset selection, e.g. env.sim.physics=newton_mjwarp) + env_cfg, _ = resolve_task_config(args_cli.task, "") + + with launch_simulation(env_cfg, args_cli): + # override with CLI arguments + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + if args_cli.disable_fabric: + env_cfg.sim.use_fabric = False + + # create environment + env = gym.make(args_cli.task, cfg=env_cfg) + + # print info (this is vectorized environment) + print(f"[INFO]: Gym observation space: {env.observation_space}") + print(f"[INFO]: Gym action space: {env.action_space}") + # reset environment + env.reset() + # simulate environment + # keep running while any visualizer is open, otherwise fall back to MAX_STEPS + sim = env.unwrapped.sim + actions = torch.zeros(env.action_space.shape, device=env.unwrapped.device) + while True: + if sim.visualizers: + # visualizer mode: run until the visualizer window is closed + if not any(v.is_running() and not v.is_closed for v in sim.visualizers): + break + # run everything in inference mode + with torch.inference_mode(): + # apply actions + env.step(actions) + # close the simulator + env.close() + + +if __name__ == "__main__": + # run the main function + main() diff --git a/simulation/modules/IsaacLab/scripts/imitation_learning/isaaclab_mimic/annotate_demos.py b/simulation/modules/IsaacLab/scripts/imitation_learning/isaaclab_mimic/annotate_demos.py new file mode 100644 index 0000000000000000000000000000000000000000..0bcf87cfb1555f443b59b90d595df4d05586742e --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/imitation_learning/isaaclab_mimic/annotate_demos.py @@ -0,0 +1,537 @@ +# Copyright (c) 2024-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +""" +Script to add mimic annotations to demos to be used as source demos for mimic dataset generation. +""" + +import argparse +import math + +from isaaclab.app import AppLauncher +from isaaclab.utils.string import list_intersection, string_to_callable + +# Launching Isaac Sim Simulator first. + + +# add argparse arguments +parser = argparse.ArgumentParser(description="Annotate demonstrations for Isaac Lab environments.") +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument( + "--input_file", type=str, default="./datasets/dataset.hdf5", help="File name of the dataset to be annotated." +) +parser.add_argument( + "--output_file", + type=str, + default="./datasets/dataset_annotated.hdf5", + help="File name of the annotated output dataset file.", +) +parser.add_argument("--auto", action="store_true", default=False, help="Automatically annotate subtasks.") +parser.add_argument( + "--annotate_subtask_start_signals", + action="store_true", + default=False, + help="Enable annotating start points of subtasks.", +) + +parser.add_argument("--external_callback", default=None, help="Fully qualified path to an externally defined callback.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli, remaining_args = parser.parse_known_args() + +# launch the simulator +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +# Call an external callback if requested. +remaining_args_env_registration = None +if args_cli.external_callback: + external_callback_function = string_to_callable(args_cli.external_callback, separator=".") + remaining_args_env_registration = external_callback_function() + +# Error on unrecognized arguments. +unrecognized_args = list_intersection(remaining_args, remaining_args_env_registration) +if unrecognized_args: + parser.error(f"unrecognized arguments: {' '.join(unrecognized_args)}") + +"""Rest everything follows.""" + +import contextlib +import os + +import gymnasium as gym +import torch + +import isaaclab_mimic.envs # noqa: F401 + +# Only enables inputs if this script is NOT headless mode +if not args_cli.headless and not os.environ.get("HEADLESS", 0): + from isaaclab.devices import Se3Keyboard, Se3KeyboardCfg + +from isaaclab.envs import ManagerBasedRLMimicEnv +from isaaclab.envs.mdp.recorders.recorders_cfg import ActionStateRecorderManagerCfg +from isaaclab.managers import RecorderTerm, RecorderTermCfg, TerminationTermCfg +from isaaclab.utils.configclass import configclass +from isaaclab.utils.datasets import EpisodeData, HDF5DatasetFileHandler + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils.parse_cfg import parse_env_cfg + +is_paused = False +current_action_index = 0 +marked_subtask_action_indices = [] +skip_episode = False + + +def play_cb(): + global is_paused + is_paused = False + + +def pause_cb(): + global is_paused + is_paused = True + + +def skip_episode_cb(): + global skip_episode + skip_episode = True + + +def mark_subtask_cb(): + global current_action_index, marked_subtask_action_indices + marked_subtask_action_indices.append(current_action_index) + print(f"Marked a subtask signal at action index: {current_action_index}") + + +class PreStepDatagenInfoRecorder(RecorderTerm): + """Recorder term that records the datagen info data in each step.""" + + def record_pre_step(self): + eef_pose_dict = {} + for eef_name in self._env.cfg.subtask_configs.keys(): + eef_pose_dict[eef_name] = self._env.get_robot_eef_pose(eef_name=eef_name) + + datagen_info = { + "object_pose": self._env.get_object_poses(), + "eef_pose": eef_pose_dict, + "target_eef_pose": self._env.action_to_target_eef_pose(self._env.action_manager.action), + } + return "obs/datagen_info", datagen_info + + +@configclass +class PreStepDatagenInfoRecorderCfg(RecorderTermCfg): + """Configuration for the datagen info recorder term.""" + + class_type: type[RecorderTerm] = PreStepDatagenInfoRecorder + + +class PreStepSubtaskStartsObservationsRecorder(RecorderTerm): + """Recorder term that records the subtask start observations in each step.""" + + def record_pre_step(self): + return "obs/datagen_info/subtask_start_signals", self._env.get_subtask_start_signals() + + +@configclass +class PreStepSubtaskStartsObservationsRecorderCfg(RecorderTermCfg): + """Configuration for the subtask start observations recorder term.""" + + class_type: type[RecorderTerm] = PreStepSubtaskStartsObservationsRecorder + + +class PreStepSubtaskTermsObservationsRecorder(RecorderTerm): + """Recorder term that records the subtask completion observations in each step.""" + + def record_pre_step(self): + return "obs/datagen_info/subtask_term_signals", self._env.get_subtask_term_signals() + + +@configclass +class PreStepSubtaskTermsObservationsRecorderCfg(RecorderTermCfg): + """Configuration for the step subtask terms observation recorder term.""" + + class_type: type[RecorderTerm] = PreStepSubtaskTermsObservationsRecorder + + +@configclass +class MimicRecorderManagerCfg(ActionStateRecorderManagerCfg): + """Mimic specific recorder terms.""" + + record_pre_step_datagen_info = PreStepDatagenInfoRecorderCfg() + record_pre_step_subtask_start_signals = PreStepSubtaskStartsObservationsRecorderCfg() + record_pre_step_subtask_term_signals = PreStepSubtaskTermsObservationsRecorderCfg() + + +def main(): + """Add Isaac Lab Mimic annotations to the given demo dataset file.""" + global is_paused, current_action_index, marked_subtask_action_indices + + # Load input dataset to be annotated + if not os.path.exists(args_cli.input_file): + raise FileNotFoundError(f"The input dataset file {args_cli.input_file} does not exist.") + dataset_file_handler = HDF5DatasetFileHandler() + dataset_file_handler.open(args_cli.input_file) + env_name = dataset_file_handler.get_env_name() + episode_count = dataset_file_handler.get_num_episodes() + + if episode_count == 0: + print("No episodes found in the dataset.") + return 0 + + # get output directory path and file name (without extension) from cli arguments + output_dir = os.path.dirname(args_cli.output_file) + output_file_name = os.path.splitext(os.path.basename(args_cli.output_file))[0] + # create output directory if it does not exist + if not os.path.exists(output_dir): + os.makedirs(output_dir) + + if args_cli.task is not None: + env_name = args_cli.task.split(":")[-1] + if env_name is None: + raise ValueError("Task/env name was not specified nor found in the dataset.") + + env_cfg = parse_env_cfg(env_name, device=args_cli.device, num_envs=1) + + env_cfg.env_name = env_name + + # extract success checking function to invoke manually + success_term = None + if hasattr(env_cfg.terminations, "success"): + success_term = env_cfg.terminations.success + env_cfg.terminations.success = None + else: + raise NotImplementedError("No success termination term was found in the environment.") + + # Disable all termination terms + env_cfg.terminations = None + + # Set up recorder terms for mimic annotations + env_cfg.recorders = MimicRecorderManagerCfg() + if not args_cli.auto: + # disable subtask term signals recorder term if in manual mode + env_cfg.recorders.record_pre_step_subtask_term_signals = None + + if not args_cli.auto or (args_cli.auto and not args_cli.annotate_subtask_start_signals): + # disable subtask start signals recorder term if in manual mode or no need for subtask start annotations + env_cfg.recorders.record_pre_step_subtask_start_signals = None + + env_cfg.recorders.dataset_export_dir_path = output_dir + env_cfg.recorders.dataset_filename = output_file_name + + # create environment from loaded config + env: ManagerBasedRLMimicEnv = gym.make(args_cli.task, cfg=env_cfg).unwrapped + + if not isinstance(env, ManagerBasedRLMimicEnv): + raise ValueError("The environment should be derived from ManagerBasedRLMimicEnv") + + if args_cli.auto: + # check if the mimic API env.get_subtask_term_signals() is implemented + if env.get_subtask_term_signals.__func__ is ManagerBasedRLMimicEnv.get_subtask_term_signals: + raise NotImplementedError( + "The environment does not implement the get_subtask_term_signals method required " + "to run automatic annotations." + ) + if ( + args_cli.annotate_subtask_start_signals + and env.get_subtask_start_signals.__func__ is ManagerBasedRLMimicEnv.get_subtask_start_signals + ): + raise NotImplementedError( + "The environment does not implement the get_subtask_start_signals method required " + "to run automatic annotations." + ) + else: + # get subtask termination signal names for each eef from the environment configs + subtask_term_signal_names = {} + subtask_start_signal_names = {} + for eef_name, eef_subtask_configs in env.cfg.subtask_configs.items(): + subtask_start_signal_names[eef_name] = ( + [subtask_config.subtask_term_signal for subtask_config in eef_subtask_configs] + if args_cli.annotate_subtask_start_signals + else [] + ) + subtask_term_signal_names[eef_name] = [ + subtask_config.subtask_term_signal for subtask_config in eef_subtask_configs + ] + # Validation: if annotating start signals, every subtask (including the last) must have a name + if args_cli.annotate_subtask_start_signals: + if any(name in (None, "") for name in subtask_start_signal_names[eef_name]): + raise ValueError( + f"Missing 'subtask_term_signal' for one or more subtasks in eef '{eef_name}'. When" + " '--annotate_subtask_start_signals' is enabled, each subtask (including the last) must" + " specify 'subtask_term_signal'. The last subtask's term signal name is used as the final" + " start signal name." + ) + # no need to annotate the last subtask term signal, so remove it from the list + subtask_term_signal_names[eef_name].pop() + + # reset environment + env.reset() + + # Only enables inputs if this script is NOT headless mode + if not args_cli.headless and not os.environ.get("HEADLESS", 0): + keyboard_interface = Se3Keyboard(Se3KeyboardCfg(pos_sensitivity=0.1, rot_sensitivity=0.1)) + keyboard_interface.add_callback("N", play_cb) + keyboard_interface.add_callback("B", pause_cb) + keyboard_interface.add_callback("Q", skip_episode_cb) + if not args_cli.auto: + keyboard_interface.add_callback("S", mark_subtask_cb) + keyboard_interface.reset() + + # simulate environment -- run everything in inference mode + exported_episode_count = 0 + processed_episode_count = 0 + successful_task_count = 0 # Counter for successful task completions + with contextlib.suppress(KeyboardInterrupt) and torch.inference_mode(): + while simulation_app.is_running() and not simulation_app.is_exiting(): + # Iterate over the episodes in the loaded dataset file + for episode_index, episode_name in enumerate(dataset_file_handler.get_episode_names()): + processed_episode_count += 1 + print(f"\nAnnotating episode #{episode_index} ({episode_name})") + episode = dataset_file_handler.load_episode(episode_name, env.device) + + is_episode_annotated_successfully = False + if args_cli.auto: + is_episode_annotated_successfully = annotate_episode_in_auto_mode(env, episode, success_term) + else: + is_episode_annotated_successfully = annotate_episode_in_manual_mode( + env, episode, success_term, subtask_term_signal_names, subtask_start_signal_names + ) + + if is_episode_annotated_successfully and not skip_episode: + # set success to the recorded episode data and export to file + env.recorder_manager.set_success_to_episodes( + None, torch.tensor([[True]], dtype=torch.bool, device=env.device) + ) + env.recorder_manager.export_episodes() + exported_episode_count += 1 + successful_task_count += 1 # Increment successful task counter + print("\tExported the annotated episode.") + else: + print("\tSkipped exporting the episode due to incomplete subtask annotations.") + break + + print( + f"\nExported {exported_episode_count} (out of {processed_episode_count}) annotated" + f" episode{'s' if exported_episode_count > 1 else ''}." + ) + print( + f"Successful task completions: {successful_task_count}" + ) # This line is used by the dataset generation test case to check if the expected number of demos were annotated + print("Exiting the app.") + + # Close environment after annotation is complete + env.close() + + return successful_task_count + + +def replay_episode( + env: ManagerBasedRLMimicEnv, + episode: EpisodeData, + success_term: TerminationTermCfg | None = None, +) -> bool: + """Replays an episode in the environment. + + This function replays the given recorded episode in the environment. It can optionally check if the task + was successfully completed using a success termination condition input. + + Args: + env: The environment to replay the episode in. + episode: The recorded episode data to replay. + success_term: Optional termination term to check for task success. + + Returns: + True if the episode was successfully replayed and the success condition was met (if provided), + False otherwise. + """ + global current_action_index, skip_episode, is_paused + # read initial state and actions from the loaded episode + initial_state = episode.data["initial_state"] + actions = episode.data["actions"] + env.sim.reset() + env.recorder_manager.reset() + env.reset_to(initial_state, None, is_relative=True) + first_action = True + for action_index, action in enumerate(actions): + current_action_index = action_index + if first_action: + first_action = False + else: + while is_paused or skip_episode: + env.sim.render() + if skip_episode: + return False + continue + action_tensor = torch.Tensor(action).reshape([1, action.shape[0]]) + env.step(torch.Tensor(action_tensor)) + if success_term is not None: + if not bool(success_term.func(env, **success_term.params)[0]): + return False + return True + + +def annotate_episode_in_auto_mode( + env: ManagerBasedRLMimicEnv, + episode: EpisodeData, + success_term: TerminationTermCfg | None = None, +) -> bool: + """Annotates an episode in automatic mode. + + This function replays the given episode in the environment and checks if the task was successfully completed. + If the task was not completed, it will print a message and return False. Otherwise, it will check if all the + subtask term signals are annotated and return True if they are, False otherwise. + + Args: + env: The environment to replay the episode in. + episode: The recorded episode data to replay. + success_term: Optional termination term to check for task success. + + Returns: + True if the episode was successfully annotated, False otherwise. + """ + global skip_episode + skip_episode = False + is_episode_annotated_successfully = replay_episode(env, episode, success_term) + if skip_episode: + print("\tSkipping the episode.") + return False + if not is_episode_annotated_successfully: + print("\tThe final task was not completed.") + else: + # check if all the subtask term signals are annotated + annotated_episode = env.recorder_manager.get_episode(0) + subtask_term_signal_dict = annotated_episode.data["obs"]["datagen_info"]["subtask_term_signals"] + for signal_name, signal_flags in subtask_term_signal_dict.items(): + signal_flags = torch.tensor(signal_flags, device=env.device) + if not torch.any(signal_flags): + is_episode_annotated_successfully = False + print(f'\tDid not detect completion for the subtask "{signal_name}".') + if args_cli.annotate_subtask_start_signals: + subtask_start_signal_dict = annotated_episode.data["obs"]["datagen_info"]["subtask_start_signals"] + for signal_name, signal_flags in subtask_start_signal_dict.items(): + if not torch.any(signal_flags): + is_episode_annotated_successfully = False + print(f'\tDid not detect start for the subtask "{signal_name}".') + return is_episode_annotated_successfully + + +def annotate_episode_in_manual_mode( + env: ManagerBasedRLMimicEnv, + episode: EpisodeData, + success_term: TerminationTermCfg | None = None, + subtask_term_signal_names: dict[str, list[str]] = {}, + subtask_start_signal_names: dict[str, list[str]] = {}, +) -> bool: + """Annotates an episode in manual mode. + + This function replays the given episode in the environment and allows for manual marking of subtask term signals. + It iterates over each eef and prompts the user to mark the subtask term signals for that eef. + + Args: + env: The environment to replay the episode in. + episode: The recorded episode data to replay. + success_term: Optional termination term to check for task success. + subtask_term_signal_names: Dictionary mapping eef names to lists of subtask term signal names. + subtask_start_signal_names: Dictionary mapping eef names to lists of subtask start signal names. + Returns: + True if the episode was successfully annotated, False otherwise. + """ + global is_paused, marked_subtask_action_indices, skip_episode + # iterate over the eefs for marking subtask term signals + subtask_term_signal_action_indices = {} + subtask_start_signal_action_indices = {} + for eef_name, eef_subtask_term_signal_names in subtask_term_signal_names.items(): + eef_subtask_start_signal_names = subtask_start_signal_names[eef_name] + # skip if no subtask annotation is needed for this eef + if len(eef_subtask_term_signal_names) == 0 and len(eef_subtask_start_signal_names) == 0: + continue + + while True: + is_paused = True + skip_episode = False + print(f'\tPlaying the episode for subtask annotations for eef "{eef_name}".') + print("\tSubtask signals to annotate:") + if len(eef_subtask_start_signal_names) > 0: + print(f"\t\t- Start:\t{eef_subtask_start_signal_names}") + print(f"\t\t- Termination:\t{eef_subtask_term_signal_names}") + + print('\n\tPress "N" to begin.') + print('\tPress "B" to pause.') + print('\tPress "S" to annotate subtask signals.') + print('\tPress "Q" to skip the episode.\n') + marked_subtask_action_indices = [] + task_success_result = replay_episode(env, episode, success_term) + if skip_episode: + print("\tSkipping the episode.") + return False + + print(f"\tSubtasks marked at action indices: {marked_subtask_action_indices}") + expected_subtask_signal_count = len(eef_subtask_term_signal_names) + len(eef_subtask_start_signal_names) + if task_success_result and expected_subtask_signal_count == len(marked_subtask_action_indices): + print(f'\tAll {expected_subtask_signal_count} subtask signals for eef "{eef_name}" were annotated.') + for marked_signal_index in range(expected_subtask_signal_count): + if args_cli.annotate_subtask_start_signals and marked_signal_index % 2 == 0: + subtask_start_signal_action_indices[ + eef_subtask_start_signal_names[int(marked_signal_index / 2)] + ] = marked_subtask_action_indices[marked_signal_index] + if not args_cli.annotate_subtask_start_signals: + # Direct mapping when only collecting termination signals + subtask_term_signal_action_indices[eef_subtask_term_signal_names[marked_signal_index]] = ( + marked_subtask_action_indices[marked_signal_index] + ) + elif args_cli.annotate_subtask_start_signals and marked_signal_index % 2 == 1: + # Every other signal is a termination when collecting both types + subtask_term_signal_action_indices[ + eef_subtask_term_signal_names[math.floor(marked_signal_index / 2)] + ] = marked_subtask_action_indices[marked_signal_index] + break + + if not task_success_result: + print("\tThe final task was not completed.") + return False + + if expected_subtask_signal_count != len(marked_subtask_action_indices): + print( + f"\tOnly {len(marked_subtask_action_indices)} out of" + f' {expected_subtask_signal_count} subtask signals for eef "{eef_name}" were' + " annotated." + ) + + print(f'\tThe episode will be replayed again for re-marking subtask signals for the eef "{eef_name}".\n') + + annotated_episode = env.recorder_manager.get_episode(0) + for ( + subtask_term_signal_name, + subtask_term_signal_action_index, + ) in subtask_term_signal_action_indices.items(): + # subtask termination signal is false until subtask is complete, and true afterwards + subtask_signals = torch.ones(len(episode.data["actions"]), dtype=torch.bool) + subtask_signals[:subtask_term_signal_action_index] = False + annotated_episode.add(f"obs/datagen_info/subtask_term_signals/{subtask_term_signal_name}", subtask_signals) + + if args_cli.annotate_subtask_start_signals: + for ( + subtask_start_signal_name, + subtask_start_signal_action_index, + ) in subtask_start_signal_action_indices.items(): + subtask_signals = torch.ones(len(episode.data["actions"]), dtype=torch.bool) + subtask_signals[:subtask_start_signal_action_index] = False + annotated_episode.add( + f"obs/datagen_info/subtask_start_signals/{subtask_start_signal_name}", subtask_signals + ) + + return True + + +if __name__ == "__main__": + # run the main function + successful_task_count = main() + # close sim app + simulation_app.close() + # exit with the number of successful task completions as return code + exit(successful_task_count) diff --git a/simulation/modules/IsaacLab/scripts/imitation_learning/isaaclab_mimic/consolidated_demo.py b/simulation/modules/IsaacLab/scripts/imitation_learning/isaaclab_mimic/consolidated_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..12bbf86b4cda8c62683f299b83a749bc5115e627 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/imitation_learning/isaaclab_mimic/consolidated_demo.py @@ -0,0 +1,474 @@ +# Copyright (c) 2024-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +""" +Script to record teleoperated demos and run mimic dataset generation in real-time. +""" + +# Launching Isaac Sim Simulator first. + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser( + description="Record demonstrations and run mimic dataset generation for Isaac Lab environments." +) +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument( + "--num_demos", type=int, default=0, help="Number of demonstrations to record. Set to 0 for infinite." +) +parser.add_argument( + "--num_success_steps", + type=int, + default=10, + help="Number of continuous steps with task success for concluding a demo as successful. Default is 10.", +) +parser.add_argument( + "--num_envs", + type=int, + default=5, + help=( + "Number of environments to instantiate to test recording and generating datasets. The environment specified by" + " `teleop_env_index` will be used for teleoperation and recording while the remaining environments will be used" + " for real-time data generation. Default is 5." + ), +) +parser.add_argument( + "--teleop_env_index", + type=int, + default=0, + help="Index of the environment to be used for teleoperation. Set -1 for disabling the teleop robot. Default is 0.", +) +parser.add_argument("--teleop_device", type=str, default="keyboard", help="Device for interacting with environment.") +parser.add_argument( + "--step_hz", type=int, default=0, help="Environment stepping rate in Hz. Set to 0 for maximum speed." +) +parser.add_argument("--input_file", type=str, default=None, help="File path to the source demo dataset file.") +parser.add_argument( + "--output_file", + type=str, + default="./datasets/output_dataset.hdf5", + help="File path to export recorded episodes.", +) +parser.add_argument( + "--generated_output_file", + type=str, + default=None, + help="File path to export generated episodes by mimic.", +) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch the simulator +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import asyncio +import contextlib +import os +import random +import time + +import gymnasium as gym +import numpy as np +import torch + +from isaaclab.devices import Se3Keyboard, Se3KeyboardCfg, Se3SpaceMouse, Se3SpaceMouseCfg +from isaaclab.envs import ManagerBasedRLMimicEnv +from isaaclab.envs.mdp.recorders.recorders_cfg import ActionStateRecorderManagerCfg +from isaaclab.managers import DatasetExportMode, RecorderTerm, RecorderTermCfg +from isaaclab.utils.configclass import configclass +from isaaclab.utils.datasets import HDF5DatasetFileHandler + +import isaaclab_mimic.envs # noqa: F401 +from isaaclab_mimic.datagen.data_generator import DataGenerator +from isaaclab_mimic.datagen.datagen_info_pool import DataGenInfoPool + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils.parse_cfg import parse_env_cfg + +# global variable to keep track of the data generation statistics +num_recorded = 0 +num_success = 0 +num_failures = 0 +num_attempts = 0 + + +class PreStepDatagenInfoRecorder(RecorderTerm): + """Recorder term that records the datagen info data in each step.""" + + def record_pre_step(self): + eef_pose_dict = {} + for eef_name in self._env.cfg.subtask_configs.keys(): + eef_pose_dict[eef_name] = self._env.get_robot_eef_pose(eef_name) + + datagen_info = { + "object_pose": self._env.get_object_poses(), + "eef_pose": eef_pose_dict, + "target_eef_pose": self._env.action_to_target_eef_pose(self._env.action_manager.action), + } + return "obs/datagen_info", datagen_info + + +@configclass +class PreStepDatagenInfoRecorderCfg(RecorderTermCfg): + """Configuration for the datagen info recorder term.""" + + class_type: type[RecorderTerm] = PreStepDatagenInfoRecorder + + +class PreStepSubtaskTermsObservationsRecorder(RecorderTerm): + """Recorder term that records the subtask completion observations in each step.""" + + def record_pre_step(self): + return "obs/datagen_info/subtask_term_signals", self._env.get_subtask_term_signals() + + +@configclass +class PreStepSubtaskTermsObservationsRecorderCfg(RecorderTermCfg): + """Configuration for the step subtask terms observation recorder term.""" + + class_type: type[RecorderTerm] = PreStepSubtaskTermsObservationsRecorder + + +@configclass +class MimicRecorderManagerCfg(ActionStateRecorderManagerCfg): + """Mimic specific recorder terms.""" + + record_pre_step_datagen_info = PreStepDatagenInfoRecorderCfg() + record_pre_step_subtask_term_signals = PreStepSubtaskTermsObservationsRecorderCfg() + + +class RateLimiter: + """Convenience class for enforcing rates in loops.""" + + def __init__(self, hz): + """ + Args: + hz (int): frequency to enforce + """ + self.hz = hz + self.last_time = time.time() + self.sleep_duration = 1.0 / hz + self.render_period = min(0.033, self.sleep_duration) + + def sleep(self, env): + """Attempt to sleep at the specified rate in hz.""" + next_wakeup_time = self.last_time + self.sleep_duration + while time.time() < next_wakeup_time: + time.sleep(self.render_period) + env.unwrapped.sim.render() + + self.last_time = self.last_time + self.sleep_duration + + # detect time jumping forwards (e.g. loop is too slow) + if self.last_time < time.time(): + while self.last_time < time.time(): + self.last_time += self.sleep_duration + + +def pre_process_actions(delta_pose: torch.Tensor, gripper_command: bool) -> torch.Tensor: + """Pre-process actions for the environment.""" + # compute actions based on environment + if "Reach" in args_cli.task: + # note: reach is the only one that uses a different action space + # compute actions + return delta_pose + else: + # resolve gripper command + gripper_vel = torch.zeros((delta_pose.shape[0], 1), dtype=torch.float, device=delta_pose.device) + gripper_vel[:] = -1 if gripper_command else 1 + # compute actions + return torch.concat([delta_pose, gripper_vel], dim=1) + + +async def run_teleop_robot( + env, env_id, env_action_queue, shared_datagen_info_pool, success_term, exported_dataset_path, teleop_interface=None +): + """Run teleop robot.""" + global num_recorded + should_reset_teleop_instance = False + # create controller if needed + if teleop_interface is None: + if args_cli.teleop_device.lower() == "keyboard": + teleop_interface = Se3Keyboard(Se3KeyboardCfg(pos_sensitivity=0.2, rot_sensitivity=0.5)) + elif args_cli.teleop_device.lower() == "spacemouse": + teleop_interface = Se3SpaceMouse(Se3SpaceMouseCfg(pos_sensitivity=0.2, rot_sensitivity=0.5)) + else: + raise ValueError( + f"Invalid device interface '{args_cli.teleop_device}'. Supported: 'keyboard', 'spacemouse'." + ) + + # add teleoperation key for reset current recording instance + def reset_teleop_instance(): + nonlocal should_reset_teleop_instance + should_reset_teleop_instance = True + + teleop_interface.add_callback("R", reset_teleop_instance) + + teleop_interface.reset() + print(teleop_interface) + + recorded_episode_dataset_file_handler = HDF5DatasetFileHandler() + recorded_episode_dataset_file_handler.create(exported_dataset_path, env_name=env.unwrapped.cfg.env_name) + + env_id_tensor = torch.tensor([env_id], dtype=torch.int64, device=env.device) + success_step_count = 0 + num_recorded = 0 + while True: + if should_reset_teleop_instance: + env.unwrapped.recorder_manager.reset(env_id_tensor) + env.unwrapped.reset(env_ids=env_id_tensor) + should_reset_teleop_instance = False + success_step_count = 0 + + # get keyboard command + delta_pose, gripper_command = teleop_interface.advance() + # convert to torch + delta_pose = torch.tensor(delta_pose, dtype=torch.float, device=env.device).repeat(1, 1) + # compute actions based on environment + teleop_action = pre_process_actions(delta_pose, gripper_command) + + await env_action_queue.put((env_id, teleop_action)) + await env_action_queue.join() + + if success_term is not None: + if bool(success_term.func(env, **success_term.params)[env_id]): + success_step_count += 1 + if success_step_count >= args_cli.num_success_steps: + env.recorder_manager.set_success_to_episodes( + env_id_tensor, torch.tensor([[True]], dtype=torch.bool, device=env.device) + ) + teleop_episode = env.unwrapped.recorder_manager.get_episode(env_id) + await shared_datagen_info_pool.add_episode(teleop_episode) + + recorded_episode_dataset_file_handler.write_episode(teleop_episode) + recorded_episode_dataset_file_handler.flush() + env.recorder_manager.reset(env_id_tensor) + num_recorded += 1 + should_reset_teleop_instance = True + else: + success_step_count = 0 + + +async def run_data_generator( + env, env_id, env_action_queue, shared_datagen_info_pool, success_term, pause_subtask=False, export_demo=True +): + """Run data generator.""" + global num_success, num_failures, num_attempts + data_generator = DataGenerator(env=env.unwrapped, src_demo_datagen_info_pool=shared_datagen_info_pool) + idle_action = torch.zeros(env.unwrapped.action_space.shape)[0] + while True: + while data_generator.src_demo_datagen_info_pool.num_datagen_infos < 1: + await env_action_queue.put((env_id, idle_action)) + await env_action_queue.join() + + results = await data_generator.generate( + env_id=env_id, + success_term=success_term, + env_action_queue=env_action_queue, + select_src_per_subtask=env.unwrapped.cfg.datagen_config.generation_select_src_per_subtask, + transform_first_robot_pose=env.unwrapped.cfg.datagen_config.generation_transform_first_robot_pose, + interpolate_from_last_target_pose=env.unwrapped.cfg.datagen_config.generation_interpolate_from_last_target_pose, + pause_subtask=pause_subtask, + export_demo=export_demo, + ) + if bool(results["success"]): + num_success += 1 + else: + num_failures += 1 + num_attempts += 1 + + +def env_loop(env, env_action_queue, shared_datagen_info_pool, asyncio_event_loop): + """Main loop for the environment.""" + global num_recorded, num_success, num_failures, num_attempts + prev_num_attempts = 0 + prev_num_recorded = 0 + + rate_limiter = None + if args_cli.step_hz > 0: + rate_limiter = RateLimiter(args_cli.step_hz) + + # simulate environment -- run everything in inference mode + is_first_print = True + with contextlib.suppress(KeyboardInterrupt) and torch.inference_mode(): + while True: + actions = torch.zeros(env.unwrapped.action_space.shape) + + # get actions from all the data generators + for i in range(env.unwrapped.num_envs): + # an async-blocking call to get an action from a data generator + env_id, action = asyncio_event_loop.run_until_complete(env_action_queue.get()) + actions[env_id] = action + + # perform action on environment + env.step(actions) + + # mark done so the data generators can continue with the step results + for i in range(env.unwrapped.num_envs): + env_action_queue.task_done() + + if prev_num_attempts != num_attempts or prev_num_recorded != num_recorded: + prev_num_attempts = num_attempts + prev_num_recorded = num_recorded + generated_sucess_rate = 100 * num_success / num_attempts if num_attempts > 0 else 0.0 + if is_first_print: + is_first_print = False + else: + print("\r", "\033[F" * 5, end="") + print("") + print("*" * 50, "\033[K") + print(f"{num_recorded} teleoperated demos recorded\033[K") + print( + f"{num_success}/{num_attempts} ({generated_sucess_rate:.1f}%) successful demos generated by" + " mimic\033[K" + ) + print("*" * 50, "\033[K") + + if args_cli.num_demos > 0 and num_recorded >= args_cli.num_demos: + print(f"All {args_cli.num_demos} demonstrations recorded. Exiting the app.") + break + + # check that simulation is stopped or not + if env.unwrapped.sim.is_stopped(): + break + + if rate_limiter: + rate_limiter.sleep(env.unwrapped) + env.close() + + +def main(): + num_envs = args_cli.num_envs + + # create output directory for recorded episodes if it does not exist + recorded_output_dir = os.path.dirname(args_cli.output_file) + if not os.path.exists(recorded_output_dir): + os.makedirs(recorded_output_dir) + + # check if the given input dataset file exists + if args_cli.input_file and not os.path.exists(args_cli.input_file): + raise FileNotFoundError(f"The dataset file {args_cli.input_file} does not exist.") + + # get the environment name + if args_cli.task is not None: + env_name = args_cli.task.split(":")[-1] + elif args_cli.input_file: + # if the environment name is not specified, try to get it from the dataset file + dataset_file_handler = HDF5DatasetFileHandler() + dataset_file_handler.open(args_cli.input_file) + env_name = dataset_file_handler.get_env_name() + else: + raise ValueError("Task/env name was not specified nor found in the dataset.") + + # parse configuration + env_cfg = parse_env_cfg(env_name, device=args_cli.device, num_envs=num_envs) + env_cfg.env_name = env_name + + # extract success checking function to invoke manually + success_term = None + if hasattr(env_cfg.terminations, "success"): + success_term = env_cfg.terminations.success + env_cfg.terminations.success = None + else: + raise NotImplementedError("No success termination term was found in the environment.") + + # data generator is in charge of resetting the environment + env_cfg.terminations = None + + env_cfg.observations.policy.concatenate_terms = False + + env_cfg.recorders = MimicRecorderManagerCfg() + + env_cfg.recorders.dataset_export_mode = DatasetExportMode.EXPORT_NONE + if args_cli.generated_output_file: + # create output directory for generated episodes if it does not exist + generated_output_dir = os.path.dirname(args_cli.generated_output_file) + if not os.path.exists(generated_output_dir): + os.makedirs(generated_output_dir) + generated_output_file_name = os.path.splitext(os.path.basename(args_cli.generated_output_file))[0] + env_cfg.recorders.dataset_export_dir_path = generated_output_dir + env_cfg.recorders.dataset_filename = generated_output_file_name + env_cfg.recorders.dataset_export_mode = DatasetExportMode.EXPORT_SUCCEEDED_ONLY + + # create environment + env = gym.make(args_cli.task, cfg=env_cfg) + + if not isinstance(env.unwrapped, ManagerBasedRLMimicEnv): + raise ValueError("The environment should be derived from ManagerBasedRLMimicEnv") + + # check if the mimic API env.unwrapped.get_subtask_term_signals() is implemented + if env.unwrapped.get_subtask_term_signals.__func__ is ManagerBasedRLMimicEnv.get_subtask_term_signals: + raise NotImplementedError( + "The environment does not implement the get_subtask_term_signals method required to run this script." + ) + + # set seed for generation + random.seed(env.unwrapped.cfg.datagen_config.seed) + np.random.seed(env.unwrapped.cfg.datagen_config.seed) + torch.manual_seed(env.unwrapped.cfg.datagen_config.seed) + + # reset before starting + env.reset() + + # Set up asyncio stuff + asyncio_event_loop = asyncio.get_event_loop() + env_action_queue = asyncio.Queue() + + shared_datagen_info_pool_lock = asyncio.Lock() + shared_datagen_info_pool = DataGenInfoPool( + env.unwrapped, env.unwrapped.cfg, env.unwrapped.device, asyncio_lock=shared_datagen_info_pool_lock + ) + if args_cli.input_file: + shared_datagen_info_pool.load_from_dataset_file(args_cli.input_file) + print(f"Loaded {shared_datagen_info_pool.num_datagen_infos} to datagen info pool") + + # make data generator object + data_generator_asyncio_tasks = [] + for i in range(num_envs): + if args_cli.teleop_env_index is not None and i == args_cli.teleop_env_index: + data_generator_asyncio_tasks.append( + asyncio_event_loop.create_task( + run_teleop_robot( + env, i, env_action_queue, shared_datagen_info_pool, success_term, args_cli.output_file + ) + ) + ) + continue + data_generator_asyncio_tasks.append( + asyncio_event_loop.create_task( + run_data_generator( + env, + i, + env_action_queue, + shared_datagen_info_pool, + success_term, + export_demo=bool(args_cli.generated_output_file), + ) + ) + ) + + try: + asyncio.ensure_future(asyncio.gather(*data_generator_asyncio_tasks)) + except asyncio.CancelledError: + print("Tasks were cancelled.") + + env_loop(env, env_action_queue, shared_datagen_info_pool, asyncio_event_loop) + + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + print("\nProgram interrupted by user. Exiting...") + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/imitation_learning/isaaclab_mimic/generate_dataset.py b/simulation/modules/IsaacLab/scripts/imitation_learning/isaaclab_mimic/generate_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..66657135b72a7f6d0c0de24501a499646bedc204 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/imitation_learning/isaaclab_mimic/generate_dataset.py @@ -0,0 +1,219 @@ +# Copyright (c) 2024-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +""" +Main data generation script. +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher +from isaaclab.utils.string import list_intersection, string_to_callable + +# add argparse arguments +parser = argparse.ArgumentParser(description="Generate demonstrations for Isaac Lab environments.") +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument("--generation_num_trials", type=int, help="Number of demos to be generated.", default=None) +parser.add_argument( + "--num_envs", type=int, default=1, help="Number of environments to instantiate for generating datasets." +) +parser.add_argument("--input_file", type=str, default=None, required=True, help="File path to the source dataset file.") +parser.add_argument( + "--output_file", + type=str, + default="./datasets/output_dataset.hdf5", + help="File path to export recorded and generated episodes.", +) +parser.add_argument( + "--pause_subtask", + action="store_true", + help="Pause after every subtask during generation for debugging - only useful with render flag", +) +parser.add_argument( + "--use_skillgen", + action="store_true", + default=False, + help="Use skillgen to generate motion trajectories", +) +parser.add_argument( + "--disable_dataset_compression", + action="store_true", + default=False, + help="Disables dataset compression", +) +parser.add_argument( + "--external_callback", + default=None, + help="Fully qualified path to an externally defined callback.", +) + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli, remaining_args = parser.parse_known_args() + +# launch the simulator +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +# Call an external callback if requested. +remaining_args_env_registration = None +if args_cli.external_callback: + external_callback_function = string_to_callable(args_cli.external_callback, separator=".") + remaining_args_env_registration = external_callback_function() + +# Error on unrecognized arguments. +unrecognized_args = list_intersection(remaining_args, remaining_args_env_registration) +if unrecognized_args: + parser.error(f"unrecognized arguments: {' '.join(unrecognized_args)}") + +"""Rest everything follows.""" + +import asyncio +import inspect +import logging +import random + +import gymnasium as gym +import numpy as np +import torch + +from isaaclab.envs import ManagerBasedRLMimicEnv + +import isaaclab_mimic.envs # noqa: F401 +from isaaclab_mimic.datagen.generation import env_loop, setup_async_generation, setup_env_config +from isaaclab_mimic.datagen.utils import get_env_name_from_dataset, setup_output_paths + +import isaaclab_tasks # noqa: F401 + +# import logger +logger = logging.getLogger(__name__) + + +def main(): + num_envs = args_cli.num_envs + + # Setup output paths and get env name + output_dir, output_file_name = setup_output_paths(args_cli.output_file) + task_name = args_cli.task + if task_name: + task_name = args_cli.task.split(":")[-1] + env_name = task_name or get_env_name_from_dataset(args_cli.input_file) + + # Configure environment + env_cfg, success_term = setup_env_config( + env_name=env_name, + output_dir=output_dir, + output_file_name=output_file_name, + num_envs=num_envs, + device=args_cli.device, + generation_num_trials=args_cli.generation_num_trials, + dataset_compression=not args_cli.disable_dataset_compression, + ) + + # Create environment + env = gym.make(env_name, cfg=env_cfg).unwrapped + + if not isinstance(env, ManagerBasedRLMimicEnv): + raise ValueError("The environment should be derived from ManagerBasedRLMimicEnv") + + # Check if the mimic API from this environment contains decprecated signatures + if "action_noise_dict" not in inspect.signature(env.target_eef_pose_to_action).parameters: + logger.warning( + f'The "noise" parameter in the "{env_name}" environment\'s mimic API "target_eef_pose_to_action", ' + "is deprecated. Please update the API to take action_noise_dict instead." + ) + + # Set seed for generation + random.seed(env.cfg.datagen_config.seed) + np.random.seed(env.cfg.datagen_config.seed) + torch.manual_seed(env.cfg.datagen_config.seed) + + # Reset before starting + env.reset() + + motion_planners = None + try: + if args_cli.use_skillgen: + from isaaclab_mimic.motion_planners.curobo.curobo_planner import CuroboPlanner + from isaaclab_mimic.motion_planners.curobo.curobo_planner_cfg import CuroboPlannerCfg + + # Create one motion planner per environment + motion_planners = {} + for env_id in range(num_envs): + print(f"Initializing motion planner for environment {env_id}") + # Create a config instance from the task name + planner_config = CuroboPlannerCfg.from_task_name(env_name) + + # Ensure visualization is only enabled for the first environment + # If not, sphere and plan visualization will be too slow in isaac lab + # It is efficient to visualize the spheres and plan for the first environment in rerun + if env_id != 0: + planner_config.visualize_spheres = False + planner_config.visualize_plan = False + + motion_planners[env_id] = CuroboPlanner( + env=env, + robot=env.scene["robot"], + config=planner_config, # Pass the config object + env_id=env_id, # Pass environment ID + ) + + env.cfg.datagen_config.use_skillgen = True + + # Setup and run async data generation + async_components = setup_async_generation( + env=env, + num_envs=args_cli.num_envs, + input_file=args_cli.input_file, + success_term=success_term, + pause_subtask=args_cli.pause_subtask, + motion_planners=motion_planners, # Pass the motion planners dictionary + ) + + try: + data_gen_tasks = asyncio.ensure_future(asyncio.gather(*async_components["tasks"])) + env_loop( + env, + async_components["reset_queue"], + async_components["action_queue"], + async_components["info_pool"], + async_components["event_loop"], + data_gen_tasks=data_gen_tasks, + ) + except asyncio.CancelledError: + print("Tasks were cancelled.") + finally: + # Cancel all async tasks when env_loop finishes + data_gen_tasks.cancel() + try: + # Wait for tasks to be cancelled + async_components["event_loop"].run_until_complete(data_gen_tasks) + except asyncio.CancelledError: + print("Remaining async tasks cancelled and cleaned up.") + except Exception as e: + print(f"Error cancelling remaining async tasks: {e}") + # Cleanup of motion planners and their visualizers + if motion_planners is not None: + for env_id, planner in motion_planners.items(): + if getattr(planner, "plan_visualizer", None) is not None: + print(f"Closing plan visualizer for environment {env_id}") + planner.plan_visualizer.close() + planner.plan_visualizer = None + motion_planners.clear() + finally: + # Close env after async tasks are done so success_term is never called on a closed env + env.close() + + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + print("\nProgram interrupted by user. Exiting...") + # Close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/generate_data.py b/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/generate_data.py new file mode 100644 index 0000000000000000000000000000000000000000..63b3e30f5ccd567d8aeb9fe3139eda1f8a67f733 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/generate_data.py @@ -0,0 +1,1067 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to replay demonstrations with Isaac Lab environments.""" + +import argparse +import os + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser(description="Locomanipulation SDG") +parser.add_argument("--task", type=str, help="The Isaac Lab locomanipulation SDG task to load for data generation.") +parser.add_argument("--dataset", type=str, help="The static manipulation dataset recorded via teleoperation.") +parser.add_argument("--output_file", type=str, help="The file name for the generated output dataset.") +parser.add_argument( + "--lift_step", + type=int, + help=( + "The step index in the input recording where the robot is ready to lift the object. Aka, where the grasp is" + " finished." + ), +) +parser.add_argument( + "--navigate_step", + type=int, + help=( + "The step index in the input recording where the robot is ready to navigate. Aka, where it has finished" + " lifting the object." + ), +) +parser.add_argument("--demo", type=str, default=None, help="The demo in the input dataset to use, e.g. 'demo_0'") +parser.add_argument("--num_runs", type=int, default=1, help="The number of trajectories to generate.") +parser.add_argument( + "--draw_visualization", + action="store_true", + default=False, + help="Draw the occupancy map and path planning visualization.", +) +parser.add_argument( + "--angular_gain", + type=float, + default=2.0, + help=( + "The angular gain to use for determining an angular control velocity when driving the robot during navigation." + ), +) +parser.add_argument( + "--linear_gain", + type=float, + default=1.0, + help="The linear gain to use for determining the linear control velocity when driving the robot during navigation.", +) +parser.add_argument( + "--linear_max", type=float, default=1.0, help="The maximum linear control velocity allowable during navigation." +) +parser.add_argument( + "--distance_threshold", + type=float, + default=0.2, + help="The distance threshold in meters to perform state transitions between navigation and manipulation tasks.", +) +parser.add_argument( + "--following_offset", + type=float, + default=0.6, + help=( + "The target point offset distance used for local path following during navigation. A larger value will result" + " in smoother trajectories, but may cut path corners." + ), +) +parser.add_argument( + "--angle_threshold", + type=float, + default=0.2, + help=( + "The angle threshold in radians to determine when the robot can move forward or transition between navigation" + " and manipulation tasks." + ), +) +parser.add_argument( + "--approach_distance", + type=float, + default=0.5, + help="An offset distance added to the destination to allow a buffer zone for reliably approaching the goal.", +) +parser.add_argument( + "--randomize_placement", + action="store_true", + default=False, + help="Whether or not to randomize the placement of fixtures in the scene upon environment initialization.", +) +parser.add_argument( + "--background_usd_path", + type=str, + default=None, + help="Path to the USD file for the background asset", +) +parser.add_argument( + "--background_occupancy_yaml_file", + type=str, + default=None, + help="Path to the occupancy map YAML file for the background asset", +) +parser.add_argument( + "--high_res_video", + action="store_true", + default=False, + help="Whether to use high resolution video for the robot's POV camera.", +) +parser.add_argument( + "--seed", + type=int, + default=None, + help="Random seed for reproducibility.", +) +parser.add_argument( + "--sensor_camera_view", + action="store_true", + default=False, + help="Set the Sim GUI viewport to the robot_pov_cam sensor view at the start of each episode.", +) + +AppLauncher.add_app_launcher_args(parser) +args_cli = parser.parse_args() + +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +import enum +import random +from dataclasses import dataclass + +import gymnasium as gym +import numpy as np +import torch +import warp as wp + +import omni.kit +import omni.kit.viewport.utility +import omni.usd + +from isaaclab.managers import DatasetExportMode +from isaaclab.utils.configclass import configclass +from isaaclab.utils.datasets import EpisodeData, HDF5DatasetFileHandler +from isaaclab.utils.math import convert_quat +from isaaclab.utils.seed import configure_seed + +import isaaclab_mimic.locomanipulation_sdg.envs # noqa: F401 +from isaaclab_mimic.locomanipulation_sdg.data_classes import ( + LocomanipulationSDGOutputData, +) + +if args_cli.seed is not None: + configure_seed(args_cli.seed) + +from isaaclab_mimic.locomanipulation_sdg.envs.locomanipulation_sdg_env import LocomanipulationSDGEnv +from isaaclab_mimic.locomanipulation_sdg.occupancy_map_utils import ( + OccupancyMap, + OccupancyMapDataValue, + merge_occupancy_maps, + occupancy_map_add_to_stage, +) +from isaaclab_mimic.locomanipulation_sdg.path_utils import ParameterizedPath, plan_path +from isaaclab_mimic.locomanipulation_sdg.scene_utils import RelativePose, place_randomly +from isaaclab_mimic.locomanipulation_sdg.transform_utils import transform_inv, transform_mul, transform_relative_pose + +from isaaclab_tasks.utils import parse_env_cfg + + +class LocomanipulationSDGDataGenerationState(enum.IntEnum): + """States for the locomanipulation SDG data generation state machine.""" + + GRASP_OBJECT = 0 + """Robot grasps object at start position""" + + LIFT_OBJECT = 1 + """Robot lifts object while stationary""" + + NAVIGATE = 2 + """Robot navigates to approach position with object""" + + APPROACH = 3 + """Robot approaches final goal position""" + + DROP_OFF_OBJECT = 4 + """Robot places object at end position""" + + DONE = 5 + """Task completed""" + + +@configclass +class LocomanipulationSDGControlConfig: + """Configuration for navigation control parameters.""" + + angular_gain: float = 2.0 + """Proportional gain for angular velocity control""" + + linear_gain: float = 1.0 + """Proportional gain for linear velocity control""" + + linear_max: float = 1.0 + """Maximum allowed linear velocity (m/s)""" + + distance_threshold: float = 0.2 + """Distance threshold for state transitions (m)""" + + following_offset: float = 0.6 + """Look-ahead distance for path following (m)""" + + angle_threshold: float = 0.2 + """Angular threshold for orientation control (rad)""" + + approach_distance: float = 0.5 + """Buffer distance from final goal (m)""" + + +@dataclass +class NavigationScene: + """Navigation scene data class.""" + + """The occupancy map of the navigation scene.""" + occupancy_map: OccupancyMap + """The base path helper of the navigation scene.""" + base_path_helper: ParameterizedPath + """The base goal of the navigation scene.""" + base_goal: RelativePose + """The approach goal of the navigation scene.""" + base_goal_approach: RelativePose + + +def compute_navigation_velocity( + current_pose: torch.Tensor, + target_xy: torch.Tensor, + config: LocomanipulationSDGControlConfig, +) -> tuple[torch.Tensor, torch.Tensor]: + """Compute linear and angular velocities for navigation control. + + Args: + current_pose: Current robot pose [x, y, yaw] + target_xy: Target position [x, y] + config: Navigation control configuration + + Returns: + Tuple of (linear_velocity, angular_velocity) + """ + current_xy = current_pose[:2] + current_yaw = current_pose[2] + + # Compute position and orientation errors + delta_xy = target_xy - current_xy + delta_distance = torch.sqrt(torch.sum(delta_xy**2)) + + target_yaw = torch.arctan2(delta_xy[1], delta_xy[0]) + # Normalize angle to [-π, π] + delta_yaw = target_yaw - current_yaw + delta_yaw = (delta_yaw + torch.pi) % (2 * torch.pi) - torch.pi + + # Compute control commands + angular_velocity = config.angular_gain * delta_yaw + linear_velocity = torch.clip(config.linear_gain * delta_distance, 0.0, config.linear_max) / ( + 1 + torch.abs(angular_velocity) + ) + + return linear_velocity, angular_velocity + + +def load_and_transform_recording_data( + env: LocomanipulationSDGEnv, + input_episode_data: EpisodeData, + recording_step: int, + reference_pose: torch.Tensor, + target_pose: torch.Tensor, +) -> tuple[torch.Tensor | None, torch.Tensor | None]: + """Load recording data and transform hand targets to current reference frame. + + Args: + env: The locomanipulation SDG environment + input_episode_data: Input episode data from static manipulation + recording_step: Current step in the recording + reference_pose: Original reference pose for the hand targets + target_pose: Current target pose to transform to + + Returns: + Tuple of transformed (left_hand_pose, right_hand_pose) + """ + recording_item = env.load_input_data(input_episode_data, recording_step) + if recording_item is None: + return None, None + + left_hand_pose = transform_relative_pose(recording_item.left_hand_pose_target, reference_pose, target_pose)[0] + right_hand_pose = transform_relative_pose(recording_item.right_hand_pose_target, reference_pose, target_pose)[0] + + return left_hand_pose, right_hand_pose + + +def sync_simulation_state(env: LocomanipulationSDGEnv): + """Push USD pose updates into physics, advance the sim, and sync back + + Args: + env: The locomanipulation SDG environment + """ + env.scene.write_data_to_sim() + env.sim.step(render=False) + env.scene.update(dt=env.physics_dt) + + +def _set_sensor_camera_view(): + """Set the Sim GUI viewport to display the robot_pov_cam sensor view.""" + viewport = omni.kit.viewport.utility.get_active_viewport() + if viewport is not None: + cam_prim_path = "/World/envs/env_0/Robot/torso_link/d435_link/camera" + viewport.set_active_camera(cam_prim_path) + + +def project_robot_state_into_env(env: LocomanipulationSDGEnv, input_episode_data: EpisodeData) -> torch.Tensor: + """Project the recorded robot pose and joint state into the current environment. + + Args: + env: The locomanipulation SDG environment + input_episode_data: Input episode data + + Returns: + The new robot pose + """ + initial_state = env.load_input_data(input_episode_data, 0) + recording_initial_state = input_episode_data.get_initial_state() + + object = env.scene["object"] + current_object_pose = torch.cat( + [ + torch.as_tensor(object.data.root_pos_w.torch[0:1], device=env.device, dtype=torch.float32), + torch.as_tensor(object.data.root_quat_w.torch[0:1], device=env.device, dtype=torch.float32), + ], + dim=-1, + ) # (1, 7) + + new_robot_pose = transform_mul( + current_object_pose, + transform_mul( + transform_inv(initial_state.object_pose.to(env.device)), + initial_state.base_pose.to(env.device), + ), + ) + + env.scene["robot"].write_root_pose_to_sim_index(root_pose=new_robot_pose, env_ids=[0]) + env.scene["robot"].write_root_velocity_to_sim_index( + root_velocity=torch.zeros((1, 6), device=env.device), env_ids=[0] + ) + # Update default root pose and velocity for correct state on reset + default_pose = env.scene["robot"].data.default_root_pose.torch.clone() + default_pose[0] = new_robot_pose[0] + env.scene["robot"].data.default_root_pose.warp.assign( + wp.from_torch(default_pose.to(env.device).contiguous()).view(wp.transformf) + ) + default_vel = env.scene["robot"].data.default_root_vel.torch.clone() + default_vel[0] = torch.zeros(6, device=env.device) + env.scene["robot"].data.default_root_vel.warp.assign(wp.from_torch(default_vel.to(env.device).contiguous())) + + robot_state = recording_initial_state["articulation"]["robot"] + joint_position = robot_state["joint_position"][0].to(env.device) + joint_velocity = robot_state["joint_velocity"][0].to(env.device) + + # Update default joint positions and velocities for correct state on reset + default_joint_pos = env.scene["robot"].data.default_joint_pos.torch.clone() + default_joint_pos[0] = joint_position + env.scene["robot"].data.default_joint_pos.warp.assign(wp.from_torch(default_joint_pos.to(env.device).contiguous())) + default_joint_vel = env.scene["robot"].data.default_joint_vel.torch.clone() + default_joint_vel[0] = joint_velocity + env.scene["robot"].data.default_joint_vel.warp.assign(wp.from_torch(default_joint_vel.to(env.device).contiguous())) + env.scene["robot"].write_joint_position_to_sim_index(position=joint_position[None, :], env_ids=[0]) + env.scene["robot"].write_joint_velocity_to_sim_index(velocity=joint_velocity[None, :], env_ids=[0]) + + return new_robot_pose + + +def project_object_state_into_env(env: LocomanipulationSDGEnv, input_episode_data: EpisodeData) -> torch.Tensor: + """Project the recorded object pose into the current environment. + + Args: + env: The locomanipulation SDG environment + input_episode_data: Input episode data + + Returns: + The new object pose + """ + initial_state = env.load_input_data(input_episode_data, 0) + + new_object_pose = transform_mul( + env.get_start_fixture().get_pose(), + transform_mul( + transform_inv(initial_state.fixture_pose.to(env.device)), + initial_state.object_pose.to(env.device), + ), + ) + + env.scene["object"].write_root_pose_to_sim_index(root_pose=new_object_pose, env_ids=[0]) + env.scene["object"].write_root_velocity_to_sim_index( + root_velocity=torch.zeros((1, 6), device=env.device), env_ids=[0] + ) + # Update default root pose and velocity for correct state on reset + default_pose = env.scene["object"].data.default_root_pose.torch.clone() + default_pose[0] = new_object_pose[0] + env.scene["object"].data.default_root_pose.warp.assign( + wp.from_torch(default_pose.to(env.device).contiguous()).view(wp.transformf) + ) + default_vel = env.scene["object"].data.default_root_vel.torch.clone() + default_vel[0] = torch.zeros(6, device=env.device) + env.scene["object"].data.default_root_vel.warp.assign(wp.from_torch(default_vel.to(env.device).contiguous())) + + return new_object_pose + + +def setup_navigation_scene( + env: LocomanipulationSDGEnv, + input_episode_data: EpisodeData, + approach_distance: float, + randomize_placement: bool = True, + draw_visualization: bool = False, +) -> NavigationScene | None: + """Set up the navigation scene with occupancy map and path planning. + + Args: + env: The locomanipulation SDG environment + input_episode_data: Input episode data + approach_distance: Buffer distance from final goal + randomize_placement: Whether to randomize fixture placement + draw_visualization: Whether to add occupancy map and path to the USD stage + + Returns: + NavigationScene or None if the navigation scene setup failed. + """ + + background_fixture = env.get_background_fixture() + if background_fixture is not None: + occupancy_map = background_fixture.get_occupancy_map() + fixtures = [env.get_start_fixture(), env.get_end_fixture()] + env.get_obstacle_fixtures() + if not randomize_placement: + raise ValueError("randomize_placement needs to be True when background_usd_path is provided") + else: + occupancy_map = merge_occupancy_maps( + [ + OccupancyMap.make_empty(start=(-7, -7), end=(7, 7), resolution=0.05), + env.get_start_fixture().get_occupancy_map(), + ] + ) + + fixtures = [env.get_end_fixture()] + env.get_obstacle_fixtures() + + for fixture in fixtures: + if randomize_placement: + if not place_randomly(fixture, occupancy_map.buffered_meters(0.7), num_iter=5000): + print(f"Failed to randomize fixture placement for {fixture.entity_name}", flush=True) + return None + + sync_simulation_state(env) + occupancy_map = merge_occupancy_maps([occupancy_map, fixture.get_occupancy_map()]) + + initial_state = env.load_input_data(input_episode_data, 0) + + base_goal = RelativePose( + relative_pose=transform_mul( + transform_inv(initial_state.fixture_pose.to(env.device)), + initial_state.base_pose.to(env.device), + ), + parent=env.get_end_fixture(), + ) + base_goal_approach = RelativePose( + relative_pose=torch.tensor([-approach_distance, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0], device=env.device), + parent=base_goal, + ) + + sync_simulation_state(env) + project_object_state_into_env(env, input_episode_data) + sync_simulation_state(env) + project_robot_state_into_env(env, input_episode_data) + # Flush physics writes so scene data buffers reflect the projected poses before path planning. + # Without this, env.get_base() would return the stale pre-projection position. + sync_simulation_state(env) + env.sim.render() + env.obs_buf = env.observation_manager.compute(update_history=True) + + nav_map = occupancy_map.buffered_meters(0.15) + nav_fs = nav_map.freespace_mask() + start_pos = env.get_base().get_pose()[0, :2].detach().cpu().numpy() + start_px = nav_map.world_to_pixel_numpy(start_pos[None])[0].astype(int) + sx, sy = int(start_px[0]), int(start_px[1]) + + # Clear the buffer zone around the robot's start pixel if it falls inside it. + # The robot stands adjacent to the start table so its position sits within the 0.15m buffer. + if 0 <= sy < nav_fs.shape[0] and 0 <= sx < nav_fs.shape[1] and not nav_fs[sy, sx]: + clear_r = int(0.15 / nav_map.resolution) + yy, xx = np.ogrid[: nav_map.data.shape[0], : nav_map.data.shape[1]] + nav_map.data[(xx - sx) ** 2 + (yy - sy) ** 2 <= clear_r**2] = OccupancyMapDataValue.FREESPACE + + base_path = plan_path(start=env.get_base(), end=base_goal_approach, occupancy_map=nav_map) + + if base_path is None: + return None + + base_path_helper = ParameterizedPath(base_path) + if len(base_path_helper.points) <= 2: + print(f"Base path does not have enough points: {len(base_path_helper.points)} points", flush=True) + return None + + sync_simulation_state(env) + + if draw_visualization: + occupancy_map_add_to_stage( + occupancy_map, + stage=omni.usd.get_context().get_stage(), + path="/OccupancyMap", + z_offset=0.01, + draw_path=base_path_helper.points, + ) + + return NavigationScene( + occupancy_map=occupancy_map, + base_path_helper=base_path_helper, + base_goal=base_goal, + base_goal_approach=base_goal_approach, + ) + + +def handle_grasp_state( + env: LocomanipulationSDGEnv, + input_episode_data: EpisodeData, + recording_step: int, + lift_step: int, + output_data: LocomanipulationSDGOutputData, +) -> tuple[int, LocomanipulationSDGDataGenerationState]: + """Handle the GRASP_OBJECT state logic. + + Args: + env: The environment + input_episode_data: Input episode data + recording_step: Current recording step + lift_step: Step to transition to lift phase + output_data: Output data to populate + + Returns: + Tuple of (next_recording_step, next_state) + """ + recording_item = env.load_input_data(input_episode_data, recording_step) + + # Set control targets - robot stays stationary during grasping + output_data.data_generation_state = int(LocomanipulationSDGDataGenerationState.GRASP_OBJECT) + output_data.recording_step = recording_step + output_data.base_velocity_target = torch.tensor([0.0, 0.0, 0.0], device=env.device) + + # Transform hand poses relative to object + output_data.left_hand_pose_target = transform_relative_pose( + recording_item.left_hand_pose_target, recording_item.object_pose, env.get_object().get_pose() + )[0] + output_data.right_hand_pose_target = transform_relative_pose( + recording_item.right_hand_pose_target, recording_item.base_pose, env.get_base().get_pose() + )[0] + output_data.left_hand_joint_positions_target = recording_item.left_hand_joint_positions_target + output_data.right_hand_joint_positions_target = recording_item.right_hand_joint_positions_target + + # Update state + + next_recording_step = recording_step + 1 + next_state = ( + LocomanipulationSDGDataGenerationState.LIFT_OBJECT + if next_recording_step > lift_step + else LocomanipulationSDGDataGenerationState.GRASP_OBJECT + ) + + return next_recording_step, next_state + + +def handle_lift_state( + env: LocomanipulationSDGEnv, + input_episode_data: EpisodeData, + recording_step: int, + navigate_step: int, + output_data: LocomanipulationSDGOutputData, +) -> tuple[int, LocomanipulationSDGDataGenerationState]: + """Handle the LIFT_OBJECT state logic. + + Args: + env: The environment + input_episode_data: Input episode data + recording_step: Current recording step + navigate_step: Step to transition to navigation phase + output_data: Output data to populate + + Returns: + Tuple of (next_recording_step, next_state) + """ + recording_item = env.load_input_data(input_episode_data, recording_step) + + # Set control targets - robot stays stationary during lifting + output_data.data_generation_state = int(LocomanipulationSDGDataGenerationState.LIFT_OBJECT) + output_data.recording_step = recording_step + output_data.base_velocity_target = torch.tensor([0.0, 0.0, 0.0], device=env.device) + + # Transform hand poses relative to base + output_data.left_hand_pose_target = transform_relative_pose( + recording_item.left_hand_pose_target, recording_item.base_pose, env.get_base().get_pose() + )[0] + output_data.right_hand_pose_target = transform_relative_pose( + recording_item.right_hand_pose_target, recording_item.object_pose, env.get_object().get_pose() + )[0] + output_data.left_hand_joint_positions_target = recording_item.left_hand_joint_positions_target + output_data.right_hand_joint_positions_target = recording_item.right_hand_joint_positions_target + + # Update state + next_recording_step = recording_step + 1 + next_state = ( + LocomanipulationSDGDataGenerationState.NAVIGATE + if next_recording_step > navigate_step + else LocomanipulationSDGDataGenerationState.LIFT_OBJECT + ) + + return next_recording_step, next_state + + +def handle_navigate_state( + env: LocomanipulationSDGEnv, + input_episode_data: EpisodeData, + recording_step: int, + base_path_helper: ParameterizedPath, + base_goal_approach: RelativePose, + config: LocomanipulationSDGControlConfig, + output_data: LocomanipulationSDGOutputData, +) -> LocomanipulationSDGDataGenerationState: + """Handle the NAVIGATE state logic. + + Args: + env: The environment + input_episode_data: Input episode data + recording_step: Current recording step + base_path_helper: Parameterized path for navigation + base_goal_approach: Approach pose goal + config: Navigation control configuration + output_data: Output data to populate + + Returns: + Next state + """ + recording_item = env.load_input_data(input_episode_data, recording_step) + current_pose = env.get_base().get_pose_2d()[0] + + # Find target point along path using pure pursuit algorithm + _, nearest_path_length, _, _ = base_path_helper.find_nearest(current_pose[:2]) + target_xy = base_path_helper.get_point_by_distance(distance=nearest_path_length + config.following_offset) + + # Compute navigation velocities + linear_velocity, angular_velocity = compute_navigation_velocity(current_pose, target_xy, config) + + # Set control targets + output_data.data_generation_state = int(LocomanipulationSDGDataGenerationState.NAVIGATE) + output_data.recording_step = recording_step + output_data.base_velocity_target = torch.tensor([linear_velocity, 0.0, angular_velocity], device=env.device) + + # Transform hand poses relative to base + output_data.left_hand_pose_target = transform_relative_pose( + recording_item.left_hand_pose_target, recording_item.base_pose, env.get_base().get_pose() + )[0] + output_data.right_hand_pose_target = transform_relative_pose( + recording_item.right_hand_pose_target, recording_item.base_pose, env.get_base().get_pose() + )[0] + output_data.left_hand_joint_positions_target = recording_item.left_hand_joint_positions_target + output_data.right_hand_joint_positions_target = recording_item.right_hand_joint_positions_target + + # Check if close enough to approach goal to transition + goal_xy = base_goal_approach.get_pose_2d()[0, :2] + distance_to_goal = torch.sqrt(torch.sum((current_pose[:2] - goal_xy) ** 2)) + + return ( + LocomanipulationSDGDataGenerationState.APPROACH + if distance_to_goal < config.distance_threshold + else LocomanipulationSDGDataGenerationState.NAVIGATE + ) + + +def handle_approach_state( + env: LocomanipulationSDGEnv, + input_episode_data: EpisodeData, + recording_step: int, + base_goal: RelativePose, + config: LocomanipulationSDGControlConfig, + output_data: LocomanipulationSDGOutputData, +) -> LocomanipulationSDGDataGenerationState: + """Handle the APPROACH state logic. + + Args: + env: The environment + input_episode_data: Input episode data + recording_step: Current recording step + base_goal: Final goal pose + config: Navigation control configuration + output_data: Output data to populate + + Returns: + Next state + """ + recording_item = env.load_input_data(input_episode_data, recording_step) + current_pose = env.get_base().get_pose_2d()[0] + + # Navigate directly to final goal position + goal_xy = base_goal.get_pose_2d()[0, :2] + linear_velocity, angular_velocity = compute_navigation_velocity(current_pose, goal_xy, config) + + # Set control targets + output_data.data_generation_state = int(LocomanipulationSDGDataGenerationState.APPROACH) + output_data.recording_step = recording_step + output_data.base_velocity_target = torch.tensor([linear_velocity, 0.0, angular_velocity], device=env.device) + + # Transform hand poses relative to base + output_data.left_hand_pose_target = transform_relative_pose( + recording_item.left_hand_pose_target, recording_item.base_pose, env.get_base().get_pose() + )[0] + output_data.right_hand_pose_target = transform_relative_pose( + recording_item.right_hand_pose_target, recording_item.base_pose, env.get_base().get_pose() + )[0] + output_data.left_hand_joint_positions_target = recording_item.left_hand_joint_positions_target + output_data.right_hand_joint_positions_target = recording_item.right_hand_joint_positions_target + + # Check if close enough to final goal to start drop-off + distance_to_goal = torch.sqrt(torch.sum((current_pose[:2] - goal_xy) ** 2)) + + return ( + LocomanipulationSDGDataGenerationState.DROP_OFF_OBJECT + if distance_to_goal < config.distance_threshold + else LocomanipulationSDGDataGenerationState.APPROACH + ) + + +def handle_drop_off_state( + env: LocomanipulationSDGEnv, + input_episode_data: EpisodeData, + recording_step: int, + base_goal: RelativePose, + config: LocomanipulationSDGControlConfig, + output_data: LocomanipulationSDGOutputData, +) -> tuple[int, LocomanipulationSDGDataGenerationState | None]: + """Handle the DROP_OFF_OBJECT state logic. + + Args: + env: The environment + input_episode_data: Input episode data + recording_step: Current recording step + base_goal: Final goal pose + config: Navigation control configuration + output_data: Output data to populate + + Returns: + Tuple of (next_recording_step, next_state) + """ + recording_item = env.load_input_data(input_episode_data, recording_step) + if recording_item is None: + return recording_step, None + + # Compute orientation control to face target orientation + current_pose = env.get_base().get_pose_2d()[0] + target_pose = base_goal.get_pose_2d()[0] + current_yaw = current_pose[2] + target_yaw = target_pose[2] + delta_yaw = target_yaw - current_yaw + delta_yaw = (delta_yaw + torch.pi) % (2 * torch.pi) - torch.pi + + angular_velocity = config.angular_gain * delta_yaw + linear_velocity = 0.0 # Stay in place while orienting + + # Set control targets + output_data.data_generation_state = int(LocomanipulationSDGDataGenerationState.DROP_OFF_OBJECT) + output_data.recording_step = recording_step + output_data.base_velocity_target = torch.tensor([linear_velocity, 0.0, angular_velocity], device=env.device) + + # Transform hand poses relative to end fixture + output_data.left_hand_pose_target = transform_relative_pose( + recording_item.left_hand_pose_target, + recording_item.fixture_pose, + env.get_end_fixture().get_pose(), + )[0] + output_data.right_hand_pose_target = transform_relative_pose( + recording_item.right_hand_pose_target, + recording_item.fixture_pose, + env.get_end_fixture().get_pose(), + )[0] + output_data.left_hand_joint_positions_target = recording_item.left_hand_joint_positions_target + output_data.right_hand_joint_positions_target = recording_item.right_hand_joint_positions_target + + # Continue playback if orientation is within threshold + next_recording_step = recording_step + 1 if abs(delta_yaw) < config.angle_threshold else recording_step + + return next_recording_step, LocomanipulationSDGDataGenerationState.DROP_OFF_OBJECT + + +def populate_output_data( + env: LocomanipulationSDGEnv, + output_data: LocomanipulationSDGOutputData, + base_goal: RelativePose, + base_goal_approach: RelativePose, + base_path: torch.Tensor, +): + """Populate remaining output data fields. + + Args: + env: The environment + output_data: Output data to populate + base_goal: Final goal pose + base_goal_approach: Approach goal pose + base_path: Planned navigation path + """ + output_data.base_pose = env.get_base().get_pose() + output_data.object_pose = env.get_object().get_pose() + output_data.start_fixture_pose = env.get_start_fixture().get_pose() + output_data.end_fixture_pose = env.get_end_fixture().get_pose() + output_data.base_goal_pose = base_goal.get_pose() + output_data.base_goal_approach_pose = base_goal_approach.get_pose() + output_data.base_path = base_path + + # Collect obstacle poses + obstacle_poses = [] + for obstacle in env.get_obstacle_fixtures(): + obstacle_poses.append(obstacle.get_pose()) + if obstacle_poses: + output_data.obstacle_fixture_poses = torch.cat(obstacle_poses, dim=0)[None, :] + else: + output_data.obstacle_fixture_poses = torch.empty((1, 0, 7)) # Empty tensor with correct shape + + +def replay( + env: LocomanipulationSDGEnv, + input_episode_data: EpisodeData, + lift_step: int, + navigate_step: int, + draw_visualization: bool = False, + angular_gain: float = 2.0, + linear_gain: float = 1.0, + linear_max: float = 1.0, + distance_threshold: float = 0.2, + following_offset: float = 0.6, + angle_threshold: float = 0.2, + approach_distance: float = 0.5, + randomize_placement: bool = True, + sensor_camera_view: bool = False, +) -> bool: + """Replay a locomanipulation SDG episode with state machine control. + + This function implements a state machine for locomanipulation SDG, where the robot: + 1. Grasps an object at the start position + 2. Lifts the object while stationary + 3. Navigates with the object to an approach position + 4. Approaches the final goal position + 5. Places the object at the end position + + Args: + env: The locomanipulation SDG environment + input_episode_data: Static manipulation episode data to replay + lift_step: Recording step where lifting phase begins + navigate_step: Recording step where navigation phase begins + draw_visualization: Whether to visualize occupancy map and path + angular_gain: Proportional gain for angular velocity control + linear_gain: Proportional gain for linear velocity control + linear_max: Maximum linear velocity (m/s) + distance_threshold: Distance threshold for state transitions (m) + following_offset: Look-ahead distance for path following (m) + angle_threshold: Angular threshold for orientation control (rad) + approach_distance: Buffer distance from final goal (m) + randomize_placement: Whether to randomize obstacle placement + sensor_camera_view: Whether to set the Sim GUI viewport to the robot_pov_cam sensor view + + Returns: + True if the episode ended with success termination, False otherwise. + """ + + # Reset recorder manager to clear any leftover episode data from previous runs + # This prevents duplicate exports when reset_to calls record_pre_reset + env.recorder_manager.reset(env_ids=[0]) + + # Initialize environment to starting state + env.reset_to( + state=input_episode_data.get_initial_state(), env_ids=torch.tensor([0], device=env.device), is_relative=True + ) + + # Create navigation control configuration + config = LocomanipulationSDGControlConfig( + angular_gain=angular_gain, + linear_gain=linear_gain, + linear_max=linear_max, + distance_threshold=distance_threshold, + following_offset=following_offset, + angle_threshold=angle_threshold, + approach_distance=approach_distance, + ) + + nav_scene = setup_navigation_scene( + env, input_episode_data, approach_distance, randomize_placement, draw_visualization + ) + if nav_scene is None: + print("Failed to setup navigation scene", flush=True) + return False + + if sensor_camera_view: + _set_sensor_camera_view() + + # Initialize state machine + output_data = LocomanipulationSDGOutputData() + current_state = LocomanipulationSDGDataGenerationState.GRASP_OBJECT + previous_state = None + recording_step = 0 + + # Main simulation loop with state machine + while simulation_app.is_running() and not simulation_app.is_exiting(): + if current_state != previous_state: + print(f"State changed: {current_state.name}, Recording step: {recording_step}", flush=True) + previous_state = current_state + + # Execute state-specific logic using helper functions + if current_state == LocomanipulationSDGDataGenerationState.GRASP_OBJECT: + recording_step, current_state = handle_grasp_state( + env, input_episode_data, recording_step, lift_step, output_data + ) + + elif current_state == LocomanipulationSDGDataGenerationState.LIFT_OBJECT: + recording_step, current_state = handle_lift_state( + env, input_episode_data, recording_step, navigate_step, output_data + ) + + elif current_state == LocomanipulationSDGDataGenerationState.NAVIGATE: + current_state = handle_navigate_state( + env, + input_episode_data, + recording_step, + nav_scene.base_path_helper, + nav_scene.base_goal_approach, + config, + output_data, + ) + + elif current_state == LocomanipulationSDGDataGenerationState.APPROACH: + current_state = handle_approach_state( + env, input_episode_data, recording_step, nav_scene.base_goal, config, output_data + ) + + elif current_state == LocomanipulationSDGDataGenerationState.DROP_OFF_OBJECT: + recording_step, next_state = handle_drop_off_state( + env, input_episode_data, recording_step, nav_scene.base_goal, config, output_data + ) + if next_state is None: # End of episode data + break + current_state = next_state + + # Populate additional output data fields + populate_output_data( + env, output_data, nav_scene.base_goal, nav_scene.base_goal_approach, nav_scene.base_path_helper.points + ) + + # Attach output data to environment for recording + env._locomanipulation_sdg_output_data = output_data + + # Build and execute action + action = env.build_action_vector( + base_velocity_target=output_data.base_velocity_target, + left_hand_joint_positions_target=output_data.left_hand_joint_positions_target, + right_hand_joint_positions_target=output_data.right_hand_joint_positions_target, + left_hand_pose_target=output_data.left_hand_pose_target, + right_hand_pose_target=output_data.right_hand_pose_target, + ) + _, _, reset_terminated, reset_time_outs, _ = env.step(action) + + if reset_terminated[0] or reset_time_outs[0]: + print(f"Environment terminated at state {current_state.name}, step {recording_step}", flush=True) + success_terminated = False + + # Check if termination was due to success + if hasattr(env, "termination_manager") and "success" in env.termination_manager.active_terms: + success_terminated = bool(env.termination_manager.get_term("success")[0].item()) + + if success_terminated: + print(f"Success termination at state {current_state.name}, step {recording_step}", flush=True) + else: + print(f"Non-success termination at state {current_state.name}, step {recording_step}", flush=True) + + return success_terminated + + print("Replay completed!", flush=True) + return False + + +if __name__ == "__main__": + with torch.no_grad(): + # Create environment + if args_cli.task is not None: + env_name = args_cli.task.split(":")[-1] + if env_name is None: + raise ValueError("Task/env name was not specified nor found in the dataset.") + + env_cfg = parse_env_cfg(env_name, device=args_cli.device, num_envs=1) + env_cfg.sim.device = "cpu" + env_cfg.recorders.dataset_export_dir_path = os.path.dirname(args_cli.output_file) + env_cfg.recorders.dataset_filename = os.path.basename(args_cli.output_file) + env_cfg.recorders.dataset_export_mode = DatasetExportMode.EXPORT_SUCCEEDED_ONLY + env_cfg.recorders.export_in_record_pre_reset = True + + if args_cli.background_usd_path is not None and args_cli.background_occupancy_yaml_file is not None: + env_cfg.background_usd_path = args_cli.background_usd_path + env_cfg.background_occupancy_yaml_file = args_cli.background_occupancy_yaml_file + + env_cfg.high_res_video = args_cli.high_res_video + + env = gym.make(args_cli.task, cfg=env_cfg).unwrapped + + # Load input data + input_dataset_file_handler = HDF5DatasetFileHandler() + input_dataset_file_handler.open(args_cli.dataset) + is_legacy_quat_format = input_dataset_file_handler.is_legacy_quaternion_format() + + run_id = 0 + success_runs = 0 + + while success_runs < args_cli.num_runs: + if args_cli.demo is None: + demo = random.choice(list(input_dataset_file_handler.get_episode_names())) + else: + demo = args_cli.demo + + input_episode_data = input_dataset_file_handler.load_episode(demo, args_cli.device) + + assert input_episode_data is not None + assert "actions" in input_episode_data.data + + # See G1LocomanipulationSDGEnv.build_action_vector() for the action layout; + # left_quat=[3:7], right_quat=[10:14]. + if is_legacy_quat_format: + actions = input_episode_data.data["actions"] + actions[:, 3:7] = convert_quat(actions[:, 3:7], to="xyzw") # left hand quat + actions[:, 10:14] = convert_quat(actions[:, 10:14], to="xyzw") # right hand quat + + success = replay( + env=env, + input_episode_data=input_episode_data, + lift_step=args_cli.lift_step, + navigate_step=args_cli.navigate_step, + draw_visualization=args_cli.draw_visualization, + angular_gain=args_cli.angular_gain, + linear_gain=args_cli.linear_gain, + linear_max=args_cli.linear_max, + distance_threshold=args_cli.distance_threshold, + following_offset=args_cli.following_offset, + angle_threshold=args_cli.angle_threshold, + approach_distance=args_cli.approach_distance, + randomize_placement=args_cli.randomize_placement, + sensor_camera_view=args_cli.sensor_camera_view, + ) + + run_id += 1 + + if success: + success_runs += 1 + print("successful episodes count", env.recorder_manager.exported_successful_episode_count, flush=True) + else: + print(f"Run {run_id} failed (demo={demo}), retrying...", flush=True) + + env.recorder_manager.close() + if env.viewport_camera_controller is not None: + env.viewport_camera_controller.update_view_to_world() + env.close() + + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/convert_dataset.py b/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/convert_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..85c7b26f8ffcf86d6af9d31fdf95b673e2671419 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/convert_dataset.py @@ -0,0 +1,372 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Convert locomanipulation SDG HDF5 datasets to LeRobot (GNx) format with parquet, videos, and meta.""" + +import argparse +import glob +import json +import math +import os +from pathlib import Path + +import cv2 +import h5py +import numpy as np +import pandas as pd +import tqdm +from scipy.spatial.transform import RigidTransform, Rotation + + +def pose_to_transform(pose: np.ndarray) -> RigidTransform: + """Convert a 7D pose array (position + quaternion) to a RigidTransform. + + Args: + pose: Pose array with shape (..., 7). First 3 elements are translation (x, y, z), + last 4 are quaternion in scalar-last (x, y, z, w) order, matching Isaac Lab's + current convention (see :attr:`isaaclab.assets.ArticulationData.body_link_pose_w`). + + Returns: + RigidTransform representing the pose. + """ + translation = pose[..., :3] + rotation = Rotation.from_quat(pose[..., 3:]) + return RigidTransform.from_components(translation, rotation) + + +def pose_from_transform(transform: RigidTransform) -> np.ndarray: + """Convert a RigidTransform to a 7D pose array. + + Args: + transform: The rigid transform to convert. + + Returns: + Pose array with shape (..., 7): translation (3) and quaternion (4) in scalar-last + (x, y, z, w) order, matching Isaac Lab's current convention. + """ + translation, rotation = transform.as_components() + quat = rotation.as_quat() + return np.concatenate([translation, quat], axis=-1) + + +def get_total_object_displacement(demo) -> float: + """Compute the horizontal distance the object moved between start and end of a demo. + + Args: + demo: HDF5 group or dict for one episode containing "locomanipulation_sdg_output_data" + with "object_pose" array (N, 7). + + Returns: + Euclidean distance in the xy-plane between first and last object position (meters). + """ + object_pose = demo["locomanipulation_sdg_output_data"]["object_pose"] + start_pose = object_pose[0] + end_pose = object_pose[-1] + distance = math.sqrt((start_pose[0] - end_pose[0]) ** 2 + (start_pose[1] - end_pose[1]) ** 2) + return distance + + +def compute_relative_pose(target_pose: np.ndarray, base_pose: np.ndarray) -> np.ndarray: + """Compute the pose of target relative to base. + + Args: + target_pose: 7D pose (position + quat) of the target in world frame. + base_pose: 7D pose (position + quat) of the base frame in world frame. + + Returns: + 7D pose of target expressed in base frame. + """ + base_pose = pose_to_transform(base_pose) + target_transform = pose_to_transform(target_pose) + relative_pose = pose_from_transform(base_pose.inv() * target_transform) + return relative_pose + + +def create_directory_structure(output_path: str, video_key: str = "observation.images.ego_view") -> None: + """Create the required directory structure for GNx LeRobot format. + + Creates meta/, data/chunk-000/, and videos/chunk-000// under output_path. + + Args: + output_path: Root path for the converted dataset. + video_key: Key used for the video subfolder (e.g. "observation.images.ego_view"). + """ + base_path = Path(output_path) + + (base_path / "meta").mkdir(parents=True, exist_ok=True) + + chunk_name = "chunk-000" + (base_path / "data" / chunk_name).mkdir(parents=True, exist_ok=True) + (base_path / "videos" / chunk_name / video_key).mkdir(parents=True, exist_ok=True) + + print(f"Created directory structure at {output_path}") + + +def extract_video_from_images(images: np.ndarray, output_path: str, fps: float = 20.0) -> None: + """Convert an image sequence to an MP4 video file. + + Args: + images: Image array of shape (S, H, W, C) in RGB, uint8 or float in [0, 1]. + output_path: Path for the output MP4 file. + fps: Frames per second for the output video. + """ + if len(images.shape) != 4: # Expected: [S, H, W, C] + raise ValueError(f"Expected 4D image array [S, H, W, C], got shape {images.shape}") + + S, H, W, C = images.shape + + if images.dtype != np.uint8: + if images.dtype in [np.float32, np.float64]: + if images.max() <= 1.0: + images = (images * 255).astype(np.uint8) + else: + images = np.clip(images, 0, 255).astype(np.uint8) + else: + images = np.clip(images, 0, 255).astype(np.uint8) + + fourcc = cv2.VideoWriter_fourcc(*"mp4v") + video_writer = cv2.VideoWriter(output_path, fourcc, fps, (W, H)) + + for s in tqdm.tqdm(range(S)): + frame = images[s] + if C == 3: + frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) + video_writer.write(frame) + + video_writer.release() + print(f"Created video: {output_path}") + + +def create_modality_json(state: dict, action: dict) -> dict: + """Build the modality.json structure for LeRobot format. + + Maps state and action key names to start/end indices in the concatenated state and + action vectors, and adds fixed video and annotation keys. + + Args: + state: Dict mapping state key names to arrays of shape (T, dim). + action: Dict mapping action key names to arrays of shape (T, dim). + + Returns: + Modality dict with "state", "action", "video", and "annotation" entries. + """ + modality = { + "state": {}, + "action": {}, + "video": {"ego_view": {"original_key": "observation.images.ego_view"}}, + "annotation": { + "human.action.task_description": {"original_key": "annotation.human.action.task_description"}, + "human.validity": {"original_key": "annotation.human.validity"}, + }, + } + + index = 0 + for k, v in state.items(): + modality["state"][k] = {"start": index, "end": index + v.shape[1]} + index = modality["state"][k]["end"] + + index = 0 + for k, v in action.items(): + modality["action"][k] = {"start": index, "end": index + v.shape[1]} + index = modality["action"][k]["end"] + + return modality + + +def create_info_json( + total_episodes: int, + total_frames: int, + state_dim: int, + action_dim: int, + fps: float = 20.0, + image_shape: tuple[int, int, int] = (160, 256, 3), + video_key: str = "observation.images.ego_view", +) -> dict: + """Create the info.json file content for LeRobot dataset metadata. + + Args: + total_episodes: Number of episodes in the dataset. + total_frames: Total number of frames across all episodes. + state_dim: Dimension of the concatenated state vector. + action_dim: Dimension of the concatenated action vector. + fps: Frames per second for video and timestamps. + image_shape: (height, width, channels) for video feature. + video_key: Key used for the video feature (e.g. "observation.images.ego_view"). + + Returns: + Dict suitable for writing to meta/info.json (codebase_version, features, paths, etc.). + """ + features = { + "observation.state": { + "dtype": "float64", + "shape": [state_dim], + "names": [f"state_{i}" for i in range(state_dim)], + }, + "action": {"dtype": "float64", "shape": [action_dim], "names": [f"action_{i}" for i in range(action_dim)]}, + "timestamp": {"dtype": "float64", "shape": [1]}, + "annotation.human.action.task_description": {"dtype": "int64", "shape": [1]}, + "task_index": {"dtype": "int64", "shape": [1]}, + "annotation.human.validity": {"dtype": "int64", "shape": [1]}, + "episode_index": {"dtype": "int64", "shape": [1]}, + "index": {"dtype": "int64", "shape": [1]}, + video_key: { + "dtype": "video", + "shape": list(image_shape), + "names": ["height", "width", "channel"], + "video_info": { + "video.fps": fps, + "video.codec": "h264", + "video.pix_fmt": "yuv420p", + "video.is_depth_map": False, + "has_audio": False, + }, + }, + } + + info = { + "codebase_version": "v2.0", + "robot_type": "custom", + "total_episodes": total_episodes, + "total_frames": total_frames, + "total_tasks": 2, + "total_videos": total_episodes, + "total_chunks": 0, + "chunks_size": 1000, + "fps": fps, + "splits": {"train": "0:100"}, + "data_path": "data/chunk-{episode_chunk:03d}/episode_{episode_index:06d}.parquet", + "video_path": "videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4", + "features": features, + } + + return info + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + parser.add_argument("input_dir", type=str) + parser.add_argument("output_path", type=str) + + args = parser.parse_args() + + output_path = args.output_path + + create_directory_structure(output_path) + dataset_paths = glob.glob(os.path.join(args.input_dir, "*.hdf5")) + + total_episodes = 0 + total_frames = 0 + episodes_data = [] + + fps = 20.0 + task_description = "Pick up and drop off the object" + + for dataset_path in dataset_paths: + dataset = h5py.File(dataset_path, "r") + + for demo_name in dataset["data"].keys(): + demo = dataset["data"][demo_name] + + if get_total_object_displacement(demo) < 2.0: + continue + + base_pose = demo["locomanipulation_sdg_output_data"]["base_pose"] + + state = { + "left_hand_pose": compute_relative_pose( + np.concatenate([demo["obs"]["left_eef_pos"], demo["obs"]["left_eef_quat"]], axis=-1), base_pose + ), + "right_hand_pose": compute_relative_pose( + np.concatenate([demo["obs"]["right_eef_pos"], demo["obs"]["right_eef_quat"]], axis=-1), base_pose + ), + "left_hand_joint_positions": demo["obs"]["hand_joint_state"][:, 0:7], + "right_hand_joint_positions": demo["obs"]["hand_joint_state"][:, 7:14], + "object_pose": compute_relative_pose( + demo["locomanipulation_sdg_output_data"]["object_pose"], base_pose + ), + "goal_pose": compute_relative_pose( + demo["locomanipulation_sdg_output_data"]["base_goal_pose"], base_pose + ), + "end_fixture_pose": compute_relative_pose( + demo["locomanipulation_sdg_output_data"]["end_fixture_pose"], base_pose + ), + } + + obs = {"image": demo["obs"]["robot_pov_cam"][:]} + + action = { + "left_hand_pose": compute_relative_pose(demo["actions"][:, 0:7], base_pose), + "right_hand_pose": compute_relative_pose(demo["actions"][:, 7:14], base_pose), + "left_hand_joint_positions": demo["actions"][:, 14:21], + "right_hand_joint_positions": demo["actions"][:, 21:28], + "base_velocity": demo["actions"][:, 28:31], + "base_height": demo["actions"][:, 31:32], + } + + episode_duration = len(base_pose) + + timestamps = np.arange(episode_duration, dtype=np.float64) / fps + state_concat = np.concatenate([v for v in state.values()], axis=-1) + action_concat = np.concatenate([v for v in action.values()], axis=-1) + + parquet_data = { + "observation.state": state_concat.tolist(), + "action": action_concat.tolist(), + "timestamp": timestamps.tolist(), + "annotation.human.action.task_description": [0] * episode_duration, + "task_index": [0] * episode_duration, + "annotation.human.validity": [1] * episode_duration, + "episode_index": [total_episodes] * episode_duration, + "index": list(range(total_frames, total_frames + episode_duration)), + } + + df = pd.DataFrame(parquet_data) + parquet_path = Path(output_path) / "data" / "chunk-000" / f"episode_{total_episodes:06d}.parquet" + df.to_parquet(parquet_path, index=False) + + video_path = ( + Path(output_path) + / "videos" + / "chunk-000" + / "observation.images.ego_view" + / f"episode_{total_episodes:06d}.mp4" + ) + extract_video_from_images(obs["image"], str(video_path), fps) + + episodes_data.append( + { + "episode_index": total_episodes, + "tasks": [task_description, "valid"], # Task description and validity + "length": episode_duration, + } + ) + + total_episodes += 1 + total_frames += episode_duration + + state_dim = sum(v.shape[1] for v in state.values()) + action_dim = sum(v.shape[1] for v in action.values()) + + modality_json = create_modality_json(state, action) + + with open(os.path.join(output_path, "meta", "modality.json"), "w") as f: + json.dump(modality_json, f, indent=2) + + info_json = create_info_json( + total_episodes=total_episodes, total_frames=total_frames, state_dim=state_dim, action_dim=action_dim + ) + + with open(os.path.join(output_path, "meta", "info.json"), "w") as f: + json.dump(info_json, f, indent=2) + + with open(os.path.join(output_path, "meta", "episodes.jsonl"), "w") as f: + for episode in episodes_data: + f.write(json.dumps(episode) + "\n") + + tasks_data = [{"task_index": 0, "task": task_description}, {"task_index": 1, "task": "valid"}] + with open(os.path.join(output_path, "meta", "tasks.jsonl"), "w") as f: + for task in tasks_data: + f.write(json.dumps(task) + "\n") diff --git a/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/data_config.py b/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/data_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f7365cb3a2b4bba3f4d916a12da89341624ef265 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/data_config.py @@ -0,0 +1,275 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. + +from abc import ABC, abstractmethod +from dataclasses import dataclass + +from gr00t.data.dataset import ModalityConfig +from gr00t.data.transform.base import ComposedModalityTransform, ModalityTransform +from gr00t.data.transform.concat import ConcatTransform +from gr00t.data.transform.state_action import ( + StateActionToTensor, + StateActionTransform, +) +from gr00t.data.transform.video import ( + VideoColorJitter, + VideoCrop, + VideoResize, + VideoToNumpy, + VideoToTensor, +) +from gr00t.model.transforms import GR00TTransform + + +@dataclass +class BaseDataConfig(ABC): + """Base class for GR00T data configurations defining modalities and transforms.""" + + def modality_config(self) -> dict[str, ModalityConfig]: + """Build the modality config mapping (video, state, action, language) for the dataset. + + Returns: + Dict mapping modality names to ModalityConfig instances. + """ + video_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.video_keys, + ) + state_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.state_keys, + ) + action_modality = ModalityConfig( + delta_indices=self.action_indices, + modality_keys=self.action_keys, + ) + language_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.language_keys, + ) + return { + "video": video_modality, + "state": state_modality, + "action": action_modality, + "language": language_modality, + } + + @abstractmethod + def transform(self) -> ModalityTransform: + """Return the composed modality transform (video, state, action, concat, model-specific). + + Returns: + ModalityTransform to apply to dataset samples. + """ + pass + + +##################################################################################### +# helper functions +##################################################################################### + + +def import_external_data_config(data_config_str: str) -> BaseDataConfig | None: + """Import and instantiate an external data configuration class. + + Format: "module_path:ClassName" (e.g., "my_configs:RobotConfig"). + Supports nested modules like "package.submodule:ClassName". + The current working directory is prepended to sys.path for resolution. + + Args: + data_config_str: String in "module_path:ClassName" format. If no ":" is present, + returns None. + + Returns: + Instance of the requested config class, or None if data_config_str has no ":". + """ + if ":" not in data_config_str: + return None + + import importlib + import os + import sys + from pathlib import Path + + # Add current working directory to Python path + current_dir = str(Path(os.getcwd()).absolute()) + if current_dir not in sys.path: + sys.path.insert(0, current_dir) + + try: + module_path, class_name = data_config_str.split(":", 1) + if not module_path or not class_name: + raise ValueError(f"Invalid format: '{data_config_str}'. Use 'module:ClassName'") + + print(f"Loading external config: {module_path}.{class_name}") + + module = importlib.import_module(module_path) + if not hasattr(module, class_name): + available = [n for n in dir(module) if not n.startswith("_") and isinstance(getattr(module, n), type)] + raise AttributeError(f"Class '{class_name}' not found in '{module_path}'. Available: {available}") + + if not hasattr(getattr(module, class_name), "transform"): + raise AttributeError(f"Class '{class_name}' does not have a 'transform' method") + if not hasattr(getattr(module, class_name), "modality_config"): + raise AttributeError(f"Class '{class_name}' does not have a 'modality_config' method") + + return getattr(module, class_name)() + + except (ModuleNotFoundError, AttributeError, ValueError) as e: + print(f"Config loading failed: {e}") + print("Example: my_configs:MyConfig, package.submodule:ClassName") + raise + + +def load_data_config(data_config_str: str) -> BaseDataConfig: + """Resolve a data config from a short name or external module:class string. + + First looks up the string in DATA_CONFIG_MAP; if not found, tries to import + and instantiate via import_external_data_config (e.g. "my_package.configs:MyConfig"). + + Args: + data_config_str: Short name (e.g. "g1_locomanipulation_sdg") or "module_path:ClassName". + + Returns: + The corresponding BaseDataConfig instance. + """ + if data_config_str in DATA_CONFIG_MAP: + return DATA_CONFIG_MAP[data_config_str] + data_config_cls = import_external_data_config(data_config_str) + if data_config_cls is not None: + return data_config_cls + yellow = "\033[93m" + reset = "\033[0m" + raise ValueError( + f"{yellow}Invalid data_config '{data_config_str}'. " + f"Available options: {list(DATA_CONFIG_MAP.keys())}, " + f"or use 'module:ClassName' for external configs{reset}" + ) + + +########################################################################################### + + +class G1LocomanipulationSDGDataConfig(BaseDataConfig): + """Data config for G1 locomanipulation SDG (video, state, action; no language).""" + + video_keys = ["video.ego_view"] + state_keys = [ + "state.left_hand_pose", + "state.right_hand_pose", + "state.left_hand_joint_positions", + "state.right_hand_joint_positions", + "state.object_pose", + "state.goal_pose", + "state.end_fixture_pose", + ] + action_keys = [ + "action.left_hand_pose", + "action.right_hand_pose", + "action.left_hand_joint_positions", + "action.right_hand_joint_positions", + "action.base_velocity", + "action.base_height", + ] + observation_indices = [0] + action_indices = list(range(16)) + + def modality_config(self) -> dict[str, ModalityConfig]: + """Build modality config for video, state, and action (no language). + + Returns: + Dict with "video", "state", and "action" ModalityConfig entries. + """ + video_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.video_keys, + ) + + state_modality = ModalityConfig( + delta_indices=self.observation_indices, + modality_keys=self.state_keys, + ) + + action_modality = ModalityConfig( + delta_indices=self.action_indices, + modality_keys=self.action_keys, + ) + + modality_configs = { + "video": video_modality, + "state": state_modality, + "action": action_modality, + } + + return modality_configs + + def transform(self) -> ModalityTransform: + """Composed transform: video (crop, resize, color jitter), state/action (tensor, normalize), concat, GR00T. + + Returns: + ComposedModalityTransform for locomanipulation SDG samples. + """ + transforms = [ + # video transforms + VideoToTensor(apply_to=self.video_keys), + VideoCrop(apply_to=self.video_keys, scale=0.95), + VideoResize(apply_to=self.video_keys, height=224, width=224, interpolation="linear"), + VideoColorJitter( + apply_to=self.video_keys, + brightness=0.3, + contrast=0.4, + saturation=0.5, + hue=0.08, + ), + VideoToNumpy(apply_to=self.video_keys), + # state transforms + StateActionToTensor(apply_to=self.state_keys), + StateActionTransform( + apply_to=self.state_keys, + normalization_modes={key: "min_max" for key in self.state_keys}, + ), + # action transforms + StateActionToTensor(apply_to=self.action_keys), + StateActionTransform( + apply_to=self.action_keys, + normalization_modes={key: "min_max" for key in self.action_keys}, + ), + # concat transforms + ConcatTransform( + video_concat_order=self.video_keys, + state_concat_order=self.state_keys, + action_concat_order=self.action_keys, + ), + # model-specific transform + GR00TTransform( + state_horizon=len(self.observation_indices), + action_horizon=len(self.action_indices), + max_state_dim=64, + max_action_dim=32, + ), + ] + return ComposedModalityTransform(transforms=transforms) + + +########################################################################################### + +DATA_CONFIG_MAP = { + "g1_locomanipulation_sdg": G1LocomanipulationSDGDataConfig(), +} diff --git a/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/no_flash_attn.patch b/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/no_flash_attn.patch new file mode 100644 index 0000000000000000000000000000000000000000..0085ec98241f501d86f37b11851657e5dacfcb14 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/no_flash_attn.patch @@ -0,0 +1,63 @@ +diff --git a/gr00t/model/backbone/eagle2_hg_model/config.json b/gr00t/model/backbone/eagle2_hg_model/config.json +index 3894adf..f1b95aa 100644 +--- a/gr00t/model/backbone/eagle2_hg_model/config.json ++++ b/gr00t/model/backbone/eagle2_hg_model/config.json +@@ -1,5 +1,5 @@ + { +- "_attn_implementation": "flash_attention_2", ++ "_attn_implementation": "sdpa", + "_commit_hash": null, + "architectures": [ + "Eagle2_5_VLForConditionalGeneration" +diff --git a/gr00t/model/backbone/eagle2_hg_model/modeling_eagle2_5_vl.py b/gr00t/model/backbone/eagle2_hg_model/modeling_eagle2_5_vl.py +index a9649d5..d99b496 100755 +--- a/gr00t/model/backbone/eagle2_hg_model/modeling_eagle2_5_vl.py ++++ b/gr00t/model/backbone/eagle2_hg_model/modeling_eagle2_5_vl.py +@@ -108,7 +108,7 @@ class Eagle2_5_VLForConditionalGeneration(Eagle2_5_VLPreTrainedModel, Generation + self.vision_model = vision_model + else: + if config.vision_config.model_type == "siglip_vision_model": +- config.vision_config._attn_implementation = "flash_attention_2" ++ config.vision_config._attn_implementation = "sdpa" + self.vision_model = SiglipVisionModel(config.vision_config) + elif config.vision_config.model_type == "radio": + self.vision_model = RADIOModel(config.vision_config) +@@ -124,9 +124,7 @@ class Eagle2_5_VLForConditionalGeneration(Eagle2_5_VLPreTrainedModel, Generation + raise NotImplementedError("Phi3 is not implemented.") + # self.language_model = Phi3ForCausalLM(config.text_config) + elif config.text_config.architectures[0] == "Qwen2ForCausalLM": +- assert ( +- config.text_config._attn_implementation == "flash_attention_2" +- ), f"Qwen2 must use flash_attention_2 but got {config.text_config._attn_implementation}" ++ config.text_config._attn_implementation = "sdpa" + self.language_model = Qwen2ForCausalLM(config.text_config) + elif config.text_config.architectures[0] == "Qwen3ForCausalLM": + self.language_model = Qwen3ForCausalLM(config.text_config) +diff --git a/gr00t/model/backbone/eagle2_hg_model/radio_model.py b/gr00t/model/backbone/eagle2_hg_model/radio_model.py +index 2df0415..eb9b741 100644 +--- a/gr00t/model/backbone/eagle2_hg_model/radio_model.py ++++ b/gr00t/model/backbone/eagle2_hg_model/radio_model.py +@@ -44,12 +44,18 @@ from transformers.utils import ModelOutput + + try: # v1 + from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func +-except ImportError: # v2 +- from flash_attn.flash_attn_interface import ( +- flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func, +- ) ++except ImportError: ++ try: # v2 ++ from flash_attn.flash_attn_interface import ( ++ flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func, ++ ) ++ except ImportError: # flash-attn unavailable — RADIO vision won't work, SigLIP does ++ flash_attn_unpadded_qkvpacked_func = None + +-from flash_attn.bert_padding import pad_input, unpad_input ++try: ++ from flash_attn.bert_padding import pad_input, unpad_input ++except ImportError: ++ pad_input = unpad_input = None + + + class FlashAttention(nn.Module): diff --git a/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/policy.py b/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..e53e3fe7b7a275eb4fcfa9bc6d28160a36296fc4 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/policy.py @@ -0,0 +1,31 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import torch +from gr00t.experiment.data_config import DATA_CONFIG_MAP +from gr00t.model.policy import Gr00tPolicy + + +class Policy: + """Wrapper around GR00T policy for G1 locomanipulation SDG.""" + + def __init__(self, model_path: str, embodiment_tag: str): + """Load the GR00T policy and locomanipulation SDG data config. + + Args: + model_path: Path to the model checkpoint. + embodiment_tag: Embodiment tag used by the model (e.g. "new_embodiment"). + """ + self.device = "cuda" if torch.cuda.is_available() else "cpu" + self.data_config = DATA_CONFIG_MAP["g1_locomanipulation_sdg"] + self.modality_config = self.data_config.modality_config() + self.modality_transform = self.data_config.transform() + self.policy = Gr00tPolicy( + model_path=model_path, + embodiment_tag=embodiment_tag, + modality_config=self.modality_config, + modality_transform=self.modality_transform, + device=self.device, + ) diff --git a/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/rollout_policy.py b/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/rollout_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..21cd2f826df2a1d92b2dc465b43754c7bffda220 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/gr00t/rollout_policy.py @@ -0,0 +1,402 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to replay demonstrations with Isaac Lab environments.""" + +import argparse +import os + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser(description="Disjoint navigation") +parser.add_argument("--task", type=str, help="The Isaac Lab disjoint navigation task to load for data generation.") +parser.add_argument("--dataset", type=str, help="The static manipulation dataset recorded via teleoperation.") +parser.add_argument("--output_file", type=str, help="The file name for the generated output dataset.") +parser.add_argument("--demo", type=str, default="demo_0", help="The demo in the input dataset to use.") +parser.add_argument( + "--randomize_placement", action="store_true", default=False, help="Randomize placement of obstacles." +) +parser.add_argument("--model_path", type=str, help="The path to the model checkpoint.") +parser.add_argument( + "--embodiment_tag", type=str, default="new_embodiment", help="The embodiment tag to use for the model." +) +parser.add_argument( + "--policy_quat_format", + type=str, + choices=["xyzw", "wxyz"], + default="xyzw", + help="Quaternion order the policy uses: 'xyzw' (current Isaac Lab) or 'wxyz' (legacy). " + "Converts env observations/actions to match. Default is 'xyzw'.", +) +AppLauncher.add_app_launcher_args(parser) +args_cli = parser.parse_args() + +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +import gymnasium as gym +import torch +from policy import Policy + +from isaaclab.envs.mdp.recorders.recorders_cfg import ActionStateRecorderManagerCfg +from isaaclab.utils.datasets import EpisodeData, HDF5DatasetFileHandler +from isaaclab.utils.math import convert_quat + +import isaaclab_mimic.locomanipulation_sdg.envs # noqa: F401 +from isaaclab_mimic.locomanipulation_sdg.envs.locomanipulation_sdg_env import LocomanipulationSDGEnv +from isaaclab_mimic.locomanipulation_sdg.occupancy_map_utils import ( + OccupancyMap, + merge_occupancy_maps, +) +from isaaclab_mimic.locomanipulation_sdg.scene_utils import RelativePose, place_randomly +from isaaclab_mimic.locomanipulation_sdg.transform_utils import ( + transform_inv, + transform_mul, +) + +from isaaclab_tasks.utils import parse_env_cfg + + +def _clone_state(state: dict) -> dict: + """Deep clone state dict so we do not mutate the episode's stored initial state. + + Args: + state: Nested dict that may contain torch tensors and other dicts. + + Returns: + Deep copy of state with tensors cloned and dicts recursively cloned. + """ + + def _clone(val): + if isinstance(val, torch.Tensor): + return val.clone() + if isinstance(val, dict): + return {k: _clone(v) for k, v in val.items()} + return val + + return _clone(state) + + +def build_initial_state_for_replay( + env: LocomanipulationSDGEnv, + input_episode_data: EpisodeData, +) -> dict: + """Build the state dict for reset_to so the scene matches the recording in the current fixture frame. + + The episode stores initial state in env-relative coordinates (world - env_origin). The fixtures + (tables) are not stored; they are reset to scene defaults by _reset_idx. So we must transform + robot and object poses from "where they were relative to the recording's fixture" to "where + they should be relative to the current scene's start fixture", and pass explicit zero velocities + so the sim starts at rest. This is the single source of truth for initial state—no post-reset + projection or sync. + + Returns: + State dict suitable for env.reset_to(..., is_relative=True). + """ + state = _clone_state(input_episode_data.get_initial_state()) + load_0 = env.load_input_data(input_episode_data, 0) + start_fixture_pose = env.get_start_fixture().get_pose() + recorded_fixture = load_0.fixture_pose.to(env.device) + if recorded_fixture.dim() == 1: + recorded_fixture = recorded_fixture.unsqueeze(0) + + env_origins = env.scene.env_origins + env_id = 0 + if env_origins.dim() == 2: + env_origin = env_origins[env_id : env_id + 1] + else: + env_origin = env_origins.unsqueeze(0).to(env.device) + + def to_world(pose: torch.Tensor) -> torch.Tensor: + p = pose.clone().to(env.device) + if p.dim() == 1: + p = p.unsqueeze(0) + p = p.clone() + p[:, :3] += env_origin + return p + + def to_env_relative(world_pose: torch.Tensor) -> torch.Tensor: + out = world_pose.clone() + out[:, :3] -= env_origin + return out + + # Robot: same relative pose to current start fixture as in recording. + r_pose = state["articulation"]["robot"]["root_pose"].clone().to(env.device) + if r_pose.dim() == 1: + r_pose = r_pose.unsqueeze(0) + recorded_robot_world = r_pose.clone() + recorded_robot_world[:, :3] += env_origin + desired_robot_world = transform_mul( + start_fixture_pose, + transform_mul(transform_inv(recorded_fixture), recorded_robot_world), + ) + state["articulation"]["robot"]["root_pose"] = to_env_relative(desired_robot_world) + state["articulation"]["robot"]["root_velocity"] = torch.zeros_like( + state["articulation"]["robot"]["root_velocity"], device=env.device + ) + state["articulation"]["robot"]["joint_velocity"] = torch.zeros_like( + state["articulation"]["robot"]["joint_velocity"], device=env.device + ) + + # Object: same. + o_pose = state["rigid_object"]["object"]["root_pose"].clone().to(env.device) + if o_pose.dim() == 1: + o_pose = o_pose.unsqueeze(0) + recorded_object_world = o_pose.clone() + recorded_object_world[:, :3] += env_origin + desired_object_world = transform_mul( + start_fixture_pose, + transform_mul(transform_inv(recorded_fixture), recorded_object_world), + ) + state["rigid_object"]["object"]["root_pose"] = to_env_relative(desired_object_world) + state["rigid_object"]["object"]["root_velocity"] = torch.zeros_like( + state["rigid_object"]["object"]["root_velocity"], device=env.device + ) + + return state + + +# State keys that contain a 7D pose (pos 3 + quat 4). Env always provides quat in XYZW. +_STATE_POSE_KEYS = ( + "state.left_hand_pose", + "state.right_hand_pose", + "state.object_pose", + "state.goal_pose", + "state.end_fixture_pose", +) + + +def _convert_pose_quat(pose: torch.Tensor, to_fmt: str) -> torch.Tensor: + """Convert quaternion part of pose (..., 7) to target format. Env is XYZW. + + Args: + pose: Pose tensor with last 4 dims as quat (xyzw from env). + to_fmt: "xyzw" (no-op) or "wxyz" for policy. + + Returns: + Pose tensor with quat in the requested format. + """ + if to_fmt == "xyzw": + return pose + # to_fmt == "wxyz": env is xyzw -> convert to wxyz for policy + pos, quat = pose[..., :3], pose[..., 3:7] + quat_wxyz = convert_quat(quat, to="wxyz") + return torch.cat([pos, quat_wxyz], dim=-1) + + +def _convert_action_pose_quats_to_env(action: torch.Tensor, policy_quat_format: str) -> None: + """Convert policy action pose quaternions (columns 0:7 and 7:14) to XYZW for env in-place. + + Args: + action: Action tensor of shape (..., 32) with pose quats in columns 3:7 and 10:14. + policy_quat_format: "xyzw" (no-op) or "wxyz" (convert to xyzw for env). + """ + if policy_quat_format == "xyzw": + return + # Policy output is WXYZ; env expects XYZW + for start in (0, 7): + quat = action[..., start + 3 : start + 7] + action[..., start + 3 : start + 7] = convert_quat(quat, to="xyzw") + + +def setup_navigation_scene( + env: LocomanipulationSDGEnv, + input_episode_data: EpisodeData, + approach_distance: float, + randomize_placement: bool = True, +) -> tuple[OccupancyMap | None, RelativePose]: + """Set up occupancy map and base goal for policy rollout (no path planning). + + Args: + env: The locomanipulation SDG environment. + input_episode_data: Input episode data used to compute base goal from initial state. + approach_distance: Unused; kept for API compatibility with generate_data. + randomize_placement: Whether to randomize end fixture and obstacle placement. + + Returns: + Tuple of (occupancy_map, base_goal). First element is None; base_goal is the goal + pose for the policy relative to the end fixture. + """ + # Create base occupancy map + occupancy_map = merge_occupancy_maps( + [ + OccupancyMap.make_empty(start=(-7, -7), end=(7, 7), resolution=0.05), + env.get_start_fixture().get_occupancy_map(), + ] + ) + + # Randomize fixture placement if enabled + if randomize_placement: + fixtures = [env.get_end_fixture()] + env.get_obstacle_fixtures() + for fixture in fixtures: + place_randomly(fixture, occupancy_map.buffered_meters(1.0)) + occupancy_map = merge_occupancy_maps([occupancy_map, fixture.get_occupancy_map()]) + else: + fixtures = [env.get_end_fixture()] + env.get_obstacle_fixtures() + for fixture in fixtures: + occupancy_map = merge_occupancy_maps([occupancy_map, fixture.get_occupancy_map()]) + + # Compute goal poses from initial state (for policy's base_goal; robot/object already set by reset_to). + initial_state = env.load_input_data(input_episode_data, 0) + base_goal = RelativePose( + relative_pose=transform_mul(transform_inv(initial_state.fixture_pose), initial_state.base_pose), + parent=env.get_end_fixture(), + ) + + return None, base_goal + + +def build_model_input(env: LocomanipulationSDGEnv, base_goal: RelativePose, policy_quat_format: str = "xyzw"): + """Build GR00T model input dict and dummy action from current env state. + + Poses are expressed relative to the robot base. State pose quats are converted + to policy format (xyzw or wxyz) if needed. + + Args: + env: The locomanipulation SDG environment. + base_goal: Goal pose (e.g. from setup_navigation_scene). + policy_quat_format: "xyzw" or "wxyz" for state pose quaternions. + + Returns: + Tuple of (model_input dict, dummy_action tensor) for the policy. + """ + obs = env.obs_buf + left_hand_pose = torch.cat([obs["policy"]["left_eef_pos"], obs["policy"]["left_eef_quat"]], dim=-1) + right_hand_pose = torch.cat([obs["policy"]["right_eef_pos"], obs["policy"]["right_eef_quat"]], dim=-1) + left_hand_joint_positions = obs["policy"]["hand_joint_state"][:, 0:7] + right_hand_joint_positions = obs["policy"]["hand_joint_state"][:, 7:14] + + base_pose = env.get_base().get_pose() + object_pose = env.get_object().get_pose() + goal_pose = base_goal.get_pose() + end_fixture_pose = env.get_end_fixture().get_pose() + + base_pose_inv = transform_inv(base_pose) + + model_input = { + "video.ego_view": obs["policy"]["robot_pov_cam"], + "state.left_hand_pose": transform_mul(base_pose_inv, left_hand_pose), + "state.right_hand_pose": transform_mul(base_pose_inv, right_hand_pose), + "state.left_hand_joint_positions": left_hand_joint_positions, + "state.right_hand_joint_positions": right_hand_joint_positions, + "state.object_pose": transform_mul(base_pose_inv, object_pose), + "state.goal_pose": transform_mul(base_pose_inv, goal_pose), + "state.end_fixture_pose": transform_mul(base_pose_inv, end_fixture_pose), + } + + if policy_quat_format == "wxyz": + for key in _STATE_POSE_KEYS: + model_input[key] = _convert_pose_quat(model_input[key], to_fmt="wxyz") + + dummy_action = torch.zeros(1, 32) + dummy_action[:, :28] = torch.cat( + [left_hand_pose, right_hand_pose, left_hand_joint_positions, right_hand_joint_positions], dim=1 + ) + dummy_action[:, 31] = 0.8 + + return model_input, dummy_action + + +def eval_policy( + env: LocomanipulationSDGEnv, + policy: Policy, + input_episode_data: EpisodeData, + randomize_placement: bool = True, + policy_quat_format: str = "xyzw", +) -> None: + """Run policy rollout in the environment with state machine and recording-based initial state. + + Resets env to the episode initial state, sets up navigation scene (occupancy map and goal), + then steps the environment using policy actions at a fixed inference interval. Handles + quaternion format conversion between env (xyzw) and policy (xyzw or wxyz). + + Args: + env: The locomanipulation SDG environment. + policy: The GR00T policy wrapper. + input_episode_data: Episode data for initial state and goal. + randomize_placement: Whether to randomize fixture placement. + policy_quat_format: Quaternion format expected by the policy ("xyzw" or "wxyz"). + """ + initial_state = input_episode_data.get_initial_state() + obs, _ = env.reset_to( + state=initial_state, + env_ids=torch.tensor([0], device=env.device), + is_relative=False, + ) + occupancy_map, base_goal = setup_navigation_scene( + env, input_episode_data, approach_distance=0.5, randomize_placement=randomize_placement + ) + + step = 0 + + action_idx = 0 + inference_interval = 16 + + while simulation_app.is_running() and not simulation_app.is_exiting(): + if step % inference_interval == 0: + model_input, dummy_action = build_model_input(env, base_goal, policy_quat_format) + action_dict = policy.policy.get_action(model_input) + action_buffer = torch.cat([torch.from_numpy(v) for v in action_dict.values()], dim=-1) + action_idx = 0 + + if step < 0: + env.step(dummy_action) + else: + base_pose = env.get_base().get_pose() + action = action_buffer.clone() + _convert_action_pose_quats_to_env(action, policy_quat_format) + + action[:, 0:7] = transform_mul(base_pose, action[:, 0:7]) + action[:, 7:14] = transform_mul(base_pose, action[:, 7:14]) + + action[:, 28:31] = action[:, 28:31] * 1.0 + _, _, reset_terminated, reset_time_outs, _ = env.step( + action[action_idx : action_idx + 1].mean(dim=0, keepdim=True) + ) + if reset_terminated.any(): + print("Reset terminated") + step = 0 + action_idx = 0 + if reset_time_outs.any(): + print("Reset timeouts") + + step += 1 + action_idx += 1 + + +if __name__ == "__main__": + with torch.no_grad(): + env_name = args_cli.task.split(":")[-1] if args_cli.task is not None else None + if env_name is None: + raise ValueError("Task/env name was not specified nor found in the dataset.") + + policy = Policy(model_path=args_cli.model_path, embodiment_tag=args_cli.embodiment_tag) + + env_cfg = parse_env_cfg(env_name, device=args_cli.device, num_envs=1) + env_cfg.sim.device = args_cli.device + # Drop the SDG output-data recorder term: it pulls env._locomanipulation_sdg_output_data, + # which is only populated by the data-generation state machine, not during policy rollout. + env_cfg.recorders = ActionStateRecorderManagerCfg() + env_cfg.recorders.dataset_export_dir_path = os.path.dirname(args_cli.output_file) + env_cfg.recorders.dataset_filename = os.path.basename(args_cli.output_file) + + env = gym.make(args_cli.task, cfg=env_cfg).unwrapped + + input_dataset_file_handler = HDF5DatasetFileHandler() + input_dataset_file_handler.open(args_cli.dataset) + input_episode_data = input_dataset_file_handler.load_episode(args_cli.demo, args_cli.device) + + eval_policy( + env=env, + policy=policy, + input_episode_data=input_episode_data, + randomize_placement=args_cli.randomize_placement, + policy_quat_format=args_cli.policy_quat_format, + ) + + env.reset() + env.close() + + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/plot_navigation_trajectory.py b/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/plot_navigation_trajectory.py new file mode 100644 index 0000000000000000000000000000000000000000..4022ea757b8bfed55ec6872a253dbbf034784c02 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/imitation_learning/locomanipulation_sdg/plot_navigation_trajectory.py @@ -0,0 +1,102 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to visualize navigation datasets from locomanipulation SDG. + +Loads an HDF5 dataset containing locomanipulation_sdg_output_data and generates +plots showing base path, base pose, object pose, start/end fixtures, and obstacles. +""" + +import argparse +import os + +import h5py +import matplotlib.pyplot as plt + + +def main() -> None: + """Load dataset, filter demos if requested, and save navigation visualization plots. + + Reads HDF5 from --input_file, optionally restricts to --demo_filter, and writes + one PNG per demo to --output_dir with path, poses, and obstacle positions. + """ + parser = argparse.ArgumentParser( + description="Visualize navigation dataset from locomanipulation sdg demonstrations." + ) + parser.add_argument( + "--input_file", type=str, help="Path to the HDF5 dataset file containing recorded demonstrations." + ) + parser.add_argument("--output_dir", type=str, help="Directory path where visualization plots will be saved.") + parser.add_argument( + "--figure_size", + type=int, + nargs=2, + default=[20, 20], + help="Size of the generated figures (width, height). Default: [20, 20]", + ) + parser.add_argument( + "--demo_filter", + type=str, + default=None, + help="If provided, only visualize specific demo(s). Can be a single demo name or comma-separated list.", + ) + + args = parser.parse_args() + + if not os.path.exists(args.input_file): + raise FileNotFoundError(f"Dataset file not found: {args.input_file}") + + os.makedirs(args.output_dir, exist_ok=True) + + dataset = h5py.File(args.input_file, "r") + + demos = list(dataset["data"].keys()) + + if args.demo_filter: + filter_demos = [d.strip() for d in args.demo_filter.split(",")] + demos = [d for d in demos if d in filter_demos] + if not demos: + print(f"Warning: No demos found matching filter '{args.demo_filter}'") + return + + print(f"Visualizing {len(demos)} demonstrations...") + + for i, demo in enumerate(demos): + print(f"Processing demo {i + 1}/{len(demos)}: {demo}") + + replay_data = dataset["data"][demo]["locomanipulation_sdg_output_data"] + path = replay_data["base_path"] + base_pose = replay_data["base_pose"] + object_pose = replay_data["object_pose"] + start_pose = replay_data["start_fixture_pose"] + end_pose = replay_data["end_fixture_pose"] + obstacle_poses = replay_data["obstacle_fixture_poses"] + + plt.figure(figsize=args.figure_size) + plt.plot(path[0, :, 0], path[0, :, 1], "r-", label="Target Path", linewidth=2) + plt.plot(base_pose[:, 0], base_pose[:, 1], "g--", label="Base Pose", linewidth=2) + plt.plot(object_pose[:, 0], object_pose[:, 1], "b--", label="Object Pose", linewidth=2) + plt.plot(obstacle_poses[0, :, 0], obstacle_poses[0, :, 1], "ro", label="Obstacles", markersize=8) + + plt.plot(start_pose[0, 0], start_pose[0, 1], "gs", label="Start", markersize=12) + plt.plot(end_pose[0, 0], end_pose[0, 1], "rs", label="End", markersize=12) + + plt.legend(loc="upper right", ncol=1, fontsize=12) + plt.axis("equal") + plt.grid(True, alpha=0.3) + plt.title(f"Navigation Visualization - {demo}", fontsize=16) + plt.xlabel("X Position (m)", fontsize=14) + plt.ylabel("Y Position (m)", fontsize=14) + + output_path = os.path.join(args.output_dir, f"{demo}.png") + plt.savefig(output_path, dpi=150, bbox_inches="tight") + plt.close() # Close the figure to free memory + + dataset.close() + print(f"Visualization complete! Plots saved to: {args.output_dir}") + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/imitation_learning/robomimic/play.py b/simulation/modules/IsaacLab/scripts/imitation_learning/robomimic/play.py new file mode 100644 index 0000000000000000000000000000000000000000..80962798920b08580d406e0caab933a297012377 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/imitation_learning/robomimic/play.py @@ -0,0 +1,183 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to play and evaluate a trained policy from robomimic. + +This script loads a robomimic policy and plays it in an Isaac Lab environment. + +Args: + task: Name of the environment. + checkpoint: Path to the robomimic policy checkpoint. + horizon: If provided, override the step horizon of each rollout. + num_rollouts: If provided, override the number of rollouts. + seed: If provided, overeride the default random seed. + norm_factor_min: If provided, minimum value of the action space normalization factor. + norm_factor_max: If provided, maximum value of the action space normalization factor. +""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Evaluate robomimic policy for Isaac Lab environment.") +parser.add_argument( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument("--checkpoint", type=str, default=None, help="Pytorch model checkpoint to load.") +parser.add_argument("--horizon", type=int, default=800, help="Step horizon of each rollout.") +parser.add_argument("--num_rollouts", type=int, default=1, help="Number of rollouts.") +parser.add_argument("--seed", type=int, default=101, help="Random seed.") +parser.add_argument( + "--norm_factor_min", type=float, default=None, help="Optional: minimum value of the normalization factor." +) +parser.add_argument( + "--norm_factor_max", type=float, default=None, help="Optional: maximum value of the normalization factor." +) + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import copy +import random + +import gymnasium as gym +import numpy as np +import robomimic.utils.file_utils as FileUtils +import robomimic.utils.torch_utils as TorchUtils +import torch + +from isaaclab_tasks.utils import parse_env_cfg + + +def rollout(policy, env, success_term, horizon, device): + """Perform a single rollout of the policy in the environment. + + Args: + policy: The robomimicpolicy to play. + env: The environment to play in. + horizon: The step horizon of each rollout. + device: The device to run the policy on. + + Returns: + terminated: Whether the rollout terminated. + traj: The trajectory of the rollout. + """ + policy.start_episode() + obs_dict, _ = env.reset() + traj = dict(actions=[], obs=[], next_obs=[]) + + for i in range(horizon): + # Prepare observations + obs = copy.deepcopy(obs_dict["policy"]) + for ob in obs: + obs[ob] = torch.squeeze(obs[ob]) + + # Check if environment image observations + if hasattr(env.cfg, "image_obs_list"): + # Process image observations for robomimic inference + for image_name in env.cfg.image_obs_list: + if image_name in obs_dict["policy"].keys(): + # Convert from chw uint8 to hwc normalized float + image = torch.squeeze(obs_dict["policy"][image_name]) + image = image.permute(2, 0, 1).clone().float() + image = image / 255.0 + image = image.clip(0.0, 1.0) + obs[image_name] = image + + traj["obs"].append(obs) + + # Compute actions + actions = policy(obs) + + # Unnormalize actions + if args_cli.norm_factor_min is not None and args_cli.norm_factor_max is not None: + actions = ( + (actions + 1) * (args_cli.norm_factor_max - args_cli.norm_factor_min) + ) / 2 + args_cli.norm_factor_min + + actions = torch.from_numpy(actions).to(device=device).view(1, env.action_space.shape[1]) + + # Apply actions + obs_dict, _, terminated, truncated, _ = env.step(actions) + obs = obs_dict["policy"] + + # Record trajectory + traj["actions"].append(actions.tolist()) + traj["next_obs"].append(obs) + + # Check if rollout was successful + if bool(success_term.func(env, **success_term.params)[0]): + return True, traj + elif terminated or truncated: + return False, traj + + return False, traj + + +def main(): + """Run a trained policy from robomimic with Isaac Lab environment.""" + # parse configuration + env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=1, use_fabric=not args_cli.disable_fabric) + + # Set observations to dictionary mode for Robomimic + env_cfg.observations.policy.concatenate_terms = False + + # Set termination conditions + env_cfg.terminations.time_out = None + + # Disable recorder + env_cfg.recorders = None + + # Extract success checking function + success_term = env_cfg.terminations.success + env_cfg.terminations.success = None + + # Create environment + env = gym.make(args_cli.task, cfg=env_cfg).unwrapped + + # Set seed + torch.manual_seed(args_cli.seed) + np.random.seed(args_cli.seed) + random.seed(args_cli.seed) + env.seed(args_cli.seed) + + # Acquire device + device = TorchUtils.get_torch_device(try_to_use_cuda=True) + + with torch.inference_mode(): + # Run policy + results = [] + for trial in range(args_cli.num_rollouts): + print(f"[INFO] Starting trial {trial}") + policy, _ = FileUtils.policy_from_checkpoint(ckpt_path=args_cli.checkpoint, device=device) + terminated, traj = rollout(policy, env, success_term, args_cli.horizon, device) + results.append(terminated) + print(f"[INFO] Trial {trial}: {terminated}\n") + + print(f"\nSuccessful trials: {results.count(True)}, out of {len(results)} trials") + print(f"Success rate: {results.count(True) / len(results)}") + print(f"Trial Results: {results}\n") + + env.close() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/imitation_learning/robomimic/robust_eval.py b/simulation/modules/IsaacLab/scripts/imitation_learning/robomimic/robust_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..08b4f9ce2ddea86c4dac73d8511fe0b8c4d940c6 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/imitation_learning/robomimic/robust_eval.py @@ -0,0 +1,328 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to evaluate a trained policy from robomimic across multiple evaluation settings. + +This script loads a trained robomimic policy and evaluates it in an Isaac Lab environment +across multiple evaluation settings (lighting, textures, etc.) and seeds. It saves the results +to a specified output directory. + +Args: + task: Name of the environment. + input_dir: Directory containing the model checkpoints to evaluate. + horizon: Step horizon of each rollout. + num_rollouts: Number of rollouts per model per setting. + num_seeds: Number of random seeds to evaluate. + seeds: Optional list of specific seeds to use instead of random ones. + log_dir: Directory to write results to. + log_file: Name of the output file. + output_vis_file: File path to export recorded episodes. + norm_factor_min: If provided, minimum value of the action space normalization factor. + norm_factor_max: If provided, maximum value of the action space normalization factor. + disable_fabric: Whether to disable fabric and use USD I/O operations. +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Evaluate robomimic policy for Isaac Lab environment.") +parser.add_argument( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument("--input_dir", type=str, default=None, help="Directory containing models to evaluate.") +parser.add_argument( + "--start_epoch", type=int, default=100, help="Epoch of the checkpoint to start the evaluation from." +) +parser.add_argument("--horizon", type=int, default=400, help="Step horizon of each rollout.") +parser.add_argument("--num_rollouts", type=int, default=15, help="Number of rollouts for each setting.") +parser.add_argument("--num_seeds", type=int, default=3, help="Number of random seeds to evaluate.") +parser.add_argument("--seeds", nargs="+", type=int, default=None, help="List of specific seeds to use.") +parser.add_argument( + "--log_dir", type=str, default="/tmp/policy_evaluation_results", help="Directory to write results to." +) +parser.add_argument("--log_file", type=str, default="results", help="Name of output file.") +parser.add_argument( + "--output_vis_file", type=str, default="visuals.hdf5", help="File path to export recorded episodes." +) +parser.add_argument( + "--norm_factor_min", type=float, default=None, help="Optional: minimum value of the normalization factor." +) +parser.add_argument( + "--norm_factor_max", type=float, default=None, help="Optional: maximum value of the normalization factor." +) + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import copy +import os +import pathlib +import random + +import gymnasium as gym +import robomimic.utils.file_utils as FileUtils +import robomimic.utils.torch_utils as TorchUtils +import torch + +from isaaclab_tasks.utils import parse_env_cfg + + +def rollout(policy, env: gym.Env, success_term, horizon: int, device: torch.device) -> tuple[bool, dict]: + """Perform a single rollout of the policy in the environment. + + Args: + policy: The robomimic policy to evaluate. + env: The environment to evaluate in. + horizon: The step horizon of each rollout. + device: The device to run the policy on. + args_cli: Command line arguments containing normalization factors. + + Returns: + terminated: Whether the rollout terminated successfully. + traj: The trajectory of the rollout. + """ + policy.start_episode() + obs_dict, _ = env.reset() + traj = dict(actions=[], obs=[], next_obs=[]) + + for _ in range(horizon): + # Prepare policy observations + obs = copy.deepcopy(obs_dict["policy"]) + for ob in obs: + obs[ob] = torch.squeeze(obs[ob]) + + # Check if environment image observations + if hasattr(env.cfg, "image_obs_list"): + # Process image observations for robomimic inference + for image_name in env.cfg.image_obs_list: + if image_name in obs_dict["policy"].keys(): + # Convert from chw uint8 to hwc normalized float + image = torch.squeeze(obs_dict["policy"][image_name]) + image = image.permute(2, 0, 1).clone().float() + image = image / 255.0 + image = image.clip(0.0, 1.0) + obs[image_name] = image + + traj["obs"].append(obs) + + # Compute actions + actions = policy(obs) + + # Unnormalize actions if normalization factors are provided + if args_cli.norm_factor_min is not None and args_cli.norm_factor_max is not None: + actions = ( + (actions + 1) * (args_cli.norm_factor_max - args_cli.norm_factor_min) + ) / 2 + args_cli.norm_factor_min + + actions = torch.from_numpy(actions).to(device=device).view(1, env.action_space.shape[1]) + + # Apply actions + obs_dict, _, terminated, truncated, _ = env.step(actions) + obs = obs_dict["policy"] + + # Record trajectory + traj["actions"].append(actions.tolist()) + traj["next_obs"].append(obs) + + if bool(success_term.func(env, **success_term.params)[0]): + return True, traj + elif terminated or truncated: + return False, traj + + return False, traj + + +def evaluate_model( + model_path: str, + env: gym.Env, + device: torch.device, + success_term, + num_rollouts: int, + horizon: int, + seed: int, + output_file: str, +) -> float: + """Evaluate a single model checkpoint across multiple rollouts. + + Args: + model_path: Path to the model checkpoint. + env: The environment to evaluate in. + device: The device to run the policy on. + num_rollouts: Number of rollouts to perform. + horizon: Step horizon of each rollout. + seed: Random seed to use. + output_file: File to write results to. + + Returns: + float: Success rate of the model + """ + # Set seed + torch.manual_seed(seed) + env.seed(seed) + random.seed(seed) + + # Load policy + policy, _ = FileUtils.policy_from_checkpoint(ckpt_path=model_path, device=device, verbose=False) + + # Run policy + results = [] + for trial in range(num_rollouts): + print(f"[Model: {os.path.basename(model_path)}] Starting trial {trial}") + terminated, _ = rollout(policy, env, success_term, horizon, device) + results.append(terminated) + with open(output_file, "a") as file: + file.write(f"[Model: {os.path.basename(model_path)}] Trial {trial}: {terminated}\n") + print(f"[Model: {os.path.basename(model_path)}] Trial {trial}: {terminated}") + + # Calculate and log results + success_rate = results.count(True) / len(results) + with open(output_file, "a") as file: + file.write( + f"[Model: {os.path.basename(model_path)}] Successful trials: {results.count(True)}, out of" + f" {len(results)} trials\n" + ) + file.write(f"[Model: {os.path.basename(model_path)}] Success rate: {success_rate}\n") + file.write(f"[Model: {os.path.basename(model_path)}] Results: {results}\n") + file.write("-" * 80 + "\n\n") + + print( + f"\n[Model: {os.path.basename(model_path)}] Successful trials: {results.count(True)}, out of" + f" {len(results)} trials" + ) + print(f"[Model: {os.path.basename(model_path)}] Success rate: {success_rate}\n") + print(f"[Model: {os.path.basename(model_path)}] Results: {results}\n") + + return success_rate + + +def main() -> None: + """Run evaluation of trained policies from robomimic with Isaac Lab environment.""" + # Parse configuration + env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=1, use_fabric=not args_cli.disable_fabric) + + # Set observations to dictionary mode for Robomimic + env_cfg.observations.policy.concatenate_terms = False + + # Set termination conditions + env_cfg.terminations.time_out = None + + # Disable recorder + env_cfg.recorders = None + + # Extract success checking function + success_term = env_cfg.terminations.success + env_cfg.terminations.success = None + + # Set evaluation settings + env_cfg.eval_mode = True + + # Create environment + env = gym.make(args_cli.task, cfg=env_cfg).unwrapped + + # Acquire device + device = TorchUtils.get_torch_device(try_to_use_cuda=False) + + # Get model checkpoints + model_checkpoints = [f.name for f in os.scandir(args_cli.input_dir) if f.is_file()] + + # Set up seeds + seeds = random.sample(range(0, 10000), args_cli.num_seeds) if args_cli.seeds is None else args_cli.seeds + + # Define evaluation settings + settings = ["vanilla", "light_intensity", "light_color", "light_texture", "table_texture", "robot_texture", "all"] + + # Create log directory if it doesn't exist + os.makedirs(args_cli.log_dir, exist_ok=True) + + # Evaluate each seed + for seed in seeds: + output_path = os.path.join(args_cli.log_dir, f"{args_cli.log_file}_seed_{seed}") + path = pathlib.Path(output_path) + path.parent.mkdir(parents=True, exist_ok=True) + + # Initialize results summary + results_summary = dict() + results_summary["overall"] = {} + for setting in settings: + results_summary[setting] = {} + + with open(output_path, "w") as file: + # Evaluate each setting + for setting in settings: + env.cfg.eval_type = setting + + file.write(f"Evaluation setting: {setting}\n") + file.write("=" * 80 + "\n\n") + + print(f"Evaluation setting: {setting}") + print("=" * 80) + + # Evaluate each model + for model in model_checkpoints: + # Skip early checkpoints + model_epoch = int(model.split(".")[0].split("_")[-1]) + if model_epoch < args_cli.start_epoch: + continue + + model_path = os.path.join(args_cli.input_dir, model) + success_rate = evaluate_model( + model_path=model_path, + env=env, + device=device, + success_term=success_term, + num_rollouts=args_cli.num_rollouts, + horizon=args_cli.horizon, + seed=seed, + output_file=output_path, + ) + + # Store results + results_summary[setting][model] = success_rate + if model not in results_summary["overall"].keys(): + results_summary["overall"][model] = 0.0 + results_summary["overall"][model] += success_rate + + env.reset() + + file.write("=" * 80 + "\n\n") + env.reset() + + # Calculate overall success rates + for model in results_summary["overall"].keys(): + results_summary["overall"][model] /= len(settings) + + # Write final summary + file.write("\nResults Summary (success rate):\n") + for setting in results_summary.keys(): + file.write(f"\nSetting: {setting}\n") + for model in results_summary[setting].keys(): + file.write(f"{model}: {results_summary[setting][model]}\n") + max_key = max(results_summary[setting], key=results_summary[setting].get) + file.write( + f"\nBest model for setting {setting} is {max_key} with success rate" + f" {results_summary[setting][max_key]}\n" + ) + + env.close() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/imitation_learning/robomimic/train.py b/simulation/modules/IsaacLab/scripts/imitation_learning/robomimic/train.py new file mode 100644 index 0000000000000000000000000000000000000000..11dd9814de6d76157af82a3ab566861ce3d84230 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/imitation_learning/robomimic/train.py @@ -0,0 +1,457 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# MIT License +# +# Copyright (c) 2021 Stanford Vision and Learning Lab +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +""" +The main entry point for training policies from pre-collected data. + +This script loads dataset(s), creates a model based on the algorithm specified, +and trains the model. It supports training on various environments with multiple +algorithms from robomimic. + +Args: + algo: Name of the algorithm to run. + task: Name of the environment. + name: If provided, override the experiment name defined in the config. + dataset: If provided, override the dataset path defined in the config. + log_dir: Directory to save logs. + normalize_training_actions: Whether to normalize actions in the training data. + +This file has been modified from the original robomimic version to integrate with IsaacLab. +""" + +"""Launch Isaac Sim Simulator first.""" + +from isaaclab.app import AppLauncher + +# launch omniverse app +app_launcher = AppLauncher(headless=True) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import argparse +import importlib +import json +import os +import shutil +import sys +import time +import traceback +from collections import OrderedDict + +import gymnasium as gym +import h5py +import numpy as np +import psutil +import robomimic.utils.env_utils as EnvUtils +import robomimic.utils.file_utils as FileUtils +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.torch_utils as TorchUtils +import robomimic.utils.train_utils as TrainUtils +import torch +from robomimic.algo import algo_factory +from robomimic.config import Config, config_factory +from robomimic.utils.log_utils import DataLogger, PrintLogger +from torch.utils.data import DataLoader + +import isaaclab_tasks # noqa: F401 +import isaaclab_tasks.manager_based.locomanipulation.pick_place # noqa: F401 +import isaaclab_tasks.manager_based.manipulation.pick_place # noqa: F401 + + +def normalize_hdf5_actions(config: Config, log_dir: str) -> str: + """Normalizes actions in hdf5 dataset to [-1, 1] range. + + Args: + config: The configuration object containing dataset path. + log_dir: Directory to save normalization parameters. + + Returns: + Path to the normalized dataset. + """ + base, ext = os.path.splitext(config.train.data) + normalized_path = base + "_normalized" + ext + + # Copy the original dataset + print(f"Creating normalized dataset at {normalized_path}") + shutil.copyfile(config.train.data, normalized_path) + + # Open the new dataset and normalize the actions + with h5py.File(normalized_path, "r+") as f: + dataset_paths = [f"/data/demo_{str(i)}/actions" for i in range(len(f["data"].keys()))] + + # Compute the min and max of the dataset + dataset = np.array(f[dataset_paths[0]]).flatten() + for i, path in enumerate(dataset_paths): + if i != 0: + data = np.array(f[path]).flatten() + dataset = np.append(dataset, data) + + max = np.max(dataset) + min = np.min(dataset) + + # Normalize the actions + for i, path in enumerate(dataset_paths): + data = np.array(f[path]) + normalized_data = 2 * ((data - min) / (max - min)) - 1 # Scale to [-1, 1] range + del f[path] + f[path] = normalized_data + + # Save the min and max values to log directory + with open(os.path.join(log_dir, "normalization_params.txt"), "w") as f: + f.write(f"min: {min}\n") + f.write(f"max: {max}\n") + + return normalized_path + + +def train(config: Config, device: str, log_dir: str, ckpt_dir: str, video_dir: str): + """Train a model using the algorithm specified in config. + + Args: + config: Configuration object. + device: PyTorch device to use for training. + log_dir: Directory to save logs. + ckpt_dir: Directory to save checkpoints. + video_dir: Directory to save videos. + """ + # first set seeds + np.random.seed(config.train.seed) + torch.manual_seed(config.train.seed) + + print("\n============= New Training Run with Config =============") + print(config) + print("") + + print(f">>> Saving logs into directory: {log_dir}") + print(f">>> Saving checkpoints into directory: {ckpt_dir}") + print(f">>> Saving videos into directory: {video_dir}") + + if config.experiment.logging.terminal_output_to_txt: + # log stdout and stderr to a text file + logger = PrintLogger(os.path.join(log_dir, "log.txt")) + sys.stdout = logger + sys.stderr = logger + + # read config to set up metadata for observation modalities (e.g. detecting rgb observations) + ObsUtils.initialize_obs_utils_with_config(config) + + # make sure the dataset exists + dataset_path = os.path.expanduser(config.train.data) + if not os.path.exists(dataset_path): + raise FileNotFoundError(f"Dataset at provided path {dataset_path} not found!") + + # load basic metadata from training file + print("\n============= Loaded Environment Metadata =============") + env_meta = FileUtils.get_env_metadata_from_dataset(dataset_path=config.train.data) + shape_meta = FileUtils.get_shape_metadata_from_dataset( + dataset_path=config.train.data, all_obs_keys=config.all_obs_keys, verbose=True + ) + + if config.experiment.env is not None: + env_meta["env_name"] = config.experiment.env + print("=" * 30 + "\n" + "Replacing Env to {}\n".format(env_meta["env_name"]) + "=" * 30) + + # create environment + envs = OrderedDict() + if config.experiment.rollout.enabled: + # create environments for validation runs + env_names = [env_meta["env_name"]] + + if config.experiment.additional_envs is not None: + for name in config.experiment.additional_envs: + env_names.append(name) + + for env_name in env_names: + env = EnvUtils.create_env_from_metadata( + env_meta=env_meta, + env_name=env_name, + render=False, + render_offscreen=config.experiment.render_video, + use_image_obs=shape_meta["use_images"], + ) + envs[env.name] = env + print(envs[env.name]) + + print("") + + # setup for a new training run + data_logger = DataLogger(log_dir, config=config, log_tb=config.experiment.logging.log_tb) + model = algo_factory( + algo_name=config.algo_name, + config=config, + obs_key_shapes=shape_meta["all_shapes"], + ac_dim=shape_meta["ac_dim"], + device=device, + ) + + # save the config as a json file + with open(os.path.join(log_dir, "..", "config.json"), "w") as outfile: + json.dump(config, outfile, indent=4) + + print("\n============= Model Summary =============") + print(model) # print model summary + print("") + + # load training data + trainset, validset = TrainUtils.load_data_for_training(config, obs_keys=shape_meta["all_obs_keys"]) + train_sampler = trainset.get_dataset_sampler() + print("\n============= Training Dataset =============") + print(trainset) + print("") + + # maybe retrieve statistics for normalizing observations + obs_normalization_stats = None + if config.train.hdf5_normalize_obs: + obs_normalization_stats = trainset.get_obs_normalization_stats() + + # initialize data loaders + train_loader = DataLoader( + dataset=trainset, + sampler=train_sampler, + batch_size=config.train.batch_size, + shuffle=(train_sampler is None), + num_workers=config.train.num_data_workers, + drop_last=True, + ) + + if config.experiment.validate: + # cap num workers for validation dataset at 1 + num_workers = min(config.train.num_data_workers, 1) + valid_sampler = validset.get_dataset_sampler() + valid_loader = DataLoader( + dataset=validset, + sampler=valid_sampler, + batch_size=config.train.batch_size, + shuffle=(valid_sampler is None), + num_workers=num_workers, + drop_last=True, + ) + else: + valid_loader = None + + # main training loop + best_valid_loss = None + last_ckpt_time = time.time() + + # number of learning steps per epoch (defaults to a full dataset pass) + train_num_steps = config.experiment.epoch_every_n_steps + valid_num_steps = config.experiment.validation_epoch_every_n_steps + + for epoch in range(1, config.train.num_epochs + 1): # epoch numbers start at 1 + step_log = TrainUtils.run_epoch(model=model, data_loader=train_loader, epoch=epoch, num_steps=train_num_steps) + model.on_epoch_end(epoch) + + # setup checkpoint path + epoch_ckpt_name = f"model_epoch_{epoch}" + + # check for recurring checkpoint saving conditions + should_save_ckpt = False + if config.experiment.save.enabled: + time_check = (config.experiment.save.every_n_seconds is not None) and ( + time.time() - last_ckpt_time > config.experiment.save.every_n_seconds + ) + epoch_check = ( + (config.experiment.save.every_n_epochs is not None) + and (epoch > 0) + and (epoch % config.experiment.save.every_n_epochs == 0) + ) + epoch_list_check = epoch in config.experiment.save.epochs + last_epoch_check = epoch == config.train.num_epochs + should_save_ckpt = time_check or epoch_check or epoch_list_check or last_epoch_check + ckpt_reason = None + if should_save_ckpt: + last_ckpt_time = time.time() + ckpt_reason = "time" + + print(f"Train Epoch {epoch}") + print(json.dumps(step_log, sort_keys=True, indent=4)) + for k, v in step_log.items(): + if k.startswith("Time_"): + data_logger.record(f"Timing_Stats/Train_{k[5:]}", v, epoch) + else: + data_logger.record(f"Train/{k}", v, epoch) + + # Evaluate the model on validation set + if config.experiment.validate: + with torch.no_grad(): + step_log = TrainUtils.run_epoch( + model=model, data_loader=valid_loader, epoch=epoch, validate=True, num_steps=valid_num_steps + ) + for k, v in step_log.items(): + if k.startswith("Time_"): + data_logger.record(f"Timing_Stats/Valid_{k[5:]}", v, epoch) + else: + data_logger.record(f"Valid/{k}", v, epoch) + + print(f"Validation Epoch {epoch}") + print(json.dumps(step_log, sort_keys=True, indent=4)) + + # save checkpoint if achieve new best validation loss + valid_check = "Loss" in step_log + if valid_check and (best_valid_loss is None or (step_log["Loss"] <= best_valid_loss)): + best_valid_loss = step_log["Loss"] + if config.experiment.save.enabled and config.experiment.save.on_best_validation: + epoch_ckpt_name += f"_best_validation_{best_valid_loss}" + should_save_ckpt = True + ckpt_reason = "valid" if ckpt_reason is None else ckpt_reason + + # Save model checkpoints based on conditions (success rate, validation loss, etc) + if should_save_ckpt: + TrainUtils.save_model( + model=model, + config=config, + env_meta=env_meta, + shape_meta=shape_meta, + ckpt_path=os.path.join(ckpt_dir, epoch_ckpt_name + ".pth"), + obs_normalization_stats=obs_normalization_stats, + ) + + # Finally, log memory usage in MB + process = psutil.Process(os.getpid()) + mem_usage = int(process.memory_info().rss / 1000000) + data_logger.record("System/RAM Usage (MB)", mem_usage, epoch) + print(f"\nEpoch {epoch} Memory Usage: {mem_usage} MB\n") + + # terminate logging + data_logger.close() + + +def main(args: argparse.Namespace): + """Train a model on a task using a specified algorithm. + + Args: + args: Command line arguments. + """ + # load config + if args.task is not None: + # obtain the configuration entry point + cfg_entry_point_key = f"robomimic_{args.algo}_cfg_entry_point" + task_name = args.task.split(":")[-1] + + print(f"Loading configuration for task: {task_name}") + print(gym.envs.registry.keys()) + print(" ") + cfg_entry_point_file = gym.spec(task_name).kwargs.pop(cfg_entry_point_key) + # check if entry point exists + if cfg_entry_point_file is None: + raise ValueError( + f"Could not find configuration for the environment: '{task_name}'." + f" Please check that the gym registry has the entry point: '{cfg_entry_point_key}'." + ) + + # resolve module path if needed + if ":" in cfg_entry_point_file: + mod_name, file_name = cfg_entry_point_file.split(":") + mod = importlib.import_module(mod_name) + if mod.__file__ is None: + raise ValueError(f"Could not find module file for: '{mod_name}'") + mod_path = os.path.dirname(mod.__file__) + config_file = os.path.join(mod_path, file_name) + else: + config_file = cfg_entry_point_file + + with open(config_file) as f: + ext_cfg = json.load(f) + config = config_factory(ext_cfg["algo_name"]) + # update config with external json - this will throw errors if + # the external config has keys not present in the base algo config + with config.values_unlocked(): + config.update(ext_cfg) + else: + raise ValueError("Please provide a task name through CLI arguments.") + + if args.dataset is not None: + config.train.data = args.dataset + + if args.name is not None: + config.experiment.name = args.name + + if args.epochs is not None: + config.train.num_epochs = args.epochs + + # change location of experiment directory + config.train.output_dir = os.path.abspath(os.path.join("./logs", args.log_dir, args.task)) + + log_dir, ckpt_dir, video_dir = TrainUtils.get_exp_dir(config) + + if args.normalize_training_actions: + config.train.data = normalize_hdf5_actions(config, log_dir) + + # get torch device + device = TorchUtils.get_torch_device(try_to_use_cuda=config.train.cuda) + + config.lock() + + # catch error during training and print it + res_str = "finished run successfully!" + try: + train(config, device, log_dir, ckpt_dir, video_dir) + except Exception as e: + res_str = f"run failed with error:\n{e}\n\n{traceback.format_exc()}" + print(res_str) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + # Experiment Name (for tensorboard, saving models, etc.) + parser.add_argument( + "--name", + type=str, + default=None, + help="(optional) if provided, override the experiment name defined in the config", + ) + + # Dataset path, to override the one in the config + parser.add_argument( + "--dataset", + type=str, + default=None, + help="(optional) if provided, override the dataset path defined in the config", + ) + + parser.add_argument("--task", type=str, default=None, help="Name of the task.") + parser.add_argument("--algo", type=str, default=None, help="Name of the algorithm.") + parser.add_argument("--log_dir", type=str, default="robomimic", help="Path to log directory") + parser.add_argument("--normalize_training_actions", action="store_true", default=False, help="Normalize actions") + parser.add_argument( + "--epochs", + type=int, + default=None, + help=( + "Optional: Number of training epochs. If specified, overrides the number of epochs from the JSON training" + " config." + ), + ) + + args = parser.parse_args() + + # run training + main(args) + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/common.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/common.py new file mode 100644 index 0000000000000000000000000000000000000000..94eb22a9d774bfcf924b719a222a7c87263b70b3 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/common.py @@ -0,0 +1,281 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Common utilities for reinforcement learning entrypoints.""" + +from __future__ import annotations + +import argparse +import importlib.util +import logging +import os +import runpy +import sys +from pathlib import Path +from types import ModuleType +from typing import Any + +import gymnasium as gym + +from isaaclab.envs import DirectMARLEnvCfg, ManagerBasedRLEnvCfg +from isaaclab.utils.dict import print_dict +from isaaclab.utils.io import dump_yaml + +from isaaclab_tasks.utils import add_launcher_args + + +def dispatch_library_entrypoint( + argv: list[str] | None, + entrypoints: dict[str, Path], + *, + action: str, + description: str, + library_help: str, + run_as_script: bool = False, +) -> int: + """Dispatch a unified entrypoint to a library-specific implementation. + + Args: + argv: Command-line arguments, excluding the script path. + entrypoints: Mapping from library name to implementation path. + action: Action name used to create a unique module name. + description: Top-level parser description. + library_help: Help text for the ``--rl_library`` argument. + run_as_script: Whether to execute the selected implementation as a script. + + Returns: + Process exit code. + """ + if argv is None: + argv = sys.argv[1:] + + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument("--rl_library", choices=sorted(entrypoints), required=True) + args_cli, library_args = parser.parse_known_args(argv) + + if args_cli.rl_library is None: + help_parser = argparse.ArgumentParser(description=description) + help_parser.add_argument("--rl_library", choices=sorted(entrypoints), required=True, help=library_help) + help_parser.add_argument("args", nargs=argparse.REMAINDER, help="Arguments forwarded to the selected library.") + help_parser.print_help() + return 0 if "-h" in argv or "--help" in argv else 2 + + module_path = entrypoints[args_cli.rl_library] + if run_as_script: + original_argv = sys.argv + original_path = list(sys.path) + try: + sys.argv = [str(module_path)] + library_args + sys.path.insert(0, str(module_path.parent)) + runpy.run_path(str(module_path), run_name="__main__") + finally: + sys.argv = original_argv + sys.path[:] = original_path + return 0 + + module = import_local_module(f"isaaclab_rl_{action}_{args_cli.rl_library}", module_path) + module.run(library_args) + return 0 + + +def add_common_train_args( + parser: argparse.ArgumentParser, + *, + agent_default: str | None, + agent_help: str, + include_agent: bool = True, + include_distributed: bool = True, +) -> None: + """Add common Isaac Lab reinforcement learning training arguments. + + Args: + parser: The parser to add arguments to. + agent_default: Default agent config entry point. + agent_help: Help text for the ``--agent`` argument. + include_agent: Whether to include the ``--agent`` argument. + include_distributed: Whether to include the ``--distributed`` argument. + """ + 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("--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.") + if include_agent: + parser.add_argument("--agent", type=str, default=agent_default, help=agent_help) + parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") + if include_distributed: + parser.add_argument( + "--distributed", action="store_true", default=False, help="Run training with multiple GPUs or nodes." + ) + parser.add_argument("--max_iterations", type=int, default=None, help="RL Policy training iterations.") + parser.add_argument("--export_io_descriptors", action="store_true", default=False, help="Export IO descriptors.") + parser.add_argument( + "--ray-proc-id", + "-rid", + type=int, + default=None, + help="Automatically configured by Ray integration, otherwise None.", + ) + + +def add_isaaclab_launcher_args(parser: argparse.ArgumentParser) -> None: + """Add Isaac Lab simulation launcher arguments to a parser. + + Args: + parser: The parser to add arguments to. + """ + add_launcher_args(parser) + + +def enable_cameras_for_video(args_cli: argparse.Namespace) -> None: + """Enable camera rendering when video recording is requested. + + Args: + args_cli: Parsed command-line arguments. + """ + if getattr(args_cli, "video", False): + args_cli.enable_cameras = True + + +def set_hydra_args(hydra_args: list[str]) -> None: + """Replace ``sys.argv`` with arguments intended for Hydra. + + Args: + hydra_args: Remaining command-line arguments not consumed by argparse. + """ + sys.argv = [sys.argv[0]] + hydra_args + + +def import_local_module(module_name: str, module_path: Path) -> ModuleType: + """Import a module from an explicit file path. + + Args: + module_name: Unique module name to use in ``sys.modules``. + module_path: Path to the Python file to import. + + Returns: + The imported module. + """ + spec = importlib.util.spec_from_file_location(module_name, module_path) + if spec is None or spec.loader is None: + raise ImportError(f"Could not load module {module_name!r} from {module_path}") + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + spec.loader.exec_module(module) + return module + + +def apply_env_overrides(args_cli: argparse.Namespace, env_cfg: Any, *, apply_device: bool = True) -> None: + """Apply common environment overrides from command-line arguments. + + Args: + args_cli: Parsed command-line arguments. + env_cfg: Isaac Lab environment config. + apply_device: Whether to apply the ``--device`` override for non-distributed runs. + """ + if getattr(args_cli, "num_envs", None) is not None: + env_cfg.scene.num_envs = args_cli.num_envs + + if apply_device and not getattr(args_cli, "distributed", False): + device = getattr(args_cli, "device", None) + env_cfg.sim.device = device if device is not None else env_cfg.sim.device + + +def validate_distributed_device(args_cli: argparse.Namespace) -> None: + """Reject unsupported CPU distributed training configuration. + + Args: + args_cli: Parsed command-line arguments. + + Raises: + ValueError: If distributed training is requested with a CPU device. + """ + device = getattr(args_cli, "device", None) + if getattr(args_cli, "distributed", False) and device is not None and "cpu" in device: + raise ValueError( + "Distributed training is not supported when using CPU device. " + "Please use GPU device (e.g., --device cuda) for distributed training." + ) + + +def configure_io_descriptors(env_cfg: Any, args_cli: argparse.Namespace, logger: logging.Logger) -> None: + """Configure IO descriptor export on supported environment configs. + + Args: + env_cfg: Isaac Lab environment config. + args_cli: Parsed command-line arguments. + logger: Logger used for unsupported environment warnings. + """ + if isinstance(env_cfg, ManagerBasedRLEnvCfg): + env_cfg.export_io_descriptors = args_cli.export_io_descriptors + else: + logger.warning( + "IO descriptors are only supported for manager based RL environments. No IO descriptors will be exported." + ) + + +def create_isaaclab_env( + task: str, + env_cfg: Any, + args_cli: argparse.Namespace, + *, + convert_marl_to_single_agent: bool, +): + """Create the Isaac Lab Gymnasium environment. + + Args: + task: Task name to instantiate. + env_cfg: Isaac Lab environment config. + args_cli: Parsed command-line arguments. + convert_marl_to_single_agent: Whether to convert direct MARL environments to single-agent environments. + + Returns: + The created Gymnasium environment. + """ + env = gym.make(task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + if convert_marl_to_single_agent and isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): + from isaaclab.envs import multi_agent_to_single_agent + + env = multi_agent_to_single_agent(env) + return env + + +def wrap_record_video(env, log_dir: str, args_cli: argparse.Namespace): + """Wrap an environment with video recording when requested. + + Args: + env: Gymnasium environment to wrap. + log_dir: Training log directory. + args_cli: Parsed command-line arguments. + + Returns: + The original or video-wrapped environment. + """ + if not args_cli.video: + return env + + video_kwargs = { + "video_folder": os.path.join(log_dir, "videos", "train"), + "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) + return gym.wrappers.RecordVideo(env, **video_kwargs) + + +def dump_train_configs(log_dir: str, env_cfg: Any, agent_cfg: Any) -> None: + """Dump training configuration files under a run log directory. + + Args: + log_dir: Training log directory. + env_cfg: Isaac Lab environment config. + agent_cfg: Reinforcement learning agent config. + """ + dump_yaml(os.path.join(log_dir, "params", "env.yaml"), env_cfg) + dump_yaml(os.path.join(log_dir, "params", "agent.yaml"), agent_cfg) diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/leapp/deploy.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/leapp/deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..5b032daa9ddacf8066f8035ea14361557819b79a --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/leapp/deploy.py @@ -0,0 +1,82 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Deploy a LEAPP-exported policy in an Isaac Lab simulation.""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +import sys + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser(description="Deploy a LEAPP-exported policy in simulation.") +parser.add_argument("--task", type=str, default=None, help="Name of the registered Isaac Lab task.") +parser.add_argument("--leapp_model", type=str, default=None, help="Path to the LEAPP .yaml pipeline description.") +parser.add_argument("--seed", type=int, default=None, help="Seed for the environment.") +AppLauncher.add_app_launcher_args(parser) +args_cli, hydra_args = parser.parse_known_args() + +if args_cli.task is None or args_cli.leapp_model is None: + missing_args = [] + if args_cli.task is None: + missing_args.append("--task") + if args_cli.leapp_model is None: + missing_args.append("--leapp_model") + parser.error(f"the following arguments are required: {', '.join(missing_args)}") + +sys.argv = [sys.argv[0]] + hydra_args + +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +from isaaclab.envs.leapp_deployment_env import LeappDeploymentEnv + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils.parse_cfg import load_cfg_from_registry + + +def main(): + # ── Load env config from gym registry ───────────────────────── + task_name = args_cli.task.split(":")[-1] + env_cfg = load_cfg_from_registry(task_name, "env_cfg_entry_point") + + if args_cli.seed is not None: + env_cfg.seed = args_cli.seed + if args_cli.device is not None: + env_cfg.sim.device = args_cli.device + + # ── Create deploy env ───────────────────────────────────────── + env = LeappDeploymentEnv(env_cfg, args_cli.leapp_model) + + if getattr(args_cli, "headless", False): + print( + "[WARN]: Running deploy without a viewport. This happens when headless mode is active, " + "including the default case where no visualizer was selected. The policy may be " + "stepping normally, but no viewport will appear unless you specify the " + "`--visualizer` field." + ) + + print(f"[INFO]: Deploying task '{task_name}' with LEAPP model: {args_cli.leapp_model}") + print(f"[INFO]: Num envs: {env.num_envs}, decimation: {env.cfg.decimation}, step_dt: {env.step_dt:.4f}s") + + # ── Run loop ────────────────────────────────────────────────── + env.reset() + try: + with torch.inference_mode(): + while simulation_app.is_running(): + env.step() + env.close() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/leapp/rsl_rl/export.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/leapp/rsl_rl/export.py new file mode 100644 index 0000000000000000000000000000000000000000..dce245448579cc8f4157a242afc69a64e9c2751d --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/leapp/rsl_rl/export.py @@ -0,0 +1,422 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to export a checkpoint if an RL agent from RSL-RL.""" + +from __future__ import annotations + +import argparse +import contextlib +import importlib.metadata as metadata +import os +import sys +import time +from collections.abc import Mapping +from pathlib import Path + +from isaaclab.app import AppLauncher + +from isaaclab_tasks.utils import setup_preset_cli + +_RSL_RL_SCRIPTS_DIR = Path(__file__).resolve().parents[2] / "rsl_rl" +if str(_RSL_RL_SCRIPTS_DIR) not in sys.path: + sys.path.insert(0, str(_RSL_RL_SCRIPTS_DIR)) +import cli_args # isort: skip + + +RSL_RL_MIN_VERSION = "5.0.1" +_RUNTIME_IMPORTS_LOADED = False + +# Keep heavy/runtime-sensitive imports out of module import time. The CLI needs +# to parse launcher arguments and start Isaac Sim/Kit before importing torch, +# LEAPP, RSL-RL, and task modules; importing them earlier has caused launcher +# import-order failures. ``_load_runtime_dependencies()`` populates these +# globals immediately before export execution. +torch = None +leapp = None +annotate = None +gym = None +DistillationRunner = None +OnPolicyRunner = None +ManagerBasedRLEnv = None +RslRlVecEnvWrapper = None +handle_deprecated_rsl_rl_cfg = None +retrieve_file_path = None +patch_env_for_export = None +ensure_env_spec_id = None +get_published_pretrained_checkpoint = None +get_checkpoint_path = None +hydra_task_config = None +installed_version = None + + +def create_arg_parser() -> argparse.ArgumentParser: + """Create the command-line parser for RSL-RL policy export.""" + parser = argparse.ArgumentParser(description="Export an RL agent with RSL-RL.") + parser.add_argument( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." + ) + parser.add_argument("--task", type=str, default=None, help="Name of the task.") + parser.add_argument( + "--agent", type=str, default="rsl_rl_cfg_entry_point", help="Name of the RL agent configuration entry point." + ) + parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") + parser.add_argument( + "--use_pretrained_checkpoint", + action="store_true", + help="Use the pre-trained checkpoint from Nucleus.", + ) + + # LEAPP arguments + parser.add_argument( + "--export_task_name", + type=str, + default=None, + help="Name of the exported graph. Defaults to the task name.", + ) + parser.add_argument( + "--export_method", + type=str, + default="onnx-dynamo", + choices=["onnx-dynamo", "onnx-torchscript", "jit-script", "jit-trace"], + help="Method to export the policy", + ) + parser.add_argument( + "--export_save_path", + type=str, + default=None, + help="Path to save the exported model", + ) + parser.add_argument( + "--validation_steps", + type=int, + default=5, + help="Number of steps to validate the exported model", + ) + parser.add_argument( + "--disable_graph_visualization", + action="store_true", + default=False, + help="Disable LEAPP graph visualization during compile_graph().", + ) + + cli_args.add_rsl_rl_args(parser) + AppLauncher.add_app_launcher_args(parser) + return parser + + +def parse_export_args(argv: list[str] | None = None) -> tuple[argparse.Namespace, list[str]]: + """Parse export arguments and return remaining Hydra overrides.""" + parser = create_arg_parser() + # setup_preset_cli attaches the preset-selection help group then parses; + # remainder still carries typed selectors (physics=/renderer=/presets=) + # verbatim for run_export_with_hydra to fold before invoking Hydra. + args_cli, hydra_args = setup_preset_cli(parser, argv) + args_cli.headless = True + return args_cli, hydra_args + + +def _load_runtime_dependencies() -> None: + """Import runtime dependencies after Isaac Sim has been launched.""" + global _RUNTIME_IMPORTS_LOADED + global annotate, leapp, torch + global DistillationRunner, ManagerBasedRLEnv, OnPolicyRunner, RslRlVecEnvWrapper, get_checkpoint_path, gym + global ensure_env_spec_id, get_published_pretrained_checkpoint, handle_deprecated_rsl_rl_cfg, hydra_task_config + global installed_version + global patch_env_for_export, retrieve_file_path + + if _RUNTIME_IMPORTS_LOADED: + return + + try: + import leapp as leapp_module + except ImportError as e: + raise ImportError("LEAPP package is required for policy export. Install with: pip install leapp") from e + annotate_module = getattr(leapp_module, "annotate") + + import gymnasium as gym_module + import torch as torch_module + from packaging import version as packaging_version_module + from rsl_rl.runners import DistillationRunner as DistillationRunnerCls + from rsl_rl.runners import OnPolicyRunner as OnPolicyRunnerCls + + # Disable TorchScript before importing task/environment modules so any + # @torch.jit.script helpers resolve to plain Python functions during export. + torch_module.jit._state.disable() + + from isaaclab.envs import ManagerBasedRLEnv as ManagerBasedRLEnvCls + from isaaclab.utils.assets import retrieve_file_path as retrieve_file_path_fn + from isaaclab.utils.leapp import patch_env_for_export as patch_env_for_export_fn + from isaaclab.utils.leapp.utils import ensure_env_spec_id as ensure_env_spec_id_fn + + from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper as RslRlVecEnvWrapperCls + from isaaclab_rl.rsl_rl import handle_deprecated_rsl_rl_cfg as handle_deprecated_rsl_rl_cfg_fn + from isaaclab_rl.utils.pretrained_checkpoint import ( + get_published_pretrained_checkpoint as get_published_pretrained_checkpoint_fn, + ) + + __import__("isaaclab_tasks") + from isaaclab_tasks.utils import get_checkpoint_path as get_checkpoint_path_fn + from isaaclab_tasks.utils.hydra import hydra_task_config as hydra_task_config_fn + + installed_version = metadata.version("rsl-rl-lib") + if packaging_version_module.parse(installed_version) < packaging_version_module.parse(RSL_RL_MIN_VERSION): + print( + f"[WARNING] LEAPP RSL-RL export is validated with rsl-rl-lib {RSL_RL_MIN_VERSION} or newer. " + f"Installed version is '{installed_version}'." + ) + + torch = torch_module + leapp = leapp_module + annotate = annotate_module + gym = gym_module + DistillationRunner = DistillationRunnerCls + OnPolicyRunner = OnPolicyRunnerCls + ManagerBasedRLEnv = ManagerBasedRLEnvCls + RslRlVecEnvWrapper = RslRlVecEnvWrapperCls + handle_deprecated_rsl_rl_cfg = handle_deprecated_rsl_rl_cfg_fn + retrieve_file_path = retrieve_file_path_fn + patch_env_for_export = patch_env_for_export_fn + ensure_env_spec_id = ensure_env_spec_id_fn + get_published_pretrained_checkpoint = get_published_pretrained_checkpoint_fn + get_checkpoint_path = get_checkpoint_path_fn + hydra_task_config = hydra_task_config_fn + _RUNTIME_IMPORTS_LOADED = True + + +def get_actor_memory_module(policy): + """Return the actor-side RNN module for supported RSL-RL recurrent policies.""" + if hasattr(policy, "rnn"): + return policy.rnn + return None + + +def is_actor_recurrent_policy(policy) -> bool: + """Return whether the actor policy has a supported recurrent state container.""" + return bool(getattr(policy, "is_recurrent", False) and get_actor_memory_module(policy) is not None) + + +def get_actor_hidden_state(policy): + """Return the actor-side recurrent hidden state for supported RSL-RL policy APIs.""" + if hasattr(policy, "get_hidden_state"): + return policy.get_hidden_state() + memory = get_actor_memory_module(policy) + return None if memory is None else getattr(memory, "hidden_state", None) + + +def set_actor_hidden_state(policy, actor_hidden) -> None: + """Assign the actor-side recurrent hidden state for supported RSL-RL policy APIs.""" + memory = get_actor_memory_module(policy) + if memory is not None: + memory.hidden_state = actor_hidden + + +def ensure_actor_hidden_state_initialized(policy, batch_size: int, device, dtype): + """Initialize and return the actor hidden state when a recurrent policy has not created it yet.""" + # ``torch`` is a lazy runtime global populated by ``_load_runtime_dependencies()`` + # after Isaac Sim launches and before export calls this helper. + assert torch is not None + actor_state = get_actor_hidden_state(policy) + if actor_state is not None: + return actor_state + + memory = get_actor_memory_module(policy) + if memory is None or not hasattr(memory, "rnn"): + return None + + num_layers = memory.rnn.num_layers + hidden_size = memory.rnn.hidden_size + zeros = torch.zeros(num_layers, batch_size, hidden_size, device=device, dtype=dtype) + if isinstance(memory.rnn, torch.nn.LSTM): + actor_state = (zeros.clone(), zeros.clone()) + else: + actor_state = zeros + set_actor_hidden_state(policy, actor_state) + return actor_state + + +def state_dict_from_actor_hidden(actor_hidden): + """Convert the actor hidden state into the named tensor mapping expected by LEAPP state APIs.""" + if actor_hidden is None: + return {} + if isinstance(actor_hidden, tuple): + return {f"actor_state_{idx}": tensor for idx, tensor in enumerate(actor_hidden)} + return {"actor_state": actor_hidden} + + +def actor_hidden_from_registered(registered_state, original_hidden): + """Restore the registered LEAPP state to the hidden-state structure expected by the actor memory module.""" + if isinstance(original_hidden, tuple): + if isinstance(registered_state, tuple): + return registered_state + return (registered_state,) + return registered_state + + +def export_rsl_rl_agent( + args_cli: argparse.Namespace, + env_cfg, + agent_cfg, + simulation_app=None, +) -> bool: + """Export a RSL-RL agent.""" + _load_runtime_dependencies() + + task_name = args_cli.task.split(":")[-1] + checkpoint_task_name = task_name.replace("-Play", "") + + agent_cfg = cli_args.update_rsl_rl_cfg(agent_cfg, args_cli) + env_cfg.scene.num_envs = 1 + + agent_cfg = handle_deprecated_rsl_rl_cfg(agent_cfg, installed_version) + + # note: certain randomizations occur in the environment initialization so we set the seed here + env_cfg.seed = agent_cfg.seed + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name) + log_root_path = os.path.abspath(log_root_path) + print(f"[INFO] Loading checkpoint search path from directory: {log_root_path}") + if args_cli.use_pretrained_checkpoint: + resume_path = get_published_pretrained_checkpoint("rsl_rl", checkpoint_task_name) + if not resume_path: + print("[INFO] Unfortunately a pre-trained checkpoint is currently unavailable for this task.") + return False + elif args_cli.checkpoint: + resume_path = retrieve_file_path(args_cli.checkpoint) + else: + resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) + + if not resume_path: + print(f"[INFO] No checkpoint found for task: {checkpoint_task_name} in directory: {log_root_path}") + return False + + log_dir = os.path.dirname(resume_path) + + env_cfg.log_dir = log_dir + + env = None + leapp_started = False + + try: + env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None) + policy_node_name = ensure_env_spec_id(env) + + graph_name = args_cli.export_task_name if args_cli.export_task_name is not None else task_name + + if isinstance(env.unwrapped, ManagerBasedRLEnv): + # Patch only the observation groups consumed by the actor policy. + # This filters out the critic and teacher observation groups. + obs_groups_cfg = getattr(agent_cfg, "obs_groups", None) + if isinstance(obs_groups_cfg, Mapping): + required_obs_groups = set(obs_groups_cfg.get("actor", ["policy"])) + else: + required_obs_groups = {"policy"} + patch_env_for_export( + env, + export_method=args_cli.export_method, + required_obs_groups=required_obs_groups, + ) + + env = RslRlVecEnvWrapper(env, clip_actions=agent_cfg.clip_actions) + + print(f"[INFO]: Loading model checkpoint from: {resume_path}") + if agent_cfg.class_name == "OnPolicyRunner": + runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + elif agent_cfg.class_name == "DistillationRunner": + runner = DistillationRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + else: + raise ValueError(f"Unsupported runner class: {agent_cfg.class_name}") + runner.load(resume_path) + + policy = runner.get_inference_policy(device=env.unwrapped.device) + + if args_cli.export_save_path is not None: + save_path = args_cli.export_save_path + elif args_cli.use_pretrained_checkpoint: + # Use a predictable path independent of the Nucleus mirror directory structure. + save_path = os.path.join(".pretrained_checkpoints", "rsl_rl", checkpoint_task_name) + else: + save_path = log_dir + leapp.start(graph_name, save_path=save_path, max_cached_io=max(args_cli.validation_steps, 2)) + leapp_started = True + obs = env.reset()[0] + if simulation_app is not None: + while not simulation_app.is_running(): + time.sleep(0.5) + + for _ in range(max(args_cli.validation_steps, 2)): + with torch.inference_mode(): + if is_actor_recurrent_policy(policy): + actor_hidden = ensure_actor_hidden_state_initialized( + policy, + batch_size=env.num_envs, + device=env.unwrapped.device, + dtype=next(policy.parameters()).dtype, + ) + registered_state = annotate.state_tensors( + policy_node_name, + state_dict_from_actor_hidden(actor_hidden), + ) + set_actor_hidden_state(policy, actor_hidden_from_registered(registered_state, actor_hidden)) + + actions = policy(obs) + + if is_actor_recurrent_policy(policy): + actor_hidden_after = get_actor_hidden_state(policy) + annotate.update_state( + policy_node_name, + state_dict_from_actor_hidden(actor_hidden_after), + ) + + obs, _, _, _ = env.step(actions) + + leapp.stop() + leapp_started = False + validate = args_cli.validation_steps > 0 + leapp.compile_graph(visualize=not args_cli.disable_graph_visualization, validate=validate) + finally: + if leapp_started: + with contextlib.suppress(Exception): + leapp.stop() + if env is not None: + env.close() + + return True + + +def run_export_with_hydra(args_cli: argparse.Namespace, hydra_args: list[str]) -> bool: + """Resolve Hydra task configuration and export one RSL-RL policy.""" + from isaaclab_tasks.utils.hydra import hydra_task_config + from isaaclab_tasks.utils.sim_launcher import launch_simulation + + original_argv = sys.argv + # Hydra reads the preset tokens (physics=/renderer=/presets=) from sys.argv directly. + sys.argv = [sys.argv[0]] + hydra_args + exported = False + + try: + + @hydra_task_config(args_cli.task, args_cli.agent) + def _main(env_cfg, agent_cfg) -> None: + nonlocal exported + with launch_simulation(env_cfg, args_cli): + exported = export_rsl_rl_agent(args_cli, env_cfg, agent_cfg) + + _main() + finally: + sys.argv = original_argv + + return exported + + +def main_cli(argv: list[str] | None = None) -> bool: + """Run the command-line export flow.""" + args_cli, hydra_args = parse_export_args(argv) + return run_export_with_hydra(args_cli, hydra_args) + + +if __name__ == "__main__": + main_cli() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/play.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/play.py new file mode 100644 index 0000000000000000000000000000000000000000..1a12ff61d9dcbdc17f9ea148b8bfbd0ace697de0 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/play.py @@ -0,0 +1,38 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unified play entrypoint for Isaac Lab reinforcement learning workflows.""" + +from __future__ import annotations + +from pathlib import Path + +from common import dispatch_library_entrypoint + +SCRIPT_DIR = Path(__file__).resolve().parent + +LIBRARY_ENTRYPOINTS = { + "rl_games": SCRIPT_DIR / "rl_games" / "play_rl_games.py", + "rlinf": SCRIPT_DIR / "rlinf" / "play_rlinf.py", + "rsl_rl": SCRIPT_DIR / "rsl_rl" / "play_rsl_rl.py", + "sb3": SCRIPT_DIR / "sb3" / "play_sb3.py", + "skrl": SCRIPT_DIR / "skrl" / "play_skrl.py", +} + + +def main(argv: list[str] | None = None) -> int: + """Run the selected reinforcement learning play library.""" + return dispatch_library_entrypoint( + argv, + LIBRARY_ENTRYPOINTS, + action="play", + description="Play an RL agent with a selected reinforcement learning library.", + library_help="Training library used by the checkpoint.", + run_as_script=True, + ) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/cluster_configs/Dockerfile b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/cluster_configs/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e75b756057fe4fca45b17cb68c04a6ba96ba437b --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/cluster_configs/Dockerfile @@ -0,0 +1,23 @@ +FROM isaac-lab-base:latest + +# WGet is needed so that GCS or other cloud providers can mark the container as ready. +# Otherwise the Ray liveliness checks fail. +RUN apt-get update && apt-get install wget + +# Set NVIDIA paths +ENV PATH="/usr/local/nvidia/bin:$PATH" +ENV LD_LIBRARY_PATH="/usr/local/nvidia/lib64" + +# Link NVIDIA binaries +RUN ln -sf /usr/local/nvidia/bin/nvidia* /usr/bin + +# Install Ray and configure it +RUN /workspace/isaaclab/_isaac_sim/python.sh -m pip install "ray[default, tune]"==2.31.0 && \ +sed -i "1i $(echo "#!/workspace/isaaclab/_isaac_sim/python.sh")" \ +/isaac-sim/kit/python/bin/ray && ln -s /isaac-sim/kit/python/bin/ray /usr/local/bin/ray + +# Install tuning dependencies +RUN /workspace/isaaclab/_isaac_sim/python.sh -m pip install optuna bayesian-optimization + +# Install MLflow for logging +RUN /workspace/isaaclab/_isaac_sim/python.sh -m pip install mlflow diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/cluster_configs/google_cloud/kuberay.yaml.jinja b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/cluster_configs/google_cloud/kuberay.yaml.jinja new file mode 100644 index 0000000000000000000000000000000000000000..40ccccf7c683f5f5750486ca7c135afb552fa88b --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/cluster_configs/google_cloud/kuberay.yaml.jinja @@ -0,0 +1,203 @@ +# Jinja is used for templating here as full helm setup is excessive for application +apiVersion: ray.io/v1alpha1 +kind: RayCluster +metadata: + name: {{ name }} + namespace: {{ namespace }} +spec: + rayVersion: "2.8.0" + enableInTreeAutoscaling: true + autoscalerOptions: + upscalingMode: Default + idleTimeoutSeconds: 120 + imagePullPolicy: Always + securityContext: {} + envFrom: [] + + headGroupSpec: + rayStartParams: + block: "true" + dashboard-host: 0.0.0.0 + dashboard-port: "8265" + port: "6379" + include-dashboard: "true" + ray-debugger-external: "true" + object-manager-port: "8076" + num-gpus: "0" + num-cpus: "0" # prevent scheduling jobs to the head node - workers only + headService: + apiVersion: v1 + kind: Service + metadata: + name: {{ name }}-head + spec: + type: LoadBalancer + template: + metadata: + labels: + app.kubernetes.io/instance: tuner + app.kubernetes.io/name: kuberay + cloud.google.com/gke-ray-node-type: head + spec: + serviceAccountName: {{ service_account_name }} + affinity: {} + securityContext: + fsGroup: 100 + containers: + - env: + image: {{ image }} + imagePullPolicy: Always + name: head + resources: + limits: + cpu: "{{ num_head_cpu }}" + memory: {{ head_ram_gb }}G + nvidia.com/gpu: "0" + requests: + cpu: "{{ num_head_cpu }}" + memory: {{ head_ram_gb }}G + nvidia.com/gpu: "0" + securityContext: {} + volumeMounts: + - mountPath: /tmp/ray + name: ray-logs + command: ["/bin/bash", "-c", "ray start --head --port=6379 --object-manager-port=8076 --dashboard-host=0.0.0.0 --dashboard-port=8265 --include-dashboard=true && tail -f /dev/null"] + - image: fluent/fluent-bit:1.9.6 + name: fluentbit + resources: + limits: + cpu: 100m + memory: 128Mi + requests: + cpu: 100m + memory: 128Mi + volumeMounts: + - mountPath: /tmp/ray + name: ray-logs + imagePullSecrets: [] + nodeSelector: + iam.gke.io/gke-metadata-server-enabled: "true" + volumes: + - configMap: + name: fluentbit-config + name: fluentbit-config + - name: ray-logs + emptyDir: {} + + workerGroupSpecs: + {% for it in range(gpu_per_worker|length) %} + - groupName: "{{ worker_accelerator[it] }}x{{ gpu_per_worker[it] }}-cpu-{{ cpu_per_worker[it] }}-ram-gb-{{ ram_gb_per_worker[it] }}" + replicas: {{ num_workers[it] }} + maxReplicas: {{ num_workers[it] }} + minReplicas: {{ num_workers[it] }} + rayStartParams: + block: "true" + ray-debugger-external: "true" + replicas: "{{num_workers[it]}}" + template: + metadata: + annotations: {} + labels: + app.kubernetes.io/instance: tuner + app.kubernetes.io/name: kuberay + cloud.google.com/gke-ray-node-type: worker + spec: + serviceAccountName: {{ service_account_name }} + affinity: {} + securityContext: + fsGroup: 100 + containers: + - env: + - name: NVIDIA_VISIBLE_DEVICES + value: "all" + - name: NVIDIA_DRIVER_CAPABILITIES + value: "compute,utility" + + image: {{ image }} + imagePullPolicy: Always + name: ray-worker + resources: + limits: + cpu: "{{ cpu_per_worker[it] }}" + memory: {{ ram_gb_per_worker[it] }}G + nvidia.com/gpu: "{{ gpu_per_worker[it] }}" + requests: + cpu: "{{ cpu_per_worker[it] }}" + memory: {{ ram_gb_per_worker[it] }}G + nvidia.com/gpu: "{{ gpu_per_worker[it] }}" + securityContext: {} + volumeMounts: + - mountPath: /tmp/ray + name: ray-logs + command: ["/bin/bash", "-c", "ray start --address={{name}}-head.{{ namespace }}.svc.cluster.local:6379 && tail -f /dev/null"] + - image: fluent/fluent-bit:1.9.6 + name: fluentbit + resources: + limits: + cpu: 100m + memory: 128Mi + requests: + cpu: 100m + memory: 128Mi + volumeMounts: + - mountPath: /tmp/ray + name: ray-logs + + imagePullSecrets: [] + nodeSelector: + cloud.google.com/gke-accelerator: {{ worker_accelerator[it] }} + iam.gke.io/gke-metadata-server-enabled: "true" + tolerations: + - key: "nvidia.com/gpu" + operator: "Exists" + effect: "NoSchedule" + volumes: + - configMap: + name: fluentbit-config + name: fluentbit-config + - name: ray-logs + emptyDir: {} + {% endfor %} + +--- +# ML Flow Server - for fetching logs +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{name}}-mlflow + namespace: {{ namespace }} +spec: + replicas: 1 + selector: + matchLabels: + app: mlflow + template: + metadata: + labels: + app: mlflow + spec: + containers: + - name: mlflow + image: ghcr.io/mlflow/mlflow:v2.9.2 + ports: + - containerPort: 5000 + command: ["mlflow"] + args: + - server + - --host=0.0.0.0 + - --port=5000 + - --backend-store-uri=sqlite:///mlflow.db +--- +# ML Flow Service (for port forwarding, kubectl port-forward service/{name}-mlflow 5000:5000) +apiVersion: v1 +kind: Service +metadata: + name: {{name}}-mlflow + namespace: {{ namespace }} +spec: + selector: + app: mlflow + ports: + - port: 5000 + targetPort: 5000 + type: ClusterIP diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/grok_cluster_with_kubectl.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/grok_cluster_with_kubectl.py new file mode 100644 index 0000000000000000000000000000000000000000..b7b3c5cf89e258aea16788d1daa9c74f19ab3f5b --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/grok_cluster_with_kubectl.py @@ -0,0 +1,275 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import argparse +import os +import re +import subprocess +import threading +import time +from concurrent.futures import ThreadPoolExecutor, as_completed + +""" +This script requires that kubectl is installed and KubeRay was used to create the cluster. + +Creates a config file containing ``name: address: http://:`` on +a new line for each cluster, and also fetches the MLFlow URI. + +Usage: + +.. code-block:: bash + + python3 scripts/reinforcement_learning/ray/grok_cluster_with_kubectl.py + # For options, supply -h arg +""" + + +def get_namespace() -> str: + """Get the current Kubernetes namespace from the context, fallback to default if not set""" + try: + namespace = ( + subprocess.check_output(["kubectl", "config", "view", "--minify", "--output", "jsonpath={..namespace}"]) + .decode() + .strip() + ) + if not namespace: + namespace = "default" + except subprocess.CalledProcessError: + namespace = "default" + return namespace + + +def get_pods(namespace: str = "default") -> list[tuple]: + """Get a list of all of the pods in the namespace""" + cmd = ["kubectl", "get", "pods", "-n", namespace, "--no-headers"] + output = subprocess.check_output(cmd).decode() + pods = [] + for line in output.strip().split("\n"): + fields = line.split() + pod_name = fields[0] + status = fields[2] + pods.append((pod_name, status)) + return pods + + +def get_clusters(pods: list, cluster_name_prefix: str) -> set: + """ + Get unique cluster name(s). Works for one or more clusters, based off of the number of head nodes. + Excludes MLflow deployments. + """ + clusters = set() + for pod_name, _ in pods: + # Skip MLflow pods + if "-mlflow" in pod_name: + continue + + match = re.match(r"(" + re.escape(cluster_name_prefix) + r"[-\w]+)", pod_name) + if match: + # Get base name without head/worker suffix (skip workers) + if "head" in pod_name: + base_name = match.group(1).split("-head")[0] + clusters.add(base_name) + return sorted(clusters) + + +def get_mlflow_info(namespace: str = None, cluster_prefix: str = "isaacray") -> str: + """ + Get MLflow service information if it exists in the namespace with the given prefix. + Only works for a single cluster instance. + Args: + namespace: Kubernetes namespace + cluster_prefix: Base cluster name (without -head/-worker suffixes) + Returns: + MLflow service URL + """ + # Strip any -head or -worker suffixes to get base name + if namespace is None: + namespace = get_namespace() + pods = get_pods(namespace=namespace) + clusters = get_clusters(pods=pods, cluster_name_prefix=cluster_prefix) + if len(clusters) > 1: + raise ValueError("More than one cluster matches prefix, could not automatically determine mlflow info.") + mlflow_name = f"{cluster_prefix}-mlflow" + + cmd = ["kubectl", "get", "svc", mlflow_name, "-n", namespace, "--no-headers"] + try: + output = subprocess.check_output(cmd).decode() + fields = output.strip().split() + + # Get cluster IP + cluster_ip = fields[2] + port = "5000" # Default MLflow port + # This needs to be http to be resolved. HTTPS can't be resolved + # This should be fine as it is on a subnet on the cluster regardless + return f"http://{cluster_ip}:{port}" + except subprocess.CalledProcessError as e: + raise ValueError(f"Could not grok MLflow: {e}") # Fixed f-string + + +def check_clusters_running(pods: list, clusters: set) -> bool: + """ + Check that all of the pods in all provided clusters are running. + + Args: + pods (list): A list of tuples where each tuple contains the pod name and its status. + clusters (set): A set of cluster names to check. + + Returns: + bool: True if all pods in any of the clusters are running, False otherwise. + """ + clusters_running = False + for cluster in clusters: + cluster_pods = [p for p in pods if p[0].startswith(cluster)] + total_pods = len(cluster_pods) + running_pods = len([p for p in cluster_pods if p[1] == "Running"]) + if running_pods == total_pods and running_pods > 0: + clusters_running = True + break + return clusters_running + + +def get_ray_address(head_pod: str, namespace: str = "default", ray_head_name: str = "head") -> str: + """ + Given a cluster head pod, check its logs, which should include the ray address which can accept job requests. + + Args: + head_pod (str): The name of the head pod. + namespace (str, optional): The Kubernetes namespace. Defaults to "default". + ray_head_name (str, optional): The name of the ray head container. Defaults to "head". + + Returns: + str: The ray address if found, None otherwise. + + Raises: + ValueError: If the logs cannot be retrieved or the ray address is not found. + """ + cmd = ["kubectl", "logs", head_pod, "-c", ray_head_name, "-n", namespace] + try: + output = subprocess.check_output(cmd).decode() + except subprocess.CalledProcessError as e: + raise ValueError( + f"Could not enter head container with cmd {cmd}: {e}Perhaps try a different namespace or ray head name." + ) + match = re.search(r"RAY_ADDRESS='([^']+)'", output) + if match: + return match.group(1) + else: + return None + + +def process_cluster(cluster_info: dict, ray_head_name: str = "head") -> str: + """ + For each cluster, check that it is running, and get the Ray head address that will accept jobs. + + Args: + cluster_info: A dictionary containing cluster information with keys 'cluster', 'pods', and 'namespace'. + ray_head_name: The name of the ray head container. Defaults to "head". + + Returns: + A string containing the cluster name and its Ray head address, or an error message if + the head pod or Ray address is not found. + """ + cluster, pods, namespace = cluster_info + head_pod = None + for pod_name, status in pods: + if pod_name.startswith(cluster + "-head"): + head_pod = pod_name + break + if not head_pod: + return f"Error: Could not find head pod for cluster {cluster}\n" + + # Get RAY_ADDRESS and status + ray_address = get_ray_address(head_pod, namespace=namespace, ray_head_name=ray_head_name) + if not ray_address: + return f"Error: Could not find RAY_ADDRESS for cluster {cluster}\n" + + # Return only cluster and ray address + return f"name: {cluster} address: {ray_address}\n" + + +def main(): + # Parse command-line arguments + parser = argparse.ArgumentParser(description="Process Ray clusters and save their specifications.") + parser.add_argument("--prefix", default="isaacray", help="The prefix for the cluster names.") + parser.add_argument("--output", default="~/.cluster_config", help="The file to save cluster specifications.") + parser.add_argument("--ray_head_name", default="head", help="The metadata name for the ray head container") + parser.add_argument( + "--namespace", help="Kubernetes namespace to use. If not provided, will detect from current context." + ) + args = parser.parse_args() + + # Get namespace from args or detect it + current_namespace = args.namespace if args.namespace else get_namespace() + print(f"Using namespace: {current_namespace}") + + cluster_name_prefix = args.prefix + cluster_spec_file = os.path.expanduser(args.output) + + # Get all pods + pods = get_pods(namespace=current_namespace) + + # Get clusters + clusters = get_clusters(pods, cluster_name_prefix) + if not clusters: + print(f"No clusters found with prefix {cluster_name_prefix}") + return + + # Wait for clusters to be running + while True: + pods = get_pods(namespace=current_namespace) + if check_clusters_running(pods, clusters): + break + print("Waiting for all clusters to spin up...") + time.sleep(5) + + print("Checking for MLflow:") + # Check MLflow status for each cluster + for cluster in clusters: + try: + mlflow_address = get_mlflow_info(current_namespace, cluster) + print(f"MLflow address for {cluster}: {mlflow_address}") + except ValueError as e: + print(f"ML Flow not located: {e}") + print() + + # Prepare cluster info for parallel processing + cluster_infos = [] + for cluster in clusters: + cluster_pods = [p for p in pods if p[0].startswith(cluster)] + cluster_infos.append((cluster, cluster_pods, current_namespace)) + + # Use ThreadPoolExecutor to process clusters in parallel + results = [] + results_lock = threading.Lock() + + with ThreadPoolExecutor() as executor: + future_to_cluster = { + executor.submit(process_cluster, info, args.ray_head_name): info[0] for info in cluster_infos + } + for future in as_completed(future_to_cluster): + cluster_name = future_to_cluster[future] + try: + result = future.result() + with results_lock: + results.append(result) + except Exception as exc: + print(f"{cluster_name} generated an exception: {exc}") + + # Sort results alphabetically by cluster name + results.sort() + + # Write sorted results to the output file (Ray info only) + with open(cluster_spec_file, "w") as f: + for result in results: + f.write(result) + + print(f"Cluster spec information saved to {cluster_spec_file}") + # Display the contents of the config file + with open(cluster_spec_file) as f: + print(f.read()) + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/hyperparameter_tuning/vision_cartpole_cfg.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/hyperparameter_tuning/vision_cartpole_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..f43ae7ecaaaa4c534057f644e8746ddbe7791027 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/hyperparameter_tuning/vision_cartpole_cfg.py @@ -0,0 +1,85 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause +import pathlib +import sys +from typing import Any + +# Allow for import of items from the ray workflow. +CUR_DIR = pathlib.Path(__file__).parent +UTIL_DIR = CUR_DIR.parent +sys.path.extend([str(UTIL_DIR), str(CUR_DIR)]) +import util +import vision_cfg +from ray import tune +from ray.tune.progress_reporter import CLIReporter +from ray.tune.stopper import Stopper + + +class CartpoleRGBNoTuneJobCfg(vision_cfg.CameraJobCfg): + def __init__(self, cfg: dict = {}): + cfg = util.populate_isaac_ray_cfg_args(cfg) + cfg["runner_args"]["--task"] = tune.choice(["Isaac-Cartpole-RGB-v0"]) + super().__init__(cfg, vary_env_count=False, vary_cnn=False, vary_mlp=False) + + +class CartpoleRGBCNNOnlyJobCfg(vision_cfg.CameraJobCfg): + def __init__(self, cfg: dict = {}): + cfg = util.populate_isaac_ray_cfg_args(cfg) + cfg["runner_args"]["--task"] = tune.choice(["Isaac-Cartpole-RGB-v0"]) + super().__init__(cfg, vary_env_count=False, vary_cnn=True, vary_mlp=False) + + +class CartpoleRGBJobCfg(vision_cfg.CameraJobCfg): + def __init__(self, cfg: dict = {}): + cfg = util.populate_isaac_ray_cfg_args(cfg) + cfg["runner_args"]["--task"] = tune.choice(["Isaac-Cartpole-RGB-v0"]) + super().__init__(cfg, vary_env_count=True, vary_cnn=True, vary_mlp=True) + + +class CartpoleResNetJobCfg(vision_cfg.ResNetCameraJob): + def __init__(self, cfg: dict = {}): + cfg = util.populate_isaac_ray_cfg_args(cfg) + cfg["runner_args"]["--task"] = tune.choice(["Isaac-Cartpole-RGB-ResNet18-v0"]) + super().__init__(cfg) + + +class CartpoleTheiaJobCfg(vision_cfg.TheiaCameraJob): + def __init__(self, cfg: dict = {}): + cfg = util.populate_isaac_ray_cfg_args(cfg) + cfg["runner_args"]["--task"] = tune.choice(["Isaac-Cartpole-RGB-TheiaTiny-v0"]) + super().__init__(cfg) + + +class CustomCartpoleProgressReporter(CLIReporter): + def __init__(self): + super().__init__( + metric_columns={ + "training_iteration": "iter", + "time_total_s": "total time (s)", + "Episode/Episode_Reward/alive": "alive", + "Episode/Episode_Reward/cart_vel": "cart velocity", + "rewards/time": "rewards/time", + }, + max_report_frequency=5, + sort_by_metric=True, + ) + + +class CartpoleEarlyStopper(Stopper): + def __init__(self): + self._bad_trials = set() + + def __call__(self, trial_id: str, result: dict[str, Any]) -> bool: + iter = result.get("training_iteration", 0) + out_of_bounds = result.get("Episode/Episode_Termination/cart_out_of_bounds") + + # Mark the trial for stopping if conditions are met + if iter >= 20 and out_of_bounds is not None and out_of_bounds > 0.85: + self._bad_trials.add(trial_id) + + return trial_id in self._bad_trials + + def stop_all(self) -> bool: + return False # only stop individual trials diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/hyperparameter_tuning/vision_cfg.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/hyperparameter_tuning/vision_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..cb59a993368df7c0fffc758a51d4f698fe0dc7f3 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/hyperparameter_tuning/vision_cfg.py @@ -0,0 +1,154 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import pathlib +import sys + +# Allow for import of items from the ray workflow. +UTIL_DIR = pathlib.Path(__file__).parent.parent.parent +sys.path.append(str(UTIL_DIR)) +import tuner +import util +from ray import tune + + +class CameraJobCfg(tuner.JobCfg): + """In order to be compatible with :meth: invoke_tuning_run, and + :class:IsaacLabTuneTrainable , configurations should + be in a similar format to this class. This class can vary env count/horizon length, + CNN structure, and MLP structure. Broad possible ranges are set, the specific values + that work can be found via tuning. Tuning results can inform better ranges for a second tuning run. + These ranges were selected for demonstration purposes. Best ranges are run/task specific.""" + + @staticmethod + def _get_batch_size_divisors(batch_size: int, min_size: int = 128) -> list[int]: + """Get valid batch divisors to combine with num_envs and horizon length""" + divisors = [i for i in range(min_size, batch_size + 1) if batch_size % i == 0] + return divisors if divisors else [min_size] + + def __init__(self, cfg={}, vary_env_count: bool = False, vary_cnn: bool = False, vary_mlp: bool = False): + cfg = util.populate_isaac_ray_cfg_args(cfg) + + # Basic configuration + cfg["runner_args"]["headless_singleton"] = "--headless" + cfg["runner_args"]["enable_cameras_singleton"] = "--enable_cameras" + cfg["hydra_args"]["agent.params.config.max_epochs"] = 200 + + if vary_env_count: # Vary the env count, and horizon length, and select a compatible mini-batch size + # Check from 512 to 8196 envs in powers of 2 + # check horizon lengths of 8 to 256 + # More envs should be better, but different batch sizes can improve gradient estimation + env_counts = [2**x for x in range(9, 13)] + horizon_lengths = [2**x for x in range(3, 8)] + + selected_env_count = tune.choice(env_counts) + selected_horizon = tune.choice(horizon_lengths) + + cfg["runner_args"]["--num_envs"] = selected_env_count + cfg["hydra_args"]["agent.params.config.horizon_length"] = selected_horizon + + def get_valid_batch_size(config): + num_envs = config["runner_args"]["--num_envs"] + horizon_length = config["hydra_args"]["agent.params.config.horizon_length"] + total_batch = horizon_length * num_envs + divisors = self._get_batch_size_divisors(total_batch) + return divisors[0] + + cfg["hydra_args"]["agent.params.config.minibatch_size"] = tune.sample_from(get_valid_batch_size) + + if vary_cnn: # Vary the depth, and size of the layers in the CNN part of the agent + # Also varies kernel size, and stride. + num_layers = tune.randint(2, 3) + cfg["hydra_args"]["agent.params.network.cnn.type"] = "conv2d" + cfg["hydra_args"]["agent.params.network.cnn.activation"] = tune.choice(["relu", "elu"]) + cfg["hydra_args"]["agent.params.network.cnn.initializer"] = "{name:default}" + cfg["hydra_args"]["agent.params.network.cnn.regularizer"] = "{name:None}" + + def get_cnn_layers(_): + layers = [] + size = 64 # Initial input size + + for _ in range(num_layers.sample()): + # Get valid kernel sizes for current size + valid_kernels = [k for k in [3, 4, 6, 8, 10, 12] if k <= size] + if not valid_kernels: + break + + kernel = int(tune.choice([str(k) for k in valid_kernels]).sample()) + stride = int(tune.choice(["1", "2", "3", "4"]).sample()) + padding = int(tune.choice(["0", "1"]).sample()) + + # Calculate next size + next_size = ((size + 2 * padding - kernel) // stride) + 1 + if next_size <= 0: + break + + layers.append( + { + "filters": tune.randint(16, 32).sample(), + "kernel_size": str(kernel), + "strides": str(stride), + "padding": str(padding), + } + ) + size = next_size + + return layers + + cfg["hydra_args"]["agent.params.network.cnn.convs"] = tune.sample_from(get_cnn_layers) + + if vary_mlp: # Vary the MLP structure; neurons (units) per layer, number of layers, + max_num_layers = 6 + max_neurons_per_layer = 128 + if "env.observations.policy.image.params.model_name" in cfg["hydra_args"]: + # By decreasing MLP size when using pretrained helps prevent out of memory on L4 + max_num_layers = 3 + max_neurons_per_layer = 32 + if "agent.params.network.cnn.convs" in cfg["hydra_args"]: + # decrease MLP size to prevent running out of memory on L4 + max_num_layers = 2 + max_neurons_per_layer = 32 + + num_layers = tune.randint(1, max_num_layers) + + def get_mlp_layers(_): + return [tune.randint(4, max_neurons_per_layer).sample() for _ in range(num_layers.sample())] + + cfg["hydra_args"]["agent.params.network.mlp.units"] = tune.sample_from(get_mlp_layers) + cfg["hydra_args"]["agent.params.network.mlp.initializer.name"] = tune.choice(["default"]).sample() + cfg["hydra_args"]["agent.params.network.mlp.activation"] = tune.choice( + ["relu", "tanh", "sigmoid", "elu"] + ).sample() + + super().__init__(cfg) + + +class ResNetCameraJob(CameraJobCfg): + """Try different ResNet sizes.""" + + def __init__(self, cfg: dict = {}): + cfg = util.populate_isaac_ray_cfg_args(cfg) + cfg["hydra_args"]["env.observations.policy.image.params.model_name"] = tune.choice( + ["resnet18", "resnet34", "resnet50", "resnet101"] + ) + super().__init__(cfg, vary_env_count=True, vary_cnn=False, vary_mlp=True) + + +class TheiaCameraJob(CameraJobCfg): + """Try different Theia sizes.""" + + def __init__(self, cfg: dict = {}): + cfg = util.populate_isaac_ray_cfg_args(cfg) + cfg["hydra_args"]["env.observations.policy.image.params.model_name"] = tune.choice( + [ + "theia-tiny-patch16-224-cddsv", + "theia-tiny-patch16-224-cdiv", + "theia-small-patch16-224-cdiv", + "theia-base-patch16-224-cdiv", + "theia-small-patch16-224-cddsv", + "theia-base-patch16-224-cddsv", + ] + ) + super().__init__(cfg, vary_env_count=True, vary_cnn=False, vary_mlp=True) diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/launch.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..3a3be716702e2cbb09cc78f12bb09750eff3b69a --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/launch.py @@ -0,0 +1,183 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""This script helps create one or more KubeRay clusters. + +Usage: + +.. code-block:: bash + # If the head node is stuck on container creating, make sure to create a secret + python3 scripts/reinforcement_learning/ray/launch.py -h + + # Examples + + # The following creates 8 GPUx1 nvidia l4 workers + python3 scripts/reinforcement_learning/ray/launch.py --cluster_host google_cloud \ + --namespace --image \ + --num_workers 8 --num_clusters 1 --worker_accelerator nvidia-l4 --gpu_per_worker 1 + + # The following creates 1 GPUx1 nvidia l4 worker, 2 GPUx2 nvidia-tesla-t4 workers, + # and 2 GPUx4 nvidia-tesla-t4 GPU workers + python3 scripts/reinforcement_learning/ray/launch.py --cluster_host google_cloud \ + --namespace --image \ + --num_workers 1 2 --num_clusters 1 \ + --worker_accelerator nvidia-l4 nvidia-tesla-t4 --gpu_per_worker 1 2 4 +""" + +import argparse +import pathlib +import subprocess + +import yaml +from jinja2 import Environment, FileSystemLoader +from kubernetes import config + +# Local imports +import util # isort: skip + +RAY_DIR = pathlib.Path(__file__).parent + + +def apply_manifest(args: argparse.Namespace) -> None: + """Provided a Jinja templated ray.io/v1alpha1 file, + populate the arguments and create the cluster. Additionally, create + kubernetes containers for resources separated by '---' from the rest + of the file. + + Args: + args: Possible arguments concerning cluster parameters. + """ + # Load Kubernetes configuration + config.load_kube_config() + + # Set up Jinja2 environment for loading templates + templates_dir = RAY_DIR / "cluster_configs" / args.cluster_host + file_loader = FileSystemLoader(str(templates_dir)) + jinja_env = Environment(loader=file_loader, keep_trailing_newline=True, autoescape=True) + + # Define template filename + template_file = "kuberay.yaml.jinja" + + # Convert args namespace to a dictionary + template_params = vars(args) + + # Load and render the template + template = jinja_env.get_template(template_file) + file_contents = template.render(template_params) + + # Parse all YAML documents in the rendered template + all_yamls = [] + for doc in yaml.safe_load_all(file_contents): + all_yamls.append(doc) + + # Convert back to YAML string, preserving multiple documents + cleaned_yaml_string = "" + for i, doc in enumerate(all_yamls): + if i > 0: + cleaned_yaml_string += "\n---\n" + cleaned_yaml_string += yaml.dump(doc) + + # Apply the Kubernetes manifest using kubectl + try: + print(cleaned_yaml_string) + subprocess.run(["kubectl", "apply", "-f", "-"], input=cleaned_yaml_string, text=True, check=True) + except subprocess.CalledProcessError as e: + exit(f"An error occurred while running `kubectl`: {e}") + + +def parse_args() -> argparse.Namespace: + """ + Parse command-line arguments for Kubernetes deployment script. + + Returns: + argparse.Namespace: Parsed command-line arguments. + """ + arg_parser = argparse.ArgumentParser( + description="Script to apply manifests to create Kubernetes objects for Ray clusters.", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + + arg_parser.add_argument( + "--cluster_host", + type=str, + default="google_cloud", + choices=["google_cloud"], + help=( + "In the cluster_configs directory, the name of the folder where a tune.yaml.jinja" + "file exists defining the KubeRay config. Currently only google_cloud is supported." + ), + ) + + arg_parser.add_argument( + "--name", + type=str, + required=False, + default="isaacray", + help="Name of the Kubernetes deployment.", + ) + + arg_parser.add_argument( + "--namespace", + type=str, + required=False, + default="default", + help="Kubernetes namespace to deploy the Ray cluster.", + ) + + arg_parser.add_argument( + "--service_acount_name", type=str, required=False, default="default", help="The service account name to use." + ) + + arg_parser.add_argument( + "--image", + type=str, + required=True, + help="Docker image for the Ray cluster pods.", + ) + + arg_parser.add_argument( + "--worker_accelerator", + nargs="+", + type=str, + default=["nvidia-l4"], + help="GPU accelerator name. Supply more than one for heterogeneous resources.", + ) + + arg_parser = util.add_resource_arguments(arg_parser, cluster_create_defaults=True) + + arg_parser.add_argument( + "--num_clusters", + type=int, + default=1, + help="How many Ray Clusters to create.", + ) + arg_parser.add_argument( + "--num_head_cpu", + type=float, # to be able to schedule partial CPU heads + default=8, + help="The number of CPUs to give the Ray head.", + ) + + arg_parser.add_argument("--head_ram_gb", type=int, default=8, help="How many gigs of ram to give the Ray head") + args = arg_parser.parse_args() + return util.fill_in_missing_resources(args, cluster_creation_flag=True) + + +def main(): + args = parse_args() + + if "head" in args.name: + raise ValueError("For compatibility with other scripts, do not include head in the name") + if args.num_clusters == 1: + apply_manifest(args) + else: + default_name = args.name + for i in range(args.num_clusters): + args.name = default_name + "-" + str(i) + apply_manifest(args) + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/mlflow_to_local_tensorboard.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/mlflow_to_local_tensorboard.py new file mode 100644 index 0000000000000000000000000000000000000000..2c45f1cd0a8d0c5251921c09f3b07cebe58e6e07 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/mlflow_to_local_tensorboard.py @@ -0,0 +1,150 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import argparse +import logging +import multiprocessing as mp +import os +import sys +from concurrent.futures import ProcessPoolExecutor, as_completed + +import mlflow +from mlflow.tracking import MlflowClient +from torch.utils.tensorboard import SummaryWriter + + +def setup_logging(level=logging.INFO): + logging.basicConfig(level=level, format="%(asctime)s - %(levelname)s - %(message)s") + + +def get_existing_runs(download_dir: str) -> set[str]: + """Get set of run IDs that have already been downloaded.""" + existing_runs = set() + tensorboard_dir = os.path.join(download_dir, "tensorboard") + if os.path.exists(tensorboard_dir): + for entry in os.listdir(tensorboard_dir): + if entry.startswith("run_"): + existing_runs.add(entry[4:]) + return existing_runs + + +def process_run(args): + """Convert MLflow run to TensorBoard format.""" + run_id, download_dir, tracking_uri = args + + try: + # Set up MLflow client + mlflow.set_tracking_uri(tracking_uri) + client = MlflowClient() + run = client.get_run(run_id) + + # Create TensorBoard writer + tensorboard_log_dir = os.path.join(download_dir, "tensorboard", f"run_{run_id}") + writer = SummaryWriter(log_dir=tensorboard_log_dir) + + # Log parameters + for key, value in run.data.params.items(): + writer.add_text(f"params/{key}", str(value)) + + # Log metrics with history + for key in run.data.metrics.keys(): + history = client.get_metric_history(run_id, key) + for m in history: + writer.add_scalar(f"metrics/{key}", m.value, m.step) + + # Log tags + for key, value in run.data.tags.items(): + writer.add_text(f"tags/{key}", str(value)) + + writer.close() + return run_id, True + except Exception: + return run_id, False + + +def download_experiment_tensorboard_logs(uri: str, experiment_name: str, download_dir: str) -> None: + """Download MLflow experiment logs and convert to TensorBoard format.""" + # import logger + logger = logging.getLogger(__name__) + + try: + # Set up MLflow + mlflow.set_tracking_uri(uri) + logger.info(f"Connected to MLflow tracking server at {uri}") + + # Get experiment + experiment = mlflow.get_experiment_by_name(experiment_name) + if experiment is None: + raise ValueError(f"Experiment '{experiment_name}' not found at URI '{uri}'.") + + # Get all runs + runs = mlflow.search_runs([experiment.experiment_id]) + logger.info(f"Found {len(runs)} total runs in experiment '{experiment_name}'") + + # Check existing runs + existing_runs = get_existing_runs(download_dir) + logger.info(f"Found {len(existing_runs)} existing runs in {download_dir}") + + # Create directory structure + os.makedirs(os.path.join(download_dir, "tensorboard"), exist_ok=True) + + # Process new runs + new_run_ids = [run.run_id for _, run in runs.iterrows() if run.run_id not in existing_runs] + + if not new_run_ids: + logger.info("No new runs to process") + return + + logger.info(f"Processing {len(new_run_ids)} new runs...") + + # Process runs in parallel + num_processes = min(mp.cpu_count(), len(new_run_ids)) + processed = 0 + + with ProcessPoolExecutor(max_workers=num_processes) as executor: + future_to_run = { + executor.submit(process_run, (run_id, download_dir, uri)): run_id for run_id in new_run_ids + } + + for future in as_completed(future_to_run): + run_id = future_to_run[future] + try: + run_id, success = future.result() + processed += 1 + if success: + logger.info(f"[{processed}/{len(new_run_ids)}] Successfully processed run {run_id}") + else: + logger.error(f"[{processed}/{len(new_run_ids)}] Failed to process run {run_id}") + except Exception as e: + logger.error(f"Error processing run {run_id}: {e}") + + logger.info(f"\nAll data saved to {download_dir}/tensorboard") + + except Exception as e: + logger.error(f"Error during download: {e}") + raise + + +def main(): + parser = argparse.ArgumentParser(description="Download MLflow experiment logs for TensorBoard visualization.") + parser.add_argument("--uri", required=True, help="The MLflow tracking URI (e.g., http://localhost:5000)") + parser.add_argument("--experiment-name", required=True, help="Name of the experiment to download") + parser.add_argument("--download-dir", required=True, help="Directory to save TensorBoard logs") + parser.add_argument("--debug", action="store_true", help="Enable debug logging") + + args = parser.parse_args() + setup_logging(level=logging.DEBUG if args.debug else logging.INFO) + + try: + download_experiment_tensorboard_logs(args.uri, args.experiment_name, args.download_dir) + print("\nSuccess! To view the logs, run:") + print(f"tensorboard --logdir {os.path.join(args.download_dir, 'tensorboard')}") + except Exception as e: + logging.error(f"Failed to download experiment logs: {e}") + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/submit_job.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/submit_job.py new file mode 100644 index 0000000000000000000000000000000000000000..21fb6a3d9b39299994b90ba27e5311c220be5e5d --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/submit_job.py @@ -0,0 +1,158 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script submits aggregate job(s) to cluster(s) described in a +config file containing ``name: address: http://:`` on +a new line for each cluster. For KubeRay clusters, this file +can be automatically created with :file:`grok_cluster_with_kubectl.py` + +Aggregate job(s) are matched with cluster(s) via the following relation: +cluster_line_index_submitted_to = job_index % total_cluster_count + +Aggregate jobs are separated by the * delimiter. The ``--aggregate_jobs`` argument must be +the last argument supplied to the script. + +An aggregate job could be a :file:`../tuner.py` tuning job, which automatically +creates several individual jobs when started on a cluster. Alternatively, an aggregate job +could be a :file:'../wrap_resources.py` resource-wrapped job, +which may contain several individual sub-jobs separated by +the + delimiter. An aggregate job could also be a :file:`../task_runner.py` multi-task submission job, +where each sub-job and its resource requirements are defined in a YAML configuration file. +In this mode, :file:`../task_runner.py` will read the YAML file (via --task_cfg), and +submit all defined sub-tasks to the Ray cluster, supporting per-job resource specification and +real-time streaming of sub-job outputs. + +If there are more aggregate jobs than cluster(s), aggregate jobs will be submitted +as clusters become available via the defined relation above. If there are less aggregate job(s) +than clusters, some clusters will not receive aggregate job(s). The maximum number of +aggregate jobs that can be run simultaneously is equal to the number of workers created by +default by a ThreadPoolExecutor on the machine submitting jobs due to fetching the log output after +jobs finish, which is unlikely to constrain overall-job submission. + +Usage: + +.. code-block:: bash + + # Example; submitting a tuning job + python3 scripts/reinforcement_learning/ray/submit_job.py \ + --aggregate_jobs /workspace/isaaclab/scripts/reinforcement_learning/ray/tuner.py \ + --cfg_file hyperparameter_tuning/vision_cartpole_cfg.py \ + --cfg_class CartpoleTheiaJobCfg --mlflow_uri + + # Example: Submitting resource wrapped job + python3 scripts/reinforcement_learning/ray/submit_job.py --aggregate_jobs wrap_resources.py --test + + # Example: submitting tasks with specific resources, and supporting pip packages and py_modules + # You may use relative paths for task_cfg and py_modules, placing them in the + # "scripts/reinforcement_learning/ray" directory, which will be uploaded to the cluster. + python3 scripts/reinforcement_learning/ray/submit_job.py --aggregate_jobs task_runner.py --task_cfg tasks.yaml + + # For all command line arguments + python3 scripts/reinforcement_learning/ray/submit_job.py -h +""" + +import argparse +import os +import time +from concurrent.futures import ThreadPoolExecutor + +from ray import job_submission + +script_directory = os.path.dirname(os.path.abspath(__file__)) +CONFIG = {"working_dir": script_directory, "executable": "/workspace/isaaclab/isaaclab.sh -p"} + + +def read_cluster_spec(fn: str | None = None) -> list[dict]: + if fn is None: + cluster_spec_path = os.path.expanduser("~/.cluster_config") + else: + cluster_spec_path = os.path.expanduser(fn) + + if not os.path.exists(cluster_spec_path): + raise FileNotFoundError(f"Cluster spec file not found at {cluster_spec_path}") + + clusters = [] + with open(cluster_spec_path) as f: + for line in f: + parts = line.strip().split(" ") + http_address = parts[3] + cluster_info = {"name": parts[1], "address": http_address} + print(f"[INFO] Setting {cluster_info['name']}") # with {cluster_info['num_gpu']} GPUs.") + clusters.append(cluster_info) + + return clusters + + +def submit_job(cluster: dict, job_command: str) -> None: + """ + Submits a job to a single cluster, prints the final result and Ray dashboard URL at the end. + """ + address = cluster["address"] + cluster_name = cluster["name"] + print(f"[INFO]: Submitting job to cluster '{cluster_name}' at {address}") # with {num_gpus} GPUs.") + client = job_submission.JobSubmissionClient(address) + runtime_env = {"working_dir": CONFIG["working_dir"], "executable": CONFIG["executable"]} + print(f"[INFO]: Checking contents of the directory: {CONFIG['working_dir']}") + try: + dir_contents = os.listdir(CONFIG["working_dir"]) + print(f"[INFO]: Directory contents: {dir_contents}") + except Exception as e: + print(f"[INFO]: Failed to list directory contents: {str(e)}") + entrypoint = f"{CONFIG['executable']} {job_command}" + print(f"[INFO]: Attempting entrypoint {entrypoint=} in cluster {cluster}") + job_id = client.submit_job(entrypoint=entrypoint, runtime_env=runtime_env) + status = client.get_job_status(job_id) + while status in [job_submission.JobStatus.PENDING, job_submission.JobStatus.RUNNING]: + time.sleep(5) + status = client.get_job_status(job_id) + + final_logs = client.get_job_logs(job_id) + print("----------------------------------------------------") + print(f"[INFO]: Cluster {cluster_name} Logs: \n") + print(final_logs) + print("----------------------------------------------------") + + +def submit_jobs_to_clusters(jobs: list[str], clusters: list[dict]) -> None: + """ + Submit all jobs to their respective clusters, cycling through clusters if there are more jobs than clusters. + """ + if not clusters: + raise ValueError("No clusters available for job submission.") + + if len(jobs) < len(clusters): + print("[INFO]: Less jobs than clusters, some clusters will not receive jobs") + elif len(jobs) == len(clusters): + print("[INFO]: Exactly one job per cluster") + else: + print("[INFO]: More jobs than clusters, jobs submitted as clusters become available.") + with ThreadPoolExecutor() as executor: + for idx, job_command in enumerate(jobs): + # Cycle through clusters using modulus to wrap around if there are more jobs than clusters + cluster = clusters[idx % len(clusters)] + executor.submit(submit_job, cluster, job_command) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Submit multiple GPU jobs to multiple Ray clusters.") + parser.add_argument("--config_file", default="~/.cluster_config", help="The cluster config path.") + parser.add_argument( + "--aggregate_jobs", + type=str, + nargs=argparse.REMAINDER, + help="This should be last argument. The aggregate jobs to submit separated by the * delimiter.", + ) + args = parser.parse_args() + if args.aggregate_jobs is not None: + jobs = " ".join(args.aggregate_jobs) + formatted_jobs = jobs.split("*") + if len(formatted_jobs) > 1: + print("Warning; Split jobs by cluster with the * delimiter") + else: + formatted_jobs = [] + print(f"[INFO]: Isaac Ray Wrapper received jobs {formatted_jobs=}") + clusters = read_cluster_spec(args.config_file) + submit_jobs_to_clusters(formatted_jobs, clusters) diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/task_runner.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/task_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..7bb3596fc91862a4b62176a2be736a4d2a2b3c0c --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/task_runner.py @@ -0,0 +1,298 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script dispatches one or more user-defined Python tasks to workers in a Ray cluster. +Each task, along with its resource requirements and execution parameters, is specified in a YAML configuration file. +Users may define the number of CPUs, GPUs, and the amount of memory to allocate per task via the config file. + +Key features: +------------- +- Fine-grained, per-task resource management via config fields (`num_gpus`, `num_cpus`, `memory`). +- Parallel execution of multiple tasks using available resources across the Ray cluster. +- Option to specify node affinity for tasks, e.g., by hostname, node ID, or any node. +- Optional batch (simultaneous) or independent scheduling of tasks. + +Task scheduling and distribution are handled via Ray’s built-in resource manager. + +YAML configuration fields: +-------------------------- +- `pip`: List of extra pip packages to install before running any tasks. +- `py_modules`: List of additional Python module paths (directories or files) to include in the runtime environment. +- `concurrent`: (bool) It determines task dispatch semantics: + - If `concurrent: true`, **all tasks are scheduled as a batch**. The script waits until + sufficient resources are available for every task in the batch, then launches all tasks + together. If resources are insufficient, all tasks remain blocked until the cluster can + support the full batch. + - If `concurrent: false`, tasks are launched as soon as resources are available for each + individual task, and Ray independently schedules them. This may result in non-simultaneous + task start times. +- `tasks`: List of task specifications, each with: + - `name`: String identifier for the task. + - `py_args`: Arguments to the Python interpreter (e.g., script/module, flags, user arguments). + - `num_gpus`: Number of GPUs to allocate (float or string arithmetic, e.g., "2*2"). + - `num_cpus`: Number of CPUs to allocate (float or string). + - `memory`: Amount of RAM in bytes (int or string). + - `node` (optional): Node placement constraints. + - `specific` (str): Type of node placement, support `hostname`, `node_id`, or `any`. + - `any`: Place the task on any available node. + - `hostname`: Place the task on a specific hostname. `hostname` must be specified + in the node field. + - `node_id`: Place the task on a specific node ID. `node_id` must be specified in + the node field. + - `hostname` (str): Specific hostname to place the task on. + - `node_id` (str): Specific node ID to place the task on. + + +Typical usage: +-------------- + +.. code-block:: bash + + # Print help and argument details: + python task_runner.py -h + + # Submit tasks defined in a YAML file to the Ray cluster (auto-detects Ray head address): + python task_runner.py --task_cfg /path/to/tasks.yaml + +YAML configuration example-1: +----------------------------- + +.. code-block:: yaml + + pip: ["xxx"] + py_modules: ["my_package/my_package"] + concurrent: false + tasks: + - name: "Isaac-Cartpole-v0" + py_args: "-m torch.distributed.run --nnodes=1 --nproc_per_node=2 --rdzv_endpoint=localhost:29501 /workspace/isaaclab/scripts/reinforcement_learning/rsl_rl/train.py --task=Isaac-Cartpole-v0 --max_iterations 200 --headless --distributed" + num_gpus: 2 + num_cpus: 10 + memory: 10737418240 + - name: "script need some dependencies" + py_args: "script.py --option arg" + num_gpus: 0 + num_cpus: 1 + memory: 10*1024*1024*1024 + +YAML configuration example-2: +----------------------------- + +.. code-block:: yaml + + pip: ["xxx"] + py_modules: ["my_package/my_package"] + concurrent: true + tasks: + - name: "Isaac-Cartpole-v0-multi-node-train-1" + py_args: "-m torch.distributed.run --nproc_per_node=1 --nnodes=2 --node_rank=0 --rdzv_id=123 --rdzv_backend=c10d --rdzv_endpoint=localhost:5555 /workspace/isaaclab/scripts/reinforcement_learning/rsl_rl/train.py --task=Isaac-Cartpole-v0 --headless --distributed --max_iterations 1000" + num_gpus: 1 + num_cpus: 10 + memory: 10*1024*1024*1024 + node: + specific: "hostname" + hostname: "xxx" + - name: "Isaac-Cartpole-v0-multi-node-train-2" + py_args: "-m torch.distributed.run --nproc_per_node=1 --nnodes=2 --node_rank=1 --rdzv_id=123 --rdzv_backend=c10d --rdzv_endpoint=x.x.x.x:5555 /workspace/isaaclab/scripts/reinforcement_learning/rsl_rl/train.py --task=Isaac-Cartpole-v0 --headless --distributed --max_iterations 1000" + num_gpus: 1 + num_cpus: 10 + memory: 10*1024*1024*1024 + node: + specific: "hostname" + hostname: "xxx" + +To stop all tasks early, press Ctrl+C; the script will cancel all running Ray tasks. +""" # noqa: E501 + +import argparse +import ast +import operator +from datetime import datetime + +import yaml + +# Local imports +import util # isort: skip + +# Safe operators for arithmetic expression evaluation +_SAFE_OPERATORS = { + ast.Add: operator.add, + ast.Sub: operator.sub, + ast.Mult: operator.mul, + ast.Div: operator.truediv, + ast.FloorDiv: operator.floordiv, + ast.Pow: operator.pow, + ast.Mod: operator.mod, + ast.USub: operator.neg, + ast.UAdd: operator.pos, +} + + +def safe_eval_arithmetic(expr: str) -> int | float: + """ + Safely evaluate a string containing only arithmetic expressions. + + Supports: +, -, *, /, //, **, % and numeric literals. + Raises ValueError for any non-arithmetic expressions. + + Args: + expr: A string containing an arithmetic expression (e.g., "10*1024*1024"). + + Returns: + The numeric result of the expression. + + Raises: + ValueError: If the expression contains non-arithmetic operations. + """ + + def _eval_node(node: ast.AST) -> int | float: + if isinstance(node, ast.Expression): + return _eval_node(node.body) + elif isinstance(node, ast.Constant) and isinstance(node.value, (int, float)): + return node.value + elif isinstance(node, ast.BinOp) and type(node.op) in _SAFE_OPERATORS: + left = _eval_node(node.left) + right = _eval_node(node.right) + return _SAFE_OPERATORS[type(node.op)](left, right) + elif isinstance(node, ast.UnaryOp) and type(node.op) in _SAFE_OPERATORS: + operand = _eval_node(node.operand) + return _SAFE_OPERATORS[type(node.op)](operand) + else: + raise ValueError(f"Unsafe expression: {ast.dump(node)}") + + try: + tree = ast.parse(expr.strip(), mode="eval") + return _eval_node(tree) + except (SyntaxError, TypeError) as e: + raise ValueError(f"Invalid arithmetic expression: {expr}") from e + + +def parse_args() -> argparse.Namespace: + """ + Parse command-line arguments for the Ray task runner. + + Returns: + A namespace containing parsed CLI arguments: + - task_cfg (str): Path to the YAML task file. + - ray_address (str): Ray cluster address. + - test (bool): Whether to run a GPU resource isolation sanity check. + """ + parser = argparse.ArgumentParser(description="Run tasks from a YAML config file.") + parser.add_argument("--task_cfg", type=str, required=True, help="Path to the YAML task file.") + parser.add_argument("--ray_address", type=str, default="auto", help="the Ray address.") + parser.add_argument( + "--test", + action="store_true", + help=( + "Run nvidia-smi test instead of the arbitrary job," + "can use as a sanity check prior to any jobs to check " + "that GPU resources are correctly isolated." + ), + ) + return parser.parse_args() + + +def parse_task_resource(task: dict) -> util.JobResource: + """ + Parse task resource requirements from the YAML configuration. + + Args: + task (dict): Dictionary representing a single task's configuration. + Keys may include `num_gpus`, `num_cpus`, and `memory`, each either + as a number or evaluatable string expression. + + Returns: + util.JobResource: Resource object with the parsed values. + """ + resource = util.JobResource() + if "num_gpus" in task: + value = task["num_gpus"] + resource.num_gpus = safe_eval_arithmetic(value) if isinstance(value, str) else value + if "num_cpus" in task: + value = task["num_cpus"] + resource.num_cpus = safe_eval_arithmetic(value) if isinstance(value, str) else value + if "memory" in task: + value = task["memory"] + resource.memory = safe_eval_arithmetic(value) if isinstance(value, str) else value + return resource + + +def run_tasks( + tasks: list[dict], args: argparse.Namespace, runtime_env: dict | None = None, concurrent: bool = False +) -> None: + """ + Submit tasks to the Ray cluster for execution. + + Args: + tasks (list[dict]): A list of task configuration dictionaries. + args (argparse.Namespace): Parsed command-line arguments. + runtime_env (dict | None): Ray runtime environment configuration containing: + - pip (list[str] | None): Additional pip packages to install. + - py_modules (list[str] | None): Python modules to include in the environment. + concurrent (bool): Whether to launch tasks simultaneously as a batch, + or independently as resources become available. + + Returns: + None + """ + job_objs = [] + util.ray_init(ray_address=args.ray_address, runtime_env=runtime_env, log_to_driver=False) + for task in tasks: + resource = parse_task_resource(task) + print(f"[INFO] Creating job {task['name']} with resource={resource}") + job = util.Job( + name=task["name"], + py_args=task["py_args"], + resources=resource, + node=util.JobNode( + specific=task.get("node", {}).get("specific"), + hostname=task.get("node", {}).get("hostname"), + node_id=task.get("node", {}).get("node_id"), + ), + ) + job_objs.append(job) + start = datetime.now() + print(f"[INFO] Creating {len(job_objs)} jobs at {start.strftime('%H:%M:%S.%f')} with runtime env={runtime_env}") + # submit jobs + util.submit_wrapped_jobs( + jobs=job_objs, + test_mode=args.test, + concurrent=concurrent, + ) + end = datetime.now() + print( + f"[INFO] All jobs completed at {end.strftime('%H:%M:%S.%f')}, took {(end - start).total_seconds():.2f} seconds." + ) + + +def main() -> None: + """ + Main entry point for the Ray task runner script. + + Reads the YAML task configuration file, parses CLI arguments, + and dispatches tasks to the Ray cluster. + + Returns: + None + """ + args = parse_args() + with open(args.task_cfg) as f: + config = yaml.safe_load(f) + tasks = config["tasks"] + runtime_env = { + "pip": None if not config.get("pip") else config["pip"], + "py_modules": None if not config.get("py_modules") else config["py_modules"], + } + concurrent = config.get("concurrent", False) + run_tasks( + tasks=tasks, + args=args, + runtime_env=runtime_env, + concurrent=concurrent, + ) + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/tuner.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/tuner.py new file mode 100644 index 0000000000000000000000000000000000000000..99dc7e8d08f54af8063d1d410ca6718b93998836 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/tuner.py @@ -0,0 +1,556 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause +import argparse +import importlib.util +import os +import random +import subprocess +import sys +from time import sleep, time + +import ray +import util +from ray import air, tune +from ray.tune import Callback +from ray.tune.progress_reporter import ProgressReporter +from ray.tune.search.optuna import OptunaSearch +from ray.tune.search.repeater import Repeater +from ray.tune.stopper import CombinedStopper + +""" +This script breaks down an aggregate tuning job, as defined by a hyperparameter sweep configuration, +into individual jobs (shell commands) to run on the GPU-enabled nodes of the cluster. +By default, one worker is created for each GPU-enabled node in the cluster for each individual job. +To use more than one worker per node (likely the case for multi-GPU machines), supply the +num_workers_per_node argument. + +Each hyperparameter sweep configuration should include the workflow, +runner arguments, and hydra arguments to vary. + +This assumes that all workers in a cluster are homogeneous. For heterogeneous workloads, +create several heterogeneous clusters (with homogeneous nodes in each cluster), +then submit several overall-cluster jobs with :file:`../submit_job.py`. +KubeRay clusters on Google GKE can be created with :file:`../launch.py` + +To report tune metrics on clusters, a running MLFlow server with a known URI that the cluster has +access to is required. For KubeRay clusters configured with :file:`../launch.py`, this is included +automatically, and can be easily found with with :file:`grok_cluster_with_kubectl.py` + +Usage: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/ray/tuner.py -h + + # Examples + # Local + ./isaaclab.sh -p scripts/reinforcement_learning/ray/tuner.py --run_mode local \ + --cfg_file scripts/reinforcement_learning/ray/hyperparameter_tuning/vision_cartpole_cfg.py \ + --cfg_class CartpoleTheiaJobCfg + # Local with a custom progress reporter + ./isaaclab.sh -p scripts/reinforcement_learning/ray/tuner.py \ + --cfg_file scripts/reinforcement_learning/ray/hyperparameter_tuning/vision_cartpole_cfg.py \ + --cfg_class CartpoleTheiaJobCfg \ + --progress_reporter CustomCartpoleProgressReporter + # Remote (run grok cluster or create config file mentioned in :file:`submit_job.py`) + ./isaaclab.sh -p scripts/reinforcement_learning/ray/submit_job.py \ + --aggregate_jobs tuner.py \ + --cfg_file hyperparameter_tuning/vision_cartpole_cfg.py \ + --cfg_class CartpoleTheiaJobCfg --mlflow_uri + +""" + +DOCKER_PREFIX = "/workspace/isaaclab/" +BASE_DIR = os.path.expanduser("~") +PYTHON_EXEC = "./isaaclab.sh -p" +WORKFLOW = "scripts/reinforcement_learning/rl_games/train.py" +NUM_WORKERS_PER_NODE = 1 # needed for local parallelism +PROCESS_RESPONSE_TIMEOUT = 200.0 # seconds to wait before killing the process when it stops responding +MAX_LINES_TO_SEARCH_EXPERIMENT_LOGS = 1000 # maximum number of lines to read from the training process logs +MAX_LOG_EXTRACTION_ERRORS = 10 # maximum allowed LogExtractionErrors before we abort the whole training + + +class IsaacLabTuneTrainable(tune.Trainable): + """The Isaac Lab Ray Tune Trainable. + This class uses the standalone workflows to start jobs, along with the hydra integration. + This class achieves Ray-based logging through reading the tensorboard logs from + the standalone workflows. This depends on a config generated in the format of + :class:`JobCfg` + """ + + def setup(self, config: dict) -> None: + """Get the invocation command, return quick for easy scheduling.""" + self.data = None + self.time_since_last_proc_response = 0.0 + self.invoke_cmd = util.get_invocation_command_from_cfg(cfg=config, python_cmd=PYTHON_EXEC, workflow=WORKFLOW) + print(f"[INFO]: Recovered invocation with {self.invoke_cmd}") + self.experiment = None + + def reset_config(self, new_config: dict): + """Allow environments to be reused by fetching a new invocation command""" + self.setup(new_config) + return True + + def step(self) -> dict: + if self.experiment is None: # start experiment + # When including this as first step instead of setup, experiments get scheduled faster + # Don't want to block the scheduler while the experiment spins up + print(f"[INFO]: Invoking experiment as first step with {self.invoke_cmd}...") + try: + experiment = util.execute_job( + self.invoke_cmd, + identifier_string="", + extract_experiment=True, # Keep this as True to return a valid dictionary + persistent_dir=BASE_DIR, + max_lines_to_search_logs=MAX_LINES_TO_SEARCH_EXPERIMENT_LOGS, + max_time_to_search_logs=PROCESS_RESPONSE_TIMEOUT, + ) + except util.LogExtractionError: + self.data = { + "LOG_EXTRACTION_ERROR_STOPPER_FLAG": True, + "done": True, + } + return self.data + self.experiment = experiment + print(f"[INFO]: Tuner recovered experiment info {experiment}") + self.proc = experiment["proc"] + self.experiment_name = experiment["experiment_name"] + self.isaac_logdir = experiment["logdir"] + self.tensorboard_logdir = self.isaac_logdir + "/" + self.experiment_name + self.done = False + + if self.proc is None: + raise ValueError("Could not start trial.") + proc_status = self.proc.poll() + if proc_status is not None: # process finished, signal finish + self.data["done"] = True + print(f"[INFO]: Process finished with {proc_status}, returning...") + else: # wait until the logs are ready or fresh + data = util.load_tensorboard_logs(self.tensorboard_logdir) + + while data is None: + data = util.load_tensorboard_logs(self.tensorboard_logdir) + proc_status = self.proc.poll() + if proc_status is not None: + break + sleep(2) # Lazy report metrics to avoid performance overhead + + if self.data is not None: + data_ = {k: v for k, v in data.items() if k != "done"} + self_data_ = {k: v for k, v in self.data.items() if k != "done"} + unresponsiveness_start_time = time() + while util._dicts_equal(data_, self_data_): + self.time_since_last_proc_response = time() - unresponsiveness_start_time + data = util.load_tensorboard_logs(self.tensorboard_logdir) + data_ = {k: v for k, v in data.items() if k != "done"} + proc_status = self.proc.poll() + if proc_status is not None: + break + if self.time_since_last_proc_response > PROCESS_RESPONSE_TIMEOUT: + self.time_since_last_proc_response = 0.0 + print("[WARNING]: Training workflow process is not responding, terminating...") + self.proc.terminate() + try: + self.proc.wait(timeout=20) + except subprocess.TimeoutExpired: + print("[ERROR]: The process did not terminate within timeout duration.") + self.proc.kill() + self.proc.wait() + self.data = data + self.data["done"] = True + return self.data + sleep(2) # Lazy report metrics to avoid performance overhead + + self.data = data + self.data["done"] = False + return self.data + + def default_resource_request(self): + """How many resources each trainable uses. Assumes homogeneous resources across gpu nodes, + and that each trainable is meant for one node, where it uses all available resources.""" + resources = util.get_gpu_node_resources(one_node_only=True) + if NUM_WORKERS_PER_NODE != 1: + print("[WARNING]: Splitting node into more than one worker") + return tune.PlacementGroupFactory( + [{"CPU": resources["CPU"] / NUM_WORKERS_PER_NODE, "GPU": resources["GPU"] / NUM_WORKERS_PER_NODE}], + strategy="STRICT_PACK", + ) + + +class LogExtractionErrorStopper(tune.Stopper): + """Stopper that stops all trials if multiple LogExtractionErrors occur. + + Args: + max_errors: The maximum number of LogExtractionErrors allowed before terminating the experiment. + """ + + def __init__(self, max_errors: int): + self.max_errors = max_errors + self.error_count = 0 + + def __call__(self, trial_id, result): + """Increments the error count if trial has encountered a LogExtractionError. + + It does not stop the trial based on the metrics, always returning False. + """ + if result.get("LOG_EXTRACTION_ERROR_STOPPER_FLAG", False): + self.error_count += 1 + print( + f"[ERROR]: Encountered LogExtractionError {self.error_count} times. " + f"Maximum allowed is {self.max_errors}." + ) + return False + + def stop_all(self): + """Returns true if number of LogExtractionErrors exceeds the maximum allowed, terminating the experiment.""" + if self.error_count > self.max_errors: + print("[FATAL]: Encountered LogExtractionError more than allowed, aborting entire tuning run... ") + return True + else: + return False + + +class ProcessCleanupCallback(Callback): + """Callback to clean up processes when trials are stopped.""" + + def on_trial_error(self, iteration, trials, trial, error, **info): + """Called when a trial encounters an error.""" + self._cleanup_trial(trial) + + def on_trial_complete(self, iteration, trials, trial, **info): + """Called when a trial completes.""" + self._cleanup_trial(trial) + + def _cleanup_trial(self, trial): + """Clean up processes for a trial using SIGKILL.""" + try: + subprocess.run(["pkill", "-9", "-f", f"rid {trial.config['runner_args']['-rid']}"], check=False) + sleep(5) + except Exception as e: + print(f"[ERROR]: Failed to cleanup trial {trial.trial_id}: {e}") + + +def invoke_tuning_run( + cfg: dict, + args: argparse.Namespace, + progress_reporter: ProgressReporter | None = None, + stopper: tune.Stopper | None = None, +) -> None: + """Invoke an Isaac-Ray tuning run. + + Log either to a local directory or to MLFlow. + Args: + cfg: Configuration dictionary extracted from job setup + args: Command-line arguments related to tuning. + progress_reporter: Custom progress reporter. Defaults to CLIReporter or JupyterNotebookReporter if not provided. + stopper: Custom stopper, optional. + """ + # Allow for early exit + os.environ["TUNE_DISABLE_STRICT_METRIC_CHECKING"] = "1" + + print("[WARNING]: Not saving checkpoints, just running experiment...") + print("[INFO]: Model parameters and metrics will be preserved.") + print("[WARNING]: For homogeneous cluster resources only...") + + # Initialize Ray + util.ray_init( + ray_address=args.ray_address, + log_to_driver=True, + ) + + # Get available resources + resources = util.get_gpu_node_resources() + print(f"[INFO]: Available resources {resources}") + + print(f"[INFO]: Using config {cfg}") + + # Configure the search algorithm and the repeater + searcher = OptunaSearch( + metric=args.metric, + mode=args.mode, + ) + repeat_search = Repeater(searcher, repeat=args.repeat_run_count) + + # Configure the stoppers + stoppers: CombinedStopper = CombinedStopper( + *[ + LogExtractionErrorStopper(max_errors=MAX_LOG_EXTRACTION_ERRORS), + *([stopper] if stopper is not None else []), + ] + ) + + if progress_reporter is not None: + os.environ["RAY_AIR_NEW_OUTPUT"] = "0" + if ( + getattr(progress_reporter, "_metric", None) is not None + or getattr(progress_reporter, "_mode", None) is not None + ): + raise ValueError( + "Do not set or directly in the custom progress reporter class, " + "provide them as arguments to tuner.py instead." + ) + + if args.run_mode == "local": # Standard config, to file + run_config = air.RunConfig( + storage_path="/tmp/ray", + name=f"IsaacRay-{args.cfg_class}-tune", + callbacks=[ProcessCleanupCallback()], + verbose=1, + checkpoint_config=air.CheckpointConfig( + checkpoint_frequency=0, # Disable periodic checkpointing + checkpoint_at_end=False, # Disable final checkpoint + ), + stop=stoppers, + progress_reporter=progress_reporter, + ) + + elif args.run_mode == "remote": # MLFlow, to MLFlow server + mlflow_callback = MLflowLoggerCallback( + tracking_uri=args.mlflow_uri, + experiment_name=f"IsaacRay-{args.cfg_class}-tune", + save_artifact=False, + tags={"run_mode": "remote", "cfg_class": args.cfg_class}, + ) + + run_config = ray.train.RunConfig( + name="mlflow", + storage_path="/tmp/ray", + callbacks=[ProcessCleanupCallback(), mlflow_callback], + checkpoint_config=ray.train.CheckpointConfig(checkpoint_frequency=0, checkpoint_at_end=False), + stop=stoppers, + progress_reporter=progress_reporter, + ) + else: + raise ValueError("Unrecognized run mode.") + # RID isn't optimized as it is sampled from, but useful for cleanup later + cfg["runner_args"]["-rid"] = tune.sample_from(lambda _: str(random.randint(int(1e9), int(1e10) - 1))) + # Configure the tuning job + tuner = tune.Tuner( + IsaacLabTuneTrainable, + param_space=cfg, + tune_config=tune.TuneConfig( + metric=args.metric, + mode=args.mode, + search_alg=repeat_search, + num_samples=args.num_samples, + reuse_actors=True, + ), + run_config=run_config, + ) + + # Execute the tuning + tuner.fit() + + # Save results to mounted volume + if args.run_mode == "local": + print("[DONE!]: Check results with tensorboard dashboard") + else: + print("[DONE!]: Check results with MLFlow dashboard") + + +class JobCfg: + """To be compatible with :meth: invoke_tuning_run and :class:IsaacLabTuneTrainable, + at a minimum, the tune job should inherit from this class.""" + + def __init__(self, cfg: dict): + """ + Runner args include command line arguments passed to the task. + For example: + cfg["runner_args"]["headless_singleton"] = "--headless" + cfg["runner_args"]["enable_cameras_singleton"] = "--enable_cameras" + """ + assert "runner_args" in cfg, "No runner arguments specified." + """ + Task is the desired task to train on. For example: + cfg["runner_args"]["--task"] = tune.choice(["Isaac-Cartpole-RGB-TheiaTiny-v0"]) + """ + assert "--task" in cfg["runner_args"], "No task specified." + """ + Hydra args define the hyperparameters varied within the sweep. For example: + cfg["hydra_args"]["agent.params.network.cnn.activation"] = tune.choice(["relu", "elu"]) + """ + assert "hydra_args" in cfg, "No hyperparameters specified." + self.cfg = cfg + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Tune Isaac Lab hyperparameters.") + parser.add_argument("--ray_address", type=str, default="auto", help="the Ray address.") + parser.add_argument( + "--cfg_file", + type=str, + default="hyperparameter_tuning/vision_cartpole_cfg.py", + required=False, + help="The relative filepath where a hyperparameter sweep is defined", + ) + parser.add_argument( + "--cfg_class", + type=str, + default="CartpoleRGBNoTuneJobCfg", + required=False, + help="Name of the hyperparameter sweep class to use", + ) + parser.add_argument( + "--run_mode", + choices=["local", "remote"], + default="remote", + help=( + "Set to local to use ./isaaclab.sh -p python, set to " + "remote to use /workspace/isaaclab/isaaclab.sh -p python" + ), + ) + parser.add_argument( + "--workflow", + default=None, # populated with RL Games + help="The absolute path of the workflow to use for the experiment. By default, RL Games is used.", + ) + parser.add_argument( + "--mlflow_uri", + type=str, + default=None, + required=False, + help="The MLFlow Uri.", + ) + parser.add_argument( + "--num_workers_per_node", + type=int, + default=1, + help="Number of workers to run on each GPU node. Only supply for parallelism on multi-gpu nodes", + ) + + parser.add_argument("--metric", type=str, default="rewards/time", help="What metric to tune for.") + + parser.add_argument( + "--mode", + choices=["max", "min"], + default="max", + help="What to optimize the metric to while tuning", + ) + parser.add_argument( + "--num_samples", + type=int, + default=100, + help="How many hyperparameter runs to try total.", + ) + parser.add_argument( + "--repeat_run_count", + type=int, + default=3, + help="How many times to repeat each hyperparameter config.", + ) + parser.add_argument( + "--process_response_timeout", + type=float, + default=PROCESS_RESPONSE_TIMEOUT, + help="Training workflow process response timeout.", + ) + parser.add_argument( + "--max_lines_to_search_experiment_logs", + type=float, + default=MAX_LINES_TO_SEARCH_EXPERIMENT_LOGS, + help="Max number of lines to search for experiment logs before terminating the training workflow process.", + ) + parser.add_argument( + "--max_log_extraction_errors", + type=float, + default=MAX_LOG_EXTRACTION_ERRORS, + help="Max number number of LogExtractionError failures before we abort the whole tuning run.", + ) + parser.add_argument( + "--progress_reporter", + type=str, + default=None, + help=( + "Optional: name of a custom reporter class defined in the cfg_file. " + "Must subclass ray.tune.ProgressReporter " + "(e.g., CustomCartpoleProgressReporter)." + ), + ) + parser.add_argument( + "--stopper", + type=str, + default=None, + help="A stop criteria in the cfg_file, must be a tune.Stopper instance.", + ) + + args = parser.parse_args() + PROCESS_RESPONSE_TIMEOUT = args.process_response_timeout + MAX_LINES_TO_SEARCH_EXPERIMENT_LOGS = int(args.max_lines_to_search_experiment_logs) + print( + "[INFO]: The max number of lines to search for experiment logs before (early) terminating the training " + f"workflow process is set to {MAX_LINES_TO_SEARCH_EXPERIMENT_LOGS}.\n" + "[INFO]: The process response timeout, used while updating tensorboard scalars and searching for " + f"experiment logs, is set to {PROCESS_RESPONSE_TIMEOUT} seconds." + ) + MAX_LOG_EXTRACTION_ERRORS = int(args.max_log_extraction_errors) + print( + "[INFO]: Max number of LogExtractionError failures before we abort the whole tuning run is " + f"set to {MAX_LOG_EXTRACTION_ERRORS}.\n" + ) + NUM_WORKERS_PER_NODE = args.num_workers_per_node + print(f"[INFO]: Using {NUM_WORKERS_PER_NODE} workers per node.") + if args.run_mode == "remote": + BASE_DIR = DOCKER_PREFIX # ensure logs are dumped to persistent location + PYTHON_EXEC = DOCKER_PREFIX + PYTHON_EXEC[2:] + if args.workflow is None: + WORKFLOW = DOCKER_PREFIX + WORKFLOW + else: + WORKFLOW = args.workflow + print(f"[INFO]: Using remote mode {PYTHON_EXEC=} {WORKFLOW=}") + + if args.mlflow_uri is not None: + import mlflow + + mlflow.set_tracking_uri(args.mlflow_uri) + from ray.air.integrations.mlflow import MLflowLoggerCallback + else: + raise ValueError("Please provide a result MLFLow URI server.") + else: # local + PYTHON_EXEC = os.getcwd() + "/" + PYTHON_EXEC[2:] + if args.workflow is None: + WORKFLOW = os.getcwd() + "/" + WORKFLOW + else: + WORKFLOW = args.workflow + BASE_DIR = os.getcwd() + print(f"[INFO]: Using local mode {PYTHON_EXEC=} {WORKFLOW=}") + file_path = args.cfg_file + class_name = args.cfg_class + print(f"[INFO]: Attempting to use sweep config from {file_path=} {class_name=}") + module_name = os.path.splitext(os.path.basename(file_path))[0] + + spec = importlib.util.spec_from_file_location(module_name, file_path) + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + spec.loader.exec_module(module) + print(f"[INFO]: Successfully imported {module_name} from {file_path}") + if hasattr(module, class_name): + ClassToInstantiate = getattr(module, class_name) + print(f"[INFO]: Found correct class {ClassToInstantiate}") + instance = ClassToInstantiate() + print(f"[INFO]: Successfully instantiated class '{class_name}' from {file_path}") + cfg = instance.cfg + print(f"[INFO]: Grabbed the following hyperparameter sweep config: \n {cfg}") + # Load optional stopper config + stopper = None + if args.stopper and hasattr(module, args.stopper): + stopper = getattr(module, args.stopper) + if isinstance(stopper, type) and issubclass(stopper, tune.Stopper): + stopper = stopper() + else: + raise TypeError(f"[ERROR]: Unsupported stop criteria type: {type(stopper)}") + print(f"[INFO]: Loaded custom stop criteria from '{args.stopper}'") + # Load optional progress reporter config + progress_reporter = None + if args.progress_reporter and hasattr(module, args.progress_reporter): + progress_reporter = getattr(module, args.progress_reporter) + if isinstance(progress_reporter, type) and issubclass(progress_reporter, tune.ProgressReporter): + progress_reporter = progress_reporter() + else: + raise TypeError(f"[ERROR]: {args.progress_reporter} is not a valid ProgressReporter.") + print(f"[INFO]: Loaded custom progress reporter from '{args.progress_reporter}'") + invoke_tuning_run(cfg, args, progress_reporter=progress_reporter, stopper=stopper) + + else: + raise AttributeError(f"[ERROR]:Class '{class_name}' not found in {file_path}") diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/util.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/util.py new file mode 100644 index 0000000000000000000000000000000000000000..a73ebdf493dc8edd5ef8cd116365e0ab89a68a99 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/util.py @@ -0,0 +1,720 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause +import argparse +import os +import re +import select +import subprocess +import sys +import threading +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import datetime +from math import isclose +from time import time +from typing import Any + +import ray +from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy +from tensorboard.backend.event_processing.directory_watcher import DirectoryDeletedError +from tensorboard.backend.event_processing.event_accumulator import EventAccumulator + + +def load_tensorboard_logs(directory: str) -> dict: + """From a tensorboard directory, get the latest scalar values. If the logs can't be + found, check the summaries sublevel. + + Args: + directory: The directory of the tensorboard logging. + + Returns: + The latest available scalar values. + """ + + # replace any non-alnum/underscore/dot with "_", then collapse runs of "_" + def replace_invalid_chars(t): + t2 = re.sub(r"[^0-9A-Za-z_./]", "_", t) + t2 = re.sub(r"_+", "_", t2) + return t2.strip("_") + + # Initialize the event accumulator with a size guidance for only the latest entry + def get_latest_scalars(path: str) -> dict: + event_acc = EventAccumulator(path, size_guidance={"scalars": 1}) + try: + event_acc.Reload() + if event_acc.Tags()["scalars"]: + return { + replace_invalid_chars(tag): event_acc.Scalars(tag)[-1].value + for tag in event_acc.Tags()["scalars"] + if event_acc.Scalars(tag) + } + except (KeyError, OSError, RuntimeError, DirectoryDeletedError): + return {} + + scalars = get_latest_scalars(directory) + return scalars or get_latest_scalars(os.path.join(directory, "summaries")) + + +def get_invocation_command_from_cfg( + cfg: dict, + python_cmd: str = "/workspace/isaaclab/isaaclab.sh -p", + workflow: str = "scripts/reinforcement_learning/rl_games/train.py", +) -> str: + """Generate command with proper Hydra arguments""" + runner_args = [] + hydra_args = [] + + def process_args(args, target_list, is_hydra=False): + for key, value in args.items(): + if not is_hydra: + if key.endswith("_singleton"): + target_list.append(value) + elif key.startswith("--") or key.startswith("-"): + target_list.append(f"{key} {value}") # Space instead of = for runner args + else: + target_list.append(f"{value}") + else: + if isinstance(value, list): + # Check the type of the first item to determine formatting + if value and isinstance(value[0], dict): + # Handle list of dictionaries (e.g., CNN convs) + formatted_items = [f"{{{','.join(f'{k}:{v}' for k, v in item.items())}}}" for item in value] + else: + # Handle list of primitives (e.g., MLP units) + formatted_items = [str(x) for x in value] + target_list.append(f"'{key}=[{','.join(formatted_items)}]'") + elif isinstance(value, str) and ("{" in value or "}" in value): + target_list.append(f"'{key}={value}'") + else: + target_list.append(f"{key}={value}") + + print(f"[INFO]: Starting workflow {workflow}") + process_args(cfg["runner_args"], runner_args) + print(f"[INFO]: Retrieved workflow runner args: {runner_args}") + process_args(cfg["hydra_args"], hydra_args, is_hydra=True) + print(f"[INFO]: Retrieved hydra args: {hydra_args}") + + invoke_cmd = f"{python_cmd} {workflow} " + invoke_cmd += " ".join(runner_args) + " " + " ".join(hydra_args) + return invoke_cmd + + +@ray.remote +def remote_execute_job( + job_cmd: str, identifier_string: str, test_mode: bool = False, extract_experiment: bool = False +) -> str | dict: + """This method has an identical signature to :meth:`execute_job`, with the ray remote decorator""" + return execute_job( + job_cmd=job_cmd, identifier_string=identifier_string, test_mode=test_mode, extract_experiment=extract_experiment + ) + + +class LogExtractionError(Exception): + """Raised when we cannot extract experiment_name/logdir from the trainer output.""" + + pass + + +def execute_job( + job_cmd: str, + identifier_string: str = "job 0", + test_mode: bool = False, + extract_experiment: bool = False, + persistent_dir: str | None = None, + log_all_output: bool = False, + max_lines_to_search_logs: int = 1000, + max_time_to_search_logs: float = 200.0, +) -> str | dict: + """Issue a job (shell command). + + Args: + job_cmd: The shell command to run. + identifier_string: What prefix to add to make logs easier to differentiate + across clusters or jobs. Defaults to "job 0". + test_mode: When true, only run 'nvidia-smi'. Defaults to False. + extract_experiment: When true, search for experiment details from a training run. Defaults to False. + persistent_dir: When supplied, change to run the directory in a persistent + directory. Can be used to avoid losing logs in the /tmp directory. Defaults to None. + log_all_output: When true, print all output to the console. Defaults to False. + max_lines_to_search_logs: Maximum number of lines to search for experiment info. Defaults to 1000. + max_time_to_search_logs: Maximum time to wait for experiment info before giving up. Defaults to 200.0 seconds. + Raises: + ValueError: If the job is unable to start, or throws an error. Most likely to happen + due to running out of memory. + + Returns: + Relevant information from the job + """ + start_time = datetime.now().strftime("%H:%M:%S.%f") + result_details = [f"{identifier_string}: ---------------------------------\n"] + result_details.append(f"{identifier_string}:[INFO]: Invocation {job_cmd} \n") + node_id = ray.get_runtime_context().get_node_id() + result_details.append(f"{identifier_string}:[INFO]: Ray Node ID: {node_id} \n") + + if test_mode: + import torch + + try: + result = subprocess.run( + ["nvidia-smi", "--query-gpu=name,memory.free,serial", "--format=csv,noheader,nounits"], + capture_output=True, + check=True, + text=True, + ) + output = result.stdout.strip().split("\n") + for gpu_info in output: + name, memory_free, serial = gpu_info.split(", ") + result_details.append( + f"{identifier_string}[INFO]: Name: {name}|Memory Available: {memory_free} MB|Serial Number" + f" {serial} \n" + ) + + # Get GPU count from PyTorch + num_gpus_detected = torch.cuda.device_count() + result_details.append(f"{identifier_string}[INFO]: Detected GPUs from PyTorch: {num_gpus_detected} \n") + + # Check CUDA_VISIBLE_DEVICES and count the number of visible GPUs + cuda_visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES") + if cuda_visible_devices: + visible_devices_count = len(cuda_visible_devices.split(",")) + result_details.append( + f"{identifier_string}[INFO]: GPUs visible via CUDA_VISIBLE_DEVICES: {visible_devices_count} \n" + ) + else: + visible_devices_count = len(output) # All GPUs visible if CUDA_VISIBLE_DEVICES is not set + result_details.append( + f"{identifier_string}[INFO]: CUDA_VISIBLE_DEVICES not set; all GPUs visible" + f" ({visible_devices_count}) \n" + ) + + # If PyTorch GPU count disagrees with nvidia-smi, reset CUDA_VISIBLE_DEVICES and rerun detection + if num_gpus_detected != len(output): + result_details.append( + f"{identifier_string}[WARNING]: PyTorch and nvidia-smi disagree on GPU count! Re-running with all" + " GPUs visible. \n" + ) + result_details.append(f"{identifier_string}[INFO]: This shows that GPU resources were isolated.\n") + os.environ["CUDA_VISIBLE_DEVICES"] = ",".join([str(i) for i in range(len(output))]) + num_gpus_detected_after_reset = torch.cuda.device_count() + result_details.append( + f"{identifier_string}[INFO]: After setting CUDA_VISIBLE_DEVICES, PyTorch detects" + f" {num_gpus_detected_after_reset} GPUs \n" + ) + + except subprocess.CalledProcessError as e: + print(f"Error calling nvidia-smi: {e.stderr}") + result_details.append({"error": "Failed to retrieve GPU information"}) + else: + if persistent_dir: + og_dir = os.getcwd() + os.chdir(persistent_dir) + process = subprocess.Popen( + job_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1 + ) + process_file_descriptor = process.stdout.fileno() + + if persistent_dir: + os.chdir(og_dir) + experiment_name = None + logdir = None + experiment_info_pattern = re.compile("Exact experiment name requested from command line: (.+)") + logdir_pattern = re.compile(r"\[INFO\] Logging experiment in directory: (.+)$") + err_pattern = re.compile("There was an error (.+)$") + + def stream_reader(stream, identifier_string, result_details): + for line in iter(stream.readline, ""): + line = line.strip() + result_details.append(f"{identifier_string}: {line}\n") + if log_all_output: + print(f"{identifier_string}: {line}") + + # Read stdout until we find exp. info, up to max_lines_to_search_logs lines, max_time_to_search_logs, or EOF. + # Do some careful handling prevent overflowing the pipe reading buffer with error 141 + lines_read = 0 + search_duration = 0.0 + search_start_time = time() + while True: + new_line_ready, _, _ = select.select([process_file_descriptor], [], [], 1.0) # Wait up to 1s for stdout + if new_line_ready: + line = process.stdout.readline() + if not line: # EOF + break + + lines_read += 1 + line = line.strip() + result_details.append(f"{identifier_string}: {line} \n") + + if log_all_output: + print(f"{identifier_string}: {line}") + + if extract_experiment: + exp_match = experiment_info_pattern.search(line) + log_match = logdir_pattern.search(line) + err_match = err_pattern.search(line) + + if err_match: + raise ValueError(f"Encountered an error during trial run. {' '.join(result_details)}") + + if exp_match: + experiment_name = exp_match.group(1) + if log_match: + logdir = log_match.group(1) + + if experiment_name and logdir: + # Start stderr reader after finding experiment info + stderr_thread = threading.Thread( + target=stream_reader, args=(process.stderr, identifier_string, result_details) + ) + stderr_thread.daemon = True + stderr_thread.start() + + # Start stdout reader to continue reading to flush buffer + stdout_thread = threading.Thread( + target=stream_reader, args=(process.stdout, identifier_string, result_details) + ) + stdout_thread.daemon = True + stdout_thread.start() + + return { + "experiment_name": experiment_name, + "logdir": logdir, + "proc": process, + "result": " ".join(result_details), + } + + if extract_experiment: # if we are looking for experiment info, check for timeouts and line limits + search_duration = time() - search_start_time + if search_duration > max_time_to_search_logs: + print(f"[ERROR]: Could not find experiment logs within {max_time_to_search_logs} seconds.") + break + if lines_read >= max_lines_to_search_logs: + print(f"[ERROR]: Could not find experiment logs within first {max_lines_to_search_logs} lines.") + break + + # If we reach here, we didn't find experiment info in the output + if extract_experiment and not (experiment_name and logdir): + error_msg = ( + "Could not extract experiment_name/logdir from trainer output " + f"(experiment_name={experiment_name!r}, logdir={logdir!r}).\n" + "\tMake sure your training script prints the following correctly:\n" + "\t\tExact experiment name requested from command line: \n" + "\t\t[INFO] Logging experiment in directory: \n\n" + ) + print(f"[ERROR]: {error_msg}") + raise LogExtractionError("Could not extract experiment_name/logdir from training workflow output.") + process.wait() + now = datetime.now().strftime("%H:%M:%S.%f") + completion_info = f"\n[INFO]: {identifier_string}: Job Started at {start_time}, completed at {now}\n" + print(completion_info) + result_details.append(completion_info) + return " ".join(result_details) + + +def ray_init(ray_address: str = "auto", runtime_env: dict[str, Any] | None = None, log_to_driver: bool = False): + """Initialize Ray with the given address and runtime environment.""" + if not ray.is_initialized(): + print( + f"[INFO] Initializing Ray with address {ray_address}, log_to_driver={log_to_driver}," + f" runtime_env={runtime_env}" + ) + ray.init(address=ray_address, runtime_env=runtime_env, log_to_driver=log_to_driver) + else: + print("[WARNING]: Attempting to initialize Ray but it is already initialized!") + + +def get_gpu_node_resources( + total_resources: bool = False, + one_node_only: bool = False, + include_gb_ram: bool = False, + include_id: bool = False, +) -> list[dict] | dict: + """Get information about available GPU node resources. + + Args: + total_resources: When true, return total available resources. Defaults to False. + one_node_only: When true, return resources for a single node. Defaults to False. + include_gb_ram: Set to true to convert MB to GB in result + include_id: Set to true to include node ID + ray_address: The ray address to connect to. + + Returns: + Resource information for all nodes, sorted by descending GPU count, then descending CPU + count, then descending RAM capacity, and finally by node ID in ascending order if available, + or simply the resource for a single node if requested. + """ + if not ray.is_initialized(): + raise RuntimeError("Ray must be initialized before calling get_gpu_node_resources().") + nodes = ray.nodes() + node_resources = [] + total_cpus = 0 + total_gpus = 0 + total_memory = 0 # in bytes + + for node in nodes: + if node["Alive"] and "GPU" in node["Resources"]: + node_id = node["NodeID"] + resources = node["Resources"] + cpus = resources.get("CPU", 0) + gpus = resources.get("GPU", 0) + memory = resources.get("memory", 0) + node_resources.append({"CPU": cpus, "GPU": gpus, "memory": memory}) + + if include_id: + node_resources[-1]["id"] = node_id + if include_gb_ram: + node_resources[-1]["ram_gb"] = memory / 1024**3 + + total_cpus += cpus + total_gpus += gpus + total_memory += memory + node_resources = sorted(node_resources, key=lambda x: (-x["GPU"], -x["CPU"], -x["memory"], x.get("id", ""))) + + if total_resources: + # Return summed total resources + return {"CPU": total_cpus, "GPU": total_gpus, "memory": total_memory} + + if one_node_only and node_resources: + return node_resources[0] + + return node_resources + + +def add_resource_arguments( + arg_parser: argparse.ArgumentParser, + defaults: list | None = None, + cluster_create_defaults: bool = False, +) -> argparse.ArgumentParser: + """Add resource arguments to a cluster; this is shared across both + wrapping resources and launching clusters. + + Args: + arg_parser: the argparser to add the arguments to. This argparser is mutated. + defaults: The default values for GPUs, CPUs, RAM, and Num Workers + cluster_create_defaults: Set to true to populate reasonable defaults for creating clusters. + Returns: + The argparser with the standard resource arguments. + """ + if defaults is None: + if cluster_create_defaults: + defaults = [[1], [8], [16], [1]] + else: + defaults = [None, None, None, [1]] + arg_parser.add_argument( + "--gpu_per_worker", + nargs="+", + type=int, + default=defaults[0], + help="Number of GPUs per worker node. Supply more than one for heterogeneous resources", + ) + arg_parser.add_argument( + "--cpu_per_worker", + nargs="+", + type=int, + default=defaults[1], + help="Number of CPUs per worker node. Supply more than one for heterogeneous resources", + ) + arg_parser.add_argument( + "--ram_gb_per_worker", + nargs="+", + type=int, + default=defaults[2], + help="RAM in GB per worker node. Supply more than one for heterogeneous resources.", + ) + arg_parser.add_argument( + "--num_workers", + nargs="+", + type=int, + default=defaults[3], + help="Number of desired workers. Supply more than one for heterogeneous resources.", + ) + return arg_parser + + +def fill_in_missing_resources( + args: argparse.Namespace, resources: dict | None = None, cluster_creation_flag: bool = False, policy: callable = max +): + """Normalize the lengths of resource lists based on the longest list provided.""" + print("[INFO]: Filling in missing command line arguments with best guess...") + if resources is None: + resources = { + "gpu_per_worker": args.gpu_per_worker, + "cpu_per_worker": args.cpu_per_worker, + "ram_gb_per_worker": args.ram_gb_per_worker, + "num_workers": args.num_workers, + } + if cluster_creation_flag: + cluster_creation_resources = {"worker_accelerator": args.worker_accelerator} + resources.update(cluster_creation_resources) + + # Calculate the maximum length of any list + max_length = max(len(v) for v in resources.values()) + print("[INFO]: Resource list lengths:") + for key, value in resources.items(): + print(f"[INFO] {key}: {len(value)} values {value}") + + # Extend each list to match the maximum length using the maximum value in each list + for key, value in resources.items(): + potential_value = getattr(args, key) + if potential_value is not None: + max_value = policy(policy(value), policy(potential_value)) + else: + max_value = policy(value) + extension_length = max_length - len(value) + if extension_length > 0: # Only extend if the current list is shorter than max_length + print(f"\n[WARNING]: Resource '{key}' needs extension:") + print(f"[INFO] Current length: {len(value)}") + print(f"[INFO] Target length: {max_length}") + print(f"[INFO] Filling in {extension_length} missing values with {max_value}") + print(f"[INFO] To avoid auto-filling, provide {extension_length} more {key} value(s)") + value.extend([max_value] * extension_length) + setattr(args, key, value) + resources[key] = value + print(f"[INFO] Final {key} values: {getattr(args, key)}") + print("[INFO]: Done filling in command line arguments...\n\n") + return args + + +def populate_isaac_ray_cfg_args(cfg: dict = {}) -> dict: + """Small utility method to create empty fields if needed for a configuration.""" + if "runner_args" not in cfg: + cfg["runner_args"] = {} + if "hydra_args" not in cfg: + cfg["hydra_args"] = {} + return cfg + + +def _dicts_equal(d1: dict, d2: dict, tol=1e-9) -> bool: + """Check if two dicts are equal; helps ensure only new logs are returned.""" + if d1.keys() != d2.keys(): + return False + for key in d1: + if isinstance(d1[key], float) and isinstance(d2[key], float): + if not isclose(d1[key], d2[key], abs_tol=tol): + return False + elif d1[key] != d2[key]: + return False + return True + + +@dataclass +class JobResource: + """A dataclass to represent a resource request for a job.""" + + num_gpus: float | None = None + num_cpus: float | None = None + memory: int | None = None # in bytes + + def to_opt(self) -> dict[str, Any]: + """Convert the resource request to a dictionary.""" + opt = {} + if self.num_gpus is not None: + opt["num_gpus"] = self.num_gpus + if self.num_cpus is not None: + opt["num_cpus"] = self.num_cpus + if self.memory is not None: + opt["memory"] = self.memory + return opt + + def to_pg_resources(self) -> dict[str, Any]: + """Convert the resource request to a dictionary suitable for placement groups.""" + res = {} + if self.num_gpus is not None: + res["GPU"] = self.num_gpus + if self.num_cpus is not None: + res["CPU"] = self.num_cpus + if self.memory is not None: + res["memory"] = self.memory + return res + + +@dataclass +class JobNode: + """A dataclass to represent a node for job affinity.""" + + specific: str | None = None + hostname: str | None = None + node_id: str | None = None + + def to_opt(self, nodes: list[dict[str, Any]]) -> dict[str, Any]: + """ + Convert node affinity settings into a dictionary of Ray actor scheduling options. + + Args: + nodes (list[dict[str, Any]]): List of node metadata from `ray.nodes()` which looks like this: + [{ + 'NodeID': 'xxx', + 'Alive': True, + 'NodeManagerAddress': 'x.x.x.x', + 'NodeManagerHostname': 'ray-head-mjzzf', + 'NodeManagerPort': 44039, + 'ObjectManagerPort': 35689, + 'ObjectStoreSocketName': '/tmp/ray/session_xxx/sockets/plasma_store', + 'RayletSocketName': '/tmp/ray/session_xxx/sockets/raylet', + 'MetricsExportPort': 8080, + 'NodeName': 'x.x.x.x', + 'RuntimeEnvAgentPort': 63725, + 'DeathReason': 0, + 'DeathReasonMessage': '', + 'alive': True, + 'Resources': { + 'node:__internal_head__': 1.0, + 'object_store_memory': 422449279795.0, + 'memory': 1099511627776.0, + 'GPU': 8.0, + 'node:x.x.x.x': 1.0, + 'CPU': 192.0, + 'accelerator_type:H20': 1.0 + }, + 'Labels': { + 'ray.io/node_id': 'xxx' + } + },...] + + Returns: + dict[str, Any]: A dictionary with possible scheduling options: + - Empty if no specific placement requirement. + - "scheduling_strategy" key set to `NodeAffinitySchedulingStrategy` + if hostname or node_id placement is specified. + + Raises: + ValueError: If hostname/node_id is specified but not found in the cluster + or the node is not alive. + """ + opt = {} + if self.specific is None or self.specific == "any": + return opt + elif self.specific == "hostname": + if self.hostname is None: + raise ValueError("Hostname must be specified when specific is 'hostname'") + for node in nodes: + if node["NodeManagerHostname"] == self.hostname: + if node["alive"] is False: + raise ValueError(f"Node {node['NodeID']} is not alive") + opt["scheduling_strategy"] = NodeAffinitySchedulingStrategy(node_id=node["NodeID"], soft=False) + return opt + raise ValueError(f"Hostname {self.hostname} not found in nodes: {nodes}") + elif self.specific == "node_id": + if self.node_id is None: + raise ValueError("Node ID must be specified when specific is 'node_id'") + for node in nodes: + if node["NodeID"] == self.node_id: + if node["alive"] is False: + raise ValueError(f"Node {node['NodeID']} is not alive") + opt["scheduling_strategy"] = NodeAffinitySchedulingStrategy(node_id=node["NodeID"], soft=False) + return opt + raise ValueError(f"Node ID {self.node_id} not found in nodes: {nodes}") + else: + raise ValueError(f"Invalid specific value: {self.specific}. Must be 'any', 'hostname', or 'node_id'.") + + +@dataclass +class Job: + """A dataclass to represent a job to be submitted to Ray.""" + + # job command + cmd: str | None = None + py_args: str | None = None + # identifier string for the job, e.g., "job 0" + name: str = "" + # job resources, e.g., {"CPU": 4, "GPU": 1} + resources: JobResource | None = None + # specify the node to run the job on, if needed to run on a specific node + node: JobNode | None = None + + def to_opt(self, nodes: list[dict[str, Any]]) -> dict[str, Any]: + """ + Convert the job definition into a dictionary of Ray scheduling options. + + Args: + nodes (list[dict[str, Any]]): Node information from `ray.nodes()`. + + Returns: + dict[str, Any]: Combined scheduling options from: + - `JobResource.to_opt()` for resource requirements + - `JobNode.to_opt()` for node placement constraints + """ + opt = {} + if self.resources is not None: + opt.update(self.resources.to_opt()) + if self.node is not None: + opt.update(self.node.to_opt(nodes)) + return opt + + +@ray.remote +class JobActor: + """Actor to run job in Ray cluster.""" + + def __init__(self, job: Job, test_mode: bool, log_all_output: bool, extract_experiment: bool = False): + self.job = job + self.test_mode = test_mode + self.log_all_output = log_all_output + self.extract_experiment = extract_experiment + self.done = True + + def ready(self) -> bool: + """Check if the job is ready to run.""" + return self.done + + def run(self): + """Run the job.""" + cmd = self.job.cmd if self.job.cmd else " ".join([sys.executable, *self.job.py_args.split()]) + return execute_job( + job_cmd=cmd, + identifier_string=self.job.name, + test_mode=self.test_mode, + extract_experiment=self.extract_experiment, + log_all_output=self.log_all_output, + ) + + +def submit_wrapped_jobs( + jobs: Sequence[Job], + log_realtime: bool = True, + test_mode: bool = False, + concurrent: bool = False, +) -> None: + """ + Submit a list of jobs to the Ray cluster and manage their execution. + + Args: + jobs (Sequence[Job]): A sequence of Job objects to execute on Ray. + log_realtime (bool): Whether to log stdout/stderr in real-time. Defaults to True. + test_mode (bool): If True, run in GPU sanity-check mode instead of actual jobs. Defaults to False. + concurrent (bool): Whether to launch tasks simultaneously as a batch, + or independently as resources become available. Defaults to False. + + Returns: + None + """ + if jobs is None or len(jobs) == 0: + print("[WARNING]: No jobs to submit") + return + if not ray.is_initialized(): + raise Exception("Ray is not initialized. Please initialize Ray before submitting jobs.") + nodes = ray.nodes() + actors = [] + for i, job in enumerate(jobs): + opts = job.to_opt(nodes) + name = job.name or f"job_{i + 1}" + print(f"[INFO] Create {name} with opts={opts}") + job_actor = JobActor.options(**opts).remote(job, test_mode, log_realtime) + actors.append(job_actor) + try: + if concurrent: + ray.get([actor.ready.remote() for actor in actors]) + print("[INFO] All actors are ready to run.") + future = [actor.run.remote() for actor in actors] + while future: + ready, not_ready = ray.wait(future, timeout=5) + for result in ray.get(ready): + print(f"\n{result}\n") + future = not_ready + print("[INFO] all jobs completed.") + except KeyboardInterrupt: + print("[INFO] KeyboardInterrupt received, cancelling …") + for actor in actors: + ray.cancel(actor, force=True) + sys.exit(0) diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/wrap_resources.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/wrap_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..158bd0d824602ea423b07288ae52758381dacf52 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/ray/wrap_resources.py @@ -0,0 +1,162 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script dispatches sub-job(s) (individual jobs, use :file:`tuner.py` for tuning jobs) +to worker(s) on GPU-enabled node(s) of a specific cluster as part of an resource-wrapped aggregate +job. If no desired compute resources for each sub-job are specified, +this script creates one worker per available node for each node with GPU(s) in the cluster. +If the desired resources for each sub-job is specified, +the maximum number of workers possible with the desired resources are created for each node +with GPU(s) in the cluster. It is also possible to split available node resources for each node +into the desired number of workers with the ``--num_workers`` flag, to be able to easily +parallelize sub-jobs on multi-GPU nodes. Due to Isaac Lab requiring a GPU, +this ignores all CPU only nodes such as loggers. + +Sub-jobs are matched with node(s) in a cluster via the following relation: +sorted_nodes = Node sorted by descending GPUs, then descending CPUs, then descending RAM, then node ID +node_submitted_to = sorted_nodes[job_index % total_node_count] + +To check the ordering of sorted nodes, supply the ``--test`` argument and run the script. + +Sub-jobs are separated by the + delimiter. The ``--sub_jobs`` argument must be the last +argument supplied to the script. + +If there is more than one available worker, and more than one sub-job, +sub-jobs will be executed in parallel. If there are more sub-jobs than workers, sub-jobs will +be dispatched to workers as they become available. There is no limit on the number +of sub-jobs that can be near-simultaneously submitted. + +This script is meant to be executed on a Ray cluster head node as an aggregate cluster job. +To submit aggregate cluster jobs such as this script to one or more remote clusters, +see :file:`../submit_isaac_ray_job.py`. + +KubeRay clusters on Google GKE can be created with :file:`../launch.py` + +Usage: + +.. code-block:: bash + # **Ensure that sub-jobs are separated by the ``+`` delimiter.** + # Generic Templates----------------------------------- + ./isaaclab.sh -p scripts/reinforcement_learning/ray/wrap_resources.py -h + # No resource isolation; no parallelization: + ./isaaclab.sh -p scripts/reinforcement_learning/ray/wrap_resources.py + --sub_jobs ++ + # Automatic Resource Isolation; Example A: needed for parallelization + ./isaaclab.sh -p scripts/reinforcement_learning/ray/wrap_resources.py \ + --num_workers \ + --sub_jobs + + # Manual Resource Isolation; Example B: needed for parallelization + ./isaaclab.sh -p scripts/reinforcement_learning/ray/wrap_resources.py --num_cpu_per_worker \ + --gpu_per_worker --ram_gb_per_worker --sub_jobs + + # Manual Resource Isolation; Example C: Needed for parallelization, for heterogeneous workloads + ./isaaclab.sh -p scripts/reinforcement_learning/ray/wrap_resources.py --num_cpu_per_worker \ + --gpu_per_worker --ram_gb_per_worker --sub_jobs + + # to see all arguments + ./isaaclab.sh -p scripts/reinforcement_learning/ray/wrap_resources.py -h +""" + +import argparse + +import util + + +def wrap_resources_to_jobs(jobs: list[str], args: argparse.Namespace) -> None: + """ + Provided a list of jobs, dispatch jobs to one worker per available node, + unless otherwise specified by resource constraints. + + Args: + jobs: bash commands to execute on a Ray cluster + args: The arguments for resource allocation + + """ + job_objs = [] + util.ray_init( + ray_address=args.ray_address, + runtime_env={ + "py_modules": None if not args.py_modules else args.py_modules, + }, + log_to_driver=False, + ) + gpu_node_resources = util.get_gpu_node_resources(include_id=True, include_gb_ram=True) + + if any([args.gpu_per_worker, args.cpu_per_worker, args.ram_gb_per_worker]) and args.num_workers: + raise ValueError("Either specify only num_workers or only granular resources(GPU,CPU,RAM_GB).") + + num_nodes = len(gpu_node_resources) + # Populate arguments + formatted_node_resources = { + "gpu_per_worker": [gpu_node_resources[i]["GPU"] for i in range(num_nodes)], + "cpu_per_worker": [gpu_node_resources[i]["CPU"] for i in range(num_nodes)], + "ram_gb_per_worker": [gpu_node_resources[i]["ram_gb"] for i in range(num_nodes)], + "num_workers": args.num_workers, # By default, 1 worker por node + } + args = util.fill_in_missing_resources(args, resources=formatted_node_resources, policy=min) + print(f"[INFO]: Number of GPU nodes found: {num_nodes}") + if args.test: + jobs = ["nvidia-smi"] * num_nodes + for i, job in enumerate(jobs): + gpu_node = gpu_node_resources[i % num_nodes] + print(f"[INFO]: Creating job {i + 1} of {len(jobs)} with job '{job}' to node {gpu_node}") + print( + f"[INFO]: Resource parameters: GPU: {args.gpu_per_worker[i]}" + f" CPU: {args.cpu_per_worker[i]} RAM {args.ram_gb_per_worker[i]}" + ) + print(f"[INFO] For the node parameters, creating {args.num_workers[i]} workers") + num_gpus = args.gpu_per_worker[i] / args.num_workers[i] + num_cpus = args.cpu_per_worker[i] / args.num_workers[i] + memory = (args.ram_gb_per_worker[i] * 1024**3) / args.num_workers[i] + job_objs.append( + util.Job( + cmd=job, + name=f"Job-{i + 1}", + resources=util.JobResource(num_gpus=num_gpus, num_cpus=num_cpus, memory=memory), + node=util.JobNode( + specific="node_id", + node_id=gpu_node["id"], + ), + ) + ) + # submit jobs + util.submit_wrapped_jobs(jobs=job_objs, test_mode=args.test, concurrent=False) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Submit multiple jobs with optional GPU testing.") + parser = util.add_resource_arguments(arg_parser=parser) + parser.add_argument("--ray_address", type=str, default="auto", help="the Ray address.") + parser.add_argument( + "--test", + action="store_true", + help=( + "Run nvidia-smi test instead of the arbitrary job," + "can use as a sanity check prior to any jobs to check " + "that GPU resources are correctly isolated." + ), + ) + parser.add_argument( + "--py_modules", + type=str, + nargs="*", + default=[], + help=( + "List of python modules or paths to add before running the job. Example: --py_modules my_package/my_package" + ), + ) + parser.add_argument( + "--sub_jobs", + type=str, + nargs=argparse.REMAINDER, + help="This should be last wrapper argument. Jobs separated by the + delimiter to run on a cluster.", + ) + args = parser.parse_args() + if args.sub_jobs is not None: + jobs = " ".join(args.sub_jobs) + formatted_jobs = jobs.split("+") + else: + formatted_jobs = [] + print(f"[INFO]: Isaac Ray Wrapper received jobs {formatted_jobs=}") + wrap_resources_to_jobs(jobs=formatted_jobs, args=args) diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rl_games/play.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rl_games/play.py new file mode 100644 index 0000000000000000000000000000000000000000..bf21caa0ca23285247290026b4521fec5b903587 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rl_games/play.py @@ -0,0 +1,224 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to play a checkpoint if an RL agent from RL-Games.""" + +import warnings + +warnings.warn( + "scripts/reinforcement_learning/rl_games/play.py is deprecated. Use " + "`./isaaclab.sh play --rl_library rl_games --task ` instead. " + "Example: `./isaaclab.sh play --rl_library rl_games --task Isaac-Cartpole-v0`.", + DeprecationWarning, + stacklevel=1, +) + +import argparse +import contextlib +import math +import os +import random +import sys +import time + +import gymnasium as gym +import torch +from rl_games.common import env_configurations, vecenv +from rl_games.common.player import BasePlayer +from rl_games.torch_runner import Runner + +from isaaclab.envs import DirectMARLEnvCfg +from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.dict import print_dict +from isaaclab.utils.seed import configure_seed + +from isaaclab_rl.rl_games import RlGamesGpuEnv, RlGamesVecEnvWrapper +from isaaclab_rl.utils.pretrained_checkpoint import get_published_pretrained_checkpoint + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + get_checkpoint_path, + launch_simulation, + resolve_task_config, + setup_preset_cli, +) + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + +# -- argparse ---------------------------------------------------------------- +parser = argparse.ArgumentParser(description="Play a checkpoint of an RL agent from RL-Games.") +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( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +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( + "--agent", type=str, default="rl_games_cfg_entry_point", help="Name of the RL agent configuration entry point." +) +parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint.") +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument( + "--use_pretrained_checkpoint", + action="store_true", + help="Use the pre-trained checkpoint from Nucleus.", +) +parser.add_argument( + "--use_last_checkpoint", + action="store_true", + help="When no checkpoint provided, use the last saved model. Otherwise use the best saved model.", +) +parser.add_argument("--real-time", action="store_true", default=False, help="Run in real-time, if possible.") +add_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args + +if args_cli.video: + args_cli.enable_cameras = True + + +def main(): + """Play with RL-Games agent.""" + env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent) + with launch_simulation(env_cfg, args_cli): + # grab task name for checkpoint path + task_name = args_cli.task.split(":")[-1] + train_task_name = task_name.replace("-Play", "") + + # override configurations with non-hydra CLI arguments + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + # randomly sample a seed if seed = -1 + if args_cli.seed == -1: + args_cli.seed = random.randint(0, 10000) + + agent_cfg["params"]["seed"] = args_cli.seed if args_cli.seed is not None else agent_cfg["params"]["seed"] + env_cfg.seed = agent_cfg["params"]["seed"] + + # specify directory for logging experiments + log_root_path = os.path.join("logs", "rl_games", agent_cfg["params"]["config"]["name"]) + log_root_path = os.path.abspath(log_root_path) + print(f"[INFO] Loading experiment from directory: {log_root_path}") + # find checkpoint + if args_cli.use_pretrained_checkpoint: + resume_path = get_published_pretrained_checkpoint("rl_games", train_task_name) + if not resume_path: + print("[INFO] Unfortunately a pre-trained checkpoint is currently unavailable for this task.") + return + elif args_cli.checkpoint is None: + run_dir = agent_cfg["params"]["config"].get("full_experiment_name", ".*") + # prefer the best-reward checkpoint (``.pth``); fall back to the latest checkpoint when it has + # not been written yet (e.g. short runs). With --use_last_checkpoint, skip the preference entirely. + best_checkpoint = None if args_cli.use_last_checkpoint else f"{agent_cfg['params']['config']['name']}.pth" + resume_path = get_checkpoint_path( + log_root_path, run_dir, ".*", other_dirs=["nn"], preferred_checkpoint=best_checkpoint + ) + else: + resume_path = retrieve_file_path(args_cli.checkpoint) + log_dir = os.path.dirname(os.path.dirname(resume_path)) + + # set the log directory for the environment + env_cfg.log_dir = log_dir + + # wrap around environment for rl-games + rl_device = agent_cfg["params"]["config"]["device"] + clip_obs = agent_cfg["params"]["env"].get("clip_observations", math.inf) + clip_actions = agent_cfg["params"]["env"].get("clip_actions", math.inf) + obs_groups = agent_cfg["params"]["env"].get("obs_groups") + concate_obs_groups = agent_cfg["params"]["env"].get("concate_obs_groups", True) + + # create isaac environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + + # convert to single-agent instance if required by the RL algorithm + if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): + from isaaclab.envs import multi_agent_to_single_agent + + env = multi_agent_to_single_agent(env) + + # wrap for video recording + if args_cli.video: + video_kwargs = { + "video_folder": os.path.join(log_root_path, log_dir, "videos", "play"), + "step_trigger": lambda step: step == 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 rl-games + env = RlGamesVecEnvWrapper(env, rl_device, clip_obs, clip_actions, obs_groups, concate_obs_groups) + + # register the environment to rl-games registry + vecenv.register( + "IsaacRlgWrapper", + lambda config_name, num_actors, **kwargs: RlGamesGpuEnv(config_name, num_actors, **kwargs), + ) + env_configurations.register("rlgpu", {"vecenv_type": "IsaacRlgWrapper", "env_creator": lambda **kwargs: env}) + + # load previously trained model + agent_cfg["params"]["load_checkpoint"] = True + agent_cfg["params"]["load_path"] = resume_path + print(f"[INFO]: Loading model checkpoint from: {agent_cfg['params']['load_path']}") + + # set number of actors into agent config + agent_cfg["params"]["config"]["num_actors"] = env.unwrapped.num_envs + runner = Runner() + # configure_seed must be called after Runner() so that PyTorch deterministic settings + # do not interfere with Runner's internal initialization. + if args_cli.deterministic: + configure_seed(env_cfg.seed, True) + runner.load(agent_cfg) + agent: BasePlayer = runner.create_player() + agent.restore(resume_path) + agent.reset() + + dt = env.unwrapped.step_dt + + # reset environment + obs = env.reset() + if isinstance(obs, dict): + obs = obs["obs"] + timestep = 0 + _ = agent.get_batch_size(obs, 1) + if agent.is_rnn: + agent.init_rnn() + # simulate environment + try: + while True: + start_time = time.time() + with torch.inference_mode(): + obs = agent.obs_to_torch(obs) + actions = agent.get_action(obs, is_deterministic=agent.is_deterministic) + obs, _, dones, _ = env.step(actions) + + if len(dones) > 0: + if agent.is_rnn and agent.states is not None: + for s in agent.states: + s[:, dones, :] = 0.0 + if args_cli.video: + timestep += 1 + if timestep == args_cli.video_length: + break + + sleep_time = dt - (time.time() - start_time) + if args_cli.real_time and sleep_time > 0: + time.sleep(sleep_time) + + # close the simulator + env.close() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rl_games/play_rl_games.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rl_games/play_rl_games.py new file mode 100644 index 0000000000000000000000000000000000000000..cf33ed8af41f3f04a52fc53f9007595b7a55be05 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rl_games/play_rl_games.py @@ -0,0 +1,210 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to play a checkpoint of an RL agent from RL-Games.""" + +import argparse +import contextlib +import math +import os +import random +import sys +import time + +import gymnasium as gym +import torch +from rl_games.common import env_configurations, vecenv +from rl_games.common.player import BasePlayer +from rl_games.torch_runner import Runner + +from isaaclab.envs import DirectMARLEnvCfg +from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.dict import print_dict + +from isaaclab_rl.rl_games import RlGamesGpuEnv, RlGamesVecEnvWrapper +from isaaclab_rl.utils.pretrained_checkpoint import get_published_pretrained_checkpoint + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + get_checkpoint_path, + launch_simulation, + resolve_task_config, + setup_preset_cli, +) + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + +# -- argparse ---------------------------------------------------------------- +parser = argparse.ArgumentParser(description="Play a checkpoint of an RL agent from RL-Games.") +parser.add_argument("--video", action="store_true", default=False, help="Record videos during play.") +parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).") +parser.add_argument( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument( + "--agent", type=str, default="rl_games_cfg_entry_point", help="Name of the RL agent configuration entry point." +) +parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint.") +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument( + "--use_pretrained_checkpoint", + action="store_true", + help="Use the pre-trained checkpoint from Nucleus.", +) +parser.add_argument( + "--use_last_checkpoint", + action="store_true", + help="When no checkpoint provided, use the last saved model. Otherwise use the best saved model.", +) +parser.add_argument("--real-time", action="store_true", default=False, help="Run in real-time, if possible.") +add_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) + +if args_cli.video: + args_cli.enable_cameras = True + +sys.argv = [sys.argv[0]] + hydra_args + + +def main(): + """Play with RL-Games agent.""" + env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent) + with launch_simulation(env_cfg, args_cli): + # grab task name for checkpoint path + task_name = args_cli.task.split(":")[-1] + train_task_name = task_name.replace("-Play", "") + + # override configurations with non-hydra CLI arguments + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + # randomly sample a seed if seed = -1 + if args_cli.seed == -1: + args_cli.seed = random.randint(0, 10000) + + agent_cfg["params"]["seed"] = args_cli.seed if args_cli.seed is not None else agent_cfg["params"]["seed"] + env_cfg.seed = agent_cfg["params"]["seed"] + + # specify directory for logging experiments + log_root_path = os.path.join("logs", "rl_games", agent_cfg["params"]["config"]["name"]) + log_root_path = os.path.abspath(log_root_path) + print(f"[INFO] Loading experiment from directory: {log_root_path}") + # find checkpoint + if args_cli.use_pretrained_checkpoint: + resume_path = get_published_pretrained_checkpoint("rl_games", train_task_name) + if not resume_path: + print("[INFO] Unfortunately a pre-trained checkpoint is currently unavailable for this task.") + return + elif args_cli.checkpoint is None: + run_dir = agent_cfg["params"]["config"].get("full_experiment_name", ".*") + # prefer the best-reward checkpoint (``.pth``); fall back to the latest checkpoint when it has + # not been written yet (e.g. short runs). With --use_last_checkpoint, skip the preference entirely. + best_checkpoint = None if args_cli.use_last_checkpoint else f"{agent_cfg['params']['config']['name']}.pth" + resume_path = get_checkpoint_path( + log_root_path, run_dir, ".*", other_dirs=["nn"], preferred_checkpoint=best_checkpoint + ) + else: + resume_path = retrieve_file_path(args_cli.checkpoint) + log_dir = os.path.dirname(os.path.dirname(resume_path)) + + # set the log directory for the environment + env_cfg.log_dir = log_dir + + # wrap around environment for rl-games + rl_device = agent_cfg["params"]["config"]["device"] + clip_obs = agent_cfg["params"]["env"].get("clip_observations", math.inf) + clip_actions = agent_cfg["params"]["env"].get("clip_actions", math.inf) + obs_groups = agent_cfg["params"]["env"].get("obs_groups") + concate_obs_groups = agent_cfg["params"]["env"].get("concate_obs_groups", True) + + # create isaac environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + + # convert to single-agent instance if required by the RL algorithm + if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): + from isaaclab.envs import multi_agent_to_single_agent + + env = multi_agent_to_single_agent(env) + + # wrap for video recording + if args_cli.video: + video_kwargs = { + "video_folder": os.path.join(log_root_path, log_dir, "videos", "play"), + "step_trigger": lambda step: step == 0, + "video_length": args_cli.video_length, + "disable_logger": True, + } + print("[INFO] Recording videos during play.") + print_dict(video_kwargs, nesting=4) + env = gym.wrappers.RecordVideo(env, **video_kwargs) + + # wrap around environment for rl-games + env = RlGamesVecEnvWrapper(env, rl_device, clip_obs, clip_actions, obs_groups, concate_obs_groups) + + # register the environment to rl-games registry + vecenv.register( + "IsaacRlgWrapper", + lambda config_name, num_actors, **kwargs: RlGamesGpuEnv(config_name, num_actors, **kwargs), + ) + env_configurations.register("rlgpu", {"vecenv_type": "IsaacRlgWrapper", "env_creator": lambda **kwargs: env}) + + # load previously trained model + agent_cfg["params"]["load_checkpoint"] = True + agent_cfg["params"]["load_path"] = resume_path + print(f"[INFO]: Loading model checkpoint from: {agent_cfg['params']['load_path']}") + + # set number of actors into agent config + agent_cfg["params"]["config"]["num_actors"] = env.unwrapped.num_envs + runner = Runner() + runner.load(agent_cfg) + agent: BasePlayer = runner.create_player() + agent.restore(resume_path) + agent.reset() + + dt = env.unwrapped.step_dt + + # reset environment + obs = env.reset() + if isinstance(obs, dict): + obs = obs["obs"] + timestep = 0 + _ = agent.get_batch_size(obs, 1) + if agent.is_rnn: + agent.init_rnn() + # simulate environment + try: + while True: + start_time = time.time() + with torch.inference_mode(): + obs = agent.obs_to_torch(obs) + actions = agent.get_action(obs, is_deterministic=agent.is_deterministic) + obs, _, dones, _ = env.step(actions) + + if len(dones) > 0: + if agent.is_rnn and agent.states is not None: + for s in agent.states: + s[:, dones, :] = 0.0 + if args_cli.video: + timestep += 1 + if timestep == args_cli.video_length: + break + + sleep_time = dt - (time.time() - start_time) + if args_cli.real_time and sleep_time > 0: + time.sleep(sleep_time) + + # close the simulator + env.close() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rl_games/train.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rl_games/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d81d0f891a508b66e21c1f3734db8784198cd519 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rl_games/train.py @@ -0,0 +1,265 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to train RL agent with RL-Games.""" + +import warnings + +warnings.warn( + "scripts/reinforcement_learning/rl_games/train.py is deprecated. Use " + "`./isaaclab.sh train --rl_library rl_games --task ` instead. " + "Example: `./isaaclab.sh train --rl_library rl_games --task Isaac-Cartpole-v0`.", + DeprecationWarning, + stacklevel=1, +) + +import argparse +import contextlib +import logging +import math +import os +import random +import sys +import time +from datetime import datetime +from distutils.util import strtobool + +import gymnasium as gym +from rl_games.common import env_configurations, vecenv +from rl_games.common.algo_observer import IsaacAlgoObserver +from rl_games.torch_runner import Runner + +from isaaclab.envs import DirectMARLEnvCfg, ManagerBasedRLEnvCfg +from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.dict import print_dict +from isaaclab.utils.io import dump_yaml +from isaaclab.utils.seed import configure_seed + +from isaaclab_rl.rl_games import MultiObserver, PbtAlgoObserver, RlGamesGpuEnv, RlGamesVecEnvWrapper + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + launch_simulation, + resolve_task_config, + setup_preset_cli, +) + +logger = logging.getLogger(__name__) + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + +# -- argparse ---------------------------------------------------------------- +parser = argparse.ArgumentParser(description="Train an RL agent with RL-Games.") +parser.add_argument("--video", action="store_true", default=False, help="Record videos during training.") +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("--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( + "--agent", type=str, default="rl_games_cfg_entry_point", help="Name of the RL agent configuration entry point." +) +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument( + "--distributed", action="store_true", default=False, help="Run training with multiple GPUs or nodes." +) +parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint.") +parser.add_argument("--sigma", type=str, default=None, help="The policy's initial standard deviation.") +parser.add_argument("--max_iterations", type=int, default=None, help="RL Policy training iterations.") +parser.add_argument("--wandb-project-name", type=str, default=None, help="the wandb's project name") +parser.add_argument("--wandb-entity", type=str, default=None, help="the entity (team) of wandb's project") +parser.add_argument("--wandb-name", type=str, default=None, help="the name of wandb's run") +parser.add_argument( + "--track", + type=lambda x: bool(strtobool(x)), + default=False, + nargs="?", + const=True, + help="if toggled, this experiment will be tracked with Weights and Biases", +) +parser.add_argument("--export_io_descriptors", action="store_true", default=False, help="Export IO descriptors.") +parser.add_argument( + "--ray-proc-id", "-rid", type=int, default=None, help="Automatically configured by Ray integration, otherwise None." +) +add_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args + +if args_cli.video: + args_cli.enable_cameras = True + + +def main(): + """Train with RL-Games agent.""" + env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent) + with launch_simulation(env_cfg, args_cli): + # override configurations with non-hydra CLI arguments + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + # For distributed training, launch_simulation() already resolved the + # correct per-rank device; only apply a CLI --device override for + # non-distributed runs (the default "cuda:0" would clobber the + # per-rank device otherwise). + if not args_cli.distributed: + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + if args_cli.distributed and args_cli.device is not None and "cpu" in args_cli.device: + raise ValueError( + "Distributed training is not supported when using CPU device. " + "Please use GPU device (e.g., --device cuda) for distributed training." + ) + + # randomly sample a seed if seed = -1 + if args_cli.seed == -1: + args_cli.seed = random.randint(0, 10000) + + agent_cfg["params"]["seed"] = args_cli.seed if args_cli.seed is not None else agent_cfg["params"]["seed"] + agent_cfg["params"]["config"]["max_epochs"] = ( + args_cli.max_iterations + if args_cli.max_iterations is not None + else agent_cfg["params"]["config"]["max_epochs"] + ) + if args_cli.checkpoint is not None: + resume_path = retrieve_file_path(args_cli.checkpoint) + agent_cfg["params"]["load_checkpoint"] = True + agent_cfg["params"]["load_path"] = resume_path + print(f"[INFO]: Loading model checkpoint from: {agent_cfg['params']['load_path']}") + train_sigma = float(args_cli.sigma) if args_cli.sigma is not None else None + + # multi-gpu training config + if args_cli.distributed: + agent_cfg["params"]["seed"] += int(os.getenv("RANK", "0")) + # env_cfg.sim.device is resolved by launch_simulation() which + # accounts for CUDA_VISIBLE_DEVICES restrictions. + agent_cfg["params"]["config"]["device"] = env_cfg.sim.device + agent_cfg["params"]["config"]["device_name"] = env_cfg.sim.device + agent_cfg["params"]["config"]["multi_gpu"] = True + + # set the environment seed (after multi-gpu config for updated rank from agent seed) + env_cfg.seed = agent_cfg["params"]["seed"] + + # specify directory for logging experiments + config_name = agent_cfg["params"]["config"]["name"] + log_root_path = os.path.join("logs", "rl_games", config_name) + if "pbt" in agent_cfg and agent_cfg["pbt"]["directory"] != ".": + log_root_path = os.path.join(agent_cfg["pbt"]["directory"], log_root_path) + else: + log_root_path = os.path.abspath(log_root_path) + + print(f"[INFO] Logging experiment in directory: {log_root_path}") + log_dir = agent_cfg["params"]["config"].get( + "full_experiment_name", datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ) + agent_cfg["params"]["config"]["train_dir"] = log_root_path + agent_cfg["params"]["config"]["full_experiment_name"] = log_dir + wandb_project = config_name if args_cli.wandb_project_name is None else args_cli.wandb_project_name + experiment_name = log_dir if args_cli.wandb_name is None else args_cli.wandb_name + + # dump the configuration into log-directory + dump_yaml(os.path.join(log_root_path, log_dir, "params", "env.yaml"), env_cfg) + dump_yaml(os.path.join(log_root_path, log_dir, "params", "agent.yaml"), agent_cfg) + print(f"Exact experiment name requested from command line: {os.path.join(log_root_path, log_dir)}") + + # read configurations about the agent-training + rl_device = agent_cfg["params"]["config"]["device"] + clip_obs = agent_cfg["params"]["env"].get("clip_observations", math.inf) + clip_actions = agent_cfg["params"]["env"].get("clip_actions", math.inf) + obs_groups = agent_cfg["params"]["env"].get("obs_groups") + concate_obs_groups = agent_cfg["params"]["env"].get("concate_obs_groups", True) + + # set the IO descriptors export flag if requested + if isinstance(env_cfg, ManagerBasedRLEnvCfg): + env_cfg.export_io_descriptors = args_cli.export_io_descriptors + else: + logger.warning( + "IO descriptors are only supported for manager based RL environments." + " No IO descriptors will be exported." + ) + + # set the log directory for the environment + env_cfg.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) + + # convert to single-agent instance if required by the RL algorithm + if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): + from isaaclab.envs import multi_agent_to_single_agent + + env = multi_agent_to_single_agent(env) + + # wrap for video recording + if args_cli.video: + video_kwargs = { + "video_folder": os.path.join(log_root_path, log_dir, "videos", "train"), + "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) + + start_time = time.time() + + # wrap around environment for rl-games + env = RlGamesVecEnvWrapper(env, rl_device, clip_obs, clip_actions, obs_groups, concate_obs_groups) + + # register the environment to rl-games registry + vecenv.register( + "IsaacRlgWrapper", + lambda config_name, num_actors, **kwargs: RlGamesGpuEnv(config_name, num_actors, **kwargs), + ) + env_configurations.register("rlgpu", {"vecenv_type": "IsaacRlgWrapper", "env_creator": lambda **kwargs: env}) + + # set number of actors into agent config + agent_cfg["params"]["config"]["num_actors"] = env.unwrapped.num_envs + + if "pbt" in agent_cfg and agent_cfg["pbt"]["enabled"]: + observers = MultiObserver([IsaacAlgoObserver(), PbtAlgoObserver(agent_cfg, args_cli)]) + runner = Runner(observers) + else: + runner = Runner(IsaacAlgoObserver()) + + # configure_seed must be called after Runner() so that PyTorch deterministic settings + # do not interfere with Runner's internal initialization. + if args_cli.deterministic: + configure_seed(env_cfg.seed, True) + + runner.load(agent_cfg) + runner.reset() + + global_rank = int(os.getenv("RANK", "0")) + if args_cli.track and global_rank == 0: + if args_cli.wandb_entity is None: + raise ValueError("Weights and Biases entity must be specified for tracking.") + import wandb + + wandb.init( + project=wandb_project, + entity=args_cli.wandb_entity, + name=experiment_name, + sync_tensorboard=True, + monitor_gym=True, + save_code=True, + ) + if not wandb.run.resumed: + wandb.config.update({"env_cfg": env_cfg.to_dict()}) + wandb.config.update({"agent_cfg": agent_cfg}) + + try: + if args_cli.checkpoint is not None: + runner.run({"train": True, "play": False, "sigma": train_sigma, "checkpoint": resume_path}) + else: + runner.run({"train": True, "play": False, "sigma": train_sigma}) + print(f"Training time: {round(time.time() - start_time, 2)} seconds") + # close the simulator + env.close() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rl_games/train_rl_games.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rl_games/train_rl_games.py new file mode 100644 index 0000000000000000000000000000000000000000..b893cf9709cc3bc88b05873795fe8943cf8a3234 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rl_games/train_rl_games.py @@ -0,0 +1,201 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""RL-Games training logic for the unified reinforcement learning entrypoint.""" + +from __future__ import annotations + +import argparse +import contextlib +import logging +import math +import os +import random +import time +from datetime import datetime +from distutils.util import strtobool + +from common import ( + add_common_train_args, + add_isaaclab_launcher_args, + apply_env_overrides, + configure_io_descriptors, + create_isaaclab_env, + dump_train_configs, + enable_cameras_for_video, + set_hydra_args, + validate_distributed_device, + wrap_record_video, +) + +import isaaclab_tasks # noqa: F401 + +logger = logging.getLogger(__name__) + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + + +def _parse_args(argv: list[str]) -> argparse.Namespace: + """Parse RL-Games training arguments.""" + parser = argparse.ArgumentParser(description="Train an RL agent with RL-Games.") + add_common_train_args( + parser, + agent_default="rl_games_cfg_entry_point", + agent_help="Name of the RL agent configuration entry point.", + ) + parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint.") + parser.add_argument("--sigma", type=str, default=None, help="The policy's initial standard deviation.") + parser.add_argument("--wandb-project-name", type=str, default=None, help="the wandb's project name") + parser.add_argument("--wandb-entity", type=str, default=None, help="the entity (team) of wandb's project") + parser.add_argument("--wandb-name", type=str, default=None, help="the name of wandb's run") + parser.add_argument( + "--track", + type=lambda x: bool(strtobool(x)), + default=False, + nargs="?", + const=True, + help="if toggled, this experiment will be tracked with Weights and Biases", + ) + from isaaclab_tasks.utils import setup_preset_cli + + add_isaaclab_launcher_args(parser) + # setup_preset_cli registers preset-selection help text + runs parse_known_args; the + # physics=/renderer=/presets= tokens pass through the remainder for hydra to parse later. + args_cli, hydra_args = setup_preset_cli(parser, argv) + enable_cameras_for_video(args_cli) + set_hydra_args(hydra_args) + return args_cli + + +def run(argv: list[str]) -> None: + """Train an RL-Games agent.""" + from rl_games.common import env_configurations, vecenv + from rl_games.common.algo_observer import IsaacAlgoObserver + from rl_games.torch_runner import Runner + + from isaaclab.envs import DirectMARLEnvCfg + from isaaclab.utils.assets import retrieve_file_path + + from isaaclab_rl.rl_games import MultiObserver, PbtAlgoObserver, RlGamesGpuEnv, RlGamesVecEnvWrapper + + from isaaclab_tasks.utils import launch_simulation, resolve_task_config + + args_cli = _parse_args(argv) + env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent) + + with launch_simulation(env_cfg, args_cli): + apply_env_overrides(args_cli, env_cfg) + validate_distributed_device(args_cli) + + if args_cli.seed == -1: + args_cli.seed = random.randint(0, 10000) + + agent_cfg["params"]["seed"] = args_cli.seed if args_cli.seed is not None else agent_cfg["params"]["seed"] + agent_cfg["params"]["config"]["max_epochs"] = ( + args_cli.max_iterations + if args_cli.max_iterations is not None + else agent_cfg["params"]["config"]["max_epochs"] + ) + if args_cli.checkpoint is not None: + resume_path = retrieve_file_path(args_cli.checkpoint) + agent_cfg["params"]["load_checkpoint"] = True + agent_cfg["params"]["load_path"] = resume_path + print(f"[INFO]: Loading model checkpoint from: {agent_cfg['params']['load_path']}") + train_sigma = float(args_cli.sigma) if args_cli.sigma is not None else None + + if args_cli.distributed: + agent_cfg["params"]["seed"] += int(os.getenv("RANK", "0")) + agent_cfg["params"]["config"]["device"] = env_cfg.sim.device + agent_cfg["params"]["config"]["device_name"] = env_cfg.sim.device + agent_cfg["params"]["config"]["multi_gpu"] = True + + env_cfg.seed = agent_cfg["params"]["seed"] + + config_name = agent_cfg["params"]["config"]["name"] + log_root_path = os.path.join("logs", "rl_games", config_name) + if "pbt" in agent_cfg and agent_cfg["pbt"]["directory"] != ".": + log_root_path = os.path.join(agent_cfg["pbt"]["directory"], log_root_path) + else: + log_root_path = os.path.abspath(log_root_path) + + print(f"[INFO] Logging experiment in directory: {log_root_path}") + log_dir = agent_cfg["params"]["config"].get( + "full_experiment_name", datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ) + agent_cfg["params"]["config"]["train_dir"] = log_root_path + agent_cfg["params"]["config"]["full_experiment_name"] = log_dir + wandb_project = config_name if args_cli.wandb_project_name is None else args_cli.wandb_project_name + experiment_name = log_dir if args_cli.wandb_name is None else args_cli.wandb_name + + run_log_dir = os.path.join(log_root_path, log_dir) + dump_train_configs(run_log_dir, env_cfg, agent_cfg) + print(f"Exact experiment name requested from command line: {run_log_dir}") + + rl_device = agent_cfg["params"]["config"]["device"] + clip_obs = agent_cfg["params"]["env"].get("clip_observations", math.inf) + clip_actions = agent_cfg["params"]["env"].get("clip_actions", math.inf) + obs_groups = agent_cfg["params"]["env"].get("obs_groups") + concate_obs_groups = agent_cfg["params"]["env"].get("concate_obs_groups", True) + + configure_io_descriptors(env_cfg, args_cli, logger) + env_cfg.log_dir = run_log_dir + + env = create_isaaclab_env( + args_cli.task, + env_cfg, + args_cli, + convert_marl_to_single_agent=isinstance(env_cfg, DirectMARLEnvCfg), + ) + env = wrap_record_video(env, run_log_dir, args_cli) + + start_time = time.time() + env = RlGamesVecEnvWrapper(env, rl_device, clip_obs, clip_actions, obs_groups, concate_obs_groups) + + vecenv.register( + "IsaacRlgWrapper", + lambda config_name, num_actors, **kwargs: RlGamesGpuEnv(config_name, num_actors, **kwargs), + ) + env_configurations.register("rlgpu", {"vecenv_type": "IsaacRlgWrapper", "env_creator": lambda **kwargs: env}) + + agent_cfg["params"]["config"]["num_actors"] = env.unwrapped.num_envs + + if "pbt" in agent_cfg and agent_cfg["pbt"]["enabled"]: + observers = MultiObserver([IsaacAlgoObserver(), PbtAlgoObserver(agent_cfg, args_cli)]) + runner = Runner(observers) + else: + runner = Runner(IsaacAlgoObserver()) + + runner.load(agent_cfg) + runner.reset() + + global_rank = int(os.getenv("RANK", "0")) + if args_cli.track and global_rank == 0: + if args_cli.wandb_entity is None: + raise ValueError("Weights and Biases entity must be specified for tracking.") + import wandb + + wandb.init( + project=wandb_project, + entity=args_cli.wandb_entity, + name=experiment_name, + sync_tensorboard=True, + monitor_gym=True, + save_code=True, + ) + if not wandb.run.resumed: + wandb.config.update({"env_cfg": env_cfg.to_dict()}) + wandb.config.update({"agent_cfg": agent_cfg}) + + try: + if args_cli.checkpoint is not None: + runner.run({"train": True, "play": False, "sigma": train_sigma, "checkpoint": resume_path}) + else: + runner.run({"train": True, "play": False, "sigma": train_sigma}) + print(f"Training time: {round(time.time() - start_time, 2)} seconds") + env.close() + except KeyboardInterrupt: + pass diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/README.md b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/README.md new file mode 100644 index 0000000000000000000000000000000000000000..725079782f97d5a4150c299caaf12a79938743e2 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/README.md @@ -0,0 +1,305 @@ +# RLinf Integration for IsaacLab + +This module integrates [RLinf](https://github.com/RLinf/RLinf.git)'s distributed RL training framework with IsaacLab, enabling **reinforcement learning fine-tuning of Vision-Language-Action (VLA) models** (e.g., GR00T, OpenVLA) on IsaacLab simulation tasks. + +## Overview + +RLinf is a flexible and scalable open-source RL infrastructure designed for Embodied and Agentic AI. This integration allows IsaacLab users to: + +- Fine-tune pretrained VLA models on IsaacLab tasks using PPO / Actor-Critic / SAC +- Leverage RLinf's FSDP-based distributed training across multiple GPUs/nodes +- Define observation/action mappings from IsaacLab to GR00T format via a single YAML config +- Register IsaacLab tasks into RLinf without modifying RLinf source code + +## Architecture + +``` +┌────────────────────────────────────────────────────────────────┐ +│ RLinf Runner │ +│ (EmbodiedRunner / EvalRunner) │ +├────────────────┬──────────────────────┬────────────────────────┤ +│ Actor Worker │ Rollout Worker │ Env Worker │ +│ (FSDP) │ (HF Inference) │ (IsaacLab Sim) │ +│ │ │ │ +│ Policy │ Multi-step rollout │ IsaacLabGenericEnv │ +│ Update │ with VLA model │ ├─ _make_env_function │ +│ │ │ ├─ _wrap_obs │ +│ │ │ └─ _wrap_action │ +└────────────────┴──────────────────────┴────────────────────────┘ +``` + +**Data flow:** +1. `EnvWorker` runs IsaacLab simulation and converts observations to RLinf format +2. `RolloutWorker` runs VLA model inference (e.g., GR00T) to produce actions +3. Actions are converted back to IsaacLab format and stepped in the environment +4. `ActorWorker` updates the VLA model with PPO/actor-critic loss via FSDP + +## Directory Structure + +``` +scripts/reinforcement_learning/rlinf/ +├── README.md # This file +├── train.py # Training entry point (launches RLinf distributed training) +├── play.py # Evaluation entry point (launches RLinf eval runner) +└── cli_args.py # Shared CLI argument definitions +``` + +**Extension module** (in `source/isaaclab_contrib/`): + +``` +source/isaaclab_contrib/isaaclab_contrib/rl/rlinf/ +├── __init__.py +└── extension.py # RLinf extension: task registration, obs/action conversion +``` + +**Task-specific config** (in `source/isaaclab_tasks/`): + +``` +source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/assemble_trocar/ +├── config/ +│ └── isaaclab_ppo_gr00t_assemble_trocar.yaml # Single YAML config (Hydra) +└── g129_dex3_env_cfg.py # IsaacLab environment config +``` + +## Prerequisites + +- **IsaacLab** installed and configured +- **RLinf** available in the parent directory (expected at `../` relative to IsaacLab root, overridable via `RLINF_ROOT`) +- **GR00T** model and Isaac-GR00T repo (for VLA inference and data transforms) +- A **pretrained VLA checkpoint** in HuggingFace format +- Multi-GPU setup recommended (FSDP requires at least 1 GPU) + +## Quick Start + +### Training + +```bash +# Basic training (uses default config) +python train.py + +# Training with a specific config +python train.py --config_name isaaclab_ppo_gr00t_assemble_trocar + +# Training with task override +python train.py --task Isaac-Assemble-Trocar-G129-Dex3-v0 + +# Training with custom settings +python train.py --num_envs 64 --max_epochs 1000 + +# List available tasks +python train.py --list_tasks +``` + +### Evaluation + +```bash +# Evaluate a trained checkpoint +python play.py --task Isaac-Assemble-Trocar-G129-Dex3-Eval-v0 --model_path /path/to/checkpoint + +# Evaluate with video recording +python play.py --task Isaac-Assemble-Trocar-G129-Dex3-Eval-v0 --model_path /path/to/checkpoint --video + +# Evaluate with specific number of environments +python play.py --task Isaac-Assemble-Trocar-G129-Dex3-Eval-v0 --model_path /path/to/checkpoint --num_envs 8 +``` + +## Configuration + +All configuration lives in a **single YAML file** loaded by [Hydra](https://hydra.cc/). By default, `train.py` and `play.py` use `isaaclab_ppo_gr00t_assemble_trocar.yaml`. Override with `--config_path` and `--config_name`. + +### Config Structure Overview + +```yaml +cluster: + num_nodes: 1 + component_placement: + actor,env,rollout: all # Co-locate all workers + +runner: + max_epochs: 1000 + logger: + logger_backends: ["tensorboard"] # Options: tensorboard, wandb, swanlab + +algorithm: + loss_type: actor_critic # Options: actor_critic, embodied_sac + update_epoch: 4 + clip_ratio_high: 0.2 + gamma: 0.99 + gae_lambda: 0.95 + +env: + train: + total_num_envs: 4 + max_episode_steps: 256 + init_params: + id: "Isaac-Assemble-Trocar-G129-Dex3-v0" + isaaclab: &isaaclab_config # IsaacLab ↔ RLinf mapping (see below) + ... + eval: + isaaclab: *isaaclab_config # Reuse via YAML anchor + +rollout: + backend: "huggingface" + model: + model_path: "/path/to/pretrained/model" + obs_converter_type: ${env.train.isaaclab.obs_converter_type} + embodiment_tag: ${env.train.isaaclab.embodiment_tag} + +actor: + training_backend: "fsdp" + micro_batch_size: 2 + global_batch_size: 4 + model: + obs_converter_type: ${env.train.isaaclab.obs_converter_type} + embodiment_tag: ${env.train.isaaclab.embodiment_tag} + optim: + lr: 5e-6 +``` + +### IsaacLab ↔ RLinf Observation/Action Mapping + +The `env.train.isaaclab` section defines how IsaacLab observations are converted to GR00T format. This is the key configuration block for adapting new tasks: + +```yaml +isaaclab: &isaaclab_config + # Task description for language conditioning + task_description: "assemble trocar from tray" + + # --- IsaacLab → RLinf observation mapping --- + main_images: "front_camera" # Single main camera → (B, H, W, C) + extra_view_images: # Extra cameras → (B, N, H, W, C) + - "left_wrist_camera" + - "right_wrist_camera" + states: # State specs with optional slicing + - key: "robot_joint_state" + slice: [15, 29] # Take indices 15..29 + - key: "robot_dex3_joint_state" # Full tensor (no slice) + + # --- RLinf → GR00T format conversion --- + gr00t_mapping: + video: + main_images: "video.room_view" + extra_view_images: + - "video.left_wrist_view" + - "video.right_wrist_view" + state: # Slice concatenated state into GR00T keys + - gr00t_key: "state.left_arm" + slice: [0, 7] + - gr00t_key: "state.right_arm" + slice: [7, 14] + - gr00t_key: "state.left_hand" + slice: [14, 21] + - gr00t_key: "state.right_hand" + slice: [21, 28] + + # --- GR00T → IsaacLab action conversion --- + action_mapping: + prefix_pad: 15 # Pad zeros for uncontrolled joints + suffix_pad: 0 + + # --- GR00T model configuration (single source of truth) --- + # Referenced by actor.model and rollout.model via Hydra ${} interpolation + obs_converter_type: "dex3" + embodiment_tag: "new_embodiment" + embodiment_tag_id: 31 + data_config_class: "gr00t_config:IsaacLabDataConfig" +``` + +## CLI Arguments + +### Common Arguments + +| Argument | Description | +|---|---| +| `--config_path` | Path to config directory (defaults to task config dir) | +| `--config_name` | Name of the Hydra config file (without `.yaml`) | +| `--task` | IsaacLab task ID (overrides YAML config if set) | +| `--num_envs` | Number of parallel environments | +| `--seed` | Random seed | +| `--model_path` | Path to pretrained VLA checkpoint | + +### Training-Specific + +| Argument | Description | +|---|---| +| `--max_epochs` | Maximum training epochs | +| `--resume_dir` | Directory to resume training from | +| `--only_eval` | Run evaluation only (no training) | +| `--list_tasks` | List available tasks and exit | + +### Evaluation-Specific + +| Argument | Description | +|---|---| +| `--num_episodes` | Number of evaluation episodes | +| `--video` | Enable video recording | + +### Logger & Experiment + +| Argument | Description | +|---|---| +| `--logger` | Logger backend: `tensorboard`, `wandb`, or `swanlab` | +| `--experiment_name` | Experiment name for log directory | +| `--run_name` | Run name suffix | + +## Adding a New Task + +To add a new IsaacLab task for RLinf training: + +### 1. Create a YAML Config + +Create a new YAML config file (e.g., `isaaclab_ppo_gr00t_my_task.yaml`) in your task's `config/` directory. Use the existing `isaaclab_ppo_gr00t_assemble_trocar.yaml` as a template. + +Key sections to customize: + +- `env.train.init_params.id` — your task's gymnasium ID +- `env.train.isaaclab` — observation/action mapping for your embodiment +- `actor.model.model_path` / `rollout.model.model_path` — your pretrained checkpoint +- `actor.model.action_dim` — total action dimensions + +### 2. Create GR00T Data Config (if needed) + +If your embodiment differs from the default, create a new data config class in your config directory (e.g., `gr00t_config.py`): + +```python +class MyTaskDataConfig(BaseDataConfig): + video_keys = ["video.front_view"] + state_keys = ["state.arm"] + action_keys = ["action.arm"] + # ... define modality_config() and transform() +``` + +Reference it in your YAML config: + +```yaml +data_config_class: "gr00t_config:MyTaskDataConfig" +``` + +### 3. Register the Task + +The task is registered automatically at runtime via the extension module. Task IDs are read from `env.train.init_params.id` and `env.eval.init_params.id` in the YAML config. You can also override with `--task`. + +### 4. Run Training + +```bash +python train.py --config_path /path/to/your/config/dir \ + --config_name isaaclab_ppo_gr00t_my_task +``` + +## Logging + +Logs are saved to `logs/rlinf/-/` and include: + +- TensorBoard / WandB / SwanLab logs (based on `--logger`) +- Video recordings (when `--video` is enabled or `video_cfg.save_video: True`) +- Model checkpoints (saved every `save_interval` epochs) + +## Key Environment Variables + +These are set automatically by `train.py` / `play.py` — you typically do not need to set them manually: + +| Variable | Description | +|---|---| +| `RLINF_EXT_MODULE` | Extension module path (`isaaclab_contrib.rl.rlinf.extension`) | +| `RLINF_CONFIG_FILE` | Full path to the Hydra config YAML | +| `RLINF_ROOT` | (Optional) Override RLinf repo location (defaults to IsaacLab's parent directory) | diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/cli_args.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/cli_args.py new file mode 100644 index 0000000000000000000000000000000000000000..7a6ef544269be86d7a05004ab069817b6e37dd1d --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/cli_args.py @@ -0,0 +1,69 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Command line argument utilities for RLinf integration with IsaacLab.""" + +from __future__ import annotations + +import argparse +import importlib.util +from pathlib import Path + +_SCRIPT_DIR = str(Path(__file__).parent.absolute()) + + +def resolve_config_dir(config_name: str, explicit_path: str | None) -> str: + """Return the directory that contains ``.yaml``. + + Resolution order: + 1. *explicit_path* if provided (``--config_path``). + 2. Walk the ``isaaclab_tasks`` package tree looking for a matching YAML. + 3. Fall back to the script directory (``scripts/reinforcement_learning/rlinf/``). + """ + if explicit_path is not None: + return explicit_path + + spec = importlib.util.find_spec("isaaclab_tasks") + if spec is not None and spec.origin is not None: + tasks_root = Path(spec.origin).parent + matches = list(tasks_root.rglob(f"{config_name}.yaml")) + if matches: + return str(matches[0].parent) + + return _SCRIPT_DIR + + +def add_rlinf_args(parser: argparse.ArgumentParser) -> None: + """Add RLinf arguments to the parser. + + Args: + parser: The parser to add the arguments to. + """ + arg_group = parser.add_argument_group("rlinf", description="Arguments for RLinf agent.") + arg_group.add_argument( + "--config_path", + type=str, + default=None, + help=( + "Path to the RLinf configuration directory (for Hydra). " + "If omitted, the isaaclab_tasks package is searched automatically." + ), + ) + arg_group.add_argument( + "--config_name", + type=str, + default=None, + help="Name of the RLinf configuration file (without .yaml extension).", + ) + arg_group.add_argument("--resume_dir", type=str, default=None, help="Directory to resume training from.") + arg_group.add_argument( + "--rl_model_path", + type=str, + default=None, + help="Path to an RLinf checkpoint directory containing full_weights.pt.", + ) + arg_group.add_argument( + "--only_eval", action="store_true", default=False, help="Only run evaluation without training." + ) diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/play.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/play.py new file mode 100644 index 0000000000000000000000000000000000000000..583a5530d4a1ce08898a849156d7cfe0961c6a99 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/play.py @@ -0,0 +1,193 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to evaluate a trained RLinf agent. + +This script runs evaluation using RLinf's distributed infrastructure, +which is required for VLA model inference. + +Usage: + # Evaluate a trained checkpoint (config YAML in the same directory as play.py) + python play.py --config_name isaaclab_ppo_gr00t_assemble_trocar \\ + --model_path /path/to/checkpoint + + # Evaluate with config YAML in a custom directory + python play.py --config_path /path/to/config/dir \\ + --config_name isaaclab_ppo_gr00t_assemble_trocar --model_path /path/to/checkpoint + + # Evaluate with video recording + python play.py --config_name isaaclab_ppo_gr00t_assemble_trocar \\ + --model_path /path/to/checkpoint --video + +Note: + Evaluation requires the full RLinf infrastructure since VLA models + are too large to run on a single GPU without FSDP. +""" + +import warnings + +warnings.warn( + "scripts/reinforcement_learning/rlinf/play.py is deprecated. Use " + "`./isaaclab.sh play --rl_library rlinf --config_name ` instead. " + "Example: `./isaaclab.sh play --rl_library rlinf " + "--config_name isaaclab_ppo_gr00t_assemble_trocar`.", + DeprecationWarning, + stacklevel=1, +) + +import argparse +import logging +import os +from datetime import datetime +from pathlib import Path + +SCRIPT_DIR = Path(__file__).parent.absolute() +# required for RLinf to register IsaacLab tasks and converters +os.environ.setdefault("RLINF_EXT_MODULE", "isaaclab_contrib.rl.rlinf.extension") + +# local imports +import cli_args # noqa: E402 # isort: skip + +# add argparse arguments +parser = argparse.ArgumentParser(description="Evaluate a trained RLinf agent.") +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 (overrides YAML config if set).") +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment (overrides config if set)") +parser.add_argument( + "--model_path", type=str, default=None, help="Path to the model checkpoint (optional, can be set in config)." +) +parser.add_argument( + "--num_episodes", type=int, default=None, help="Number of evaluation episodes (overrides config if set)." +) +parser.add_argument("--video", action="store_true", default=False, help="Enable video recording.") +cli_args.add_rlinf_args(parser) +args_cli = parser.parse_args() + +# Resolve config path and name from CLI args +if not args_cli.config_name: + parser.error("--config_name is required (e.g. --config_name isaaclab_ppo_gr00t_assemble_trocar)") +config_name = args_cli.config_name +config_dir = cli_args.resolve_config_dir(config_name, args_cli.config_path) +os.environ["RLINF_CONFIG_FILE"] = str(Path(config_dir) / f"{config_name}.yaml") + +# Add config dir to PYTHONPATH so that Ray rollout workers can resolve +# data_config_class references like "gr00t_config:IsaacLabDataConfig" +if config_dir not in os.environ.get("PYTHONPATH", ""): + os.environ["PYTHONPATH"] = config_dir + os.pathsep + os.environ.get("PYTHONPATH", "") + + +"""launch RLinf evaluation.""" +import rlinf # noqa: F401 +import torch.multiprocessing as mp # noqa: E402 +from hydra import compose, initialize_config_dir # noqa: E402 +from hydra.core.global_hydra import GlobalHydra # noqa: E402 +from omegaconf import open_dict # noqa: E402 +from rlinf.config import validate_cfg # noqa: E402 +from rlinf.runners.embodied_eval_runner import EmbodiedEvalRunner # noqa: E402 +from rlinf.scheduler import Cluster # noqa: E402 +from rlinf.utils.placement import HybridComponentPlacement # noqa: E402 +from rlinf.workers.env.env_worker import EnvWorker # noqa: E402 +from rlinf.workers.rollout.hf.huggingface_worker import MultiStepRolloutWorker # noqa: E402 + +logger = logging.getLogger(__name__) + +mp.set_start_method("spawn", force=True) + + +def main(): + """Launch RLinf evaluation.""" + print(f"[INFO] Using config: {config_name}") + print(f"[INFO] Config path: {config_dir}") + + # Initialize Hydra and load config + GlobalHydra.instance().clear() + initialize_config_dir(config_dir=config_dir, version_base="1.1") + cfg = compose(config_name=config_name) + + # Get task_id from config (eval task) + task_id = cfg.env.eval.init_params.id + print(f"[INFO] Task: {task_id}") + + # Setup logging directory + # Use hyphens instead of colons in time — colons are invalid in Windows paths. + timestamp = datetime.now().strftime("%Y%m%d-%H-%M-%S") + log_dir = SCRIPT_DIR / "logs" / "rlinf" / "eval" / f"{timestamp}-{task_id.replace('/', '_')}" + log_dir.mkdir(parents=True, exist_ok=True) + print(f"[INFO] Logging to: {log_dir}") + + # Apply runtime overrides + with open_dict(cfg): + # Set evaluation mode + cfg.runner.only_eval = True + # Set logging + cfg.runner.logger.log_path = str(log_dir) + + # Override checkpoint if provided via CLI + if args_cli.model_path: + cfg.rollout.model.model_path = args_cli.model_path + if args_cli.rl_model_path: + cfg.rollout.model.rl_model_path = args_cli.rl_model_path + + # Enable video saving if requested + if args_cli.video: + cfg.env.eval.video_cfg.save_video = True + cfg.env.eval.video_cfg.video_base_dir = str(log_dir / "videos") + + # Override task if provided via CLI + if args_cli.task: + cfg.env.eval.init_params.id = args_cli.task + cfg.env.train.init_params.id = args_cli.task + + # Apply CLI args + if args_cli.num_envs is not None: + cfg.env.eval.total_num_envs = args_cli.num_envs + if args_cli.seed is not None: + cfg.actor.seed = args_cli.seed + if args_cli.num_episodes is not None: + cfg.algorithm.eval_rollout_epoch = args_cli.num_episodes + + # Validate config + cfg = validate_cfg(cfg) + + # Print config summary + print("\n" + "=" * 60) + print("RLinf Evaluation Configuration") + print("=" * 60) + print(f" Task: {cfg.env.eval.init_params.id}") + print(f" Num envs: {cfg.env.eval.total_num_envs}") + print(f" Model: {cfg.rollout.model.model_path}") + print(f" Videos: {cfg.env.eval.video_cfg.save_video}") + if cfg.env.eval.video_cfg.save_video: + print(f" Video dir: {cfg.env.eval.video_cfg.video_base_dir}") + print(f" Log dir: {log_dir}") + print("=" * 60 + "\n") + + # Create cluster and workers + cluster = Cluster(cluster_cfg=cfg.cluster) + component_placement = HybridComponentPlacement(cfg, cluster) + + # Create rollout worker + rollout_placement = component_placement.get_strategy("rollout") + rollout_group = MultiStepRolloutWorker.create_group(cfg).launch( + cluster, name=cfg.rollout.group_name, placement_strategy=rollout_placement + ) + + # Create env worker + env_placement = component_placement.get_strategy("env") + env_group = EnvWorker.create_group(cfg).launch(cluster, name=cfg.env.group_name, placement_strategy=env_placement) + + # Run evaluation + runner = EmbodiedEvalRunner( + cfg=cfg, + rollout=rollout_group, + env=env_group, + ) + + runner.init_workers() + runner.run() + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/play_rlinf.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/play_rlinf.py new file mode 100644 index 0000000000000000000000000000000000000000..5cd634fbf9d61221581100a5a020e901a8c6c277 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/play_rlinf.py @@ -0,0 +1,180 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to evaluate a trained RLinf agent. + +This script runs evaluation using RLinf's distributed infrastructure, +which is required for VLA model inference. + +Usage: + # Evaluate a trained checkpoint (config YAML in the same directory as play.py) + ./isaaclab.sh play --rl_library rlinf --config_name isaaclab_ppo_gr00t_assemble_trocar \\ + --model_path /path/to/checkpoint + + # Evaluate with config YAML in a custom directory + ./isaaclab.sh play --rl_library rlinf --config_path /path/to/config/dir \\ + --config_name isaaclab_ppo_gr00t_assemble_trocar --model_path /path/to/checkpoint + + # Evaluate with video recording + ./isaaclab.sh play --rl_library rlinf --config_name isaaclab_ppo_gr00t_assemble_trocar \\ + --model_path /path/to/checkpoint --video + +Note: + Evaluation requires the full RLinf infrastructure since VLA models + are too large to run on a single GPU without FSDP. +""" + +import argparse +import logging +import os +from datetime import datetime +from pathlib import Path + +SCRIPT_DIR = Path(__file__).parent.absolute() +# required for RLinf to register IsaacLab tasks and converters +os.environ.setdefault("RLINF_EXT_MODULE", "isaaclab_contrib.rl.rlinf.extension") + +# local imports +import cli_args # noqa: E402 # isort: skip + +# add argparse arguments +parser = argparse.ArgumentParser(description="Evaluate a trained RLinf agent.") +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 (overrides YAML config if set).") +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment (overrides config if set)") +parser.add_argument( + "--model_path", type=str, default=None, help="Path to the model checkpoint (optional, can be set in config)." +) +parser.add_argument( + "--num_episodes", type=int, default=None, help="Number of evaluation episodes (overrides config if set)." +) +parser.add_argument("--video", action="store_true", default=False, help="Enable video recording.") +cli_args.add_rlinf_args(parser) +args_cli = parser.parse_args() + +# Resolve config path and name from CLI args +if not args_cli.config_name: + parser.error("--config_name is required (e.g. --config_name isaaclab_ppo_gr00t_assemble_trocar)") +config_name = args_cli.config_name +config_dir = cli_args.resolve_config_dir(config_name, args_cli.config_path) +os.environ["RLINF_CONFIG_FILE"] = str(Path(config_dir) / f"{config_name}.yaml") + +# Add config dir to PYTHONPATH so that Ray rollout workers can resolve +# data_config_class references like "gr00t_config:IsaacLabDataConfig" +if config_dir not in os.environ.get("PYTHONPATH", ""): + os.environ["PYTHONPATH"] = config_dir + os.pathsep + os.environ.get("PYTHONPATH", "") + + +"""launch RLinf evaluation.""" +import rlinf # noqa: F401 +import torch.multiprocessing as mp # noqa: E402 +from hydra import compose, initialize_config_dir # noqa: E402 +from hydra.core.global_hydra import GlobalHydra # noqa: E402 +from omegaconf import open_dict # noqa: E402 +from rlinf.config import validate_cfg # noqa: E402 +from rlinf.runners.embodied_eval_runner import EmbodiedEvalRunner # noqa: E402 +from rlinf.scheduler import Cluster # noqa: E402 +from rlinf.utils.placement import HybridComponentPlacement # noqa: E402 +from rlinf.workers.env.env_worker import EnvWorker # noqa: E402 +from rlinf.workers.rollout.hf.huggingface_worker import MultiStepRolloutWorker # noqa: E402 + +logger = logging.getLogger(__name__) + +mp.set_start_method("spawn", force=True) + + +def main(): + """Launch RLinf evaluation.""" + print(f"[INFO] Using config: {config_name}") + print(f"[INFO] Config path: {config_dir}") + + # Initialize Hydra and load config + GlobalHydra.instance().clear() + initialize_config_dir(config_dir=config_dir, version_base="1.1") + cfg = compose(config_name=config_name) + + # Get task_id from config (eval task) + task_id = cfg.env.eval.init_params.id + print(f"[INFO] Task: {task_id}") + + # Setup logging directory + # Use hyphens instead of colons in time — colons are invalid in Windows paths. + timestamp = datetime.now().strftime("%Y%m%d-%H-%M-%S") + log_dir = SCRIPT_DIR / "logs" / "rlinf" / "eval" / f"{timestamp}-{task_id.replace('/', '_')}" + log_dir.mkdir(parents=True, exist_ok=True) + print(f"[INFO] Logging to: {log_dir}") + + # Apply runtime overrides + with open_dict(cfg): + # Set evaluation mode + cfg.runner.only_eval = True + # Set logging + cfg.runner.logger.log_path = str(log_dir) + + # Override checkpoint if provided via CLI + if args_cli.model_path: + cfg.rollout.model.model_path = args_cli.model_path + + # Enable video saving if requested + if args_cli.video: + cfg.env.eval.video_cfg.save_video = True + cfg.env.eval.video_cfg.video_base_dir = str(log_dir / "videos") + + # Override task if provided via CLI + if args_cli.task: + cfg.env.eval.init_params.id = args_cli.task + cfg.env.train.init_params.id = args_cli.task + + # Apply CLI args + if args_cli.num_envs is not None: + cfg.env.eval.total_num_envs = args_cli.num_envs + if args_cli.seed is not None: + cfg.actor.seed = args_cli.seed + if args_cli.num_episodes is not None: + cfg.algorithm.eval_rollout_epoch = args_cli.num_episodes + + # Validate config + cfg = validate_cfg(cfg) + + # Print config summary + print("\n" + "=" * 60) + print("RLinf Evaluation Configuration") + print("=" * 60) + print(f" Task: {cfg.env.eval.init_params.id}") + print(f" Num envs: {cfg.env.eval.total_num_envs}") + print(f" Model: {cfg.rollout.model.model_path}") + print(f" Videos: {cfg.env.eval.video_cfg.save_video}") + if cfg.env.eval.video_cfg.save_video: + print(f" Video dir: {cfg.env.eval.video_cfg.video_base_dir}") + print(f" Log dir: {log_dir}") + print("=" * 60 + "\n") + + # Create cluster and workers + cluster = Cluster(cluster_cfg=cfg.cluster) + component_placement = HybridComponentPlacement(cfg, cluster) + + # Create rollout worker + rollout_placement = component_placement.get_strategy("rollout") + rollout_group = MultiStepRolloutWorker.create_group(cfg).launch( + cluster, name=cfg.rollout.group_name, placement_strategy=rollout_placement + ) + + # Create env worker + env_placement = component_placement.get_strategy("env") + env_group = EnvWorker.create_group(cfg).launch(cluster, name=cfg.env.group_name, placement_strategy=env_placement) + + # Run evaluation + runner = EmbodiedEvalRunner( + cfg=cfg, + rollout=rollout_group, + env=env_group, + ) + + runner.init_workers() + runner.run() + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/train.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d16e3ddabed6da322f9e39243b3cd32725b8e992 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/train.py @@ -0,0 +1,220 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to train RL agent with RLinf. + +This script launches RLinf distributed training for IsaacLab tasks. +Tasks can be either: +1. Registered in IsaacLab with `rlinf_cfg_entry_point` - will be auto-registered into RLinf +2. Already registered in RLinf's REGISTER_ISAACLAB_ENVS + +Usage: + # Train an IsaacLab task (config YAML in the same directory as train.py) + python train.py --config_name isaaclab_ppo_gr00t_assemble_trocar + + # Train with config YAML in a custom directory + python train.py --config_path /path/to/config/dir \\ + --config_name isaaclab_ppo_gr00t_assemble_trocar + + # Train with task override and custom settings + python train.py --config_name isaaclab_ppo_gr00t_assemble_trocar \\ + --task Isaac-Assemble-Trocar-G129-Dex3-RLinf-v0 --num_envs 64 --max_epochs 1000 + +Note: + RLinf training requires a pretrained VLA model (e.g., GR00T, OpenVLA). + The model_path should point to a HuggingFace format checkpoint directory. +""" + +import warnings + +warnings.warn( + "scripts/reinforcement_learning/rlinf/train.py is deprecated. Use " + "`./isaaclab.sh train --rl_library rlinf --config_name ` instead. " + "Example: `./isaaclab.sh train --rl_library rlinf " + "--config_name isaaclab_ppo_gr00t_assemble_trocar`.", + DeprecationWarning, + stacklevel=1, +) + +import argparse +import logging +import os +import sys +from datetime import datetime +from pathlib import Path + +SCRIPT_DIR = Path(__file__).parent.absolute() +# required for RLinf to register IsaacLab tasks and converters +os.environ.setdefault("RLINF_EXT_MODULE", "isaaclab_contrib.rl.rlinf.extension") + +# local imports +import cli_args # noqa: E402 # isort: skip + +# add argparse arguments +parser = argparse.ArgumentParser(description="Train an RL agent with RLinf.") +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 (overrides config if set)") +parser.add_argument("--max_epochs", type=int, default=None, help="RL Policy training iterations.") +parser.add_argument("--list_tasks", action="store_true", default=False, help="List all available tasks and exit.") +parser.add_argument("--model_path", type=str, default=None, help="Path to pretrained model checkpoint (required).") + +# append RLinf cli arguments +cli_args.add_rlinf_args(parser) +args_cli = parser.parse_args() + +# Resolve config path and name from CLI args +if not args_cli.config_name: + parser.error("--config_name is required (e.g. --config_name isaaclab_ppo_gr00t_assemble_trocar)") +config_name = args_cli.config_name +config_dir = cli_args.resolve_config_dir(config_name, args_cli.config_path) +os.environ["RLINF_CONFIG_FILE"] = str(Path(config_dir) / f"{config_name}.yaml") + +# Add config dir to PYTHONPATH so that Ray rollout workers can resolve +# data_config_class references like "gr00t_config:IsaacLabDataConfig" +if config_dir not in os.environ.get("PYTHONPATH", ""): + os.environ["PYTHONPATH"] = config_dir + os.pathsep + os.environ.get("PYTHONPATH", "") + +# Handle --list_tasks before any heavy imports +if args_cli.list_tasks: + print("\n" + "=" * 60) + print("Available RLinf Tasks") + print("=" * 60) + + # List RLinf registered tasks + print("\n[RLinf Registered Tasks]") + try: + from rlinf.envs.isaaclab import REGISTER_ISAACLAB_ENVS + + for task_id in sorted(REGISTER_ISAACLAB_ENVS.keys()): + print(f" - {task_id}") + except ImportError: + print(" (Could not import RLinf registry)") + + print("\n" + "=" * 60) + sys.exit(0) + +"""Rest of the script - launch RLinf training.""" +import rlinf # noqa: F401 +import torch.multiprocessing as mp # noqa: E402 +from hydra import compose, initialize_config_dir # noqa: E402 +from hydra.core.global_hydra import GlobalHydra # noqa: E402 +from omegaconf import open_dict # noqa: E402 +from rlinf.config import validate_cfg # noqa: E402 +from rlinf.runners.embodied_runner import EmbodiedRunner # noqa: E402 +from rlinf.scheduler import Cluster # noqa: E402 +from rlinf.utils.placement import HybridComponentPlacement # noqa: E402 +from rlinf.workers.env.env_worker import EnvWorker # noqa: E402 +from rlinf.workers.rollout.hf.huggingface_worker import MultiStepRolloutWorker # noqa: E402 + +logger = logging.getLogger(__name__) + +mp.set_start_method("spawn", force=True) + + +def main(): + """Launch RLinf training.""" + print(f"[INFO] Using config: {config_name}") + print(f"[INFO] Config path: {config_dir}") + + # Initialize Hydra and load config + GlobalHydra.instance().clear() + initialize_config_dir(config_dir=config_dir, version_base="1.1") + cfg = compose(config_name=config_name) + + # Get task_id from config + task_id = cfg.env.train.init_params.id + print(f"[INFO] Task: {task_id}") + + # Setup logging directory + # Use hyphens instead of colons in time — colons are invalid in Windows paths. + timestamp = datetime.now().strftime("%Y%m%d-%H-%M-%S") + log_dir = SCRIPT_DIR / "logs" / "rlinf" / f"{timestamp}-{task_id.replace('/', '_')}" + log_dir.mkdir(parents=True, exist_ok=True) + print(f"[INFO] Logging to: {log_dir}") + + # Apply runtime overrides from CLI arguments + with open_dict(cfg): + cfg.runner.logger.log_path = str(log_dir) + + # Override task if provided via CLI + if args_cli.task: + cfg.env.train.init_params.id = args_cli.task + cfg.env.eval.init_params.id = args_cli.task + + # Override from CLI if provided + if args_cli.num_envs is not None: + cfg.env.train.total_num_envs = args_cli.num_envs + cfg.env.eval.total_num_envs = args_cli.num_envs + if args_cli.seed is not None: + cfg.actor.seed = args_cli.seed + if args_cli.max_epochs is not None: + cfg.runner.max_epochs = args_cli.max_epochs + if args_cli.model_path is not None: + cfg.actor.model.model_path = args_cli.model_path + cfg.rollout.model.model_path = args_cli.model_path + if args_cli.only_eval: + cfg.runner.only_eval = True + if args_cli.resume_dir: + cfg.runner.resume_dir = args_cli.resume_dir + + # Validate config + cfg = validate_cfg(cfg) + + # Print config summary + print("\n" + "=" * 60) + print("RLinf Training Configuration") + print("=" * 60) + print(f" Task: {cfg.env.train.init_params.id}") + print(f" Num envs: {cfg.env.train.total_num_envs}") + print(f" Max epochs: {cfg.runner.max_epochs}") + print(f" Model: {cfg.actor.model.model_path}") + print(f" Algorithm: {cfg.algorithm.loss_type}") + print(f" Log dir: {log_dir}") + print("=" * 60 + "\n") + + # Create cluster and component placement + cluster = Cluster(cluster_cfg=cfg.cluster) + component_placement = HybridComponentPlacement(cfg, cluster) + + # Create actor worker + actor_placement = component_placement.get_strategy("actor") + if cfg.algorithm.loss_type == "embodied_sac": + from rlinf.workers.actor.fsdp_sac_policy_worker import EmbodiedSACFSDPPolicy + + actor_worker_cls = EmbodiedSACFSDPPolicy + else: + from rlinf.workers.actor.fsdp_actor_worker import EmbodiedFSDPActor + + actor_worker_cls = EmbodiedFSDPActor + + actor_group = actor_worker_cls.create_group(cfg).launch( + cluster, name=cfg.actor.group_name, placement_strategy=actor_placement + ) + + # Create rollout worker + rollout_placement = component_placement.get_strategy("rollout") + rollout_group = MultiStepRolloutWorker.create_group(cfg).launch( + cluster, name=cfg.rollout.group_name, placement_strategy=rollout_placement + ) + + # Create env worker + env_placement = component_placement.get_strategy("env") + env_group = EnvWorker.create_group(cfg).launch(cluster, name=cfg.env.group_name, placement_strategy=env_placement) + + # Create and run training + runner = EmbodiedRunner( + cfg=cfg, + actor=actor_group, + rollout=rollout_group, + env=env_group, + ) + + runner.init_workers() + runner.run() + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/train_rlinf.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/train_rlinf.py new file mode 100644 index 0000000000000000000000000000000000000000..2389ab186fe4eca77620d5f6c18217cbf3e5cb52 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rlinf/train_rlinf.py @@ -0,0 +1,178 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""RLinf training logic for the unified reinforcement learning entrypoint.""" + +from __future__ import annotations + +import argparse +import logging +import os +from datetime import datetime +from pathlib import Path + +from common import import_local_module + +logger = logging.getLogger(__name__) + +RL_ROOT = Path(__file__).resolve().parents[1] +RLINF_DIR = RL_ROOT / "rlinf" +CLI_ARGS = import_local_module("isaaclab_rlinf_cli_args", RLINF_DIR / "cli_args.py") + + +def _parse_args(argv: list[str]) -> argparse.Namespace: + """Parse RLinf training arguments.""" + parser = argparse.ArgumentParser(description="Train an RL agent with RLinf.") + 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 (overrides config if set)", + ) + parser.add_argument("--max_epochs", type=int, default=None, help="RL Policy training iterations.") + parser.add_argument("--list_tasks", action="store_true", default=False, help="List all available tasks and exit.") + parser.add_argument("--model_path", type=str, default=None, help="Path to pretrained model checkpoint (required).") + CLI_ARGS.add_rlinf_args(parser) + args_cli = parser.parse_args(argv) + if not args_cli.list_tasks and not args_cli.config_name: + parser.error("--config_name is required (e.g. --config_name isaaclab_ppo_gr00t_assemble_trocar)") + return args_cli + + +def _list_tasks() -> None: + """List available RLinf tasks.""" + print("\n" + "=" * 60) + print("Available RLinf Tasks") + print("=" * 60) + + print("\n[RLinf Registered Tasks]") + try: + from rlinf.envs.isaaclab import REGISTER_ISAACLAB_ENVS + + for task_id in sorted(REGISTER_ISAACLAB_ENVS.keys()): + print(f" - {task_id}") + except ImportError: + print(" (Could not import RLinf registry)") + + print("\n" + "=" * 60) + + +def run(argv: list[str]) -> None: + """Launch RLinf training.""" + os.environ.setdefault("RLINF_EXT_MODULE", "isaaclab_contrib.rl.rlinf.extension") + args_cli = _parse_args(argv) + + if args_cli.list_tasks: + _list_tasks() + return + + config_name = args_cli.config_name + config_dir = CLI_ARGS.resolve_config_dir(config_name, args_cli.config_path) + os.environ["RLINF_CONFIG_FILE"] = str(Path(config_dir) / f"{config_name}.yaml") + + if config_dir not in os.environ.get("PYTHONPATH", ""): + os.environ["PYTHONPATH"] = config_dir + os.pathsep + os.environ.get("PYTHONPATH", "") + + import rlinf # noqa: F401 + import torch.multiprocessing as mp + from hydra import compose, initialize_config_dir + from hydra.core.global_hydra import GlobalHydra + from omegaconf import open_dict + from rlinf.config import validate_cfg + from rlinf.runners.embodied_runner import EmbodiedRunner + from rlinf.scheduler import Cluster + from rlinf.utils.placement import HybridComponentPlacement + from rlinf.workers.env.env_worker import EnvWorker + from rlinf.workers.rollout.hf.huggingface_worker import MultiStepRolloutWorker + + mp.set_start_method("spawn", force=True) + + print(f"[INFO] Using config: {config_name}") + print(f"[INFO] Config path: {config_dir}") + + GlobalHydra.instance().clear() + initialize_config_dir(config_dir=config_dir, version_base="1.1") + cfg = compose(config_name=config_name) + + task_id = cfg.env.train.init_params.id + print(f"[INFO] Task: {task_id}") + + # Use hyphens instead of colons in time — colons are invalid in Windows paths. + timestamp = datetime.now().strftime("%Y%m%d-%H-%M-%S") + log_dir = RLINF_DIR / "logs" / "rlinf" / f"{timestamp}-{task_id.replace('/', '_')}" + log_dir.mkdir(parents=True, exist_ok=True) + print(f"[INFO] Logging to: {log_dir}") + + with open_dict(cfg): + cfg.runner.logger.log_path = str(log_dir) + + if args_cli.task: + cfg.env.train.init_params.id = args_cli.task + cfg.env.eval.init_params.id = args_cli.task + + if args_cli.num_envs is not None: + cfg.env.train.total_num_envs = args_cli.num_envs + cfg.env.eval.total_num_envs = args_cli.num_envs + if args_cli.seed is not None: + cfg.actor.seed = args_cli.seed + if args_cli.max_epochs is not None: + cfg.runner.max_epochs = args_cli.max_epochs + if args_cli.model_path is not None: + cfg.actor.model.model_path = args_cli.model_path + cfg.rollout.model.model_path = args_cli.model_path + if args_cli.only_eval: + cfg.runner.only_eval = True + if args_cli.resume_dir: + cfg.runner.resume_dir = args_cli.resume_dir + + cfg = validate_cfg(cfg) + + print("\n" + "=" * 60) + print("RLinf Training Configuration") + print("=" * 60) + print(f" Task: {cfg.env.train.init_params.id}") + print(f" Num envs: {cfg.env.train.total_num_envs}") + print(f" Max epochs: {cfg.runner.max_epochs}") + print(f" Model: {cfg.actor.model.model_path}") + print(f" Algorithm: {cfg.algorithm.loss_type}") + print(f" Log dir: {log_dir}") + print("=" * 60 + "\n") + + cluster = Cluster(cluster_cfg=cfg.cluster) + component_placement = HybridComponentPlacement(cfg, cluster) + + actor_placement = component_placement.get_strategy("actor") + if cfg.algorithm.loss_type == "embodied_sac": + from rlinf.workers.actor.fsdp_sac_policy_worker import EmbodiedSACFSDPPolicy + + actor_worker_cls = EmbodiedSACFSDPPolicy + else: + from rlinf.workers.actor.fsdp_actor_worker import EmbodiedFSDPActor + + actor_worker_cls = EmbodiedFSDPActor + + actor_group = actor_worker_cls.create_group(cfg).launch( + cluster, name=cfg.actor.group_name, placement_strategy=actor_placement + ) + + rollout_placement = component_placement.get_strategy("rollout") + rollout_group = MultiStepRolloutWorker.create_group(cfg).launch( + cluster, name=cfg.rollout.group_name, placement_strategy=rollout_placement + ) + + env_placement = component_placement.get_strategy("env") + env_group = EnvWorker.create_group(cfg).launch(cluster, name=cfg.env.group_name, placement_strategy=env_placement) + + runner = EmbodiedRunner( + cfg=cfg, + actor=actor_group, + rollout=rollout_group, + env=env_group, + ) + + runner.init_workers() + runner.run() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/cli_args.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/cli_args.py new file mode 100644 index 0000000000000000000000000000000000000000..10edbe2e17f2352c8d4d5357018fb6245c040e85 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/cli_args.py @@ -0,0 +1,93 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import argparse +import random +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from isaaclab_rl.rsl_rl import RslRlBaseRunnerCfg + + +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", action="store_true", default=False, 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) -> RslRlBaseRunnerCfg: + """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 isaaclab_tasks.utils.parse_cfg import load_cfg_from_registry + + # load the default configuration + rslrl_cfg: RslRlBaseRunnerCfg = load_cfg_from_registry(task_name, "rsl_rl_cfg_entry_point") + rslrl_cfg = update_rsl_rl_cfg(rslrl_cfg, args_cli) + return rslrl_cfg + + +def update_rsl_rl_cfg(agent_cfg: RslRlBaseRunnerCfg, args_cli: argparse.Namespace): + """Update configuration for RSL-RL agent based on inputs. + + Args: + agent_cfg: The configuration for RSL-RL agent. + args_cli: The command line arguments. + + Returns: + The updated configuration for RSL-RL agent based on inputs. + """ + # override the default configuration with CLI arguments + if hasattr(args_cli, "seed") and args_cli.seed is not None: + # randomly sample a seed if seed = -1 + if args_cli.seed == -1: + args_cli.seed = random.randint(0, 10000) + agent_cfg.seed = args_cli.seed + if args_cli.resume is not None: + agent_cfg.resume = args_cli.resume + if args_cli.load_run is not None: + agent_cfg.load_run = args_cli.load_run + if args_cli.checkpoint is not None: + agent_cfg.load_checkpoint = args_cli.checkpoint + if args_cli.experiment_name is not None: + agent_cfg.experiment_name = args_cli.experiment_name + if args_cli.run_name is not None: + agent_cfg.run_name = args_cli.run_name + if args_cli.logger is not None: + agent_cfg.logger = args_cli.logger + # set the project name for wandb and neptune + if agent_cfg.logger in {"wandb", "neptune"} and args_cli.log_project_name: + agent_cfg.wandb_project = args_cli.log_project_name + agent_cfg.neptune_project = args_cli.log_project_name + + return agent_cfg diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/play.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/play.py new file mode 100644 index 0000000000000000000000000000000000000000..a033e2d7b2a0e6c556b9d6ae50e09a25621d825c --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/play.py @@ -0,0 +1,251 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to play a checkpoint if an RL agent from RSL-RL.""" + +import warnings + +warnings.warn( + "scripts/reinforcement_learning/rsl_rl/play.py is deprecated. Use " + "`./isaaclab.sh play --rl_library rsl_rl --task ` instead. " + "Example: `./isaaclab.sh play --rl_library rsl_rl --task Isaac-Cartpole-v0`.", + DeprecationWarning, + stacklevel=1, +) + +import argparse +import contextlib +import importlib.metadata as metadata +import os +import sys +import time + +import gymnasium as gym +import torch +from packaging import version +from rsl_rl.runners import DistillationRunner, OnPolicyRunner + +from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg +from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.dict import print_dict +from isaaclab.utils.seed import configure_seed +from isaaclab.utils.string import list_intersection, string_to_callable + +from isaaclab_rl.rsl_rl import ( + RslRlBaseRunnerCfg, + RslRlVecEnvWrapper, + export_policy_as_jit, + export_policy_as_onnx, + handle_deprecated_rsl_rl_cfg, +) +from isaaclab_rl.utils.pretrained_checkpoint import get_published_pretrained_checkpoint + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + get_checkpoint_path, + launch_simulation, + setup_preset_cli, +) +from isaaclab_tasks.utils.hydra import hydra_task_config + +# local imports +import cli_args # isort: skip + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + +# -- argparse ---------------------------------------------------------------- +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( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +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( + "--agent", type=str, default="rsl_rl_cfg_entry_point", help="Name of the RL agent configuration entry point." +) +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument( + "--use_pretrained_checkpoint", + action="store_true", + help="Use the pre-trained checkpoint from Nucleus.", +) +parser.add_argument("--real-time", action="store_true", default=False, help="Run in real-time, if possible.") +parser.add_argument("--external_callback", default=None, help="Fully qualified path to an externally defined callback.") +cli_args.add_rsl_rl_args(parser) +add_launcher_args(parser) +args_cli, remaining_args = setup_preset_cli(parser) + +if args_cli.video: + args_cli.enable_cameras = True + + +# Call an external callback if requested. This gives opportunity to external code to register the environments +# The function is expected to return a list of arguments that were not consumed by the callback. +remaining_args_env_registration = None +if args_cli.external_callback: + external_callback_function = string_to_callable(args_cli.external_callback, separator=".") + remaining_args_env_registration = external_callback_function() + +# clear out sys.argv for Hydra +# The remaining arguments are the arguments that were not consumed by both this scripts +# argparser and (optionally) the external callback function. Both sides of this +# intersection are pre-fold (the callback reads the user's original sys.argv), so +# preset tokens like ``physics=NAME`` compare correctly here. Fold runs after. +remaining_args = list_intersection(remaining_args, remaining_args_env_registration) +sys.argv = [sys.argv[0]] + remaining_args + +# Check for installed RSL-RL version +installed_version = metadata.version("rsl-rl-lib") + + +@hydra_task_config(args_cli.task, args_cli.agent) +def main(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agent_cfg: RslRlBaseRunnerCfg): + """Play with RSL-RL agent.""" + with launch_simulation(env_cfg, args_cli): + # grab task name for checkpoint path + task_name = args_cli.task.split(":")[-1] + train_task_name = task_name.replace("-Play", "") + + # override configurations with non-hydra CLI arguments + agent_cfg = cli_args.update_rsl_rl_cfg(agent_cfg, args_cli) + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + + # handle deprecated configurations + agent_cfg = handle_deprecated_rsl_rl_cfg(agent_cfg, installed_version) + + # set the environment seed + # note: certain randomizations occur in the environment initialization so we set the seed here + env_cfg.seed = agent_cfg.seed + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + # 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}") + if args_cli.use_pretrained_checkpoint: + resume_path = get_published_pretrained_checkpoint("rsl_rl", train_task_name) + if not resume_path: + print("[INFO] Unfortunately a pre-trained checkpoint is currently unavailable for this task.") + return + elif args_cli.checkpoint: + resume_path = retrieve_file_path(args_cli.checkpoint) + else: + resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) + + log_dir = os.path.dirname(resume_path) + + # set the log directory for the environment + env_cfg.log_dir = log_dir + + # create isaac environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + + # convert to single-agent instance if required by the RL algorithm + if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): + from isaaclab.envs import multi_agent_to_single_agent + + env = multi_agent_to_single_agent(env) + + # wrap for video recording + if args_cli.video: + video_kwargs = { + "video_folder": os.path.join(log_dir, "videos", "play"), + "step_trigger": lambda step: step == 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, clip_actions=agent_cfg.clip_actions) + + print(f"[INFO]: Loading model checkpoint from: {resume_path}") + # load previously trained model + if agent_cfg.class_name == "OnPolicyRunner": + runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + elif agent_cfg.class_name == "DistillationRunner": + runner = DistillationRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + else: + raise ValueError(f"Unsupported runner class: {agent_cfg.class_name}") + # configure_seed must be called after runner construction so that PyTorch deterministic settings + # do not interfere with the runner's internal initialization. + if args_cli.deterministic: + configure_seed(env_cfg.seed, True) + runner.load(resume_path) + + # obtain the trained policy for inference + policy = runner.get_inference_policy(device=env.unwrapped.device) + + # export the trained policy to JIT and ONNX formats + export_model_dir = os.path.join(os.path.dirname(resume_path), "exported") + + if version.parse(installed_version) >= version.parse("4.0.0"): + # use the new export functions for rsl-rl >= 4.0.0 + runner.export_policy_to_jit(path=export_model_dir, filename="policy.pt") + runner.export_policy_to_onnx(path=export_model_dir, filename="policy.onnx") + policy_nn = None # Not needed for rsl-rl >= 4.0.0 + else: + # extract the neural network for rsl-rl < 4.0.0 + if version.parse(installed_version) >= version.parse("2.3.0"): + policy_nn = runner.alg.policy + else: + policy_nn = runner.alg.actor_critic + + # extract the normalizer + if hasattr(policy_nn, "actor_obs_normalizer"): + normalizer = policy_nn.actor_obs_normalizer + elif hasattr(policy_nn, "student_obs_normalizer"): + normalizer = policy_nn.student_obs_normalizer + else: + normalizer = None + + # export to JIT and ONNX + export_policy_as_jit(policy_nn, normalizer=normalizer, path=export_model_dir, filename="policy.pt") + export_policy_as_onnx(policy_nn, normalizer=normalizer, path=export_model_dir, filename="policy.onnx") + + dt = env.unwrapped.step_dt + + # reset environment + obs = env.get_observations() + timestep = 0 + # simulate environment + try: + while True: + start_time = time.time() + # run everything in inference mode + with torch.inference_mode(): + # agent stepping + actions = policy(obs) + # env stepping + obs, _, dones, _ = env.step(actions) + # reset recurrent states for episodes that have terminated + if version.parse(installed_version) >= version.parse("4.0.0"): + policy.reset(dones) + else: + policy_nn.reset(dones) + if args_cli.video: + timestep += 1 + if timestep == args_cli.video_length: + break + + sleep_time = dt - (time.time() - start_time) + if args_cli.real_time and sleep_time > 0: + time.sleep(sleep_time) + + # close the simulator + env.close() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/play_rsl_rl.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/play_rsl_rl.py new file mode 100644 index 0000000000000000000000000000000000000000..ce7281074e7d43c7c4b463478da8be486e34dbd6 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/play_rsl_rl.py @@ -0,0 +1,234 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to play a checkpoint of an RL agent from RSL-RL.""" + +import argparse +import contextlib +import importlib.metadata as metadata +import os +import sys +import time + +import gymnasium as gym +import torch +from packaging import version +from rsl_rl.runners import DistillationRunner, OnPolicyRunner + +from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg +from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.dict import print_dict +from isaaclab.utils.string import list_intersection, string_to_callable + +from isaaclab_rl.rsl_rl import ( + RslRlBaseRunnerCfg, + RslRlVecEnvWrapper, + export_policy_as_jit, + export_policy_as_onnx, + handle_deprecated_rsl_rl_cfg, +) +from isaaclab_rl.utils.pretrained_checkpoint import get_published_pretrained_checkpoint + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + get_checkpoint_path, + launch_simulation, + setup_preset_cli, +) +from isaaclab_tasks.utils.hydra import hydra_task_config + +# local imports +import cli_args # isort: skip + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + +# -- argparse ---------------------------------------------------------------- +parser = argparse.ArgumentParser(description="Play a checkpoint of an RL agent from RSL-RL.") +parser.add_argument("--video", action="store_true", default=False, help="Record videos during play.") +parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).") +parser.add_argument( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument( + "--agent", type=str, default="rsl_rl_cfg_entry_point", help="Name of the RL agent configuration entry point." +) +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument( + "--use_pretrained_checkpoint", + action="store_true", + help="Use the pre-trained checkpoint from Nucleus.", +) +parser.add_argument("--real-time", action="store_true", default=False, help="Run in real-time, if possible.") +parser.add_argument("--external_callback", default=None, help="Fully qualified path to an externally defined callback.") +cli_args.add_rsl_rl_args(parser) +add_launcher_args(parser) +args_cli, remaining_args = setup_preset_cli(parser) + +if args_cli.video: + args_cli.enable_cameras = True + + +# Call an external callback if requested. This gives opportunity to external code to register the environments +# The function is expected to return a list of arguments that were not consumed by the callback. +remaining_args_env_registration = None +if args_cli.external_callback: + external_callback_function = string_to_callable(args_cli.external_callback, separator=".") + remaining_args_env_registration = external_callback_function() + +# clear out sys.argv for Hydra +# The remaining arguments are the arguments that were not consumed by both this scripts +# argparser and (optionally) the external callback function. +remaining_args = list_intersection(remaining_args, remaining_args_env_registration) +sys.argv = [sys.argv[0]] + remaining_args + +# Check for installed RSL-RL version +installed_version = metadata.version("rsl-rl-lib") + + +@hydra_task_config(args_cli.task, args_cli.agent) +def main(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agent_cfg: RslRlBaseRunnerCfg): + """Play with RSL-RL agent.""" + with launch_simulation(env_cfg, args_cli): + # grab task name for checkpoint path + task_name = args_cli.task.split(":")[-1] + train_task_name = task_name.replace("-Play", "") + + # override configurations with non-hydra CLI arguments + agent_cfg = cli_args.update_rsl_rl_cfg(agent_cfg, args_cli) + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + + # handle deprecated configurations + agent_cfg = handle_deprecated_rsl_rl_cfg(agent_cfg, installed_version) + + # set the environment seed + # note: certain randomizations occur in the environment initialization so we set the seed here + env_cfg.seed = agent_cfg.seed + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + # 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}") + if args_cli.use_pretrained_checkpoint: + resume_path = get_published_pretrained_checkpoint("rsl_rl", train_task_name) + if not resume_path: + print("[INFO] Unfortunately a pre-trained checkpoint is currently unavailable for this task.") + return + elif args_cli.checkpoint: + resume_path = retrieve_file_path(args_cli.checkpoint) + else: + resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) + + log_dir = os.path.dirname(resume_path) + + # set the log directory for the environment + env_cfg.log_dir = log_dir + + # create isaac environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + + # convert to single-agent instance if required by the RL algorithm + if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): + from isaaclab.envs import multi_agent_to_single_agent + + env = multi_agent_to_single_agent(env) + + # wrap for video recording + if args_cli.video: + video_kwargs = { + "video_folder": os.path.join(log_dir, "videos", "play"), + "step_trigger": lambda step: step == 0, + "video_length": args_cli.video_length, + "disable_logger": True, + } + print("[INFO] Recording videos during play.") + print_dict(video_kwargs, nesting=4) + env = gym.wrappers.RecordVideo(env, **video_kwargs) + + # wrap around environment for rsl-rl + env = RslRlVecEnvWrapper(env, clip_actions=agent_cfg.clip_actions) + + print(f"[INFO]: Loading model checkpoint from: {resume_path}") + # load previously trained model + if agent_cfg.class_name == "OnPolicyRunner": + runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + elif agent_cfg.class_name == "DistillationRunner": + runner = DistillationRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + else: + raise ValueError(f"Unsupported runner class: {agent_cfg.class_name}") + runner.load(resume_path) + + # obtain the trained policy for inference + policy = runner.get_inference_policy(device=env.unwrapped.device) + + # export the trained policy to JIT and ONNX formats + export_model_dir = os.path.join(os.path.dirname(resume_path), "exported") + + if version.parse(installed_version) >= version.parse("4.0.0"): + # use the new export functions for rsl-rl >= 4.0.0 + runner.export_policy_to_jit(path=export_model_dir, filename="policy.pt") + runner.export_policy_to_onnx(path=export_model_dir, filename="policy.onnx") + policy_nn = None # Not needed for rsl-rl >= 4.0.0 + else: + # extract the neural network for rsl-rl < 4.0.0 + if version.parse(installed_version) >= version.parse("2.3.0"): + policy_nn = runner.alg.policy + else: + policy_nn = runner.alg.actor_critic + + # extract the normalizer + if hasattr(policy_nn, "actor_obs_normalizer"): + normalizer = policy_nn.actor_obs_normalizer + elif hasattr(policy_nn, "student_obs_normalizer"): + normalizer = policy_nn.student_obs_normalizer + else: + normalizer = None + + # export to JIT and ONNX + export_policy_as_jit(policy_nn, normalizer=normalizer, path=export_model_dir, filename="policy.pt") + export_policy_as_onnx(policy_nn, normalizer=normalizer, path=export_model_dir, filename="policy.onnx") + + dt = env.unwrapped.step_dt + + # reset environment + obs = env.get_observations() + timestep = 0 + # simulate environment + try: + while True: + start_time = time.time() + # run everything in inference mode + with torch.inference_mode(): + # agent stepping + actions = policy(obs) + # env stepping + obs, _, dones, _ = env.step(actions) + # reset recurrent states for episodes that have terminated + if version.parse(installed_version) >= version.parse("4.0.0"): + policy.reset(dones) + else: + policy_nn.reset(dones) + if args_cli.video: + timestep += 1 + if timestep == args_cli.video_length: + break + + sleep_time = dt - (time.time() - start_time) + if args_cli.real_time and sleep_time > 0: + time.sleep(sleep_time) + + # close the simulator + env.close() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/train.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3ea4449f3dde1286ba3cf06273ad84552c1b1311 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/train.py @@ -0,0 +1,255 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to train RL agent with RSL-RL.""" + +import warnings + +warnings.warn( + "scripts/reinforcement_learning/rsl_rl/train.py is deprecated. Use " + "`./isaaclab.sh train --rl_library rsl_rl --task ` instead. " + "Example: `./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-v0`.", + DeprecationWarning, + stacklevel=1, +) + +import argparse +import contextlib +import importlib.metadata as metadata +import logging +import os +import platform +import sys +import time +from datetime import datetime + +import gymnasium as gym +import torch +from packaging import version +from rsl_rl.runners import DistillationRunner, OnPolicyRunner + +from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg +from isaaclab.utils.dict import print_dict +from isaaclab.utils.io import dump_yaml +from isaaclab.utils.seed import configure_seed +from isaaclab.utils.string import list_intersection, string_to_callable + +from isaaclab_rl.rsl_rl import RslRlBaseRunnerCfg, RslRlVecEnvWrapper, handle_deprecated_rsl_rl_cfg + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + get_checkpoint_path, + launch_simulation, + setup_preset_cli, +) +from isaaclab_tasks.utils.hydra import hydra_task_config + +# local imports +import cli_args # isort: skip + +logger = logging.getLogger(__name__) + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + +RSL_RL_VERSION = "5.0.1" + +torch.backends.cuda.matmul.allow_tf32 = True +torch.backends.cudnn.allow_tf32 = True +torch.backends.cudnn.deterministic = False +torch.backends.cudnn.benchmark = False + +# -- argparse ---------------------------------------------------------------- +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("--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( + "--agent", type=str, default="rsl_rl_cfg_entry_point", help="Name of the RL agent configuration entry point." +) +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument("--max_iterations", type=int, default=None, help="RL Policy training iterations.") +parser.add_argument( + "--distributed", action="store_true", default=False, help="Run training with multiple GPUs or nodes." +) +parser.add_argument("--export_io_descriptors", action="store_true", default=False, help="Export IO descriptors.") +parser.add_argument( + "--ray-proc-id", "-rid", type=int, default=None, help="Automatically configured by Ray integration, otherwise None." +) +parser.add_argument("--external_callback", default=None, help="Fully qualified path to an externally defined callback.") +cli_args.add_rsl_rl_args(parser) +add_launcher_args(parser) +args_cli, remaining_args = setup_preset_cli(parser) + +if args_cli.video: + args_cli.enable_cameras = True + + +# Call an external callback if requested. This gives opportunity to external code to register the environments +# The function is expected to return a list of arguments that were not consumed by the callback. +remaining_args_env_registration = None +if args_cli.external_callback: + external_callback_function = string_to_callable(args_cli.external_callback, separator=".") + remaining_args_env_registration = external_callback_function() + +# clear out sys.argv for Hydra +# The remaining arguments are the arguments that were not consumed by both this scripts +# argparser and (optionally) the external callback function. Both sides of this +# intersection share the same token vocabulary (the callback reads the user's +# original sys.argv), so preset tokens like ``physics=NAME`` compare correctly. +remaining_args = list_intersection(remaining_args, remaining_args_env_registration) +sys.argv = [sys.argv[0]] + remaining_args + +# -- check RSL-RL version ---------------------------------------------------- +installed_version = metadata.version("rsl-rl-lib") +if version.parse(installed_version) < version.parse(RSL_RL_VERSION): + if platform.system() == "Windows": + cmd = [r".\isaaclab.bat", "-p", "-m", "pip", "install", f"rsl-rl-lib=={RSL_RL_VERSION}"] + else: + cmd = ["./isaaclab.sh", "-p", "-m", "pip", "install", f"rsl-rl-lib=={RSL_RL_VERSION}"] + print( + f"Please install the correct version of RSL-RL.\nExisting version is: '{installed_version}'" + f" and required version is: '{RSL_RL_VERSION}'.\nTo install the correct version, run:" + f"\n\n\t{' '.join(cmd)}\n" + ) + exit(1) + + +@hydra_task_config(args_cli.task, args_cli.agent) +def main(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agent_cfg: RslRlBaseRunnerCfg): + """Train with RSL-RL agent.""" + with launch_simulation(env_cfg, args_cli): + # override configurations with non-hydra CLI arguments + agent_cfg = cli_args.update_rsl_rl_cfg(agent_cfg, args_cli) + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + agent_cfg.max_iterations = ( + args_cli.max_iterations if args_cli.max_iterations is not None else agent_cfg.max_iterations + ) + + # handle deprecated configurations + agent_cfg = handle_deprecated_rsl_rl_cfg(agent_cfg, installed_version) + + # set the environment seed + # note: certain randomizations occur in the environment initialization so we set the seed here + env_cfg.seed = agent_cfg.seed + # For distributed training, launch_simulation() already resolved the + # correct per-rank device; only apply a CLI --device override for + # non-distributed runs (the default "cuda:0" would clobber the + # per-rank device otherwise). + if not args_cli.distributed: + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + # check for invalid combination of CPU device with distributed training + if args_cli.distributed and args_cli.device is not None and "cpu" in args_cli.device: + raise ValueError( + "Distributed training is not supported when using CPU device. " + "Please use GPU device (e.g., --device cuda) for distributed training." + ) + + # multi-gpu training configuration + if args_cli.distributed: + global_rank = int(os.getenv("RANK", "0")) + # env_cfg.sim.device is resolved by launch_simulation() which + # accounts for CUDA_VISIBLE_DEVICES restrictions. + agent_cfg.device = env_cfg.sim.device + + # use global rank for seed diversity across all nodes + seed = agent_cfg.seed + global_rank + env_cfg.seed = seed + agent_cfg.seed = seed + + # 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") + # The Ray Tune workflow extracts experiment name using the logging line below, hence, do not + # change it (see PR #2346, comment-2819298849) + print(f"Exact experiment name requested from command line: {log_dir}") + if agent_cfg.run_name: + log_dir += f"_{agent_cfg.run_name}" + log_dir = os.path.join(log_root_path, log_dir) + + # set the IO descriptors export flag if requested + if isinstance(env_cfg, ManagerBasedRLEnvCfg): + env_cfg.export_io_descriptors = args_cli.export_io_descriptors + else: + logger.warning( + "IO descriptors are only supported for manager based RL environments." + " No IO descriptors will be exported." + ) + + # set the log directory for the environment (works for all environment types) + env_cfg.log_dir = log_dir + + # create isaac environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + + # convert to single-agent instance if required by the RL algorithm + if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): + from isaaclab.envs import multi_agent_to_single_agent + + env = multi_agent_to_single_agent(env) + + # save resume path before creating a new log_dir + if agent_cfg.resume or agent_cfg.algorithm.class_name == "Distillation": + resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) + + # wrap for video recording + if args_cli.video: + video_kwargs = { + "video_folder": os.path.join(log_dir, "videos", "train"), + "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) + + start_time = time.time() + + # wrap around environment for rsl-rl + env = RslRlVecEnvWrapper(env, clip_actions=agent_cfg.clip_actions) + + # create runner from rsl-rl + if agent_cfg.class_name == "OnPolicyRunner": + runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=log_dir, device=agent_cfg.device) + elif agent_cfg.class_name == "DistillationRunner": + runner = DistillationRunner(env, agent_cfg.to_dict(), log_dir=log_dir, device=agent_cfg.device) + else: + raise ValueError(f"Unsupported runner class: {agent_cfg.class_name}") + # configure_seed must be called after runner construction so that PyTorch deterministic settings + # do not interfere with the runner's internal initialization. + if args_cli.deterministic: + configure_seed(env_cfg.seed, True) + # write git state to logs + runner.add_git_repo_to_log(__file__) + # load the checkpoint + if agent_cfg.resume or agent_cfg.algorithm.class_name == "Distillation": + print(f"[INFO]: Loading model checkpoint from: {resume_path}") + # load previously trained model + runner.load(resume_path) + + # 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) + + # run training + try: + runner.learn(num_learning_iterations=agent_cfg.max_iterations, init_at_random_ep_len=True) + print(f"Training time: {round(time.time() - start_time, 2)} seconds") + # close the simulator + env.close() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/train_rsl_rl.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/train_rsl_rl.py new file mode 100644 index 0000000000000000000000000000000000000000..78d391196b72a958d834b4c4c1a63cf194abc065 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/rsl_rl/train_rsl_rl.py @@ -0,0 +1,183 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""RSL-RL training logic for the unified reinforcement learning entrypoint.""" + +from __future__ import annotations + +import argparse +import contextlib +import importlib.metadata as metadata +import logging +import os +import platform +import time +from datetime import datetime +from pathlib import Path + +from common import ( + add_common_train_args, + add_isaaclab_launcher_args, + apply_env_overrides, + configure_io_descriptors, + create_isaaclab_env, + dump_train_configs, + enable_cameras_for_video, + import_local_module, + set_hydra_args, + validate_distributed_device, + wrap_record_video, +) +from packaging import version + +import isaaclab_tasks # noqa: F401 + +logger = logging.getLogger(__name__) + +RSL_RL_VERSION = "5.0.1" +RL_ROOT = Path(__file__).resolve().parents[1] +CLI_ARGS = import_local_module("isaaclab_rsl_rl_cli_args", RL_ROOT / "rsl_rl" / "cli_args.py") + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + + +def _check_rsl_rl_version() -> str: + """Check that the installed RSL-RL version is supported.""" + installed_version = metadata.version("rsl-rl-lib") + if version.parse(installed_version) < version.parse(RSL_RL_VERSION): + if platform.system() == "Windows": + cmd = [r".\isaaclab.bat", "-p", "-m", "pip", "install", f"rsl-rl-lib=={RSL_RL_VERSION}"] + else: + cmd = ["./isaaclab.sh", "-p", "-m", "pip", "install", f"rsl-rl-lib=={RSL_RL_VERSION}"] + print( + f"Please install the correct version of RSL-RL.\nExisting version is: '{installed_version}'" + f" and required version is: '{RSL_RL_VERSION}'.\nTo install the correct version, run:" + f"\n\n\t{' '.join(cmd)}\n" + ) + raise SystemExit(1) + return installed_version + + +def _parse_args(argv: list[str]) -> argparse.Namespace: + """Parse RSL-RL training arguments.""" + from isaaclab.utils.string import list_intersection, string_to_callable + + from isaaclab_tasks.utils import setup_preset_cli + + parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.") + add_common_train_args( + parser, + agent_default="rsl_rl_cfg_entry_point", + agent_help="Name of the RL agent configuration entry point.", + ) + parser.add_argument( + "--external_callback", + default=None, + help="Fully qualified path to an externally defined callback.", + ) + CLI_ARGS.add_rsl_rl_args(parser) + add_isaaclab_launcher_args(parser) + # setup_preset_cli registers preset-selection help text + runs parse_known_args + args_cli, remaining_args = setup_preset_cli(parser, argv) + enable_cameras_for_video(args_cli) + + remaining_args_env_registration = None + if args_cli.external_callback: + external_callback_function = string_to_callable(args_cli.external_callback, separator=".") + remaining_args_env_registration = external_callback_function() + + # physics=/renderer=/presets= tokens pass through the remainder for hydra to parse later + set_hydra_args(list_intersection(remaining_args, remaining_args_env_registration)) + return args_cli + + +def run(argv: list[str]) -> None: + """Train an RSL-RL agent.""" + import torch + from rsl_rl.runners import DistillationRunner, OnPolicyRunner + + from isaaclab.envs import DirectMARLEnvCfg + + from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper, handle_deprecated_rsl_rl_cfg + + from isaaclab_tasks.utils import get_checkpoint_path, launch_simulation, resolve_task_config + + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.backends.cudnn.deterministic = False + torch.backends.cudnn.benchmark = False + + args_cli = _parse_args(argv) + installed_version = _check_rsl_rl_version() + env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent) + + with launch_simulation(env_cfg, args_cli): + agent_cfg = CLI_ARGS.update_rsl_rl_cfg(agent_cfg, args_cli) + apply_env_overrides(args_cli, env_cfg) + agent_cfg.max_iterations = ( + args_cli.max_iterations if args_cli.max_iterations is not None else agent_cfg.max_iterations + ) + + agent_cfg = handle_deprecated_rsl_rl_cfg(agent_cfg, installed_version) + + env_cfg.seed = agent_cfg.seed + validate_distributed_device(args_cli) + + if args_cli.distributed: + global_rank = int(os.getenv("RANK", "0")) + agent_cfg.device = env_cfg.sim.device + + seed = agent_cfg.seed + global_rank + env_cfg.seed = seed + agent_cfg.seed = seed + + log_root_path = os.path.abspath(os.path.join("logs", "rsl_rl", agent_cfg.experiment_name)) + print(f"[INFO] Logging experiment in directory: {log_root_path}") + log_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + print(f"Exact experiment name requested from command line: {log_dir}") + if agent_cfg.run_name: + log_dir += f"_{agent_cfg.run_name}" + log_dir = os.path.join(log_root_path, log_dir) + + configure_io_descriptors(env_cfg, args_cli, logger) + env_cfg.log_dir = log_dir + + env = create_isaaclab_env( + args_cli.task, + env_cfg, + args_cli, + convert_marl_to_single_agent=isinstance(env_cfg, DirectMARLEnvCfg), + ) + + if agent_cfg.resume or agent_cfg.algorithm.class_name == "Distillation": + resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) + + env = wrap_record_video(env, log_dir, args_cli) + + start_time = time.time() + env = RslRlVecEnvWrapper(env, clip_actions=agent_cfg.clip_actions) + + if agent_cfg.class_name == "OnPolicyRunner": + runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=log_dir, device=agent_cfg.device) + elif agent_cfg.class_name == "DistillationRunner": + runner = DistillationRunner(env, agent_cfg.to_dict(), log_dir=log_dir, device=agent_cfg.device) + else: + raise ValueError(f"Unsupported runner class: {agent_cfg.class_name}") + + runner.add_git_repo_to_log(__file__) + if agent_cfg.resume or agent_cfg.algorithm.class_name == "Distillation": + print(f"[INFO]: Loading model checkpoint from: {resume_path}") + runner.load(resume_path) + + dump_train_configs(log_dir, env_cfg, agent_cfg) + + try: + runner.learn(num_learning_iterations=agent_cfg.max_iterations, init_at_random_ep_len=True) + print(f"Training time: {round(time.time() - start_time, 2)} seconds") + env.close() + except KeyboardInterrupt: + pass diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/sb3/play.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/sb3/play.py new file mode 100644 index 0000000000000000000000000000000000000000..3dfb0c3747ac1f09d628c61b0cc269764d615ab0 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/sb3/play.py @@ -0,0 +1,203 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to play a checkpoint if an RL agent from Stable-Baselines3.""" + +import warnings + +warnings.warn( + "scripts/reinforcement_learning/sb3/play.py is deprecated. Use " + "`./isaaclab.sh play --rl_library sb3 --task ` instead. " + "Example: `./isaaclab.sh play --rl_library sb3 --task Isaac-Cartpole-v0`.", + DeprecationWarning, + stacklevel=1, +) + +import argparse +import contextlib +import os +import random +import sys +import time +from pathlib import Path + +import gymnasium as gym +import torch +from stable_baselines3 import PPO +from stable_baselines3.common.vec_env import VecNormalize + +from isaaclab.envs import DirectMARLEnvCfg +from isaaclab.utils.dict import print_dict +from isaaclab.utils.seed import configure_seed + +from isaaclab_rl.sb3 import Sb3VecEnvWrapper, process_sb3_cfg +from isaaclab_rl.utils.pretrained_checkpoint import get_published_pretrained_checkpoint + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + get_checkpoint_path, + launch_simulation, + resolve_task_config, + setup_preset_cli, +) + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + +# -- argparse ---------------------------------------------------------------- +parser = argparse.ArgumentParser(description="Play a checkpoint of an RL agent from Stable-Baselines3.") +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( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +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( + "--agent", type=str, default="sb3_cfg_entry_point", help="Name of the RL agent configuration entry point." +) +parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint.") +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument( + "--use_pretrained_checkpoint", + action="store_true", + help="Use the pre-trained checkpoint from Nucleus.", +) +parser.add_argument("--real-time", action="store_true", default=False, help="Run in real-time, if possible.") +parser.add_argument( + "--keep_all_info", + action="store_true", + default=False, + help="Use a slower SB3 wrapper but keep all the extra training info.", +) +add_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args + +if args_cli.video: + args_cli.enable_cameras = True + + +def main(): + """Play with stable-baselines agent.""" + env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent) + with launch_simulation(env_cfg, args_cli): + # grab task name for checkpoint path + task_name = args_cli.task.split(":")[-1] + train_task_name = task_name.replace("-Play", "") + # randomly sample a seed if seed = -1 + if args_cli.seed == -1: + args_cli.seed = random.randint(0, 10000) + + # override configurations with non-hydra CLI arguments + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + agent_cfg["seed"] = args_cli.seed if args_cli.seed is not None else agent_cfg["seed"] + env_cfg.seed = agent_cfg["seed"] + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + # directory for logging into + log_root_path = os.path.join("logs", "sb3", train_task_name) + log_root_path = os.path.abspath(log_root_path) + # checkpoint and log_dir stuff + if args_cli.use_pretrained_checkpoint: + checkpoint_path = get_published_pretrained_checkpoint("sb3", train_task_name) + if not checkpoint_path: + print("[INFO] Unfortunately a pre-trained checkpoint is currently unavailable for this task.") + return + elif args_cli.checkpoint is None: + # prefer the final model (``model.zip``); fall back to the latest periodic checkpoint when it has + # not been written yet (e.g. short or interrupted runs) + checkpoint_path = get_checkpoint_path( + log_root_path, ".*", r"model_.*\.zip", sort_alpha=False, preferred_checkpoint=r"model\.zip" + ) + else: + checkpoint_path = args_cli.checkpoint + log_dir = os.path.dirname(checkpoint_path) + + # set the log directory for the environment + env_cfg.log_dir = log_dir + + # create isaac environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + + # post-process agent configuration + agent_cfg = process_sb3_cfg(agent_cfg, env.unwrapped.num_envs) + + # convert to single-agent instance if required by the RL algorithm + if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): + from isaaclab.envs import multi_agent_to_single_agent + + env = multi_agent_to_single_agent(env) + + # wrap for video recording + if args_cli.video: + video_kwargs = { + "video_folder": os.path.join(log_dir, "videos", "play"), + "step_trigger": lambda step: step == 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 stable baselines + env = Sb3VecEnvWrapper(env, fast_variant=not args_cli.keep_all_info) + + vec_norm_path = checkpoint_path.replace("/model", "/model_vecnormalize").replace(".zip", ".pkl") + vec_norm_path = Path(vec_norm_path) + + # normalize environment (if needed) + if vec_norm_path.exists(): + print(f"Loading saved normalization: {vec_norm_path}") + env = VecNormalize.load(vec_norm_path, env) + env.training = False + env.norm_reward = False + elif "normalize_input" in agent_cfg: + env = VecNormalize( + env, + training=True, + norm_obs="normalize_input" in agent_cfg and agent_cfg.pop("normalize_input"), + clip_obs="clip_obs" in agent_cfg and agent_cfg.pop("clip_obs"), + ) + + # create agent from stable baselines + print(f"Loading checkpoint from: {checkpoint_path}") + agent = PPO.load(checkpoint_path, env, print_system_info=True) + # configure_seed must be called after PPO.load so that PyTorch deterministic settings + # do not interfere with SB3's internal initialization. + if args_cli.deterministic: + configure_seed(env_cfg.seed, True) + + dt = env.unwrapped.step_dt + + # reset environment + obs = env.reset() + timestep = 0 + # simulate environment + try: + while True: + start_time = time.time() + with torch.inference_mode(): + actions, _ = agent.predict(obs, deterministic=True) + obs, _, _, _ = env.step(actions) + if args_cli.video: + timestep += 1 + if timestep == args_cli.video_length: + break + + sleep_time = dt - (time.time() - start_time) + if args_cli.real_time and sleep_time > 0: + time.sleep(sleep_time) + + # close the simulator + env.close() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/sb3/play_sb3.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/sb3/play_sb3.py new file mode 100644 index 0000000000000000000000000000000000000000..788da139ce9587c42ae3722d64482b6a9de2fe15 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/sb3/play_sb3.py @@ -0,0 +1,189 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to play a checkpoint of an RL agent from Stable-Baselines3.""" + +import argparse +import contextlib +import os +import random +import sys +import time +from pathlib import Path + +import gymnasium as gym +import torch +from stable_baselines3 import PPO +from stable_baselines3.common.vec_env import VecNormalize + +from isaaclab.envs import DirectMARLEnvCfg +from isaaclab.utils.dict import print_dict + +from isaaclab_rl.sb3 import Sb3VecEnvWrapper, process_sb3_cfg +from isaaclab_rl.utils.pretrained_checkpoint import get_published_pretrained_checkpoint + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + get_checkpoint_path, + launch_simulation, + resolve_task_config, + setup_preset_cli, +) + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + +# -- argparse ---------------------------------------------------------------- +parser = argparse.ArgumentParser(description="Play a checkpoint of an RL agent from Stable-Baselines3.") +parser.add_argument("--video", action="store_true", default=False, help="Record videos during play.") +parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).") +parser.add_argument( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument( + "--agent", type=str, default="sb3_cfg_entry_point", help="Name of the RL agent configuration entry point." +) +parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint.") +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument( + "--use_pretrained_checkpoint", + action="store_true", + help="Use the pre-trained checkpoint from Nucleus.", +) +parser.add_argument("--real-time", action="store_true", default=False, help="Run in real-time, if possible.") +parser.add_argument( + "--keep_all_info", + action="store_true", + default=False, + help="Use a slower SB3 wrapper but keep all the extra training info.", +) +add_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) + +if args_cli.video: + args_cli.enable_cameras = True + +sys.argv = [sys.argv[0]] + hydra_args + + +def main(): + """Play with stable-baselines agent.""" + env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent) + with launch_simulation(env_cfg, args_cli): + # grab task name for checkpoint path + task_name = args_cli.task.split(":")[-1] + train_task_name = task_name.replace("-Play", "") + # randomly sample a seed if seed = -1 + if args_cli.seed == -1: + args_cli.seed = random.randint(0, 10000) + + # override configurations with non-hydra CLI arguments + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + agent_cfg["seed"] = args_cli.seed if args_cli.seed is not None else agent_cfg["seed"] + env_cfg.seed = agent_cfg["seed"] + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + # directory for logging into + log_root_path = os.path.join("logs", "sb3", train_task_name) + log_root_path = os.path.abspath(log_root_path) + # checkpoint and log_dir stuff + if args_cli.use_pretrained_checkpoint: + checkpoint_path = get_published_pretrained_checkpoint("sb3", train_task_name) + if not checkpoint_path: + print("[INFO] Unfortunately a pre-trained checkpoint is currently unavailable for this task.") + return + elif args_cli.checkpoint is None: + # prefer the final model (``model.zip``); fall back to the latest periodic checkpoint when it has + # not been written yet (e.g. short or interrupted runs) + checkpoint_path = get_checkpoint_path( + log_root_path, ".*", r"model_.*\.zip", sort_alpha=False, preferred_checkpoint=r"model\.zip" + ) + else: + checkpoint_path = args_cli.checkpoint + log_dir = os.path.dirname(checkpoint_path) + + # set the log directory for the environment + env_cfg.log_dir = log_dir + + # create isaac environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + + # post-process agent configuration + agent_cfg = process_sb3_cfg(agent_cfg, env.unwrapped.num_envs) + + # convert to single-agent instance if required by the RL algorithm + if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): + from isaaclab.envs import multi_agent_to_single_agent + + env = multi_agent_to_single_agent(env) + + # wrap for video recording + if args_cli.video: + video_kwargs = { + "video_folder": os.path.join(log_dir, "videos", "play"), + "step_trigger": lambda step: step == 0, + "video_length": args_cli.video_length, + "disable_logger": True, + } + print("[INFO] Recording videos during play.") + print_dict(video_kwargs, nesting=4) + env = gym.wrappers.RecordVideo(env, **video_kwargs) + # wrap around environment for stable baselines + env = Sb3VecEnvWrapper(env, fast_variant=not args_cli.keep_all_info) + + vec_norm_path = checkpoint_path.replace("/model", "/model_vecnormalize").replace(".zip", ".pkl") + vec_norm_path = Path(vec_norm_path) + + # normalize environment (if needed) + if vec_norm_path.exists(): + print(f"Loading saved normalization: {vec_norm_path}") + env = VecNormalize.load(vec_norm_path, env) + env.training = False + env.norm_reward = False + elif "normalize_input" in agent_cfg: + env = VecNormalize( + env, + training=True, + norm_obs="normalize_input" in agent_cfg and agent_cfg.pop("normalize_input"), + clip_obs="clip_obs" in agent_cfg and agent_cfg.pop("clip_obs"), + ) + + # create agent from stable baselines + print(f"Loading checkpoint from: {checkpoint_path}") + agent = PPO.load(checkpoint_path, env, print_system_info=True) + + dt = env.unwrapped.step_dt + + # reset environment + obs = env.reset() + timestep = 0 + # simulate environment + try: + while True: + start_time = time.time() + with torch.inference_mode(): + actions, _ = agent.predict(obs, deterministic=True) + obs, _, _, _ = env.step(actions) + if args_cli.video: + timestep += 1 + if timestep == args_cli.video_length: + break + + sleep_time = dt - (time.time() - start_time) + if args_cli.real_time and sleep_time > 0: + time.sleep(sleep_time) + + # close the simulator + env.close() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/sb3/train.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/sb3/train.py new file mode 100644 index 0000000000000000000000000000000000000000..941603ac747e0296d43001b11cac774a895f4154 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/sb3/train.py @@ -0,0 +1,238 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + + +"""Script to train RL agent with Stable Baselines3.""" + +import warnings + +warnings.warn( + "scripts/reinforcement_learning/sb3/train.py is deprecated. Use " + "`./isaaclab.sh train --rl_library sb3 --task ` instead. " + "Example: `./isaaclab.sh train --rl_library sb3 --task Isaac-Cartpole-v0`.", + DeprecationWarning, + stacklevel=1, +) + +import argparse +import contextlib +import logging +import os +import random +import signal +import sys +import time +from datetime import datetime +from pathlib import Path + +import gymnasium as gym +import numpy as np +from stable_baselines3 import PPO +from stable_baselines3.common.callbacks import CheckpointCallback, LogEveryNTimesteps +from stable_baselines3.common.vec_env import VecNormalize + +from isaaclab.envs import DirectMARLEnvCfg, ManagerBasedRLEnvCfg +from isaaclab.utils.dict import print_dict +from isaaclab.utils.io import dump_yaml +from isaaclab.utils.seed import configure_seed + +from isaaclab_rl.sb3 import Sb3VecEnvWrapper, process_sb3_cfg + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + launch_simulation, + resolve_task_config, + setup_preset_cli, +) + +logger = logging.getLogger(__name__) + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + +# -- argparse ---------------------------------------------------------------- +parser = argparse.ArgumentParser(description="Train an RL agent with Stable-Baselines3.") +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("--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( + "--agent", type=str, default="sb3_cfg_entry_point", help="Name of the RL agent configuration entry point." +) +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument("--log_interval", type=int, default=100_000, help="Log data every n timesteps.") +parser.add_argument("--checkpoint", type=str, default=None, help="Continue the training from checkpoint.") +parser.add_argument("--max_iterations", type=int, default=None, help="RL Policy training iterations.") +parser.add_argument("--export_io_descriptors", action="store_true", default=False, help="Export IO descriptors.") +parser.add_argument( + "--keep_all_info", + action="store_true", + default=False, + help="Use a slower SB3 wrapper but keep all the extra training info.", +) +parser.add_argument( + "--ray-proc-id", "-rid", type=int, default=None, help="Automatically configured by Ray integration, otherwise None." +) +add_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args + +if args_cli.video: + args_cli.enable_cameras = True + + +def cleanup_pbar(*args): + """ + A small helper to stop training and + cleanup progress bar properly on ctrl+c + """ + import gc + + tqdm_objects = [obj for obj in gc.get_objects() if "tqdm" in type(obj).__name__] + for tqdm_object in tqdm_objects: + if "tqdm_rich" in type(tqdm_object).__name__: + tqdm_object.close() + raise KeyboardInterrupt + + +signal.signal(signal.SIGINT, cleanup_pbar) + + +def main(): + """Train with stable-baselines agent.""" + env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent) + with launch_simulation(env_cfg, args_cli): + # randomly sample a seed if seed = -1 + if args_cli.seed == -1: + args_cli.seed = random.randint(0, 10000) + + # override configurations with non-hydra CLI arguments + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + agent_cfg["seed"] = args_cli.seed if args_cli.seed is not None else agent_cfg["seed"] + # max iterations for training + if args_cli.max_iterations is not None: + agent_cfg["n_timesteps"] = args_cli.max_iterations * agent_cfg["n_steps"] * env_cfg.scene.num_envs + + # set the environment seed + env_cfg.seed = agent_cfg["seed"] + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + # directory for logging into + run_info = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + log_root_path = os.path.abspath(os.path.join("logs", "sb3", args_cli.task)) + print(f"[INFO] Logging experiment in directory: {log_root_path}") + print(f"Exact experiment name requested from command line: {run_info}") + log_dir = os.path.join(log_root_path, run_info) + # 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) + + # save command used to run the script + command = " ".join(sys.orig_argv) + (Path(log_dir) / "command.txt").write_text(command) + + # post-process agent configuration + agent_cfg = process_sb3_cfg(agent_cfg, env_cfg.scene.num_envs) + # read configurations about the agent-training + policy_arch = agent_cfg.pop("policy") + n_timesteps = agent_cfg.pop("n_timesteps") + + # set the IO descriptors export flag if requested + if isinstance(env_cfg, ManagerBasedRLEnvCfg): + env_cfg.export_io_descriptors = args_cli.export_io_descriptors + else: + logger.warning( + "IO descriptors are only supported for manager based RL environments." + " No IO descriptors will be exported." + ) + + # set the log directory for the environment + env_cfg.log_dir = log_dir + + # create isaac environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + + # convert to single-agent instance if required by the RL algorithm + if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): + from isaaclab.envs import multi_agent_to_single_agent + + env = multi_agent_to_single_agent(env) + + # wrap for video recording + if args_cli.video: + video_kwargs = { + "video_folder": os.path.join(log_dir, "videos", "train"), + "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) + + start_time = time.time() + + # wrap around environment for stable baselines + env = Sb3VecEnvWrapper(env, fast_variant=not args_cli.keep_all_info) + + norm_keys = {"normalize_input", "normalize_value", "clip_obs"} + norm_args = {} + for key in norm_keys: + if key in agent_cfg: + norm_args[key] = agent_cfg.pop(key) + + if norm_args and norm_args.get("normalize_input"): + print(f"Normalizing input, {norm_args=}") + env = VecNormalize( + env, + training=True, + norm_obs=norm_args["normalize_input"], + norm_reward=norm_args.get("normalize_value", False), + clip_obs=norm_args.get("clip_obs", 100.0), + gamma=agent_cfg["gamma"], + clip_reward=np.inf, + ) + + # create agent from stable baselines + agent = PPO(policy_arch, env, verbose=1, tensorboard_log=log_dir, **agent_cfg) + if args_cli.checkpoint is not None: + agent = agent.load(args_cli.checkpoint, env, print_system_info=True) + # configure_seed must be called after PPO construction (and optional load) so that PyTorch + # deterministic settings do not interfere with SB3's internal initialization. + if args_cli.deterministic: + configure_seed(env_cfg.seed, True) + + # callbacks for agent + checkpoint_callback = CheckpointCallback(save_freq=1000, save_path=log_dir, name_prefix="model", verbose=2) + callbacks = [checkpoint_callback, LogEveryNTimesteps(n_steps=args_cli.log_interval)] + + # train the agent + with contextlib.suppress(KeyboardInterrupt): + agent.learn( + total_timesteps=n_timesteps, + callback=callbacks, + progress_bar=True, + log_interval=None, + ) + # save the final model + agent.save(os.path.join(log_dir, "model")) + print("Saving to:") + print(os.path.join(log_dir, "model.zip")) + + if isinstance(env, VecNormalize): + print("Saving normalization") + env.save(os.path.join(log_dir, "model_vecnormalize.pkl")) + + print(f"Training time: {round(time.time() - start_time, 2)} seconds") + + # close the simulator + env.close() + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/sb3/train_sb3.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/sb3/train_sb3.py new file mode 100644 index 0000000000000000000000000000000000000000..a337cd66fd53f224fe9670de732e875bacd788fb --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/sb3/train_sb3.py @@ -0,0 +1,180 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Stable-Baselines3 training logic for the unified reinforcement learning entrypoint.""" + +from __future__ import annotations + +import argparse +import contextlib +import logging +import os +import random +import signal +import sys +import time +from datetime import datetime +from pathlib import Path + +from common import ( + add_common_train_args, + add_isaaclab_launcher_args, + apply_env_overrides, + configure_io_descriptors, + create_isaaclab_env, + dump_train_configs, + enable_cameras_for_video, + set_hydra_args, + wrap_record_video, +) + +import isaaclab_tasks # noqa: F401 + +logger = logging.getLogger(__name__) + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + + +def _cleanup_pbar(*args): + """Stop training and clean up rich progress bars on Ctrl+C.""" + import gc + + tqdm_objects = [obj for obj in gc.get_objects() if "tqdm" in type(obj).__name__] + for tqdm_object in tqdm_objects: + if "tqdm_rich" in type(tqdm_object).__name__: + tqdm_object.close() + raise KeyboardInterrupt + + +def _parse_args(argv: list[str]) -> argparse.Namespace: + """Parse Stable-Baselines3 training arguments.""" + parser = argparse.ArgumentParser(description="Train an RL agent with Stable-Baselines3.") + add_common_train_args( + parser, + agent_default="sb3_cfg_entry_point", + agent_help="Name of the RL agent configuration entry point.", + include_distributed=False, + ) + parser.add_argument("--log_interval", type=int, default=100_000, help="Log data every n timesteps.") + parser.add_argument("--checkpoint", type=str, default=None, help="Continue the training from checkpoint.") + parser.add_argument( + "--keep_all_info", + action="store_true", + default=False, + help="Use a slower SB3 wrapper but keep all the extra training info.", + ) + from isaaclab_tasks.utils import setup_preset_cli + + add_isaaclab_launcher_args(parser) + # setup_preset_cli registers preset-selection help text + runs parse_known_args; the + # physics=/renderer=/presets= tokens pass through the remainder for hydra to parse later. + args_cli, hydra_args = setup_preset_cli(parser, argv) + enable_cameras_for_video(args_cli) + set_hydra_args(hydra_args) + return args_cli + + +def run(argv: list[str]) -> None: + """Train a Stable-Baselines3 agent.""" + import numpy as np + from stable_baselines3 import PPO + from stable_baselines3.common.callbacks import CheckpointCallback, LogEveryNTimesteps + from stable_baselines3.common.vec_env import VecNormalize + + from isaaclab.envs import DirectMARLEnvCfg + + from isaaclab_rl.sb3 import Sb3VecEnvWrapper, process_sb3_cfg + + from isaaclab_tasks.utils import launch_simulation, resolve_task_config + + signal.signal(signal.SIGINT, _cleanup_pbar) + + args_cli = _parse_args(argv) + env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent) + + with launch_simulation(env_cfg, args_cli): + if args_cli.seed == -1: + args_cli.seed = random.randint(0, 10000) + + apply_env_overrides(args_cli, env_cfg) + agent_cfg["seed"] = args_cli.seed if args_cli.seed is not None else agent_cfg["seed"] + if args_cli.max_iterations is not None: + agent_cfg["n_timesteps"] = args_cli.max_iterations * agent_cfg["n_steps"] * env_cfg.scene.num_envs + + env_cfg.seed = agent_cfg["seed"] + + run_info = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + log_root_path = os.path.abspath(os.path.join("logs", "sb3", args_cli.task)) + print(f"[INFO] Logging experiment in directory: {log_root_path}") + print(f"Exact experiment name requested from command line: {run_info}") + log_dir = os.path.join(log_root_path, run_info) + dump_train_configs(log_dir, env_cfg, agent_cfg) + + command = " ".join(sys.orig_argv) + (Path(log_dir) / "command.txt").write_text(command) + + agent_cfg = process_sb3_cfg(agent_cfg, env_cfg.scene.num_envs) + policy_arch = agent_cfg.pop("policy") + n_timesteps = agent_cfg.pop("n_timesteps") + + configure_io_descriptors(env_cfg, args_cli, logger) + env_cfg.log_dir = log_dir + + env = create_isaaclab_env( + args_cli.task, + env_cfg, + args_cli, + convert_marl_to_single_agent=isinstance(env_cfg, DirectMARLEnvCfg), + ) + env = wrap_record_video(env, log_dir, args_cli) + + start_time = time.time() + env = Sb3VecEnvWrapper(env, fast_variant=not args_cli.keep_all_info) + + norm_keys = {"normalize_input", "normalize_value", "clip_obs"} + norm_args = {} + for key in norm_keys: + if key in agent_cfg: + norm_args[key] = agent_cfg.pop(key) + + if norm_args and norm_args.get("normalize_input"): + print(f"Normalizing input, {norm_args=}") + env = VecNormalize( + env, + training=True, + norm_obs=norm_args["normalize_input"], + norm_reward=norm_args.get("normalize_value", False), + clip_obs=norm_args.get("clip_obs", 100.0), + gamma=agent_cfg["gamma"], + clip_reward=np.inf, + ) + + agent = PPO(policy_arch, env, verbose=1, tensorboard_log=log_dir, **agent_cfg) + if args_cli.checkpoint is not None: + agent = agent.load(args_cli.checkpoint, env, print_system_info=True) + + checkpoint_callback = CheckpointCallback(save_freq=1000, save_path=log_dir, name_prefix="model", verbose=2) + callbacks = [checkpoint_callback, LogEveryNTimesteps(n_steps=args_cli.log_interval)] + + with contextlib.suppress(KeyboardInterrupt): + agent.learn( + total_timesteps=n_timesteps, + callback=callbacks, + progress_bar=True, + log_interval=None, + ) + + agent.save(os.path.join(log_dir, "model")) + print("Saving to:") + print(os.path.join(log_dir, "model.zip")) + + if isinstance(env, VecNormalize): + print("Saving normalization") + env.save(os.path.join(log_dir, "model_vecnormalize.pkl")) + + print(f"Training time: {round(time.time() - start_time, 2)} seconds") + env.close() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/skrl/play.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/skrl/play.py new file mode 100644 index 0000000000000000000000000000000000000000..8b7c6c53e5b85d8bfd802f1a9b87362a3040966a --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/skrl/play.py @@ -0,0 +1,249 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Script to play a checkpoint of an RL agent from skrl. + +Visit the skrl documentation (https://skrl.readthedocs.io) to see the examples structured in +a more user-friendly way. +""" + +import warnings + +warnings.warn( + "scripts/reinforcement_learning/skrl/play.py is deprecated. Use " + "`./isaaclab.sh play --rl_library skrl --task ` instead. " + "Example: `./isaaclab.sh play --rl_library skrl --task Isaac-Cartpole-v0`.", + DeprecationWarning, + stacklevel=1, +) + +import argparse +import contextlib +import os +import random +import sys +import time + +import gymnasium as gym +import skrl +import torch +from packaging import version + +from isaaclab.envs import DirectMARLEnvCfg +from isaaclab.utils.dict import print_dict +from isaaclab.utils.seed import configure_seed + +from isaaclab_rl.utils.pretrained_checkpoint import get_published_pretrained_checkpoint + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + get_checkpoint_path, + launch_simulation, + resolve_task_config, + setup_preset_cli, +) + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + +SKRL_VERSION = "2.1.0" + +# -- argparse ---------------------------------------------------------------- +parser = argparse.ArgumentParser(description="Play a checkpoint of an RL agent from skrl.") +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( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +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( + "--agent", + type=str, + default=None, + help=( + "Name of the RL agent configuration entry point. Defaults to None, in which case the argument " + "--algorithm is used to determine the default agent configuration entry point." + ), +) +parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint.") +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument( + "--use_pretrained_checkpoint", + action="store_true", + help="Use the pre-trained checkpoint from Nucleus.", +) +parser.add_argument( + "--ml_framework", + type=str, + default="torch", + choices=["torch", "jax"], + help="The ML framework used for training the skrl agent.", +) +parser.add_argument( + "--algorithm", + type=str, + default="PPO", + choices=["AMP", "PPO", "IPPO", "MAPPO"], + help="The RL algorithm used for training the skrl agent.", +) +parser.add_argument("--real-time", action="store_true", default=False, help="Run in real-time, if possible.") +add_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args + +if args_cli.video: + args_cli.enable_cameras = True + +# -- check skrl version ------------------------------------------------------ +if version.parse(skrl.__version__) < version.parse(SKRL_VERSION): + skrl.logger.error( + f"Unsupported skrl version: {skrl.__version__}. " + f"Install supported version using 'pip install skrl>={SKRL_VERSION}'" + ) + exit() + +# config shortcuts +if args_cli.agent is None: + algorithm = args_cli.algorithm.lower() + agent_cfg_entry_point = "skrl_cfg_entry_point" if algorithm in ["ppo"] else f"skrl_{algorithm}_cfg_entry_point" +else: + agent_cfg_entry_point = args_cli.agent + algorithm = agent_cfg_entry_point.split("_cfg")[0].split("skrl_")[-1].lower() + + +def main(): + """Play with skrl agent.""" + env_cfg, experiment_cfg = resolve_task_config(args_cli.task, agent_cfg_entry_point) + with launch_simulation(env_cfg, args_cli): + if args_cli.ml_framework.startswith("torch"): + from skrl.utils.runner.torch import Runner + elif args_cli.ml_framework.startswith("jax"): + from skrl.utils.runner.jax import Runner + + from isaaclab_rl.skrl import SkrlVecEnvWrapper + + # grab task name for checkpoint path + task_name = args_cli.task.split(":")[-1] + train_task_name = task_name.replace("-Play", "") + + # override configurations with non-hydra CLI arguments + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + # configure the ML framework into the global skrl variable + if args_cli.ml_framework.startswith("jax"): + skrl.config.jax.backend = "jax" if args_cli.ml_framework == "jax" else "numpy" + + # randomly sample a seed if seed = -1 + if args_cli.seed == -1: + args_cli.seed = random.randint(0, 10000) + + # set the agent and environment seed from command line + experiment_cfg["seed"] = args_cli.seed if args_cli.seed is not None else experiment_cfg["seed"] + env_cfg.seed = experiment_cfg["seed"] + + # specify directory for logging experiments (load checkpoint) + log_root_path = os.path.join("logs", "skrl", experiment_cfg["agent"]["experiment"]["directory"]) + log_root_path = os.path.abspath(log_root_path) + print(f"[INFO] Loading experiment from directory: {log_root_path}") + # get checkpoint path + if args_cli.use_pretrained_checkpoint: + resume_path = get_published_pretrained_checkpoint("skrl", train_task_name) + if not resume_path: + print("[INFO] Unfortunately a pre-trained checkpoint is currently unavailable for this task.") + return + elif args_cli.checkpoint: + resume_path = os.path.abspath(args_cli.checkpoint) + else: + resume_path = get_checkpoint_path( + log_root_path, run_dir=f".*_{algorithm}_{args_cli.ml_framework}", other_dirs=["checkpoints"] + ) + log_dir = os.path.dirname(os.path.dirname(resume_path)) + + # set the log directory for the environment + env_cfg.log_dir = log_dir + + # create isaac environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + + # convert to single-agent instance if required by the RL algorithm + if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg) and algorithm in ["ppo"]: + from isaaclab.envs import multi_agent_to_single_agent + + env = multi_agent_to_single_agent(env) + + # get environment (step) dt for real-time evaluation + try: + dt = env.step_dt + except AttributeError: + dt = env.unwrapped.step_dt + + # wrap for video recording + if args_cli.video: + video_kwargs = { + "video_folder": os.path.join(log_dir, "videos", "play"), + "step_trigger": lambda step: step == 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 skrl + env = SkrlVecEnvWrapper(env, ml_framework=args_cli.ml_framework) + + # configure and instantiate the skrl runner + experiment_cfg["trainer"]["close_environment_at_exit"] = False + experiment_cfg["agent"]["experiment"]["write_interval"] = 0 + experiment_cfg["agent"]["experiment"]["checkpoint_interval"] = 0 + runner = Runner(env, experiment_cfg) + # configure_seed must be called after Runner() so that PyTorch deterministic settings + # do not interfere with Runner's internal initialization. + if args_cli.deterministic: + configure_seed(env_cfg.seed, True) + + print(f"[INFO] Loading model checkpoint from: {resume_path}") + runner.agent.load(resume_path) + runner.agent.enable_training_mode(False, apply_to_models=True) + + # reset environment + obs, _ = env.reset() + states = env.state() + timestep = 0 + # simulate environment + try: + while True: + start_time = time.time() + + with torch.inference_mode(): + outputs = runner.agent.act(obs, states, timestep=0, timesteps=0) + if hasattr(env, "possible_agents"): + actions = {a: outputs[-1][a].get("mean_actions", outputs[0][a]) for a in env.possible_agents} + else: + actions = outputs[-1].get("mean_actions", outputs[0]) + obs, _, _, _, _ = env.step(actions) + states = env.state() + if args_cli.video: + timestep += 1 + if timestep == args_cli.video_length: + break + + sleep_time = dt - (time.time() - start_time) + if args_cli.real_time and sleep_time > 0: + time.sleep(sleep_time) + + # close the simulator + env.close() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/skrl/play_skrl.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/skrl/play_skrl.py new file mode 100644 index 0000000000000000000000000000000000000000..96a6eaa0a47a591a6a17e764ddaf237b2bd679c7 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/skrl/play_skrl.py @@ -0,0 +1,235 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Script to play a checkpoint of an RL agent from skrl. + +Visit the skrl documentation (https://skrl.readthedocs.io) to see the examples structured in +a more user-friendly way. +""" + +import argparse +import contextlib +import os +import random +import sys +import time + +import gymnasium as gym +import skrl +import torch +from packaging import version + +from isaaclab.envs import DirectMARLEnvCfg +from isaaclab.utils.dict import print_dict + +from isaaclab_rl.utils.pretrained_checkpoint import get_published_pretrained_checkpoint + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + get_checkpoint_path, + launch_simulation, + resolve_task_config, + setup_preset_cli, +) + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + +SKRL_VERSION = "2.1.0" + +# -- argparse ---------------------------------------------------------------- +parser = argparse.ArgumentParser(description="Play a checkpoint of an RL agent from skrl.") +parser.add_argument("--video", action="store_true", default=False, help="Record videos during play.") +parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).") +parser.add_argument( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument( + "--agent", + type=str, + default=None, + help=( + "Name of the RL agent configuration entry point. Defaults to None, in which case the argument " + "--algorithm is used to determine the default agent configuration entry point." + ), +) +parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint.") +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument( + "--use_pretrained_checkpoint", + action="store_true", + help="Use the pre-trained checkpoint from Nucleus.", +) +parser.add_argument( + "--ml_framework", + type=str, + default="torch", + choices=["torch", "jax"], + help="The ML framework used for training the skrl agent.", +) +parser.add_argument( + "--algorithm", + type=str, + default="PPO", + choices=["AMP", "PPO", "IPPO", "MAPPO"], + help="The RL algorithm used for training the skrl agent.", +) +parser.add_argument("--real-time", action="store_true", default=False, help="Run in real-time, if possible.") +add_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) + +if args_cli.video: + args_cli.enable_cameras = True + +sys.argv = [sys.argv[0]] + hydra_args + +# -- check skrl version ------------------------------------------------------ +if version.parse(skrl.__version__) < version.parse(SKRL_VERSION): + skrl.logger.error( + f"Unsupported skrl version: {skrl.__version__}. " + f"Install supported version using 'pip install skrl>={SKRL_VERSION}'" + ) + exit() + +# config shortcuts +if args_cli.agent is None: + algorithm = args_cli.algorithm.lower() + agent_cfg_entry_point = "skrl_cfg_entry_point" if algorithm in ["ppo"] else f"skrl_{algorithm}_cfg_entry_point" +else: + agent_cfg_entry_point = args_cli.agent + algorithm = agent_cfg_entry_point.split("_cfg")[0].split("skrl_")[-1].lower() + + +def main(): + """Play with skrl agent.""" + env_cfg, experiment_cfg = resolve_task_config(args_cli.task, agent_cfg_entry_point) + with launch_simulation(env_cfg, args_cli): + if args_cli.ml_framework.startswith("torch"): + from skrl.utils.runner.torch import Runner + elif args_cli.ml_framework.startswith("jax"): + from skrl.utils.runner.jax import Runner + + from isaaclab_rl.skrl import SkrlVecEnvWrapper + + # grab task name for checkpoint path + task_name = args_cli.task.split(":")[-1] + train_task_name = task_name.replace("-Play", "") + + # override configurations with non-hydra CLI arguments + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + # configure the ML framework into the global skrl variable + if args_cli.ml_framework.startswith("jax"): + skrl.config.jax.backend = "jax" if args_cli.ml_framework == "jax" else "numpy" + + # randomly sample a seed if seed = -1 + if args_cli.seed == -1: + args_cli.seed = random.randint(0, 10000) + + # set the agent and environment seed from command line + experiment_cfg["seed"] = args_cli.seed if args_cli.seed is not None else experiment_cfg["seed"] + env_cfg.seed = experiment_cfg["seed"] + + # specify directory for logging experiments (load checkpoint) + log_root_path = os.path.join("logs", "skrl", experiment_cfg["agent"]["experiment"]["directory"]) + log_root_path = os.path.abspath(log_root_path) + print(f"[INFO] Loading experiment from directory: {log_root_path}") + # get checkpoint path + if args_cli.use_pretrained_checkpoint: + resume_path = get_published_pretrained_checkpoint("skrl", train_task_name) + if not resume_path: + print("[INFO] Unfortunately a pre-trained checkpoint is currently unavailable for this task.") + return + elif args_cli.checkpoint: + resume_path = os.path.abspath(args_cli.checkpoint) + else: + resume_path = get_checkpoint_path( + log_root_path, run_dir=f".*_{algorithm}_{args_cli.ml_framework}", other_dirs=["checkpoints"] + ) + log_dir = os.path.dirname(os.path.dirname(resume_path)) + + # set the log directory for the environment + env_cfg.log_dir = log_dir + + # create isaac environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + + # convert to single-agent instance if required by the RL algorithm + if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg) and algorithm in ["ppo"]: + from isaaclab.envs import multi_agent_to_single_agent + + env = multi_agent_to_single_agent(env) + + # get environment (step) dt for real-time evaluation + try: + dt = env.step_dt + except AttributeError: + dt = env.unwrapped.step_dt + + # wrap for video recording + if args_cli.video: + video_kwargs = { + "video_folder": os.path.join(log_dir, "videos", "play"), + "step_trigger": lambda step: step == 0, + "video_length": args_cli.video_length, + "disable_logger": True, + } + print("[INFO] Recording videos during play.") + print_dict(video_kwargs, nesting=4) + env = gym.wrappers.RecordVideo(env, **video_kwargs) + + # wrap around environment for skrl + env = SkrlVecEnvWrapper(env, ml_framework=args_cli.ml_framework) + + # configure and instantiate the skrl runner + experiment_cfg["trainer"]["close_environment_at_exit"] = False + experiment_cfg["agent"]["experiment"]["write_interval"] = 0 + experiment_cfg["agent"]["experiment"]["checkpoint_interval"] = 0 + runner = Runner(env, experiment_cfg) + + print(f"[INFO] Loading model checkpoint from: {resume_path}") + runner.agent.load(resume_path) + runner.agent.enable_training_mode(False, apply_to_models=True) + + # reset environment + obs, _ = env.reset() + states = env.state() + timestep = 0 + # simulate environment + try: + while True: + start_time = time.time() + + with torch.inference_mode(): + outputs = runner.agent.act(obs, states, timestep=0, timesteps=0) + if hasattr(env, "possible_agents"): + actions = {a: outputs[-1][a].get("mean_actions", outputs[0][a]) for a in env.possible_agents} + else: + actions = outputs[-1].get("mean_actions", outputs[0]) + obs, _, _, _, _ = env.step(actions) + states = env.state() + if args_cli.video: + timestep += 1 + if timestep == args_cli.video_length: + break + + sleep_time = dt - (time.time() - start_time) + if args_cli.real_time and sleep_time > 0: + time.sleep(sleep_time) + + # close the simulator + env.close() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/skrl/train.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/skrl/train.py new file mode 100644 index 0000000000000000000000000000000000000000..93a38dd79a2d8d1be2538ca4f2afe9e692a124f6 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/skrl/train.py @@ -0,0 +1,259 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Script to train RL agent with skrl. + +Visit the skrl documentation (https://skrl.readthedocs.io) to see the examples structured in +a more user-friendly way. +""" + +import warnings + +warnings.warn( + "scripts/reinforcement_learning/skrl/train.py is deprecated. Use " + "`./isaaclab.sh train --rl_library skrl --task ` instead. " + "Example: `./isaaclab.sh train --rl_library skrl --task Isaac-Cartpole-v0`.", + DeprecationWarning, + stacklevel=1, +) + +import argparse +import contextlib +import logging +import os +import random +import sys +import time +from datetime import datetime + +import gymnasium as gym +import skrl +from packaging import version + +from isaaclab.envs import DirectMARLEnvCfg, ManagerBasedRLEnvCfg +from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.dict import print_dict +from isaaclab.utils.io import dump_yaml +from isaaclab.utils.seed import configure_seed + +from isaaclab_rl.skrl import SkrlVecEnvWrapper + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + launch_simulation, + resolve_task_config, + setup_preset_cli, +) + +logger = logging.getLogger(__name__) + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + +SKRL_VERSION = "2.1.0" + +# -- argparse ---------------------------------------------------------------- +parser = argparse.ArgumentParser(description="Train an RL agent with skrl.") +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("--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( + "--agent", + type=str, + default=None, + help=( + "Name of the RL agent configuration entry point. Defaults to None, in which case the argument " + "--algorithm is used to determine the default agent configuration entry point." + ), +) +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument( + "--distributed", action="store_true", default=False, help="Run training with multiple GPUs or nodes." +) +parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint to resume training.") +parser.add_argument("--max_iterations", type=int, default=None, help="RL Policy training iterations.") +parser.add_argument("--export_io_descriptors", action="store_true", default=False, help="Export IO descriptors.") +parser.add_argument( + "--ml_framework", + type=str, + default="torch", + choices=["torch", "jax"], + help="The ML framework used for training the skrl agent.", +) +parser.add_argument( + "--algorithm", + type=str, + default="PPO", + choices=["AMP", "PPO", "IPPO", "MAPPO"], + help="The RL algorithm used for training the skrl agent.", +) +parser.add_argument( + "--ray-proc-id", "-rid", type=int, default=None, help="Automatically configured by Ray integration, otherwise None." +) +add_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args + +if args_cli.video: + args_cli.enable_cameras = True + +# -- check skrl version ------------------------------------------------------ +if version.parse(skrl.__version__) < version.parse(SKRL_VERSION): + skrl.logger.error( + f"Unsupported skrl version: {skrl.__version__}. " + f"Install supported version using 'pip install skrl>={SKRL_VERSION}'" + ) + exit() + +# config shortcuts +if args_cli.agent is None: + algorithm = args_cli.algorithm.lower() + agent_cfg_entry_point = "skrl_cfg_entry_point" if algorithm in ["ppo"] else f"skrl_{algorithm}_cfg_entry_point" +else: + agent_cfg_entry_point = args_cli.agent + algorithm = agent_cfg_entry_point.split("_cfg")[0].split("skrl_")[-1].lower() + + +def main(): + """Train with skrl agent.""" + env_cfg, agent_cfg = resolve_task_config(args_cli.task, agent_cfg_entry_point) + with launch_simulation(env_cfg, args_cli): + if args_cli.ml_framework.startswith("torch"): + from skrl.utils.runner.torch import Runner + elif args_cli.ml_framework.startswith("jax"): + from skrl.utils.runner.jax import Runner + + # override configurations with non-hydra CLI arguments + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + # For distributed training, launch_simulation() already resolved the + # correct per-rank device; only apply a CLI --device override for + # non-distributed runs (the default "cuda:0" would clobber the + # per-rank device otherwise). + if not args_cli.distributed: + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + if args_cli.distributed and args_cli.device is not None and "cpu" in args_cli.device: + raise ValueError( + "Distributed training is not supported when using CPU device. " + "Please use GPU device (e.g., --device cuda) for distributed training." + ) + + # multi-gpu training config + if args_cli.distributed: + global_rank = int(os.getenv("RANK", "0")) + # env_cfg.sim.device is resolved by launch_simulation() which + # accounts for CUDA_VISIBLE_DEVICES restrictions. + # max iterations for training + if args_cli.max_iterations: + agent_cfg["trainer"]["timesteps"] = args_cli.max_iterations * agent_cfg["agent"]["rollouts"] + agent_cfg["trainer"]["close_environment_at_exit"] = False + # configure the ML framework into the global skrl variable + if args_cli.ml_framework.startswith("jax"): + skrl.config.jax.backend = "jax" if args_cli.ml_framework == "jax" else "numpy" + + # randomly sample a seed if seed = -1 + if args_cli.seed == -1: + args_cli.seed = random.randint(0, 10000) + + # set the agent and environment seed from command line + agent_cfg["seed"] = args_cli.seed if args_cli.seed is not None else agent_cfg["seed"] + # use global rank for seed diversity across all nodes + if args_cli.distributed: + agent_cfg["seed"] = agent_cfg["seed"] + global_rank + env_cfg.seed = agent_cfg["seed"] + + # specify directory for logging experiments + log_root_path = os.path.join("logs", "skrl", agent_cfg["agent"]["experiment"]["directory"]) + log_root_path = os.path.abspath(log_root_path) + print(f"[INFO] Logging experiment in directory: {log_root_path}") + log_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + f"_{algorithm}_{args_cli.ml_framework}" + print(f"Exact experiment name requested from command line: {log_dir}") + if agent_cfg["agent"]["experiment"]["experiment_name"]: + log_dir += f"_{agent_cfg['agent']['experiment']['experiment_name']}" + agent_cfg["agent"]["experiment"]["directory"] = log_root_path + agent_cfg["agent"]["experiment"]["experiment_name"] = log_dir + log_dir = os.path.join(log_root_path, log_dir) + + # 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) + + # get checkpoint path (to resume training) + resume_path = retrieve_file_path(args_cli.checkpoint) if args_cli.checkpoint else None + + # set the IO descriptors export flag if requested + if isinstance(env_cfg, ManagerBasedRLEnvCfg): + env_cfg.export_io_descriptors = args_cli.export_io_descriptors + else: + logger.warning( + "IO descriptors are only supported for manager based RL environments." + " No IO descriptors will be exported." + ) + + # set the log directory for the environment + env_cfg.log_dir = log_dir + + # create isaac environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + + # convert to single-agent instance if required by the RL algorithm + if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg) and algorithm in ["ppo"]: + from isaaclab.envs import multi_agent_to_single_agent + + env = multi_agent_to_single_agent(env) + + # wrap for video recording + if args_cli.video: + video_kwargs = { + "video_folder": os.path.join(log_dir, "videos", "train"), + "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) + + start_time = time.time() + + # wrap around environment for skrl + env = SkrlVecEnvWrapper(env, ml_framework=args_cli.ml_framework) + + # configure and instantiate the skrl runner + runner = Runner(env, agent_cfg) + # configure_seed must be called after Runner() so that PyTorch deterministic settings + # do not interfere with Runner's internal initialization. + if args_cli.deterministic: + configure_seed(env_cfg.seed, True) + + # load checkpoint (if specified) + if resume_path: + print(f"[INFO] Loading model checkpoint from: {resume_path}") + runner.agent.load(resume_path) + + # run training + try: + runner.run() + print(f"Training time: {round(time.time() - start_time, 2)} seconds") + + # skrl only saves checkpoints at checkpoint_interval multiples during training, + # so save a final checkpoint to ensure at least one always exists + total_timesteps = agent_cfg["trainer"]["timesteps"] + os.makedirs(os.path.join(log_dir, "checkpoints"), exist_ok=True) + runner.agent.write_checkpoint(timestep=total_timesteps, timesteps=total_timesteps) + print(f"[INFO] Saved final agent checkpoint to: {log_dir}/checkpoints") + # close the simulator + env.close() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/skrl/train_skrl.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/skrl/train_skrl.py new file mode 100644 index 0000000000000000000000000000000000000000..f6a6f42df38b045e7fa09ab724d9624687aba76c --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/skrl/train_skrl.py @@ -0,0 +1,184 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""skrl training logic for the unified reinforcement learning entrypoint.""" + +from __future__ import annotations + +import argparse +import contextlib +import logging +import os +import random +import time +from datetime import datetime + +from common import ( + add_common_train_args, + add_isaaclab_launcher_args, + apply_env_overrides, + configure_io_descriptors, + create_isaaclab_env, + dump_train_configs, + enable_cameras_for_video, + set_hydra_args, + validate_distributed_device, + wrap_record_video, +) +from packaging import version + +import isaaclab_tasks # noqa: F401 + +logger = logging.getLogger(__name__) + +SKRL_VERSION = "2.1.0" + +# PLACEHOLDER: Extension template (do not remove this comment) +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 + + +def _parse_args(argv: list[str]) -> argparse.Namespace: + """Parse skrl training arguments.""" + parser = argparse.ArgumentParser(description="Train an RL agent with skrl.") + add_common_train_args( + parser, + agent_default=None, + agent_help=( + "Name of the RL agent configuration entry point. Defaults to None, in which case the argument " + "--algorithm is used to determine the default agent configuration entry point." + ), + ) + parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint to resume training.") + parser.add_argument( + "--ml_framework", + type=str, + default="torch", + choices=["torch", "jax"], + help="The ML framework used for training the skrl agent.", + ) + parser.add_argument( + "--algorithm", + type=str, + default="PPO", + choices=["AMP", "PPO", "IPPO", "MAPPO"], + help="The RL algorithm used for training the skrl agent.", + ) + from isaaclab_tasks.utils import setup_preset_cli + + add_isaaclab_launcher_args(parser) + # setup_preset_cli registers preset-selection help text + runs parse_known_args; the + # physics=/renderer=/presets= tokens pass through the remainder for hydra to parse later. + args_cli, hydra_args = setup_preset_cli(parser, argv) + enable_cameras_for_video(args_cli) + set_hydra_args(hydra_args) + return args_cli + + +def _resolve_agent_entry_point(args_cli: argparse.Namespace) -> tuple[str, str]: + """Resolve the skrl agent entry point and algorithm from CLI arguments.""" + if args_cli.agent is None: + algorithm = args_cli.algorithm.lower() + agent_cfg_entry_point = "skrl_cfg_entry_point" if algorithm in ["ppo"] else f"skrl_{algorithm}_cfg_entry_point" + else: + agent_cfg_entry_point = args_cli.agent + algorithm = agent_cfg_entry_point.split("_cfg")[0].split("skrl_")[-1].lower() + return agent_cfg_entry_point, algorithm + + +def run(argv: list[str]) -> None: + """Train a skrl agent.""" + import skrl + + from isaaclab.envs import DirectMARLEnvCfg + from isaaclab.utils.assets import retrieve_file_path + + from isaaclab_rl.skrl import SkrlVecEnvWrapper + + from isaaclab_tasks.utils import launch_simulation, resolve_task_config + + args_cli = _parse_args(argv) + + if version.parse(skrl.__version__) < version.parse(SKRL_VERSION): + skrl.logger.error( + f"Unsupported skrl version: {skrl.__version__}. " + f"Install supported version using 'pip install skrl>={SKRL_VERSION}'" + ) + raise SystemExit(1) + + agent_cfg_entry_point, algorithm = _resolve_agent_entry_point(args_cli) + env_cfg, agent_cfg = resolve_task_config(args_cli.task, agent_cfg_entry_point) + + with launch_simulation(env_cfg, args_cli): + if args_cli.ml_framework.startswith("torch"): + from skrl.utils.runner.torch import Runner + elif args_cli.ml_framework.startswith("jax"): + from skrl.utils.runner.jax import Runner + + apply_env_overrides(args_cli, env_cfg) + validate_distributed_device(args_cli) + + if args_cli.distributed: + global_rank = int(os.getenv("RANK", "0")) + + if args_cli.max_iterations: + agent_cfg["trainer"]["timesteps"] = args_cli.max_iterations * agent_cfg["agent"]["rollouts"] + agent_cfg["trainer"]["close_environment_at_exit"] = False + + if args_cli.ml_framework.startswith("jax"): + skrl.config.jax.backend = "jax" if args_cli.ml_framework == "jax" else "numpy" + + if args_cli.seed == -1: + args_cli.seed = random.randint(0, 10000) + + agent_cfg["seed"] = args_cli.seed if args_cli.seed is not None else agent_cfg["seed"] + if args_cli.distributed: + agent_cfg["seed"] = agent_cfg["seed"] + global_rank + env_cfg.seed = agent_cfg["seed"] + + log_root_path = os.path.abspath(os.path.join("logs", "skrl", agent_cfg["agent"]["experiment"]["directory"])) + print(f"[INFO] Logging experiment in directory: {log_root_path}") + log_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + f"_{algorithm}_{args_cli.ml_framework}" + print(f"Exact experiment name requested from command line: {log_dir}") + if agent_cfg["agent"]["experiment"]["experiment_name"]: + log_dir += f"_{agent_cfg['agent']['experiment']['experiment_name']}" + agent_cfg["agent"]["experiment"]["directory"] = log_root_path + agent_cfg["agent"]["experiment"]["experiment_name"] = log_dir + log_dir = os.path.join(log_root_path, log_dir) + + dump_train_configs(log_dir, env_cfg, agent_cfg) + + resume_path = retrieve_file_path(args_cli.checkpoint) if args_cli.checkpoint else None + + configure_io_descriptors(env_cfg, args_cli, logger) + env_cfg.log_dir = log_dir + + env = create_isaaclab_env( + args_cli.task, + env_cfg, + args_cli, + convert_marl_to_single_agent=isinstance(env_cfg, DirectMARLEnvCfg) and algorithm in ["ppo"], + ) + env = wrap_record_video(env, log_dir, args_cli) + + start_time = time.time() + env = SkrlVecEnvWrapper(env, ml_framework=args_cli.ml_framework) + runner = Runner(env, agent_cfg) + + if resume_path: + print(f"[INFO] Loading model checkpoint from: {resume_path}") + runner.agent.load(resume_path) + + try: + runner.run() + print(f"Training time: {round(time.time() - start_time, 2)} seconds") + + total_timesteps = agent_cfg["trainer"]["timesteps"] + os.makedirs(os.path.join(log_dir, "checkpoints"), exist_ok=True) + runner.agent.write_checkpoint(timestep=total_timesteps, timesteps=total_timesteps) + print(f"[INFO] Saved final agent checkpoint to: {log_dir}/checkpoints") + env.close() + except KeyboardInterrupt: + pass diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/test/test_typed_preset_cli_train_play.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/test/test_typed_preset_cli_train_play.py new file mode 100644 index 0000000000000000000000000000000000000000..09e58b588e1bf4c9da1909e3c72dcf122c8ecd48 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/test/test_typed_preset_cli_train_play.py @@ -0,0 +1,101 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""End-to-end test that typed preset selectors reach the resolver from each +unified train/play entrypoint. + +The four supported RL libraries (rl_games, rsl_rl, sb3, skrl) each have a +``train_.py`` / ``play_.py`` script that the unified +``scripts/reinforcement_learning/{train,play}.py`` dispatchers route to via +``--rl_library``. Each entrypoint must wire :func:`setup_preset_cli` and pass +its remainder through to Hydra so that user-typed ``physics=NAME`` / +``renderer=NAME`` / ``presets=NAME`` tokens reach +:func:`~isaaclab_tasks.utils.hydra.register_task`, which parses them directly. +If an entrypoint dropped the remainder (or routed the token to Hydra as a raw +override), the token would hit Hydra as a struct override against a +non-existent top-level key and raise ``Key 'physics' is not in struct`` -- the +original symptom of the #5715 regression. + +This test invokes each entrypoint via the unified dispatcher with +``physics=does_not_exist`` and asserts: + +* the Hydra struct error is **absent** (would indicate the token was not + routed to ``register_task``), and +* the resolver's own ``Unknown preset(s)`` error is **present** (the token + reached the resolver). + +Resolve fails before any Kit/sim launch, so each subprocess exits in a +few seconds without needing GPU. + +``rlinf`` is intentionally excluded: those scripts manage their own +``GlobalHydra`` instance and have never been integrated with the typed +preset CLI. +""" + +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[3] + +# Each (action, library) pair runs through the unified dispatcher at +# ``scripts/reinforcement_learning/{action}.py``. Dispatching matches how +# ``./isaaclab.sh train`` / ``./isaaclab.sh play`` invoke these in practice. +_ENTRYPOINT_CASES = [ + (action, library) for action in ("train", "play") for library in ("rl_games", "rsl_rl", "sb3", "skrl") +] + + +@pytest.mark.parametrize("action,library", _ENTRYPOINT_CASES) +def test_typed_preset_reaches_resolver(action: str, library: str) -> None: + """``physics=`` must reach the resolver, not crash Hydra's struct check. + + Confirms that the dispatched entrypoint wired ``setup_preset_cli`` and + passed its remainder through, so the typed selector reached + ``register_task``, which surfaced its own ``Unknown preset(s)`` error + against the deliberately invalid name. + """ + dispatcher = REPO_ROOT / "scripts" / "reinforcement_learning" / f"{action}.py" + assert dispatcher.exists(), f"missing dispatcher: {dispatcher}" + + cmd = [ + sys.executable, + str(dispatcher), + "--rl_library", + library, + "--task=Isaac-Ant-v0", + "physics=does_not_exist", + "--headless", + ] + result = subprocess.run( + cmd, + cwd=REPO_ROOT, + capture_output=True, + text=True, + timeout=120, + check=False, + env=os.environ.copy(), + ) + + combined = result.stdout + result.stderr + label = f"{action}.py --rl_library {library}" + assert "is not in struct" not in combined, ( + f"{label}: Hydra's struct-override error reached the user, meaning the typed preset " + f"selector was routed to Hydra as a raw override instead of register_task. The entrypoint " + f"must call setup_preset_cli and pass its remainder through to set_hydra_args / sys.argv.\n" + f"--- stderr tail ---\n{result.stderr[-2000:]}\n" + f"--- stdout tail ---\n{result.stdout[-2000:]}\n" + ) + assert "Unknown preset(s): does_not_exist" in combined, ( + f"{label}: resolver's 'Unknown preset(s)' error did not appear. Either the token did not " + f"reach the resolver, or the script exited earlier with a different error.\n" + f"--- stderr tail ---\n{result.stderr[-2000:]}\n" + f"--- stdout tail ---\n{result.stdout[-2000:]}\n" + ) diff --git a/simulation/modules/IsaacLab/scripts/reinforcement_learning/train.py b/simulation/modules/IsaacLab/scripts/reinforcement_learning/train.py new file mode 100644 index 0000000000000000000000000000000000000000..99313867c2a2d2ff88aac38c25c340568f8a8fa0 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/reinforcement_learning/train.py @@ -0,0 +1,37 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unified training entrypoint for Isaac Lab reinforcement learning workflows.""" + +from __future__ import annotations + +from pathlib import Path + +from common import dispatch_library_entrypoint + +SCRIPT_DIR = Path(__file__).resolve().parent + +LIBRARY_ENTRYPOINTS = { + "rl_games": SCRIPT_DIR / "rl_games" / "train_rl_games.py", + "rlinf": SCRIPT_DIR / "rlinf" / "train_rlinf.py", + "rsl_rl": SCRIPT_DIR / "rsl_rl" / "train_rsl_rl.py", + "sb3": SCRIPT_DIR / "sb3" / "train_sb3.py", + "skrl": SCRIPT_DIR / "skrl" / "train_skrl.py", +} + + +def main(argv: list[str] | None = None) -> int: + """Run the selected reinforcement learning training library.""" + return dispatch_library_entrypoint( + argv, + LIBRARY_ENTRYPOINTS, + action="train", + description="Train an RL agent with a selected reinforcement learning library.", + library_help="Training library to use.", + ) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/simulation/modules/IsaacLab/scripts/sim2sim_transfer/config/newton_to_physx_anymal_d.yaml b/simulation/modules/IsaacLab/scripts/sim2sim_transfer/config/newton_to_physx_anymal_d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..00d2925345b161e9470d353340a325a0ae22fac4 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/sim2sim_transfer/config/newton_to_physx_anymal_d.yaml @@ -0,0 +1,34 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# Joint names in the source physics engine where policy is trained (Newton) +source_joint_names: + - "LF_HAA" + - "LF_HFE" + - "LF_KFE" + - "LH_HAA" + - "LH_HFE" + - "LH_KFE" + - "RF_HAA" + - "RF_HFE" + - "RF_KFE" + - "RH_HAA" + - "RH_HFE" + - "RH_KFE" + +# Joint names in the target physics engine where policy is deployed (PhysX) +target_joint_names: + - "LF_HAA" + - "LH_HAA" + - "RF_HAA" + - "RH_HAA" + - "LF_HFE" + - "LH_HFE" + - "RF_HFE" + - "RH_HFE" + - "LF_KFE" + - "LH_KFE" + - "RF_KFE" + - "RH_KFE" diff --git a/simulation/modules/IsaacLab/scripts/sim2sim_transfer/config/newton_to_physx_g1.yaml b/simulation/modules/IsaacLab/scripts/sim2sim_transfer/config/newton_to_physx_g1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..839980c4d10e74818fc4618dc9b563f42aa5ab2f --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/sim2sim_transfer/config/newton_to_physx_g1.yaml @@ -0,0 +1,84 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# Joint names in the source physics engine where policy is trained (Newton) +source_joint_names: + - "left_hip_pitch_joint" + - "left_hip_roll_joint" + - "left_hip_yaw_joint" + - "left_knee_joint" + - "left_ankle_pitch_joint" + - "left_ankle_roll_joint" + - "right_hip_pitch_joint" + - "right_hip_roll_joint" + - "right_hip_yaw_joint" + - "right_knee_joint" + - "right_ankle_pitch_joint" + - "right_ankle_roll_joint" + - "torso_joint" + - "left_shoulder_pitch_joint" + - "left_shoulder_roll_joint" + - "left_shoulder_yaw_joint" + - "left_elbow_pitch_joint" + - "left_elbow_roll_joint" + - "left_five_joint" + - "left_six_joint" + - "left_three_joint" + - "left_four_joint" + - "left_zero_joint" + - "left_one_joint" + - "left_two_joint" + - "right_shoulder_pitch_joint" + - "right_shoulder_roll_joint" + - "right_shoulder_yaw_joint" + - "right_elbow_pitch_joint" + - "right_elbow_roll_joint" + - "right_five_joint" + - "right_six_joint" + - "right_three_joint" + - "right_four_joint" + - "right_zero_joint" + - "right_one_joint" + - "right_two_joint" + +# Joint names in the target physics engine where policy is deployed (PhysX) +target_joint_names: + - "left_hip_pitch_joint" + - "right_hip_pitch_joint" + - "torso_joint" + - "left_hip_roll_joint" + - "right_hip_roll_joint" + - "left_shoulder_pitch_joint" + - "right_shoulder_pitch_joint" + - "left_hip_yaw_joint" + - "right_hip_yaw_joint" + - "left_shoulder_roll_joint" + - "right_shoulder_roll_joint" + - "left_knee_joint" + - "right_knee_joint" + - "left_shoulder_yaw_joint" + - "right_shoulder_yaw_joint" + - "left_ankle_pitch_joint" + - "right_ankle_pitch_joint" + - "left_elbow_pitch_joint" + - "right_elbow_pitch_joint" + - "left_ankle_roll_joint" + - "right_ankle_roll_joint" + - "left_elbow_roll_joint" + - "right_elbow_roll_joint" + - "left_five_joint" + - "left_three_joint" + - "left_zero_joint" + - "right_five_joint" + - "right_three_joint" + - "right_zero_joint" + - "left_six_joint" + - "left_four_joint" + - "left_one_joint" + - "right_six_joint" + - "right_four_joint" + - "right_one_joint" + - "left_two_joint" + - "right_two_joint" diff --git a/simulation/modules/IsaacLab/scripts/sim2sim_transfer/config/newton_to_physx_go2.yaml b/simulation/modules/IsaacLab/scripts/sim2sim_transfer/config/newton_to_physx_go2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d9f976ee1bb683a943aafc9460193d8b5cb417cf --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/sim2sim_transfer/config/newton_to_physx_go2.yaml @@ -0,0 +1,33 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# Joint names in the source physics engine where policy is trained (Newton) +source_joint_names: + - "FL_hip_joint" + - "FL_thigh_joint" + - "FL_calf_joint" + - "FR_hip_joint" + - "FR_thigh_joint" + - "FR_calf_joint" + - "RL_hip_joint" + - "RL_thigh_joint" + - "RL_calf_joint" + - "RR_hip_joint" + - "RR_thigh_joint" + - "RR_calf_joint" +# Joint names in the target physics engine where policy is deployed (PhysX) +target_joint_names: + - "FL_hip_joint" + - "FR_hip_joint" + - "RL_hip_joint" + - "RR_hip_joint" + - "FL_thigh_joint" + - "FR_thigh_joint" + - "RL_thigh_joint" + - "RR_thigh_joint" + - "FL_calf_joint" + - "FR_calf_joint" + - "RL_calf_joint" + - "RR_calf_joint" diff --git a/simulation/modules/IsaacLab/scripts/sim2sim_transfer/config/newton_to_physx_h1.yaml b/simulation/modules/IsaacLab/scripts/sim2sim_transfer/config/newton_to_physx_h1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cb0e0996f054dae891c3881edc582776a55f42c1 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/sim2sim_transfer/config/newton_to_physx_h1.yaml @@ -0,0 +1,48 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# Joint names in the source physics engine where policy is trained (Newton) +source_joint_names: + - "left_hip_yaw" + - "left_hip_roll" + - "left_hip_pitch" + - "left_knee" + - "left_ankle" + - "right_hip_yaw" + - "right_hip_roll" + - "right_hip_pitch" + - "right_knee" + - "right_ankle" + - "torso" + - "left_shoulder_pitch" + - "left_shoulder_roll" + - "left_shoulder_yaw" + - "left_elbow" + - "right_shoulder_pitch" + - "right_shoulder_roll" + - "right_shoulder_yaw" + - "right_elbow" + +# Joint names in the target physics engine where policy is deployed (PhysX) +target_joint_names: + - "left_hip_yaw" + - "right_hip_yaw" + - "torso" + - "left_hip_roll" + - "right_hip_roll" + - "left_shoulder_pitch" + - "right_shoulder_pitch" + - "left_hip_pitch" + - "right_hip_pitch" + - "left_shoulder_roll" + - "right_shoulder_roll" + - "left_knee" + - "right_knee" + - "left_shoulder_yaw" + - "right_shoulder_yaw" + - "left_ankle" + - "right_ankle" + - "left_elbow" + - "right_elbow" diff --git a/simulation/modules/IsaacLab/scripts/sim2sim_transfer/rsl_rl_transfer.py b/simulation/modules/IsaacLab/scripts/sim2sim_transfer/rsl_rl_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..528d24ded94691d04eceeb74f77a4580dcef1f40 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/sim2sim_transfer/rsl_rl_transfer.py @@ -0,0 +1,283 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to play a checkpoint of an RL agent from RSL-RL with policy transfer capabilities.""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +import os +import sys + +from isaaclab.app import AppLauncher + +from isaaclab_tasks.utils import setup_preset_cli + +# local imports +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../..")) +from scripts.reinforcement_learning.rsl_rl import cli_args # isort: skip + +# add argparse arguments +parser = argparse.ArgumentParser(description="Play an RL agent with RSL-RL with policy transfer.") +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( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +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( + "--agent", type=str, default="rsl_rl_cfg_entry_point", help="Name of the RL agent configuration entry point." +) +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument("--real-time", action="store_true", default=False, help="Run in real-time, if possible.") +# Joint ordering arguments +parser.add_argument( + "--policy_transfer_file", + type=str, + default=None, + help="Path to YAML file containing joint mapping configuration for policy transfer between physics engines.", +) +# append RSL-RL cli arguments +cli_args.add_rsl_rl_args(parser) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) +sys.argv = [sys.argv[0]] + hydra_args +if args_cli.video: + args_cli.enable_cameras = True + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import os +import time + +import gymnasium as gym +import torch +import yaml +from rsl_rl.runners import DistillationRunner, OnPolicyRunner + +from isaaclab.envs import ( + DirectMARLEnv, + DirectMARLEnvCfg, + DirectRLEnvCfg, + ManagerBasedRLEnvCfg, + multi_agent_to_single_agent, +) +from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.dict import print_dict + +from isaaclab_rl.rsl_rl import RslRlBaseRunnerCfg, RslRlVecEnvWrapper, export_policy_as_jit, export_policy_as_onnx + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import get_checkpoint_path, hydra_task_config + +# PLACEHOLDER: Extension template (do not remove this comment) + + +def get_joint_mappings(args_cli, action_space_dim): + """Get joint mappings based on command line arguments. + + Args: + args_cli: Command line arguments + action_space_dim: Dimension of the action space (number of joints) + + Returns: + tuple: (source_to_target_list, target_to_source_list, source_to_target_obs_list) + """ + num_joints = action_space_dim + if args_cli.policy_transfer_file: + # Load from YAML file + try: + with open(args_cli.policy_transfer_file) as file: + config = yaml.safe_load(file) + except Exception as e: + raise RuntimeError(f"Failed to load joint mapping from {args_cli.policy_transfer_file}: {e}") + + source_joint_names = config["source_joint_names"] + target_joint_names = config["target_joint_names"] + # Find joint mapping + source_to_target = [] + target_to_source = [] + + # Create source to target mapping + for joint_name in source_joint_names: + if joint_name in target_joint_names: + source_to_target.append(target_joint_names.index(joint_name)) + else: + raise ValueError(f"Joint '{joint_name}' not found in target joint names") + + # Create target to source mapping + for joint_name in target_joint_names: + if joint_name in source_joint_names: + target_to_source.append(source_joint_names.index(joint_name)) + else: + raise ValueError(f"Joint '{joint_name}' not found in source joint names") + print(f"[INFO] Loaded joint mapping for policy transfer from YAML: {args_cli.policy_transfer_file}") + assert len(source_to_target) == len(target_to_source) == num_joints, ( + "Number of source and target joints must match" + ) + else: + # Use identity mapping (one-to-one) + identity_map = list(range(num_joints)) + source_to_target, target_to_source = identity_map, identity_map + + # Create observation mapping (first 12 values stay the same for locomotion examples, then map joint-related values) + obs_map = ( + [0, 1, 2] + + [3, 4, 5] + + [6, 7, 8] + + [9, 10, 11] + + [i + 12 + num_joints * 0 for i in source_to_target] + + [i + 12 + num_joints * 1 for i in source_to_target] + + [i + 12 + num_joints * 2 for i in source_to_target] + ) + + return source_to_target, target_to_source, obs_map + + +@hydra_task_config(args_cli.task, args_cli.agent) +def main(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agent_cfg: RslRlBaseRunnerCfg): + """Play with RSL-RL agent with policy transfer capabilities.""" + + # override configurations with non-hydra CLI arguments + agent_cfg = cli_args.update_rsl_rl_cfg(agent_cfg, args_cli) + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + + # set the environment seed + # note: certain randomizations occur in the environment initialization so we set the seed here + env_cfg.seed = agent_cfg.seed + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + # 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}") + if args_cli.checkpoint: + resume_path = retrieve_file_path(args_cli.checkpoint) + else: + resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) + + log_dir = os.path.dirname(resume_path) + + # set the log directory for the environment (works for all environment types) + env_cfg.log_dir = log_dir + + # create isaac environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + + # convert to single-agent instance if required by the RL algorithm + if isinstance(env.unwrapped, DirectMARLEnv): + env = multi_agent_to_single_agent(env) + + # wrap for video recording + if args_cli.video: + video_kwargs = { + "video_folder": os.path.join(log_dir, "videos", "play"), + "step_trigger": lambda step: step == 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, clip_actions=agent_cfg.clip_actions) + + print(f"[INFO]: Loading model checkpoint from: {resume_path}") + # load previously trained model + if agent_cfg.class_name == "OnPolicyRunner": + runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + elif agent_cfg.class_name == "DistillationRunner": + runner = DistillationRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + else: + raise ValueError(f"Unsupported runner class: {agent_cfg.class_name}") + runner.load(resume_path) + + # obtain the trained policy for inference + policy = runner.get_inference_policy(device=env.unwrapped.device) + + # extract the neural network module + # we do this in a try-except to maintain backwards compatibility. + try: + # version 2.3 onwards + policy_nn = runner.alg.policy + except AttributeError: + # version 2.2 and below + policy_nn = runner.alg.actor_critic + + # extract the normalizer + if hasattr(policy_nn, "actor_obs_normalizer"): + normalizer = policy_nn.actor_obs_normalizer + elif hasattr(policy_nn, "student_obs_normalizer"): + normalizer = policy_nn.student_obs_normalizer + else: + normalizer = None + + # export policy to onnx/jit + export_model_dir = os.path.join(os.path.dirname(resume_path), "exported") + export_policy_as_jit(policy_nn, normalizer=normalizer, path=export_model_dir, filename="policy.pt") + export_policy_as_onnx(policy_nn, normalizer=normalizer, path=export_model_dir, filename="policy.onnx") + + dt = env.unwrapped.step_dt + + # reset environment + obs = env.get_observations() + timestep = 0 + + # Get joint mappings for policy transfer + _, target_to_source, obs_map = get_joint_mappings(args_cli, env.action_space.shape[1]) + + # Create torch tensors for mappings + device = args_cli.device if args_cli.device else "cuda:0" + target_to_source_tensor = torch.tensor(target_to_source, device=device) if target_to_source else None + obs_map_tensor = torch.tensor(obs_map, device=device) if obs_map else None + + def remap_obs(obs): + """Remap the observation to the target observation space.""" + if obs_map_tensor is not None: + obs = obs[:, obs_map_tensor] + return obs + + def remap_actions(actions): + """Remap the actions to the target action space.""" + if target_to_source_tensor is not None: + actions = actions[:, target_to_source_tensor] + return actions + + # simulate environment + while simulation_app.is_running(): + start_time = time.time() + # run everything in inference mode + with torch.inference_mode(): + # agent stepping + actions = policy(remap_obs(obs)) + # env stepping + obs, _, _, _ = env.step(remap_actions(actions)) + if args_cli.video: + timestep += 1 + # Exit the play loop after recording one video + if timestep == args_cli.video_length: + break + + # time delay for real-time evaluation + sleep_time = dt - (time.time() - start_time) + if args_cli.real_time and sleep_time > 0: + time.sleep(sleep_time) + + # close the simulator + env.close() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tools/blender_obj.py b/simulation/modules/IsaacLab/scripts/tools/blender_obj.py new file mode 100644 index 0000000000000000000000000000000000000000..c03a525fae499ca88f49d993b95bb87c3295c5ed --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/blender_obj.py @@ -0,0 +1,100 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Convert a mesh file to `.obj` using blender. + +This file processes a given dae mesh file and saves the resulting mesh file in obj format. + +It needs to be called using the python packaged with blender, i.e.: + + blender --background --python blender_obj.py -- -in_file FILE -out_file FILE + +For more information: https://docs.blender.org/api/current/index.html + +The script was tested on Blender 3.2 on Ubuntu 20.04LTS. +""" + +import os +import sys + +import bpy + + +def parse_cli_args(): + """Parse the input command line arguments.""" + import argparse + + # get the args passed to blender after "--", all of which are ignored by + # blender so scripts may receive their own arguments + argv = sys.argv + + if "--" not in argv: + argv = [] # as if no args are passed + else: + argv = argv[argv.index("--") + 1 :] # get all args after "--" + + # When --help or no args are given, print this help + usage_text = ( + f"Run blender in background mode with this script:\n\tblender --background --python {__file__} -- [options]" + ) + parser = argparse.ArgumentParser(description=usage_text) + # Add arguments + parser.add_argument("-i", "--in_file", metavar="FILE", type=str, required=True, help="Path to input OBJ file.") + parser.add_argument("-o", "--out_file", metavar="FILE", type=str, required=True, help="Path to output OBJ file.") + args = parser.parse_args(argv) + # Check if any arguments provided + if not argv or not args.in_file or not args.out_file: + parser.print_help() + return None + # return arguments + return args + + +def convert_to_obj(in_file: str, out_file: str, save_usd: bool = False): + """Convert a mesh file to `.obj` using blender. + + Args: + in_file: Input mesh file to process. + out_file: Path to store output obj file. + """ + # check valid input file + if not os.path.exists(in_file): + raise FileNotFoundError(in_file) + # add ending of file format + if not out_file.endswith(".obj"): + out_file += ".obj" + # create directory if it doesn't exist for destination file + if not os.path.exists(os.path.dirname(out_file)): + os.makedirs(os.path.dirname(out_file), exist_ok=True) + # reset scene to empty + bpy.ops.wm.read_factory_settings(use_empty=True) + # load object into scene + if in_file.endswith(".dae"): + bpy.ops.wm.collada_import(filepath=in_file) + elif in_file.endswith(".stl") or in_file.endswith(".STL"): + bpy.ops.import_mesh.stl(filepath=in_file) + else: + raise ValueError(f"Input file not in dae/stl format: {in_file}") + # convert to obj format and store with z up + # TODO: Read the convention from dae file instead of manually fixing it. + # Reference: https://docs.blender.org/api/2.79/bpy.ops.export_scene.html + bpy.ops.export_scene.obj( + filepath=out_file, check_existing=False, axis_forward="Y", axis_up="Z", global_scale=1, path_mode="RELATIVE" + ) + # save it as usd as well + if save_usd: + out_file = out_file.replace("obj", "usd") + bpy.ops.wm.usd_export(filepath=out_file, check_existing=False) + + +if __name__ == "__main__": + # read arguments + cli_args = parse_cli_args() + # check CLI args + if cli_args is None: + sys.exit() + # process via blender + convert_to_obj(cli_args.in_file, cli_args.out_file) diff --git a/simulation/modules/IsaacLab/scripts/tools/check_instanceable.py b/simulation/modules/IsaacLab/scripts/tools/check_instanceable.py new file mode 100644 index 0000000000000000000000000000000000000000..71e1fe0f66b663d1e2b71bea0718578f6e59d05a --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/check_instanceable.py @@ -0,0 +1,128 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script uses the cloner API to check if asset has been instanced properly. + +Usage with different inputs (replace `` and `` with the path to the +original asset and the instanced asset respectively): + +```bash +./isaaclab.sh -p source/tools/check_instanceable.py -n 4096 --headless --physics +./isaaclab.sh -p source/tools/check_instanceable.py -n 4096 --headless --physics +./isaaclab.sh -p source/tools/check_instanceable.py -n 4096 --headless +./isaaclab.sh -p source/tools/check_instanceable.py -n 4096 --headless +``` + +Output from the above commands: + +```bash +>>> Cloning time (cloner.clone): 0.648198 seconds +>>> Setup time (sim.reset): : 5.843589 seconds +[#clones: 4096, physics: True] Asset: : 6.491870 seconds + +>>> Cloning time (cloner.clone): 0.693133 seconds +>>> Setup time (sim.reset): 50.860526 seconds +[#clones: 4096, physics: True] Asset: : 51.553743 seconds + +>>> Cloning time (cloner.clone) : 0.687201 seconds +>>> Setup time (sim.reset) : 6.302215 seconds +[#clones: 4096, physics: False] Asset: : 6.989500 seconds + +>>> Cloning time (cloner.clone) : 0.678150 seconds +>>> Setup time (sim.reset) : 52.854054 seconds +[#clones: 4096, physics: False] Asset: : 53.532287 seconds +``` + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +import contextlib +import os + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser("Utility to empirically check if asset in instanced properly.") +parser.add_argument("input", type=str, help="The path to the USD file.") +parser.add_argument("-n", "--num_clones", type=int, default=128, help="Number of clones to spawn.") +parser.add_argument("-s", "--spacing", type=float, default=1.5, help="Spacing between instances in a grid.") +parser.add_argument("-p", "--physics", action="store_true", default=False, help="Clone assets using physics cloner.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + + +from isaacsim.core.cloner import GridCloner + +import isaaclab.sim as sim_utils +from isaaclab.sim import SimulationCfg, SimulationContext +from isaaclab.utils import Timer +from isaaclab.utils.assets import check_file_path + + +def main(): + """Spawns the USD asset robot and clones it using Isaac Gym Cloner API.""" + # check valid file path + if not check_file_path(args_cli.input): + raise ValueError(f"Invalid file path: {args_cli.input}") + # Load kit helper + sim = SimulationContext(SimulationCfg(dt=0.01)) + + # get stage handle + stage = sim_utils.get_current_stage() + + # Fabric and PhysX GPU buffers are configured through SimulationCfg/PhysxCfg defaults. + # enable hydra scene-graph instancing + # this is needed to visualize the scene when fabric is enabled + sim.set_setting("/persistent/omnihydra/useSceneGraphInstancing", True) + + # Create interface to clone the scene + cloner = GridCloner(spacing=args_cli.spacing, stage=stage) + cloner.define_base_env("/World/envs") + stage.DefinePrim("/World/envs/env_0", "Xform") + # Spawn things into stage + sim_utils.create_prim("/World/Light", "DistantLight") + + # Everything under the namespace "/World/envs/env_0" will be cloned + sim_utils.create_prim("/World/envs/env_0/Asset", "Xform", usd_path=os.path.abspath(args_cli.input)) + # Clone the scene + num_clones = args_cli.num_clones + + # Create a timer to measure the cloning time + with Timer(f"[#clones: {num_clones}, physics: {args_cli.physics}] Asset: {args_cli.input}"): + # Clone the scene + with Timer(">>> Cloning time (cloner.clone)"): + cloner.define_base_env("/World/envs") + envs_prim_paths = cloner.generate_paths("/World/envs/env", num_paths=num_clones) + _ = cloner.clone( + source_prim_path="/World/envs/env_0", prim_paths=envs_prim_paths, replicate_physics=args_cli.physics + ) + # Play the simulator + with Timer(">>> Setup time (sim.reset)"): + sim.reset() + + # Simulate scene (if not headless) + if not args_cli.headless: + with contextlib.suppress(KeyboardInterrupt): + while sim.is_playing(): + # perform step + sim.step() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tools/convert_instanceable.py b/simulation/modules/IsaacLab/scripts/tools/convert_instanceable.py new file mode 100644 index 0000000000000000000000000000000000000000..7713bdc728f35eb3d19f0d60c16f668e5d7b17e4 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/convert_instanceable.py @@ -0,0 +1,160 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Utility to bulk convert URDFs or mesh files into instanceable USD format. + +Unified Robot Description Format (URDF) is an XML file format used in ROS to describe all elements of +a robot. For more information, see: http://wiki.ros.org/urdf + +This script uses the URDF importer extension from Isaac Sim (``omni.isaac.urdf_importer``) to convert a +URDF asset into USD format. It is designed as a convenience script for command-line use. For more +information on the URDF importer, see the documentation for the extension: +https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html + + +positional arguments: + input The path to the input directory containing URDFs and Meshes. + output The path to directory to store the instanceable files. + +optional arguments: + -h, --help Show this help message and exit + --conversion-type Select file type to convert, urdf or mesh. (default: urdf) + --merge-joints Consolidate links that are connected by fixed joints. (default: False) + --fix-base Fix the base to where it is imported. (default: False) + --make-instanceable Make the asset instanceable for efficient cloning. (default: False) + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Utility to convert a URDF or mesh into an Instanceable asset.") +parser.add_argument("input", type=str, help="The path to the input directory.") +parser.add_argument("output", type=str, help="The path to directory to store converted instanceable files.") +parser.add_argument( + "--conversion-type", type=str, default="both", help="Select file type to convert, urdf, mesh, or both." +) +parser.add_argument( + "--merge-joints", + action="store_true", + default=False, + help="Consolidate links that are connected by fixed joints.", +) +parser.add_argument("--fix-base", action="store_true", default=False, help="Fix the base to where it is imported.") +parser.add_argument( + "--make-instanceable", + action="store_true", + default=True, + help="Make the asset instanceable for efficient cloning.", +) +parser.add_argument( + "--collision-approximation", + type=str, + default="convexDecomposition", + choices=["convexDecomposition", "convexHull", "none"], + help=( + 'The method used for approximating collision mesh. Set to "none" ' + "to not add a collision mesh to the converted mesh." + ), +) +parser.add_argument( + "--mass", + type=float, + default=None, + help="The mass (in kg) to assign to the converted asset. If not provided, then no mass is added.", +) + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import os + +from isaaclab.sim.converters import MeshConverter, MeshConverterCfg, UrdfConverter, UrdfConverterCfg +from isaaclab.sim.schemas import schemas_cfg + + +def main(): + # Define conversion time given + conversion_type = args_cli.conversion_type.lower() + # Warning if conversion type input is not valid + if conversion_type != "urdf" and conversion_type != "mesh" and conversion_type != "both": + raise Warning("Conversion type is not valid, please select either 'urdf', 'mesh', or 'both'.") + + if not os.path.exists(args_cli.input): + print(f"Error: The directory {args_cli.input} does not exist.") + + # For each file and subsequent sub-directory + for root, dirs, files in os.walk(args_cli.input): + # For each file + for filename in files: + # Check for URDF extensions + if (conversion_type == "urdf" or conversion_type == "both") and filename.lower().endswith(".urdf"): + # URDF converter call + urdf_converter_cfg = UrdfConverterCfg( + asset_path=f"{root}/{filename}", + usd_dir=f"{args_cli.output}/{filename[:-5]}", + usd_file_name=f"{filename[:-5]}.usd", + fix_base=args_cli.fix_base, + merge_fixed_joints=args_cli.merge_joints, + force_usd_conversion=True, + make_instanceable=args_cli.make_instanceable, + ) + # Create Urdf converter and import the file + urdf_converter = UrdfConverter(urdf_converter_cfg) + print(f"Generated USD file: {urdf_converter.usd_path}") + + elif (conversion_type == "mesh" or conversion_type == "both") and ( + filename.lower().endswith(".fbx") + or filename.lower().endswith(".obj") + or filename.lower().endswith(".dae") + or filename.lower().endswith(".stl") + ): + # Mass properties + if args_cli.mass is not None: + mass_props = schemas_cfg.MassPropertiesCfg(mass=args_cli.mass) + rigid_props = schemas_cfg.RigidBodyPropertiesCfg() + else: + mass_props = None + rigid_props = None + + # Collision properties + collision_props = schemas_cfg.CollisionPropertiesCfg( + collision_enabled=args_cli.collision_approximation != "none" + ) + # Mesh converter call + mesh_converter_cfg = MeshConverterCfg( + mass_props=mass_props, + rigid_props=rigid_props, + collision_props=collision_props, + asset_path=f"{root}/{filename}", + force_usd_conversion=True, + usd_dir=f"{args_cli.output}/{filename[:-4]}", + usd_file_name=f"{filename[:-4]}.usd", + make_instanceable=args_cli.make_instanceable, + collision_approximation=args_cli.collision_approximation, + ) + # Create mesh converter and import the file + mesh_converter = MeshConverter(mesh_converter_cfg) + print(f"Generated USD file: {mesh_converter.usd_path}") + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tools/convert_mesh.py b/simulation/modules/IsaacLab/scripts/tools/convert_mesh.py new file mode 100644 index 0000000000000000000000000000000000000000..6e9fd46befd301d97e11274fa51f8004c43ff4bc --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/convert_mesh.py @@ -0,0 +1,205 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Utility to convert a OBJ/STL/FBX into USD format. + +The OBJ file format is a simple data-format that represents 3D geometry alone — namely, the position +of each vertex, the UV position of each texture coordinate vertex, vertex normals, and the faces that +make each polygon defined as a list of vertices, and texture vertices. + +An STL file describes a raw, unstructured triangulated surface by the unit normal and vertices (ordered +by the right-hand rule) of the triangles using a three-dimensional Cartesian coordinate system. + +FBX files are a type of 3D model file created using the Autodesk FBX software. They can be designed and +modified in various modeling applications, such as Maya, 3ds Max, and Blender. Moreover, FBX files typically +contain mesh, material, texture, and skeletal animation data. +Link: https://www.autodesk.com/products/fbx/overview + + +This script uses the asset converter extension from Isaac Sim (``omni.kit.asset_converter``) to convert a +OBJ/STL/FBX asset into USD format. It is designed as a convenience script for command-line use. + + +positional arguments: + input The path to the input mesh (.OBJ/.STL/.FBX) file. + output The path to store the USD file. + +optional arguments: + -h, --help Show this help message and exit + --make-instanceable, Make the asset instanceable for efficient cloning. (default: False) + --collision-approximation The method used for approximating collision mesh. Defaults to convexDecomposition. + Set to \"none\" to not add a collision mesh to the converted mesh. + (default: convexDecomposition) + --mass The mass (in kg) to assign to the converted asset. (default: None) + +""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# Define collision approximation choices (must be defined before parser) +_valid_collision_approx = [ + "convexDecomposition", + "convexHull", + "triangleMesh", + "meshSimplification", + "sdf", + "boundingCube", + "boundingSphere", + "none", +] + +# add argparse arguments +parser = argparse.ArgumentParser(description="Utility to convert a mesh file into USD format.") +parser.add_argument("input", type=str, help="The path to the input mesh file.") +parser.add_argument("output", type=str, help="The path to store the USD file.") +parser.add_argument( + "--make-instanceable", + action="store_true", + default=False, + help="Make the asset instanceable for efficient cloning.", +) +parser.add_argument( + "--collision-approximation", + type=str, + default="convexDecomposition", + choices=_valid_collision_approx, + help="The method used for approximating the collision mesh. Set to 'none' to disable collision mesh generation.", +) +parser.add_argument( + "--mass", + type=float, + default=None, + help="The mass (in kg) to assign to the converted asset. If not provided, then no mass is added.", +) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import contextlib +import os + +import carb +import omni.kit.app + +import isaaclab.sim as sim_utils +from isaaclab.sim.converters import MeshConverter, MeshConverterCfg +from isaaclab.sim.schemas import schemas_cfg +from isaaclab.utils.assets import check_file_path +from isaaclab.utils.dict import print_dict + +collision_approximation_map = { + "convexDecomposition": schemas_cfg.ConvexDecompositionPropertiesCfg, + "convexHull": schemas_cfg.ConvexHullPropertiesCfg, + "triangleMesh": schemas_cfg.TriangleMeshPropertiesCfg, + "meshSimplification": schemas_cfg.TriangleMeshSimplificationPropertiesCfg, + "sdf": schemas_cfg.SDFMeshPropertiesCfg, + "boundingCube": schemas_cfg.BoundingCubePropertiesCfg, + "boundingSphere": schemas_cfg.BoundingSpherePropertiesCfg, + "none": None, +} + + +def main(): + # check valid file path + mesh_path = args_cli.input + if not os.path.isabs(mesh_path): + mesh_path = os.path.abspath(mesh_path) + if not check_file_path(mesh_path): + raise ValueError(f"Invalid mesh file path: {mesh_path}") + + # create destination path + dest_path = args_cli.output + if not os.path.isabs(dest_path): + dest_path = os.path.abspath(dest_path) + + # Mass properties + if args_cli.mass is not None: + mass_props = schemas_cfg.MassPropertiesCfg(mass=args_cli.mass) + rigid_props = schemas_cfg.RigidBodyPropertiesCfg() + else: + mass_props = None + rigid_props = None + + # Collision properties + collision_props = schemas_cfg.CollisionPropertiesCfg(collision_enabled=args_cli.collision_approximation != "none") + + # Create Mesh converter config + cfg_class = collision_approximation_map.get(args_cli.collision_approximation) + if cfg_class is None and args_cli.collision_approximation != "none": + valid_keys = ", ".join(sorted(collision_approximation_map.keys())) + raise ValueError( + f"Invalid collision approximation type '{args_cli.collision_approximation}'. " + f"Valid options are: {valid_keys}." + ) + collision_cfg = cfg_class() if cfg_class is not None else None + + mesh_converter_cfg = MeshConverterCfg( + mass_props=mass_props, + rigid_props=rigid_props, + collision_props=collision_props, + asset_path=mesh_path, + force_usd_conversion=True, + usd_dir=os.path.dirname(dest_path), + usd_file_name=os.path.basename(dest_path), + make_instanceable=args_cli.make_instanceable, + mesh_collision_props=collision_cfg, + ) + + # Print info + print("-" * 80) + print("-" * 80) + print(f"Input Mesh file: {mesh_path}") + print("Mesh importer config:") + print_dict(mesh_converter_cfg.to_dict(), nesting=0) + print("-" * 80) + print("-" * 80) + + # Create Mesh converter and import the file + mesh_converter = MeshConverter(mesh_converter_cfg) + # print output + print("Mesh importer output:") + print(f"Generated USD file: {mesh_converter.usd_path}") + print("-" * 80) + print("-" * 80) + + # Determine if there is a GUI to update: + # acquire settings interface + carb_settings_iface = carb.settings.get_settings() + # read flag for whether a local GUI is enabled + local_gui = carb_settings_iface.get("/app/window/enabled") + # read flag for whether livestreaming GUI is enabled + livestream_gui = carb_settings_iface.get("/app/livestream/enabled") + + # Simulate scene (if not headless) + if local_gui or livestream_gui: + # Open the stage with USD + sim_utils.open_stage(mesh_converter.usd_path) + # Reinitialize the simulation + app = omni.kit.app.get_app_interface() + # Run simulation + with contextlib.suppress(KeyboardInterrupt): + while app.is_running(): + # perform step + app.update() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tools/convert_mjcf.py b/simulation/modules/IsaacLab/scripts/tools/convert_mjcf.py new file mode 100644 index 0000000000000000000000000000000000000000..d693a493bd6e1c681b8ca3c3c9a857c2798f288a --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/convert_mjcf.py @@ -0,0 +1,160 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Utility to convert a MJCF into USD format. + +MuJoCo XML Format (MJCF) is an XML file format used in MuJoCo to describe all elements of a robot. +For more information, see: http://www.mujoco.org/book/XMLreference.html + +This script uses the MJCF importer extension from Isaac Sim (``isaacsim.asset.importer.mjcf``) to convert +a MJCF asset into USD format. It is designed as a convenience script for command-line use. For more information +on the MJCF importer, see the documentation for the extension: +https://docs.isaacsim.omniverse.nvidia.com/latest/robot_setup/ext_isaacsim_asset_importer_mjcf.html + + +positional arguments: + input The path to the input MJCF file. + output The path to store the USD file. + +optional arguments: + -h, --help Show this help message and exit + --merge-mesh Merge meshes where possible to optimize the model. (default: False) + --collision-from-visuals Generate collision geometry from visual geometries. (default: False) + --collision-type Type of collision geometry to use. (default: "default") + --self-collision Activate self-collisions between links. (default: False) + --import-physics-scene Import the physics scene from the MJCF file. (default: False) +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Utility to convert a MJCF into USD format.") +parser.add_argument("input", type=str, help="The path to the input MJCF file.") +parser.add_argument("output", type=str, help="The path to store the USD file.") +parser.add_argument( + "--merge-mesh", + action="store_true", + default=False, + help="Merge meshes where possible to optimize the model.", +) +parser.add_argument( + "--collision-from-visuals", + action="store_true", + default=False, + help="Generate collision geometry from visual geometries.", +) +parser.add_argument( + "--collision-type", + type=str, + default="default", + help='Type of collision geometry to use (e.g. "default", "Convex Hull", "Convex Decomposition").', +) +parser.add_argument( + "--self-collision", + action="store_true", + default=False, + help="Activate self-collisions between links of the articulation.", +) +parser.add_argument( + "--import-physics-scene", + action="store_true", + default=False, + help="Import the physics scene (worldbody, defaults) from the MJCF file. Use --no-import-physics-scene to disable.", +) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import contextlib +import os + +import carb + +from isaaclab.sim.converters import MjcfConverter, MjcfConverterCfg +from isaaclab.utils.assets import check_file_path +from isaaclab.utils.dict import print_dict + + +def main(): + # check valid file path + mjcf_path = args_cli.input + if not os.path.isabs(mjcf_path): + mjcf_path = os.path.abspath(mjcf_path) + if not check_file_path(mjcf_path): + raise ValueError(f"Invalid file path: {mjcf_path}") + # create destination path + dest_path = args_cli.output + if not os.path.isabs(dest_path): + dest_path = os.path.abspath(dest_path) + + # create the converter configuration + mjcf_converter_cfg = MjcfConverterCfg( + asset_path=mjcf_path, + usd_dir=os.path.dirname(dest_path), + force_usd_conversion=True, + merge_mesh=args_cli.merge_mesh, + collision_from_visuals=args_cli.collision_from_visuals, + collision_type=args_cli.collision_type, + self_collision=args_cli.self_collision, + import_physics_scene=args_cli.import_physics_scene, + ) + + # Print info + print("-" * 80) + print("-" * 80) + print(f"Input MJCF file: {mjcf_path}") + print("MJCF importer config:") + print_dict(mjcf_converter_cfg.to_dict(), nesting=0) + print("-" * 80) + print("-" * 80) + + # Create mjcf converter and import the file + mjcf_converter = MjcfConverter(mjcf_converter_cfg) + # print output + print("MJCF importer output:") + print(f"Generated USD file: {mjcf_converter.usd_path}") + print("-" * 80) + print("-" * 80) + + # Determine if there is a GUI to update: + # acquire settings interface + carb_settings_iface = carb.settings.get_settings() + # read flag for whether a local GUI is enabled + local_gui = carb_settings_iface.get("/app/window/enabled") + # read flag for whether livestreaming GUI is enabled + livestream_gui = carb_settings_iface.get("/app/livestream/enabled") + + # Simulate scene (if not headless) + if local_gui or livestream_gui: + # Open the stage with USD and attach it to the Kit viewport context + import omni.usd + + omni.usd.get_context().open_stage(mjcf_converter.usd_path) + # Reinitialize the simulation + app = omni.kit.app.get_app_interface() + # Run simulation + with contextlib.suppress(KeyboardInterrupt): + while app.is_running(): + # perform step + app.update() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tools/convert_urdf.py b/simulation/modules/IsaacLab/scripts/tools/convert_urdf.py new file mode 100644 index 0000000000000000000000000000000000000000..e1385f82cb428e8cec009b50cca04ab08fa07cde --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/convert_urdf.py @@ -0,0 +1,164 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Utility to convert a URDF into USD format. + +Unified Robot Description Format (URDF) is an XML file format used in ROS to describe all elements of +a robot. For more information, see: http://wiki.ros.org/urdf + +This script uses the URDF importer extension from Isaac Sim (``isaacsim.asset.importer.urdf``) to convert a +URDF asset into USD format. It is designed as a convenience script for command-line use. For more +information on the URDF importer, see the documentation for the extension: +https://docs.isaacsim.omniverse.nvidia.com/latest/robot_setup/ext_isaacsim_asset_importer_urdf.html + + +positional arguments: + input The path to the input URDF file. + output The path to store the USD file. + +optional arguments: + -h, --help Show this help message and exit + --merge-joints Consolidate links that are connected by fixed joints. (default: False) + --fix-base Fix the base to where it is imported. (default: False) + --joint-stiffness The stiffness of the joint drive. (default: 100.0) + --joint-damping The damping of the joint drive. (default: 1.0) + --joint-target-type The type of control to use for the joint drive. (default: "position") + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Utility to convert a URDF into USD format.") +parser.add_argument("input", type=str, help="The path to the input URDF file.") +parser.add_argument("output", type=str, help="The path to store the USD file.") +parser.add_argument( + "--merge-joints", + action="store_true", + default=False, + help="Consolidate links that are connected by fixed joints.", +) +parser.add_argument("--fix-base", action="store_true", default=False, help="Fix the base to where it is imported.") +parser.add_argument( + "--joint-stiffness", + type=float, + default=100.0, + help="The stiffness of the joint drive.", +) +parser.add_argument( + "--joint-damping", + type=float, + default=1.0, + help="The damping of the joint drive.", +) +parser.add_argument( + "--joint-target-type", + type=str, + default="position", + choices=["position", "velocity", "none"], + help="The type of control to use for the joint drive.", +) + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import contextlib +import os + +import carb + +from isaaclab.sim.converters import UrdfConverter, UrdfConverterCfg +from isaaclab.utils.assets import check_file_path +from isaaclab.utils.dict import print_dict + + +def main(): + # check valid file path + urdf_path = args_cli.input + if not os.path.isabs(urdf_path): + urdf_path = os.path.abspath(urdf_path) + if not check_file_path(urdf_path): + raise ValueError(f"Invalid file path: {urdf_path}") + # create destination path + dest_path = args_cli.output + if not os.path.isabs(dest_path): + dest_path = os.path.abspath(dest_path) + + # Create Urdf converter config + # Note: usd_file_name is determined by the URDF importer 3.0 based on the robot name + # and cannot be overridden. The output is placed under dest_path as usd_dir. + urdf_converter_cfg = UrdfConverterCfg( + asset_path=urdf_path, + usd_dir=dest_path, + fix_base=args_cli.fix_base, + merge_fixed_joints=args_cli.merge_joints, + force_usd_conversion=True, + joint_drive=UrdfConverterCfg.JointDriveCfg( + gains=UrdfConverterCfg.JointDriveCfg.PDGainsCfg( + stiffness=args_cli.joint_stiffness, + damping=args_cli.joint_damping, + ), + target_type=args_cli.joint_target_type, + ), + ) + + # Print info + print("-" * 80) + print("-" * 80) + print(f"Input URDF file: {urdf_path}") + print("URDF importer config:") + print_dict(urdf_converter_cfg.to_dict(), nesting=0) + print("-" * 80) + print("-" * 80) + + # Create Urdf converter and import the file + urdf_converter = UrdfConverter(urdf_converter_cfg) + # print output + print("URDF importer output:") + print(f"Generated USD file: {urdf_converter.usd_path}") + print("-" * 80) + print("-" * 80) + + # Determine if there is a GUI to update: + # acquire settings interface + carb_settings_iface = carb.settings.get_settings() + # read flag for whether a local GUI is enabled + local_gui = carb_settings_iface.get("/app/window/enabled") + # read flag for whether livestreaming GUI is enabled + livestream_gui = carb_settings_iface.get("/app/livestream/enabled") + + # Simulate scene (if not headless) + if local_gui or livestream_gui: + # Open the stage with USD and attach it to the Kit viewport context + import omni.usd + + omni.usd.get_context().open_stage(urdf_converter.usd_path) + # Reinitialize the simulation + app = omni.kit.app.get_app_interface() + # Run simulation + with contextlib.suppress(KeyboardInterrupt): + while app.is_running(): + # perform step + app.update() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tools/cosmos/cosmos_prompt_gen.py b/simulation/modules/IsaacLab/scripts/tools/cosmos/cosmos_prompt_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..32db884adc566ba963cac823312194b6b92e2646 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/cosmos/cosmos_prompt_gen.py @@ -0,0 +1,85 @@ +# Copyright (c) 2024-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Script to construct prompts to control the Cosmos model's generation. + +Required arguments: + --templates_path Path to the file containing templates for the prompts. + +Optional arguments: + --num_prompts Number of prompts to generate (default: 1). + --output_path Path to the output file to write generated prompts (default: prompts.txt). +""" + +import argparse +import json +import random + + +def parse_args(): + """Parse command line arguments.""" + parser = argparse.ArgumentParser(description="Generate prompts for controlling Cosmos model's generation.") + parser.add_argument( + "--templates_path", type=str, required=True, help="Path to the JSON file containing prompt templates" + ) + parser.add_argument("--num_prompts", type=int, default=1, help="Number of prompts to generate (default: 1)") + parser.add_argument( + "--output_path", type=str, default="prompts.txt", help="Path to the output file to write generated prompts" + ) + args = parser.parse_args() + + return args + + +def generate_prompt(templates_path: str): + """Generate a random prompt for controlling the Cosmos model's visual augmentation. + + The prompt describes the scene and desired visual variations, which the model + uses to guide the augmentation process while preserving the core robotic actions. + + Args: + templates_path (str): Path to the JSON file containing prompt templates. + + Returns: + str: Generated prompt string that specifies visual aspects to modify in the video. + """ + try: + with open(templates_path) as f: + templates = json.load(f) + except FileNotFoundError: + raise FileNotFoundError(f"Prompt templates file not found: {templates_path}") + except json.JSONDecodeError: + raise ValueError(f"Invalid JSON in prompt templates file: {templates_path}") + + prompt_parts = [] + + for section_name, section_options in templates.items(): + if not isinstance(section_options, list): + continue + if len(section_options) == 0: + continue + selected_option = random.choice(section_options) + prompt_parts.append(selected_option) + + return " ".join(prompt_parts) + + +def main(): + # Parse command line arguments + args = parse_args() + + prompts = [generate_prompt(args.templates_path) for _ in range(args.num_prompts)] + + try: + with open(args.output_path, "w") as f: + for prompt in prompts: + f.write(prompt + "\n") + except Exception as e: + print(f"Failed to write to {args.output_path}: {e}") + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/tools/cosmos/transfer1_templates.json b/simulation/modules/IsaacLab/scripts/tools/cosmos/transfer1_templates.json new file mode 100644 index 0000000000000000000000000000000000000000..d2d4b063a2682c9c10eac2e2f06648da269f91af --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/cosmos/transfer1_templates.json @@ -0,0 +1,96 @@ +{ + "env": [ + "A robotic arm is picking up and stacking cubes inside a foggy industrial scrapyard at dawn, surrounded by piles of old robotic parts and twisted metal. The background includes large magnetic cranes, rusted conveyor belts, and flickering yellow floodlights struggling to penetrate the fog.", + "A robotic arm is picking up and stacking cubes inside a luxury penthouse showroom during sunset. The background includes minimalist designer furniture, a panoramic view of a glowing city skyline, and hovering autonomous drones offering refreshments.", + "A robotic arm is picking up and stacking cubes within an ancient temple-themed robotics exhibit in a museum. The background includes stone columns with hieroglyphic-style etchings, interactive display panels, and a few museum visitors observing silently from behind glass barriers.", + "A robotic arm is picking up and stacking cubes inside a futuristic daycare facility for children. The background includes robotic toys, soft padded walls, holographic storybooks floating in mid-air, and tiny humanoid robots assisting toddlers.", + "A robotic arm is picking up and stacking cubes inside a deep underwater laboratory where pressure-resistant glass panels reveal a shimmering ocean outside. The background includes jellyfish drifting outside the windows, robotic submarines gliding by, and walls lined with wet-surface equipment panels.", + "A robotic arm is picking up and stacking cubes inside a post-apocalyptic lab, partially collapsed and exposed to the open sky. The background includes ruined machinery, exposed rebar, and a distant city skyline covered in ash and fog.", + "A robotic arm is picking up and stacking cubes in a biotech greenhouse surrounded by lush plant life. The background includes rows of bio-engineered plants, misting systems, and hovering inspection drones checking crop health.", + "A robotic arm is picking up and stacking cubes inside a dark, volcanic research outpost. The background includes robotic arms encased in heat-resistant suits, seismic monitors, and distant lava fountains occasionally illuminating the space.", + "A robotic arm is picking up and stacking cubes inside an icy arctic base, with frost-covered walls and equipment glinting under bright artificial white lights. The background includes heavy-duty heaters, control consoles wrapped in thermal insulation, and a large window looking out onto a frozen tundra with polar winds swirling snow outside.", + "A robotic arm is picking up and stacking cubes inside a zero-gravity chamber on a rotating space habitat. The background includes floating lab instruments, panoramic windows showing stars and Earth in rotation, and astronauts monitoring data.", + "A robotic arm is picking up and stacking cubes inside a mystical tech-art installation blending robotics with generative art. The background includes sculptural robotics, shifting light patterns on the walls, and visitors interacting with the exhibit using gestures.", + "A robotic arm is picking up and stacking cubes in a Martian colony dome, under a terraformed red sky filtering through thick glass. The background includes pressure-locked entry hatches, Martian rovers parked outside, and domed hydroponic farms stretching into the distance.", + "A robotic arm is picking up and stacking cubes inside a high-security military robotics testing bunker, with matte green steel walls and strict order. The background includes surveillance cameras, camouflage netting over equipment racks, and military personnel observing from a secure glass-walled control room.", + "A robotic arm is picking up and stacking cubes inside a retro-futuristic robotics lab from the 1980s with checkered floors and analog computer panels. The background includes CRT monitors with green code, rotary dials, printed schematics on the walls, and operators in lab coats typing on clunky terminals.", + "A robotic arm is picking up and stacking cubes inside a sunken ancient ruin repurposed for modern robotics experiments. The background includes carved pillars, vines creeping through gaps in stone, and scattered crates of modern equipment sitting on ancient floors.", + "A robotic arm is picking up and stacking cubes on a luxury interstellar yacht cruising through deep space. The background includes elegant furnishings, ambient synth music systems, and holographic butlers attending to other passengers.", + "A robotic arm is picking up and stacking cubes in a rebellious underground cybernetic hacker hideout. The background includes graffiti-covered walls, tangled wires, makeshift workbenches, and anonymous figures hunched over terminals with scrolling code.", + "A robotic arm is picking up and stacking cubes inside a dense jungle outpost where technology is being tested in extreme organic environments. The background includes humid control panels, vines creeping onto the robotics table, and occasional wildlife observed from a distance by researchers in camo gear.", + "A robotic arm is picking up and stacking cubes in a minimalist Zen tech temple. The background includes bonsai trees on floating platforms, robotic monks sweeping floors silently, and smooth stone pathways winding through digital meditation alcoves." + ], + + "robot": [ + "The robot arm is matte dark green with yellow diagonal hazard stripes along the upper arm; the joints are rugged and chipped, and the hydraulics are exposed with faded red tubing.", + "The robot arm is worn orange with black caution tape markings near the wrist; the elbow joint is dented and the pistons have visible scarring from long use.", + "The robot arm is steel gray with smooth curved panels and subtle blue stripes running down the length; the joints are sealed tight and the hydraulics have a glossy black casing.", + "The robot arm is bright yellow with alternating black bands around each segment; the joints show minor wear, and the hydraulics gleam with fresh lubrication.", + "The robot arm is navy blue with white serial numbers stenciled along the arm; the joints are well-maintained and the hydraulic shafts are matte silver with no visible dirt.", + "The robot arm is deep red with a matte finish and faint white grid lines across the panels; the joints are squared off and the hydraulic units look compact and embedded.", + "The robot arm is dirty white with dark gray speckled patches from wear; the joints are squeaky with exposed rivets, and the hydraulics are rusted at the base.", + "The robot arm is olive green with chipped paint and a black triangle warning icon near the shoulder; the joints are bulky and the hydraulics leak slightly around the seals.", + "The robot arm is bright teal with a glossy surface and silver stripes on the outer edges; the joints rotate smoothly and the pistons reflect a pale cyan hue.", + "The robot arm is orange-red with carbon fiber textures and white racing-style stripes down the forearm; the joints have minimal play and the hydraulics are tightly sealed in synthetic tubing.", + "The robot arm is flat black with uneven camouflage blotches in dark gray; the joints are reinforced and the hydraulic tubes are dusty and loose-fitting.", + "The robot arm is dull maroon with vertical black grooves etched into the panels; the joints show corrosion on the bolts and the pistons are thick and slow-moving.", + "The robot arm is powder blue with repeating geometric patterns printed in light gray; the joints are square and the hydraulic systems are internal and silent.", + "The robot arm is brushed silver with high-gloss finish and blue LED strips along the seams; the joints are shiny and tight, and the hydraulics hiss softly with every movement.", + "The robot arm is lime green with paint faded from sun exposure and white warning labels near each joint; the hydraulics are scraped and the fittings show heat marks.", + "The robot arm is dusty gray with chevron-style black stripes pointing toward the claw; the joints have uneven wear, and the pistons are dented and slightly bent.", + "The robot arm is cobalt blue with glossy texture and stylized angular black patterns across each segment; the joints are clean and the hydraulics show new flexible tubing.", + "The robot arm is industrial brown with visible welded seams and red caution tape wrapped loosely around the middle section; the joints are clunky and the hydraulics are slow and loud.", + "The robot arm is flat tan with dark green splotches and faint stencil text across the forearm; the joints have dried mud stains and the pistons are partially covered in grime.", + "The robot arm is light orange with chrome hexagon detailing and black number codes on the side; the joints are smooth and the hydraulic actuators shine under the lab lights." + ], + + "table": [ + "The robot arm is mounted on a table that is dull gray metal with scratches and scuff marks across the surface; faint rust rings are visible where older machinery used to be mounted.", + "The robot arm is mounted on a table that is smooth black plastic with a matte finish and faint fingerprint smudges near the edges; corners are slightly worn from regular use.", + "The robot arm is mounted on a table that is light oak wood with a natural grain pattern and a glossy varnish that reflects overhead lights softly; small burn marks dot one corner.", + "The robot arm is mounted on a table that is rough concrete with uneven texture and visible air bubbles; some grease stains and faded yellow paint markings suggest heavy usage.", + "The robot arm is mounted on a table that is brushed aluminum with a clean silver tone and very fine linear grooves; surface reflects light evenly, giving a soft glow.", + "The robot arm is mounted on a table that is pale green composite with chipped corners and scratches revealing darker material beneath; tape residue is stuck along the edges.", + "The robot arm is mounted on a table that is dark brown with a slightly cracked synthetic coating; patches of discoloration suggest exposure to heat or chemicals over time.", + "The robot arm is mounted on a table that is polished steel with mirror-like reflections; every small movement of the robot is mirrored faintly across the surface.", + "The robot arm is mounted on a table that is white with a slightly textured ceramic top, speckled with tiny black dots; the surface is clean but the edges are chipped.", + "The robot arm is mounted on a table that is glossy black glass with a deep shine and minimal dust; any lights above are clearly reflected, and fingerprints are visible under certain angles.", + "The robot arm is mounted on a table that is matte red plastic with wide surface scuffs and paint transfer from other objects; faint gridlines are etched into one side.", + "The robot arm is mounted on a table that is dark navy laminate with a low-sheen surface and subtle wood grain texture; the edge banding is slightly peeling off.", + "The robot arm is mounted on a table that is yellow-painted steel with diagonal black warning stripes running along one side; the paint is scratched and faded in high-contact areas.", + "The robot arm is mounted on a table that is translucent pale blue polymer with internal striations and slight glow under overhead lights; small bubbles are frozen inside the material.", + "The robot arm is mounted on a table that is cold concrete with embedded metal panels bolted into place; the surface has oil stains, welding marks, and tiny debris scattered around.", + "The robot arm is mounted on a table that is shiny chrome with heavy smudging and streaks; the table reflects distorted shapes of everything around it, including the arm itself.", + "The robot arm is mounted on a table that is matte forest green with shallow dents and drag marks from prior mechanical operations; a small sticker label is half-torn in one corner.", + "The robot arm is mounted on a table that is textured black rubber with slight give under pressure; scratches from the robot's base and clamp marks are clearly visible.", + "The robot arm is mounted on a table that is medium gray ceramic tile with visible grout lines and chips along the edges; some tiles have tiny cracks or stains.", + "The robot arm is mounted on a table that is old dark wood with faded polish and visible circular stains from spilled liquids; a few deep grooves are carved into the surface near the center." + ], + + "cubes": [ + "The arm is connected to the base mounted on the table. The bottom cube is deep blue, the second cube is bright red, and the top cube is vivid green, maintaining their correct order after stacking." + ], + + "light": [ + "The lighting is soft and diffused from large windows, allowing daylight to fill the room, creating gentle shadows that elongate throughout the space, with a natural warmth due to the sunlight streaming in.", + "Bright fluorescent tubes overhead cast a harsh, even light across the scene, creating sharp, well-defined shadows under the arm and cubes, with a sterile, clinical feel due to the cold white light.", + "Warm tungsten lights in the ceiling cast a golden glow over the table, creating long, soft shadows and a cozy, welcoming atmosphere. The light contrasts with cool blue tones from the robot arm.", + "The lighting comes from several intense spotlights mounted above, each casting focused beams of light that create stark, dramatic shadows around the cubes and the robotic arm, producing a high-contrast look.", + "A single adjustable desk lamp with a soft white bulb casts a directional pool of light over the cubes, causing deep, hard shadows and a quiet, intimate feel in the dimly lit room.", + "The space is illuminated with bright daylight filtering in through a skylight above, casting diffused, soft shadows and giving the scene a clean and natural look, with a cool tint from the daylight.", + "Soft, ambient lighting from hidden LEDs embedded in the ceiling creates a halo effect around the robotic arm, while subtle, elongated shadows stretch across the table surface, giving a sleek modern vibe.", + "Neon strip lights line the walls, casting a cool blue and purple glow across the scene. The robot and table are bathed in this colored light, producing sharp-edged shadows with a futuristic feel.", + "Bright artificial lights overhead illuminate the scene in a harsh white, with scattered, uneven shadows across the table and robot arm. There's a slight yellow hue to the light, giving it an industrial ambiance.", + "Soft morning sunlight spills through a large open window, casting long shadows across the floor and the robot arm. The warm, golden light creates a peaceful, natural atmosphere with a slight coolness in the shadows.", + "Dim ambient lighting with occasional flashes of bright blue light from overhead digital screens creates a high-tech, slightly eerie atmosphere. The shadows are soft, stretching in an almost surreal manner.", + "Lighting from tall lamps outside the room filters in through large glass doors, casting angled shadows across the table and robot arm. The ambient light creates a relaxing, slightly diffused atmosphere.", + "Artificial overhead lighting casts a harsh, stark white light with little warmth, producing sharply defined, almost clinical shadows on the robot arm and cubes. The space feels cold and industrial.", + "Soft moonlight from a large window at night creates a cool, ethereal glow on the table and arm. The shadows are long and faint, and the lighting provides a calm and serene atmosphere.", + "Bright overhead LED panels illuminate the scene with clean, white light, casting neutral shadows that give the environment a modern, sleek feel with minimal distortion or softness in the shadows.", + "A floodlight positioned outside casts bright, almost blinding natural light through an open door, creating high-contrast, sharp-edged shadows across the table and robot arm, adding dramatic tension to the scene.", + "Dim lighting from vintage tungsten bulbs hanging from the ceiling gives the room a warm, nostalgic glow, casting elongated, soft shadows that provide a cozy atmosphere around the robotic arm.", + "Bright fluorescent lights directly above produce a harsh, clinical light that creates sharp, defined shadows on the table and robotic arm, enhancing the industrial feel of the scene.", + "Neon pink and purple lights flicker softly from the walls, illuminating the robot arm with an intense glow that produces sharp, angular shadows across the cubes. The atmosphere feels futuristic and edgy.", + "Sunlight pouring in from a large, open window bathes the table and robotic arm in a warm golden light. The shadows are soft, and the scene feels natural and inviting with a slight contrast between light and shadow." + ] +} diff --git a/simulation/modules/IsaacLab/scripts/tools/find_quaternions.py b/simulation/modules/IsaacLab/scripts/tools/find_quaternions.py new file mode 100644 index 0000000000000000000000000000000000000000..9eb4e0decf2ce8d73e38978e92cd0ecb72361af2 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/find_quaternions.py @@ -0,0 +1,672 @@ +#!/usr/bin/env python3 +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tool to find potential quaternion values that may need wxyz->xyzw conversion. + +This script searches for 4-element tuples/lists in Python files and flags those +that haven't been modified compared to the main branch. + +Usage: + python tools/find_quaternions.py [--path PATH] [--show-all] [--check-identity] +""" + +import argparse +import ast +import re +import subprocess +import sys +from pathlib import Path + + +def get_changed_files_from_base(base_ref="main"): + """Get list of files that have been modified compared to base ref.""" + try: + result = subprocess.run( + ["git", "diff", "--name-only", base_ref], + capture_output=True, + text=True, + check=True, + ) + return set(result.stdout.strip().split("\n")) + except subprocess.CalledProcessError: + print(f"Warning: Could not get git diff from {base_ref}. Showing all potential quaternions.") + return set() + + +def get_diff_lines_for_file(filepath, base_ref="main"): + """Get the line numbers that have been modified in a file compared to base ref.""" + try: + result = subprocess.run( + ["git", "diff", "-U0", base_ref, "--", filepath], + capture_output=True, + text=True, + ) + # Parse the unified diff to get changed line numbers + changed_lines = set() + for line in result.stdout.split("\n"): + # Match lines like @@ -10,5 +12,7 @@ + match = re.match(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", line) + if match: + start_line = int(match.group(1)) + count = int(match.group(2)) if match.group(2) else 1 + for i in range(count): + changed_lines.add(start_line + i) + return changed_lines + except subprocess.CalledProcessError: + return set() + + +def is_potential_quaternion(values): + """Check if 4 values look like a quaternion.""" + if len(values) != 4: + return False + + # Skip boolean lists + if any(isinstance(v, bool) for v in values): + return False + + # Check if all values are numeric + try: + floats = [float(v) for v in values] + except (ValueError, TypeError): + return False + + # Check if it's roughly a unit quaternion (sum of squares ≈ 1) + sum_sq = sum(v * v for v in floats) + if 0.9 < sum_sq < 1.1: + return True + + # Also catch identity-like patterns + if floats in [[1, 0, 0, 0], [0, 0, 0, 1], [1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0]]: + return True + + return False + + +def is_wxyz_identity(values): + """Check if values look like wxyz identity quaternion [1, 0, 0, 0].""" + try: + # Skip boolean lists + if any(isinstance(v, bool) for v in values): + return False + floats = [float(v) for v in values] + # wxyz identity: w=1, x=0, y=0, z=0 + return abs(floats[0] - 1.0) < 0.01 and all(abs(v) < 0.01 for v in floats[1:]) + except (ValueError, TypeError): + return False + + +def is_wxyz_format_likely(values): + """Heuristic to check if quaternion might be in wxyz format. + + Returns True if the quaternion is LIKELY in wxyz format and needs conversion. + Returns False if it looks like valid xyzw (last element is the w component). + """ + try: + floats = [float(v) for v in values] + w_first, x, y, z_last = floats + + # Common cos(theta/2) values for typical rotations (0, 30, 45, 60, 90, 120, 135, 150, 180 degrees) + common_cos_values = [1.0, 0.9659, 0.866, 0.707, 0.5, 0.2588, 0.0, -0.2588, -0.5, -0.707, -0.866, -0.9659, -1.0] + + def looks_like_w(val): + """Check if value looks like a w component (cos of half-angle).""" + return any(abs(val - c) < 0.02 for c in common_cos_values) + + # If last element looks like a valid w component (xyzw format), NOT wxyz + if looks_like_w(z_last) and abs(z_last) > 0.1: + return False + + # If first element looks like w and last is small, likely wxyz + if looks_like_w(w_first) and abs(z_last) < 0.1: + return True + + # wxyz identity [1,0,0,0] - first is 1, rest are 0 + if abs(w_first - 1.0) < 0.01 and all(abs(v) < 0.01 for v in [x, y, z_last]): + return True + + # Check for pattern where first element is large and last is small (typical wxyz) + if abs(w_first) > 0.5 and abs(z_last) < 0.2: + return True + + # Pattern: [0, sin, 0, 0] or [0, 0, sin, 0] - rotation around single axis in wxyz + # e.g., [0, 1, 0, 0] is 180° around X in wxyz format + if abs(w_first) < 0.01 and abs(z_last) < 0.01: + non_zero = sum(1 for v in [x, y] if abs(v) > 0.1) + if non_zero == 1: + return True + + return False + except (ValueError, TypeError): + return False + + +class QuaternionFinder(ast.NodeVisitor): + """AST visitor to find potential quaternion values.""" + + def __init__(self, source_lines): + self.source_lines = source_lines + self.quaternions = [] + + def visit_Tuple(self, node): + self._check_sequence(node) + self.generic_visit(node) + + def visit_List(self, node): + self._check_sequence(node) + self.generic_visit(node) + + def _check_sequence(self, node): + if len(node.elts) != 4: + return + + # Try to extract constant values + values = [] + for elt in node.elts: + if isinstance(elt, ast.Constant): + values.append(elt.value) + elif isinstance(elt, ast.UnaryOp) and isinstance(elt.op, ast.USub): + if isinstance(elt.operand, ast.Constant) and isinstance(elt.operand.value, (int, float)): + values.append(-elt.operand.value) + else: + return + else: + return + + if is_potential_quaternion(values): + # Get the source line for context + line = self.source_lines[node.lineno - 1] if node.lineno <= len(self.source_lines) else "" + is_identity = is_wxyz_identity(values) + likely_wxyz = is_wxyz_format_likely(values) + # Ambiguous: looks like a valid quaternion but we can't tell the format + is_ambiguous = not is_identity and not likely_wxyz + self.quaternions.append( + { + "line": node.lineno, + "col": node.col_offset, + "values": values, + "source": line.strip(), + "is_wxyz_identity": is_identity, + "likely_wxyz": likely_wxyz, + "is_ambiguous": is_ambiguous, + } + ) + + +def find_quaternions_in_file(filepath): + """Find potential quaternions in a Python file.""" + try: + with open(filepath, encoding="utf-8") as f: + source = f.read() + source_lines = source.split("\n") + + tree = ast.parse(source) + finder = QuaternionFinder(source_lines) + finder.visit(tree) + return finder.quaternions + except (SyntaxError, UnicodeDecodeError): + return [] + + +def find_quaternions_in_json(filepath): + """Find potential quaternions in JSON files.""" + import json + + quaternions = [] + + try: + with open(filepath, encoding="utf-8") as f: + content = f.read() + lines = content.split("\n") + + # Simple regex to find 4-element arrays + pattern = r"\[([^[\]]+)\]" + for i, line in enumerate(lines, 1): + for match in re.finditer(pattern, line): + try: + values = [float(v.strip()) for v in match.group(1).split(",")] + if is_potential_quaternion(values): + is_identity = is_wxyz_identity(values) + likely_wxyz = is_wxyz_format_likely(values) + quaternions.append( + { + "line": i, + "col": match.start(), + "values": values, + "source": line.strip(), + "is_wxyz_identity": is_identity, + "likely_wxyz": likely_wxyz, + "is_ambiguous": not is_identity and not likely_wxyz, + } + ) + except ValueError: + pass + except (json.JSONDecodeError, UnicodeDecodeError): + pass + + return quaternions + + +def find_quaternions_in_rst(filepath): + """Find potential quaternions in RST documentation files.""" + quaternions = [] + + try: + with open(filepath, encoding="utf-8") as f: + lines = f.readlines() + + # Patterns to find quaternions in RST files + # Look for tuples like (1.0, 0.0, 0.0, 0.0) or lists like [1.0, 0.0, 0.0, 0.0] + tuple_pattern = r"\(([^()]+)\)" + list_pattern = r"\[([^[\]]+)\]" + + for i, line in enumerate(lines, 1): + for pattern in [tuple_pattern, list_pattern]: + for match in re.finditer(pattern, line): + try: + # Try to parse as comma-separated floats + parts = match.group(1).split(",") + if len(parts) != 4: + continue + values = [float(v.strip()) for v in parts] + if is_potential_quaternion(values): + is_identity = is_wxyz_identity(values) + likely_wxyz = is_wxyz_format_likely(values) + quaternions.append( + { + "line": i, + "col": match.start(), + "values": values, + "source": line.strip()[:100], + "is_wxyz_identity": is_identity, + "likely_wxyz": likely_wxyz, + "is_ambiguous": not is_identity and not likely_wxyz, + } + ) + except ValueError: + pass + except UnicodeDecodeError: + pass + + return quaternions + + +def convert_wxyz_to_xyzw(values): + """Convert quaternion from wxyz [w,x,y,z] to xyzw [x,y,z,w] format.""" + w, x, y, z = values + return [x, y, z, w] + + +def format_quaternion(values, use_tuple=False, use_float=True): + """Format quaternion values as a string.""" + if use_float: + # Preserve the original precision + formatted = [f"{v}" for v in values] + else: + formatted = [str(v) for v in values] + + if use_tuple: + return f"({', '.join(formatted)})" + else: + return f"[{', '.join(formatted)}]" + + +def get_file_context(filepath, line_num, context_lines=2): + """Get lines around the target line for context.""" + try: + with open(filepath, encoding="utf-8") as f: + lines = f.readlines() + + start = max(0, line_num - context_lines - 1) + end = min(len(lines), line_num + context_lines) + + context = [] + for i in range(start, end): + prefix = ">>>" if i == line_num - 1 else " " + line_content = lines[i].rstrip() + context.append(f"{prefix} {i + 1:4d} | {line_content}") + + return "\n".join(context) + except Exception: + return None + + +def apply_fix(filepath, line_num, old_values, new_values): + """Apply a fix to a specific line in a file. Replaces ALL occurrences on the line. + + Returns (success, new_line_content). + """ + try: + with open(filepath, encoding="utf-8") as f: + lines = f.readlines() + + if line_num > len(lines): + return False, None + + line = lines[line_num - 1] + modified = False + + # Detect if tuple or list format - replace ALL occurrences + for use_tuple in [True, False]: + for use_float in [True, False]: + old_str = format_quaternion(old_values, use_tuple, use_float) + if old_str in line: + new_str = format_quaternion(new_values, use_tuple, use_float) + line = line.replace(old_str, new_str) # Replace ALL + modified = True + + # Try without spaces - replace ALL + for use_tuple in [True, False]: + old_str = f"{'(' if use_tuple else '['}{','.join(str(v) for v in old_values)}{')' if use_tuple else ']'}" + if old_str in line: + new_str = ( + f"{'(' if use_tuple else '['}{', '.join(str(v) for v in new_values)}{')' if use_tuple else ']'}" + ) + line = line.replace(old_str, new_str) # Replace ALL + modified = True + + if modified: + lines[line_num - 1] = line + with open(filepath, "w", encoding="utf-8") as f: + f.writelines(lines) + return True, line.rstrip() + + return False, None + except Exception as e: + print(f" Error applying fix: {e}") + return False, None + + +def preview_fix(filepath, line_num, old_values, new_values): + """Preview what a fix would look like without applying it. Shows ALL replacements.""" + try: + with open(filepath, encoding="utf-8") as f: + lines = f.readlines() + + if line_num > len(lines): + return None, 0 + + line = lines[line_num - 1] + count = 0 + + # Try to find and replace the old pattern - ALL occurrences + for use_tuple in [True, False]: + for use_float in [True, False]: + old_str = format_quaternion(old_values, use_tuple, use_float) + occurrences = line.count(old_str) + if occurrences > 0: + new_str = format_quaternion(new_values, use_tuple, use_float) + line = line.replace(old_str, new_str) + count += occurrences + + # Try without spaces + for use_tuple in [True, False]: + old_str = f"{'(' if use_tuple else '['}{','.join(str(v) for v in old_values)}{')' if use_tuple else ']'}" + occurrences = line.count(old_str) + if occurrences > 0: + new_str = ( + f"{'(' if use_tuple else '['}{', '.join(str(v) for v in new_values)}{')' if use_tuple else ']'}" + ) + line = line.replace(old_str, new_str) + count += occurrences + + if count > 0: + return line.rstrip(), count + return None, 0 + except Exception: + return None, 0 + + +def prompt_user(message, default="y"): + """Prompt user for yes/no/all/quit response.""" + valid = {"y": "yes", "n": "no", "a": "all", "q": "quit", "": default} + prompt_str = f"{message} [Y/n/a/q]: " + + while True: + choice = input(prompt_str).lower().strip() + if choice in valid: + return valid[choice] if choice else valid[default] + print("Please respond with 'y' (yes), 'n' (no), 'a' (all), or 'q' (quit)") + + +def main(): # noqa: C901 + parser = argparse.ArgumentParser(description="Find potential quaternion values that may need conversion") + parser.add_argument("--path", default="source", help="Path to search (default: source)") + parser.add_argument("--show-all", action="store_true", help="Show all quaternions, not just unchanged ones") + parser.add_argument("--check-identity", action="store_true", help="Only show wxyz identity quaternions [1,0,0,0]") + parser.add_argument("--likely-wxyz", action="store_true", help="Only show quaternions likely in wxyz format") + parser.add_argument("--fix", action="store_true", help="Interactively fix quaternions (converts wxyz to xyzw)") + parser.add_argument("--fix-identity-only", action="store_true", help="Only fix identity quaternions [1,0,0,0]") + parser.add_argument("--force", action="store_true", help="Apply fixes without confirmation (use with --fix)") + parser.add_argument("--dry-run", action="store_true", help="Show what would be fixed without making changes") + parser.add_argument("--context", type=int, default=2, help="Lines of context to show (default: 2)") + parser.add_argument( + "--all-quats", "--all", action="store_true", help="Show ALL potential quaternions (ignore format heuristics)" + ) + parser.add_argument("--base", default="main", help="Git ref to compare against (default: main)") + args = parser.parse_args() + + # Get changed files + changed_files = get_changed_files_from_base(args.base) + + # Find all Python, JSON, and RST files + search_path = Path(args.path) + if not search_path.exists(): + print(f"Error: Path '{args.path}' does not exist") + sys.exit(1) + + py_files = list(search_path.rglob("*.py")) + json_files = list(search_path.rglob("*.json")) + rst_files = list(search_path.rglob("*.rst")) + + print(f"Searching {len(py_files)} Python, {len(json_files)} JSON, and {len(rst_files)} RST files...") + print(f"Comparing against: {args.base}") + print(f"Found {len(changed_files)} files changed from {args.base}\n") + + findings = [] + + for filepath in py_files: + rel_path = str(filepath) + quaternions = find_quaternions_in_file(filepath) + + if not quaternions: + continue + + # Get changed lines for this file + changed_lines = get_diff_lines_for_file(rel_path, args.base) + + for q in quaternions: + # Filter based on options + if args.check_identity and not q["is_wxyz_identity"]: + continue + if args.likely_wxyz and not q["likely_wxyz"]: + continue + # --all-quats shows everything regardless of heuristics + # (no filtering applied) + + # Check if this line was changed + is_changed = q["line"] in changed_lines + + if args.show_all or not is_changed: + findings.append({"file": rel_path, "changed": is_changed, **q}) + + for filepath in json_files: + rel_path = str(filepath) + quaternions = find_quaternions_in_json(filepath) + + if not quaternions: + continue + + changed_lines = get_diff_lines_for_file(rel_path, args.base) + + for q in quaternions: + if args.check_identity and not q["is_wxyz_identity"]: + continue + if args.likely_wxyz and not q["likely_wxyz"]: + continue + + is_changed = q["line"] in changed_lines + + if args.show_all or not is_changed: + findings.append({"file": rel_path, "changed": is_changed, **q}) + + for filepath in rst_files: + rel_path = str(filepath) + quaternions = find_quaternions_in_rst(filepath) + + if not quaternions: + continue + + changed_lines = get_diff_lines_for_file(rel_path, args.base) + + for q in quaternions: + if args.check_identity and not q["is_wxyz_identity"]: + continue + if args.likely_wxyz and not q["likely_wxyz"]: + continue + + is_changed = q["line"] in changed_lines + + if args.show_all or not is_changed: + findings.append({"file": rel_path, "changed": is_changed, **q}) + + # Sort by priority: unchanged wxyz identity first, then unchanged likely wxyz, then others + def sort_key(f): + priority = 0 + if not f["changed"]: + priority -= 100 + if f["is_wxyz_identity"]: + priority -= 50 + if f["likely_wxyz"]: + priority -= 25 + return priority + + findings.sort(key=sort_key) + + # Print results + if not findings: + print("No potential quaternions found that need review!") + return + + print(f"Found {len(findings)} potential quaternions to review:\n") + print("=" * 100) + + fixed_count = 0 + skipped_count = 0 + apply_all = args.force # If --force, apply all without prompting + + for f in findings: + status = "✓ CHANGED" if f["changed"] else "⚠ UNCHANGED" + flags = [] + if f["is_wxyz_identity"]: + flags.append("WXYZ_IDENTITY") + if f["likely_wxyz"]: + flags.append("LIKELY_WXYZ") + if f.get("is_ambiguous"): + flags.append("AMBIGUOUS") + + flag_str = f" [{', '.join(flags)}]" if flags else "" + + # Handle fixing mode + if (args.fix or args.fix_identity_only) and not f["changed"]: + # Skip non-identity if fix-identity-only + if args.fix_identity_only and not f["is_wxyz_identity"]: + print(f"\n{f['file']}:{f['line']}:{f['col']} {status}{flag_str}") + print(f" Values: {f['values']}") + print(" ⏭ Skipped: not an identity quaternion") + skipped_count += 1 + continue + + # Skip ambiguous unless --all-quats is set + if not args.all_quats and not f["likely_wxyz"] and not f["is_wxyz_identity"]: + print(f"\n{f['file']}:{f['line']}:{f['col']} {status}{flag_str}") + print(f" Values: {f['values']}") + print(" ⏭ Skipped: ambiguous format (use --all to include)") + skipped_count += 1 + continue + + # Skip boolean lists (false positive) + if any(isinstance(v, bool) for v in f["values"]): + print(f"\n{f['file']}:{f['line']}:{f['col']} {status}{flag_str}") + print(f" Values: {f['values']}") + print(" ⏭ Skipped: boolean list, not a quaternion") + skipped_count += 1 + continue + + new_values = convert_wxyz_to_xyzw(f["values"]) + + # Show context + print("\n" + "─" * 80) + print(f"📍 {f['file']}:{f['line']}{flag_str}") + print("─" * 80) + + context = get_file_context(f["file"], f["line"], args.context) + if context: + print(context) + + print("─" * 80) + print(f" Change: {f['values']} → {new_values}") + + # Preview the fix + preview, count = preview_fix(f["file"], f["line"], f["values"], new_values) + if preview: + count_str = f" ({count} occurrence{'s' if count > 1 else ''})" if count > 1 else "" + print(f" Result{count_str}: {preview.strip()}") + + if args.dry_run: + print(" [DRY RUN - no changes made]") + continue + + # Prompt user unless force mode or apply_all + if not apply_all: + response = prompt_user("Apply this fix?") + if response == "quit": + print("\n⛔ Aborted by user") + break + if response == "all": + apply_all = True + elif response == "no": + print(" ⏭ Skipped") + skipped_count += 1 + continue + + # Apply the fix + success, new_line = apply_fix(f["file"], f["line"], f["values"], new_values) + if success: + print(" ✅ Fixed!") + fixed_count += 1 + else: + print(" ❌ Failed to fix (pattern not found exactly)") + skipped_count += 1 + else: + # Just display mode (no fixing) + print(f"\n{f['file']}:{f['line']}:{f['col']} {status}{flag_str}") + print(f" Values: {f['values']}") + print(f" Source: {f['source'][:80]}...") + + print("\n" + "=" * 100) + + # Summary + unchanged = sum(1 for f in findings if not f["changed"]) + wxyz_identity = sum(1 for f in findings if f["is_wxyz_identity"] and not f["changed"]) + likely_wxyz = sum(1 for f in findings if f["likely_wxyz"] and not f["changed"]) + ambiguous = sum(1 for f in findings if f.get("is_ambiguous") and not f["changed"]) + + print("\nSummary:") + print(f" Total potential quaternions: {len(findings)}") + print(f" Unchanged from main: {unchanged}") + print(f" Unchanged wxyz identity [1,0,0,0]: {wxyz_identity}") + print(f" Unchanged likely wxyz format: {likely_wxyz}") + print(f" Unchanged ambiguous (review manually): {ambiguous}") + + if args.fix or args.fix_identity_only: + print("\nFix Results:") + print(f" Fixed: {fixed_count}") + print(f" Skipped: {skipped_count}") + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/tools/hdf5_to_mp4.py b/simulation/modules/IsaacLab/scripts/tools/hdf5_to_mp4.py new file mode 100644 index 0000000000000000000000000000000000000000..b9e7bdb1a31635616e7756f3dae82377195aa123 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/hdf5_to_mp4.py @@ -0,0 +1,221 @@ +# Copyright (c) 2024-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Script to convert HDF5 demonstration files to MP4 videos. + +This script converts camera frames stored in HDF5 demonstration files to MP4 videos. +It supports multiple camera modalities including RGB, segmentation, and normal maps. +The output videos are saved in the specified directory with appropriate naming. + +required arguments: + --input_file Path to the input HDF5 file. + --output_dir Directory to save the output MP4 files. + +optional arguments: + --input_keys List of input keys to process from the HDF5 file. + (default: ["table_cam", "wrist_cam", "table_cam_segmentation", + "table_cam_normals", "table_cam_shaded_segmentation"]) + --video_height Height of the output video in pixels. (default: 704) + --video_width Width of the output video in pixels. (default: 1280) + --framerate Frames per second for the output video. (default: 30) + --demo_id If provided, only export this specific demo_id. (default: None) +""" + +import argparse +import os + +import cv2 +import h5py +import numpy as np + +# Constants +DEFAULT_VIDEO_HEIGHT = 704 +DEFAULT_VIDEO_WIDTH = 1280 +DEFAULT_INPUT_KEYS = [ + "table_cam", + "wrist_cam", + "table_cam_segmentation", + "table_cam_normals", + "table_cam_shaded_segmentation", + "table_cam_depth", +] +DEFAULT_FRAMERATE = 30 +LIGHT_SOURCE = np.array([0.0, 0.0, 1.0]) +MIN_DEPTH = 0.0 +MAX_DEPTH = 1.5 + + +def parse_args(): + """Parse command line arguments.""" + parser = argparse.ArgumentParser(description="Convert HDF5 demonstration files to MP4 videos.") + parser.add_argument( + "--input_file", + type=str, + required=True, + help="Path to the input HDF5 file containing demonstration data.", + ) + parser.add_argument( + "--output_dir", + type=str, + required=True, + help="Directory path where the output MP4 files will be saved.", + ) + + parser.add_argument( + "--input_keys", + type=str, + nargs="+", + default=DEFAULT_INPUT_KEYS, + help="List of input keys to process.", + ) + parser.add_argument( + "--video_height", + type=int, + default=DEFAULT_VIDEO_HEIGHT, + help="Height of the output video in pixels.", + ) + parser.add_argument( + "--video_width", + type=int, + default=DEFAULT_VIDEO_WIDTH, + help="Width of the output video in pixels.", + ) + parser.add_argument( + "--framerate", + type=int, + default=DEFAULT_FRAMERATE, + help="Frames per second for the output video.", + ) + parser.add_argument( + "--demo_id", + type=int, + default=None, + help="If provided, only export this specific demo_id.", + ) + + args = parser.parse_args() + + return args + + +def write_demo_to_mp4( + hdf5_file, + demo_id, + frames_path, + input_key, + output_dir, + video_height, + video_width, + framerate=DEFAULT_FRAMERATE, +): + """Convert frames from an HDF5 file to an MP4 video. + + Args: + hdf5_file (str): Path to the HDF5 file containing the frames. + demo_id (int): ID of the demonstration to convert. + frames_path (str): Path to the frames data in the HDF5 file. + input_key (str): Name of the input key to convert. + output_dir (str): Directory to save the output MP4 file. + video_height (int): Height of the output video in pixels. + video_width (int): Width of the output video in pixels. + framerate (int, optional): Frames per second for the output video. Defaults to 30. + """ + with h5py.File(hdf5_file, "r") as f: + # Get frames based on input key type + if "shaded_segmentation" in input_key: + temp_key = input_key.replace("shaded_segmentation", "segmentation") + frames = f[f"data/demo_{demo_id}/obs/{temp_key}"] + else: + frames = f[frames_path + "/" + input_key] + + # Setup video writer + output_path = os.path.join(output_dir, f"demo_{demo_id}_{input_key}.mp4") + fourcc = cv2.VideoWriter_fourcc(*"mp4v") + if "depth" in input_key: + video = cv2.VideoWriter(output_path, fourcc, framerate, (video_width, video_height), isColor=False) + else: + video = cv2.VideoWriter(output_path, fourcc, framerate, (video_width, video_height)) + + # Process and write frames + for ix, frame in enumerate(frames): + # Convert normal maps to uint8 if needed + if "normals" in input_key: + frame = (frame * 255.0).astype(np.uint8) + + # Process shaded segmentation frames + elif "shaded_segmentation" in input_key: + seg = frame[..., :-1] + normals_key = input_key.replace("shaded_segmentation", "normals") + normals = f[f"data/demo_{demo_id}/obs/{normals_key}"][ix] + shade = 0.5 + (normals * LIGHT_SOURCE[None, None, :]).sum(axis=-1) * 0.5 + shaded_seg = (shade[..., None] * seg).astype(np.uint8) + frame = np.concatenate((shaded_seg, frame[..., -1:]), axis=-1) + + # Convert RGB to BGR + if "depth" not in input_key: + frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) + else: + frame = (frame[..., 0] - MIN_DEPTH) / (MAX_DEPTH - MIN_DEPTH) + frame = np.where(frame < 0.01, 1.0, frame) + frame = 1.0 - frame + frame = (frame * 255.0).astype(np.uint8) + + # Resize to video resolution + frame = cv2.resize(frame, (video_width, video_height), interpolation=cv2.INTER_CUBIC) + video.write(frame) + + video.release() + + +def get_num_demos(hdf5_file): + """Get the number of demonstrations in the HDF5 file. + + Args: + hdf5_file (str): Path to the HDF5 file. + + Returns: + int: Number of demonstrations found in the file. + """ + with h5py.File(hdf5_file, "r") as f: + return len(f["data"].keys()) + + +def main(): + """Main function to convert all demonstrations to MP4 videos.""" + # Parse command line arguments + args = parse_args() + + # Create output directory if it doesn't exist + os.makedirs(args.output_dir, exist_ok=True) + + # Get number of demonstrations from the file + num_demos = get_num_demos(args.input_file) + print(f"Found {num_demos} demonstrations in {args.input_file}") + + if args.demo_id is not None: + demo_ids = [args.demo_id] + print(f"Exporting only demo_id {args.demo_id}") + else: + demo_ids = list(range(num_demos)) + + # Convert each demonstration + for i in demo_ids: + frames_path = f"data/demo_{str(i)}/obs" + for input_key in args.input_keys: + write_demo_to_mp4( + args.input_file, + i, + frames_path, + input_key, + args.output_dir, + args.video_height, + args.video_width, + args.framerate, + ) + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/tools/merge_hdf5_datasets.py b/simulation/modules/IsaacLab/scripts/tools/merge_hdf5_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..a9fe1c63561d28218d2a7914cafd124e8b4a4098 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/merge_hdf5_datasets.py @@ -0,0 +1,47 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import argparse +import os + +import h5py + +parser = argparse.ArgumentParser(description="Merge a set of HDF5 datasets.") +parser.add_argument( + "--input_files", + type=str, + nargs="+", + default=[], + help="A list of paths to HDF5 files to merge.", +) +parser.add_argument("--output_file", type=str, default="merged_dataset.hdf5", help="File path to merged output.") + +args_cli = parser.parse_args() + + +def merge_datasets(): + for filepath in args_cli.input_files: + if not os.path.exists(filepath): + raise FileNotFoundError(f"The dataset file {filepath} does not exist.") + + with h5py.File(args_cli.output_file, "w") as output: + episode_idx = 0 + copy_attributes = True + + for filepath in args_cli.input_files: + with h5py.File(filepath, "r") as input: + for episode, data in input["data"].items(): + input.copy(f"data/{episode}", output, f"data/demo_{episode_idx}") + episode_idx += 1 + + if copy_attributes: + output["data"].attrs["env_args"] = input["data"].attrs["env_args"] + copy_attributes = False + + print(f"Merged dataset saved to {args_cli.output_file}") + + +if __name__ == "__main__": + merge_datasets() diff --git a/simulation/modules/IsaacLab/scripts/tools/mp4_to_hdf5.py b/simulation/modules/IsaacLab/scripts/tools/mp4_to_hdf5.py new file mode 100644 index 0000000000000000000000000000000000000000..61f7b5b0b40b0f2112f03da8190383f44e9469ac --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/mp4_to_hdf5.py @@ -0,0 +1,169 @@ +# Copyright (c) 2024-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Script to create a new dataset by combining existing HDF5 demonstrations with visually augmented MP4 videos. + +This script takes an existing HDF5 dataset containing demonstrations and a directory of MP4 videos +that are visually augmented versions of the original demonstration videos (e.g., with different lighting, +color schemes, or visual effects). It creates a new HDF5 dataset that preserves all the original +demonstration data (actions, robot state, etc.) but replaces the video frames with the augmented versions. + +required arguments: + --input_file Path to the input HDF5 file containing original demonstrations. + --output_file Path to save the new HDF5 file with augmented videos. + --videos_dir Directory containing the visually augmented MP4 videos. +""" + +import argparse +import glob +import os + +import cv2 +import h5py +import numpy as np + + +def parse_args(): + """Parse command line arguments.""" + parser = argparse.ArgumentParser(description="Create a new dataset with visually augmented videos.") + parser.add_argument( + "--input_file", + type=str, + required=True, + help="Path to the input HDF5 file containing original demonstrations.", + ) + parser.add_argument( + "--videos_dir", + type=str, + required=True, + help="Directory containing the visually augmented MP4 videos.", + ) + parser.add_argument( + "--output_file", + type=str, + required=True, + help="Path to save the new HDF5 file with augmented videos.", + ) + + args = parser.parse_args() + + return args + + +def get_frames_from_mp4(video_path, target_height=None, target_width=None): + """Extract frames from an MP4 video file. + + Args: + video_path (str): Path to the MP4 video file. + target_height (int, optional): Target height for resizing frames. If None, no resizing is done. + target_width (int, optional): Target width for resizing frames. If None, no resizing is done. + + Returns: + np.ndarray: Array of frames from the video in RGB format. + """ + # Open the video file + video = cv2.VideoCapture(video_path) + + # Get video properties + frame_count = int(video.get(cv2.CAP_PROP_FRAME_COUNT)) + + # Read all frames into a numpy array + frames = [] + for _ in range(frame_count): + ret, frame = video.read() + if not ret: + break + frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + if target_height is not None and target_width is not None: + frame = cv2.resize(frame, (target_width, target_height), interpolation=cv2.INTER_LINEAR) + frames.append(frame) + + # Convert to numpy array + frames = np.array(frames).astype(np.uint8) + + # Release the video object + video.release() + + return frames + + +def process_video_and_demo(f_in, f_out, video_path, orig_demo_id, new_demo_id): + """Process a single video and create a new demo with augmented video frames. + + Args: + f_in (h5py.File): Input HDF5 file. + f_out (h5py.File): Output HDF5 file. + video_path (str): Path to the augmented video file. + orig_demo_id (int): ID of the original demo to copy. + new_demo_id (int): ID for the new demo. + """ + # Get original demo data + actions = f_in[f"data/demo_{str(orig_demo_id)}/actions"] + eef_pos = f_in[f"data/demo_{str(orig_demo_id)}/obs/eef_pos"] + eef_quat = f_in[f"data/demo_{str(orig_demo_id)}/obs/eef_quat"] + gripper_pos = f_in[f"data/demo_{str(orig_demo_id)}/obs/gripper_pos"] + wrist_cam = f_in[f"data/demo_{str(orig_demo_id)}/obs/wrist_cam"] + + # Get original video resolution + orig_video = f_in[f"data/demo_{str(orig_demo_id)}/obs/table_cam"] + target_height, target_width = orig_video.shape[1:3] + + # Extract frames from video with original resolution + frames = get_frames_from_mp4(video_path, target_height, target_width) + + # Create new datasets + f_out.create_dataset(f"data/demo_{str(new_demo_id)}/actions", data=actions, compression="gzip") + f_out.create_dataset(f"data/demo_{str(new_demo_id)}/obs/eef_pos", data=eef_pos, compression="gzip") + f_out.create_dataset(f"data/demo_{str(new_demo_id)}/obs/eef_quat", data=eef_quat, compression="gzip") + f_out.create_dataset(f"data/demo_{str(new_demo_id)}/obs/gripper_pos", data=gripper_pos, compression="gzip") + f_out.create_dataset( + f"data/demo_{str(new_demo_id)}/obs/table_cam", data=frames.astype(np.uint8), compression="gzip" + ) + f_out.create_dataset(f"data/demo_{str(new_demo_id)}/obs/wrist_cam", data=wrist_cam, compression="gzip") + + # Copy attributes + f_out[f"data/demo_{str(new_demo_id)}"].attrs["num_samples"] = f_in[f"data/demo_{str(orig_demo_id)}"].attrs[ + "num_samples" + ] + + +def main(): + """Main function to create a new dataset with augmented videos.""" + # Parse command line arguments + args = parse_args() + + # Get list of MP4 videos + search_path = os.path.join(args.videos_dir, "*.mp4") + video_paths = glob.glob(search_path) + video_paths.sort() + print(f"Found {len(video_paths)} MP4 videos in {args.videos_dir}") + + # Create output directory if it doesn't exist + os.makedirs(os.path.dirname(args.output_file), exist_ok=True) + + with h5py.File(args.input_file, "r") as f_in, h5py.File(args.output_file, "w") as f_out: + # Copy all data from input to output + f_in.copy("data", f_out) + + # Get the largest demo ID to start new demos from + demo_ids = [int(key.split("_")[1]) for key in f_in["data"].keys()] + next_demo_id = max(demo_ids) + 1 # noqa: SIM113 + print(f"Starting new demos from ID: {next_demo_id}") + + # Process each video and create new demo + for video_path in video_paths: + # Extract original demo ID from video filename + video_filename = os.path.basename(video_path) + orig_demo_id = int(video_filename.split("_")[1]) + + process_video_and_demo(f_in, f_out, video_path, orig_demo_id, next_demo_id) + next_demo_id += 1 + + print(f"Augmented data saved to {args.output_file}") + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/scripts/tools/process_meshes_to_obj.py b/simulation/modules/IsaacLab/scripts/tools/process_meshes_to_obj.py new file mode 100644 index 0000000000000000000000000000000000000000..2c5be04c0e5ce30aa1254704489043f2d445e67c --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/process_meshes_to_obj.py @@ -0,0 +1,90 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Convert all mesh files to `.obj` in given folders.""" + +import argparse +import os +import shutil +import subprocess + +# Constants +# Path to blender +BLENDER_EXE_PATH = shutil.which("blender") + + +def parse_cli_args(): + """Parse the input command line arguments.""" + # add argparse arguments + parser = argparse.ArgumentParser("Utility to convert all mesh files to `.obj` in given folders.") + parser.add_argument("input_dir", type=str, help="The input directory from which to load meshes.") + parser.add_argument( + "-o", + "--output_dir", + type=str, + default=None, + help="The output directory to save converted meshes into. Default is same as input directory.", + ) + args_cli = parser.parse_args() + # resolve output directory + if args_cli.output_dir is None: + args_cli.output_dir = args_cli.input_dir + # return arguments + return args_cli + + +def run_blender_convert2obj(in_file: str, out_file: str): + """Calls the python script using `subprocess` to perform processing of mesh file. + + Args: + in_file: Input mesh file. + out_file: Output obj file. + """ + # resolve for python file + tools_dirname = os.path.dirname(os.path.abspath(__file__)) + script_file = os.path.join(tools_dirname, "blender_obj.py") + # complete command + command_exe = f"{BLENDER_EXE_PATH} --background --python {script_file} -- -i {in_file} -o {out_file}" + # break command into list + command_exe_list = command_exe.split(" ") + # run command + subprocess.run(command_exe_list) + + +def convert_meshes(source_folders: list[str], destination_folders: list[str]): + """Processes all mesh files of supported format into OBJ file using blender. + + Args: + source_folders: List of directories to search for meshes. + destination_folders: List of directories to dump converted files. + """ + # create folder for corresponding destination + for folder in destination_folders: + os.makedirs(folder, exist_ok=True) + # iterate over each folder + for in_folder, out_folder in zip(source_folders, destination_folders): + # extract all dae files in the directory + mesh_filenames = [f for f in os.listdir(in_folder) if f.endswith("dae")] + mesh_filenames += [f for f in os.listdir(in_folder) if f.endswith("stl")] + mesh_filenames += [f for f in os.listdir(in_folder) if f.endswith("STL")] + # print status + print(f"Found {len(mesh_filenames)} files to process in directory: {in_folder}") + # iterate over each OBJ file + for mesh_file in mesh_filenames: + # extract meshname + mesh_name = os.path.splitext(mesh_file)[0] + # complete path of input and output files + in_file_path = os.path.join(in_folder, mesh_file) + out_file_path = os.path.join(out_folder, mesh_name + ".obj") + # perform blender processing + print("Processing: ", in_file_path) + run_blender_convert2obj(in_file_path, out_file_path) + + +if __name__ == "__main__": + # Parse command line arguments + args = parse_cli_args() + # Run conversion + convert_meshes([args.input_dir], [args.output_dir]) diff --git a/simulation/modules/IsaacLab/scripts/tools/record_demos.py b/simulation/modules/IsaacLab/scripts/tools/record_demos.py new file mode 100644 index 0000000000000000000000000000000000000000..c15330b52c37531e22707a4885aa591f9943ba39 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/record_demos.py @@ -0,0 +1,716 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause +""" +Script to record demonstrations with Isaac Lab environments using human teleoperation. + +This script allows users to record demonstrations operated by human teleoperation for a specified task. +The recorded demonstrations are stored as episodes in a hdf5 file. Users can specify the task, teleoperation +device, dataset directory, and environment stepping rate through command-line arguments. + +This script supports two teleoperation stacks: +1. Native Isaac Lab teleop stack (via teleop_devices in env_cfg) +2. IsaacTeleop-based stack (via isaac_teleop in env_cfg) + +The script automatically detects which stack to use based on the environment config. + +required arguments: + --task Name of the task. + +optional arguments: + -h, --help Show this help message and exit + --teleop_device Legacy teleop device name. When omitted, IsaacTeleop is used if + configured, otherwise keyboard. When set, forces the legacy path. + --dataset_file File path to export recorded demos. (default: "./datasets/dataset.hdf5") + --step_hz Environment stepping rate in Hz. (default: 30) + --num_demos Number of demonstrations to record. (default: 0) + --num_success_steps Number of continuous steps with task success for concluding a demo as successful. + (default: 10) +""" + +"""Launch Isaac Sim Simulator first.""" + +# Standard library imports +import argparse +import contextlib + +# Isaac Lab AppLauncher +from isaaclab.app import AppLauncher +from isaaclab.utils.string import list_intersection, string_to_callable + +# add argparse arguments +parser = argparse.ArgumentParser(description="Record demonstrations for Isaac Lab environments.") +parser.add_argument("--task", type=str, required=True, help="Name of the task.") +parser.add_argument( + "--teleop_device", + type=str, + default=None, + help=( + "Legacy teleop device name. When omitted, the IsaacTeleop pipeline is used if configured in the env," + " otherwise keyboard is used as fallback. When explicitly provided, the script uses the legacy" + " teleop_devices path and looks up this name in env_cfg.teleop_devices.devices." + ), +) +parser.add_argument( + "--dataset_file", type=str, default="./datasets/dataset.hdf5", help="File path to export recorded demos." +) +parser.add_argument("--step_hz", type=int, default=30, help="Environment stepping rate in Hz.") +parser.add_argument( + "--num_demos", type=int, default=0, help="Number of demonstrations to record. Set to 0 for infinite." +) +parser.add_argument( + "--num_success_steps", + type=int, + default=10, + help="Number of continuous steps with task success for concluding a demo as successful. Default is 10.", +) +parser.add_argument( + "--reset_sim_buffer_each_episode", + action=argparse.BooleanOptionalAction, + default=True, + help=( + "Call env.sim.reset() before the initial episode and between recording attempts." + " Use --no-reset_sim_buffer_each_episode to preserve simulation buffers." + ), +) +parser.add_argument( + "--cloudxr_env", + type=str, + default="cloudxrjs", + help=( + "Path to a CloudXR .env file, or a shorthand: 'cloudxrjs' (Quest/Pico, default) or 'avp' (Apple Vision Pro)." + " Set to 'none' to disable CloudXR auto-launch entirely." + ), +) +parser.add_argument( + "--auto_launch_cloudxr", + action=argparse.BooleanOptionalAction, + default=True, + help="Auto-launch the CloudXR runtime when --cloudxr_env is set. Use --no-auto_launch_cloudxr to disable.", +) +parser.add_argument( + "--mcap_record_path", + type=str, + default=None, + help=( + "Debug-only: write the live IsaacTeleop session to this MCAP file (one continuous file for the whole run)." + " Intended for pairing with teleop_replay_agent.py in CI -- NOT a data-generation format. MCAPs produced" + " here lack per-episode segmentation, world-frame anchor state, env reset state, and have no public Python" + " decoder. For data-gen workflows use the HDF5 dataset path (default). Ignored when the IsaacTeleop stack" + " is not in use." + ), +) + +parser.add_argument("--external_callback", default=None, help="Fully qualified path to an externally defined callback.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli, remaining_args = parser.parse_known_args() + +# Validate required arguments +if args_cli.task is None: + parser.error("--task is required") + +app_launcher_args = vars(args_cli) + +# launch the simulator +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +# Call an external callback if requested. +remaining_args_env_registration = None +if args_cli.external_callback: + external_callback_function = string_to_callable(args_cli.external_callback, separator=".") + remaining_args_env_registration = external_callback_function() + +# Error on unrecognized arguments. +unrecognized_args = list_intersection(remaining_args, remaining_args_env_registration) +if unrecognized_args: + parser.error(f"unrecognized arguments: {' '.join(unrecognized_args)}") + +"""Rest everything follows.""" + + +# Third-party imports +import logging +import os +import time +from collections.abc import Callable + +import gymnasium as gym +import torch + +import omni.ui as ui + +from isaaclab.devices import Se3Keyboard, Se3KeyboardCfg, Se3SpaceMouse, Se3SpaceMouseCfg +from isaaclab.devices.openxr import remove_camera_configs +from isaaclab.devices.teleop_device_factory import create_teleop_device +from isaaclab.envs import DirectRLEnvCfg, ManagerBasedRLEnvCfg +from isaaclab.envs.mdp.recorders.recorders_cfg import ActionStateRecorderManagerCfg +from isaaclab.envs.ui import EmptyWindow +from isaaclab.managers import DatasetExportMode + +import isaaclab_mimic.envs # noqa: F401 +from isaaclab_mimic.ui.instruction_display import InstructionDisplay, show_subtask_instructions + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils.parse_cfg import load_cfg_from_registry, parse_env_cfg + +logger = logging.getLogger(__name__) + +_CLOUDXR_ENV_SHORTHANDS: dict[str, str] = {} + + +def _resolve_cloudxr_env(value: str | None) -> str | None: + """Resolve ``--cloudxr_env`` shorthands to absolute ``.env`` file paths. + + Accepts ``"cloudxrjs"`` (Quest/Pico), ``"avp"`` (Apple Vision Pro), + ``"none"`` / ``None`` (disable), or an arbitrary file path. + """ + if value is None or value.strip() == "" or value.lower() == "none": + return None + if not _CLOUDXR_ENV_SHORTHANDS: + from isaaclab_teleop import CLOUDXR_AVP_ENV, CLOUDXR_JS_ENV + + _CLOUDXR_ENV_SHORTHANDS["cloudxrjs"] = CLOUDXR_JS_ENV + _CLOUDXR_ENV_SHORTHANDS["avp"] = CLOUDXR_AVP_ENV + return _CLOUDXR_ENV_SHORTHANDS.get(value.lower(), value) + + +class RateLimiter: + """Convenience class for enforcing rates in loops.""" + + def __init__(self, hz: int): + """Initialize a RateLimiter with specified frequency. + + Args: + hz: Frequency to enforce in Hertz. + """ + self.hz = hz + self.last_time = time.time() + self.sleep_duration = 1.0 / hz + self.render_period = min(0.033, self.sleep_duration) + + def sleep(self, env: gym.Env): + """Attempt to sleep at the specified rate in hz. + + Args: + env: Environment to render during sleep periods. + """ + next_wakeup_time = self.last_time + self.sleep_duration + while time.time() < next_wakeup_time: + time.sleep(self.render_period) + env.sim.render() + + self.last_time = self.last_time + self.sleep_duration + + # detect time jumping forwards (e.g. loop is too slow) + if self.last_time < time.time(): + while self.last_time < time.time(): + self.last_time += self.sleep_duration + + +def setup_output_directories() -> tuple[str, str]: + """Set up output directories for saving demonstrations. + + Creates the output directory if it doesn't exist and extracts the file name + from the dataset file path. + + Returns: + tuple[str, str]: A tuple containing: + - output_dir: The directory path where the dataset will be saved + - output_file_name: The filename (without extension) for the dataset + """ + # get directory path and file name (without extension) from cli arguments + output_dir = os.path.dirname(args_cli.dataset_file) + output_file_name = os.path.splitext(os.path.basename(args_cli.dataset_file))[0] + + # create directory if it does not exist + if not os.path.exists(output_dir): + os.makedirs(output_dir) + print(f"Created output directory: {output_dir}") + + return output_dir, output_file_name + + +def create_environment_config( + output_dir: str, output_file_name: str +) -> tuple[ManagerBasedRLEnvCfg | DirectRLEnvCfg, object | None, bool]: + """Create and configure the environment configuration. + + Parses the environment configuration and makes necessary adjustments for demo recording. + Extracts the success termination function and configures the recorder manager. + + Args: + output_dir: Directory where recorded demonstrations will be saved + output_file_name: Name of the file to store the demonstrations + + Returns: + tuple[isaaclab_tasks.utils.parse_cfg.EnvCfg, Optional[object], bool]: A tuple containing: + - env_cfg: The configured environment configuration + - success_term: The success termination object or None if not available + - use_isaac_teleop: Whether IsaacTeleop stack should be used + + Raises: + Exception: If parsing the environment configuration fails + """ + # parse configuration + try: + env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=1) + env_cfg.env_name = args_cli.task.split(":")[-1] + except Exception as e: + logger.error(f"Failed to parse environment configuration: {e}") + exit(1) + + # When --teleop_device is explicitly provided, use the legacy teleop_devices path + # even if isaac_teleop is configured. Otherwise prefer isaac_teleop when available. + teleop_device_explicitly_set = args_cli.teleop_device is not None + use_isaac_teleop = ( + not teleop_device_explicitly_set and hasattr(env_cfg, "isaac_teleop") and env_cfg.isaac_teleop is not None + ) + + # extract success checking function to invoke in the main loop + success_term = None + if hasattr(env_cfg.terminations, "success"): + success_term = env_cfg.terminations.success + env_cfg.terminations.success = None + else: + logger.warning( + "No success termination term was found in the environment." + " Will not be able to mark recorded demos as successful." + ) + + if use_isaac_teleop or args_cli.xr: + # If cameras are not enabled and XR is enabled, remove camera configs + if not args_cli.enable_cameras: + env_cfg = remove_camera_configs(env_cfg) + env_cfg.sim.render.antialiasing_mode = "DLSS" + + # modify configuration such that the environment runs indefinitely until + # the goal is reached or other termination conditions are met + env_cfg.terminations.time_out = None + env_cfg.observations.policy.concatenate_terms = False + + demo_recorder_cfg_entry_point = gym.spec(args_cli.task.split(":")[-1]).kwargs.get("demo_recorder_cfg_entry_point") + if demo_recorder_cfg_entry_point is None: + env_cfg.recorders = ActionStateRecorderManagerCfg() + else: + env_cfg.recorders = load_cfg_from_registry(args_cli.task, "demo_recorder_cfg_entry_point") + env_cfg.recorders.dataset_export_dir_path = output_dir + env_cfg.recorders.dataset_filename = output_file_name + env_cfg.recorders.dataset_export_mode = DatasetExportMode.EXPORT_SUCCEEDED_ONLY + + return env_cfg, success_term, use_isaac_teleop + + +def create_environment(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg) -> gym.Env: + """Create the environment from the configuration. + + Args: + env_cfg: The environment configuration object that defines the environment properties. + This should be an instance of EnvCfg created by parse_env_cfg(). + + Returns: + gym.Env: A Gymnasium environment instance for the specified task. + + Raises: + Exception: If environment creation fails for any reason. + """ + try: + env = gym.make(args_cli.task, cfg=env_cfg).unwrapped + return env + except Exception as e: + logger.error(f"Failed to create environment: {e}") + exit(1) + + +def _create_builtin_device(device_name: str) -> object | None: + """Create a built-in teleop device by name, or return None if unrecognized.""" + name = device_name.lower() + if name == "keyboard": + return Se3Keyboard(Se3KeyboardCfg(pos_sensitivity=0.2, rot_sensitivity=0.5)) + elif name == "spacemouse": + return Se3SpaceMouse(Se3SpaceMouseCfg(pos_sensitivity=0.2, rot_sensitivity=0.5)) + return None + + +def setup_teleop_device(callbacks: dict[str, Callable], use_isaac_teleop: bool = False) -> object: + """Set up the teleoperation device based on configuration. + + Attempts to create a teleoperation device based on the environment configuration. + Falls back to default devices if the specified device is not found in the configuration. + + Args: + callbacks: Dictionary mapping callback keys to functions that will be + attached to the teleop device + use_isaac_teleop: Whether to use IsaacTeleop stack instead of native stack + + Returns: + object: The configured teleoperation device interface + + Raises: + Exception: If teleop device creation fails + """ + teleop_device_explicitly_set = args_cli.teleop_device is not None + teleop_interface = None + try: + if use_isaac_teleop: + from isaaclab_teleop import create_isaac_teleop_device + + teleop_interface = create_isaac_teleop_device( + env_cfg.isaac_teleop, + sim_device=args_cli.device, + callbacks=callbacks, + cloudxr_env_file=_resolve_cloudxr_env(args_cli.cloudxr_env), + auto_launch_cloudxr=args_cli.auto_launch_cloudxr, + mcap_record_path=args_cli.mcap_record_path, + ) + if args_cli.mcap_record_path is not None: + logger.info("Recording live IsaacTeleop session to MCAP (debug-only): %s", args_cli.mcap_record_path) + + elif teleop_device_explicitly_set: + device_name = args_cli.teleop_device + if hasattr(env_cfg, "teleop_devices") and device_name in env_cfg.teleop_devices.devices: + teleop_interface = create_teleop_device(device_name, env_cfg.teleop_devices.devices, callbacks) + else: + teleop_interface = _create_builtin_device(device_name) + if teleop_interface is None: + logger.error( + f"--teleop_device={device_name} was passed but no matching entry exists in" + " env_cfg.teleop_devices and it is not a built-in device name. Either remove" + " --teleop_device to use the IsaacTeleop pipeline, or add a" + f" '{device_name}' entry under teleop_devices in the environment config." + " Built-in devices: keyboard, spacemouse." + ) + exit(1) + for key, callback in callbacks.items(): + teleop_interface.add_callback(key, callback) + else: + # No --teleop_device and no isaac_teleop: fall back to keyboard + teleop_interface = Se3Keyboard(Se3KeyboardCfg(pos_sensitivity=0.2, rot_sensitivity=0.5)) + for key, callback in callbacks.items(): + teleop_interface.add_callback(key, callback) + except Exception as e: + logger.error(f"Failed to create teleop device: {e}") + exit(1) + + if teleop_interface is None: + logger.error("Failed to create teleop interface") + exit(1) + + return teleop_interface + + +def setup_ui(label_text: str, env: gym.Env) -> InstructionDisplay: + """Set up the user interface elements. + + Creates instruction display and UI window with labels for showing information + to the user during demonstration recording. + + Args: + label_text: Text to display showing current recording status + env: The environment instance for which UI is being created + + Returns: + InstructionDisplay: The configured instruction display object + """ + instruction_display = InstructionDisplay(args_cli.xr) + if not args_cli.xr: + window = EmptyWindow(env, "Instruction") + with window.ui_window_elements["main_vstack"]: + demo_label = ui.Label(label_text) + subtask_label = ui.Label("") + instruction_display.set_labels(subtask_label, demo_label) + + return instruction_display + + +def process_success_condition(env: gym.Env, success_term: object | None, success_step_count: int) -> tuple[int, bool]: + """Process the success condition for the current step. + + Checks if the environment has met the success condition for the required + number of consecutive steps. Marks the episode as successful if criteria are met. + + Args: + env: The environment instance to check + success_term: The success termination object or None if not available + success_step_count: Current count of consecutive successful steps + + Returns: + tuple[int, bool]: A tuple containing: + - updated success_step_count: The updated count of consecutive successful steps + - success_reset_needed: Boolean indicating if reset is needed due to success + """ + if success_term is None: + return success_step_count, False + + if bool(success_term.func(env, **success_term.params)[0]): + success_step_count += 1 + if success_step_count >= args_cli.num_success_steps: + env.recorder_manager.record_pre_reset([0], force_export_or_skip=False) + env.recorder_manager.set_success_to_episodes( + [0], torch.tensor([[True]], dtype=torch.bool, device=env.device) + ) + env.recorder_manager.export_episodes([0]) + print("Success condition met! Recording completed.") + return success_step_count, True + else: + success_step_count = 0 + + return success_step_count, False + + +def handle_reset( + env: gym.Env, + success_step_count: int, + instruction_display: InstructionDisplay, + label_text: str, + teleop_interface: object | None = None, +) -> int: + """Handle resetting the environment. + + Resets the environment, recorder manager, teleop device, and related + state variables. Updates the instruction display with current status. + + Args: + env: The environment instance to reset. + success_step_count: Current count of consecutive successful steps. + instruction_display: The display object to update. + label_text: Text to display showing current recording status. + teleop_interface: Optional teleop device to reset (resets XR anchor + and retargeter cross-step state). + + Returns: + Reset success step count (0). + """ + print("Resetting environment...") + if args_cli.reset_sim_buffer_each_episode: + env.sim.reset() + env.recorder_manager.reset() + env.reset() + if teleop_interface is not None and hasattr(teleop_interface, "reset"): + teleop_interface.reset() + success_step_count = 0 + instruction_display.show_demo(label_text) + return success_step_count + + +def run_simulation_loop( + env: gym.Env, + teleop_interface: object | None, + success_term: object | None, + rate_limiter: RateLimiter | None, + use_isaac_teleop: bool = False, +) -> int: + """Run the main simulation loop for collecting demonstrations. + + Sets up callback functions for teleop device, initializes the UI, + and runs the main loop that processes user inputs and environment steps. + Records demonstrations when success conditions are met. + + Args: + env: The environment instance + teleop_interface: Optional teleop interface (will be created if None) + success_term: The success termination object or None if not available + rate_limiter: Optional rate limiter to control simulation speed + use_isaac_teleop: Whether to use IsaacTeleop stack + + Returns: + int: Number of successful demonstrations recorded + """ + current_recorded_demo_count = 0 + success_step_count = 0 + should_reset_recording_instance = False + # For IsaacTeleop or XR, default to inactive until START is triggered + running_recording_instance = not (args_cli.xr or use_isaac_teleop) + + # Callback closures for the teleop device + def reset_recording_instance(): + nonlocal should_reset_recording_instance + if success_step_count > 0: + print( + "Manual reset ignored. Success has fired and post-success steps are still recording. Please wait for" + " the automatic reset." + ) + return + should_reset_recording_instance = True + print("Recording instance reset requested") + + def start_recording_instance(): + nonlocal running_recording_instance + running_recording_instance = True + print("Recording started") + + def stop_recording_instance(): + nonlocal running_recording_instance + running_recording_instance = False + print("Recording paused") + + # Set up teleoperation callbacks. For IsaacTeleop the primary control + # path is poll_control_events(); these callbacks are bridged automatically + # and also serve native (keyboard / spacemouse) devices. + teleoperation_callbacks = { + "R": reset_recording_instance, + "START": start_recording_instance, + "STOP": stop_recording_instance, + "RESET": reset_recording_instance, + } + + teleop_interface = setup_teleop_device(teleoperation_callbacks, use_isaac_teleop) + + label_text = f"Recorded {current_recorded_demo_count} successful demonstrations." + instruction_display = setup_ui(label_text, env) + + def inner_loop(): + """Inner loop function with access to nonlocal variables.""" + nonlocal current_recorded_demo_count, success_step_count, should_reset_recording_instance + nonlocal running_recording_instance, label_text + + # Reset before starting + if args_cli.reset_sim_buffer_each_episode: + env.sim.reset() + env.reset() + teleop_interface.reset() + + subtasks = {} + stack_name = "IsaacTeleop" if use_isaac_teleop else "native" + print(f"{stack_name} recording started.") + + if use_isaac_teleop: + from isaaclab_teleop import poll_control_events + + with contextlib.suppress(KeyboardInterrupt), torch.inference_mode(): + while simulation_app.is_running(): + # Get teleop command (may be None while waiting for session start) + action = teleop_interface.advance() + + if use_isaac_teleop: + ctrl = poll_control_events(teleop_interface) + if ctrl.is_active is not None: + running_recording_instance = ctrl.is_active + if ctrl.should_reset: + should_reset_recording_instance = True + + if action is None: + env.sim.render() + continue + # Expand to batch dimension + actions = action.repeat(env.num_envs, 1) + + # Perform action on environment + if running_recording_instance: + # Compute actions based on environment + obv = env.step(actions) + if subtasks is not None: + if subtasks == {}: + subtasks = obv[0].get("subtask_terms") + elif subtasks: + show_subtask_instructions(instruction_display, subtasks, obv, env.cfg) + else: + env.sim.render() + + # Check for success condition + success_step_count_new, success_reset_needed = process_success_condition( + env, success_term, success_step_count + ) + success_step_count = success_step_count_new + if success_reset_needed: + should_reset_recording_instance = True + + # Update demo count if it has changed + if env.recorder_manager.exported_successful_episode_count > current_recorded_demo_count: + current_recorded_demo_count = env.recorder_manager.exported_successful_episode_count + label_text = f"Recorded {current_recorded_demo_count} successful demonstrations." + print(label_text) + + # Check if we've reached the desired number of demos + if ( + args_cli.num_demos > 0 + and env.recorder_manager.exported_successful_episode_count >= args_cli.num_demos + ): + label_text = f"All {current_recorded_demo_count} demonstrations recorded.\nExiting the app." + instruction_display.show_demo(label_text) + print(label_text) + target_time = time.time() + 0.8 + while time.time() < target_time: + if rate_limiter: + rate_limiter.sleep(env) + else: + env.sim.render() + break + + # Handle reset if requested + if should_reset_recording_instance: + success_step_count = handle_reset( + env, success_step_count, instruction_display, label_text, teleop_interface + ) + should_reset_recording_instance = False + + # Check if simulation is stopped + if env.sim.is_stopped(): + break + + # Rate limiting + if rate_limiter: + rate_limiter.sleep(env) + + # Run the loop with or without context manager based on stack + if use_isaac_teleop: + with teleop_interface: + inner_loop() + else: + inner_loop() + + return current_recorded_demo_count + + +def main() -> None: + """Collect demonstrations from the environment using teleop interfaces. + + Main function that orchestrates the entire process: + 1. Sets up rate limiting based on configuration + 2. Creates output directories for saving demonstrations + 3. Configures the environment + 4. Runs the simulation loop to collect demonstrations + 5. Cleans up resources when done + + Raises: + Exception: Propagates exceptions from any of the called functions + """ + # Set up output directories + output_dir, output_file_name = setup_output_directories() + + # Create and configure environment + global env_cfg # Make env_cfg available to setup_teleop_device + env_cfg, success_term, use_isaac_teleop = create_environment_config(output_dir, output_file_name) + + # if handtracking or IsaacTeleop is selected, rate limiting is achieved via OpenXR + if args_cli.xr or use_isaac_teleop: + rate_limiter = None + from isaaclab.ui.xr_widgets import TeleopVisualizationManager, XRVisualization + + # Assign the teleop visualization manager to the visualization system + XRVisualization.assign_manager(TeleopVisualizationManager) + else: + rate_limiter = RateLimiter(args_cli.step_hz) + + # Create environment + env = create_environment(env_cfg) + + # Run simulation loop + current_recorded_demo_count = run_simulation_loop(env, None, success_term, rate_limiter, use_isaac_teleop) + + # Clean up + env.close() + print(f"Recording session completed with {current_recorded_demo_count} successful demonstrations") + print(f"Demonstrations saved to: {args_cli.dataset_file}") + + +if __name__ == "__main__": + # run the main function + main() + # env.close() already closes the USD stage via sim.clear_instance(). + # Pump the event loop so the viewport processes closure, then close the app. + simulation_app.update() + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tools/replay_demos.py b/simulation/modules/IsaacLab/scripts/tools/replay_demos.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ecae95f1184cf7398c9647a0e67c4af717dc54 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/replay_demos.py @@ -0,0 +1,354 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause +"""Script to replay demonstrations with Isaac Lab environments.""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher +from isaaclab.utils.string import list_intersection, string_to_callable + +# add argparse arguments +parser = argparse.ArgumentParser(description="Replay demonstrations in Isaac Lab environments.") +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to replay episodes.") +parser.add_argument("--task", type=str, default=None, help="Force to use the specified task.") +parser.add_argument( + "--select_episodes", + type=int, + nargs="+", + default=[], + help="A list of episode indices to be replayed. Keep empty to replay all in the dataset file.", +) +parser.add_argument("--dataset_file", type=str, default="datasets/dataset.hdf5", help="Dataset file to be replayed.") +parser.add_argument( + "--validate_states", + action="store_true", + default=False, + help=( + "Validate if the states, if available, match between loaded from datasets and replayed. Only valid if" + " --num_envs is 1." + ), +) +parser.add_argument( + "--validate_success_rate", + action="store_true", + default=False, + help="Validate the replay success rate using the task environment termination criteria", +) +parser.add_argument( + "--reset_sim_buffer_each_episode", + action="store_true", + default=False, + help=( + "Before loading each episode's initial state, call env.sim.reset() to clear" + " simulation buffers. Only valid with --num_envs 1." + ), +) + +parser.add_argument("--external_callback", default=None, help="Fully qualified path to an externally defined callback.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli, remaining_args = parser.parse_known_args() +# args_cli.headless = True + +# launch the simulator +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +# Call an external callback if requested. +remaining_args_env_registration = None +if args_cli.external_callback: + external_callback_function = string_to_callable(args_cli.external_callback, separator=".") + remaining_args_env_registration = external_callback_function() + +# Error on unrecognized arguments. +unrecognized_args = list_intersection(remaining_args, remaining_args_env_registration) +if unrecognized_args: + parser.error(f"unrecognized arguments: {' '.join(unrecognized_args)}") + +"""Rest everything follows.""" + +import contextlib +import os + +import gymnasium as gym +import torch + +from isaaclab.devices import Se3Keyboard, Se3KeyboardCfg +from isaaclab.utils.datasets import EpisodeData, HDF5DatasetFileHandler + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils.parse_cfg import parse_env_cfg + +is_paused = False + + +def play_cb(): + global is_paused + is_paused = False + + +def pause_cb(): + global is_paused + is_paused = True + + +def compare_states(state_from_dataset, runtime_state, runtime_env_index) -> (bool, str): + """Compare states from dataset and runtime. + + Args: + state_from_dataset: State from dataset. + runtime_state: State from runtime. + runtime_env_index: Index of the environment in the runtime states to be compared. + + Returns: + bool: True if states match, False otherwise. + str: Log message if states don't match. + """ + states_matched = True + output_log = "" + for asset_type in ["articulation", "rigid_object"]: + for asset_name in runtime_state[asset_type].keys(): + for state_name in runtime_state[asset_type][asset_name].keys(): + runtime_asset_state = runtime_state[asset_type][asset_name][state_name][runtime_env_index] + dataset_asset_state = state_from_dataset[asset_type][asset_name][state_name] + if len(dataset_asset_state) != len(runtime_asset_state): + raise ValueError(f"State shape of {state_name} for asset {asset_name} don't match") + for i in range(len(dataset_asset_state)): + if abs(dataset_asset_state[i] - runtime_asset_state[i]) > 0.01: + states_matched = False + output_log += f'\tState ["{asset_type}"]["{asset_name}"]["{state_name}"][{i}] don\'t match\r\n' + output_log += f"\t Dataset:\t{dataset_asset_state[i]}\r\n" + output_log += f"\t Runtime: \t{runtime_asset_state[i]}\r\n" + return states_matched, output_log + + +def replay_episodes_loop( # noqa: C901 + env, + dataset_file_handler: HDF5DatasetFileHandler, + episode_names: list[str], + episode_count: int, + episode_indices_to_replay: list[int], + num_envs: int, + success_term, + state_validation_enabled: bool, + idle_action: torch.Tensor, + reset_sim_buffer_each_episode: bool, +) -> tuple[int, int, list[int]]: + """Run the replay loop until all selected episodes finish or the app exits. + + Returns: + Tuple of (replayed_episode_count, recorded_episode_count, failed_demo_ids). + """ + replayed_episode_count = 0 + recorded_episode_count = 0 + current_episode_indices: list[int | None] = [None] * num_envs + failed_demo_ids: list[int] = [] + + with contextlib.suppress(KeyboardInterrupt) and torch.inference_mode(): + while simulation_app.is_running() and not simulation_app.is_exiting(): + env_episode_data_map = {index: EpisodeData() for index in range(num_envs)} + first_loop = True + has_next_action = True + episode_ended = [False] * num_envs + while has_next_action: + # initialize actions with idle action so those without next action will not move + actions = idle_action.clone() + has_next_action = False + for env_id in range(num_envs): + env_next_action = env_episode_data_map[env_id].get_next_action() + if env_next_action is None: + # check if the episode is successful after the whole episode_data is + if ( + (success_term is not None) + and (current_episode_indices[env_id]) is not None + and (not episode_ended[env_id]) + ): + if bool(success_term.func(env, **success_term.params)[env_id]): + recorded_episode_count += 1 + plural_trailing_s = "s" if recorded_episode_count > 1 else "" + + print( + f"Successfully replayed {recorded_episode_count} episode{plural_trailing_s} out" + f" of {replayed_episode_count} demos." + ) + else: + # if not successful, add to failed demo IDs list + cid = current_episode_indices[env_id] + if cid is not None and cid not in failed_demo_ids: + failed_demo_ids.append(cid) + + episode_ended[env_id] = True + + next_episode_index = None + while episode_indices_to_replay: + next_episode_index = episode_indices_to_replay.pop(0) + + if next_episode_index < episode_count: + episode_ended[env_id] = False + break + next_episode_index = None + + if next_episode_index is not None: + replayed_episode_count += 1 + current_episode_indices[env_id] = next_episode_index + print(f"{replayed_episode_count:4}: Loading #{next_episode_index} episode to env_{env_id}") + episode_data = dataset_file_handler.load_episode( + episode_names[next_episode_index], env.device + ) + env_episode_data_map[env_id] = episode_data + # Set initial state for the new episode + initial_state = episode_data.get_initial_state() + if reset_sim_buffer_each_episode: + env.sim.reset() + env.reset_to(initial_state, torch.tensor([env_id], device=env.device), is_relative=True) + # Get the first action for the new episode + env_next_action = env_episode_data_map[env_id].get_next_action() + has_next_action = True + else: + continue + else: + has_next_action = True + actions[env_id] = env_next_action + if first_loop: + first_loop = False + else: + while is_paused: + env.sim.render() + continue + env.step(actions) + + if state_validation_enabled: + state_from_dataset = env_episode_data_map[0].get_next_state() + if state_from_dataset is not None: + print( + f"Validating states at action-index: {env_episode_data_map[0].next_state_index - 1:4}", + end="", + ) + current_runtime_state = env.scene.get_state(is_relative=True) + states_matched, comparison_log = compare_states(state_from_dataset, current_runtime_state, 0) + if states_matched: + print("\t- matched.") + else: + print("\t- mismatched.") + print(comparison_log) + break + + return replayed_episode_count, recorded_episode_count, failed_demo_ids + + +def main(): + """Replay episodes loaded from a file.""" + global is_paused + + # Load dataset + if not os.path.exists(args_cli.dataset_file): + raise FileNotFoundError(f"The dataset file {args_cli.dataset_file} does not exist.") + dataset_file_handler = HDF5DatasetFileHandler() + dataset_file_handler.open(args_cli.dataset_file) + env_name = dataset_file_handler.get_env_name() + episode_count = dataset_file_handler.get_num_episodes() + + if episode_count == 0: + print("No episodes found in the dataset.") + exit() + + episode_indices_to_replay = list(args_cli.select_episodes) + if len(episode_indices_to_replay) == 0: + episode_indices_to_replay = list(range(episode_count)) + + if args_cli.task is not None: + env_name = args_cli.task.split(":")[-1] + if env_name is None: + raise ValueError("Task/env name was not specified nor found in the dataset.") + + num_envs = args_cli.num_envs + if args_cli.reset_sim_buffer_each_episode and num_envs != 1: + raise ValueError( + "--reset_sim_buffer_each_episode is only supported with a single environment (--num_envs 1). " + f"Got num_envs={num_envs}. Use --num_envs 1 or disable --reset_sim_buffer_each_episode." + ) + + env_cfg = parse_env_cfg(env_name, device=args_cli.device, num_envs=num_envs) + + # extract success checking function to invoke in the main loop + success_term = None + if args_cli.validate_success_rate: + if hasattr(env_cfg.terminations, "success"): + success_term = env_cfg.terminations.success + env_cfg.terminations.success = None + else: + print( + "No success termination term was found in the environment." + " Will not be able to mark recorded demos as successful." + ) + + # Disable all recorders and terminations + env_cfg.recorders = {} + env_cfg.terminations = {} + + # create environment from loaded config + env = gym.make(args_cli.task, cfg=env_cfg).unwrapped + + teleop_interface = Se3Keyboard(Se3KeyboardCfg(pos_sensitivity=0.1, rot_sensitivity=0.1)) + teleop_interface.add_callback("N", play_cb) + teleop_interface.add_callback("B", pause_cb) + print('Press "B" to pause and "N" to resume the replayed actions.') + + # Determine if state validation should be conducted + state_validation_enabled = False + if args_cli.validate_states and num_envs == 1: + state_validation_enabled = True + elif args_cli.validate_states and num_envs > 1: + print("Warning: State validation is only supported with a single environment. Skipping state validation.") + + # Get idle action (idle actions are applied to envs without next action) + if hasattr(env_cfg, "idle_action"): + idle_action = torch.tensor(env_cfg.idle_action, device=env.unwrapped.device).repeat(num_envs, 1) + else: + idle_action = torch.zeros(env.action_space.shape) + + # reset before starting + env.reset() + teleop_interface.reset() + + episode_names = list(dataset_file_handler.get_episode_names()) + replayed_episode_count, recorded_episode_count, failed_demo_ids = replay_episodes_loop( + env, + dataset_file_handler, + episode_names, + episode_count, + episode_indices_to_replay, + num_envs, + success_term, + state_validation_enabled, + idle_action, + args_cli.reset_sim_buffer_each_episode, + ) + + # Close environment after replay in complete + plural_trailing_s = "s" if replayed_episode_count > 1 else "" + print(f"Finished replaying {replayed_episode_count} episode{plural_trailing_s}.") + + # Print success statistics only if validation was enabled + if success_term is not None: + print(f"Successfully replayed: {recorded_episode_count}/{replayed_episode_count}") + + # Print failed demo IDs if any + if failed_demo_ids: + print(f"\nFailed demo IDs ({len(failed_demo_ids)} total):") + print(f" {sorted(failed_demo_ids)}") + + env.close() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tools/test/test_cosmos_prompt_gen.py b/simulation/modules/IsaacLab/scripts/tools/test/test_cosmos_prompt_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..17f1764d914b4f85195cced469ddf1d3b004d196 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/test/test_cosmos_prompt_gen.py @@ -0,0 +1,169 @@ +# Copyright (c) 2024-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Test cases for Cosmos prompt generation script.""" + +import json +import os +import tempfile + +import pytest + +from scripts.tools.cosmos.cosmos_prompt_gen import generate_prompt, main + + +@pytest.fixture(scope="class") +def temp_templates_file(): + """Create temporary templates file.""" + temp_file = tempfile.NamedTemporaryFile(suffix=".json", delete=False) # noqa: SIM115 + + # Create test templates + test_templates = { + "lighting": ["with bright lighting", "with dim lighting", "with natural lighting"], + "color": ["in warm colors", "in cool colors", "in vibrant colors"], + "style": ["in a realistic style", "in an artistic style", "in a minimalist style"], + "empty_section": [], # Test empty section + "invalid_section": "not a list", # Test invalid section + } + + # Write templates to file + with open(temp_file.name, "w") as f: + json.dump(test_templates, f) + + yield temp_file.name + # Cleanup + os.remove(temp_file.name) + + +@pytest.fixture +def temp_output_file(): + """Create temporary output file.""" + temp_file = tempfile.NamedTemporaryFile(suffix=".txt", delete=False) # noqa: SIM115 + yield temp_file.name + # Cleanup + os.remove(temp_file.name) + + +class TestCosmosPromptGen: + """Test cases for Cosmos prompt generation functionality.""" + + def test_generate_prompt_valid_templates(self, temp_templates_file): + """Test generating a prompt with valid templates.""" + prompt = generate_prompt(temp_templates_file) + + # Check that prompt is a string + assert isinstance(prompt, str) + + # Check that prompt contains at least one word + assert len(prompt.split()) > 0 + + # Check that prompt contains valid sections + valid_sections = ["lighting", "color", "style"] + found_sections = [section for section in valid_sections if section in prompt.lower()] + assert len(found_sections) > 0 + + def test_generate_prompt_invalid_file(self): + """Test generating a prompt with invalid file path.""" + with pytest.raises(FileNotFoundError): + generate_prompt("nonexistent_file.json") + + def test_generate_prompt_invalid_json(self): + """Test generating a prompt with invalid JSON file.""" + # Create a temporary file with invalid JSON + with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as temp_file: + temp_file.write(b"invalid json content") + temp_file.flush() + + try: + with pytest.raises(ValueError): + generate_prompt(temp_file.name) + finally: + os.remove(temp_file.name) + + def test_main_function_single_prompt(self, temp_templates_file, temp_output_file): + """Test main function with single prompt generation.""" + # Mock command line arguments + import sys + + original_argv = sys.argv + sys.argv = [ + "cosmos_prompt_gen.py", + "--templates_path", + temp_templates_file, + "--num_prompts", + "1", + "--output_path", + temp_output_file, + ] + + try: + main() + + # Check if output file was created + assert os.path.exists(temp_output_file) + + # Check content of output file + with open(temp_output_file) as f: + content = f.read().strip() + assert len(content) > 0 + assert len(content.split("\n")) == 1 + finally: + # Restore original argv + sys.argv = original_argv + + def test_main_function_multiple_prompts(self, temp_templates_file, temp_output_file): + """Test main function with multiple prompt generation.""" + # Mock command line arguments + import sys + + original_argv = sys.argv + sys.argv = [ + "cosmos_prompt_gen.py", + "--templates_path", + temp_templates_file, + "--num_prompts", + "3", + "--output_path", + temp_output_file, + ] + + try: + main() + + # Check if output file was created + assert os.path.exists(temp_output_file) + + # Check content of output file + with open(temp_output_file) as f: + content = f.read().strip() + assert len(content) > 0 + assert len(content.split("\n")) == 3 + + # Check that each line is a valid prompt + for line in content.split("\n"): + assert len(line) > 0 + finally: + # Restore original argv + sys.argv = original_argv + + def test_main_function_default_output(self, temp_templates_file): + """Test main function with default output path.""" + # Mock command line arguments + import sys + + original_argv = sys.argv + sys.argv = ["cosmos_prompt_gen.py", "--templates_path", temp_templates_file, "--num_prompts", "1"] + + try: + main() + + # Check if default output file was created + assert os.path.exists("prompts.txt") + + # Clean up default output file + os.remove("prompts.txt") + finally: + # Restore original argv + sys.argv = original_argv diff --git a/simulation/modules/IsaacLab/scripts/tools/test/test_hdf5_to_mp4.py b/simulation/modules/IsaacLab/scripts/tools/test/test_hdf5_to_mp4.py new file mode 100644 index 0000000000000000000000000000000000000000..33ccd0d1723eab2e2200a537abd49f974af93dee --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/test/test_hdf5_to_mp4.py @@ -0,0 +1,173 @@ +# Copyright (c) 2024-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Test cases for HDF5 to MP4 conversion script.""" + +import os +import tempfile + +import h5py +import numpy as np +import pytest + +from scripts.tools.hdf5_to_mp4 import get_num_demos, main, write_demo_to_mp4 + + +@pytest.fixture(scope="class") +def temp_hdf5_file(): + """Create temporary HDF5 file with test data.""" + temp_file = tempfile.NamedTemporaryFile(suffix=".h5", delete=False) # noqa: SIM115 + with h5py.File(temp_file.name, "w") as h5f: + # Create test data structure + for demo_id in range(2): # Create 2 demos + demo_group = h5f.create_group(f"data/demo_{demo_id}/obs") + + # Create RGB frames (2 frames per demo) + rgb_data = np.random.randint(0, 255, (2, 704, 1280, 3), dtype=np.uint8) + demo_group.create_dataset("table_cam", data=rgb_data) + + # Create segmentation frames + seg_data = np.random.randint(0, 255, (2, 704, 1280, 4), dtype=np.uint8) + demo_group.create_dataset("table_cam_segmentation", data=seg_data) + + # Create normal maps + normals_data = np.random.rand(2, 704, 1280, 3).astype(np.float32) + demo_group.create_dataset("table_cam_normals", data=normals_data) + + # Create depth maps + depth_data = np.random.rand(2, 704, 1280, 1).astype(np.float32) + demo_group.create_dataset("table_cam_depth", data=depth_data) + + yield temp_file.name + # Cleanup + os.remove(temp_file.name) + + +@pytest.fixture +def temp_output_dir(): + """Create temporary output directory.""" + temp_dir = tempfile.mkdtemp() # noqa: SIM115 + yield temp_dir + # Cleanup + for file in os.listdir(temp_dir): + os.remove(os.path.join(temp_dir, file)) + os.rmdir(temp_dir) + + +class TestHDF5ToMP4: + """Test cases for HDF5 to MP4 conversion functionality.""" + + def test_get_num_demos(self, temp_hdf5_file): + """Test the get_num_demos function.""" + num_demos = get_num_demos(temp_hdf5_file) + assert num_demos == 2 + + def test_write_demo_to_mp4_rgb(self, temp_hdf5_file, temp_output_dir): + """Test writing RGB frames to MP4.""" + write_demo_to_mp4(temp_hdf5_file, 0, "data/demo_0/obs", "table_cam", temp_output_dir, 704, 1280) + + output_file = os.path.join(temp_output_dir, "demo_0_table_cam.mp4") + assert os.path.exists(output_file) + assert os.path.getsize(output_file) > 0 + + def test_write_demo_to_mp4_segmentation(self, temp_hdf5_file, temp_output_dir): + """Test writing segmentation frames to MP4.""" + write_demo_to_mp4(temp_hdf5_file, 0, "data/demo_0/obs", "table_cam_segmentation", temp_output_dir, 704, 1280) + + output_file = os.path.join(temp_output_dir, "demo_0_table_cam_segmentation.mp4") + assert os.path.exists(output_file) + assert os.path.getsize(output_file) > 0 + + def test_write_demo_to_mp4_normals(self, temp_hdf5_file, temp_output_dir): + """Test writing normal maps to MP4.""" + write_demo_to_mp4(temp_hdf5_file, 0, "data/demo_0/obs", "table_cam_normals", temp_output_dir, 704, 1280) + + output_file = os.path.join(temp_output_dir, "demo_0_table_cam_normals.mp4") + assert os.path.exists(output_file) + assert os.path.getsize(output_file) > 0 + + def test_write_demo_to_mp4_shaded_segmentation(self, temp_hdf5_file, temp_output_dir): + """Test writing shaded_segmentation frames to MP4.""" + write_demo_to_mp4( + temp_hdf5_file, + 0, + "data/demo_0/obs", + "table_cam_shaded_segmentation", + temp_output_dir, + 704, + 1280, + ) + + output_file = os.path.join(temp_output_dir, "demo_0_table_cam_shaded_segmentation.mp4") + assert os.path.exists(output_file) + assert os.path.getsize(output_file) > 0 + + def test_write_demo_to_mp4_depth(self, temp_hdf5_file, temp_output_dir): + """Test writing depth maps to MP4.""" + write_demo_to_mp4(temp_hdf5_file, 0, "data/demo_0/obs", "table_cam_depth", temp_output_dir, 704, 1280) + + output_file = os.path.join(temp_output_dir, "demo_0_table_cam_depth.mp4") + assert os.path.exists(output_file) + assert os.path.getsize(output_file) > 0 + + def test_write_demo_to_mp4_invalid_demo(self, temp_hdf5_file, temp_output_dir): + """Test writing with invalid demo ID.""" + with pytest.raises(KeyError): + write_demo_to_mp4( + temp_hdf5_file, + 999, # Invalid demo ID + "data/demo_999/obs", + "table_cam", + temp_output_dir, + 704, + 1280, + ) + + def test_write_demo_to_mp4_invalid_key(self, temp_hdf5_file, temp_output_dir): + """Test writing with invalid input key.""" + with pytest.raises(KeyError): + write_demo_to_mp4(temp_hdf5_file, 0, "data/demo_0/obs", "invalid_key", temp_output_dir, 704, 1280) + + def test_main_function(self, temp_hdf5_file, temp_output_dir): + """Test the main function.""" + # Mock command line arguments + import sys + + original_argv = sys.argv + sys.argv = [ + "hdf5_to_mp4.py", + "--input_file", + temp_hdf5_file, + "--output_dir", + temp_output_dir, + "--input_keys", + "table_cam", + "table_cam_segmentation", + "--video_height", + "704", + "--video_width", + "1280", + "--framerate", + "30", + ] + + try: + main() + + # Check if output files were created + expected_files = [ + "demo_0_table_cam.mp4", + "demo_0_table_cam_segmentation.mp4", + "demo_1_table_cam.mp4", + "demo_1_table_cam_segmentation.mp4", + ] + + for file in expected_files: + output_file = os.path.join(temp_output_dir, file) + assert os.path.exists(output_file) + assert os.path.getsize(output_file) > 0 + finally: + # Restore original argv + sys.argv = original_argv diff --git a/simulation/modules/IsaacLab/scripts/tools/test/test_mp4_to_hdf5.py b/simulation/modules/IsaacLab/scripts/tools/test/test_mp4_to_hdf5.py new file mode 100644 index 0000000000000000000000000000000000000000..631ac41da228573228e2a73f572c29805b0c661b --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/test/test_mp4_to_hdf5.py @@ -0,0 +1,181 @@ +# Copyright (c) 2024-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Test cases for MP4 to HDF5 conversion script.""" + +import os +import tempfile + +import cv2 +import h5py +import numpy as np +import pytest + +from scripts.tools.mp4_to_hdf5 import get_frames_from_mp4, main, process_video_and_demo + + +@pytest.fixture(scope="class") +def temp_hdf5_file(): + """Create temporary HDF5 file with test data.""" + temp_file = tempfile.NamedTemporaryFile(suffix=".h5", delete=False) # noqa: SIM115 + with h5py.File(temp_file.name, "w") as h5f: + # Create test data structure for 2 demos + for demo_id in range(2): + demo_group = h5f.create_group(f"data/demo_{demo_id}") + obs_group = demo_group.create_group("obs") + + # Create actions data + actions_data = np.random.rand(10, 7).astype(np.float32) + demo_group.create_dataset("actions", data=actions_data) + + # Create robot state data + eef_pos_data = np.random.rand(10, 3).astype(np.float32) + eef_quat_data = np.random.rand(10, 4).astype(np.float32) + gripper_pos_data = np.random.rand(10, 1).astype(np.float32) + obs_group.create_dataset("eef_pos", data=eef_pos_data) + obs_group.create_dataset("eef_quat", data=eef_quat_data) + obs_group.create_dataset("gripper_pos", data=gripper_pos_data) + + # Create camera data + table_cam_data = np.random.randint(0, 255, (10, 704, 1280, 3), dtype=np.uint8) + wrist_cam_data = np.random.randint(0, 255, (10, 704, 1280, 3), dtype=np.uint8) + obs_group.create_dataset("table_cam", data=table_cam_data) + obs_group.create_dataset("wrist_cam", data=wrist_cam_data) + + # Set attributes + demo_group.attrs["num_samples"] = 10 + + yield temp_file.name + # Cleanup + os.remove(temp_file.name) + + +@pytest.fixture(scope="class") +def temp_videos_dir(): + """Create temporary MP4 files.""" + temp_dir = tempfile.mkdtemp() # noqa: SIM115 + video_paths = [] + + for demo_id in range(2): + video_path = os.path.join(temp_dir, f"demo_{demo_id}_table_cam.mp4") + video_paths.append(video_path) + + # Create a test video + fourcc = cv2.VideoWriter_fourcc(*"mp4v") + video = cv2.VideoWriter(video_path, fourcc, 30, (1280, 704)) + + # Write some random frames + for _ in range(10): + frame = np.random.randint(0, 255, (704, 1280, 3), dtype=np.uint8) + video.write(frame) + video.release() + + yield temp_dir, video_paths + + # Cleanup + for video_path in video_paths: + os.remove(video_path) + os.rmdir(temp_dir) + + +@pytest.fixture +def temp_output_file(): + """Create temporary output file.""" + temp_file = tempfile.NamedTemporaryFile(suffix=".h5", delete=False) # noqa: SIM115 + yield temp_file.name + # Cleanup + os.remove(temp_file.name) + + +class TestMP4ToHDF5: + """Test cases for MP4 to HDF5 conversion functionality.""" + + def test_get_frames_from_mp4(self, temp_videos_dir): + """Test extracting frames from MP4 video.""" + _, video_paths = temp_videos_dir + frames = get_frames_from_mp4(video_paths[0]) + + # Check frame properties + assert frames.shape[0] == 10 # Number of frames + assert frames.shape[1:] == (704, 1280, 3) # Frame dimensions + assert frames.dtype == np.uint8 # Data type + + def test_get_frames_from_mp4_resize(self, temp_videos_dir): + """Test extracting frames with resizing.""" + _, video_paths = temp_videos_dir + target_height, target_width = 352, 640 + frames = get_frames_from_mp4(video_paths[0], target_height, target_width) + + # Check resized frame properties + assert frames.shape[0] == 10 # Number of frames + assert frames.shape[1:] == (target_height, target_width, 3) # Resized dimensions + assert frames.dtype == np.uint8 # Data type + + def test_process_video_and_demo(self, temp_hdf5_file, temp_videos_dir, temp_output_file): + """Test processing a single video and creating a new demo.""" + _, video_paths = temp_videos_dir + with h5py.File(temp_hdf5_file, "r") as f_in, h5py.File(temp_output_file, "w") as f_out: + process_video_and_demo(f_in, f_out, video_paths[0], 0, 2) + + # Check if new demo was created with correct data + assert "data/demo_2" in f_out + assert "data/demo_2/actions" in f_out + assert "data/demo_2/obs/eef_pos" in f_out + assert "data/demo_2/obs/eef_quat" in f_out + assert "data/demo_2/obs/gripper_pos" in f_out + assert "data/demo_2/obs/table_cam" in f_out + assert "data/demo_2/obs/wrist_cam" in f_out + + # Check data shapes + assert f_out["data/demo_2/actions"].shape == (10, 7) + assert f_out["data/demo_2/obs/eef_pos"].shape == (10, 3) + assert f_out["data/demo_2/obs/eef_quat"].shape == (10, 4) + assert f_out["data/demo_2/obs/gripper_pos"].shape == (10, 1) + assert f_out["data/demo_2/obs/table_cam"].shape == (10, 704, 1280, 3) + assert f_out["data/demo_2/obs/wrist_cam"].shape == (10, 704, 1280, 3) + + # Check attributes + assert f_out["data/demo_2"].attrs["num_samples"] == 10 + + def test_main_function(self, temp_hdf5_file, temp_videos_dir, temp_output_file): + """Test the main function.""" + # Mock command line arguments + import sys + + original_argv = sys.argv + sys.argv = [ + "mp4_to_hdf5.py", + "--input_file", + temp_hdf5_file, + "--videos_dir", + temp_videos_dir[0], + "--output_file", + temp_output_file, + ] + + try: + main() + + # Check if output file was created with correct data + with h5py.File(temp_output_file, "r") as f: + # Check if original demos were copied + assert "data/demo_0" in f + assert "data/demo_1" in f + + # Check if new demos were created + assert "data/demo_2" in f + assert "data/demo_3" in f + + # Check data in new demos + for demo_id in [2, 3]: + assert f"data/demo_{demo_id}/actions" in f + assert f"data/demo_{demo_id}/obs/eef_pos" in f + assert f"data/demo_{demo_id}/obs/eef_quat" in f + assert f"data/demo_{demo_id}/obs/gripper_pos" in f + assert f"data/demo_{demo_id}/obs/table_cam" in f + assert f"data/demo_{demo_id}/obs/wrist_cam" in f + finally: + # Restore original argv + sys.argv = original_argv diff --git a/simulation/modules/IsaacLab/scripts/tools/train_and_publish_checkpoints.py b/simulation/modules/IsaacLab/scripts/tools/train_and_publish_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..13c55fa6fb55a3860c7a5c455d3e452507024e20 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tools/train_and_publish_checkpoints.py @@ -0,0 +1,416 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to manage pretrained checkpoints for Isaac Lab environments. + +This script is used to train and publish pretrained checkpoints for Isaac Lab environments. +It supports multiple workflows: rl_games, rsl_rl, sb3, and skrl. + +* To train an agent using the rl_games workflow on the Isaac-Cartpole-v0 environment: + + .. code-block:: shell + + python scripts/tools/train_and_publish_checkpoints.py --train rl_games:Isaac-Cartpole-v0 + +* To train and publish the checkpoints for all workflows on only the direct Cartpole environments: + + .. code-block:: shell + + python scripts/tools/train_and_publish_checkpoints.py \ + -tp "*:Isaac-Cartpole-*Direct-v0" \ + --/persistent/isaaclab/asset_root/pretrained_checkpoints="/some/path" + +* To review all repose cube jobs, excluding the 'Play' tasks and 'skrl' workflows: + + .. code-block:: shell + + python scripts/tools/train_and_publish_checkpoints.py \ + -r "*:*Repose-Cube*" \ + --exclude "*:*Play*" \ + --exclude skrl:* + +* To publish all results (that have been reviewed and approved). + + .. code-block:: shell + + python scripts/tools/train_and_publish_checkpoints.py \ + --publish --all \ + --/persistent/isaaclab/asset_root/pretrained_checkpoints="/some/path" + +""" + +import argparse + +from isaaclab.app import AppLauncher + +# Initialize the parser +parser = argparse.ArgumentParser( + description=""" +Script for training and publishing pre-trained checkpoints in Isaac Lab. + +Examples: + # Train an agent using the rl_games workflow for the Isaac-Cartpole-v0 environment. + train_and_publish_checkpoints.py --train rl_games:Isaac-Cartpole-v0 + + # Train and publish checkpoints for all workflows, targeting only direct Cartpole environments. + train_and_publish_checkpoints.py -tp "*:Isaac-Cartpole-*Direct-v0" \\ + --/persistent/isaaclab/asset_root/pretrained_checkpoints="/some/path" + + # Review all Repose Cube jobs, excluding Play tasks and skrl jobs. + train_and_publish_checkpoints.py -r "*:*Repose-Cube*" --exclude "*:*Play*" --exclude skrl:* + + # Publish all results that have been reviewed and approved. + train_and_publish_checkpoints.py --publish --all \\ + --/persistent/isaaclab/asset_root/pretrained_checkpoints="/some/path" +""", + formatter_class=argparse.RawTextHelpFormatter, +) + +# Add positional arguments that can accept zero or more values +parser.add_argument( + "jobs", + nargs="*", + help=""" +A job consists of a workflow and a task name, separated by a colon (wildcards are optional). Examples: + + rl_games:Isaac-Humanoid-*v0 # Wildcard for any Humanoid version + rsl_rl:Isaac-Ant-*-v0 # Wildcard for any Ant environment + *:Isaac-Velocity-Flat-Spot-v0 # Wildcard for any workflow, specific task + +Wildcards can be used in either the workflow or task name to match multiple entries. +""", +) +parser.add_argument("-t", "--train", action="store_true", help="Train checkpoints for later publishing.") +parser.add_argument("-p", "--publish_checkpoint", action="store_true", help="Publish pre-trained checkpoints.") +parser.add_argument("-r", "--review", action="store_true", help="Review checkpoints.") +parser.add_argument("-l", "--list", action="store_true", help="List all available environments and workflows.") +parser.add_argument("-f", "--force", action="store_true", help="Force training when results already exist.") +parser.add_argument("-a", "--all", action="store_true", help="Run all valid workflow task pairs.") +parser.add_argument( + "-E", + "--exclude", + action="append", + type=str, + default=[], + help="Excludes jobs matching the argument, with wildcard support.", +) +parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") +parser.add_argument("--force_review", action="store_true", help="Forces review when one already exists.") +parser.add_argument("--force_publish", action="store_true", help="Publish checkpoints without review.") +parser.add_argument("--headless", action="store_true", help="Run training without the UI.") + +args, _ = parser.parse_known_args() + +# Need something to do +if len(args.jobs) == 0 and not args.all: + parser.error("Jobs must be provided, or --all.") + +# Must train, publish, review or list +if not (args.train or args.publish_checkpoint or args.review or args.list): + parser.error("A train, publish, review or list flag must be given.") + +# List excludes train and publish +if args.list and (args.train or args.publish_checkpoint): + parser.error("Can't train or publish when listing.") + +# launch omniverse app +app_launcher = AppLauncher(headless=True) +simulation_app = app_launcher.app + + +import csv + +# Now everything else +import fnmatch +import json +import os +import subprocess +import sys + +import gymnasium as gym +import numpy as np + +import omni.client +from omni.client._omniclient import CopyBehavior + +from isaaclab_rl.utils.pretrained_checkpoint import ( + WORKFLOW_EXPERIMENT_NAME_VARIABLE, + WORKFLOW_PLAYER, + WORKFLOW_TRAINER, + WORKFLOWS, + get_log_root_path, + get_pretrained_checkpoint_path, + get_pretrained_checkpoint_publish_path, + get_pretrained_checkpoint_review, + get_pretrained_checkpoint_review_path, + has_pretrained_checkpoint_job_finished, + has_pretrained_checkpoint_job_run, + has_pretrained_checkpoints_asset_root_dir, +) + +# Need somewhere to publish +if args.publish_checkpoint and not has_pretrained_checkpoints_asset_root_dir(): + raise Exception( + "An asset root directory (persistent.isaac.asset_root.cloud) must be configured in the app kit file to publish." + ) + + +def train_job(workflow, task_name, headless=False, force=False, num_envs=None): + """ + This trains a task using the workflow's train.py script, overriding the experiment name to ensure unique + log directories. By default it will return if an experiment has already been run. + + Args: + workflow: The workflow. + task_name: The task name. + headless: Should the training run without the UI. + force: Run training even if previous experiments have been run. + num_envs: How many simultaneous environments to simulate, overriding the config. + """ + + log_root_path = get_log_root_path(workflow, task_name) + + # We already ran this + if not force and os.path.exists(log_root_path) and len(os.listdir(log_root_path)) > 0: + print(f"Skipping training of {workflow}:{task_name}, already has been run") + return + + print(f"Training {workflow}:{task_name}") + + # Construct our command + cmd = [ + sys.executable, + WORKFLOW_TRAINER[workflow], + "--task", + task_name, + "--enable_cameras", + ] + + # Changes the directory name for logging + if WORKFLOW_EXPERIMENT_NAME_VARIABLE[workflow]: + cmd.append(f"{WORKFLOW_EXPERIMENT_NAME_VARIABLE[workflow]}={task_name}") + + if headless: + cmd.append("--headless") + if num_envs: + cmd.extend(["--num_envs", str(num_envs)]) + + print("Running : " + " ".join(cmd)) + + subprocess.run(cmd) + + +def review_pretrained_checkpoint(workflow, task_name, force_review=False, num_envs=None): + """ + This initiates a review of the pretrained checkpoint. The play.py script for the workflow is run, and the user + inspects the results. When done they close the simulator and will be prompted for their review. + + Args: + workflow: The workflow. + task_name: The task name. + force_review: Performs the review even if a review already exists. + num_envs: How many simultaneous environments to simulate, overriding the config. + """ + + # This workflow task pair hasn't been trained + if not has_pretrained_checkpoint_job_run(workflow, task_name): + print(f"Skipping review of {workflow}:{task_name}, hasn't been trained yet") + return + + # Couldn't find the checkpoint + if not has_pretrained_checkpoint_job_finished(workflow, task_name): + print(f"Training not complete for {workflow}:{task_name}") + return + + review = get_pretrained_checkpoint_review(workflow, task_name) + + if not force_review and review and review["reviewed"]: + print(f"Review already complete for {workflow}:{task_name}") + return + + print(f"Reviewing {workflow}:{task_name}") + + # Construct our command + cmd = [ + sys.executable, + WORKFLOW_PLAYER[workflow], + "--task", + task_name, + "--checkpoint", + get_pretrained_checkpoint_path(workflow, task_name), + "--enable_cameras", + ] + + if num_envs: + cmd.extend(["--num_envs", str(num_envs)]) + + print("Running : " + " ".join(cmd)) + + subprocess.run(cmd) + + # Give user a chance to leave the old review + if force_review and review and review["reviewed"]: + result = review["result"] + notes = review.get("notes") + print(f"A review already exists for {workflow}:{task_name}, it was marked as '{result}'.") + print(f" Notes: {notes}") + answer = input("Would you like to replace it? Please answer yes or no (y/n) [n]: ").strip().lower() + if answer != "y": + return + + # Get the verdict from the user + print(f"Do you accept this checkpoint for {workflow}:{task_name}?") + + answer = input("Please answer yes, no or undetermined (y/n/u) [u]: ").strip().lower() + if answer not in {"y", "n", "u"}: + answer = "u" + answer_map = { + "y": "accepted", + "n": "rejected", + "u": "undetermined", + } + + # Create the review dict + review = { + "reviewed": True, + "result": answer_map[answer], + } + + # Maybe add some notes + notes = input("Please add notes or hit enter: ").strip().lower() + if notes: + review["notes"] = notes + + # Save the review JSON file + path = get_pretrained_checkpoint_review_path(workflow, task_name) + if not path: + raise Exception("This shouldn't be possible, something went very wrong.") + + with open(path, "w") as f: + json.dump(review, f, indent=4) + + +def publish_pretrained_checkpoint(workflow, task_name, force_publish=False): + """ + This publishes the pretrained checkpoint to Nucleus using the asset path in the + /persistent/isaaclab/asset_root/pretrained_checkpoints Carb variable. + + Args: + workflow: The workflow. + task_name: The task name. + force_publish: Publish without review. + """ + + # This workflow task pair hasn't been trained + if not has_pretrained_checkpoint_job_run(workflow, task_name): + print(f"Skipping publishing of {workflow}:{task_name}, hasn't been trained yet") + return + + # Couldn't find the checkpoint + if not has_pretrained_checkpoint_job_finished(workflow, task_name): + print(f"Training not complete for {workflow}:{task_name}") + return + + # Get local pretrained checkpoint path + local_path = get_pretrained_checkpoint_path(workflow, task_name) + if not local_path: + raise Exception("This shouldn't be possible, something went very wrong.") + + # Not forcing, need to check review results + if not force_publish: + # Grab the review if it exists + review = get_pretrained_checkpoint_review(workflow, task_name) + + if not review or not review["reviewed"]: + print(f"Skipping publishing of {workflow}:{task_name}, hasn't been reviewed yet") + return + + result = review["result"] + if result != "accepted": + print(f'Skipping publishing of {workflow}:{task_name}, review result was "{result}"') + return + + print(f"Publishing {workflow}:{task_name}") + + # Copy the file + publish_path = get_pretrained_checkpoint_publish_path(workflow, task_name) + omni.client.copy_file(local_path, publish_path, CopyBehavior.OVERWRITE) + + +def get_job_summary_row(workflow, task_name): + """Returns a single row summary of the job""" + + has_run = has_pretrained_checkpoint_job_run(workflow, task_name) + has_finished = has_pretrained_checkpoint_job_finished(workflow, task_name) + review = get_pretrained_checkpoint_review(workflow, task_name) + + if review: + result = review.get("result", "undetermined") + notes = review.get("notes", "") + else: + result = "" + notes = "" + + return [workflow, task_name, has_run, has_finished, result, notes] + + +def main(): + # Figure out what workflows and tasks we'll be using + if args.all: + jobs = ["*:*"] + else: + jobs = args.jobs + + if args.list: + print() + print("# Workflow, Task, Ran, Finished, Review, Notes") + + summary_rows = [] + + # Could be implemented more efficiently, but the performance gain would be inconsequential + for workflow in WORKFLOWS: + for task_spec in sorted(gym.registry.values(), key=lambda t: t.id): + job_id = f"{workflow}:{task_spec.id}" + + # We've excluded this job + if any(fnmatch.fnmatch(job_id, e) for e in args.exclude): + continue + + # None of our jobs match this pair + if not np.any(np.array([fnmatch.fnmatch(job_id, job) for job in jobs])): + continue + + # No config for this workflow + if workflow + "_cfg_entry_point" not in task_spec.kwargs: + continue + + if args.list: + summary_rows.append(get_job_summary_row(workflow, task_spec.id)) + continue + + # Training reviewing and publishing + if args.train: + train_job(workflow, task_spec.id, args.headless, args.force, args.num_envs) + + if args.review: + review_pretrained_checkpoint(workflow, task_spec.id, args.force_review, args.num_envs) + + if args.publish_checkpoint: + publish_pretrained_checkpoint(workflow, task_spec.id, args.force_publish) + + if args.list: + writer = csv.writer(sys.stdout, quotechar='"', quoting=csv.QUOTE_MINIMAL) + writer.writerows(summary_rows) + + +if __name__ == "__main__": + try: + # Run the main function + main() + except Exception as e: + raise e + finally: + # Close the app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/00_sim/create_empty.py b/simulation/modules/IsaacLab/scripts/tutorials/00_sim/create_empty.py new file mode 100644 index 0000000000000000000000000000000000000000..6fa283a68f1f026a4959c28cee6e6ba6cad33767 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/00_sim/create_empty.py @@ -0,0 +1,61 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""This script demonstrates how to create a simple stage in Isaac Sim. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/00_sim/create_empty.py + +""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# create argparser +parser = argparse.ArgumentParser(description="Tutorial on creating an empty stage.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +from isaaclab.sim import SimulationCfg, SimulationContext + + +def main(): + """Main function.""" + + # Initialize the simulation context + sim_cfg = SimulationCfg(dt=0.01) + sim = SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.5, 2.5, 2.5], [0.0, 0.0, 0.0]) + + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + + # Simulate physics + while simulation_app.is_running(): + # perform step + sim.step() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/00_sim/launch_app.py b/simulation/modules/IsaacLab/scripts/tutorials/00_sim/launch_app.py new file mode 100644 index 0000000000000000000000000000000000000000..ca60aa39a7fa573c783f84b77b82f748cb2f6a65 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/00_sim/launch_app.py @@ -0,0 +1,96 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates how to run IsaacSim via the AppLauncher + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/00_sim/launch_app.py + +""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# create argparser +parser = argparse.ArgumentParser(description="Tutorial on running IsaacSim via the AppLauncher.") +parser.add_argument("--size", type=float, default=1.0, help="Side-length of cuboid") +# SimulationApp arguments https://docs.omniverse.nvidia.com/py/isaacsim/source/isaacsim.simulation_app/docs/index.html?highlight=simulationapp#isaacsim.simulation_app.SimulationApp +parser.add_argument( + "--width", type=int, default=1280, help="Width of the viewport and generated images. Defaults to 1280" +) +parser.add_argument( + "--height", type=int, default=720, help="Height of the viewport and generated images. Defaults to 720" +) + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import isaaclab.sim as sim_utils + + +def design_scene(): + """Designs the scene by spawning ground plane, light, objects and meshes from usd files.""" + # Ground-plane + cfg_ground = sim_utils.GroundPlaneCfg() + cfg_ground.func("/World/defaultGroundPlane", cfg_ground) + + # spawn distant light + cfg_light_distant = sim_utils.DistantLightCfg( + intensity=3000.0, + color=(0.75, 0.75, 0.75), + ) + cfg_light_distant.func("/World/lightDistant", cfg_light_distant, translation=(1, 0, 10)) + + # spawn a cuboid + cfg_cuboid = sim_utils.CuboidCfg( + size=[args_cli.size] * 3, + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 1.0, 1.0)), + ) + # Spawn cuboid, altering translation on the z-axis to scale to its size + cfg_cuboid.func("/World/Object", cfg_cuboid, translation=(0.0, 0.0, args_cli.size / 2)) + + +def main(): + """Main function.""" + + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(device=args_cli.device, dt=0.01) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.0, 0.0, 2.5], [-0.5, 0.0, 0.5]) + + # Design scene by adding assets to it + design_scene() + + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + + # Simulate physics + while simulation_app.is_running(): + # perform step + sim.step() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/00_sim/log_time.py b/simulation/modules/IsaacLab/scripts/tutorials/00_sim/log_time.py new file mode 100644 index 0000000000000000000000000000000000000000..2e4445c3d47005ece02946d03e0a7b709d2ab191 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/00_sim/log_time.py @@ -0,0 +1,84 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates how to generate log outputs while the simulation plays. +It accompanies the tutorial on docker usage. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/00_sim/log_time.py + +""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse +import os + +from isaaclab.app import AppLauncher + +# create argparser +parser = argparse.ArgumentParser(description="Tutorial on creating logs from within the docker container.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +from isaaclab.sim import SimulationCfg, SimulationContext + + +def main(): + """Main function.""" + # Specify that the logs must be in logs/docker_tutorial + log_dir_path = os.path.join("logs") + if not os.path.isdir(log_dir_path): + os.mkdir(log_dir_path) + # In the container, the absolute path will be + # /workspace/isaaclab/logs/docker_tutorial, because + # all python execution is done through /workspace/isaaclab/isaaclab.sh + # and the calling process' path will be /workspace/isaaclab + log_dir_path = os.path.abspath(os.path.join(log_dir_path, "docker_tutorial")) + if not os.path.isdir(log_dir_path): + os.mkdir(log_dir_path) + print(f"[INFO] Logging experiment to directory: {log_dir_path}") + + # Initialize the simulation context + sim_cfg = SimulationCfg(dt=0.01) + sim = SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.5, 2.5, 2.5], [0.0, 0.0, 0.0]) + + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + + # Prepare to count sim_time + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + + # Open logging file + with open(os.path.join(log_dir_path, "log.txt"), "w") as log_file: + # Simulate physics + while simulation_app.is_running(): + log_file.write(f"{sim_time}" + "\n") + # perform step + sim.step() + sim_time += sim_dt + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/00_sim/set_rendering_mode.py b/simulation/modules/IsaacLab/scripts/tutorials/00_sim/set_rendering_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..d0feb87dee3e1821a2df203f52b994a2e8a2f268 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/00_sim/set_rendering_mode.py @@ -0,0 +1,93 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""This script demonstrates how to spawn prims into the scene. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/00_sim/set_rendering_mode.py + +""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# create argparser +parser = argparse.ArgumentParser( + description="Tutorial on viewing a warehouse scene with a given rendering mode preset." +) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# tutorials should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import isaaclab.sim as sim_utils +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR + + +def add_remote_usd_reference(prim_path: str, usd_path: str) -> None: + """Add a remote USD reference without localizing it through the temp asset cache.""" + stage = sim_utils.get_current_stage() + prim = stage.DefinePrim(prim_path, "Xform") + if not prim.GetReferences().AddReference(usd_path): + raise RuntimeError(f"Unable to add USD reference to '{prim_path}' from '{usd_path}'.") + + +def main(): + """Main function.""" + + # rendering modes include performance, balanced, and quality + # note, the rendering_mode specified in the CLI argument (--rendering_mode) takes precedence over + # this Render Config setting + rendering_mode = "balanced" + + # carb setting dictionary can include any rtx carb setting which will overwrite the native preset setting + carb_settings = {"rtx.reflections.enabled": True} + + # Initialize render config + render_cfg = sim_utils.RenderCfg( + rendering_mode=rendering_mode, + carb_settings=carb_settings, + ) + + # Initialize the simulation context with render coofig + sim_cfg = sim_utils.SimulationCfg(render=render_cfg) + sim = sim_utils.SimulationContext(sim_cfg) + + # Pose camera in the hospital lobby area + sim.set_camera_view([-11, -0.5, 2], [0, 0, 0.5]) + + # Load hospital scene + hospital_usd_path = f"{ISAAC_NUCLEUS_DIR}/Environments/Hospital/hospital.usd" + add_remote_usd_reference("/Scene", hospital_usd_path) + + # Play the simulator + sim.reset() + + # Now we are ready! + print("[INFO]: Setup complete...") + + # Run simulation and view scene + while simulation_app.is_running(): + sim.step() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/00_sim/spawn_prims.py b/simulation/modules/IsaacLab/scripts/tutorials/00_sim/spawn_prims.py new file mode 100644 index 0000000000000000000000000000000000000000..8d366c650e6be49c5e73f1d09c91d65ea143494b --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/00_sim/spawn_prims.py @@ -0,0 +1,117 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""This script demonstrates how to spawn prims into the scene. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/00_sim/spawn_prims.py + +""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# create argparser +parser = argparse.ArgumentParser(description="Tutorial on spawning prims into the scene.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +from isaaclab_physx.sim.schemas import PhysxDeformableBodyPropertiesCfg +from isaaclab_physx.sim.spawners.materials import PhysxDeformableBodyMaterialCfg + +import isaaclab.sim as sim_utils +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR + + +def design_scene(): + """Designs the scene by spawning ground plane, light, objects and meshes from usd files.""" + # Ground-plane + cfg_ground = sim_utils.GroundPlaneCfg() + cfg_ground.func("/World/defaultGroundPlane", cfg_ground) + + # spawn distant light + cfg_light_distant = sim_utils.DistantLightCfg( + intensity=3000.0, + color=(0.75, 0.75, 0.75), + ) + cfg_light_distant.func("/World/lightDistant", cfg_light_distant, translation=(1, 0, 10)) + + # create a new xform prim for all objects to be spawned under + sim_utils.create_prim("/World/Objects", "Xform") + # spawn a red cone + cfg_cone = sim_utils.ConeCfg( + radius=0.15, + height=0.5, + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)), + ) + cfg_cone.func("/World/Objects/Cone1", cfg_cone, translation=(-1.0, 1.0, 1.0)) + cfg_cone.func("/World/Objects/Cone2", cfg_cone, translation=(-1.0, -1.0, 1.0)) + + # spawn a green cone with colliders and rigid body + cfg_cone_rigid = sim_utils.ConeCfg( + radius=0.15, + height=0.5, + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)), + ) + cfg_cone_rigid.func( + "/World/Objects/ConeRigid", cfg_cone_rigid, translation=(-0.2, 0.0, 2.0), orientation=(0.5, 0.0, 0.5, 0.0) + ) + + # spawn a blue cuboid with deformable body + cfg_cuboid_deformable = sim_utils.MeshCuboidCfg( + size=(0.2, 0.5, 0.2), + deformable_props=PhysxDeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 1.0)), + physics_material=PhysxDeformableBodyMaterialCfg(), + ) + cfg_cuboid_deformable.func("/World/Objects/CuboidDeformable", cfg_cuboid_deformable, translation=(0.15, 0.0, 2.0)) + + # spawn a usd file of a table into the scene + cfg = sim_utils.UsdFileCfg(usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Mounts/SeattleLabTable/table_instanceable.usd") + cfg.func("/World/Objects/Table", cfg, translation=(0.0, 0.0, 1.05)) + + +def main(): + """Main function.""" + + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.0, 0.0, 2.5], [-0.5, 0.0, 0.5]) + # Design scene + design_scene() + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + + # Simulate physics + while simulation_app.is_running(): + # perform step + sim.step() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/01_assets/add_new_robot.py b/simulation/modules/IsaacLab/scripts/tutorials/01_assets/add_new_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..00af569307ff4683bef780c3838ea8d00540d2cc --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/01_assets/add_new_robot.py @@ -0,0 +1,188 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser( + description="This script demonstrates adding a custom robot to an Isaac Lab environment." +) +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to spawn.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +import numpy as np +import torch + +import isaaclab.sim as sim_utils +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets import AssetBaseCfg +from isaaclab.assets.articulation import ArticulationCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR + +JETBOT_CONFIG = ArticulationCfg( + spawn=sim_utils.UsdFileCfg(usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/NVIDIA/Jetbot/jetbot.usd"), + actuators={"wheel_acts": ImplicitActuatorCfg(joint_names_expr=[".*"], damping=None, stiffness=None)}, +) + +DOFBOT_CONFIG = ArticulationCfg( + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/Yahboom/Dofbot/dofbot.usd", + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=False, + max_depenetration_velocity=5.0, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=True, solver_position_iteration_count=8, solver_velocity_iteration_count=0 + ), + ), + init_state=ArticulationCfg.InitialStateCfg( + joint_pos={ + "joint1": 0.0, + "joint2": 0.0, + "joint3": 0.0, + "joint4": 0.0, + }, + pos=(0.25, -0.25, 0.0), + ), + actuators={ + "front_joints": ImplicitActuatorCfg( + joint_names_expr=["joint[1-2]"], + effort_limit_sim=100.0, + velocity_limit_sim=100.0, + stiffness=10000.0, + damping=100.0, + ), + "joint3_act": ImplicitActuatorCfg( + joint_names_expr=["joint3"], + effort_limit_sim=100.0, + velocity_limit_sim=100.0, + stiffness=10000.0, + damping=100.0, + ), + "joint4_act": ImplicitActuatorCfg( + joint_names_expr=["joint4"], + effort_limit_sim=100.0, + velocity_limit_sim=100.0, + stiffness=10000.0, + damping=100.0, + ), + }, +) + + +class NewRobotsSceneCfg(InteractiveSceneCfg): + """Designs the scene.""" + + # Ground-plane + ground = AssetBaseCfg(prim_path="/World/defaultGroundPlane", spawn=sim_utils.GroundPlaneCfg()) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # robot + Jetbot = JETBOT_CONFIG.replace(prim_path="{ENV_REGEX_NS}/Jetbot") + Dofbot = DOFBOT_CONFIG.replace(prim_path="{ENV_REGEX_NS}/Dofbot") + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + # wheel-velocity templates allocated once on the simulation device; the joint + # target setters dispatch to GPU Warp kernels and reject CPU tensors. + straight_action = torch.tensor([[10.0, 10.0]], device=sim.device) + turn_action = torch.tensor([[5.0, -5.0]], device=sim.device) + + while simulation_app.is_running(): + # reset + if count % 500 == 0: + # reset counters + count = 0 + # reset the scene entities to their initial positions offset by the environment origins + root_jetbot_pose = scene["Jetbot"].data.default_root_pose.torch.clone() + root_jetbot_pose[:, :3] += scene.env_origins + root_dofbot_pose = scene["Dofbot"].data.default_root_pose.torch.clone() + root_dofbot_pose[:, :3] += scene.env_origins + + # copy the default root state to the sim for the jetbot's orientation and velocity + scene["Jetbot"].write_root_pose_to_sim_index(root_pose=root_jetbot_pose) + root_jetbot_vel = scene["Jetbot"].data.default_root_vel.torch.clone() + scene["Jetbot"].write_root_velocity_to_sim_index(root_velocity=root_jetbot_vel) + scene["Dofbot"].write_root_pose_to_sim_index(root_pose=root_dofbot_pose) + root_dofbot_vel = scene["Dofbot"].data.default_root_vel.torch.clone() + scene["Dofbot"].write_root_velocity_to_sim_index(root_velocity=root_dofbot_vel) + + # copy the default joint states to the sim + joint_pos, joint_vel = ( + scene["Jetbot"].data.default_joint_pos.torch.clone(), + scene["Jetbot"].data.default_joint_vel.torch.clone(), + ) + scene["Jetbot"].write_joint_position_to_sim_index(position=joint_pos) + scene["Jetbot"].write_joint_velocity_to_sim_index(velocity=joint_vel) + joint_pos, joint_vel = ( + scene["Dofbot"].data.default_joint_pos.torch.clone(), + scene["Dofbot"].data.default_joint_vel.torch.clone(), + ) + scene["Dofbot"].write_joint_position_to_sim_index(position=joint_pos) + scene["Dofbot"].write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + scene.reset() + print("[INFO]: Resetting Jetbot and Dofbot state...") + + # drive around + if count % 100 < 75: + # Drive straight by setting equal wheel velocities + action = straight_action + else: + # Turn by applying different velocities + action = turn_action + + scene["Jetbot"].set_joint_velocity_target_index(target=action) + + # wave + wave_action = scene["Dofbot"].data.default_joint_pos.torch + wave_action[:, 0:4] = 0.25 * np.sin(2 * np.pi * 0.5 * sim_time) + scene["Dofbot"].set_joint_position_target_index(target=wave_action) + + scene.write_data_to_sim() + sim.step() + sim_time += sim_dt + count += 1 + scene.update(sim_dt) + + +def main(): + """Main function.""" + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + sim.set_camera_view([3.5, 0.0, 3.2], [0.0, 0.0, 0.5]) + # Design scene + scene_cfg = NewRobotsSceneCfg(args_cli.num_envs, env_spacing=2.0) + scene = InteractiveScene(scene_cfg) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + main() + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/01_assets/run_articulation.py b/simulation/modules/IsaacLab/scripts/tutorials/01_assets/run_articulation.py new file mode 100644 index 0000000000000000000000000000000000000000..944edf943d4e16beca03f2a70e85c4bd2079d476 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/01_assets/run_articulation.py @@ -0,0 +1,146 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""This script demonstrates how to spawn a cart-pole and interact with it. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/01_assets/run_articulation.py + +""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Tutorial on spawning and interacting with an articulation.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import Articulation +from isaaclab.sim import SimulationContext + +## +# Pre-defined configs +## +from isaaclab_assets import CARTPOLE_CFG # isort:skip + + +def design_scene() -> tuple[dict, list[list[float]]]: + """Designs the scene.""" + # Ground-plane + cfg = sim_utils.GroundPlaneCfg() + cfg.func("/World/defaultGroundPlane", cfg) + # Lights + cfg = sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + cfg.func("/World/Light", cfg) + + # Create separate groups called "Origin1", "Origin2" + # Each group will have a robot in it + origins = [[0.0, 0.0, 0.0], [-1.0, 0.0, 0.0]] + # Origin 1 + sim_utils.create_prim("/World/Origin1", "Xform", translation=origins[0]) + # Origin 2 + sim_utils.create_prim("/World/Origin2", "Xform", translation=origins[1]) + + # Articulation + cartpole_cfg = CARTPOLE_CFG.copy() + cartpole_cfg.prim_path = "/World/Origin.*/Robot" + cartpole = Articulation(cfg=cartpole_cfg) + + # return the scene information + scene_entities = {"cartpole": cartpole} + return scene_entities, origins + + +def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articulation], origins: torch.Tensor): + """Runs the simulation loop.""" + # Extract scene entities + # note: we only do this here for readability. In general, it is better to access the entities directly from + # the dictionary. This dictionary is replaced by the InteractiveScene class in the next tutorial. + robot = entities["cartpole"] + # Define simulation stepping + sim_dt = sim.get_physics_dt() + count = 0 + # Simulation loop + while simulation_app.is_running(): + # Reset + if count % 500 == 0: + # reset counter + count = 0 + # reset the scene entities + # root state + # we offset the root state by the origin since the states are written in simulation world frame + # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world + root_pose = robot.data.default_root_pose.torch.clone() + root_pose[:, :3] += origins + robot.write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = robot.data.default_root_vel.torch.clone() + robot.write_root_velocity_to_sim_index(root_velocity=root_vel) + # set joint positions with some noise + joint_pos, joint_vel = ( + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), + ) + joint_pos += torch.rand_like(joint_pos) * 0.1 + robot.write_joint_position_to_sim_index(position=joint_pos) + robot.write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + robot.reset() + print("[INFO]: Resetting robot state...") + # Apply random action + # -- generate random joint efforts + efforts = torch.randn_like(robot.data.joint_pos.torch) * 5.0 + # -- apply action to the robot + robot.set_joint_effort_target_index(target=efforts) + # -- write data to sim + robot.write_data_to_sim() + # Perform step + sim.step() + # Increment counter + count += 1 + # Update buffers + robot.update(sim_dt) + + +def main(): + """Main function.""" + # Load kit helper + sim_cfg = sim_utils.SimulationCfg(device=args_cli.device) + sim = SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.5, 0.0, 4.0], [0.0, 0.0, 2.0]) + # Design scene + scene_entities, scene_origins = design_scene() + scene_origins = torch.tensor(scene_origins, device=sim.device) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene_entities, scene_origins) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/01_assets/run_deformable_object.py b/simulation/modules/IsaacLab/scripts/tutorials/01_assets/run_deformable_object.py new file mode 100644 index 0000000000000000000000000000000000000000..9d42a5301ba3b792fdeff8ab2a7884a2d4d92e69 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/01_assets/run_deformable_object.py @@ -0,0 +1,209 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates how to work with the deformable object and interact with it. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/01_assets/run_deformable_object.py + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +import os + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Tutorial on interacting with a deformable object.") +parser.add_argument("--backend", type=str, default="physx", choices=["physx", "newton"], help="Physics backend.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +import isaaclab.utils.math as math_utils +from isaaclab.assets import DeformableObject, DeformableObjectCfg + + +def design_scene(): + """Designs the scene.""" + # Ground-plane + cfg = sim_utils.GroundPlaneCfg() + cfg.func("/World/defaultGroundPlane", cfg) + # Lights + cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.8, 0.8, 0.8)) + cfg.func("/World/Light", cfg) + + # Create a dictionary for the scene entities + scene_entities = {} + + # Create separate groups called "env_0", "env_1", ... + # Newton's scene loader requires the "env_\d+" naming convention to + # detect per-environment Xforms and replicate them as separate worlds. + origins = [[0.25, 0.25, 0.0], [-0.25, 0.25, 0.0], [0.25, -0.25, 0.0], [-0.25, -0.25, 0.0]] + for i, origin in enumerate(origins): + sim_utils.create_prim(f"/World/env_{i}", "Xform", translation=origin) + + youngs_modulus = 1e5 + poissons_ratio = 0.4 + density = 500.0 + if args_cli.backend == "newton": + from isaaclab_newton.sim.schemas import NewtonDeformableBodyPropertiesCfg + from isaaclab_newton.sim.spawners.materials import NewtonDeformableBodyMaterialCfg + + deformable_props = NewtonDeformableBodyPropertiesCfg() + physics_material = NewtonDeformableBodyMaterialCfg( + k_mu=youngs_modulus / (2.0 * (1.0 + poissons_ratio)), + k_lambda=youngs_modulus * poissons_ratio / ((1.0 + poissons_ratio) * (1.0 - 2.0 * poissons_ratio)), + density=density, + ) + else: + from isaaclab_physx.sim.schemas import PhysxDeformableBodyPropertiesCfg + from isaaclab_physx.sim.spawners.materials import PhysxDeformableBodyMaterialCfg + + deformable_props = PhysxDeformableBodyPropertiesCfg(rest_offset=0.0, contact_offset=0.001) + physics_material = PhysxDeformableBodyMaterialCfg( + poissons_ratio=poissons_ratio, youngs_modulus=youngs_modulus, density=density + ) + + # 3D Deformable Object + cfg = DeformableObjectCfg( + prim_path="/World/env_.*/Cube", + spawn=sim_utils.MeshCuboidCfg( + size=(0.2, 0.2, 0.2), + deformable_props=deformable_props, + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.5, 0.1, 0.0)), + physics_material=physics_material, + ), + init_state=DeformableObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 1.0)), + debug_vis=True, + ) + + cube_object = DeformableObject(cfg=cfg) + scene_entities["cube_object"] = cube_object + + # return the scene information + return scene_entities, origins + + +def run_simulator(sim: sim_utils.SimulationContext, entities: dict, origins: torch.Tensor, output_dir: str): + """Runs the simulation loop.""" + # Extract scene entities + # note: we only do this here for readability. In general, it is better to access the entities directly from + # the dictionary. This dictionary is replaced by the InteractiveScene class in the next tutorial. + cube_object: DeformableObject = entities["cube_object"] + + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + # Nodal kinematic targets of the deformable bodies + nodal_kinematic_target = cube_object.data.nodal_kinematic_target.torch.clone() + + # Simulate physics + while simulation_app.is_running(): + # reset at start and after 3 seconds + if count % int(3.0 / sim_dt) == 0: + # reset counters + count = 0 + + # reset the nodal state of the object + nodal_state = cube_object.data.default_nodal_state_w.torch.clone() + # apply random pose to the object + pos_w = torch.rand(cube_object.num_instances, 3, device=sim.device) * 0.1 + origins + quat_w = math_utils.random_orientation(cube_object.num_instances, device=sim.device) + nodal_state[..., :3] = cube_object.transform_nodal_pos(nodal_state[..., :3], pos_w, quat_w) + + # write nodal state to simulation + cube_object.write_nodal_state_to_sim_index(nodal_state) + + # Write the nodal state to the kinematic target and free all vertices + nodal_kinematic_target[..., :3] = nodal_state[..., :3] + nodal_kinematic_target[..., 3] = 1.0 + cube_object.write_nodal_kinematic_target_to_sim_index(nodal_kinematic_target) + + # reset buffers + cube_object.reset() + + print("----------------------------------------") + print("[INFO]: Resetting object state...") + + # update the kinematic target for cubes at index 0 and 3 + kinematic_cubes = [0, 3] + # we slightly move the cube in the z-direction by picking the vertex at index 0 + nodal_kinematic_target[kinematic_cubes, 0, 2] += 0.2 * sim_dt + # set vertex at index 0 to be kinematically constrained + # 0: constrained, 1: free + nodal_kinematic_target[kinematic_cubes, 0, 3] = 0.0 + # write kinematic target to simulation + cube_object.write_nodal_kinematic_target_to_sim_index(nodal_kinematic_target) + + # write internal data to simulation + cube_object.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + cube_object.update(sim_dt) + + # print the root positions every second + if count % int(1.0 / sim_dt) == 0: + print(f"Time {sim_time:.2f}s: \tRoot position (in world): {cube_object.data.root_pos_w.torch[:, :3]}") + + +def main(): + """Main function.""" + # Load kit helper + if args_cli.backend == "newton": + from isaaclab_newton.physics import NewtonCfg + + from isaaclab_contrib.deformable.newton_manager_cfg import VBDSolverCfg + + physics_cfg = NewtonCfg(solver_cfg=VBDSolverCfg(iterations=10), num_substeps=4) + else: + from isaaclab_physx.physics import PhysxCfg + + physics_cfg = PhysxCfg() + sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device, physics=physics_cfg) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[2.0, 2.0, 2.0], target=[0.0, 0.0, 0.75]) + # Design scene + scene_entities, scene_origins = design_scene() + scene_origins = torch.tensor(scene_origins, device=sim.device) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + camera_output = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output", "camera") + run_simulator(sim, scene_entities, scene_origins, camera_output) + print("[INFO]: Simulation complete...") + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/01_assets/run_rigid_object.py b/simulation/modules/IsaacLab/scripts/tutorials/01_assets/run_rigid_object.py new file mode 100644 index 0000000000000000000000000000000000000000..232e24f9743f0bd2944bf1e0ca68d28c356ef942 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/01_assets/run_rigid_object.py @@ -0,0 +1,147 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates how to create a rigid object and interact with it. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/01_assets/run_rigid_object.py + +""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Tutorial on spawning and interacting with a rigid object.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +import isaaclab.utils.math as math_utils +from isaaclab.assets import RigidObject, RigidObjectCfg +from isaaclab.sim import SimulationContext + + +def design_scene(): + """Designs the scene.""" + # Ground-plane + cfg = sim_utils.GroundPlaneCfg() + cfg.func("/World/defaultGroundPlane", cfg) + # Lights + cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.8, 0.8, 0.8)) + cfg.func("/World/Light", cfg) + + # Create separate groups called "Origin1", "Origin2", "Origin3" + # Each group will have a robot in it + origins = [[0.25, 0.25, 0.0], [-0.25, 0.25, 0.0], [0.25, -0.25, 0.0], [-0.25, -0.25, 0.0]] + for i, origin in enumerate(origins): + sim_utils.create_prim(f"/World/Origin{i}", "Xform", translation=origin) + + # Rigid Object + cone_cfg = RigidObjectCfg( + prim_path="/World/Origin.*/Cone", + spawn=sim_utils.ConeCfg( + radius=0.1, + height=0.2, + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0), metallic=0.2), + ), + init_state=RigidObjectCfg.InitialStateCfg(), + ) + cone_object = RigidObject(cfg=cone_cfg) + + # return the scene information + scene_entities = {"cone": cone_object} + return scene_entities, origins + + +def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, RigidObject], origins: torch.Tensor): + """Runs the simulation loop.""" + # Extract scene entities + # note: we only do this here for readability. In general, it is better to access the entities directly from + # the dictionary. This dictionary is replaced by the InteractiveScene class in the next tutorial. + cone_object = entities["cone"] + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + # Simulate physics + while simulation_app.is_running(): + # reset + if count % 250 == 0: + # reset counters + sim_time = 0.0 + count = 0 + # reset root state + root_pose = cone_object.data.default_root_pose.torch.clone() + # sample a random position on a cylinder around the origins + root_pose[:, :3] += origins + root_pose[:, :3] += math_utils.sample_cylinder( + radius=0.1, h_range=(0.25, 0.5), size=cone_object.num_instances, device=cone_object.device + ) + # write root state to simulation + cone_object.write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = cone_object.data.default_root_vel.torch.clone() + cone_object.write_root_velocity_to_sim_index(root_velocity=root_vel) + # reset buffers + cone_object.reset() + print("----------------------------------------") + print("[INFO]: Resetting object state...") + # apply sim data + cone_object.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + cone_object.update(sim_dt) + # print the root position + if count % 50 == 0: + print(f"Root position (in world): {cone_object.data.root_pos_w.torch}") + + +def main(): + """Main function.""" + # Load kit helper + sim_cfg = sim_utils.SimulationCfg(device=args_cli.device) + sim = SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[1.5, 0.0, 1.0], target=[0.0, 0.0, 0.0]) + # Design scene + scene_entities, scene_origins = design_scene() + scene_origins = torch.tensor(scene_origins, device=sim.device) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene_entities, scene_origins) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/01_assets/run_surface_gripper.py b/simulation/modules/IsaacLab/scripts/tutorials/01_assets/run_surface_gripper.py new file mode 100644 index 0000000000000000000000000000000000000000..e875e3dfa84898aa50d8609526206c99d691a4d2 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/01_assets/run_surface_gripper.py @@ -0,0 +1,191 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""This script demonstrates how to spawn a pick-and-place robot equipped with a surface gripper and interact with it. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/01_assets/run_surface_gripper.py --device=cpu + +When running this script make sure the --device flag is set to cpu. This is because the surface gripper is +currently only supported on the CPU. +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Tutorial on spawning and interacting with a Surface Gripper.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# tutorials should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch +import warp as wp +from isaaclab_physx.assets import SurfaceGripper, SurfaceGripperCfg + +import isaaclab.sim as sim_utils +from isaaclab.assets import Articulation +from isaaclab.sim import SimulationContext + +## +# Pre-defined configs +## +from isaaclab_assets import PICK_AND_PLACE_CFG # isort:skip + + +def design_scene(): + """Designs the scene.""" + # Ground-plane + cfg = sim_utils.GroundPlaneCfg() + cfg.func("/World/defaultGroundPlane", cfg) + # Lights + cfg = sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + cfg.func("/World/Light", cfg) + + # Create separate groups called "Origin1", "Origin2" + # Each group will have a robot in it + origins = [[2.75, 0.0, 0.0], [-2.75, 0.0, 0.0]] + # Origin 1 + sim_utils.create_prim("/World/Origin1", "Xform", translation=origins[0]) + # Origin 2 + sim_utils.create_prim("/World/Origin2", "Xform", translation=origins[1]) + + # Articulation: First we define the robot config + pick_and_place_robot_cfg = PICK_AND_PLACE_CFG.copy() + pick_and_place_robot_cfg.prim_path = "/World/Origin.*/Robot" + pick_and_place_robot = Articulation(cfg=pick_and_place_robot_cfg) + + # Surface Gripper: Next we define the surface gripper config + surface_gripper_cfg = SurfaceGripperCfg() + # We need to tell the View which prim to use for the surface gripper + surface_gripper_cfg.prim_path = "/World/Origin.*/Robot/picker_head/SurfaceGripper" + # We can then set different parameters for the surface gripper, note that if these parameters are not set, + # the View will try to read them from the prim. + surface_gripper_cfg.max_grip_distance = 0.1 # [m] (Maximum distance at which the gripper can grasp an object) + surface_gripper_cfg.shear_force_limit = 500.0 # [N] (Force limit in the direction perpendicular direction) + surface_gripper_cfg.coaxial_force_limit = 500.0 # [N] (Force limit in the direction of the gripper's axis) + surface_gripper_cfg.retry_interval = 0.1 # seconds (Time the gripper will stay in a grasping state) + # We can now spawn the surface gripper + surface_gripper = SurfaceGripper(cfg=surface_gripper_cfg) + + # return the scene information + scene_entities = {"pick_and_place_robot": pick_and_place_robot, "surface_gripper": surface_gripper} + return scene_entities, origins + + +def run_simulator( + sim: sim_utils.SimulationContext, entities: dict[str, Articulation | SurfaceGripper], origins: torch.Tensor +): + """Runs the simulation loop.""" + # Extract scene entities + robot: Articulation = entities["pick_and_place_robot"] + surface_gripper: SurfaceGripper = entities["surface_gripper"] + + # Define simulation stepping + sim_dt = sim.get_physics_dt() + count = 0 + # Simulation loop + while simulation_app.is_running(): + # Reset + if count % 500 == 0: + # reset counter + count = 0 + # reset the scene entities + # root state + # we offset the root state by the origin since the states are written in simulation world frame + # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world + root_pose = robot.data.default_root_pose.torch.clone() + root_pose[:, :3] += origins + robot.write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = robot.data.default_root_vel.torch.clone() + robot.write_root_velocity_to_sim_index(root_velocity=root_vel) + # set joint positions with some noise + joint_pos, joint_vel = ( + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), + ) + joint_pos += torch.rand_like(joint_pos) * 0.1 + robot.write_joint_position_to_sim_index(position=joint_pos) + robot.write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + robot.reset() + print("[INFO]: Resetting robot state...") + # Opens the gripper and makes sure the gripper is in the open state + surface_gripper.reset() + print("[INFO]: Resetting gripper state...") + + # Sample a random command between -1 and 1. + gripper_commands = torch.rand(surface_gripper.num_instances) * 2.0 - 1.0 + # The gripper behavior is as follows: + # -1 < command < -0.3 --> Gripper is Opening + # -0.3 < command < 0.3 --> Gripper is Idle + # 0.3 < command < 1 --> Gripper is Closing + print(f"[INFO]: Gripper commands: {gripper_commands}") + mapped_commands = [ + "Opening" if command < -0.3 else "Closing" if command > 0.3 else "Idle" for command in gripper_commands + ] + print(f"[INFO]: Mapped commands: {mapped_commands}") + # Set the gripper command + surface_gripper.set_grippers_command(gripper_commands) + # Write data to sim + surface_gripper.write_data_to_sim() + # Perform step + sim.step() + # Increment counter + count += 1 + # Read the gripper state from the simulation + surface_gripper.update(sim_dt) + # Read the gripper state from the buffer + surface_gripper_state = surface_gripper.state + # The gripper state is a list of integers that can be mapped to the following: + # -1 --> Open + # 0 --> Closing + # 1 --> Closed + # Print the gripper state + print(f"[INFO]: Gripper state: {surface_gripper_state}") + mapped_commands = [ + "Open" if state == -1 else "Closing" if state == 0 else "Closed" + for state in wp.to_torch(surface_gripper_state).tolist() + ] + print(f"[INFO]: Mapped commands: {mapped_commands}") + + +def main(): + """Main function.""" + # Load kit helper + sim_cfg = sim_utils.SimulationCfg(device=args_cli.device) + sim = SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.75, 7.5, 10.0], [2.75, 0.0, 0.0]) + # Design scene + scene_entities, scene_origins = design_scene() + scene_origins = torch.tensor(scene_origins, device=sim.device) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene_entities, scene_origins) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/02_scene/create_scene.py b/simulation/modules/IsaacLab/scripts/tutorials/02_scene/create_scene.py new file mode 100644 index 0000000000000000000000000000000000000000..b60234fbb32d01726aeba5f966d02de5ed144238 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/02_scene/create_scene.py @@ -0,0 +1,137 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""This script demonstrates how to use the interactive scene interface to setup a scene with multiple prims. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/02_scene/create_scene.py --num_envs 32 + +""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Tutorial on using the interactive scene interface.") +parser.add_argument("--num_envs", type=int, default=2, help="Number of environments to spawn.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg, AssetBaseCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sim import SimulationContext +from isaaclab.utils.configclass import configclass + +## +# Pre-defined configs +## +from isaaclab_assets import CARTPOLE_CFG # isort:skip + + +@configclass +class CartpoleSceneCfg(InteractiveSceneCfg): + """Configuration for a cart-pole scene.""" + + # ground plane + ground = AssetBaseCfg(prim_path="/World/defaultGroundPlane", spawn=sim_utils.GroundPlaneCfg()) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # articulation + cartpole: ArticulationCfg = CARTPOLE_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Runs the simulation loop.""" + # Extract scene entities + # note: we only do this here for readability. + robot = scene["cartpole"] + # Define simulation stepping + sim_dt = sim.get_physics_dt() + count = 0 + # Simulation loop + while simulation_app.is_running(): + # Reset + if count % 500 == 0: + # reset counter + count = 0 + # reset the scene entities + # root state + # we offset the root state by the origin since the states are written in simulation world frame + # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world + root_pose = robot.data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + robot.write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = robot.data.default_root_vel.torch.clone() + robot.write_root_velocity_to_sim_index(root_velocity=root_vel) + # set joint positions with some noise + joint_pos, joint_vel = ( + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), + ) + joint_pos += torch.rand_like(joint_pos) * 0.1 + robot.write_joint_position_to_sim_index(position=joint_pos) + robot.write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + scene.reset() + print("[INFO]: Resetting robot state...") + # Apply random action + # -- generate random joint efforts + efforts = torch.randn_like(robot.data.joint_pos.torch) * 5.0 + # -- apply action to the robot + robot.set_joint_effort_target_index(target=efforts) + # -- write data to sim + scene.write_data_to_sim() + # Perform step + sim.step() + # Increment counter + count += 1 + # Update buffers + scene.update(sim_dt) + + +def main(): + """Main function.""" + # Load kit helper + sim_cfg = sim_utils.SimulationCfg(device=args_cli.device) + sim = SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.5, 0.0, 4.0], [0.0, 0.0, 2.0]) + # Design scene + scene_cfg = CartpoleSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0) + scene = InteractiveScene(scene_cfg) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/03_envs/create_cartpole_base_env.py b/simulation/modules/IsaacLab/scripts/tutorials/03_envs/create_cartpole_base_env.py new file mode 100644 index 0000000000000000000000000000000000000000..ef0105ae63641e045a53e5d3897b9f4a5e9a6b0f --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/03_envs/create_cartpole_base_env.py @@ -0,0 +1,175 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates how to create a simple environment with a cartpole. It combines the concepts of +scene, action, observation and event managers to create an environment. + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tutorials/03_envs/create_cartpole_base_env.py --num_envs 32 + +""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Tutorial on creating a cartpole base environment.") +parser.add_argument("--num_envs", type=int, default=16, help="Number of environments to spawn.") + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import math + +import torch + +import isaaclab.envs.mdp as mdp +from isaaclab.envs import ManagerBasedEnv, ManagerBasedEnvCfg +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.utils.configclass import configclass + +from isaaclab_tasks.manager_based.classic.cartpole.cartpole_env_cfg import CartpoleSceneCfg + + +@configclass +class ActionsCfg: + """Action specifications for the environment.""" + + joint_efforts = mdp.JointEffortActionCfg(asset_name="robot", joint_names=["slider_to_cart"], scale=5.0) + + +@configclass +class ObservationsCfg: + """Observation specifications for the environment.""" + + @configclass + class PolicyCfg(ObsGroup): + """Observations for policy group.""" + + # observation terms (order preserved) + joint_pos_rel = ObsTerm(func=mdp.joint_pos_rel) + joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel) + + def __post_init__(self) -> None: + self.enable_corruption = False + self.concatenate_terms = True + + # observation groups + policy: PolicyCfg = PolicyCfg() + + +@configclass +class EventCfg: + """Configuration for events.""" + + # on startup + add_pole_mass = EventTerm( + func=mdp.randomize_rigid_body_mass, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=["pole"]), + "mass_distribution_params": (0.1, 0.5), + "operation": "add", + }, + ) + + # on reset + reset_cart_position = EventTerm( + func=mdp.reset_joints_by_offset, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"]), + "position_range": (-1.0, 1.0), + "velocity_range": (-0.1, 0.1), + }, + ) + + reset_pole_position = EventTerm( + func=mdp.reset_joints_by_offset, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"]), + "position_range": (-0.125 * math.pi, 0.125 * math.pi), + "velocity_range": (-0.01 * math.pi, 0.01 * math.pi), + }, + ) + + +@configclass +class CartpoleEnvCfg(ManagerBasedEnvCfg): + """Configuration for the cartpole environment.""" + + # Scene settings + scene = CartpoleSceneCfg(num_envs=1024, env_spacing=2.5) + # Basic settings + observations = ObservationsCfg() + actions = ActionsCfg() + events = EventCfg() + + def __post_init__(self): + """Post initialization.""" + # viewer settings + self.viewer.eye = [4.5, 0.0, 6.0] + self.viewer.lookat = [0.0, 0.0, 2.0] + # step settings + self.decimation = 4 # env step every 4 sim steps: 200Hz / 4 = 50Hz + # simulation settings + self.sim.dt = 0.005 # sim step every 5ms: 200Hz + + +def main(): + """Main function.""" + # parse the arguments + env_cfg = CartpoleEnvCfg() + env_cfg.scene.num_envs = args_cli.num_envs + env_cfg.sim.device = args_cli.device + # setup base environment + env = ManagerBasedEnv(cfg=env_cfg) + + # simulate physics + count = 0 + while simulation_app.is_running(): + with torch.inference_mode(): + # reset + if count % 300 == 0: + count = 0 + env.reset() + print("-" * 80) + print("[INFO]: Resetting environment...") + # sample random actions + joint_efforts = torch.randn_like(env.action_manager.action) + # step the environment + obs, _ = env.step(joint_efforts) + # print current orientation of pole + print("[Env 0]: Pole joint: ", obs["policy"][0][1].item()) + # update counter + count += 1 + + # close the environment + env.close() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/03_envs/create_cube_base_env.py b/simulation/modules/IsaacLab/scripts/tutorials/03_envs/create_cube_base_env.py new file mode 100644 index 0000000000000000000000000000000000000000..a2b4224acd147b9c4cfd2cc4c70b1f92109ec06c --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/03_envs/create_cube_base_env.py @@ -0,0 +1,352 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script creates a simple environment with a floating cube. The cube is controlled by a PD +controller to track an arbitrary target position. + +While going through this tutorial, we recommend you to pay attention to how a custom action term +is defined. The action term is responsible for processing the raw actions and applying them to the +scene entities. + +We also define an event term called 'randomize_scale' that randomizes the scale of +the cube. This event term has the mode 'prestartup', which means that it is applied on the USD stage +before the simulation starts. Additionally, the flag 'replicate_physics' is set to False, +which means that the cube is not replicated across multiple environments but rather each +environment gets its own cube instance. + +The rest of the environment is similar to the previous tutorials. + +.. code-block:: bash + + # Run the script + ./isaaclab.sh -p scripts/tutorials/03_envs/create_cube_base_env.py --num_envs 32 + +""" + +from __future__ import annotations + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Tutorial on creating a floating cube environment.") +parser.add_argument("--num_envs", type=int, default=64, help="Number of environments to spawn.") + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.envs.mdp as mdp +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg, RigidObject, RigidObjectCfg +from isaaclab.envs import ManagerBasedEnv, ManagerBasedEnvCfg +from isaaclab.managers import ActionTerm, ActionTermCfg, SceneEntityCfg +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils.configclass import configclass + +## +# Custom action term +## + + +class CubeActionTerm(ActionTerm): + """Simple action term that implements a PD controller to track a target position. + + The action term is applied to the cube asset. It involves two steps: + + 1. **Process the raw actions**: Typically, this includes any transformations of the raw actions + that are required to map them to the desired space. This is called once per environment step. + 2. **Apply the processed actions**: This step applies the processed actions to the asset. + It is called once per simulation step. + + In this case, the action term simply applies the raw actions to the cube asset. The raw actions + are the desired target positions of the cube in the environment frame. The pre-processing step + simply copies the raw actions to the processed actions as no additional processing is required. + The processed actions are then applied to the cube asset by implementing a PD controller to + track the target position. + """ + + _asset: RigidObject + """The articulation asset on which the action term is applied.""" + + def __init__(self, cfg: CubeActionTermCfg, env: ManagerBasedEnv): + # call super constructor + super().__init__(cfg, env) + # create buffers + self._raw_actions = torch.zeros(env.num_envs, 3, device=self.device) + self._processed_actions = torch.zeros(env.num_envs, 3, device=self.device) + self._vel_command = torch.zeros(self.num_envs, 6, device=self.device) + # gains of controller + self.p_gain = cfg.p_gain + self.d_gain = cfg.d_gain + + """ + Properties. + """ + + @property + def action_dim(self) -> int: + return self._raw_actions.shape[1] + + @property + def raw_actions(self) -> torch.Tensor: + return self._raw_actions + + @property + def processed_actions(self) -> torch.Tensor: + return self._processed_actions + + """ + Operations + """ + + def process_actions(self, actions: torch.Tensor): + # store the raw actions + self._raw_actions[:] = actions + # no-processing of actions + self._processed_actions[:] = self._raw_actions[:] + + def apply_actions(self): + # implement a PD controller to track the target position + pos_error = self._processed_actions - (self._asset.data.root_pos_w.torch - self._env.scene.env_origins) + vel_error = -self._asset.data.root_lin_vel_w.torch + # set velocity targets + self._vel_command[:, :3] = self.p_gain * pos_error + self.d_gain * vel_error + self._asset.write_root_velocity_to_sim_index(root_velocity=self._vel_command) + + +@configclass +class CubeActionTermCfg(ActionTermCfg): + """Configuration for the cube action term.""" + + class_type: type = CubeActionTerm + """The class corresponding to the action term.""" + + p_gain: float = 5.0 + """Proportional gain of the PD controller.""" + d_gain: float = 0.5 + """Derivative gain of the PD controller.""" + + +## +# Custom observation term +## + + +def base_position(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg) -> torch.Tensor: + """Root linear velocity in the asset's root frame.""" + # extract the used quantities (to enable type-hinting) + asset: RigidObject = env.scene[asset_cfg.name] + return asset.data.root_pos_w.torch - env.scene.env_origins + + +## +# Scene definition +## + + +@configclass +class MySceneCfg(InteractiveSceneCfg): + """Example scene configuration. + + The scene comprises of a ground plane, light source and floating cubes (gravity disabled). + """ + + # add terrain + terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane", debug_vis=False) + + # add cube + cube: RigidObjectCfg = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/cube", + spawn=sim_utils.CuboidCfg( + size=(0.2, 0.2, 0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg(max_depenetration_velocity=1.0, disable_gravity=True), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + physics_material=sim_utils.RigidBodyMaterialCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.5, 0.0, 0.0)), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 5)), + ) + + # lights + light = AssetBaseCfg( + prim_path="/World/light", + spawn=sim_utils.DomeLightCfg(color=(0.75, 0.75, 0.75), intensity=2000.0), + ) + + +## +# Environment settings +## + + +@configclass +class ActionsCfg: + """Action specifications for the MDP.""" + + joint_pos = CubeActionTermCfg(asset_name="cube") + + +@configclass +class ObservationsCfg: + """Observation specifications for the MDP.""" + + @configclass + class PolicyCfg(ObsGroup): + """Observations for policy group.""" + + # cube velocity + position = ObsTerm(func=base_position, params={"asset_cfg": SceneEntityCfg("cube")}) + + def __post_init__(self): + self.enable_corruption = True + self.concatenate_terms = True + + # observation groups + policy: PolicyCfg = PolicyCfg() + + +@configclass +class EventCfg: + """Configuration for events.""" + + # This event term resets the base position of the cube. + # The mode is set to 'reset', which means that the base position is reset whenever + # the environment instance is reset (because of terminations defined in 'TerminationCfg'). + reset_base = EventTerm( + func=mdp.reset_root_state_uniform, + mode="reset", + params={ + "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, + "velocity_range": { + "x": (-0.5, 0.5), + "y": (-0.5, 0.5), + "z": (-0.5, 0.5), + }, + "asset_cfg": SceneEntityCfg("cube"), + }, + ) + + # This event term randomizes the scale of the cube. + # The mode is set to 'prestartup', which means that the scale is randomize on the USD stage before the + # simulation starts. + # Note: USD-level randomizations require the flag 'replicate_physics' to be set to False. + randomize_scale = EventTerm( + func=mdp.randomize_rigid_body_scale, + mode="prestartup", + params={ + "scale_range": {"x": (0.5, 1.5), "y": (0.5, 1.5), "z": (0.5, 1.5)}, + "asset_cfg": SceneEntityCfg("cube"), + }, + ) + + # This event term randomizes the visual color of the cube. + # Similar to the scale randomization, this is also a USD-level randomization and requires the flag + # 'replicate_physics' to be set to False. + randomize_color = EventTerm( + func=mdp.randomize_visual_color, + mode="prestartup", + params={ + "colors": {"r": (0.0, 1.0), "g": (0.0, 1.0), "b": (0.0, 1.0)}, + "asset_cfg": SceneEntityCfg("cube"), + "mesh_name": "geometry/mesh", + "event_name": "rep_cube_randomize_color", + }, + ) + + +## +# Environment configuration +## + + +@configclass +class CubeEnvCfg(ManagerBasedEnvCfg): + """Configuration for the locomotion velocity-tracking environment.""" + + # Scene settings + # The flag 'replicate_physics' is set to False, which means that the cube is not replicated + # across multiple environments but rather each environment gets its own cube instance. + # This allows modifying the cube's properties independently for each environment. + scene: MySceneCfg = MySceneCfg(num_envs=args_cli.num_envs, env_spacing=2.5, replicate_physics=False) + + # Basic settings + observations: ObservationsCfg = ObservationsCfg() + actions: ActionsCfg = ActionsCfg() + events: EventCfg = EventCfg() + + def __post_init__(self): + """Post initialization.""" + # general settings + self.decimation = 2 + # simulation settings + self.sim.dt = 0.01 + self.sim.physics_material = self.scene.terrain.physics_material + self.sim.render_interval = 2 # render interval should be a multiple of decimation + self.sim.device = args_cli.device + # viewer settings + self.viewer.eye = (5.0, 5.0, 5.0) + self.viewer.lookat = (0.0, 0.0, 2.0) + + +def main(): + """Main function.""" + + # setup base environment + env_cfg = CubeEnvCfg() + env = ManagerBasedEnv(cfg=env_cfg) + + # setup target position commands + target_position = torch.rand(env.num_envs, 3, device=env.device) * 2 + target_position[:, 2] += 2.0 + # offset all targets so that they move to the world origin + target_position -= env.scene.env_origins + + # simulate physics + count = 0 + obs, _ = env.reset() + while simulation_app.is_running(): + with torch.inference_mode(): + # reset + if count % 300 == 0: + count = 0 + obs, _ = env.reset() + print("-" * 80) + print("[INFO]: Resetting environment...") + # step env + obs, _ = env.step(target_position) + # print mean squared position error between target and current position + error = torch.linalg.norm(obs["policy"] - target_position).mean().item() + print(f"[Step: {count:04d}]: Mean position error: {error:.4f}") + # update counter + count += 1 + + # close the environment + env.close() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/03_envs/create_quadruped_base_env.py b/simulation/modules/IsaacLab/scripts/tutorials/03_envs/create_quadruped_base_env.py new file mode 100644 index 0000000000000000000000000000000000000000..26cce6250a8dd0a4bcd371f3dc183497f6711ca4 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/03_envs/create_quadruped_base_env.py @@ -0,0 +1,245 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates the environment for a quadruped robot with height-scan sensor. + +In this example, we use a locomotion policy to control the robot. The robot is commanded to +move forward at a constant velocity. The height-scan sensor is used to detect the height of +the terrain. + +.. code-block:: bash + + # Run the script + ./isaaclab.sh -p scripts/tutorials/03_envs/create_quadruped_base_env.py --num_envs 32 + +""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Tutorial on creating a quadruped base environment.") +parser.add_argument("--num_envs", type=int, default=64, help="Number of environments to spawn.") + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.envs.mdp as mdp +import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg, AssetBaseCfg +from isaaclab.envs import ManagerBasedEnv, ManagerBasedEnvCfg +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sensors import RayCasterCfg, patterns +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR, check_file_path, read_file +from isaaclab.utils.configclass import configclass +from isaaclab.utils.noise import UniformNoiseCfg as Unoise + +## +# Pre-defined configs +## +from isaaclab.terrains.config.rough import ROUGH_TERRAINS_CFG # isort: skip +from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip + + +## +# Custom observation terms +## + + +def constant_commands(env: ManagerBasedEnv) -> torch.Tensor: + """The generated command from the command generator.""" + return torch.tensor([[1, 0, 0]], device=env.device).repeat(env.num_envs, 1) + + +## +# Scene definition +## + + +@configclass +class MySceneCfg(InteractiveSceneCfg): + """Example scene configuration.""" + + # add 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, + ), + debug_vis=False, + ) + + # add robot + robot: ArticulationCfg = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + # sensors + height_scanner = RayCasterCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)), + ray_alignment="yaw", + pattern_cfg=patterns.GridPatternCfg(resolution=0.1, size=[1.6, 1.0]), + debug_vis=True, + mesh_prim_paths=["/World/ground"], + ) + + # lights + light = AssetBaseCfg( + prim_path="/World/light", + spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0), + ) + + +## +# MDP settings +## + + +@configclass +class ActionsCfg: + """Action specifications for the MDP.""" + + joint_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=constant_commands) + 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 EventCfg: + """Configuration for events.""" + + reset_scene = EventTerm(func=mdp.reset_scene_to_default, mode="reset") + + +## +# Environment configuration +## + + +@configclass +class QuadrupedEnvCfg(ManagerBasedEnvCfg): + """Configuration for the locomotion velocity-tracking environment.""" + + # Scene settings + scene: MySceneCfg = MySceneCfg(num_envs=args_cli.num_envs, env_spacing=2.5) + # Basic settings + observations: ObservationsCfg = ObservationsCfg() + actions: ActionsCfg = ActionsCfg() + events: EventCfg = EventCfg() + + def __post_init__(self): + """Post initialization.""" + # general settings + self.decimation = 4 # env decimation -> 50 Hz control + # simulation settings + self.sim.dt = 0.005 # simulation timestep -> 200 Hz physics + self.sim.physics_material = self.scene.terrain.physics_material + self.sim.device = args_cli.device + # 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 # 50 Hz + + +def main(): + """Main function.""" + # setup base environment + env_cfg = QuadrupedEnvCfg() + env = ManagerBasedEnv(cfg=env_cfg) + + # load level policy + policy_path = ISAACLAB_NUCLEUS_DIR + "/Policies/ANYmal-C/HeightScan/policy.pt" + # check if policy file exists + if not check_file_path(policy_path): + raise FileNotFoundError(f"Policy file '{policy_path}' does not exist.") + file_bytes = read_file(policy_path) + # jit load the policy + policy = torch.jit.load(file_bytes).to(env.device).eval() + + # simulate physics + count = 0 + obs, _ = env.reset() + while simulation_app.is_running(): + with torch.inference_mode(): + # reset + if count % 1000 == 0: + obs, _ = env.reset() + count = 0 + print("-" * 80) + print("[INFO]: Resetting environment...") + # infer action + action = policy(obs["policy"]) + # step env + obs, _ = env.step(action) + # update counter + count += 1 + + # close the environment + env.close() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/03_envs/policy_inference_in_usd.py b/simulation/modules/IsaacLab/scripts/tutorials/03_envs/policy_inference_in_usd.py new file mode 100644 index 0000000000000000000000000000000000000000..7560b6ef988af7158537ffa6d37935f5d6000df6 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/03_envs/policy_inference_in_usd.py @@ -0,0 +1,84 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates policy inference in a prebuilt USD environment. + +In this example, we use a locomotion policy to control the H1 robot. The robot was trained +using Isaac-Velocity-Rough-H1-v0. The robot is commanded to move forward at a constant velocity. + +.. code-block:: bash + + # Run the script + ./isaaclab.sh -p scripts/tutorials/03_envs/policy_inference_in_usd.py --checkpoint /path/to/jit/checkpoint.pt + +""" + +"""Launch Isaac Sim Simulator first.""" + + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Tutorial on inferencing a policy on an H1 robot in a warehouse.") +parser.add_argument("--checkpoint", type=str, help="Path to model checkpoint exported as jit.", required=True) + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" +import os + +import torch + +from isaaclab.envs import ManagerBasedRLEnv +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, read_file + +from isaaclab_tasks.manager_based.locomotion.velocity.config.h1.rough_env_cfg import H1RoughEnvCfg_PLAY + + +def main(): + """Main function.""" + # load the trained jit policy + policy_path = os.path.abspath(args_cli.checkpoint) + file = read_file(policy_path) + policy = torch.jit.load(file, map_location=args_cli.device) + + # setup environment + env_cfg = H1RoughEnvCfg_PLAY() + env_cfg.scene.num_envs = 1 + env_cfg.curriculum = None + env_cfg.scene.terrain = TerrainImporterCfg( + prim_path="/World/ground", + terrain_type="usd", + usd_path=f"{ISAAC_NUCLEUS_DIR}/Environments/Simple_Warehouse/warehouse.usd", + ) + env_cfg.sim.device = args_cli.device + if args_cli.device == "cpu": + env_cfg.sim.use_fabric = False + + # create environment + env = ManagerBasedRLEnv(cfg=env_cfg) + + # run inference with the policy + obs, _ = env.reset() + with torch.inference_mode(): + while simulation_app.is_running(): + action = policy(obs["policy"]) + obs, _, _, _, _ = env.step(action) + + +if __name__ == "__main__": + main() + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/03_envs/run_cartpole_rl_env.py b/simulation/modules/IsaacLab/scripts/tutorials/03_envs/run_cartpole_rl_env.py new file mode 100644 index 0000000000000000000000000000000000000000..7d7a195a481a19e65c0684d9a7741a9355803eec --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/03_envs/run_cartpole_rl_env.py @@ -0,0 +1,81 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates how to run the RL environment for the cartpole balancing task. + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tutorials/03_envs/run_cartpole_rl_env.py --num_envs 32 + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Tutorial on running the cartpole RL environment.") +parser.add_argument("--num_envs", type=int, default=16, help="Number of environments to spawn.") + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# tutorials should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +from isaaclab.envs import ManagerBasedRLEnv + +from isaaclab_tasks.manager_based.classic.cartpole.cartpole_env_cfg import CartpoleEnvCfg + + +def main(): + """Main function.""" + # create environment configuration + env_cfg = CartpoleEnvCfg() + env_cfg.scene.num_envs = args_cli.num_envs + env_cfg.sim.device = args_cli.device + # setup RL environment + env = ManagerBasedRLEnv(cfg=env_cfg) + + # simulate physics + count = 0 + while simulation_app.is_running(): + with torch.inference_mode(): + # reset + if count % 300 == 0: + count = 0 + env.reset() + print("-" * 80) + print("[INFO]: Resetting environment...") + # sample random actions + joint_efforts = torch.randn_like(env.action_manager.action) + # step the environment + obs, rew, terminated, truncated, info = env.step(joint_efforts) + # print current orientation of pole + print("[Env 0]: Pole joint: ", obs["policy"][0][1].item()) + # update counter + count += 1 + + # close the environment + env.close() + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/add_sensors_on_robot.py b/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/add_sensors_on_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..521f44d712ca66576e540f82c541bb8a5da16edc --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/add_sensors_on_robot.py @@ -0,0 +1,184 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates how to add and simulate on-board sensors for a robot. + +We add the following sensors on the quadruped robot, ANYmal-C (ANYbotics): + +* USD-Camera: This is a camera sensor that is attached to the robot's base. +* Height Scanner: This is a height scanner sensor that is attached to the robot's base. +* Contact Sensor: This is a contact sensor that is attached to the robot's feet. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/04_sensors/add_sensors_on_robot.py --enable_cameras --viz kit + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Tutorial on adding sensors on a robot.") +parser.add_argument("--num_envs", type=int, default=2, help="Number of environments to spawn.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg, AssetBaseCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors import CameraCfg, ContactSensorCfg, RayCasterCfg, patterns +from isaaclab.utils.configclass import configclass + +## +# Pre-defined configs +## +from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip + + +@configclass +class SensorsSceneCfg(InteractiveSceneCfg): + """Design the scene with sensors on the robot.""" + + # ground plane + ground = AssetBaseCfg(prim_path="/World/defaultGroundPlane", spawn=sim_utils.GroundPlaneCfg()) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # robot + robot: ArticulationCfg = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + # sensors + camera = CameraCfg( + prim_path="{ENV_REGEX_NS}/Robot/base/front_cam", + update_period=0.1, + height=480, + width=640, + data_types=["rgb", "distance_to_image_plane"], + spawn=sim_utils.PinholeCameraCfg( + focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 1.0e5) + ), + offset=CameraCfg.OffsetCfg(pos=(0.510, 0.0, 0.015), rot=(0.5, -0.5, 0.5, -0.5), convention="ros"), + ) + height_scanner = RayCasterCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + update_period=0.02, + offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)), + ray_alignment="yaw", + pattern_cfg=patterns.GridPatternCfg(resolution=0.1, size=[1.6, 1.0]), + debug_vis=True, + mesh_prim_paths=["/World/defaultGroundPlane"], + ) + contact_forces = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/.*_FOOT", update_period=0.0, history_length=6, debug_vis=True + ) + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Run the simulator.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + # Simulate physics + while simulation_app.is_running(): + # Reset + if count % 500 == 0: + # reset counter + count = 0 + # reset the scene entities + # root state + # we offset the root state by the origin since the states are written in simulation world frame + # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world + root_pose = scene["robot"].data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + scene["robot"].write_root_pose_to_sim_index(root_pose=root_pose) + root_vel = scene["robot"].data.default_root_vel.torch.clone() + scene["robot"].write_root_velocity_to_sim_index(root_velocity=root_vel) + # set joint positions with some noise + joint_pos, joint_vel = ( + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), + ) + joint_pos += torch.rand_like(joint_pos) * 0.1 + scene["robot"].write_joint_position_to_sim_index(position=joint_pos) + scene["robot"].write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + scene.reset() + print("[INFO]: Resetting robot state...") + # Apply default actions to the robot + # -- generate actions/commands + targets = scene["robot"].data.default_joint_pos.torch + # -- apply action to the robot + scene["robot"].set_joint_position_target_index(target=targets) + # -- write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + scene.update(sim_dt) + + # print information from the sensors + print("-------------------------------") + print(scene["camera"]) + print("Received shape of rgb image: ", scene["camera"].data.output["rgb"].shape) + print("Received shape of depth image: ", scene["camera"].data.output["distance_to_image_plane"].shape) + print("-------------------------------") + print(scene["height_scanner"]) + print( + "Received max height value: ", + torch.max(scene["height_scanner"].data.ray_hits_w.torch[..., -1]).item(), + ) + print("-------------------------------") + print(scene["contact_forces"]) + print("Received max contact force of: ", torch.max(scene["contact_forces"].data.net_forces_w).item()) + + +def main(): + """Main function.""" + + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[3.5, 3.5, 3.5], target=[0.0, 0.0, 0.0]) + # Design scene + scene_cfg = SensorsSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0) + scene = InteractiveScene(scene_cfg) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/run_frame_transformer.py b/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/run_frame_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..79052a12b8c800d9a82fd533763bf0d2efb6c3a9 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/run_frame_transformer.py @@ -0,0 +1,193 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates the FrameTransformer sensor by visualizing the frames that it creates. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/04_sensors/run_frame_transformer.py --viz kit + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser( + description="This script checks the FrameTransformer sensor by visualizing the frames that it creates." +) +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 math + +import torch + +from isaacsim.core.experimental.utils.app import enable_extension + +enable_extension("isaacsim.util.debug_draw") + +from isaacsim.util.debug_draw import _debug_draw as omni_debug_draw + +import isaaclab.sim as sim_utils +import isaaclab.utils.math as math_utils +from isaaclab.assets import Articulation +from isaaclab.markers import VisualizationMarkers +from isaaclab.markers.config import FRAME_MARKER_CFG +from isaaclab.sensors import FrameTransformer, FrameTransformerCfg, OffsetCfg +from isaaclab.sim import SimulationContext + +## +# Pre-defined configs +## +from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort:skip + +ROBOT_PRIM_PATH = "/World/envs/env_0/Robot" +ROBOT_PRIM_PATH_EXPR = "/World/envs/env_.*/Robot" + + +def define_sensor() -> FrameTransformer: + """Defines the FrameTransformer sensor to add to the scene.""" + # define offset + rot_offset = math_utils.quat_from_euler_xyz(torch.zeros(1), torch.zeros(1), torch.tensor(-math.pi / 2)) + pos_offset = math_utils.quat_apply(rot_offset, torch.tensor([0.08795, 0.01305, -0.33797])) + + # Example using .* to get full body + LF_FOOT + frame_transformer_cfg = FrameTransformerCfg( + prim_path=f"{ROBOT_PRIM_PATH_EXPR}/base", + target_frames=[ + FrameTransformerCfg.FrameCfg(prim_path=f"{ROBOT_PRIM_PATH_EXPR}/.*"), + FrameTransformerCfg.FrameCfg( + prim_path=f"{ROBOT_PRIM_PATH_EXPR}/LF_SHANK", + name="LF_FOOT_USER", + offset=OffsetCfg(pos=tuple(pos_offset.tolist()), rot=tuple(rot_offset[0].tolist())), + ), + ], + debug_vis=False, + ) + frame_transformer = FrameTransformer(frame_transformer_cfg) + + return frame_transformer + + +def design_scene() -> dict: + """Design the scene.""" + # Populate scene + # -- Ground-plane + cfg = sim_utils.GroundPlaneCfg() + cfg.func("/World/defaultGroundPlane", cfg) + # -- Lights + cfg = sim_utils.DistantLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + cfg.func("/World/Light", cfg) + # -- Robot + robot = Articulation(ANYMAL_C_CFG.replace(prim_path=ROBOT_PRIM_PATH)) + # -- Sensors + frame_transformer = define_sensor() + + # return the scene information + scene_entities = {"robot": robot, "frame_transformer": frame_transformer} + return scene_entities + + +def run_simulator(sim: sim_utils.SimulationContext, scene_entities: dict): + """Run the simulator.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + # extract entities for simplified notation + robot: Articulation = scene_entities["robot"] + frame_transformer: FrameTransformer = scene_entities["frame_transformer"] + + # We only want one visualization at a time. This visualizer will be used + # to step through each frame so the user can verify that the correct frame + # is being visualized as the frame names are printing to console + if not args_cli.headless: + cfg = FRAME_MARKER_CFG.replace(prim_path="/Visuals/FrameVisualizerFromScript") + cfg.markers["frame"].scale = (0.1, 0.1, 0.1) + transform_visualizer = VisualizationMarkers(cfg) + # debug drawing for lines connecting the frame + draw_interface = omni_debug_draw.acquire_debug_draw_interface() + else: + transform_visualizer = None + draw_interface = None + + frame_index = 0 + # Simulate physics + while simulation_app.is_running(): + # perform this loop at policy control freq (50 Hz) + robot.set_joint_position_target_index(target=robot.data.default_joint_pos.torch.clone()) + robot.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # read data from sim + robot.update(sim_dt) + frame_transformer.update(dt=sim_dt) + + # Change the frame that we are visualizing to ensure that frame names + # are correctly associated with the frames + if not args_cli.headless: + if count % 50 == 0: + # get frame names + frame_names = frame_transformer.data.target_frame_names + # increment frame index + frame_index += 1 + frame_index = frame_index % len(frame_names) + print(f"Displaying Frame ID {frame_index}: {frame_names[frame_index]}") + + # visualize frame + source_pos = frame_transformer.data.source_pos_w.torch + source_quat = frame_transformer.data.source_quat_w.torch + target_pos = frame_transformer.data.target_pos_w.torch[:, frame_index] + target_quat = frame_transformer.data.target_quat_w.torch[:, frame_index] + # draw the frames + transform_visualizer.visualize( + torch.cat([source_pos, target_pos], dim=0), torch.cat([source_quat, target_quat], dim=0) + ) + # draw the line connecting the frames + draw_interface.clear_lines() + # plain color for lines + lines_colors = [[1.0, 1.0, 0.0, 1.0]] * source_pos.shape[0] + line_thicknesses = [5.0] * source_pos.shape[0] + draw_interface.draw_lines(source_pos.tolist(), target_pos.tolist(), lines_colors, line_thicknesses) + + +def main(): + """Main function.""" + # Load kit helper + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device) + sim = SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[2.5, 2.5, 2.5], target=[0.0, 0.0, 0.0]) + # Design scene + scene_entities = design_scene() + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene_entities) + + +if __name__ == "__main__": + # Run the main function + main() + # Close the simulator + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/run_ray_caster.py b/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/run_ray_caster.py new file mode 100644 index 0000000000000000000000000000000000000000..8a76054e5e922dafedfb14691b1474fe8d376466 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/run_ray_caster.py @@ -0,0 +1,150 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates how to use the ray-caster sensor. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/04_sensors/run_ray_caster.py --viz kit + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Ray Caster Test Script") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import RigidObject, RigidObjectCfg +from isaaclab.sensors.ray_caster import RayCaster, RayCasterCfg, patterns +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR +from isaaclab.utils.timer import Timer + + +def define_sensor() -> RayCaster: + """Defines the ray-caster sensor to add to the scene.""" + # Create a ray-caster sensor + ray_caster_cfg = RayCasterCfg( + prim_path="/World/Origin.*/ball", + mesh_prim_paths=["/World/ground"], + pattern_cfg=patterns.GridPatternCfg(resolution=0.1, size=(2.0, 2.0)), + ray_alignment="yaw", + debug_vis=not args_cli.headless, + ) + ray_caster = RayCaster(cfg=ray_caster_cfg) + + return ray_caster + + +def design_scene() -> dict: + """Design the scene.""" + # Populate scene + # -- Rough terrain + cfg = sim_utils.UsdFileCfg(usd_path=f"{ISAAC_NUCLEUS_DIR}/Environments/Terrains/rough_plane.usd") + cfg.func("/World/ground", cfg) + # -- Light + cfg = sim_utils.DistantLightCfg(intensity=2000) + cfg.func("/World/light", cfg) + + # Create separate groups called "Origin1", "Origin2", "Origin3" + # Each group will have a robot in it + origins = [[0.25, 0.25, 0.0], [-0.25, 0.25, 0.0], [0.25, -0.25, 0.0], [-0.25, -0.25, 0.0]] + for i, origin in enumerate(origins): + sim_utils.create_prim(f"/World/Origin{i}", "Xform", translation=origin) + # -- Balls + cfg = RigidObjectCfg( + prim_path="/World/Origin.*/ball", + spawn=sim_utils.SphereCfg( + radius=0.25, + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=0.5), + collision_props=sim_utils.CollisionPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 1.0)), + ), + ) + balls = RigidObject(cfg) + # -- Sensors + ray_caster = define_sensor() + + # return the scene information + scene_entities = {"balls": balls, "ray_caster": ray_caster} + return scene_entities + + +def run_simulator(sim: sim_utils.SimulationContext, scene_entities: dict): + """Run the simulator.""" + # Extract scene_entities for simplified notation + ray_caster: RayCaster = scene_entities["ray_caster"] + balls: RigidObject = scene_entities["balls"] + + # define an initial position of the sensor + ball_default_pose = balls.data.default_root_pose.torch.clone() + ball_default_pose[:, :3] = torch.rand_like(ball_default_pose[:, :3]) * 10 + ball_default_vel = balls.data.default_root_vel.torch.clone() + + # Create a counter for resetting the scene + step_count = 0 + # Simulate physics + while simulation_app.is_running(): + # Reset the scene + if step_count % 250 == 0: + # reset the balls + balls.write_root_pose_to_sim_index(root_pose=ball_default_pose) + balls.write_root_velocity_to_sim_index(root_velocity=ball_default_vel) + # reset the sensor + ray_caster.reset() + # reset the counter + step_count = 0 + # Step simulation + sim.step() + # Update the ray-caster + with Timer( + f"Ray-caster update with {4} x {ray_caster.num_rays} rays with max height of" + f" {torch.max(ray_caster.data.pos_w.torch).item():.2f}" + ): + ray_caster.update(dt=sim.get_physics_dt(), force_recompute=True) + # Update counter + step_count += 1 + + +def main(): + """Main function.""" + # Load simulation context + sim_cfg = sim_utils.SimulationCfg(device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([0.0, 15.0, 15.0], [0.0, 0.0, -2.5]) + # Design scene + scene_entities = design_scene() + # Play simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run simulator + run_simulator(sim=sim, scene_entities=scene_entities) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/run_ray_caster_camera.py b/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/run_ray_caster_camera.py new file mode 100644 index 0000000000000000000000000000000000000000..fc4c97c62cb45efc5be84fd5824bdf6235550b56 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/run_ray_caster_camera.py @@ -0,0 +1,182 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script shows how to use the ray-cast camera sensor from the Isaac Lab framework. + +The camera sensor is based on using Warp kernels which do ray-casting against static meshes. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/04_sensors/run_ray_caster_camera.py --viz kit + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="This script demonstrates how to use the ray-cast camera sensor.") +parser.add_argument("--num_envs", type=int, default=16, help="Number of environments to generate.") +parser.add_argument("--save", action="store_true", default=False, help="Save the obtained data to disk.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import os + +import torch + +import omni.replicator.core as rep + +import isaaclab.sim as sim_utils +from isaaclab.sensors.ray_caster import RayCasterCamera, RayCasterCameraCfg, patterns +from isaaclab.utils import convert_dict_to_backend +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR +from isaaclab.utils.math import project_points, unproject_depth + + +def define_sensor() -> RayCasterCamera: + """Defines the ray-cast camera sensor to add to the scene.""" + # Camera base frames + # In contras to the USD camera, we associate the sensor to the prims at these locations. + # This means that parent prim of the sensor is the prim at this location. + sim_utils.create_prim("/World/Origin_00/CameraSensor", "Xform") + sim_utils.create_prim("/World/Origin_01/CameraSensor", "Xform") + + # Setup camera sensor + camera_cfg = RayCasterCameraCfg( + prim_path="/World/Origin_.*/CameraSensor", + mesh_prim_paths=["/World/ground"], + update_period=0.1, + offset=RayCasterCameraCfg.OffsetCfg(pos=(0.0, 0.0, 0.0), rot=(1.0, 0.0, 0.0, 0.0)), + data_types=["distance_to_image_plane", "normals", "distance_to_camera"], + debug_vis=True, + pattern_cfg=patterns.PinholeCameraPatternCfg( + focal_length=24.0, + horizontal_aperture=20.955, + height=480, + width=640, + ), + ) + # Create camera + camera = RayCasterCamera(cfg=camera_cfg) + + return camera + + +def design_scene(): + # Populate scene + # -- Rough terrain + cfg = sim_utils.UsdFileCfg(usd_path=f"{ISAAC_NUCLEUS_DIR}/Environments/Terrains/rough_plane.usd") + cfg.func("/World/ground", cfg) + # -- Lights + cfg = sim_utils.DistantLightCfg(intensity=600.0, color=(0.75, 0.75, 0.75)) + cfg.func("/World/Light", cfg) + # -- Sensors + camera = define_sensor() + + # return the scene information + scene_entities = {"camera": camera} + return scene_entities + + +def run_simulator(sim: sim_utils.SimulationContext, scene_entities: dict): + """Run the simulator.""" + # extract entities for simplified notation + camera: RayCasterCamera = scene_entities["camera"] + + # Create replicator writer + output_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output", "ray_caster_camera") + rep_writer = rep.BasicWriter(output_dir=output_dir, frame_padding=3) + + # Set pose: There are two ways to set the pose of the camera. + # -- Option-1: Set pose using view + eyes = torch.tensor([[2.5, 2.5, 2.5], [-2.5, -2.5, 2.5]], device=sim.device) + targets = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], device=sim.device) + camera.set_world_poses_from_view(eyes, targets) + # -- Option-2: Set pose using ROS + # position = torch.tensor([[2.5, 2.5, 2.5]], device=sim.device) + # orientation = torch.tensor([[-0.17591989, 0.33985114, 0.82047325, -0.42470819]], device=sim.device) + # camera.set_world_poses(position, orientation, indices=[0], convention="ros") + + # Simulate physics + while simulation_app.is_running(): + # Step simulation + sim.step() + # Update camera data + camera.update(dt=sim.get_physics_dt()) + + # Print camera info + print(camera) + print("Received shape of depth image: ", camera.data.output["distance_to_image_plane"].shape) + print("-------------------------------") + + # Extract camera data + if args_cli.save: + # Extract camera data + camera_index = 0 + # note: BasicWriter only supports saving data in numpy format, so we need to convert the data to numpy. + single_cam_data = convert_dict_to_backend( + {k: v[camera_index] for k, v in camera.data.output.items()}, backend="numpy" + ) + # Pack data back into replicator format to save them using its writer + rep_output = {"annotators": {}} + for key, data in single_cam_data.items(): + info = camera.data.info.get(key) + if info is not None: + rep_output["annotators"][key] = {"render_product": {"data": data, **info}} + else: + rep_output["annotators"][key] = {"render_product": {"data": data}} + # Save images + rep_output["trigger_outputs"] = {"on_time": camera.frame[camera_index]} + rep_writer.write(rep_output) + + # Pointcloud in world frame + points_3d_cam = unproject_depth( + camera.data.output["distance_to_image_plane"], camera.data.intrinsic_matrices + ) + + # Check methods are valid + im_height, im_width = camera.image_shape + # -- project points to (u, v, d) + reproj_points = project_points(points_3d_cam, camera.data.intrinsic_matrices) + reproj_depths = reproj_points[..., -1].view(-1, im_width, im_height).transpose_(1, 2) + sim_depths = camera.data.output["distance_to_image_plane"].squeeze(-1) + torch.testing.assert_close(reproj_depths, sim_depths) + + +def main(): + """Main function.""" + # Load kit helper + sim_cfg = sim_utils.SimulationCfg() + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.5, 2.5, 3.5], [0.0, 0.0, 0.0]) + # Design scene + scene_entities = design_scene() + # Play simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run simulator + run_simulator(sim=sim, scene_entities=scene_entities) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/run_usd_camera.py b/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/run_usd_camera.py new file mode 100644 index 0000000000000000000000000000000000000000..941a34bc7df51126a0b73682263fe7441b1acc46 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/04_sensors/run_usd_camera.py @@ -0,0 +1,294 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script shows how to use the camera sensor from the Isaac Lab framework. + +The camera sensor is created and interfaced through the Omniverse Replicator API. However, instead of using +the simulator or OpenGL convention for the camera, we use the robotics or ROS convention. + +.. code-block:: bash + + # Usage with GUI + ./isaaclab.sh -p scripts/tutorials/04_sensors/run_usd_camera.py --enable_cameras --viz kit + + # Usage with headless + ./isaaclab.sh -p scripts/tutorials/04_sensors/run_usd_camera.py --headless --enable_cameras + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="This script demonstrates how to use the camera sensor.") +parser.add_argument( + "--draw", + action="store_true", + default=False, + help="Draw the pointcloud from camera at index specified by ``--camera_id``.", +) +parser.add_argument( + "--save", + action="store_true", + default=False, + help="Save the data from camera at index specified by ``--camera_id``.", +) +parser.add_argument( + "--camera_id", + type=int, + choices={0, 1}, + default=0, + help=( + "The camera ID to use for displaying points or saving the camera data. Default is 0." + " The viewport will always initialize with the perspective of camera 0." + ), +) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import os +import random + +import numpy as np +import torch +from isaaclab_physx.renderers import IsaacRtxRendererCfg + +import omni.replicator.core as rep + +import isaaclab.sim as sim_utils +from isaaclab.assets import RigidObject, RigidObjectCfg +from isaaclab.markers import VisualizationMarkers +from isaaclab.markers.config import RAY_CASTER_MARKER_CFG +from isaaclab.sensors.camera import Camera, CameraCfg +from isaaclab.sensors.camera.utils import create_pointcloud_from_depth +from isaaclab.utils import convert_dict_to_backend + + +def define_sensor() -> Camera: + """Defines the camera sensor to add to the scene.""" + # Setup camera sensor + # In contrast to the ray-cast camera, we spawn the prim at these locations. + # This means the camera sensor will be attached to these prims. + sim_utils.create_prim("/World/Origin_00", "Xform") + sim_utils.create_prim("/World/Origin_01", "Xform") + camera_cfg = CameraCfg( + prim_path="/World/Origin_.*/CameraSensor", + update_period=0, + height=480, + width=640, + data_types=[ + "rgb", + "distance_to_image_plane", + "normals", + "semantic_segmentation", + "instance_segmentation_fast", + "instance_id_segmentation_fast", + ], + renderer_cfg=IsaacRtxRendererCfg( + colorize_semantic_segmentation=True, + colorize_instance_id_segmentation=True, + colorize_instance_segmentation=True, + ), + spawn=sim_utils.PinholeCameraCfg( + focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 1.0e5) + ), + ) + # Create camera + camera = Camera(cfg=camera_cfg) + + return camera + + +def design_scene() -> dict: + """Design the scene.""" + # Populate scene + # -- Ground-plane + cfg = sim_utils.GroundPlaneCfg() + cfg.func("/World/defaultGroundPlane", cfg) + # -- Lights + cfg = sim_utils.DistantLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + cfg.func("/World/Light", cfg) + + # Create a dictionary for the scene entities + scene_entities = {} + + # Xform to hold objects + sim_utils.create_prim("/World/Objects", "Xform") + # Random objects + for i in range(8): + # sample random position + position = np.random.rand(3) - np.asarray([0.05, 0.05, -1.0]) + position *= np.asarray([1.5, 1.5, 0.5]) + # sample random color + color = (random.random(), random.random(), random.random()) + # choose random prim type + prim_type = random.choice(["Cube", "Cone", "Cylinder"]) + common_properties = { + "rigid_props": sim_utils.RigidBodyPropertiesCfg(), + "mass_props": sim_utils.MassPropertiesCfg(mass=5.0), + "collision_props": sim_utils.CollisionPropertiesCfg(), + "visual_material": sim_utils.PreviewSurfaceCfg(diffuse_color=color, metallic=0.5), + "semantic_tags": [("class", prim_type)], + } + if prim_type == "Cube": + shape_cfg = sim_utils.CuboidCfg(size=(0.25, 0.25, 0.25), **common_properties) + elif prim_type == "Cone": + shape_cfg = sim_utils.ConeCfg(radius=0.1, height=0.25, **common_properties) + elif prim_type == "Cylinder": + shape_cfg = sim_utils.CylinderCfg(radius=0.25, height=0.25, **common_properties) + # Rigid Object + obj_cfg = RigidObjectCfg( + prim_path=f"/World/Objects/Obj_{i:02d}", + spawn=shape_cfg, + init_state=RigidObjectCfg.InitialStateCfg(pos=position), + ) + scene_entities[f"rigid_object{i}"] = RigidObject(cfg=obj_cfg) + + # Sensors + camera = define_sensor() + + # return the scene information + scene_entities["camera"] = camera + return scene_entities + + +def run_simulator(sim: sim_utils.SimulationContext, scene_entities: dict): + """Run the simulator.""" + # extract entities for simplified notation + camera: Camera = scene_entities["camera"] + + # Create replicator writer + output_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output", "camera") + rep_writer = rep.BasicWriter( + output_dir=output_dir, + frame_padding=0, + colorize_instance_id_segmentation=camera.cfg.renderer_cfg.colorize_instance_id_segmentation, + colorize_instance_segmentation=camera.cfg.renderer_cfg.colorize_instance_segmentation, + colorize_semantic_segmentation=camera.cfg.renderer_cfg.colorize_semantic_segmentation, + ) + + # Camera positions, targets, orientations + camera_positions = torch.tensor([[2.5, 2.5, 2.5], [-2.5, -2.5, 2.5]], device=sim.device) + camera_targets = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], device=sim.device) + # These orientations are in ROS-convention, and will position the cameras to view the origin + camera_orientations = torch.tensor( # noqa: F841 + [[-0.1759, 0.3399, 0.8205, -0.4247], [-0.4247, 0.8205, -0.3399, 0.1759]], device=sim.device + ) + + # Set pose: There are two ways to set the pose of the camera. + # -- Option-1: Set pose using view + camera.set_world_poses_from_view(camera_positions, camera_targets) + # -- Option-2: Set pose using ROS + # camera.set_world_poses(camera_positions, camera_orientations, convention="ros") + + # Index of the camera to use for visualization and saving + camera_index = args_cli.camera_id + + # Create the markers for the --draw option outside of is_running() loop + if sim.get_setting("/isaaclab/has_gui") and args_cli.draw: + cfg = RAY_CASTER_MARKER_CFG.replace(prim_path="/Visuals/CameraPointCloud") + cfg.markers["hit"].radius = 0.002 + pc_markers = VisualizationMarkers(cfg) + + # Simulate physics + while simulation_app.is_running(): + # Step simulation + sim.step() + # Update camera data + camera.update(dt=sim.get_physics_dt()) + + # Print camera info + print(camera) + if "rgb" in camera.data.output.keys(): + print("Received shape of rgb image : ", camera.data.output["rgb"].shape) + if "distance_to_image_plane" in camera.data.output.keys(): + print("Received shape of depth image : ", camera.data.output["distance_to_image_plane"].shape) + if "normals" in camera.data.output.keys(): + print("Received shape of normals : ", camera.data.output["normals"].shape) + if "semantic_segmentation" in camera.data.output.keys(): + print("Received shape of semantic segm. : ", camera.data.output["semantic_segmentation"].shape) + if "instance_segmentation_fast" in camera.data.output.keys(): + print("Received shape of instance segm. : ", camera.data.output["instance_segmentation_fast"].shape) + if "instance_id_segmentation_fast" in camera.data.output.keys(): + print("Received shape of instance id segm.: ", camera.data.output["instance_id_segmentation_fast"].shape) + print("-------------------------------") + + # Extract camera data + if args_cli.save: + # Save images from camera at camera_index + # note: BasicWriter only supports saving data in numpy format, so we need to convert the data to numpy. + single_cam_data = convert_dict_to_backend( + {k: v[camera_index] for k, v in camera.data.output.items()}, backend="numpy" + ) + + # Pack data back into replicator format to save them using its writer + rep_output = {"annotators": {}} + for key, data in single_cam_data.items(): + info = camera.data.info.get(key) + if info is not None: + rep_output["annotators"][key] = {"render_product": {"data": data, **info}} + else: + rep_output["annotators"][key] = {"render_product": {"data": data}} + # Save images + # Note: We need to provide On-time data for Replicator to save the images. + rep_output["trigger_outputs"] = {"on_time": camera.frame[camera_index]} + rep_writer.write(rep_output) + + # Draw pointcloud if there is a GUI and --draw has been passed + if ( + sim.get_setting("/isaaclab/has_gui") + and args_cli.draw + and "distance_to_image_plane" in camera.data.output.keys() + ): + # Derive pointcloud from camera at camera_index + pointcloud = create_pointcloud_from_depth( + intrinsic_matrix=camera.data.intrinsic_matrices[camera_index], + depth=camera.data.output["distance_to_image_plane"][camera_index], + position=camera.data.pos_w[camera_index], + orientation=camera.data.quat_w_ros[camera_index], + device=sim.device, + ) + + # In the first few steps, things are still being instanced and Camera.data + # can be empty. If we attempt to visualize an empty pointcloud it will crash + # the sim, so we check that the pointcloud is not empty. + if pointcloud.size()[0] > 0: + pc_markers.visualize(translations=pointcloud) + + +def main(): + """Main function.""" + # Load simulation context + sim_cfg = sim_utils.SimulationCfg(device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.5, 2.5, 2.5], [0.0, 0.0, 0.0]) + # Design scene + scene_entities = design_scene() + # Play simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run simulator + run_simulator(sim, scene_entities) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/05_controllers/run_diff_ik.py b/simulation/modules/IsaacLab/scripts/tutorials/05_controllers/run_diff_ik.py new file mode 100644 index 0000000000000000000000000000000000000000..b3825dcd294575198d8685f84afd67ab93a87420 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/05_controllers/run_diff_ik.py @@ -0,0 +1,216 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates how to use the differential inverse kinematics controller with the simulator. + +The differential IK controller can be configured in different modes. It uses the Jacobians computed by +PhysX. This helps perform parallelized computation of the inverse kinematics. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/05_controllers/run_diff_ik.py + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Tutorial on using the differential IK controller.") +parser.add_argument("--robot", type=str, default="franka_panda", help="Name of the robot.") +parser.add_argument("--num_envs", type=int, default=128, help="Number of environments to spawn.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg +from isaaclab.controllers import DifferentialIKController, DifferentialIKControllerCfg +from isaaclab.managers import SceneEntityCfg +from isaaclab.markers import VisualizationMarkers +from isaaclab.markers.config import FRAME_MARKER_CFG +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR +from isaaclab.utils.configclass import configclass +from isaaclab.utils.math import subtract_frame_transforms + +## +# Pre-defined configs +## +from isaaclab_assets import FRANKA_PANDA_HIGH_PD_CFG, UR10_CFG # isort:skip + + +@configclass +class TableTopSceneCfg(InteractiveSceneCfg): + """Configuration for a cart-pole scene.""" + + # ground plane + ground = AssetBaseCfg( + prim_path="/World/defaultGroundPlane", + spawn=sim_utils.GroundPlaneCfg(), + init_state=AssetBaseCfg.InitialStateCfg(pos=(0.0, 0.0, -1.05)), + ) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # mount + table = AssetBaseCfg( + prim_path="{ENV_REGEX_NS}/Table", + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Mounts/Stand/stand_instanceable.usd", scale=(2.0, 2.0, 2.0) + ), + ) + + # articulation + if args_cli.robot == "franka_panda": + robot = FRANKA_PANDA_HIGH_PD_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + elif args_cli.robot == "ur10": + robot = UR10_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + else: + raise ValueError(f"Robot {args_cli.robot} is not supported. Valid: franka_panda, ur10") + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Runs the simulation loop.""" + # Extract scene entities + # note: we only do this here for readability. + robot = scene["robot"] + + # Create controller + diff_ik_cfg = DifferentialIKControllerCfg(command_type="pose", use_relative_mode=False, ik_method="dls") + diff_ik_controller = DifferentialIKController(diff_ik_cfg, num_envs=scene.num_envs, device=sim.device) + + # Markers + frame_marker_cfg = FRAME_MARKER_CFG.copy() + frame_marker_cfg.markers["frame"].scale = (0.1, 0.1, 0.1) + ee_marker = VisualizationMarkers(frame_marker_cfg.replace(prim_path="/Visuals/ee_current")) + goal_marker = VisualizationMarkers(frame_marker_cfg.replace(prim_path="/Visuals/ee_goal")) + + # Define goals for the arm (x,y,z,qx,qy,qz,qw) + ee_goals = [ + [0.5, 0.5, 0.7, 0, 0.707, 0, 0.707], + [0.5, -0.4, 0.6, 0.707, 0, 0, 0.707], + [0.5, 0, 0.5, 1.0, 0.0, 0.0, 0.0], + ] + ee_goals = torch.tensor(ee_goals, device=sim.device) + # Track the given command + current_goal_idx = 0 + # Create buffers to store actions + ik_commands = torch.zeros(scene.num_envs, diff_ik_controller.action_dim, device=robot.device) + ik_commands[:] = ee_goals[current_goal_idx] + + # Specify robot-specific parameters + if args_cli.robot == "franka_panda": + robot_entity_cfg = SceneEntityCfg("robot", joint_names=["panda_joint.*"], body_names=["panda_hand"]) + elif args_cli.robot == "ur10": + robot_entity_cfg = SceneEntityCfg("robot", joint_names=[".*"], body_names=["ee_link"]) + else: + raise ValueError(f"Robot {args_cli.robot} is not supported. Valid: franka_panda, ur10") + # Resolving the scene entities + robot_entity_cfg.resolve(scene) + # Obtain the frame index of the end-effector + # For a fixed base robot, the frame index is one less than the body index. This is because + # the root body is not included in the returned Jacobians. + if robot.is_fixed_base: + ee_jacobi_idx = robot_entity_cfg.body_ids[0] - 1 + else: + ee_jacobi_idx = robot_entity_cfg.body_ids[0] + + # Define simulation stepping + sim_dt = sim.get_physics_dt() + count = 0 + # Simulation loop + while simulation_app.is_running(): + # reset + if count % 150 == 0: + # reset time + count = 0 + # reset joint state + joint_pos = robot.data.default_joint_pos.torch.clone() + joint_vel = robot.data.default_joint_vel.torch.clone() + robot.write_joint_position_to_sim_index(position=joint_pos) + robot.write_joint_velocity_to_sim_index(velocity=joint_vel) + robot.reset() + # reset actions + ik_commands[:] = ee_goals[current_goal_idx] + joint_pos_des = joint_pos[:, robot_entity_cfg.joint_ids].clone() + # reset controller + diff_ik_controller.reset() + diff_ik_controller.set_command(ik_commands) + # change goal + current_goal_idx = (current_goal_idx + 1) % len(ee_goals) + else: + # obtain quantities from simulation. The Jacobian DoF axis prepends + # ``num_base_dofs`` floating-base columns (0 for fixed-base, 6 for + # floating-base); shift the actuated-joint ids accordingly. + jacobi_joint_ids = [j + robot.num_base_dofs for j in robot_entity_cfg.joint_ids] + jacobian = robot.data.body_link_jacobian_w.torch[:, ee_jacobi_idx, :, jacobi_joint_ids] + ee_pose_w = robot.data.body_pose_w.torch[:, robot_entity_cfg.body_ids[0]] + root_pose_w = robot.data.root_pose_w.torch + joint_pos = robot.data.joint_pos.torch[:, robot_entity_cfg.joint_ids] + # compute frame in root frame + ee_pos_b, ee_quat_b = subtract_frame_transforms( + root_pose_w[:, 0:3], root_pose_w[:, 3:7], ee_pose_w[:, 0:3], ee_pose_w[:, 3:7] + ) + # compute the joint commands + joint_pos_des = diff_ik_controller.compute(ee_pos_b, ee_quat_b, jacobian, joint_pos) + + # apply actions + robot.set_joint_position_target_index(target=joint_pos_des, joint_ids=robot_entity_cfg.joint_ids) + scene.write_data_to_sim() + # perform step + sim.step() + # update sim-time + count += 1 + # update buffers + scene.update(sim_dt) + + # obtain quantities from simulation + ee_pose_w = robot.data.body_state_w.torch[:, robot_entity_cfg.body_ids[0], 0:7] + # update marker positions + ee_marker.visualize(ee_pose_w[:, 0:3], ee_pose_w[:, 3:7]) + goal_marker.visualize(ik_commands[:, 0:3] + scene.env_origins, ik_commands[:, 3:7]) + + +def main(): + """Main function.""" + # Load kit helper + sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.5, 2.5, 2.5], [0.0, 0.0, 0.0]) + # Design scene + scene_cfg = TableTopSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0) + scene = InteractiveScene(scene_cfg) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/05_controllers/run_osc.py b/simulation/modules/IsaacLab/scripts/tutorials/05_controllers/run_osc.py new file mode 100644 index 0000000000000000000000000000000000000000..c37ace736ef93a7955a616a6b1bb75bdcf558081 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/05_controllers/run_osc.py @@ -0,0 +1,489 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates how to use the operational space controller (OSC) with the simulator. + +The OSC controller can be configured in different modes. It uses the dynamical quantities such as Jacobians and +mass matricescomputed by PhysX. + +.. code-block:: bash + + # Usage + ./isaaclab.sh -p scripts/tutorials/05_controllers/run_osc.py + +""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Tutorial on using the operational space controller.") +parser.add_argument("--num_envs", type=int, default=128, help="Number of environments to spawn.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import Articulation, AssetBaseCfg +from isaaclab.controllers import OperationalSpaceController, OperationalSpaceControllerCfg +from isaaclab.markers import VisualizationMarkers +from isaaclab.markers.config import FRAME_MARKER_CFG +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors import ContactSensorCfg +from isaaclab.utils.configclass import configclass +from isaaclab.utils.math import ( + combine_frame_transforms, + matrix_from_quat, + quat_apply_inverse, + quat_inv, + subtract_frame_transforms, +) + +## +# Pre-defined configs +## +from isaaclab_assets import FRANKA_PANDA_HIGH_PD_CFG # isort:skip + + +@configclass +class SceneCfg(InteractiveSceneCfg): + """Configuration for a simple scene with a tilted wall.""" + + # ground plane + ground = AssetBaseCfg( + prim_path="/World/defaultGroundPlane", + spawn=sim_utils.GroundPlaneCfg(), + ) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)) + ) + + # Tilted wall + tilted_wall = AssetBaseCfg( + prim_path="{ENV_REGEX_NS}/TiltedWall", + spawn=sim_utils.CuboidCfg( + size=(2.0, 1.5, 0.01), + collision_props=sim_utils.CollisionPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0), opacity=0.1), + rigid_props=sim_utils.RigidBodyPropertiesCfg(kinematic_enabled=True), + activate_contact_sensors=True, + ), + init_state=AssetBaseCfg.InitialStateCfg( + pos=(0.6 + 0.085, 0.0, 0.3), rot=(0.0, -0.3826834324, 0.0, 0.9238795325) + ), + ) + + contact_forces = ContactSensorCfg( + prim_path="/World/envs/env_.*/TiltedWall", + update_period=0.0, + history_length=2, + debug_vis=False, + ) + + robot = FRANKA_PANDA_HIGH_PD_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + robot.actuators["panda_shoulder"].stiffness = 0.0 + robot.actuators["panda_shoulder"].damping = 0.0 + robot.actuators["panda_forearm"].stiffness = 0.0 + robot.actuators["panda_forearm"].damping = 0.0 + robot.spawn.rigid_props.disable_gravity = True + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Runs the simulation loop. + + Args: + sim: (SimulationContext) Simulation context. + scene: (InteractiveScene) Interactive scene. + """ + + # Extract scene entities for readability. + robot = scene["robot"] + contact_forces = scene["contact_forces"] + + # Obtain indices for the end-effector and arm joints + ee_frame_name = "panda_leftfinger" + arm_joint_names = ["panda_joint.*"] + ee_frame_idx = robot.find_bodies(ee_frame_name)[0][0] + arm_joint_ids = robot.find_joints(arm_joint_names)[0] + + # Create the OSC + osc_cfg = OperationalSpaceControllerCfg( + target_types=["pose_abs", "wrench_abs"], + impedance_mode="variable_kp", + inertial_dynamics_decoupling=True, + partial_inertial_dynamics_decoupling=False, + gravity_compensation=False, + motion_damping_ratio_task=1.0, + contact_wrench_stiffness_task=[0.0, 0.0, 0.1, 0.0, 0.0, 0.0], + motion_control_axes_task=[1, 1, 0, 1, 1, 1], + contact_wrench_control_axes_task=[0, 0, 1, 0, 0, 0], + nullspace_control="position", + ) + osc = OperationalSpaceController(osc_cfg, num_envs=scene.num_envs, device=sim.device) + + # Markers + frame_marker_cfg = FRAME_MARKER_CFG.copy() + frame_marker_cfg.markers["frame"].scale = (0.1, 0.1, 0.1) + ee_marker = VisualizationMarkers(frame_marker_cfg.replace(prim_path="/Visuals/ee_current")) + goal_marker = VisualizationMarkers(frame_marker_cfg.replace(prim_path="/Visuals/ee_goal")) + + # Define targets for the arm (x,y,z,qx,qy,qz,qw) + ee_goal_pose_set_tilted_b = torch.tensor( + [ + [0.6, 0.15, 0.3, 0.0, 0.38268343, 0.0, 0.92387953], + [0.6, -0.3, 0.3, 0.0, 0.38268343, 0.0, 0.92387953], + [0.8, 0.0, 0.5, 0.0, 0.38268343, 0.0, 0.92387953], + ], + device=sim.device, + ) + ee_goal_wrench_set_tilted_task = torch.tensor( + [ + [0.0, 0.0, 10.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 10.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 10.0, 0.0, 0.0, 0.0], + ], + device=sim.device, + ) + kp_set_task = torch.tensor( + [ + [360.0, 360.0, 360.0, 360.0, 360.0, 360.0], + [420.0, 420.0, 420.0, 420.0, 420.0, 420.0], + [320.0, 320.0, 320.0, 320.0, 320.0, 320.0], + ], + device=sim.device, + ) + ee_target_set = torch.cat([ee_goal_pose_set_tilted_b, ee_goal_wrench_set_tilted_task, kp_set_task], dim=-1) + + # Define simulation stepping + sim_dt = sim.get_physics_dt() + + # Update existing buffers + # Note: We need to update buffers before the first step for the controller. + robot.update(dt=sim_dt) + + # Get the center of the robot soft joint limits + joint_centers = torch.mean(robot.data.soft_joint_pos_limits.torch[:, arm_joint_ids, :], dim=-1) + + # get the updated states + ( + jacobian_b, + mass_matrix, + gravity, + ee_pose_b, + ee_vel_b, + root_pose_w, + ee_pose_w, + ee_force_b, + joint_pos, + joint_vel, + ) = update_states(sim, scene, robot, ee_frame_idx, arm_joint_ids, contact_forces) + + # Track the given target command + current_goal_idx = 0 # Current goal index for the arm + command = torch.zeros( + scene.num_envs, osc.action_dim, device=sim.device + ) # Generic target command, which can be pose, position, force, etc. + ee_target_pose_b = torch.zeros(scene.num_envs, 7, device=sim.device) # Target pose in the body frame + ee_target_pose_w = torch.zeros(scene.num_envs, 7, device=sim.device) # Target pose in the world frame (for marker) + + # Set joint efforts to zero + zero_joint_efforts = torch.zeros(scene.num_envs, robot.num_joints, device=sim.device) + joint_efforts = torch.zeros(scene.num_envs, len(arm_joint_ids), device=sim.device) + + count = 0 + # Simulation loop + while simulation_app.is_running(): + # reset every 500 steps + if count % 500 == 0: + # reset joint state to default + default_joint_pos = robot.data.default_joint_pos.torch.clone() + default_joint_vel = robot.data.default_joint_vel.torch.clone() + robot.write_joint_position_to_sim_index(position=default_joint_pos) + robot.write_joint_velocity_to_sim_index(velocity=default_joint_vel) + robot.set_joint_effort_target_index(target=zero_joint_efforts) # Set zero torques in the initial step + robot.write_data_to_sim() + robot.reset() + # reset contact sensor + contact_forces.reset() + # reset target pose + robot.update(sim_dt) + _, _, _, ee_pose_b, _, _, _, _, _, _ = update_states( + sim, scene, robot, ee_frame_idx, arm_joint_ids, contact_forces + ) # at reset, the jacobians are not updated to the latest state + command, ee_target_pose_b, ee_target_pose_w, current_goal_idx = update_target( + sim, scene, osc, root_pose_w, ee_target_set, current_goal_idx + ) + # set the osc command + osc.reset() + command, task_frame_pose_b = convert_to_task_frame(osc, command=command, ee_target_pose_b=ee_target_pose_b) + osc.set_command(command=command, current_ee_pose_b=ee_pose_b, current_task_frame_pose_b=task_frame_pose_b) + else: + # get the updated states + ( + jacobian_b, + mass_matrix, + gravity, + ee_pose_b, + ee_vel_b, + root_pose_w, + ee_pose_w, + ee_force_b, + joint_pos, + joint_vel, + ) = update_states(sim, scene, robot, ee_frame_idx, arm_joint_ids, contact_forces) + # compute the joint commands + joint_efforts = osc.compute( + jacobian_b=jacobian_b, + current_ee_pose_b=ee_pose_b, + current_ee_vel_b=ee_vel_b, + current_ee_force_b=ee_force_b, + mass_matrix=mass_matrix, + gravity=gravity, + current_joint_pos=joint_pos, + current_joint_vel=joint_vel, + nullspace_joint_pos_target=joint_centers, + ) + # apply actions + robot.set_joint_effort_target_index(target=joint_efforts, joint_ids=arm_joint_ids) + robot.write_data_to_sim() + + # update marker positions + ee_marker.visualize(ee_pose_w[:, 0:3], ee_pose_w[:, 3:7]) + goal_marker.visualize(ee_target_pose_w[:, 0:3], ee_target_pose_w[:, 3:7]) + + # perform step + sim.step(render=True) + # update robot buffers + robot.update(sim_dt) + # update buffers + scene.update(sim_dt) + # update sim-time + count += 1 + + +# Update robot states +def update_states( + sim: sim_utils.SimulationContext, + scene: InteractiveScene, + robot: Articulation, + ee_frame_idx: int, + arm_joint_ids: list[int], + contact_forces, +): + """Update the robot states. + + Args: + sim: (SimulationContext) Simulation context. + scene: (InteractiveScene) Interactive scene. + robot: (Articulation) Robot articulation. + ee_frame_idx: (int) End-effector frame index. + arm_joint_ids: (list[int]) Arm joint indices. + contact_forces: (ContactSensor) Contact sensor. + + Returns: + jacobian_b (torch.tensor): Jacobian in the body frame. + mass_matrix (torch.tensor): Mass matrix. + gravity (torch.tensor): Gravity vector. + ee_pose_b (torch.tensor): End-effector pose in the body frame. + ee_vel_b (torch.tensor): End-effector velocity in the body frame. + root_pose_w (torch.tensor): Root pose in the world frame. + ee_pose_w (torch.tensor): End-effector pose in the world frame. + ee_force_b (torch.tensor): End-effector force in the body frame. + joint_pos (torch.tensor): The joint positions. + joint_vel (torch.tensor): The joint velocities. + + Raises: + ValueError: Undefined target_type. + """ + # obtain dynamics related quantities from simulation + ee_jacobi_idx = ee_frame_idx - 1 + # The J / M / g DoF axis prepends ``num_base_dofs`` floating-base columns + # (0 for fixed-base, 6 for floating-base); shift the actuated-joint ids by + # ``num_base_dofs`` to address the actuated-joint columns directly. + jacobi_joint_ids = [j + robot.num_base_dofs for j in arm_joint_ids] + jacobian_w = robot.data.body_link_jacobian_w.torch[:, ee_jacobi_idx, :, jacobi_joint_ids] + mass_matrix = robot.data.mass_matrix.torch[:, jacobi_joint_ids, :][:, :, jacobi_joint_ids] + gravity = robot.data.gravity_compensation_forces.torch[:, jacobi_joint_ids] + # Convert the Jacobian from world to root frame + jacobian_b = jacobian_w.clone() + root_rot_matrix = matrix_from_quat(quat_inv(robot.data.root_quat_w.torch)) + jacobian_b[:, :3, :] = torch.bmm(root_rot_matrix, jacobian_b[:, :3, :]) + jacobian_b[:, 3:, :] = torch.bmm(root_rot_matrix, jacobian_b[:, 3:, :]) + + # Compute current pose of the end-effector + root_pos_w = robot.data.root_pos_w.torch + root_quat_w = robot.data.root_quat_w.torch + ee_pos_w = robot.data.body_pos_w.torch[:, ee_frame_idx] + ee_quat_w = robot.data.body_quat_w.torch[:, ee_frame_idx] + ee_pos_b, ee_quat_b = subtract_frame_transforms(root_pos_w, root_quat_w, ee_pos_w, ee_quat_w) + root_pose_w = torch.cat([root_pos_w, root_quat_w], dim=-1) + ee_pose_w = torch.cat([ee_pos_w, ee_quat_w], dim=-1) + ee_pose_b = torch.cat([ee_pos_b, ee_quat_b], dim=-1) + + # Compute the current velocity of the end-effector + ee_vel_w = robot.data.body_vel_w.torch[:, ee_frame_idx, :] # Extract end-effector velocity in the world frame + root_vel_w = robot.data.root_vel_w.torch # Extract root velocity in the world frame + relative_vel_w = ee_vel_w - root_vel_w # Compute the relative velocity in the world frame + ee_lin_vel_b = quat_apply_inverse(robot.data.root_quat_w.torch, relative_vel_w[:, 0:3]) # From world to root frame + ee_ang_vel_b = quat_apply_inverse(robot.data.root_quat_w.torch, relative_vel_w[:, 3:6]) + ee_vel_b = torch.cat([ee_lin_vel_b, ee_ang_vel_b], dim=-1) + + # Calculate the contact force + ee_force_w = torch.zeros(scene.num_envs, 3, device=sim.device) + sim_dt = sim.get_physics_dt() + contact_forces.update(sim_dt) # update contact sensor + # Calculate the contact force by averaging over last four time steps (i.e., to smoothen) and + # taking the max of three surfaces as only one should be the contact of interest + ee_force_w, _ = torch.max(torch.mean(contact_forces.data.net_forces_w_history, dim=1), dim=1) + + # This is a simplification, only for the sake of testing. + ee_force_b = ee_force_w + + # Get joint positions and velocities + joint_pos = robot.data.joint_pos.torch[:, arm_joint_ids] + joint_vel = robot.data.joint_vel.torch[:, arm_joint_ids] + + return ( + jacobian_b, + mass_matrix, + gravity, + ee_pose_b, + ee_vel_b, + root_pose_w, + ee_pose_w, + ee_force_b, + joint_pos, + joint_vel, + ) + + +# Update the target commands +def update_target( + sim: sim_utils.SimulationContext, + scene: InteractiveScene, + osc: OperationalSpaceController, + root_pose_w: torch.tensor, + ee_target_set: torch.tensor, + current_goal_idx: int, +): + """Update the targets for the operational space controller. + + Args: + sim: (SimulationContext) Simulation context. + scene: (InteractiveScene) Interactive scene. + osc: (OperationalSpaceController) Operational space controller. + root_pose_w: (torch.tensor) Root pose in the world frame. + ee_target_set: (torch.tensor) End-effector target set. + current_goal_idx: (int) Current goal index. + + Returns: + command (torch.tensor): Updated target command. + ee_target_pose_b (torch.tensor): Updated target pose in the body frame. + ee_target_pose_w (torch.tensor): Updated target pose in the world frame. + next_goal_idx (int): Next goal index. + + Raises: + ValueError: Undefined target_type. + """ + + # update the ee desired command + command = torch.zeros(scene.num_envs, osc.action_dim, device=sim.device) + command[:] = ee_target_set[current_goal_idx] + + # update the ee desired pose + ee_target_pose_b = torch.zeros(scene.num_envs, 7, device=sim.device) + for target_type in osc.cfg.target_types: + if target_type == "pose_abs": + ee_target_pose_b[:] = command[:, :7] + elif target_type == "wrench_abs": + pass # ee_target_pose_b could stay at the root frame for force control, what matters is ee_target_b + else: + raise ValueError("Undefined target_type within update_target().") + + # update the target desired pose in world frame (for marker) + ee_target_pos_w, ee_target_quat_w = combine_frame_transforms( + root_pose_w[:, 0:3], root_pose_w[:, 3:7], ee_target_pose_b[:, 0:3], ee_target_pose_b[:, 3:7] + ) + ee_target_pose_w = torch.cat([ee_target_pos_w, ee_target_quat_w], dim=-1) + + next_goal_idx = (current_goal_idx + 1) % len(ee_target_set) + + return command, ee_target_pose_b, ee_target_pose_w, next_goal_idx + + +# Convert the target commands to the task frame +def convert_to_task_frame(osc: OperationalSpaceController, command: torch.tensor, ee_target_pose_b: torch.tensor): + """Converts the target commands to the task frame. + + Args: + osc: OperationalSpaceController object. + command: Command to be converted. + ee_target_pose_b: Target pose in the body frame. + + Returns: + command (torch.tensor): Target command in the task frame. + task_frame_pose_b (torch.tensor): Target pose in the task frame. + + Raises: + ValueError: Undefined target_type. + """ + command = command.clone() + task_frame_pose_b = ee_target_pose_b.clone() + + cmd_idx = 0 + for target_type in osc.cfg.target_types: + if target_type == "pose_abs": + command[:, :3], command[:, 3:7] = subtract_frame_transforms( + task_frame_pose_b[:, :3], task_frame_pose_b[:, 3:], command[:, :3], command[:, 3:7] + ) + cmd_idx += 7 + elif target_type == "wrench_abs": + # These are already defined in target frame for ee_goal_wrench_set_tilted_task (since it is + # easier), so not transforming + cmd_idx += 6 + else: + raise ValueError("Undefined target_type within _convert_to_task_frame().") + + return command, task_frame_pose_b + + +def main(): + """Main function.""" + # Load kit helper + sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.5, 2.5, 2.5], [0.0, 0.0, 0.0]) + # Design scene + scene_cfg = SceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0) + scene = InteractiveScene(scene_cfg) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/simulation/modules/IsaacLab/scripts/tutorials/06_deploy/anymal_c_env.py b/simulation/modules/IsaacLab/scripts/tutorials/06_deploy/anymal_c_env.py new file mode 100644 index 0000000000000000000000000000000000000000..302fba78faa1d8d4c2de7523ae90e2b3d6898456 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/06_deploy/anymal_c_env.py @@ -0,0 +1,209 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# ruff: noqa: I001 + +from __future__ import annotations + +import gymnasium as gym +import torch +import warp as wp + +import isaaclab.sim as sim_utils +from isaaclab.assets import Articulation +from isaaclab.envs import DirectRLEnv +from isaaclab.sensors import ContactSensor, RayCaster + +from .anymal_c_env_cfg import AnymalCFlatEnvCfg, AnymalCRoughEnvCfg +from leapp import annotate # isort: skip + + +class AnymalCEnv(DirectRLEnv): + cfg: AnymalCFlatEnvCfg | AnymalCRoughEnvCfg + + def __init__(self, cfg: AnymalCFlatEnvCfg | AnymalCRoughEnvCfg, render_mode: str | None = None, **kwargs): + super().__init__(cfg, render_mode, **kwargs) + + self._actions = torch.zeros(self.num_envs, gym.spaces.flatdim(self.single_action_space), device=self.device) + self._previous_actions = torch.zeros( + self.num_envs, gym.spaces.flatdim(self.single_action_space), device=self.device + ) + + self._commands = torch.zeros(self.num_envs, 3, device=self.device) + + self._episode_sums = { + key: torch.zeros(self.num_envs, dtype=torch.float, device=self.device) + for key in [ + "track_lin_vel_xy_exp", + "track_ang_vel_z_exp", + "lin_vel_z_l2", + "ang_vel_xy_l2", + "dof_torques_l2", + "dof_acc_l2", + "action_rate_l2", + "feet_air_time", + "undesired_contacts", + "flat_orientation_l2", + ] + } + self._base_id, _ = self._contact_sensor.find_sensors("base") + self._feet_ids, _ = self._contact_sensor.find_sensors(".*FOOT") + self._undesired_contact_body_ids, _ = self._contact_sensor.find_sensors(".*THIGH") + + def _setup_scene(self): + self._robot = Articulation(self.cfg.robot) + self.scene.articulations["robot"] = self._robot + self._contact_sensor = ContactSensor(self.cfg.contact_sensor) + self.scene.sensors["contact_sensor"] = self._contact_sensor + if isinstance(self.cfg, AnymalCRoughEnvCfg): + self._height_scanner = RayCaster(self.cfg.height_scanner) + self.scene.sensors["height_scanner"] = self._height_scanner + self.cfg.terrain.num_envs = self.scene.cfg.num_envs + self.cfg.terrain.env_spacing = self.scene.cfg.env_spacing + self._terrain = self.cfg.terrain.class_type(self.cfg.terrain) + self.scene.clone_environments(copy_from_source=False) + if self.device == "cpu": + self.scene.filter_collisions(global_prim_paths=[self.cfg.terrain.prim_path]) + light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) + light_cfg.func("/World/Light", light_cfg) + + def _pre_physics_step(self, actions: torch.Tensor): + self._actions = actions.clone() + self._processed_actions = self.cfg.action_scale * self._actions + self._robot.data.default_joint_pos.torch + # start LEAPP annotations for outputs + annotate.update_state(self.spec.id, {"previous_actions": actions}) + annotate.output_tensors(self.spec.id, {"processed_actions": self._processed_actions}, export_with="onnx-dynamo") + # end LEAPP annotations for outputs + + def _apply_action(self): + self._robot.set_joint_position_target_index(target=self._processed_actions) + + def _get_observations(self) -> dict: + self._previous_actions = self._actions.clone() + height_data = None + if isinstance(self.cfg, AnymalCRoughEnvCfg): + height_data = ( + self._height_scanner.data.pos_w.torch[:, 2].unsqueeze(1) + - self._height_scanner.data.ray_hits_w.torch[..., 2] + - 0.5 + ).clip(-1.0, 1.0) + # start LEAPP annotations for inputs + root_lin_vel_b = annotate.input_tensors(self.spec.id, {"root_lin_vel_b": self._robot.data.root_lin_vel_b.torch}) + root_ang_vel_b = annotate.input_tensors(self.spec.id, {"root_ang_vel_b": self._robot.data.root_ang_vel_b.torch}) + projected_gravity_b = annotate.input_tensors( + self.spec.id, {"projected_gravity_b": self._robot.data.projected_gravity_b.torch} + ) + commands = annotate.input_tensors(self.spec.id, {"commands": self._commands}) + joint_pos = annotate.input_tensors(self.spec.id, {"joint_pos": self._robot.data.joint_pos.torch}) + default_joint_pos = annotate.input_tensors( + self.spec.id, {"default_joint_pos": self._robot.data.default_joint_pos.torch} + ) + joint_vel = annotate.input_tensors(self.spec.id, {"joint_vel": self._robot.data.joint_vel.torch}) + if height_data is not None: + height_data = annotate.input_tensors(self.spec.id, {"height_data": height_data}) + previous_actions = annotate.state_tensors(self.spec.id, {"previous_actions": self._actions}) + # end LEAPP annotations for inputs + + obs = torch.cat( + [ + tensor + for tensor in ( + root_lin_vel_b, + root_ang_vel_b, + projected_gravity_b, + commands, + joint_pos - default_joint_pos, + joint_vel, + height_data, + previous_actions, + ) + if tensor is not None + ], + dim=-1, + ) + observations = {"policy": obs} + return observations + + def _get_rewards(self) -> torch.Tensor: + lin_vel_error = torch.sum( + torch.square(self._commands[:, :2] - self._robot.data.root_lin_vel_b.torch[:, :2]), dim=1 + ) + lin_vel_error_mapped = torch.exp(-lin_vel_error / 0.25) + yaw_rate_error = torch.square(self._commands[:, 2] - self._robot.data.root_ang_vel_b.torch[:, 2]) + yaw_rate_error_mapped = torch.exp(-yaw_rate_error / 0.25) + z_vel_error = torch.square(self._robot.data.root_lin_vel_b.torch[:, 2]) + ang_vel_error = torch.sum(torch.square(self._robot.data.root_ang_vel_b.torch[:, :2]), dim=1) + joint_torques = torch.sum(torch.square(self._robot.data.applied_torque.torch), dim=1) + joint_accel = torch.sum(torch.square(self._robot.data.joint_acc.torch), dim=1) + action_rate = torch.sum(torch.square(self._actions - self._previous_actions), dim=1) + first_contact = self._contact_sensor.compute_first_contact(self.step_dt).torch[:, self._feet_ids] + last_air_time = self._contact_sensor.data.last_air_time.torch[:, self._feet_ids] + air_time = torch.sum((last_air_time - 0.5) * first_contact, dim=1) * ( + torch.linalg.norm(self._commands[:, :2], dim=1) > 0.1 + ) + net_contact_forces = self._contact_sensor.data.net_forces_w_history.torch + is_contact = ( + torch.max(torch.linalg.norm(net_contact_forces[:, :, self._undesired_contact_body_ids], dim=-1), dim=1)[0] + > 1.0 + ) + contacts = torch.sum(is_contact, dim=1) + flat_orientation = torch.sum(torch.square(self._robot.data.projected_gravity_b.torch[:, :2]), dim=1) + + rewards = { + "track_lin_vel_xy_exp": lin_vel_error_mapped * self.cfg.lin_vel_reward_scale * self.step_dt, + "track_ang_vel_z_exp": yaw_rate_error_mapped * self.cfg.yaw_rate_reward_scale * self.step_dt, + "lin_vel_z_l2": z_vel_error * self.cfg.z_vel_reward_scale * self.step_dt, + "ang_vel_xy_l2": ang_vel_error * self.cfg.ang_vel_reward_scale * self.step_dt, + "dof_torques_l2": joint_torques * self.cfg.joint_torque_reward_scale * self.step_dt, + "dof_acc_l2": joint_accel * self.cfg.joint_accel_reward_scale * self.step_dt, + "action_rate_l2": action_rate * self.cfg.action_rate_reward_scale * self.step_dt, + "feet_air_time": air_time * self.cfg.feet_air_time_reward_scale * self.step_dt, + "undesired_contacts": contacts * self.cfg.undesired_contact_reward_scale * self.step_dt, + "flat_orientation_l2": flat_orientation * self.cfg.flat_orientation_reward_scale * self.step_dt, + } + reward = torch.sum(torch.stack(list(rewards.values())), dim=0) + for key, value in rewards.items(): + self._episode_sums[key] += value + return reward + + def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: + time_out = self.episode_length_buf >= self.max_episode_length - 1 + net_contact_forces = self._contact_sensor.data.net_forces_w_history.torch + died = torch.any( + torch.max(torch.linalg.norm(net_contact_forces[:, :, self._base_id], dim=-1), dim=1)[0] > 1.0, dim=1 + ) + return died, time_out + + def _reset_idx(self, env_ids: torch.Tensor | None): + if env_ids is None or len(env_ids) == self.num_envs: + env_ids = wp.to_torch(self._robot._ALL_INDICES) + assert env_ids is not None + self._robot.reset(env_ids) + super()._reset_idx(env_ids) + if len(env_ids) == self.num_envs: + self.episode_length_buf[:] = torch.randint_like(self.episode_length_buf, high=int(self.max_episode_length)) + self._actions[env_ids] = 0.0 + self._previous_actions[env_ids] = 0.0 + self._commands[env_ids] = torch.zeros_like(self._commands[env_ids]).uniform_(-1.0, 1.0) + joint_pos = self._robot.data.default_joint_pos.torch[env_ids] + joint_vel = self._robot.data.default_joint_vel.torch[env_ids] + default_root_pose = self._robot.data.default_root_pose.torch[env_ids] + default_root_vel = self._robot.data.default_root_vel.torch[env_ids] + default_root_pose[:, :3] += self._terrain.env_origins[env_ids] + self._robot.write_root_pose_to_sim_index(root_pose=default_root_pose, env_ids=env_ids) + self._robot.write_root_velocity_to_sim_index(root_velocity=default_root_vel, env_ids=env_ids) + self._robot.write_joint_position_to_sim_index(position=joint_pos, env_ids=env_ids) + self._robot.write_joint_velocity_to_sim_index(velocity=joint_vel, env_ids=env_ids) + extras = dict() + for key in self._episode_sums.keys(): + episodic_sum_avg = torch.mean(self._episode_sums[key][env_ids]) + extras["Episode_Reward/" + key] = episodic_sum_avg / self.max_episode_length_s + self._episode_sums[key][env_ids] = 0.0 + self.extras["log"] = dict() + self.extras["log"].update(extras) + extras = dict() + extras["Episode_Termination/base_contact"] = torch.count_nonzero(self.reset_terminated[env_ids]).item() + extras["Episode_Termination/time_out"] = torch.count_nonzero(self.reset_time_outs[env_ids]).item() + self.extras["log"].update(extras) diff --git a/simulation/modules/IsaacLab/scripts/tutorials/07_visualizers/run_tiled_camera_visualizer.py b/simulation/modules/IsaacLab/scripts/tutorials/07_visualizers/run_tiled_camera_visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..3b8bb6ac377f7ff99a48681b8d8428105e283820 --- /dev/null +++ b/simulation/modules/IsaacLab/scripts/tutorials/07_visualizers/run_tiled_camera_visualizer.py @@ -0,0 +1,185 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script demonstrates the visualizer tiled camera panel. + +.. code-block:: bash + + # Kit visualizer tiled camera panel + ./isaaclab.sh -p scripts/tutorials/07_visualizers/run_tiled_camera_visualizer.py \ + --enable_cameras --task Isaac-Velocity-Rough-Anymal-D-v0 --num_envs 256 --viz kit + + # Newton visualizer tiled camera panel + ./isaaclab.sh -p scripts/tutorials/07_visualizers/run_tiled_camera_visualizer.py \ + --task Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor-v0 --num_envs 25 --viz newton + +""" + +from __future__ import annotations + +import argparse +import contextlib +import sys + +import gymnasium as gym +import torch + +import isaaclab_tasks # noqa: F401 + +with contextlib.suppress(ImportError): + import isaaclab_tasks_experimental # noqa: F401 +from isaaclab_tasks.utils import ( + add_launcher_args, + launch_simulation, + resolve_task_config, + setup_preset_cli, +) + +KIT_DEFAULT_TASK = "Isaac-Velocity-Rough-Anymal-D-v0" +NEWTON_DEFAULT_TASK = "Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor-v0" +SUPPORTED_TILED_VISUALIZERS = {"kit", "newton"} +UNSUPPORTED_TILED_VISUALIZERS = {"rerun", "viser"} + + +def _resolve_env_regex_path(prim_path: str) -> str: + """Resolve scene config env namespace macros to the cloned-env regex.""" + return prim_path.format(ENV_REGEX_NS="/World/envs/env_.*") + + +def _requested_visualizers(args_cli: argparse.Namespace) -> list[str]: + """Return requested visualizers, defaulting to Kit for this tutorial.""" + visualizers = args_cli.visualizer or ["kit"] + visualizers = [str(visualizer).lower() for visualizer in visualizers] + + if "none" in visualizers: + raise ValueError("This demo requires a tiled-camera visualizer. Use '--viz kit' or '--viz newton'.") + unsupported = sorted(set(visualizers) & UNSUPPORTED_TILED_VISUALIZERS) + if unsupported: + raise ValueError( + "The visualizer tiled camera panel is only implemented for Kit and Newton. " + f"Unsupported selection: {unsupported}." + ) + unknown = sorted(set(visualizers) - SUPPORTED_TILED_VISUALIZERS) + if unknown: + raise ValueError(f"Unknown visualizer selection for this demo: {unknown}.") + return visualizers + + +def _make_kit_visualizer_cfg(env_cfg): + """Create the Kit tiled-camera visualizer for the selected task.""" + from isaaclab_visualizers.kit import KitVisualizerCfg + + visualizer_cfg = KitVisualizerCfg() + visualizer_cfg.tiled_cam_view = True + visualizer_cfg.tiled_cam_num = 36 + + ego_cam_cfg = getattr(env_cfg.scene, "ego_cam", None) + if ego_cam_cfg is not None: + visualizer_cfg.tiled_cam_prim_path = _resolve_env_regex_path(ego_cam_cfg.prim_path) + visualizer_cfg.tiled_cam_eye = None + visualizer_cfg.tiled_cam_target_prim_path = None + return visualizer_cfg + + visualizer_cfg.tiled_cam_prim_path = None + # Here is an alternative eye position for a top down view + # visualizer_cfg.tiled_cam_eye = (0.0, 0.0, 5.0) + visualizer_cfg.tiled_cam_eye = (3.0, 3.0, 3.0) + visualizer_cfg.tiled_cam_target_prim_path = "/World/envs/*/Robot/base" + return visualizer_cfg + + +def _make_newton_visualizer_cfg(env_cfg): + """Create the Newton tiled-camera visualizer for the selected task.""" + from isaaclab_visualizers.newton import NewtonVisualizerCfg + + visualizer_cfg = NewtonVisualizerCfg() + visualizer_cfg.tiled_cam_view = True + visualizer_cfg.tiled_cam_num = 12 + + ego_cam_cfg = getattr(env_cfg.scene, "ego_cam", None) + if ego_cam_cfg is not None: + visualizer_cfg.tiled_cam_prim_path = _resolve_env_regex_path(ego_cam_cfg.prim_path) + visualizer_cfg.tiled_cam_eye = None + visualizer_cfg.tiled_cam_target_prim_path = None + return visualizer_cfg + + # Here are other robot mounted camera options for this environment + # visualizer_cfg.tiled_cam_prim_path = "/World/envs/env_.*/Robot/left_arm_camera_sim_view_frame/left_camera" + # visualizer_cfg.tiled_cam_prim_path = "/World/envs/env_.*/Robot/right_arm_camera_sim_view_frame/right_camera" + visualizer_cfg.tiled_cam_prim_path = None + visualizer_cfg.tiled_cam_eye = (3.0, 3.0, 3.0) + visualizer_cfg.tiled_cam_target_prim_path = "/World/envs/*/Robot/base" + return visualizer_cfg + + +def _configure_visualizers(env_cfg, args_cli: argparse.Namespace) -> None: + """Attach tiled camera visualizer configs to the environment simulation config.""" + visualizers = _requested_visualizers(args_cli) + args_cli.visualizer = visualizers + env_cfg.sim.visualizer_cfgs = [ + _make_kit_visualizer_cfg(env_cfg) if visualizer == "kit" else _make_newton_visualizer_cfg(env_cfg) + for visualizer in visualizers + ] + + +def _resolve_task(args_cli: argparse.Namespace) -> str: + """Resolve the task for the selected visualizer.""" + if args_cli.task is not None: + return args_cli.task + if "newton" in _requested_visualizers(args_cli): + return NEWTON_DEFAULT_TASK + return KIT_DEFAULT_TASK + + +# add argparse arguments +parser = argparse.ArgumentParser(description="Showcase the Kit/Newton visualizer tiled camera panel.") +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.") +# append AppLauncher cli args +add_launcher_args(parser) +args_cli, hydra_args = setup_preset_cli(parser) +args_cli.task = _resolve_task(args_cli) +sys.argv = [sys.argv[0]] + hydra_args + + +def main(): + """Run a random-action environment with a tiled camera visualizer.""" + # parse configuration via Hydra (supports preset selection, e.g. presets=newton_mjwarp) + env_cfg, _ = resolve_task_config(args_cli.task, "") + _configure_visualizers(env_cfg, args_cli) + + with launch_simulation(env_cfg, args_cli): + # override with CLI arguments + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + # create environment + env = gym.make(args_cli.task, cfg=env_cfg) + + # print info (this is vectorized environment) + print(f"[INFO]: Gym observation space: {env.observation_space}") + print(f"[INFO]: Gym action space: {env.action_space}") + env.reset() + + # keep stepping until all visualizer windows have been closed + sim = env.unwrapped.sim + if not sim.visualizers: + print("[WARN]: No visualizers found. Exiting.") + env.close() + return + + while True: + if sim.visualizers and not any(v.is_running() and not v.is_closed for v in sim.visualizers): + break + with torch.inference_mode(): + actions = 2 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1 + env.step(actions) + + env.close() + + +if __name__ == "__main__": + main() diff --git a/simulation/modules/IsaacLab/source/isaaclab/changelog.d/.gitkeep b/simulation/modules/IsaacLab/source/isaaclab/changelog.d/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/modules/IsaacLab/source/isaaclab/changelog.d/fix-arm-nlopt-install.rst b/simulation/modules/IsaacLab/source/isaaclab/changelog.d/fix-arm-nlopt-install.rst new file mode 100644 index 0000000000000000000000000000000000000000..15343e41393df407a5fa61b723985d0ff79e6af9 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/changelog.d/fix-arm-nlopt-install.rst @@ -0,0 +1,12 @@ +Fixed +^^^^^ + +* Fixed ``./isaaclab.sh --install`` unnecessarily building ``nlopt==2.6.2`` on + ARM Linux (e.g. DGX Spark), where it fails with CMake 4.x. The ARM-only + ``nlopt`` pre-install and its temporary ``swig`` install were removed because + ``nlopt`` is only pulled in by Linux x86_64 dependencies. + +* Fixed unavoidable ARM source builds such as ``egl-probe==1.0.2`` failing when + CMake 4.x rejects policy compatibility older than 3.5. The installer now + temporarily sets ``CMAKE_POLICY_VERSION_MINIMUM=3.5`` during ARM dependency + builds. diff --git a/simulation/modules/IsaacLab/source/isaaclab/config/extension.toml b/simulation/modules/IsaacLab/source/isaaclab/config/extension.toml new file mode 100644 index 0000000000000000000000000000000000000000..f21e69af563f9d7cd8721a630117cec98b1749c5 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/config/extension.toml @@ -0,0 +1,43 @@ +[package] + +# Note: Semantic Versioning is used: https://semver.org/ +version = "6.1.17" + +# Description +title = "Isaac Lab framework for Robot Learning" +description="Extension providing main framework interfaces and abstractions for robot learning." +readme = "docs/README.md" +repository = "https://github.com/isaac-sim/IsaacLab" +category = "robotics" +keywords = ["kit", "robotics", "learning", "ai"] + +[python.pipapi] +requirements = [ + "numpy", + "prettytable==3.3.0", + "toml", + "lazy_loader>=0.4", + "hidapi", + "gymnasium==0.29.0", + "trimesh", + "websockets" +] + +modules = [ + "numpy", + "prettytable", + "toml", + "lazy_loader", + "hid", + "gymnasium", + "trimesh", + "websockets" +] + +use_online_index=true + +[core] +reloadable = false + +[[python.module]] +name = "isaaclab" diff --git a/simulation/modules/IsaacLab/source/isaaclab/docs/CHANGELOG.rst b/simulation/modules/IsaacLab/source/isaaclab/docs/CHANGELOG.rst new file mode 100644 index 0000000000000000000000000000000000000000..c0f341247e6d628c46843714da782f6c1c33c03a --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/docs/CHANGELOG.rst @@ -0,0 +1,8980 @@ +Changelog +--------- + +6.1.17 (2026-07-24) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added support for an optional ``demo_recorder_cfg_entry_point`` Gym registry entry in demonstration collection. + +Fixed +^^^^^ + +* Fixed simulator tests and examples to use the available legacy Franka Panda USD asset. + + +6.1.16 (2026-07-14) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed docker installs deleting ``pillow`` from Isaac Sim's + ``omni.kit.pip_archive`` prebundle by relaxing the exact ``pillow==12.2.0`` + pin to a ``>=12.1.1`` floor. An exact pin below the version prebundled by a + future Isaac Sim base image forces a downgrade that deletes the prebundled + copy, dangling the per-file symlink farm on aarch64 and breaking extension + startup. + + +6.1.15 (2026-07-11) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added a fail-loud post-install check that aborts installation when pip + operations leave a prebundled Isaac Sim package with a dangling + ``__init__.py`` (other new dangling symlinks are reported as warnings). +* Fixed the ``isaacsim.robot_motion.pink`` extension failing to load after + installation by moving the ``pin-pink`` pin from ``3.1.0`` to ``3.3.0``, which + provides ``pink.exceptions.NoSolutionFound`` while staying below the pink 3.4 + task-API break. Environments installed manually should update with + ``pip install pin-pink==3.3.0``. + + +6.1.14 (2026-06-30) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed a crash (``undefined symbol: ncclDevCommCreate``) when launching the Isaac Sim + streaming app (e.g. ``isaac-sim.streaming.sh`` / ``runheadless.sh``) from an Isaac Lab + install against Isaac Sim 6.0. Isaac Sim's deprecated ``omni.isaac.ml_archive`` prebundle + ships its own PyTorch and NCCL while Isaac Lab installs a different pinned PyTorch; on + launch paths that do not import Isaac Lab (which otherwise deprioritizes the prebundle on + ``sys.path``), the two NCCL copies collide and the prebundled torch binds to the wrong + one. The install step that repoints the prebundle to the active environment now uses + overlayfs-safe filesystem operations, so it works inside the Docker image build (where it + previously failed silently with ``EXDEV`` / ``EINVAL``) and fails loudly if a shadowing + copy remains. + + +6.1.13 (2026-06-29) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated the Isaac Sim pip dependency to ``6.0.1.0`` and aligned the + ``pillow`` dependency with Isaac Sim by pinning ``pillow==12.2.0``. + + +6.1.12 (2026-06-18) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed Linux ARM installation by pre-installing ``nlopt==2.6.2`` before + Isaac Lab dependencies are resolved, and by keeping ``swig`` available in + Docker only until dependency installation completes. + + +6.1.11 (2026-06-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :func:`~isaaclab.sim.utils.newton_model_utils.replace_newton_shape_colors` incorrectly + keeping Newton's random palette colors for environments 1–N when USD cloning is skipped + Shape labels for non-source environments now resolve to the clone-plan source prim so + the correct USD material color is applied to all environments. + + +6.1.10 (2026-06-14) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated the ``newton`` extra installation message to list the Newton GL + viewer's ``pyglet`` dependency. + +Fixed +^^^^^ + +* Fixed SimulationContext reset ordering so initial visualizers are created before the timeline play event pump can invalidate freshly created PhysX tensor views. +* Fixed Pink IK USD-to-URDF conversion to use Isaac Sim's URDF exporter instead of the unavailable ``nvidia.srl`` package. + + +6.1.9 (2026-06-13) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Prevented MARL adapter wrappers from raising destructor tracebacks when destroyed by setting their environment lifecycle state explicitly. + + +6.1.8 (2026-06-12) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed OVRTX-backed Newton scenes to keep USD cloning enabled and preserve env-local camera transforms in heterogeneous clone plans. + + +6.1.7 (2026-06-11) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed LEAPP export of :func:`isaaclab.envs.mdp.projected_gravity` to expose + root orientation as the graph input and compute projected gravity inside the + exported graph. +* Fixed a quaternion convention bug in :class:`~isaaclab.controllers.rmp_flow.RmpFlowController` + where the end-effector orientation target was re-converted to ``(x, y, z, w)`` even though + IsaacLab quaternions are already in that order. The spurious conversion scrambled the target + orientation handed to RMPFlow, causing the arm to drift away from its commanded pose (e.g. the + Agibot RMPFlow place tasks no longer hold their reset pose under a zero relative command). +* Guarded asset and sensor destructors against Python interpreter shutdown so + callback cleanup does not touch lazy imports after import machinery is torn down. +* Fixed :func:`isaaclab.utils.string.string_to_callable` to validate lambda + expression strings before evaluating them and to evaluate them without + Python builtins. + + +6.1.6 (2026-06-10) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the ``isaaclab.python.kit`` GUI experience failing to start with a Kit + dependency-solver error on Isaac Sim builds that do not ship + ``isaacsim.robot.experimental.wheeled_robots`` or + ``isaacsim.robot.wheeled_robots.nodes``. These extensions are not imported by + Isaac Lab and are now declared optional, so the experience loads regardless of + the Isaac Sim build. +* Fixed livestream launch handling to reject Isaac Sim full-app experiences + that depend on ``isaacsim.exp.full`` and to ensure Kit-backed examples open + a Kit visualizer by default when needed. + + +6.1.5 (2026-06-09) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed ``isaaclab`` install metadata to include ``isaaclab_ppisp`` as a peer extension. +* Fixed local asset retrieval for MDL files that import sibling MDL modules, such as Hospital materials importing OmniUe4 modules. +* Prevented environment destructors from emitting cleanup tracebacks after Python import shutdown begins. +* Fixed :func:`~isaaclab.controllers.utils.import_lula` failing to locate the ``lula`` module on + pip-based Isaac Sim installs by extending :func:`~isaaclab.controllers.utils.find_lula_prebundle_dir` + to also search the ``extscache/-`` and ``extsDeprecated/`` layouts used by pip + installs (the Isaac Sim 6.0 pip packages ship ``isaacsim.robot_motion.lula`` under + ``extsDeprecated``, where the Kit resolver reports it as unavailable), in addition to the + ``exts/`` layout used by binary installs. :func:`~isaaclab.controllers.utils.import_lula` now + adds the prebundle to ``sys.path`` before attempting to enable the Kit extension, avoiding a spurious + ``Failed to resolve extension dependencies`` error logged when Kit tries to enable the deprecated + ``isaacsim.robot_motion.lula`` extension even though ``lula`` itself loads correctly. When ``lula`` + still cannot be found, a clear, actionable :class:`ModuleNotFoundError` is raised instead of the bare + import error. + + +6.1.4 (2026-06-08) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a scene-data backend hook for active ``InteractiveScene`` access so + backends can source scene-owned entity transforms without relying on global + rigid-body views, and visualizers can discover scene-owned contact sensors. + +Changed +^^^^^^^ + +* Clarified ``--video`` behavior when multiple video-capable visualizers are active: + Gymnasium video recording captures one ``env.render()`` stream, with Kit taking + priority over Newton. +* Updated the visualizer tiled camera tutorial to show generated Kit cameras and + existing Newton robot-mounted camera streams with matching documentation figures. + +Fixed +^^^^^ + +* Improved visualizer tiled-camera errors when ``tiled_cam_prim_path`` is set but + the scene has no Isaac Lab ``Camera`` sensors, and clarified the camera-mode + documentation for Cartpole camera tasks. +* Fixed remote asset mirroring to include textures referenced by downloaded MDL materials. + + +6.1.3 (2026-06-07) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed a memory leak in :meth:`~isaaclab.envs.ManagerBasedEnv.close`, + :meth:`~isaaclab.envs.DirectRLEnv.close` and :meth:`~isaaclab.envs.DirectMARLEnv.close` + where the cached observation buffers and the :class:`gym.spaces` observation/action + spaces were never released, causing host and GPU memory to accumulate on each + environment construct/teardown cycle. +* Fixed the ``create_cube_base_env`` tutorial crashing at startup with a ``RuntimeError`` + because its prestartup USD-level randomization terms ran while scene replication was enabled. + + +6.1.2 (2026-06-06) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed :class:`~isaaclab.controllers.rmp_flow.RmpFlowController` to load RMPFlow directly from the + ``lula`` library on every backend, instead of going through the Isaac Sim Kit motion-generation + extension. ``lula`` is importable both under Kit and kitless (e.g. the Newton visualizer), giving a + single code path. The ``rmp_flow_smoothed`` variant is now available in both modes as well. + +Removed +^^^^^^^ + +* Removed obsolete ``scripts/tools/wrap_warp_to_torch.py`` migration helper. Use + :attr:`~isaaclab.utils.warp.ProxyArray.torch` when tensor interop is needed. + +Fixed +^^^^^ + +* Fixed missing :mod:`isaaclab.cloner` lazy exports for clone-plan source resolution. + + +6.1.1 (2026-06-05) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed compliant-contact USD spawning to use + :class:`~isaaclab_physx.sim.spawners.materials.PhysxRigidBodyMaterialCfg` + instead of the deprecated rigid-body material alias. + + +6.1.0 (2026-06-02) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.sim.ServiceLocator` and exposed it as + :attr:`~isaaclab.sim.SimulationContext.services`. + + Backend-specific caches can be registered and retrieved using subscript + syntax (``services[cls] = instance``, ``services[cls]``). Services with + a ``close()`` method are automatically closed on ``clear_instance()``. +* Added :class:`~isaaclab.sensors.camera.CameraISPMode` (values ``AUTO_CAMERA`` and ``AUTO_ANY``) and the :attr:`~isaaclab.sensors.camera.CameraCfg.isp_cfg` field to author or auto-discover an ISP cfg (:class:`~isaaclab_ppisp.PpispCfg`) from a USD ``RenderProduct`` bound to the camera (or anywhere on the stage as a fallback). +* Added :attr:`~isaaclab.renderers.RenderBufferKind.RGB_HDR` to the renderer output contract so backends can advertise a 3-channel float HDR AOV. +* Added :meth:`~isaaclab.renderers.BaseRenderer.prepare_cameras` hook so backends can author per-camera USD overrides. +* Added :class:`~isaaclab.renderers.CameraRenderSpec`, an immutable description of a tiled camera passed to render backends so they no longer hold a reference to the camera sensor instance. +* Added shared visualizer defaults for CLI-created visualizer configs. +* Auto-install ``libgl1-mesa-dev``, ``libopengl-dev``, ``libglx-dev``, + ``libx11-dev``, ``libxcursor-dev``, ``libxi-dev``, ``libxinerama-dev``, + and ``libxrandr-dev`` on ARM when sudo is available, so + ``./isaaclab.sh -i`` can build ``imgui-bundle`` from source without a + separate provisioning step. +* Added :func:`~isaaclab.utils.string.compile_template_pattern` to compile a slotted template + (with ``{}`` slots expanding to a caller-provided regex fragment) into a regular expression. +* Added :func:`~isaaclab.utils.string.strip_templated_prefix` to strip a templated prefix + (with ``{}`` slots matching one path segment each) from a string and return the remainder. +* Added multi-GPU troubleshooting documentation describing the NCCL hang that can occur when + ``CUDA_VISIBLE_DEVICES`` selects a subset of a node's GPUs, including the + ``NCCL_P2P_DISABLE=1`` workaround and an explanation of why it is not needed when all GPUs + are visible. + +Changed +^^^^^^^ + +* Updated the ``usd-core`` dependency to 25.11.0 to match Kit 110.1.1. +* Renamed the ``./isaaclab.sh -i none`` core-only install selector to + ``./isaaclab.sh -i core`` for clarity (the install still ships the + core submodules, so ``"core"`` describes the result better than + ``"none"``). +* Updated shared visualizer tiled camera defaults for the visualizer integration test coverage. +* ``./isaaclab.sh -i mimic`` now also installs ``isaaclab_teleop`` as an editable + submodule, since :mod:`isaaclab_mimic` declares it as a required dependency. +* Updated installation, quickstart, and pip documentation to match ``./isaaclab.sh -i`` + install tokens and pip wheel extras. +* Regenerated the environments overview table from task configuration metadata. + +Fixed +^^^^^ + +* Fixed visualizer tiled camera defaults and camera pose helpers so tiled camera views remain opt-in and respect selected environment ids. +* Fixed ``scripts/tutorials/01_assets/add_new_robot.py`` failing at the Jetbot + velocity-target setter when the action was a CPU ``torch.Tensor``. The + tutorial now allocates the wheel-velocity templates on ``sim.device`` and + uses :meth:`~isaaclab.assets.BaseArticulation.set_joint_velocity_target_index`. +* Fixed lazy-eval sensors (contact, IMU, PVA, joint-wrench across PhysX and Newton) + returning stale pre-reset data when :meth:`~isaaclab.scene.InteractiveScene.reset` was + called inside an environment step without a subsequent physics step (e.g. inside + :meth:`~isaaclab.envs.ManagerBasedRLEnv._reset_idx`). Each step-dependent sensor's + update kernel now skips envs whose ``timestamp`` is still ``0`` (the signal that no + physics step has occurred since the last reset), so the next ``data`` access returns + the values that the sensor's ``reset()`` populated rather than re-reading a physics + buffer that holds pre-reset values. +* Fixed ``--viz none`` parsing to use the internal disable-all sentinel. +* Fixed Kit launches hiding Isaac Lab Python ``INFO`` logs, including joint + wrench sensor initialization messages. +* Restricted the ``pytetwild`` install requirement to x86_64 platforms. + PyPI ships no aarch64 wheel and the sdist build fails on ARM + (``-m64`` hardcoded in CMake), which broke the ARM64 docker image + build. Tetrahedralization of volume deformables now degrades + gracefully on ARM64 with the existing "install pytetwild" message + instead of failing the install outright. +* Made ``./isaaclab.sh -i`` skip the ARM-only swig auto-install when + ``sudo`` is unavailable instead of crashing with a ``FileNotFoundError``. + Users on locked-down ARM containers can now run the install and + pre-provision swig themselves if they need to build nlopt from source. +* Fixed Hydra space deserialization for direct MARL environment configs so + per-agent observation and action spaces remain populated for skrl multi-agent + wrappers. +* Fixed Newton replicated-scene cloning so source clone plans are available + before sensor construction and asset USD replication is skipped for Newton + physics replication. +* Fixed :class:`~isaaclab.sim.converters.MjcfConverter` to enable the Isaac Sim MJCF importer + extension before importing MJCF assets. +* Fixed module-import-time ``from pxr import …`` in :mod:`isaaclab.sim.simulation_context`, + :mod:`isaaclab.assets.asset_base`, :mod:`isaaclab.scene.interactive_scene`, + :mod:`isaaclab.sim.spawners.from_files.from_files`, :mod:`isaaclab.sim.utils.prims`, + :mod:`isaaclab.sim.utils.queries`, :mod:`isaaclab.sim.utils.semantics`, + :mod:`isaaclab.sim.utils.stage`, and :mod:`isaaclab.sim.utils.transforms`. Previously, + ``from isaaclab.assets import Articulation`` or ``from isaaclab.sim import SimulationContext`` + forced ``pxr`` (USD) into ``sys.modules`` before :class:`~isaaclab.app.AppLauncher`, + which broke Kit's USD binding registration with a cascade of + ``TfNotice`` / ``UsdAPISchemaBase`` / ``GfVec3f`` converter errors during + ``SimulationApp.startup``. Kit-less env-cfg parsing followed by ``--visualizer kit`` + now succeeds without any pxr modules preloaded. Type hints stay under + ``TYPE_CHECKING``; where pxr is used at runtime, the ``from pxr import …`` is deferred + into the function body that needs it. +* Fixed ignored shutdown traceback from environment destructors when Python import + machinery has already finalized. +* Fixed the pip wheel build so that extensions promoted to top-level packages + (e.g. ``isaaclab_assets``, ``isaaclab_tasks``, ``isaaclab_rl``) keep their + ``config/extension.toml`` under ``isaaclab/source/`` where the bundled Kit + experience files search for them. Without this, launching a Kit app from the + wheel failed during dependency resolution with + ``isaaclab_assets ... (none found)`` before the simulator started. + + +6.0.0 (2026-05-20) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :func:`~isaaclab.sim.schemas.define_actuator_properties` to author + ``NewtonActuator`` USD prims from IsaacLab actuator configs. Lives alongside + the other ``define_*_properties`` schema writers and is invoked from the + schema-side post-spawn hook below. +* Added :meth:`~isaaclab.assets.AssetBaseCfg._post_spawn` hook (no-op by + default) invoked by :class:`~isaaclab.assets.AssetBase` after spawning the + asset. :class:`~isaaclab.assets.ArticulationCfg` overrides it to author + Newton-native actuator prims from :attr:`~isaaclab.assets.ArticulationCfg.actuators`. +* Added common deformable property and material base cfgs in :mod:`isaaclab.sim`. +* Added backend-neutral deformable asset APIs, including + :class:`~isaaclab.assets.DeformableObject`, + :class:`~isaaclab.assets.DeformableObjectCfg`, and shared base/data classes. +* Added deformable body spawner, schema, and material APIs under + :mod:`isaaclab.sim`, including + :class:`~isaaclab.sim.DeformableObjectSpawnerCfg`, + :class:`~isaaclab.sim.DeformableBodyPropertiesCfg`, + :func:`~isaaclab.sim.define_deformable_body_properties`, + :func:`~isaaclab.sim.modify_deformable_body_properties`, + :class:`~isaaclab.sim.DeformableBodyMaterialCfg`, + :class:`~isaaclab.sim.SurfaceDeformableBodyMaterialCfg`, and + :func:`~isaaclab.sim.spawn_deformable_body_material`. +* Added ``pytetwild`` as a package dependency for tetrahedral mesh generation. +* Added deformable API, migration, and tutorial documentation for + backend-neutral imports and Newton backend selection. +* Added :mod:`isaaclab.scene_data` sub-package consolidating + :class:`~isaaclab.scene_data.SceneDataProvider`, + :class:`~isaaclab.scene_data.SceneDataBackend`, and + :class:`~isaaclab.scene_data.SceneDataFormat` in a single import location. + +Changed +^^^^^^^ + +* :class:`~isaaclab.assets.BaseArticulation` no longer imports + ``isaaclab_newton`` from its ``__init__``. Newton-native actuator authoring + now flows through the generic ``_post_spawn`` hook on + :class:`~isaaclab.assets.AssetBaseCfg`. +* :meth:`~isaaclab.physics.PhysicsManager.set_decimation` now has an explicit + ``pass`` body so the base class is consistent with the other no-op + classmethods. +* Removed temporary startup and runtime debug breadcrumbs from core simulation and environment setup logs. +* Changed deformable spawners to accept backend-specific deformable property and + material cfgs. Use PhysX cfgs from :mod:`isaaclab_physx.sim` or Newton cfgs + from :mod:`isaaclab_newton.sim`. +* Changed deformable demos and tutorials to use the backend-neutral + :mod:`isaaclab.assets` and :mod:`isaaclab.sim` APIs with selectable PhysX or + Newton backends. +* Changed USD spawning to support deformable objects whose USD assets contain + embedded tetrahedral mesh data. +* **Breaking:** Renamed :class:`~isaaclab.sim.spawners.meshes.MeshSquareCfg` + to :class:`~isaaclab.sim.spawners.meshes.MeshRectangleCfg` and + :func:`~isaaclab.sim.spawners.meshes.spawn_mesh_square` to + :func:`~isaaclab.sim.spawners.meshes.spawn_mesh_rectangle`. The ``size`` + attribute is now a ``tuple[float, float]`` of X- and Y-axis lengths instead + of a single edge length. Migrate ``MeshSquareCfg(size=s)`` to + ``MeshRectangleCfg(size=(s, s))``. +* **Breaking:** Moved :class:`~isaaclab.scene_data.SceneDataProvider` from + :mod:`isaaclab.scene.scene_data_provider` and + :class:`~isaaclab.scene_data.SceneDataBackend` / + :class:`~isaaclab.scene_data.SceneDataFormat` from :mod:`isaaclab.physics` + to the new :mod:`isaaclab.scene_data` sub-package. Update imports:: + + # before + from isaaclab.scene.scene_data_provider import SceneDataProvider + from isaaclab.physics import SceneDataBackend, SceneDataFormat + + # after + from isaaclab.scene_data import SceneDataProvider, SceneDataBackend, SceneDataFormat + +Deprecated +^^^^^^^^^^ + +* Deprecated generic deformable property and material cfgs in favor of + ``PhysxDeformableBodyPropertiesCfg``, ``PhysxDeformableBodyMaterialCfg``, + ``PhysxSurfaceDeformableBodyMaterialCfg``, ``NewtonDeformableBodyPropertiesCfg``, + ``NewtonDeformableBodyMaterialCfg``, and ``NewtonSurfaceDeformableBodyMaterialCfg``. + +Fixed +^^^^^ + +* Fixed three places where ``OvPhysxManager`` was misclassified as the + PhysX backend by a substring/schema match: + + - :meth:`~isaaclab.sensors.SensorBase._register_callbacks` matched + ``"physx" in physics_mgr_cls.__name__.lower()`` to gate the PhysX + ``IsaacEvents.PRIM_DELETION`` import — the substring also matches + ``"OvPhysxManager"``, so the ``isaaclab_physx`` import fired in + kitless OVPhysX mode and raised + :exc:`ModuleNotFoundError` because ``omni.physics.tensors`` is not + loaded. Switched to an exact ``physics_mgr_cls.__name__ == + "PhysxManager"`` match. + - :meth:`~isaaclab.assets.AssetBase.set_debug_vis` had the same + substring check guarding an ``import omni.kit.app`` call, which + would fire for OVPhysX-backed assets and break under + ``./scripts/run_ovphysx.sh``. Switched to an exact + ``"PhysxManager"`` match. + - :meth:`~isaaclab.physics.SceneDataProvider._get_backend` used + ``"physx" in manager_name`` to dispatch the backend factory; this + silently routed ``OvPhysxManager`` to the PhysX scene-data + provider. Switched to exact ``"PhysxManager"`` / + ``"NewtonManager"`` matches and an explicit ``ValueError`` for + unknown managers. +* Made + :attr:`~isaaclab.scene.InteractiveScene.physics_scene_path` accept a + bare :class:`pxr.UsdPhysics.Scene` prim as a fallback when no prim + with ``PhysxSceneAPI`` applied is on the stage. Kitless OVPhysX + does not load the ``omni.physx`` schema, so the auto-created scene + prim only carries the stock USD type. PhysX-backed flows continue + to prefer the ``PhysxSceneAPI`` prim. +* Fixed a per-step performance regression in :func:`~isaaclab.envs.mdp.events.apply_external_force_torque` + when the event was configured with all-zero ``force_range`` and ``torque_range`` (a common default + for tasks that declare the event term but apply no disturbance). The event was unconditionally + sampling zero wrenches and routing them through the dual-buffer ``WrenchComposer`` introduced in + PR #5265, paying the full per-step compose-and-apply cost in + :meth:`~isaaclab.assets.Articulation.write_data_to_sim` for what is semantically a no-op. The + function now returns early when both ranges are exactly zero. This restores the H1, G1, and + Anymal-C ``Velocity-Rough`` throughput observed prior to PR #5265. Behaviour for non-zero ranges + is unchanged. +* Fixed visualization marker backend initialization so USD markers remain available during rendering even when standalone visualizers are not launched. +* Fixed :class:`~isaaclab.sim.views.FrameView` dispatch under the OVPhysX + backend. ``FrameView(...)`` now routes to + :class:`~isaaclab_ovphysx.sim.views.OvPhysxFrameView` instead of silently + falling through to ``FabricFrameView``, which returned stale USD spawn + poses for sensor frames riding on physics bodies. + + +5.5.1 (2026-05-19) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed a Windows fatal exception (``0xc0000139``) that crashed the process on startup when + running any :class:`~isaaclab.envs.ManagerBasedRLEnv`-based script (e.g. ``skrl/play.py``) + on machines where ``h5py``'s native DLL could not be loaded. The ``import h5py`` in + :class:`~isaaclab.utils.datasets.HDF5DatasetFileHandler` was a top-level statement that + executed unconditionally at import time. It is now deferred to the individual methods that + open or create HDF5 files, so the DLL is only loaded when dataset recording is actually used. + + +5.5.0 (2026-05-18) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed the installation model of :meth:`~isaaclab.cli.commands.install.command_install` + from per-submodule selection to a three-tier system. All core submodules + (``isaaclab``, ``isaaclab_assets``, ``isaaclab_contrib``, ``isaaclab_experimental``, + ``isaaclab_newton``, ``isaaclab_ov``, ``isaaclab_ovphysx``, ``isaaclab_physx``, + ``isaaclab_rl``, ``isaaclab_tasks``, ``isaaclab_tasks_experimental``, + ``isaaclab_visualizers``) + are now always installed by ``./isaaclab.sh -i``. Optional submodules + (``mimic``, ``teleop``) and automatic extra feature sets + (``newton``, ``rl[...]``, ``visualizer[...]``) are installed by ``./isaaclab.sh -i`` + / ``./isaaclab.sh -i all``. + Optional dependency extras require selectors, so rlinf dependencies are + installed with ``contrib[rlinf]`` and the ``ovrtx`` / ``ovphysx`` wheels are installed + with ``ov[ovrtx]``, ``ov[ovphysx]``, or ``ov[all]``. Old per-submodule tokens (e.g. + ``assets``, ``tasks``, ``physx``) now emit a warning and are skipped gracefully. + Migrate using the table below: + + +----------------------------------------------+-------------------------------------------+ + | Old command | New command | + +==============================================+===========================================+ + | ``./isaaclab.sh -i assets,tasks,physx`` | ``./isaaclab.sh -i none`` | + +----------------------------------------------+-------------------------------------------+ + | ``./isaaclab.sh -i assets,tasks,ov,rl[...]`` | ``./isaaclab.sh -i ov[all],rl[...]`` | + +----------------------------------------------+-------------------------------------------+ + | ``./isaaclab.sh -i newton,rl[all]`` | unchanged | + +----------------------------------------------+-------------------------------------------+ + | ``./isaaclab.sh -i mimic,teleop`` | unchanged | + +----------------------------------------------+-------------------------------------------+ + | ``uv pip install isaaclab[tasks,rl,assets]`` | ``uv pip install isaaclab[all]`` | + +----------------------------------------------+-------------------------------------------+ + +* Simplified :mod:`isaaclab` package extras to ``isaacsim`` and ``all``; removed the old + per-submodule extras (``tasks``, ``rl``, ``assets``, etc.) from ``pip install isaaclab[...]``. + +Removed +^^^^^^^ + +* Removed :func:`~isaaclab.cloner.cloner_utils.is_homogeneous` because it is an implementation detail. + +Fixed +^^^^^ + +* Fixed the ``isaaclab`` wheel's ``rsl-rl`` optional dependency to install + ``rsl-rl-lib==5.0.1``, matching the version required by the RSL-RL training + scripts. +* Fixed the root ``uv run`` workflow by restoring the documented + ``pyproject.toml`` extras, the IsaacLab-only ``all`` extra, and removing the + Isaac Sim extra from the development project. +* Fixed ``uv run`` creating ``.venv`` from an active conda Python by requiring + uv-managed Python for the development project. + + +5.4.0 (2026-05-17) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.sensors.ray_caster.BaseRayCaster`, + :class:`~isaaclab.sensors.ray_caster.BaseRayCasterCamera`, + :class:`~isaaclab.sensors.ray_caster.BaseMultiMeshRayCaster`, and + :class:`~isaaclab.sensors.ray_caster.BaseMultiMeshRayCasterCamera` + carrying the backend-agnostic ray-caster logic. Backend subclasses + override only the body-tracker and target-mesh-tracker hooks. + +Changed +^^^^^^^ + +* **Breaking:** Changed :class:`~isaaclab.sensors.camera.CameraData` + camera-owned buffers to :class:`~isaaclab.utils.warp.ProxyArray`. + Access torch tensor operations through the explicit ``.torch`` view. +* :class:`~isaaclab.sensors.ray_caster.RayCaster`, + :class:`~isaaclab.sensors.ray_caster.RayCasterCamera`, + :class:`~isaaclab.sensors.ray_caster.MultiMeshRayCaster`, and + :class:`~isaaclab.sensors.ray_caster.MultiMeshRayCasterCamera` are now + :class:`~isaaclab.utils.backend_utils.FactoryBase` shims dispatching + to PhysX / Newton implementations. Cfg surface and runtime semantics + unchanged. +* Changed ray-caster camera update paths to keep pose, ray, depth, normal, + and mesh-id buffers Warp-owned internally, while exposing public camera + outputs through :class:`~isaaclab.utils.warp.ProxyArray`. + + +5.3.0 (2026-05-16) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added unified ``train`` and ``play`` console-script entry points (``isaaclab.cli:train`` + and ``isaaclab.cli:play``) that dispatch to a library-specific implementation via + ``--rl_library``. Supported libraries are ``rsl_rl``, ``rl_games``, ``skrl``, ``sb3``, + and ``rlinf``. +* Added refactored per-library train/play scripts under + ``scripts/reinforcement_learning/`` with a shared ``common.dispatch_library_entrypoint`` + helper, replacing the previous standalone per-library scripts. +* Added experimental ``uv run`` workflow allowing ``uv run train`` and ``uv run play`` + directly from the repository root without manual environment setup. See + :ref:`uv-run-training` for usage. +* Added :attr:`~isaaclab.sim.converters.UrdfConverterCfg.ros_package_paths`, + :attr:`~isaaclab.sim.converters.UrdfConverterCfg.robot_type`, + :attr:`~isaaclab.sim.converters.UrdfConverterCfg.run_asset_transformer`, + :attr:`~isaaclab.sim.converters.UrdfConverterCfg.run_multi_physics_conversion`, and + :attr:`~isaaclab.sim.converters.UrdfConverterCfg.debug_mode` config fields that mirror the + new :class:`isaacsim.asset.importer.urdf.URDFImporterConfig` options. +* Extended :attr:`~isaaclab.sim.converters.UrdfConverterCfg.collision_type` to accept + ``"Bounding Sphere"`` and ``"Bounding Cube"`` in addition to the existing ``"Convex Hull"`` + and ``"Convex Decomposition"`` values. +* Added :attr:`~isaaclab.sim.converters.MjcfConverterCfg.fix_base`, + :attr:`~isaaclab.sim.converters.MjcfConverterCfg.link_density`, + :attr:`~isaaclab.sim.converters.MjcfConverterCfg.robot_type`, + :attr:`~isaaclab.sim.converters.MjcfConverterCfg.override_gain_type`, + :attr:`~isaaclab.sim.converters.MjcfConverterCfg.override_bias_type`, + :attr:`~isaaclab.sim.converters.MjcfConverterCfg.override_gain_prm`, + :attr:`~isaaclab.sim.converters.MjcfConverterCfg.override_bias_prm`, + :attr:`~isaaclab.sim.converters.MjcfConverterCfg.run_asset_transformer`, + :attr:`~isaaclab.sim.converters.MjcfConverterCfg.run_multi_physics_conversion`, and + :attr:`~isaaclab.sim.converters.MjcfConverterCfg.debug_mode` config fields that mirror the + new :class:`isaacsim.asset.importer.mjcf.MJCFImporterConfig` options. +* Added ``--deterministic`` flag to :class:`~isaaclab.app.app_launcher.AppLauncher` so training and + rendering runs can opt into RTX/RTPT carb settings for more reproducible output after startup. +* Added :func:`~isaaclab.cloner.cloner_utils.is_homogeneous` to detect whether a :class:`~isaaclab.cloner.ClonePlan` + assigns every environment from every source (a homogeneous clone mask). +* Added :class:`~isaaclab.envs.mdp.observations.stacked_image`, a stateful + :class:`~isaaclab.managers.ManagerTermBase` that channel-stacks the last ``N`` frames + from a camera sensor. Manager-based environments can reference it in observation cfg + to add explicit temporal information for camera-based RL tasks whose renderer doesn't + supply implicit temporal data (e.g., Newton Warp). + +Changed +^^^^^^^ + +* Refactored :class:`~isaaclab.sim.converters.UrdfConverter` to delegate the full conversion + pipeline to :class:`isaacsim.asset.importer.urdf.URDFImporter` / + :class:`isaacsim.asset.importer.urdf.URDFImporterConfig`. The duplicated IsaacLab + implementations of ``_apply_fix_base``, ``_apply_link_density``, ``_apply_joint_drives``, + ``_set_drive_type_on_joints``, ``_set_target_type_on_joints``, ``_set_drive_gains_on_joints``, + and ``_fix_articulation_root_for_fixed_base`` have been removed and replaced with a thin + translation layer that maps :class:`~isaaclab.sim.converters.UrdfConverterCfg` onto the + Isaac Sim importer config. All behaviour is preserved. +* Updated :class:`~isaaclab.sim.converters.MjcfConverter` to forward the full set of + :class:`isaacsim.asset.importer.mjcf.MJCFImporterConfig` options to the Isaac Sim importer. +* Bumped the ``newton[sim]`` pin from ``v1.2.0rc2`` to ``v1.2.0`` + (stable) across :mod:`isaaclab_newton`, :mod:`isaaclab_physx` + (``[newton]`` extra), :mod:`isaaclab_visualizers` (3×), and + ``tools/wheel_builder/res/python_packages.toml``. Upstream release + notes: `newton-physics/newton v1.2.0 + `_. +* No IsaacLab-side ``mujoco`` / ``mujoco-warp`` pin change — the + transitive ``mjwarp`` bump flows in through ``newton[sim]`` since + `isaac-sim/IsaacLab#5566 + `_ dropped the + explicit pins. +* Changed Isaac Lab Docker images to run as the non-root ``isaaclab`` user by default. Use an explicit + container user override when root access is required. +* Changed :class:`~isaaclab.sensors.camera.CameraData` to expose all sensor buffers as + :class:`~isaaclab.utils.warp.ProxyArray` instead of :class:`torch.Tensor`. The fields + :attr:`~isaaclab.sensors.camera.CameraData.pos_w` (``wp.vec3f``), + :attr:`~isaaclab.sensors.camera.CameraData.quat_w_world` (``wp.quatf``), + :attr:`~isaaclab.sensors.camera.CameraData.intrinsic_matrices` (``wp.mat33f``), and all + entries in :attr:`~isaaclab.sensors.camera.CameraData.output` are now backed by warp arrays. + Use ``.torch`` for a zero-copy :class:`torch.Tensor` view or ``.warp`` to pass the array + directly to a warp kernel. Existing code using these fields as tensors (indexing, arithmetic, + :func:`torch.testing.assert_close`, etc.) continues to work via the + :class:`~isaaclab.utils.warp.ProxyArray` deprecation bridge with a one-time + :class:`DeprecationWarning`. +* Updated :meth:`~isaaclab.renderers.BaseRenderer.set_outputs` and + :meth:`~isaaclab.renderers.BaseRenderer.update_camera` in :class:`~isaaclab.renderers.BaseRenderer` + to accept :class:`~isaaclab.utils.warp.ProxyArray` arguments instead of :class:`torch.Tensor`. + +Removed +^^^^^^^ + +* Removed :func:`~isaaclab.sim.converters.urdf_utils.merge_fixed_joints` as it is now handled by the Isaac Sim URDF importer. + +Fixed +^^^^^ + +* Fixed a startup crash in :class:`~isaaclab.app.AppLauncher` when launching with a CUDA device. + Setting the current torch CUDA device used to happen before ``SimulationApp`` was created, which + imported ``torch`` (and transitively NumPy/OpenBLAS) prior to Kit's platform-info fork. On systems + where OpenBLAS's at-fork handlers were not yet safe, that fork could crash. The + ``torch.cuda.set_device`` call is now deferred until after ``SimulationApp`` starts. +* Fixed ``calculate_rotation_error`` in + ``source/isaaclab/test/controllers/test_pink_ik.py`` composing rotation matrices + with element-wise ``*`` instead of matrix multiplication ``@`` — a latent bug + from `isaac-sim/IsaacLab#3149 + `_ that surfaced as NaN after + `isaac-sim/IsaacLab#5609 + `_ added the unit-norm guard to + ``quat_from_matrix``. +* Made ``test_pink_ik`` deterministic by seeding the env (``env_cfg.seed = 42``) + in ``create_test_env``. +* Loosened the G1 Pink IK rotation tolerance from ``0.030`` rad to ``0.100`` rad + in ``pink_ik_g1_test_configs.json`` to accommodate G1's intentionally smooth IK + tuning (slower-converging than GR1T2). GR1T2 tolerance unchanged at ``0.020`` rad. + + +5.2.1 (2026-05-15) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :func:`~isaaclab.utils.math.create_rotation_matrix_from_view` returning a singular + matrix when the look-at direction was parallel to the up axis. The function now produces + a valid orthonormal frame via an alternate reference vector, and fills NaN for rows with + truly undefined forward direction (``eyes == targets`` or non-finite input). Callers + detect per-row failure with ``torch.isnan(R).any(dim=(-2, -1))``. +* Fixed :func:`~isaaclab.utils.math.quat_from_matrix` silently returning a non-unit + quaternion for non-rotation input (singular, reflection, or scale-error matrices). + Such inputs now return NaN, detectable via :func:`torch.isnan`. +* Fixed :meth:`~isaaclab.sensors.camera.Camera.set_world_poses_from_view` and + :meth:`~isaaclab.sensors.ray_caster.RayCasterCamera.set_world_poses_from_view` silently + applying garbage poses when an eye position equaled its target. Degenerate rows are now + skipped (with a logged warning), and ``ValueError`` is raised if every row in the batch + is degenerate. + + +5.2.0 (2026-05-14) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`~isaaclab.assets.BaseArticulationData.body_link_jacobian_w` and + :attr:`~isaaclab.assets.BaseArticulationData.body_com_jacobian_w` properties, + exposing the per-body geometric Jacobian referenced at the link origin and + body center of mass respectively. The pair mirrors the existing + :attr:`~isaaclab.assets.BaseArticulationData.body_link_pose_w` / + :attr:`~isaaclab.assets.BaseArticulationData.body_com_pose_w` and + :attr:`~isaaclab.assets.BaseArticulationData.body_link_vel_w` / + :attr:`~isaaclab.assets.BaseArticulationData.body_com_vel_w` exposure pattern. + Backends without a native primitive raise :class:`NotImplementedError`. +* Added :attr:`~isaaclab.assets.BaseArticulationData.mass_matrix` property, + exposing the joint-space generalized mass matrix ``M(q)``. +* Added :attr:`~isaaclab.assets.BaseArticulationData.gravity_compensation_forces` + property, exposing the joint-space gravity-loading torque vector ``g(q)``. +* Added :attr:`~isaaclab.assets.BaseArticulation.num_base_dofs` — number of + free DoFs of the floating base (``0`` for fixed-base, ``6`` for floating- + base). Use it to map an actuated-joint index ``j`` to its column in the + Jacobian / mass matrix / gravity vector via ``j + num_base_dofs``. + +* The Jacobian / mass-matrix / gravity-comp DoF axis includes the floating- + base DoFs at the front: shape ``(N, num_jacobi_bodies, 6, num_joints + + num_base_dofs)`` for the Jacobian and ``(N, num_joints + num_base_dofs, + num_joints + num_base_dofs)`` for the mass matrix. This matches the + cross-library industry convention (Pinocchio's ``nv = 6 + n_actuated``, + Drake's ephemeral floating joint, MuJoCo's ````, RBDL's + ``JointTypeFloatingBase``, OCS2's ``generalizedCoordinatesNum = + 6 + actuatedJointsNum``, iDynTree's ``getFreeFloatingMassMatrix`` + returning ``(6 + dofs, 6 + dofs)``). +* Added :attr:`~isaaclab.scene_data.SceneDataProvider.usd_stage`, + :attr:`~isaaclab.scene_data.SceneDataProvider.num_envs`, and + :meth:`~isaaclab.scene_data.SceneDataProvider.get_camera_transforms` + so visualizers and renderers can pull stage-derived data through the same + Warp-native provider that already exposes transforms. + +Changed +^^^^^^^ + +* Migrated :class:`~isaaclab.envs.mdp.actions.task_space_actions.DifferentialInverseKinematicsAction`, + :class:`~isaaclab.envs.mdp.actions.task_space_actions.OperationalSpaceControllerAction`, + and :class:`~isaaclab.envs.mdp.actions.rmpflow_task_space_actions.RMPFlowAction` + to fetch dynamic quantities through the new + :class:`~isaaclab.assets.BaseArticulationData` properties instead of the + PhysX-only ``root_view``. The OSC action term now also gates the + per-step mass-matrix and gravity-compensation fetches behind the + controller cfg's :attr:`inertial_dynamics_decoupling`, + :attr:`nullspace_control`, and :attr:`gravity_compensation` flags + so backends without a native primitive are not invoked when the + controller does not consume the result. +* Action terms (DiffIK / OSC / RMPFlow / Pink) compute their Jacobian + joint-axis indices via + ``[j + asset.num_base_dofs for j in joint_ids]``, which is ``0`` for + fixed-base and ``+6`` for floating-base. Pink IK previously hardcoded + a private ``_physx_floating_joint_indices_offset = 6``; that was + removed in favor of the cross-backend property. +* PhysX backend's :attr:`body_link_jacobian_w` applies the COM→origin shift to + PhysX's natively COM-referenced Jacobian. The previously-exposed + ``Articulation.get_jacobians()`` was a passthrough that returned the raw + COM-referenced Jacobian, while IK / OSC consumers also read + :attr:`body_link_pose_w` as the EE pose setpoint — a frame mismatch that + produced a ``ω × r_com_w`` per-body bias in tracking. The new property + reads the same engine buffer and applies the shift so ``J · q_dot`` matches + ``body_link_lin_vel_w``. Consumers that intentionally want the raw + COM-referenced form can read :attr:`body_com_jacobian_w`. +* **Breaking:** :class:`~isaaclab.visualizers.base_visualizer.BaseVisualizer` + subclasses now receive a + :class:`~isaaclab.scene_data.SceneDataProvider` in + :meth:`~isaaclab.visualizers.base_visualizer.BaseVisualizer.initialize` + instead of the removed ``BaseSceneDataProvider``. Read environment count + from :attr:`~isaaclab.scene_data.SceneDataProvider.num_envs` + and call + :meth:`~isaaclab.scene_data.SceneDataProvider.get_camera_transforms` + on the new provider; both replace the previous ``get_metadata()`` / + ``get_camera_transforms()`` calls on the legacy interface. + +Removed +^^^^^^^ + +* **Breaking:** Removed ``isaaclab.physics.BaseSceneDataProvider``, + ``isaaclab.physics.SceneDataProvider`` (the legacy factory), + ``SimulationContext.initialize_scene_data_provider()``, and + ``SimulationContext.update_scene_data_provider()``. Use + :meth:`~isaaclab.sim.simulation_context.SimulationContext.get_scene_data_provider` + to obtain the new provider; consumers that previously called + ``get_newton_model()`` / ``get_newton_state()`` should call + ``NewtonManager.get_model()`` / ``NewtonManager.get_state()`` instead. +* Removed explicit ``mujoco`` and ``mujoco-warp`` dependencies from + :mod:`isaaclab`. These packages are not used by ``isaaclab`` core and are + now resolved transitively through Newton's ``[sim]`` extra in + :mod:`isaaclab_newton`. Users installing only the PhysX or Kit backends no + longer pull in MuJoCo. + +Fixed +^^^^^ + +* Fixed :class:`~envs.LeappDeploymentEnv` crashing on ``reset()`` with + ``AttributeError: 'LeappDeploymentEnv' object has no attribute 'extras'`` + by initializing ``self.extras`` in ``__init__``. +* Fixed ``./isaaclab.sh -p -m pip ...`` failing with ``No module named pip`` + in the conda env created from ``environment.yml`` on Linux aarch64 + (e.g. DGX Spark / GB10). The conda-forge solver was not pulling + ``pip`` in transitively on aarch64, so the resulting ``env_isaaclab`` + had no pip. ``environment.yml`` now lists ``pip`` explicitly so it + is seeded on every platform. +* Fixed ``pip install isaaclab[isaacsim,all]==3.0.0`` failing with + ``No solution found`` (UV) or ``error: resolution-too-deep`` (pip) when + resolving against ``isaacsim==6.0.0.0``. ``viser>=1.0.16`` was a base + dependency of the built ``isaaclab`` wheel and transitively requires + ``websockets>=13.1``, but ``isaacsim-kernel==6.0.0.0`` pins + ``websockets==12.0``. Moved ``viser`` to an opt-in ``viser`` extra in + ``tools/wheel_builder/res/python_packages.toml`` so the base wheel is + installable alongside ``isaacsim==6.0.0.0``. Users who want the Viser + visualizer can request it explicitly with ``isaaclab[viser]``. + + +5.1.1 (2026-05-13) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed Newton-related dependencies to use MuJoCo 3.8, MuJoCo Warp 3.8.0.2, + Warp 1.13 or newer, and the packaged Newton 1.2.0 release candidate. + +Fixed +^^^^^ + +* Fixed a spurious ``[Error][carb] Client passed into the framework is nullptr.`` + log emitted from :meth:`~isaaclab.cloner._fabric_notices.FabricNoticeBindings.initialize` + when an environment imports IsaacLab outside Kit (e.g. remote asset resolution + via ``omni.client``). The helper was passing ``clientName=None`` as a fallback + to ``tryAcquireInterfaceWithClient``; Carbonite has rejected null client names + since 2018, so the call only emitted a misleading error log and never returned + a valid interface. The fallback has been removed; the helper still fails closed + when Fabric is unavailable, with no impact on the cloning speedup when Fabric + is present. + + +5.1.0 (2026-05-12) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :meth:`~isaaclab.scene.InteractiveScene.initialize_renderers` to + pre-create renderer backends for all scene sensors with a + ``renderer_cfg`` against the shared + :class:`~isaaclab.renderers.render_context.RenderContext`. The method is + idempotent and is now invoked from + :class:`~isaaclab.envs.DirectRLEnv`, + :class:`~isaaclab.envs.DirectMARLEnv`, + :class:`~isaaclab.envs.ManagerBasedEnv`, and + :class:`~isaaclab.envs.LeappDeploymentEnv` after scene construction so + that renderer backend creation order is deterministic and front-loaded + before the first :meth:`~isaaclab.sim.SimulationContext.reset`. +* Added :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.initialize` + post-physics lifecycle hook (default no-op) that runs once per backend + after :meth:`~isaaclab.sim.SimulationContext.reset` builds physics + models. ``__init__`` now defines the pre-physics phase (eagerly invoked + by :meth:`~isaaclab.scene.InteractiveScene.initialize_renderers`) and + ``initialize`` defines the post-physics phase, letting backends whose + setup needs scene data (e.g. a built Newton model) defer that work + cleanly. Driven by + :meth:`~isaaclab.renderers.render_context.RenderContext.ensure_initialize`, + registered on + :class:`~isaaclab.physics.physics_manager.PhysicsEvent` ``PHYSICS_READY`` + by :class:`~isaaclab.sim.SimulationContext` at ``order=5`` so it fires + before sensor/asset callbacks (``order=10``). This decouples renderer + post-physics setup from camera initialization. Backends created lazily + after PHYSICS_READY are eagerly initialized at + :meth:`~isaaclab.renderers.render_context.RenderContext.get_renderer` + time. +* Added forwarding shims on :mod:`isaaclab.sim.schemas` and :mod:`isaaclab.sim` for the + Newton/MuJoCo cfg classes added in :mod:`isaaclab_newton.sim.schemas` + (:class:`NewtonRigidBodyPropertiesCfg`, :class:`NewtonJointDrivePropertiesCfg`, + :class:`NewtonCollisionPropertiesCfg`, :class:`NewtonMeshCollisionPropertiesCfg`, + :class:`NewtonMaterialPropertiesCfg`, :class:`NewtonArticulationRootPropertiesCfg`, + :class:`MujocoRigidBodyPropertiesCfg`, :class:`MujocoJointDrivePropertiesCfg`). + The shims resolve lazily on first access so importing :mod:`isaaclab.sim.schemas` + does not require :mod:`isaaclab_newton` to be installed. + +Fixed +^^^^^ + +* Fixed extension installation to honor ``pip_upgrade_dependencies`` declared + in ``config/extension.toml``. + + +5.0.0 (2026-05-11) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.cloner.ClonePlan` as the flat clone contract shared by + scene cloning, backend replication, and scene-data providers. +* Added :meth:`~isaaclab.sim.SimulationContext.get_clone_plan` and + :meth:`~isaaclab.sim.SimulationContext.set_clone_plan` for publishing the + scene's clone plan. +* Added :attr:`~isaaclab.scene.InteractiveScene.clone_plan` for consumers holding + a scene reference. +* Added explicit ``spawn_paths`` support to multi-asset spawners so scene + planning can spawn representative heterogeneous sources directly. + +Changed +^^^^^^^ + +* **Breaking:** Changed scene-data providers to build visualizer backend models + from :meth:`~isaaclab.sim.SimulationContext.get_clone_plan` instead of a + clone-time visualizer artifact. Use the published + :class:`~isaaclab.cloner.ClonePlan` for custom scene-data integrations. +* **Breaking:** Changed :class:`~isaaclab.scene.InteractiveScene` to build clone + plans directly from asset configuration, spawn representative sources in their + selected environments, and replicate from those sources instead of spawning and + discovering prototypes under ``/World/template``. +* **Breaking:** Replaced ``TemplateCloneCfg`` with + :class:`~isaaclab.cloner.CloneCfg` for clone execution settings. +* **Breaking:** Changed :func:`~isaaclab.cloner.make_clone_plan` to return a + :class:`~isaaclab.cloner.ClonePlan` object directly. +* **Breaking:** Changed clone plan publication to use + :meth:`~isaaclab.sim.SimulationContext.get_clone_plan` and + :meth:`~isaaclab.sim.SimulationContext.set_clone_plan` for the single scene + clone plan. + +Removed +^^^^^^^ + +* **Breaking:** Removed + :attr:`~isaaclab.cloner.TemplateCloneCfg.visualizer_clone_fn`, + :func:`~isaaclab.cloner.resolve_visualizer_clone_fn`, and + :class:`~isaaclab.physics.scene_data_requirements.VisualizerPrebuiltArtifacts`. + Use the :class:`~isaaclab.cloner.ClonePlan` published through + :meth:`~isaaclab.sim.SimulationContext.get_clone_plan` instead. +* **Breaking:** Removed + :meth:`~isaaclab.sim.SimulationContext.get_scene_data_visualizer_prebuilt_artifact`, + :meth:`~isaaclab.sim.SimulationContext.set_scene_data_visualizer_prebuilt_artifact`, + and + :meth:`~isaaclab.sim.SimulationContext.clear_scene_data_visualizer_prebuilt_artifact`. + Use :meth:`~isaaclab.sim.SimulationContext.get_clone_plan` / + :meth:`~isaaclab.sim.SimulationContext.set_clone_plan` instead. +* **Breaking:** Removed :func:`~isaaclab.cloner.clone_from_template`. Use + :func:`~isaaclab.cloner.make_clone_plan`, + :func:`~isaaclab.cloner.usd_replicate`, and backend physics replication + functions for direct cloning workflows. + + +4.8.2 (2026-05-10) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed Pink IK setup checks to reinstall and report the required ``daqp`` + solver when it is missing or incompatible. + + +4.8.1 (2026-05-09) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed the Pink IK task-space action base link frame lookup to read direct + body link pose data instead of slicing packed body link state. No user + migration is required. +* Added :mod:`filelock` to ``isaaclab`` install requirements. + +Fixed +^^^^^ + +* Fixed :class:`~isaaclab.assets.Articulation` joint friction API docs to clarify backend-specific semantics. +* Fixed :class:`~isaaclab.envs.mdp.actions.PinkInverseKinematicsAction` + base link pose reads to avoid deprecated body link state access. +* Fixed the sensor overview documentation to include + :class:`~isaaclab.sensors.Pva` and + :class:`~isaaclab.sensors.JointWrenchSensor`. +* Fixed the PVA sensor demo to align front-foot sensor names with their prim + paths. +* Fixed Sphinx docs build failing due to ``https://nvidia.github.io/warp/objects.inv`` returning 404. + Pinned the ``warp`` intersphinx mapping to ``/stable/``, which is where the inventory now lives. +* Fixed the sensor prim-deletion callback guard so the OvPhysX backend is not + treated as the Kit PhysX backend. +* Relaxed the ``starlette`` pin in :mod:`isaaclab` from ``==0.49.1`` to + ``>=0.46.0,<0.50`` so installs of ``isaaclab[isaacsim,all]==3.0.0`` + alongside ``isaacsim==6.0.0.0`` resolve cleanly. The transitive pin + from ``isaacsim-kernel`` -> ``fastapi==0.117.1`` requires + ``starlette<0.49.0``; the previous exact pin was mutually exclusive. +* Fixed :mod:`isaaclab.sim.spawners.from_files` failing to import on Windows + due to an unconditional ``import fcntl`` (Unix-only). The distributed-rank + USD spawn lock now uses :class:`filelock.FileLock`, which works on both + Windows and POSIX. +* Certain functions in test_math were failing non deterministically. This was caused by not setting seed values. + + +4.8.0 (2026-05-08) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Bumped Newton pin to ``v1.2.0rc2``. Pulls in IsaacLab-relevant fixes from + `newton-physics/newton#2678 `_ + and `newton-physics/newton#2720 + `_ (``SolverKamino`` + reset under ``world_mask``), the upstream tendon-scoping fix from + `newton-physics/newton#2659 + `_ ("Scope USD + custom-frequency parsing"), and a VRAM-leak fix on example reset + (`newton-physics/newton#2710 + `_). +* Newton ``v1.2.0rc2`` requires ``warp-lang==1.13.0``, ``mujoco==3.8.0``, + and ``mujoco-warp==3.8.0.1``. ``warp-lang``/``mujoco``/``mujoco-warp`` + pins live in :mod:`isaaclab` and ``tools/wheel_builder/res/python_packages.toml``; + the Newton pin is mirrored across :mod:`isaaclab_newton`, + :mod:`isaaclab_visualizers` (3×), :mod:`isaaclab_physx` (``[newton]`` + extra), and the wheel-builder TOML. +* Updated ``wp.math.transform_to_matrix`` to ``wp.transform_to_matrix`` in + :mod:`~isaaclab_newton.physics.newton_manager` and + :mod:`~isaaclab_ov.renderers.ovrtx_renderer_kernels` to match the + ``warp-lang`` 1.13 API (the ``wp.math`` namespace was removed). + + +4.7.0 (2026-05-08) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added LEAPP export support for manager-based RSL-RL policies, including + export-time observation/action annotation, recurrent actor-state handling, and + deployment through :mod:`scripts.reinforcement_learning.leapp.deploy`. +* Added a Direct workflow LEAPP export tutorial and annotated ANYmal-C example + script showing how to mark policy inputs, outputs, and persistent state with + LEAPP annotations. Direct workflow policies can be exported with + :mod:`scripts.reinforcement_learning.leapp.rsl_rl.export`, but are not yet + supported by :mod:`scripts.reinforcement_learning.leapp.deploy`. +* Added LEAPP deployment documentation describing the exported-policy validation + flow and linking the manager-based and Direct workflow export paths. +* Added LEAPP export annotations, proxy utilities, and deployment environment + support for Isaac Lab assets, sensors, commands, and manager-based environments. +* Added :class:`~isaaclab.renderers.camera_render_spec.CameraRenderSpec` so render backends + take explicit camera inputs (USD paths, :class:`~isaaclab.sensors.camera.CameraCfg`, device, + counts) instead of the :class:`~isaaclab.sensors.camera.Camera` instance. +* Added :class:`~isaaclab.renderers.render_context.RenderContext` (accessed as + :attr:`~isaaclab.sim.simulation_context.SimulationContext.render_context`) to own one or + more :class:`~isaaclab.renderers.base_renderer.BaseRenderer` instances: configurations that + compare equal under ``==`` and share the same concrete + :class:`~isaaclab.renderers.renderer_cfg.RendererCfg` class reuse a backend; distinct + types (e.g. Isaac RTX and Newton) register separate backends, each with + :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.prepare_stage` the first time a camera + with that configuration initializes. +* Added :meth:`~isaaclab.renderers.render_context.RenderContext.render_into_camera` to run + :meth:`~isaaclab.renderers.render_context.RenderContext.update_transforms` (at most once + per physics step), then :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.render` and + :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.read_output`. +* Added :meth:`~isaaclab.sim.simulation_context.SimulationContext.get_physics_step_count`. +* Added :class:`~isaaclab.cloner.ClonePlan` frozen dataclass capturing per-group + prototype-to-environment mappings (``dest_template``, ``prototype_paths``, + ``clone_mask``). Lets downstream consumers (scene data providers, mesh samplers) + read prototype geometry once and scatter to environments via the per-group mask + instead of walking per-env USD paths. +* Added :meth:`~isaaclab.sim.SimulationContext.get_clone_plans` and + :meth:`~isaaclab.sim.SimulationContext.set_clone_plans` for publishing and + consuming the cloner's per-group plan map. +* Added :attr:`~isaaclab.scene.InteractiveScene.clone_plans` property (forwards to + :meth:`~isaaclab.sim.SimulationContext.get_clone_plans`) so consumers holding a + scene reference can read the published plans without going through the sim + context. +* Added backend-agnostic :class:`~isaaclab.markers.VisualizationMarkers` support for + marker-capable Kit, Newton, Rerun, and Viser visualizers. +* Added :meth:`~isaaclab.utils.backend_utils.get_default_renderer_cfg`. to lazy load the IsaacRtxRendererCfg +* Added :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialBaseCfg`, the solver-common + base class for rigid-body physics materials. Carries the ``UsdPhysics.MaterialAPI`` standard + fields (``static_friction``, ``dynamic_friction``, ``restitution``). The PhysX-specific + compliant-contact and combine-mode fields moved to + :class:`~isaaclab_physx.sim.spawners.materials.PhysxRigidBodyMaterialCfg`. +* Added :class:`~isaaclab.sim.schemas.CollisionBaseCfg`, the solver-common base class for + collision properties. Carries :attr:`collision_enabled` (``UsdPhysics.CollisionAPI``) plus + :attr:`contact_offset` and :attr:`rest_offset` whose USD attributes are PhysX-namespaced + but are consumed by Newton's importer via the PhysX bridge resolver + (``import_usd.py:2104, 2111``). +* Added :class:`~isaaclab.sim.schemas.ArticulationRootBaseCfg`, the solver-common base class + for articulation root properties (``fix_root_link``, ``articulation_enabled``). +* Added :class:`~isaaclab.sim.schemas.MeshCollisionBaseCfg`, the solver-common base class for + mesh collision properties carrying ``mesh_approximation_name`` (writes + ``physics:approximation`` via :class:`UsdPhysics.MeshCollisionAPI`). The class-level + ``_usd_applied_schema`` metadata replaces the deprecated ``usd_api`` / ``physx_api`` + instance-field dispatch. + +Changed +^^^^^^^ + +* :class:`~isaaclab.sensors.camera.Camera` obtains a backend via + :meth:`~isaaclab.renderers.render_context.RenderContext.get_renderer` and calls + :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.create_render_data` with + a :class:`~isaaclab.renderers.camera_render_spec.CameraRenderSpec` (no + :class:`~isaaclab.sensors.sensor_base.SensorBase` reference on the public API). +* :class:`~isaaclab.scene.interactive_scene.InteractiveScene` calls + :meth:`~isaaclab.renderers.render_context.RenderContext.update_transforms` once at the start + of :meth:`~isaaclab.scene.interactive_scene.InteractiveScene.update` when + ``lazy_sensor_update`` is false; fetches that render still dedupe the same way via + ``physics_step_count`` in :class:`~isaaclab.renderers.render_context.RenderContext`. +* **Breaking:** :func:`~isaaclab.cloner.clone_from_template` now returns + ``dict[str, ClonePlan]`` instead of ``None``. Bind the result and publish it + through :meth:`~isaaclab.sim.SimulationContext.set_clone_plans` if downstream + consumers (e.g. the PhysX scene data provider's Newton-visualizer build path) + need to read the plan. +* Changed :func:`~isaaclab.envs.mdp.body_incoming_wrench` to read from + :class:`~isaaclab.sensors.JointWrenchSensor`. Pass + ``sensor_cfg=SceneEntityCfg("joint_wrench", body_names=...)`` instead of an + articulation asset config. +* Updated :class:`~isaaclab.sensors.camera.Camera` to construct its internal + :class:`~isaaclab.sim.views.FrameView` without the now-removed + ``sync_usd_on_fabric_write`` kwarg. USD attributes on camera prims are + no longer kept in sync with Fabric writes; read poses through the view's + getters instead. +* :class:`~isaaclab.sensors.camera.CameraCfg` now defaults its render_cfg to :class:`~isaaclab.renderers.RenderCfg` + :meth:`~isaaclab.utils.backend_utils.get_default_renderer_cfg` is called during __post_init__ to replace + the generic RenderCfg with the default config :class:`~isaaclab_physx.renderers.IsaacRtxRendererCfg` +* Cleaned up the schema-cfg base classes to no longer carry PhysX namespace metadata. + :class:`~isaaclab.sim.schemas.RigidBodyBaseCfg`, + :class:`~isaaclab.sim.schemas.CollisionBaseCfg`, + :class:`~isaaclab.sim.schemas.ArticulationRootBaseCfg`, and + :class:`~isaaclab.sim.schemas.JointDriveBaseCfg` now declare ``_usd_namespace = None`` and + ``_usd_applied_schema = None``. Per-field PhysX overrides for fields whose only USD path + today is the ``physx*:*`` namespace (``disable_gravity``, ``contact_offset``, + ``rest_offset``, ``articulation_enabled``, ``max_velocity``) are declared via a new + ``_usd_field_exceptions`` mapping ``applied_schema -> (namespace, {cfg_field: usd_attr})``. + When any listed field is non-None at write time, the writer applies that schema and writes + the attribute under the exception namespace; otherwise the schema is not stamped onto the + prim. PhysX subclasses (:class:`PhysxRigidBodyPropertiesCfg`, + :class:`PhysxCollisionPropertiesCfg`, :class:`PhysxArticulationRootPropertiesCfg`, + :class:`PhysxJointDrivePropertiesCfg`) now self-declare ``_usd_namespace`` and + ``_usd_applied_schema`` for their own fields. Observable behavior on standard inputs is + unchanged. +* Consolidated the per-writer schema-application loop in + :mod:`isaaclab.sim.schemas` into a single shared helper ``_apply_namespaced_schemas``. + ``modify_articulation_root_properties``, ``modify_rigid_body_properties``, + ``modify_collision_properties``, ``modify_joint_drive_properties``, + ``modify_mesh_collision_properties``, and ``spawn_rigid_body_material`` all delegate to the + helper after writing their typed-API ``UsdPhysics`` fields. The canonical exception-table + + main-namespace gating logic now lives in one place instead of being duplicated across + six call sites. +* Moved the ``max_velocity`` field from :class:`~isaaclab_physx.sim.schemas.PhysxJointDrivePropertiesCfg` + to :class:`~isaaclab.sim.schemas.JointDriveBaseCfg`. The field is the only USD path to set + Newton's ``Model.joint_velocity_limit`` and is consumed by Newton's importer. The USD + attribute written is unchanged (``physxJoint:maxJointVelocity``); existing code using + ``PhysxJointDrivePropertiesCfg(max_velocity=...)`` continues to work because the field + is inherited. +* Moved the ``disable_gravity`` field from :class:`~isaaclab_physx.sim.schemas.PhysxRigidBodyPropertiesCfg` + to :class:`~isaaclab.sim.schemas.RigidBodyBaseCfg`. PhysX honors per-body via + ``physxRigidBody:disableGravity``; Newton currently honors at scene level (partial), + documented in the field docstring. Existing code using + ``PhysxRigidBodyPropertiesCfg(disable_gravity=...)`` continues to work via inheritance. +* Documented :attr:`~isaaclab.sim.schemas.ArticulationRootPropertiesCfg.articulation_enabled` + and :attr:`~isaaclab.sim.schemas.ArticulationRootPropertiesCfg.enabled_self_collisions` + to lock their placement for the future :class:`ArticulationRootBaseCfg` / + ``PhysxArticulationRootPropertiesCfg`` split: ``articulation_enabled`` stays on the base + (single-namespace USD with verified Newton consumer); ``enabled_self_collisions`` moves + to the PhysX subclass (dual-namespace USD, with a future Newton sibling cfg owning the + ``newton:*`` namespace). +* Changed the defaults of :attr:`~isaaclab_physx.sim.spawners.materials.PhysxRigidBodyMaterialCfg.compliant_contact_stiffness`, + :attr:`compliant_contact_damping`, :attr:`friction_combine_mode`, and + :attr:`restitution_combine_mode` from concrete values (``0.0``, ``0.0``, ``"average"``, + ``"average"``) to ``None``. PhysX engine defaults match the previous concrete values, so + user-observable simulation behavior is unchanged; the difference is that these attributes + are now authored on the prim only when the user explicitly sets them (consistent with the + rest of the consumption-gated cfg layer). +* Relocated :class:`RigidBodyMaterialCfg` to :mod:`isaaclab_physx.sim.spawners.materials` and + split its fields between the new :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialBaseCfg` + (UsdPhysics-standard friction/restitution) and + :class:`~isaaclab_physx.sim.spawners.materials.PhysxRigidBodyMaterialCfg` + (PhysX-specific compliant-contact and combine-mode fields). A forwarding shim on + :mod:`isaaclab.sim.spawners.materials` and :mod:`isaaclab.sim` preserves existing imports. +* Refactored :func:`~isaaclab.sim.spawners.materials.spawn_rigid_body_material` to be + metadata-driven: it reads ``_usd_applied_schema``, ``_usd_namespace``, and + ``_usd_attr_name_map`` from the cfg class and gates ``PhysxMaterialAPI`` application on + whether the user authored at least one PhysX-namespaced field with a non-``None`` value. + Previously, the writer applied ``PhysxMaterialAPI`` unconditionally on every material spawn. +* Relocated :class:`CollisionPropertiesCfg` to :mod:`isaaclab_physx.sim.schemas` and split + its fields between the new :class:`~isaaclab.sim.schemas.CollisionBaseCfg` (solver-common + ``collision_enabled`` plus the PhysX-namespaced but Newton-consumed + ``contact_offset`` / ``rest_offset``) and + :class:`~isaaclab_physx.sim.schemas.PhysxCollisionPropertiesCfg` (PhysX-only + ``torsional_patch_radius`` / ``min_torsional_patch_radius``). A forwarding shim on + :mod:`isaaclab.sim.schemas`, :mod:`isaaclab.sim.schemas.schemas_cfg`, and + :mod:`isaaclab.sim` preserves existing imports. +* Refactored :func:`~isaaclab.sim.schemas.modify_collision_properties` to be metadata-driven + and to gate ``PhysxCollisionAPI`` application on whether the user authored at least one + PhysX-namespaced field with a non-``None`` value. Previously, the writer applied + ``PhysxCollisionAPI`` unconditionally on every collision prim, stamping the schema onto + Newton-targeted prims that only set ``collision_enabled``. +* Relocated :class:`ArticulationRootPropertiesCfg` to :mod:`isaaclab_physx.sim.schemas` and + split its fields between the new :class:`~isaaclab.sim.schemas.ArticulationRootBaseCfg` + (solver-common ``fix_root_link`` plus the PhysX-namespaced ``articulation_enabled`` which + is consumed by the IL Newton wrapper as a spawn-time guard) and + :class:`~isaaclab_physx.sim.schemas.PhysxArticulationRootPropertiesCfg` + (``enabled_self_collisions`` and PhysX TGS solver iter / sleep / stabilization thresholds). + A forwarding shim on :mod:`isaaclab.sim.schemas`, + :mod:`isaaclab.sim.schemas.schemas_cfg`, and :mod:`isaaclab.sim` preserves existing imports. +* Refactored :func:`~isaaclab.sim.schemas.modify_articulation_root_properties` to be + metadata-driven and to gate ``PhysxArticulationAPI`` application on whether the user + authored at least one PhysX-namespaced field with a non-``None`` value. Previously, the + writer applied ``PhysxArticulationAPI`` unconditionally on every articulation root, + stamping the schema onto Newton-targeted prims that only set ``fix_root_link``. +* Relocated :class:`MeshCollisionPropertiesCfg`, :class:`ConvexHullPropertiesCfg`, + :class:`ConvexDecompositionPropertiesCfg`, :class:`TriangleMeshPropertiesCfg`, + :class:`TriangleMeshSimplificationPropertiesCfg`, and :class:`SDFMeshPropertiesCfg` to + :mod:`isaaclab_physx.sim.schemas`. :class:`BoundingCubePropertiesCfg` and + :class:`BoundingSpherePropertiesCfg` stay in core because they author no PhysX schema. + A forwarding shim preserves existing imports. +* Refactored :func:`~isaaclab.sim.schemas.modify_mesh_collision_properties` to be + metadata-driven. The writer now reads ``_usd_applied_schema`` and ``_usd_namespace`` from + the cfg class instead of consulting instance-level ``usd_api`` / ``physx_api`` fields. + The standard :class:`UsdPhysics.MeshCollisionAPI` is always applied; PhysX cooking + schemas (``PhysxConvexHullCollisionAPI`` etc.) are gated on at least one + PhysX-namespaced tuning field being set. +* Relocated :class:`FixedTendonPropertiesCfg` and :class:`SpatialTendonPropertiesCfg` to + :mod:`isaaclab_physx.sim.schemas` as :class:`PhysxFixedTendonPropertiesCfg` and + :class:`PhysxSpatialTendonPropertiesCfg`. Tendons are a PhysX-only feature; no Newton + equivalent exists. A forwarding shim on :mod:`isaaclab.sim.schemas`, + :mod:`isaaclab.sim.schemas.schemas_cfg`, and :mod:`isaaclab.sim` preserves existing + imports. + +Deprecated +^^^^^^^^^^ + +* Deprecated the ``usd_api`` and ``physx_api`` instance attributes on the mesh-collision + cfg classes in favor of class-level ``_usd_applied_schema`` metadata. Reading these + attributes still works through one minor version but emits a ``DeprecationWarning``. + Scheduled for removal in 5.0. + +Removed +^^^^^^^ + +* **Breaking:** Removed + :attr:`~isaaclab.cloner.TemplateCloneCfg.visualizer_clone_fn`, + :func:`~isaaclab.cloner.resolve_visualizer_clone_fn`, and + :class:`~isaaclab.physics.scene_data_requirements.VisualizerPrebuiltArtifacts`. + Scene data providers now build backend models from the + :class:`~isaaclab.cloner.ClonePlan` map via + :meth:`~isaaclab.sim.SimulationContext.get_clone_plans` instead of receiving a + prebuilt artifact through a clone-time callback. +* **Breaking:** Removed + :meth:`~isaaclab.sim.SimulationContext.get_scene_data_visualizer_prebuilt_artifact`, + :meth:`~isaaclab.sim.SimulationContext.set_scene_data_visualizer_prebuilt_artifact`, + and + :meth:`~isaaclab.sim.SimulationContext.clear_scene_data_visualizer_prebuilt_artifact`. + Use :meth:`~isaaclab.sim.SimulationContext.get_clone_plans` / + :meth:`~isaaclab.sim.SimulationContext.set_clone_plans` instead. +* Removed ``BaseArticulationData.body_incoming_joint_wrench_b``. Add + :class:`~isaaclab.sensors.JointWrenchSensorCfg` to the scene and read + :attr:`~isaaclab.sensors.JointWrenchSensorData.force` and + :attr:`~isaaclab.sensors.JointWrenchSensorData.torque` instead. + +Fixed +^^^^^ + +* Pinned ``omniverseclient`` to ``2.71.1.7015``. +* Fixed :meth:`~isaaclab.sim.schemas.modify_joint_drive_properties` and + :meth:`~isaaclab.sim.schemas.modify_rigid_body_properties` so that ``PhysxJointAPI`` and + ``PhysxRigidBodyAPI`` are applied only when the user authored at least one PhysX-namespaced + field with a non-``None`` value. Previously, schema application was gated on class-level + metadata being defined, which caused Newton-targeted prims to receive PhysX schemas even + when the user only set base ``UsdPhysics``-standard fields. + + +4.6.27 (2026-05-01) +~~~~~~~~~~~~~~~~~~~ + +* Added :class:`~isaaclab.sensors.JointWrenchSensor`. + + +4.6.26 (2026-05-01) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``Metrics/success_rate`` tracking to benchmark scripts. The result is always logged + to the benchmark artifact; ``--check_success`` additionally early-stops training on convergence. + + +4.6.25 (2026-04-28) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed ``isaaclab.bat --install`` on Windows 11 failing with + ``'"setuptools<82.0.0"': Expected package name at the start of dependency + specifier``. ``extract_python_exe`` now prefers the underlying + ``kit/python/python.exe`` over Isaac Sim's ``python.bat`` so child pip calls + bypass the cmd.exe quoting hop that was preserving the literal double + quotes through to pip's argv. The fallback ``cmd.exe /c`` wrapper for + ``.bat``/``.cmd`` invocations now also uses caret-escaping + (e.g. ``setuptools^<82.0.0``) for metacharacters instead of double-quoting, + so the bat-hop path no longer leaks quotes. + + +4.6.24 (2026-04-28) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed ``./isaaclab.sh -i`` failing to build the ``nlopt`` wheel on ARM Linux + (e.g. DGX Spark) when the host image is missing SWIG. The bare-metal install + path now mirrors ``docker/Dockerfile.base``: on ARM Linux it installs + ``swig`` via apt and pre-installs ``nlopt==2.6.2`` with + ``--no-build-isolation`` so later submodule installs skip the source-build + fallback. + + +4.6.23 (2026-04-30) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`~isaaclab.assets.AssetBaseCfg.disable_shape_checks` configuration option + to skip shape/dtype validation in setter and writer methods, reducing per-call overhead + in production workloads. + +Fixed +^^^^^ + +* Fixed cross-backend asset interface regression tests to cover tensor views passed to + backend index resolution helpers. + + +4.6.22 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* :class:`~isaaclab.renderers.BaseRenderer` now publishes a renderer-owned + output contract via ``supported_output_types() -> {RenderBufferKind: RenderBufferSpec}``. + :class:`~isaaclab.sensors.camera.CameraData` allocates buffers for the + intersection of the requested ``data_types`` and the contract; ``rgb`` is + exposed as a view into ``rgba`` when both are published. Requested types + the active backend cannot produce are dropped with a single warning instead + of being silently discarded later. +* :class:`~isaaclab_ov.renderers.OVRTXRenderer` now writes rendered tiles + directly into the torch storage backing ``camera.data.output``, eliminating + the per-frame ``wp.copy`` bridge. +* Moved Kit/RTX-only logic out of :class:`~isaaclab.sensors.camera.Camera` + into :class:`~isaaclab_physx.renderers.IsaacRtxRenderer`. + +Deprecated +^^^^^^^^^^ + +* Deprecated RTX-flavored fields on :class:`~isaaclab.sensors.camera.CameraCfg` + (``semantic_filter``, ``colorize_semantic_segmentation``, + ``colorize_instance_segmentation``, ``colorize_instance_id_segmentation``, + ``semantic_segmentation_mapping``, ``depth_clipping_behavior``); set them on + :attr:`~isaaclab.sensors.camera.CameraCfg.renderer_cfg` instead. + + +4.6.21 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed ProxyArray migration guidance and static regression checks to cover + deprecated ``wp.to_torch(proxy_array)`` usage and direct tensor/wp.array + method calls on data properties. + + +4.6.20 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :func:`~isaaclab.utils.checked_apply` for forwarding declared + fields from an Isaac Lab configclass onto an external dataclass + (typically an upstream library config object). Raises + :class:`AttributeError` if the target is missing a declared field, so + upstream renames surface at startup instead of as silent no-ops. +* Added an opt-in runtime detector on :class:`~isaaclab.utils.warp.ProxyArray` + that emits a :class:`UserWarning` with the call site (``stacklevel=2``) on + every ``.torch`` read of a ``wp.quatf``-typed array when the + ``WARN_ON_TORCH_QUATF_ACCESS`` environment variable is set to ``"1"``. + Helps users find code that still assumes Isaac Lab 2.x's ``(w, x, y, z)`` + quaternion convention after the migration to Isaac Lab 3.x's + ``(x, y, z, w)`` convention. Documented in the Isaac Lab 3.0 migration + guide as a complement to the source-level quaternion finder tool. + + +4.6.19 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Marked :meth:`~isaaclab.envs.manager_based_rl_mimic_env.ManagerBasedRLMimicEnv.get_subtask_start_signals` and + :meth:`~isaaclab.envs.manager_based_rl_mimic_env.ManagerBasedRLMimicEnv.get_subtask_term_signals` with + ``@optional_method``. + + +4.6.18 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated the :class:`~isaaclab.cloner.TemplateCloneCfg` docstring example to import + ``get_current_stage`` from :mod:`isaaclab.sim.utils.stage` instead of + ``isaacsim.core.experimental.utils.stage``, aligning with the Isaac Lab API. +* Added a "Migration off Deprecated Isaac Sim APIs" section to the Isaac Lab 3.0 + migration guide (``docs/source/migration/migrating_to_isaaclab_3-0.rst``) that maps + deprecated ``isaacsim.core.*`` paths to their recommended replacements, preferring + Isaac Lab in-tree APIs (``isaaclab.sim.utils.*``, :class:`~isaaclab.sim.views.FrameView`, + :mod:`~isaaclab.cloner`) over the ``isaacsim.core.experimental.*`` fallbacks where + an Isaac Lab API exists. + +Fixed +^^^^^ + +* Fixed :class:`~isaaclab.envs.mdp.randomize_visual_color` and + :class:`~isaaclab.envs.mdp.randomize_visual_texture` failing with + ``'rtx::neuraylib::MdlModuleId' for '' is Invalid`` on Replicator >= 1.13.0. + Kit's ``omni_usd_resolver`` intentionally returns an empty string when resolving + builtin MDL short-names such as ``OmniPBR.mdl`` (``OMNI_USD_RESOLVER_MDL_BUILTIN_BYPASS=1``), + but Replicator's ``create_sdf_spec_material`` now passes that empty resolved path directly + into ``UsdMdl.RegistryUtils.GetSubIdentifiersForAsset``. The fix pre-resolves the absolute + on-disk path via ``carb.tokens`` (``${kit}/mdl/core/Base/OmniPBR.mdl``) before handing it + to Replicator so the resolver returns a valid path. + + +4.6.17 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated cross-backend asset interface tests to import :class:`~isaaclab_physx.physics.PhysxManager` + (aliased as ``SimulationManager``) instead of ``isaacsim.core.simulation_manager.SimulationManager``. +* Stopped registering deprecated Isaac Sim extension search paths in Isaac Lab Kit experiences and + switched explicit Isaac Sim extension dependencies to non-deprecated ``isaacsim.core.experimental.*``, + ``isaacsim.robot.experimental.wheeled_robots``, ``isaacsim.robot.wheeled_robots.nodes``, and + ``isaacsim.sensors.experimental.*`` equivalents. +* Migrated remaining Isaac Lab imports off deprecated Isaac Sim core utility/prim Python module paths + to their ``isaacsim.core.experimental.*`` replacements. + +Fixed +^^^^^ + +* Fixed ``isaaclab.sh --install`` leaving ``pinocchio`` uninstalled on top of recent Isaac Sim + base images that preinstall ``pin-pink`` in the kit's bundled ``site-packages`` without its + ``pin`` (cmeel pinocchio) dependency. Pip treats the ``pin-pink`` requirement as already + satisfied and skips the transitive ``pin`` resolve, so the pink IK controller and its tests + fail to import. ``isaaclab.cli.commands.install`` now probes ``import pinocchio`` after + installing the Isaac Lab submodules and force-reinstalls the cmeel ``pin``/``pin-pink``/ + ``daqp`` stack when the probe fails. + +Removed +^^^^^^^ + +* Retired several ``source/isaaclab/test/deps/isaacsim`` standalone reproducers that depended on + deprecated Isaac Sim core extensions; use :mod:`isaaclab.sim` and ``isaacsim.core.experimental.*`` + for similar debugging workflows. + + +4.6.16 (2026-04-24) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Renamed the ``TorchArray`` wrapper to + :class:`~isaaclab.utils.warp.ProxyArray` and its module from + ``isaaclab.utils.warp.torch_array`` to + ``isaaclab.utils.warp.proxy_array``. The new name better describes + the class as a proxy around a :class:`wp.array` exposing both + ``.warp`` and ``.torch`` accessors, rather than a torch-first type. + No backward-compatibility alias — downstream code must update + imports and type hints. + +Removed +^^^^^^^ + +* Removed :meth:`~isaaclab.utils.warp.ProxyArray.rebind`. ``ProxyArray`` + instances are now immutable after construction: assigning to any + attribute other than the internal ``_torch_cache`` raises + :class:`AttributeError`. Call sites that previously rebound a + sim-bound wrapper (Newton / PhysX asset data classes when the solver + re-creates its arrays) now assign a fresh + ``ProxyArray(new_buf)`` instead. The old pattern was unsafe — + callers holding a stale ``.torch`` reference read the old memory + silently after ``rebind``. Forcing a new wrapper per rebind makes + the stale-reference hazard local and explicit. + + .. code-block:: python + + # Before (4.6.15) + self._joint_pos_ta.rebind(self._sim_bind_joint_pos) + # After (4.6.16) + self._joint_pos_ta = ProxyArray(self._sim_bind_joint_pos) + + +4.6.15 (2026-04-24) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* :meth:`~isaaclab.sim.views.BaseFrameView.get_world_poses` and + :meth:`~isaaclab.sim.views.BaseFrameView.get_local_poses` now return + a pair of :class:`~isaaclab.utils.warp.ProxyArray` wrappers instead + of raw ``wp.array``. :class:`~isaaclab.sim.views.UsdFrameView`, + :class:`~isaaclab_physx.sim.views.FabricFrameView`, and + :class:`~isaaclab_newton.sim.views.NewtonSiteFrameView` were updated + accordingly. Calls without ``indices`` reuse a cached ProxyArray + wrapping the backend's stable buffer (Fabric/Newton); calls with + ``indices`` and all calls on USD construct a fresh ProxyArray per + invocation. + + **Breaking change** — call sites that wrapped the return in + ``wp.to_torch(...)`` or passed the result directly to a kernel must + migrate: + + .. code-block:: python + + # Before (4.6.14) + pos_wp, quat_wp = view.get_world_poses(indices) + tensor = wp.to_torch(pos_wp) + # After (4.6.15) + pos_w, quat_w = view.get_world_poses(indices) + tensor = pos_w.torch + # ... and when passing to a warp kernel: + wp.launch(..., inputs=[pos_w.warp, ...]) + + +4.6.14 (2026-04-24) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* :class:`~isaaclab.sensors.RayCasterData` and + :class:`~isaaclab.sensors.MultiMeshRayCasterData` properties + :attr:`~isaaclab.sensors.RayCasterData.pos_w`, + :attr:`~isaaclab.sensors.RayCasterData.quat_w`, and + :attr:`~isaaclab.sensors.RayCasterData.ray_hits_w` now return + :class:`~isaaclab.utils.warp.ProxyArray` instead of raw ``wp.array``. + Use ``.torch`` for a cached zero-copy ``torch.Tensor`` view or ``.warp`` + for the underlying ``wp.array``. + + **Breaking change** — call sites that previously wrapped these in + ``wp.to_torch(...)`` must migrate to the ``.torch`` accessor: + + .. code-block:: python + + # Before (4.6.13) + hits = wp.to_torch(sensor.data.ray_hits_w) + # After (4.6.14) + hits = sensor.data.ray_hits_w.torch + + +4.6.13 (2026-04-23) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.utils.warp.ProxyArray`, a warp-first dual-access array + that provides explicit ``.torch`` and ``.warp`` accessors for seamless + interoperability between warp and PyTorch workflows. + +Changed +^^^^^^^ + +* All properties on the following base data classes now return + :class:`~isaaclab.utils.warp.ProxyArray` instead of raw ``wp.array``: + :class:`~isaaclab.assets.articulation.BaseArticulationData`, + :class:`~isaaclab.assets.rigid_object.BaseRigidObjectData`, + :class:`~isaaclab.assets.rigid_object_collection.BaseRigidObjectCollectionData`, + :class:`~isaaclab.sensors.contact_sensor.BaseContactSensorData`, + :class:`~isaaclab.sensors.frame_transformer.BaseFrameTransformerData`, + :class:`~isaaclab.sensors.imu.BaseImuData`, and + :class:`~isaaclab.sensors.pva.BasePvaData`. + Use ``.torch`` for a cached zero-copy ``torch.Tensor`` view, or ``.warp`` for + the underlying ``wp.array``. Implicit torch operations (arithmetic, + ``torch.*`` functions) work during the deprecation period but emit a warning. + + +4.6.12 (2026-04-23) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added caching to :func:`~isaaclab.utils.string.resolve_matching_names`, + avoiding repeated regex matching across ``find_bodies``, ``find_joints``, + and related calls. + + +4.6.11 (2026-04-22) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed :class:`~isaaclab.sensors.RayCaster` to spawn its own non-physics Xform prim via + the new :attr:`~isaaclab.sensors.RayCasterCfg.spawn` attribute. ``prim_path`` should now + point to a child under the parent link (e.g. ``{ENV_REGEX_NS}/Robot/base/raycaster``). +* Renamed :class:`~isaaclab.sim.views.XformPrimView` to :class:`~isaaclab.sim.views.FrameView`, + ``BaseXformPrimView`` to :class:`~isaaclab.sim.views.BaseFrameView`, + and ``UsdXformPrimView`` to :class:`~isaaclab.sim.views.UsdFrameView`. + ``XformPrimView`` is kept as a deprecated alias. +* Moved :class:`~isaaclab.sensors.RayCasterCfg` offset into the spawned prim's local transform + instead of applying it at runtime. The :class:`~isaaclab.sim.views.FrameView` world pose now + includes the offset directly. +* Unified sensor prim path resolution in :class:`~isaaclab.sensors.SensorBase`. When + ``prim_path`` points at a physics body and a spawner is configured, a child prim is + automatically created underneath. + +Deprecated +^^^^^^^^^^ + +* Deprecated passing a ``prim_path`` with ``ArticulationRootAPI`` or ``RigidBodyAPI`` to + :class:`~isaaclab.sensors.RayCasterCfg`. The path is automatically extended with + ``/raycaster``; users should migrate to the child-path convention. + +Removed +^^^^^^^ + +* Removed :attr:`~isaaclab.sensors.RayCasterCfg.attach_yaw_only` (deprecated since 2.1.1). + Use ``ray_alignment="yaw"`` or ``ray_alignment="base"`` instead. + + +4.6.10 (2026-04-22) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :meth:`~isaaclab.utils.wrench_composer.WrenchComposer.add_raw_buffers_from` to merge one composer's raw + input buffers into another. +* Added ``render_enabled`` property to all environment base classes + (:class:`~isaaclab.envs.ManagerBasedEnv`, :class:`~isaaclab.envs.ManagerBasedRLEnv`, + :class:`~isaaclab.envs.DirectRLEnv`, :class:`~isaaclab.envs.DirectMARLEnv`). + Setting ``env.render_enabled = False`` before calling ``step()`` skips the Kit app loop + (``app.update()``) and camera/RTX sensor rendering, while standalone visualizers (Newton, + Rerun, Viser) continue to update normally. Kit bundles camera rendering with its app loop + so the two cannot be separated; non-Kit visualizers have independent ``step()`` methods and + are unaffected by this flag. Post-reset re-renders for RTX sensors are also skipped when + disabled. The property can be toggled between steps for per-step control. Defaults to + ``True`` for full backward compatibility. +* Added ``skip_app_pumping`` parameter to + :meth:`~isaaclab.sim.SimulationContext.render` and + :meth:`~isaaclab.sim.SimulationContext.update_visualizers` to selectively skip + visualizers that pump the Kit app loop (``pumps_app_update() == True``). + +Changed +^^^^^^^ + +* Refactored :class:`~isaaclab.utils.wrench_composer.WrenchComposer` to a dual-buffer architecture with separate + global (world-frame) and local (body-frame) buffers. A new + :meth:`~isaaclab.utils.wrench_composer.WrenchComposer.compose_to_body_frame` method rotates global forces/torques + into the body frame at apply time using the current body orientation, then sums with local forces/torques. +* Updated imports of the PhysX tensors API in the ray caster sensors from + ``omni.physics.tensors.impl.api`` to ``omni.physics.tensors.api`` to track the upstream + Isaac Sim module relocation (the ``impl`` submodule was removed). + +Deprecated +^^^^^^^^^^ + +* Deprecated :attr:`~isaaclab.utils.wrench_composer.WrenchComposer.composed_force` and + :attr:`~isaaclab.utils.wrench_composer.WrenchComposer.composed_torque` in favor of + :attr:`~isaaclab.utils.wrench_composer.WrenchComposer.out_force_b` and + :attr:`~isaaclab.utils.wrench_composer.WrenchComposer.out_torque_b`. + +Fixed +^^^^^ + +* Fixed :class:`~isaaclab.utils.wrench_composer.WrenchComposer` not correctly updating the composed torque from global + positional forces when the body moves. +* Fixed :meth:`~isaaclab.utils.wrench_composer.WrenchComposer.reset` not clearing the ``_active`` flag when called + with ``slice(None)``. +* Fixed :class:`~isaaclab.utils.wrench_composer.WrenchComposer` producing spurious torque when global forces are + applied without explicit positions. +* Fixed ``set_external_force_and_torque`` wiping forces from non-resetting environments during partial + episode resets by using ``reset(env_ids)`` + ``add_forces_and_torques`` instead of ``set_forces_and_torques``. + + +4.6.9 (2026-04-22) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Converted all four ray caster sensor classes (:class:`~isaaclab.sensors.RayCaster`, + :class:`~isaaclab.sensors.RayCasterCamera`, :class:`~isaaclab.sensors.MultiMeshRayCaster`, + :class:`~isaaclab.sensors.MultiMeshRayCasterCamera`) to launch Warp kernels directly via + ``wp.launch`` instead of going through Python-level torch wrappers. A new + :mod:`~isaaclab.sensors.ray_caster.kernels` module contains all sensor-specific kernels. + All intermediate ray buffers are now Warp-owned with zero-copy torch views, eliminating + per-step allocations. The existing :func:`~isaaclab.utils.warp.kernels.raycast_dynamic_meshes_kernel` + gained an ``env_mask`` parameter to support partial environment updates natively. A new + :func:`~isaaclab.utils.warp.kernels.raycast_mesh_masked_kernel` was added to + :mod:`~isaaclab.utils.warp.kernels` as the general-purpose masked single-mesh variant, + with ``return_distance`` and ``return_normal`` flags matching the design of + :func:`~isaaclab.utils.warp.kernels.raycast_mesh_kernel`. + + **Breaking change** — :attr:`~isaaclab.sensors.RayCasterData.pos_w`, + :attr:`~isaaclab.sensors.RayCasterData.quat_w`, and + :attr:`~isaaclab.sensors.RayCasterData.ray_hits_w` now return :class:`wp.array` + instead of :class:`torch.Tensor`. Call-sites that previously accessed these as tensors + must wrap the result with :func:`wp.to_torch`: + + .. code-block:: python + + # Before + hits = sensor.data.ray_hits_w # torch.Tensor (old) + # After + hits = wp.to_torch(sensor.data.ray_hits_w) # torch.Tensor (zero-copy view) + +* Changed the :attr:`~isaaclab.sensors.RayCaster.meshes` class variable cache key from + ``prim_path`` to a ``(prim_path, device)`` tuple so that meshes built on one device + (e.g. CPU) are not reused by a sensor running on another device (e.g. CUDA). + + **Breaking change** — callers that read or write :attr:`~isaaclab.sensors.RayCaster.meshes` + directly must update the key: + + .. code-block:: python + + # Before + wp_mesh = RayCaster.meshes[prim_path] + # After + wp_mesh = RayCaster.meshes[(prim_path, device)] + +Fixed +^^^^^ + +* Fixed frame composition in :meth:`~isaaclab.sensors.MultiMeshRayCaster._update_mesh_transforms` + which used simple subtraction instead of proper frame decomposition when applying mesh offsets. + With non-identity orientation offsets, tracked mesh positions were incorrect, causing raycasts to + miss or hit wrong surfaces. The method now uses :func:`~isaaclab.utils.math.combine_frame_transforms`. + + +4.6.8 (2026-04-21) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Pinned ``mujoco`` and ``mujoco-warp`` to ``3.6.0`` to align with the Newton library. + + +4.6.7 (2026-04-20) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :func:`~isaaclab.sim.utils.newton_model_utils.replace_newton_shape_colors` + to align Newton ``shape_color`` with authored USD where OmniPBR inputs or + ``primvars:displayColor`` apply. Set ``ISAACLAB_REPLACE_NEWTON_SHAPE_COLORS`` + to ``0``, ``false``, ``off``, or ``no`` to disable the pass; the function emits + a ``FutureWarning`` because this path is temporary until neutral USD materials + replace OmniPBR in content. +* Added ``test_newton_model_utils`` tests for the Newton shape color pass. + +Fixed +^^^^^ + +* Fixed nondeterministic environment replication when cloning from a template by + sorting prototype roots before building the clone plan in + :func:`~isaaclab.cloner.cloner_utils.clone_from_template`, keeping downstream + order stable across simulation and visualization backends. + +4.6.6 (2026-04-17) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed the way the python interpreter is called from ``isaaclab.sh`` to allow + error codes to bubble up to the process level. + + +4.6.5 (2026-04-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed flaky ``test_first_frame_is_textured_camera`` by removing warmup-step + workaround and relying on the renderer's streaming wait instead. + + +4.6.4 (2026-04-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed Newton viewer compatibility by restricting ``pyglet`` to ``<3``. + + +4.6.3 (2026-04-16) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed :class:`~isaaclab.sensors.imu.Imu` and + :class:`~isaaclab.sensors.imu.ImuData` factory type annotations to include + the Newton IMU backend types. + + +4.6.2 (2026-04-14) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + + +* Added :class:`~isaaclab.sim.spawners.meshes.MeshSquareCfg` and + :func:`~isaaclab.sim.spawners.meshes.spawn_mesh_square` for spawning 2D triangle + mesh grids, used as surface deformable bodies (cloth). +* Added physics material support to + :func:`~isaaclab.sim.spawners.from_files.spawn_from_usd` for deformable bodies + loaded from USD files. +* Added wheel builder installation CI tests that verify the isaaclab wheel + builds, installs, and imports correctly in a clean uv environment. + +Changed +^^^^^^^ + +* Moved :class:`DeformableBodyPropertiesCfg`, :class:`DeformableBodyMaterialCfg`, + and :class:`DeformableObjectSpawnerCfg` from ``isaaclab`` to ``isaaclab_physx``. + These are PhysX-specific and are now imported from + ``isaaclab_physx.sim.schemas``, ``isaaclab_physx.sim.spawners.materials``, and + ``isaaclab_physx.sim.spawners.spawner_cfg`` respectively. +* Changed deformable body property and material application in mesh and USD spawners + to use ``isaaclab_physx.sim.schemas`` instead of ``isaaclab.sim.schemas``. +* Changed :func:`~isaaclab.sim.spawners.from_files.spawn_from_usd` to call + ``define_deformable_body_properties`` when the deformable body API is not yet + present on the prim, instead of always calling ``modify_deformable_body_properties``. + +Removed +^^^^^^^ + +* Removed :func:`define_deformable_body_properties` and + :func:`modify_deformable_body_properties` from ``isaaclab.sim.schemas``. Use + ``isaaclab_physx.sim.schemas`` instead. +* Removed :class:`DeformableBodyPropertiesCfg` from ``isaaclab.sim.schemas``. Use + :class:`isaaclab_physx.sim.schemas.DeformableBodyPropertiesCfg` instead. +* Removed :class:`DeformableBodyMaterialCfg` and + :func:`spawn_deformable_body_material` from ``isaaclab.sim.spawners.materials``. + Use ``isaaclab_physx.sim.spawners.materials`` instead. +* Removed :class:`DeformableObjectSpawnerCfg` from ``isaaclab.sim.spawners``. Use + ``isaaclab_physx.sim.spawners.spawner_cfg.DeformableObjectSpawnerCfg`` instead. + + +4.6.1 (2026-04-14) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`~isaaclab.sim.schemas.JointDrivePropertiesCfg.ensure_drives_exist` + flag to :class:`~isaaclab.sim.schemas.JointDrivePropertiesCfg`. When enabled, + joints with zero stiffness and damping receive a minimal stiffness so that + backends like Newton recognise the drive as active. + + +4.6.0 (2026-04-13) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Unified :class:`~isaaclab.sensors.camera.Camera` and :class:`~isaaclab.sensors.camera.TiledCamera` + into a single implementation. :class:`Camera` now delegates all rendering to the + :class:`~isaaclab.renderers.Renderer` abstraction (same approach :class:`TiledCamera` used). + The public API is unchanged for :class:`Camera` users. +* **Breaking:** :attr:`~isaaclab.sensors.camera.CameraData.info` is now a flat + ``dict[str, Any]`` keyed by data type (e.g. ``camera.data.info["semantic_segmentation"]``). + The metadata is shared across all cameras and identical to what the underlying renderer returns. + + - **Camera users (old):** replace ``camera.data.info[cam_idx][data_type]`` with + ``camera.data.info[data_type]``. + - **TiledCamera users (old):** access pattern ``camera.data.info[data_type]`` is unchanged. + +* **Breaking:** :meth:`~isaaclab.renderers.BaseRenderer.write_output` has been replaced by + :meth:`~isaaclab.renderers.BaseRenderer.read_output`. The new method receives the full + :class:`~isaaclab.sensors.camera.CameraData` instance and iterates output types internally. + Custom renderer implementations must replace ``write_output(render_data, output_name, output_data)`` + with ``read_output(render_data, camera_data)``. + +Deprecated +^^^^^^^^^^ + +* :class:`~isaaclab.sensors.camera.TiledCamera` is deprecated. Use + :class:`~isaaclab.sensors.camera.Camera` directly — it now supports all renderer backends. +* :class:`~isaaclab.sensors.camera.TiledCameraCfg` is deprecated. Use + :class:`~isaaclab.sensors.camera.CameraCfg` directly. + +Removed +^^^^^^^ + +* Removed :attr:`~isaaclab.sensors.camera.Camera.render_product_paths`. Render products are + now managed internally by the renderer backend and are not part of the public API. + + +4.5.33 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.sensors.Pva` (Pose Velocity Acceleration) sensor, + renamed from the former ``Imu`` to better reflect its full output: pose, + velocity, and acceleration. +* Added :class:`~isaaclab.sensors.Imu` sensor that models a real inertial + measurement unit, providing only angular velocity (gyroscope) and linear + acceleration (accelerometer) in the sensor's body frame. +* Added :func:`~isaaclab.envs.mdp.observations.pva_orientation` and + :func:`~isaaclab.envs.mdp.observations.pva_projected_gravity` observation + functions for the PVA sensor. + +Changed +^^^^^^^ + +* Changed ``isaaclab.sensors.Imu`` to refer to a new lightweight IMU sensor + that only provides angular velocity and linear acceleration. The old + ``Imu``, ``ImuCfg``, ``ImuData``, ``BaseImu``, and ``BaseImuData`` names + now refer to this new sensor. For the original full-featured sensor, use + :class:`~isaaclab.sensors.Pva`, :class:`~isaaclab.sensors.PvaCfg`, etc. + +Removed +^^^^^^^ + +* Removed ``gravity_bias`` configuration parameter from + :class:`~isaaclab.sensors.PvaCfg`. The PVA sensor now always reports raw + kinematic acceleration without gravity contribution. +* Removed ``gravity_bias`` and ``visualizer_cfg`` configuration parameters from + :class:`~isaaclab.sensors.ImuCfg`. The IMU sensor now unconditionally includes + gravity in its accelerometer readings, matching real hardware behavior. The + gravity vector is queried from the simulation automatically. +* Removed ``imu_orientation`` and ``imu_projected_gravity`` observation + functions. Use :func:`~isaaclab.envs.mdp.observations.pva_orientation` and + :func:`~isaaclab.envs.mdp.observations.pva_projected_gravity` instead. + + +4.5.32 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :class:`~isaaclab.envs.mdp.events.randomize_actuator_gains` producing zero + stiffness and damping for explicit actuators. The default gains were read from + ``asset.data.joint_stiffness``, which is zeroed out at the sim level for explicit + actuator models. The defaults are now patched with the actual actuator PD gains. + + +4.5.31 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.envs.mdp.randomize_rigid_body_inertia` event term for + randomizing body inertia tensors independently of mass. Supports diagonal-only + (Ixx, Iyy, Izz) and full 3x3 modes. + +Changed +^^^^^^^ + +* Split :class:`~isaaclab.envs.mdp.randomize_rigid_body_material` into + backend-specific implementations. PhysX uses bucket-based 3-tuple materials via the + tensor API; Newton samples friction and restitution continuously per shape via + view-level attribute bindings. +* Converted ``randomize_rigid_body_com`` from a plain function to a + :class:`~isaaclab.managers.ManagerTermBase` class with repeatable randomization + from cached defaults. Newton passes position-only (vec3); PhysX passes full pose + (pos + quat). +* Converted ``randomize_rigid_body_collider_offsets`` from a plain function to a + :class:`~isaaclab.managers.ManagerTermBase` class with backend-specific + implementations. PhysX uses rest/contact offsets directly; Newton maps them to + ``shape_margin`` and ``shape_gap``. + + +4.5.30 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :func:`~isaaclab.utils.warp.math_ops.transform_to_vec_quat` utility for + zero-copy splitting of ``wp.transformf`` arrays into ``vec3f`` and ``quatf`` views. + + +4.5.29 (2026-04-10) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added flag to toggle dataset compression in RecorderManager and dataset file handler. + +Changed +^^^^^^^ + +* Changed RecorderManager to clone value tensors before adding to episode data, removing multiple clones in ``episodes.add()`` and replacing with a single clone. + + +4.5.28 (2026-04-10) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :meth:`~isaaclab.physics.PhysicsManager.wait_for_playing` hook and + integrated it into :meth:`~isaaclab.sim.SimulationContext.step` so the + training loop blocks while the Kit GUI timeline is paused. + + +4.5.27 (2026-04-08) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + + +* Added :class:`~isaaclab.sim.views.BaseXformPrimView` abstract base class that defines + the common interface for backend-specific ``XformPrimView`` implementations. +* Added :class:`~isaaclab.sim.views.XformPrimView` factory to instantiate the correct + backend-specific ``XformPrimView`` based on the active simulation backend. + +Changed +^^^^^^^ + +* Refactored :class:`~isaaclab.sim.views.XformPrimView` to delegate backend-specific + logic to :class:`~isaaclab_physx.sim.views.FabricXformPrimView` and + :class:`~isaaclab_newton.sim.views.NewtonSiteXformPrimView`. The public API is + unchanged; use :class:`~isaaclab.sim.views.XformPrimView` for backend-aware + instantiation. + +* Added release version to + :class:`~isaaclab.test.benchmark.recorders.VersionInfoRecorder` output. + + +4.5.26 (2026-04-08) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed ``SummaryMetrics`` backend to + dynamically render unknown benchmark phases. Previously only hard-coded phase + names (``startup``, ``runtime``, ``train``, ``frametime``) were printed in the + summary report; any other phases were silently dropped. Unknown phases now + render their ``SingleMeasurement`` and ``StatisticalMeasurement`` entries + automatically. + + +4.5.25 (2026-04-01) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added app launcher initialization marker to app launcher for auto hanging detection. + + +4.5.24 (2026-03-25) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added support for absolute named imports (``from pkg import a, b``) in + ``.pyi`` stubs processed by :func:`~isaaclab.utils.module.lazy_export`. + Previously only relative imports and absolute wildcard fallbacks were + handled; explicit names from absolute packages are now eagerly resolved + and re-exported. + +Fixed +^^^^^ + +* Fixed incorrect mass matrix and gravity compensation force indexing for + floating-base robots in :class:`~isaaclab.envs.mdp.actions.OperationalSpaceControllerAction`. + The method ``_compute_dynamic_quantities()`` used ``self._joint_ids`` to index into PhysX + generalized quantities, which does not account for the 6 virtual base DOFs prepended by PhysX + for floating-base articulations. Replaced with ``self._jacobi_joint_idx`` which correctly + applies the +6 offset for floating-base robots and is identical to ``self._joint_ids`` for + fixed-base robots. + + +4.5.23 (2026-03-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed flaky tests in ``test_mock_data_properties`` caused by use-after-free in + mock asset data properties. Warp view properties (e.g. :attr:`root_com_lin_vel_w`) + created pointer aliases into locally-scoped temporary arrays; when those temporaries + were freed by CPython's reference counter before the view was consumed, subsequent + reads produced garbage. Fixed by caching default arrays in the backing attribute + (``self._root_link_vel_w``, ``self._root_com_vel_w``, ``self._body_com_vel_w``, + etc.) so the backing memory remains alive for the lifetime of the mock object. + + +4.5.22 (2026-03-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed multi-GPU distributed training segfault in + :func:`~isaaclab.sim.spawners.from_files.spawn_from_usd` caused by concurrent + USD asset downloads and ``Sdf_CrateFile::_MmapStream::Read`` mmap races. When + ``LOCAL_WORLD_SIZE > 1``, the download and stage composition are now serialized + with an ``fcntl`` file lock. + + +4.5.21 (2026-03-13) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :meth:`~isaaclab.sim.SimulationContext.initialize_visualizers` silently + swallowing failures when visualizers were explicitly requested via the + ``--visualizer`` CLI flag. Unknown visualizer types and missing packages were + not caught because they failed during config resolution, before the + create/initialize loop. A ``RuntimeError`` is now raised for any explicitly + requested visualizer that cannot be configured or initialized. + + +4.5.20 (2026-03-13) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Removed verbose ``logger.info`` and ``logger.debug`` calls from + :class:`~isaaclab.managers.ManagerBase` term initialization and entity resolution, + :func:`~isaaclab.sim.schemas.activate_contact_sensors` contact report setup, and + :class:`~isaaclab.sim.views.XformPrimView` Fabric detection. These messages added + noise to logs without actionable information. + + +4.5.19 (2026-03-11) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :class:`~isaaclab.sim.views.XFormPrimView` crashing on multi-GPU setups (``cuda:1`` + and higher) when Fabric mode is enabled. USDRT ``SelectPrims`` and Warp fabric arrays only + support ``cuda:0`` internally — ``SelectPrims`` raises a C++ error when the active CUDA + context is not GPU 0, regardless of the ``device`` argument. The fix disables Fabric and + falls back to USD operations when ``self._device`` is not ``cuda:0``. Additionally fixed + device mismatches in the Fabric methods where Warp arrays were allocated on ``self._device`` + but kernel launches targeted ``_fabric_device`` (``cuda:0``). + + +4.5.18 (2026-03-11) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added reward convergence checking to benchmark scripts. New ``--check_convergence`` + flag loads thresholds from ``configs.yaml`` automatically. Also accepts + ``--reward_threshold`` for manual override and ``--convergence_config`` to select + config section (default: ``full``). Adds ``check_convergence()`` and + ``log_convergence()`` to benchmark utils. + + +4.5.17 (2026-03-11) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed simulation hanging on exit by removing the prim-by-prim + ``clear_stage()`` call from :meth:`~isaaclab.sim.SimulationContext.clear_instance`. + The subsequent :func:`~isaaclab.sim.utils.close_stage` and app shutdown already + tear down the entire stage, making the per-prim deletion redundant and slow. +* Fixed ``close_stage()`` ordering so that Kit's USD context is closed before + the stage cache is cleared, preventing the ``Removal of UsdStage from cache + failed`` error. + + +4.5.16 (2026-03-10) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed "[Error] [omni.usd] Stage opening or closing already in progress" on + shutdown when running with Kit: ``env.close()`` already closes the stage, so + the redundant explicit :func:`~isaaclab.sim.utils.stage.close_stage` calls + in the scripts were removed; :meth:`~isaaclab.sim.SimulationContext.clear_instance` + (invoked by ``env.close()``) already closes the stage, so the duplicate calls + in the shutdown block triggered the error. + + +4.5.15 (2026-03-10) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed semantic label warnings (``OgnSdSemanticLabelsMap: invalid input AOV``) + by restoring standard ``SemanticsLabelsAPI`` usage in :func:`~isaaclab.sim.utils.prims.clone`. + + +4.5.14 (2026-03-10) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``validate_config`` hook to :func:`~isaaclab.utils.configclass`. Configclass + subclasses can now override ``validate_config(self)`` to perform domain-specific + validation that runs automatically as part of :func:`_validate`. + +Fixed +^^^^^ + +* Fixed ``SimulationContext`` singleton leak when environment ``__init__`` fails + after creating the context. :class:`~isaaclab.envs.DirectRLEnv`, + :class:`~isaaclab.envs.DirectMARLEnv`, and :class:`~isaaclab.envs.ManagerBasedEnv` + now call ``clear_instance()`` on the context when initialization raises, preventing + cascading "Simulation context already exists" errors in test suites and training loops. + + +4.5.13 (2026-03-10) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ +* Added recursive resolution of nested :class:`~isaaclab.managers.ManagerTermBaseCfg` inside + :meth:`~isaaclab.managers.ManagerBase._resolve_param_value` so that ``params`` containing + manager term configs in dicts or lists have their ``func`` references and class-based + managers resolved automatically. + + +4.5.12 (2026-03-10) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Unified :class:`~isaaclab.envs.mdp.randomize_physics_scene_gravity` into a single + class-based term that auto-detects the active physics backend (PhysX or Newton). + +Removed +^^^^^^^ + +* Removed ``randomize_newton_physics_scene_gravity``. Use + :class:`~isaaclab.envs.mdp.randomize_physics_scene_gravity` instead, which + handles both PhysX and Newton backends automatically. + + +4.5.11 (2026-02-28) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``visualizers`` parameter to ``build_simulation_context()``. + + +4.5.10 (2026-03-09) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Refactored :func:`~isaaclab.utils.module.lazy_export` to infer fallback packages + and relative wildcard re-exports from the ``.pyi`` stub, making the stub the + single source of truth. The ``packages`` argument is deprecated. + + +4.5.9 (2026-03-08) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* :mod:`isaaclab_ov` is now always installed when using ``./isaaclab.sh -i`` (or + ``--install all``), but with ``--no-deps`` so it is importable (e.g. by + :mod:`isaaclab_tasks` presets) without pulling in the optional ``ovrtx`` dependency. + To install the ovrtx dependency for OVRTX rendering, run ``./isaaclab.sh -i ovrtx``. + +4.5.8 (2026-03-06) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``debugpy`` to :mod:`isaaclab` package dependencies to support debugging out of the box. + +4.5.7 (2026-03-06) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Extended ``test_articulation_iface.py`` with Newton backend mock tests — added + Newton-specific mock view setup, sim config, and test parametrization alongside + existing PhysX tests. + +* Extended ``test_rigid_object_iface.py`` with Newton backend mock tests — added + Newton-specific mock view setup and test parametrization. + +* Fixed mask type handling in ``test_rigid_object_collection_iface.py`` to use + consistent mask types across backends. + + +4.5.6 (2026-03-06) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Reorganized Visualizers and SDP packages +* Added Visualizer unit tests +* Improved PhysX Scene Data Provider perf +* Tweaked default Visualizer Configs + + +4.5.5 (2026-03-05) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added documentation for :class:`~isaaclab.renderers.BaseRenderer` and the renderer + extension architecture in ``docs/source/overview/core-concepts/renderers.rst``, + including the factory pattern. + + +4.5.4 (2026-03-01) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Enhanced :class:`~isaaclab.utils.timer.Timer` with configurable time format + (``s``/``ms``/``us``/``ns``), global enable/disable toggle, display output + control, and ``wp.synchronize()`` before stopping to ensure accurate + GPU timing. + + +4.5.3 (2026-03-05) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Passed ``default_env_origins`` to the Newton replication pipeline so environment offsets to adapt new newton + cloning logic. + +4.5.2 (2026-03-04) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.test.benchmark.backends.SummaryMetrics` backend for benchmarks: + prints a human-readable boxed summary to the console while still writing full JSON output. + Use ``--benchmark_backend summary`` in benchmark scripts. + +Fixed +^^^^^ + +* Fixed runtime stats in benchmark scripts so FPS metrics (e.g. Collection FPS, Total FPS) + are labeled with unit "FPS" instead of "ms". Unit is now inferred from the me + name in ``log_min_max_mean_stats`` (benchmark utils). + +* Enabled frametime recorders for the ``omniperf`` backend in benchmark scripts to + preserve Grafana metrics ingestion. + + +4.5.1 (2026-03-02) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added interface-conformance test suites that verify data property shapes/dtypes, writer + methods, setters, and alias consistency across Mock and PhysX backends: + + - ``test/assets/test_articulation_iface.py`` for + :class:`~isaaclab.assets.BaseArticulation`. + - ``test/assets/test_rigid_object_iface.py`` for + :class:`~isaaclab.assets.BaseRigidObject`. + - ``test/assets/test_rigid_object_collection_iface.py`` for + :class:`~isaaclab.assets.BaseRigidObjectCollection`. + +Fixed +^^^^^ + +* Fixed structured warp types in ``MockArticulationData``, ``MockRigidObjectData``, and + ``MockRigidObjectCollectionData``: velocity, acceleration, and limit properties now + return the correct structured dtypes (``wp.spatial_vectorf``, ``wp.vec2f``, etc.) and + sliced velocity properties use zero-copy pointer arithmetic instead of torch-based + slicing, matching the PhysX backend contract. + +* Added shape and dtype validation to all ``_index`` / ``_mask`` writer methods in + ``MockArticulation``, ``MockRigidObject``, and ``MockRigidObjectCollection``, replacing + bare ``pass`` stubs. + +* Fixed ``set_coms_index`` / ``set_coms_mask`` docstrings in + :class:`~isaaclab.assets.BaseArticulation` to document the correct dtype + (``wp.transformf``) and frame of reference (body link frame). + +* Fixed XR instruction widget for Fabric and switch to current scene view APIs. + +* Fixed session lifecycle pre-shutdown by removing invalid unsubscribe() call. + + +4.5.0 (2026-02-27) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Replaced ``omni.kit.commands`` and async Nucleus calls in asset utilities, prim + helpers. + + +4.4.0 (2026-02-26) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Migrated lazy-loading to ``lazy_loader.attach_stub`` with ``.pyi`` stubs as the + single source of truth for module exports. Removed the old ``attach_cascading`` + helper, avoided eager callable resolution during deepcopy of + :class:`~isaaclab.utils.string.ResolvableString`, and updated MDP + exports/import boundaries so ``test_env_cfg_no_forbidden_imports.py`` passes + without importing runtime modules. + + +4.3.2 (2026-02-25) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed inconsistent ``body_mass`` shape in :class:`~isaaclab.assets.BaseRigidObjectData` + from ``(num_instances, 1, 1)`` to ``(num_instances, 1)`` to align with the articulation + convention. + +* Unified inertia scaling in :func:`~isaaclab.envs.mdp.events.randomize_rigid_body_mass` + to use a single code path for both articulations and rigid objects. + +Changed +^^^^^^^ + +* Reworked mock interfaces for assets and sensors to align with updated data shapes and + remove stale convenience aliases. + + +4.3.1 (2026-02-27) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :meth:`~isaaclab.assets.AssetBase.assert_shape_and_dtype` and + :meth:`~isaaclab.assets.AssetBase.assert_shape_and_dtype_mask` validation methods to + :class:`~isaaclab.assets.AssetBase` for runtime shape and dtype checking of write method + inputs. Checks are only active in debug mode (``__debug__``), adding zero overhead in + optimized builds. + +Changed +^^^^^^^ + +* Fixed tendon setter signatures in :class:`~isaaclab.assets.BaseArticulation` + (``set_fixed_tendon_*`` and ``set_spatial_tendon_*``) now accept ``float`` values in + addition to tensors and warp arrays. + + +4.3.0 (2026-02-26) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added lazy callable-string resolution for config fields through + :class:`~isaaclab.utils.string.ResolvableString` in :mod:`isaaclab.utils.configclass`. + Config values such as ``class_type``/``func`` can now remain as strings until first + use and then resolve/cached automatically. + +* Added ``{DIR}`` callable-string shorthand support in :mod:`isaaclab.utils.configclass` + for config defaults. ``"{DIR}.module:Symbol"`` now expands to the declaring config + module directory before resolution. + +* Updated :func:`~isaaclab.utils.dict.update_class_from_dict` to stop eagerly resolving + callable strings during updates. Callable-string inputs are now preserved as lazy + :class:`~isaaclab.utils.string.ResolvableString` values and resolve only on first use. + + +4.2.3 (2026-02-25) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :func:`~isaaclab.cloner.usd_replicate` and :func:`~isaaclab.cloner.physx_replicate` + skipping ``Sdf.CopySpec`` when the source and destination paths are identical (self-copy), + avoiding a redundant and potentially destructive USD spec overwrite. + + +4.2.2 (2026-02-26) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :meth:`~isaaclab.assets.AssetBase.assert_shape_and_dtype` and + :meth:`~isaaclab.assets.AssetBase.assert_shape_and_dtype_mask` validation methods to + :class:`~isaaclab.assets.AssetBase` for runtime shape and dtype checking of write method + inputs. Checks are only active in debug mode (``__debug__``), adding zero overhead in + optimized builds. + +Changed +^^^^^^^ + +* Fixed tendon setter signatures in :class:`~isaaclab.assets.BaseArticulation` + (``set_fixed_tendon_*`` and ``set_spatial_tendon_*``) now accept ``float`` values in + addition to tensors and warp arrays. + + +4.2.1 (2026-02-25) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Migrated all MDP action terms to use new ``_index`` write/set APIs with keyword-only arguments. + +* Migrated all MDP event terms to use new ``_index`` write/set APIs (mass, inertia, COM, + joint properties, root state resets, fixed tendon parameters). + +* Updated ``InteractiveScene.set_state`` to use new ``_index`` APIs for root pose/velocity + and joint state writes. + +* Updated ``SceneEntityCfg`` body resolution to use ``find_sensors``/``num_sensors`` for + ContactSensor entities. + + +4.2.0 (2026-02-24) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Refined base asset class abstractions (:class:`~isaaclab.assets.BaseArticulation`, + :class:`~isaaclab.assets.BaseRigidObject`) to better support multiple backends. + Removed abstract method requirements that forced unnecessary boilerplate in backend + implementations, making it easier to add new physics backends. + +* Unified docstrings across all base asset classes with precise shape and dtype annotations + for warp array properties and write methods, ensuring consistent documentation between + PhysX and Newton backend implementations. + + +4.1.0 (2026-02-18) +~~~~~~~~~~~~~~~~~~ + +Removed +^^^^^^^ + +* Removed hard dependency on the Isaac Sim Cloner for scene replication. Replication now uses internal utilities + :func:`~isaaclab.scene.cloner.usd_replicate` and :func:`~isaaclab.scene.cloner.physx_replicate`, reducing coupling + to Isaac Sim. Public APIs in :class:`~isaaclab.scene.interactive_scene.InteractiveScene` remain unchanged; code + directly importing the external Cloner should migrate to these utilities. + +Added +^^^^^ + +* Added optional random prototype selection during environment cloning in + :class:`~isaaclab.scene.interactive_scene.InteractiveScene` via + :attr:`~isaaclab.scene.interactive_scene_cfg.InteractiveSceneCfg.random_heterogeneous_cloning`. + Defaults to ``True``; round-robin (modulo) mapping remains available by setting it to ``False``. + +* Added flexible per-object cloning path in + :class:`~isaaclab.scene.interactive_scene.InteractiveScene`: when environments are heterogeneous + (different prototypes across envs), replication switches to per-object instead of whole-env cloning. + This reduces PhysX cloning time in heterogeneous scenes. + + +4.0.0 (2026-02-22) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated :class:`~isaaclab.sim.converters.MjcfConverter` and + :class:`~isaaclab.sim.converters.MjcfConverterCfg` for the rewritten MJCF importer in Isaac Sim 5.0. + The converter now uses the ``MJCFImporter`` / ``MJCFImporterConfig`` API backed by the + ``mujoco-usd-converter`` library. The old settings ``fix_base``, ``link_density``, + ``import_inertia_tensor``, ``import_sites``, and ``make_instanceable`` have been removed + (handled automatically by the new converter). New settings ``merge_mesh``, + ``collision_from_visuals``, and ``collision_type`` have been added. The ``convert_mjcf.py`` + CLI tool has been updated accordingly. Note that the new importer produces assets with nested + rigid bodies (``RigidBodyAPI`` applied per link) instead of a flat hierarchy. + + + +3.5.3 (2026-02-22) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Refactored ``SimulationContext.clear_instance`` to delegate stage teardown to + :func:`~isaaclab.sim.utils.close_stage` instead of manually clearing the stage cache, + thread-local context, and Kit USD context inline. +* Updated :func:`~isaaclab.sim.utils.close_stage` to also close the Kit USD context stage + (``omni.usd.get_context().close_stage()``) when Kit is running, making it a complete + stage teardown function. + + +3.5.2 (2026-02-23) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* ``NUCLEUS_ASSET_ROOT_DIR`` and derived Nucleus path constants are now parsed from ``apps/isaaclab.python.kit`` + + +3.5.1 (2026-02-21) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed ``omni.usd`` calls with pure USD (``pxr``) equivalents in sim utils and sensors. + +Deprecated +^^^^^^^^^^ + +* ``create_new_stage_in_memory`` — use ``create_new_stage`` instead. +* ``is_stage_loading`` — Kit-only, no production callers. + + +3.5.0 (2026-02-21) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* The in-memory stage created with ``SimulationCfg(create_stage_in_memory=True)`` is now automatically + attached to the USD context at :class:`~isaaclab.sim.SimulationContext` creation. This ensures proper + stage lifecycle events for viewport and physics systems, preventing test isolation issues. + + +3.4.3 (2026-02-22) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Migrated settings access from ``carb.settings`` to :class:`~isaaclab.app.settings_manager.SettingsManager`. + Application code and tests now use :func:`~isaaclab.app.settings_manager.get_settings_manager` or + :meth:`~isaaclab.sim.SimulationContext.get_setting` / :meth:`~isaaclab.sim.SimulationContext.set_setting` + instead of ``carb.settings.get_settings()``. + + +3.4.2 (2026-02-20) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Replaced PhysX schema interactions via ``pxr.PhysxSchema`` API helpers with direct prim schema apply/get calls. +* Replaced ``omni.kit.commands.execute("ChangePropertyCommand")`` uses with direct ``CreateAttribute`` + ``Set`` calls. + + +Removed +^^^^^^^ + +* Removed :func:`~isaaclab.sim.utils.attach_stage_to_usd_context`. This function is no longer needed + since the in-memory stage is now automatically attached to the USD context at ``SimulationContext`` + creation. Remove any calls to this function from your code. + +Fixed +^^^^^ + +* Fixed :func:`~isaaclab.sim.utils.add_labels` to use :class:`UsdSemantics.LabelsAPI` directly + instead of the Replicator API for Isaac Sim 5.0+. This resolves ``'NoneType' object has no + attribute 'GetEditTarget'`` errors when using stage-in-memory mode. + + +3.4.0 (2026-02-18) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Integrated TeleopCore as the teleoperation backend via the new :mod:`isaaclab_teleop` extension. + The :class:`~isaaclab_teleop.IsaacTeleopDevice` provides a unified teleoperation interface that + replaces the previous XR-specific device and retargeter classes. + +Deprecated +^^^^^^^^^^ + +* Deprecated the existing XR teleoperation solution. :class:`~isaaclab.devices.openxr.OpenXRDevice`, + :class:`~isaaclab.devices.openxr.OpenXRDeviceCfg`, :class:`~isaaclab.devices.openxr.ManusVive`, + :class:`~isaaclab.devices.RetargeterBase`, :class:`~isaaclab.devices.RetargeterCfg`, and all + retargeters under :mod:`isaaclab.devices.openxr.retargeters` are deprecated in favor of + :class:`~isaaclab_teleop.IsaacTeleopDevice`. Existing imports will continue to work but emit + :class:`DeprecationWarning` when ``isaaclab_teleop`` is installed. + + +3.3.0 (2026-02-13) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Migrated all asset and sensor data properties from ``torch.Tensor`` to ``wp.array`` (NVIDIA Warp). + All ``.data.*`` properties on :class:`~isaaclab.assets.Articulation`, + :class:`~isaaclab.assets.RigidObject`, :class:`~isaaclab.assets.RigidObjectCollection`, and + sensor data classes now return ``wp.array``. Use ``wp.to_torch()`` to convert back to + ``torch.Tensor`` when needed. + +* Split all asset write methods into ``_index`` and ``_mask`` variants. The old ``env_ids`` + parameter has been replaced by explicit ``_index`` methods (sparse indexed data) and ``_mask`` + methods (full data with boolean mask). For example, + ``write_root_link_pose_to_sim(data, env_ids)`` is now + ``write_root_link_pose_to_sim_index(data, env_ids)`` or + ``write_root_link_pose_to_sim_mask(data, env_mask)``. + +* Refactored :mod:`isaaclab.utils.wrench_composer` to use warp kernels internally. + +* Updated all MDP action, observation, reward, termination, command, and event functions + to wrap ``wp.array`` data accesses with ``wp.to_torch()`` for torch compatibility. + +* Updated mock interfaces for all assets and sensors to produce ``wp.array``-backed data. + +Added +^^^^^ + +* Added :class:`~isaaclab.utils.buffers.TimestampedBufferWarp` for warp-native timestamped + data buffers, replacing ``TimestampedBuffer`` in warp-backed asset and sensor classes. + +* Added shared warp math kernels in :mod:`isaaclab.utils.warp.kernels` for quaternion + operations, coordinate transforms, and velocity computations. + +3.2.0 (2026-02-06) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Refactored :class:`~isaaclab.sim.SimulationContext` to use :class:`~isaaclab.physics.PhysicsManager` + abstraction layer for cleaner separation between simulation orchestration and physics backend. + + +3.1.0 (2026-02-05) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.test.benchmark.BaseIsaacLabBenchmark` class replacing dependency on + ``isaacsim.benchmark.services`` for benchmarking workflows. This provides a standalone framework + for measuring performance of Isaac Lab components. + +* Added measurement types in :mod:`isaaclab.test.benchmark.measurements`: + + * :class:`~isaaclab.test.benchmark.SingleMeasurement`: Single floating-point measurement with unit. + * :class:`~isaaclab.test.benchmark.StatisticalMeasurement`: Mean, std, and sample count. + * :class:`~isaaclab.test.benchmark.DictMeasurement`: Dictionary-valued measurement. + * :class:`~isaaclab.test.benchmark.ListMeasurement`: List-valued measurement. + * :class:`~isaaclab.test.benchmark.BooleanMeasurement`: Boolean measurement. + +* Added metadata types in :mod:`isaaclab.test.benchmark.measurements`: + + * :class:`~isaaclab.test.benchmark.StringMetadata`: String metadata. + * :class:`~isaaclab.test.benchmark.IntMetadata`: Integer metadata. + * :class:`~isaaclab.test.benchmark.FloatMetadata`: Float metadata. + * :class:`~isaaclab.test.benchmark.DictMetadata`: Dictionary metadata. + +* Added :class:`~isaaclab.test.benchmark.TestPhase` for organizing measurements and metadata + into logical phases within a benchmark. + +* Added :class:`~isaaclab.test.benchmark.BenchmarkMonitor` context manager for async system + resource monitoring during blocking operations like RL training loops. + +* Added pluggable backend architecture in :mod:`isaaclab.test.benchmark.backends`: + + * ``json``: Full JSON output with all phases, measurements, and metadata. + * ``osmo``: Osmo KPI format for CI/CD integration. + * ``omniperf``: OmniPerf format for database upload. + * ``summary``: Human-readable console summary plus JSON output. + +* Added system recorders in :mod:`isaaclab.test.benchmark.recorders`: + + * :class:`~isaaclab.test.benchmark.recorders.CPUInfoRecorder`: CPU information capture. + * :class:`~isaaclab.test.benchmark.recorders.GPUInfoRecorder`: GPU information capture. + * :class:`~isaaclab.test.benchmark.recorders.MemoryInfoRecorder`: Memory usage tracking. + * :class:`~isaaclab.test.benchmark.recorders.VersionInfoRecorder`: Software version capture. + +* Added CLI arguments for benchmark scripts: ``--benchmark_backend``, ``--output_path``. + +* Added shell scripts for running benchmark suites: + + * ``scripts/benchmarks/run_non_rl_benchmarks.sh``: Non-RL environment stepping benchmarks. + * ``scripts/benchmarks/run_physx_benchmarks.sh``: PhysX micro-benchmarks. + * ``scripts/benchmarks/run_training_benchmarks.sh``: RL training benchmarks. + +* Added fallback in :mod:`isaaclab.test.benchmark.benchmark_core` for Isaac Sim packaging that + bundles frametime recorders in a single module, so frametime collection works across variants. + +Changed +^^^^^^^ + +* Refactored benchmark scripts to use new :class:`~isaaclab.test.benchmark.BaseIsaacLabBenchmark` + class instead of ``isaacsim.benchmark.services``. + +Fixed +^^^^^ + +* Fixed runtime stats in ``log_min_max_mean_stats`` (``scripts/benchmarks/utils.py``) so FPS + metrics are labeled with unit ``FPS`` and time metrics with ``ms`` instead of all being ``ms``. + +Removed +^^^^^^^ + +* Removed hard dependency on ``isaacsim.benchmark.services`` extension for benchmarking. + The extension is now optional and only used for frametime recorders when available. + + +3.0.3 (2026-02-05) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Modified all the base classes so that they implement the shorthands and the deprecation cycle to IsaacLab 4.0 + + +3.0.2 (2026-02-04) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Removed exact version pinning for URDF asset importer extension that is incompatible with Isaac Sim 6.0. + + +3.0.1 (2026-02-04) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :file:`isaaclab.sh` to use libstdc++ CXXABI_1.3.15 from conda for systems that lack that version (e.g., Ubuntu 22.04). + + +3.0.0 (2026-02-02) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added albedo annotator for faster diffuse albedo rendering. This path will be the most performant when GUI is not required and only albedo and/or depth annotations are requested. + +Changed +^^^^^^^ + +* Updated Isaac Lab to be compatible with Isaac Sim 6.0.0. +* Updated the required Python version to 3.12 for Isaac Lab installation. +* Updated the required PyTorch version to 2.9.0+cu128 and torchvision to 0.24.0 for Isaac Lab installation. +* Updated numpy to 2.3.1 following version in Kit 109.0. +* Updated dex-retargeting to 0.5.0 with numpy 2.0+ dependency. +* Removed explicit URDF importer extension version dependency in :class:`~isaaclab.sim.converters.urdf_converter.UrdfConverter` and related code. + + +2.1.2 (2026-01-30) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :mod:`isaaclab.test.benchmark` module providing a comprehensive benchmarking framework + for measuring performance of Isaac Lab components. Includes: + + * :class:`BenchmarkConfig`: Configuration dataclass for benchmark execution parameters + (iterations, warmup steps, instances, device). + * :class:`BenchmarkResult`: Dataclass capturing timing statistics (mean, std in microseconds), + skip status, and dependency information. + * :class:`MethodBenchmark`: Definition class for methods to benchmark with multi-mode + input generators. + * Input generator helpers for creating standardized tensors and Warp masks: + ``make_tensor_env_ids``, ``make_tensor_joint_ids``, ``make_tensor_body_ids``, + ``make_warp_env_mask``, ``make_warp_joint_mask``, ``make_warp_body_mask``. + * :func:`benchmark_method`: Core function for benchmarking with warmup phases, + GPU synchronization, and graceful error handling. + * I/O utilities: :func:`get_hardware_info`, :func:`get_git_info`, :func:`print_hardware_info`, + :func:`print_results`, :func:`export_results_json`, :func:`export_results_csv`. + + +2.1.1 (2026-02-03) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :mod:`isaaclab.test.mock_interfaces` module providing mock implementations for unit testing + without requiring Isaac Sim. Includes: + + * Mock assets: :class:`MockArticulation`, :class:`MockRigidObject`, :class:`MockRigidObjectCollection` + with full state tracking and property management. + * Mock sensors: :class:`MockContactSensor`, :class:`MockImu`, :class:`MockFrameTransformer` + with configurable data outputs. + * Utility classes: :class:`MockArticulationBuilder`, :class:`MockSensorBuilder`, + :class:`MockWrenchComposer` for flexible mock construction. + * Factory functions for common robot morphologies (quadruped, humanoid). + * Patching utilities and decorators for easy test injection. + + +2.1.0 (2026-02-02) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.sensors.contact_sensor.BaseContactSensor` and + :class:`~isaaclab.sensors.contact_sensor.BaseContactSensorData` abstract base classes that define + the interface for contact sensors. These classes provide a backend-agnostic API for contact sensing. +* Added :class:`~isaaclab.sensors.imu.BaseImu` and :class:`~isaaclab.sensors.imu.BaseImuData` abstract + base classes that define the interface for IMU sensors. These classes provide a backend-agnostic + API for inertial measurement. +* Added :class:`~isaaclab.sensors.frame_transformer.BaseFrameTransformer` and + :class:`~isaaclab.sensors.frame_transformer.BaseFrameTransformerData` abstract base classes that + define the interface for frame transformer sensors. These classes provide a backend-agnostic API + for coordinate frame transformations. + +Changed +^^^^^^^ + +* Refactored the sensor classes (:class:`~isaaclab.sensors.ContactSensor`, + :class:`~isaaclab.sensors.Imu`, :class:`~isaaclab.sensors.FrameTransformer`) to follow the + multi-backend architecture. The classes now act as factory wrappers that instantiate the + appropriate backend-specific implementation (PhysX by default). +* Refactored the sensor data classes (:class:`~isaaclab.sensors.ContactSensorData`, + :class:`~isaaclab.sensors.ImuData`, :class:`~isaaclab.sensors.FrameTransformerData`) to use the + factory pattern for backend-specific instantiation. +* Moved PhysX-specific sensor tests to the ``isaaclab_physx`` package: + + * ``test_contact_sensor.py`` → ``isaaclab_physx/test/sensors/`` + * ``test_imu.py`` → ``isaaclab_physx/test/sensors/`` + * ``test_frame_transformer.py`` → ``isaaclab_physx/test/sensors/`` + + +2.0.0 (2026-01-30) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.assets.BaseArticulation` and :class:`~isaaclab.assets.BaseArticulationData` + abstract base classes that define the interface for articulation assets. These classes provide + a backend-agnostic API for articulation operations. +* Added :class:`~isaaclab.assets.BaseRigidObject` and :class:`~isaaclab.assets.BaseRigidObjectData` + abstract base classes that define the interface for rigid object assets. These classes provide + a backend-agnostic API for rigid object operations. +* Added :class:`~isaaclab.assets.BaseRigidObjectCollection` and :class:`~isaaclab.assets.BaseRigidObjectCollectionData` + abstract base classes that define the interface for rigid object collection assets. These classes + provide a backend-agnostic API for managing collections of rigid objects. +* Added :mod:`~isaaclab.utils.backend_utils` module with utilities for managing simulation backends. + +Changed +^^^^^^^ + +* Refactored the asset classes to follow a multi-backend architecture. The core :mod:`isaaclab.assets` + module now provides abstract base classes that define the interface, while backend-specific + implementations are provided in separate packages (e.g., ``isaaclab_physx``). +* The concrete :class:`~isaaclab.assets.Articulation`, :class:`~isaaclab.assets.RigidObject`, + and :class:`~isaaclab.assets.RigidObjectCollection` classes in the ``isaaclab`` package + now inherit from their respective base classes, and using the backend-specific implementations provided + in the ``isaaclab_physx`` package, provide the default PhysX-based implementation. +* Moved :class:`DeformableObject`, :class:`DeformableObjectCfg`, and :class:`DeformableObjectData` + to the ``isaaclab_physx`` package since deformable bodies are specific to PhysX simulation. +* Moved :class:`SurfaceGripper` and :class:`SurfaceGripperCfg` to the ``isaaclab_physx`` package + since surface grippers rely on PhysX-specific contact APIs. + +Deprecated +^^^^^^^^^^ + +* Deprecated the ``root_physx_view`` property on :class:`~isaaclab.assets.Articulation`, + :class:`~isaaclab.assets.RigidObject`, and :class:`~isaaclab.assets.RigidObjectCollection` + in favor of the backend-agnostic ``root_view`` property. + +* Deprecated the ``object_*`` naming convention in :class:`~isaaclab.assets.RigidObjectCollection` + and :class:`~isaaclab.assets.RigidObjectCollectionData` in favor of ``body_*``: + + **RigidObjectCollection methods:** + + * ``write_object_state_to_sim()`` → use ``write_body_state_to_sim()`` + * ``write_object_link_state_to_sim()`` → use ``write_body_link_state_to_sim()`` + * ``write_object_pose_to_sim()`` → use ``write_body_pose_to_sim()`` + * ``write_object_link_pose_to_sim()`` → use ``write_body_link_pose_to_sim()`` + * ``write_object_com_pose_to_sim()`` → use ``write_body_com_pose_to_sim()`` + * ``write_object_velocity_to_sim()`` → use ``write_body_com_velocity_to_sim()`` + * ``write_object_com_velocity_to_sim()`` → use ``write_body_com_velocity_to_sim()`` + * ``write_object_link_velocity_to_sim()`` → use ``write_body_link_velocity_to_sim()`` + * ``find_objects()`` → use ``find_bodies()`` + + **RigidObjectCollectionData properties:** + + * ``default_object_state`` → use ``default_body_state`` + * ``object_names`` → use ``body_names`` + * ``object_pose_w``, ``object_pos_w``, ``object_quat_w`` → use ``body_pose_w``, ``body_pos_w``, ``body_quat_w`` + * ``object_vel_w``, ``object_lin_vel_w``, ``object_ang_vel_w`` → use ``body_vel_w``, ``body_lin_vel_w``, ``body_ang_vel_w`` + * ``object_acc_w``, ``object_lin_acc_w``, ``object_ang_acc_w`` → use ``body_acc_w``, ``body_lin_acc_w``, ``body_ang_acc_w`` + * And all other ``object_*`` properties (see :ref:`migrating-to-isaaclab-3-0` for complete list). + +Migration +^^^^^^^^^ + +* See :ref:`migrating-to-isaaclab-3-0` for detailed migration instructions. + + +1.0.0 (2026-01-30) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a tool to find hard-coded quaternions in the codebase and help user convert them to the new XYZW ordering. + +Changed +^^^^^^^ + +* Changed the quaternion ordering to match warp, PhysX, and Newton native XYZW quaternion ordering. + + +0.54.5 (2026-01-30) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :meth:`~isaaclab.utils.timer.Timer.get_timer_statistics` to get the statistics of the elapsed time of a timer. + +Changed +^^^^^^^ + +* Changed :class:`~isaaclab.utils.timer.Timer` class to use the online Welford's algorithm to compute the mean and standard deviation of the elapsed time. + + +0.54.4 (2026-02-04) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :class:`~isaaclab.envs.mdp.actions.JointPositionToLimitsAction` and + :class:`~isaaclab.envs.mdp.actions.EMAJointPositionToLimitsAction` ignoring + ``preserve_order=True`` when the number of specified joints matches the total + number of joints in the asset. The optimization that replaced joint indices with + ``slice(None)`` now correctly checks for the ``preserve_order`` flag. + + +0.54.3 (2026-01-28) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Moved :mod:`isaaclab.sensors.tacsl_sensor` to :mod:`isaaclab_contrib.sensors.tacsl_sensor` module, + since it is not completely ready for release yet. + + +0.54.2 (2026-01-25) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added test suite for ray caster patterns with comprehensive parameterized tests. + +Fixed +^^^^^ + +* Fixed incorrect horizontal angle calculation in :func:`~isaaclab.sensors.ray_caster.patterns.patterns.lidar_pattern` + that caused the actual angular resolution to differ from the requested resolution. + + +0.54.1 (2026-01-28) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Teleop: update carb settings to be compatible with Isaac Sim 6.0/Kit XR 110.0 + + +0.54.0 (2026-01-13) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added Fabric backend support to :class:`~isaaclab.sim.views.XformPrimView` for GPU-accelerated + batch transform operations on all Boundable prims using Warp kernels. +* Added :mod:`~isaaclab.sim.utils.fabric_utils` module with Warp kernels for efficient Fabric matrix operations. + +Changed +^^^^^^^ + +* Changed :class:`~isaaclab.sensors.camera.Camera` to use Fabric backend for faster pose queries. + + +0.53.2 (2026-01-14) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.assets.utils.wrench_composer.WrenchComposer` to compose forces and torques at the body's center of mass frame. +* Added :meth:`~isaaclab.assets.Articulation.instantaneous_wrench_composer` to add or set instantaneous external wrenches to the articulation. +* Added :meth:`~isaaclab.assets.Articulation.permanent_wrench_composer` to add or set permanent external wrenches to the articulation. +* Added :meth:`~isaaclab.assets.RigidObject.instantaneous_wrench_composer` to add or set instantaneous external wrenches to the rigid object. +* Added :meth:`~isaaclab.assets.RigidObject.permanent_wrench_composer` to add or set permanent external wrenches to the rigid object. +* Added :meth:`~isaaclab.assets.RigidObjectCollection.instantaneous_wrench_composer` to add or set instantaneous external wrenches to the rigid object collection. +* Added :meth:`~isaaclab.assets.RigidObjectCollection.permanent_wrench_composer` to add or set permanent external wrenches to the rigid object collection. +* Added unit tests for the wrench composer. +* Added kernels for the wrench composer in the :mod:`isaaclab.utils.warp.kernels` module. + +Changed +^^^^^^^ + +* Deprecated :meth:`~isaaclab.assets.Articulation.set_external_force_and_torque` in favor of :meth:`~isaaclab.assets.Articulation.permanent_wrench_composer.set_forces_and_torques`. +* Deprecated :meth:`~isaaclab.assets.RigidObject.set_external_force_and_torque` in favor of :meth:`~isaaclab.assets.RigidObject.permanent_wrench_composer.set_forces_and_torques`. +* Deprecated :meth:`~isaaclab.assets.RigidObjectCollection.set_external_force_and_torque` in favor of :meth:`~isaaclab.assets.RigidObjectCollection.permanent_wrench_composer.set_forces_and_torques`. +* Modified the tests of the articulation, rigid object, and rigid object collection to use the new permanent and instantaneous external wrench functions and test them. + +0.53.1 (2026-01-08) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added function :func:`~isaaclab.sim.utils.prims.change_prim_property` to change attributes on a USD prim. + This replaces the previously used USD command ``ChangeProperty`` that depends on Omniverse Kit API. + +Changed +^^^^^^^ + +* Replaced occurrences of ``ChangeProperty`` USD command to :func:`~isaaclab.sim.utils.prims.change_prim_property`. + + +0.53.0 (2026-01-07) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.sim.views.XformPrimView` class to provide a + view of the USD Xform operations. Compared to Isaac Sim implementation, + this class optimizes several operations using USD SDF API. + +Changed +^^^^^^^ + +* Switched the sensor classes to use the :class:`~isaaclab.sim.views.XformPrimView` + class for the internal view wherever applicable. + +Removed +^^^^^^^ + +* Removed the usage of :class:`isaacsim.core.utils.prims.XformPrim` + class from the sensor classes. + + +0.52.2 (2026-01-06) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Improved logic for the URDF importer extension version pinning: the older extension version + is now pinned only on Isaac Sim 5.1 and later, while older Isaac Sim versions no longer + attempt to pin to a version that does not exist. + + +0.52.1 (2026-01-02) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed FrameTransformer body name collision when tracking bodies with the same name but different hierarchical paths + (e.g., Robot/left_hand vs Robot_1/left_hand). The sensor now uses the full prim path (with env_* patterns normalized) + as the unique body identifier instead of just the leaf body name. This ensures bodies at different hierarchy levels + are tracked separately. The change is backwards compatible: user-facing frame names still default to leaf names when + not explicitly provided, while internal body tracking uses full paths to avoid collisions. Works for both + environment-scoped paths (e.g., /World/envs/env_0/Robot) and non-environment paths (e.g., /World/Robot). + + +0.52.0 (2026-01-02) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :mod:`~isaaclab.sim.utils.transforms` module to handle USD Xform operations. +* Added passing of ``stage`` to the :func:`~isaaclab.sim.utils.prims.create_prim` function + inside spawning functions to allow for the creation of prims in a specific stage. + +Changed +^^^^^^^ + +* Changed :func:`~isaaclab.sim.utils.prims.create_prim` function to use the :mod:`~isaaclab.sim.utils.transforms` + module for USD Xform operations. It removes the usage of Isaac Sim's XformPrim class. + + +0.51.2 (2025-12-30) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :attr:`~isaaclab.managers.ObservationManager.get_active_iterable_terms` + to handle observation data when not concatenated along the last dimension. + + +0.51.1 (2025-12-29) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :func:`~isaaclab.utils.version.get_isaac_sim_version` to get the version of Isaac Sim. + This function caches the version of Isaac Sim and returns it immediately if it has already been computed. + This helps avoid parsing the VERSION file from disk multiple times. + +Changed +^^^^^^^ + +* Changed the function :meth:`~isaaclab.utils.version.compare_versions` to use :mod:`packaging.version.Version` module. +* Changed occurrences of :func:`isaacsim.core.version.get_version` to :func:`~isaaclab.utils.version.get_isaac_sim_version`. + +Removed +^^^^^^^ + +* Removed storing of Isaac Sim version inside the environment base classes defined inside + :mod:`isaaclab.envs` module. + + +0.51.0 (2025-12-29) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added tests for the :mod:`isaaclab.sim.utils.prims` module. +* Added tests for the :mod:`isaaclab.sim.utils.stage` module. +* Created :mod:`isaaclab.sim.utils.legacy` sub-module to keep deprecated functions. + +Removed +^^^^^^^ + +* Removed many unused USD prim and stage related operations from the :mod:`isaaclab.sim.utils` module. +* Moved :mod:`isaaclab.sim.utils.nucleus` sub-module to the ``tests/deps/isaacsim`` directory as it + is only being used for Isaac Sim check scripts. + +Changed +^^^^^^^ + +* Changed the organization of the :mod:`isaaclab.sim.utils` module to make it clearer which functions + are related to the stage and which are related to the prims. +* Modified imports of :mod:`~isaaclab.sim.utils.stage` and :mod:`~isaaclab.sim.utils.prims` modules + to only use the :mod:`isaaclab.sim.utils` module. +* Moved ``logger.py`` to the :mod:`isaaclab.utils` module. + + +0.50.7 (2025-12-29) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Moved ``pretrained_checkpoint.py`` to the :mod:`isaaclab_rl.utils` module. + + +0.50.6 (2025-12-18) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed issue where :meth:~isaaclab.envs.mdp.observations.body_pose_w` was modifying the original body pose data + when using slice or int for body_ids in the observation config. A clone of the data is now created to avoid modifying + the original data. + + +0.50.5 (2025-12-15) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.sensors.MultiMeshRayCaster` sensor to support tracking of dynamic meshes for ray-casting. + We keep the previous implementation of :class:`~isaaclab.sensors.RayCaster` for backwards compatibility. +* Added :mod:`isaaclab.utils.mesh` sub-module to perform various Trimesh and USD Mesh related operations. + + +0.50.4 (2025-12-15) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`~isaaclab.sim.PhysxCfg.enable_external_forces_every_iteration` to enable external forces every position + iteration. This can help improve the accuracy of velocity updates. Consider enabling this flag if the velocities + generated by the simulation are noisy. +* Added warning when :attr:`~isaaclab.sim.PhysxCfg.enable_external_forces_every_iteration` is set to False and + the solver type is TGS. + + +0.50.3 (2025-12-11) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed missing mesh collision approximation attribute when running :class:`~isaaclab.sim.converters.MeshConverter`. + The collision approximation attribute is now properly set on the USD prim when converting meshes with mesh collision + properties. + + +0.50.2 (2025-11-21) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Prevent randomizing mass to zero in :meth:`~isaaclab.envs.mdp.events.randomize_mass_by_scale` to avoid physics errors. + + +0.50.1 (2025-11-25) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed advanced indexing issue in resetting prev action + in :class:`~isaaclab.envs.mdp.actions.JointPositionToLimitsAction` . + + +0.50.0 (2025-12-8) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Implemented ability to attach an imu sensor to xform primitives in a usd file. This PR is based on work by '@GiulioRomualdi' + here: #3094 Addressing issue #3088. + + +0.49.3 (2025-12-03) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`G1TriHandUpperBodyMotionControllerGripperRetargeter` and :class:`G1TriHandUpperBodyMotionControllerGripperRetargeterCfg` for retargeting the gripper state from motion controllers. +* Added unit tests for the retargeters. + + +0.49.2 (2025-11-17) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`~isaaclab.sensors.contact_sensor.ContactSensorCfg.track_friction_forces` to toggle tracking of friction forces between sensor bodies and filtered bodies. +* Added :attr:`~isaaclab.sensors.contact_sensor.ContactSensorData.friction_forces_w` data field for tracking friction forces. + + +0.49.1 (2025-11-26) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed import from ``isaacsim.core.utils.prims`` to ``isaaclab.sim.utils.prims`` across repo to reduce IsaacLab dependencies. + +0.49.0 (2025-11-10) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Updated the URDF Importer version to 2.4.31 to avoid issues with merging joints on the latest URDF importer in Isaac Sim 5.1 + + +0.48.9 (2025-11-21) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Add navigation state API to IsaacLabManagerBasedRLMimicEnv +* Add optional custom recorder config to MimicEnvCfg + + +0.48.8 (2025-10-15) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`preserve_order` flag to :class:`~isaaclab.envs.mdp.actions.actions_cfg.JointPositionToLimitsActionCfg` + + +0.48.7 (2025-11-25) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed import from ``isaaclab.sim.utils`` to ``isaaclab.sim.utils.stage`` in ``isaaclab.devices.openxr.xr_anchor_utils.py`` + to properly propagate the Isaac Sim stage context. + + +0.48.6 (2025-11-18) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added OpenXR motion controller support for the G1 robot locomanipulation environment + ``Isaac-PickPlace-Locomanipulation-G1-Abs-v0``. This enables teleoperation using XR motion controllers + in addition to hand tracking. +* Added :class:`OpenXRDeviceMotionController` for motion controller-based teleoperation with headset anchoring control. +* Added motion controller-specific retargeters: + * :class:`G1TriHandControllerUpperBodyRetargeterCfg` for upper body and hand control using motion controllers. + * :class:`G1LowerBodyStandingControllerRetargeterCfg` for lower body control using motion controllers. + + +0.48.5 (2025-11-14) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed import from ``isaacsim.core.utils.stage`` to ``isaaclab.sim.utils.stage`` to reduce IsaacLab dependencies. + + +0.48.4 (2025-11-14) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Refactored modules related to the actuator configs in order to remediate a circular import necessary to support future + actuator drive model improvements. + + +0.48.3 (2025-11-13) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Moved retargeter and device declaration out of factory and into the devices/retargeters themselves. + + +0.48.2 (2025-11-13) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed from using :meth:`isaacsim.core.utils.torch.set_seed` to :meth:`~isaaclab.utils.seed.configure_seed` + + +0.48.1 (2025-11-10) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.devices.haply.HaplyDevice` class for SE(3) teleoperation with dual Haply Inverse3 and Versegrip devices, + supporting robot manipulation with haptic feedback. +* Added demo script ``scripts/demos/haply_teleoperation.py`` and documentation guide in + ``docs/source/how-to/haply_teleoperation.rst`` for Haply-based robot teleoperation. + + +0.48.0 (2025-11-03) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Detected contacts are reported with the threshold of 0.0 (instead of 1.0). This increases the sensitivity of contact + detection. + +Fixed +^^^^^ + +* Removed passing the boolean flag to :meth:`isaaclab.sim.schemas.activate_contact_sensors` when activating contact + sensors. This was incorrectly modifying the threshold attribute to 1.0 when contact sensors were activated. + + +0.47.11 (2025-11-03) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the bug where effort limits were being overridden in :class:`~isaaclab.actuators.ActuatorBase` when the ``effort_limit`` parameter is set to None. +* Corrected the unit tests for three effort limit scenarios with proper assertions + + +0.47.10 (2025-11-06) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``num_rerenders_on_reset`` parameter to ManagerBasedEnvCfg and DirectRLEnvCfg to configure the number + of render steps to perform after reset. This enables more control over DLSS rendering behavior after reset. + +Changed +^^^^^^^ + +* Added deprecation warning for ``rerender_on_reset`` parameter in ManagerBasedEnv and DirectRLEnv. + + +0.47.9 (2025-11-05) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Fixed termination term bookkeeping in :class:`~isaaclab.managers.TerminationManager`: + per-step termination and last-episode termination bookkeeping are now separated. + last-episode dones are now updated once per step from all term outputs, avoiding per-term overwrites + and ensuring Episode_Termination metrics reflect the actual triggering terms. + + +0.47.8 (2025-11-06) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added parameter :attr:`~isaaclab.terrains.TerrainImporterCfg.use_terrain_origins` to allow generated sub terrains with grid origins. + + +0.47.7 (2025-10-31) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed Pink IK controller qpsolver from osqp to daqp. +* Changed Null Space matrix computation in Pink IK's Null Space Posture Task to a faster matrix pseudo inverse computation. + + +0.47.6 (2025-11-01) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed an issue in recurrent policy evaluation in RSL-RL framework where the recurrent state was not reset after an episode termination. + + +0.47.5 (2025-10-30) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added docstrings notes to clarify the friction coefficient modeling in Isaac Sim 4.5 and 5.0. + + +0.47.4 (2025-10-30) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Enhanced :meth:`~isaaclab.managers.RecorderManager.export_episodes` method to support customizable sequence of demo IDs: + + - Added argument ``demo_ids`` to :meth:`~isaaclab.managers.RecorderManager.export_episodes` to accept a sequence of integers + for custom episode identifiers. + +* Enhanced :meth:`~isaaclab.utils.datasets.HDF5DatasetFileHandler.write_episode` method to support customizable episode identifiers: + + - Added argument ``demo_id`` to :meth:`~isaaclab.utils.datasets.HDF5DatasetFileHandler.write_episode` to accept a custom integer + for episode identifier. + + +0.47.3 (2025-10-22) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the data type conversion in :class:`~isaaclab.sensors.tiled_camera.TiledCamera` to + support the correct data type when converting from numpy arrays to warp arrays on the CPU. + + +0.47.2 (2025-10-17) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :meth:`~isaaclab.sim.utils.resolve_prim_pose` to resolve the pose of a prim with respect to another prim. +* Added :meth:`~isaaclab.sim.utils.resolve_prim_scale` to resolve the scale of a prim in the world frame. + + +0.47.1 (2025-10-17) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Suppressed yourdfpy warnings when trying to load meshes from hand urdfs in dex_retargeting. These mesh files are not + used by dex_retargeting, but the parser is incorrectly configured by dex_retargeting to load them anyway which results + in warning spam. + + +0.47.0 (2025-10-14) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Removed pickle utilities for saving and loading configurations as pickle contains security vulnerabilities in its APIs. + Configurations can continue to be saved and loaded through yaml. + + +0.46.11 (2025-10-15) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added support for modifying the :attr:`/rtx/domeLight/upperLowerStrategy` Sim rendering setting. + + +0.46.10 (2025-10-13) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ARM64 architecture for pink ik and dex-retargetting setup installations. + + +0.46.9 (2025-10-09) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :meth:`~isaaclab.devices.keyboard.se3_keyboard.Se3Keyboard.__del__` to use the correct method name + for unsubscribing from keyboard events "unsubscribe_to_keyboard_events" instead of "unsubscribe_from_keyboard_events". + + +0.46.8 (2025-10-02) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed scaling factor for retargeting of GR1T2 hand. + + +0.46.7 (2025-09-30) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed finger joint indices with manus extension. + + +0.46.6 (2025-09-30) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added argument :attr:`traverse_instance_prims` to :meth:`~isaaclab.sim.utils.get_all_matching_child_prims` and + :meth:`~isaaclab.sim.utils.get_first_matching_child_prim` to control whether to traverse instance prims + during the traversal. Earlier, instanced prims were skipped since :meth:`Usd.Prim.GetChildren` did not return + instanced prims, which is now fixed. + +Changed +^^^^^^^ + +* Made parsing of instanced prims in :meth:`~isaaclab.sim.utils.get_all_matching_child_prims` and + :meth:`~isaaclab.sim.utils.get_first_matching_child_prim` as the default behavior. +* Added parsing of instanced prims in :meth:`~isaaclab.sim.utils.make_uninstanceable` to make all prims uninstanceable. + + +0.46.5 (2025-10-14) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Exposed parameter :attr:`~isaaclab.sim.spawners.PhysxCfg.solve_articulation_contact_last` + to configure USD attribute ``physxscene:solveArticulationContactLast``. This parameter may + help improve solver stability with grippers, which previously required reducing simulation time-steps. + :class:`~isaaclab.sim.spawners.PhysxCfg` + + +0.46.4 (2025-10-06) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Fixed :attr:`~isaaclab.sim.simulation_context.SimulationContext.device` to return the device from the configuration. + Previously, it was returning the device from the simulation manager, which was causing a performance overhead. + + +0.46.3 (2025-09-17) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Modified setter to support for viscous and dynamic joint friction coefficients in articulation based on IsaacSim 5.0. +* Added randomization of viscous and dynamic joint friction coefficients in event term. + + +0.46.2 (2025-09-13) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Fixed missing actuator indices in :meth:`~isaaclab.envs.mdp.events.randomize_actuator_gains` + + +0.46.1 (2025-09-10) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Moved IO descriptors output directory to a subfolder under the task log directory. + + +0.46.0 (2025-09-06) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added argument :attr:`traverse_instance_prims` to :meth:`~isaaclab.sim.utils.get_all_matching_child_prims` and + :meth:`~isaaclab.sim.utils.get_first_matching_child_prim` to control whether to traverse instance prims + during the traversal. Earlier, instanced prims were skipped since :meth:`Usd.Prim.GetChildren` did not return + instanced prims, which is now fixed. + +Changed +^^^^^^^ + +* Made parsing of instanced prims in :meth:`~isaaclab.sim.utils.get_all_matching_child_prims` and + :meth:`~isaaclab.sim.utils.get_first_matching_child_prim` as the default behavior. +* Added parsing of instanced prims in :meth:`~isaaclab.sim.utils.make_uninstanceable` to make all prims uninstanceable. + + +0.45.16 (2025-09-06) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added teleoperation environments for Unitree G1. This includes an environment with lower body fixed and upper body + controlled by IK, and an environment with the lower body controlled by a policy and the upper body controlled by IK. + + +0.45.15 (2025-09-05) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added action terms for using RMPFlow in Manager-Based environments. + + +0.45.14 (2025-09-08) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.ui.xr_widgets.TeleopVisualizationManager` and :class:`~isaaclab.ui.xr_widgets.XRVisualization` + classes to provide real-time visualization of teleoperation and inverse kinematics status in XR environments. + + +0.45.13 (2025-09-08) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.devices.openxr.manus_vive.ManusVive` to support teleoperation with Manus gloves and Vive trackers. + + +0.45.12 (2025-09-05) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.envs.mdp.actions.SurfaceGripperBinaryAction` for supporting surface grippers in Manager-Based workflows. + +Changed +^^^^^^^ + +* Added AssetBase inheritance for :class:`~isaaclab.assets.surface_gripper.SurfaceGripper`. + + +0.45.11 (2025-09-04) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixes a high memory usage and perf slowdown issue in episode data by removing the use of torch.cat when appending to the episode data + at each timestep. The use of torch.cat was causing the episode data to be copied at each timestep, which causes high memory usage and + significant performance slowdown when recording longer episode data. +* Patches the configclass to allow validate dict with key is not a string. + +Added +^^^^^ + +* Added optional episode metadata (ep_meta) to be stored in the HDF5 data attributes. +* Added option to record data pre-physics step. +* Added joint_target data to episode data. Joint target data can be optionally recorded by the user and replayed to improve + determinism of replay. + + +0.45.10 (2025-09-02) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed regression in reach task configuration where the gripper command was being returned. +* Added :attr:`~isaaclab.devices.Se3GamepadCfg.gripper_term` to :class:`~isaaclab.devices.Se3GamepadCfg` + to control whether the gamepad device should return a gripper command. +* Added :attr:`~isaaclab.devices.Se3SpaceMouseCfg.gripper_term` to :class:`~isaaclab.devices.Se3SpaceMouseCfg` + to control whether the spacemouse device should return a gripper command. +* Added :attr:`~isaaclab.devices.Se3KeyboardCfg.gripper_term` to :class:`~isaaclab.devices.Se3KeyboardCfg` + to control whether the keyboard device should return a gripper command. + + +0.45.9 (2025-08-27) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed removing import of pink_ik controller from isaaclab.controllers which is causing pinocchio import error. + + +0.45.8 (2025-07-25) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Created :attr:`~isaaclab.controllers.pink_ik.PinkIKControllerCfg.target_eef_link_names` to :class:`~isaaclab.controllers.pink_ik.PinkIKControllerCfg` + to specify the target end-effector link names for the pink inverse kinematics controller. + +Changed +^^^^^^^ + +* Updated pink inverse kinematics controller configuration for the following tasks (Isaac-PickPlace-GR1T2, Isaac-NutPour-GR1T2, Isaac-ExhaustPipe-GR1T2) + to increase end-effector tracking accuracy and speed. Also added a null-space regularizer that enables turning on of waist degrees-of-freedom. +* Improved the test_pink_ik script to more comprehensive test on controller accuracy. Also, migrated to use pytest. With the current IK controller + improvements, our unit tests pass position and orientation accuracy test within **(1 mm, 1 degree)**. Previously, the position accuracy tolerances + were set to **(30 mm, 10 degrees)**. +* Included a new config parameter :attr:`fail_on_ik_error` to :class:`~isaaclab.controllers.pink_ik.PinkIKControllerCfg` + to control whether the IK controller raise an exception if robot joint limits are exceeded. In the case of an exception, the controller will hold the + last joint position. This adds to stability of the controller and avoids operator experiencing what is perceived as sudden large delays in robot control. + + +0.45.7 (2025-08-21) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added periodic logging when checking if a USD path exists on a Nucleus server + to improve user experience when the checks takes a while. + + +0.45.6 (2025-08-22) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :meth:`~isaaclab.envs.mdp.events.randomize_rigid_body_com` to broadcasts the environment ids. + + +0.45.5 (2025-08-21) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :meth:`~isaaclab.assets.Articulation.write_joint_friction_coefficient_to_sim` to set the friction coefficients in the simulation. +* Fixed :meth:`~isaaclab.assets.Articulation.write_joint_dynamic_friction_coefficient_to_sim` to set the friction coefficients in the simulation.* Added :meth:`~isaaclab.envs.ManagerBasedEnvCfg.export_io_descriptors` to toggle the export of the IO descriptors. +* Fixed :meth:`~isaaclab.assets.Articulation.write_joint_viscous_friction_coefficient_to_sim` to set the friction coefficients in the simulation. + + + +0.45.4 (2025-08-21) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added unit tests for :class:`~isaaclab.sensor.sensor_base` + + +0.45.3 (2025-08-20) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :meth:`isaaclab.envs.mdp.terminations.joint_effort_out_of_limit` so that it correctly reports whether a joint + effort limit has been violated. Previously, the implementation marked a violation when the applied and computed + torques were equal; in fact, equality should indicate no violation, and vice versa. + + +0.45.2 (2025-08-18) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :meth:`~isaaclab.managers.ObservationManager.get_IO_descriptors` to export the IO descriptors for the observation manager. +* Added :meth:`~isaaclab.envs.ManagerBasedEnvCfg.io_descriptors_output_dir` to configure the directory to export the IO descriptors to. +* Added :meth:`~isaaclab.envs.ManagerBasedEnvCfg.export_io_descriptors` to toggle the export of the IO descriptors. +* Added the option to export the Observation and Action of the managed environments into a YAML file. This can be used to more easily + deploy policies trained in Isaac Lab. + + +0.45.1 (2025-08-16) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added validations for scale-based randomization ranges across mass, actuator, joint, and tendon parameters. + +Changed +^^^^^^^ + +* Refactored randomization functions into classes with initialization-time checks to avoid runtime overhead. + + +0.45.0 (2025-08-07) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`~isaaclab.sensors.contact_sensor.ContactSensorCfg.track_contact_points` to toggle tracking of contact + point locations between sensor bodies and filtered bodies. +* Added :attr:`~isaaclab.sensors.contact_sensor.ContactSensorCfg.max_contact_data_per_prim` to configure the maximum + amount of contacts per sensor body. +* Added :attr:`~isaaclab.sensors.contact_sensor.ContactSensorData.contact_pos_w` data field for tracking contact point + locations. + + +0.44.12 (2025-08-12) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed IndexError in :meth:`isaaclab.envs.mdp.events.reset_joints_by_scale`, + :meth:`isaaclab.envs.mdp.events.reset_joints_by_offsets` by adding dimension to env_ids when indexing. + + +0.44.11 (2025-08-11) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed rendering preset mode when an experience CLI arg is provided. + + +0.44.10 (2025-08-06) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the old termination manager in :class:`~isaaclab.managers.TerminationManager` term_done logging that + logs the instantaneous term done count at reset. This let to inaccurate aggregation of termination count, + obscuring the what really happening during the training. Instead we log the episodic term done. + + +0.44.9 (2025-07-30) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``from __future__ import annotations`` to manager_based_rl_mimic_env.py to fix Sphinx + doc warnings for IsaacLab Mimic docs. + + +0.44.8 (2025-07-30) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Improved handling of deprecated flag :attr:`~isaaclab.sensors.RayCasterCfg.attach_yaw_only`. + Previously, the flag was only handled if it was set to True. This led to a bug where the yaw was not accounted for + when the flag was set to False. +* Fixed the handling of interval-based events inside :class:`~isaaclab.managers.EventManager` to properly handle + their resets. Previously, only class-based events were properly handled. + + +0.44.7 (2025-07-30) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a new argument ``is_global`` to :meth:`~isaaclab.assets.Articulation.set_external_force_and_torque`, + :meth:`~isaaclab.assets.RigidObject.set_external_force_and_torque`, and + :meth:`~isaaclab.assets.RigidObjectCollection.set_external_force_and_torque` allowing to set external wrenches + in the global frame directly from the method call rather than having to set the frame in the configuration. + +Removed +^^^^^^^^ + +* Removed :attr:`xxx_external_wrench_frame` flag from asset configuration classes in favor of direct argument + passed to the :meth:`set_external_force_and_torque` function. + + +0.44.6 (2025-07-28) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Tweak default behavior for rendering preset modes. + + +0.44.5 (2025-07-28) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :meth:`isaaclab.scene.reset_to` to properly accept None as valid argument. +* Added tests to verify that argument types. + + +0.44.4 (2025-07-22) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added safe callbacks for stage in memory attaching. +* Remove on prim deletion callback workaround + + +0.44.3 (2025-07-21) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed rendering preset mode regression. + + +0.44.2 (2025-07-22) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated teleop scripts to print to console vs omni log. + + +0.44.1 (2025-07-17) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated test_pink_ik.py test case to pytest format. + + +0.44.0 (2025-07-21) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed the way clipping is handled for :class:`~isaaclab.actuator.DCMotor` for torque-speed points in when in + negative power regions. + +Added +^^^^^ + +* Added unit tests for :class:`~isaaclab.actuator.ImplicitActuator`, :class:`~isaaclab.actuator.IdealPDActuator`, + and :class:`~isaaclab.actuator.DCMotor` independent of :class:`~isaaclab.assets.Articulation` + + +0.43.0 (2025-07-21) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updates torch version to 2.7.0 and torchvision to 0.22.0. + Some dependencies now require torch>=2.6, and given the vulnerabilities in Torch 2.5.1, + we are updating the torch version to 2.7.0 to also include Blackwell support. Since Isaac Sim 4.5 has not updated the + torch version, we are now overwriting the torch installation step in isaaclab.sh when running ``./isaaclab.sh -i``. + + +0.42.26 (2025-06-29) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added MangerBasedRLEnv support for composite gym observation spaces. +* A test for the composite gym observation spaces in ManagerBasedRLEnv is added to ensure that the observation spaces + are correctly configured base on the clip. + + +0.42.25 (2025-07-11) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`~isaaclab.sensors.ContactSensorData.force_matrix_w_history` that tracks the history of the filtered + contact forces in the world frame. + + +0.42.24 (2025-06-25) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added new curriculum mdp :func:`~isaaclab.envs.mdp.curriculums.modify_env_param` and + :func:`~isaaclab.envs.mdp.curriculums.modify_env_param` that enables flexible changes to any configurations in the + env instance + + +0.42.23 (2025-07-11) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :meth:`isaaclab.envs.mdp.events.reset_joints_by_scale`, :meth:`isaaclab.envs.mdp.events.reset_joints_by_offsets` + restricting the resetting joint indices be that user defined joint indices. + + +0.42.22 (2025-07-11) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed missing attribute in :class:`~isaaclab.sensors.ray_caster.RayCasterCamera` class and its reset method when no + env_ids are passed. + + +0.42.21 (2025-07-09) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added input param ``update_history`` to :meth:`~isaaclab.managers.ObservationManager.compute` + to control whether the history buffer should be updated. +* Added unit test for :class:`~isaaclab.envs.ManagerBasedEnv`. + +Fixed +^^^^^ + +* Fixed :class:`~isaaclab.envs.ManagerBasedEnv` and :class:`~isaaclab.envs.ManagerBasedRLEnv` to not update the history + buffer on recording. + + +0.42.20 (2025-07-10) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added unit tests for multiple math functions: + :func:`~isaaclab.utils.math.scale_transform`. + :func:`~isaaclab.utils.math.unscale_transform`. + :func:`~isaaclab.utils.math.saturate`. + :func:`~isaaclab.utils.math.normalize`. + :func:`~isaaclab.utils.math.copysign`. + :func:`~isaaclab.utils.math.convert_quat`. + :func:`~isaaclab.utils.math.quat_conjugate`. + :func:`~isaaclab.utils.math.quat_from_euler_xyz`. + :func:`~isaaclab.utils.math.quat_from_matrix`. + :func:`~isaaclab.utils.math.euler_xyz_from_quat`. + :func:`~isaaclab.utils.math.matrix_from_euler`. + :func:`~isaaclab.utils.math.quat_from_angle_axis`. + :func:`~isaaclab.utils.math.axis_angle_from_quat`. + :func:`~isaaclab.utils.math.skew_symmetric_matrix`. + :func:`~isaaclab.utils.math.combine_transform`. + :func:`~isaaclab.utils.math.subtract_transform`. + :func:`~isaaclab.utils.math.compute_pose_error`. + +Changed +^^^^^^^ + +* Changed the implementation of :func:`~isaaclab.utils.math.copysign` to better reflect the documented functionality. + + +0.42.19 (2025-07-09) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added clone_in_fabric config flag to :class:`~isaaclab.scene.interactive_scene_cfg.InteractiveSceneCfg` +* Enable clone_in_fabric for envs which work with limited benchmark_non_rl.py script + + +0.42.18 (2025-07-07) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed texture and color randomization to use new replicator functional APIs. + + +0.42.17 (2025-07-08) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed hanging quat_rotate calls to point to quat_apply in :class:`~isaaclab.assets.articulation.ArticulationData` and + :class:`~isaaclab.assets.articulation.RigidObjectCollectionData` + + +0.42.16 (2025-07-08) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ability to set platform height independent of object height for trimesh terrains. + + +0.42.15 (2025-07-01) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`abs_height_noise` and :attr:`rel_height_noise` to give minimum and maximum absolute and relative noise to + :class:`isaaclab.terrrains.trimesh.MeshRepeatedObjectsTerrainCfg` +* Added deprecation warnings to the existing :attr:`max_height_noise` but still functions. + + +0.42.14 (2025-07-03) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed unittest tests that are floating inside pytests for articulation and rendering + + +0.42.13 (2025-07-07) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated gymnasium to v1.2.0. This update includes fixes for a memory leak that appears when recording + videos with the ``--video`` flag. + + +0.42.12 (2025-06-27) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added unit test for :func:`~isaaclab.utils.math.quat_inv`. + +Fixed +^^^^^ + +* Fixed the implementation mistake in :func:`~isaaclab.utils.math.quat_inv`. + + +0.42.11 (2025-06-25) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :func:`~isaaclab.utils.dict.update_class_from_dict` preventing setting flat Iterables with different lengths. + + +0.42.10 (2025-06-25) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``sample_bias_per_component`` flag to :class:`~isaaclab.utils.noise.noise_model.NoiseModelWithAdditiveBias` + to enable independent per-component bias sampling, which is now the default behavior. If set to False, the previous + behavior of sharing the same bias value across all components is retained. + + +0.42.9 (2025-06-18) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed data inconsistency between read_body, read_link, read_com when write_body, write_com, write_joint performed, in + :class:`~isaaclab.assets.Articulation`, :class:`~isaaclab.assets.RigidObject`, and + :class:`~isaaclab.assets.RigidObjectCollection` +* added pytest that check against these data consistencies + + +0.42.8 (2025-06-24) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* :class:`~isaaclab.utils.noise.NoiseModel` support for manager-based workflows. + +Changed +^^^^^^^ + +* Renamed :func:`~isaaclab.utils.noise.NoiseModel.apply` method to :func:`~isaaclab.utils.noise.NoiseModel.__call__`. + + +0.42.7 (2025-06-12) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed potential issues in :func:`~isaaclab.envs.mdp.events.randomize_visual_texture_material` related to handling + visual prims during texture randomization. + + +0.42.6 (2025-06-11) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Remove deprecated usage of quat_rotate from articulation data class and replace with quat_apply. + + +0.42.5 (2025-05-22) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed collision filtering logic for CPU simulation. The automatic collision filtering feature + currently has limitations for CPU simulation. Collision filtering needs to be manually enabled when using + CPU simulation. + + +0.42.4 (2025-06-03) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Removes the hardcoding to :class:`~isaaclab.terrains.terrain_generator.TerrainGenerator` in + :class:`~isaaclab.terrains.terrain_generator.TerrainImporter` and instead the ``class_type`` is used which is + passed in the ``TerrainGeneratorCfg``. + + +0.42.3 (2025-03-20) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Made separate data buffers for poses and velocities for the :class:`~isaaclab.assets.Articulation`, + :class:`~isaaclab.assets.RigidObject`, and :class:`~isaaclab.assets.RigidObjectCollection` classes. + Previously, the two data buffers were stored together in a single buffer requiring an additional + concatenation operation when accessing the data. +* Cleaned up ordering of members inside the data classes for the assets to make them easier + to comprehend. This reduced the code duplication within the class and made the class + more readable. + + +0.42.2 (2025-05-31) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Updated gymnasium to >= 1.0 +* Added support for specifying module:task_name as task name to avoid module import for ``gym.make`` + + +0.42.1 (2025-06-02) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added time observation functions to ~isaaclab.envs.mdp.observations module, + :func:`~isaaclab.envs.mdp.observations.current_time_s` and :func:`~isaaclab.envs.mdp.observations.remaining_time_s`. + +Changed +^^^^^^^ + +* Moved initialization of ``episode_length_buf`` outside of :meth:`load_managers()` of + :class:`~isaaclab.envs.ManagerBasedRLEnv` to make it available for mdp functions. + + +0.42.0 (2025-06-02) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added support for stage in memory and cloning in fabric. This will help improve performance for scene setup and lower + overall startup time. + + +0.41.0 (2025-05-19) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added simulation schemas for spatial tendons. These can be configured for assets imported + from file formats. +* Added support for spatial tendons. + + +0.40.14 (2025-05-29) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added deprecation warning for :meth:`~isaaclab.utils.math.quat_rotate` and + :meth:`~isaaclab.utils.math.quat_rotate_inverse` + +Changed +^^^^^^^ + +* Changed all calls to :meth:`~isaaclab.utils.math.quat_rotate` and :meth:`~isaaclab.utils.math.quat_rotate_inverse` to + :meth:`~isaaclab.utils.math.quat_apply` and :meth:`~isaaclab.utils.math.quat_apply_inverse` for speed. + + +0.40.13 (2025-05-19) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Raising exceptions in step, render and reset if they occurred inside the initialization callbacks + of assets and sensors.used from the experience files and the double definition is removed. + + +0.40.12 (2025-01-30) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added method :meth:`omni.isaac.lab.assets.AssetBase.set_visibility` to set the visibility of the asset + in the simulation. + + +0.40.11 (2025-05-16) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added support for concatenation of observations along different dimensions in + :class:`~isaaclab.managers.observation_manager.ObservationManager`. + +Changed +^^^^^^^ + +* Updated the :class:`~isaaclab.managers.command_manager.CommandManager` to update the command counter after the + resampling call. + + +0.40.10 (2025-05-16) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed penetration issue for negative border height in :class:`~isaaclab.terrains.terrain_generator.TerrainGeneratorCfg`. + + +0.40.9 (2025-05-20) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed the implementation of :meth:`~isaaclab.utils.math.quat_box_minus` + +Added +^^^^^ + +* Added :meth:`~isaaclab.utils.math.quat_box_plus` +* Added :meth:`~isaaclab.utils.math.rigid_body_twist_transform` + + +0.40.8 (2025-05-15) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :meth:`omni.isaac.lab.sensors.camera.camera.Camera.set_intrinsic_matrices` preventing setting of unused USD + camera parameters. +* Fixed :meth:`omni.isaac.lab.sensors.camera.camera.Camera._update_intrinsic_matrices` preventing unused USD camera + parameters from being used to calculate :attr:`omni.isaac.lab.sensors.camera.CameraData.intrinsic_matrices` +* Fixed :meth:`omni.isaac.lab.spawners.sensors.sensors_cfg.PinholeCameraCfg.from_intrinsic_matrix` preventing setting of + unused USD camera parameters. + + +0.40.7 (2025-05-14) +~~~~~~~~~~~~~~~~~~~ + +* Added a new attribute :attr:`articulation_root_prim_path` to the :class:`~isaaclab.assets.ArticulationCfg` class + to allow explicitly specifying the prim path of the articulation root. + + +0.40.6 (2025-05-14) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Enabled external cameras in XR. + + +0.40.5 (2025-05-23) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added feature for animation recording through baking physics operations into OVD files. + + +0.40.4 (2025-05-17) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed livestreaming options to use ``LIVESTREAM=1`` for WebRTC over public networks and ``LIVESTREAM=2`` for WebRTC over private networks. + + +0.40.3 (2025-05-20) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Made modifications to :func:`isaaclab.envs.mdp.image` to handle image normalization for normal maps. + + +0.40.2 (2025-05-14) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Refactored remove_camera_configs to be a function that can be used in the record_demos and teleop scripts. + + +0.40.1 (2025-05-14) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed spacemouse device add callback function to work with record_demos/teleop_se3_agent scripts. + + +0.40.0 (2025-05-03) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added check in RecorderManager to ensure that the success indicator is only set if the termination manager is present. +* Added semantic tags in :func:`isaaclab.sim.spawners.from_files.spawn_ground_plane`. + This allows for :attr:`semantic_segmentation_mapping` to be used when using the ground plane spawner. + + +0.39.0 (2025-04-01) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the :meth:`~isaaclab.env.mdp.observations.joint_effort` + + +0.38.0 (2025-04-01) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :meth:`~isaaclab.envs.mdp.observations.body_pose_w` +* Added :meth:`~isaaclab.envs.mdp.observations.body_projected_gravity_b` + + +0.37.5 (2025-05-12) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a new teleop configuration class :class:`~isaaclab.devices.DevicesCfg` to support multiple teleoperation + devices declared in the environment configuration file. +* Implemented a factory function to create teleoperation devices based on the device configuration. + + +0.37.4 (2025-05-12) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Remove isaacsim.xr.openxr from openxr experience file. +* Use Performance AR profile for XR rendering. + + +0.37.3 (2025-05-08) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Updated PINK task space action to record processed actions. +* Added new recorder term for recording post step processed actions. + + +0.37.2 (2025-05-06) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Migrated OpenXR device to use the new OpenXR handtracking API from omni.kit.xr.core. + + +0.37.1 (2025-05-05) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Removed xr rendering mode. + + +0.37.0 (2025-04-24) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated pytorch to latest 2.7.0 with cuda 12.8 for Blackwell support. + Torch is now installed as part of the isaaclab.sh/bat scripts to ensure the correct version is installed. +* Removed :attr:`~isaaclab.sim.spawners.PhysicsMaterialCfg.improve_patch_friction` as it has been deprecated and removed from the simulation. + The simulation will always behave as if this attribute is set to true. + + +0.36.23 (2025-04-24) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed ``return_latest_camera_pose`` option in :class:`~isaaclab.sensors.TiledCameraCfg` from not being used to the + argument ``update_latest_camera_pose`` in :class:`~isaaclab.sensors.CameraCfg` with application in both + :class:`~isaaclab.sensors.Camera` and :class:`~isaaclab.sensors.TiledCamera`. + + +0.36.22 (2025-04-23) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^^^ + +* Adds correct type check for ManagerTermBase class in event_manager.py. + + +0.36.21 (2025-04-15) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Removed direct call of qpsovlers library from pink_ik controller and changed solver from quadprog to osqp. + + +0.36.20 (2025-04-09) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added call to set cuda device after each ``app.update()`` call in :class:`~isaaclab.sim.SimulationContext`. + This is now required for multi-GPU workflows because some underlying logic in ``app.update()`` is modifying + the cuda device, which results in NCCL errors on distributed setups. + + +0.36.19 (2025-04-01) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added check in RecorderManager to ensure that the success indicator is only set if the termination manager is present. + + +0.36.18 (2025-03-26) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a dynamic text instruction widget that provides real-time feedback + on the number of successful recordings during demonstration sessions. + + +0.36.17 (2025-03-26) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added override in AppLauncher to apply patch for ``pxr.Gf.Matrix4d`` to work with Pinocchio 2.7.0. + + +0.36.16 (2025-03-25) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Modified rendering mode default behavior when the launcher arg :attr:`enable_cameras` is not set. + + +0.36.15 (2025-03-25) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added near plane distance configuration for XR device. + + +0.36.14 (2025-03-24) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed default render settings in :class:`~isaaclab.sim.SimulationCfg` to None, which means that + the default settings will be used from the experience files and the double definition is removed. + + +0.36.13 (2025-03-24) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added headpose support to OpenXRDevice. + + +0.36.12 (2025-03-19) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added parameter to show warning if Pink IK solver fails to find a solution. + + +0.36.11 (2025-03-19) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed default behavior of :class:`~isaaclab.actuators.ImplicitActuator` if no :attr:`effort_limits_sim` or + :attr:`effort_limit` is set. + + +0.36.10 (2025-03-17) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* App launcher to update the cli arguments if conditional defaults are used. + + +0.36.9 (2025-03-18) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^^^ + +* Xr rendering mode, which is default when xr is used. + + +0.36.8 (2025-03-17) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Removed ``scalar_first`` from scipy function usage to support older versions of scipy. + + +0.36.7 (2025-03-14) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Changed the import structure to only import ``pinocchio`` when ``pink-ik`` or ``dex-retargeting`` is being used. + This also solves for the problem that ``pink-ik`` and ``dex-retargeting`` are not supported in windows. +* Removed ``isaacsim.robot_motion.lula`` and ``isaacsim.robot_motion.motion_generation`` from the default loaded Isaac Sim extensions. +* Moved pink ik action config to a separate file. + + +0.36.6 (2025-03-13) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Worked around an issue where the render mode is set to ``"RayTracedLighting"`` instead of ``"RaytracedLighting"`` by + some dependencies. + + +0.36.5 (2025-03-11) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^^^ + +* Added 3 rendering mode presets: performance, balanced, and quality. +* Preset settings are stored in ``apps/rendering_modes``. +* Presets can be set with cli arg ``--rendering_mode`` or with :class:`RenderCfg`. +* Preset rendering settings can be overwritten with :class:`RenderCfg`. +* :class:`RenderCfg` supports all native RTX carb settings. + +Changed +^^^^^^^ +* :class:`RenderCfg` default settings are unset. + + +0.36.4 (2025-03-11) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated the OpenXR kit file ``isaaclab.python.xr.openxr.kit`` to inherit from ``isaaclab.python.kit`` instead of + ``isaaclab.python.rendering.kit`` which is not appropriate. + + +0.36.3 (2025-03-10) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added the PinkIKController controller class that interfaces Isaac Lab with the Pink differential inverse kinematics solver + to allow control of multiple links in a robot using a single solver. + + +0.36.2 (2025-03-07) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Allowed users to exit on 1 Ctrl+C instead of consecutive 2 key strokes. +* Allowed physics reset during simulation through :meth:`reset` in :class:`~isaaclab.sim.SimulationContext`. + + +0.36.1 (2025-03-10) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`semantic_segmentation_mapping` for camera configs to allow specifying colors for semantics. + + +0.36.0 (2025-03-07) +~~~~~~~~~~~~~~~~~~~ + +Removed +^^^^^^^ + +* Removed the storage of tri-meshes and warp meshes inside the :class:`~isaaclab.terrains.TerrainImporter` class. + Initially these meshes were added for ray-casting purposes. However, since the ray-caster reads the terrains + directly from the USD files, these meshes are no longer needed. +* Deprecated the :attr:`warp_meshes` and :attr:`meshes` attributes from the + :class:`~isaaclab.terrains.TerrainImporter` class. These attributes now return an empty dictionary + with a deprecation warning. + +Changed +^^^^^^^ + +* Changed the prim path of the "plane" terrain inside the :class:`~isaaclab.terrains.TerrainImporter` class. + Earlier, the terrain was imported directly as the importer's prim path. Now, the terrain is imported as + ``{importer_prim_path}/{name}``, where ``name`` is the name of the terrain. + + +0.35.0 (2025-03-07) +~~~~~~~~~~~~~~~~~~~ + +* Improved documentation of various attributes in the :class:`~isaaclab.assets.ArticulationData` class to make + it clearer which values represent the simulation and internal class values. In the new convention, + the ``default_xxx`` attributes are whatever the user configured from their configuration of the articulation + class, while the ``xxx`` attributes are the values from the simulation. +* Updated the soft joint position limits inside the :meth:`~isaaclab.assets.Articulation.write_joint_pos_limits_to_sim` + method to use the new limits passed to the function. +* Added setting of :attr:`~isaaclab.assets.ArticulationData.default_joint_armature` and + :attr:`~isaaclab.assets.ArticulationData.default_joint_friction` attributes in the + :class:`~isaaclab.assets.Articulation` class based on user configuration. + +Changed +^^^^^^^ + +* Removed unnecessary buffer creation operations inside the :class:`~isaaclab.assets.Articulation` class. + Earlier, the class initialized a variety of buffer data with zeros and in the next function assigned + them the value from PhysX. This made the code bulkier and more complex for no reason. +* Renamed parameters for a consistent nomenclature. These changes are backwards compatible with previous releases + with a deprecation warning for the old names. + + * ``joint_velocity_limits`` → ``joint_vel_limits`` (to match attribute ``joint_vel`` and ``joint_vel_limits``) + * ``joint_limits`` → ``joint_pos_limits`` (to match attribute ``joint_pos`` and ``soft_joint_pos_limits``) + * ``default_joint_limits`` → ``default_joint_pos_limits`` + * ``write_joint_limits_to_sim`` → ``write_joint_position_limit_to_sim`` + * ``joint_friction`` → ``joint_friction_coeff`` + * ``default_joint_friction`` → ``default_joint_friction_coeff`` + * ``write_joint_friction_to_sim`` → ``write_joint_friction_coefficient_to_sim`` + * ``fixed_tendon_limit`` → ``fixed_tendon_pos_limits`` + * ``default_fixed_tendon_limit`` → ``default_fixed_tendon_pos_limits`` + * ``set_fixed_tendon_limit`` → ``set_fixed_tendon_position_limit`` + + +0.34.13 (2025-03-06) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a new event mode called "prestartup", which gets called right after the scene design is complete + and before the simulation is played. +* Added a callback to resolve the scene entity configurations separately once the simulation plays, + since the scene entities cannot be resolved before the simulation starts playing + (as we currently rely on PhysX to provide us with the joint/body ordering) + + +0.34.12 (2025-03-06) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Updated the mimic API :meth:`target_eef_pose_to_action` in :class:`isaaclab.envs.ManagerBasedRLMimicEnv` to take a dictionary of + eef noise values instead of a single noise value. +* Added support for optional subtask constraints based on DexMimicGen to the mimic configuration class :class:`isaaclab.envs.MimicEnvCfg`. +* Enabled data compression in HDF5 dataset file handler :class:`isaaclab.utils.datasets.hdf5_dataset_file_handler.HDF5DatasetFileHandler`. + + +0.34.11 (2025-03-04) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed issue in :class:`~isaaclab.sensors.TiledCamera` and :class:`~isaaclab.sensors.Camera` where segmentation outputs only display the first tile + when scene instancing is enabled. A workaround is added for now to disable instancing when segmentation + outputs are requested. + + +0.34.10 (2025-03-04) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the issue of misalignment in the motion vectors from the :class:`TiledCamera` + with other modalities such as RGBA and depth. + + +0.34.9 (2025-03-04) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added methods inside the :class:`omni.isaac.lab.assets.Articulation` class to set the joint + position and velocity for the articulation. Previously, the joint position and velocity could + only be set using the :meth:`omni.isaac.lab.assets.Articulation.write_joint_state_to_sim` method, + which didn't allow setting the joint position and velocity separately. + + +0.34.8 (2025-03-02) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the propagation of the :attr:`activate_contact_sensors` attribute to the + :class:`~isaaclab.sim.spawners.wrappers.wrappers_cfg.MultiAssetSpawnerCfg` class. Previously, this value + was always set to False, which led to incorrect contact sensor settings for the spawned assets. + + +0.34.7 (2025-03-02) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Enabled the physics flag for disabling contact processing in the :class:`~isaaclab.sim.SimulationContact` + class. This means that by default, no contact reporting is done by the physics engine, which should provide + a performance boost in simulations with no contact processing requirements. +* Disabled the physics flag for disabling contact processing in the :class:`~isaaclab.sensors.ContactSensor` + class when the sensor is created to allow contact reporting for the sensor. + +Removed +^^^^^^^ + +* Removed the attribute ``disable_contact_processing`` from :class:`~isaaclab.sim.SimulationContact`. + + +0.34.6 (2025-03-01) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a new attribute :attr:`is_implicit_model` to the :class:`isaaclab.actuators.ActuatorBase` class to + indicate if the actuator model is implicit or explicit. This helps checking that the correct model type + is being used when initializing the actuator models. + +Fixed +^^^^^ + +* Added copy of configurations to :class:`~isaaclab.assets.AssetBase` and :class:`~isaaclab.sensors.SensorBase` + to prevent modifications of the configurations from leaking outside of the classes. +* Fixed the case where setting velocity/effort limits for the simulation in the + :class:`~isaaclab.actuators.ActuatorBaseCfg` class was not being used to update the actuator-specific + velocity/effort limits. + +Changed +^^^^^^^ + +* Moved warnings and checks for implicit actuator models to the :class:`~isaaclab.actuators.ImplicitActuator` class. +* Reverted to IsaacLab v1.3 behavior where :attr:`isaaclab.actuators.ImplicitActuatorCfg.velocity_limit` + attribute was not used for setting the velocity limits in the simulation. This makes it possible to deploy + policies from previous release without any changes. If users want to set the velocity limits for the simulation, + they should use the :attr:`isaaclab.actuators.ImplicitActuatorCfg.velocity_limit_sim` attribute instead. + + +0.34.5 (2025-02-28) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added IP address support for WebRTC livestream to allow specifying IP address to stream across networks. + This feature requires an updated livestream extension, which is current only available in the pre-built Isaac Lab 2.0.1 docker image. + Support for other Isaac Sim builds will become available in Isaac Sim 5.0. + + +0.34.4 (2025-02-27) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Refactored retargeting code from Se3Handtracking class into separate modules for better modularity +* Added scaffolding for developing additional retargeters (e.g. dex) + + +0.34.3 (2025-02-26) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Enablec specifying the placement of the simulation when viewed in an XR device. This is achieved by + adding an ``XrCfg`` environment configuration with ``anchor_pos`` and ``anchor_rot`` parameters. + + +0.34.2 (2025-02-21) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed setting of root velocities inside the event term :meth:`reset_root_state_from_terrain`. Earlier, the indexing + based on the environment IDs was missing. + + +0.34.1 (2025-02-17) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Ensured that the loaded torch JIT models inside actuator networks are correctly set to eval mode + to prevent any unexpected behavior during inference. + + +0.34.0 (2025-02-14) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added attributes :attr:`velocity_limits_sim` and :attr:`effort_limits_sim` to the + :class:`isaaclab.actuators.ActuatorBaseCfg` class to separate solver limits from actuator limits. + + +0.33.17 (2025-02-13) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed Imu sensor based observations at first step by updating scene during initialization for + :class:`~isaaclab.envs.ManagerBasedEnv`, :class:`~isaaclab.envs.DirectRLEnv`, and :class:`~isaaclab.envs.DirectMARLEnv` + + +0.33.16 (2025-02-09) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Removes old deprecation warning from :attr:`isaaclab.assets.RigidObectData.body_state_w` + + +0.33.15 (2025-02-09) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed not updating the ``drift`` when calling :func:`~isaaclab.sensors.RayCaster.reset` + + +0.33.14 (2025-02-01) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed not updating the timestamp of ``body_link_state_w`` and ``body_com_state_w`` when ``write_root_pose_to_sim`` and ``write_joint_state_to_sim`` in the ``Articulation`` class are called. + + +0.33.13 (2025-01-30) +~~~~~~~~~~~~~~~~~~~~ + +* Fixed resampling of interval time left for the next event in the :class:`~isaaclab.managers.EventManager` + class. Earlier, the time left for interval-based events was not being resampled on episodic resets. This led + to the event being triggered at the wrong time after the reset. + + +0.33.12 (2025-01-28) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed missing import in ``line_plot.py`` + + +0.33.11 (2025-01-25) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`isaaclab.scene.InteractiveSceneCfg.filter_collisions` to allow specifying whether collision masking across environments is desired. + +Changed +^^^^^^^ + +* Automatic collision filtering now happens as part of the replicate_physics call. When replicate_physics is not enabled, we call the previous + ``filter_collisions`` API to mask collisions between environments. + + +0.33.10 (2025-01-22) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* In :meth:`isaaclab.assets.Articulation.write_joint_limits_to_sim`, we previously added a check for if default joint positions exceed the + new limits being set. When this is True, we log a warning message to indicate that the default joint positions will be clipped to be within + the range of the new limits. However, the warning message can become overly verbose in a randomization setting where this API is called on + every environment reset. We now default to only writing the message to info level logging if called within randomization, and expose a + parameter that can be used to choose the logging level desired. + + +0.33.9 (2025-01-22) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed typo in /physics/autoPopupSimulationOutputWindow setting in :class:`~isaaclab.sim.SimulationContext` + + +0.33.8 (2025-01-17) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Removed deprecation of :attr:`isaaclab.assets.ArticulationData.root_state_w` and + :attr:`isaaclab.assets.ArticulationData.body_state_w` derived properties. +* Removed deprecation of :meth:`isaaclab.assets.Articulation.write_root_state_to_sim`. +* Replaced calls to :attr:`isaaclab.assets.ArticulationData.root_com_state_w` and + :attr:`isaaclab.assets.ArticulationData.root_link_state_w` with corresponding calls to + :attr:`isaaclab.assets.ArticulationData.root_state_w`. +* Replaced calls to :attr:`isaaclab.assets.ArticulationData.body_com_state_w` and + :attr:`isaaclab.assets.ArticulationData.body_link_state_w` properties with corresponding calls to + :attr:`isaaclab.assets.ArticulationData.body_state_w` properties. +* Removed deprecation of :attr:`isaaclab.assets.RigidObjectData.root_state_w` derived properties. +* Removed deprecation of :meth:`isaaclab.assets.RigidObject.write_root_state_to_sim`. +* Replaced calls to :attr:`isaaclab.assets.RigidObjectData.root_com_state_w` and + :attr:`isaaclab.assets.RigidObjectData.root_link_state_w` properties with corresponding calls to + :attr:`isaaclab.assets.RigidObjectData.root_state_w` properties. +* Removed deprecation of :attr:`isaaclab.assets.RigidObjectCollectionData.root_state_w` derived properties. +* Removed deprecation of :meth:`isaaclab.assets.RigidObjectCollection.write_root_state_to_sim`. +* Replaced calls to :attr:`isaaclab.assets.RigidObjectCollectionData.root_com_state_w` and + :attr:`isaaclab.assets.RigidObjectData.root_link_state_w` properties with corresponding calls to + :attr:`isaaclab.assets.RigidObjectData.root_state_w` properties. +* Fixed indexing issue in ``write_root_link_velocity_to_sim`` in :class:`isaaclab.assets.RigidObject` +* Fixed index broadcasting in ``write_object_link_velocity_to_sim`` and ``write_object_com_pose_to_sim`` in + the :class:`isaaclab.assets.RigidObjectCollection` class. + + +0.33.7 (2025-01-14) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the respawn of only wrong object samples in :func:`repeated_objects_terrain` of :mod:`isaaclab.terrains.trimesh` module. + Previously, the function was respawning all objects in the scene instead of only the wrong object samples, which in worst case + could lead to infinite respawn loop. + + +0.33.6 (2025-01-16) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added initial unit tests for multiple tiled cameras, including tests for initialization, groundtruth annotators, different poses, and different resolutions. + + +0.33.5 (2025-01-13) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Moved the definition of ``/persistent/isaac/asset_root/*`` settings from :class:`AppLauncher` to the app files. + This is needed to prevent errors where ``isaaclab_assets`` was loaded prior to the carbonite setting being set. + + +0.33.4 (2025-01-10) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added an optional parameter in the :meth:`record_pre_reset` method in + :class:`~isaaclab.managers.RecorderManager` to override the export config upon invoking. + + +0.33.3 (2025-01-08) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed docstring in articulation data :class:`isaaclab.assets.ArticulationData`. + In body properties sections, the second dimension should be num_bodies but was documented as 1. + + +0.33.2 (2025-01-02) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added body tracking as an origin type to :class:`isaaclab.envs.ViewerCfg` and :class:`isaaclab.envs.ui.ViewportCameraController`. + + +0.33.1 (2024-12-26) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added kinematics initialization call for populating kinematic prim transforms to fabric for rendering. +* Added ``enable_env_ids`` flag for cloning and replication to replace collision filtering. + + +0.33.0 (2024-12-22) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed populating default_joint_stiffness and default_joint_damping values for ImplicitActuator instances in :class:`isaaclab.assets.Articulation` + + +0.32.2 (2024-12-17) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added null-space (position) control option to :class:`isaaclab.controllers.OperationalSpaceController`. +* Added test cases that uses null-space control for :class:`isaaclab.controllers.OperationalSpaceController`. +* Added information regarding null-space control to the tutorial script and documentation of + :class:`isaaclab.controllers.OperationalSpaceController`. +* Added arguments to set specific null-space joint position targets within + :class:`isaaclab.envs.mdp.actions.OperationalSpaceControllerAction` class. + + +0.32.1 (2024-12-17) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added a default and generic implementation of the :meth:`get_object_poses` function + in the :class:`ManagerBasedRLMimicEnv` class. +* Added a ``EXPORT_NONE`` mode in the :class:`DatasetExportMode` class and updated + :class:`~isaaclab.managers.RecorderManager` to enable recording without exporting + the data to a file. + + +0.32.0 (2024-12-16) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Previously, physx returns the rigid bodies and articulations velocities in the com of bodies rather than the + link frame, while poses are in link frames. We now explicitly provide :attr:`body_link_state` and + :attr:`body_com_state` APIs replacing the previous :attr:`body_state` API. Previous APIs are now marked as + deprecated. Please update any code using the previous pose and velocity APIs to use the new + ``*_link_*`` or ``*_com_*`` APIs in :attr:`isaaclab.assets.RigidBody`, + :attr:`isaaclab.assets.RigidBodyCollection`, and :attr:`isaaclab.assets.Articulation`. + + +0.31.0 (2024-12-16) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`ManagerBasedRLMimicEnv` and config classes for mimic data generation workflow for imitation learning. + + +0.30.3 (2024-12-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed ordering of logging and resamping in the command manager, where we were logging the metrics + after resampling the commands. This leads to incorrect logging of metrics when inside the resample call, + the metrics tensors get reset. + + +0.30.2 (2024-12-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed errors within the calculations of :class:`isaaclab.controllers.OperationalSpaceController`. + +Added +^^^^^ + +* Added :class:`isaaclab.controllers.OperationalSpaceController` to API documentation. +* Added test cases for :class:`isaaclab.controllers.OperationalSpaceController`. +* Added a tutorial for :class:`isaaclab.controllers.OperationalSpaceController`. +* Added the implementation of :class:`isaaclab.envs.mdp.actions.OperationalSpaceControllerAction` class. + + +0.30.1 (2024-12-15) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added call to update articulation kinematics after reset to ensure states are updated for non-rendering sensors. + Previously, some changes in reset such as modifying joint states would not be reflected in the rigid body + states immediately after reset. + + +0.30.0 (2024-12-15) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added UI interface to the Managers in the ManagerBasedEnv and MangerBasedRLEnv classes. +* Added UI widgets for :class:`LiveLinePlot` and :class:`ImagePlot`. +* Added ``ManagerLiveVisualizer/Cfg``: Given a ManagerBase (i.e. action_manager, observation_manager, etc) and a + config file this class creates the the interface between managers and the UI. +* Added :class:`EnvLiveVisualizer`: A 'manager' of ManagerLiveVisualizer. This is added to the ManagerBasedEnv + but is only called during the initialization of the managers in load_managers +* Added ``get_active_iterable_terms`` implementation methods to ActionManager, ObservationManager, CommandsManager, + CurriculumManager, RewardManager, and TerminationManager. This method exports the active term data and labels + for each manager and is called by ManagerLiveVisualizer. +* Additions to :class:`BaseEnvWindow` and :class:`RLEnvWindow` to register ManagerLiveVisualizer UI interfaces + for the chosen managers. + + +0.29.0 (2024-12-15) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added observation history computation to :class:`isaaclab.manager.observation_manager.ObservationManager`. +* Added ``history_length`` and ``flatten_history_dim`` configuration parameters to :class:`isaaclab.manager.manager_term_cfg.ObservationTermCfg` +* Added ``history_length`` and ``flatten_history_dim`` configuration parameters to :class:`isaaclab.manager.manager_term_cfg.ObservationGroupCfg` +* Added full buffer property to :class:`isaaclab.utils.buffers.circular_buffer.CircularBuffer` + + +0.28.4 (2024-12-15) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added action clip to all :class:`isaaclab.envs.mdp.actions`. + + +0.28.3 (2024-12-14) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added check for error below threshold in state machines to ensure the state has been reached. + + +0.28.2 (2024-12-13) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the shape of ``quat_w`` in the ``apply_actions`` method of :attr:`~isaaclab.env.mdp.NonHolonomicAction` + (previously (N,B,4), now (N,4) since the number of root bodies B is required to be 1). Previously ``apply_actions`` + errored because ``euler_xyz_from_quat`` requires inputs of shape (N,4). + + +0.28.1 (2024-12-13) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the internal buffers for ``set_external_force_and_torque`` where the buffer values would be stale if zero + values are sent to the APIs. + + +0.28.0 (2024-12-12) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Adapted the :class:`~isaaclab.sim.converters.UrdfConverter` to use the latest URDF converter API from Isaac Sim 4.5. + The physics articulation root can now be set separately, and the joint drive gains can be set on a per joint basis. + + +0.27.33 (2024-12-11) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Introduced an optional ``sensor_cfg`` parameter to the :meth:`~isaaclab.envs.mdp.rewards.base_height_l2` function, + enabling the use of :class:`~isaaclab.sensors.RayCaster` for height adjustments. For flat terrains, the function + retains its previous behavior. +* Improved documentation to clarify the usage of the :meth:`~isaaclab.envs.mdp.rewards.base_height_l2` function in + both flat and rough terrain settings. + + +0.27.32 (2024-12-11) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Modified :class:`isaaclab.envs.mdp.actions.DifferentialInverseKinematicsAction` class to use the geometric + Jacobian computed w.r.t. to the root frame of the robot. This helps ensure that root pose does not affect the tracking. + + +0.27.31 (2024-12-09) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Introduced configuration options in :class:`Se3HandTracking` to: + + - Zero out rotation around the x/y axes + - Apply smoothing and thresholding to position and rotation deltas for reduced jitter + - Use wrist-based rotation reference as an alternative to fingertip-based rotation + +* Switched the default position reference in :class:`Se3HandTracking` to the wrist joint pose, providing more stable + relative-based positioning. + + +0.27.30 (2024-12-09) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the initial state recorder term in :class:`isaaclab.envs.mdp.recorders.InitialStateRecorder` to + return only the states of the specified environment IDs. + + +0.27.29 (2024-12-06) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the enforcement of :attr:`~isaaclab.actuators.ActuatorBaseCfg.velocity_limits` at the + :attr:`~isaaclab.assets.Articulation.root_physx_view` level. + + +0.27.28 (2024-12-06) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* If a USD that contains an articulation root is loaded using a + :attr:`isaaclab.assets.RigidBody` we now fail unless the articulation root is explicitly + disabled. Using an articulation root for rigid bodies is not needed and decreases overall performance. + + +0.27.27 (2024-12-06) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Corrected the projection types of fisheye camera in :class:`isaaclab.sim.spawners.sensors.sensors_cfg.FisheyeCameraCfg`. + Earlier, the projection names used snakecase instead of camelcase. + + +0.27.26 (2024-12-06) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added option to define the clipping behavior for depth images generated by + :class:`~isaaclab.sensors.RayCasterCamera`, :class:`~isaaclab.sensors.Camera`, and :class:`~isaaclab.sensors.TiledCamera` + +Changed +^^^^^^^ + +* Unified the clipping behavior for the depth images of all camera implementations. Per default, all values exceeding + the range are clipped to zero for both ``distance_to_image_plane`` and ``distance_to_camera`` depth images. Prev. + :class:`~isaaclab.sensors.RayCasterCamera` clipped the values to the maximum value of the depth image, + :class:`~isaaclab.sensors.Camera` did not clip them and had a different behavior for both types. + + +0.27.25 (2024-12-05) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the condition in ``isaaclab.sh`` that checks whether ``pre-commit`` is installed before attempting installation. + + +0.27.24 (2024-12-05) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Removed workaround in :class:`isaaclab.sensors.TiledCamera` and :class:`isaaclab.sensors.Camera` + that was previously required to prevent frame offsets in renders. The denoiser setting is no longer + automatically modified based on the resolution of the cameras. + + +0.27.23 (2024-12-04) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added the attributes :attr:`~isaaclab.envs.DirectRLEnvCfg.wait_for_textures` and + :attr:`~isaaclab.envs.ManagerBasedEnvCfg.wait_for_textures` to enable assets loading check + during :class:`~isaaclab.DirectRLEnv` and :class:`~isaaclab.ManagerBasedEnv` reset method when + rtx sensors are added to the scene. + + +0.27.22 (2024-12-04) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the order of the incoming parameters in :class:`isaaclab.envs.DirectMARLEnv` to correctly use + ``NoiseModel`` in marl-envs. + + +0.27.21 (2024-12-04) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.managers.RecorderManager` and its utility classes to record data from the simulation. +* Added :class:`~isaaclab.utils.datasets.EpisodeData` to store data for an episode. +* Added :class:`~isaaclab.utils.datasets.DatasetFileHandlerBase` as a base class for handling dataset files. +* Added :class:`~isaaclab.utils.datasets.HDF5DatasetFileHandler` as a dataset file handler implementation to + export and load episodes from HDF5 files. +* Added ``record_demos.py`` script to record human-teleoperated demos for a specified task and export to an HDF5 file. +* Added ``replay_demos.py`` script to replay demos loaded from an HDF5 file. + + +0.27.20 (2024-12-02) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed :class:`isaaclab.envs.DirectMARLEnv` to inherit from ``Gymnasium.Env`` due to requirement from Gymnasium + v1.0.0 requiring all environments to be a subclass of ``Gymnasium.Env`` when using the ``make`` interface. + + +0.27.19 (2024-12-02) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``isaaclab.utils.pretrained_checkpoints`` containing constants and utility functions used to manipulate + paths and load checkpoints from Nucleus. + + +0.27.18 (2024-11-28) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Renamed Isaac Sim imports to follow Isaac Sim 4.5 naming conventions. + + +0.27.17 (2024-11-20) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``create_new_stage`` setting in :class:`~isaaclab.app.AppLauncher` to avoid creating a default new + stage on startup in Isaac Sim. This helps reduce the startup time when launching Isaac Lab. + + +0.27.16 (2024-11-15) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the class :class:`~isaaclab.devices.Se3HandTracking` which enables XR teleop for manipulators. + + +0.27.15 (2024-11-09) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed indexing in :meth:`isaaclab.assets.Articulation.write_joint_limits_to_sim` to correctly process + non-None ``env_ids`` and ``joint_ids``. + + +0.27.14 (2024-10-23) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the class :class:`~isaaclab.assets.RigidObjectCollection` which allows to spawn + multiple objects in each environment and access/modify the quantities with a unified (env_ids, object_ids) API. + + +0.27.13 (2024-10-30) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the attributes :attr:`~isaaclab.sim.converters.MeshConverterCfg.translation`, :attr:`~isaaclab.sim.converters.MeshConverterCfg.rotation`, + :attr:`~isaaclab.sim.converters.MeshConverterCfg.scale` to translate, rotate, and scale meshes + when importing them with :class:`~isaaclab.sim.converters.MeshConverter`. + + +0.27.12 (2024-11-04) +~~~~~~~~~~~~~~~~~~~~ + +Removed +^^^^^^^ + +* Removed TensorDict usage in favor of Python dictionary in sensors + + +0.27.11 (2024-10-31) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added support to define tuple of floats to scale observation terms by expanding the + :attr:`isaaclab.managers.manager_term_cfg.ObservationManagerCfg.scale` attribute. + + +0.27.10 (2024-11-01) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Cached the PhysX view's joint paths before looping over them when processing fixed joint tendons + inside the :class:`Articulation` class. This helps improve the processing time for the tendons. + + +0.27.9 (2024-11-01) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the :class:`isaaclab.utils.types.ArticulationActions` class to store the joint actions + for an articulation. Earlier, the class from Isaac Sim was being used. However, it used a different + type for the joint actions which was not compatible with the Isaac Lab framework. + + +0.27.8 (2024-11-01) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added sanity check if the term is a valid type inside the command manager. +* Corrected the iteration over ``group_cfg_items`` inside the observation manager. + + +0.27.7 (2024-10-28) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added frozen encoder feature extraction observation space with ResNet and Theia + + +0.27.6 (2024-10-25) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed usage of ``meshes`` property in :class:`isaaclab.sensors.RayCasterCamera` to use ``self.meshes`` + instead of the undefined ``RayCaster.meshes``. +* Fixed issue in :class:`isaaclab.envs.ui.BaseEnvWindow` where undefined configs were being accessed when + creating debug visualization elements in UI. + + +0.27.5 (2024-10-25) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added utilities for serializing/deserializing Gymnasium spaces. + + +0.27.4 (2024-10-18) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Updated installation path instructions for Windows in the Isaac Lab documentation to remove redundancy in the + use of %USERPROFILE% for path definitions. + + +0.27.3 (2024-10-22) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the issue with using list or tuples of ``configclass`` within a ``configclass``. Earlier, the list of + configclass objects were not converted to dictionary properly when ``to_dict`` function was called. + + +0.27.2 (2024-10-21) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``--kit_args`` to :class:`~isaaclab.app.AppLauncher` to allow passing command line arguments directly to + Omniverse Kit SDK. + + +0.27.1 (2024-10-20) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.sim.RenderCfg` and the attribute :attr:`~isaaclab.sim.SimulationCfg.render` for + specifying render related settings. + + +0.27.0 (2024-10-14) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a method to :class:`~isaaclab.utils.configclass` to check for attributes with values of + type ``MISSING``. This is useful when the user wants to check if a certain attribute has been set or not. +* Added the configuration validation check inside the constructor of all the core classes + (such as sensor base, asset base, scene and environment base classes). +* Added support for environments without commands by leaving the attribute + :attr:`isaaclab.envs.ManagerBasedRLEnvCfg.commands` as None. Before, this had to be done using + the class :class:`isaaclab.command_generators.NullCommandGenerator`. +* Moved the ``meshes`` attribute in the :class:`isaaclab.sensors.RayCaster` class from class variable to instance variable. + This prevents the meshes to overwrite each other. + + +0.26.0 (2024-10-16) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added Imu sensor implementation that directly accesses the physx view :class:`isaaclab.sensors.Imu`. The + sensor comes with a configuration class :class:`isaaclab.sensors.ImuCfg` and data class + :class:`isaaclab.sensors.ImuData`. +* Moved and renamed :meth:`isaaclab.sensors.camera.utils.convert_orientation_convention` to + :meth:`isaaclab.utils.math.convert_camera_frame_orientation_convention` +* Moved :meth:`isaaclab.sensors.camera.utils.create_rotation_matrix_from_view` to + :meth:`isaaclab.utils.math.create_rotation_matrix_from_view` + + +0.25.2 (2024-10-16) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added support for different Gymnasium spaces (``Box``, ``Discrete``, ``MultiDiscrete``, ``Tuple`` and ``Dict``) + to define observation, action and state spaces in the direct workflow. +* Added :meth:`sample_space` to environment utils to sample supported spaces where data containers are torch tensors. + +Changed +^^^^^^^ + +* Mark the :attr:`num_observations`, :attr:`num_actions` and :attr:`num_states` in :class:`DirectRLEnvCfg` as deprecated + in favor of :attr:`observation_space`, :attr:`action_space` and :attr:`state_space` respectively. +* Mark the :attr:`num_observations`, :attr:`num_actions` and :attr:`num_states` in :class:`DirectMARLEnvCfg` as deprecated + in favor of :attr:`observation_spaces`, :attr:`action_spaces` and :attr:`state_space` respectively. + + +0.25.1 (2024-10-10) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed potential issue where default joint positions can fall outside of the limits being set with Articulation's + ``write_joint_limits_to_sim`` API. + + +0.25.0 (2024-10-06) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added configuration classes for spawning assets from a list of individual asset configurations randomly + at the specified prim paths. + + +0.24.20 (2024-10-07) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the :meth:`isaaclab.envs.mdp.events.randomize_rigid_body_material` function to + correctly sample friction and restitution from the given ranges. + + +0.24.19 (2024-10-05) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added new functionalities to the FrameTransformer to make it more general. It is now possible to track: + + * Target frames that aren't children of the source frame prim_path + * Target frames that are based upon the source frame prim_path + + +0.24.18 (2024-10-04) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixes parsing and application of ``size`` parameter for :class:`~isaaclab.sim.spawn.GroundPlaneCfg` to correctly + scale the grid-based ground plane. + + +0.24.17 (2024-10-04) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the deprecation notice for using ``pxr.Semantics``. The corresponding modules use ``Semantics`` module + directly. + + +0.24.16 (2024-10-03) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Renamed the observation function :meth:`grab_images` to :meth:`image` to follow convention of noun-based naming. +* Renamed the function :meth:`convert_perspective_depth_to_orthogonal_depth` to a shorter name + :meth:`isaaclab.utils.math.orthogonalize_perspective_depth`. + + +0.24.15 (2024-09-20) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :meth:`grab_images` to be able to use images for an observation term in manager-based environments. + + +0.24.14 (2024-09-20) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the method :meth:`convert_perspective_depth_to_orthogonal_depth` to convert perspective depth + images to orthogonal depth images. This is useful for the :meth:`~isaaclab.utils.math.unproject_depth`, + since it expects orthogonal depth images as inputs. + + +0.24.13 (2024-09-08) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Moved the configuration of visualization markers for the command terms to their respective configuration classes. + This allows users to modify the markers for the command terms without having to modify the command term classes. + + +0.24.12 (2024-09-18) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed outdated fetching of articulation data by using the method ``update_articulations_kinematic`` in + :class:`isaaclab.assets.ArticulationData`. Before if an articulation was moved during a reset, the pose of the + links were outdated if fetched before the next physics step. Adding this method ensures that the pose of the links + is always up-to-date. Similarly ``update_articulations_kinematic`` was added before any render step to ensure that the + articulation displays correctly after a reset. + + +0.24.11 (2024-09-11) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added skrl's JAX environment variables to :class:`~isaaclab.app.AppLauncher` + to support distributed multi-GPU and multi-node training using JAX + + +0.24.10 (2024-09-10) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added config class, support, and tests for MJCF conversion via standalone python scripts. + + +0.24.9 (2024-09-09) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a seed parameter to the :attr:`isaaclab.envs.ManagerBasedEnvCfg` and :attr:`isaaclab.envs.DirectRLEnvCfg` + classes to set the seed for the environment. This seed is used to initialize the random number generator for the environment. +* Adapted the workflow scripts to set the seed for the environment using the seed specified in the learning agent's configuration + file or the command line argument. This ensures that the simulation results are reproducible across different runs. + + +0.24.8 (2024-09-08) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Modified:meth:`quat_rotate` and :meth:`quat_rotate_inverse` operations to use :meth:`torch.einsum` + for faster processing of high dimensional input tensors. + + +0.24.7 (2024-09-06) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added support for property attributes in the :meth:``isaaclab.utils.configclass`` method. + Earlier, the configclass decorator failed to parse the property attributes correctly and made them + instance variables instead. + + +0.24.6 (2024-09-05) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Adapted the ``A`` and ``D`` button bindings inside :meth:`isaaclab.device.Se3Keyboard` to make them now + more-intuitive to control the y-axis motion based on the right-hand rule. + + +0.24.5 (2024-08-29) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added alternative data type "distance_to_camera" in :class:`isaaclab.sensors.TiledCamera` class to be + consistent with all other cameras (equal to type "depth"). + + +0.24.4 (2024-09-02) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added missing SI units to the documentation of :class:`isaaclab.sensors.Camera` and + :class:`isaaclab.sensors.RayCasterCamera`. +* Added test to check :attr:`isaaclab.sensors.RayCasterCamera.set_intrinsic_matrices` + + +0.24.3 (2024-08-29) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the support for class-bounded methods when creating a configclass + out of them. Earlier, these methods were being made as instance methods + which required initialization of the class to call the class-methods. + + +0.24.2 (2024-08-28) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a class method to initialize camera configurations with an intrinsic matrix in the + :class:`isaaclab.sim.spawner.sensors.PinholeCameraCfg` + :class:`isaaclab.sensors.ray_caster.patterns_cfg.PinholeCameraPatternCfg` classes. + +Fixed +^^^^^ + +* Fixed the ray direction in :func:`isaaclab.sensors.ray_caster.patterns.patterns.pinhole_camera_pattern` to + point to the center of the pixel instead of the top-left corner. +* Fixed the clipping of the "distance_to_image_plane" depth image obtained using the + :class:`isaaclab.sensors.ray_caster.RayCasterCamera` class. Earlier, the depth image was being clipped + before the depth image was generated. Now, the clipping is applied after the depth image is generated. This makes + the behavior equal to the USD Camera. + + +0.24.1 (2024-08-21) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Disabled default viewport in certain headless scenarios for better performance. + + +0.24.0 (2024-08-17) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added additional annotators for :class:`isaaclab.sensors.camera.TiledCamera` class. + +Changed +^^^^^^^ + +* Updated :class:`isaaclab.sensors.TiledCamera` to latest RTX tiled rendering API. +* Single channel outputs for :class:`isaaclab.sensors.TiledCamera`, :class:`isaaclab.sensors.Camera` and :class:`isaaclab.sensors.RayCasterCamera` now has shape (H, W, 1). +* Data type for RGB output for :class:`isaaclab.sensors.TiledCamera` changed from ``torch.float`` to ``torch.uint8``. +* Dimension of RGB output for :class:`isaaclab.sensors.Camera` changed from (H, W, 4) to (H, W, 3). Use type ``rgba`` to retrieve the previous dimension. + + +0.23.1 (2024-08-17) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated torch to version 2.4.0. + + +0.23.0 (2024-08-16) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added direct workflow base class :class:`isaaclab.envs.DirectMARLEnv` for multi-agent environments. + + +0.22.1 (2024-08-17) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added APIs to interact with the physics simulation of deformable objects. This includes setting the + material properties, setting kinematic targets, and getting the state of the deformable object. + For more information, please refer to the :mod:`isaaclab.assets.DeformableObject` class. + + +0.22.0 (2024-08-14) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :mod:`~isaaclab.utils.modifiers` module to provide framework for configurable and custom + observation data modifiers. +* Adapted the :class:`~isaaclab.managers.ObservationManager` class to support custom modifiers. + These are applied to the observation data before applying any noise or scaling operations. + + +0.21.2 (2024-08-13) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Moved event mode-based checks in the :meth:`isaaclab.managers.EventManager.apply` method outside + the loop that iterates over the event terms. This prevents unnecessary checks and improves readability. +* Fixed the logic for global and per environment interval times when using the "interval" mode inside the + event manager. Earlier, the internal lists for these times were of unequal lengths which led to wrong indexing + inside the loop that iterates over the event terms. + + +0.21.1 (2024-08-06) +~~~~~~~~~~~~~~~~~~~ + +* Added a flag to preserve joint ordering inside the :class:`isaaclab.envs.mdp.JointAction` action term. + + +0.21.0 (2024-08-05) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the command line argument ``--device`` in :class:`~isaaclab.app.AppLauncher`. Valid options are: + + * ``cpu``: Use CPU. + * ``cuda``: Use GPU with device ID ``0``. + * ``cuda:N``: Use GPU, where N is the device ID. For example, ``cuda:0``. The default value is ``cuda:0``. + +Changed +^^^^^^^ + +* Simplified setting the device throughout the code by relying on :attr:`isaaclab.sim.SimulationCfg.device` + to activate gpu/cpu pipelines. + +Removed +^^^^^^^ + +* Removed the parameter :attr:`isaaclab.sim.SimulationCfg.use_gpu_pipeline`. This is now directly inferred from + :attr:`isaaclab.sim.SimulationCfg.device`. +* Removed the command line input argument ``--device_id`` in :class:`~isaaclab.app.AppLauncher`. The device id can + now be set using the ``--device`` argument, for example with ``--device cuda:0``. + + +0.20.8 (2024-08-02) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the handling of observation terms with different shapes in the + :class:`~isaaclab.managers.ObservationManager` class. Earlier, the constructor would throw an error if the + shapes of the observation terms were different. Now, this operation only happens when the terms in an observation + group are being concatenated. Otherwise, the terms are stored as a dictionary of tensors. +* Improved the error message when the observation terms are not of the same shape in the + :class:`~isaaclab.managers.ObservationManager` class and the terms are being concatenated. + + +0.20.7 (2024-08-02) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Performance improvements for material randomization in events. + +Added +^^^^^ + +* Added minimum randomization frequency for reset mode randomizations. + + +0.20.6 (2024-08-02) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Removed the hierarchy from :class:`~isaaclab.assets.RigidObject` class to + :class:`~isaaclab.assets.Articulation` class. Previously, the articulation class overrode almost + all the functions of the rigid object class making the hierarchy redundant. Now, the articulation class + is a standalone class that does not inherit from the rigid object class. This does add some code + duplication but the simplicity and clarity of the code is improved. + + +0.20.5 (2024-08-02) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`isaaclab.terrain.TerrainGeneratorCfg.border_height` to set the height of the border + around the terrain. + + +0.20.4 (2024-08-02) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the caching of terrains when using the :class:`isaaclab.terrains.TerrainGenerator` class. + Earlier, the random sampling of the difficulty levels led to different hash values for the same terrain + configuration. This caused the terrains to be re-generated even when the same configuration was used. + Now, the numpy random generator is seeded with the same seed to ensure that the difficulty levels are + sampled in the same order between different runs. + + +0.20.3 (2024-08-02) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the setting of translation and orientation when spawning a mesh prim. Earlier, the translation + and orientation was being applied both on the parent Xform and the mesh prim. This was causing the + mesh prim to be offset by the translation and orientation of the parent Xform, which is not the intended + behavior. + + +0.20.2 (2024-08-02) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Modified the computation of body acceleration for rigid body data to use PhysX APIs instead of + numerical finite-differencing. This removes the need for computation of body acceleration at + every update call of the data buffer. + + +0.20.1 (2024-07-30) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the :meth:`isaaclab.utils.math.wrap_to_pi` method to handle the wrapping of angles correctly. + Earlier, the method was not wrapping the angles to the range [-pi, pi] correctly when the angles were outside + the range [-2*pi, 2*pi]. + + +0.20.0 (2024-07-26) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Support for the Isaac Sim 4.1.0 release. + +Removed +^^^^^^^ + +* The ``mdp.add_body_mass`` method in the events. Please use the + :meth:`isaaclab.envs.mdp.randomize_rigid_body_mass` method instead. +* The classes ``managers.RandomizationManager`` and ``managers.RandomizationTermCfg`` are replaced with + :class:`isaaclab.managers.EventManager` and :class:`isaaclab.managers.EventTermCfg` classes. +* The following properties in :class:`isaaclab.sensors.FrameTransformerData`: + + * ``target_rot_source`` --> :attr:`~isaaclab.sensors.FrameTransformerData.target_quat_w` + * ``target_rot_w`` --> :attr:`~isaaclab.sensors.FrameTransformerData.target_quat_source` + * ``source_rot_w`` --> :attr:`~isaaclab.sensors.FrameTransformerData.source_quat_w` + +* The kit experience file ``isaaclab.backwards.compatible.kit``. This is followed by dropping the support for + Isaac Sim 2023.1.1 completely. + + +0.19.4 (2024-07-13) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added the call to "startup" events when using the :class:`~isaaclab.envs.ManagerBasedEnv` class. + Earlier, the "startup" events were not being called when the environment was initialized. This issue + did not occur when using the :class:`~isaaclab.envs.ManagerBasedRLEnv` class since the "startup" + events were called in the constructor. + + +0.19.3 (2024-07-13) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added schemas for setting and modifying deformable body properties on a USD prim. +* Added API to spawn a deformable body material in the simulation. +* Added APIs to spawn rigid and deformable meshes of primitive shapes (cone, cylinder, sphere, box, capsule) + in the simulation. This is possible through the :mod:`isaaclab.sim.spawners.meshes` module. + + +0.19.2 (2024-07-05) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Modified cloning scheme based on the attribute :attr:`~isaaclab.scene.InteractiveSceneCfg.replicate_physics` + to determine whether environment is homogeneous or heterogeneous. + + +0.19.1 (2024-07-05) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a lidar pattern function :func:`~isaaclab.sensors.ray_caster.patterns.patterns.lidar_pattern` with + corresponding config :class:`~isaaclab.sensors.ray_caster.patterns_cfg.LidarPatternCfg`. + + +0.19.0 (2024-07-04) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed parsing of articulations with nested rigid links while using the :class:`isaaclab.assets.Articulation` + class. Earlier, the class initialization failed when the articulation had nested rigid links since the rigid + links were not being parsed correctly by the PhysX view. + +Removed +^^^^^^^ + +* Removed the attribute :attr:`body_physx_view` from the :class:`isaaclab.assets.Articulation` and + :class:`isaaclab.assets.RigidObject` classes. These were causing confusions when used with articulation + view since the body names were not following the same ordering. +* Dropped support for Isaac Sim 2023.1.1. The minimum supported version is now Isaac Sim 4.0.0. + + +0.18.6 (2024-07-01) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the environment stepping logic. Earlier, the environments' rendering logic was updating the kit app which + would in turn step the physics :attr:`isaaclab.sim.SimulationCfg.render_interval` times. Now, a render + call only does rendering and does not step the physics. + + +0.18.5 (2024-06-26) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the gravity vector direction used inside the :class:`isaaclab.assets.RigidObjectData` class. + Earlier, the gravity direction was hard-coded as (0, 0, -1) which may be different from the actual + gravity direction in the simulation. Now, the gravity direction is obtained from the simulation context + and used to compute the projection of the gravity vector on the object. + + +0.18.4 (2024-06-26) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed double reference count of the physics sim view inside the asset classes. This was causing issues + when destroying the asset class instance since the physics sim view was not being properly released. + +Added +^^^^^ + +* Added the attribute :attr:`~isaaclab.assets.AssetBase.is_initialized` to check if the asset and sensor + has been initialized properly. This can be used to ensure that the asset or sensor is ready to use in the simulation. + + +0.18.3 (2024-06-25) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the docstrings at multiple places related to the different buffer implementations inside the + :mod:`isaaclab.utils.buffers` module. The docstrings were not clear and did not provide enough + information about the classes and their methods. + +Added +^^^^^ + +* Added the field for fixed tendom names in the :class:`isaaclab.assets.ArticulationData` class. + Earlier, this information was not exposed which was inconsistent with other name related information + such as joint or body names. + +Changed +^^^^^^^ + +* Renamed the fields ``min_num_time_lags`` and ``max_num_time_lags`` to ``min_delay`` and + ``max_delay`` in the :class:`isaaclab.actuators.DelayedPDActuatorCfg` class. This is to make + the naming simpler to understand. + + +0.18.2 (2024-06-25) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Moved the configuration for tile-rendered camera into its own file named ``tiled_camera_cfg.py``. + This makes it easier to follow where the configuration is located and how it is related to the class. + + +0.18.1 (2024-06-25) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Ensured that a parity between class and its configuration class is explicitly visible in the + :mod:`isaaclab.envs` module. This makes it easier to follow where definitions are located and how + they are related. This should not be a breaking change as the classes are still accessible through the same module. + + +0.18.0 (2024-06-13) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the rendering logic to render at the specified interval. Earlier, the substep parameter had no effect and rendering + would happen once every env.step() when active. + +Changed +^^^^^^^ + +* Renamed :attr:`isaaclab.sim.SimulationCfg.substeps` to :attr:`isaaclab.sim.SimulationCfg.render_interval`. + The render logic is now integrated in the decimation loop of the environment. + + +0.17.13 (2024-06-13) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the orientation reset logic in :func:`isaaclab.envs.mdp.events.reset_root_state_uniform` to make it relative to + the default orientation. Earlier, the position was sampled relative to the default and the orientation not. + + +0.17.12 (2024-06-13) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the class :class:`isaaclab.utils.buffers.TimestampedBuffer` to store timestamped data. + +Changed +^^^^^^^ + +* Added time-stamped buffers in the classes :class:`isaaclab.assets.RigidObjectData` and :class:`isaaclab.assets.ArticulationData` + to update some values lazily and avoid unnecessary computations between physics updates. Before, all the data was always + updated at every step, even if it was not used by the task. + + +0.17.11 (2024-05-30) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :class:`isaaclab.sensor.ContactSensor` not loading correctly in extension mode. + Earlier, the :attr:`isaaclab.sensor.ContactSensor.body_physx_view` was not initialized when + :meth:`isaaclab.sensor.ContactSensor._debug_vis_callback` is called which references it. + + +0.17.10 (2024-05-30) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed compound classes being directly assigned in ``default_factory`` generator method + :meth:`isaaclab.utils.configclass._return_f`, which resulted in shared references such that modifications to + compound objects were reflected across all instances generated from the same ``default_factory`` method. + + +0.17.9 (2024-05-30) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``variants`` attribute to the :class:`isaaclab.sim.from_files.UsdFileCfg` class to select USD + variants when loading assets from USD files. + + +0.17.8 (2024-05-28) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Implemented the reset methods in the action terms to avoid returning outdated data. + + +0.17.7 (2024-05-28) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added debug visualization utilities in the :class:`isaaclab.managers.ActionManager` class. + + +0.17.6 (2024-05-27) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``wp.init()`` call in Warp utils. + + +0.17.5 (2024-05-22) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Websocket livestreaming is no longer supported. Valid livestream options are {0, 1, 2}. +* WebRTC livestream is now set with livestream=2. + + +0.17.4 (2024-05-17) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Modified the noise functions to also support add, scale, and abs operations on the data. Added aliases + to ensure backward compatibility with the previous functions. + + * Added :attr:`isaaclab.utils.noise.NoiseCfg.operation` for the different operations. + * Renamed ``constant_bias_noise`` to :func:`isaaclab.utils.noise.constant_noise`. + * Renamed ``additive_uniform_noise`` to :func:`isaaclab.utils.noise.uniform_noise`. + * Renamed ``additive_gaussian_noise`` to :func:`isaaclab.utils.noise.gaussian_noise`. + + +0.17.3 (2024-05-15) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Set ``hide_ui`` flag in the app launcher for livestream. +* Fix native client livestream extensions. + + +0.17.2 (2024-05-09) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Renamed ``_range`` to ``distribution_params`` in ``events.py`` for methods that defined a distribution. +* Apply additive/scaling randomization noise on default data instead of current data. +* Changed material bucketing logic to prevent exceeding 64k materials. + +Fixed +^^^^^ + +* Fixed broadcasting issues with indexing when environment and joint IDs are provided. +* Fixed incorrect tensor dimensions when setting a subset of environments. + +Added +^^^^^ + +* Added support for randomization of fixed tendon parameters. +* Added support for randomization of dof limits. +* Added support for randomization of gravity. +* Added support for Gaussian sampling. +* Added default buffers to Articulation/Rigid object data classes for randomization. + + +0.17.1 (2024-05-10) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added attribute :attr:`isaaclab.sim.converters.UrdfConverterCfg.override_joint_dynamics` to properly parse + joint dynamics in :class:`isaaclab.sim.converters.UrdfConverter`. + + +0.17.0 (2024-05-07) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Renamed ``BaseEnv`` to :class:`isaaclab.envs.ManagerBasedEnv`. +* Renamed ``base_env.py`` to ``manager_based_env.py``. +* Renamed ``BaseEnvCfg`` to :class:`isaaclab.envs.ManagerBasedEnvCfg`. +* Renamed ``RLTaskEnv`` to :class:`isaaclab.envs.ManagerBasedRLEnv`. +* Renamed ``rl_task_env.py`` to ``manager_based_rl_env.py``. +* Renamed ``RLTaskEnvCfg`` to :class:`isaaclab.envs.ManagerBasedRLEnvCfg`. +* Renamed ``rl_task_env_cfg.py`` to ``rl_env_cfg.py``. +* Renamed ``OIGEEnv`` to :class:`isaaclab.envs.DirectRLEnv`. +* Renamed ``oige_env.py`` to ``direct_rl_env.py``. +* Renamed ``RLTaskEnvWindow`` to :class:`isaaclab.envs.ui.ManagerBasedRLEnvWindow`. +* Renamed ``rl_task_env_window.py`` to ``manager_based_rl_env_window.py``. +* Renamed all references of ``BaseEnv``, ``BaseEnvCfg``, ``RLTaskEnv``, ``RLTaskEnvCfg``, ``OIGEEnv``, and ``RLTaskEnvWindow``. + +Added +^^^^^ + +* Added direct workflow base class :class:`isaaclab.envs.DirectRLEnv`. + + +0.16.4 (2024-05-06) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added :class:`isaaclab.sensors.TiledCamera` to support tiled rendering with RGB and depth. + + +0.16.3 (2024-04-26) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed parsing of filter prim path expressions in the :class:`isaaclab.sensors.ContactSensor` class. + Earlier, the filter prim paths given to the physics view was not being parsed since they were specified as + regex expressions instead of glob expressions. + + +0.16.2 (2024-04-25) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Simplified the installation procedure, isaaclab -e is no longer needed +* Updated torch dependency to 2.2.2 + + +0.16.1 (2024-04-20) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added attribute :attr:`isaaclab.sim.ArticulationRootPropertiesCfg.fix_root_link` to fix the root link + of an articulation to the world frame. + + +0.16.0 (2024-04-16) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the function :meth:`isaaclab.utils.math.quat_unique` to standardize quaternion representations, + i.e. always have a non-negative real part. +* Added events terms for randomizing mass by scale, simulation joint properties (stiffness, damping, armature, + and friction) + +Fixed +^^^^^ + +* Added clamping of joint positions and velocities in event terms for resetting joints. The simulation does not + throw an error if the set values are out of their range. Hence, users are expected to clamp them before setting. +* Fixed :class:`isaaclab.envs.mdp.EMAJointPositionToLimitsActionCfg` to smoothen the actions + at environment frequency instead of simulation frequency. + +* Renamed the following functions in :meth:`isaaclab.envs.mdp` to avoid confusions: + + * Observation: :meth:`joint_pos_norm` -> :meth:`joint_pos_limit_normalized` + * Action: :class:`ExponentialMovingAverageJointPositionAction` -> :class:`EMAJointPositionToLimitsAction` + * Termination: :meth:`base_height` -> :meth:`root_height_below_minimum` + * Termination: :meth:`joint_pos_limit` -> :meth:`joint_pos_out_of_limit` + * Termination: :meth:`joint_pos_manual_limit` -> :meth:`joint_pos_out_of_manual_limit` + * Termination: :meth:`joint_vel_limit` -> :meth:`joint_vel_out_of_limit` + * Termination: :meth:`joint_vel_manual_limit` -> :meth:`joint_vel_out_of_manual_limit` + * Termination: :meth:`joint_torque_limit` -> :meth:`joint_effort_out_of_limit` + +Deprecated +^^^^^^^^^^ + +* Deprecated the function :meth:`isaaclab.envs.mdp.add_body_mass` in favor of + :meth:`isaaclab.envs.mdp.randomize_rigid_body_mass`. This supports randomizing the mass based on different + operations (add, scale, or set) and sampling distributions. + + +0.15.13 (2024-04-16) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Improved startup performance by enabling rendering-based extensions only when necessary and caching of nucleus directory. +* Renamed the flag ``OFFSCREEN_RENDER`` or ``--offscreen_render`` to ``ENABLE_CAMERAS`` or ``--enable_cameras`` respectively. + + +0.15.12 (2024-04-16) +~~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Replaced calls to the ``check_file_path`` function in the :mod:`isaaclab.sim.spawners.from_files` + with the USD stage resolve identifier function. This helps speed up the loading of assets from file paths + by avoiding Nucleus server calls. + + +0.15.11 (2024-04-15) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the :meth:`isaaclab.sim.SimulationContext.has_rtx_sensors` method to check if any + RTX-related sensors such as cameras have been created in the simulation. This is useful to determine + if simulation requires RTX rendering during step or not. + +Fixed +^^^^^ + +* Fixed the rendering of RTX-related sensors such as cameras inside the :class:`isaaclab.envs.RLTaskEnv` class. + Earlier the rendering did not happen inside the step function, which caused the sensor data to be empty. + + +0.15.10 (2024-04-11) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed sharing of the same memory address between returned tensors from observation terms + in the :class:`isaaclab.managers.ObservationManager` class. Earlier, the returned + tensors could map to the same memory address, causing issues when the tensors were modified + during scaling, clipping or other operations. + + +0.15.9 (2024-04-04) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed assignment of individual termination terms inside the :class:`isaaclab.managers.TerminationManager` + class. Earlier, the terms were being assigned their values through an OR operation which resulted in incorrect + values. This regression was introduced in version 0.15.1. + + +0.15.8 (2024-04-02) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added option to define ordering of points for the mesh-grid generation in the + :func:`isaaclab.sensors.ray_caster.patterns.grid_pattern`. This parameter defaults to 'xy' + for backward compatibility. + + +0.15.7 (2024-03-28) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Adds option to return indices/data in the specified query keys order in + :class:`isaaclab.managers.SceneEntityCfg` class, and the respective + :func:`isaaclab.utils.string.resolve_matching_names_values` and + :func:`isaaclab.utils.string.resolve_matching_names` functions. + + +0.15.6 (2024-03-28) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Extended the :class:`isaaclab.app.AppLauncher` class to support the loading of experience files + from the command line. This allows users to load a specific experience file when running the application + (such as for multi-camera rendering or headless mode). + +Changed +^^^^^^^ + +* Changed default loading of experience files in the :class:`isaaclab.app.AppLauncher` class from the ones + provided by Isaac Sim to the ones provided in Isaac Lab's ``apps`` directory. + + +0.15.5 (2024-03-23) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the env origins in :meth:`_compute_env_origins_grid` of :class:`isaaclab.terrain.TerrainImporter` + to match that obtained from the Isaac Sim :class:`isaacsim.core.cloner.GridCloner` class. + +Added +^^^^^ + +* Added unit test to ensure consistency between environment origins generated by IsaacSim's Grid Cloner and those + produced by the TerrainImporter. + + +0.15.4 (2024-03-22) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the :class:`isaaclab.envs.mdp.actions.NonHolonomicActionCfg` class to use + the correct variable when applying actions. + + +0.15.3 (2024-03-21) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added unit test to check that :class:`isaaclab.scene.InteractiveScene` entity data is not shared between separate instances. + +Fixed +^^^^^ + +* Moved class variables in :class:`isaaclab.scene.InteractiveScene` to correctly be assigned as + instance variables. +* Removed custom ``__del__`` magic method from :class:`isaaclab.scene.InteractiveScene`. + + +0.15.2 (2024-03-21) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added resolving of relative paths for the main asset USD file when using the + :class:`isaaclab.sim.converters.UrdfConverter` class. This is to ensure that the material paths are + resolved correctly when the main asset file is moved to a different location. + + +0.15.1 (2024-03-19) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the imitation learning workflow example script, updating Isaac Lab and Robomimic API calls. +* Removed the resetting of :attr:`_term_dones` in the :meth:`isaaclab.managers.TerminationManager.reset`. + Previously, the environment cleared out all the terms. However, it impaired reading the specific term's values externally. + + +0.15.0 (2024-03-17) +~~~~~~~~~~~~~~~~~~~ + +Deprecated +^^^^^^^^^^ + +* Renamed :class:`isaaclab.managers.RandomizationManager` to :class:`isaaclab.managers.EventManager` + class for clarification as the manager takes care of events such as reset in addition to pure randomizations. +* Renamed :class:`isaaclab.managers.RandomizationTermCfg` to :class:`isaaclab.managers.EventTermCfg` + for consistency with the class name change. + + +0.14.1 (2024-03-16) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added simulation schemas for joint drive and fixed tendons. These can be configured for assets imported + from file formats. +* Added logging of tendon properties to the articulation class (if they are present in the USD prim). + + +0.14.0 (2024-03-15) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the ordering of body names used in the :class:`isaaclab.assets.Articulation` class. Earlier, + the body names were not following the same ordering as the bodies in the articulation. This led + to issues when using the body names to access data related to the links from the articulation view + (such as Jacobians, mass matrices, etc.). + +Removed +^^^^^^^ + +* Removed the attribute :attr:`body_physx_view` from the :class:`isaaclab.assets.RigidObject` + and :class:`isaaclab.assets.Articulation` classes. These were causing confusions when used + with articulation view since the body names were not following the same ordering. + + +0.13.1 (2024-03-14) +~~~~~~~~~~~~~~~~~~~ + +Removed +^^^^^^^ + +* Removed the :mod:`isaaclab.compat` module. This module was used to provide compatibility + with older versions of Isaac Sim. It is no longer needed since we have most of the functionality + absorbed into the main classes. + + +0.13.0 (2024-03-12) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added support for the following data types inside the :class:`isaaclab.sensors.Camera` class: + ``instance_segmentation_fast`` and ``instance_id_segmentation_fast``. These are GPU-supported annotations + and are faster than the regular annotations. + +Fixed +^^^^^ + +* Fixed handling of semantic filtering inside the :class:`isaaclab.sensors.Camera` class. Earlier, + the annotator was given ``semanticTypes`` as an argument. However, with Isaac Sim 2023.1, the annotator + does not accept this argument. Instead the mapping needs to be set to the synthetic data interface directly. +* Fixed the return shape of colored images for segmentation data types inside the + :class:`isaaclab.sensors.Camera` class. Earlier, the images were always returned as ``int32``. Now, + they are casted to ``uint8`` 4-channel array before returning if colorization is enabled for the annotation type. + +Removed +^^^^^^^ + +* Dropped support for ``instance_segmentation`` and ``instance_id_segmentation`` annotations in the + :class:`isaaclab.sensors.Camera` class. Their "fast" counterparts should be used instead. +* Renamed the argument :attr:`isaaclab.sensors.CameraCfg.semantic_types` to + :attr:`isaaclab.sensors.CameraCfg.semantic_filter`. This is more aligned with Replicator's terminology + for semantic filter predicates. +* Replaced the argument :attr:`isaaclab.sensors.CameraCfg.colorize` with separate colorized + arguments for each annotation type (:attr:`~isaaclab.sensors.CameraCfg.colorize_instance_segmentation`, + :attr:`~isaaclab.sensors.CameraCfg.colorize_instance_id_segmentation`, and + :attr:`~isaaclab.sensors.CameraCfg.colorize_semantic_segmentation`). + + +0.12.4 (2024-03-11) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + + +* Adapted randomization terms to deal with ``slice`` for the body indices. Earlier, the terms were not + able to handle the slice object and were throwing an error. +* Added ``slice`` type-hinting to all body and joint related methods in the rigid body and articulation + classes. This is to make it clear that the methods can handle both list of indices and slices. + + +0.12.3 (2024-03-11) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added signal handler to the :class:`isaaclab.app.AppLauncher` class to catch the ``SIGINT`` signal + and close the application gracefully. This is to prevent the application from crashing when the user + presses ``Ctrl+C`` to close the application. + + +0.12.2 (2024-03-10) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added observation terms for states of a rigid object in world frame. +* Added randomization terms to set root state with randomized orientation and joint state within user-specified limits. +* Added reward term for penalizing specific termination terms. + +Fixed +^^^^^ + +* Improved sampling of states inside randomization terms. Earlier, the code did multiple torch calls + for sampling different components of the vector. Now, it uses a single call to sample the entire vector. + + +0.12.1 (2024-03-09) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added an option to the last actions observation term to get a specific term by name from the action manager. + If None, the behavior remains the same as before (the entire action is returned). + + +0.12.0 (2024-03-08) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added functionality to sample flat patches on a generated terrain. This can be configured using + :attr:`isaaclab.terrains.SubTerrainBaseCfg.flat_patch_sampling` attribute. +* Added a randomization function for setting terrain-aware root state. Through this, an asset can be + reset to a randomly sampled flat patches. + +Fixed +^^^^^ + +* Separated normal and terrain-base position commands. The terrain based commands rely on the + terrain to sample flat patches for setting the target position. +* Fixed command resample termination function. + +Changed +^^^^^^^ + +* Added the attribute :attr:`isaaclab.envs.mdp.commands.UniformVelocityCommandCfg.heading_control_stiffness` + to control the stiffness of the heading control term in the velocity command term. Earlier, this was + hard-coded to 0.5 inside the term. + +Removed +^^^^^^^ + +* Removed the function :meth:`sample_new_targets` in the terrain importer. Instead the attribute + :attr:`isaaclab.terrains.TerrainImporter.flat_patches` should be used to sample new targets. + + +0.11.3 (2024-03-04) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Corrects the functions :func:`isaaclab.utils.math.axis_angle_from_quat` and :func:`isaaclab.utils.math.quat_error_magnitude` + to accept tensors of the form (..., 4) instead of (N, 4). This brings us in line with our documentation and also upgrades one of our functions + to handle higher dimensions. + + +0.11.2 (2024-03-04) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added checks for default joint position and joint velocity in the articulation class. This is to prevent + users from configuring values for these quantities that might be outside the valid range from the simulation. + + +0.11.1 (2024-02-29) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Replaced the default values for ``joint_ids`` and ``body_ids`` from ``None`` to ``slice(None)`` + in the :class:`isaaclab.managers.SceneEntityCfg`. +* Adapted rewards and observations terms so that the users can query a subset of joints and bodies. + + +0.11.0 (2024-02-27) +~~~~~~~~~~~~~~~~~~~ + +Removed +^^^^^^^ + +* Dropped support for Isaac Sim<=2022.2. As part of this, removed the components of :class:`isaaclab.app.AppLauncher` + which handled ROS extension loading. We no longer need them in Isaac Sim>=2023.1 to control the load order to avoid crashes. +* Upgraded Dockerfile to use ISAACSIM_VERSION=2023.1.1 by default. + + +0.10.28 (2024-02-29) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Implemented relative and moving average joint position action terms. These allow the user to specify + the target joint positions as relative to the current joint positions or as a moving average of the + joint positions over a window of time. + + +0.10.27 (2024-02-28) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added UI feature to start and stop animation recording in the stage when running an environment. + To enable this feature, please pass the argument ``--disable_fabric`` to the environment script to allow + USD read/write operations. Be aware that this will slow down the simulation. + + +0.10.26 (2024-02-26) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a viewport camera controller class to the :class:`isaaclab.envs.BaseEnv`. This is useful + for applications where the user wants to render the viewport from different perspectives even when the + simulation is running in headless mode. + + +0.10.25 (2024-02-26) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Ensures that all path arguments in :mod:`isaaclab.sim.utils` are cast to ``str``. Previously, + we had handled path types as strings without casting. + + +0.10.24 (2024-02-26) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added tracking of contact time in the :class:`isaaclab.sensors.ContactSensor` class. Previously, + only the air time was being tracked. +* Added contact force threshold, :attr:`isaaclab.sensors.ContactSensorCfg.force_threshold`, to detect + when the contact sensor is in contact. Previously, this was set to hard-coded 1.0 in the sensor class. + + +0.10.23 (2024-02-21) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixes the order of size arguments in :meth:`isaaclab.terrains.height_field.random_uniform_terrain`. Previously, the function + would crash if the size along x and y were not the same. + + +0.10.22 (2024-02-14) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed "divide by zero" bug in :class:`~isaaclab.sim.SimulationContext` when setting gravity vector. + Now, it is correctly disabled when the gravity vector is set to zero. + + +0.10.21 (2024-02-12) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the printing of articulation joint information when the articulation has only one joint. + Earlier, the function was performing a squeeze operation on the tensor, which caused an error when + trying to index the tensor of shape (1,). + + +0.10.20 (2024-02-12) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Adds :attr:`isaaclab.sim.PhysxCfg.enable_enhanced_determinism` to enable improved + determinism from PhysX. Please note this comes at the expense of performance. + + +0.10.19 (2024-02-08) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed environment closing so that articulations, objects, and sensors are cleared properly. + + +0.10.18 (2024-02-05) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Pinned :mod:`torch` version to 2.0.1 in the setup.py to keep parity version of :mod:`torch` supplied by + Isaac 2023.1.1, and prevent version incompatibility between :mod:`torch` ==2.2 and + :mod:`typing-extensions` ==3.7.4.3 + + +0.10.17 (2024-02-02) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^^ + +* Fixed carb setting ``/app/livestream/enabled`` to be set as False unless live-streaming is specified + by :class:`isaaclab.app.AppLauncher` settings. This fixes the logic of :meth:`SimulationContext.render`, + which depended on the config in previous versions of Isaac defaulting to false for this setting. + + +0.10.16 (2024-01-29) +~~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^^ + +* Added an offset parameter to the height scan observation term. This allows the user to specify the + height offset of the scan from the tracked body. Previously it was hard-coded to be 0.5. + + +0.10.15 (2024-01-29) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed joint torque computation for implicit actuators. Earlier, the torque was always zero for implicit + actuators. Now, it is computed approximately by applying the PD law. + + +0.10.14 (2024-01-22) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the tensor shape of :attr:`isaaclab.sensors.ContactSensorData.force_matrix_w`. Earlier, the reshaping + led to a mismatch with the data obtained from PhysX. + + +0.10.13 (2024-01-15) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed running of environments with a single instance even if the :attr:`replicate_physics`` flag is set to True. + + +0.10.12 (2024-01-10) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed indexing of source and target frames in the :class:`isaaclab.sensors.FrameTransformer` class. + Earlier, it always assumed that the source frame body is at index 0. Now, it uses the body index of the + source frame to compute the transformation. + +Deprecated +^^^^^^^^^^ + +* Renamed quantities in the :class:`isaaclab.sensors.FrameTransformerData` class to be more + consistent with the terminology used in the asset classes. The following quantities are deprecated: + + * ``target_rot_w`` -> ``target_quat_w`` + * ``source_rot_w`` -> ``source_quat_w`` + * ``target_rot_source`` -> ``target_quat_source`` + + +0.10.11 (2024-01-08) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed attribute error raised when calling the :class:`isaaclab.envs.mdp.TerrainBasedPositionCommand` + command term. +* Added a dummy function in :class:`isaaclab.terrain.TerrainImporter` that returns environment + origins as terrain-aware sampled targets. This function should be implemented by child classes based on + the terrain type. + + +0.10.10 (2023-12-21) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed reliance on non-existent ``Viewport`` in :class:`isaaclab.sim.SimulationContext` when loading livestreaming + by ensuring that the extension ``omni.kit.viewport.window`` is enabled in :class:`isaaclab.app.AppLauncher` when + livestreaming is enabled + + +0.10.9 (2023-12-21) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed invalidation of physics views inside the asset and sensor classes. Earlier, they were left initialized + even when the simulation was stopped. This caused issues when closing the application. + + +0.10.8 (2023-12-20) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the :class:`isaaclab.envs.mdp.actions.DifferentialInverseKinematicsAction` class + to account for the offset pose of the end-effector. + + +0.10.7 (2023-12-19) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added a check to ray-cast and camera sensor classes to ensure that the sensor prim path does not + have a regex expression at its leaf. For instance, ``/World/Robot/camera_.*`` is not supported + for these sensor types. This behavior needs to be fixed in the future. + + +0.10.6 (2023-12-19) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added support for using articulations as visualization markers. This disables all physics APIs from + the articulation and allows the user to use it as a visualization marker. It is useful for creating + visualization markers for the end-effectors or base of the robot. + +Fixed +^^^^^ + +* Fixed hiding of debug markers from secondary images when using the + :class:`isaaclab.markers.VisualizationMarkers` class. Earlier, the properties were applied on + the XForm prim instead of the Mesh prim. + + +0.10.5 (2023-12-18) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed test ``check_base_env_anymal_locomotion.py``, which + previously called :func:`torch.jit.load` with the path to a policy (which would work + for a local file), rather than calling + :func:`isaaclab.utils.assets.read_file` on the path to get the file itself. + + +0.10.4 (2023-12-14) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed potentially breaking import of omni.kit.widget.toolbar by ensuring that + if live-stream is enabled, then the :mod:`omni.kit.widget.toolbar` + extension is loaded. + +0.10.3 (2023-12-12) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the attribute :attr:`isaaclab.actuators.ActuatorNetMLPCfg.input_order` + to specify the order of the input tensors to the MLP network. + +Fixed +^^^^^ + +* Fixed computation of metrics for the velocity command term. Earlier, the norm was being computed + over the entire batch instead of the last dimension. +* Fixed the clipping inside the :class:`isaaclab.actuators.DCMotor` class. Earlier, it was + not able to handle the case when configured saturation limit was set to None. + + +0.10.2 (2023-12-12) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added a check in the simulation stop callback in the :class:`isaaclab.sim.SimulationContext` class + to not render when an exception is raised. The while loop in the callback was preventing the application + from closing when an exception was raised. + + +0.10.1 (2023-12-06) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added command manager class with terms defined by :class:`isaaclab.managers.CommandTerm`. This + allow for multiple types of command generators to be used in the same environment. + + +0.10.0 (2023-12-04) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Modified the sensor and asset base classes to use the underlying PhysX views instead of Isaac Sim views. + Using Isaac Sim classes led to a very high load time (of the order of minutes) when using a scene with + many assets. This is because Isaac Sim supports USD paths which are slow and not required. + +Added +^^^^^ + +* Added faster implementation of USD stage traversal methods inside the :class:`isaaclab.sim.utils` module. +* Added properties :attr:`isaaclab.assets.AssetBase.num_instances` and + :attr:`isaaclab.sensor.SensorBase.num_instances` to obtain the number of instances of the asset + or sensor in the simulation respectively. + +Removed +^^^^^^^ + +* Removed dependencies on Isaac Sim view classes. It is no longer possible to use :attr:`root_view` and + :attr:`body_view`. Instead use :attr:`root_physx_view` and :attr:`body_physx_view` to access the underlying + PhysX views. + + +0.9.55 (2023-12-03) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the Nucleus directory path in the :attr:`isaaclab.utils.assets.NVIDIA_NUCLEUS_DIR`. + Earlier, it was referring to the ``NVIDIA/Assets`` directory instead of ``NVIDIA``. + + +0.9.54 (2023-11-29) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed pose computation in the :class:`isaaclab.sensors.Camera` class to obtain them from XFormPrimView + instead of using ``UsdGeomCamera.ComputeLocalToWorldTransform`` method. The latter is not updated correctly + during GPU simulation. +* Fixed initialization of the annotator info in the class :class:`isaaclab.sensors.Camera`. Previously + all dicts had the same memory address which caused all annotators to have the same info. +* Fixed the conversion of ``uint32`` warp arrays inside the :meth:`isaaclab.utils.array.convert_to_torch` + method. PyTorch does not support this type, so it is converted to ``int32`` before converting to PyTorch tensor. +* Added render call inside :meth:`isaaclab.sim.SimulationContext.reset` to initialize Replicator + buffers when the simulation is reset. + + +0.9.53 (2023-11-29) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed the behavior of passing :obj:`None` to the :class:`isaaclab.actuators.ActuatorBaseCfg` + class. Earlier, they were resolved to fixed default values. Now, they imply that the values are loaded + from the USD joint drive configuration. + +Added +^^^^^ + +* Added setting of joint armature and friction quantities to the articulation class. + + +0.9.52 (2023-11-29) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed the warning print in :meth:`isaaclab.sim.utils.apply_nested` method + to be more descriptive. Earlier, it was printing a warning for every instanced prim. + Now, it only prints a warning if it could not apply the attribute to any of the prims. + +Added +^^^^^ + +* Added the method :meth:`isaaclab.utils.assets.retrieve_file_path` to + obtain the absolute path of a file on the Nucleus server or locally. + +Fixed +^^^^^ + +* Fixed hiding of STOP button in the :class:`AppLauncher` class when running the + simulation in headless mode. +* Fixed a bug with :meth:`isaaclab.sim.utils.clone` failing when the input prim path + had no parent (example: "/Table"). + + +0.9.51 (2023-11-29) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed the :meth:`isaaclab.sensor.SensorBase.update` method to always recompute the buffers if + the sensor is in visualization mode. + +Added +^^^^^ + +* Added available entities to the error message when accessing a non-existent entity in the + :class:`InteractiveScene` class. +* Added a warning message when the user tries to reference an invalid prim in the :class:`FrameTransformer` sensor. + + +0.9.50 (2023-11-28) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Hid the ``STOP`` button in the UI when running standalone Python scripts. This is to prevent + users from accidentally clicking the button and stopping the simulation. They should only be able to + play and pause the simulation from the UI. + +Removed +^^^^^^^ + +* Removed :attr:`isaaclab.sim.SimulationCfg.shutdown_app_on_stop`. The simulation is always rendering + if it is stopped from the UI. The user needs to close the window or press ``Ctrl+C`` to close the simulation. + + +0.9.49 (2023-11-27) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added an interface class, :class:`isaaclab.managers.ManagerTermBase`, to serve as the parent class + for term implementations that are functional classes. +* Adapted all managers to support terms that are classes and not just functions clearer. This allows the user to + create more complex terms that require additional state information. + + +0.9.48 (2023-11-24) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed initialization of drift in the :class:`isaaclab.sensors.RayCasterCamera` class. + + +0.9.47 (2023-11-24) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Automated identification of the root prim in the :class:`isaaclab.assets.RigidObject` and + :class:`isaaclab.assets.Articulation` classes. Earlier, the root prim was hard-coded to + the spawn prim path. Now, the class searches for the root prim under the spawn prim path. + + +0.9.46 (2023-11-24) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed a critical issue in the asset classes with writing states into physics handles. + Earlier, the states were written over all the indices instead of the indices of the + asset that were being updated. This caused the physics handles to refresh the states + of all the assets in the scene, which is not desirable. + + +0.9.45 (2023-11-24) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`isaaclab.command_generators.UniformPoseCommandGenerator` to generate + poses in the asset's root frame by uniformly sampling from a given range. + + +0.9.44 (2023-11-16) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added methods :meth:`reset` and :meth:`step` to the :class:`isaaclab.envs.BaseEnv`. This unifies + the environment interface for simple standalone applications with the class. + + +0.9.43 (2023-11-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Replaced subscription of physics play and stop events in the :class:`isaaclab.assets.AssetBase` and + :class:`isaaclab.sensors.SensorBase` classes with subscription to time-line play and stop events. + This is to prevent issues in cases where physics first needs to perform mesh cooking and handles are not + available immediately. For instance, with deformable meshes. + + +0.9.42 (2023-11-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed setting of damping values from the configuration for :class:`ActuatorBase` class. Earlier, + the stiffness values were being set into damping when a dictionary configuration was passed to the + actuator model. +* Added dealing with :class:`int` and :class:`float` values in the configurations of :class:`ActuatorBase`. + Earlier, a type-error was thrown when integer values were passed to the actuator model. + + +0.9.41 (2023-11-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the naming and shaping issues in the binary joint action term. + + +0.9.40 (2023-11-09) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Simplified the manual initialization of Isaac Sim :class:`ArticulationView` class. Earlier, we basically + copied the code from the Isaac Sim source code. Now, we just call their initialize method. + +Changed +^^^^^^^ + +* Changed the name of attribute :attr:`default_root_state_w` to :attr:`default_root_state`. The latter is + more correct since the data is actually in the local environment frame and not the simulation world frame. + + +0.9.39 (2023-11-08) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Changed the reference of private ``_body_view`` variable inside the :class:`RigidObject` class + to the public ``body_view`` property. For a rigid object, the private variable is not defined. + + +0.9.38 (2023-11-07) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Upgraded the :class:`isaaclab.envs.RLTaskEnv` class to support Gym 0.29.0 environment definition. + +Added +^^^^^ + +* Added computation of ``time_outs`` and ``terminated`` signals inside the termination manager. These follow the + definition mentioned in `Gym 0.29.0 `_. +* Added proper handling of observation and action spaces in the :class:`isaaclab.envs.RLTaskEnv` class. + These now follow closely to how Gym VecEnv handles the spaces. + + +0.9.37 (2023-11-06) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed broken visualization in :mod:`isaaclab.sensors.FrameTramsformer` class by overwriting the + correct ``_debug_vis_callback`` function. +* Moved the visualization marker configurations of sensors to their respective sensor configuration classes. + This allows users to set these configurations from the configuration object itself. + + +0.9.36 (2023-11-03) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added explicit deleting of different managers in the :class:`isaaclab.envs.BaseEnv` and + :class:`isaaclab.envs.RLTaskEnv` classes. This is required since deleting the managers + is order-sensitive (many managers need to be deleted before the scene is deleted). + + +0.9.35 (2023-11-02) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the error: ``'str' object has no attribute '__module__'`` introduced by adding the future import inside the + :mod:`isaaclab.utils.warp.kernels` module. Warp language does not support the ``__future__`` imports. + + +0.9.34 (2023-11-02) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added missing import of ``from __future__ import annotations`` in the :mod:`isaaclab.utils.warp` + module. This is needed to have a consistent behavior across Python versions. + + +0.9.33 (2023-11-02) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the :class:`isaaclab.command_generators.NullCommandGenerator` class. Earlier, + it was having a runtime error due to infinity in the resampling time range. Now, the class just + overrides the parent methods to perform no operations. + + +0.9.32 (2023-11-02) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Renamed the :class:`isaaclab.envs.RLEnv` class to :class:`isaaclab.envs.RLTaskEnv` to + avoid confusions in terminologies between environments and tasks. + + +0.9.31 (2023-11-02) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the :class:`isaaclab.sensors.RayCasterCamera` class, as a ray-casting based camera for + "distance_to_camera", "distance_to_image_plane" and "normals" annotations. It has the same interface and + functionalities as the USD Camera while it is on average 30% faster. + + +0.9.30 (2023-11-01) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added skipping of None values in the :class:`InteractiveScene` class when creating the scene from configuration + objects. Earlier, it was throwing an error when the user passed a None value for a scene element. +* Added ``kwargs`` to the :class:`RLEnv` class to allow passing additional arguments from gym registry function. + This is now needed since the registry function passes args beyond the ones specified in the constructor. + + +0.9.29 (2023-11-01) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the material path resolution inside the :class:`isaaclab.sim.converters.UrdfConverter` class. + With Isaac Sim 2023.1, the material paths from the importer are always saved as absolute paths. This caused + issues when the generated USD file was moved to a different location. The fix now resolves the material paths + relative to the USD file location. + + +0.9.28 (2023-11-01) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed the way the :func:`isaaclab.sim.spawners.from_files.spawn_ground_plane` function sets the + height of the ground. Earlier, it was reading the height from the configuration object. Now, it expects the + desired transformation as inputs to the function. This makes it consistent with the other spawner functions. + + +0.9.27 (2023-10-31) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Removed the default value of the argument ``camel_case`` in setters of USD attributes. This is to avoid + confusion with the naming of the attributes in the USD file. + +Fixed +^^^^^ + +* Fixed the selection of material prim in the :class:`isaaclab.sim.spawners.materials.spawn_preview_surface` + method. Earlier, the created prim was being selected in the viewport which interfered with the selection of + prims by the user. +* Updated :class:`isaaclab.sim.converters.MeshConverter` to use a different stage than the default stage + for the conversion. This is to avoid the issue of the stage being closed when the conversion is done. + + +0.9.26 (2023-10-31) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the sensor implementation for :class:`isaaclab.sensors.FrameTransformer` class. Currently, + it handles obtaining the transformation between two frames in the same articulation. + + +0.9.25 (2023-10-27) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the :mod:`isaaclab.envs.ui` module to put all the UI-related classes in one place. This currently + implements the :class:`isaaclab.envs.ui.BaseEnvWindow` and :class:`isaaclab.envs.ui.RLEnvWindow` + classes. Users can inherit from these classes to create their own UI windows. +* Added the attribute :attr:`isaaclab.envs.BaseEnvCfg.ui_window_class_type` to specify the UI window class + to be used for the environment. This allows the user to specify their own UI window class to be used for the + environment. + + +0.9.24 (2023-10-27) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed the behavior of setting up debug visualization for assets, sensors and command generators. + Earlier it was raising an error if debug visualization was not enabled in the configuration object. + Now it checks whether debug visualization is implemented and only sets up the callback if it is + implemented. + + +0.9.23 (2023-10-27) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed a typo in the :class:`AssetBase` and :class:`SensorBase` that effected the class destructor. + Earlier, a tuple was being created in the constructor instead of the actual object. + + +0.9.22 (2023-10-26) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a :class:`isaaclab.command_generators.NullCommandGenerator` class for no command environments. + This is easier to work with than having checks for :obj:`None` in the command generator. + +Fixed +^^^^^ + +* Moved the randomization manager to the :class:`isaaclab.envs.BaseEnv` class with the default + settings to reset the scene to the defaults specified in the configurations of assets. +* Moved command generator to the :class:`isaaclab.envs.RlEnv` class to have all task-specification + related classes in the same place. + + +0.9.21 (2023-10-26) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Decreased the priority of callbacks in asset and sensor base classes. This may help in preventing + crashes when warm starting the simulation. +* Fixed no rendering mode when running the environment from the GUI. Earlier the function + :meth:`SimulationContext.set_render_mode` was erroring out. + + +0.9.20 (2023-10-25) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Changed naming in :class:`isaaclab.sim.SimulationContext.RenderMode` to use ``NO_GUI_OR_RENDERING`` + and ``NO_RENDERING`` instead of ``HEADLESS`` for clarity. +* Changed :class:`isaaclab.sim.SimulationContext` to be capable of handling livestreaming and + offscreen rendering. +* Changed :class:`isaaclab.app.AppLauncher` envvar ``VIEWPORT_RECORD`` to the more descriptive + ``OFFSCREEN_RENDER``. + + +0.9.19 (2023-10-25) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added Gym observation and action spaces for the :class:`isaaclab.envs.RLEnv` class. + + +0.9.18 (2023-10-23) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Created :class:`isaaclab.sim.converters.asset_converter.AssetConverter` to serve as a base + class for all asset converters. +* Added :class:`isaaclab.sim.converters.mesh_converter.MeshConverter` to handle loading and conversion + of mesh files (OBJ, STL and FBX) into USD format. +* Added script ``convert_mesh.py`` to ``source/tools`` to allow users to convert a mesh to USD via command line arguments. + +Changed +^^^^^^^ + +* Renamed the submodule :mod:`isaaclab.sim.loaders` to :mod:`isaaclab.sim.converters` to be more + general with the functionality of the module. +* Updated ``check_instanceable.py`` script to convert relative paths to absolute paths. + + +0.9.17 (2023-10-22) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added setters and getters for term configurations in the :class:`RandomizationManager`, :class:`RewardManager` + and :class:`TerminationManager` classes. This allows the user to modify the term configurations after the + manager has been created. +* Added the method :meth:`compute_group` to the :class:`isaaclab.managers.ObservationManager` class to + compute the observations for only a given group. +* Added the curriculum term for modifying reward weights after certain environment steps. + + +0.9.16 (2023-10-22) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added support for keyword arguments for terms in the :class:`isaaclab.managers.ManagerBase`. + +Fixed +^^^^^ + +* Fixed resetting of buffers in the :class:`TerminationManager` class. Earlier, the values were being set + to ``0.0`` instead of ``False``. + + +0.9.15 (2023-10-22) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added base yaw heading and body acceleration into :class:`isaaclab.assets.RigidObjectData` class. + These quantities are computed inside the :class:`RigidObject` class. + +Fixed +^^^^^ + +* Fixed the :meth:`isaaclab.assets.RigidObject.set_external_force_and_torque` method to correctly + deal with the body indices. +* Fixed a bug in the :meth:`isaaclab.utils.math.wrap_to_pi` method to prevent self-assignment of + the input tensor. + + +0.9.14 (2023-10-21) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added 2-D drift (i.e. along x and y) to the :class:`isaaclab.sensors.RayCaster` class. +* Added flags to the :class:`isaaclab.sensors.ContactSensorCfg` to optionally obtain the + sensor origin and air time information. Since these are not required by default, they are + disabled by default. + +Fixed +^^^^^ + +* Fixed the handling of contact sensor history buffer in the :class:`isaaclab.sensors.ContactSensor` class. + Earlier, the buffer was not being updated correctly. + + +0.9.13 (2023-10-20) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the issue with double :obj:`Ellipsis` when indexing tensors with multiple dimensions. + The fix now uses :obj:`slice(None)` instead of :obj:`Ellipsis` to index the tensors. + + +0.9.12 (2023-10-18) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed bugs in actuator model implementation for actuator nets. Earlier the DC motor clipping was not working. +* Fixed bug in applying actuator model in the :class:`isaaclab.asset.Articulation` class. The new + implementation caches the outputs from explicit actuator model into the ``joint_pos_*_sim`` buffer to + avoid feedback loops in the tensor operation. + + +0.9.11 (2023-10-17) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the support for semantic tags into the :class:`isaaclab.sim.spawner.SpawnerCfg` class. This allows + the user to specify the semantic tags for a prim when spawning it into the scene. It follows the same format as + Omniverse Replicator. + + +0.9.10 (2023-10-16) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``--livestream`` and ``--ros`` CLI args to :class:`isaaclab.app.AppLauncher` class. +* Added a static function :meth:`isaaclab.app.AppLauncher.add_app_launcher_args`, which + appends the arguments needed for :class:`isaaclab.app.AppLauncher` to the argument parser. + +Changed +^^^^^^^ + +* Within :class:`isaaclab.app.AppLauncher`, removed ``REMOTE_DEPLOYMENT`` env-var processing + in the favor of ``HEADLESS`` and ``LIVESTREAM`` env-vars. These have clearer uses and better parity + with the CLI args. + + +0.9.9 (2023-10-12) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the property :attr:`isaaclab.assets.Articulation.is_fixed_base` to the articulation class to + check if the base of the articulation is fixed or floating. +* Added the task-space action term corresponding to the differential inverse-kinematics controller. + +Fixed +^^^^^ + +* Simplified the :class:`isaaclab.controllers.DifferentialIKController` to assume that user provides the + correct end-effector poses and Jacobians. Earlier it was doing internal frame transformations which made the + code more complicated and error-prone. + + +0.9.8 (2023-09-30) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the boundedness of class objects that register callbacks into the simulator. + These include devices, :class:`AssetBase`, :class:`SensorBase` and :class:`CommandGenerator`. + The fix ensures that object gets deleted when the user deletes the object. + + +0.9.7 (2023-09-26) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Modified the :class:`isaaclab.markers.VisualizationMarkers` to use the + :class:`isaaclab.sim.spawner.SpawnerCfg` class instead of their + own configuration objects. This makes it consistent with the other ways to spawn assets in the scene. + +Added +^^^^^ + +* Added the method :meth:`copy` to configclass to allow copying of configuration objects. + + +0.9.6 (2023-09-26) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Changed class-level configuration classes to refer to class types using ``class_type`` attribute instead + of ``cls`` or ``cls_name``. + + +0.9.5 (2023-09-25) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added future import of ``annotations`` to have a consistent behavior across Python versions. +* Removed the type-hinting from docstrings to simplify maintenance of the documentation. All type-hints are + now in the code itself. + + +0.9.4 (2023-08-29) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`isaaclab.scene.InteractiveScene`, as the central scene unit that contains all entities + that are part of the simulation. These include the terrain, sensors, articulations, rigid objects etc. + The scene groups the common operations of these entities and allows to access them via their unique names. +* Added :mod:`isaaclab.envs` module that contains environment definitions that encapsulate the different + general (scene, action manager, observation manager) and RL-specific (reward and termination manager) managers. +* Added :class:`isaaclab.managers.SceneEntityCfg` to handle which scene elements are required by the + manager's terms. This allows the manager to parse useful information from the scene elements, such as the + joint and body indices, and pass them to the term. +* Added :class:`isaaclab.sim.SimulationContext.RenderMode` to handle different rendering modes based on + what the user wants to update (viewport, cameras, or UI elements). + +Fixed +^^^^^ + +* Fixed the :class:`isaaclab.command_generators.CommandGeneratorBase` to register a debug visualization + callback similar to how sensors and robots handle visualization. + + +0.9.3 (2023-08-23) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Enabled the `faulthander `_ to catch segfaults and print + the stack trace. This is enabled by default in the :class:`isaaclab.app.AppLauncher` class. + +Fixed +^^^^^ + +* Re-added the :mod:`isaaclab.utils.kit` to the ``compat`` directory and fixed all the references to it. +* Fixed the deletion of Replicator nodes for the :class:`isaaclab.sensors.Camera` class. Earlier, the + Replicator nodes were not being deleted when the camera was deleted. However, this does not prevent the random + crashes that happen when the camera is deleted. +* Fixed the :meth:`isaaclab.utils.math.convert_quat` to support both numpy and torch tensors. + +Changed +^^^^^^^ + +* Renamed all the scripts inside the ``test`` directory to follow the convention: + + * ``test_.py``: Tests for the module ```` using unittest. + * ``check_``: Check for the module ```` using python main function. + + +0.9.2 (2023-08-22) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the ability to color meshes in the :class:`isaaclab.terrain.TerrainGenerator` class. Currently, + it only supports coloring the mesh randomly (``"random"``), based on the terrain height (``"height"``), and + no coloring (``"none"``). + +Fixed +^^^^^ + +* Modified the :class:`isaaclab.terrain.TerrainImporter` class to configure visual and physics materials + based on the configuration object. + + +0.9.1 (2023-08-18) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Introduced three different rotation conventions in the :class:`isaaclab.sensors.Camera` class. These + conventions are: + + * ``opengl``: the camera is looking down the -Z axis with the +Y axis pointing up + * ``ros``: the camera is looking down the +Z axis with the +Y axis pointing down + * ``world``: the camera is looking along the +X axis with the -Z axis pointing down + + These can be used to declare the camera offset in :class:`isaaclab.sensors.CameraCfg.OffsetCfg` class + and in :meth:`isaaclab.sensors.Camera.set_world_pose` method. Additionally, all conventions are + saved to :class:`isaaclab.sensors.CameraData` class for easy access. + +Changed +^^^^^^^ + +* Adapted all the sensor classes to follow a structure similar to the :class:`isaaclab.assets.AssetBase`. + Hence, the spawning and initialization of sensors manually by the users is avoided. +* Removed the :meth:`debug_vis` function since that this functionality is handled by a render callback automatically + (based on the passed configuration for the :class:`isaaclab.sensors.SensorBaseCfg.debug_vis` flag). + + +0.9.0 (2023-08-18) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Introduces a new set of asset interfaces. These interfaces simplify the spawning of assets into the scene + and initializing the physics handle by putting that inside post-startup physics callbacks. With this, users + no longer need to worry about the :meth:`spawn` and :meth:`initialize` calls. +* Added utility methods to :mod:`isaaclab.utils.string` module that resolve regex expressions based + on passed list of target keys. + +Changed +^^^^^^^ + +* Renamed all references of joints in an articulation from "dof" to "joint". This makes it consistent with the + terminology used in robotics. + +Deprecated +^^^^^^^^^^ + +* Removed the previous modules for objects and robots. Instead the :class:`Articulation` and :class:`RigidObject` + should be used. + + +0.8.12 (2023-08-18) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added other properties provided by ``PhysicsScene`` to the :class:`isaaclab.sim.SimulationContext` + class to allow setting CCD, solver iterations, etc. +* Added commonly used functions to the :class:`SimulationContext` class itself to avoid having additional + imports from Isaac Sim when doing simple tasks such as setting camera view or retrieving the simulation settings. + +Fixed +^^^^^ + +* Switched the notations of default buffer values in :class:`isaaclab.sim.PhysxCfg` from multiplication + to scientific notation to avoid confusion with the values. + + +0.8.11 (2023-08-18) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Adds utility functions and configuration objects in the :mod:`isaaclab.sim.spawners` + to create the following prims in the scene: + + * :mod:`isaaclab.sim.spawners.from_file`: Create a prim from a USD/URDF file. + * :mod:`isaaclab.sim.spawners.shapes`: Create USDGeom prims for shapes (box, sphere, cylinder, capsule, etc.). + * :mod:`isaaclab.sim.spawners.materials`: Create a visual or physics material prim. + * :mod:`isaaclab.sim.spawners.lights`: Create a USDLux prim for different types of lights. + * :mod:`isaaclab.sim.spawners.sensors`: Create a USD prim for supported sensors. + +Changed +^^^^^^^ + +* Modified the :class:`SimulationContext` class to take the default physics material using the material spawn + configuration object. + + +0.8.10 (2023-08-17) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added methods for defining different physics-based schemas in the :mod:`isaaclab.sim.schemas` module. + These methods allow creating the schema if it doesn't exist at the specified prim path and modify + its properties based on the configuration object. + + +0.8.9 (2023-08-09) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Moved the :class:`isaaclab.asset_loader.UrdfLoader` class to the :mod:`isaaclab.sim.loaders` + module to make it more accessible to the user. + + +0.8.8 (2023-08-09) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added configuration classes and functions for setting different physics-based schemas in the + :mod:`isaaclab.sim.schemas` module. These allow modifying properties of the physics solver + on the asset using configuration objects. + + +0.8.7 (2023-08-03) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added support for `__post_init__ `_ in + the :class:`isaaclab.utils.configclass` decorator. + + +0.8.6 (2023-08-03) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added support for callable classes in the :class:`isaaclab.managers.ManagerBase`. + + +0.8.5 (2023-08-03) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the :class:`isaaclab.markers.Visualizationmarkers` class so that the markers are not visible in camera rendering mode. + +Changed +^^^^^^^ + +* Simplified the creation of the point instancer in the :class:`isaaclab.markers.Visualizationmarkers` class. It now creates a new + prim at the next available prim path if a prim already exists at the given path. + + +0.8.4 (2023-08-02) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the :class:`isaaclab.sim.SimulationContext` class to the :mod:`isaaclab.sim` module. + This class inherits from the :class:`isaacsim.core.api.simulation_context.SimulationContext` class and adds + the ability to create a simulation context from a configuration object. + + +0.8.3 (2023-08-02) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Moved the :class:`ActuatorBase` class to the :mod:`isaaclab.actuators.actuator_base` module. +* Renamed the :mod:`isaaclab.actuators.actuator` module to :mod:`isaaclab.actuators.actuator_pd` + to make it more explicit that it contains the PD actuator models. + + +0.8.2 (2023-08-02) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Cleaned up the :class:`isaaclab.terrain.TerrainImporter` class to take all the parameters from the configuration + object. This makes it consistent with the other classes in the package. +* Moved the configuration classes for terrain generator and terrain importer into separate files to resolve circular + dependency issues. + + +0.8.1 (2023-08-02) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added a hack into :class:`isaaclab.app.AppLauncher` class to remove Isaac Lab packages from the path before launching + the simulation application. This prevents the warning messages that appears when the user launches the ``SimulationApp``. + +Added +^^^^^ + +* Enabled necessary viewport extensions in the :class:`isaaclab.app.AppLauncher` class itself if ``VIEWPORT_ENABLED`` + flag is true. + + +0.8.0 (2023-07-26) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the :class:`ActionManager` class to the :mod:`isaaclab.managers` module to handle actions in the + environment through action terms. +* Added contact force history to the :class:`isaaclab.sensors.ContactSensor` class. The history is stored + in the ``net_forces_w_history`` attribute of the sensor data. + +Changed +^^^^^^^ + +* Implemented lazy update of buffers in the :class:`isaaclab.sensors.SensorBase` class. This allows the user + to update the sensor data only when required, i.e. when the data is requested by the user. This helps avoid double + computation of sensor data when a reset is called in the environment. + +Deprecated +^^^^^^^^^^ + +* Removed the support for different backends in the sensor class. We only use Pytorch as the backend now. +* Removed the concept of actuator groups. They are now handled by the :class:`isaaclab.managers.ActionManager` + class. The actuator models are now directly handled by the robot class itself. + + +0.7.4 (2023-07-26) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed the behavior of the :class:`isaaclab.terrains.TerrainImporter` class. It now expects the terrain + type to be specified in the configuration object. This allows the user to specify everything in the configuration + object and not have to do an explicit call to import a terrain. + +Fixed +^^^^^ + +* Fixed setting of quaternion orientations inside the :class:`isaaclab.markers.Visualizationmarkers` class. + Earlier, the orientation was being set into the point instancer in the wrong order (``wxyz`` instead of ``xyzw``). + + +0.7.3 (2023-07-25) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the issue with multiple inheritance in the :class:`isaaclab.utils.configclass` decorator. + Earlier, if the inheritance tree was more than one level deep and the lowest level configuration class was + not updating its values from the middle level classes. + + +0.7.2 (2023-07-24) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the method :meth:`replace` to the :class:`isaaclab.utils.configclass` decorator to allow + creating a new configuration object with values replaced from keyword arguments. This function internally + calls the `dataclasses.replace `_. + +Fixed +^^^^^ + +* Fixed the handling of class types as member values in the :meth:`isaaclab.utils.configclass`. Earlier it was + throwing an error since class types were skipped in the if-else block. + + +0.7.1 (2023-07-22) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the :class:`TerminationManager`, :class:`CurriculumManager`, and :class:`RandomizationManager` classes + to the :mod:`isaaclab.managers` module to handle termination, curriculum, and randomization respectively. + + +0.7.0 (2023-07-22) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Created a new :mod:`isaaclab.managers` module for all the managers related to the environment / scene. + This includes the :class:`isaaclab.managers.ObservationManager` and :class:`isaaclab.managers.RewardManager` + classes that were previously in the :mod:`isaaclab.utils.mdp` module. +* Added the :class:`isaaclab.managers.ManagerBase` class to handle the creation of managers. +* Added configuration classes for :class:`ObservationTermCfg` and :class:`RewardTermCfg` to allow easy creation of + observation and reward terms. + +Changed +^^^^^^^ + +* Changed the behavior of :class:`ObservationManager` and :class:`RewardManager` classes to accept the key ``func`` + in each configuration term to be a callable. This removes the need to inherit from the base class + and allows more reusability of the functions across different environments. +* Moved the old managers to the :mod:`isaaclab.compat.utils.mdp` module. +* Modified the necessary scripts to use the :mod:`isaaclab.compat.utils.mdp` module. + + +0.6.2 (2023-07-21) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the :mod:`isaaclab.command_generators` to generate different commands based on the desired task. + It allows the user to generate commands for different tasks in the same environment without having to write + custom code for each task. + + +0.6.1 (2023-07-16) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the :meth:`isaaclab.utils.math.quat_apply_yaw` to compute the yaw quaternion correctly. + +Added +^^^^^ + +* Added functions to convert string and callable objects in :mod:`isaaclab.utils.string`. + + +0.6.0 (2023-07-16) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the argument :attr:`sort_keys` to the :meth:`isaaclab.utils.io.yaml.dump_yaml` method to allow + enabling/disabling of sorting of keys in the output yaml file. + +Fixed +^^^^^ + +* Fixed the ordering of terms in :mod:`isaaclab.utils.configclass` to be consistent in the order in which + they are defined. Previously, the ordering was done alphabetically which made it inconsistent with the order in which + the parameters were defined. + +Changed +^^^^^^^ + +* Changed the default value of the argument :attr:`sort_keys` in the :meth:`isaaclab.utils.io.yaml.dump_yaml` + method to ``False``. +* Moved the old config classes in :mod:`isaaclab.utils.configclass` to + :mod:`isaaclab.compat.utils.configclass` so that users can still run their old code where alphabetical + ordering was used. + + +0.5.0 (2023-07-04) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a generalized :class:`isaaclab.sensors.SensorBase` class that leverages the ideas of views to + handle multiple sensors in a single class. +* Added the classes :class:`isaaclab.sensors.RayCaster`, :class:`isaaclab.sensors.ContactSensor`, + and :class:`isaaclab.sensors.Camera` that output a batched tensor of sensor data. + +Changed +^^^^^^^ + +* Renamed the parameter ``sensor_tick`` to ``update_freq`` to make it more intuitive. +* Moved the old sensors in :mod:`isaaclab.sensors` to :mod:`isaaclab.compat.sensors`. +* Modified the standalone scripts to use the :mod:`isaaclab.compat.sensors` module. + + +0.4.4 (2023-07-05) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the :meth:`isaaclab.terrains.trimesh.utils.make_plane` method to handle the case when the + plane origin does not need to be centered. +* Added the :attr:`isaaclab.terrains.TerrainGeneratorCfg.seed` to make generation of terrains reproducible. + The default value is ``None`` which means that the seed is not set. + +Changed +^^^^^^^ + +* Changed the saving of ``origins`` in :class:`isaaclab.terrains.TerrainGenerator` class to be in CSV format + instead of NPY format. + + +0.4.3 (2023-06-28) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the :class:`isaaclab.markers.PointInstancerMarker` class that wraps around + `UsdGeom.PointInstancer `_ + to directly work with torch and numpy arrays. + +Changed +^^^^^^^ + +* Moved the old markers in :mod:`isaaclab.markers` to :mod:`isaaclab.compat.markers`. +* Modified the standalone scripts to use the :mod:`isaaclab.compat.markers` module. + + +0.4.2 (2023-06-28) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the sub-module :mod:`isaaclab.terrains` to allow procedural generation of terrains and supporting + importing of terrains from different sources (meshes, usd files or default ground plane). + + +0.4.1 (2023-06-27) +~~~~~~~~~~~~~~~~~~ + +* Added the :class:`isaaclab.app.AppLauncher` class to allow controlled instantiation of + the SimulationApp and extension loading for remote deployment and ROS bridges. + +Changed +^^^^^^^ + +* Modified all standalone scripts to use the :class:`isaaclab.app.AppLauncher` class. + + +0.4.0 (2023-05-27) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a helper class :class:`isaaclab.asset_loader.UrdfLoader` that converts a URDF file to instanceable USD + file based on the input configuration object. + + +0.3.2 (2023-04-27) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added safe-printing of functions while using the :meth:`isaaclab.utils.dict.print_dict` function. + + +0.3.1 (2023-04-23) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added a modified version of ``lula_franka_gen.urdf`` which includes an end-effector frame. +* Added a standalone script ``play_rmpflow.py`` to show RMPFlow controller. + +Fixed +^^^^^ + +* Fixed the splitting of commands in the :meth:`ActuatorGroup.compute` method. Earlier it was reshaping the + commands to the shape ``(num_actuators, num_commands)`` which was causing the commands to be split incorrectly. +* Fixed the processing of actuator command in the :meth:`RobotBase._process_actuators_cfg` to deal with multiple + command types when using "implicit" actuator group. + +0.3.0 (2023-04-20) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Added the destructor to the keyboard devices to unsubscribe from carb. + +Added +^^^^^ + +* Added the :class:`Se2Gamepad` and :class:`Se3Gamepad` for gamepad teleoperation support. + + +0.2.8 (2023-04-10) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed bugs in :meth:`axis_angle_from_quat` in the ``isaaclab.utils.math`` to handle quaternion with negative w component. +* Fixed bugs in :meth:`subtract_frame_transforms` in the ``isaaclab.utils.math`` by adding the missing final rotation. + + +0.2.7 (2023-04-07) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed repetition in applying mimic multiplier for "p_abs" in the :class:`GripperActuatorGroup` class. +* Fixed bugs in :meth:`reset_buffers` in the :class:`RobotBase` and :class:`LeggedRobot` classes. + +0.2.6 (2023-03-16) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added the :class:`CollisionPropertiesCfg` to rigid/articulated object and robot base classes. +* Added the :class:`PhysicsMaterialCfg` to the :class:`SingleArm` class for tool sites. + +Changed +^^^^^^^ + +* Changed the default control mode of the :obj:`PANDA_HAND_MIMIC_GROUP_CFG` to be from ``"v_abs"`` to ``"p_abs"``. + Using velocity control for the mimic group can cause the hand to move in a jerky manner. + + +0.2.5 (2023-03-08) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the indices used for the Jacobian and dynamics quantities in the :class:`MobileManipulator` class. + + +0.2.4 (2023-03-04) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :meth:`apply_nested_physics_material` to the ``isaaclab.utils.kit``. +* Added the :meth:`sample_cylinder` to sample points from a cylinder's surface. +* Added documentation about the issue in using instanceable asset as markers. + +Fixed +^^^^^ + +* Simplified the physics material application in the rigid object and legged robot classes. + +Removed +^^^^^^^ + +* Removed the ``geom_prim_rel_path`` argument in the :class:`RigidObjectCfg.MetaInfoCfg` class. + + +0.2.3 (2023-02-24) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the end-effector body index used for getting the Jacobian in the :class:`SingleArm` and :class:`MobileManipulator` classes. + + +0.2.2 (2023-01-27) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the :meth:`set_world_pose_ros` and :meth:`set_world_pose_from_view` in the :class:`Camera` class. + +Deprecated +^^^^^^^^^^ + +* Removed the :meth:`set_world_pose_from_ypr` method from the :class:`Camera` class. + + +0.2.1 (2023-01-26) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the :class:`Camera` class to support different fisheye projection types. + + +0.2.0 (2023-01-25) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added support for warp backend in camera utilities. +* Extended the ``play_camera.py`` with ``--gpu`` flag to use GPU replicator backend. + +0.1.1 (2023-01-24) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed setting of physics material on the ground plane when using :meth:`isaaclab.utils.kit.create_ground_plane` function. + + +0.1.0 (2023-01-17) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Initial release of the extension with experimental API. +* Available robot configurations: + + * **Quadrupeds:** Unitree A1, ANYmal B, ANYmal C + * **Single-arm manipulators:** Franka Emika arm, UR5 + * **Mobile manipulators:** Clearpath Ridgeback with Franka Emika arm or UR5 diff --git a/simulation/modules/IsaacLab/source/isaaclab/docs/README.md b/simulation/modules/IsaacLab/source/isaaclab/docs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f5ded99b04773e465321109359134f5357efde34 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/docs/README.md @@ -0,0 +1,11 @@ +# Isaac Lab: Framework + +Isaac Lab includes its own set of interfaces and wrappers around Isaac Sim classes. One of the main goals behind this +decision is to have a unified description for different systems. While isaac Sim tries to be general for a wider +variety of simulation requires, our goal has been to specialize these for learning requirements. These include +features such as augmenting simulators with non-ideal actuator models, managing different observation and reward +settings, integrate different sensors, as well as provide interfaces to features that are currently not available in +Isaac Sim but are available from the physics side (such as deformable bodies). + +We recommend the users to try out the demo scripts present in `scripts/demos` that display how different parts +of the framework can be integrated together. diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d547b628372e3a118dcbef5772a53df4596692ef --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/__init__.py @@ -0,0 +1,106 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Package containing the core framework.""" + +import os +import sys + + +def _deprioritize_prebundle_paths(): + """Move Isaac Sim ``pip_prebundle`` and known conflicting extension directories to the end of ``sys.path``. + + Isaac Sim's ``setup_python_env.sh`` injects ``pip_prebundle`` directories + onto ``PYTHONPATH``. These contain older copies of packages like torch, + warp, and nvidia-cudnn that shadow the versions installed by Isaac Lab, + causing CUDA runtime errors. + + Additionally, certain Isaac Sim kit extensions (such as ``omni.warp.core``) + bundle their own copies of Python packages that conflict with pip-installed + versions. When loaded by the extension system these paths can appear on + ``sys.path`` before ``site-packages``, leading to version mismatches. + + Rather than removing these paths entirely (which would break packages like + ``sympy`` that only exist in the prebundle), this function moves them to + the **end** of ``sys.path`` so that pip-installed packages in + ``site-packages`` take priority. + + The ``PYTHONPATH`` environment variable is also rewritten so that child + processes inherit the corrected ordering. + """ + + # Extension directory fragments that are known to ship Python packages + # which conflict with Isaac Lab's pip-installed versions. + _CONFLICTING_EXT_FRAGMENTS = ( + "omni.warp.core", + "omni.isaac.ml_archive", + "omni.isaac.core_archive", + "omni.kit.pip_archive", + "isaacsim.pip.newton", + ) + + def _should_demote(path: str) -> bool: + norm = path.replace("\\", "/").lower() + if "pip_prebundle" in norm: + return True + for frag in _CONFLICTING_EXT_FRAGMENTS: + if frag.lower() in norm: + return True + return False + + # Partition: keep non-conflicting in place, collect conflicting. + clean = [] + demoted = [] + for p in sys.path: + if _should_demote(p): + demoted.append(p) + else: + clean.append(p) + + if not demoted: + return + + # Rebuild sys.path: originals first, then demoted at the very end. + sys.path[:] = clean + demoted + + # Rewrite PYTHONPATH with the same ordering for subprocesses. + if "PYTHONPATH" in os.environ: + parts = os.environ["PYTHONPATH"].split(os.pathsep) + env_clean = [] + env_demoted = [] + for p in parts: + if _should_demote(p): + env_demoted.append(p) + else: + env_clean.append(p) + os.environ["PYTHONPATH"] = os.pathsep.join(env_clean + env_demoted) + + +_deprioritize_prebundle_paths() + +# Conveniences to other module directories via relative paths. +ISAACLAB_EXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../")) +"""Path to the extension source directory.""" + +# The CLI imports this module to run installation. We must handle the case where +# dependencies (like toml) are not yet installed in a fresh environment. +# This prevents ImportError during the initial bootstrap phase. +try: + import toml + ISAACLAB_METADATA = toml.load(os.path.join(ISAACLAB_EXT_DIR, "config", "extension.toml")) + """Extension metadata dictionary parsed from the extension.toml file.""" + __version__ = ISAACLAB_METADATA["package"]["version"] +except ImportError: + # Check for tomllib (Python 3.11+). + try: + import tomllib + with open(os.path.join(ISAACLAB_EXT_DIR, "config", "extension.toml"), "rb") as f: + ISAACLAB_METADATA = tomllib.load(f) + __version__ = ISAACLAB_METADATA["package"]["version"] + except (ImportError, FileNotFoundError): + # Tomllib is not part of the standard library before Python 3.11. + # Stub is good enough for installation purposes. + ISAACLAB_METADATA = {"package": {"version": "0.0.0"}} + __version__ = "0.0.0" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/__pycache__/__init__.cpython-310.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c193d46185b4965217999190009efcd514299a1b Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/__pycache__/__init__.cpython-310.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/__pycache__/__init__.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c280ede2574746a9db2b482d4330d0bd00b3aec Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b0dff8dafd51e5acd4b07ec647555528abee0369 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__init__.py @@ -0,0 +1,27 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-package for different actuator models. + +Actuator models are used to model the behavior of the actuators in an articulation. These +are usually meant to be used in simulation to model different actuator dynamics and delays. + +There are two main categories of actuator models that are supported: + +- **Implicit**: Motor model with ideal PD from the physics engine. This is similar to having a continuous time + PD controller. The motor model is implicit in the sense that the motor model is not explicitly defined by the user. +- **Explicit**: Motor models based on physical drive models. + + - **Physics-based**: Derives the motor models based on first-principles. + - **Neural Network-based**: Learned motor models from actuator data. + +Every actuator model inherits from the :class:`isaaclab.actuators.ActuatorBase` class, +which defines the common interface for all actuator models. The actuator models are handled +and called by the :class:`isaaclab.assets.Articulation` class. +""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..566967cf11007add8aa1d27cf37ee33c6ad5bdb3 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__init__.pyi @@ -0,0 +1,42 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "ActuatorBase", + "ActuatorBaseCfg", + "ActuatorNetLSTM", + "ActuatorNetMLP", + "ActuatorNetLSTMCfg", + "ActuatorNetMLPCfg", + "DCMotor", + "DelayedPDActuator", + "IdealPDActuator", + "ImplicitActuator", + "RemotizedPDActuator", + "DCMotorCfg", + "DelayedPDActuatorCfg", + "IdealPDActuatorCfg", + "ImplicitActuatorCfg", + "RemotizedPDActuatorCfg", +] + +from .actuator_base import ActuatorBase +from .actuator_base_cfg import ActuatorBaseCfg +from .actuator_net import ActuatorNetLSTM, ActuatorNetMLP +from .actuator_net_cfg import ActuatorNetLSTMCfg, ActuatorNetMLPCfg +from .actuator_pd import ( + DCMotor, + DelayedPDActuator, + IdealPDActuator, + ImplicitActuator, + RemotizedPDActuator, +) +from .actuator_pd_cfg import ( + DCMotorCfg, + DelayedPDActuatorCfg, + IdealPDActuatorCfg, + ImplicitActuatorCfg, + RemotizedPDActuatorCfg, +) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/__init__.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05af5a8745a09800012d03a369b3e91af717521d Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_base.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ade0b4b495057fc77fe2593e37ee5467a3c2643 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_base.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_base_cfg.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_base_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2014aa3b8595885725b241aaaceed4daf4512c8 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_base_cfg.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_net_cfg.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_net_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c36f5a8490e2ef9f79784e87df1f6791fa14f01 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_net_cfg.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_pd.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_pd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ccef5d8eebb579b45b63652fd0e0581fcc3a36e Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_pd.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_pd_cfg.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_pd_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa609720511f63f1e093b4f186dcc8bebdaf4a2d Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/__pycache__/actuator_pd_cfg.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_base.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_base.py new file mode 100644 index 0000000000000000000000000000000000000000..4489983366d30b4570ae77cb4f8f1a94b8230426 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_base.py @@ -0,0 +1,381 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from abc import ABC, abstractmethod +from collections.abc import Sequence +from typing import TYPE_CHECKING, ClassVar + +import torch + +import isaaclab.utils.string as string_utils +from isaaclab.utils.types import ArticulationActions + +if TYPE_CHECKING: + from .actuator_base_cfg import ActuatorBaseCfg + + +class ActuatorBase(ABC): + """Base class for actuator models over a collection of actuated joints in an articulation. + + Actuator models augment the simulated articulation joints with an external drive dynamics model. + The model is used to convert the user-provided joint commands (positions, velocities and efforts) + into the desired joint positions, velocities and efforts that are applied to the simulated articulation. + + The base class provides the interface for the actuator models. It is responsible for parsing the + actuator parameters from the configuration and storing them as buffers. It also provides the + interface for resetting the actuator state and computing the desired joint commands for the simulation. + + For each actuator model, a corresponding configuration class is provided. The configuration class + is used to parse the actuator parameters from the configuration. It also specifies the joint names + for which the actuator model is applied. These names can be specified as regular expressions, which + are matched against the joint names in the articulation. + + To see how the class is used, check the :class:`isaaclab.assets.Articulation` class. + """ + + is_implicit_model: ClassVar[bool] = False + """Flag indicating if the actuator is an implicit or explicit actuator model. + + If a class inherits from :class:`ImplicitActuator`, then this flag should be set to :obj:`True`. + """ + + computed_effort: torch.Tensor + """The computed effort for the actuator group. Shape is (num_envs, num_joints).""" + + applied_effort: torch.Tensor + """The applied effort for the actuator group. Shape is (num_envs, num_joints). + + This is the effort obtained after clipping the :attr:`computed_effort` based on the + actuator characteristics. + """ + + effort_limit: torch.Tensor + """The effort limit for the actuator group. Shape is (num_envs, num_joints). + + This limit is used differently depending on the actuator type: + + - **Explicit actuators**: Used for internal torque clipping within the actuator model + (e.g., motor torque limits in DC motor models). + - **Implicit actuators**: Same as :attr:`effort_limit_sim` (aliased for consistency). + """ + + effort_limit_sim: torch.Tensor + """The effort limit for the actuator group in the simulation. Shape is (num_envs, num_joints). + + For implicit actuators, the :attr:`effort_limit` and :attr:`effort_limit_sim` are the same. + + - **Explicit actuators**: Typically set to a large value (1.0e9) to avoid double-clipping, + since the actuator model already clips efforts using :attr:`effort_limit`. + - **Implicit actuators**: Same as :attr:`effort_limit` (both values are synchronized). + """ + + velocity_limit: torch.Tensor + """The velocity limit for the actuator group. Shape is (num_envs, num_joints). + + For implicit actuators, the :attr:`velocity_limit` and :attr:`velocity_limit_sim` are the same. + """ + + velocity_limit_sim: torch.Tensor + """The velocity limit for the actuator group in the simulation. Shape is (num_envs, num_joints). + + For implicit actuators, the :attr:`velocity_limit` and :attr:`velocity_limit_sim` are the same. + """ + + stiffness: torch.Tensor + """The stiffness (P gain) of the PD controller. Shape is (num_envs, num_joints).""" + + damping: torch.Tensor + """The damping (D gain) of the PD controller. Shape is (num_envs, num_joints).""" + + armature: torch.Tensor + """The armature of the actuator joints. Shape is (num_envs, num_joints).""" + + friction: torch.Tensor + """The joint static friction of the actuator joints. Shape is (num_envs, num_joints).""" + + dynamic_friction: torch.Tensor + """The joint dynamic friction of the actuator joints. Shape is (num_envs, num_joints).""" + + viscous_friction: torch.Tensor + """The joint viscous friction of the actuator joints. Shape is (num_envs, num_joints).""" + + _DEFAULT_MAX_EFFORT_SIM: ClassVar[float] = 1.0e9 + """The default maximum effort for the actuator joints in the simulation. Defaults to 1.0e9. + + If the :attr:`ActuatorBaseCfg.effort_limit_sim` is not specified and the actuator is an explicit + actuator, then this value is used. + """ + + def __init__( + self, + cfg: ActuatorBaseCfg, + joint_names: list[str], + joint_ids: slice | torch.Tensor, + num_envs: int, + device: str, + stiffness: torch.Tensor | float = 0.0, + damping: torch.Tensor | float = 0.0, + armature: torch.Tensor | float = 0.0, + friction: torch.Tensor | float = 0.0, + dynamic_friction: torch.Tensor | float = 0.0, + viscous_friction: torch.Tensor | float = 0.0, + effort_limit: torch.Tensor | float = torch.inf, + velocity_limit: torch.Tensor | float = torch.inf, + ): + """Initialize the actuator. + + The actuator parameters are parsed from the configuration and stored as buffers. If the parameters + are not specified in the configuration, then their values provided in the constructor are used. + + .. note:: + The values in the constructor are typically obtained through the USD values passed from the PhysX API calls + corresponding to the joints in the actuator model; these values serve as default values if the parameters + are not specified in the cfg. + + + + Args: + cfg: The configuration of the actuator model. + joint_names: The joint names in the articulation. + joint_ids: The joint indices in the articulation. If :obj:`slice(None)`, then all + the joints in the articulation are part of the group. + num_envs: Number of articulations in the view. + device: Device used for processing. + stiffness: The default joint stiffness (P gain). Defaults to 0.0. + If a tensor, then the shape is (num_envs, num_joints). + damping: The default joint damping (D gain). Defaults to 0.0. + If a tensor, then the shape is (num_envs, num_joints). + armature: The default joint armature. Defaults to 0.0. + If a tensor, then the shape is (num_envs, num_joints). + friction: The default joint static friction. Defaults to 0.0. + If a tensor, then the shape is (num_envs, num_joints). + dynamic_friction: The default joint dynamic friction. Defaults to 0.0. + If a tensor, then the shape is (num_envs, num_joints). + viscous_friction: The default joint viscous friction. Defaults to 0.0. + If a tensor, then the shape is (num_envs, num_joints). + effort_limit: The default effort limit. Defaults to infinity. + If a tensor, then the shape is (num_envs, num_joints). + velocity_limit: The default velocity limit. Defaults to infinity. + If a tensor, then the shape is (num_envs, num_joints). + """ + # save parameters + self.cfg = cfg + self._num_envs = num_envs + self._device = device + self._joint_names = joint_names + self._joint_indices = joint_ids + self.joint_property_resolution_table: dict[str, list] = {} + # For explicit models, we do not want to enforce the effort limit through the solver + # (unless it is explicitly set) + if not self.is_implicit_model and self.cfg.effort_limit_sim is None: + self.cfg.effort_limit_sim = self._DEFAULT_MAX_EFFORT_SIM + + # resolve usd, actuator configuration values + # case 1: if usd_value == actuator_cfg_value: all good, + # case 2: if usd_value != actuator_cfg_value: we use actuator_cfg_value + # case 3: if actuator_cfg_value is None: we use usd_value + + to_check = [ + ("velocity_limit_sim", velocity_limit), + ("effort_limit_sim", effort_limit), + ("stiffness", stiffness), + ("damping", damping), + ("armature", armature), + ("friction", friction), + ("dynamic_friction", dynamic_friction), + ("viscous_friction", viscous_friction), + ] + for param_name, usd_val in to_check: + cfg_val = getattr(self.cfg, param_name) + setattr(self, param_name, self._parse_joint_parameter(cfg_val, usd_val)) + new_val = getattr(self, param_name) + + allclose = ( + torch.all(new_val == usd_val) if isinstance(usd_val, (float, int)) else torch.allclose(new_val, usd_val) + ) + if cfg_val is None or not allclose: + self._record_actuator_resolution( + cfg_val=getattr(self.cfg, param_name), + new_val=new_val[0], # new val always has the shape of (num_envs, num_joints) + usd_val=usd_val, + joint_names=joint_names, + joint_ids=joint_ids, + actuator_param=param_name, + ) + + self.velocity_limit = self._parse_joint_parameter(self.cfg.velocity_limit, self.velocity_limit_sim) + # Parse effort_limit with special default handling: + # - If cfg.effort_limit is None, use the original USD value (effort_limit parameter from constructor) + # - Otherwise, use effort_limit_sim as the default + # Please refer to the documentation of the effort_limit and effort_limit_sim parameters for more details. + effort_default = effort_limit if self.cfg.effort_limit is None else self.effort_limit_sim + self.effort_limit = self._parse_joint_parameter(self.cfg.effort_limit, effort_default) + + # create commands buffers for allocation + self.computed_effort = torch.zeros(self._num_envs, self.num_joints, device=self._device) + self.applied_effort = torch.zeros_like(self.computed_effort) + + def __str__(self) -> str: + """Returns: A string representation of the actuator group.""" + # resolve joint indices for printing + joint_indices = self.joint_indices + if joint_indices == slice(None): + joint_indices = list(range(self.num_joints)) + # resolve model type (implicit or explicit) + model_type = "implicit" if self.is_implicit_model else "explicit" + + return ( + f" object:\n" + f"\tModel type : {model_type}\n" + f"\tNumber of joints : {self.num_joints}\n" + f"\tJoint names expression: {self.cfg.joint_names_expr}\n" + f"\tJoint names : {self.joint_names}\n" + f"\tJoint indices : {joint_indices}\n" + ) + + """ + Properties. + """ + + @property + def num_joints(self) -> int: + """Number of actuators in the group.""" + return len(self._joint_names) + + @property + def joint_names(self) -> list[str]: + """Articulation's joint names that are part of the group.""" + return self._joint_names + + @property + def joint_indices(self) -> slice | torch.Tensor: + """Articulation's joint indices that are part of the group. + + Note: + If :obj:`slice(None)` is returned, then the group contains all the joints in the articulation. + We do this to avoid unnecessary indexing of the joints for performance reasons. + """ + return self._joint_indices + + """ + Operations. + """ + + @abstractmethod + def reset(self, env_ids: Sequence[int]): + """Reset the internals within the group. + + Args: + env_ids: List of environment IDs to reset. + """ + raise NotImplementedError + + @abstractmethod + def compute( + self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor + ) -> ArticulationActions: + """Process the actuator group actions and compute the articulation actions. + + It computes the articulation actions based on the actuator model type + + Args: + control_action: The joint action instance comprising of the desired joint positions, joint velocities + and (feed-forward) joint efforts. + joint_pos: The current joint positions of the joints in the group. Shape is (num_envs, num_joints). + joint_vel: The current joint velocities of the joints in the group. Shape is (num_envs, num_joints). + + Returns: + The computed desired joint positions, joint velocities and joint efforts. + """ + raise NotImplementedError + + """ + Helper functions. + """ + + def _record_actuator_resolution(self, cfg_val, new_val, usd_val, joint_names, joint_ids, actuator_param: str): + if actuator_param not in self.joint_property_resolution_table: + self.joint_property_resolution_table[actuator_param] = [] + table = self.joint_property_resolution_table[actuator_param] + + ids = joint_ids if isinstance(joint_ids, torch.Tensor) else list(range(len(joint_names))) + for idx, name in enumerate(joint_names): + cfg_val_log = "Not Specified" if cfg_val is None else float(new_val[idx]) + default_usd_val = usd_val if isinstance(usd_val, (float, int)) else float(usd_val[0][idx]) + applied_val_log = default_usd_val if cfg_val is None else float(new_val[idx]) + table.append([name, int(ids[idx]), default_usd_val, cfg_val_log, applied_val_log]) + + def _parse_joint_parameter( + self, cfg_value: float | dict[str, float] | None, default_value: float | torch.Tensor | None + ) -> torch.Tensor: + """Parse the joint parameter from the configuration. + + Args: + cfg_value: The parameter value from the configuration. If None, then use the default value. + default_value: The default value to use if the parameter is None. If it is also None, + then an error is raised. + + Returns: + The parsed parameter value. + + Raises: + TypeError: If the parameter value is not of the expected type. + TypeError: If the default value is not of the expected type. + ValueError: If the parameter value is None and no default value is provided. + ValueError: If the default value tensor is the wrong shape. + """ + # create parameter buffer + param = torch.zeros(self._num_envs, self.num_joints, device=self._device) + # parse the parameter + if cfg_value is not None: + if isinstance(cfg_value, (float, int)): + # if float, then use the same value for all joints + param[:] = float(cfg_value) + elif isinstance(cfg_value, dict): + # if dict, then parse the regular expression + indices, _, values = string_utils.resolve_matching_names_values(cfg_value, self.joint_names) + # note: need to specify type to be safe (e.g. values are ints, but we want floats) + param[:, indices] = torch.tensor(values, dtype=torch.float, device=self._device) + else: + raise TypeError( + f"Invalid type for parameter value: {type(cfg_value)} for " + + f"actuator on joints {self.joint_names}. Expected float or dict." + ) + elif default_value is not None: + if isinstance(default_value, (float, int)): + # if float, then use the same value for all joints + param[:] = float(default_value) + elif isinstance(default_value, torch.Tensor): + # if tensor, then use the same tensor for all joints + if default_value.shape == (self._num_envs, self.num_joints): + param = default_value.float() + else: + raise ValueError( + "Invalid default value tensor shape.\n" + f"Got: {default_value.shape}\n" + f"Expected: {(self._num_envs, self.num_joints)}" + ) + else: + raise TypeError( + f"Invalid type for default value: {type(default_value)} for " + + f"actuator on joints {self.joint_names}. Expected float or Tensor." + ) + else: + raise ValueError("The parameter value is None and no default value is provided.") + + return param + + def _clip_effort(self, effort: torch.Tensor) -> torch.Tensor: + """Clip the desired torques based on the motor limits. + + Args: + desired_torques: The desired torques to clip. + + Returns: + The clipped torques. + """ + return torch.clip(effort, min=-self.effort_limit, max=self.effort_limit) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_base_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_base_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..8afa1807754ddd57f34a8a76231cb57965092903 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_base_cfg.py @@ -0,0 +1,167 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from dataclasses import MISSING + +from isaaclab.utils.configclass import configclass + + +@configclass +class ActuatorBaseCfg: + """Configuration for default actuators in an articulation.""" + + class_type: type = MISSING + """The associated actuator class. + + The class should inherit from :class:`isaaclab.actuators.ActuatorBase`. + """ + + joint_names_expr: list[str] = MISSING + """Articulation's joint names that are part of the group. + + Note: + This can be a list of joint names or a list of regex expressions (e.g. ".*"). + """ + + effort_limit: dict[str, float] | float | None = None + """Force/Torque limit of the joints in the group. Defaults to None. + + This limit is used to clip the computed torque sent to the simulation. If None, the + limit is set to the value specified in the USD joint prim. + + .. attention:: + + The :attr:`effort_limit_sim` attribute should be used to set the effort limit for + the simulation physics solver. + + The :attr:`effort_limit` attribute is used for clipping the effort output of the + actuator model **only** in the case of explicit actuators, such as the + :class:`~isaaclab.actuators.IdealPDActuator`. + + .. note:: + + For implicit actuators, the attributes :attr:`effort_limit` and :attr:`effort_limit_sim` + are equivalent. However, we suggest using the :attr:`effort_limit_sim` attribute because + it is more intuitive. + + """ + + velocity_limit: dict[str, float] | float | None = None + """Velocity limit of the joints in the group. Defaults to None. + + This limit is used by the actuator model. If None, the limit is set to the value specified + in the USD joint prim. + + .. attention:: + + The :attr:`velocity_limit_sim` attribute should be used to set the velocity limit for + the simulation physics solver. + + The :attr:`velocity_limit` attribute is used for clipping the effort output of the + actuator model **only** in the case of explicit actuators, such as the + :class:`~isaaclab.actuators.IdealPDActuator`. + + .. note:: + + For implicit actuators, the attribute :attr:`velocity_limit` is not used. This is to stay + backwards compatible with previous versions of the Isaac Lab, where this parameter was + unused since PhysX did not support setting the velocity limit for the joints using the + PhysX Tensor API. + """ + + effort_limit_sim: dict[str, float] | float | None = None + """Effort limit of the joints in the group applied to the simulation physics solver. Defaults to None. + + The effort limit is used to constrain the computed joint efforts in the physics engine. If the + computed effort exceeds this limit, the physics engine will clip the effort to this value. + + Since explicit actuators (e.g. DC motor), compute and clip the effort in the actuator model, this + limit is by default set to a large value to prevent the physics engine from any additional clipping. + However, at times, it may be necessary to set this limit to a smaller value as a safety measure. + + If None, the limit is resolved based on the type of actuator model: + + * For implicit actuators, the limit is set to the value specified in the USD joint prim. + * For explicit actuators, the limit is set to 1.0e9. + + """ + + velocity_limit_sim: dict[str, float] | float | None = None + """Velocity limit of the joints in the group applied to the simulation physics solver. Defaults to None. + + The velocity limit is used to constrain the joint velocities in the physics engine. The joint will only + be able to reach this velocity if the joint's effort limit is sufficiently large. If the joint is moving + faster than this velocity, the physics engine will actually try to brake the joint to reach this velocity. + + If None, the limit is set to the value specified in the USD joint prim for both implicit and explicit actuators. + + .. tip:: + If the velocity limit is too tight, the physics engine may have trouble converging to a solution. + In such cases, we recommend either keeping this value sufficiently large or tuning the stiffness and + damping parameters of the joint to ensure the limits are not violated. + + """ + + stiffness: dict[str, float] | float | None = MISSING + """Stiffness gains (also known as p-gain) of the joints in the group. + + The behavior of the stiffness is different for implicit and explicit actuators. For implicit actuators, + the stiffness gets set into the physics engine directly. For explicit actuators, the stiffness is used + by the actuator model to compute the joint efforts. + + If None, the stiffness is set to the value from the USD joint prim. + """ + + damping: dict[str, float] | float | None = MISSING + """Damping gains (also known as d-gain) of the joints in the group. + + The behavior of the damping is different for implicit and explicit actuators. For implicit actuators, + the damping gets set into the physics engine directly. For explicit actuators, the damping gain is used + by the actuator model to compute the joint efforts. + + If None, the damping is set to the value from the USD joint prim. + """ + + armature: dict[str, float] | float | None = None + """Armature of the joints in the group. Defaults to None. + + The armature is directly added to the corresponding joint-space inertia. It helps improve the + simulation stability by reducing the joint velocities. + + It is a physics engine solver parameter that gets set into the simulation. + + If None, the armature is set to the value from the USD joint prim. + """ + + friction: dict[str, float] | float | None = None + r"""The static friction coefficient of the joints in the group. Defaults to None. + + The joint static friction is a unitless quantity. It relates the magnitude of the spatial force transmitted + from the parent body to the child body to the maximal static friction force that may be applied by the solver + to resist the joint motion. + + Mathematically, this means that: :math:`F_{resist} \leq \mu F_{spatial}`, where :math:`F_{resist}` + is the resisting force applied by the solver and :math:`F_{spatial}` is the spatial force + transmitted from the parent body to the child body. The simulated static friction effect is therefore + similar to static and Coulomb static friction. + + If None, the joint static friction is set to the value from the USD joint prim. + + Note: In Isaac Sim 4.5, this parameter is modeled as a coefficient. In Isaac Sim 5.0 and later, + it is modeled as an effort (torque or force). + """ + + dynamic_friction: dict[str, float] | float | None = None + """The dynamic friction coefficient of the joints in the group. Defaults to None. + + Note: In Isaac Sim 4.5, this parameter is modeled as a coefficient. In Isaac Sim 5.0 and later, + it is modeled as an effort (torque or force). + """ + + viscous_friction: dict[str, float] | float | None = None + """The viscous friction coefficient of the joints in the group. Defaults to None. + """ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..5cacb8ffa4084c00fca41c6b106511d70a0c007c --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_cfg.py @@ -0,0 +1,36 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import sys +import warnings + +from . import actuator_base_cfg, actuator_net_cfg, actuator_pd_cfg + + +def __getattr__(name): + new_module = None + if name in dir(actuator_pd_cfg): + new_module = actuator_pd_cfg + elif name in dir(actuator_net_cfg): + new_module = actuator_net_cfg + elif name in dir(actuator_base_cfg): + new_module = actuator_base_cfg + + if new_module is not None: + warnings.warn( + f"The module actuator_cfg.py is deprecated. Please import {name} directly from the isaaclab.actuators" + f" package, or from its new module {new_module.__name__}.", + DeprecationWarning, + stacklevel=2, + ) + return getattr(new_module, name) + if name in dir(sys.modules[__name__]): + return vars(sys.modules[__name__])[name] + if name == "__path__": + return __file__ + raise ImportError( + f"Failed to import attribute {name} from actuator_cfg.py. Warning: actuator_cfg.py has been " + + "deprecated. Please import actuator config classes directly from the isaaclab.actuators package.", + ) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_net.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_net.py new file mode 100644 index 0000000000000000000000000000000000000000..2274d1b78db39003ef3d555b9bc230c67b4fc02a --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -0,0 +1,188 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Neural network models for actuators. + +Currently, the following models are supported: + +* Multi-Layer Perceptron (MLP) +* Long Short-Term Memory (LSTM) + +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch + +from isaaclab.utils.assets import read_file +from isaaclab.utils.types import ArticulationActions + +from .actuator_pd import DCMotor + +if TYPE_CHECKING: + from .actuator_net_cfg import ActuatorNetLSTMCfg, ActuatorNetMLPCfg + + +class ActuatorNetLSTM(DCMotor): + """Actuator model based on recurrent neural network (LSTM). + + Unlike the MLP implementation :cite:t:`hwangbo2019learning`, this class implements + the learned model as a temporal neural network (LSTM) based on the work from + :cite:t:`rudin2022learning`. This removes the need of storing a history as the + hidden states of the recurrent network captures the history. + + Note: + Only the desired joint positions are used as inputs to the network. + """ + + cfg: ActuatorNetLSTMCfg + """The configuration of the actuator model.""" + + def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): + super().__init__(cfg, *args, **kwargs) + + # load the model from JIT file + file_bytes = read_file(self.cfg.network_file) + self.network = torch.jit.load(file_bytes, map_location=self._device).eval() + + # extract number of lstm layers and hidden dim from the shape of weights + num_layers = len(self.network.lstm.state_dict()) // 4 + hidden_dim = self.network.lstm.state_dict()["weight_hh_l0"].shape[1] + # create buffers for storing LSTM inputs + self.sea_input = torch.zeros(self._num_envs * self.num_joints, 1, 2, device=self._device) + self.sea_hidden_state = torch.zeros( + num_layers, self._num_envs * self.num_joints, hidden_dim, device=self._device + ) + self.sea_cell_state = torch.zeros(num_layers, self._num_envs * self.num_joints, hidden_dim, device=self._device) + # reshape via views (doesn't change the actual memory layout) + layer_shape_per_env = (num_layers, self._num_envs, self.num_joints, hidden_dim) + self.sea_hidden_state_per_env = self.sea_hidden_state.view(layer_shape_per_env) + self.sea_cell_state_per_env = self.sea_cell_state.view(layer_shape_per_env) + + """ + Operations. + """ + + def reset(self, env_ids: Sequence[int]): + # reset the hidden and cell states for the specified environments + with torch.no_grad(): + self.sea_hidden_state_per_env[:, env_ids] = 0.0 + self.sea_cell_state_per_env[:, env_ids] = 0.0 + + def compute( + self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor + ) -> ArticulationActions: + # compute network inputs + self.sea_input[:, 0, 0] = (control_action.joint_positions - joint_pos).flatten() + self.sea_input[:, 0, 1] = joint_vel.flatten() + + # run network inference + with torch.inference_mode(): + torques, (self.sea_hidden_state[:], self.sea_cell_state[:]) = self.network( + self.sea_input, (self.sea_hidden_state, self.sea_cell_state) + ) + self.computed_effort = torques.reshape(self._num_envs, self.num_joints) + + # clip the computed effort based on the motor limits + self.applied_effort = self._clip_effort(self.computed_effort) + + # return torques + control_action.joint_efforts = self.applied_effort + control_action.joint_positions = None + control_action.joint_velocities = None + return control_action + + +class ActuatorNetMLP(DCMotor): + """Actuator model based on multi-layer perceptron and joint history. + + Many times the analytical model is not sufficient to capture the actuator dynamics, the + delay in the actuator response, or the non-linearities in the actuator. In these cases, + a neural network model can be used to approximate the actuator dynamics. This model is + trained using data collected from the physical actuator and maps the joint state and the + desired joint command to the produced torque by the actuator. + + This class implements the learned model as a neural network based on the work from + :cite:t:`hwangbo2019learning`. The class stores the history of the joint positions errors + and velocities which are used to provide input to the neural network. The model is loaded + as a TorchScript. + + Note: + Only the desired joint positions are used as inputs to the network. + + """ + + cfg: ActuatorNetMLPCfg + """The configuration of the actuator model.""" + + def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): + super().__init__(cfg, *args, **kwargs) + + # load the model from JIT file + file_bytes = read_file(self.cfg.network_file) + self.network = torch.jit.load(file_bytes, map_location=self._device).eval() + + # create buffers for MLP history + history_length = max(self.cfg.input_idx) + 1 + self._joint_pos_error_history = torch.zeros( + self._num_envs, history_length, self.num_joints, device=self._device + ) + self._joint_vel_history = torch.zeros(self._num_envs, history_length, self.num_joints, device=self._device) + + """ + Operations. + """ + + def reset(self, env_ids: Sequence[int]): + # reset the history for the specified environments + self._joint_pos_error_history[env_ids] = 0.0 + self._joint_vel_history[env_ids] = 0.0 + + def compute( + self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor + ) -> ArticulationActions: + # move history queue by 1 and update top of history + # -- positions + self._joint_pos_error_history = self._joint_pos_error_history.roll(1, 1) + self._joint_pos_error_history[:, 0] = control_action.joint_positions - joint_pos + # -- velocity + self._joint_vel_history = self._joint_vel_history.roll(1, 1) + self._joint_vel_history[:, 0] = joint_vel + # save current joint vel for dc-motor clipping + self._joint_vel[:] = joint_vel + + # compute network inputs + # -- positions + pos_input = torch.cat([self._joint_pos_error_history[:, i].unsqueeze(2) for i in self.cfg.input_idx], dim=2) + pos_input = pos_input.view(self._num_envs * self.num_joints, -1) + # -- velocity + vel_input = torch.cat([self._joint_vel_history[:, i].unsqueeze(2) for i in self.cfg.input_idx], dim=2) + vel_input = vel_input.view(self._num_envs * self.num_joints, -1) + # -- scale and concatenate inputs + if self.cfg.input_order == "pos_vel": + network_input = torch.cat([pos_input * self.cfg.pos_scale, vel_input * self.cfg.vel_scale], dim=1) + elif self.cfg.input_order == "vel_pos": + network_input = torch.cat([vel_input * self.cfg.vel_scale, pos_input * self.cfg.pos_scale], dim=1) + else: + raise ValueError( + f"Invalid input order for MLP actuator net: {self.cfg.input_order}. Must be 'pos_vel' or 'vel_pos'." + ) + + # run network inference + with torch.inference_mode(): + torques = self.network(network_input).view(self._num_envs, self.num_joints) + self.computed_effort = torques.view(self._num_envs, self.num_joints) * self.cfg.torque_scale + + # clip the computed effort based on the motor limits + self.applied_effort = self._clip_effort(self.computed_effort) + + # return torques + control_action.joint_efforts = self.applied_effort + control_action.joint_positions = None + control_action.joint_velocities = None + return control_action diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..4a2d9ff30465c2b062e966b82c607bbf6cea0970 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py @@ -0,0 +1,66 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from collections.abc import Iterable +from dataclasses import MISSING +from typing import TYPE_CHECKING, Literal + +from isaaclab.utils.configclass import configclass + +from .actuator_pd_cfg import DCMotorCfg + +if TYPE_CHECKING: + from .actuator_net import ActuatorNetLSTM, ActuatorNetMLP + + +@configclass +class ActuatorNetLSTMCfg(DCMotorCfg): + """Configuration for LSTM-based actuator model.""" + + class_type: type["ActuatorNetLSTM"] | str = "{DIR}.actuator_net:ActuatorNetLSTM" + # we don't use stiffness and damping for actuator net + stiffness = None + damping = None + + network_file: str = MISSING + """Path to the file containing network weights.""" + + +@configclass +class ActuatorNetMLPCfg(DCMotorCfg): + """Configuration for MLP-based actuator model.""" + + class_type: type["ActuatorNetMLP"] | str = "{DIR}.actuator_net:ActuatorNetMLP" + # we don't use stiffness and damping for actuator net + + stiffness = None + damping = None + + network_file: str = MISSING + """Path to the file containing network weights.""" + + pos_scale: float = MISSING + """Scaling of the joint position errors input to the network.""" + vel_scale: float = MISSING + """Scaling of the joint velocities input to the network.""" + torque_scale: float = MISSING + """Scaling of the joint efforts output from the network.""" + + input_order: Literal["pos_vel", "vel_pos"] = MISSING + """Order of the inputs to the network. + + The order can be one of the following: + + * ``"pos_vel"``: joint position errors followed by joint velocities + * ``"vel_pos"``: joint velocities followed by joint position errors + """ + + input_idx: Iterable[int] = MISSING + """ + Indices of the actuator history buffer passed as inputs to the network. + + The index *0* corresponds to current time-step, while *n* corresponds to n-th + time-step in the past. The allocated history length is `max(input_idx) + 1`. + """ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_pd.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_pd.py new file mode 100644 index 0000000000000000000000000000000000000000..ff014fa7a58eaaf9fa058161f1d93c669075050c --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_pd.py @@ -0,0 +1,451 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import logging +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch + +from isaaclab.utils import DelayBuffer, LinearInterpolation +from isaaclab.utils.types import ArticulationActions + +from .actuator_base import ActuatorBase + +if TYPE_CHECKING: + from .actuator_pd_cfg import ( + DCMotorCfg, + DelayedPDActuatorCfg, + IdealPDActuatorCfg, + ImplicitActuatorCfg, + RemotizedPDActuatorCfg, + ) + +# import logger +logger = logging.getLogger(__name__) + +""" +Implicit Actuator Models. +""" + + +class ImplicitActuator(ActuatorBase): + """Implicit actuator model that is handled by the simulation. + + This performs a similar function as the :class:`IdealPDActuator` class. However, the PD control is handled + implicitly by the simulation which performs continuous-time integration of the PD control law. This is + generally more accurate than the explicit PD control law used in :class:`IdealPDActuator` when the simulation + time-step is large. + + The articulation class sets the stiffness and damping parameters from the implicit actuator configuration + into the simulation. Thus, the class does not perform its own computations on the joint action that + needs to be applied to the simulation. However, it computes the approximate torques for the actuated joint + since PhysX does not expose this quantity explicitly. + + .. caution:: + + The class is only provided for consistency with the other actuator models. It does not implement any + functionality and should not be used. All values should be set to the simulation directly. + """ + + cfg: ImplicitActuatorCfg + """The configuration for the actuator model.""" + + def __init__(self, cfg: ImplicitActuatorCfg, *args, **kwargs): + # effort limits + if cfg.effort_limit_sim is None and cfg.effort_limit is not None: + # throw a warning that we have a replacement for the deprecated parameter + logger.warning( + "The object has a value for 'effort_limit'." + " This parameter will be removed in the future." + " To set the effort limit, please use 'effort_limit_sim' instead." + ) + cfg.effort_limit_sim = cfg.effort_limit + elif cfg.effort_limit_sim is not None and cfg.effort_limit is None: + # TODO: Eventually we want to get rid of 'effort_limit' for implicit actuators. + # We should do this once all parameters have an "_sim" suffix. + cfg.effort_limit = cfg.effort_limit_sim + elif cfg.effort_limit_sim is not None and cfg.effort_limit is not None: + if cfg.effort_limit_sim != cfg.effort_limit: + raise ValueError( + "The object has set both 'effort_limit_sim' and 'effort_limit'" + f" and they have different values {cfg.effort_limit_sim} != {cfg.effort_limit}." + " Please only set 'effort_limit_sim' for implicit actuators." + ) + + # velocity limits + if cfg.velocity_limit_sim is None and cfg.velocity_limit is not None: + # throw a warning that previously this was not set + # it leads to different simulation behavior so we want to remain backwards compatible + logger.warning( + "The object has a value for 'velocity_limit'." + " Previously, although this value was specified, it was not getting used by implicit" + " actuators. Since this parameter affects the simulation behavior, we continue to not" + " use it. This parameter will be removed in the future." + " To set the velocity limit, please use 'velocity_limit_sim' instead." + ) + cfg.velocity_limit = None + elif cfg.velocity_limit_sim is not None and cfg.velocity_limit is None: + # TODO: Eventually we want to get rid of 'velocity_limit' for implicit actuators. + # We should do this once all parameters have an "_sim" suffix. + cfg.velocity_limit = cfg.velocity_limit_sim + elif cfg.velocity_limit_sim is not None and cfg.velocity_limit is not None: + if cfg.velocity_limit_sim != cfg.velocity_limit: + raise ValueError( + "The object has set both 'velocity_limit_sim' and 'velocity_limit'" + f" and they have different values {cfg.velocity_limit_sim} != {cfg.velocity_limit}." + " Please only set 'velocity_limit_sim' for implicit actuators." + ) + + # set implicit actuator model flag + ImplicitActuator.is_implicit_model = True + # call the base class + super().__init__(cfg, *args, **kwargs) + + """ + Operations. + """ + + def reset(self, *args, **kwargs): + # This is a no-op. There is no state to reset for implicit actuators. + pass + + def compute( + self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor + ) -> ArticulationActions: + """Process the actuator group actions and compute the articulation actions. + + In case of implicit actuator, the control action is directly returned as the computed action. + This function is a no-op and does not perform any computation on the input control action. + However, it computes the approximate torques for the actuated joint since PhysX does not compute + this quantity explicitly. + + Args: + control_action: The joint action instance comprising of the desired joint positions, joint velocities + and (feed-forward) joint efforts. + joint_pos: The current joint positions of the joints in the group. Shape is (num_envs, num_joints). + joint_vel: The current joint velocities of the joints in the group. Shape is (num_envs, num_joints). + + Returns: + The computed desired joint positions, joint velocities and joint efforts. + """ + # store approximate torques for reward computation + error_pos = control_action.joint_positions - joint_pos + error_vel = control_action.joint_velocities - joint_vel + self.computed_effort = self.stiffness * error_pos + self.damping * error_vel + control_action.joint_efforts + # clip the torques based on the motor limits + self.applied_effort = self._clip_effort(self.computed_effort) + return control_action + + +""" +Explicit Actuator Models. +""" + + +class IdealPDActuator(ActuatorBase): + r"""Ideal torque-controlled actuator model with a simple saturation model. + + It employs the following model for computing torques for the actuated joint :math:`j`: + + .. math:: + + \tau_{j, computed} = k_p * (q_{des} - q) + k_d * (\dot{q}_{des} - \dot{q}) + \tau_{ff} + + 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 clipping model is based on the maximum torque applied by the motor. It is implemented as: + + .. math:: + + \tau_{j, max} & = \gamma \times \tau_{motor, max} \\ + \tau_{j, applied} & = clip(\tau_{computed}, -\tau_{j, max}, \tau_{j, max}) + + where the clipping function is defined as :math:`clip(x, x_{min}, x_{max}) = min(max(x, x_{min}), x_{max})`. + The parameters :math:`\gamma` is the gear ratio of the gear box connecting the motor and the actuated joint ends, + and :math:`\tau_{motor, max}` is the maximum motor effort possible. These parameters are read from + the configuration instance passed to the class. + """ + + cfg: IdealPDActuatorCfg + """The configuration for the actuator model.""" + + """ + Operations. + """ + + def reset(self, env_ids: Sequence[int]): + pass + + def compute( + self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor + ) -> ArticulationActions: + # compute errors + error_pos = control_action.joint_positions - joint_pos + error_vel = control_action.joint_velocities - joint_vel + # calculate the desired joint torques + self.computed_effort = self.stiffness * error_pos + self.damping * error_vel + control_action.joint_efforts + # clip the torques based on the motor limits + self.applied_effort = self._clip_effort(self.computed_effort) + # set the computed actions back into the control action + control_action.joint_efforts = self.applied_effort + control_action.joint_positions = None + control_action.joint_velocities = None + return control_action + + +class DCMotor(IdealPDActuator): + r"""Direct control (DC) motor actuator model with velocity-based saturation model. + + It uses the same model as the :class:`IdealPDActuator` for computing the torques from input commands. + However, it implements a saturation model defined by a linear four quadrant DC motor torque-speed curve. + + A DC motor is a type of electric motor that is powered by direct current electricity. In most cases, + the motor is connected to a constant source of voltage supply, and the current is controlled by a rheostat. + Depending on various design factors such as windings and materials, the motor can draw a limited maximum power + from the electronic source, which limits the produced motor torque and speed. + + A DC motor characteristics are defined by the following parameters: + + * No-load speed (:math:`\dot{q}_{motor, max}`) : The maximum-rated speed of the motor at + zero torque (:attr:`velocity_limit`). + * Stall torque (:math:`\tau_{motor, stall}`): The maximum-rated torque produced at + zero speed (:attr:`saturation_effort`). + * Continuous torque (:math:`\tau_{motor, con}`): The maximum torque that can be outputted for a short period. + This is often enforced on the current drives for a DC motor to limit overheating, prevent mechanical damage, + or enforced by electrical limitations (:attr:`effort_limit`). + * Corner velocity (:math:`V_{c}`): The velocity where the torque-speed curve intersects with continuous torque. + + Based on these parameters, the instantaneous minimum and maximum torques for velocities between corner velocities + (where torque-speed curve intersects with continuous torque) are defined as follows: + + .. math:: + + \tau_{j, max}(\dot{q}) & = clip \left (\tau_{j, stall} \times \left(1 - + \frac{\dot{q}}{\dot{q}_{j, max}}\right), -∞, \tau_{j, con} \right) \\ + \tau_{j, min}(\dot{q}) & = clip \left (\tau_{j, stall} \times \left( -1 - + \frac{\dot{q}}{\dot{q}_{j, max}}\right), - \tau_{j, con}, ∞ \right) + + where :math:`\gamma` is the gear ratio of the gear box connecting the motor and the actuated joint ends, + :math:`\dot{q}_{j, max} = \gamma^{-1} \times \dot{q}_{motor, max}`, :math:`\tau_{j, con} = + \gamma \times \tau_{motor, con}` and :math:`\tau_{j, stall} = \gamma \times \tau_{motor, stall}` + are the maximum joint velocity, continuous joint torque and stall torque, respectively. These parameters + are read from the configuration instance passed to the class. + + Using these values, the computed torques are clipped to the minimum and maximum values based on the + instantaneous joint velocity: + + .. math:: + + \tau_{j, applied} = clip(\tau_{computed}, \tau_{j, min}(\dot{q}), \tau_{j, max}(\dot{q})) + + If the velocity of the joint is outside corner velocities (this would be due to external forces) the + applied output torque will be driven to the Continuous Torque (`effort_limit`). + + The figure below demonstrates the clipping action for example (velocity, torque) pairs. + + .. figure:: ../../_static/actuator-group/dc_motor_clipping.jpg + :align: center + :figwidth: 100% + :alt: The effort clipping as a function of joint velocity for a linear DC Motor. + + """ + + cfg: DCMotorCfg + """The configuration for the actuator model.""" + + def __init__(self, cfg: DCMotorCfg, *args, **kwargs): + super().__init__(cfg, *args, **kwargs) + # parse configuration + if self.cfg.saturation_effort is None: + raise ValueError("The saturation_effort must be provided for the DC motor actuator model.") + self._saturation_effort = self.cfg.saturation_effort + # find the velocity on the torque-speed curve that intersects effort_limit in the second and fourth quadrant + self._vel_at_effort_lim = self.velocity_limit * (1 + self.effort_limit / self._saturation_effort) + # prepare joint vel buffer for max effort computation + self._joint_vel = torch.zeros_like(self.computed_effort) + # create buffer for zeros effort + self._zeros_effort = torch.zeros_like(self.computed_effort) + # check that quantities are provided + if self.cfg.velocity_limit is None: + raise ValueError("The velocity limit must be provided for the DC motor actuator model.") + + """ + Operations. + """ + + def compute( + self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor + ) -> ArticulationActions: + # save current joint vel + self._joint_vel[:] = joint_vel + # calculate the desired joint torques + return super().compute(control_action, joint_pos, joint_vel) + + """ + Helper functions. + """ + + def _clip_effort(self, effort: torch.Tensor) -> torch.Tensor: + # save current joint vel + self._joint_vel[:] = torch.clip(self._joint_vel, min=-self._vel_at_effort_lim, max=self._vel_at_effort_lim) + # compute torque limits + torque_speed_top = self._saturation_effort * (1.0 - self._joint_vel / self.velocity_limit) + torque_speed_bottom = self._saturation_effort * (-1.0 - self._joint_vel / self.velocity_limit) + # -- max limit + max_effort = torch.clip(torque_speed_top, max=self.effort_limit) + # -- min limit + min_effort = torch.clip(torque_speed_bottom, min=-self.effort_limit) + # clip the torques based on the motor limits + clamped = torch.clip(effort, min=min_effort, max=max_effort) + return clamped + + +class DelayedPDActuator(IdealPDActuator): + """Ideal PD actuator with delayed command application. + + This class extends the :class:`IdealPDActuator` class by adding a delay to the actuator commands. The delay + is implemented using a circular buffer that stores the actuator commands for a certain number of physics steps. + The most recent actuation value is pushed to the buffer at every physics step, but the final actuation value + applied to the simulation is lagged by a certain number of physics steps. + + The amount of time lag is configurable and can be set to a random value between the minimum and maximum time + lag bounds at every reset. The minimum and maximum time lag values are set in the configuration instance passed + to the class. + """ + + cfg: DelayedPDActuatorCfg + """The configuration for the actuator model.""" + + def __init__(self, cfg: DelayedPDActuatorCfg, *args, **kwargs): + super().__init__(cfg, *args, **kwargs) + # instantiate the delay buffers + self.positions_delay_buffer = DelayBuffer(cfg.max_delay, self._num_envs, device=self._device) + self.velocities_delay_buffer = DelayBuffer(cfg.max_delay, self._num_envs, device=self._device) + self.efforts_delay_buffer = DelayBuffer(cfg.max_delay, self._num_envs, device=self._device) + # all of the envs + self._ALL_INDICES = torch.arange(self._num_envs, dtype=torch.long, device=self._device) + + def reset(self, env_ids: Sequence[int]): + super().reset(env_ids) + # number of environments (since env_ids can be a slice) + if env_ids is None or env_ids == slice(None): + num_envs = self._num_envs + else: + num_envs = len(env_ids) + # set a new random delay for environments in env_ids + time_lags = torch.randint( + low=self.cfg.min_delay, + high=self.cfg.max_delay + 1, + size=(num_envs,), + dtype=torch.int, + device=self._device, + ) + # set delays + self.positions_delay_buffer.set_time_lag(time_lags, env_ids) + self.velocities_delay_buffer.set_time_lag(time_lags, env_ids) + self.efforts_delay_buffer.set_time_lag(time_lags, env_ids) + # reset buffers + self.positions_delay_buffer.reset(env_ids) + self.velocities_delay_buffer.reset(env_ids) + self.efforts_delay_buffer.reset(env_ids) + + def compute( + self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor + ) -> ArticulationActions: + # apply delay based on the delay the model for all the setpoints + control_action.joint_positions = self.positions_delay_buffer.compute(control_action.joint_positions) + control_action.joint_velocities = self.velocities_delay_buffer.compute(control_action.joint_velocities) + control_action.joint_efforts = self.efforts_delay_buffer.compute(control_action.joint_efforts) + # compte actuator model + return super().compute(control_action, joint_pos, joint_vel) + + +class RemotizedPDActuator(DelayedPDActuator): + """Ideal PD actuator with angle-dependent torque limits. + + This class extends the :class:`DelayedPDActuator` class by adding angle-dependent torque limits to the actuator. + The torque limits are applied by querying a lookup table describing the relationship between the joint angle + and the maximum output torque. The lookup table is provided in the configuration instance passed to the class. + + The torque limits are interpolated based on the current joint positions and applied to the actuator commands. + """ + + def __init__( + self, + cfg: RemotizedPDActuatorCfg, + joint_names: list[str], + joint_ids: Sequence[int], + num_envs: int, + device: str, + stiffness: torch.Tensor | float = 0.0, + damping: torch.Tensor | float = 0.0, + armature: torch.Tensor | float = 0.0, + friction: torch.Tensor | float = 0.0, + dynamic_friction: torch.Tensor | float = 0.0, + viscous_friction: torch.Tensor | float = 0.0, + effort_limit: torch.Tensor | float = torch.inf, + velocity_limit: torch.Tensor | float = torch.inf, + ): + # remove effort and velocity box constraints from the base class + cfg.effort_limit = torch.inf + cfg.velocity_limit = torch.inf + # call the base method and set default effort_limit and velocity_limit to inf + super().__init__( + cfg, + joint_names, + joint_ids, + num_envs, + device, + stiffness, + damping, + armature, + friction, + dynamic_friction, + viscous_friction, + effort_limit, + velocity_limit, + ) + self._joint_parameter_lookup = torch.tensor(cfg.joint_parameter_lookup, device=device) + # define remotized joint torque limit + self._torque_limit = LinearInterpolation(self.angle_samples, self.max_torque_samples, device=device) + + """ + Properties. + """ + + @property + def angle_samples(self) -> torch.Tensor: + return self._joint_parameter_lookup[:, 0] + + @property + def transmission_ratio_samples(self) -> torch.Tensor: + return self._joint_parameter_lookup[:, 1] + + @property + def max_torque_samples(self) -> torch.Tensor: + return self._joint_parameter_lookup[:, 2] + + """ + Operations. + """ + + def compute( + self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor + ) -> ArticulationActions: + # call the base method + control_action = super().compute(control_action, joint_pos, joint_vel) + # compute the absolute torque limits for the current joint positions + abs_torque_limits = self._torque_limit.compute(joint_pos) + # apply the limits + control_action.joint_efforts = torch.clamp( + control_action.joint_efforts, min=-abs_torque_limits, max=abs_torque_limits + ) + self.applied_effort = control_action.joint_efforts + return control_action diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_pd_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_pd_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..c4cad3e69f41cea627fe8650de9e86628a334841 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_pd_cfg.py @@ -0,0 +1,84 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from dataclasses import MISSING +from typing import TYPE_CHECKING + +from isaaclab.utils.configclass import configclass + +from .actuator_base_cfg import ActuatorBaseCfg + +if TYPE_CHECKING: + from .actuator_pd import DCMotor, DelayedPDActuator, IdealPDActuator, ImplicitActuator, RemotizedPDActuator + +""" +Implicit Actuator Models. +""" + + +@configclass +class ImplicitActuatorCfg(ActuatorBaseCfg): + """Configuration for an implicit actuator. + + Note: + The PD control is handled implicitly by the simulation. + """ + + class_type: type["ImplicitActuator"] | str = "{DIR}.actuator_pd:ImplicitActuator" + + +""" +Explicit Actuator Models. +""" + + +@configclass +class IdealPDActuatorCfg(ActuatorBaseCfg): + """Configuration for an ideal PD actuator.""" + + class_type: type["IdealPDActuator"] | str = "{DIR}.actuator_pd:IdealPDActuator" + + +@configclass +class DCMotorCfg(IdealPDActuatorCfg): + """Configuration for direct control (DC) motor actuator model.""" + + class_type: type["DCMotor"] | str = "{DIR}.actuator_pd:DCMotor" + + saturation_effort: float = MISSING + """Peak motor force/torque of the electric DC motor (in N-m).""" + + +@configclass +class DelayedPDActuatorCfg(IdealPDActuatorCfg): + """Configuration for a delayed PD actuator.""" + + class_type: type["DelayedPDActuator"] | str = "{DIR}.actuator_pd:DelayedPDActuator" + + min_delay: int = 0 + """Minimum number of physics time-steps with which the actuator command may be delayed. Defaults to 0.""" + + max_delay: int = 0 + """Maximum number of physics time-steps with which the actuator command may be delayed. Defaults to 0.""" + + +@configclass +class RemotizedPDActuatorCfg(DelayedPDActuatorCfg): + """Configuration for a remotized PD actuator. + + Note: + The torque output limits for this actuator is derived from a linear interpolation of a lookup table + in :attr:`joint_parameter_lookup`. This table describes the relationship between joint angles and + the output torques. + """ + + class_type: type["RemotizedPDActuator"] | str = "{DIR}.actuator_pd:RemotizedPDActuator" + + joint_parameter_lookup: list[list[float]] = MISSING + """Joint parameter lookup table. Shape is (num_lookup_points, 3). + + This tensor describes the relationship between the joint angle (rad), the transmission ratio (in/out), + and the output torque (N*m). The table is used to interpolate the output torque based on the joint angle. + """ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e630c2e21f9787c9432bc47008000cf4b287c5bc --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__init__.py @@ -0,0 +1,17 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-package containing app-specific functionalities. + +These include: + +* Ability to launch the simulation app with different configurations +* Run tests with the simulation app + +""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d4387a37b8b87bb5d59a56e00a19d7335d8b279b --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__init__.pyi @@ -0,0 +1,14 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "AppLauncher", + "SettingsManager", + "get_settings_manager", + "initialize_carb_settings", +] + +from .app_launcher import AppLauncher +from .settings_manager import SettingsManager, get_settings_manager, initialize_carb_settings diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__pycache__/__init__.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..081940865034c5fb991ebdf5d2c609ce896fd3c6 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__pycache__/app_launcher.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__pycache__/app_launcher.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bd2f4b3340d920360701fc7d02ea29278389312 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__pycache__/app_launcher.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__pycache__/settings_manager.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__pycache__/settings_manager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ced9f3ca4da2d929740abcea64ba1be5b4cf0a38 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/__pycache__/settings_manager.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/app_launcher.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/app_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..2d5192dd074919390e4f65667fb1ea2cccf45df4 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/app_launcher.py @@ -0,0 +1,1393 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-package with the utility class to configure the :class:`isaacsim.simulation_app.SimulationApp`. + +The :class:`AppLauncher` parses environment variables and input CLI arguments to launch the simulator in +various different modes. This includes with or without GUI and switching between different Omniverse remote +clients. Some of these require the extensions to be loaded in a specific order, otherwise a segmentation +fault occurs. The launched :class:`isaacsim.simulation_app.SimulationApp` instance is accessible via the +:attr:`AppLauncher.app` property. +""" + +from __future__ import annotations + +import argparse +import atexit +import contextlib +import logging +import os +import re +import signal +import sys +from typing import Any, Literal + +with contextlib.suppress(ModuleNotFoundError): + import isaacsim # noqa: F401 + from isaacsim import SimulationApp + +from isaaclab.app.settings_manager import get_settings_manager, initialize_carb_settings + +# import logger +logger = logging.getLogger(__name__) + +# Suppress noisy debug-level logs from third-party libraries +logging.getLogger("websockets").setLevel(logging.WARNING) +logging.getLogger("matplotlib").setLevel(logging.WARNING) +logging.getLogger("h5py").setLevel(logging.WARNING) + + +class ExplicitAction(argparse.Action): + """Custom action to track if an argument was explicitly passed by the user.""" + + def __call__(self, parser, namespace, values, option_string=None): + # Set the parameter value + setattr(namespace, self.dest, values) + # Set a flag indicating the parameter was explicitly passed + setattr(namespace, f"{self.dest}_explicit", True) + + +class ExplicitTrueAction(argparse.Action): + """Custom action to track explicit use of boolean flags.""" + + def __init__(self, option_strings, dest, default=False, required=False, help=None): + super().__init__( + option_strings=option_strings, dest=dest, nargs=0, default=default, required=required, help=help + ) + + def __call__(self, parser, namespace, values, option_string=None): + setattr(namespace, self.dest, True) + setattr(namespace, f"{self.dest}_explicit", True) + + +class AppLauncher: + """A utility class to launch Isaac Sim application based on command-line arguments and environment variables. + + The class resolves the simulation app settings that appear through environments variables, + command-line arguments (CLI) or as input keyword arguments. Based on these settings, it launches the + simulation app and configures the extensions to load (as a part of post-launch setup). + + The input arguments provided to the class are given higher priority than the values set + from the corresponding environment variables. This provides flexibility to deal with different + users' preferences. + + .. note:: + Explicitly defined arguments are only given priority when their value is set to something outside + their default configuration. For example, the ``livestream`` argument is -1 by default. It only + overrides the ``LIVESTREAM`` environment variable when ``livestream`` argument is set to a + value >-1. In other words, if ``livestream=-1``, then the value from the environment variable + ``LIVESTREAM`` is used. + + """ + + @staticmethod + def sync_visualizer_cli_settings_to_carb(launcher_args: dict) -> None: + """Write visualizer CLI selection and ``--max_visible_envs`` to carb settings. + + Callers may set ``visualizer_explicit`` / ``visualizer_disable_all`` when those values + were resolved elsewhere (e.g. :class:`AppLauncher` strips flags from *launcher_args*). + Otherwise ``disable_all`` is inferred from ``"none"`` in ``visualizer``. + + Also used when Kit is skipped (see :mod:`isaaclab_tasks.utils.sim_launcher`). + """ + visualizers = launcher_args.get("visualizer") + + if "max_visible_envs" in launcher_args: + v = launcher_args["max_visible_envs"] + if v is not None and int(v) < 0: + raise ValueError(f"Invalid value for --max_visible_envs: {v}. Expected non-negative int.") + + cli_explicit = bool(launcher_args.get("visualizer_explicit", False)) + if "visualizer_disable_all" in launcher_args: + cli_disable_all = bool(launcher_args["visualizer_disable_all"]) + else: + cli_disable_all = bool(cli_explicit) and visualizers is not None and "none" in visualizers + + with contextlib.suppress(Exception): + visualizer_str = " ".join(visualizers) if visualizers else "" + settings = get_settings_manager() + settings.set_string("/isaaclab/visualizer/types", visualizer_str) + settings.set_bool("/isaaclab/visualizer/explicit", cli_explicit) + settings.set_bool("/isaaclab/visualizer/disable_all", cli_disable_all) + + # Sentinel: ``-1`` means ``--max_visible_envs`` was not passed (see ``SimulationContext``). + if "max_visible_envs" in launcher_args: + settings.set_int("/isaaclab/visualizer/max_visible_envs", int(launcher_args["max_visible_envs"])) + else: + settings.set_int("/isaaclab/visualizer/max_visible_envs", -1) + + @staticmethod + def apply_rtx_determinism_settings() -> None: + """Apply RTX RealTimePathTracing and disable RTPT caches for reproducible RTX rendering. + Called after :class:`isaacsim.simulation_app.SimulationApp` starts whenever ``--deterministic`` is set. + """ + settings = get_settings_manager() + settings.set_string("/rtx/rendermode", "RealTimePathTracing") + settings.set_bool("/rtx/rtpt/cached/enabled", False) + settings.set_bool("/rtx/rtpt/lightcache/cached/enabled", False) + + @staticmethod + def _parse_visualizer_csv(value: str) -> list[str] | None: + """Parse visualizer list from a single comma-delimited CLI token.""" + valid = {"kit", "newton", "rerun", "viser", "none"} + token = (value or "").strip() + if not token: + raise argparse.ArgumentTypeError( + "Invalid --visualizer value: empty string. Use a comma-separated list, e.g. --viz kit,newton." + ) + if " " in token: + raise argparse.ArgumentTypeError( + "Invalid --visualizer value: spaces are not allowed. " + "Use a comma-separated list without spaces, e.g. --viz kit,newton,rerun,viser." + ) + + names = [item.strip().lower() for item in token.split(",")] + if any(not name for name in names): + raise argparse.ArgumentTypeError( + "Invalid --visualizer value: empty visualizer entry detected. " + "Use a comma-separated list without empty items." + ) + invalid = [name for name in names if name not in valid] + if invalid: + raise argparse.ArgumentTypeError( + f"Invalid --visualizer value(s): {', '.join(invalid)}. Valid options: {', '.join(sorted(valid))}." + ) + if "none" in names: + if len(names) > 1: + raise argparse.ArgumentTypeError( + "Invalid --visualizer value: 'none' cannot be combined with other visualizer types." + ) + return None + # De-duplicate while preserving order. + return list(dict.fromkeys(names)) + + @staticmethod + def _normalize_visualizer_intent(intent: Any) -> tuple[bool, bool]: + """Normalize and validate upstream config visualizer intent payload. + + The expected schema is: + ``{"has_any_visualizers": bool, "has_kit_visualizer": bool}``. + """ + if intent is None: + return False, False + if not isinstance(intent, dict): + raise ValueError("Invalid value for `visualizer_intent`: expected dict or None.") + + has_any = intent.get("has_any_visualizers", False) + has_kit = intent.get("has_kit_visualizer", False) + if not isinstance(has_any, bool) or not isinstance(has_kit, bool): + raise ValueError( + "Invalid `visualizer_intent` values: expected booleans for `has_any_visualizers` and " + "`has_kit_visualizer`." + ) + if has_kit and not has_any: + raise ValueError( + "Invalid `visualizer_intent`: `has_kit_visualizer=True` requires `has_any_visualizers=True`." + ) + return has_any, has_kit + + @staticmethod + def _resolve_python_logging_level(launcher_args: dict) -> int: + """Resolve the Python logging level that should survive Kit startup.""" + if launcher_args.get("verbose", False) or "--verbose" in sys.argv: + return logging.DEBUG + if launcher_args.get("info", False) or "--info" in sys.argv: + return logging.INFO + + level = logging.getLogger().getEffectiveLevel() + return logging.WARNING if level == logging.NOTSET else level + + @staticmethod + def _apply_python_logging_level(level: int) -> None: + """Apply a Python logging level to the root logger and its handlers.""" + root_logger = logging.getLogger() + root_logger.setLevel(level) + for handler in root_logger.handlers: + handler.setLevel(level) + + @staticmethod + def _ensure_isaaclab_info_stream_handler() -> None: + """Add a stream handler for Isaac Lab INFO records hidden by Kit logging.""" + handler_name = "isaaclab_info_stream" + root_logger = logging.getLogger() + if any(getattr(handler, "name", None) == handler_name for handler in root_logger.handlers): + return + + class _IsaacLabInfoFilter(logging.Filter): + def filter(self, record: logging.LogRecord) -> bool: + return record.levelno == logging.INFO and record.name.startswith("isaaclab") + + handler = logging.StreamHandler(sys.stdout) + handler.name = handler_name + handler.setLevel(logging.INFO) + handler.addFilter(_IsaacLabInfoFilter()) + handler.setFormatter(logging.Formatter("[INFO]: %(message)s")) + root_logger.addHandler(handler) + + def __init__(self, launcher_args: argparse.Namespace | dict | None = None, **kwargs): + """Create a `SimulationApp`_ instance based on the input settings. + + Args: + launcher_args: Input arguments to parse using the AppLauncher and set into the SimulationApp. + Defaults to None, which is equivalent to passing an empty dictionary. A detailed description of + the possible arguments is available in the `SimulationApp`_ documentation. + **kwargs : Additional keyword arguments that will be merged into :attr:`launcher_args`. + They serve as a convenience for those who want to pass some arguments using the argparse + interface and others directly into the AppLauncher. Duplicated arguments with + the :attr:`launcher_args` will raise a ValueError. + + Raises: + ValueError: If there are common/duplicated arguments between ``launcher_args`` and ``kwargs``. + ValueError: If combination of ``launcher_args`` and ``kwargs`` are missing the necessary arguments + that are needed by the AppLauncher to resolve the desired app configuration. + ValueError: If incompatible or undefined values are assigned to relevant environment values, + such as ``LIVESTREAM``. + + .. _argparse.Namespace: https://docs.python.org/3/library/argparse.html?highlight=namespace#argparse.Namespace + .. _SimulationApp: https://docs.isaacsim.omniverse.nvidia.com/latest/py/source/extensions/isaacsim.simulation_app/docs/index.html#isaacsim.simulation_app.SimulationApp + """ + # We allow users to pass either a dict or an argparse.Namespace into + # __init__, anticipating that these will be all of the argparse arguments + # used by the calling script. Those which we appended via add_app_launcher_args + # will be used to control extension loading logic. Additional arguments are allowed, + # and will be passed directly to the SimulationApp initialization. + # + # We could potentially require users to enter each argument they want passed here + # as a kwarg, but this would require them to pass livestream, headless, and + # any other options we choose to add here explicitly, and with the correct keywords. + # + # @hunter: I feel that this is cumbersome and could introduce error, and would prefer to do + # some sanity checking in the add_app_launcher_args function + if launcher_args is None: + launcher_args = {} + elif isinstance(launcher_args, argparse.Namespace): + launcher_args = launcher_args.__dict__ + + # Check that arguments are unique + if len(kwargs) > 0: + if not set(kwargs.keys()).isdisjoint(launcher_args.keys()): + overlapping_args = set(kwargs.keys()).intersection(launcher_args.keys()) + raise ValueError( + f"Input `launcher_args` and `kwargs` both provided common attributes: {overlapping_args}." + " Please ensure that each argument is supplied to only one of them, as the AppLauncher cannot" + " discern priority between them." + ) + launcher_args.update(kwargs) + + # Preserve the Python logging intent before Kit installs its own logging bridge. + self._python_logging_level = AppLauncher._resolve_python_logging_level(launcher_args) + + # Define config members that are read from env-vars or keyword args + self._headless: bool # 0: GUI, 1: Headless + self._livestream: Literal[0, 1, 2] # 0: Disabled, 1: WebRTC public, 2: WebRTC private + self._offscreen_render: bool # 0: Disabled, 1: Enabled + self._sim_experience_file: str # Experience file to load + self._video_enabled: bool # Whether --video recording is enabled + + # Exposed to train scripts + self.device_id: int # device ID for GPU simulation (defaults to 0) + self.device: str # resolved device string (e.g. "cuda:0" or "cpu") + self._deferred_cuda_device_id: int | None = None + self.local_rank: int # local rank of GPUs in the current node + self.global_rank: int # global rank for multi-node training + + # Integrate env-vars and input keyword args into simulation app config + self._config_resolution(launcher_args) + + # Create SimulationApp, passing the resolved self._config to it for initialization + self._create_app() + self._set_deferred_cuda_device() + # Load IsaacSim extensions + self._load_extensions() + + # Re-run path sanitization. Kit and its extensions may have inserted + # additional ``pip_prebundle`` or conflicting extension directories onto + # ``sys.path`` during startup. A second pass ensures pip-installed + # packages still take priority over bundled copies. + from isaaclab import _deprioritize_prebundle_paths + + _deprioritize_prebundle_paths() + + # Hide the stop button in the toolbar + self._hide_stop_button() + # Set settings from the given rendering mode + self._set_rendering_mode_settings(launcher_args) + # Set animation recording settings + self._set_animation_recording_settings(launcher_args) + # Set visualizer settings (if requested) + self._set_visualizer_settings(launcher_args) + + # Hide play button callback if the timeline is stopped + import omni.timeline + + self._hide_play_button_callback = ( + omni.timeline.get_timeline_interface() + .get_timeline_event_stream() + .create_subscription_to_pop_by_type( + int(omni.timeline.TimelineEventType.STOP), lambda e: self._hide_play_button(True) + ) + ) + self._unhide_play_button_callback = ( + omni.timeline.get_timeline_interface() + .get_timeline_event_stream() + .create_subscription_to_pop_by_type( + int(omni.timeline.TimelineEventType.PLAY), lambda e: self._hide_play_button(False) + ) + ) + # Signal to the CI test runner that Kit initialization is complete. + # stdout may be redirected to /dev/null during _create_app(), so we + # use __stderr__ which is never suppressed. + print("[ISAACLAB] AppLauncher initialization complete", file=sys.__stderr__, flush=True) + + # Ensure SimulationApp.close() is called on normal process exit so Kit + # shuts down cleanly instead of relying on __del__ (which logs a warning + # and can leave GPU resources in a bad state for the next test). + def _atexit_close(app=self._app): + with contextlib.suppress(Exception): + app.close() + + atexit.register(_atexit_close) + + # Set up signal handlers for graceful shutdown + # -- during explicit `kill` commands + signal.signal(signal.SIGTERM, self._abort_signal_handle_callback) + # -- during aborts + signal.signal(signal.SIGABRT, self._abort_signal_handle_callback) + # -- during segfaults + signal.signal(signal.SIGSEGV, self._abort_signal_handle_callback) + + """ + Properties. + """ + + @property + def app(self) -> SimulationApp: + """The launched SimulationApp.""" + if self._app is not None: + return self._app + else: + raise RuntimeError("The `AppLauncher.app` member cannot be retrieved until the class is initialized.") + + """ + Operations. + """ + + @staticmethod + def add_app_launcher_args(parser: argparse.ArgumentParser) -> None: + """Utility function to configure AppLauncher arguments with an existing argument parser object. + + This function takes an ``argparse.ArgumentParser`` object and does some sanity checking on the existing + arguments for ingestion by the SimulationApp. It then appends custom command-line arguments relevant + to the SimulationApp to the input :class:`argparse.ArgumentParser` instance. This allows overriding the + environment variables using command-line arguments. + + Currently, it adds the following parameters to the argparser object: + + * ``headless`` (bool): [Deprecated CLI] If True, visualizers are disabled and host execution is headless. + To run headless by default, omit ``--viz``. To force headless when config visualizers may be enabled, + use ``--viz none``. + * ``livestream`` (int): If one of {1, 2}, then livestreaming and headless mode is enabled. The values + map the same as that for the ``LIVESTREAM`` environment variable. If :obj:`-1`, then livestreaming is + determined by the ``LIVESTREAM`` environment variable. + Valid options are: + + - ``0``: Disabled + - ``1``: `WebRTC`_ over public network + - ``2``: `WebRTC`_ over local/private network + + * ``enable_cameras`` (bool): If True, the app will enable camera sensors and render them, even when in + headless mode. This flag must be set to True if the environments contains any camera sensors. + The values map the same as that for the ``ENABLE_CAMERAS`` environment variable. + If False, then enable_cameras mode is determined by the ``ENABLE_CAMERAS`` environment variable. + * ``device`` (str): The device to run the simulation on. + Valid options are: + + - ``cpu``: Use CPU. + - ``cuda``: Use GPU with device ID ``0``. + - ``cuda:N``: Use GPU, where N is the device ID. For example, "cuda:0". + + * ``experience`` (str): The experience file to load when launching the SimulationApp. If a relative path + is provided, it is resolved relative to the ``apps`` folder in Isaac Sim and Isaac Lab (in that order). + + If provided as an empty string, the experience file is determined based on the command-line flags: + + * If headless and enable_cameras are True, the experience file is set to + ``isaaclab.python.headless.rendering.kit``. + * If headless is False and enable_cameras is True, the experience file is set to + ``isaaclab.python.rendering.kit``. + * If headless and enable_cameras are False, the experience file is set to + ``isaaclab.python.kit``. + * If headless is True and enable_cameras is False, the experience file is set to + ``isaaclab.python.headless.kit``. + + * ``deterministic`` (bool): After startup, applies RTX/RTPT carb settings for reproducible rendering. + Does not change how the default experience file is chosen. + + * ``kit_args`` (str): Optional command line arguments to be passed to Omniverse Kit directly. + Arguments should be combined into a single string separated by space. + Example usage: --kit_args "--ext-folder=/path/to/ext1 --ext-folder=/path/to/ext2" + + * ``visualizer`` (str): Visualizer backends to enable. + Valid options are: + + - ``rerun``: Use Rerun visualizer. + - ``newton``: Use Newton visualizer. + - ``viser``: Use Viser visualizer. + - ``kit``: Use Omniverse Kit visualizer. + - ``none``: Disable all visualizers explicitly. + - Multiple visualizers can be specified as a comma-delimited list: + ``--viz rerun,newton,viser``. + + * ``max_visible_envs`` (int | None): Optional global override for partial visualization by capping + how many environments are shown in the visualizers. + More partial visualization configuration fields are available in the ``VisualizerCfg`` class. + + .. _`WebRTC`: https://docs.isaacsim.omniverse.nvidia.com/latest/installation/manual_livestream_clients.html#isaac-sim-short-webrtc-streaming-client + + Args: + parser: An argument parser instance to be extended with the AppLauncher specific options. + """ + # If the passed parser has an existing _HelpAction when passed, + # we here remove the options which would invoke it, + # to be added back after the additional AppLauncher args + # have been added. This is equivalent to + # initially constructing the ArgParser with add_help=False, + # but this means we don't have to require that behavior + # in users and can handle it on our end. + # We do this because calling parse_known_args() will handle + # any -h/--help options being passed and then exit immediately, + # before the additional arguments can be added to the help readout. + parser_help = None + if len(parser._actions) > 0 and isinstance(parser._actions[0], argparse._HelpAction): # type: ignore + parser_help = parser._actions[0] + parser._option_string_actions.pop("-h") + parser._option_string_actions.pop("--help") + + # Parse known args for potential name collisions/type mismatches + # between the config fields SimulationApp expects and the ArgParse + # arguments that the user passed. + known, _ = parser.parse_known_args() + config = vars(known) + if len(config) == 0: + logger.warning( + "[WARN][AppLauncher]: There are no arguments attached to the ArgumentParser object." + " If you have your own arguments, please load your own arguments before calling the" + " `AppLauncher.add_app_launcher_args` method. This allows the method to check the validity" + " of the arguments and perform checks for argument names." + ) + else: + AppLauncher._check_argparser_config_params(config) + + # Add custom arguments to the parser + arg_group = parser.add_argument_group( + "app_launcher arguments", + description="Arguments for the AppLauncher. For more details, please check the documentation.", + ) + arg_group.add_argument( + "--headless", + action=ExplicitTrueAction, + default=AppLauncher._APPLAUNCHER_CFG_INFO["headless"][1], + help=( + "[DEPRECATED] Disable visualizers and force headless mode (display off)." + " Omit '--viz' for default headless, or use '--viz none' to force-disable visualizers." + ), + ) + arg_group.add_argument( + "--livestream", + type=int, + default=AppLauncher._APPLAUNCHER_CFG_INFO["livestream"][1], + choices={0, 1, 2}, + help="Force enable livestreaming. Mapping corresponds to that for the `LIVESTREAM` environment variable.", + ) + arg_group.add_argument( + "--enable_cameras", + action="store_true", + default=AppLauncher._APPLAUNCHER_CFG_INFO["enable_cameras"][1], + help="Enable camera sensors and relevant extension dependencies.", + ) + arg_group.add_argument( + "--xr", + action="store_true", + default=AppLauncher._APPLAUNCHER_CFG_INFO["xr"][1], + help="Enable XR mode for VR/AR applications.", + ) + arg_group.add_argument( + "--device", + type=str, + action=ExplicitAction, + default=AppLauncher._APPLAUNCHER_CFG_INFO["device"][1], + help='The device to run the simulation on. Can be "cpu", "cuda", "cuda:N", where N is the device ID', + ) + arg_group.add_argument( + "--visualizer", + "--viz", + type=AppLauncher._parse_visualizer_csv, + action=ExplicitAction, + default=None, + help="Visualizer backends to enable as CSV (e.g., kit,newton,rerun,viser).", + ) + # Add the deprecated cpu flag to raise an error if it is used + arg_group.add_argument("--cpu", action="store_true", help=argparse.SUPPRESS) + arg_group.add_argument( + "--verbose", # Note: This is read by SimulationApp through sys.argv + action="store_true", + help="Enable verbose-level log output from the SimulationApp.", + ) + arg_group.add_argument( + "--info", # Note: This is read by SimulationApp through sys.argv + action="store_true", + help="Enable info-level log output from the SimulationApp.", + ) + arg_group.add_argument( + "--experience", + type=str, + default="", + help=( + "The experience file to load when launching the SimulationApp. If an empty string is provided," + " the experience file is determined based on the headless flag. If a relative path is provided," + " it is resolved relative to the `apps` folder in Isaac Sim and Isaac Lab (in that order)." + ), + ) + arg_group.add_argument( + "--deterministic", + action="store_true", + default=AppLauncher._APPLAUNCHER_CFG_INFO["deterministic"][1], + help="After startup, apply RTX/RTPT settings for reproducible rendering (see AppLauncher docs).", + ) + arg_group.add_argument( + "--rendering_mode", + type=str, + action=ExplicitAction, + choices={"performance", "balanced", "quality"}, + help=( + "Sets the rendering mode. Preset settings files can be found in apps/rendering_modes." + ' Can be "performance", "balanced", or "quality".' + " Individual settings can be overwritten by using the RenderCfg class." + ), + ) + arg_group.add_argument( + "--kit_args", + type=str, + default="", + help=( + "Command line arguments for Omniverse Kit as a string separated by a space delimiter." + ' Example usage: --kit_args "--ext-folder=/path/to/ext1 --ext-folder=/path/to/ext2"' + ), + ) + arg_group.add_argument( + "--anim_recording_enabled", + action="store_true", + help="Enable recording time-sampled USD animations from IsaacLab PhysX simulations.", + ) + arg_group.add_argument( + "--anim_recording_start_time", + type=float, + default=0, + help=( + "Set time that animation recording begins playing. If not set, the recording will start from the" + " beginning." + ), + ) + arg_group.add_argument( + "--anim_recording_stop_time", + type=float, + default=10, + help=( + "Set time that animation recording stops playing. If the process is shutdown before the stop time is" + " exceeded, then the animation is not recorded." + ), + ) + arg_group.add_argument( + "--max_visible_envs", + type=int, + default=argparse.SUPPRESS, + help=("When set, caps the nums of envs shown in the launched visualizers."), + ) + # special flag for backwards compatibility + + # Corresponding to the beginning of the function, + # if we have removed -h/--help handling, we add it back. + if parser_help is not None: + parser._option_string_actions["-h"] = parser_help + parser._option_string_actions["--help"] = parser_help + + """ + Internal functions. + """ + + _APPLAUNCHER_CFG_INFO: dict[str, tuple[list[type], Any]] = { + "headless": ([bool], False), + "livestream": ([int], -1), + "enable_cameras": ([bool], False), + "xr": ([bool], False), + "device": ([str], "cuda:0"), + "experience": ([str], ""), + "deterministic": ([bool], False), + "rendering_mode": ([str], "balanced"), + "max_visible_envs": ([int, type(None)], None), + } + """A dictionary of arguments added manually by the :meth:`AppLauncher.add_app_launcher_args` method. + + The values are a tuple of the expected type and default value. This is used to check against name collisions + for arguments passed to the :class:`AppLauncher` class as well as for type checking. + + They have corresponding environment variables as detailed in the documentation. + """ + + # TODO: Find some internally managed NVIDIA list of these types. + # SimulationApp.DEFAULT_LAUNCHER_CONFIG almost works, except that + # it is ambiguous where the default types are None + _SIM_APP_CFG_TYPES: dict[str, list[type]] = { + "headless": [bool], + "hide_ui": [bool, type(None)], + "active_gpu": [int, type(None)], + "physics_gpu": [int], + "multi_gpu": [bool], + "sync_loads": [bool], + "width": [int], + "height": [int], + "window_width": [int], + "window_height": [int], + "display_options": [int], + "subdiv_refinement_level": [int], + "renderer": [str], + "anti_aliasing": [int], + "samples_per_pixel_per_frame": [int], + "denoiser": [bool], + "max_bounces": [int], + "max_specular_transmission_bounces": [int], + "max_volume_bounces": [int], + "open_usd": [str, type(None)], + "livesync_usd": [str, type(None)], + "fast_shutdown": [bool], + "experience": [str], + } + """A dictionary containing the type of arguments passed to SimulationApp. + + This is used to check against name collisions for arguments passed to the :class:`AppLauncher` class + as well as for type checking. It corresponds closely to the :attr:`SimulationApp.DEFAULT_LAUNCHER_CONFIG`, + but specifically denotes where None types are allowed. + """ + + @staticmethod + def _check_argparser_config_params(config: dict) -> None: + """Checks that input argparser object has parameters with valid settings with no name conflicts. + + First, we inspect the dictionary to ensure that the passed ArgParser object is not attempting to add arguments + which should be assigned by calling :meth:`AppLauncher.add_app_launcher_args`. + + Then, we check that if the key corresponds to a config setting expected by SimulationApp, then the type of + that key's value corresponds to the type expected by the SimulationApp. If it passes the check, the function + prints out that the setting with be passed to the SimulationApp. Otherwise, we raise a ValueError exception. + + Args: + config: A configuration parameters which will be passed to the SimulationApp constructor. + + Raises: + ValueError: If a key is an already existing field in the configuration parameters but + should be added by calling the :meth:`AppLauncher.add_app_launcher_args. + ValueError: If keys corresponding to those used to initialize SimulationApp + (as found in :attr:`_SIM_APP_CFG_TYPES`) are of the wrong value type. + """ + # check that no config key conflicts with AppLauncher config names + applauncher_keys = set(AppLauncher._APPLAUNCHER_CFG_INFO.keys()) + for key, value in config.items(): + if key in applauncher_keys: + raise ValueError( + f"The passed ArgParser object already has the field '{key}'. This field will be added by" + " `AppLauncher.add_app_launcher_args()`, and should not be added directly. Please remove the" + " argument or rename it to a non-conflicting name." + ) + # check that type of the passed keys are valid + simulationapp_keys = set(AppLauncher._SIM_APP_CFG_TYPES.keys()) + for key, value in config.items(): + if key in simulationapp_keys: + given_type = type(value) + expected_types = AppLauncher._SIM_APP_CFG_TYPES[key] + if type(value) not in set(expected_types): + raise ValueError( + f"Invalid value type for the argument '{key}': {given_type}. Expected one of {expected_types}," + " if intended to be ingested by the SimulationApp object. Please change the type if this" + " intended for the SimulationApp or change the name of the argument to avoid name conflicts." + ) + # Print out values which will be used + logger.info("The argument '%s' will be used to configure the SimulationApp.", key) + + def _config_resolution(self, launcher_args: dict): + """Resolve the input arguments and environment variables. + + Args: + launcher_args: A dictionary of all input arguments passed to the class object. + """ + # Handle core settings + livestream_arg, livestream_env = self._resolve_livestream_settings(launcher_args) + self._resolve_visualizer_settings(launcher_args) + # XR must be resolved before headless so that XR can prevent + # visualizer-intent-based headless forcing. + self._resolve_xr_settings(launcher_args) + self._resolve_headless_settings(launcher_args, livestream_arg, livestream_env) + self._resolve_camera_settings(launcher_args) + self._resolve_viewport_settings(launcher_args) + + # Handle device and distributed settings + self._resolve_device_settings(launcher_args) + + # Handle experience file settings + self._resolve_experience_file(launcher_args) + + # Handle animation recording settings + self._resolve_anim_recording_settings(launcher_args) + + # Handle additional arguments + self._resolve_kit_args(launcher_args) + + # Prepare final simulation app config + # Remove all values from input keyword args which are not meant for SimulationApp + # Assign all the passed settings to a dictionary for the simulation app + self._sim_app_config = { + key: launcher_args[key] for key in set(AppLauncher._SIM_APP_CFG_TYPES.keys()) & set(launcher_args.keys()) + } + + def _resolve_livestream_settings(self, launcher_args: dict) -> tuple[int, int]: + """Resolve livestream related settings.""" + livestream_env = int(os.environ.get("LIVESTREAM", 0)) + livestream_arg = launcher_args.pop("livestream", AppLauncher._APPLAUNCHER_CFG_INFO["livestream"][1]) + livestream_valid_vals = {0, 1, 2} + # Value checking on LIVESTREAM + if livestream_env not in livestream_valid_vals: + raise ValueError( + f"Invalid value for environment variable `LIVESTREAM`: {livestream_env} ." + f" Expected: {livestream_valid_vals}." + ) + # We allow livestream kwarg to supersede LIVESTREAM envvar + if livestream_arg >= 0: + if livestream_arg in livestream_valid_vals: + self._livestream = livestream_arg + # print info that we overrode the env-var + logger.info( + "Input keyword argument `livestream=%s` has overridden the environment variable `LIVESTREAM=%s`.", + livestream_arg, + livestream_env, + ) + else: + raise ValueError( + f"Invalid value for input keyword argument `livestream`: {livestream_arg} ." + f" Expected: {livestream_valid_vals}." + ) + else: + self._livestream = livestream_env + + # Set public IP address of a remote instance + public_ip_env = os.environ.get("PUBLIC_IP", "127.0.0.1") + + # Process livestream here before launching kit because some of the extensions only work + # when launched with the kit file + self._livestream_args = [] + if self._livestream >= 1: + # Note: Only one livestream extension can be enabled at a time + if self._livestream == 1: + # WebRTC public network + self._livestream_args += [ + f"--/exts/omni.kit.livestream.app/primaryStream/publicIp={public_ip_env}", + "--/exts/omni.kit.livestream.app/primaryStream/signalPort=49100", + "--/exts/omni.kit.livestream.app/primaryStream/streamPort=47998", + "--enable", + "omni.kit.livestream.app", + ] + elif self._livestream == 2: + # WebRTC private network + self._livestream_args += [ + "--enable", + "omni.kit.livestream.app", + ] + else: + raise ValueError(f"Invalid value for livestream: {self._livestream}. Expected: 1, 2 .") + sys.argv += self._livestream_args + + return livestream_arg, livestream_env + + def _resolve_headless_settings(self, launcher_args: dict, livestream_arg: int, livestream_env: int): + """Resolve headless related settings.""" + # Resolve headless execution of simulation app + # HEADLESS is initially passed as an int instead of + # the bool of headless_arg to avoid messy string processing, + headless_env = int(os.environ.get("HEADLESS", 0)) + headless_arg = launcher_args.pop("headless", AppLauncher._APPLAUNCHER_CFG_INFO["headless"][1]) + headless_arg_explicit = launcher_args.pop("headless_explicit", False) + headless_valid_vals = {0, 1} + # Value checking on HEADLESS + if headless_env not in headless_valid_vals: + raise ValueError( + f"Invalid value for environment variable `HEADLESS`: {headless_env} . Expected: {headless_valid_vals}." + ) + if headless_arg and headless_arg_explicit: + logger.warning( + "The '--headless' CLI argument is deprecated. Omit '--viz' for default headless. " + "If config visualizers are enabled and you want to force headless, use '--viz none'." + ) + if self._cli_visualizer_explicit: + logger.warning( + "Both '--headless' and '--visualizer/--viz' were provided. " + "Deprecated '--headless' takes precedence and disables all visualizers." + ) + self._cli_visualizer_disable_all = True + self._cli_visualizer_types = [] + # We allow headless kwarg to supersede HEADLESS envvar if headless_arg does not have the default value + # Note: Headless is always true when livestreaming + if headless_arg is True: + self._headless = headless_arg + elif self._livestream in {1, 2}: + # we are always headless on the host machine + self._headless = True + # inform who has toggled the headless flag + if self._livestream == livestream_arg: + logger.info( + "Input keyword argument `livestream=%s` has implicitly overridden the " + "environment variable `HEADLESS=%s` to True.", + self._livestream, + headless_env, + ) + elif self._livestream == livestream_env: + logger.info( + "Environment variable `LIVESTREAM=%s` has implicitly overridden the " + "environment variable `HEADLESS=%s` to True.", + self._livestream, + headless_env, + ) + else: + # Headless needs to be a bool to be ingested by SimulationApp + self._headless = bool(headless_env) + + # Resolve headless from visualizer intent when livestream is disabled. + if self._livestream == 0: + if self._cli_visualizer_explicit: + # Explicit CLI selection controls headless: only Kit implies non-headless. + requested_visualizers = set(self._cli_visualizer_types) + if self._cli_visualizer_disable_all or "kit" not in requested_visualizers: + if not self._headless: + logger.debug( + "Forcing headless mode because visualizer selection " + "excludes 'kit' and livestream is disabled." + ) + self._headless = True + else: + # No CLI visualizer selection: use upstream config intent defaults. + # - no config visualizers => headless + # - config visualizers without kit => headless + # - config includes kit => allow non-headless + if (not self._cfg_has_any_visualizers) or (not self._cfg_has_kit_visualizer): + if not headless_arg_explicit: + logger.info( + "No visualizer was selected, so running in headless mode. " + "To launch a visualizer app, pass '--viz ' " + "(for example '--viz kit')." + ) + if not self._headless: + logger.debug( + "Forcing headless mode because no Kit visualizer was requested via CLI or upstream " + "visualizer config intent." + ) + self._headless = True + # Headless needs to be passed to the SimulationApp so we keep it here + launcher_args["headless"] = self._headless + + def _resolve_visualizer_settings(self, launcher_args: dict) -> None: + """Resolve visualizer CLI semantics and normalize selection.""" + raw_visualizers = launcher_args.get("visualizer") + cfg_has_any, cfg_has_kit = AppLauncher._normalize_visualizer_intent( + launcher_args.pop("visualizer_intent", None) + ) + self._cfg_has_any_visualizers = cfg_has_any + self._cfg_has_kit_visualizer = cfg_has_kit + visualizer_explicit = bool(launcher_args.pop("visualizer_explicit", False)) + if not visualizer_explicit and "visualizer" in launcher_args: + visualizer_explicit = raw_visualizers is not None + + visualizer_types: list[str] = [] + if raw_visualizers is not None: + if isinstance(raw_visualizers, str): + parsed_visualizers = AppLauncher._parse_visualizer_csv(raw_visualizers) + visualizer_types = [] if parsed_visualizers is None else parsed_visualizers + else: + visualizer_types = [str(v).strip().lower() for v in raw_visualizers if str(v).strip()] + + if visualizer_explicit and "none" in visualizer_types and len(visualizer_types) > 1: + raise ValueError("Invalid '--visualizer' value: 'none' cannot be combined with other visualizer types.") + + valid_visualizer_types = {"kit", "newton", "rerun", "viser", "none"} + # Secondary validation for the list path (kwargs); the string path is already validated by + invalid_visualizers = [v for v in visualizer_types if v not in valid_visualizer_types] + if invalid_visualizers: + raise ValueError( + f"Invalid value(s) for '--visualizer': {invalid_visualizers}. " + "Expected one or more of: ['kit', 'newton', 'rerun', 'viser', 'none']." + ) + + self._cli_visualizer_explicit = visualizer_explicit + self._cli_visualizer_disable_all = visualizer_explicit and ( + raw_visualizers is None or "none" in visualizer_types + ) + self._cli_visualizer_types = [] if self._cli_visualizer_disable_all else visualizer_types + launcher_args["visualizer"] = self._cli_visualizer_types + + def _resolve_camera_settings(self, launcher_args: dict): + """Resolve camera related settings.""" + enable_cameras_env = int(os.environ.get("ENABLE_CAMERAS", 0)) + enable_cameras_arg = launcher_args.get("enable_cameras", AppLauncher._APPLAUNCHER_CFG_INFO["enable_cameras"][1]) + enable_cameras_valid_vals = {0, 1} + if enable_cameras_env not in enable_cameras_valid_vals: + raise ValueError( + f"Invalid value for environment variable `ENABLE_CAMERAS`: {enable_cameras_env} ." + f"Expected: {enable_cameras_valid_vals} ." + ) + # We allow enable_cameras kwarg to supersede ENABLE_CAMERAS envvar + if enable_cameras_arg is True: + self._enable_cameras = enable_cameras_arg + else: + self._enable_cameras = bool(enable_cameras_env) + self._offscreen_render = False + if self._enable_cameras and self._headless: + self._offscreen_render = True + + def _resolve_xr_settings(self, launcher_args: dict): + """Resolve XR related settings.""" + xr_env = int(os.environ.get("XR", 0)) + xr_arg = launcher_args.get("xr", AppLauncher._APPLAUNCHER_CFG_INFO["xr"][1]) + xr_valid_vals = {0, 1} + if xr_env not in xr_valid_vals: + raise ValueError(f"Invalid value for environment variable `XR`: {xr_env} .Expected: {xr_valid_vals} .") + # We allow xr kwarg to supersede XR envvar + if xr_arg is True: + self._xr = xr_arg + else: + self._xr = bool(xr_env) + + # Determine whether XR should auto-inject a KitVisualizer. + # When XR is enabled but no Kit visualizer was explicitly requested via + # CLI, we auto-inject one so that app.update() and forward() are pumped + # each frame -- the XR runtime needs both to receive updated hand/joint + # transforms. + if self._xr: + has_explicit_kit = self._cli_visualizer_explicit and "kit" in set(self._cli_visualizer_types) + self._xr_auto_start = not has_explicit_kit + else: + self._xr_auto_start = False + + def _resolve_viewport_settings(self, launcher_args: dict): + """Resolve viewport related settings.""" + self._video_enabled = bool(launcher_args.get("video", False)) + # Check if we can disable the viewport to improve performance + # This should only happen if we are running headless and do not require livestreaming or video recording + # This is different from offscreen_render because this only affects the default viewport and + # not other render-products in the scene + self._render_viewport = True + if self._headless and not self._livestream and not self._video_enabled: + self._render_viewport = False + + # hide_ui flag + launcher_args["hide_ui"] = False + if self._headless and not self._livestream: + launcher_args["hide_ui"] = True + + # avoid creating new stage at startup by default for performance reasons + launcher_args["create_new_stage"] = False + + def _resolve_device_settings(self, launcher_args: dict): + """Resolve simulation GPU device related settings.""" + self.device_id = 0 + device = launcher_args.get("device", AppLauncher._APPLAUNCHER_CFG_INFO["device"][1]) + + device_explicitly_passed = launcher_args.pop("device_explicit", False) + if self._xr and not device_explicitly_passed: + # If no device is specified, default to the CPU device if we are running in XR + device = "cpu" + + # Overwrite for downstream consumers + launcher_args["device"] = "cpu" + + if "cuda" not in device and "cpu" not in device: + raise ValueError( + f"Invalid value for input keyword argument `device`: {device}." + " Expected: a string with the format 'cuda', 'cuda:', or 'cpu'." + ) + + if "cuda:" in device: + self.device_id = int(device.split(":")[-1]) + + # Raise an error for the deprecated cpu flag + if launcher_args.get("cpu", False): + raise ValueError("The `--cpu` flag is deprecated. Please use `--device cpu` instead.") + + if "distributed" in launcher_args and launcher_args["distributed"]: + # local rank (GPU id) in a current multi-gpu mode + self.local_rank = int(os.getenv("LOCAL_RANK", "0")) + int(os.getenv("JAX_LOCAL_RANK", "0")) + # global rank (GPU id) in multi-gpu multi-node mode + self.global_rank = int(os.getenv("RANK", "0")) + int(os.getenv("JAX_RANK", "0")) + + # When CUDA_VISIBLE_DEVICES restricts each process to a single GPU, + # local_rank may exceed the visible device count. Fall back to cuda:0 + # so the process uses the one GPU it can see. + # We compare local_rank against device_count (not WORLD_SIZE) so that + # multi-node setups work correctly: WORLD_SIZE is global across all + # nodes, but device_count is local. + import torch + + num_visible_gpus = torch.cuda.device_count() + if self.local_rank < num_visible_gpus: + self.device_id = self.local_rank + else: + self.device_id = 0 + + device = "cuda:" + str(self.device_id) + launcher_args["multi_gpu"] = False + # limit CPU threads to minimize thread context switching + # this ensures processes do not take up all available threads and fight for resources + num_cpu_cores = os.cpu_count() + num_threads_per_process = num_cpu_cores // int(os.getenv("WORLD_SIZE", 1)) + # set environment variables to limit CPU threads + os.environ["PXR_WORK_THREAD_LIMIT"] = str(num_threads_per_process) + os.environ["OPENBLAS_NUM_THREADS"] = str(num_threads_per_process) + # pass command line variable to kit + sys.argv.append(f"--/plugins/carb.tasking.plugin/threadCount={num_threads_per_process}") + + # set rendering device. We do not need to set physics_gpu because it will automatically pick the same one + # as the active_gpu device. Setting physics_gpu explicitly may result in a different device to be used. + launcher_args["physics_gpu"] = self.device_id + launcher_args["active_gpu"] = self.device_id + + # Defer importing torch until after SimulationApp starts. Importing + # torch can import NumPy/OpenBLAS, whose at-fork handlers can crash + # Kit's platform-info fork during startup. + if "cuda" in device: + self._deferred_cuda_device_id = self.device_id + + # Store the resolved device string for downstream consumers (e.g. sim_launcher) + self.device = device + + logger.info("Using device: %s", device) + + def _set_deferred_cuda_device(self) -> None: + """Set the current torch CUDA device after Kit startup.""" + if self._deferred_cuda_device_id is None: + return + + import torch + + torch.cuda.set_device(self._deferred_cuda_device_id) + + def _resolve_experience_file(self, launcher_args: dict): + """Resolve experience file related settings.""" + # Check if input keywords contain an 'experience' file setting + # Note: since experience is taken as a separate argument by Simulation App, we store it separately + self._sim_experience_file = launcher_args.pop("experience", "") + deterministic_mode = bool( + launcher_args.get("deterministic", AppLauncher._APPLAUNCHER_CFG_INFO["deterministic"][1]) + ) + + # If nothing is provided resolve the experience file based on the headless flag + kit_app_exp_path = os.environ["EXP_PATH"] + isaaclab_app_exp_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), *[".."] * 4, "apps") + # For Isaac Sim 4.5 compatibility, we use the 4.5 app files in a different folder + # if launcher_args.get("use_isaacsim_45", False): + if self.is_isaac_sim_version_5(): + isaaclab_app_exp_path = os.path.join(isaaclab_app_exp_path, "isaacsim_5") + + if self._sim_experience_file == "": + # check if the headless flag is set + # xr rendering overrides camera rendering settings + if self._enable_cameras and not self._xr: + if self._headless and not self._livestream: + self._sim_experience_file = os.path.join( + isaaclab_app_exp_path, "isaaclab.python.headless.rendering.kit" + ) + else: + self._sim_experience_file = os.path.join(isaaclab_app_exp_path, "isaaclab.python.rendering.kit") + elif self._xr: + if self._headless and not self._livestream: + self._sim_experience_file = os.path.join( + isaaclab_app_exp_path, "isaaclab.python.xr.openxr.headless.kit" + ) + else: + self._sim_experience_file = os.path.join(isaaclab_app_exp_path, "isaaclab.python.xr.openxr.kit") + elif self._headless and not self._livestream: + self._sim_experience_file = os.path.join(isaaclab_app_exp_path, "isaaclab.python.headless.kit") + else: + self._sim_experience_file = os.path.join(isaaclab_app_exp_path, "isaaclab.python.kit") + elif not os.path.isabs(self._sim_experience_file): + option_1_app_exp_path = os.path.join(kit_app_exp_path, self._sim_experience_file) + option_2_app_exp_path = os.path.join(isaaclab_app_exp_path, self._sim_experience_file) + if os.path.exists(option_1_app_exp_path): + self._sim_experience_file = option_1_app_exp_path + elif os.path.exists(option_2_app_exp_path): + self._sim_experience_file = option_2_app_exp_path + else: + raise FileNotFoundError( + f"Invalid value for input keyword argument `experience`: {self._sim_experience_file}." + "\n No such file exists in either the Kit or Isaac Lab experience paths. Checked paths:" + f"\n\t [1]: {option_1_app_exp_path}" + f"\n\t [2]: {option_2_app_exp_path}" + ) + elif not os.path.exists(self._sim_experience_file): + raise FileNotFoundError( + f"Invalid value for input keyword argument `experience`: {self._sim_experience_file}." + " The file does not exist." + ) + + # Resolve the absolute path of the experience file + self._sim_experience_file = os.path.abspath(self._sim_experience_file) + # Detect a known incompatibility between Isaac Lab and Isaac Sim full-app experiences. + if self._livestream in {1, 2} and self._experience_depends_on_isaacsim_exp_full(self._sim_experience_file): + raise ValueError( + "The experience file depends on 'isaacsim.exp.full', which is known to hang or invalidate PhysX " + "tensor views when launched through Isaac Lab with livestreaming enabled. Omit '--experience' so " + "AppLauncher can select an Isaac Lab experience file, or remove the 'isaacsim.exp.full' dependency." + ) + self._apply_rtx_determinism = bool(deterministic_mode) + logger.info("Loading experience file: %s", self._sim_experience_file) + + @staticmethod + def _experience_depends_on_isaacsim_exp_full(experience_file: str) -> bool: + """Return whether a Kit experience directly depends on ``isaacsim.exp.full``.""" + with open(experience_file, encoding="utf-8") as file: + return re.search(r'^\s*["\']isaacsim\.exp\.full["\']\s*=', file.read(), re.MULTILINE) is not None + + def _resolve_anim_recording_settings(self, launcher_args: dict): + """Resolve animation recording settings.""" + + # Enable omni.physx.pvd extension if recording is enabled + recording_enabled = launcher_args.get("anim_recording_enabled", False) + if recording_enabled: + if self._headless: + raise ValueError("Animation recording is not supported in headless mode.") + sys.argv += ["--enable", "omni.physx.pvd"] + + def _resolve_kit_args(self, launcher_args: dict): + """Resolve additional arguments passed to Kit.""" + # Resolve additional arguments passed to Kit + self._kit_args = [] + if "kit_args" in launcher_args: + self._kit_args = [arg for arg in launcher_args["kit_args"].split()] + sys.argv += self._kit_args + + def _create_app(self): + """Launch and create the SimulationApp based on the parsed simulation config.""" + # Initialize SimulationApp + # hack sys module to make sure that the SimulationApp is initialized correctly + # this is to avoid the warnings from the simulation app about not ok modules + r = re.compile(".*lab.*") + found_modules = list(filter(r.match, list(sys.modules.keys()))) + # remove Isaac Lab modules from sys.modules + hacked_modules = dict() + for key in found_modules: + hacked_modules[key] = sys.modules[key] + del sys.modules[key] + + # disable sys stdout and stderr to avoid printing the warning messages + # this is mainly done to purge the print statements from the simulation app + if "--verbose" not in sys.argv and "--info" not in sys.argv: + sys.stdout = open(os.devnull, "w") # noqa: SIM115 + + # pytest may have left some things in sys.argv, this will check for some of those + # do a mark and sweep to remove any -m pytest and -m isaacsim_ci and -c **/pyproject.toml + indexes_to_remove = [] + for idx, arg in enumerate(sys.argv[:-1]): + if arg == "-m": + value_for_dash_m = sys.argv[idx + 1] + if "pytest" in value_for_dash_m or "isaacsim_ci" in value_for_dash_m: + indexes_to_remove.append(idx) + indexes_to_remove.append(idx + 1) + if arg.startswith("--config-file=") and "pyproject.toml" in arg: + indexes_to_remove.append(idx) + if arg == "--capture=no": + indexes_to_remove.append(idx) + for idx in sorted(indexes_to_remove, reverse=True): + sys.argv = sys.argv[:idx] + sys.argv[idx + 1 :] + + self._app = SimulationApp(self._sim_app_config, experience=self._sim_experience_file) + + # enable sys stdout and stderr + sys.stdout = sys.__stdout__ + + # add Isaac Lab modules back to sys.modules + for key, value in hacked_modules.items(): + sys.modules[key] = value + # remove the threadCount argument from sys.argv if it was added for distributed training + pattern = r"--/plugins/carb\.tasking\.plugin/threadCount=\d+" + sys.argv = [arg for arg in sys.argv if not re.match(pattern, arg)] + + # remove additional OV args from sys.argv + if len(self._kit_args) > 0: + sys.argv = [arg for arg in sys.argv if arg not in self._kit_args] + if len(self._livestream_args) > 0: + sys.argv = [arg for arg in sys.argv if arg not in self._livestream_args] + + def _rendering_enabled(self) -> bool: + """Check if rendering is required by the app.""" + # Indicates whether rendering is required by the app. + # Extensions required for rendering bring startup and simulation costs, so we do not + # enable them if not required. + return not self._headless or self._livestream >= 1 or self._enable_cameras or self._xr + + def _load_extensions(self): + """Load correct extensions based on AppLauncher's resolved config member variables.""" + # These have to be loaded after SimulationApp is initialized. + # Use SettingsManager (backs onto carb when in Omniverse after initialize_carb_settings). + initialize_carb_settings() + + if self._apply_rtx_determinism: + AppLauncher.apply_rtx_determinism_settings() + logger.info("Applied RTX settings for deterministic rendering (--deterministic).") + + # After SimulationApp starts, Kit installs its Python log bridge at DEBUG level. + # Re-apply the intended Python logging level, then add a scoped stream handler for + # Isaac Lab INFO records that Kit's bridge does not mirror to the console. + AppLauncher._apply_python_logging_level(self._python_logging_level) + if self._python_logging_level <= logging.INFO: + AppLauncher._ensure_isaaclab_info_stream_handler() + elif self._python_logging_level == logging.WARNING: + AppLauncher._ensure_isaaclab_info_stream_handler() + # Let Isaac Lab INFO records reach the scoped handler while the other root + # handlers remain at WARNING. + logging.getLogger().setLevel(logging.INFO) + settings = get_settings_manager() + + # set setting to indicate Isaac Lab's offscreen_render pipeline should be enabled + settings.set_bool("/isaaclab/render/offscreen", self._offscreen_render) + + # set setting to indicate Isaac Lab's render_viewport pipeline should be enabled + settings.set_bool("/isaaclab/render/active_viewport", self._render_viewport) + + # set setting to indicate XR mode is enabled + settings.set_bool("/isaaclab/xr/enabled", self._xr) + # set setting to indicate XR auto-start mode -- when running headless + # (no Kit GUI) the AR profile must be enabled programmatically so that + # the OpenXR session starts without user interaction + settings.set_bool("/isaaclab/xr/auto_start", self._headless and self._xr) + # set setting to indicate video recording mode + settings.set_bool("/isaaclab/video/enabled", self._video_enabled) + + # set setting to indicate no RTX sensors are used (set to True when RTX sensor is created) + settings.set_bool("/isaaclab/render/rtx_sensors", False) + + # set fabric update flag to disable updating transforms when rendering is disabled + settings.set_bool("/physics/fabricUpdateTransformations", self._rendering_enabled()) + + # use fixed time stepping disabled; custom loop runner from Isaac Sim is used instead + settings.set_bool("/app/player/useFixedTimeStepping", False) + + def _hide_stop_button(self): + """Hide the stop button in the toolbar. + + For standalone executions, having a stop button is confusing since it invalidates the whole simulation. + Thus, we hide the button so that users don't accidentally click it. + """ + # when we are truly headless, then we can't import the widget toolbar + # thus, we only hide the stop button when we are not headless (i.e. GUI is enabled) + if self._livestream >= 1 or not self._headless: + import omni.kit.widget.toolbar + + # grey out the stop button because we don't want to stop the simulation manually in standalone mode + toolbar = omni.kit.widget.toolbar.get_instance() + play_button_group = toolbar._builtin_tools._play_button_group # type: ignore + if play_button_group is not None: + play_button_group._stop_button.visible = False # type: ignore + play_button_group._stop_button.enabled = False # type: ignore + play_button_group._stop_button = None # type: ignore + + def _set_rendering_mode_settings(self, launcher_args: dict) -> None: + """Store RTX rendering mode in settings.""" + rendering_mode = launcher_args.get("rendering_mode") + + if rendering_mode is None: + # use default kit rendering settings if cameras are disabled and a rendering mode is not selected + if not self._enable_cameras: + return + rendering_mode = "" + + get_settings_manager().set_string("/isaaclab/rendering/rendering_mode", rendering_mode) + + def _set_animation_recording_settings(self, launcher_args: dict) -> None: + """Store animation recording settings in settings.""" + recording_enabled = launcher_args.get("anim_recording_enabled", False) + if not recording_enabled: + return + + # arg checks + if launcher_args.get("anim_recording_start_time") >= launcher_args.get("anim_recording_stop_time"): + raise ValueError( + f"'anim_recording_start_time' {launcher_args.get('anim_recording_start_time')} must be less than" + f" 'anim_recording_stop_time' {launcher_args.get('anim_recording_stop_time')}" + ) + + start_time = launcher_args.get("anim_recording_start_time") + stop_time = launcher_args.get("anim_recording_stop_time") + + settings = get_settings_manager() + settings.set_bool("/isaaclab/anim_recording/enabled", recording_enabled) + settings.set_float("/isaaclab/anim_recording/start_time", start_time) + settings.set_float("/isaaclab/anim_recording/stop_time", stop_time) + + def _set_visualizer_settings(self, launcher_args: dict) -> None: + """Persist visualizer CLI flags and ``max_visible_envs`` override for :class:`SimulationContext`.""" + AppLauncher.sync_visualizer_cli_settings_to_carb( + { + **launcher_args, + "visualizer_explicit": getattr(self, "_cli_visualizer_explicit", False), + "visualizer_disable_all": getattr(self, "_cli_visualizer_disable_all", False), + } + ) + + def _interrupt_signal_handle_callback(self, signal, frame): + """Handle the interrupt signal from the keyboard.""" + # close the app + self._app.close() + # raise the error for keyboard interrupt + raise KeyboardInterrupt + + def is_isaac_sim_version_5(self) -> bool: + if not hasattr(self, "_is_sim_ver_5"): + # 1) Try to read the VERSION file (for manual / binary installs) + version_path = os.path.abspath(os.path.join(os.path.dirname(isaacsim.__file__), "../../VERSION")) + if os.path.isfile(version_path): + with open(version_path) as f: + ver = f.readline().strip() + if ver.startswith("5"): + self._is_sim_ver_5 = True + return True + + # 2) Fall back to metadata (for pip installs) + from importlib.metadata import version as pkg_version + + try: + ver = pkg_version("isaacsim") + if ver.startswith("5"): + self._is_sim_ver_5 = True + else: + self._is_sim_ver_5 = False + except Exception: + self._is_sim_ver_5 = False + return self._is_sim_ver_5 + + def _hide_play_button(self, flag): + """Hide/Unhide the play button in the toolbar. + + This is used if the timeline is stopped by a GUI action like "save as" to not allow the user to + resume the timeline afterwards. + """ + # when we are truly headless, then we can't import the widget toolbar + # thus, we only hide the play button when we are not headless (i.e. GUI is enabled) + if self._livestream >= 1 or not self._headless: + import omni.kit.widget.toolbar + + toolbar = omni.kit.widget.toolbar.get_instance() + play_button_group = toolbar._builtin_tools._play_button_group # type: ignore + if play_button_group is not None: + play_button_group._play_button.visible = not flag # type: ignore + play_button_group._play_button.enabled = not flag # type: ignore + + def _abort_signal_handle_callback(self, signal, frame): + """Handle the abort/segmentation/kill signals.""" + # close the app + self._app.close() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/settings_manager.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/settings_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..8281c627a910be23ea068924963173a5ca9b0236 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/app/settings_manager.py @@ -0,0 +1,205 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Settings manager for Isaac Lab that works with or without Omniverse carb.settings. + +This module provides a unified settings interface that can work in two modes: +1. Omniverse mode: Uses carb.settings when SimulationApp is launched +2. Standalone mode: Uses pure Python dictionary when running without Omniverse + +This allows Isaac Lab to run visualizers like Rerun and Newton without requiring +the full Omniverse/SimulationApp stack. +""" + +import sys +from typing import Any + +# Key for storing singleton in sys.modules to survive module reloads (e.g., from Hydra) +_SINGLETON_KEY = "__isaaclab_settings_manager_singleton__" + + +class SettingsManager: + """A settings manager that provides a carb.settings-like interface without requiring Omniverse. + + This class can work in two modes: + - Standalone mode: Uses a Python dictionary to store settings + - Omniverse mode: Delegates to carb.settings when available + + The interface is designed to be compatible with the carb.settings API. + + This is implemented as a singleton to ensure only one instance exists across the application, + even when used in different execution contexts (e.g., Hydra). The singleton is stored in + sys.modules to survive module reloads. + """ + + def __new__(cls): + """Singleton pattern - always return the same instance, stored in sys.modules to survive reloads.""" + # Check if instance exists in sys.modules (survives module reloads) + instance = sys.modules.get(_SINGLETON_KEY) + + if instance is None: + instance = super().__new__(cls) + sys.modules[_SINGLETON_KEY] = instance + # Mark that this instance needs initialization + instance._needs_init = True + + return instance + + def __init__(self): + """Initialize the settings manager (only runs once due to singleton pattern).""" + # Check if this instance needs initialization + needs_init = getattr(self, "_needs_init", False) + + if not needs_init: + return + + self._standalone_settings: dict[str, Any] = {} + self._carb_settings = None + self._use_carb = False + self._needs_init = False + + @classmethod + def instance(cls) -> "SettingsManager": + """Get the singleton instance of the settings manager. + + Returns: + The singleton SettingsManager instance + """ + # Get instance from sys.modules (survives module reloads) + instance = sys.modules.get(_SINGLETON_KEY) + + if instance is None: + instance = cls() + + return instance + + def initialize_carb_settings(self): + """Initialize carb.settings if SimulationApp has been launched. + + This should be called after SimulationApp is created to enable + Omniverse mode. If not called, the manager operates in standalone mode. + """ + try: + import carb + + self._carb_settings = carb.settings.get_settings() + self._use_carb = True + except (ImportError, AttributeError): + # carb not available or SimulationApp not launched - use standalone mode + self._use_carb = False + + def set(self, path: str, value: Any) -> None: + """Set a setting value at the given path. + + Args: + path: The settings path (e.g., "/isaaclab/render/offscreen") + value: The value to set + """ + if self._use_carb and self._carb_settings is not None: + # Delegate to carb.settings + if isinstance(value, bool): + self._carb_settings.set_bool(path, value) + elif isinstance(value, int): + self._carb_settings.set_int(path, value) + elif isinstance(value, float): + self._carb_settings.set_float(path, value) + elif isinstance(value, str): + self._carb_settings.set_string(path, value) + else: + # For other types, try generic set + self._carb_settings.set(path, value) + else: + # Standalone mode - use dictionary + self._standalone_settings[path] = value + + def get(self, path: str, default: Any = None) -> Any: + """Get a setting value at the given path. + + Args: + path: The settings path (e.g., "/isaaclab/render/offscreen") + default: Default value to return if path doesn't exist + + Returns: + The value at the path, or default if not found + """ + if self._use_carb and self._carb_settings is not None: + # Delegate to carb.settings + value = self._carb_settings.get(path) + return value if value is not None else default + else: + # Standalone mode - use dictionary + return self._standalone_settings.get(path, default) + + def set_bool(self, path: str, value: bool) -> None: + """Set a boolean setting value. + + Args: + path: The settings path + value: The boolean value to set + """ + self.set(path, value) + + def set_int(self, path: str, value: int) -> None: + """Set an integer setting value. + + Args: + path: The settings path + value: The integer value to set + """ + self.set(path, value) + + def set_float(self, path: str, value: float) -> None: + """Set a float setting value. + + Args: + path: The settings path + value: The float value to set + """ + self.set(path, value) + + def set_string(self, path: str, value: str) -> None: + """Set a string setting value. + + Args: + path: The settings path + value: The string value to set + """ + self.set(path, value) + + @property + def is_omniverse_mode(self) -> bool: + """Check if the settings manager is using carb.settings (Omniverse mode). + + Returns: + True if using carb.settings, False if using standalone mode + """ + return self._use_carb + + +def get_settings_manager() -> SettingsManager: + """Get the global settings manager instance. + + The SettingsManager is implemented as a singleton, so this function + always returns the same instance. The singleton is stored in sys.modules + to survive module reloads (e.g., from Hydra). + + Returns: + The global SettingsManager instance + """ + # Get instance from sys.modules (survives module reloads) + instance = sys.modules.get(_SINGLETON_KEY) + if instance is None: + instance = SettingsManager() + return instance + + +def initialize_carb_settings(): + """Initialize carb.settings integration for the global settings manager. + + This should be called after SimulationApp is created to enable + Omniverse mode for the global settings manager. + """ + manager = get_settings_manager() + manager.initialize_carb_settings() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..42d690079199c073ce92961e71855dd93848d6ca --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__init__.py @@ -0,0 +1,43 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-package for different assets, such as rigid objects and articulations. + +An asset is a physical object that can be spawned in the simulation. The class handles both +the spawning of the asset into the USD stage as well as initialization of necessary physics +handles to interact with the asset. + +Upon construction of the asset instance, the prim corresponding to the asset is spawned into the +USD stage if the spawn configuration is not None. The spawn configuration is defined in the +:attr:`AssetBaseCfg.spawn` attribute. In case the configured :attr:`AssetBaseCfg.prim_path` is +an expression, then the prim is spawned at all the matching paths. Otherwise, a single prim is +spawned at the configured path. For more information on the spawn configuration, see the +:mod:`isaaclab.sim.spawners` module. + +The asset class also registers callbacks for the stage play/stop events. These are used to +construct the physics handles for the asset as the physics engine is only available when the +stage is playing. Additionally, the class registers a callback for debug visualization of the +asset. This can be enabled by setting the :attr:`AssetBaseCfg.debug_vis` attribute to True. + +The asset class follows the following naming convention for its methods: + +* **set_xxx()**: These are used to only set the buffers into the :attr:`data` instance. However, they + do not write the data into the simulator. The writing of data only happens when the + :meth:`write_data_to_sim` method is called. +* **write_xxx_to_sim()**: These are used to set the buffers into the :attr:`data` instance and write + the corresponding data into the simulator as well. +* **update(dt)**: These are used to update the buffers in the :attr:`data` instance. This should + be called after a simulation step is performed. + +The main reason to separate the ``set`` and ``write`` operations is to provide flexibility to the +user when they need to perform a post-processing operation of the buffers before applying them +into the simulator. A common example for this is dealing with explicit actuator models where the +specified joint targets are not directly applied to the simulator but are instead used to compute +the corresponding actuator torques. +""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..55b42b8819abd03531205ac82af315fe57449be1 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__init__.pyi @@ -0,0 +1,60 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "BaseArticulation", + "BaseArticulationData", + "Articulation", + "ArticulationCfg", + "ArticulationData", + "AssetBase", + "AssetBaseCfg", + "BaseRigidObject", + "BaseRigidObjectData", + "RigidObject", + "RigidObjectCfg", + "RigidObjectData", + "BaseRigidObjectCollection", + "BaseRigidObjectCollectionData", + "RigidObjectCollection", + "RigidObjectCollectionCfg", + "RigidObjectCollectionData", + "BaseDeformableObject", + "BaseDeformableObjectData", + "DeformableObject", + "DeformableObjectCfg", + "DeformableObjectData", +] + +from .articulation import ( + BaseArticulation, + BaseArticulationData, + Articulation, + ArticulationCfg, + ArticulationData, +) +from .asset_base import AssetBase +from .asset_base_cfg import AssetBaseCfg +from .rigid_object import ( + BaseRigidObject, + BaseRigidObjectData, + RigidObject, + RigidObjectCfg, + RigidObjectData, +) +from .rigid_object_collection import ( + BaseRigidObjectCollection, + BaseRigidObjectCollectionData, + RigidObjectCollection, + RigidObjectCollectionCfg, + RigidObjectCollectionData, +) +from .deformable_object import ( + BaseDeformableObject, + BaseDeformableObjectData, + DeformableObject, + DeformableObjectCfg, + DeformableObjectData, +) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__pycache__/__init__.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0480744212bd527eac593d478f45456b2bcfa4f7 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__pycache__/asset_base.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__pycache__/asset_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f3b7d3fcd9aee8e4d0510e153b9e8ff07465469 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__pycache__/asset_base.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__pycache__/asset_base_cfg.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__pycache__/asset_base_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97d7bdb35e312757bff6adcc317ffb8fd7b4f49e Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/__pycache__/asset_base_cfg.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..91dd3a0caa25c1f9f257c4cb304180acef46c2a4 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module for rigid articulated assets.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..646d9e450c27edbc6e57505bbd8b3652c741abe4 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__init__.pyi @@ -0,0 +1,18 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "BaseArticulation", + "BaseArticulationData", + "Articulation", + "ArticulationCfg", + "ArticulationData", +] + +from .base_articulation import BaseArticulation +from .base_articulation_data import BaseArticulationData +from .articulation import Articulation +from .articulation_cfg import ArticulationCfg +from .articulation_data import ArticulationData diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/__init__.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e21a7f47af147612f99033da0066b1780f678861 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/articulation.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/articulation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46dae99dd55581605cf4e27a291c0a6815b6e887 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/articulation.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/articulation_cfg.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/articulation_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ef701c078898b91faf138963441a4b608e0f6f8 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/articulation_cfg.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/base_articulation.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/base_articulation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2616c73696eb5fef779a5a0d5d33df5b3aaa5ede --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/base_articulation.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50ee3711bc7def0ca0288819bdf5da82df1c133ab2c44797fd7dfe701e1ee378 +size 119931 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/base_articulation_data.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/base_articulation_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..724d5f6afd2f163f4788628814aa926d2888e58b Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/base_articulation_data.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/articulation.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/articulation.py new file mode 100644 index 0000000000000000000000000000000000000000..4efd7074585985313f8f1269202b1e443ae34968 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/articulation.py @@ -0,0 +1,30 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.backend_utils import FactoryBase + +from .base_articulation import BaseArticulation +from .base_articulation_data import BaseArticulationData + +if TYPE_CHECKING: + from isaaclab_physx.assets.articulation import Articulation as PhysXArticulation + from isaaclab_physx.assets.articulation import ArticulationData as PhysXArticulationData + + +class Articulation(FactoryBase, BaseArticulation): + """Factory for creating articulation instances.""" + + data: BaseArticulationData | PhysXArticulationData + + def __new__(cls, *args, **kwargs) -> BaseArticulation | PhysXArticulation: + """Create a new instance of an articulation based on the backend.""" + # The `FactoryBase` __new__ method will handle the logic and return + # an instance of the correct backend-specific articulation class, + # which is guaranteed to be a subclass of `BaseArticulation` by convention. + return super().__new__(cls, *args, **kwargs) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/articulation_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/articulation_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..2124e02aee771d747e897a396b9385c67f75e764 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/articulation_cfg.py @@ -0,0 +1,98 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from dataclasses import MISSING +from typing import TYPE_CHECKING, Any + +from isaaclab.actuators import ActuatorBaseCfg +from isaaclab.utils.configclass import configclass + +from ..asset_base_cfg import AssetBaseCfg + +if TYPE_CHECKING: + from .articulation import Articulation + + +@configclass +class ArticulationCfg(AssetBaseCfg): + """Configuration parameters for an articulation.""" + + @configclass + class InitialStateCfg(AssetBaseCfg.InitialStateCfg): + """Initial state of the articulation.""" + + # root velocity + lin_vel: tuple[float, float, float] = (0.0, 0.0, 0.0) + """Linear velocity of the root in simulation world frame. Defaults to (0.0, 0.0, 0.0).""" + ang_vel: tuple[float, float, float] = (0.0, 0.0, 0.0) + """Angular velocity of the root in simulation world frame. Defaults to (0.0, 0.0, 0.0).""" + + # joint state + joint_pos: dict[str, float] = {".*": 0.0} + """Joint positions of the joints. Defaults to 0.0 for all joints.""" + joint_vel: dict[str, float] = {".*": 0.0} + """Joint velocities of the joints. Defaults to 0.0 for all joints.""" + + ## + # Initialize configurations. + ## + + class_type: type[Articulation] | str = "{DIR}.articulation:Articulation" + + articulation_root_prim_path: str | None = None + """Path to the articulation root prim under the :attr:`prim_path`. Defaults to None, in which case the class + will search for a prim with the USD ArticulationRootAPI on it. + + This path should be relative to the :attr:`prim_path` of the asset. If the asset is loaded from a USD file, + this path should be relative to the root of the USD stage. For instance, if the loaded USD file at :attr:`prim_path` + contains two articulations, one at `/robot1` and another at `/robot2`, and you want to use `robot2`, + then you should set this to `/robot2`. + + The path must start with a slash (`/`). + """ + + init_state: InitialStateCfg = InitialStateCfg() + """Initial state of the articulated object. Defaults to identity pose with zero velocity and zero joint state.""" + + soft_joint_pos_limit_factor: float = 1.0 + """Fraction specifying the range of joint position limits (parsed from the asset) to use. Defaults to 1.0. + + The soft joint position limits are scaled by this factor to specify a safety region within the simulated + joint position limits. This isn't used by the simulation, but is useful for learning agents to prevent the joint + positions from violating the limits, such as for termination conditions. + + The soft joint position limits are accessible through the :attr:`ArticulationData.soft_joint_pos_limits` attribute. + """ + + actuators: dict[str, ActuatorBaseCfg] = MISSING + """Actuators for the robot with corresponding joint names.""" + + actuator_value_resolution_debug_print = False + """Print the resolution of actuator final value when input cfg is different from USD value, Defaults to False + """ + + def _post_spawn(self, stage: Any) -> None: + """Author ``NewtonActuator`` USD prims from :attr:`actuators` after spawn. + + Invoked by :class:`~isaaclab.assets.AssetBase` once the articulation's prims + exist on the stage. Delegates to + :func:`~isaaclab.sim.schemas.define_actuator_properties`, which gates itself + on ``sim_cfg.use_newton_actuators`` and silently no-ops when the simulation + is not configured for Newton-native actuators. + """ + if self.actuators is MISSING: + return + from isaaclab.sim.schemas.schemas_actuators import define_actuator_properties # noqa: PLC0415 + + # In InteractiveScene, articulated assets are often spawned first under + # a template path (for example ``/World/template/Robot``) and cloned + # into ``{ENV_REGEX_NS}`` later. Author NewtonActuator prims on the + # actual spawned source prim so clones inherit them. + author_prim_path = ( + self.spawn.spawn_path if self.spawn is not None and self.spawn.spawn_path is not None else self.prim_path + ) + define_actuator_properties(author_prim_path, self.actuators, stage=stage) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/articulation_data.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/articulation_data.py new file mode 100644 index 0000000000000000000000000000000000000000..5a45d0d1425be97a5ff9dd50da5a96dbd28a40ea --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/articulation_data.py @@ -0,0 +1,23 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.backend_utils import FactoryBase + +from .base_articulation_data import BaseArticulationData + +if TYPE_CHECKING: + from isaaclab_physx.assets.articulation.articulation_data import ArticulationData as PhysXArticulationData + + +class ArticulationData(FactoryBase): + """Factory for creating articulation data instances.""" + + def __new__(cls, *args, **kwargs) -> BaseArticulationData | PhysXArticulationData: + """Create a new instance of an articulation data based on the backend.""" + return super().__new__(cls, *args, **kwargs) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/base_articulation.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/base_articulation.py new file mode 100644 index 0000000000000000000000000000000000000000..76e831bdad17854ffaab91c5c2c1d9e79cb7a686 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/base_articulation.py @@ -0,0 +1,2826 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# Flag for pyright to ignore type errors in this file. +# pyright: reportPrivateUsage=false + +from __future__ import annotations + +import warnings +from abc import abstractmethod +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch +import warp as wp + +from ...sim import SimulationContext +from ...utils.leapp.leapp_semantics import OutputKindEnum, joint_names_resolver, leapp_tensor_semantics +from ..asset_base import AssetBase + +if TYPE_CHECKING: + from isaaclab.utils.wrench_composer import WrenchComposer + + from .articulation_cfg import ArticulationCfg + from .articulation_data import ArticulationData + + +class BaseArticulation(AssetBase): + """An articulation asset class. + + An articulation is a collection of rigid bodies connected by joints. The joints can be either + fixed or actuated. The joints can be of different types, such as revolute, prismatic, D-6, etc. + However, the articulation class has currently been tested with revolute and prismatic joints. + The class supports both floating-base and fixed-base articulations. The type of articulation + is determined based on the root joint of the articulation. If the root joint is fixed, then + the articulation is considered a fixed-base system. Otherwise, it is considered a floating-base + system. This can be checked using the :attr:`Articulation.is_fixed_base` attribute. + + For an asset to be considered an articulation, the root prim of the asset must have the + `USD ArticulationRootAPI`_. This API is used to define the sub-tree of the articulation using + the reduced coordinate formulation. On playing the simulation, the physics engine parses the + articulation root prim and creates the corresponding articulation in the physics engine. The + articulation root prim can be specified using the :attr:`AssetBaseCfg.prim_path` attribute. + + The articulation class also provides the functionality to augment the simulation of an articulated + system with custom actuator models. These models can either be explicit or implicit, as detailed in + the :mod:`isaaclab.actuators` module. The actuator models are specified using the + :attr:`ArticulationCfg.actuators` attribute. These are then parsed and used to initialize the + corresponding actuator models, when the simulation is played. + + During the simulation step, the articulation class first applies the actuator models to compute + the joint commands based on the user-specified targets. These joint commands are then applied + into the simulation. The joint commands can be either position, velocity, or effort commands. + As an example, the following snippet shows how this can be used for position commands: + + .. code-block:: python + + # an example instance of the articulation class + my_articulation = Articulation(cfg) + + # set joint position targets + my_articulation.set_joint_position_target(position) + # propagate the actuator models and apply the computed commands into the simulation + my_articulation.write_data_to_sim() + + # step the simulation using the simulation context + sim_context.step() + + # update the articulation state, where dt is the simulation time step + my_articulation.update(dt) + + .. _`USD ArticulationRootAPI`: https://openusd.org/dev/api/class_usd_physics_articulation_root_a_p_i.html + + """ + + cfg: ArticulationCfg + """Configuration instance for the articulations.""" + + __backend_name__: str = "base" + """The name of the backend for the articulation.""" + + actuators: dict + """Dictionary of actuator instances for the articulation. + + The keys are the actuator names and the values are the actuator instances. The actuator instances + are initialized based on the actuator configurations specified in the :attr:`ArticulationCfg.actuators` + attribute. They are used to compute the joint commands during the :meth:`write_data_to_sim` function. + """ + + def __init__(self, cfg: ArticulationCfg): + """Initialize the articulation. + + Args: + cfg: A configuration instance. + """ + super().__init__(cfg) + sim_ctx = SimulationContext.instance() + self._sim_cfg = sim_ctx.cfg if sim_ctx is not None else None + + """ + Properties + """ + + @property + @abstractmethod + def data(self) -> ArticulationData: + raise NotImplementedError() + + @property + @abstractmethod + def num_instances(self) -> int: + raise NotImplementedError() + + @property + @abstractmethod + def is_fixed_base(self) -> bool: + """Whether the articulation is a fixed-base or floating-base system.""" + raise NotImplementedError() + + @property + @abstractmethod + def num_joints(self) -> int: + """Number of joints in articulation.""" + raise NotImplementedError() + + @property + @abstractmethod + def num_fixed_tendons(self) -> int: + """Number of fixed tendons in articulation.""" + raise NotImplementedError() + + @property + @abstractmethod + def num_spatial_tendons(self) -> int: + """Number of spatial tendons in articulation.""" + raise NotImplementedError() + + @property + @abstractmethod + def num_bodies(self) -> int: + """Number of bodies in articulation.""" + raise NotImplementedError() + + @property + @abstractmethod + def joint_names(self) -> list[str]: + """Ordered names of joints in articulation.""" + raise NotImplementedError() + + @property + @abstractmethod + def fixed_tendon_names(self) -> list[str]: + """Ordered names of fixed tendons in articulation.""" + raise NotImplementedError() + + @property + @abstractmethod + def spatial_tendon_names(self) -> list[str]: + """Ordered names of spatial tendons in articulation.""" + raise NotImplementedError() + + @property + @abstractmethod + def body_names(self) -> list[str]: + """Ordered names of bodies in articulation.""" + raise NotImplementedError() + + @property + @abstractmethod + def root_view(self): + """Root view for the asset. + + .. note:: + Use this view with caution. It requires handling of tensors in a specific way. + """ + raise NotImplementedError() + + @property + def num_base_dofs(self) -> int: + """Number of free DoFs of the floating base. + + A floating-base articulation can translate and rotate freely in space, so + its base contributes 6 DoFs (3 linear, 3 angular). A fixed-base articulation + is bolted to the world and contributes 0. + + Use this to map an actuated-joint index ``j`` to its column in the Jacobian + / mass matrix / gravity vector: ``column = j + num_base_dofs``. + """ + return 0 if self.is_fixed_base else 6 + + @property + @abstractmethod + def instantaneous_wrench_composer(self) -> WrenchComposer: + """Instantaneous wrench composer. + + Returns a :class:`~isaaclab.utils.wrench_composer.WrenchComposer` instance. Wrenches added or set to this wrench + composer are only valid for the current simulation step. At the end of the simulation step, the wrenches set + to this object are discarded. This is useful to apply forces that change all the time, things like drag forces + for instance. + """ + raise NotImplementedError() + + @property + @abstractmethod + def permanent_wrench_composer(self) -> WrenchComposer: + """Permanent wrench composer. + + Returns a :class:`~isaaclab.utils.wrench_composer.WrenchComposer` instance. Wrenches added or set to this wrench + composer are persistent and are applied to the simulation at every step. This is useful to apply forces that + are constant over a period of time, things like the thrust of a motor for instance. + """ + raise NotImplementedError() + + """ + Operations. + """ + + @abstractmethod + def reset( + self, env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, env_mask: wp.array | None = None + ) -> None: + """Reset the articulation. + + .. caution:: + If both `env_ids` and `env_mask` are provided, then `env_mask` takes precedence over `env_ids`. + + Args: + env_ids: Environment indices. If None, then all indices are used. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_data_to_sim(self) -> None: + """Write external wrenches and joint commands to the simulation. + + If any explicit actuators are present, then the actuator models are used to compute the + joint commands. Otherwise, the joint commands are directly set into the simulation. + + .. note:: + We write external wrench to the simulation here since this function is called before the simulation step. + This ensures that the external wrench is applied at every simulation step. + """ + raise NotImplementedError() + + @abstractmethod + def update(self, dt: float) -> None: + """Updates the simulation data. + + Args: + dt: The time step size in seconds. + """ + raise NotImplementedError() + + """ + Operations - Finders. + """ + + @abstractmethod + def find_bodies(self, name_keys: str | Sequence[str], preserve_order: bool = False) -> tuple[list[int], list[str]]: + """Find bodies in the articulation based on the name keys. + + Please check the :meth:`isaaclab.utils.string_utils.resolve_matching_names` function for more + information on the name matching. + + Args: + name_keys: A regular expression or a list of regular expressions to match the body names. + preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False. + + Returns: + A tuple of lists containing the body indices and names. + """ + raise NotImplementedError() + + @abstractmethod + def find_joints( + self, name_keys: str | Sequence[str], joint_subset: list[str] | None = None, preserve_order: bool = False + ) -> tuple[list[int], list[str]]: + """Find joints in the articulation based on the name keys. + + Please see the :func:`isaaclab.utils.string.resolve_matching_names` function for more information + on the name matching. + + Args: + name_keys: A regular expression or a list of regular expressions to match the joint names. + joint_subset: A subset of joints to search for. Defaults to None, which means all joints + in the articulation are searched. + preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False. + + Returns: + A tuple of lists containing the joint indices, names. + """ + raise NotImplementedError() + + @abstractmethod + def find_fixed_tendons( + self, name_keys: str | Sequence[str], tendon_subsets: list[str] | None = None, preserve_order: bool = False + ) -> tuple[list[int], list[str]]: + """Find fixed tendons in the articulation based on the name keys. + + Please see the :func:`isaaclab.utils.string.resolve_matching_names` function for more information + on the name matching. + + Args: + name_keys: A regular expression or a list of regular expressions to match the joint + names with fixed tendons. + tendon_subsets: A subset of joints with fixed tendons to search for. Defaults to None, which means + all joints in the articulation are searched. + preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False. + + Returns: + A tuple of lists containing the tendon indices, names. + """ + raise NotImplementedError() + + @abstractmethod + def find_spatial_tendons( + self, name_keys: str | Sequence[str], tendon_subsets: list[str] | None = None, preserve_order: bool = False + ) -> tuple[list[int], list[str]]: + """Find spatial tendons in the articulation based on the name keys. + + Please see the :func:`isaaclab.utils.string.resolve_matching_names` function for more information + on the name matching. + + Args: + name_keys: A regular expression or a list of regular expressions to match the tendon names. + tendon_subsets: A subset of tendons to search for. Defaults to None, which means all tendons + in the articulation are searched. + preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False. + + Returns: + A tuple of lists containing the tendon indices, names. + """ + raise NotImplementedError() + + """ + Operations - State Writers. + """ + + @abstractmethod + def write_root_pose_to_sim_index( + self, + *, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the root pose over selected environment indices into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_pose: Root poses in simulation frame. Shape is (len(env_ids), 7) + or (len(env_ids),) with dtype wp.transformf. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_root_pose_to_sim_mask( + self, + *, + root_pose: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root pose over selected environment mask into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_pose: Root poses in simulation frame. Shape is (num_instances, 7) + or (num_instances,) with dtype wp.transformf. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_root_link_pose_to_sim_index( + self, + *, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the root link pose over selected environment indices into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_pose: Root poses in simulation frame. Shape is (len(env_ids), 7) + or (len(env_ids),) with dtype wp.transformf. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_root_link_pose_to_sim_mask( + self, + *, + root_pose: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root link pose over selected environment mask into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_pose: Root poses in simulation frame. Shape is (num_instances, 7) + or (num_instances,) with dtype wp.transformf. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_root_com_pose_to_sim_index( + self, + *, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the root center of mass pose over selected environment indices into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + The orientation is the orientation of the principal axes of inertia. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_pose: Root center of mass poses in simulation frame. Shape is (len(env_ids), 7) + or (len(env_ids),) with dtype wp.transformf. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_root_com_pose_to_sim_mask( + self, + *, + root_pose: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root center of mass pose over selected environment mask into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + The orientation is the orientation of the principal axes of inertia. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_pose: Root center of mass poses in simulation frame. Shape is (num_instances, 7) + or (num_instances,) with dtype wp.transformf. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_root_velocity_to_sim_index( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the root center of mass velocity over selected environment indices into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the root's center of mass rather than the root's frame. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_velocity: Root center of mass velocities in simulation world frame. Shape is (len(env_ids), 6) + or (len(env_ids),) with dtype wp.spatial_vectorf. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_root_velocity_to_sim_mask( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root center of mass velocity over selected environment mask into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the root's center of mass rather than the root's frame. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_velocity: Root center of mass velocities in simulation world frame. Shape is (num_instances, 6) + or (num_instances,) with dtype wp.spatial_vectorf. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_root_com_velocity_to_sim_index( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the root center of mass velocity over selected environment indices into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the root's center of mass rather than the root's frame. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_velocity: Root center of mass velocities in simulation world frame. Shape is (len(env_ids), 6) + or (len(env_ids),) with dtype wp.spatial_vectorf. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_root_com_velocity_to_sim_mask( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root center of mass velocity over selected environment mask into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the root's center of mass rather than the root's frame. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_velocity: Root center of mass velocities in simulation world frame. Shape is (num_instances, 6) + or (num_instances,) with dtype wp.spatial_vectorf. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_root_link_velocity_to_sim_index( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the root link velocity over selected environment indices into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the root's frame rather than the root's center of mass. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_velocity: Root frame velocities in simulation world frame. Shape is (len(env_ids), 6) + or (len(env_ids),) with dtype wp.spatial_vectorf. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_root_link_velocity_to_sim_mask( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root link velocity over selected environment mask into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the root's frame rather than the root's center of mass. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_velocity: Root frame velocities in simulation world frame. Shape is (num_instances, 6) + or (num_instances,) with dtype wp.spatial_vectorf. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_position_to_sim_index( + self, + *, + position: torch.Tensor | wp.array, + joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Write joint positions to the simulation. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + position: Joint positions. Shape is (len(env_ids), len(joint_ids)). + joint_ids: The joint indices to set the targets for. Defaults to None (all joints). + env_ids: The environment indices to set the targets for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_position_to_sim_mask( + self, + *, + position: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint positions to the simulation. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + position: Joint positions. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all the joints are updated. Shape is (num_joints,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_velocity_to_sim_index( + self, + *, + velocity: torch.Tensor | wp.array, + joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Write joint velocities to the simulation. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + velocity: Joint velocities. Shape is (len(env_ids), len(joint_ids)). + joint_ids: The joint indices to set the targets for. Defaults to None (all joints). + env_ids: The environment indices to set the targets for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_velocity_to_sim_mask( + self, + *, + velocity: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint velocities to the simulation. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + velocity: Joint velocities. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all the joints are updated. Shape is (num_joints,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + """ + Operations - Simulation Parameters Writers. + """ + + @abstractmethod + def write_joint_stiffness_to_sim_index( + self, + *, + stiffness: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Write joint stiffness into the simulation. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + stiffness: Joint stiffness. Shape is (len(env_ids), len(joint_ids)). + joint_ids: The joint indices to set the stiffness for. Defaults to None (all joints). + env_ids: The environment indices to set the stiffness for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_stiffness_to_sim_mask( + self, + *, + stiffness: torch.Tensor | float | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint stiffness into the simulation. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + stiffness: Joint stiffness. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all the joints are updated. Shape is (num_joints,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_damping_to_sim_index( + self, + *, + damping: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Write joint damping into the simulation. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + damping: Joint damping. Shape is (len(env_ids), len(joint_ids)). + joint_ids: The joint indices to set the damping for. Defaults to None (all joints). + env_ids: The environment indices to set the damping for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_damping_to_sim_mask( + self, + *, + damping: torch.Tensor | float | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint damping into the simulation. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + damping: Joint damping. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all the joints are updated. Shape is (num_joints,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_position_limit_to_sim_index( + self, + *, + limits: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + warn_limit_violation: bool = True, + ) -> None: + """Write joint position limits into the simulation. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + limits: Joint limits. Shape is (len(env_ids), len(joint_ids), 2) or (len(env_ids), len(joint_ids)) with + dtype wp.vec2f. + joint_ids: The joint indices to set the limits for. Defaults to None (all joints). + env_ids: The environment indices to set the limits for. Defaults to None (all instances). + warn_limit_violation: Whether to use warning or info level logging when default joint positions + exceed the new limits. Defaults to True. + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_position_limit_to_sim_mask( + self, + *, + limits: torch.Tensor | float | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + warn_limit_violation: bool = True, + ) -> None: + """Write joint position limits into the simulation. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + limits: Joint limits. Shape is (num_instances, num_joints, 2) or (num_instances, num_joints) with dtype + wp.vec2f. + joint_mask: Joint mask. If None, then all the joints are updated. Shape is (num_joints,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + warn_limit_violation: Whether to use warning or info level logging when default joint positions + exceed the new limits. Defaults to True. + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_velocity_limit_to_sim_index( + self, + *, + limits: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Write joint max velocity to the simulation. + + The velocity limit is used to constrain the joint velocities in the physics engine. The joint will only + be able to reach this velocity if the joint's effort limit is sufficiently large. If the joint is moving + faster than this velocity, the physics engine will actually try to brake the joint to reach this velocity. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + limits: Joint max velocity. Shape is (len(env_ids), len(joint_ids)). + joint_ids: The joint indices to set the max velocity for. Defaults to None (all joints). + env_ids: The environment indices to set the max velocity for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_velocity_limit_to_sim_mask( + self, + *, + limits: torch.Tensor | float | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint max velocity to the simulation. + + The velocity limit is used to constrain the joint velocities in the physics engine. The joint will only + be able to reach this velocity if the joint's effort limit is sufficiently large. If the joint is moving + faster than this velocity, the physics engine will actually try to brake the joint to reach this velocity. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + limits: Joint max velocity. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all the joints are updated. Shape is (num_joints,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_effort_limit_to_sim_index( + self, + *, + limits: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Write joint effort limits into the simulation. + + The effort limit is used to constrain the computed joint efforts in the physics engine. If the + computed effort exceeds this limit, the physics engine will clip the effort to this value. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + limits: Joint torque limits. Shape is (len(env_ids), len(joint_ids)). + joint_ids: The joint indices to set the joint torque limits for. Defaults to None (all joints). + env_ids: The environment indices to set the joint torque limits for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_effort_limit_to_sim_mask( + self, + *, + limits: torch.Tensor | float | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint effort limits into the simulation. + + The effort limit is used to constrain the computed joint efforts in the physics engine. If the + computed effort exceeds this limit, the physics engine will clip the effort to this value. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + limits: Joint torque limits. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all the joints are updated. Shape is (num_joints,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_armature_to_sim_index( + self, + *, + armature: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Write joint armature into the simulation. + + The armature is directly added to the corresponding joint-space inertia. It helps improve the + simulation stability by reducing the joint velocities. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + armature: Joint armature. Shape is (len(env_ids), len(joint_ids)). + joint_ids: The joint indices to set the joint torque limits for. Defaults to None (all joints). + env_ids: The environment indices to set the joint torque limits for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_armature_to_sim_mask( + self, + *, + armature: torch.Tensor | float | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint armature into the simulation. + + The armature is directly added to the corresponding joint-space inertia. It helps improve the + simulation stability by reducing the joint velocities. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + armature: Joint armature. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all the joints are updated. Shape is (num_joints,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_friction_coefficient_to_sim_index( + self, + *, + joint_friction_coeff: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + r"""Write backend-specific joint friction values into the simulation. + + .. warning:: + The physical meaning and units of joint friction depend on the concrete backend and solver. Do not assume + values are comparable across backends; check the backend-specific implementation before interpreting or + reusing them. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + joint_friction_coeff: Backend-specific joint friction values. Shape is (len(env_ids), len(joint_ids)). + joint_ids: The joint indices to set the joint torque limits for. Defaults to None (all joints). + env_ids: The environment indices to set the joint torque limits for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def write_joint_friction_coefficient_to_sim_mask( + self, + *, + joint_friction_coeff: torch.Tensor | float | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + r"""Write backend-specific joint friction values into the simulation. + + .. warning:: + The physical meaning and units of joint friction depend on the concrete backend and solver. Do not assume + values are comparable across backends; check the backend-specific implementation before interpreting or + reusing them. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + joint_friction_coeff: Backend-specific joint friction values. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all the joints are updated. Shape is (num_joints,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + """ + Operations - Setters. + """ + + @abstractmethod + def set_masses_index( + self, + *, + masses: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set masses of all bodies in the simulation world frame. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + masses: Masses of all bodies. Shape is (len(env_ids), len(body_ids)). + body_ids: The body indices to set the masses for. Defaults to None (all bodies). + env_ids: The environment indices to set the masses for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def set_masses_mask( + self, + *, + masses: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set masses of all bodies in the simulation world frame. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + masses: Masses of all bodies. Shape is (num_instances, num_bodies). + body_mask: Body mask. If None, then all the bodies are updated. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_coms_index( + self, + *, + coms: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set center of mass pose of all bodies in their respective body link frames. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + coms: Center of mass pose of all bodies. Shape is (len(env_ids), len(body_ids), 7) + or (len(env_ids), len(body_ids)) with dtype wp.transformf. + body_ids: The body indices to set the center of mass pose for. Defaults to None (all bodies). + env_ids: The environment indices to set the center of mass pose for. Defaults to None + (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def set_coms_mask( + self, + *, + coms: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set center of mass pose of all bodies in their respective body link frames. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + coms: Center of mass pose of all bodies. Shape is (num_instances, num_bodies, 7) + or (num_instances, num_bodies) with dtype wp.transformf. + body_mask: Body mask. If None, then all the bodies are updated. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_inertias_index( + self, + *, + inertias: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set inertias of all bodies in the simulation world frame. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + inertias: Inertias of all bodies. Shape is (len(env_ids), len(body_ids), 9). + body_ids: The body indices to set the inertias for. Defaults to None (all bodies). + env_ids: The environment indices to set the inertias for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def set_inertias_mask( + self, + *, + inertias: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set inertias of all bodies in the simulation world frame. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + inertias: Inertias of all bodies. Shape is (num_instances, num_bodies, 9). + body_mask: Body mask. If None, then all the bodies are updated. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + @leapp_tensor_semantics(kind=OutputKindEnum.JOINT_POSITION, element_names_resolver=joint_names_resolver) + def set_joint_position_target_index( + self, + *, + target: torch.Tensor | wp.array, + joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set joint position targets into internal buffers. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + This function does not apply the joint targets to the simulation. It only fills the buffers with + the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function. + + Args: + target: Joint position targets. Shape is (len(env_ids), len(joint_ids)). + joint_ids: The joint indices to set the targets for. Defaults to None (all joints). + env_ids: The environment indices to set the targets for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + @leapp_tensor_semantics(kind=OutputKindEnum.JOINT_POSITION, element_names_resolver=joint_names_resolver) + def set_joint_position_target_mask( + self, + *, + target: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set joint position targets into internal buffers. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + This function does not apply the joint targets to the simulation. It only fills the buffers with + the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function. + + Args: + target: Joint position targets. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all the joints are updated. Shape is (num_joints,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + @leapp_tensor_semantics(kind=OutputKindEnum.JOINT_VELOCITY, element_names_resolver=joint_names_resolver) + def set_joint_velocity_target_index( + self, + *, + target: torch.Tensor | wp.array, + joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set joint velocity targets into internal buffers. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + This function does not apply the joint targets to the simulation. It only fills the buffers with + the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function. + + Args: + target: Joint velocity targets. Shape is (len(env_ids), len(joint_ids)). + joint_ids: The joint indices to set the targets for. Defaults to None (all joints). + env_ids: The environment indices to set the targets for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + @leapp_tensor_semantics(kind=OutputKindEnum.JOINT_VELOCITY, element_names_resolver=joint_names_resolver) + def set_joint_velocity_target_mask( + self, + *, + target: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set joint velocity targets into internal buffers. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + This function does not apply the joint targets to the simulation. It only fills the buffers with + the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function. + + Args: + target: Joint velocity targets. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all the joints are updated. Shape is (num_joints,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + @leapp_tensor_semantics(kind=OutputKindEnum.JOINT_EFFORT, element_names_resolver=joint_names_resolver) + def set_joint_effort_target_index( + self, + *, + target: torch.Tensor | wp.array, + joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set joint efforts into internal buffers. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + This function does not apply the joint targets to the simulation. It only fills the buffers with + the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function. + + Args: + target: Joint effort targets. Shape is (len(env_ids), len(joint_ids)). + joint_ids: The joint indices to set the targets for. Defaults to None (all joints). + env_ids: The environment indices to set the targets for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + @leapp_tensor_semantics(kind=OutputKindEnum.JOINT_EFFORT, element_names_resolver=joint_names_resolver) + def set_joint_effort_target_mask( + self, + *, + target: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set joint efforts into internal buffers. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + This function does not apply the joint targets to the simulation. It only fills the buffers with + the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function. + + Args: + target: Joint effort targets. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all the joints are updated. Shape is (num_joints,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + """ + Operations - Tendons. + """ + + @abstractmethod + def set_fixed_tendon_stiffness_index( + self, + *, + stiffness: float | torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set fixed tendon stiffness into internal buffers. + + This function does not apply the tendon stiffness to the simulation. It only fills the buffers with + the desired values. To apply the tendon stiffness, call the :meth:`write_fixed_tendon_properties_to_sim_index` + function. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + stiffness: Fixed tendon stiffness. Shape is (len(env_ids), len(fixed_tendon_ids)). + fixed_tendon_ids: The tendon indices to set the stiffness for. Defaults to None (all fixed tendons). + env_ids: The environment indices to set the stiffness for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def set_fixed_tendon_stiffness_mask( + self, + *, + stiffness: float | torch.Tensor | wp.array, + fixed_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set fixed tendon stiffness into internal buffers. + + This function does not apply the tendon stiffness to the simulation. It only fills the buffers with + the desired values. To apply the tendon stiffness, call the :meth:`write_fixed_tendon_properties_to_sim_mask` + function. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + stiffness: Fixed tendon stiffness. Shape is (num_instances, num_fixed_tendons). + fixed_tendon_mask: Fixed tendon mask. If None, then all the fixed tendons are updated. + Shape is (num_fixed_tendons,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_fixed_tendon_damping_index( + self, + *, + damping: float | torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set fixed tendon damping into internal buffers. + + This function does not apply the tendon damping to the simulation. It only fills the buffers with + the desired values. To apply the tendon damping, call the :meth:`write_fixed_tendon_properties_to_sim_index` + function. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + damping: Fixed tendon damping. Shape is (len(env_ids), len(fixed_tendon_ids)). + fixed_tendon_ids: The tendon indices to set the damping for. Defaults to None (all fixed tendons). + env_ids: The environment indices to set the damping for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def set_fixed_tendon_damping_mask( + self, + *, + damping: float | torch.Tensor | wp.array, + fixed_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set fixed tendon damping into internal buffers. + + This function does not apply the tendon damping to the simulation. It only fills the buffers with + the desired values. To apply the tendon damping, call the :meth:`write_fixed_tendon_properties_to_sim_mask` + function. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + damping: Fixed tendon damping. Shape is (num_instances, num_fixed_tendons). + fixed_tendon_mask: Fixed tendon mask. If None, then all the fixed tendons are updated. + Shape is (num_fixed_tendons,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_fixed_tendon_limit_stiffness_index( + self, + *, + limit_stiffness: float | torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set fixed tendon limit stiffness into internal buffers. + + This function does not apply the tendon limit stiffness to the simulation. It only fills the buffers with + the desired values. To apply the tendon limit stiffness, call the + :meth:`write_fixed_tendon_properties_to_sim_index` function. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + limit_stiffness: Fixed tendon limit stiffness. Shape is (len(env_ids), len(fixed_tendon_ids)). + fixed_tendon_ids: The tendon indices to set the limit stiffness for. Defaults to None (all fixed tendons). + env_ids: The environment indices to set the limit stiffness for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def set_fixed_tendon_limit_stiffness_mask( + self, + *, + limit_stiffness: float | torch.Tensor | wp.array, + fixed_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set fixed tendon limit stiffness into internal buffers. + + This function does not apply the tendon limit stiffness to the simulation. It only fills the buffers with + the desired values. To apply the tendon limit stiffness, call the + :meth:`write_fixed_tendon_properties_to_sim_mask` function. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + limit_stiffness: Fixed tendon limit stiffness. Shape is (num_instances, num_fixed_tendons). + fixed_tendon_mask: Fixed tendon mask. If None, then all the fixed tendons are updated. + Shape is (num_fixed_tendons,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_fixed_tendon_position_limit_index( + self, + *, + limit: float | torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set fixed tendon position limits into internal buffers. + + This function does not apply the tendon limit to the simulation. It only fills the buffers with + the desired values. To apply the tendon limit, call the :meth:`write_fixed_tendon_properties_to_sim_index` + function. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + limit: Fixed tendon limit. Shape is (len(env_ids), len(fixed_tendon_ids)). + fixed_tendon_ids: The tendon indices to set the limit for. Defaults to None (all fixed tendons). + env_ids: The environment indices to set the limit for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def set_fixed_tendon_position_limit_mask( + self, + *, + limit: float | torch.Tensor | wp.array, + fixed_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set fixed tendon position limits into internal buffers. + + This function does not apply the tendon limit to the simulation. It only fills the buffers with + the desired values. To apply the tendon limit, call the :meth:`write_fixed_tendon_properties_to_sim_mask` + function. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + limit: Fixed tendon limit. Shape is (num_instances, num_fixed_tendons). + fixed_tendon_mask: Fixed tendon mask. If None, then all the fixed tendons are updated. + Shape is (num_fixed_tendons,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_fixed_tendon_rest_length_index( + self, + *, + rest_length: float | torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set fixed tendon rest length into internal buffers. + + This function does not apply the tendon rest length to the simulation. It only fills the buffers with + the desired values. To apply the tendon rest length, call the :meth:`write_fixed_tendon_properties_to_sim_index` + function. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + rest_length: Fixed tendon rest length. Shape is (len(env_ids), len(fixed_tendon_ids)). + fixed_tendon_ids: The tendon indices to set the rest length for. Defaults to None (all fixed tendons). + env_ids: The environment indices to set the rest length for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def set_fixed_tendon_rest_length_mask( + self, + *, + rest_length: float | torch.Tensor | wp.array, + fixed_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set fixed tendon rest length into internal buffers. + + This function does not apply the tendon rest length to the simulation. It only fills the buffers with + the desired values. To apply the tendon rest length, call the :meth:`write_fixed_tendon_properties_to_sim_mask` + function. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + rest_length: Fixed tendon rest length. Shape is (num_instances, num_fixed_tendons). + fixed_tendon_mask: Fixed tendon mask. If None, then all the fixed tendons are updated. + Shape is (num_fixed_tendons,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_fixed_tendon_offset_index( + self, + *, + offset: float | torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set fixed tendon offset into internal buffers. + + This function does not apply the tendon offset to the simulation. It only fills the buffers with + the desired values. To apply the tendon offset, call the :meth:`write_fixed_tendon_properties_to_sim_index` + function. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + offset: Fixed tendon offset. Shape is (len(env_ids), len(fixed_tendon_ids)). + fixed_tendon_ids: The tendon indices to set the offset for. Defaults to None (all fixed tendons). + env_ids: The environment indices to set the offset for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def set_fixed_tendon_offset_mask( + self, + *, + offset: float | torch.Tensor | wp.array, + fixed_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set fixed tendon offset into internal buffers. + + This function does not apply the tendon offset to the simulation. It only fills the buffers with + the desired values. To apply the tendon offset, call the :meth:`write_fixed_tendon_properties_to_sim_mask` + function. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + offset: Fixed tendon offset. Shape is (num_instances, num_fixed_tendons). + fixed_tendon_mask: Fixed tendon mask. If None, then all the fixed tendons are updated. + Shape is (num_fixed_tendons,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_fixed_tendon_properties_to_sim_index( + self, + *, + fixed_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Write fixed tendon properties into the simulation. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + fixed_tendon_ids: The fixed tendon indices to set the limits for. Defaults to None (all fixed tendons). + env_ids: The environment indices to set the limits for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def write_fixed_tendon_properties_to_sim_mask( + self, + *, + fixed_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write fixed tendon properties into the simulation. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + fixed_tendon_mask: Fixed tendon mask. If None, then all the fixed tendons are updated. + Shape is (num_fixed_tendons,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_spatial_tendon_stiffness_index( + self, + *, + stiffness: float | torch.Tensor | wp.array, + spatial_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set spatial tendon stiffness into internal buffers. + + This function does not apply the tendon stiffness to the simulation. It only fills the buffers with + the desired values. To apply the tendon stiffness, call the :meth:`write_spatial_tendon_properties_to_sim_index` + function. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + stiffness: Spatial tendon stiffness. Shape is (len(env_ids), len(spatial_tendon_ids)). + spatial_tendon_ids: The tendon indices to set the stiffness for. Defaults to None (all spatial tendons). + env_ids: The environment indices to set the stiffness for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def set_spatial_tendon_stiffness_mask( + self, + *, + stiffness: float | torch.Tensor | wp.array, + spatial_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set spatial tendon stiffness into internal buffers. + + This function does not apply the tendon stiffness to the simulation. It only fills the buffers with + the desired values. To apply the tendon stiffness, call the :meth:`write_spatial_tendon_properties_to_sim_mask` + function. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + stiffness: Spatial tendon stiffness. Shape is (num_instances, num_spatial_tendons). + spatial_tendon_mask: Spatial tendon mask. If None, then all the spatial tendons are updated. + Shape is (num_spatial_tendons,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_spatial_tendon_damping_index( + self, + *, + damping: float | torch.Tensor | wp.array, + spatial_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set spatial tendon damping into internal buffers. + + This function does not apply the tendon damping to the simulation. It only fills the buffers with + the desired values. To apply the tendon damping, call the :meth:`write_spatial_tendon_properties_to_sim_index` + function. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + damping: Spatial tendon damping. Shape is (len(env_ids), len(spatial_tendon_ids)). + spatial_tendon_ids: The tendon indices to set the damping for. Defaults to None (all spatial tendons). + env_ids: The environment indices to set the damping for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def set_spatial_tendon_damping_mask( + self, + *, + damping: float | torch.Tensor | wp.array, + spatial_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set spatial tendon damping into internal buffers. + + This function does not apply the tendon damping to the simulation. It only fills the buffers with + the desired values. To apply the tendon damping, call the :meth:`write_spatial_tendon_properties_to_sim_mask` + function. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + damping: Spatial tendon damping. Shape is (num_instances, num_spatial_tendons). + spatial_tendon_mask: Spatial tendon mask. If None, then all the spatial tendons are updated. + Shape is (num_spatial_tendons,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_spatial_tendon_limit_stiffness_index( + self, + *, + limit_stiffness: float | torch.Tensor | wp.array, + spatial_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set spatial tendon limit stiffness into internal buffers. + + This function does not apply the tendon limit stiffness to the simulation. It only fills the buffers with + the desired values. To apply the tendon limit stiffness, call the + :meth:`write_spatial_tendon_properties_to_sim_index` function. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + limit_stiffness: Spatial tendon limit stiffness. Shape is (len(env_ids), len(spatial_tendon_ids)). + spatial_tendon_ids: The tendon indices to set the limit stiffness for. Defaults to None + (all spatial tendons). + env_ids: The environment indices to set the limit stiffness for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def set_spatial_tendon_limit_stiffness_mask( + self, + *, + limit_stiffness: float | torch.Tensor | wp.array, + spatial_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set spatial tendon limit stiffness into internal buffers. + + This function does not apply the tendon limit stiffness to the simulation. It only fills the buffers with + the desired values. To apply the tendon limit stiffness, call the + :meth:`write_spatial_tendon_properties_to_sim_mask` function. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + limit_stiffness: Spatial tendon limit stiffness. Shape is (num_instances, num_spatial_tendons). + spatial_tendon_mask: Spatial tendon mask. If None, then all the spatial tendons are updated. + Shape is (num_spatial_tendons,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_spatial_tendon_offset_index( + self, + *, + offset: float | torch.Tensor | wp.array, + spatial_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set spatial tendon offset into internal buffers. + + This function does not apply the tendon offset to the simulation. It only fills the buffers with + the desired values. To apply the tendon offset, call the :meth:`write_spatial_tendon_properties_to_sim_index` + function. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + offset: Spatial tendon offset. Shape is (len(env_ids), len(spatial_tendon_ids)). + spatial_tendon_ids: The tendon indices to set the offset for. Defaults to None (all spatial tendons). + env_ids: The environment indices to set the offset for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def set_spatial_tendon_offset_mask( + self, + *, + offset: float | torch.Tensor | wp.array, + spatial_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set spatial tendon offset into internal buffers. + + This function does not apply the tendon offset to the simulation. It only fills the buffers with + the desired values. To apply the tendon offset, call the :meth:`write_spatial_tendon_properties_to_sim_mask` + function. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + offset: Spatial tendon offset. Shape is (num_instances, num_spatial_tendons). + spatial_tendon_mask: Spatial tendon mask. If None, then all the spatial tendons are updated. + Shape is (num_spatial_tendons,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_spatial_tendon_properties_to_sim_index( + self, + *, + spatial_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Write spatial tendon properties into the simulation. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + spatial_tendon_ids: The spatial tendon indices to set the properties for. Defaults to None + (all spatial tendons). + env_ids: The environment indices to set the properties for. Defaults to None (all instances). + """ + raise NotImplementedError() + + @abstractmethod + def write_spatial_tendon_properties_to_sim_mask( + self, + *, + spatial_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write spatial tendon properties into the simulation. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + spatial_tendon_mask: Spatial tendon mask. If None, then all the spatial tendons are updated. + Shape is (num_spatial_tendons,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + """ + Internal helper. + """ + + @abstractmethod + def _initialize_impl(self) -> None: + raise NotImplementedError() + + @abstractmethod + def _create_buffers(self) -> None: + raise NotImplementedError() + + @abstractmethod + def _process_cfg(self) -> None: + """Post processing of configuration parameters.""" + raise NotImplementedError() + + """ + Internal simulation callbacks. + """ + + @abstractmethod + def _invalidate_initialize_callback(self, event) -> None: + """Invalidates the scene elements.""" + super()._invalidate_initialize_callback(event) + + """ + Internal helpers -- Actuators. + """ + + @abstractmethod + def _process_actuators_cfg(self) -> None: + """Process and apply articulation joint properties.""" + raise NotImplementedError() + + @abstractmethod + def _process_tendons(self) -> None: + """Process fixed and spatial tendons.""" + raise NotImplementedError() + + @abstractmethod + def _apply_actuator_model(self) -> None: + """Processes joint commands for the articulation by forwarding them to the actuators. + + The actions are first processed using actuator models. Depending on the robot configuration, + the actuator models compute the joint level simulation commands and sets them into the PhysX buffers. + """ + raise NotImplementedError() + + """ + Internal helpers -- Debugging. + """ + + @abstractmethod + def _validate_cfg(self) -> None: + """Validate the configuration after processing. + + .. note:: + This function should be called only after the configuration has been processed and the buffers have been + created. Otherwise, some settings that are altered during processing may not be validated. + For instance, the actuator models may change the joint max velocity limits. + """ + raise NotImplementedError() + + @abstractmethod + def _log_articulation_info(self) -> None: + """Log information about the articulation. + + .. note:: + We purposefully read the values from the simulator to ensure that the values are configured as expected. + """ + raise NotImplementedError() + + """ + Deprecated methods. + """ + + def write_joint_friction_to_sim( + self, + joint_friction: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Write joint friction coefficients into the simulation. + + .. deprecated:: 2.1.0 + Please use :meth:`write_joint_friction_coefficient_to_sim` instead. + """ + warnings.warn( + "The function 'write_joint_friction_to_sim' will be deprecated in a future release. Please" + " use 'write_joint_friction_coefficient_to_sim' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_joint_friction_coefficient_to_sim(joint_friction, joint_ids=joint_ids, env_ids=env_ids) + + def write_joint_limits_to_sim( + self, + limits: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + warn_limit_violation: bool = True, + ) -> None: + """Write joint limits into the simulation. + + .. deprecated:: 2.1.0 + Please use :meth:`write_joint_position_limit_to_sim` instead. + """ + warnings.warn( + "The function 'write_joint_limits_to_sim' will be deprecated in a future release. Please" + " use 'write_joint_position_limit_to_sim' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_joint_position_limit_to_sim( + limits, + joint_ids=joint_ids, + env_ids=env_ids, + warn_limit_violation=warn_limit_violation, + ) + + def set_fixed_tendon_limit( + self, + limit: torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set fixed tendon position limits into internal buffers. + + .. deprecated:: 2.1.0 + Please use :meth:`set_fixed_tendon_position_limit` instead. + """ + warnings.warn( + "The function 'set_fixed_tendon_limit' will be deprecated in a future release. Please" + " use 'set_fixed_tendon_position_limit' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_fixed_tendon_position_limit( + limit, + fixed_tendon_ids=fixed_tendon_ids, + env_ids=env_ids, + ) + + @abstractmethod + def write_root_state_to_sim( + self, + root_state: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_pose_to_sim_index` and :meth:`write_root_velocity_to_sim_index`.""" + raise NotImplementedError() + + @abstractmethod + def write_root_com_state_to_sim( + self, + root_state: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_com_pose_to_sim_index` and :meth:`write_root_velocity_to_sim_index`.""" + raise NotImplementedError() + + @abstractmethod + def write_root_link_state_to_sim( + self, + root_state: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_pose_to_sim_index` and + :meth:`write_root_link_velocity_to_sim_index`.""" + raise NotImplementedError() + + def write_root_pose_to_sim( + self, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_pose_to_sim_index`.""" + warnings.warn( + "The function 'write_root_pose_to_sim' will be deprecated in a future release. Please" + " use 'write_root_pose_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_root_pose_to_sim_index(root_pose=root_pose, env_ids=env_ids) + + def write_root_link_pose_to_sim( + self, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_link_pose_to_sim_index`.""" + warnings.warn( + "The function 'write_root_link_pose_to_sim' will be deprecated in a future release. Please" + " use 'write_root_link_pose_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_root_link_pose_to_sim_index(root_pose=root_pose, env_ids=env_ids) + + def write_root_com_pose_to_sim( + self, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_com_pose_to_sim_index`.""" + warnings.warn( + "The function 'write_root_com_pose_to_sim' will be deprecated in a future release. Please" + " use 'write_root_com_pose_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_root_com_pose_to_sim_index(root_pose=root_pose, env_ids=env_ids) + + def write_root_velocity_to_sim( + self, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_velocity_to_sim_index`.""" + warnings.warn( + "The function 'write_root_velocity_to_sim' will be deprecated in a future release. Please" + " use 'write_root_velocity_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_root_velocity_to_sim_index(root_velocity=root_velocity, env_ids=env_ids) + + def write_root_com_velocity_to_sim( + self, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_com_velocity_to_sim_index`.""" + warnings.warn( + "The function 'write_root_com_velocity_to_sim' will be deprecated in a future release. Please" + " use 'write_root_com_velocity_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_root_com_velocity_to_sim_index(root_velocity=root_velocity, env_ids=env_ids) + + def write_root_link_velocity_to_sim( + self, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_link_velocity_to_sim_index`.""" + warnings.warn( + "The function 'write_root_link_velocity_to_sim' will be deprecated in a future release. Please" + " use 'write_root_link_velocity_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_root_link_velocity_to_sim_index(root_velocity=root_velocity, env_ids=env_ids) + + @abstractmethod + def write_joint_state_to_sim( + self, + position: torch.Tensor | wp.array, + velocity: torch.Tensor | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | slice | None = None, + ) -> None: + """Deprecated, same as :meth:`write_joint_position_to_sim_index` and + :meth:`write_joint_velocity_to_sim_index`.""" + raise NotImplementedError() + + def write_joint_position_to_sim( + self, + position: torch.Tensor | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | slice | None = None, + ) -> None: + """Deprecated, same as :meth:`write_joint_position_to_sim_index`.""" + warnings.warn( + "The function 'write_joint_position_to_sim' will be deprecated in a future release. Please" + " use 'write_joint_position_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_joint_position_to_sim_index(position=position, joint_ids=joint_ids, env_ids=env_ids) + + def write_joint_velocity_to_sim( + self, + velocity: torch.Tensor | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | slice | None = None, + ) -> None: + """Deprecated, same as :meth:`write_joint_velocity_to_sim_index`.""" + warnings.warn( + "The function 'write_joint_velocity_to_sim' will be deprecated in a future release. Please" + " use 'write_joint_velocity_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_joint_velocity_to_sim_index(velocity=velocity, joint_ids=joint_ids, env_ids=env_ids) + + def write_joint_stiffness_to_sim( + self, + stiffness: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_joint_stiffness_to_sim_index`.""" + warnings.warn( + "The function 'write_joint_stiffness_to_sim' will be deprecated in a future release. Please" + " use 'write_joint_stiffness_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_joint_stiffness_to_sim_index(stiffness=stiffness, joint_ids=joint_ids, env_ids=env_ids) + + def write_joint_damping_to_sim( + self, + damping: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_joint_damping_to_sim_index`.""" + warnings.warn( + "The function 'write_joint_damping_to_sim' will be deprecated in a future release. Please" + " use 'write_joint_damping_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_joint_damping_to_sim_index(damping=damping, joint_ids=joint_ids, env_ids=env_ids) + + def write_joint_position_limit_to_sim( + self, + limits: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + warn_limit_violation: bool = True, + ) -> None: + """Deprecated, same as :meth:`write_joint_position_limit_to_sim_index`.""" + warnings.warn( + "The function 'write_joint_position_limit_to_sim' will be deprecated in a future release. Please" + " use 'write_joint_position_limit_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_joint_position_limit_to_sim_index( + limits=limits, joint_ids=joint_ids, env_ids=env_ids, warn_limit_violation=warn_limit_violation + ) + + def write_joint_velocity_limit_to_sim( + self, + limits: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_joint_velocity_limit_to_sim_index`.""" + warnings.warn( + "The function 'write_joint_velocity_limit_to_sim' will be deprecated in a future release. Please" + " use 'write_joint_velocity_limit_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_joint_velocity_limit_to_sim_index(limits=limits, joint_ids=joint_ids, env_ids=env_ids) + + def write_joint_effort_limit_to_sim( + self, + limits: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_joint_effort_limit_to_sim_index`.""" + warnings.warn( + "The function 'write_joint_effort_limit_to_sim' will be deprecated in a future release. Please" + " use 'write_joint_effort_limit_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_joint_effort_limit_to_sim_index(limits=limits, joint_ids=joint_ids, env_ids=env_ids) + + def write_joint_armature_to_sim( + self, + armature: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_joint_armature_to_sim_index`.""" + warnings.warn( + "The function 'write_joint_armature_to_sim' will be deprecated in a future release. Please" + " use 'write_joint_armature_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_joint_armature_to_sim_index(armature=armature, joint_ids=joint_ids, env_ids=env_ids) + + def write_joint_friction_coefficient_to_sim( + self, + joint_friction_coeff: torch.Tensor | float | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_joint_friction_coefficient_to_sim_index`.""" + warnings.warn( + "The function 'write_joint_friction_coefficient_to_sim' will be deprecated in a future release. Please" + " use 'write_joint_friction_coefficient_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_joint_friction_coefficient_to_sim_index( + joint_friction_coeff=joint_friction_coeff, joint_ids=joint_ids, env_ids=env_ids + ) + + def set_masses( + self, + masses: torch.Tensor | wp.array, + body_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_masses_index`.""" + warnings.warn( + "The function 'set_masses' will be deprecated in a future release. Please use 'set_masses_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_masses_index(masses=masses, body_ids=body_ids, env_ids=env_ids) + + def set_coms( + self, + coms: torch.Tensor | wp.array, + body_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_coms_index`.""" + warnings.warn( + "The function 'set_coms' will be deprecated in a future release. Please use 'set_coms_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_coms_index(coms=coms, body_ids=body_ids, env_ids=env_ids) + + def set_inertias( + self, + inertias: torch.Tensor | wp.array, + body_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_inertias_index`.""" + warnings.warn( + "The function 'set_inertias' will be deprecated in a future release. Please" + " use 'set_inertias_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_inertias_index(inertias=inertias, body_ids=body_ids, env_ids=env_ids) + + def set_external_force_and_torque( + self, + forces: torch.Tensor | wp.array, + torques: torch.Tensor | wp.array, + positions: torch.Tensor | wp.array | None = None, + body_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + is_global: bool = False, + ) -> None: + """Deprecated. Resets target environments, then adds forces and torques via the permanent wrench composer.""" + warnings.warn( + "The function 'set_external_force_and_torque' is deprecated. Please use" + " 'permanent_wrench_composer.reset' followed by 'permanent_wrench_composer.add_forces_and_torques'" + " instead.", + DeprecationWarning, + stacklevel=2, + ) + # Reset only target env_ids then add (not set which clears all envs globally) + self.permanent_wrench_composer.reset(env_ids=env_ids) + self.permanent_wrench_composer.add_forces_and_torques( + forces, torques, positions=positions, body_ids=body_ids, env_ids=env_ids, is_global=is_global + ) + + def set_joint_position_target( + self, + target: torch.Tensor | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_joint_position_target_index`.""" + warnings.warn( + "The function 'set_joint_position_target' will be deprecated in a future release. Please" + " use 'set_joint_position_target_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_joint_position_target_index(target=target, joint_ids=joint_ids, env_ids=env_ids) + + def set_joint_velocity_target( + self, + target: torch.Tensor | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_joint_velocity_target_index`.""" + warnings.warn( + "The function 'set_joint_velocity_target' will be deprecated in a future release. Please" + " use 'set_joint_velocity_target_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_joint_velocity_target_index(target=target, joint_ids=joint_ids, env_ids=env_ids) + + def set_joint_effort_target( + self, + target: torch.Tensor | wp.array, + joint_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_joint_effort_target_index`.""" + warnings.warn( + "The function 'set_joint_effort_target' will be deprecated in a future release. Please" + " use 'set_joint_effort_target_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_joint_effort_target_index(target=target, joint_ids=joint_ids, env_ids=env_ids) + + def set_fixed_tendon_stiffness( + self, + stiffness: torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_fixed_tendon_stiffness_index`.""" + warnings.warn( + "The function 'set_fixed_tendon_stiffness' will be deprecated in a future release. Please" + " use 'set_fixed_tendon_stiffness_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_fixed_tendon_stiffness_index(stiffness=stiffness, fixed_tendon_ids=fixed_tendon_ids, env_ids=env_ids) + + def set_fixed_tendon_damping( + self, + damping: torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_fixed_tendon_damping_index`.""" + warnings.warn( + "The function 'set_fixed_tendon_damping' will be deprecated in a future release. Please" + " use 'set_fixed_tendon_damping_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_fixed_tendon_damping_index(damping=damping, fixed_tendon_ids=fixed_tendon_ids, env_ids=env_ids) + + def set_fixed_tendon_limit_stiffness( + self, + limit_stiffness: torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_fixed_tendon_limit_stiffness_index`.""" + warnings.warn( + "The function 'set_fixed_tendon_limit_stiffness' will be deprecated in a future release. Please" + " use 'set_fixed_tendon_limit_stiffness_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_fixed_tendon_limit_stiffness_index( + limit_stiffness=limit_stiffness, fixed_tendon_ids=fixed_tendon_ids, env_ids=env_ids + ) + + def set_fixed_tendon_position_limit( + self, + limit: torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_fixed_tendon_position_limit_index`.""" + warnings.warn( + "The function 'set_fixed_tendon_position_limit' will be deprecated in a future release. Please" + " use 'set_fixed_tendon_position_limit_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_fixed_tendon_position_limit_index(limit=limit, fixed_tendon_ids=fixed_tendon_ids, env_ids=env_ids) + + def set_fixed_tendon_rest_length( + self, + rest_length: torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_fixed_tendon_rest_length_index`.""" + warnings.warn( + "The function 'set_fixed_tendon_rest_length' will be deprecated in a future release. Please" + " use 'set_fixed_tendon_rest_length_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_fixed_tendon_rest_length_index( + rest_length=rest_length, fixed_tendon_ids=fixed_tendon_ids, env_ids=env_ids + ) + + def set_fixed_tendon_offset( + self, + offset: torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_fixed_tendon_offset_index`.""" + warnings.warn( + "The function 'set_fixed_tendon_offset' will be deprecated in a future release. Please" + " use 'set_fixed_tendon_offset_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_fixed_tendon_offset_index(offset=offset, fixed_tendon_ids=fixed_tendon_ids, env_ids=env_ids) + + def write_fixed_tendon_properties_to_sim( + self, + fixed_tendon_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_fixed_tendon_properties_to_sim_index`.""" + warnings.warn( + "The function 'write_fixed_tendon_properties_to_sim' will be deprecated in a future release. Please" + " use 'write_fixed_tendon_properties_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + # Removing the fixed tendon ids argument as it is not used. + self.write_fixed_tendon_properties_to_sim_index(env_ids=env_ids) + + def set_spatial_tendon_stiffness( + self, + stiffness: torch.Tensor | wp.array, + spatial_tendon_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_spatial_tendon_stiffness_index`.""" + warnings.warn( + "The function 'set_spatial_tendon_stiffness' will be deprecated in a future release. Please" + " use 'set_spatial_tendon_stiffness_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_spatial_tendon_stiffness_index( + stiffness=stiffness, spatial_tendon_ids=spatial_tendon_ids, env_ids=env_ids + ) + + def set_spatial_tendon_damping( + self, + damping: torch.Tensor | wp.array, + spatial_tendon_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_spatial_tendon_damping_index`.""" + warnings.warn( + "The function 'set_spatial_tendon_damping' will be deprecated in a future release. Please" + " use 'set_spatial_tendon_damping_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_spatial_tendon_damping_index(damping=damping, spatial_tendon_ids=spatial_tendon_ids, env_ids=env_ids) + + def set_spatial_tendon_limit_stiffness( + self, + limit_stiffness: torch.Tensor | wp.array, + spatial_tendon_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_spatial_tendon_limit_stiffness_index`.""" + warnings.warn( + "The function 'set_spatial_tendon_limit_stiffness' will be deprecated in a future release. Please" + " use 'set_spatial_tendon_limit_stiffness_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_spatial_tendon_limit_stiffness_index( + limit_stiffness=limit_stiffness, spatial_tendon_ids=spatial_tendon_ids, env_ids=env_ids + ) + + def set_spatial_tendon_offset( + self, + offset: torch.Tensor, + spatial_tendon_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_spatial_tendon_offset_index`.""" + warnings.warn( + "The function 'set_spatial_tendon_offset' will be deprecated in a future release. Please" + " use 'set_spatial_tendon_offset_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_spatial_tendon_offset_index(offset=offset, spatial_tendon_ids=spatial_tendon_ids, env_ids=env_ids) + + def write_spatial_tendon_properties_to_sim( + self, + spatial_tendon_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_spatial_tendon_properties_to_sim_index`.""" + warnings.warn( + "The function 'write_spatial_tendon_properties_to_sim' will be deprecated in a future release. Please" + " use 'write_spatial_tendon_properties_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + # Removing the spatial tendon ids argument as it is not used. + self.write_spatial_tendon_properties_to_sim_index(env_ids=env_ids) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/base_articulation_data.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/base_articulation_data.py new file mode 100644 index 0000000000000000000000000000000000000000..894bb6bd8f44dd66e9895bdad01f5fecb08f970c --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/base_articulation_data.py @@ -0,0 +1,1590 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from abc import ABC, abstractmethod + +import warp as wp + +from isaaclab.utils.leapp import ( + POSE6_ELEMENT_NAMES, + POSE7_ELEMENT_NAMES, + QUAT_XYZW_ELEMENT_NAMES, + XYZ_ELEMENT_NAMES, + InputKindEnum, + body_pose6_resolver, + body_pose_resolver, + body_quat_resolver, + body_xyz_resolver, + joint_names_resolver, + leapp_tensor_semantics, +) +from isaaclab.utils.warp import ProxyArray + + +class BaseArticulationData(ABC): + """Data container for an articulation. + + This class contains the data for an articulation in the simulation. The data includes the state of + the root rigid body, the state of all the bodies in the articulation, and the joint state. The data is + stored in the simulation world frame unless otherwise specified. + + An articulation is comprised of multiple rigid bodies or links. For a rigid body, there are two frames + of reference that are used: + + - Actor frame: The frame of reference of the rigid body prim. This typically corresponds to the Xform prim + with the rigid body schema. + - Center of mass frame: The frame of reference of the center of mass of the rigid body. + + Depending on the settings, the two frames may not coincide with each other. In the robotics sense, the actor frame + can be interpreted as the link frame. + """ + + def __init__(self, root_view, device: str): + """Initializes the articulation data. + + Args: + root_view: The root articulation view. + device: The device used for processing. + """ + # Set the parameters + self.device = device + + @abstractmethod + def update(self, dt: float) -> None: + raise NotImplementedError + + ## + # Names. + ## + + body_names: list[str] | None = None + """Body names in the order parsed by the simulation view.""" + + joint_names: list[str] | None = None + """Joint names in the order parsed by the simulation view.""" + + fixed_tendon_names: list[str] | None = None + """Fixed tendon names in the order parsed by the simulation view.""" + + spatial_tendon_names: list[str] | None = None + """Spatial tendon names in the order parsed by the simulation view.""" + + ## + # Defaults - Initial state. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def default_root_pose(self) -> ProxyArray: + """Default root pose ``[pos, quat]`` in the local environment frame. + + The position and quaternion are of the articulation root's actor frame. Shape is (num_instances), + dtype = wp.transformf. In torch this resolves to (num_instances, 7). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def default_root_vel(self) -> ProxyArray: + """Default root velocity ``[lin_vel, ang_vel]`` in the local environment frame. + + The linear and angular velocities are of the articulation root's center of mass frame. + Shape is (num_instances), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def default_root_state(self) -> ProxyArray: + """Deprecated, same as :attr:`default_root_pose` and :attr:`default_root_vel`.""" + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def default_joint_pos(self) -> ProxyArray: + """Default joint positions of all joints. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + + This quantity is configured through the :attr:`isaaclab.assets.ArticulationCfg.init_state` parameter. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def default_joint_vel(self) -> ProxyArray: + """Default joint velocities of all joints. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + + This quantity is configured through the :attr:`isaaclab.assets.ArticulationCfg.init_state` parameter. + """ + raise NotImplementedError + + ## + # Joint commands -- Set into simulation. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.COMMAND_JOINT_POSITION) + def joint_pos_target(self) -> ProxyArray: + """Joint position targets commanded by the user. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + + For an implicit actuator model, the targets are directly set into the simulation. + For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`), + which are then set into the simulation. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.COMMAND_JOINT_VELOCITY) + def joint_vel_target(self) -> ProxyArray: + """Joint velocity targets commanded by the user. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + + For an implicit actuator model, the targets are directly set into the simulation. + For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`), + which are then set into the simulation. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.COMMAND_JOINT_TORQUES) + def joint_effort_target(self) -> ProxyArray: + """Joint effort targets commanded by the user. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + + For an implicit actuator model, the targets are directly set into the simulation. + For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`), + which are then set into the simulation. + """ + raise NotImplementedError + + ## + # Joint commands -- Explicit actuators. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/joint/computed_torque") + def computed_torque(self) -> ProxyArray: + """Joint torques computed from the actuator model (before clipping). + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + + This quantity is the raw torque output from the actuator mode, before any clipping is applied. + It is exposed for users who want to inspect the computations inside the actuator model. + For instance, to penalize the learning agent for a difference between the computed and applied torques. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/joint/applied_torque") + def applied_torque(self) -> ProxyArray: + """Joint torques applied from the actuator model (after clipping). + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + + These torques are set into the simulation, after clipping the :attr:`computed_torque` based on the + actuator model. + """ + raise NotImplementedError + + ## + # Joint properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def joint_stiffness(self) -> ProxyArray: + """Joint stiffness provided to the simulation. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + + In the case of explicit actuators, the value for the corresponding joints is zero. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def joint_damping(self) -> ProxyArray: + """Joint damping provided to the simulation. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + + In the case of explicit actuators, the value for the corresponding joints is zero. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def joint_armature(self) -> ProxyArray: + """Joint armature provided to the simulation. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def joint_friction_coeff(self) -> ProxyArray: + """Backend-specific joint friction values provided to the simulation. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + + .. warning:: + The physical meaning and units of this value depend on the concrete backend and solver. Do not assume + values are comparable across backends; check the backend-specific :class:`ArticulationData` + implementation before interpreting or reusing them. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def joint_pos_limits(self) -> ProxyArray: + """Joint position limits provided to the simulation. + + Shape is (num_instances, num_joints, 2), dtype = wp.vec2f. In torch this resolves to + (num_instances, num_joints, 2). + + The limits are in the order :math:`[lower, upper]`. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def joint_vel_limits(self) -> ProxyArray: + """Joint maximum velocity provided to the simulation. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def joint_effort_limits(self) -> ProxyArray: + """Joint maximum effort provided to the simulation. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + """ + raise NotImplementedError + + ## + # Joint properties - Custom. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def soft_joint_pos_limits(self) -> ProxyArray: + r"""Soft joint positions limits for all joints. + + Shape is (num_instances, num_joints), dtype = wp.vec2f. In torch this resolves to + (num_instances, num_joints, 2). + + The limits are in the order :math:`[lower, upper]`.The soft joint position limits are computed as + a sub-region of the :attr:`joint_pos_limits` based on the + :attr:`~isaaclab.assets.ArticulationCfg.soft_joint_pos_limit_factor` parameter. + + Consider the joint position limits :math:`[lower, upper]` and the soft joint position limits + :math:`[soft_lower, soft_upper]`. The soft joint position limits are computed as: + + .. math:: + + soft\_lower = (lower + upper) / 2 - factor * (upper - lower) / 2 + soft\_upper = (lower + upper) / 2 + factor * (upper - lower) / 2 + + The soft joint position limits help specify a safety region around the joint limits. It isn't used by the + simulation, but is useful for learning agents to prevent the joint positions from violating the limits. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def soft_joint_vel_limits(self) -> ProxyArray: + """Soft joint velocity limits for all joints. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + + These are obtained from the actuator model. It may differ from :attr:`joint_vel_limits` if the actuator model + has a variable velocity limit model. For instance, in a variable gear ratio actuator model. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def gear_ratio(self) -> ProxyArray: + """Gear ratio for relating motor torques to applied Joint torques. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). + """ + raise NotImplementedError + + ## + # Fixed tendon properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def fixed_tendon_stiffness(self) -> ProxyArray: + """Fixed tendon stiffness provided to the simulation. + + Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_fixed_tendons). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def fixed_tendon_damping(self) -> ProxyArray: + """Fixed tendon damping provided to the simulation. + + Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_fixed_tendons). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def fixed_tendon_limit_stiffness(self) -> ProxyArray: + """Fixed tendon limit stiffness provided to the simulation. + + Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_fixed_tendons). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def fixed_tendon_rest_length(self) -> ProxyArray: + """Fixed tendon rest length provided to the simulation. + + Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_fixed_tendons). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def fixed_tendon_offset(self) -> ProxyArray: + """Fixed tendon offset provided to the simulation. + + Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_fixed_tendons). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def fixed_tendon_pos_limits(self) -> ProxyArray: + """Fixed tendon position limits provided to the simulation. + + Shape is (num_instances, num_fixed_tendons, 2), dtype = wp.vec2f. In torch this resolves to + (num_instances, num_fixed_tendons, 2). + """ + raise NotImplementedError + + ## + # Spatial tendon properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def spatial_tendon_stiffness(self) -> ProxyArray: + """Spatial tendon stiffness provided to the simulation. + + Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_spatial_tendons). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def spatial_tendon_damping(self) -> ProxyArray: + """Spatial tendon damping provided to the simulation. + + Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_spatial_tendons). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def spatial_tendon_limit_stiffness(self) -> ProxyArray: + """Spatial tendon limit stiffness provided to the simulation. + + Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_spatial_tendons). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def spatial_tendon_offset(self) -> ProxyArray: + """Spatial tendon offset provided to the simulation. + + Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_spatial_tendons). + """ + raise NotImplementedError + + ## + # Root state properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def root_link_pose_w(self) -> ProxyArray: + """Root link pose ``[pos, quat]`` in simulation world frame. + + Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). + + This quantity is the pose of the articulation root's actor frame relative to the world. + The orientation is provided in (x, y, z, w) format. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names=POSE6_ELEMENT_NAMES) + def root_link_vel_w(self) -> ProxyArray: + """Root link velocity ``[lin_vel, ang_vel]`` in simulation world frame. + + Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). + + This quantity contains the linear and angular velocities of the articulation root's actor frame + relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def root_com_pose_w(self) -> ProxyArray: + """Root center of mass pose ``[pos, quat]`` in simulation world frame. + + Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). + + This quantity is the pose of the articulation root's center of mass frame relative to the world. + The orientation is provided in (x, y, z, w) format. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names=POSE6_ELEMENT_NAMES) + def root_com_vel_w(self) -> ProxyArray: + """Root center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. + + Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). + + This quantity contains the linear and angular velocities of the articulation root's center of mass frame + relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/state") + def root_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_com_vel_w`.""" + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/link_state") + def root_link_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_link_vel_w`.""" + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/com_state") + def root_com_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`root_com_pose_w` and :attr:`root_com_vel_w`.""" + raise NotImplementedError + + ## + # Body state properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def body_mass(self) -> ProxyArray: + """Body mass ``wp.float32`` in the world frame. + + Shape is (num_instances, num_bodies), dtype = wp.float32. In torch this resolves to (num_instances, num_bodies). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def body_inertia(self) -> ProxyArray: + """Flattened body inertia in the world frame. + + Shape is (num_instances, num_bodies, 9), dtype = wp.float32. In torch this resolves to + (num_instances, num_bodies, 9). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_link_pose_w(self) -> ProxyArray: + """Body link pose ``[pos, quat]`` in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to + (num_instances, num_bodies, 7). + + This quantity is the pose of the articulation links' actor frame relative to the world. + The orientation is provided in (x, y, z, w) format. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_link_vel_w(self) -> ProxyArray: + """Body link velocity ``[lin_vel, ang_vel]`` in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to + (num_instances, num_bodies, 6). + + This quantity contains the linear and angular velocities of the articulation links' actor frame + relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_com_pose_w(self) -> ProxyArray: + """Body center of mass pose ``[pos, quat]`` in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to + (num_instances, num_bodies, 7). + + This quantity is the pose of the center of mass frame of the articulation links relative to the world. + The orientation is provided in (x, y, z, w) format. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_com_vel_w(self) -> ProxyArray: + """Body center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to + (num_instances, num_bodies, 6). + + This quantity contains the linear and angular velocities of the articulation links' center of mass frame + relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/state") + def body_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_com_vel_w`.""" + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/link_state") + def body_link_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_link_vel_w`.""" + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/com_state") + def body_com_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`body_com_pose_w` and :attr:`body_com_vel_w`.""" + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def body_com_acc_w(self) -> ProxyArray: + """Acceleration of all bodies center of mass ``[lin_acc, ang_acc]``. + + Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to + (num_instances, num_bodies, 6). + + All values are relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_com_pose_b(self) -> ProxyArray: + """Center of mass pose ``[pos, quat]`` of all bodies in their respective body's link frames. + + Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to + (num_instances, num_bodies, 7). + + This quantity is the pose of the center of mass frame of the rigid body relative to the body's link frame. + The orientation is provided in (x, y, z, w) format. + """ + raise NotImplementedError + + ## + # Dynamics quantities (task-space controllers). + ## + + @property + def body_link_jacobian_w(self) -> ProxyArray: + """Per-body geometric Jacobian referenced at each body's link origin in world frame. + + Shape: ``(num_instances, num_jacobi_bodies, 6, num_joints + num_base_dofs)``, + dtype ``wp.float32``. Linear rows ``[0:3]`` [m/s per unit DoF velocity]; + angular rows ``[3:6]`` [rad/s per unit DoF velocity]. + + Contract: for any generalized velocity ``v`` of length + ``num_joints + num_base_dofs``, + + .. code-block:: text + + J[:, jacobi_body_idx, 0:3, :] @ v == body_link_lin_vel_w[:, body_idx] + J[:, jacobi_body_idx, 3:6, :] @ v == body_link_ang_vel_w[:, body_idx] + + Conventions: + * Body axis: ``jacobi_body_idx == body_idx - 1`` for fixed-base (fixed-root + row excluded); ``jacobi_body_idx == body_idx`` for floating-base. + * DoF axis: leading + :attr:`~isaaclab.assets.BaseArticulation.num_base_dofs` floating-base + columns (world-frame ``[lin_x, lin_y, lin_z, ang_x, ang_y, ang_z]``), + then actuated-joint columns in :attr:`joint_names` order. + """ + raise NotImplementedError(f"{type(self).__name__} does not implement body_link_jacobian_w.") + + @property + def body_com_jacobian_w(self) -> ProxyArray: + """Per-body geometric Jacobian referenced at each body's center of mass in world frame. + + Same shape and indexing conventions as :attr:`body_link_jacobian_w`. Linear + rows ``[0:3]`` give the velocity at the body's center of mass; angular rows + ``[3:6]`` are reference-point invariant (identical to + :attr:`body_link_jacobian_w`). + + Contract: for any generalized velocity ``v``, + + .. code-block:: text + + J[:, jacobi_body_idx, 0:3, :] @ v == body_com_lin_vel_w[:, body_idx] + J[:, jacobi_body_idx, 3:6, :] @ v == body_com_ang_vel_w[:, body_idx] + """ + raise NotImplementedError(f"{type(self).__name__} does not implement body_com_jacobian_w.") + + @property + def mass_matrix(self) -> ProxyArray: + """Per-env generalized mass matrix ``M(q)`` in joint space. + + Shape: ``(num_instances, num_joints + num_base_dofs, num_joints + num_base_dofs)``, + dtype ``wp.float32`` [kg·m² or kg, per DoF type]. DoF-axis convention matches + :attr:`body_link_jacobian_w`. + + ``M(q)`` is symmetric positive-definite. ``M[i, j]`` is the coefficient + relating DoF ``j``'s acceleration to the inertial torque on DoF ``i`` in + ``M(q) q_ddot + C(q, q_dot) q_dot + g(q) = tau``. + """ + raise NotImplementedError(f"{type(self).__name__} does not implement mass_matrix.") + + @property + def gravity_compensation_forces(self) -> ProxyArray: + """Per-env gravity compensation torques ``g(q)`` in joint space. + + Shape: ``(num_instances, num_joints + num_base_dofs)``, dtype ``wp.float32`` + [N·m or N, per DoF type]. DoF-axis convention matches + :attr:`body_link_jacobian_w`. + + ``g(q)`` is the gravity-loading term in + ``M(q) q_ddot + C(q, q_dot) q_dot + g(q) = tau``. Applying ``tau = g(q)`` at + ``q_dot = 0`` with no external load yields ``q_ddot = 0`` (static equilibrium + under gravity). + """ + raise NotImplementedError(f"{type(self).__name__} does not implement gravity_compensation_forces.") + + ## + # Joint state properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.JOINT_POSITION, element_names_resolver=joint_names_resolver) + def joint_pos(self) -> ProxyArray: + """Joint positions of all joints. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.JOINT_VELOCITY, element_names_resolver=joint_names_resolver) + def joint_vel(self) -> ProxyArray: + """Joint velocities of all joints. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/joint/acceleration", element_names_resolver=joint_names_resolver) + def joint_acc(self) -> ProxyArray: + """Joint acceleration of all joints. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + """ + raise NotImplementedError + + ## + # Derived Properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.VECTOR3D, element_names=XYZ_ELEMENT_NAMES) + def projected_gravity_b(self) -> ProxyArray: + """Projection of the gravity direction on base frame. + + Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/heading") + def heading_w(self) -> ProxyArray: + """Yaw heading of the base frame (in radians). + + Shape is (num_instances), dtype = wp.float32. In torch this resolves to (num_instances,). + + .. note:: + This quantity is computed by assuming that the forward-direction of the base + frame is along x-direction, i.e. :math:`(1, 0, 0)`. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_lin_vel_b(self) -> ProxyArray: + """Root link linear velocity in base frame. + + Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the linear velocity of the articulation root's actor frame with respect to + its actor frame. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_ang_vel_b(self) -> ProxyArray: + """Root link angular velocity in base frame. + + Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the angular velocity of the articulation root's actor frame with respect to + its actor frame. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_lin_vel_b(self) -> ProxyArray: + """Root center of mass linear velocity in base frame. + + Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the linear velocity of the articulation root's center of mass frame with respect to + its actor frame. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_ang_vel_b(self) -> ProxyArray: + """Root center of mass angular velocity in base frame. + + Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the angular velocity of the articulation root's center of mass frame with respect to + its actor frame. + """ + raise NotImplementedError + + ## + # Sliced properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def root_link_pos_w(self) -> ProxyArray: + """Root link position in simulation world frame. + + Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the position of the actor frame of the root rigid body relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def root_link_quat_w(self) -> ProxyArray: + """Root link orientation (x, y, z, w) in simulation world frame. + + Shape is (num_instances), dtype = wp.quatf. In torch this resolves to (num_instances, 4). + + This quantity is the orientation of the actor frame of the root rigid body. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_lin_vel_w(self) -> ProxyArray: + """Root linear velocity in simulation world frame. + + Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the linear velocity of the root rigid body's actor frame relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_ang_vel_w(self) -> ProxyArray: + """Root link angular velocity in simulation world frame. + + Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the angular velocity of the actor frame of the root rigid body relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def root_com_pos_w(self) -> ProxyArray: + """Root center of mass position in simulation world frame. + + Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the position of the center of mass frame of the root rigid body relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def root_com_quat_w(self) -> ProxyArray: + """Root center of mass orientation (x, y, z, w) in simulation world frame. + + Shape is (num_instances), dtype = wp.quatf. In torch this resolves to (num_instances, 4). + + This quantity is the orientation of the principal axes of inertia of the root rigid body relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_lin_vel_w(self) -> ProxyArray: + """Root center of mass linear velocity in simulation world frame. + + Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the linear velocity of the root rigid body's center of mass frame relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_ang_vel_w(self) -> ProxyArray: + """Root center of mass angular velocity in simulation world frame. + + Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the angular velocity of the root rigid body's center of mass frame relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_link_pos_w(self) -> ProxyArray: + """Positions of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the position of the articulation bodies' actor frame relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_link_quat_w(self) -> ProxyArray: + """Orientation (x, y, z, w) of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to + (num_instances, num_bodies, 4). + + This quantity is the orientation of the articulation bodies' actor frame relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_lin_vel_w(self) -> ProxyArray: + """Linear velocity of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the linear velocity of the articulation bodies' actor frame relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_ang_vel_w(self) -> ProxyArray: + """Angular velocity of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the angular velocity of the articulation bodies' actor frame relative to the world. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_com_pos_w(self) -> ProxyArray: + """Positions of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the position of the articulation bodies' center of mass frame. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_com_quat_w(self) -> ProxyArray: + """Orientation (x, y, z, w) of the principal axes of inertia of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to + (num_instances, num_bodies, 4). + + This quantity is the orientation of the principal axes of inertia of the articulation bodies. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_lin_vel_w(self) -> ProxyArray: + """Linear velocity of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the linear velocity of the articulation bodies' center of mass frame. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_ang_vel_w(self) -> ProxyArray: + """Angular velocity of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the angular velocity of the articulation bodies' center of mass frame. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_com_lin_acc_w(self) -> ProxyArray: + """Linear acceleration of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the linear acceleration of the articulation bodies' center of mass frame. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_com_ang_acc_w(self) -> ProxyArray: + """Angular acceleration of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the angular acceleration of the articulation bodies' center of mass frame. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_com_pos_b(self) -> ProxyArray: + """Center of mass position of all of the bodies in their respective link frames. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the center of mass location relative to its body's link frame. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_com_quat_b(self) -> ProxyArray: + """Orientation (x, y, z, w) of the principal axes of inertia of all of the bodies in their respective link + frames. + + Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to + (num_instances, num_bodies, 4). + + This quantity is the orientation of the principal axes of inertia relative to its body's link frame. + """ + raise NotImplementedError + + def _create_buffers(self) -> None: + # -- Defaults (Lazy allocation of default values) + self._default_mass = None + self._default_inertia = None + self._default_joint_stiffness = None + self._default_joint_damping = None + self._default_joint_armature = None + self._default_joint_friction_coeff = None + self._default_joint_viscous_friction_coeff = None + self._default_joint_pos_limits = None + self._default_fixed_tendon_stiffness = None + self._default_fixed_tendon_damping = None + self._default_fixed_tendon_limit_stiffness = None + self._default_fixed_tendon_rest_length = None + self._default_fixed_tendon_offset = None + self._default_fixed_tendon_pos_limits = None + self._default_spatial_tendon_stiffness = None + self._default_spatial_tendon_damping = None + self._default_spatial_tendon_limit_stiffness = None + self._default_spatial_tendon_offset = None + + """ + Shorthands for commonly used properties. + """ + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def root_pose_w(self) -> ProxyArray: + """Shorthand for :attr:`root_link_pose_w`.""" + return self.root_link_pose_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def root_pos_w(self) -> ProxyArray: + """Shorthand for :attr:`root_link_pos_w`.""" + return self.root_link_pos_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def root_quat_w(self) -> ProxyArray: + """Shorthand for :attr:`root_link_quat_w`.""" + return self.root_link_quat_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names=POSE6_ELEMENT_NAMES) + def root_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`root_com_vel_w`.""" + return self.root_com_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_lin_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`root_com_lin_vel_w`.""" + return self.root_com_lin_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_ang_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`root_com_ang_vel_w`.""" + return self.root_com_ang_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_lin_vel_b(self) -> ProxyArray: + """Shorthand for :attr:`root_com_lin_vel_b`.""" + return self.root_com_lin_vel_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_ang_vel_b(self) -> ProxyArray: + """Shorthand for :attr:`root_com_ang_vel_b`.""" + return self.root_com_ang_vel_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_pose_w(self) -> ProxyArray: + """Shorthand for :attr:`body_link_pose_w`.""" + return self.body_link_pose_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_pos_w(self) -> ProxyArray: + """Shorthand for :attr:`body_link_pos_w`.""" + return self.body_link_pos_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_quat_w(self) -> ProxyArray: + """Shorthand for :attr:`body_link_quat_w`.""" + return self.body_link_quat_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_vel_w`.""" + return self.body_com_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_lin_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_lin_vel_w`.""" + return self.body_com_lin_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_ang_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_ang_vel_w`.""" + return self.body_com_ang_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def body_acc_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_acc_w`.""" + return self.body_com_acc_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_lin_acc_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_lin_acc_w`.""" + return self.body_com_lin_acc_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_ang_acc_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_ang_acc_w`.""" + return self.body_com_ang_acc_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def com_pos_b(self) -> ProxyArray: + """Shorthand for :attr:`body_com_pos_b`.""" + return self.body_com_pos_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def com_quat_b(self) -> ProxyArray: + """Shorthand for :attr:`body_com_quat_b`.""" + return self.body_com_quat_b + + @property + @leapp_tensor_semantics(const=True) + def joint_limits(self) -> ProxyArray: + """Shorthand for :attr:`joint_pos_limits`.""" + return self.joint_pos_limits + + @property + @leapp_tensor_semantics(const=True) + def default_joint_limits(self) -> ProxyArray: + """Shorthand for :attr:`default_joint_pos_limits`.""" + return self.default_joint_pos_limits + + @property + @leapp_tensor_semantics(const=True) + def joint_velocity_limits(self) -> ProxyArray: + """Shorthand for :attr:`joint_vel_limits`.""" + return self.joint_vel_limits + + @property + @leapp_tensor_semantics(const=True) + def joint_friction(self) -> ProxyArray: + """Shorthand for :attr:`joint_friction_coeff`.""" + return self.joint_friction_coeff + + @property + @leapp_tensor_semantics(const=True) + def fixed_tendon_limit(self) -> ProxyArray: + """Shorthand for :attr:`fixed_tendon_pos_limits`.""" + return self.fixed_tendon_pos_limits + + """ + Defaults - Default values will no longer be stored. + """ + + @property + @leapp_tensor_semantics(const=True) + def default_mass(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_mass` instead and manage the default mass manually.""" + warnings.warn( + "The `default_mass` property will be deprecated in a IsaacLab 4.0. Please use `body_mass` instead. " + "The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_mass is None: + self._default_mass = wp.clone(self.body_mass.warp, self.device) + return ProxyArray(self._default_mass) + + @property + @leapp_tensor_semantics(const=True) + def default_inertia(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_inertia` instead and manage the default inertia manually.""" + warnings.warn( + "The `default_inertia` property will be deprecated in a IsaacLab 4.0. Please use `body_inertia` instead. " + "The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_inertia is None: + self._default_inertia = wp.clone(self.body_inertia.warp, self.device) + return ProxyArray(self._default_inertia) + + @property + @leapp_tensor_semantics(const=True) + def default_joint_stiffness(self) -> ProxyArray: + """Deprecated property. Please use :attr:`joint_stiffness` instead and manage the default joint stiffness + manually.""" + warnings.warn( + "The `default_joint_stiffness` property will be deprecated in a IsaacLab 4.0. Please use `joint_stiffness` " + "instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_joint_stiffness is None: + self._default_joint_stiffness = wp.clone(self.joint_stiffness.warp, self.device) + return ProxyArray(self._default_joint_stiffness) + + @property + @leapp_tensor_semantics(const=True) + def default_joint_damping(self) -> ProxyArray: + """Deprecated property. Please use :attr:`joint_damping` instead and manage the default joint damping + manually.""" + warnings.warn( + "The `default_joint_damping` property will be deprecated in a IsaacLab 4.0. Please use `joint_damping` " + "instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_joint_damping is None: + self._default_joint_damping = wp.clone(self.joint_damping.warp, self.device) + return ProxyArray(self._default_joint_damping) + + @property + @leapp_tensor_semantics(const=True) + def default_joint_armature(self) -> ProxyArray: + """Deprecated property. Please use :attr:`joint_armature` instead and manage the default joint armature + manually.""" + warnings.warn( + "The `default_joint_armature` property will be deprecated in a IsaacLab 4.0. Please use `joint_armature` " + "instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_joint_armature is None: + self._default_joint_armature = wp.clone(self.joint_armature.warp, self.device) + return ProxyArray(self._default_joint_armature) + + @property + @leapp_tensor_semantics(const=True) + def default_joint_friction_coeff(self) -> ProxyArray: + """Deprecated property. Please use :attr:`joint_friction_coeff` instead and manage the default joint friction + coefficient manually.""" + warnings.warn( + "The `default_joint_friction_coeff` property will be deprecated in a IsaacLab 4.0. Please use " + "`joint_friction_coeff` instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_joint_friction_coeff is None: + self._default_joint_friction_coeff = wp.clone(self.joint_friction_coeff.warp, self.device) + return ProxyArray(self._default_joint_friction_coeff) + + @property + @leapp_tensor_semantics(const=True) + def default_joint_viscous_friction_coeff(self) -> ProxyArray: + """Deprecated property. Please use :attr:`joint_viscous_friction_coeff` instead and manage the default joint + viscous friction coefficient manually.""" + warnings.warn( + "The `default_joint_viscous_friction_coeff` property will be deprecated in a IsaacLab 4.0. Please use " + "`joint_viscous_friction_coeff` instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_joint_viscous_friction_coeff is None: + self._default_joint_viscous_friction_coeff = wp.clone( + getattr(self, "joint_viscous_friction_coeff").warp, self.device + ) + return ProxyArray(self._default_joint_viscous_friction_coeff) + + @property + @leapp_tensor_semantics(const=True) + def default_joint_pos_limits(self) -> ProxyArray: + """Deprecated property. Please use :attr:`joint_pos_limits` instead and manage the default joint position + limits manually.""" + warnings.warn( + "The `default_joint_pos_limits` property will be deprecated in a IsaacLab 4.0. Please use " + "`joint_pos_limits` instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_joint_pos_limits is None: + self._default_joint_pos_limits = wp.clone(self.joint_pos_limits.warp, self.device) + return ProxyArray(self._default_joint_pos_limits) + + @property + @leapp_tensor_semantics(const=True) + def default_fixed_tendon_stiffness(self) -> ProxyArray: + """Deprecated property. Please use :attr:`fixed_tendon_stiffness` instead and manage the default fixed tendon + stiffness manually.""" + warnings.warn( + "The `default_fixed_tendon_stiffness` property will be deprecated in a IsaacLab 4.0. Please use " + "`fixed_tendon_stiffness` instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_fixed_tendon_stiffness is None: + self._default_fixed_tendon_stiffness = wp.clone(self.fixed_tendon_stiffness.warp, self.device) + return ProxyArray(self._default_fixed_tendon_stiffness) + + @property + @leapp_tensor_semantics(const=True) + def default_fixed_tendon_damping(self) -> ProxyArray: + """Deprecated property. Please use :attr:`fixed_tendon_damping` instead and manage the default fixed tendon + damping manually.""" + warnings.warn( + "The `default_fixed_tendon_damping` property will be deprecated in a IsaacLab 4.0. Please use " + "`fixed_tendon_damping` instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_fixed_tendon_damping is None: + self._default_fixed_tendon_damping = wp.clone(self.fixed_tendon_damping.warp, self.device) + return ProxyArray(self._default_fixed_tendon_damping) + + @property + @leapp_tensor_semantics(const=True) + def default_fixed_tendon_limit_stiffness(self) -> ProxyArray: + """Deprecated property. Please use :attr:`fixed_tendon_limit_stiffness` instead and manage the default fixed + tendon limit stiffness manually.""" + warnings.warn( + "The `default_fixed_tendon_limit_stiffness` property will be deprecated in a IsaacLab 4.0. Please use " + "`fixed_tendon_limit_stiffness` instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_fixed_tendon_limit_stiffness is None: + self._default_fixed_tendon_limit_stiffness = wp.clone(self.fixed_tendon_limit_stiffness.warp, self.device) + return ProxyArray(self._default_fixed_tendon_limit_stiffness) + + @property + @leapp_tensor_semantics(const=True) + def default_fixed_tendon_rest_length(self) -> ProxyArray: + """Deprecated property. Please use :attr:`fixed_tendon_rest_length` instead and manage the default fixed tendon + rest length manually.""" + warnings.warn( + "The `default_fixed_tendon_rest_length` property will be deprecated in a IsaacLab 4.0. Please use " + "`fixed_tendon_rest_length` instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_fixed_tendon_rest_length is None: + self._default_fixed_tendon_rest_length = wp.clone(self.fixed_tendon_rest_length.warp, self.device) + return ProxyArray(self._default_fixed_tendon_rest_length) + + @property + @leapp_tensor_semantics(const=True) + def default_fixed_tendon_offset(self) -> ProxyArray: + """Deprecated property. Please use :attr:`fixed_tendon_offset` instead and manage the default fixed tendon + offset manually.""" + warnings.warn( + "The `default_fixed_tendon_offset` property will be deprecated in a IsaacLab 4.0. Please use " + "`fixed_tendon_offset` instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_fixed_tendon_offset is None: + self._default_fixed_tendon_offset = wp.clone(self.fixed_tendon_offset.warp, self.device) + return ProxyArray(self._default_fixed_tendon_offset) + + @property + @leapp_tensor_semantics(const=True) + def default_fixed_tendon_pos_limits(self) -> ProxyArray: + """Deprecated property. Please use :attr:`fixed_tendon_pos_limits` instead and manage the default fixed tendon + position limits manually.""" + warnings.warn( + "The `default_fixed_tendon_pos_limits` property will be deprecated in a IsaacLab 4.0. Please use " + "`fixed_tendon_pos_limits` instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_fixed_tendon_pos_limits is None: + self._default_fixed_tendon_pos_limits = wp.clone(self.fixed_tendon_pos_limits.warp, self.device) + return ProxyArray(self._default_fixed_tendon_pos_limits) + + @property + @leapp_tensor_semantics(const=True) + def default_spatial_tendon_stiffness(self) -> ProxyArray: + """Deprecated property. Please use :attr:`spatial_tendon_stiffness` instead and manage the default spatial + tendon stiffness manually.""" + warnings.warn( + "The `default_spatial_tendon_stiffness` property will be deprecated in a IsaacLab 4.0. Please use " + "`spatial_tendon_stiffness` instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_spatial_tendon_stiffness is None: + self._default_spatial_tendon_stiffness = wp.clone(self.spatial_tendon_stiffness.warp, self.device) + return ProxyArray(self._default_spatial_tendon_stiffness) + + @property + @leapp_tensor_semantics(const=True) + def default_spatial_tendon_damping(self) -> ProxyArray: + """Deprecated property. Please use :attr:`spatial_tendon_damping` instead and manage the default spatial tendon + damping manually.""" + warnings.warn( + "The `default_spatial_tendon_damping` property will be deprecated in a IsaacLab 4.0. Please use " + "`spatial_tendon_damping` instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_spatial_tendon_damping is None: + self._default_spatial_tendon_damping = wp.clone(self.spatial_tendon_damping.warp, self.device) + return ProxyArray(self._default_spatial_tendon_damping) + + @property + @leapp_tensor_semantics(const=True) + def default_spatial_tendon_limit_stiffness(self) -> ProxyArray: + """Deprecated property. Please use :attr:`spatial_tendon_limit_stiffness` instead and manage the default + spatial tendon limit stiffness manually.""" + warnings.warn( + "The `default_spatial_tendon_limit_stiffness` property will be deprecated in a IsaacLab 4.0. Please use " + "`spatial_tendon_limit_stiffness` instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_spatial_tendon_limit_stiffness is None: + self._default_spatial_tendon_limit_stiffness = wp.clone( + self.spatial_tendon_limit_stiffness.warp, self.device + ) + return ProxyArray(self._default_spatial_tendon_limit_stiffness) + + @property + @leapp_tensor_semantics(const=True) + def default_spatial_tendon_offset(self) -> ProxyArray: + """Deprecated property. Please use :attr:`spatial_tendon_offset` instead and manage the default spatial tendon + offset manually.""" + warnings.warn( + "The `default_spatial_tendon_offset` property will be deprecated in a IsaacLab 4.0. Please use " + "`spatial_tendon_offset` instead. The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_spatial_tendon_offset is None: + self._default_spatial_tendon_offset = wp.clone(self.spatial_tendon_offset.warp, self.device) + return ProxyArray(self._default_spatial_tendon_offset) + + @property + @leapp_tensor_semantics(const=True) + def default_fixed_tendon_limit(self) -> ProxyArray: + """Deprecated property. Please use :attr:`default_fixed_tendon_pos_limits` instead.""" + warnings.warn( + "The `default_fixed_tendon_limit` property will be deprecated in a IsaacLab 4.0. Please use" + " `default_fixed_tendon_pos_limits` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.default_fixed_tendon_pos_limits + + @property + @leapp_tensor_semantics(const=True) + def default_joint_friction(self) -> ProxyArray: + """Deprecated property. Please use :attr:`default_joint_friction_coeff` instead.""" + warnings.warn( + "The `default_joint_friction` property will be deprecated in a IsaacLab 4.0. Please use" + " `default_joint_friction_coeff` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.default_joint_friction_coeff diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/asset_base.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/asset_base.py new file mode 100644 index 0000000000000000000000000000000000000000..5eb08c95b3bf64fc5608d62ce9b1f9636846ee20 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/asset_base.py @@ -0,0 +1,447 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import inspect +import re +import sys +import weakref +from abc import ABC, abstractmethod +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any + +import torch +import warp as wp + +import isaaclab.sim as sim_utils +from isaaclab.physics import PhysicsEvent, PhysicsManager +from isaaclab.sim.simulation_context import SimulationContext +from isaaclab.sim.utils.stage import get_current_stage + +if TYPE_CHECKING: + from pxr import Usd + + from .asset_base_cfg import AssetBaseCfg + + +class AssetBase(ABC): + """The base interface class for assets. + + An asset corresponds to any physics-enabled object that can be spawned in the simulation. These include + rigid objects, articulated objects, deformable objects etc. The core functionality of an asset is to + provide a set of buffers that can be used to interact with the simulator. The buffers are updated + by the asset class and can be written into the simulator using the their respective ``write`` methods. + This allows a convenient way to perform post-processing operations on the buffers before writing them + into the simulator and obtaining the corresponding simulation results. + + The class handles both the spawning of the asset into the USD stage as well as initialization of necessary + physics handles to interact with the asset. Upon construction of the asset instance, the prim corresponding + to the asset is spawned into the USD stage if the spawn configuration is not None. The spawn configuration + is defined in the :attr:`AssetBaseCfg.spawn` attribute. In case the configured :attr:`AssetBaseCfg.prim_path` + is an expression, then the prim is spawned at all the matching paths. Otherwise, a single prim is spawned + at the configured path. For more information on the spawn configuration, see the + :mod:`isaaclab.sim.spawners` module. + + Unlike backend-specific interfaces (e.g. Isaac Sim PhysX) where one usually needs to call + initialize explicitly, the asset class automatically initializes and invalidates physics + handles when the simulation is ready or stopped. This is done by registering callbacks + for the physics lifecycle events (:attr:`PhysicsEvent.PHYSICS_READY`, :attr:`PhysicsEvent.STOP`). + + Additionally, the class registers a callback for debug visualization of the asset if a debug visualization + is implemented in the asset class. This can be enabled by setting the :attr:`AssetBaseCfg.debug_vis` attribute + to True. The debug visualization is implemented through the :meth:`_set_debug_vis_impl` and + :meth:`_debug_vis_callback` methods. + """ + + _check_shapes: bool = __debug__ + """Class-level default for shape validation. Overridden per-instance in ``__init__``.""" + + def __init__(self, cfg: AssetBaseCfg): + """Initialize the asset base. + + Args: + cfg: The configuration class for the asset. + + Raises: + RuntimeError: If no prims found at input prim path or prim path expression. + """ + # check that the config is valid + cfg.validate() + # store inputs + self.cfg = cfg.copy() + # Resolve shape-check flag once: True means checks are active. + # cfg.disable_shape_checks: None -> follow __debug__ + # True -> force disable checks; False -> force enable checks. + if self.cfg.disable_shape_checks is None: + self._check_shapes = __debug__ + else: + self._check_shapes = not self.cfg.disable_shape_checks + # flag for whether the asset is initialized + self._is_initialized = False + # get stage handle + self.stage: Usd.Stage = get_current_stage() + + # spawn the asset + # determine path where prims should exist after spawn + if self.cfg.spawn is not None: + # Use spawn_path if set (by InteractiveScene), otherwise fall back to prim_path + check_path = self.cfg.spawn.spawn_path if self.cfg.spawn.spawn_path is not None else self.cfg.prim_path + self.cfg.spawn.func( + check_path, + self.cfg.spawn, + translation=self.cfg.init_state.pos, + orientation=self.cfg.init_state.rot, + ) + # check that prims exist + matching_prims = sim_utils.find_matching_prims(check_path) + if len(matching_prims) == 0: + raise RuntimeError(f"Could not find prim with path {check_path}.") + # schema-side post-spawn hook (e.g. ArticulationCfg authors NewtonActuator prims here) + self.cfg._post_spawn(self.stage) + else: + # asset should exist at run time + check_path = self.cfg.prim_path + + # register various callback functions + self._register_callbacks() + + # add handle for debug visualization (this is set to a valid handle inside set_debug_vis) + self._debug_vis_handle = None + # set initial state of debug visualization + self.set_debug_vis(self.cfg.debug_vis) + + def __del__(self, _sys=sys): + """Unsubscribe from the callbacks.""" + # clear events handles + if not _sys.is_finalizing() and _sys.meta_path is not None: + self._clear_callbacks() + + """ + Properties + """ + + @property + def is_initialized(self) -> bool: + """Whether the asset is initialized. + + Returns True if the asset is initialized, False otherwise. + """ + return self._is_initialized + + @property + @abstractmethod + def num_instances(self) -> int: + """Number of instances of the asset. + + This is equal to the number of asset instances per environment multiplied by the number of environments. + """ + return NotImplementedError + + @property + def device(self) -> str: + """Memory device for computation.""" + return self._device + + @property + @abstractmethod + def data(self) -> Any: + """Data related to the asset.""" + return NotImplementedError + + @property + def has_debug_vis_implementation(self) -> bool: + """Whether the asset has a debug visualization implemented.""" + # check if function raises NotImplementedError + source_code = inspect.getsource(self._set_debug_vis_impl) + return "NotImplementedError" not in source_code + + """ + Operations. + """ + + def set_visibility(self, visible: bool, env_ids: Sequence[int] | None = None): + """Set the visibility of the prims corresponding to the asset. + + This operation affects the visibility of the prims corresponding to the asset in the USD stage. + It is useful for toggling the visibility of the asset in the simulator. For instance, one can + hide the asset when it is not being used to reduce the rendering overhead. + + .. note:: + This operation uses the PXR API to set the visibility of the prims. Thus, the operation + may have an overhead if the number of prims is large. + + Args: + visible: Whether to make the prims visible or not. + env_ids: The indices of the object to set visibility. Defaults to None (all instances). + """ + # resolve the environment ids + if env_ids is None: + env_ids = range(len(self._prims)) + elif isinstance(env_ids, torch.Tensor): + env_ids = env_ids.detach().cpu().tolist() + + # obtain the prims corresponding to the asset + # note: we only want to find the prims once since this is a costly operation + if not hasattr(self, "_prims"): + self._prims = sim_utils.find_matching_prims(self.cfg.prim_path) + + # iterate over the environment ids + for env_id in env_ids: + sim_utils.set_prim_visibility(self._prims[env_id], visible) + + def set_debug_vis(self, debug_vis: bool) -> bool: + """Sets whether to visualize the asset data. + + Args: + debug_vis: Whether to visualize the asset data. + + Returns: + Whether the debug visualization was successfully set. False if the asset + does not support debug visualization. + """ + # check if debug visualization is supported + if not self.has_debug_vis_implementation: + return False + # toggle debug visualization objects + self._set_debug_vis_impl(debug_vis) + # toggle debug visualization handles (Kit/omni only for PhysX backend) + if debug_vis: + if self._debug_vis_handle is None: + sim_ctx = SimulationContext.instance() + if sim_ctx is not None: + self._debug_vis_handle = sim_ctx.vis_marker_registry.add_debug_vis_callback(self) + else: + sim_ctx = SimulationContext.instance() + if sim_ctx is not None: + sim_ctx.vis_marker_registry.clear_debug_vis_callback(self) + else: + self._debug_vis_handle = None + # return success + return True + + @abstractmethod + def reset(self, env_ids: Sequence[int] | None = None): + """Resets all internal buffers of selected environments. + + Args: + env_ids: The indices of the object to reset. Defaults to None (all instances). + """ + raise NotImplementedError + + @abstractmethod + def write_data_to_sim(self): + """Writes data to the simulator.""" + raise NotImplementedError + + @abstractmethod + def update(self, dt: float): + """Update the internal buffers. + + The time step ``dt`` is used to compute numerical derivatives of quantities such as joint + accelerations which are not provided by the simulator. + + Args: + dt: The amount of time passed from last ``update`` call. + """ + raise NotImplementedError + + """ + Validation. + """ + + # Mapping from warp dtype to the trailing dimensions that a torch.Tensor + # would have for the same data. Subclasses may extend this (e.g. custom + # ``vec6f`` in deformable objects) by updating the dict in their ``__init__``. + _DTYPE_TO_TORCH_TRAILING_DIMS: dict[type, tuple[int, ...]] = { + wp.float32: (), + wp.int32: (), + wp.vec2f: (2,), + wp.vec3f: (3,), + wp.vec4f: (4,), + wp.transformf: (7,), + wp.spatial_vectorf: (6,), + } + + def assert_shape_and_dtype( + self, tensor: float | torch.Tensor | wp.array, shape: tuple[int, ...], dtype: type, name: str = "" + ) -> None: + """Assert the shape and dtype of a tensor or warp array. + + Controlled by :attr:`AssetBaseCfg.disable_shape_checks`. When checks are + disabled this method is a no-op. + + Args: + tensor: The tensor or warp array to assert the shape of. Floats are skipped. + shape: The expected leading dimensions (e.g. ``(num_envs, num_joints)``). + dtype: The expected warp dtype. + name: Optional parameter name for error messages. + """ + if self._check_shapes: + cls = type(self).__name__ + prefix = f"{cls}: '{name}' " if name else f"{cls}: " + if isinstance(tensor, (int, float)): + return + elif isinstance(tensor, wp.array): + assert tensor.dtype == dtype, f"{prefix}Dtype mismatch: {tensor.dtype} != {dtype}" + assert tensor.shape == shape, f"{prefix}Shape mismatch: {tensor.shape} != {shape}" + elif isinstance(tensor, torch.Tensor): + offset = self._DTYPE_TO_TORCH_TRAILING_DIMS.get(dtype) + if offset is None: + raise ValueError(f"Unsupported dtype: {dtype}") + assert tensor.shape == (*shape, *offset), ( + f"{prefix}Shape mismatch: {tensor.shape} != {(*shape, *offset)}" + ) + + def assert_shape_and_dtype_mask( + self, + tensor: float | torch.Tensor | wp.array, + masks: tuple[wp.array, ...], + dtype: type, + name: str = "", + trailing_dims: tuple[int, ...] = (), + ) -> None: + """Assert the shape of a tensor or warp array against mask dimensions. + + Mask-based write methods expect **full-sized** data — one element per entry in each mask + dimension, regardless of how many entries are ``True``. The expected leading shape is therefore + ``(mask_0.shape[0], mask_1.shape[0], ...)`` (i.e. the *total* size of each dimension, not the + number of selected entries). + + Controlled by :attr:`AssetBaseCfg.disable_shape_checks`. When checks are + disabled this method is a no-op. + + Args: + tensor: The tensor or warp array to assert the shape of. Floats are skipped. + masks: Tuple of mask arrays whose ``shape[0]`` dimensions form the expected leading shape. + dtype: The expected warp dtype. + name: Optional parameter name for error messages. + trailing_dims: Extra trailing dimensions to append (e.g. ``(9,)`` for inertias with ``wp.float32``). + """ + if self._check_shapes: + shape = (*tuple(m.shape[0] for m in masks), *trailing_dims) + self.assert_shape_and_dtype(tensor, shape, dtype, name) + + """ + Implementation specific. + """ + + @abstractmethod + def _initialize_impl(self): + """Initializes the physics handles and internal buffers for the current backend.""" + raise NotImplementedError + + def _set_debug_vis_impl(self, debug_vis: bool): + """Set debug visualization into visualization objects. + + This function is responsible for creating the visualization objects if they don't exist + and input ``debug_vis`` is True. If the visualization objects exist, the function should + set their visibility into the stage. + """ + raise NotImplementedError(f"Debug visualization is not implemented for {self.__class__.__name__}.") + + def _debug_vis_callback(self, event): + """Callback for debug visualization. + + This function calls the visualization objects and sets the data to visualize into them. + """ + raise NotImplementedError(f"Debug visualization is not implemented for {self.__class__.__name__}.") + + """ + Internal simulation callbacks. + """ + + def _register_callbacks(self): + """Registers physics lifecycle callbacks via the current backend's physics manager.""" + physics_mgr_cls = SimulationContext.instance().physics_manager + + # note: use weakref on callbacks to ensure that this object can be deleted when its destructor is called. + obj_ref = weakref.proxy(self) + + def _invoke(callback_name, event): + getattr(obj_ref, callback_name)(event) + + # Backend-agnostic: PHYSICS_READY (init) and STOP (invalidate) + self._initialize_handle = physics_mgr_cls.register_callback( + lambda payload: PhysicsManager.safe_callback_invoke( + _invoke, "_initialize_callback", payload, physics_manager=physics_mgr_cls + ), + PhysicsEvent.PHYSICS_READY, + order=10, + ) + self._invalidate_initialize_handle = physics_mgr_cls.register_callback( + lambda payload: PhysicsManager.safe_callback_invoke( + _invoke, "_invalidate_initialize_callback", payload, physics_manager=physics_mgr_cls + ), + PhysicsEvent.STOP, + order=10, + ) + # Optional: prim deletion (only supported by Kit PhysX backend, not ovphysx) + self._prim_deletion_handle = None + physics_backend = physics_mgr_cls.__name__.lower() + if physics_backend.startswith("physx"): + from isaaclab_physx.physics import IsaacEvents + + self._prim_deletion_handle = physics_mgr_cls.register_callback( + lambda event: PhysicsManager.safe_callback_invoke( + _invoke, "_on_prim_deletion", event, physics_manager=physics_mgr_cls + ), + IsaacEvents.PRIM_DELETION, + ) + + def _initialize_callback(self, event): + """Initializes the scene elements. + + .. note:: + Physics handles are only valid once the simulation is ready. This callback runs when + :attr:`PhysicsEvent.PHYSICS_READY` is dispatched by the current backend. + """ + if not self._is_initialized: + self._backend = SimulationContext.instance().physics_manager.get_backend() + self._device = SimulationContext.instance().physics_manager.get_device() + self._initialize_impl() + self._is_initialized = True + + def _invalidate_initialize_callback(self, event): + """Invalidates the scene elements.""" + self._is_initialized = False + sim_ctx = SimulationContext.instance() + if sim_ctx is not None: + sim_ctx.vis_marker_registry.clear_debug_vis_callback(self) + else: + self._debug_vis_handle = None + + def _on_prim_deletion(self, event) -> None: + """Invalidates and clears callbacks when the prim is deleted. + + Only used when the backend supports prim deletion events (e.g. PhysX). + """ + payload = getattr(event, "payload", event) if not isinstance(event, dict) else event + prim_path = payload.get("prim_path", "") if isinstance(payload, dict) else "" + if prim_path == "/": + self._clear_callbacks() + return + result = re.match( + pattern="^" + "/".join(self.cfg.prim_path.split("/")[: prim_path.count("/") + 1]) + "$", string=prim_path + ) + if result: + self._clear_callbacks() + + def _clear_callbacks(self) -> None: + """Clears all registered callbacks.""" + if self._initialize_handle is not None: + self._initialize_handle.deregister() + self._initialize_handle = None + if self._invalidate_initialize_handle is not None: + self._invalidate_initialize_handle.deregister() + self._invalidate_initialize_handle = None + if self._prim_deletion_handle is not None: + self._prim_deletion_handle.deregister() + self._prim_deletion_handle = None + sim_ctx = SimulationContext.instance() + if sim_ctx is not None: + sim_ctx.vis_marker_registry.clear_debug_vis_callback(self) + else: + self._debug_vis_handle = None diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/asset_base_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/asset_base_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..a284ba394125871f69c9119f805cfcd7a2f5434f --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/asset_base_cfg.py @@ -0,0 +1,104 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from dataclasses import MISSING +from typing import Any, Literal + +from isaaclab.sim import SpawnerCfg +from isaaclab.utils.configclass import configclass + + +@configclass +class AssetBaseCfg: + """The base configuration class for an asset's parameters. + + Please see the :class:`AssetBase` class for more information on the asset class. + """ + + @configclass + class InitialStateCfg: + """Initial state of the asset. + + This defines the default initial state of the asset when it is spawned into the simulation, as + well as the default state when the simulation is reset. + + After parsing the initial state, the asset class stores this information in the :attr:`data` + attribute of the asset class. This can then be accessed by the user to modify the state of the asset + during the simulation, for example, at resets. + """ + + # root position + pos: tuple[float, float, float] = (0.0, 0.0, 0.0) + """Position of the root in simulation world frame. Defaults to (0.0, 0.0, 0.0).""" + rot: tuple[float, float, float, float] = (0.0, 0.0, 0.0, 1.0) + """Quaternion rotation (x, y, z, w) of the root in simulation world frame. + Defaults to (0.0, 0.0, 0.0, 1.0). + """ + + class_type: type | str | None = None + """The associated asset class. Defaults to None, which means that the asset will be spawned + but cannot be interacted with via the asset class. + + The class should inherit from :class:`isaaclab.assets.asset_base.AssetBase`. + """ + + prim_path: str = MISSING + """Prim path (or expression) to the asset. + + .. note:: + The expression can contain the environment namespace regex ``{ENV_REGEX_NS}`` which + will be replaced with the environment namespace. + + Example: ``{ENV_REGEX_NS}/Robot`` will be replaced with ``/World/envs/env_.*/Robot``. + """ + + spawn: SpawnerCfg | None = None + """Spawn configuration for the asset. Defaults to None. + + If None, then no prims are spawned by the asset class. Instead, it is assumed that the + asset is already present in the scene. + """ + + init_state: InitialStateCfg = InitialStateCfg() + """Initial state of the rigid object. Defaults to identity pose.""" + + collision_group: Literal[0, -1] = 0 + """Collision group of the asset. Defaults to ``0``. + + * ``-1``: global collision group (collides with all assets in the scene). + * ``0``: local collision group (collides with other assets in the same environment). + """ + + debug_vis: bool = False + """Whether to enable debug visualization for the asset. Defaults to ``False``.""" + + disable_shape_checks: bool | None = None + """Disable shape/dtype validation in setter and writer methods. + + When ``True``, :meth:`~AssetBase.assert_shape_and_dtype` and + :meth:`~AssetBase.assert_shape_and_dtype_mask` become no-ops, + eliminating per-call assertion overhead. + + When ``False``, shape checks are always enabled, even under ``python -O``. + + When ``None`` (the default), shape checks follow Python's ``__debug__`` + flag — enabled in normal mode, disabled with ``python -O``. + """ + + def _post_spawn(self, stage: Any) -> None: + """Hook invoked by :class:`~isaaclab.assets.AssetBase` after the asset's prims are + spawned and verified to exist on the stage. + + The default implementation is a no-op. Subclasses that need to author additional + USD schemas tied to this asset (for example, :class:`~isaaclab.assets.ArticulationCfg` + which authors ``NewtonActuator`` prims from its ``actuators`` mapping) should + override this method. + + Args: + stage: The USD stage on which the asset was spawned. + """ + pass diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..525b6ae5fd9830d549133036c5d3d5ed4fc8596d --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module for deformable object assets.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ebe78d5b6dbca75ef902365fa9f19728fe6c711f --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__init__.pyi @@ -0,0 +1,18 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from .base_deformable_object import BaseDeformableObject +from .base_deformable_object_data import BaseDeformableObjectData +from .deformable_object import DeformableObject +from .deformable_object_cfg import DeformableObjectCfg +from .deformable_object_data import DeformableObjectData + +__all__ = [ + "BaseDeformableObject", + "BaseDeformableObjectData", + "DeformableObject", + "DeformableObjectCfg", + "DeformableObjectData", +] diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/__init__.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75ce01644bb9dd3b01f0dcf2dbf7fa228687b3fe Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/base_deformable_object.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/base_deformable_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adae91a28cbed2cf4ec4d6077ea9f46047a84ef6 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/base_deformable_object.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/base_deformable_object_data.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/base_deformable_object_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab35b45f8d8485b180dbf870af48e38df6c9852b Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/base_deformable_object_data.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/deformable_object.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/deformable_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ddb50e70713f4cf0128b0f478f7d301337ab484 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/deformable_object.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/deformable_object_cfg.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/deformable_object_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1ab9e1fd45ed77a71b533a26992e7243e664409 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/__pycache__/deformable_object_cfg.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/base_deformable_object.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/base_deformable_object.py new file mode 100644 index 0000000000000000000000000000000000000000..e21895a10bfbb76d35eaceea892017f7d0e38b76 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/base_deformable_object.py @@ -0,0 +1,371 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import warnings +from abc import abstractmethod +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch +import warp as wp + +import isaaclab.utils.math as math_utils +from isaaclab.assets.asset_base import AssetBase +from isaaclab.utils.warp import ProxyArray + +if TYPE_CHECKING: + from .base_deformable_object_data import BaseDeformableObjectData + from .deformable_object_cfg import DeformableObjectCfg + + +class BaseDeformableObject(AssetBase): + """Abstract base class for deformable object assets. + + Deformable objects are assets that can be deformed in the simulation. They are typically used for + soft bodies, such as stuffed animals, food items, and cloth. + + Unlike rigid object assets, deformable objects have a more complex structure and require additional + handling for simulation. The state of a deformable object comprises of its nodal positions and + velocities, and not the object's root position and orientation. The nodal positions and velocities + are in the simulation frame. + + Soft bodies can be `partially kinematic`_, where some nodes are driven by kinematic targets, and + the rest are simulated. The kinematic targets are the desired positions of the nodes, and the + simulation drives the nodes towards these targets. + + .. _partially kinematic: https://nvidia-omniverse.github.io/PhysX/physx/5.4.1/docs/SoftBodies.html#kinematic-soft-bodies + """ + + cfg: DeformableObjectCfg + """Configuration instance for the deformable object.""" + + __backend_name__: str = "base" + """The name of the backend for the deformable object.""" + + def __init__(self, cfg: DeformableObjectCfg): + """Initialize the deformable object. + + Args: + cfg: A configuration instance. + """ + super().__init__(cfg) + + """ + Properties + """ + + @property + @abstractmethod + def data(self) -> BaseDeformableObjectData: + """Data container for the deformable object.""" + raise NotImplementedError() + + @property + @abstractmethod + def num_instances(self) -> int: + """Number of instances of the asset.""" + raise NotImplementedError() + + @property + @abstractmethod + def num_bodies(self) -> int: + """Number of bodies in the asset. + + This is always 1 since each object is a single deformable body. + """ + raise NotImplementedError() + + @property + @abstractmethod + def max_sim_vertices_per_body(self) -> int: + """The maximum number of simulation mesh vertices per deformable body.""" + raise NotImplementedError() + + """ + Operations. + """ + + @abstractmethod + def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None = None) -> None: + """Reset the deformable object. + + Args: + env_ids: Environment indices. If None, then all indices are used. + env_mask: Environment mask. If None, then all the instances are updated. + Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_data_to_sim(self): + """Write data to the simulator.""" + raise NotImplementedError() + + @abstractmethod + def update(self, dt: float): + """Update the internal buffers. + + Args: + dt: The amount of time passed from last :meth:`update` call [s]. + """ + raise NotImplementedError() + + """ + Operations - Write to simulation (index variants). + """ + + def write_nodal_state_to_sim_index( + self, + nodal_state: torch.Tensor | wp.array | ProxyArray, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + full_data: bool = False, + ) -> None: + """Set the nodal state over selected environment indices into the simulation. + + The nodal state comprises of the nodal positions and velocities. Since these are nodes, + the velocity only has a translational component. All the quantities are in the simulation frame. + + Args: + nodal_state: Nodal state in simulation frame [m, m/s]. + Shape is (len(env_ids), max_sim_vertices_per_body, 6) + or (num_instances, max_sim_vertices_per_body, 6). + env_ids: Environment indices. If None, then all indices are used. + full_data: Whether to expect full data. Defaults to False. + """ + # Convert array wrappers to torch for slicing into position and velocity views. + if isinstance(nodal_state, ProxyArray): + nodal_state = nodal_state.torch + elif isinstance(nodal_state, wp.array): + nodal_state = wp.to_torch(nodal_state) + # set into simulation + self.write_nodal_pos_to_sim_index(nodal_state[..., :3], env_ids=env_ids, full_data=full_data) + self.write_nodal_velocity_to_sim_index(nodal_state[..., 3:], env_ids=env_ids, full_data=full_data) + + @abstractmethod + def write_nodal_pos_to_sim_index( + self, + nodal_pos: torch.Tensor | wp.array | ProxyArray, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + full_data: bool = False, + ) -> None: + """Set the nodal positions over selected environment indices into the simulation. + + Args: + nodal_pos: Nodal positions in simulation frame [m]. + Shape is (len(env_ids), max_sim_vertices_per_body, 3) + or (num_instances, max_sim_vertices_per_body, 3). + env_ids: Environment indices. If None, then all indices are used. + full_data: Whether to expect full data. Defaults to False. + """ + raise NotImplementedError() + + @abstractmethod + def write_nodal_velocity_to_sim_index( + self, + nodal_vel: torch.Tensor | wp.array | ProxyArray, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + full_data: bool = False, + ) -> None: + """Set the nodal velocity over selected environment indices into the simulation. + + Args: + nodal_vel: Nodal velocities in simulation frame [m/s]. + Shape is (len(env_ids), max_sim_vertices_per_body, 3) + or (num_instances, max_sim_vertices_per_body, 3). + env_ids: Environment indices. If None, then all indices are used. + full_data: Whether to expect full data. Defaults to False. + """ + raise NotImplementedError() + + @abstractmethod + def write_nodal_kinematic_target_to_sim_index( + self, + targets: torch.Tensor | wp.array | ProxyArray, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + full_data: bool = False, + ) -> None: + """Set the kinematic targets of the simulation mesh for the deformable bodies using indices. + + The kinematic targets comprise of individual nodal positions of the simulation mesh + for the deformable body and a flag indicating whether the node is kinematically driven or not. + The positions are in the simulation frame. + + .. note:: + The flag is set to 0.0 for kinematically driven nodes and 1.0 for free nodes. + + Args: + targets: The kinematic targets comprising of nodal positions and flags [m]. + Shape is (len(env_ids), max_sim_vertices_per_body, 4) + or (num_instances, max_sim_vertices_per_body, 4). + env_ids: Environment indices. If None, then all indices are used. + full_data: Whether to expect full data. Defaults to False. + """ + raise NotImplementedError() + + """ + Operations - Write to simulation (mask variants). + """ + + def write_nodal_state_to_sim_mask( + self, + nodal_state: torch.Tensor | wp.array | ProxyArray, + env_mask: wp.array | None = None, + ) -> None: + """Set the nodal state over selected environment mask into the simulation. + + Args: + nodal_state: Nodal state in simulation frame [m, m/s]. + Shape is (num_instances, max_sim_vertices_per_body, 6). + env_mask: Environment mask. If None, then all indices are used. + """ + if env_mask is not None: + env_ids = wp.nonzero(env_mask) + else: + env_ids = self._ALL_INDICES + self.write_nodal_state_to_sim_index(nodal_state, env_ids=env_ids, full_data=True) + + def write_nodal_pos_to_sim_mask( + self, + nodal_pos: torch.Tensor | wp.array | ProxyArray, + env_mask: wp.array | None = None, + ) -> None: + """Set the nodal positions over selected environment mask into the simulation. + + Args: + nodal_pos: Nodal positions in simulation frame [m]. + Shape is (num_instances, max_sim_vertices_per_body, 3). + env_mask: Environment mask. If None, then all indices are used. + """ + if env_mask is not None: + env_ids = wp.nonzero(env_mask) + else: + env_ids = self._ALL_INDICES + self.write_nodal_pos_to_sim_index(nodal_pos, env_ids=env_ids, full_data=True) + + def write_nodal_velocity_to_sim_mask( + self, + nodal_vel: torch.Tensor | wp.array | ProxyArray, + env_mask: wp.array | None = None, + ) -> None: + """Set the nodal velocity over selected environment mask into the simulation. + + Args: + nodal_vel: Nodal velocities in simulation frame [m/s]. + Shape is (num_instances, max_sim_vertices_per_body, 3). + env_mask: Environment mask. If None, then all indices are used. + """ + if env_mask is not None: + env_ids = wp.nonzero(env_mask) + else: + env_ids = self._ALL_INDICES + self.write_nodal_velocity_to_sim_index(nodal_vel, env_ids=env_ids, full_data=True) + + def write_nodal_kinematic_target_to_sim_mask( + self, + targets: torch.Tensor | wp.array | ProxyArray, + env_mask: wp.array | None = None, + ) -> None: + """Set the kinematic targets of the simulation mesh for the deformable bodies using mask. + + Args: + targets: The kinematic targets comprising of nodal positions and flags [m]. + Shape is (num_instances, max_sim_vertices_per_body, 4). + env_mask: Environment mask. If None, then all indices are used. + """ + if env_mask is not None: + env_ids = wp.nonzero(env_mask) + else: + env_ids = self._ALL_INDICES + self.write_nodal_kinematic_target_to_sim_index(targets, env_ids=env_ids, full_data=True) + + """ + Operations - Deprecated wrappers. + """ + + def write_nodal_state_to_sim( + self, + nodal_state: torch.Tensor | wp.array | ProxyArray, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated. Please use :meth:`write_nodal_state_to_sim_index` instead.""" + warnings.warn( + "The method 'write_nodal_state_to_sim' is deprecated. Please use 'write_nodal_state_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_nodal_state_to_sim_index(nodal_state, env_ids=env_ids) + + def write_nodal_kinematic_target_to_sim( + self, + targets: torch.Tensor | wp.array | ProxyArray, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated. Please use :meth:`write_nodal_kinematic_target_to_sim_index` instead.""" + warnings.warn( + "The method 'write_nodal_kinematic_target_to_sim' is deprecated." + " Please use 'write_nodal_kinematic_target_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_nodal_kinematic_target_to_sim_index(targets, env_ids=env_ids) + + def write_nodal_pos_to_sim( + self, + nodal_pos: torch.Tensor | wp.array | ProxyArray, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated. Please use :meth:`write_nodal_pos_to_sim_index` instead.""" + warnings.warn( + "The method 'write_nodal_pos_to_sim' is deprecated. Please use 'write_nodal_pos_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_nodal_pos_to_sim_index(nodal_pos, env_ids=env_ids) + + def write_nodal_velocity_to_sim( + self, + nodal_vel: torch.Tensor | wp.array | ProxyArray, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated. Please use :meth:`write_nodal_velocity_to_sim_index` instead.""" + warnings.warn( + "The method 'write_nodal_velocity_to_sim' is deprecated." + " Please use 'write_nodal_velocity_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_nodal_velocity_to_sim_index(nodal_vel, env_ids=env_ids) + + """ + Operations - Helper. + """ + + def transform_nodal_pos( + self, nodal_pos: torch.Tensor, pos: torch.Tensor | None = None, quat: torch.Tensor | None = None + ) -> torch.Tensor: + """Transform the nodal positions based on the pose transformation. + + This function computes the transformation of the nodal positions based on the pose transformation. + It multiplies the nodal positions with the rotation matrix of the pose and adds the translation. + Internally, it calls the :meth:`isaaclab.utils.math.transform_points` function. + + Args: + nodal_pos: The nodal positions in the simulation frame [m]. + Shape is (N, max_sim_vertices_per_body, 3). + pos: The position transformation [m]. Shape is (N, 3). + Defaults to None, in which case the position is assumed to be zero. + quat: The orientation transformation as quaternion (x, y, z, w). Shape is (N, 4). + Defaults to None, in which case the orientation is assumed to be identity. + + Returns: + The transformed nodal positions [m]. Shape is (N, max_sim_vertices_per_body, 3). + """ + # offset the nodal positions to center them around the origin + mean_nodal_pos = nodal_pos.mean(dim=1, keepdim=True) + nodal_pos = nodal_pos - mean_nodal_pos + # transform the nodal positions based on the pose around the origin + return math_utils.transform_points(nodal_pos, pos, quat) + mean_nodal_pos diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/base_deformable_object_data.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/base_deformable_object_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b1ae4975110d146681cb7388c9ffd122e977fa --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/base_deformable_object_data.py @@ -0,0 +1,136 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from abc import ABC, abstractmethod + +from isaaclab.utils.warp import ProxyArray + + +class BaseDeformableObjectData(ABC): + """Abstract data container for a deformable object. + + This class defines the interface for deformable object data in the simulation. + The data includes the nodal states of the root deformable body in the object. + The data is stored in the simulation world frame unless otherwise specified. + + The data is lazily updated, meaning that the data is only updated when it is accessed. + This is useful when the data is expensive to compute or retrieve. The data is updated + when the timestamp of the buffer is older than the current simulation timestamp. + """ + + def __init__(self, device: str): + """Initialize the deformable object data. + + Args: + device: The device used for processing. + """ + self.device = device + # Set initial time stamp + self._sim_timestamp = 0.0 + + def update(self, dt: float): + """Update the data for the deformable object. + + Args: + dt: The time step for the update [s]. This must be a positive value. + """ + # update the simulation timestamp + self._sim_timestamp += dt + + ## + # Defaults. + ## + + default_nodal_state_w: ProxyArray | None = None + """Default nodal state ``[nodal_pos, nodal_vel]`` in simulation world frame. + + Shape is (num_instances, max_sim_vertices_per_body), dtype ``vec6f``. + Use :attr:`ProxyArray.warp` for the underlying :class:`warp.array` or + :attr:`ProxyArray.torch` for a cached zero-copy :class:`torch.Tensor` view. + """ + + ## + # Kinematic commands. + ## + + nodal_kinematic_target: ProxyArray | None = None + """Simulation mesh kinematic targets for the deformable bodies. + + Shape is (num_instances, max_sim_vertices_per_body), dtype ``wp.vec4f``. + Use :attr:`ProxyArray.warp` for the underlying :class:`warp.array` or + :attr:`ProxyArray.torch` for a cached zero-copy :class:`torch.Tensor` view. + + The kinematic targets are used to drive the simulation mesh vertices to the target positions. + The targets are stored as (x, y, z, is_not_kinematic) where "is_not_kinematic" is a binary + flag indicating whether the vertex is kinematic or not. The flag is set to 0 for kinematic vertices + and 1 for non-kinematic vertices. + """ + + ## + # Properties. + ## + + @property + @abstractmethod + def nodal_pos_w(self) -> ProxyArray: + """Nodal positions in simulation world frame [m]. + + Shape is (num_instances, max_sim_vertices_per_body), dtype ``wp.vec3f``. + Use :attr:`ProxyArray.warp` for the underlying :class:`warp.array` or + :attr:`ProxyArray.torch` for a cached zero-copy :class:`torch.Tensor` view. + """ + raise NotImplementedError() + + @property + @abstractmethod + def nodal_vel_w(self) -> ProxyArray: + """Nodal velocities in simulation world frame [m/s]. + + Shape is (num_instances, max_sim_vertices_per_body), dtype ``wp.vec3f``. + Use :attr:`ProxyArray.warp` for the underlying :class:`warp.array` or + :attr:`ProxyArray.torch` for a cached zero-copy :class:`torch.Tensor` view. + """ + raise NotImplementedError() + + @property + @abstractmethod + def nodal_state_w(self) -> ProxyArray: + """Nodal state ``[nodal_pos, nodal_vel]`` in simulation world frame [m, m/s]. + + Shape is (num_instances, max_sim_vertices_per_body), dtype ``vec6f``. + Use :attr:`ProxyArray.warp` for the underlying :class:`warp.array` or + :attr:`ProxyArray.torch` for a cached zero-copy :class:`torch.Tensor` view. + """ + raise NotImplementedError() + + ## + # Derived properties. + ## + + @property + @abstractmethod + def root_pos_w(self) -> ProxyArray: + """Root position from nodal positions of the simulation mesh for the deformable bodies + in simulation world frame [m]. Shape is (num_instances,) vec3f. + + This quantity is computed as the mean of the nodal positions. + Use :attr:`ProxyArray.warp` for the underlying :class:`warp.array` or + :attr:`ProxyArray.torch` for a cached zero-copy :class:`torch.Tensor` view. + """ + raise NotImplementedError() + + @property + @abstractmethod + def root_vel_w(self) -> ProxyArray: + """Root velocity from vertex velocities for the deformable bodies in simulation + world frame [m/s]. Shape is (num_instances,) vec3f. + + This quantity is computed as the mean of the nodal velocities. + Use :attr:`ProxyArray.warp` for the underlying :class:`warp.array` or + :attr:`ProxyArray.torch` for a cached zero-copy :class:`torch.Tensor` view. + """ + raise NotImplementedError() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/deformable_object.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/deformable_object.py new file mode 100644 index 0000000000000000000000000000000000000000..3bd41c8728be49f7e48bd6b22f887acf1eed4b21 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/deformable_object.py @@ -0,0 +1,27 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.backend_utils import FactoryBase + +from .base_deformable_object import BaseDeformableObject +from .base_deformable_object_data import BaseDeformableObjectData + +if TYPE_CHECKING: + from isaaclab_physx.assets.deformable_object import DeformableObject as PhysXDeformableObject + from isaaclab_physx.assets.deformable_object import DeformableObjectData as PhysXDeformableObjectData + + +class DeformableObject(FactoryBase, BaseDeformableObject): + """Factory for creating deformable object instances.""" + + data: BaseDeformableObjectData | PhysXDeformableObjectData + + def __new__(cls, *args, **kwargs) -> BaseDeformableObject | PhysXDeformableObject: + """Create a new instance of a deformable object based on the backend.""" + return super().__new__(cls, *args, **kwargs) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/deformable_object_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/deformable_object_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..9c54aa7b6b0be97449118bd2d831bfd951ca76da --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/deformable_object_cfg.py @@ -0,0 +1,32 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.assets.asset_base_cfg import AssetBaseCfg +from isaaclab.markers import VisualizationMarkersCfg +from isaaclab.markers.config import DEFORMABLE_TARGET_MARKER_CFG +from isaaclab.utils.configclass import configclass + +if TYPE_CHECKING: + from .deformable_object import DeformableObject + + +@configclass +class DeformableObjectCfg(AssetBaseCfg): + """Configuration parameters for a deformable object.""" + + class_type: type[DeformableObject] | str = "{DIR}.deformable_object:DeformableObject" + + visualizer_cfg: VisualizationMarkersCfg = DEFORMABLE_TARGET_MARKER_CFG.replace( + prim_path="/Visuals/DeformableTarget" + ) + """The configuration object for the visualization markers. Defaults to DEFORMABLE_TARGET_MARKER_CFG. + + .. note:: + This attribute is only used when debug visualization is enabled. + """ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/deformable_object_data.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/deformable_object_data.py new file mode 100644 index 0000000000000000000000000000000000000000..35567aceb8474a0cc64d50b0a9b94ece2b3d6e23 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/deformable_object/deformable_object_data.py @@ -0,0 +1,25 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.backend_utils import FactoryBase + +from .base_deformable_object_data import BaseDeformableObjectData + +if TYPE_CHECKING: + from isaaclab_physx.assets.deformable_object.deformable_object_data import ( + DeformableObjectData as PhysXDeformableObjectData, + ) + + +class DeformableObjectData(FactoryBase): + """Factory for creating deformable object data instances.""" + + def __new__(cls, *args, **kwargs) -> BaseDeformableObjectData | PhysXDeformableObjectData: + """Create a new instance of a deformable object data based on the backend.""" + return super().__new__(cls, *args, **kwargs) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89af788c3f4f84cb0740f3dd6d2e7d16e77eab07 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module for rigid object assets.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..162a9c1cc4e4d94b15b4c94d35b23b2c6e0bb19e --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__init__.pyi @@ -0,0 +1,18 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "BaseRigidObject", + "BaseRigidObjectData", + "RigidObject", + "RigidObjectCfg", + "RigidObjectData", +] + +from .base_rigid_object import BaseRigidObject +from .base_rigid_object_data import BaseRigidObjectData +from .rigid_object import RigidObject +from .rigid_object_cfg import RigidObjectCfg +from .rigid_object_data import RigidObjectData diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/__init__.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4de63b2f4c6cf3ca34a7696b3d5e389d82196793 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/base_rigid_object.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/base_rigid_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6799b6c0231084db0593c89af1476b6e26345dde Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/base_rigid_object.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/base_rigid_object_data.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/base_rigid_object_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51d1d54770edce8e943e91ee7313250aa49eef76 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/base_rigid_object_data.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/rigid_object.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/rigid_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8977f860b11883ef3c588694ee4bf93e31f13107 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/rigid_object.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/rigid_object_cfg.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/rigid_object_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef73b712907b326f6b1187af3de0b87d41aa7599 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/__pycache__/rigid_object_cfg.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/base_rigid_object.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/base_rigid_object.py new file mode 100644 index 0000000000000000000000000000000000000000..d7bc6ea4c85d7dbda3a28167f3290abc22f29a70 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/base_rigid_object.py @@ -0,0 +1,860 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import warnings +from abc import abstractmethod +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch +import warp as wp + +from isaaclab.utils.wrench_composer import WrenchComposer + +from ..asset_base import AssetBase + +if TYPE_CHECKING: + from .rigid_object_cfg import RigidObjectCfg + from .rigid_object_data import RigidObjectData + + +class BaseRigidObject(AssetBase): + """A rigid object asset class. + + Rigid objects are assets comprising of rigid bodies. They can be used to represent dynamic objects + such as boxes, spheres, etc. A rigid body is described by its pose, velocity and mass distribution. + + For an asset to be considered a rigid object, the root prim of the asset must have the `USD RigidBodyAPI`_ + applied to it. This API is used to define the simulation properties of the rigid body. On playing the + simulation, the physics engine will automatically register the rigid body and create a corresponding + rigid body handle. This handle can be accessed using the :attr:`root_view` attribute. + + .. note:: + + For users familiar with Isaac Sim, the PhysX view class API is not the exactly same as Isaac Sim view + class API. Similar to Isaac Lab, Isaac Sim wraps around the PhysX view API. However, as of now (2023.1 release), + we see a large difference in initializing the view classes in Isaac Sim. This is because the view classes + in Isaac Sim perform additional USD-related operations which are slow and also not required. + + .. _`USD RigidBodyAPI`: https://openusd.org/dev/api/class_usd_physics_rigid_body_a_p_i.html + """ + + cfg: RigidObjectCfg + """Configuration instance for the rigid object.""" + + __backend_name__: str = "base" + """The name of the backend for the rigid object.""" + + def __init__(self, cfg: RigidObjectCfg): + """Initialize the rigid object. + + Args: + cfg: A configuration instance. + """ + super().__init__(cfg) + + """ + Properties + """ + + @property + @abstractmethod + def data(self) -> RigidObjectData: + raise NotImplementedError() + + @property + @abstractmethod + def num_instances(self) -> int: + raise NotImplementedError() + + @property + @abstractmethod + def num_bodies(self) -> int: + """Number of bodies in the asset. + + This is always 1 since each object is a single rigid body. + """ + raise NotImplementedError() + + @property + @abstractmethod + def body_names(self) -> list[str]: + """Ordered names of bodies in the rigid object.""" + raise NotImplementedError() + + @property + @abstractmethod + def root_view(self): + """Root view for the asset. + + .. note:: + Use this view with caution. It requires handling of tensors in a specific way. + """ + raise NotImplementedError() + + @property + @abstractmethod + def instantaneous_wrench_composer(self) -> WrenchComposer: + """Instantaneous wrench composer. + + Returns a :class:`~isaaclab.utils.wrench_composer.WrenchComposer` instance. Wrenches added or set to this wrench + composer are only valid for the current simulation step. At the end of the simulation step, the wrenches set + to this object are discarded. This is useful to apply forces that change all the time, things like drag forces + for instance. + """ + raise NotImplementedError() + + @property + @abstractmethod + def permanent_wrench_composer(self) -> WrenchComposer: + """Permanent wrench composer. + + Returns a :class:`~isaaclab.utils.wrench_composer.WrenchComposer` instance. Wrenches added or set to this wrench + composer are persistent and are applied to the simulation at every step. This is useful to apply forces that + are constant over a period of time, things like the thrust of a motor for instance. + """ + raise NotImplementedError() + + """ + Operations. + """ + + @abstractmethod + def reset( + self, env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, env_mask: wp.array | None = None + ) -> None: + """Reset the rigid object. + + .. caution:: + If both `env_ids` and `env_mask` are provided, then `env_mask` takes precedence over `env_ids`. + + Args: + env_ids: Environment indices. If None, then all indices are used. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_data_to_sim(self) -> None: + """Write external wrench to the simulation. + + .. note:: + We write external wrench to the simulation here since this function is called before the simulation step. + This ensures that the external wrench is applied at every simulation step. + """ + raise NotImplementedError() + + @abstractmethod + def update(self, dt: float) -> None: + """Updates the simulation data. + + Args: + dt: The time step size in seconds. + """ + raise NotImplementedError() + + """ + Operations - Finders. + """ + + @abstractmethod + def find_bodies(self, name_keys: str | Sequence[str], preserve_order: bool = False) -> tuple[list[int], list[str]]: + """Find bodies in the rigid body based on the name keys. + + Please check the :meth:`isaaclab.utils.string_utils.resolve_matching_names` function for more + information on the name matching. + + Args: + name_keys: A regular expression or a list of regular expressions to match the body names. + preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False. + + Returns: + A tuple of lists containing the body indices and names. + """ + raise NotImplementedError() + + """ + Operations - Write to simulation. + """ + + @abstractmethod + def write_root_pose_to_sim_index( + self, + *, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the root pose over selected environment indices into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_pose: Root poses in simulation frame. Shape is (len(env_ids), 7) or + (len(env_ids),) with dtype wp.transformf. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_root_pose_to_sim_mask( + self, + *, + root_pose: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root pose over selected environment mask into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_pose: Root poses in simulation frame. Shape is (num_instances, 7) or + (num_instances,) with dtype wp.transformf. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_root_link_pose_to_sim_index( + self, + *, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the root link pose over selected environment indices into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_pose: Root link poses in simulation frame. Shape is (len(env_ids), 7) or + (len(env_ids),) with dtype wp.transformf. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_root_link_pose_to_sim_mask( + self, + *, + root_pose: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root link pose over selected environment mask into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_pose: Root link poses in simulation frame. Shape is (num_instances, 7) or + (num_instances,) with dtype wp.transformf. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_root_com_pose_to_sim_index( + self, + *, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the root center of mass pose over selected environment indices into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + The orientation is the orientation of the principal axes of inertia. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_pose: Root center of mass poses in simulation frame. Shape is (len(env_ids), 7) or + (len(env_ids),) with dtype wp.transformf. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_root_com_pose_to_sim_mask( + self, + *, + root_pose: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root center of mass pose over selected environment mask into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + The orientation is the orientation of the principal axes of inertia. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_pose: Root center of mass poses in simulation frame. Shape is (num_instances, 7) or + (num_instances,) with dtype wp.transformf. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_root_velocity_to_sim_index( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the root center of mass velocity over selected environment indices into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the root's center of mass rather than the root's frame. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_velocity: Root center of mass velocities in simulation world frame. Shape is (len(env_ids), 6) + or (len(env_ids),) with dtype wp.spatial_vectorf. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_root_velocity_to_sim_mask( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root center of mass velocity over selected environment mask into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the root's center of mass rather than the root's frame. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_velocity: Root center of mass velocities in simulation world frame. Shape is (num_instances, 6) + or (num_instances,) with dtype wp.spatial_vectorf. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_root_com_velocity_to_sim_index( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the root center of mass velocity over selected environment indices into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the root's center of mass rather than the root's frame. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_velocity: Root center of mass velocities in simulation world frame. Shape is (len(env_ids), 6) + or (len(env_ids),) with dtype wp.spatial_vectorf. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_root_com_velocity_to_sim_mask( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root center of mass velocity over selected environment mask into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the root's center of mass rather than the root's frame. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_velocity: Root center of mass velocities in simulation world frame. Shape is (num_instances, 6) + or (num_instances,) with dtype wp.spatial_vectorf. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_root_link_velocity_to_sim_index( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the root link velocity over selected environment indices into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the root's frame rather than the root's center of mass. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_velocity: Root frame velocities in simulation world frame. Shape is (len(env_ids), 6) + or (len(env_ids),) with dtype wp.spatial_vectorf. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_root_link_velocity_to_sim_mask( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root link velocity over selected environment mask into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the root's frame rather than the root's center of mass. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + root_velocity: Root frame velocities in simulation world frame. Shape is (num_instances, 6) + or (num_instances,) with dtype wp.spatial_vectorf. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + """ + Operations - Setters. + """ + + @abstractmethod + def set_masses_index( + self, + *, + masses: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set masses of all bodies. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + masses: Masses of all bodies. Shape is (len(env_ids), len(body_ids)). + body_ids: The body indices to set the masses for. Defaults to None (all bodies). + env_ids: The environment indices to set the masses for. Defaults to None (all environments). + """ + raise NotImplementedError() + + @abstractmethod + def set_masses_mask( + self, + *, + masses: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set masses of all bodies. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + masses: Masses of all bodies. Shape is (num_instances, num_bodies). + body_mask: Body mask. If None, then all bodies are used. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_coms_index( + self, + *, + coms: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set center of mass positions of all bodies. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + coms: Center of mass positions of all bodies. Shape is (len(env_ids), len(body_ids), 3). + body_ids: The body indices to set the center of mass positions for. Defaults to None (all bodies). + env_ids: The environment indices to set the center of mass positions for. Defaults to None + (all environments). + """ + raise NotImplementedError() + + @abstractmethod + def set_coms_mask( + self, + *, + coms: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set center of mass positions of all bodies. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + coms: Center of mass positions of all bodies. Shape is (num_instances, num_bodies, 3) + or (num_instances, num_bodies) with dtype wp.vec3f. + body_mask: Body mask. If None, then all bodies are used. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_inertias_index( + self, + *, + inertias: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set inertias of all bodies. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + inertias: Inertias of all bodies. Shape is (len(env_ids), len(body_ids), 9). + body_ids: The body indices to set the inertias for. Defaults to None (all bodies). + env_ids: The environment indices to set the inertias for. Defaults to None (all environments). + """ + raise NotImplementedError() + + @abstractmethod + def set_inertias_mask( + self, + *, + inertias: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set inertias of all bodies. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + inertias: Inertias of all bodies. Shape is (num_instances, num_bodies, 9). + body_mask: Body mask. If None, then all bodies are used. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + """ + Internal helper. + """ + + @abstractmethod + def _initialize_impl(self) -> None: + raise NotImplementedError() + + @abstractmethod + def _create_buffers(self) -> None: + raise NotImplementedError() + + @abstractmethod + def _process_cfg(self) -> None: + """Post processing of configuration parameters.""" + raise NotImplementedError() + + """ + Internal simulation callbacks. + """ + + @abstractmethod + def _invalidate_initialize_callback(self, event) -> None: + """Invalidates the scene elements.""" + super()._invalidate_initialize_callback(event) + + """ + Deprecated. + """ + + @abstractmethod + def write_root_state_to_sim( + self, + root_state: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_pose_to_sim_index` and :meth:`write_root_velocity_to_sim_index`.""" + raise NotImplementedError() + + @abstractmethod + def write_root_com_state_to_sim( + self, + root_state: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_com_pose_to_sim_index` and :meth:`write_root_velocity_to_sim_index`.""" + raise NotImplementedError() + + @abstractmethod + def write_root_link_state_to_sim( + self, + root_state: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_pose_to_sim_index` + and :meth:`write_root_link_velocity_to_sim_index`.""" + raise NotImplementedError() + + def write_root_pose_to_sim( + self, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_pose_to_sim_index`.""" + warnings.warn( + "The function 'write_root_pose_to_sim' will be deprecated in a future release. Please" + " use 'write_root_pose_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_root_pose_to_sim_index(root_pose=root_pose, env_ids=env_ids) + + def write_root_link_pose_to_sim( + self, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_link_pose_to_sim_index`.""" + warnings.warn( + "The function 'write_root_link_pose_to_sim' will be deprecated in a future release. Please" + " use 'write_root_link_pose_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_root_link_pose_to_sim_index(root_pose=root_pose, env_ids=env_ids) + + def write_root_com_pose_to_sim( + self, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_com_pose_to_sim_index`.""" + warnings.warn( + "The function 'write_root_com_pose_to_sim' will be deprecated in a future release. Please" + " use 'write_root_com_pose_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_root_com_pose_to_sim_index(root_pose=root_pose, env_ids=env_ids) + + def write_root_velocity_to_sim( + self, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_velocity_to_sim_index`.""" + warnings.warn( + "The function 'write_root_velocity_to_sim' will be deprecated in a future release. Please" + " use 'write_root_velocity_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_root_velocity_to_sim_index(root_velocity=root_velocity, env_ids=env_ids) + + def write_root_com_velocity_to_sim( + self, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_com_velocity_to_sim_index`.""" + warnings.warn( + "The function 'write_root_com_velocity_to_sim' will be deprecated in a future release. Please" + " use 'write_root_com_velocity_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_root_com_velocity_to_sim_index(root_velocity=root_velocity, env_ids=env_ids) + + def write_root_link_velocity_to_sim( + self, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`write_root_link_velocity_to_sim_index`.""" + warnings.warn( + "The function 'write_root_link_velocity_to_sim' will be deprecated in a future release. Please" + " use 'write_root_link_velocity_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_root_link_velocity_to_sim_index(root_velocity=root_velocity, env_ids=env_ids) + + def set_masses( + self, + masses: torch.Tensor | wp.array, + body_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_masses_index`.""" + warnings.warn( + "The function 'set_masses' will be deprecated in a future release. Please use 'set_masses_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_masses_index(masses=masses, body_ids=body_ids, env_ids=env_ids) + + def set_coms( + self, + coms: torch.Tensor | wp.array, + body_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_coms_index`.""" + warnings.warn( + "The function 'set_coms' will be deprecated in a future release. Please use 'set_coms_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_coms_index(coms=coms, body_ids=body_ids, env_ids=env_ids) + + def set_inertias( + self, + inertias: torch.Tensor | wp.array, + body_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_inertias_index`.""" + warnings.warn( + "The function 'set_inertias' will be deprecated in a future release. Please" + " use 'set_inertias_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_inertias_index(inertias=inertias, body_ids=body_ids, env_ids=env_ids) + + def set_external_force_and_torque( + self, + forces: torch.Tensor | wp.array, + torques: torch.Tensor | wp.array, + positions: torch.Tensor | wp.array | None = None, + body_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + is_global: bool = False, + ) -> None: + """Deprecated. Resets target environments, then adds forces and torques via the permanent wrench composer.""" + warnings.warn( + "The function 'set_external_force_and_torque' is deprecated. Please use" + " 'permanent_wrench_composer.reset' followed by 'permanent_wrench_composer.add_forces_and_torques'" + " instead.", + DeprecationWarning, + stacklevel=2, + ) + # Reset only target env_ids then add (not set which clears all envs globally) + self.permanent_wrench_composer.reset(env_ids=env_ids) + self.permanent_wrench_composer.add_forces_and_torques( + forces, torques, positions=positions, body_ids=body_ids, env_ids=env_ids, is_global=is_global + ) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/base_rigid_object_data.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/base_rigid_object_data.py new file mode 100644 index 0000000000000000000000000000000000000000..b9134cf9ec93596fd112c76e877dca08e6dfb210 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/base_rigid_object_data.py @@ -0,0 +1,789 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from abc import ABC, abstractmethod + +import warp as wp + +from isaaclab.utils.leapp import ( + POSE6_ELEMENT_NAMES, + POSE7_ELEMENT_NAMES, + QUAT_XYZW_ELEMENT_NAMES, + XYZ_ELEMENT_NAMES, + InputKindEnum, + body_pose6_resolver, + body_pose_resolver, + body_quat_resolver, + body_xyz_resolver, + leapp_tensor_semantics, +) +from isaaclab.utils.warp import ProxyArray + + +class BaseRigidObjectData(ABC): + """Data container for a rigid object. + + This class contains the data for a rigid object in the simulation. The data includes the state of + the root rigid body and the state of all the bodies in the object. The data is stored in the simulation + world frame unless otherwise specified. + + For a rigid body, there are two frames of reference that are used: + + - Actor frame: The frame of reference of the rigid body prim. This typically corresponds to the Xform prim + with the rigid body schema. + - Center of mass frame: The frame of reference of the center of mass of the rigid body. + Depending on the settings of the simulation, the actor frame and the center of mass frame may be the same. + This needs to be taken into account when interpreting the data. + + The data is lazily updated, meaning that the data is only updated when it is accessed. This is useful + when the data is expensive to compute or retrieve. The data is updated when the timestamp of the buffer + is older than the current simulation timestamp. The timestamp is updated whenever the data is updated. + """ + + def __init__(self, root_view, device: str): + """Initializes the rigid object data. + + Args: + root_view: The root rigid body view. + device: The device used for processing. + """ + # Set the parameters + self.device = device + + @abstractmethod + def update(self, dt: float) -> None: + """Updates the data for the rigid object. + + Args: + dt: The time step for the update. This must be a positive value. + """ + raise NotImplementedError() + + ## + # Names. + ## + + body_names: list[str] | None = None + """Body names in the order parsed by the simulation view.""" + + ## + # Defaults. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def default_root_pose(self) -> ProxyArray: + """Default root pose ``[pos, quat]`` in local environment frame. + + The position and quaternion are of the rigid body's actor frame. + Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def default_root_vel(self) -> ProxyArray: + """Default root velocity ``[lin_vel, ang_vel]`` in local environment frame. + + The linear and angular velocities are of the rigid body's center of mass frame. + Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). + """ + raise NotImplementedError() + + @property + @abstractmethod + def default_root_state(self) -> ProxyArray: + """Deprecated, same as :attr:`default_root_pose` and :attr:`default_root_vel`.""" + raise NotImplementedError() + + ## + # Root state properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def root_link_pose_w(self) -> ProxyArray: + """Root link pose ``[pos, quat]`` in simulation world frame. + + Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). + + This quantity is the pose of the actor frame of the root rigid body relative to the world. + The orientation is provided in (x, y, z, w) format. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names=POSE6_ELEMENT_NAMES) + def root_link_vel_w(self) -> ProxyArray: + """Root link velocity ``[lin_vel, ang_vel]`` in simulation world frame. + + Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). + + This quantity contains the linear and angular velocities of the actor frame of the root + rigid body relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def root_com_pose_w(self) -> ProxyArray: + """Root center of mass pose ``[pos, quat]`` in simulation world frame. + + Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). + + This quantity is the pose of the center of mass frame of the root rigid body relative to the world. + The orientation is provided in (x, y, z, w) format. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names=POSE6_ELEMENT_NAMES) + def root_com_vel_w(self) -> ProxyArray: + """Root center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. + + Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). + + This quantity contains the linear and angular velocities of the root rigid body's center of mass frame + relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/state") + def root_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_com_vel_w`.""" + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/link_state") + def root_link_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_link_vel_w`.""" + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/com_state") + def root_com_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`root_com_pose_w` and :attr:`root_com_vel_w`.""" + raise NotImplementedError() + + ## + # Body state properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_link_pose_w(self) -> ProxyArray: + """Body link pose ``[pos, quat]`` in simulation world frame. + + Shape is (num_instances, 1), dtype = wp.transformf. + In torch this resolves to (num_instances, 1, 7). + + This quantity is the pose of the actor frame of the rigid body relative to the world. + The orientation is provided in (x, y, z, w) format. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_link_vel_w(self) -> ProxyArray: + """Body link velocity ``[lin_vel, ang_vel]`` in simulation world frame. + + Shape is (num_instances, 1), dtype = wp.spatial_vectorf. + In torch this resolves to (num_instances, 1, 6). + + This quantity contains the linear and angular velocities of the actor frame of the root + rigid body relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_com_pose_w(self) -> ProxyArray: + """Body center of mass pose ``[pos, quat]`` in simulation world frame. + + Shape is (num_instances, 1), dtype = wp.transformf. + In torch this resolves to (num_instances, 1, 7). + + This quantity is the pose of the center of mass frame of the rigid body relative to the world. + The orientation is provided in (x, y, z, w) format. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_com_vel_w(self) -> ProxyArray: + """Body center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. + + Shape is (num_instances, 1), dtype = wp.spatial_vectorf. + In torch this resolves to (num_instances, 1, 6). + + This quantity contains the linear and angular velocities of the root rigid body's center of mass frame + relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/state") + def body_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_com_vel_w`.""" + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/link_state") + def body_link_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_link_vel_w`.""" + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/com_state") + def body_com_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`body_com_pose_w` and :attr:`body_com_vel_w`.""" + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def body_com_acc_w(self) -> ProxyArray: + """Acceleration of all bodies ``[lin_acc, ang_acc]`` in the simulation world frame. + + Shape is (num_instances, 1), dtype = wp.spatial_vectorf. + In torch this resolves to (num_instances, 1, 6). + + This quantity is the acceleration of the rigid bodies' center of mass frame relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_com_pose_b(self) -> ProxyArray: + """Center of mass pose ``[pos, quat]`` of all bodies in their respective body's link frames. + + Shape is (num_instances, 1), dtype = wp.transformf. + In torch this resolves to (num_instances, 1, 7). + + This quantity is the pose of the center of mass frame of the rigid body relative to the body's link frame. + The orientation is provided in (x, y, z, w) format. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def body_mass(self) -> ProxyArray: + """Mass of all bodies in the simulation world frame. + + Shape is (num_instances, 1), dtype = wp.float32. + In torch this resolves to (num_instances, 1). + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def body_inertia(self) -> ProxyArray: + """Inertia of all bodies in the simulation world frame. + + Shape is (num_instances, 1, 9), dtype = wp.float32. + In torch this resolves to (num_instances, 1, 9). + """ + raise NotImplementedError() + + ## + # Derived Properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.VECTOR3D, element_names=XYZ_ELEMENT_NAMES) + def projected_gravity_b(self) -> ProxyArray: + """Projection of the gravity direction on base frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/heading") + def heading_w(self) -> ProxyArray: + """Yaw heading of the base frame (in radians). + + Shape is (num_instances,), dtype = wp.float32. In torch this resolves to (num_instances,). + + .. note:: + This quantity is computed by assuming that the forward-direction of the base + frame is along x-direction, i.e. :math:`(1, 0, 0)`. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_lin_vel_b(self) -> ProxyArray: + """Root link linear velocity in base frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the linear velocity of the actor frame of the root rigid body frame with respect to the + rigid body's actor frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_ang_vel_b(self) -> ProxyArray: + """Root link angular velocity in base frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the angular velocity of the actor frame of the root rigid body frame with respect to the + rigid body's actor frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_lin_vel_b(self) -> ProxyArray: + """Root center of mass linear velocity in base frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the linear velocity of the root rigid body's center of mass frame with respect to the + rigid body's actor frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_ang_vel_b(self) -> ProxyArray: + """Root center of mass angular velocity in base frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the angular velocity of the root rigid body's center of mass frame with respect to the + rigid body's actor frame. + """ + raise NotImplementedError() + + ## + # Sliced properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def root_link_pos_w(self) -> ProxyArray: + """Root link position in simulation world frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the position of the actor frame of the root rigid body relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def root_link_quat_w(self) -> ProxyArray: + """Root link orientation (x, y, z, w) in simulation world frame. + + Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). + + This quantity is the orientation of the actor frame of the root rigid body. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_lin_vel_w(self) -> ProxyArray: + """Root linear velocity in simulation world frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the linear velocity of the root rigid body's actor frame relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_ang_vel_w(self) -> ProxyArray: + """Root link angular velocity in simulation world frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the angular velocity of the actor frame of the root rigid body relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def root_com_pos_w(self) -> ProxyArray: + """Root center of mass position in simulation world frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the position of the center of mass frame of the root rigid body relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def root_com_quat_w(self) -> ProxyArray: + """Root center of mass orientation (x, y, z, w) in simulation world frame. + + Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). + + This quantity is the orientation of the principal axes of inertia of the root rigid body relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_lin_vel_w(self) -> ProxyArray: + """Root center of mass linear velocity in simulation world frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the linear velocity of the root rigid body's center of mass frame relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_ang_vel_w(self) -> ProxyArray: + """Root center of mass angular velocity in simulation world frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the angular velocity of the root rigid body's center of mass frame relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_link_pos_w(self) -> ProxyArray: + """Positions of all bodies in simulation world frame. + + Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). + + This quantity is the position of the rigid bodies' actor frame relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_link_quat_w(self) -> ProxyArray: + """Orientation (x, y, z, w) of all bodies in simulation world frame. + + Shape is (num_instances, 1), dtype = wp.quatf. In torch this resolves to (num_instances, 1, 4). + + This quantity is the orientation of the rigid bodies' actor frame relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_lin_vel_w(self) -> ProxyArray: + """Linear velocity of all bodies in simulation world frame. + + Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). + + This quantity is the linear velocity of the rigid bodies' actor frame relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_ang_vel_w(self) -> ProxyArray: + """Angular velocity of all bodies in simulation world frame. + + Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). + + This quantity is the angular velocity of the rigid bodies' actor frame relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_com_pos_w(self) -> ProxyArray: + """Positions of all bodies' center of mass in simulation world frame. + + Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). + + This quantity is the position of the rigid bodies' center of mass frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_com_quat_w(self) -> ProxyArray: + """Orientation (x, y, z, w) of the principal axes of inertia of all bodies in simulation world frame. + + Shape is (num_instances, 1), dtype = wp.quatf. In torch this resolves to (num_instances, 1, 4). + + This quantity is the orientation of the rigid bodies' principal axes of inertia. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_lin_vel_w(self) -> ProxyArray: + """Linear velocity of all bodies in simulation world frame. + + Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). + + This quantity is the linear velocity of the rigid bodies' center of mass frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_ang_vel_w(self) -> ProxyArray: + """Angular velocity of all bodies in simulation world frame. + + Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). + + This quantity is the angular velocity of the rigid bodies' center of mass frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_com_lin_acc_w(self) -> ProxyArray: + """Linear acceleration of all bodies in simulation world frame. + + Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). + + This quantity is the linear acceleration of the rigid bodies' center of mass frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_com_ang_acc_w(self) -> ProxyArray: + """Angular acceleration of all bodies in simulation world frame. + + Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). + + This quantity is the angular acceleration of the rigid bodies' center of mass frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_com_pos_b(self) -> ProxyArray: + """Center of mass position of all of the bodies in their respective link frames. + + Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). + + This quantity is the center of mass location relative to its body's link frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_com_quat_b(self) -> ProxyArray: + """Orientation (x, y, z, w) of the principal axes of inertia of all of the bodies in their + respective link frames. + + Shape is (num_instances, 1), dtype = wp.quatf. In torch this resolves to (num_instances, 1, 4). + + This quantity is the orientation of the principal axes of inertia relative to its body's link frame. + """ + raise NotImplementedError() + + def _create_buffers(self) -> None: + # -- Default mass and inertia (Lazy allocation of default values) + self._default_mass = None + self._default_inertia = None + + """ + Shorthands for commonly used properties. + """ + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def root_pose_w(self) -> ProxyArray: + """Shorthand for :attr:`root_link_pose_w`.""" + return self.root_link_pose_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def root_pos_w(self) -> ProxyArray: + """Shorthand for :attr:`root_link_pos_w`.""" + return self.root_link_pos_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def root_quat_w(self) -> ProxyArray: + """Shorthand for :attr:`root_link_quat_w`.""" + return self.root_link_quat_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names=POSE6_ELEMENT_NAMES) + def root_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`root_com_vel_w`.""" + return self.root_com_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_lin_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`root_com_lin_vel_w`.""" + return self.root_com_lin_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_ang_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`root_com_ang_vel_w`.""" + return self.root_com_ang_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_lin_vel_b(self) -> ProxyArray: + """Shorthand for :attr:`root_com_lin_vel_b`.""" + return self.root_com_lin_vel_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_ang_vel_b(self) -> ProxyArray: + """Shorthand for :attr:`root_com_ang_vel_b`.""" + return self.root_com_ang_vel_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_pose_w(self) -> ProxyArray: + """Shorthand for :attr:`body_link_pose_w`.""" + return self.body_link_pose_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_pos_w(self) -> ProxyArray: + """Shorthand for :attr:`body_link_pos_w`.""" + return self.body_link_pos_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_quat_w(self) -> ProxyArray: + """Shorthand for :attr:`body_link_quat_w`.""" + return self.body_link_quat_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_vel_w`.""" + return self.body_com_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_lin_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_lin_vel_w`.""" + return self.body_com_lin_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_ang_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_ang_vel_w`.""" + return self.body_com_ang_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def body_acc_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_acc_w`.""" + return self.body_com_acc_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_lin_acc_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_lin_acc_w`.""" + return self.body_com_lin_acc_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_ang_acc_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_ang_acc_w`.""" + return self.body_com_ang_acc_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def com_pos_b(self) -> ProxyArray: + """Shorthand for :attr:`body_com_pos_b`.""" + return self.body_com_pos_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def com_quat_b(self) -> ProxyArray: + """Shorthand for :attr:`body_com_quat_b`.""" + return self.body_com_quat_b + + """ + Removed - Default values are no longer stored. + """ + + @property + @leapp_tensor_semantics(const=True) + def default_mass(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_mass` instead and manage the default mass manually.""" + warnings.warn( + "The `default_mass` property will be deprecated in a IsaacLab 4.0. Please use `body_mass` instead. " + "The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_mass is None: + self._default_mass = wp.clone(self.body_mass.warp, self.device) + return ProxyArray(self._default_mass) + + @property + @leapp_tensor_semantics(const=True) + def default_inertia(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_inertia` instead and manage the default inertia manually.""" + warnings.warn( + "The `default_inertia` property will be deprecated in a IsaacLab 4.0. Please use `body_inertia` instead. " + "The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_inertia is None: + self._default_inertia = wp.clone(self.body_inertia.warp, self.device) + return ProxyArray(self._default_inertia) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/rigid_object.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/rigid_object.py new file mode 100644 index 0000000000000000000000000000000000000000..d1a8ecc11ce93f2a16b4cf7ddbbe3160eed16138 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/rigid_object.py @@ -0,0 +1,30 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.backend_utils import FactoryBase + +from .base_rigid_object import BaseRigidObject +from .base_rigid_object_data import BaseRigidObjectData + +if TYPE_CHECKING: + from isaaclab_physx.assets.rigid_object import RigidObject as PhysXRigidObject + from isaaclab_physx.assets.rigid_object import RigidObjectData as PhysXRigidObjectData + + +class RigidObject(FactoryBase, BaseRigidObject): + """Factory for creating rigid object instances.""" + + data: BaseRigidObjectData | PhysXRigidObjectData + + def __new__(cls, *args, **kwargs) -> BaseRigidObject | PhysXRigidObject: + """Create a new instance of a rigid object based on the backend.""" + # The `FactoryBase` __new__ method will handle the logic and return + # an instance of the correct backend-specific rigid object class, + # which is guaranteed to be a subclass of `BaseRigidObject` by convention. + return super().__new__(cls, *args, **kwargs) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/rigid_object_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/rigid_object_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1f881fae891b8912bbaaa85a57e02f369b0ae6 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/rigid_object_cfg.py @@ -0,0 +1,36 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from typing import TYPE_CHECKING + +from isaaclab.utils.configclass import configclass + +from ..asset_base_cfg import AssetBaseCfg + +if TYPE_CHECKING: + from .rigid_object import RigidObject + + +@configclass +class RigidObjectCfg(AssetBaseCfg): + """Configuration parameters for a rigid object.""" + + @configclass + class InitialStateCfg(AssetBaseCfg.InitialStateCfg): + """Initial state of the rigid body.""" + + lin_vel: tuple[float, float, float] = (0.0, 0.0, 0.0) + """Linear velocity of the root in simulation world frame. Defaults to (0.0, 0.0, 0.0).""" + ang_vel: tuple[float, float, float] = (0.0, 0.0, 0.0) + """Angular velocity of the root in simulation world frame. Defaults to (0.0, 0.0, 0.0).""" + + ## + # Initialize configurations. + ## + + class_type: type["RigidObject"] | str = "{DIR}.rigid_object:RigidObject" + + init_state: InitialStateCfg = InitialStateCfg() + """Initial state of the rigid object. Defaults to identity pose with zero velocity.""" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/rigid_object_data.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/rigid_object_data.py new file mode 100644 index 0000000000000000000000000000000000000000..a81e44892c0a70e27268a7d7e1add8841af8c9db --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object/rigid_object_data.py @@ -0,0 +1,23 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.backend_utils import FactoryBase + +from .base_rigid_object_data import BaseRigidObjectData + +if TYPE_CHECKING: + from isaaclab_physx.assets.rigid_object.rigid_object_data import RigidObjectData as PhysXRigidObjectData + + +class RigidObjectData(FactoryBase): + """Factory for creating rigid object data instances.""" + + def __new__(cls, *args, **kwargs) -> BaseRigidObjectData | PhysXRigidObjectData: + """Create a new instance of a rigid object data based on the backend.""" + return super().__new__(cls, *args, **kwargs) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bb3636b55d8aba773c7a4895fe0f4178b093a648 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module for rigid object collection.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4c0a20555613e6c03d74ff291762ea32944a9f12 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__init__.pyi @@ -0,0 +1,18 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "BaseRigidObjectCollection", + "BaseRigidObjectCollectionData", + "RigidObjectCollection", + "RigidObjectCollectionCfg", + "RigidObjectCollectionData", +] + +from .base_rigid_object_collection import BaseRigidObjectCollection +from .base_rigid_object_collection_data import BaseRigidObjectCollectionData +from .rigid_object_collection import RigidObjectCollection +from .rigid_object_collection_cfg import RigidObjectCollectionCfg +from .rigid_object_collection_data import RigidObjectCollectionData diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/__init__.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c0a0e232d93a82ddcf4954e96ef8d1cbb7c5753 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/base_rigid_object_collection.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/base_rigid_object_collection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b823f8b0f4757f74eb2ba11a29ba2fe1ff4e75c Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/base_rigid_object_collection.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/base_rigid_object_collection_data.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/base_rigid_object_collection_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac8e0d54454b2553b27a69c45d3075e5e1b27530 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/base_rigid_object_collection_data.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/rigid_object_collection.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/rigid_object_collection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38f3d78a6ef3544dd610566dbdab33e12d10f293 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/rigid_object_collection.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/rigid_object_collection_cfg.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/rigid_object_collection_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ec620f36720cca8b1189d0fc37b17eb6083e246 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/__pycache__/rigid_object_collection_cfg.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/base_rigid_object_collection.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/base_rigid_object_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..4be586145b0e7653788a06dacdf2c6236270ec4f --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/base_rigid_object_collection.py @@ -0,0 +1,1070 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import warnings +from abc import abstractmethod +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch +import warp as wp + +from isaaclab.utils.wrench_composer import WrenchComposer + +from ..asset_base import AssetBase + +if TYPE_CHECKING: + from .rigid_object_collection_cfg import RigidObjectCollectionCfg + from .rigid_object_collection_data import RigidObjectCollectionData + + +class BaseRigidObjectCollection(AssetBase): + """A rigid object collection class. + + This class represents a collection of rigid objects in the simulation, where the state of the + rigid objects can be accessed and modified using a batched ``(env_ids, object_ids)`` API. + + For each rigid body in the collection, the root prim of the asset must have the `USD RigidBodyAPI`_ + applied to it. This API is used to define the simulation properties of the rigid bodies. On playing the + simulation, the physics engine will automatically register the rigid bodies and create a corresponding + rigid body handle. This handle can be accessed using the :attr:`root_view` attribute. + + Rigid objects in the collection are uniquely identified via the key of the dictionary + :attr:`~isaaclab.assets.RigidObjectCollectionCfg.rigid_objects` in the + :class:`~isaaclab.assets.RigidObjectCollectionCfg` configuration class. + This differs from the :class:`~isaaclab.assets.RigidObject` class, where a rigid object is identified by + the name of the Xform where the `USD RigidBodyAPI`_ is applied. This would not be possible for the rigid + object collection since the :attr:`~isaaclab.assets.RigidObjectCollectionCfg.rigid_objects` dictionary + could contain the same rigid object multiple times, leading to ambiguity. + + .. _`USD RigidBodyAPI`: https://openusd.org/dev/api/class_usd_physics_rigid_body_a_p_i.html + """ + + cfg: RigidObjectCollectionCfg + """Configuration instance for the rigid object.""" + + __backend_name__: str = "base" + """The name of the backend for the rigid object.""" + + def __init__(self, cfg: RigidObjectCollectionCfg): + """Initialize the rigid object. + + Args: + cfg: A configuration instance. + """ + pass + + """ + Properties + """ + + @property + @abstractmethod + def data(self) -> RigidObjectCollectionData: + raise NotImplementedError() + + @property + @abstractmethod + def num_instances(self) -> int: + raise NotImplementedError() + + @property + @abstractmethod + def num_bodies(self) -> int: + """Number of bodies in the rigid object collection.""" + raise NotImplementedError() + + @property + @abstractmethod + def body_names(self) -> list[str]: + """Ordered names of bodies in the rigid object collection.""" + raise NotImplementedError() + + @property + @abstractmethod + def root_view(self): + """Root view for the rigid object collection. + + .. note:: + Use this view with caution. It requires handling of tensors in a specific way. + """ + raise NotImplementedError() + + @property + @abstractmethod + def instantaneous_wrench_composer(self) -> WrenchComposer: + """Instantaneous wrench composer. + + Returns a :class:`~isaaclab.utils.wrench_composer.WrenchComposer` instance. Wrenches added or set to this wrench + composer are only valid for the current simulation step. At the end of the simulation step, the wrenches set + to this object are discarded. This is useful to apply forces that change all the time, things like drag forces + for instance. + """ + raise NotImplementedError() + + @property + @abstractmethod + def permanent_wrench_composer(self) -> WrenchComposer: + """Permanent wrench composer. + + Returns a :class:`~isaaclab.utils.wrench_composer.WrenchComposer` instance. Wrenches added or set to this wrench + composer are persistent and are applied to the simulation at every step. This is useful to apply forces that + are constant over a period of time, things like the thrust of a motor for instance. + """ + raise NotImplementedError() + + """ + Operations. + """ + + @abstractmethod + def reset( + self, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + object_ids: slice | torch.Tensor | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Resets all internal buffers of selected environments and objects. + + .. caution:: + If both `env_ids` and `env_mask` are provided, then `env_mask` takes precedence over `env_ids`. + + Args: + env_ids: Environment indices. If None, then all indices are used. + object_ids: Object indices. If None, then all indices are used. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_data_to_sim(self) -> None: + """Write external wrench to the simulation. + + .. note:: + We write external wrench to the simulation here since this function is called before the simulation step. + This ensures that the external wrench is applied at every simulation step. + """ + raise NotImplementedError() + + @abstractmethod + def update(self, dt: float) -> None: + """Updates the simulation data. + + Args: + dt: The time step size in seconds. + """ + raise NotImplementedError() + + """ + Operations - Finders. + """ + + @abstractmethod + def find_bodies( + self, name_keys: str | Sequence[str], preserve_order: bool = False + ) -> tuple[torch.Tensor, list[str]]: + """Find bodies in the rigid body collection based on the name keys. + + Please check the :meth:`isaaclab.utils.string_utils.resolve_matching_names` function for more + information on the name matching. + + Args: + name_keys: A regular expression or a list of regular expressions to match the body names. + preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False. + + Returns: + A tuple of lists containing the body indices and names. + """ + raise NotImplementedError() + + """ + Operations - Write to simulation. + """ + + @abstractmethod + def write_body_pose_to_sim_index( + self, + *, + body_poses: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the body poses over selected environment and body indices into the simulation. + + The body pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + body_poses: Body poses in simulation frame. Shape is (len(env_ids), len(body_ids), 7) + or (len(env_ids), len(body_ids)) with dtype wp.transformf. + body_ids: Body indices. If None, then all indices are used. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_body_pose_to_sim_mask( + self, + *, + body_poses: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set the body poses over selected environment and body mask into the simulation. + + The body pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + body_poses: Body poses in simulation frame. Shape is (num_instances, num_bodies, 7) + or (num_instances, num_bodies) with dtype wp.transformf. + body_mask: Body mask. If None, then all bodies are used. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_body_link_pose_to_sim_index( + self, + *, + body_poses: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the body link pose over selected environment and body indices into the simulation. + + The body link pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + body_poses: Body link poses in simulation frame. Shape is (len(env_ids), len(body_ids), 7) + or (len(env_ids), len(body_ids)) with dtype wp.transformf. + body_ids: Body indices. If None, then all indices are used. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_body_link_pose_to_sim_mask( + self, + *, + body_poses: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set the body link pose over selected environment and body mask into the simulation. + + The body link pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + body_poses: Body link poses in simulation frame. Shape is (num_instances, num_bodies, 7) + or (num_instances, num_bodies) with dtype wp.transformf. + body_mask: Body mask. If None, then all bodies are used. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_body_com_pose_to_sim_index( + self, + *, + body_poses: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the body center of mass pose over selected environment and body indices into the simulation. + + The body center of mass pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + The orientation is the orientation of the principal axes of inertia. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + body_poses: Body center of mass poses in simulation frame. Shape is (len(env_ids), len(body_ids), 7) + or (len(env_ids), len(body_ids)) with dtype wp.transformf. + body_ids: Body indices. If None, then all indices are used. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_body_com_pose_to_sim_mask( + self, + *, + body_poses: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set the body center of mass pose over selected environment and body mask into the simulation. + + The body center of mass pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + The orientation is the orientation of the principal axes of inertia. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + body_poses: Body center of mass poses in simulation frame. Shape is (num_instances, num_bodies, 7) + or (num_instances, num_bodies) with dtype wp.transformf. + body_mask: Body mask. If None, then all bodies are used. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_body_velocity_to_sim_index( + self, + *, + body_velocities: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the body velocity over selected environment and body indices into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the body's center of mass rather than the body's frame. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + body_velocities: Body velocities in simulation frame. Shape is (len(env_ids), len(body_ids), 6) + or (len(env_ids), len(body_ids)) with dtype wp.spatial_vectorf. + body_ids: Body indices. If None, then all indices are used. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_body_velocity_to_sim_mask( + self, + *, + body_velocities: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set the body velocity over selected environment and body mask into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the body's center of mass rather than the body's frame. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + body_velocities: Body velocities in simulation frame. Shape is (num_instances, num_bodies, 6) + or (num_instances, num_bodies) with dtype wp.spatial_vectorf. + body_mask: Body mask. If None, then all bodies are used. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_body_com_velocity_to_sim_index( + self, + *, + body_velocities: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the body center of mass velocity over selected environment and body indices into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the body's center of mass rather than the body's frame. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + body_velocities: Body center of mass velocities in simulation frame. Shape is + (len(env_ids), len(body_ids), 6) or (len(env_ids), len(body_ids)) with dtype wp.spatial_vectorf. + body_ids: Body indices. If None, then all indices are used. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_body_com_velocity_to_sim_mask( + self, + *, + body_velocities: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set the body center of mass velocity over selected environment and body mask into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the body's center of mass rather than the body's frame. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + body_velocities: Body center of mass velocities in simulation frame. Shape is + (num_instances, num_bodies, 6) or (num_instances, num_bodies) with dtype wp.spatial_vectorf. + body_mask: Body mask. If None, then all bodies are used. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def write_body_link_velocity_to_sim_index( + self, + *, + body_velocities: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set the body link velocity over selected environment and body indices into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the body's frame rather than the body's center of mass. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + body_velocities: Body link velocities in simulation frame. Shape is (len(env_ids), len(body_ids), 6) + or (len(env_ids), len(body_ids)) with dtype wp.spatial_vectorf. + body_ids: Body indices. If None, then all indices are used. + env_ids: Environment indices. If None, then all indices are used. + """ + raise NotImplementedError() + + @abstractmethod + def write_body_link_velocity_to_sim_mask( + self, + *, + body_velocities: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set the body link velocity over selected environment and body mask into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the body's frame rather than the body's center of mass. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + body_velocities: Body link velocities in simulation frame. Shape is (num_instances, num_bodies, 6) + or (num_instances, num_bodies) with dtype wp.spatial_vectorf. + body_mask: Body mask. If None, then all bodies are used. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + """ + Operations - Setters. + """ + + @abstractmethod + def set_masses_index( + self, + *, + masses: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set masses of all bodies. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + masses: Masses of all bodies. Shape is (len(env_ids), len(body_ids)). + body_ids: The body indices to set the masses for. Defaults to None (all bodies). + env_ids: The environment indices to set the masses for. Defaults to None (all environments). + """ + raise NotImplementedError() + + @abstractmethod + def set_masses_mask( + self, + *, + masses: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set masses of all bodies. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + masses: Masses of all bodies. Shape is (num_instances, num_bodies). + body_mask: Body mask. If None, then all bodies are used. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_coms_index( + self, + *, + coms: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set center of mass positions of all bodies. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + coms: Center of mass positions of all bodies. Shape is (len(env_ids), len(body_ids), 3). + body_ids: The body indices to set the center of mass positions for. Defaults to None (all bodies). + env_ids: The environment indices to set the center of mass positions for. Defaults to None + (all environments). + """ + raise NotImplementedError() + + @abstractmethod + def set_coms_mask( + self, + *, + coms: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set center of mass positions of all bodies. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + coms: Center of mass positions of all bodies. Shape is (num_instances, num_bodies, 3) + or (num_instances, num_bodies) with dtype wp.vec3f. + body_mask: Body mask. If None, then all bodies are used. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + @abstractmethod + def set_inertias_index( + self, + *, + inertias: torch.Tensor | wp.array, + body_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set inertias of all bodies. + + .. note:: + This method expects partial data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + inertias: Inertias of all bodies. Shape is (len(env_ids), len(body_ids), 9). + body_ids: The body indices to set the inertias for. Defaults to None (all bodies). + env_ids: The environment indices to set the inertias for. Defaults to None (all environments). + """ + raise NotImplementedError() + + @abstractmethod + def set_inertias_mask( + self, + *, + inertias: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set inertias of all bodies. + + .. note:: + This method expects full data. + + .. tip:: + For maximum performance we recommend looking at the actual implementation of the method in the backend. + Some backends may provide optimized implementations for masks / indices. + + Args: + inertias: Inertias of all bodies. Shape is (num_instances, num_bodies, 9). + body_mask: Body mask. If None, then all bodies are used. Shape is (num_bodies,). + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + raise NotImplementedError() + + """ + Internal helper. + """ + + @abstractmethod + def _initialize_impl(self) -> None: + raise NotImplementedError() + + @abstractmethod + def _create_buffers(self) -> None: + raise NotImplementedError() + + @abstractmethod + def _process_cfg(self) -> None: + """Post processing of configuration parameters.""" + raise NotImplementedError() + + """ + Internal simulation callbacks. + """ + + @abstractmethod + def _invalidate_initialize_callback(self, event) -> None: + """Invalidates the scene elements.""" + super()._invalidate_initialize_callback(event) + + """ + Deprecated properties and methods. + """ + + @property + def num_objects(self) -> int: + """Deprecated property. Please use :attr:`num_bodies` instead.""" + warnings.warn( + "The `num_objects` property will be deprecated in a future release. Please use `num_bodies` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.num_bodies + + @property + def object_names(self) -> list[str]: + """Deprecated property. Please use :attr:`body_names` instead.""" + warnings.warn( + "The `object_names` property will be deprecated in a future release. Please use `body_names` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_names + + @abstractmethod + def write_body_state_to_sim( + self, + body_states: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + body_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated, same as :meth:`write_body_link_pose_to_sim_index` and + :meth:`write_body_com_velocity_to_sim_index`.""" + raise NotImplementedError() + + @abstractmethod + def write_body_com_state_to_sim( + self, + body_states: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + body_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated, same as :meth:`write_body_com_pose_to_sim_index` and + :meth:`write_body_com_velocity_to_sim_index`.""" + raise NotImplementedError() + + @abstractmethod + def write_body_link_state_to_sim( + self, + body_states: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + body_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated, same as :meth:`write_body_link_pose_to_sim_index` and + :meth:`write_body_link_velocity_to_sim_index`.""" + raise NotImplementedError() + + def write_body_pose_to_sim( + self, + body_poses: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + body_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated, same as :meth:`write_body_pose_to_sim_index`.""" + warnings.warn( + "The function 'write_body_pose_to_sim' will be deprecated in a future release. Please" + " use 'write_body_pose_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_pose_to_sim_index(body_poses=body_poses, env_ids=env_ids, body_ids=body_ids) + + def write_body_link_pose_to_sim( + self, + body_poses: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + body_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated, same as :meth:`write_body_link_pose_to_sim_index`.""" + warnings.warn( + "The function 'write_body_link_pose_to_sim' will be deprecated in a future release. Please" + " use 'write_body_link_pose_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_link_pose_to_sim_index(body_poses=body_poses, env_ids=env_ids, body_ids=body_ids) + + def write_body_com_pose_to_sim( + self, + body_poses: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + body_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated, same as :meth:`write_body_com_pose_to_sim_index`.""" + warnings.warn( + "The function 'write_body_com_pose_to_sim' will be deprecated in a future release. Please" + " use 'write_body_com_pose_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_com_pose_to_sim_index(body_poses=body_poses, env_ids=env_ids, body_ids=body_ids) + + def write_body_velocity_to_sim( + self, + body_velocities: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + body_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated, same as :meth:`write_body_velocity_to_sim_index`.""" + warnings.warn( + "The function 'write_body_velocity_to_sim' will be deprecated in a future release. Please" + " use 'write_body_velocity_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_velocity_to_sim_index(body_velocities=body_velocities, env_ids=env_ids, body_ids=body_ids) + + def write_body_com_velocity_to_sim( + self, + body_velocities: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + body_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated, same as :meth:`write_body_com_velocity_to_sim_index`.""" + warnings.warn( + "The function 'write_body_com_velocity_to_sim' will be deprecated in a future release. Please" + " use 'write_body_com_velocity_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_com_velocity_to_sim_index(body_velocities=body_velocities, env_ids=env_ids, body_ids=body_ids) + + def write_body_link_velocity_to_sim( + self, + body_velocities: torch.Tensor | wp.array, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + body_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated, same as :meth:`write_body_link_velocity_to_sim_index`.""" + warnings.warn( + "The function 'write_body_link_velocity_to_sim' will be deprecated in a future release. Please" + " use 'write_body_link_velocity_to_sim_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_link_velocity_to_sim_index(body_velocities=body_velocities, env_ids=env_ids, body_ids=body_ids) + + def set_masses( + self, + masses: torch.Tensor | wp.array, + body_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_masses_index`.""" + warnings.warn( + "The function 'set_masses' will be deprecated in a future release. Please use 'set_masses_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_masses_index(masses=masses, body_ids=body_ids, env_ids=env_ids) + + def set_coms( + self, + coms: torch.Tensor | wp.array, + body_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_coms_index`.""" + warnings.warn( + "The function 'set_coms' will be deprecated in a future release. Please use 'set_coms_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_coms_index(coms=coms, body_ids=body_ids, env_ids=env_ids) + + def set_inertias( + self, + inertias: torch.Tensor | wp.array, + body_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Deprecated, same as :meth:`set_inertias_index`.""" + warnings.warn( + "The function 'set_inertias' will be deprecated in a future release. Please" + " use 'set_inertias_index' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.set_inertias_index(inertias=inertias, body_ids=body_ids, env_ids=env_ids) + + def set_external_force_and_torque( + self, + forces: torch.Tensor | wp.array, + torques: torch.Tensor | wp.array, + positions: torch.Tensor | wp.array | None = None, + body_ids: Sequence[int] | slice | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + is_global: bool = False, + ) -> None: + """Deprecated. Resets target environments, then adds forces and torques via the permanent wrench composer.""" + warnings.warn( + "The function 'set_external_force_and_torque' is deprecated. Please use" + " 'permanent_wrench_composer.reset' followed by 'permanent_wrench_composer.add_forces_and_torques'" + " instead.", + DeprecationWarning, + stacklevel=2, + ) + # Reset only target env_ids then add (not set which clears all envs globally) + self.permanent_wrench_composer.reset(env_ids=env_ids) + self.permanent_wrench_composer.add_forces_and_torques( + forces, torques, positions=positions, body_ids=body_ids, env_ids=env_ids, is_global=is_global + ) + + def write_object_state_to_sim( + self, + object_state: torch.Tensor, + env_ids: torch.Tensor | None = None, + object_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated method. Please use :meth:`write_body_pose_to_sim_index` and + :meth:`write_body_link_velocity_to_sim_index` instead.""" + warnings.warn( + "The `write_object_state_to_sim` method will be deprecated in a future release. Please use" + " `write_body_pose_to_sim_index` and `write_body_link_velocity_to_sim_index` instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_state_to_sim(object_state, env_ids=env_ids, body_ids=object_ids) + + def write_object_com_state_to_sim( + self, + object_state: torch.Tensor, + env_ids: torch.Tensor | None = None, + object_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated method. Please use :meth:`write_body_com_pose_to_sim_index` and + :meth:`write_body_velocity_to_sim_index` instead.""" + warnings.warn( + "The `write_object_com_state_to_sim` method will be deprecated in a future release. Please use" + " `write_body_com_pose_to_sim_index` and `write_body_velocity_to_sim_index` instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_com_state_to_sim(object_state, env_ids=env_ids, body_ids=object_ids) + + def write_object_link_state_to_sim( + self, + object_state: torch.Tensor, + env_ids: torch.Tensor | None = None, + object_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated method. Please use :meth:`write_body_pose_to_sim_index` and + :meth:`write_body_link_velocity_to_sim_index` instead.""" + warnings.warn( + "The `write_object_link_state_to_sim` method will be deprecated in a future release. Please use" + " `write_body_pose_to_sim_index` and `write_body_link_velocity_to_sim_index` instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_link_state_to_sim(object_state, env_ids=env_ids, body_ids=object_ids) + + def write_object_pose_to_sim( + self, + object_pose: torch.Tensor, + env_ids: torch.Tensor | None = None, + object_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated method. Please use :meth:`write_body_pose_to_sim_index` instead.""" + warnings.warn( + "The `write_object_pose_to_sim` method will be deprecated in a future release. Please use" + " `write_body_pose_to_sim_index` instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_pose_to_sim_index(body_poses=object_pose, env_ids=env_ids, body_ids=object_ids) + + def write_object_link_pose_to_sim( + self, + object_pose: torch.Tensor, + env_ids: torch.Tensor | None = None, + object_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated method. Please use :meth:`write_body_link_pose_to_sim_index` instead.""" + warnings.warn( + "The `write_object_link_pose_to_sim` method will be deprecated in a future release. Please use" + " `write_body_link_pose_to_sim_index` instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_link_pose_to_sim_index(body_poses=object_pose, env_ids=env_ids, body_ids=object_ids) + + def write_object_com_pose_to_sim( + self, + object_pose: torch.Tensor, + env_ids: torch.Tensor | None = None, + object_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated method. Please use :meth:`write_body_com_pose_to_sim_index` instead.""" + warnings.warn( + "The `write_object_com_pose_to_sim` method will be deprecated in a future release. Please use" + " `write_body_com_pose_to_sim_index` instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_com_pose_to_sim_index(body_poses=object_pose, env_ids=env_ids, body_ids=object_ids) + + def write_object_velocity_to_sim( + self, + object_velocity: torch.Tensor, + env_ids: torch.Tensor | None = None, + object_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated method. Please use :meth:`write_body_com_velocity_to_sim_index` instead.""" + warnings.warn( + "The `write_object_velocity_to_sim` method will be deprecated in a future release. Please use" + " `write_body_com_velocity_to_sim_index` instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_com_velocity_to_sim_index(body_velocities=object_velocity, env_ids=env_ids, body_ids=object_ids) + + def write_object_com_velocity_to_sim( + self, + object_velocity: torch.Tensor, + env_ids: torch.Tensor | None = None, + object_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated method. Please use :meth:`write_body_com_velocity_to_sim_index` instead.""" + warnings.warn( + "The `write_object_com_velocity_to_sim` method will be deprecated in a future release. Please use" + " `write_body_com_velocity_to_sim_index` instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_com_velocity_to_sim_index(body_velocities=object_velocity, env_ids=env_ids, body_ids=object_ids) + + def write_object_link_velocity_to_sim( + self, + object_velocity: torch.Tensor, + env_ids: torch.Tensor | None = None, + object_ids: slice | torch.Tensor | None = None, + ) -> None: + """Deprecated method. Please use :meth:`write_body_link_velocity_to_sim_index` instead.""" + warnings.warn( + "The `write_object_link_velocity_to_sim` method will be deprecated in a future release. Please use" + " `write_body_link_velocity_to_sim_index` instead.", + DeprecationWarning, + stacklevel=2, + ) + self.write_body_link_velocity_to_sim_index( + body_velocities=object_velocity, env_ids=env_ids, body_ids=object_ids + ) + + def find_objects( + self, name_keys: str | Sequence[str], preserve_order: bool = False + ) -> tuple[torch.Tensor, list[str]]: + """Deprecated method. Please use :meth:`find_bodies` instead.""" + warnings.warn( + "The `find_objects` method will be deprecated in a future release. Please use `find_bodies` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.find_bodies(name_keys, preserve_order) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/base_rigid_object_collection_data.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/base_rigid_object_collection_data.py new file mode 100644 index 0000000000000000000000000000000000000000..37842c23264a45717e2e4dca2203eb50092f9b92 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/base_rigid_object_collection_data.py @@ -0,0 +1,1052 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from abc import ABC, abstractmethod + +import warp as wp + +from isaaclab.utils.leapp import ( + InputKindEnum, + body_pose6_resolver, + body_pose_resolver, + body_quat_resolver, + body_xyz_resolver, + leapp_tensor_semantics, +) +from isaaclab.utils.warp import ProxyArray + + +class BaseRigidObjectCollectionData(ABC): + """Data container for a rigid object collection. + + This class contains the data for a rigid object collection in the simulation. The data includes the state of + all the bodies in the collection. The data is stored in the simulation world frame unless otherwise specified. + The data is in the order ``(num_instances, num_objects, data_size)``, where data_size is the size of the data. + + For a rigid body, there are two frames of reference that are used: + + - Actor frame: The frame of reference of the rigid body prim. This typically corresponds to the Xform prim + with the rigid body schema. + - Center of mass frame: The frame of reference of the center of mass of the rigid body. + + Depending on the settings of the simulation, the actor frame and the center of mass frame may be the same. + This needs to be taken into account when interpreting the data. + + The data is lazily updated, meaning that the data is only updated when it is accessed. This is useful + when the data is expensive to compute or retrieve. The data is updated when the timestamp of the buffer + is older than the current simulation timestamp. The timestamp is updated whenever the data is updated. + """ + + def __init__(self, root_view, num_objects: int, device: str): + """Initializes the rigid object data. + + Args: + root_view: The root rigid body collection view. + num_objects: The number of objects in the collection. + device: The device used for processing. + """ + # Set the parameters + self.device = device + + @abstractmethod + def update(self, dt: float) -> None: + """Updates the data for the rigid object. + + Args: + dt: The time step for the update. This must be a positive value. + """ + raise NotImplementedError() + + ## + # Names. + ## + + body_names: list[str] | None = None + """Body names in the order parsed by the simulation view.""" + + ## + # Defaults. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def default_body_pose(self) -> ProxyArray: + """Default body pose ``[pos, quat]`` in local environment frame. + + The position and quaternion are of the rigid body's actor frame. + Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to + (num_instances, num_bodies, 7). + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def default_body_vel(self) -> ProxyArray: + """Default body velocity ``[lin_vel, ang_vel]`` in local environment frame. + + The linear and angular velocities are of the rigid body's center of mass frame. + Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to + (num_instances, num_bodies, 6). + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def default_body_state(self) -> ProxyArray: + """Deprecated, same as :attr:`default_body_pose` and :attr:`default_body_vel`.""" + raise NotImplementedError() + + ## + # Body state properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_link_pose_w(self) -> ProxyArray: + """Body link pose ``[pos, quat]`` in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to + (num_instances, num_bodies, 7). + + This quantity is the pose of the actor frame of the rigid body relative to the world. + The orientation is provided in (x, y, z, w) format. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_link_vel_w(self) -> ProxyArray: + """Body link velocity ``[lin_vel, ang_vel]`` in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to + (num_instances, num_bodies, 6). + + This quantity contains the linear and angular velocities of the actor frame of the root + rigid body relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_com_pose_w(self) -> ProxyArray: + """Body center of mass pose ``[pos, quat]`` in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to + (num_instances, num_bodies, 7). + + This quantity is the pose of the center of mass frame of the rigid body relative to the world. + The orientation is provided in (x, y, z, w) format. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_com_vel_w(self) -> ProxyArray: + """Body center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to + (num_instances, num_bodies, 6). + + This quantity contains the linear and angular velocities of the root rigid body's center of mass frame + relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/state") + def body_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_com_vel_w`.""" + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/link_state") + def body_link_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_link_vel_w`.""" + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/com_state") + def body_com_state_w(self) -> ProxyArray: + """Deprecated, same as :attr:`body_com_pose_w` and :attr:`body_com_vel_w`.""" + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def body_com_acc_w(self) -> ProxyArray: + """Acceleration of all bodies ``[lin_acc, ang_acc]`` in the simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to + (num_instances, num_bodies, 6). + + This quantity is the acceleration of the rigid bodies' center of mass frame relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_com_pose_b(self) -> ProxyArray: + """Center of mass pose ``[pos, quat]`` of all bodies in their respective body's link frames. + + Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to + (num_instances, num_bodies, 7). + + This quantity is the pose of the center of mass frame of the rigid body relative to the body's link frame. + The orientation is provided in (x, y, z, w) format. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def body_mass(self) -> ProxyArray: + """Mass of all bodies in the simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.float32. In torch this resolves to (num_instances, num_bodies). + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(const=True) + def body_inertia(self) -> ProxyArray: + """Inertia of all bodies in the simulation world frame. + + Shape is (num_instances, num_bodies, 9), dtype = wp.float32. In torch this resolves to + (num_instances, num_bodies, 9). + """ + raise NotImplementedError() + + ## + # Derived Properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.VECTOR3D, element_names_resolver=body_xyz_resolver) + def projected_gravity_b(self) -> ProxyArray: + """Projection of the gravity direction on base frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind="state/body/heading") + def heading_w(self) -> ProxyArray: + """Yaw heading of the base frame (in radians). + + Shape is (num_instances, num_bodies), dtype = wp.float32. + In torch this resolves to (num_instances, num_bodies). + + .. note:: + This quantity is computed by assuming that the forward-direction of the base + frame is along x-direction, i.e. :math:`(1, 0, 0)`. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_lin_vel_b(self) -> ProxyArray: + """Root link linear velocity in base frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the linear velocity of the actor frame of the root rigid body frame with respect to the + rigid body's actor frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_ang_vel_b(self) -> ProxyArray: + """Root link angular velocity in base frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the angular velocity of the actor frame of the root rigid body frame with respect to the + rigid body's actor frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_lin_vel_b(self) -> ProxyArray: + """Root center of mass linear velocity in base frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the linear velocity of the root rigid body's center of mass frame with respect to the + rigid body's actor frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_ang_vel_b(self) -> ProxyArray: + """Root center of mass angular velocity in base frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the angular velocity of the root rigid body's center of mass frame with respect to the + rigid body's actor frame. + """ + raise NotImplementedError() + + ## + # Sliced properties. + ## + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_link_pos_w(self) -> ProxyArray: + """Positions of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the position of the rigid bodies' actor frame relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_link_quat_w(self) -> ProxyArray: + """Orientation (x, y, z, w) of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to + (num_instances, num_bodies, 4). + + This quantity is the orientation of the rigid bodies' actor frame relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_lin_vel_w(self) -> ProxyArray: + """Linear velocity of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the linear velocity of the rigid bodies' actor frame relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_ang_vel_w(self) -> ProxyArray: + """Angular velocity of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the angular velocity of the rigid bodies' actor frame relative to the world. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_com_pos_w(self) -> ProxyArray: + """Positions of all bodies' center of mass in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the position of the rigid bodies' center of mass frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_com_quat_w(self) -> ProxyArray: + """Orientation (x, y, z, w) of the principal axes of inertia of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to + (num_instances, num_bodies, 4). + + This quantity is the orientation of the rigid bodies' principal axes of inertia. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_lin_vel_w(self) -> ProxyArray: + """Linear velocity of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the linear velocity of the rigid bodies' center of mass frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_ang_vel_w(self) -> ProxyArray: + """Angular velocity of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the angular velocity of the rigid bodies' center of mass frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_com_lin_acc_w(self) -> ProxyArray: + """Linear acceleration of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the linear acceleration of the rigid bodies' center of mass frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_com_ang_acc_w(self) -> ProxyArray: + """Angular acceleration of all bodies in simulation world frame. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the angular acceleration of the rigid bodies' center of mass frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_com_pos_b(self) -> ProxyArray: + """Center of mass position of all of the bodies in their respective link frames. + + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the center of mass location relative to its body's link frame. + """ + raise NotImplementedError() + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_com_quat_b(self) -> ProxyArray: + """Orientation (x, y, z, w) of the principal axes of inertia of all of the bodies in their + respective link frames. + + Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to + (num_instances, num_bodies, 4). + + This quantity is the orientation of the principal axes of inertia relative to its body's link frame. + """ + raise NotImplementedError() + + """ + Shorthands for commonly used properties. + """ + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_pose_w(self) -> ProxyArray: + """Shorthand for :attr:`body_link_pose_w`.""" + return self.body_link_pose_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_pos_w(self) -> ProxyArray: + """Shorthand for :attr:`body_link_pos_w`.""" + return self.body_link_pos_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_quat_w(self) -> ProxyArray: + """Shorthand for :attr:`body_link_quat_w`.""" + return self.body_link_quat_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_vel_w`.""" + return self.body_com_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_lin_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_lin_vel_w`.""" + return self.body_com_lin_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_ang_vel_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_ang_vel_w`.""" + return self.body_com_ang_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def body_acc_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_acc_w`.""" + return self.body_com_acc_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_lin_acc_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_lin_acc_w`.""" + return self.body_com_lin_acc_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_ang_acc_w(self) -> ProxyArray: + """Shorthand for :attr:`body_com_ang_acc_w`.""" + return self.body_com_ang_acc_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def com_pos_b(self) -> ProxyArray: + """Shorthand for :attr:`body_com_pos_b`.""" + return self.body_com_pos_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def com_quat_b(self) -> ProxyArray: + """Shorthand for :attr:`body_com_quat_b`.""" + return self.body_com_quat_b + + def _create_buffers(self): + # -- Default mass and inertia (Lazy allocation of default values) + self._default_mass = None + self._default_inertia = None + + """ + Deprecated properties for backwards compatibility. + """ + + @property + @leapp_tensor_semantics(const=True) + def default_object_pose(self) -> ProxyArray: + """Deprecated property. Please use :attr:`default_body_pose` instead.""" + warnings.warn( + "The `default_object_pose` property will be deprecated in a IsaacLab 4.0. Please use" + " `default_body_pose` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.default_body_pose + + @property + @leapp_tensor_semantics(const=True) + def default_object_vel(self) -> ProxyArray: + """Deprecated property. Please use :attr:`default_body_vel` instead.""" + warnings.warn( + "The `default_object_vel` property will be deprecated in a IsaacLab 4.0. Please use" + " `default_body_vel` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.default_body_vel + + @property + @leapp_tensor_semantics(const=True) + def default_object_state(self) -> ProxyArray: + """Deprecated property. Please use :attr:`default_body_state` instead.""" + warnings.warn( + "The `default_object_state` property will be deprecated in a IsaacLab 4.0. Please use" + " `default_body_state` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.default_body_state + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def object_link_pose_w(self): + """Deprecated property. Please use :attr:`body_link_pose_w` instead.""" + warnings.warn( + "The `object_link_pose_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_link_pose_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_link_pose_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def object_link_vel_w(self): + """Deprecated property. Please use :attr:`body_link_vel_w` instead.""" + warnings.warn( + "The `object_link_vel_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_link_vel_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_link_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def object_com_pose_w(self): + """Deprecated property. Please use :attr:`body_com_pose_w` instead.""" + warnings.warn( + "The `object_com_pose_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_pose_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_pose_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def object_com_vel_w(self): + """Deprecated property. Please use :attr:`body_com_vel_w` instead.""" + warnings.warn( + "The `object_com_vel_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_vel_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_vel_w + + @property + @leapp_tensor_semantics(kind="state/body/state") + def object_state_w(self): + """Deprecated property. Please use :attr:`body_state_w` instead.""" + warnings.warn( + "The `object_state_w` property will be deprecated in a IsaacLab 4.0. Please use `body_state_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_state_w + + @property + @leapp_tensor_semantics(kind="state/body/link_state") + def object_link_state_w(self): + """Deprecated property. Please use :attr:`body_link_state_w` instead.""" + warnings.warn( + "The `object_link_state_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_link_state_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_link_state_w + + @property + @leapp_tensor_semantics(kind="state/body/com_state") + def object_com_state_w(self): + """Deprecated property. Please use :attr:`body_com_state_w` instead.""" + warnings.warn( + "The `object_com_state_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_state_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_state_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def object_com_acc_w(self): + """Deprecated property. Please use :attr:`body_com_acc_w` instead.""" + warnings.warn( + "The `object_com_acc_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_acc_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_acc_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def object_com_pose_b(self): + """Deprecated property. Please use :attr:`body_com_pose_b` instead.""" + warnings.warn( + "The `object_com_pose_b` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_pose_b` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_pose_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def object_link_pos_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_link_pos_w` instead.""" + warnings.warn( + "The `object_link_pos_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_link_pos_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_link_pos_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def object_link_quat_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_link_quat_w` instead.""" + warnings.warn( + "The `object_link_quat_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_link_quat_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_link_quat_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_link_lin_vel_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_link_lin_vel_w` instead.""" + warnings.warn( + "The `object_link_lin_vel_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_link_lin_vel_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_link_lin_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_link_ang_vel_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_link_ang_vel_w` instead.""" + warnings.warn( + "The `object_link_ang_vel_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_link_ang_vel_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_link_ang_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def object_com_pos_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_pos_w` instead.""" + warnings.warn( + "The `object_com_pos_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_pos_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_pos_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def object_com_quat_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_quat_w` instead.""" + warnings.warn( + "The `object_com_quat_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_quat_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_quat_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_com_lin_vel_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_lin_vel_w` instead.""" + warnings.warn( + "The `object_com_lin_vel_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_lin_vel_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_lin_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_com_ang_vel_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_ang_vel_w` instead.""" + warnings.warn( + "The `object_com_ang_vel_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_ang_vel_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_ang_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def object_com_lin_acc_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_lin_acc_w` instead.""" + warnings.warn( + "The `object_com_lin_acc_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_lin_acc_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_lin_acc_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def object_com_ang_acc_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_ang_acc_w` instead.""" + warnings.warn( + "The `object_com_ang_acc_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_ang_acc_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_ang_acc_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def object_com_pos_b(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_pos_b` instead.""" + warnings.warn( + "The `object_com_pos_b` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_pos_b` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_pos_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def object_com_quat_b(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_quat_b` instead.""" + warnings.warn( + "The `object_com_quat_b` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_quat_b` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_quat_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_link_lin_vel_b(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_link_lin_vel_b` instead.""" + warnings.warn( + "The `object_link_lin_vel_b` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_link_lin_vel_b` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_link_lin_vel_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_link_ang_vel_b(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_link_ang_vel_b` instead.""" + warnings.warn( + "The `object_link_ang_vel_b` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_link_ang_vel_b` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_link_ang_vel_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_com_lin_vel_b(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_lin_vel_b` instead.""" + warnings.warn( + "The `object_com_lin_vel_b` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_lin_vel_b` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_lin_vel_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_com_ang_vel_b(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_ang_vel_b` instead.""" + warnings.warn( + "The `object_com_ang_vel_b` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_ang_vel_b` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_ang_vel_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def object_pose_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_link_pose_w` instead.""" + warnings.warn( + "The `object_pose_w` property will be deprecated in a IsaacLab 4.0. Please use `body_link_pose_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_link_pose_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def object_pos_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_link_pos_w` instead.""" + warnings.warn( + "The `object_pos_w` property will be deprecated in a IsaacLab 4.0. Please use `body_link_pos_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_link_pos_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def object_quat_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_link_quat_w` instead.""" + warnings.warn( + "The `object_quat_w` property will be deprecated in a IsaacLab 4.0. Please use `body_link_quat_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_link_quat_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def object_vel_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_vel_w` instead.""" + warnings.warn( + "The `object_vel_w` property will be deprecated in a IsaacLab 4.0. Please use `body_com_vel_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_lin_vel_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_lin_vel_w` instead.""" + warnings.warn( + "The `object_lin_vel_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_lin_vel_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_lin_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_ang_vel_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_ang_vel_w` instead.""" + warnings.warn( + "The `object_ang_vel_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_ang_vel_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_ang_vel_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_lin_vel_b(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_lin_vel_b` instead.""" + warnings.warn( + "The `object_lin_vel_b` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_lin_vel_b` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_lin_vel_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_ang_vel_b(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_ang_vel_b` instead.""" + warnings.warn( + "The `object_ang_vel_b` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_ang_vel_b` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_ang_vel_b + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def object_acc_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_acc_w` instead.""" + warnings.warn( + "The `object_acc_w` property will be deprecated in a IsaacLab 4.0. Please use `body_com_acc_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_acc_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def object_lin_acc_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_lin_acc_w` instead.""" + warnings.warn( + "The `object_lin_acc_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_lin_acc_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_lin_acc_w + + @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def object_ang_acc_w(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_com_ang_acc_w` instead.""" + warnings.warn( + "The `object_ang_acc_w` property will be deprecated in a IsaacLab 4.0. Please use" + " `body_com_ang_acc_w` instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_ang_acc_w + + """ + Removed - Default values are no longer stored. + """ + + @property + @leapp_tensor_semantics(const=True) + def default_mass(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_mass` instead and manage the default mass manually.""" + warnings.warn( + "The `default_mass` property will be deprecated in a IsaacLab 4.0. Please use `body_mass` instead. " + "The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_mass is None: + self._default_mass = wp.clone(self.body_mass.warp, self.device) + return ProxyArray(self._default_mass) + + @property + @leapp_tensor_semantics(const=True) + def default_inertia(self) -> ProxyArray: + """Deprecated property. Please use :attr:`body_inertia` instead and manage the default inertia manually.""" + warnings.warn( + "The `default_inertia` property will be deprecated in a IsaacLab 4.0. Please use `body_inertia` instead. " + "The default value will need to be managed manually.", + DeprecationWarning, + stacklevel=2, + ) + if self._default_inertia is None: + self._default_inertia = wp.clone(self.body_inertia.warp, self.device) + return ProxyArray(self._default_inertia) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/rigid_object_collection.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/rigid_object_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..21071e3d6967c858e2f4aacb54f295ddd089bd1c --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/rigid_object_collection.py @@ -0,0 +1,32 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.backend_utils import FactoryBase + +from .base_rigid_object_collection import BaseRigidObjectCollection +from .base_rigid_object_collection_data import BaseRigidObjectCollectionData + +if TYPE_CHECKING: + from isaaclab_physx.assets.rigid_object_collection import RigidObjectCollection as PhysXRigidObjectCollection + from isaaclab_physx.assets.rigid_object_collection import ( + RigidObjectCollectionData as PhysXRigidObjectCollectionData, + ) + + +class RigidObjectCollection(FactoryBase, BaseRigidObjectCollection): + """Factory for creating rigid object collection instances.""" + + data: BaseRigidObjectCollectionData | PhysXRigidObjectCollectionData + + def __new__(cls, *args, **kwargs) -> BaseRigidObjectCollection | PhysXRigidObjectCollection: + """Create a new instance of a rigid object collection based on the backend.""" + # The `FactoryBase` __new__ method will handle the logic and return + # an instance of the correct backend-specific rigid object collection class, + # which is guaranteed to be a subclass of `BaseRigidObjectCollection` by convention. + return super().__new__(cls, *args, **kwargs) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/rigid_object_collection_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/rigid_object_collection_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..28c8f8998709390a661c74dbed0e7c3735282536 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/rigid_object_collection_cfg.py @@ -0,0 +1,30 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from dataclasses import MISSING +from typing import TYPE_CHECKING + +from isaaclab.assets.rigid_object import RigidObjectCfg +from isaaclab.utils.configclass import configclass + +if TYPE_CHECKING: + from .rigid_object_collection import RigidObjectCollection + + +@configclass +class RigidObjectCollectionCfg: + """Configuration parameters for a rigid object collection.""" + + class_type: type["RigidObjectCollection"] | str = "{DIR}.rigid_object_collection:RigidObjectCollection" + """The associated asset class. + + The class should inherit from :class:`isaaclab.assets.asset_base.AssetBase`. + """ + + rigid_objects: dict[str, RigidObjectCfg] = MISSING + """Dictionary of rigid object configurations to spawn. + + The keys are the names for the objects, which are used as unique identifiers throughout the code. + """ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/rigid_object_collection_data.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/rigid_object_collection_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c9ca2f7ccadaa10a78826482d2a177dd84539b5d --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/rigid_object_collection/rigid_object_collection_data.py @@ -0,0 +1,25 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.backend_utils import FactoryBase + +from .base_rigid_object_collection_data import BaseRigidObjectCollectionData + +if TYPE_CHECKING: + from isaaclab_physx.assets.rigid_object_collection.rigid_object_collection_data import ( + RigidObjectCollectionData as PhysXRigidObjectCollectionData, + ) + + +class RigidObjectCollectionData(FactoryBase): + """Factory for creating rigid object collection data instances.""" + + def __new__(cls, *args, **kwargs) -> BaseRigidObjectCollectionData | PhysXRigidObjectCollectionData: + """Create a new instance of a rigid object collection data based on the backend.""" + return super().__new__(cls, *args, **kwargs) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..830ceeb48c7b846613cf72beb2648e585be5a0bc --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__init__.py @@ -0,0 +1,221 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import argparse +import sys +from pathlib import Path + +from .commands.envs import command_setup_conda, command_setup_uv +from .commands.format import command_format +from .commands.install import ( + CORE_ISAACLAB_SUBMODULES, + OPTIONAL_ISAACLAB_SUBMODULES, + VALID_EXTRA_FEATURES, + command_install, +) +from .commands.misc import ( + command_build_docs, + command_new, + command_run_docker, + command_run_isaacsim, + command_test, + command_vscode_settings, +) +from .utils import ( + ISAACLAB_ROOT, + is_windows, + run_python_command, +) + + +def train(args: list[str] | None = None) -> None: + """Run the unified reinforcement learning training script.""" + if args is None: + args = sys.argv[1:] + run_python_command(ISAACLAB_ROOT / "scripts" / "reinforcement_learning" / "train.py", args, check=True) + + +def play(args: list[str] | None = None) -> None: + """Run the unified reinforcement learning play script.""" + if args is None: + args = sys.argv[1:] + run_python_command(ISAACLAB_ROOT / "scripts" / "reinforcement_learning" / "play.py", args, check=True) + + +def cli() -> None: + """Parse CLI arguments and run the requested command.""" + if len(sys.argv) > 1 and sys.argv[1] == "train": + train(sys.argv[2:]) + return + if len(sys.argv) > 1 and sys.argv[1] == "play": + play(sys.argv[2:]) + return + + executable_name = Path(sys.argv[0]).name + default_prog = "isaaclab.bat" if is_windows() else "isaaclab.sh" + parser = argparse.ArgumentParser( + description="Isaac Lab CLI", + prog=executable_name if executable_name != "__main__.py" else default_prog, + formatter_class=argparse.RawTextHelpFormatter, + epilog=( + "commands:\n" + " train Run scripts/reinforcement_learning/train.py\n" + " play Run scripts/reinforcement_learning/play.py" + ), + ) + + _optional_str = ", ".join(sorted(OPTIONAL_ISAACLAB_SUBMODULES)) + _extras_str = ", ".join(sorted(VALID_EXTRA_FEATURES)) + _core_str = ", ".join(CORE_ISAACLAB_SUBMODULES) + parser.add_argument( + "-i", + "--install", + nargs="?", + const="all", + help=( + "Install Isaac Lab submodules and optional extra dependencies.\n" + "\n" + "All core submodules are always installed:\n" + f" {_core_str}\n" + "\n" + "Accepts a comma-separated list of optional submodule names and/or\n" + "extra feature selectors, or one of the special values below.\n" + "\n" + f"* Optional submodules: {_optional_str}\n" + " Installed by 'all' or by explicit token.\n" + "\n" + f"* Extra feature sets: {_extras_str}\n" + " Install optional heavy dependencies for a feature on top of the core.\n" + " Supports an optional selector in brackets:\n" + " contrib[rlinf]\n" + " ov[ovrtx|ovphysx|all]\n" + " rl[rsl-rl|skrl|sb3|rl-games] (default: all)\n" + " visualizer[kit|newton|rerun|viser] (default: all)\n" + " On Linux/macOS, quote selectors containing brackets:\n" + " --install 'rl[rsl-rl]'\n" + "\n" + "* Special values:\n" + " all - Core + optional submodules (mimic, teleop) + auto extra\n" + " features (newton, rl, visualizer). Does not install contrib/ov\n" + " dependency extras (default).\n" + " core - Core submodules only; no optional submodules, no extra features.\n" + " (-i with no value) - Same as 'all'.\n" + "\n" + "Note: Contrib and OV source packages are core; runtime dependencies require selectors:\n" + " ./isaaclab.sh -i 'contrib[rlinf]'\n" + " ./isaaclab.sh -i 'ov[ovrtx]'\n" + "\n" + "Examples:\n" + " ./isaaclab.sh -i\n" + " ./isaaclab.sh -i core\n" + " ./isaaclab.sh -i newton,'rl[rsl-rl]'\n" + " ./isaaclab.sh -i mimic,teleop,'visualizer[rerun]'\n" + " ./isaaclab.sh -i 'ov[ovrtx]'\n" + "\n" + ), + ) + parser.add_argument( + "-f", + "--format", + action="store_true", + help="Run pre-commit to format the code and check lints.", + ) + parser.add_argument( + "-p", + "--python", + nargs=argparse.REMAINDER, + help="Run the python executable provided by Isaac Sim or virtual environment (if active).", + ) + parser.add_argument( + "-s", + "--sim", + nargs=argparse.REMAINDER, + help="Run the simulator executable (isaac-sim.sh) provided by Isaac Sim.", + ) + parser.add_argument( + "-t", + "--test", + nargs=argparse.REMAINDER, + help="Run all python pytest tests.", + ) + parser.add_argument( + "-o", + "--docker", + nargs=argparse.REMAINDER, + help="Run the docker container helper script (docker/container.sh).", + ) + parser.add_argument( + "-v", + "--vscode", + action="store_true", + help="Generate the VSCode settings file from template.", + ) + parser.add_argument( + "-d", + "--docs", + action="store_true", + help="Build the documentation from source using sphinx.", + ) + parser.add_argument( + "-n", + "--new", + nargs=argparse.REMAINDER, + help="Create a new external project or internal task from template.", + ) + parser.add_argument( + "-c", + "--conda", + nargs="?", + const="env_isaaclab", + help="Create a new conda environment for Isaac Lab. Default name is 'env_isaaclab'.", + ) + parser.add_argument( + "-u", + "--uv", + nargs="?", + const="env_isaaclab", + help="Create a new uv environment for Isaac Lab. Default name is 'env_isaaclab'.", + ) + + args = parser.parse_args() + + if args.install: + command_install(args.install) + + elif args.format: + command_format() + + elif args.conda: + command_setup_conda(args.conda) + + elif args.uv: + command_setup_uv(args.uv) + + elif args.vscode: + command_vscode_settings() + + elif args.docs: + command_build_docs() + + elif args.docker is not None: + command_run_docker(args.docker) + + elif args.python is not None: + if args.python: + run_python_command(args.python[0], args.python[1:], check=True) + else: + run_python_command("-i", [], check=True) + + elif args.sim is not None: + command_run_isaacsim(args.sim) + + elif args.new is not None: + command_new(args.new) + + elif args.test is not None: + command_test(args.test) + + else: + parser.print_help() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__pycache__/__init__.cpython-310.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f13b6c43afb75453ab8e49a59419dba8fe9b7c12 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__pycache__/__init__.cpython-310.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__pycache__/__init__.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a12ca4b43d1d694b7f26a05cccc87938a66cbada Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__pycache__/utils.cpython-310.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a212726b6c2f152a54431c0744397599ff5d4d15 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__pycache__/utils.cpython-310.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__pycache__/utils.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fc4d65c0c8533bbb7fa385873dcfa7c25c43ace Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/__pycache__/utils.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/envs.cpython-310.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/envs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..359250fd65a3494da6d0b1b67a0511d5d6f60edc Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/envs.cpython-310.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/envs.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/envs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b67581774544cc69cff9d2057af59e5b4465a69 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/envs.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/format.cpython-310.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/format.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfde28e6327fafd79cfb7da51957874aaa8e5394 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/format.cpython-310.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/format.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/format.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..539170c0ca3e12801232dc8505851366dd60a73d Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/format.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/install.cpython-310.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/install.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c49824917799a3a985f099a0b46ab2872815075a Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/install.cpython-310.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/install.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/install.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a26805b851fe664eafab73c719f601749d60d9f Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/install.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/misc.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/misc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..339d5305c7871f85067bf0083ba4c7887854d770 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/__pycache__/misc.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/envs.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/envs.py new file mode 100644 index 0000000000000000000000000000000000000000..1436b9e6ee2370cd3c0010a2c1c10b40dd56c997 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/envs.py @@ -0,0 +1,716 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import os +import re +import shutil +import subprocess +import sys +import textwrap +from pathlib import Path + +from ..utils import ( + ISAACLAB_ROOT, + determine_python_version, + is_windows, + print_debug, + print_error, + print_info, + print_warning, + run_command, +) + + +def _sanitized_conda_env() -> dict[str, str]: + """ + Return an environment safe for invoking conda after Isaac Sim has added a bunch of env vars. + Otherwise if there were different python version in the system vs IS python, + it causes conda to fail with 'SRE mismatch error' due to incompatible python + stdlib/runtime mix. + """ + env = dict(os.environ) + + # Prevent mixed Python stdlib/runtime when the CLI is launched from Isaac Sim's bundled Python. + for key in ("PYTHONHOME", "PYTHONPATH", "PYTHONSTARTUP", "PYTHONEXECUTABLE"): + env.pop(key, None) + + # Isaac Sim injects Kit shared libraries that can interfere with conda's Py runtime. + env.pop("LD_LIBRARY_PATH", None) + + return env + + +def _patch_environment_yml(yml_path: str | Path, python_version: str = "3.12") -> str: + """ + Read environment.yml, return content with altered python version. + + Args: + yml_path: Path to the source environment file. + python_version: Python version to inject. + + Returns: + Patched YML file content. + """ + with open(yml_path, encoding="utf-8") as f: + lines = f.readlines() + + new_lines = [] + for line in lines: + if "python=3." in line: + line = re.sub(r"python=3\.\d+(?:\.\d+)?", f"python={python_version}", line) + new_lines.append(line) + return "".join(new_lines) + + +def _get_conda_prefix(env_name: str) -> Path | None: + """Get the prefix of the conda environment. + + Args: + env_name: Name of the conda environment. + + Returns: + Environment path, or ``None`` if it cannot be determined. + """ + # Use conda run to get sys.prefix + env = _sanitized_conda_env() + cmd = ["conda", "run", "-n", env_name, "python", "-c", "import sys; print(sys.prefix)"] + result = run_command(cmd, capture_output=True, text=True, check=False, env=env) + if result.returncode == 0: + return Path(result.stdout.strip()) + return None + + +def _create_conda_envhooks_shell(conda_prefix: Path) -> None: + """Write Linux/Mac conda activation/deactivation hooks for Isaac Lab environment variables. + + Args: + conda_prefix: Prefix path of the target conda environment. + """ + activate_d = conda_prefix / "etc" / "conda" / "activate.d" + deactivate_d = conda_prefix / "etc" / "conda" / "deactivate.d" + activate_d.mkdir(parents=True, exist_ok=True) + deactivate_d.mkdir(parents=True, exist_ok=True) + + activate_hook = activate_d / "setenv.sh" + deactivate_hook = deactivate_d / "unsetenv.sh" + isaacsim_setup_conda_env_script = ISAACLAB_ROOT / "_isaac_sim" / "setup_conda_env.sh" + + activate_content = textwrap.dedent( + f"""\ + #!/usr/bin/env bash + + # for Isaac Lab + : "${{_IL_PREV_PYTHONPATH:=${{PYTHONPATH-}}}}" + : "${{_IL_PREV_LD_LIBRARY_PATH:=${{LD_LIBRARY_PATH-}}}}" + export ISAACLAB_PATH="{ISAACLAB_ROOT}" + alias isaaclab="{ISAACLAB_ROOT / "isaaclab.sh"}" + + # show icon if not running headless + export RESOURCE_NAME="IsaacSim" + + # for Isaac Sim + if [ -f "{isaacsim_setup_conda_env_script}" ]; then + source "{isaacsim_setup_conda_env_script}" + fi + """ + ) + + deactivate_content = textwrap.dedent( + f"""\ + #!/usr/bin/env bash + + # for Isaac Lab + unalias isaaclab &>/dev/null + unset ISAACLAB_PATH + + # restore paths + if [ -v _IL_PREV_PYTHONPATH ]; then + export PYTHONPATH="$_IL_PREV_PYTHONPATH" + unset _IL_PREV_PYTHONPATH + fi + if [ -v _IL_PREV_LD_LIBRARY_PATH ]; then + export LD_LIBRARY_PATH="$_IL_PREV_LD_LIBRARY_PATH" + unset _IL_PREV_LD_LIBRARY_PATH + fi + + # for Isaac Sim + unset RESOURCE_NAME + if [ -f "{isaacsim_setup_conda_env_script}" ]; then + unset CARB_APP_PATH + unset EXP_PATH + unset ISAAC_PATH + fi + """ + ) + + activate_hook.write_text(activate_content, encoding="utf-8") + deactivate_hook.write_text(deactivate_content, encoding="utf-8") + + print_debug(f"Created activation hook: {activate_hook}") + print_debug(f"Created deactivation hook: {deactivate_hook}") + + +def _write_torch_gomp_hooks_linux(conda_prefix: Path) -> None: + """Write Linux-only conda hooks for torch libgomp/libstdc++ LD_PRELOAD handling. + + Args: + conda_prefix: Path of the target conda environment. + """ + if not sys.platform.startswith("linux"): + return + + activate_d = conda_prefix / "etc" / "conda" / "activate.d" + deactivate_d = conda_prefix / "etc" / "conda" / "deactivate.d" + activate_d.mkdir(parents=True, exist_ok=True) + deactivate_d.mkdir(parents=True, exist_ok=True) + + activate_hook = activate_d / "torch_gomp.sh" + deactivate_hook = deactivate_d / "torch_gomp_unset.sh" + + activate_content = textwrap.dedent( + """\ + # Resolve Torch-bundled libgomp and prepend to LD_PRELOAD (quiet + idempotent) + : "${_IL_PREV_LD_PRELOAD:=${LD_PRELOAD-}}" + + __gomp="$($CONDA_PREFIX/bin/python - <<'PY' 2>/dev/null || true + import pathlib + try: + import torch + p = pathlib.Path(torch.__file__).parent / 'lib' / 'libgomp.so.1' + print(p if p.exists() else "", end="") + except Exception: + pass + PY + )" + + if [ -n "$__gomp" ] && [ -r "$__gomp" ]; then + case ":${LD_PRELOAD:-}:" in + *":$__gomp:"*) : ;; + *) export LD_PRELOAD="$__gomp${LD_PRELOAD:+:$LD_PRELOAD}";; + esac + fi + unset __gomp + + # WAR for Ubuntu 22.04: preload conda's libstdc++ to provide CXXABI_1.3.15 + __libstdcxx="$CONDA_PREFIX/lib/libstdc++.so.6" + if [ -r "$__libstdcxx" ]; then + __sys_libstdcxx=$(readlink -f /lib/x86_64-linux-gnu/libstdc++.so.6 \ + 2>/dev/null || echo "/lib/x86_64-linux-gnu/libstdc++.so.6") + if [ -r "$__sys_libstdcxx" ] \ + && ! strings "$__sys_libstdcxx" 2>/dev/null | grep -qE 'CXXABI_1\\.3\\.15'; then + case ":${LD_PRELOAD:-}:" in + *":$__libstdcxx:"*) : ;; + *) export LD_PRELOAD="$__libstdcxx${LD_PRELOAD:+:$LD_PRELOAD}";; + esac + fi + unset __sys_libstdcxx + fi + unset __libstdcxx + """ + ) + + deactivate_content = textwrap.dedent( + """\ + # restore LD_PRELOAD to pre-activation value + if [ -v _IL_PREV_LD_PRELOAD ]; then + export LD_PRELOAD="$_IL_PREV_LD_PRELOAD" + unset _IL_PREV_LD_PRELOAD + fi + """ + ) + + activate_hook.write_text(activate_content, encoding="utf-8") + deactivate_hook.write_text(deactivate_content, encoding="utf-8") + + print_debug(f"Created torch gomp activation hook: {activate_hook}") + print_debug(f"Created torch gomp deactivation hook: {deactivate_hook}") + + +def _create_conda_envhooks_cmdexe(conda_prefix: Path) -> None: + """Write Windows cmd.exe conda activation/deactivation hooks. + + Args: + conda_prefix: Path of the target conda environment. + """ + activate_d = conda_prefix / "etc" / "conda" / "activate.d" + deactivate_d = conda_prefix / "etc" / "conda" / "deactivate.d" + activate_d.mkdir(parents=True, exist_ok=True) + deactivate_d.mkdir(parents=True, exist_ok=True) + + activate_hook = activate_d / "setenv.bat" + deactivate_hook = deactivate_d / "unsetenv.bat" + isaacsim_setup_conda_env_script = ISAACLAB_ROOT / "_isaac_sim" / "setup_conda_env.bat" + + activate_content = textwrap.dedent( + f"""\ + @echo off + + REM for Isaac Lab + if not defined _IL_PREV_PYTHONPATH set "_IL_PREV_PYTHONPATH=%PYTHONPATH%" + if not defined _IL_PREV_PATH set "_IL_PREV_PATH=%PATH%" + set "ISAACLAB_PATH={ISAACLAB_ROOT}" + doskey isaaclab={ISAACLAB_ROOT / "isaaclab.bat"} $* + + REM show icon if not running headless + set "RESOURCE_NAME=IsaacSim" + + REM for Isaac Sim + if exist "{isaacsim_setup_conda_env_script}" call "{isaacsim_setup_conda_env_script}" + """ + ) + + deactivate_content = textwrap.dedent( + """\ + @echo off + + REM for Isaac Lab + set "ISAACLAB_PATH=" + doskey isaaclab= + + REM restore paths + if defined _IL_PREV_PYTHONPATH ( + set "PYTHONPATH=%_IL_PREV_PYTHONPATH%" + set "_IL_PREV_PYTHONPATH=" + ) + if defined _IL_PREV_PATH ( + set "PATH=%_IL_PREV_PATH%" + set "_IL_PREV_PATH=" + ) + + REM for Isaac Sim + set "RESOURCE_NAME=" + set "CARB_APP_PATH=" + set "EXP_PATH=" + set "ISAAC_PATH=" + """ + ) + + activate_hook.write_text(activate_content, encoding="utf-8") + deactivate_hook.write_text(deactivate_content, encoding="utf-8") + + print_debug(f"Created cmd activation hook: {activate_hook}") + print_debug(f"Created cmd deactivation hook: {deactivate_hook}") + + +def _create_conda_envhooks_powershell(conda_prefix: Path) -> None: + """Write Windows PowerShell conda activation/deactivation hooks. + + Args: + conda_prefix: Path of the target conda environment. + """ + activate_d = conda_prefix / "etc" / "conda" / "activate.d" + deactivate_d = conda_prefix / "etc" / "conda" / "deactivate.d" + activate_d.mkdir(parents=True, exist_ok=True) + deactivate_d.mkdir(parents=True, exist_ok=True) + + activate_hook = activate_d / "setenv.ps1" + deactivate_hook = deactivate_d / "unsetenv.ps1" + isaacsim_setup_conda_env_script = ISAACLAB_ROOT / "_isaac_sim" / "setup_conda_env.ps1" + + activate_content = textwrap.dedent( + f"""\ + # for Isaac Lab + if (-not (Test-Path Env:_IL_PREV_PYTHONPATH)) {{ + $Env:_IL_PREV_PYTHONPATH = $Env:PYTHONPATH + }} + if (-not (Test-Path Env:_IL_PREV_PATH)) {{ + $Env:_IL_PREV_PATH = $Env:PATH + }} + $Env:ISAACLAB_PATH = "{ISAACLAB_ROOT}" + Set-Alias -Scope Global isaaclab "{ISAACLAB_ROOT / "isaaclab.bat"}" -Force + + # show icon if not running headless + $Env:RESOURCE_NAME = "IsaacSim" + + # for Isaac Sim + if (Test-Path "{isaacsim_setup_conda_env_script}") {{ + . "{isaacsim_setup_conda_env_script}" + }} + """ + ) + + deactivate_content = textwrap.dedent( + """\ + # for Isaac Lab + Remove-Item Alias:isaaclab -ErrorAction SilentlyContinue + Remove-Item Env:ISAACLAB_PATH -ErrorAction SilentlyContinue + + # restore paths + if (Test-Path Env:_IL_PREV_PYTHONPATH) { + $Env:PYTHONPATH = $Env:_IL_PREV_PYTHONPATH + Remove-Item Env:_IL_PREV_PYTHONPATH -ErrorAction SilentlyContinue + } + if (Test-Path Env:_IL_PREV_PATH) { + $Env:PATH = $Env:_IL_PREV_PATH + Remove-Item Env:_IL_PREV_PATH -ErrorAction SilentlyContinue + } + + # for Isaac Sim + Remove-Item Env:RESOURCE_NAME -ErrorAction SilentlyContinue + Remove-Item Env:CARB_APP_PATH -ErrorAction SilentlyContinue + Remove-Item Env:EXP_PATH -ErrorAction SilentlyContinue + Remove-Item Env:ISAAC_PATH -ErrorAction SilentlyContinue + """ + ) + + activate_hook.write_text(activate_content, encoding="utf-8") + deactivate_hook.write_text(deactivate_content, encoding="utf-8") + + print_debug(f"Created PowerShell activation hook: {activate_hook}") + print_debug(f"Created PowerShell deactivation hook: {deactivate_hook}") + + +def _write_conda_env_hooks(conda_prefix: Path) -> None: + """Write conda activation/deactivation hooks for current platform shell(s). + + Args: + conda_prefix: Path of the target conda environment. + """ + if is_windows(): + _create_conda_envhooks_cmdexe(conda_prefix) + _create_conda_envhooks_powershell(conda_prefix) + else: + _create_conda_envhooks_shell(conda_prefix) + _write_torch_gomp_hooks_linux(conda_prefix) + + +def _append_hook_if_missing(script_path: Path, marker: str, hook_content: str) -> None: + """Append hook content to a script once, guarded by a marker. + + Args: + script_path: Activation script file to update. + marker: Unique marker used to detect an existing hook. + hook_content: Hook text to append when missing. + """ + if not script_path.exists(): + print_warning(f"Activation script not found, skipping hook injection: {script_path}") + return + + content = script_path.read_text(encoding="utf-8") + if marker in content: + print_debug(f"Hook already present in: {script_path}") + return + + if content and not content.endswith("\n"): + content += "\n" + content += hook_content + script_path.write_text(content, encoding="utf-8") + print_debug(f"Injected hook into: {script_path}") + + +def _create_uv_envhooks_shell(env_path: Path) -> None: + """Inject Bash activation hook for uv environments. + + Args: + env_path: Root path of the uv environment. + """ + activate_script = env_path / "bin" / "activate" + isaacsim_setup_conda_env_script = ISAACLAB_ROOT / "_isaac_sim" / "setup_conda_env.sh" + + hook_content = textwrap.dedent( + f"""\ + # >>> Isaac Lab hook >>> + export ISAACLAB_PATH="{ISAACLAB_ROOT}" + alias isaaclab="{ISAACLAB_ROOT / "isaaclab.sh"}" + export RESOURCE_NAME="IsaacSim" + + if [ -f "{isaacsim_setup_conda_env_script}" ]; then + . "{isaacsim_setup_conda_env_script}" + fi + # <<< Isaac Lab hook <<< + """ + ) + + _append_hook_if_missing(activate_script, "# >>> Isaac Lab hook >>>", hook_content) + + +def _create_uv_envhooks_cmdexe(env_path: Path) -> None: + """Inject cmd.exe activation hook for uv environments. + + Args: + env_path: Root path of the uv environment. + """ + activate_script = env_path / "Scripts" / "activate.bat" + isaacsim_setup_conda_env_script = ISAACLAB_ROOT / "_isaac_sim" / "setup_conda_env.bat" + + hook_content = textwrap.dedent( + f"""\ + REM >>> Isaac Lab hook >>> + set "ISAACLAB_PATH={ISAACLAB_ROOT}" + doskey isaaclab={ISAACLAB_ROOT / "isaaclab.bat"} $* + set "RESOURCE_NAME=IsaacSim" + + if exist "{isaacsim_setup_conda_env_script}" call "{isaacsim_setup_conda_env_script}" + REM <<< Isaac Lab hook <<< + """ + ) + + _append_hook_if_missing(activate_script, "REM >>> Isaac Lab hook >>>", hook_content) + + +def _create_uv_envhooks_powershell(env_path: Path) -> None: + """Inject PowerShell activation hook for uv environments. + + Args: + env_path: Root path of the uv environment. + """ + activate_script = env_path / "Scripts" / "Activate.ps1" + isaacsim_setup_conda_env_script = ISAACLAB_ROOT / "_isaac_sim" / "setup_conda_env.ps1" + + hook_content = textwrap.dedent( + f"""\ + # >>> Isaac Lab hook >>> + $Env:ISAACLAB_PATH = "{ISAACLAB_ROOT}" + Set-Alias -Scope Global isaaclab "{ISAACLAB_ROOT / "isaaclab.bat"}" -Force + $Env:RESOURCE_NAME = "IsaacSim" + + if (Test-Path "{isaacsim_setup_conda_env_script}") {{ + . "{isaacsim_setup_conda_env_script}" + }} + # <<< Isaac Lab hook <<< + """ + ) + + _append_hook_if_missing(activate_script, "# >>> Isaac Lab hook >>>", hook_content) + + +def _write_uv_env_hooks(env_path: Path) -> None: + """Write uv activation hooks for current platform shell(s). + + Args: + env_path: Root path of the uv environment. + """ + if is_windows(): + _create_uv_envhooks_cmdexe(env_path) + _create_uv_envhooks_powershell(env_path) + else: + _create_uv_envhooks_shell(env_path) + + +def command_setup_conda(env_name: str) -> None: + """Setup conda environment for Isaac Lab + + Args: + env_name: Name for the conda environment to create or reuse. + """ + + # Check if conda is installed. + if not shutil.which("conda"): + print_error("Conda could not be found. Please install conda and try again.") + sys.exit(1) + + # Check if _isaac_sim symlink exists + symlink_missing = not (ISAACLAB_ROOT / "_isaac_sim").exists() + + # Check if isaacsim is importable. + pip_package_missing = True + result = run_command( + [sys.executable, "-c", "import isaacsim"], + check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + # avoid EULA prompt + stdin=subprocess.DEVNULL, + ) + if result.returncode == 0: + pip_package_missing = False # installed + + if symlink_missing and pip_package_missing: + print_warning(f"_isaac_sim symlink not found at {ISAACLAB_ROOT}/_isaac_sim") + print("\tThis warning can be ignored if you plan to install Isaac Sim via pip.") + print( + "\tIf you are using a binary installation of Isaac Sim, please ensure the " + + "symlink is created before setting up the conda environment." + ) + + # Check if the environment exists. + conda_env = _sanitized_conda_env() + result = run_command(["conda", "env", "list", "--json"], capture_output=True, text=True, check=False, env=conda_env) + if '"' + env_name + '"' in result.stdout: + print_info(f"Conda environment named '{env_name}' already exists.") + env_exists = True + else: + print_info(f"Creating conda environment named '{env_name}'...") + print_info(f"Installing dependencies from {ISAACLAB_ROOT}/environment.yml") + env_exists = False + + if not env_exists: + # Patch Python version if needed. + env_yml = ISAACLAB_ROOT / "environment.yml" + + # Determine appropriate python version based on Isaac Sim version. + python_version = determine_python_version() + + # Prepare patched yml. + + # Write a temp file. + temp_yml = ISAACLAB_ROOT / "environment_temp.yml" + patched_content = _patch_environment_yml(env_yml, python_version) + with open(temp_yml, "w") as f: + f.write(patched_content) + + try: + run_command(["conda", "env", "create", "-y", "--file", str(temp_yml), "-n", env_name], env=conda_env) + finally: + if temp_yml.exists(): + temp_yml.unlink() + + # Now configure activation scripts. + conda_prefix = _get_conda_prefix(env_name) + if not conda_prefix: + print_error(f"Could not determine prefix for env {env_name}") + return + + # Setup Isaac Lab and Isaac Sim environment variables through conda hooks. + _write_conda_env_hooks(conda_prefix) + + if not is_windows(): + print_info("Added 'isaaclab' alias and environment hooks to conda activation scripts.") + print_info(f"Created conda environment named '{env_name}'.\n") + print(f"\t\t1. To activate the environment, run: conda activate {env_name}") + print("\t\t2. To install Isaac Lab extensions, run: isaaclab.sh -i") + print("\t\t3. To perform formatting, run: isaaclab.sh -f") + print("\t\t4. To deactivate the environment, run: conda deactivate") + print("\n") + + if is_windows(): + print_info(f"Created conda environment named '{env_name}'.\n") + print(f"\t\t1. To activate the environment, run: conda activate {env_name}") + print("\t\t2. To install Isaac Lab extensions, run: isaaclab.bat -i") + print("\t\t3. To perform formatting, run: isaaclab.bat -f") + print("\t\t4. To deactivate the environment, run: conda deactivate") + print("\n") + + +def _check_venv_python_version(env_path: Path, required_ver: str) -> None: + """Validate that a virtual environment's Python matches the required version. + + Args: + env_path: Root path of the virtual environment. + required_ver: Required Python minor version string (e.g. "3.12"). + + Raises: + SystemExit: If the Python version does not match. + """ + if is_windows(): + python_exe = env_path / "Scripts" / "python.exe" + else: + python_exe = env_path / "bin" / "python" + + if not python_exe.exists(): + return + + result = run_command( + [str(python_exe), "-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"], + capture_output=True, + text=True, + check=False, + ) + if result.returncode != 0: + print_warning( + f"Could not determine Python version in virtual environment at {env_path}. " + "The environment may be corrupted." + ) + return + actual_ver = result.stdout.strip() + if actual_ver != required_ver: + print_error(f"Virtual environment Python is {actual_ver}, but Isaac Sim requires {required_ver}.") + print_error( + "Please recreate the environment with the correct Python version, e.g.:\n" + f"\tuv venv --python {required_ver} {env_path}" + ) + sys.exit(1) + + +def command_setup_uv(env_name: str) -> None: + """setup uv environment for Isaac Lab + + Args: + env_name: Name for the uv environment directory to create or reuse. + If a virtual environment is already active (VIRTUAL_ENV is set), + the active environment is configured for Isaac Lab instead of + creating a new one. + """ + # Check if uv is installed. + if not shutil.which("uv"): + print_error("uv could not be found. Please install uv and try again.") + print_error("uv can be installed here:") + print_error("https://docs.astral.sh/uv/getting-started/installation/") + sys.exit(1) + + # Check if _isaac_sim symlink exists and isaacsim is not importable. + if not (ISAACLAB_ROOT / "_isaac_sim").is_symlink(): + try: + result = run_command( + [sys.executable, "-c", "import isaacsim"], + check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + # avoid EULA prompt + stdin=subprocess.DEVNULL, + ) + if result.returncode != 0 and not (ISAACLAB_ROOT / "_isaac_sim").exists(): + print_warning(f"_isaac_sim symlink not found at {ISAACLAB_ROOT}/_isaac_sim") + print("\tThis warning can be ignored if you plan to install Isaac Sim via pip.") + print( + "\tIf you are using a binary installation of Isaac Sim, please ensure " + + "the symlink is created before setting up the uv environment." + ) + except Exception: + pass + + # Determine appropriate python version based on Isaac Sim version. + py_ver = determine_python_version() + + # If a virtual environment is already active, configure it for Isaac Lab + # instead of creating a new one. + active_venv = os.environ.get("VIRTUAL_ENV") + if active_venv: + env_path = Path(active_venv) + print_info(f"Detected active virtual environment: {env_path}") + + # Validate Python version. + _check_venv_python_version(env_path, py_ver) + + # Inject Isaac Lab hooks into the existing environment. + _write_uv_env_hooks(env_path) + + print_info("Added Isaac Lab environment hooks to the active virtual environment.") + print_info("Deactivate and reactivate the environment for hooks to take effect:\n") + if is_windows(): + print("\t\tdeactivate && " + str(env_path / "Scripts" / "activate")) + else: + print("\t\tdeactivate && source " + str(env_path / "bin" / "activate")) + print("\n") + return + + env_path = ISAACLAB_ROOT / env_name + + # Check if the environment exists. + if not env_path.exists(): + print_info(f"Creating uv environment named '{env_name}'...") + run_command(["uv", "venv", "--clear", "--seed", "--python", py_ver, str(env_path)]) + else: + print_info(f"uv environment '{env_name}' already exists.") + # Validate Python version of existing environment. + _check_venv_python_version(env_path, py_ver) + + # Setup Isaac Lab and Isaac Sim environment variables through uv activation hooks. + _write_uv_env_hooks(env_path) + + print_info("Added environment hooks to uv activation scripts.") + + print_info(f"Created uv environment named '{env_name}'.") + print() + if is_windows(): + print(f"\t\t1. To activate the environment, run: {env_name}\\Scripts\\activate") + print("\t\t2. To install Isaac Lab extensions, run: isaaclab.bat -i") + print("\t\t3. To perform formatting, run: isaaclab.bat -f") + print("\t\t4. To deactivate the environment, run: deactivate") + else: + print(f"\t\t1. To activate the environment, run: source {env_name}/bin/activate") + print("\t\t2. To install Isaac Lab extensions, run: ./isaaclab.sh -i") + print("\t\t3. To perform formatting, run: ./isaaclab.sh -f") + print("\t\t4. To deactivate the environment, run: deactivate") diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/format.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/format.py new file mode 100644 index 0000000000000000000000000000000000000000..b26b93af90e7d4ea1dfe8217c8368339918b4b8a --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/format.py @@ -0,0 +1,52 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import subprocess + +from ..utils import ISAACLAB_ROOT, extract_python_exe, get_pip_command, print_info, run_command + + +def command_format() -> None: + """Run code formatting using pre-commit.""" + python_exe = extract_python_exe() + + def _run_pre_commit() -> None: + run_command([python_exe, "-m", "pre_commit", "run", "--all-files"], cwd=ISAACLAB_ROOT) + + # Check if pre-commit is installed. + + pre_commit_module = False + + result = run_command( + [python_exe, "-c", "import pre_commit"], + check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + if result.returncode == 0: + pre_commit_module = True + + # If pre-commit is not installed, install it. + if not pre_commit_module: + print_info('Pre-commit not found. Installing "pre-commit" module...') + pip_cmd = get_pip_command(python_exe) + run_command(pip_cmd + ["install", "pre-commit"]) + + print_info("Formatting the repository...") + + try: + # Run pre-commit as a module since we may have just installed it. + _run_pre_commit() + + except SystemExit: + # Pre-commit exits with code=1 when files changed, that is expected. + # To verify if the error is due to pre-commit just changing files, + # run pre-commit again to see if it exits with code=0. + print_info("Pre-commit changed some files, running it again to validate...") + _run_pre_commit() + + finally: + pass diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/install.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/install.py new file mode 100644 index 0000000000000000000000000000000000000000..3c459d203e629e272831b89d3fb23fa7e46cde63 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/install.py @@ -0,0 +1,1128 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import os +import re +import shutil +import sys +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + +import tomllib + +from ..utils import ( + ISAACLAB_ROOT, + extract_isaacsim_path, + extract_python_exe, + get_pip_command, + is_arm, + is_windows, + print_debug, + print_info, + print_warning, + run_command, +) +from .misc import command_vscode_settings + + +@contextmanager +def _arm_cmake_policy_compatibility() -> Iterator[None]: + """Allow legacy CMake projects to configure during ARM dependency installs. + + CMake 4 removed compatibility with policy versions older than 3.5. Some + transitive ARM dependencies, including ``nlopt==2.6.2`` and + ``egl-probe==1.0.2``, still declare an older minimum. CMake provides this + environment variable specifically so users can configure such unmaintained + third-party projects without patching their sources. + """ + if not is_arm(): + yield + return + + variable = "CMAKE_POLICY_VERSION_MINIMUM" + saved_value = os.environ.get(variable) + os.environ[variable] = "3.5" + print_info(f"ARM install sandbox: temporarily setting {variable}=3.5 for legacy dependency builds.") + try: + yield + finally: + if saved_value is None: + os.environ.pop(variable, None) + else: + os.environ[variable] = saved_value + + +def _install_system_deps() -> None: + """install system dependencies""" + if is_windows(): + return + + # Check if cmake is already installed. + if shutil.which("cmake"): + print_info("cmake is already installed.") + else: + print_info("Installing system dependencies...") + + # apt-get update + cmd = ["apt-get", "update"] + run_command(["sudo"] + cmd if os.geteuid() != 0 else cmd) + + # apt-get install -y --no-install-recommends cmake build-essential + cmd = [ + "apt-get", + "install", + "-y", + "--no-install-recommends", + "cmake", + "build-essential", + ] + run_command(["sudo"] + cmd if os.geteuid() != 0 else cmd) + + # On ARM Linux (e.g. DGX Spark), Python dev headers (Python.h) are needed + # to build C extensions such as quadprog. They are typically pre-installed + # in x86 Docker images but missing on bare-metal ARM systems. + if is_arm(): + python_dev_pkg = f"python{sys.version_info.major}.{sys.version_info.minor}-dev" + try: + import sysconfig + + if sysconfig.get_path("include") and os.path.isfile( + os.path.join(sysconfig.get_path("include"), "Python.h") + ): + print_info("Python dev headers are already installed.") + else: + raise FileNotFoundError + except (FileNotFoundError, AttributeError): + print_info(f"Installing {python_dev_pkg} (required for building C extensions on ARM)...") + cmd = ["apt-get", "update"] + run_command(["sudo"] + cmd if os.geteuid() != 0 else cmd) + cmd = [ + "apt-get", + "install", + "-y", + "--no-install-recommends", + python_dev_pkg, + ] + run_command(["sudo"] + cmd if os.geteuid() != 0 else cmd) + + # nlopt has no aarch64 manylinux wheel for the version pinned by + # isaacteleop[retargeters]. The installer pre-installs nlopt below to + # avoid the CMake source-build fallback that would require SWIG. + if not shutil.which("swig"): + print_info( + "swig is missing; continuing because nlopt is pre-installed on ARM before optional " + "dependencies are resolved. Pre-install swig manually only if you need to build nlopt from source." + ) + + # imgui-bundle has no aarch64 manylinux wheel, so pip falls back to a + # CMake source build that needs GL/X11 dev headers (via glfw). + # Mirrors the apt step in docker/Dockerfile.base. + _gl_x11_packages = [ + "libgl1-mesa-dev", + "libopengl-dev", + "libglx-dev", + "libx11-dev", + "libxcursor-dev", + "libxi-dev", + "libxinerama-dev", + "libxrandr-dev", + ] + if not os.path.isfile("/usr/include/X11/Xlib.h"): + if os.geteuid() != 0 and not shutil.which("sudo"): + print_info( + "GL/X11 dev headers are missing and sudo is unavailable; " + "skipping install. Pre-install " + " ".join(_gl_x11_packages) + " " + "if you need to build imgui-bundle from source." + ) + else: + print_info("Installing GL/X11 dev headers (required for building imgui-bundle on ARM)...") + cmd = ["apt-get", "update"] + run_command(["sudo"] + cmd if os.geteuid() != 0 else cmd) + cmd = ["apt-get", "install", "-y", "--no-install-recommends", *_gl_x11_packages] + run_command(["sudo"] + cmd if os.geteuid() != 0 else cmd) + + +def _torch_first_on_sys_path_is_prebundle(python_exe: str, *, env: dict[str, str]) -> bool: + """Return True when the first ``torch`` on ``sys.path`` comes from a prebundle directory. + + Checks whether the first directory on ``sys.path`` that contains a + ``torch`` package lives under a ``pip_prebundle`` path (e.g. + ``omni.isaac.ml_archive/pip_prebundle``). This catches the prebundle + regardless of whether the extension lives under ``exts/``, + ``extsDeprecated/``, or any other search path. + + Does not import ``torch`` (that can fail on missing ``libcudnn`` while the + prebundle still appears earlier on ``sys.path`` than ``site-packages``). + """ + probe = """import os, sys +for p in sys.path: + if not p: + continue + if os.path.isfile(os.path.join(p, "torch", "__init__.py")): + norm = os.path.normpath(p) + sys.exit(1 if "pip_prebundle" in norm else 0) +sys.exit(0) +""" + result = run_command( + [python_exe, "-c", probe], + env=env, + check=False, + capture_output=True, + text=True, + ) + return result.returncode == 1 + + +def _maybe_uninstall_prebundled_torch( + python_exe: str, + pip_cmd: list[str], + using_uv: bool, + *, + probe_env: dict[str, str], +) -> None: + """Uninstall pip torch stack when ``sys.path`` would load ``torch`` from a prebundle first.""" + if not _torch_first_on_sys_path_is_prebundle(python_exe, env=probe_env): + return + print_info( + "The first ``torch`` on ``sys.path`` is under a prebundle directory (e.g. " + "``omni.isaac.ml_archive/pip_prebundle``). Uninstalling pip " + "``torch``/``torchvision``/``torchaudio`` before continuing." + ) + uninstall_flags = ["-y"] if not using_uv else [] + run_command( + pip_cmd + ["uninstall"] + uninstall_flags + ["torch", "torchvision", "torchaudio"], + check=False, + ) + + +# Dependency stack required by isaaclab.controllers.pink_ik. Pinocchio is installed +# via the cmeel ``pin`` wheel, which provides the ``pinocchio`` Python module under +# ``cmeel.prefix/lib/python3.12/site-packages/`` and registers it on sys.path via a +# ``cmeel.pth`` hook. DAQP provides the QP solver selected by the Pink IK controller. +# pin-pink: Isaac Sim 6.x needs >=3.3, 3.4+ breaks pink_ik; daqp >0.8.5 changes behavior. +_PINK_IK_STACK = ("pin", "pin-pink==3.3.0", "daqp==0.8.5") + + +def _ensure_pink_ik_dependencies_installed(python_exe: str, pip_cmd: list[str], *, probe_env: dict[str, str]) -> None: + """Ensure the Pink IK dependency stack is importable, force-installing it if not. + + Recent Isaac Sim base images preinstall ``pin-pink`` into the kit's bundled + ``site-packages`` without its ``pin`` (cmeel pinocchio) dependency. Pip then + treats the ``pin-pink`` requirement as satisfied and never resolves the + transitive ``pin`` dep, leaving ``import pinocchio`` broken. This checks + the runtime dependencies and force-installs the cmeel stack when needed so + the pink IK controller and its tests work out of the box. + + Only runs on Linux x86_64 / aarch64 — the same platforms that have + pinocchio listed in :mod:`isaaclab`'s ``setup.py`` install requirements. + Skipped on Windows and macOS (no cmeel wheels) and on unsupported + architectures so the rest of ``--install`` behaves unchanged there. + + A force-reinstall failure (e.g. transient PyPI / NVIDIA Artifactory issue) + is logged as a warning rather than aborting ``--install``: pinocchio is only + needed by the optional pink IK controller, so the rest of Isaac Lab should + still install cleanly. + """ + import platform + + if platform.system() != "Linux": + return + if platform.machine() not in {"x86_64", "AMD64", "aarch64", "arm64"}: + return + + probe_result = run_command( + [ + python_exe, + "-c", + "import inspect, pinocchio, daqp, qpsolvers; " + "assert 'daqp' in qpsolvers.available_solvers; " + "assert 'primal_start' in inspect.signature(daqp.solve).parameters", + ], + env=probe_env, + check=False, + capture_output=True, + text=True, + ) + if probe_result.returncode == 0: + return + + print_info("Pink IK dependency probe failed. Force-installing the cmeel pinocchio and DAQP stack.") + install_result = run_command( + pip_cmd + ["install", "--upgrade", "--force-reinstall", *_PINK_IK_STACK], + check=False, + ) + if install_result.returncode != 0: + print_warning( + "Force-installing the cmeel pinocchio and DAQP stack failed (returncode " + f"{install_result.returncode}). The pink IK controller and its tests will not be" + f" usable until ``{' '.join(_PINK_IK_STACK)}`` is installed manually." + ) + + +def _ensure_cuda_torch() -> None: + """Ensure correct PyTorch and CUDA versions are installed.""" + python_exe = extract_python_exe() + pip_cmd = get_pip_command(python_exe) + using_uv = pip_cmd[0] == "uv" + + # Base index for torch. + base_index = "https://download.pytorch.org/whl" + + # Choose pins per arch. + torch_ver = "2.10.0" + tv_ver = "0.25.0" + + if is_arm(): + cuda_ver = "130" + else: + cuda_ver = "128" + + cuda_tag = f"cu{cuda_ver}" + index_url = f"{base_index}/{cuda_tag}" + + want_torch = f"{torch_ver}+{cuda_tag}" + + # Check current torch version using pip show (includes build tags). + current_ver = "" + try: + result = run_command( + pip_cmd + ["show", "torch"], + capture_output=True, + text=True, + check=False, + ) + if result.returncode == 0: + for line in result.stdout.split("\n"): + if line.startswith("Version: "): + current_ver = line.split("Version: ", 1)[1].strip() + break + except Exception: + pass + + # Skip install if version already matches (including CUDA build tag). + if current_ver == want_torch: + print_info(f"PyTorch {want_torch} already installed.") + return + + # Clean install torch. + print_info(f"Installing torch=={torch_ver} and torchvision=={tv_ver} ({cuda_tag}) from {index_url}...") + + # uv pip uninstall does not accept -y + uninstall_flags = ["-y"] if not using_uv else [] + run_command( + pip_cmd + ["uninstall"] + uninstall_flags + ["torch", "torchvision", "torchaudio"], + check=False, + ) + + run_command(pip_cmd + ["install", "--index-url", index_url, f"torch=={torch_ver}", f"torchvision=={tv_ver}"]) + + +# Isaac Sim install settings. +ISAACSIM_VERSION_SPEC = ">=6.0.0" +ISAACSIM_EXTRAS = "all" +NVIDIA_INDEX_URL = "https://pypi.nvidia.com" + + +def _normalize_package_name(name: str) -> str: + """Normalize a Python package name for metadata comparisons.""" + return re.sub(r"[-_.]+", "-", name).lower() + + +def _requirement_name(requirement: str) -> str: + """Extract the distribution name from a requirement string.""" + requirement = requirement.split(";", 1)[0].strip() + return re.split(r"\s|<|>|=|!|~|\[|@", requirement, maxsplit=1)[0] + + +def _get_installed_distribution_requirements(python_exe: str, distribution_name: str) -> list[str]: + """Return installed ``Requires-Dist`` requirements for a distribution.""" + probe = """import importlib.metadata +import sys + +try: + dist = importlib.metadata.distribution(sys.argv[1]) +except importlib.metadata.PackageNotFoundError: + sys.exit(1) + +for requirement in dist.requires or []: + print(requirement) +""" + result = run_command( + [python_exe, "-c", probe, distribution_name], + capture_output=True, + text=True, + check=False, + ) + if result.returncode != 0: + print_warning(f"Could not read installed metadata for {distribution_name}; skipping dependency upgrades.") + return [] + return [line.strip() for line in result.stdout.splitlines() if line.strip()] + + +def _get_extension_pip_upgrade_dependencies(extension_dir: Path) -> list[str]: + """Read dependency names opted into targeted pip upgrades from ``extension.toml``.""" + extension_toml = extension_dir / "config" / "extension.toml" + if not extension_toml.is_file(): + return [] + + try: + with extension_toml.open("rb") as fd: + extension_data = tomllib.load(fd) + except tomllib.TOMLDecodeError as exc: + print_warning(f"Could not parse {extension_toml}: {exc}; skipping targeted dependency upgrades.") + return [] + + isaac_lab_settings = extension_data.get("isaac_lab_settings", {}) + if not isinstance(isaac_lab_settings, dict): + print_warning( + f"Ignoring invalid isaac_lab_settings in {extension_toml}; expected a table with pip_upgrade_dependencies." + ) + return [] + + upgrade_dependencies = isaac_lab_settings.get("pip_upgrade_dependencies", []) + if not isinstance(upgrade_dependencies, list) or not all(isinstance(item, str) for item in upgrade_dependencies): + print_warning(f"Ignoring invalid pip_upgrade_dependencies in {extension_toml}; expected a list of strings.") + return [] + + return upgrade_dependencies + + +def _get_pip_upgrade_command(pip_cmd: list[str], dependency_name: str, requirement: str) -> list[str]: + """Return a pip command that upgrades one dependency requirement.""" + if pip_cmd[0] == "uv": + return pip_cmd + ["install", "--upgrade-package", dependency_name, requirement] + return pip_cmd + ["install", "--upgrade", requirement] + + +def _upgrade_extension_pip_dependencies( + python_exe: str, + pip_cmd: list[str], + distribution_name: str, + dependency_names: list[str], +) -> None: + """Upgrade selected dependencies using installed distribution metadata requirements.""" + if not dependency_names: + return + + requirements = _get_installed_distribution_requirements(python_exe, distribution_name) + seen_dependency_names = set() + + for dependency_name in dependency_names: + normalized_dependency_name = _normalize_package_name(dependency_name) + if normalized_dependency_name in seen_dependency_names: + continue + seen_dependency_names.add(normalized_dependency_name) + + matching_requirements = [ + req for req in requirements if _normalize_package_name(_requirement_name(req)) == normalized_dependency_name + ] + if not matching_requirements: + print_warning( + f"Could not find dependency '{dependency_name}' in installed metadata for {distribution_name}; " + "skipping targeted upgrade." + ) + continue + + for requirement in matching_requirements: + print_info(f"Upgrading {dependency_name} for {distribution_name}: {requirement}") + run_command(_get_pip_upgrade_command(pip_cmd, dependency_name, requirement)) + + +def _install_isaacsim() -> None: + """Install Isaac Sim pip package if not already present.""" + python_exe = extract_python_exe() + pip_cmd = get_pip_command(python_exe) + + # Check if already installed. + result = run_command( + [python_exe, "-c", "from importlib.metadata import version; print(version('isaacsim'))"], + capture_output=True, + text=True, + check=False, + ) + if result.returncode == 0: + installed_ver = result.stdout.strip() + print_info(f"Isaac Sim {installed_ver} already installed.") + return + + print_info("Installing Isaac Sim...") + using_uv = pip_cmd[0] == "uv" + extra_flags = [] + if using_uv: + # uv needs unsafe-best-match to resolve packages across multiple indexes + # (isaacsim is on pypi.nvidia.com, its deps are on pypi.org). + extra_flags = ["--index-strategy", "unsafe-best-match"] + + run_command( + pip_cmd + + [ + "install", + f"isaacsim[{ISAACSIM_EXTRAS}]{ISAACSIM_VERSION_SPEC}", + "--extra-index-url", + NVIDIA_INDEX_URL, + ] + + extra_flags + ) + + +# Source directories installed on every ./isaaclab.sh -i invocation (even "core"). +# Order matters: isaaclab must be first so dependents resolve against the local copy, +# and isaaclab_ppisp should precede renderer backends (newton/ov/physx) so local +# camera ISP support is available when CameraCfg.isp_cfg is used. +CORE_ISAACLAB_SUBMODULES: list[str] = [ + "isaaclab", + "isaaclab_ppisp", + "isaaclab_assets", + "isaaclab_contrib", + "isaaclab_experimental", + "isaaclab_newton", + "isaaclab_ov", + "isaaclab_ovphysx", + "isaaclab_physx", + "isaaclab_rl", + "isaaclab_tasks", + "isaaclab_tasks_experimental", + "isaaclab_visualizers", +] + +# Optional submodules — only installed when explicitly requested or with 'all'. +# Maps the short CLI name to one or more source directory names under source/. +OPTIONAL_ISAACLAB_SUBMODULES: dict[str, tuple[str, ...]] = { + "mimic": ("isaaclab_teleop", "isaaclab_mimic"), + "teleop": ("isaaclab_teleop",), +} + +# Extra feature sets that install optional heavy dependencies on top of the +# always-installed core submodules. Each name corresponds to one or more +# 'pip install --editable path[extra]' calls against packages already in the +# core set. +VALID_EXTRA_FEATURES: set[str] = { + "contrib", + "newton", + "ov", + "rl", + "visualizer", +} + +# Extra features excluded from the automatic ``-i all`` / ``-i`` install. +MANUAL_EXTRA_FEATURES: set[str] = {"contrib", "ov"} + + +def split_install_items(install_type: str) -> list[str]: + """Split comma-separated install items, ignoring commas inside brackets.""" + parts: list[str] = [] + buf: list[str] = [] + bracket_depth = 0 + for ch in install_type: + if ch == "[": + bracket_depth += 1 + elif ch == "]": + bracket_depth = max(0, bracket_depth - 1) + if ch == "," and bracket_depth == 0: + token = "".join(buf).strip() + if token: + parts.append(token) + buf = [] + else: + buf.append(ch) + token = "".join(buf).strip() + if token: + parts.append(token) + return parts + + +def _install_isaaclab_submodules(isaaclab_submodules: list[str]) -> None: + """Install Isaac Lab submodules from the source directory as editable packages. + + Args: + isaaclab_submodules: Ordered list of source directory names to install + (e.g. ``["isaaclab", "isaaclab_assets", ...]``). ``isaaclab`` must + appear first so downstream packages resolve against the local copy. + """ + python_exe = extract_python_exe() + source_dir = ISAACLAB_ROOT / "source" + + if not source_dir.exists(): + print_warning(f"Source directory not found: {source_dir}") + return + + pip_cmd = get_pip_command(python_exe) + for pkg_name in isaaclab_submodules: + item = source_dir / pkg_name + if not item.is_dir() or not (item / "setup.py").exists(): + print_warning(f"Submodule directory not found or missing setup.py: {item}") + continue + print_info(f"Installing submodule: {pkg_name}") + run_command(pip_cmd + ["install", "--editable", str(item)]) + _upgrade_extension_pip_dependencies( + python_exe, + pip_cmd, + pkg_name, + _get_extension_pip_upgrade_dependencies(item), + ) + + +def _install_optional_submodule_extra_dependencies(submodule_name: str, selector: str) -> None: + """Install optional dependency extras for an optional submodule. + + Args: + submodule_name: One of :data:`OPTIONAL_ISAACLAB_SUBMODULES`. + selector: Extra selector from a token such as ``mimic[foo]``. + """ + if not selector: + return + + print_warning(f"Optional submodule '{submodule_name}' does not support selectors (got '{selector}').") + + +def _install_contrib_extra_dependencies(selector: str) -> None: + """Install optional contrib runtime dependencies. + + Args: + selector: Contrib extra selector, currently ``rlinf``. + """ + if not selector: + print_info( + "Contrib source package is installed with the core submodules. " + "Use 'contrib[rlinf]' to install contrib runtime dependencies." + ) + return + + python_exe = extract_python_exe() + pip_cmd = get_pip_command(python_exe) + source_dir = ISAACLAB_ROOT / "source" + + print_info(f"Installing contrib optional dependencies: {selector}...") + run_command(pip_cmd + ["install", "--editable", f"{source_dir}/isaaclab_contrib[{selector}]"]) + + +def _install_ov_extra_dependencies(selector: str) -> None: + """Install optional OV runtime dependencies. + + Args: + selector: One or more OV selectors from ``ov[ovrtx]``, + ``ov[ovphysx]``, or ``ov[all]``. + """ + if not selector: + print_info( + "OV source packages are installed with the core submodules. " + "Use 'ov[ovrtx]', 'ov[ovphysx]', or 'ov[all]' to install OV runtime dependencies." + ) + return + + python_exe = extract_python_exe() + pip_cmd = get_pip_command(python_exe) + source_dir = ISAACLAB_ROOT / "source" + + selectors = {item.strip().lower() for item in selector.split(",") if item.strip()} + valid_selectors = {"all", "ovrtx", "ovphysx"} + unknown_selectors = selectors - valid_selectors + if unknown_selectors: + print_warning( + f"Unknown ov selector(s): {', '.join(sorted(unknown_selectors))}. " + f"Valid selectors: {', '.join(sorted(valid_selectors))}." + ) + if "all" in selectors: + selectors.update({"ovrtx", "ovphysx"}) + if "ovrtx" in selectors: + print_info("Installing OVRTX optional dependency...") + run_command(pip_cmd + ["install", "--editable", f"{source_dir}/isaaclab_ov[ovrtx]"]) + if "ovphysx" in selectors: + print_info("Installing OVPhysX optional dependency...") + run_command(pip_cmd + ["install", "--editable", f"{source_dir}/isaaclab_ovphysx[ovphysx]"]) + + +def _install_extra_feature(feature_name: str, selector: str = "") -> None: + """Install optional extra dependencies for a feature set. + + Each feature maps to one or more editable installs with extras applied to + packages that are already part of the core set. + + Args: + feature_name: One of :data:`VALID_EXTRA_FEATURES`. + selector: Optional extra selector (e.g. ``"rsl-rl"`` for + ``rl[rsl-rl]``). When empty a sensible default is chosen per + feature (``"all"`` for ``rl`` and ``visualizer``). + """ + python_exe = extract_python_exe() + pip_cmd = get_pip_command(python_exe) + source_dir = ISAACLAB_ROOT / "source" + + if feature_name == "contrib": + _install_contrib_extra_dependencies(selector) + elif feature_name == "newton": + if selector: + print_warning(f"'newton' does not support selectors (got '{selector}'). Installing all newton extras.") + print_info( + "Installing newton extras (newton[sim], pyglet, PyOpenGL-accelerate, imgui-bundle, typing-extensions)..." + ) + run_command(pip_cmd + ["install", "--editable", f"{source_dir}/isaaclab_newton[all]"]) + run_command(pip_cmd + ["install", "--editable", f"{source_dir}/isaaclab_physx[newton]"]) + run_command(pip_cmd + ["install", "--editable", f"{source_dir}/isaaclab_visualizers[newton]"]) + elif feature_name == "rl": + extra = selector if selector else "all" + print_info(f"Installing RL framework extras: {extra}...") + run_command(pip_cmd + ["install", "--editable", f"{source_dir}/isaaclab_rl[{extra}]"]) + elif feature_name == "visualizer": + extra = selector if selector else "all" + print_info(f"Installing visualizer extras: {extra}...") + run_command(pip_cmd + ["install", "--editable", f"{source_dir}/isaaclab_visualizers[{extra}]"]) + elif feature_name == "ov": + _install_ov_extra_dependencies(selector) + else: + print_warning( + f"Unknown extra feature '{feature_name}'. " + f"Valid features: {', '.join(sorted(VALID_EXTRA_FEATURES))}. Skipping." + ) + + +_PREBUNDLE_REPOINT_PACKAGES: list[str] = [ + "torch", + "torchvision", + "torchaudio", + "nvidia", + "newton", + "newton_actuators", + "warp", + "mujoco_warp", + "websockets", + "viser", + "imgui_bundle", + "attr", + "attrs", +] +"""Package directory names in Isaac Sim prebundle directories to repoint. + +When a local ``_isaac_sim`` symlink exists, its ``setup_conda_env.sh`` injects +``pip_prebundle`` paths into ``PYTHONPATH``. These prebundled copies can shadow +the versions installed in the active conda/uv environment (e.g. ``torch+cu128`` +overriding the ``torch+cu130`` the user installed). + +After installation we replace each prebundled copy with a symlink that points +back to the environment's ``site-packages``, so the *same* version is loaded +regardless of import path order. +""" + + +def _force_remove(path: Path) -> None: + """Recursively remove a file, directory, or symlink. A missing path is a no-op. + + Uses absolute-path :func:`os.unlink` / :func:`os.rmdir` rather than the + ``dir_fd``-relative operations :func:`shutil.rmtree` performs internally. On + an overlayfs *lower* layer (e.g. inside a Docker image build) the ``dir_fd`` + variant raises ``EINVAL``, whereas the plain ``unlink(2)`` / ``rmdir(2)`` + syscalls create the proper whiteout. This makes prebundle neutralization + behave identically on a normal filesystem and on an overlayfs lower layer. + """ + if path.is_symlink() or path.is_file(): + os.unlink(path) + elif path.is_dir(): + for child in path.iterdir(): + _force_remove(child) + os.rmdir(path) + + +def _discover_prebundle_dirs() -> set[Path]: + """Find every ``pip_prebundle`` directory under the Isaac Sim installation. + + Searches both the Isaac Sim tree and the Omniverse cache roots — some Isaac + Sim directories are symlinked into ``~/.local/share/ov`` and would be missed + by a plain ``rglob()`` on ``_isaac_sim``. Returns an empty set when no Isaac + Sim installation is present. + """ + isaacsim_path = extract_isaacsim_path(required=False) + if isaacsim_path is None or not isaacsim_path.exists(): + return set() + + candidate_roots: set[Path] = set() + for root in ( + isaacsim_path, + isaacsim_path.resolve(), + isaacsim_path / "extscache", + Path.home() / ".local" / "share" / "ov" / "data" / "exts", + Path.home() / ".local" / "share" / "ov" / "data" / "exts" / "v2", + ): + if root.exists(): + candidate_roots.add(root) + candidate_roots.add(root.resolve()) + + prebundle_dirs: set[Path] = set() + for root in candidate_roots: + prebundle_dirs.update(root.rglob("pip_prebundle")) + return prebundle_dirs + + +def _find_dangling_prebundle_symlinks() -> set[Path]: + """Find symlinks under Isaac Sim prebundles whose targets do not resolve. + + Isaac Sim deduplicates packages shared by several extensions as per-file + symlink farms between ``pip_prebundle`` directories. pip operations routinely + replace prebundled distributions with copies in ``site-packages`` — harmless + on its own — but deleting a copy that other prebundles link into leaves + dangling symlinks that break extension startup at runtime. + """ + dangling: set[Path] = set() + for prebundle_dir in _discover_prebundle_dirs(): + for root, _dirs, files in os.walk(prebundle_dir): + for name in files: + path = Path(root) / name + if path.is_symlink() and not path.exists(): + dangling.add(path) + return dangling + + +def _assert_no_new_dangling_prebundle_symlinks(before: set[Path]) -> None: + """Fail when the installation broke a prebundled package's symlinked ``__init__.py``. + + A new dangling symlink means a pip operation deleted a prebundled package + that other extensions reference through Isaac Sim's symlink farms — the + failure mode behind the ``packaging`` removal cascade in nvbugs 6343978 + (14 extensions failing to start). Routine pip replacements do leave a few + dozen dangling links to files Python never imports at startup (test modules, + ``WHEEL``/license files, cmake hooks), so only a dangling ``__init__.py`` — + which makes the whole package unimportable — fails the install; other new + dangling links are reported as warnings. + + Args: + before: Dangling symlinks from :func:`_find_dangling_prebundle_symlinks`, + collected before the pip operations. + + Raises: + RuntimeError: If the installation left a prebundled package with a + dangling ``__init__.py``. + """ + introduced = sorted(_find_dangling_prebundle_symlinks() - before) + if not introduced: + return + broken_packages = [p for p in introduced if p.name == "__init__.py"] + if broken_packages: + shown = "\n ".join(str(p) for p in broken_packages) + raise RuntimeError( + f"Installation broke {len(broken_packages)} prebundled package(s) in Isaac Sim" + f" (dangling __init__.py, {len(introduced)} new dangling symlink(s) total):\n " + + shown + + "\nA pip operation deleted a prebundled package that other Isaac Sim extensions share" + " via symlinks; extensions will fail to start at runtime (see nvbugs 6343978). This" + " usually means a dependency pin forced pip to downgrade/replace the prebundled copy —" + " fix that pin instead of shipping a broken prebundle, and restore the Isaac Sim" + " installation before retrying." + ) + print_warning( + f"Installation left {len(introduced)} new dangling symlink(s) in Isaac Sim prebundles" + " (no package __init__.py affected — extensions should still start). First few: " + + ", ".join(str(p) for p in introduced[:5]) + ) + + +def _repoint_prebundle_packages() -> None: + """Replace prebundled packages in Isaac Sim with symlinks to the active environment. + + Scans every ``pip_prebundle`` directory under the Isaac Sim installation + for package directories listed in :data:`_PREBUNDLE_REPOINT_PACKAGES`. + When the same package exists in the active environment's ``site-packages``, + the prebundled copy is moved to ``.bak`` and replaced with a symlink. + + This is idempotent — existing symlinks that already point to the correct + target are left untouched. + """ + use_symlinks = not is_windows() + + isaacsim_path = extract_isaacsim_path(required=False) + if isaacsim_path is None or not isaacsim_path.exists(): + print_debug("No Isaac Sim installation found — skipping prebundle repoint.") + return + + python_exe = extract_python_exe() + result = run_command( + [python_exe, "-c", "import site; print(site.getsitepackages()[0])"], + capture_output=True, + text=True, + check=False, + ) + if result.returncode != 0: + print_warning("Could not determine site-packages path — skipping prebundle repoint.") + return + site_packages = Path(result.stdout.strip()) + if not site_packages.is_dir(): + print_warning(f"site-packages directory not found: {site_packages} — skipping prebundle repoint.") + return + + prebundle_dirs = _discover_prebundle_dirs() + if not prebundle_dirs: + print_debug("No pip_prebundle directories found under Isaac Sim.") + return + + repointed = 0 + for prebundle_dir in prebundle_dirs: + for pkg_name in _PREBUNDLE_REPOINT_PACKAGES: + prebundled = prebundle_dir / pkg_name + venv_pkg = site_packages / pkg_name + + if not venv_pkg.exists(): + continue + if not prebundled.exists() and not prebundled.is_symlink(): + continue + + # The 'nvidia' directory is a Python namespace package shared across many + # distributions (nvidia-cudnn-cu12, nvidia-cublas-cu12, nvidia-srl, …). + # When using Isaac Sim's built-in Python, site-packages/nvidia only contains + # 'srl'; replacing the whole prebundle nvidia/ with that symlink strips away + # the CUDA shared libraries (libcudnn.so.9, etc.) that torch needs. + # Only repoint the nvidia namespace when the target actually provides the + # CUDA subpackages (cudnn is the minimal required indicator). + if pkg_name == "nvidia" and not (venv_pkg / "cudnn").exists(): + print_debug(f"Skipping repoint of {prebundled}: {venv_pkg} lacks CUDA subpackages (cudnn missing).") + continue + + try: + # Already repointed to the right place — nothing to do. + if prebundled.is_symlink() and prebundled.resolve() == venv_pkg.resolve(): + continue + # Replace the prebundled copy (a stale symlink or a real directory) + # with a symlink to the active environment. We remove rather than + # rename-to-``.bak``: the env copy is the symlink target, so the + # prebundle content is redundant, and renaming a directory on an + # overlayfs lower layer (Docker image build) fails with ``EXDEV``. + _force_remove(prebundled) + if use_symlinks: + prebundled.symlink_to(venv_pkg) + else: + shutil.copytree(venv_pkg, prebundled) + repointed += 1 + print_debug(f"Repointed {prebundled} -> {venv_pkg}") + except OSError as exc: + print_warning(f"Could not repoint {prebundled}: {exc} — skipping.") + + if repointed: + print_info( + f"Repointed {repointed} prebundled package(s) in Isaac Sim to the active environment's site-packages." + ) + else: + print_debug("All prebundled packages already up-to-date — nothing to repoint.") + + # Fail loud: a real (non-symlink) prebundled ``torch`` left behind shadows the + # pip-installed torch on launch paths that do not import ``isaaclab`` (e.g. + # ``isaac-sim.streaming.sh``), pulling a mismatched NCCL and crashing with + # ``undefined symbol: ncclDevCommCreate``. Never let that state ship silently. + # Only relevant when symlinking (Linux); the Windows branch deliberately copies the + # env package into the prebundle, which is a real directory by design. + if use_symlinks and (site_packages / "torch").exists(): + shadowing = [ + prebundle_dir / "torch" + for prebundle_dir in prebundle_dirs + if (prebundle_dir / "torch").is_dir() and not (prebundle_dir / "torch").is_symlink() + ] + if shadowing: + raise RuntimeError( + "Failed to neutralize prebundled torch under Isaac Sim; the following would shadow the " + "pip-installed torch and crash non-isaaclab launches:\n " + "\n ".join(str(p) for p in shadowing) + ) + + +def command_install(install_type: str = "all") -> None: + """Install Isaac Lab extensions and optional extras. + + All core submodules are always installed. Optional submodules, optional + submodule extras, and extra feature dependencies are installed based on + *install_type*. + + Args: + install_type: Controls which optional submodules and extra feature + dependencies to install on top of the always-installed core set. + + * ``"all"`` (default) — install core submodules + optional + submodules (``mimic``, ``teleop``) + all automatic + extra features. + * ``"core"`` — install core submodules only; no optional + submodules, no extra feature dependencies. + * Comma-separated tokens — install core submodules plus the listed + optional submodules and extra features. Valid tokens: + + - Optional submodules: ``mimic``, ``teleop`` + - Extra features: ``contrib[rlinf]``, ``newton``, ``rl[]``, + ``visualizer[]``, ``ov[ovrtx|ovphysx|all]`` + - Special: ``isaacsim`` + + Examples:: + + ./isaaclab.sh -i newton,rl[rsl-rl] + ./isaaclab.sh -i mimic,visualizer[rerun] + ./isaaclab.sh -i teleop,rl[skrl],newton + """ + + # Install system dependencies first. + _install_system_deps() + + print_info("Installing extensions inside the Isaac Lab repository...") + python_exe = extract_python_exe() + + if os.environ.get("VIRTUAL_ENV"): + print_info(f"Using uv/venv environment: {os.environ['VIRTUAL_ENV']}") + elif os.environ.get("CONDA_PREFIX"): + print_info(f"Using conda environment: {os.environ['CONDA_PREFIX']}") + print_info(f"Python executable: {python_exe}") + + install_isaacsim = False + # Always start with the full core set (isaaclab must be first). + submodules_to_install: list[str] = list(CORE_ISAACLAB_SUBMODULES) + # List of (feature_name, selector) tuples to apply after the base install. + extra_features: list[tuple[str, str]] = [] + # List of (submodule_name, selector) tuples for optional submodule extras. + optional_submodule_extra_dependencies: list[tuple[str, str]] = [] + + def append_submodules_once(package_dirs: tuple[str, ...]) -> None: + for pkg_dir in package_dirs: + if pkg_dir not in submodules_to_install: + submodules_to_install.append(pkg_dir) + + # back-compat: "none" is the old name for "core" + if install_type == "none": + install_type = "core" + + if install_type == "all": + for package_dirs in OPTIONAL_ISAACLAB_SUBMODULES.values(): + append_submodules_once(package_dirs) + extra_features = [(name, "") for name in sorted(VALID_EXTRA_FEATURES - MANUAL_EXTRA_FEATURES)] + elif install_type == "core": + # Core only — no optional submodules, no extra features. + pass + else: + for token in split_install_items(install_type): + if "[" in token: + bracket_pos = token.index("[") + name = token[:bracket_pos].strip() + if "]" not in token: + print_warning(f"Malformed install token '{token}': missing closing ']'. Skipping.") + continue + selector = token[bracket_pos + 1 : token.index("]")].strip() + else: + name = token.strip() + selector = "" + + if name == "isaacsim": + install_isaacsim = True + elif name in OPTIONAL_ISAACLAB_SUBMODULES: + append_submodules_once(OPTIONAL_ISAACLAB_SUBMODULES[name]) + if selector: + optional_submodule_extra_dependencies.append((name, selector)) + elif name in VALID_EXTRA_FEATURES: + extra_features.append((name, selector)) + else: + valid = sorted(OPTIONAL_ISAACLAB_SUBMODULES) + sorted(VALID_EXTRA_FEATURES) + ["isaacsim"] + print_warning(f"Unknown install token '{name}'. Valid values: {', '.join(valid)}. Skipping.") + + # Configure extra package indexes for NVIDIA and MuJoCo wheels. + os.environ.setdefault("UV_EXTRA_INDEX_URL", "https://pypi.nvidia.com") + os.environ.setdefault("PIP_EXTRA_INDEX_URL", "https://pypi.nvidia.com") + os.environ.setdefault("PIP_FIND_LINKS", "https://py.mujoco.org/") + + # if on ARM arch, temporarily clear LD_PRELOAD + # LD_PRELOAD is restored below, after installation + saved_ld_preload = None + if is_arm() and "LD_PRELOAD" in os.environ: + print_info("ARM install sandbox: temporarily unsetting LD_PRELOAD for installation.") + saved_ld_preload = os.environ.pop("LD_PRELOAD") + + # Temporarily filter Isaac Sim pre-bundled package paths from PYTHONPATH during all pip operations. + # This prevents pip from scanning and managing packages in Isaac Sim's pip_prebundle directories, + # which can cause those packages to be deleted or modified. This is especially important + # in conda environments where Isaac Sim setup scripts add these paths to PYTHONPATH. + saved_pythonpath = None + filtered_pythonpath = None + if "PYTHONPATH" in os.environ: + saved_pythonpath = os.environ["PYTHONPATH"] + # Filter out any paths containing pip_prebundle (pre-bundled packages that pip shouldn't manage) + paths = saved_pythonpath.split(os.pathsep) + filtered_paths = [p for p in paths if p and "pip_prebundle" not in p] + + if len(filtered_paths) != len(paths): + filtered_pythonpath = os.pathsep.join(filtered_paths) + os.environ["PYTHONPATH"] = filtered_pythonpath + filtered_count = len(paths) - len(filtered_paths) + print_info( + f"Temporarily filtering {filtered_count} Isaac Sim pre-bundled package path(s) from PYTHONPATH " + "during pip operations to prevent interference with pre-bundled packages." + ) + + pip_cmd = get_pip_command(python_exe) + using_uv = pip_cmd[0] == "uv" + + # Probe with the user's original PYTHONPATH (before pip-time filtering) so we detect + # Isaac Sim's setup_python_env.sh ordering that prefers extsDeprecated/ml_archive. + probe_env = {**os.environ} + if saved_pythonpath is not None: + probe_env["PYTHONPATH"] = saved_pythonpath + + # Baseline for the post-install integrity check: no pip operation below may + # leave new dangling symlinks in Isaac Sim's prebundles (nvbugs 6343978). + dangling_symlinks_before = _find_dangling_prebundle_symlinks() + + with _arm_cmake_policy_compatibility(): + try: + # Upgrade pip first to avoid compatibility issues (skip when using uv). + if not using_uv: + print_info("Upgrading pip...") + run_command(pip_cmd + ["install", "--upgrade", "pip"]) + + # Pin setuptools to avoid issues with pkg_resources removal in 82.0.0. + run_command(pip_cmd + ["install", "setuptools<82.0.0"]) + + # Drop pip-installed torch if Isaac Sim's deprecated ML prebundle would shadow it. + _maybe_uninstall_prebundled_torch(python_exe, pip_cmd, using_uv, probe_env=probe_env) + + # Install Isaac Sim if requested. + if install_isaacsim: + _install_isaacsim() + + # Install pytorch (version based on arch). + _ensure_cuda_torch() + + # Install all submodules (core set + any explicitly requested optional ones). + _install_isaaclab_submodules(submodules_to_install) + + # Install requested optional submodule dependency extras. + if optional_submodule_extra_dependencies: + print_info("Installing optional submodule dependencies...") + for submodule_name, selector in optional_submodule_extra_dependencies: + _install_optional_submodule_extra_dependencies(submodule_name, selector) + + # Install requested extra feature dependencies. + if extra_features: + print_info("Installing extra feature dependencies...") + for feature_name, selector in extra_features: + _install_extra_feature(feature_name, selector) + + # In some rare cases, torch might not be installed properly by setup.py, add one more check here. + # Can prevent that from happening. + _ensure_cuda_torch() + + # Ensure Pink IK's runtime dependencies are actually importable. The kit-bundled + # ``pin-pink`` in recent Isaac Sim images can cause transitive dependencies from + # ``pip install -e source/isaaclab`` to be silently skipped. + _ensure_pink_ik_dependencies_installed(python_exe, pip_cmd, probe_env=probe_env) + + # Repoint prebundled packages in Isaac Sim to the environment's copies so + # the active venv/conda versions are always loaded regardless of PYTHONPATH + # ordering (e.g. torch+cu130 in venv vs torch+cu128 in prebundle on aarch64). + _repoint_prebundle_packages() + + # Fail loud if any pip operation above broke Isaac Sim's cross-extension + # symlink farms. Prebundle deletions on their own are routine (pip + # replaces those packages in site-packages, which shadows the prebundle + # at runtime); only newly dangling symlinks break extension startup. + _assert_no_new_dangling_prebundle_symlinks(dangling_symlinks_before) + + finally: + # Restore LD_PRELOAD if we cleared it. + if saved_ld_preload: + os.environ["LD_PRELOAD"] = saved_ld_preload + # Restore PYTHONPATH if we filtered it. + if saved_pythonpath is not None: + os.environ["PYTHONPATH"] = saved_pythonpath + + # Install vscode update unless we're in docker. + if not (os.path.exists("/.dockerenv") or os.path.exists("/run/.containerenv")): + command_vscode_settings() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/misc.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..f1d92a766870484604108f21d27a1a3951c1cad3 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/commands/misc.py @@ -0,0 +1,123 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Misc commands""" + +from ..utils import ( + ISAACLAB_ROOT, + extract_isaacsim_exe, + extract_python_exe, + get_pip_command, + is_windows, + print_info, + print_warning, + run_command, + run_python_command, +) + + +def command_run_isaacsim(sim_args: list[str]) -> None: + """Run Isaac Sim (-s). + + Args: + sim_args: Additional arguments passed to the Isaac Sim executable. + """ + + isaacsim_exe = extract_isaacsim_exe() + print_info(f"Running Isaac Sim from: {isaacsim_exe}") + + isaacsim_exe.append("--ext-folder") + isaacsim_exe.append(str(ISAACLAB_ROOT / "source")) + isaacsim_exe.extend(sim_args) + + run_command(isaacsim_exe, check=False) + + +def command_new(new_args: list[str]) -> None: + """Create a new external project or internal task from template (-n). + + Args: + new_args: Arguments forwarded to the template generator CLI. + """ + + print_info("Installing template dependencies...") + reqs = ISAACLAB_ROOT / "tools" / "template" / "requirements.txt" + run_python_command("pip", ["install", "-q", "-r", str(reqs)], is_module=True) + + print_info("Running template generator...") + cli_script = ISAACLAB_ROOT / "tools" / "template" / "cli.py" + run_python_command(cli_script, new_args) + + +def command_test(test_args: list[str]) -> None: + """Run pytest for Isaac Lab tests (-t). + + Args: + test_args: Additional pytest arguments. + """ + run_python_command("-m", ["pytest", str(ISAACLAB_ROOT / "tools")] + test_args) + + +def command_vscode_settings() -> None: + """Update the vscode settings from template and Isaac Sim settings""" + + print_info("Setting up vscode settings...") + + # Path to setup_vscode.py. + setup_vscode_script = ISAACLAB_ROOT / ".vscode" / "tools" / "setup_vscode.py" + + # Check if the file exists before attempting to run it. + if setup_vscode_script.exists(): + run_python_command(setup_vscode_script, []) + print_info("VS Code settings generated successfully.") + else: + print_warning("Unable to find the script 'setup_vscode.py'. Aborting vscode settings setup.") + + +def command_build_docs() -> None: + """Build the documentation.""" + print_info("Building documentation...") + python_exe = extract_python_exe() + docs_dir = ISAACLAB_ROOT / "docs" + + # Install reqs. + pip_cmd = get_pip_command(python_exe) + run_command( + pip_cmd + ["install", "-r", "requirements.txt"], + cwd=docs_dir, + ) + + # Build + # sphinx-build -b html -d _build/doctrees . _build/current + # using python -m sphinx. + out_dir = docs_dir / "_build" / "current" + cmd = [ + python_exe, + "-m", + "sphinx", + "-b", + "html", + "-d", + "_build/doctrees", + ".", + str(out_dir), + ] + run_command(cmd, cwd=docs_dir) + + index_path = out_dir / "index.html" + print_info(f"Documentation built at {index_path}") + if not is_windows(): + print_info(f"Open with: xdg-open {index_path}") + + +def command_run_docker(args: list[str]) -> None: + """Run the docker container helper script (docker/container.py). + + Args: + args: Arguments forwarded to ``docker/container.py``. + """ + script_path = ISAACLAB_ROOT / "docker" / "container.py" + print_info(f"Running docker utility script from: {script_path}") + run_python_command(script_path, args) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/utils.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c7de00d9656ff7438b0c01913fab0d977845377b --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cli/utils.py @@ -0,0 +1,571 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import os +import platform +import shutil +import subprocess +import sys +from pathlib import Path +from typing import IO, Any + +# Path to Isaac Lab installation. +ISAACLAB_ROOT = Path(__file__).parents[4].resolve() + +# Default path to look for Isaac Sim is _isaac_sim symlink. +DEFAULT_ISAAC_SIM_PATH = ISAACLAB_ROOT / "_isaac_sim" + +# Short script names supported by ``isaaclab -p``. +_PYTHON_SCRIPT_ALIASES = { + "train.py": ISAACLAB_ROOT / "scripts" / "reinforcement_learning" / "train.py", + "play.py": ISAACLAB_ROOT / "scripts" / "reinforcement_learning" / "play.py", +} + +# ANSI colors. +_ANSI_COLOR_RESET = "\033[0m" +_ANSI_COLOR_INFO = "\033[36m" # cyan +_ANSI_COLOR_WARNING = "\033[33m" # yellow +_ANSI_COLOR_ERROR = "\033[31m" # red +_ANSI_COLOR_DEBUG = "\033[1;32m" # bold green + + +def is_windows() -> bool: + """Check if the platform is Windows.""" + return platform.system().lower() == "windows" + + +def is_arm() -> bool: + """Check if the architecture is ARM (likely Mac).""" + machine = platform.machine().lower() + return "aarch64" in machine or "arm64" in machine + + +def _colorize(text: str, color: str, stream: IO[str]) -> str: + """Colorize bit of text, if the stream supports colors or colors aren't disabled. + + Args: + label: Text to colorize. + color: ANSI color code prefix. + stream: Output stream used to detectcolor support. + + Returns: + Colorized label when supported; otherwise the original label. + """ + + if os.environ.get("NO_COLOR"): + return f"{text}" + + if os.environ.get("TERM") == "dumb": + return f"{text}" + + color_supported = hasattr(stream, "isatty") and stream.isatty() + + if not color_supported: + return f"{text}" + else: + return f"{color}{text}{_ANSI_COLOR_RESET}" + + +def print_info(message: str, stream: IO[str] = sys.stdout) -> None: + """Print informational message. + + Args: + message: Message text to print. + stream: Output stream where the message is written. + """ + label = _colorize("[INFO]", _ANSI_COLOR_INFO, stream) + print(f"{label} {message}", file=stream) + + +def print_warning(message: str, stream: IO[str] = sys.stdout) -> None: + """Print warning message. + + Args: + message: Message text to print. + stream: Output stream where the message is written. + """ + label = _colorize("[WARNING]", _ANSI_COLOR_WARNING, stream) + print(f"{label} {message}", file=stream) + + +def print_error(message: str, stream: IO[str] = sys.stderr) -> None: + """Print error message. + + Args: + message: Message text to print. + stream: Output stream where the message is written. + """ + label = _colorize("[ERROR]", _ANSI_COLOR_ERROR, stream) + print(f"{label} {message}", file=stream) + + +def print_debug(message: str, stream: IO[str] = sys.stdout) -> None: + """Print debug message, when debugging is enabled. + + Args: + message: Message text to print. + stream: Output stream where the message is written. + """ + if os.environ.get("DEBUG") != "1": + return + label = _colorize("[DEBUG]", _ANSI_COLOR_DEBUG, stream) + print(f"{label} {message}", file=stream) + + +def _print_debug_env(prefix: str, env: dict[str, str] | None) -> None: + """ + Print the environment for debugging purpose. + Only prints the vars that are added, changed or removed vs the os.environ. + + Args: + prefix: Prefix identifying the caller function in debug output. + env: Environment to compare against os.environ. + """ + + if env is None: + print_debug(f"{prefix}: ENV: ") + return + + current_env = os.environ + env_added = {key: value for key, value in env.items() if key not in current_env} + env_changed = { + key: {"from": current_env[key], "to": value} + for key, value in env.items() + if key in current_env and current_env[key] != value + } + env_removed = [key for key in current_env if key not in env] + + if not env_added and not env_changed and not env_removed: + print_debug(f"{prefix}: ENV: ") + return + + if env_added: + print_debug(f"{prefix}: ENV added: {env_added}") + if env_changed: + print_debug(f"{prefix}: ENV changed: {env_changed}") + if env_removed: + print_debug(f"{prefix}: ENV removed: {env_removed}") + + +_CMD_METACHARACTERS = frozenset("<>|&^") + + +def _escape_for_cmd_exe(cmd: list[str] | tuple[str, ...]) -> list[str]: + """Wrap .bat/.cmd calls in cmd.exe /c so args with < > | & ^ stay literal. + + Uses cmd.exe caret-escaping (``^<``) for metacharacters in args without + whitespace; double-quotes args that contain whitespace. Avoids wrapping a + metacharacter-bearing arg in double quotes -- ``cmd.exe /c "...\"X subprocess.CompletedProcess[Any]: + """Run a command in a subprocess. + + Args: + cmd: Command to execute. + cwd: Working directory for the subprocess. + env: Environment variables for the subprocess. + shell: Whether to run the command through the shell. + check: Whether to raise on non-zero exit code. + stdout: Standard output stream or redirection target. + stderr: Standard error stream or redirection target. + **kwargs: Additional keyword arguments forwarded to ``subprocess.run``. + + Returns: + Result object returned by ``subprocess.run``. + """ + + if cwd is None: + cwd = ISAACLAB_ROOT + + command_str = " ".join(str(part) for part in cmd) if isinstance(cmd, (list, tuple)) else str(cmd) + + # Print some debug info. + print_debug(f'run_command(): CWD: "{cwd}"') + print_debug(f'run_command(): CMD: "{command_str}"') + _print_debug_env("run_command()", env) + + # On Windows, escape cmd.exe metacharacters when invoking .bat/.cmd files. + if isinstance(cmd, (list, tuple)) and is_windows(): + cmd = _escape_for_cmd_exe(cmd) + + try: + return subprocess.run( + cmd, + cwd=cwd, + env=env, + shell=shell, + check=check, + stdout=stdout, + stderr=stderr, + **kwargs, + ) + except subprocess.CalledProcessError as e: + print_error(f'Command failed with code {e.returncode}: "{command_str}"') + sys.exit(e.returncode) + except KeyboardInterrupt: + sys.exit(130) + + +def _is_virtualenv_python(python_exe: str | Path) -> bool: + """Check whether a Python executable belongs to a virtual environment. + + Args: + python_exe: Python executable path. + + Returns: + True when the executable is inside a Python virtual environment. + """ + python_path = Path(python_exe) + return (python_path.parent.parent / "pyvenv.cfg").is_file() + + +def get_pip_command(python_exe: str | None = None) -> list[str]: + """Return the base pip command tokens for the current environment. + + When ``uv`` is available and a virtual environment is active, returns + ``["uv", "pip"]``. When the target Python belongs to a virtual + environment, ``UV_PYTHON`` is set so ``uv pip`` installs into that + environment even if the process itself is not activated. Otherwise returns + ``[python_exe, "-m", "pip"]`` so that the target interpreter's own pip is + used (e.g. Isaac Sim's bundled ``python.sh``). + + Args: + python_exe: Python executable path. Resolved via + :func:`extract_python_exe` when ``None``. + """ + if python_exe is None: + python_exe = extract_python_exe() + + in_venv = bool(os.environ.get("VIRTUAL_ENV") or os.environ.get("CONDA_PREFIX") or (sys.prefix != sys.base_prefix)) + if shutil.which("uv") and (in_venv or _is_virtualenv_python(python_exe)): + os.environ["UV_PYTHON"] = python_exe + return ["uv", "pip"] + + return [python_exe, "-m", "pip"] + + +def extract_python_exe() -> str: + """ + Find the Python executable to use. + """ + + python_exe = None + + # Try uv virtual environment python. + venv_prefix = os.environ.get("VIRTUAL_ENV") + if venv_prefix: + print_debug(f"extract_python_exe(): Found VIRTUAL_ENV: {venv_prefix}") + if is_windows(): + python_exe = Path(venv_prefix) / "Scripts" / "python.exe" + else: + python_exe = Path(venv_prefix) / "bin" / "python" + if not python_exe.exists(): + python_exe = Path(venv_prefix) / "bin" / "python3" + else: + print_debug("extract_python_exe(): No VIRTUAL_ENV found.") + + # Try conda python. + if not python_exe or not Path(python_exe).exists(): + if python_exe: + print_debug( + f'extract_python_exe(): Venv python "{python_exe}" does not exist, trying to find conda python...' + ) + + conda_prefix = os.environ.get("CONDA_PREFIX") + if conda_prefix: + print_debug(f"extract_python_exe(): Found CONDA_PREFIX: {conda_prefix}") + if is_windows(): + python_exe = Path(conda_prefix) / "python.exe" + else: + python_exe = Path(conda_prefix) / "bin" / "python" + if not python_exe.exists(): + python_exe = Path(conda_prefix) / "bin" / "python3" + else: + print_debug("extract_python_exe(): No CONDA_PREFIX found.") + + # Try the current interpreter when already inside a virtual environment. + if (not python_exe or not Path(python_exe).exists()) and sys.prefix != sys.base_prefix: + python_exe = Path(sys.executable) + print_debug(f"extract_python_exe(): Using active virtual environment python: {python_exe}") + + # Try repo-local virtual environments. + if not python_exe or not Path(python_exe).exists(): + for default_venv in (ISAACLAB_ROOT / "env_isaaclab", ISAACLAB_ROOT / ".venv"): + if is_windows(): + candidate = default_venv / "Scripts" / "python.exe" + else: + candidate = default_venv / "bin" / "python" + if candidate.exists(): + print_debug(f"extract_python_exe(): Found repo-local venv python: {candidate}") + python_exe = candidate + break + + # Try kit python. + if not python_exe or not Path(python_exe).exists(): + print_debug("extract_python_exe(): Checking for Kit python...") + + isaacsim_path = extract_isaacsim_path(required=False) + + if isaacsim_path is not None: + if is_windows(): + # Prefer the underlying python.exe over python.bat so we avoid + # cmd.exe metacharacter-quoting hazards on pip args like + # ``setuptools<82.0.0``. isaaclab.bat already sources + # setup_conda_env.bat before reaching the CLI, so children + # inherit the right env without going back through python.bat. + kit_python_exe = isaacsim_path / "kit" / "python" / "python.exe" + if kit_python_exe.exists(): + python_exe = kit_python_exe + else: + python_exe = isaacsim_path / "python.bat" + else: + python_exe = isaacsim_path / "python.sh" + + # Try system python3.12 specifically, then generic python/python3. + if not python_exe or not Path(python_exe).exists(): + system_python_exe = shutil.which("python3.12") or shutil.which("python") or shutil.which("python3") + python_exe = Path(system_python_exe) if system_python_exe else None + print_debug(f"extract_python_exe(): System python candidate: {python_exe}") + if python_exe and python_exe.exists(): + result = subprocess.run( + [str(python_exe), "-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"], + capture_output=True, + text=True, + check=False, + ) + version = result.stdout.strip() + if version != "3.12": + print_error(f"Falling back on system Python {version} ({python_exe}), but 3.12 is required.") + sys.exit(1) + + # Nothing found, error out :) + if not python_exe or not Path(python_exe).exists(): + print_error("Unable to find suitable Python executable") + sys.exit(1) + + print_info(f'Using Python: "{python_exe}"') + + return str(python_exe) + + +def extract_isaacsim_path(*, required: bool = True) -> Path | None: + """Find the Isaac Sim installation path. + + Args: + required: When ``True`` (default), exit the process if Isaac Sim + cannot be found. When ``False``, return ``None`` instead. + """ + # Use the sym-link path to Isaac Sim directory. + isaacsim_path = DEFAULT_ISAAC_SIM_PATH + + # If above path is not available, try to find the path using python. + if not isaacsim_path.exists(): + # Use the current interpreter to probe for isaacsim — avoids a recursive extract_python_exe call. + # Retrieve the path importing isaac sim and getting the environment path. + try: + result = subprocess.run( + [sys.executable, "-c", "import isaacsim"], + capture_output=True, + text=True, + check=False, + # avoid EULA prompt + stdin=subprocess.DEVNULL, + ) + if result.returncode == 0: + # Helper to print env var. + cmd = [sys.executable, "-c", "import isaacsim; import os; print(os.environ['ISAAC_PATH'])"] + res = subprocess.run( + cmd, + capture_output=True, + text=True, + check=False, + # avoid EULA prompt + stdin=subprocess.DEVNULL, + ) + if res.returncode == 0: + output = res.stdout.strip() + if output: + isaacsim_path = Path(output) + except Exception: + pass + + # Check if there is a path available. + if not isaacsim_path.exists(): + if not required: + return None + # Throw an error if no path is found. + print_error(f"Unable to find the Isaac Sim directory: '{isaacsim_path}'") + print("\tThis could be due to the following reasons:") + print("\t1. Conda environment is not activated.") + print("\t2. Isaac Sim package is not installed.") + print(f"\t3. Isaac Sim directory is not available at the default path: {DEFAULT_ISAAC_SIM_PATH}") + # Exit. + sys.exit(1) + + return isaacsim_path + + +def extract_isaacsim_exe() -> list[str]: + """ + Find the Isaac Sim executable. + """ + # Obtain the isaac sim path. + isaacsim_path = extract_isaacsim_path() + + # Isaac Sim executable to use. + if is_windows(): + isaacsim_exe = isaacsim_path / "isaac-sim.bat" + else: + isaacsim_exe = isaacsim_path / "isaac-sim.sh" + + # Check if there is a python path available. + if not isaacsim_exe.exists(): + # Check for installation using Isaac Sim pip. + # Note: pip installed Isaac Sim can only come from a direct + # python environment, so we can directly use 'python' here. + python_exe = sys.executable + try: + result = run_command( + [python_exe, "-c", "import isaacsim"], + capture_output=True, + text=True, + check=False, + # avoid EULA prompt + stdin=subprocess.DEVNULL, + ) + if result.returncode == 0: + # Isaac Sim - Python packages entry point. + return ["isaacsim", "isaacsim.exp.full"] + except Exception: + pass + + print_error(f"No Isaac Sim executable found at path: {isaacsim_path}") + sys.exit(1) + + return [str(isaacsim_exe)] + + +def determine_python_version() -> str: + """Detect Isaac Sim version and return the matching Python version.""" + + isaacsim_version = None + + # 1. Version file (only if Isaac Sim is available) + isaacsim_path = extract_isaacsim_path(required=False) + if isaacsim_path is not None: + version_file = isaacsim_path / "VERSION" + if version_file.exists(): + with open(version_file) as f: + version = f.read().strip() + if version: + isaacsim_version = version + + # 2. Try importing package metadata + if isaacsim_version is None: + try: + from importlib.metadata import version + + isaacsim_version = version("isaacsim") + except Exception: + pass + + # No Isaac Sim found -- default to 3.12 (required by Isaac Sim 6.x). + if isaacsim_version is None: + python_version = "3.12" + print_warning(f"Unable to determine Isaac Sim version. Defaulting to python={python_version}.") + return python_version + + # We found some Isaac Sim + if isaacsim_version.startswith("5."): + python_version = "3.11" + elif isaacsim_version.startswith("6."): + python_version = "3.12" + else: + # We don't recognize the IsaacSim version. + print_error(f"Unsupported Isaac Sim version: {isaacsim_version}") + raise RuntimeError(f"Unsupported Isaac Sim version: {isaacsim_version}") + + print_info(f"Detected Isaac Sim {isaacsim_version} -> using python={python_version}") + return python_version + + +def run_python_command( + script_or_module: str | Path, + args: list[str], + is_module: bool = False, + env: dict[str, str] | None = None, + check: bool = False, +) -> subprocess.CompletedProcess[Any]: + """Run a python script or module using the resolved Python executable. + + Args: + script_or_module: Script path or module name to execute. + args: Additional arguments. + is_module: Whether to execute script_or_module as a module (``python -m``). + env: Environment for the subprocess. Uses current environment if ``None``. + check: Whether to raise ``CalledProcessError`` on non-zero exit codes. + + Returns: + [subprocess.CompletedProcess] Result returned by ``subprocess.run``. + """ + + cmd = [extract_python_exe()] + + if is_module: + cmd.append("-m") + else: + script_or_module = _PYTHON_SCRIPT_ALIASES.get(str(script_or_module), script_or_module) + + cmd.append(str(script_or_module)) + cmd.extend(args) + + command_str = " ".join(str(part) for part in cmd) + + print_debug(f'run_python_command(): CWD: "{os.getcwd()}"') + print_debug(f'run_python_command(): CMD: "{command_str}"') + + return run_command( + cmd, + cwd=os.getcwd(), + env=env, + check=check, + ) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e14e0f6d52c5bb1cbaf714105fcc828fbca2d5c6 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..348294dc1c12339e55c883031e77e3e425bbc524 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__init__.pyi @@ -0,0 +1,29 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "CloneCfg", + "ClonePlan", + "disabled_fabric_change_notifies", + "filter_collisions", + "grid_transforms", + "make_clone_plan", + "random", + "resolve_clone_plan_source", + "sequential", + "usd_replicate", +] + +from .clone_plan import ClonePlan +from .cloner_cfg import CloneCfg +from .cloner_strategies import random, sequential +from .cloner_utils import ( + disabled_fabric_change_notifies, + filter_collisions, + grid_transforms, + make_clone_plan, + resolve_clone_plan_source, + usd_replicate, +) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/__init__.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d22b5be8859e6385372ee0243b80218ce7eafff5 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/_fabric_notices.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/_fabric_notices.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..151774d8e4807cfd0043a1d7f6d46daf0fb6b21a Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/_fabric_notices.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/clone_plan.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/clone_plan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a7016f489d13d7176bd60a79f105af8915a973c Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/clone_plan.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/cloner_cfg.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/cloner_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cef40460c4cdc66c5b2acade492fb34d8bc72141 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/cloner_cfg.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/cloner_strategies.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/cloner_strategies.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71217585643178da56a075ace4b822b80c8ecf01 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/cloner_strategies.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/cloner_utils.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/cloner_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b2e422c37e389c99b89aa5eac59d8fa997ae669 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/__pycache__/cloner_utils.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/_fabric_notices.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/_fabric_notices.py new file mode 100644 index 0000000000000000000000000000000000000000..4326f4ae31950ec9e9c7f39615cc08d3d183162f --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/_fabric_notices.py @@ -0,0 +1,151 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Pure-Python ctypes binding for ``omni::fabric::IFabricUsd::setEnableChangeNotifies``. + +Acquires the ``omni::fabric::IFabricUsd`` carb interface directly from the Carbonite +framework so cloning can suspend Fabric's USD notice listener without depending on +``isaacsim.core.simulation_manager``. + +Mirrors the in-tree pattern in :mod:`isaaclab_newton.physics._cubric` for +``omni::cubric::IAdapter`` — same problem (base-Kit Carbonite interface with no +Python binding), same solution. When Kit exposes this from Python, replace this +module with a one-line import. +""" + +from __future__ import annotations + +import ctypes +import logging +import threading + +logger = logging.getLogger(__name__) + +# carb::Framework vtable (carb/Framework.h) +# 0: loadPluginsEx, 8: unloadAllPlugins, 16: acquireInterfaceWithClient, +# 24: tryAcquireInterfaceWithClient ← used here +_FW_OFF_TRY_ACQUIRE = 24 + +# omni::fabric::IFabricUsd vtable (omni/fabric/usd/interface/IFabricUsd.h) +# 0..88: prefetch / export / type-conversion entry points +# 96: setEnableChangeNotifies(FabricId, bool) +# 104: getEnableChangeNotifies(FabricId) -> bool +_IFU_OFF_SET_ENABLE = 96 +_IFU_OFF_GET_ENABLE = 104 + + +class _Version(ctypes.Structure): + _fields_ = [("major", ctypes.c_uint32), ("minor", ctypes.c_uint32)] + + +class _InterfaceDesc(ctypes.Structure): + _fields_ = [("name", ctypes.c_char_p), ("version", _Version)] + + +def _read_u64(addr: int) -> int: + return ctypes.c_uint64.from_address(addr).value + + +class FabricNoticeBindings: + """Typed wrappers around ``omni::fabric::IFabricUsd``'s notice toggle.""" + + def __init__(self) -> None: + self._iface_ptr: int = 0 + self._set_fn = None + self._get_fn = None + self._validated: bool = False + + def initialize(self) -> bool: + """Acquire the ``IFabricUsd`` interface. Returns False if unavailable.""" + try: + libcarb = ctypes.CDLL("libcarb.so") + except OSError: + logger.info("libcarb.so unavailable — Fabric notice suspension disabled (Linux x86_64 only)") + return False + + libcarb.acquireFramework.restype = ctypes.c_void_p + libcarb.acquireFramework.argtypes = [ctypes.c_char_p, _Version] + fw_ptr = libcarb.acquireFramework(b"isaaclab.cloner", _Version(0, 0)) + if not fw_ptr: + return False + + try_acquire_addr = _read_u64(fw_ptr + _FW_OFF_TRY_ACQUIRE) + if not try_acquire_addr: + return False + + try_acquire = ctypes.CFUNCTYPE( + ctypes.c_void_p, # IFabricUsd* + ctypes.c_char_p, # clientName + _InterfaceDesc, # desc (by value) + ctypes.c_char_p, # pluginName + )(try_acquire_addr) + + desc = _InterfaceDesc(name=b"omni::fabric::IFabricUsd", version=_Version(1, 0)) + + ptr = try_acquire(b"isaaclab.cloner", desc, None) + if not ptr: + return False + self._iface_ptr = ptr + + set_addr = _read_u64(ptr + _IFU_OFF_SET_ENABLE) + get_addr = _read_u64(ptr + _IFU_OFF_GET_ENABLE) + if not (set_addr and get_addr): + return False + + # FabricId is uint64; CARB_ABI uses the platform's standard C calling convention + self._set_fn = ctypes.CFUNCTYPE(None, ctypes.c_uint64, ctypes.c_bool)(set_addr) + self._get_fn = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_uint64)(get_addr) + return True + + @property + def available(self) -> bool: + return self._iface_ptr != 0 + + def set_enable(self, fabric_id: int, enable: bool) -> None: + if self._set_fn is not None: + self._set_fn(ctypes.c_uint64(fabric_id), ctypes.c_bool(enable)) + + def is_enabled(self, fabric_id: int) -> bool: + if self._get_fn is None: + return False + return bool(self._get_fn(ctypes.c_uint64(fabric_id))) + + def validate_with(self, fabric_id: int) -> bool: + """One-time toggle round-trip — guards against ABI offset drift. + + If Kit's ``IFabricUsd`` vtable layout changes, our hardcoded offsets call the + wrong functions and ``set_enable`` no longer flips the flag ``is_enabled`` reads + from. This catches that case the first time we have a real fabric_id to work + with, and lets the caller fall back to a no-op. + """ + if self._validated: + return True + original = self.is_enabled(fabric_id) + self.set_enable(fabric_id, not original) + ok = self.is_enabled(fabric_id) != original + self.set_enable(fabric_id, original) + self._validated = ok + return ok + + +_BINDINGS: FabricNoticeBindings | None = None +_INIT_TRIED: bool = False +_LOCK = threading.Lock() + + +def get_bindings() -> FabricNoticeBindings | None: + """Return the lazily-initialised bindings, or ``None`` if Kit/Carbonite is unavailable.""" + global _BINDINGS, _INIT_TRIED + with _LOCK: + if _BINDINGS is not None: + return _BINDINGS + if _INIT_TRIED: + return None + _INIT_TRIED = True + b = FabricNoticeBindings() + if not b.initialize(): + return None + _BINDINGS = b + return _BINDINGS diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/clone_plan.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/clone_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..973122e7744beaff8d07dcf1824f9b69b1312ba1 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/clone_plan.py @@ -0,0 +1,33 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from dataclasses import dataclass + +import torch + + +@dataclass(frozen=True, eq=False) +class ClonePlan: + """Flat cloning source of truth. + + Produced by scene planning after representative source prims are assigned. The + three fields are the same flat replication contract consumed by USD, physics, + and downstream scene-data providers: each source path maps to the destination + template at the same index, and :attr:`clone_mask` selects the environments + populated from that source. + """ + + sources: tuple[str, ...] + """Source prim paths used for replication.""" + + destinations: tuple[str, ...] + """Destination path templates, one per source path.""" + + clone_mask: torch.Tensor + """Boolean tensor of shape ``[len(sources), num_envs]``; + ``clone_mask[i, j]`` is ``True`` if env ``j`` was populated from + :attr:`sources` ``[i]``.""" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/cloner_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/cloner_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..477b4bbfc2c23e2cc89452c28aade34280c7462d --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/cloner_cfg.py @@ -0,0 +1,45 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from isaaclab.utils.configclass import configclass + +from .cloner_strategies import random + + +@configclass +class CloneCfg: + """Configuration for environment replication. + + The scene builds a :class:`~isaaclab.cloner.ClonePlan` directly from asset + configuration, spawns the representative source prims, and then uses this + configuration to dispatch USD and physics replication for that plan. + """ + + clone_regex: str = "/World/envs/env_.*" + """Destination template for per-environment paths. + + The substring ``".*"`` is replaced with ``"{}"`` internally and formatted with the + environment index (e.g., ``/World/envs/env_0``, ``/World/envs/env_1``). + """ + + clone_usd: bool = True + """Enable USD-spec replication to author cloned prims and optional transforms.""" + + clone_physics: bool = True + """Enable PhysX replication for the same mapping to speed up physics setup.""" + + physics_clone_fn: callable | None = None + """Function used to perform physics replication.""" + + clone_strategy: callable = random + """Function used to build prototype-to-environment mapping. Default is :func:`random`.""" + + device: str = "cpu" + """Torch device on which mapping buffers are allocated.""" + + clone_in_fabric: bool = False + """Enable/disable cloning in fabric for PhysX replication. Default is False.""" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/cloner_strategies.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/cloner_strategies.py new file mode 100644 index 0000000000000000000000000000000000000000..4e54c33be40c1ee898ac8144584faf93ece16bf1 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/cloner_strategies.py @@ -0,0 +1,46 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import torch + + +def random(combinations: torch.Tensor, num_clones: int, device: str) -> torch.Tensor: + """Randomly assign prototypes to environments. + + Each environment is assigned a random prototype combination sampled uniformly from + :attr:`combinations`. + + Args: + combinations: Tensor of shape (num_combos, num_prototypes) containing all possible + prototype combinations. + num_clones: Number of environments to assign combinations to. + device: Torch device on which the output tensor is allocated. + + Returns: + Tensor of shape (num_clones, num_prototypes) containing the chosen prototype + combination for each environment. + """ + chosen = combinations[torch.randint(len(combinations), (num_clones,), device=device)] + return chosen + + +def sequential(combinations: torch.Tensor, num_clones: int, device: str) -> torch.Tensor: + """Deterministically assign prototypes to environments in round-robin fashion. + + Each environment is assigned a prototype combination based on its index modulo the + number of available combinations. + + Args: + combinations: Tensor of shape (num_combos, num_prototypes) containing all possible + prototype combinations. + num_clones: Number of environments to assign combinations to. + device: Torch device on which the output tensor is allocated. + + Returns: + Tensor of shape (num_clones, num_prototypes) containing the chosen prototype + combination for each environment. + """ + chosen = combinations[torch.arange(num_clones, device=device) % len(combinations)] + return chosen diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/cloner_utils.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/cloner_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..86d7232176f53d58feaf0ce2033009503e81792f --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/cloner/cloner_utils.py @@ -0,0 +1,530 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import contextlib +import itertools +import logging +import math +import re +from collections.abc import Iterator, Sequence + +import torch + +from pxr import Gf, Sdf, Usd, UsdGeom, UsdUtils, Vt + +from . import _fabric_notices +from .clone_plan import ClonePlan + +logger = logging.getLogger(__name__) + + +def get_suffix(path_expr: str, destination_template: str) -> str | None: + """Return the part of ``path_expr`` below a destination template's env-instance root. + + The template's ``"{}"`` slot matches exactly one path segment (a concrete id like ``env_3`` + or a wildcard like ``env_.*``). + + Example: + >>> tmpl = "/World/scenes/{}/Robot" + >>> get_suffix("/World/scenes/env_3/Robot/base", tmpl) + '/base' + >>> get_suffix("/World/scenes/.*/Robot/base", tmpl) + '/base' + >>> get_suffix("/World/scenes/env_3/Robot", tmpl) + '' + >>> get_suffix("/World/scenes/env_3/Sensor", tmpl) is None + True + >>> get_suffix("/World/scenes/env_3/RobotArm", tmpl) is None + True + >>> get_suffix("/World/scenes/env_3/sub/Robot/base", tmpl) is None + True + """ + pattern = re.compile(r"[^/]+".join(re.escape(part) for part in destination_template.split("{}"))) + match = pattern.match(path_expr) + if match is None: + return None + suffix = path_expr[match.end() :] + return None if suffix and not suffix.startswith("/") else suffix + + +def resolve_clone_plan_source(path_expr: str, plan: ClonePlan) -> tuple[str, str, str] | None: + """Resolve a destination path expression to its row's source path, destination glob, and asset suffix. + + Finds the rows whose destination template owns ``path_expr`` (same matching + logic as :func:`iter_clone_plan_matches`), OR-merges their + :attr:`~isaaclab.cloner.ClonePlan.clone_mask` rows, and splits the + expression at the row's destination template so the asset-relative suffix is + returned for downstream walks. + + Args: + path_expr: Destination-side path expression (e.g., a sensor's ``prim_path``, + with ``.*`` env wildcard). + plan: Active clone plan. + + Returns: + Three-tuple of ``(source_asset_path, dest_glob_prefix, asset_suffix)``. The + ``asset_suffix`` is the part of ``path_expr`` beyond the matching row's + destination template (empty when ``path_expr`` equals the row's template). + Returns ``None`` when ``path_expr`` matches no row in the plan, letting + callers fall back to direct stage resolution (e.g. for sensor frames + mounted at the env root rather than under a planned asset). + + Raises: + ValueError: When ``path_expr``'s matching rows span multiple distinct + destination templates. + NotImplementedError: When the union of matching rows' clone masks does not + cover every env (partial-env heterogeneous coverage is unsupported). + """ + matching_template: str | None = None + matching_rows: list[int] = [] + matching_suffix: str | None = None + for source_index, destination_template in enumerate(plan.destinations): + if "{}" not in destination_template: + continue + suffix = get_suffix(path_expr, destination_template) + if suffix is None: + continue + if matching_template is None: + matching_template = destination_template + matching_suffix = suffix + elif destination_template != matching_template: + raise ValueError( + f"path_expr {path_expr!r}: matches multiple destination templates" + f" {matching_template!r} and {destination_template!r}." + ) + matching_rows.append(source_index) + if matching_template is None: + return None + if not plan.clone_mask[matching_rows].any(dim=0).all(): + raise NotImplementedError( + f"path_expr {path_expr!r}: partial-env heterogeneous coverage is unsupported;" + " matching rows must collectively cover all envs." + ) + return plan.sources[matching_rows[0]], matching_template.replace("{}", "*"), matching_suffix or "" + + +def iter_clone_plan_matches(plan: ClonePlan, path_expr: str) -> Iterator[tuple[str, str, str, tuple[int, ...]]]: + """Yield clone-plan entries whose destinations own a path expression. + + Example: + For an entry with source root ``"/World/source/Robot"``, destination + template ``"/World/scenes/{}/Robot"``, and populated env ids + ``(0, 2)``, querying ``"/World/scenes/.*/Robot/base"`` yields + ``("/World/source/Robot", "/World/scenes/{}/Robot", + "/World/source/Robot/base", (0, 2))``. + + Args: + plan: Clone plan to query. + path_expr: Destination prim path or path expression. Expressions are + matched against each clone-plan destination template by treating + the template's ``"{}"`` field as the populated environment slot. + + Yields: + Tuples ``(source_root, destination_template, source_path, env_ids)`` + for the nearest matching destination root. Multiple source variants + with the same destination root are preserved. + """ + matches: list[tuple[str, str, str, tuple[int, ...]]] = [] + for source_index, (source_root, destination_template) in enumerate(zip(plan.sources, plan.destinations)): + if "{}" not in destination_template: + continue + + env_ids = tuple(int(i) for i in plan.clone_mask[source_index].nonzero(as_tuple=False).flatten().tolist()) + if not env_ids: + continue + + source_root = source_root.rstrip("/") or "/" + destination_template = destination_template.rstrip("/") or "/" + + suffix = get_suffix(path_expr, destination_template) + if suffix is None: + continue + source_path = source_root + suffix if source_root != "/" else suffix or "/" + + matches.append((source_root, destination_template, source_path, env_ids)) + + matches.sort(key=lambda match: len(match[1].format(match[3][0])), reverse=True) + if matches: + owner_length = len(matches[0][1].format(matches[0][3][0])) + yield from (match for match in matches if len(match[1].format(match[3][0])) == owner_length) + + +@contextlib.contextmanager +def disabled_fabric_change_notifies(stage: Usd.Stage, *, restore: bool = True) -> Iterator[None]: + """Suspend the ``IFabricUsd`` USD notice listener for the body of the ``with`` block. + + Targets the same handler that :meth:`isaacsim.core.cloner.Cloner.disable_change_listener` + toggles, but goes through ``omni::fabric::IFabricUsd`` directly so we don't take an + ``isaacsim.core.simulation_manager`` dependency. + + The listener is a global ``TfNotice`` registered when ``omni.fabric`` loads; it + short-circuits via a soft flag (``IFabricUsd.cpp:739``). Toggling that flag is what + skips the per-``Sdf.CopySpec`` Fabric sync that dominates cloning time on large scenes. + + When this provides a measurable speedup + ---------------------------------------- + Bisection on the regression test (see ``test_cloner.py``) shows the listener cost is + only on the critical path when **all** of these hold: + + 1. The clone happens through the ``InteractiveScene`` path with ``replicate_physics=True``. + Calling :func:`usd_replicate` directly on a stage produces no measurable gap; with + ``replicate_physics=False`` the gap drops to ~1.19x. The PhysX replication path is + what amplifies per-spec listener work. + 2. The cloned prims carry PhysX rigid-body schemas (e.g. ``UsdPhysics.RigidBodyAPI``, + authored via ``rigid_props`` on a spawn cfg). Plain Xforms or geometry without + physics schemas produce ~1.0x — the listener has no Fabric-tracked state to sync. + ``mass_props`` and ``collision_props`` add nothing beyond ``rigid_props``. + 3. Total per-``Sdf.CopySpec`` firings reach ~32K — i.e. ``num_bodies × num_envs`` is + large enough to dominate scene-init cost. Below this the speedup sinks into noise. + + Conditions outside this envelope (no PhysX schemas, single-env scenes, raw + ``usd_replicate`` calls, ``replicate_physics=False``) won't see a perf win — the + suspension is correct but its effect is lost in the rest of the work. + + Re-entrant: if the flag is already off on entry, ``__exit__`` leaves it off. Falls + through to a no-op if the Carbonite interface can't be acquired (e.g. outside a live + Kit application) — the caller never breaks, it just doesn't get the perf win. + + Args: + stage: USD stage whose Fabric notice handler should be suspended. + restore: When ``True`` (default), re-enable the handler on exit. Set to ``False`` + inside a known clone-then-``sim.reset`` window where the downstream Fabric + resync happens anyway and re-enabling here would trigger a redundant + ``forceMinimalPopulate`` batch — see ``PluginInterface.cpp:337``. + + Yields: + None. + """ + bindings = _fabric_notices.get_bindings() + if bindings is None: + yield + return + + # usdrt only works with a live Kit app — defer import so module load stays cheap. + import usdrt + + # Avoid leaking a strong reference into the global ``StageCache`` for stages we did not + # author into the cache: ``Insert`` keeps the stage alive for the rest of the process. + cache = UsdUtils.StageCache.Get() + cached_id = cache.GetId(stage) + stage_id = cached_id.ToLongInt() if cached_id.IsValid() else cache.Insert(stage).ToLongInt() + # ``FabricId`` wraps a uint64; the C ABI needs the raw integer. + fabric_id = usdrt.Usd.Stage.Attach(stage_id).GetFabricId().id + # First-call ABI sanity check — if the toggle doesn't actually round-trip the flag + # (e.g. Kit's vtable shifted), fall through to a no-op rather than corrupting state. + if not bindings.validate_with(fabric_id): + logger.warning("Fabric notice toggle failed round-trip check — suspension disabled") + yield + return + was_enabled = bindings.is_enabled(fabric_id) + if was_enabled: + bindings.set_enable(fabric_id, False) + try: + yield + finally: + if restore and was_enabled: + bindings.set_enable(fabric_id, True) + + +def make_clone_plan( + sources: Sequence[Sequence[str]], + destinations: Sequence[str], + num_clones: int, + clone_strategy: callable, + device: str = "cpu", +) -> tuple[tuple[str, ...], tuple[str, ...], torch.Tensor]: + """Compute the flat source/destination/mask components of a clone plan. + + Enumerates all combinations of prototypes, selects a combination per environment using + ``clone_strategy``, and builds the boolean masking matrix that indicates which prototype + populates each environment slot. The caller composes the returned tuple into a + :class:`ClonePlan`. + + Args: + sources: Prototype prim paths grouped by asset type (e.g., ``[[robot_a, robot_b], [obj_x]]``). + destinations: Destination path templates (one per group) with ``"{}"`` placeholder for env id. + num_clones: Number of environments to populate. + clone_strategy: Function that picks a prototype combo per environment; signature + ``clone_strategy(combos: Tensor, num_clones: int, device: str) -> Tensor[num_clones, num_groups]``. + device: Torch device for the returned mask. Defaults to ``"cpu"``. + + Returns: + A tuple ``(sources, destinations, clone_mask)`` where ``sources`` and ``destinations`` + are flattened per-source entries (one entry per prototype) and ``clone_mask`` is a + ``[num_src, num_clones]`` boolean tensor on ``device``. + """ + if len(sources) != len(destinations): + raise ValueError(f"Expected one destination per source group, got {len(destinations)} and {len(sources)}.") + if not sources: + raise ValueError("Expected at least one source group.") + group_sizes = [len(group) for group in sources] + if any(size == 0 for size in group_sizes): + raise ValueError("Source groups must not be empty.") + + # 1) Flatten into src and dest lists + src = tuple(p for group in sources for p in group) + dest = tuple(dst for dst, group in zip(destinations, sources) for _ in group) + + # 2) Enumerate all combinations of "one prototype per group" + # all_combos: list of tuples (g0_idx, g1_idx, ..., g_{G-1}_idx) + all_combos = list(itertools.product(*[range(s) for s in group_sizes])) + combos = torch.tensor(all_combos, dtype=torch.long, device=device) + + # 3) Assign a combination to each environment + chosen = clone_strategy(combos, num_clones, device) + + # 4) Build masking: [num_src, num_clones] boolean + # For each env, for each group, mark exactly one prototype row as True. + group_offsets = torch.tensor([0] + list(itertools.accumulate(group_sizes[:-1])), dtype=torch.long, device=device) + rows = (chosen + group_offsets).view(-1) + cols = torch.arange(num_clones, device=device).view(-1, 1).expand(-1, len(group_sizes)).reshape(-1) + + masking = torch.zeros((sum(group_sizes), num_clones), dtype=torch.bool, device=device) + masking[rows, cols] = True + return src, dest, masking + + +def usd_replicate( + stage: Usd.Stage, + sources: Sequence[str], + destinations: Sequence[str], + env_ids: torch.Tensor, + mask: torch.Tensor | None = None, + positions: torch.Tensor | None = None, + quaternions: torch.Tensor | None = None, +) -> None: + """Replicate USD prims to per-environment destinations. + + Copies each source prim spec to destination templates for selected environments + (``mask``). Optionally authors translate/orient from position/quaternion buffers. + Replication runs in path-depth order (parents before children) for robust composition. + + Args: + stage: USD stage. + sources: Source prim paths. + destinations: Destination formattable templates with ``"{}"`` for env index. + env_ids: Environment indices. + mask: Optional per-source or shared mask. ``None`` selects all. + positions: Optional positions (``[E, 3]``) -> ``xformOp:translate``. + quaternions: Optional orientations (``[E, 4]``) in ``xyzw`` -> ``xformOp:orient``. + + """ + rl = stage.GetRootLayer() + + # Group replication by destination path depth so ancestors land before deeper paths. + # This avoids composition issues for nested or interdependent specs. + def dp_depth(template: str) -> int: + """Return destination prim path depth for stable parent-first replication.""" + dp = template.format(0) + return Sdf.Path(dp).pathElementCount + + order = sorted(range(len(sources)), key=lambda i: dp_depth(destinations[i])) + + # Process in layers of equal depth, committing at each depth to stabilize composition + depth_to_indices: dict[int, list[int]] = {} + for i in order: + d = dp_depth(destinations[i]) + depth_to_indices.setdefault(d, []).append(i) + + for depth in sorted(depth_to_indices.keys()): + with Sdf.ChangeBlock(): + for i in depth_to_indices[depth]: + src = sources[i] + tmpl = destinations[i] + # Select target environments for this source (supports None, [E], or [S, E]) + target_envs = env_ids if mask is None else env_ids[mask[i]] + for wid in target_envs.tolist(): + dp = tmpl.format(wid) + Sdf.CreatePrimInLayer(rl, dp) + if src == dp: + pass # self-copy: CreatePrimInLayer already ensures it exists; CopySpec would be destructive + else: + Sdf.CopySpec(rl, Sdf.Path(src), rl, Sdf.Path(dp)) + + if positions is not None or quaternions is not None: + ps = rl.GetPrimAtPath(dp) + op_names = [] + if positions is not None: + p = positions[wid] + t_attr = ps.GetAttributeAtPath(dp + ".xformOp:translate") + if t_attr is None: + t_attr = Sdf.AttributeSpec(ps, "xformOp:translate", Sdf.ValueTypeNames.Double3) + t_attr.default = Gf.Vec3d(float(p[0]), float(p[1]), float(p[2])) + op_names.append("xformOp:translate") + if quaternions is not None: + q = quaternions[wid] + o_attr = ps.GetAttributeAtPath(dp + ".xformOp:orient") + if o_attr is None: + o_attr = Sdf.AttributeSpec(ps, "xformOp:orient", Sdf.ValueTypeNames.Quatd) + # xyzw convention: q[3] is w, q[0:3] is xyz + o_attr.default = Gf.Quatd(float(q[3]), Gf.Vec3d(float(q[0]), float(q[1]), float(q[2]))) + op_names.append("xformOp:orient") + # Only author xformOpOrder for the ops we actually authored + if op_names: + op_order = ps.GetAttributeAtPath(dp + ".xformOpOrder") or Sdf.AttributeSpec( + ps, UsdGeom.Tokens.xformOpOrder, Sdf.ValueTypeNames.TokenArray + ) + op_order.default = Vt.TokenArray(op_names) + + +def filter_collisions( + stage: Usd.Stage, + physicsscene_path: str, + collision_root_path: str, + prim_paths: list[str], + global_paths: list[str] = [], +) -> None: + """Create inverted collision groups for clones (PhysX only). + + Sets PhysX scene attributes and collision groups on the prim at ``physicsscene_path`` + (no PhysxSchema import). Call only when the physics backend is PhysX; Newton uses + its own collision/world handling and does not use USD PhysX collision groups. + + Creates one PhysicsCollisionGroup per prim under ``collision_root_path``, enabling + inverted filtering so clones don't collide across groups. Optionally adds a global + group that collides with all. + + Args: + stage: USD stage. + physicsscene_path: Path to PhysicsScene prim. + collision_root_path: Root scope for collision groups. + prim_paths: Per-clone prim paths. + global_paths: Optional global-collider paths. + + """ + + scene_prim = stage.GetPrimAtPath(physicsscene_path) + # We invert the collision group filters for more efficient collision filtering across environments + invert_attr = scene_prim.CreateAttribute("physxScene:invertCollisionGroupFilter", Sdf.ValueTypeNames.Bool) + invert_attr.Set(True) + + # Make sure we create the collision_scope in the RootLayer since the edit target + # may be a live layer in the case of Live Sync. + with Usd.EditContext(stage, Usd.EditTarget(stage.GetRootLayer())): + UsdGeom.Scope.Define(stage, collision_root_path) + + with Sdf.ChangeBlock(): + if len(global_paths) > 0: + global_collision_group_path = collision_root_path + "/global_group" + # add collision group prim + global_collision_group = Sdf.PrimSpec( + stage.GetRootLayer().GetPrimAtPath(collision_root_path), + "global_group", + Sdf.SpecifierDef, + "PhysicsCollisionGroup", + ) + # prepend collision API schema + global_collision_group.SetInfo(Usd.Tokens.apiSchemas, Sdf.TokenListOp.Create({"CollectionAPI:colliders"})) + + # expansion rule + expansion_rule = Sdf.AttributeSpec( + global_collision_group, + "collection:colliders:expansionRule", + Sdf.ValueTypeNames.Token, + Sdf.VariabilityUniform, + ) + expansion_rule.default = "expandPrims" + + # includes rel + global_includes_rel = Sdf.RelationshipSpec(global_collision_group, "collection:colliders:includes", False) + for global_path in global_paths: + global_includes_rel.targetPathList.Append(global_path) + + # filteredGroups rel + global_filtered_groups = Sdf.RelationshipSpec(global_collision_group, "physics:filteredGroups", False) + # We are using inverted collision group filtering, which means objects by default don't collide across + # groups. We need to add this group as a filtered group, so that objects within this group collide with + # each other. + global_filtered_groups.targetPathList.Append(global_collision_group_path) + + # set collision groups and filters + for i, prim_path in enumerate(prim_paths): + collision_group_path = collision_root_path + f"/group{i}" + # add collision group prim + collision_group = Sdf.PrimSpec( + stage.GetRootLayer().GetPrimAtPath(collision_root_path), + f"group{i}", + Sdf.SpecifierDef, + "PhysicsCollisionGroup", + ) + # prepend collision API schema + collision_group.SetInfo(Usd.Tokens.apiSchemas, Sdf.TokenListOp.Create({"CollectionAPI:colliders"})) + + # expansion rule + expansion_rule = Sdf.AttributeSpec( + collision_group, + "collection:colliders:expansionRule", + Sdf.ValueTypeNames.Token, + Sdf.VariabilityUniform, + ) + expansion_rule.default = "expandPrims" + + # includes rel + includes_rel = Sdf.RelationshipSpec(collision_group, "collection:colliders:includes", False) + includes_rel.targetPathList.Append(prim_path) + + # filteredGroups rel + filtered_groups = Sdf.RelationshipSpec(collision_group, "physics:filteredGroups", False) + # We are using inverted collision group filtering, which means objects by default don't collide across + # groups. We need to add this group as a filtered group, so that objects within this group collide with + # each other. + filtered_groups.targetPathList.Append(collision_group_path) + if len(global_paths) > 0: + filtered_groups.targetPathList.Append(global_collision_group_path) + global_filtered_groups.targetPathList.Append(collision_group_path) + + +def grid_transforms(N: int, spacing: float = 1.0, up_axis: str = "z", device="cpu"): + """Create a centered grid of transforms for ``N`` instances. + + Computes ``(x, y)`` coordinates in a roughly square grid centered at the origin + with the provided spacing, places the third coordinate according to ``up_axis``, + and returns identity orientations. This matches the grid layout used by + :class:`isaaclab.terrains.TerrainImporter` for consistent environment positioning. + + Args: + N: Number of instances. + spacing: Distance between neighboring grid positions. + up_axis: Up axis for positions ("z", "y", or "x"). + device: Torch device for returned tensors. + + Returns: + A tuple ``(pos, ori)`` where: + - ``pos`` is a tensor of shape ``(N, 3)`` with positions. + - ``ori`` is a tensor of shape ``(N, 4)`` with identity quaternions in ``(x, y, z, w)``. + """ + # Match terrain_importer._compute_env_origins_grid layout for consistency + num_rows = int(math.ceil(N / math.sqrt(N))) + num_cols = int(math.ceil(N / num_rows)) + + # Create meshgrid matching terrain's "ij" indexing + ii, jj = torch.meshgrid( + torch.arange(num_rows, device=device, dtype=torch.float32), + torch.arange(num_cols, device=device, dtype=torch.float32), + indexing="ij", + ) + # Flatten and take first N elements + ii = ii.flatten()[:N] + jj = jj.flatten()[:N] + + # Match terrain's coordinate system: X from rows (negated), Y from cols + x = -(ii - (num_rows - 1) / 2) * spacing + y = (jj - (num_cols - 1) / 2) * spacing + z0 = torch.zeros(N, device=device) + + # place on plane based on up_axis + if up_axis.lower() == "z": + pos = torch.stack([x, y, z0], dim=1) + elif up_axis.lower() == "y": + pos = torch.stack([x, z0, y], dim=1) + else: # up_axis == "x" + pos = torch.stack([z0, x, y], dim=1) + + # identity orientations (x,y,z,w) + ori = torch.zeros((N, 4), device=device) + ori[:, 3] = 1.0 # w=1 for identity quaternion + return pos, ori diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b1704a4bc4455b6351f0050acdec08878b329586 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__init__.py @@ -0,0 +1,16 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-package for different controllers and motion-generators. + +Controllers or motion generators are responsible for closed-loop tracking of a given command. The +controller can be a simple PID controller or a more complex controller such as impedance control +or inverse kinematics control. The controller is responsible for generating the desired joint-level +commands to be sent to the robot. +""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..753e292c6f97250afe2bebcc2cf942511b192662 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__init__.pyi @@ -0,0 +1,16 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "DifferentialIKController", + "DifferentialIKControllerCfg", + "OperationalSpaceController", + "OperationalSpaceControllerCfg", +] + +from .differential_ik import DifferentialIKController +from .differential_ik_cfg import DifferentialIKControllerCfg +from .operational_space import OperationalSpaceController +from .operational_space_cfg import OperationalSpaceControllerCfg diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__pycache__/__init__.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d22344ea01310e53b6aa45bada2f588779ad2ec Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__pycache__/differential_ik.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__pycache__/differential_ik.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddaf62c2b30c00981292badfc23f75eb98c435d7 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__pycache__/differential_ik.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__pycache__/differential_ik_cfg.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__pycache__/differential_ik_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45ab65b864d212d7474d78e4ad86e770c828dcd8 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__pycache__/differential_ik_cfg.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__pycache__/operational_space_cfg.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__pycache__/operational_space_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd6fd3d66606c715616e59013d7bcf6123f32ecc Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/__pycache__/operational_space_cfg.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/config/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..460a30569089052537f30b25ddab421f8aba8568 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/config/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/config/data/lula_franka_gen.urdf b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/config/data/lula_franka_gen.urdf new file mode 100644 index 0000000000000000000000000000000000000000..2d00a71e12d5ef85e0d20d64aea2be49539a6b1a --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/config/data/lula_franka_gen.urdf @@ -0,0 +1,415 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/config/rmp_flow.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/config/rmp_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..a7545d0a9917c471a88b77032a8b26fb7634459b --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/config/rmp_flow.py @@ -0,0 +1,93 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import os + +from isaaclab.controllers.rmp_flow_cfg import RmpFlowControllerCfg +from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR + +# Directory on Nucleus Server for RMP-Flow assets (URDFs, collision models, etc.) +ISAACLAB_NUCLEUS_RMPFLOW_DIR = os.path.join(ISAACLAB_NUCLEUS_DIR, "Controllers", "RmpFlowAssets") + +# Sentinel prefix for paths inside the isaacsim.robot_motion.motion_generation extension. +# RmpFlowController resolves these at init time (after enabling the extension) so that +# this cfg file stays free of any isaacsim/Kit imports. +_EXT_MOTION_CFG = "rmpflow_ext:motion_policy_configs/" + +# Path to current directory +_CUR_DIR = os.path.dirname(os.path.realpath(__file__)) + +FRANKA_RMPFLOW_CFG = RmpFlowControllerCfg( + config_file=_EXT_MOTION_CFG + "franka/rmpflow/franka_rmpflow_common.yaml", + urdf_file=os.path.join(_CUR_DIR, "data", "lula_franka_gen.urdf"), + collision_file=_EXT_MOTION_CFG + "franka/rmpflow/robot_descriptor.yaml", + frame_name="panda_end_effector", + evaluations_per_frame=5, +) +"""Configuration of RMPFlow for Franka arm (default from `isaacsim.robot_motion.motion_generation`).""" + + +UR10_RMPFLOW_CFG = RmpFlowControllerCfg( + config_file=_EXT_MOTION_CFG + "ur10/rmpflow/ur10_rmpflow_config.yaml", + urdf_file=_EXT_MOTION_CFG + "ur10/ur10_robot.urdf", + collision_file=_EXT_MOTION_CFG + "ur10/rmpflow/ur10_robot_description.yaml", + frame_name="ee_link", + evaluations_per_frame=5, +) +"""Configuration of RMPFlow for UR10 arm (default from `isaacsim.robot_motion.motion_generation`).""" + +GALBOT_LEFT_ARM_RMPFLOW_CFG = RmpFlowControllerCfg( + config_file=os.path.join( + ISAACLAB_NUCLEUS_RMPFLOW_DIR, + "galbot_one_charlie", + "rmpflow", + "galbot_one_charlie_left_arm_rmpflow_config.yaml", + ), + urdf_file=os.path.join(ISAACLAB_NUCLEUS_RMPFLOW_DIR, "galbot_one_charlie", "galbot_one_charlie.urdf"), + collision_file=os.path.join( + ISAACLAB_NUCLEUS_RMPFLOW_DIR, "galbot_one_charlie", "rmpflow", "galbot_one_charlie_left_arm_gripper.yaml" + ), + frame_name="left_gripper_tcp_link", + evaluations_per_frame=5, + ignore_robot_state_updates=True, +) + +GALBOT_RIGHT_ARM_RMPFLOW_CFG = RmpFlowControllerCfg( + config_file=os.path.join( + ISAACLAB_NUCLEUS_RMPFLOW_DIR, + "galbot_one_charlie", + "rmpflow", + "galbot_one_charlie_right_arm_rmpflow_config.yaml", + ), + urdf_file=os.path.join(ISAACLAB_NUCLEUS_RMPFLOW_DIR, "galbot_one_charlie", "galbot_one_charlie.urdf"), + collision_file=os.path.join( + ISAACLAB_NUCLEUS_RMPFLOW_DIR, "galbot_one_charlie", "rmpflow", "galbot_one_charlie_right_arm_suction.yaml" + ), + frame_name="right_suction_cup_tcp_link", + evaluations_per_frame=5, + ignore_robot_state_updates=True, +) + +"""Configuration of RMPFlow for Galbot humanoid.""" + +AGIBOT_LEFT_ARM_RMPFLOW_CFG = RmpFlowControllerCfg( + config_file=os.path.join(ISAACLAB_NUCLEUS_RMPFLOW_DIR, "agibot", "rmpflow", "agibot_left_arm_rmpflow_config.yaml"), + urdf_file=os.path.join(ISAACLAB_NUCLEUS_RMPFLOW_DIR, "agibot", "agibot.urdf"), + collision_file=os.path.join(ISAACLAB_NUCLEUS_RMPFLOW_DIR, "agibot", "rmpflow", "agibot_left_arm_gripper.yaml"), + frame_name="gripper_center", + evaluations_per_frame=5, + ignore_robot_state_updates=True, +) + +AGIBOT_RIGHT_ARM_RMPFLOW_CFG = RmpFlowControllerCfg( + config_file=os.path.join(ISAACLAB_NUCLEUS_RMPFLOW_DIR, "agibot", "rmpflow", "agibot_right_arm_rmpflow_config.yaml"), + urdf_file=os.path.join(ISAACLAB_NUCLEUS_RMPFLOW_DIR, "agibot", "agibot.urdf"), + collision_file=os.path.join(ISAACLAB_NUCLEUS_RMPFLOW_DIR, "agibot", "rmpflow", "agibot_right_arm_gripper.yaml"), + frame_name="right_gripper_center", + evaluations_per_frame=5, + ignore_robot_state_updates=True, +) + +"""Configuration of RMPFlow for Agibot humanoid.""" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/differential_ik.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/differential_ik.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8f74bade85ec1935d120e2d9796ecc9732ae88 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/differential_ik.py @@ -0,0 +1,241 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +from isaaclab.utils.math import apply_delta_pose, compute_pose_error + +if TYPE_CHECKING: + from .differential_ik_cfg import DifferentialIKControllerCfg + + +class DifferentialIKController: + r"""Differential inverse kinematics (IK) controller. + + This controller is based on the concept of differential inverse kinematics [1, 2] which is a method for computing + the change in joint positions that yields the desired change in pose. + + .. math:: + + \Delta \mathbf{q} &= \mathbf{J}^{\dagger} \Delta \mathbf{x} \\ + \mathbf{q}_{\text{desired}} &= \mathbf{q}_{\text{current}} + \Delta \mathbf{q} + + where :math:`\mathbf{J}^{\dagger}` is the pseudo-inverse of the Jacobian matrix :math:`\mathbf{J}`, + :math:`\Delta \mathbf{x}` is the desired change in pose, and :math:`\mathbf{q}_{\text{current}}` + is the current joint positions. + + To deal with singularity in Jacobian, the following methods are supported for computing inverse of the Jacobian: + + - "pinv": Moore-Penrose pseudo-inverse + - "svd": Adaptive singular-value decomposition (SVD) + - "trans": Transpose of matrix + - "dls": Damped version of Moore-Penrose pseudo-inverse (also called Levenberg-Marquardt) + + + .. caution:: + The controller does not assume anything about the frames of the current and desired end-effector pose, + or the joint-space velocities. It is up to the user to ensure that these quantities are given + in the correct format. + + Reference: + + 1. `Robot Dynamics Lecture Notes `_ + by Marco Hutter (ETH Zurich) + 2. `Introduction to Inverse Kinematics `_ + by Samuel R. Buss (University of California, San Diego) + + """ + + def __init__(self, cfg: DifferentialIKControllerCfg, num_envs: int, device: str): + """Initialize the controller. + + Args: + cfg: The configuration for the controller. + num_envs: The number of environments. + device: The device to use for computations. + """ + # store inputs + self.cfg = cfg + self.num_envs = num_envs + self._device = device + # create buffers + self.ee_pos_des = torch.zeros(self.num_envs, 3, device=self._device) + self.ee_quat_des = torch.zeros(self.num_envs, 4, device=self._device) + # -- input command + self._command = torch.zeros(self.num_envs, self.action_dim, device=self._device) + + """ + Properties. + """ + + @property + def action_dim(self) -> int: + """Dimension of the controller's input command.""" + if self.cfg.command_type == "position": + return 3 # (x, y, z) + elif self.cfg.command_type == "pose" and self.cfg.use_relative_mode: + return 6 # (dx, dy, dz, droll, dpitch, dyaw) + else: + return 7 # (x, y, z, qx, qy, qz, qw) + + """ + Operations. + """ + + def reset(self, env_ids: torch.Tensor = None): + """Reset the internals. + + Args: + env_ids: The environment indices to reset. If None, then all environments are reset. + """ + pass + + def set_command( + self, command: torch.Tensor, ee_pos: torch.Tensor | None = None, ee_quat: torch.Tensor | None = None + ): + """Set target end-effector pose command. + + Based on the configured command type and relative mode, the method computes the desired end-effector pose. + It is up to the user to ensure that the command is given in the correct frame. The method only + applies the relative mode if the command type is ``position_rel`` or ``pose_rel``. + + Args: + command: The input command in shape (N, 3) or (N, 6) or (N, 7). + ee_pos: The current end-effector position in shape (N, 3). + This is only needed if the command type is ``position_rel`` or ``pose_rel``. + ee_quat: The current end-effector orientation (x, y, z, w) in shape (N, 4). + This is only needed if the command type is ``position_*`` or ``pose_rel``. + + Raises: + ValueError: If the command type is ``position_*`` and :attr:`ee_quat` is None. + ValueError: If the command type is ``position_rel`` and :attr:`ee_pos` is None. + ValueError: If the command type is ``pose_rel`` and either :attr:`ee_pos` or :attr:`ee_quat` is None. + """ + # store command + self._command[:] = command + # compute the desired end-effector pose + if self.cfg.command_type == "position": + # we need end-effector orientation even though we are in position mode + # this is only needed for display purposes + if ee_quat is None: + raise ValueError("End-effector orientation can not be None for `position_*` command type!") + # compute targets + if self.cfg.use_relative_mode: + if ee_pos is None: + raise ValueError("End-effector position can not be None for `position_rel` command type!") + self.ee_pos_des[:] = ee_pos + self._command + self.ee_quat_des[:] = ee_quat + else: + self.ee_pos_des[:] = self._command + self.ee_quat_des[:] = ee_quat + else: + # compute targets + if self.cfg.use_relative_mode: + if ee_pos is None or ee_quat is None: + raise ValueError( + "Neither end-effector position nor orientation can be None for `pose_rel` command type!" + ) + self.ee_pos_des, self.ee_quat_des = apply_delta_pose(ee_pos, ee_quat, self._command) + else: + self.ee_pos_des = self._command[:, 0:3] + self.ee_quat_des = self._command[:, 3:7] + + def compute( + self, ee_pos: torch.Tensor, ee_quat: torch.Tensor, jacobian: torch.Tensor, joint_pos: torch.Tensor + ) -> torch.Tensor: + """Computes the target joint positions that will yield the desired end effector pose. + + Args: + ee_pos: The current end-effector position in shape (N, 3). + ee_quat: The current end-effector orientation in shape (N, 4). + jacobian: The geometric jacobian matrix in shape (N, 6, num_joints). + joint_pos: The current joint positions in shape (N, num_joints). + + Returns: + The target joint positions commands in shape (N, num_joints). + """ + # compute the delta in joint-space + if "position" in self.cfg.command_type: + position_error = self.ee_pos_des - ee_pos + jacobian_pos = jacobian[:, 0:3] + delta_joint_pos = self._compute_delta_joint_pos(delta_pose=position_error, jacobian=jacobian_pos) + else: + position_error, axis_angle_error = compute_pose_error( + ee_pos, ee_quat, self.ee_pos_des, self.ee_quat_des, rot_error_type="axis_angle" + ) + pose_error = torch.cat((position_error, axis_angle_error), dim=1) + delta_joint_pos = self._compute_delta_joint_pos(delta_pose=pose_error, jacobian=jacobian) + # return the desired joint positions + return joint_pos + delta_joint_pos + + """ + Helper functions. + """ + + def _compute_delta_joint_pos(self, delta_pose: torch.Tensor, jacobian: torch.Tensor) -> torch.Tensor: + """Computes the change in joint position that yields the desired change in pose. + + The method uses the Jacobian mapping from joint-space velocities to end-effector velocities + to compute the delta-change in the joint-space that moves the robot closer to a desired + end-effector position. + + Args: + delta_pose: The desired delta pose in shape (N, 3) or (N, 6). + jacobian: The geometric jacobian matrix in shape (N, 3, num_joints) or (N, 6, num_joints). + + Returns: + The desired delta in joint space. Shape is (N, num-jointsß). + """ + if self.cfg.ik_params is None: + raise RuntimeError(f"Inverse-kinematics parameters for method '{self.cfg.ik_method}' is not defined!") + # compute the delta in joint-space + if self.cfg.ik_method == "pinv": # Jacobian pseudo-inverse + # parameters + k_val = self.cfg.ik_params["k_val"] + # computation + jacobian_pinv = torch.linalg.pinv(jacobian) + delta_joint_pos = k_val * jacobian_pinv @ delta_pose.unsqueeze(-1) + delta_joint_pos = delta_joint_pos.squeeze(-1) + elif self.cfg.ik_method == "svd": # adaptive SVD + # parameters + k_val = self.cfg.ik_params["k_val"] + min_singular_value = self.cfg.ik_params["min_singular_value"] + # computation + # U: 6xd, S: dxd, V: d x num-joint + U, S, Vh = torch.linalg.svd(jacobian) + S_inv = 1.0 / S + S_inv = torch.where(min_singular_value < S, S_inv, torch.zeros_like(S_inv)) + jacobian_pinv = ( + torch.transpose(Vh, dim0=1, dim1=2)[:, :, :6] + @ torch.diag_embed(S_inv) + @ torch.transpose(U, dim0=1, dim1=2) + ) + delta_joint_pos = k_val * jacobian_pinv @ delta_pose.unsqueeze(-1) + delta_joint_pos = delta_joint_pos.squeeze(-1) + elif self.cfg.ik_method == "trans": # Jacobian transpose + # parameters + k_val = self.cfg.ik_params["k_val"] + # computation + jacobian_T = torch.transpose(jacobian, dim0=1, dim1=2) + delta_joint_pos = k_val * jacobian_T @ delta_pose.unsqueeze(-1) + delta_joint_pos = delta_joint_pos.squeeze(-1) + elif self.cfg.ik_method == "dls": # damped least squares + # parameters + lambda_val = self.cfg.ik_params["lambda_val"] + # computation + jacobian_T = torch.transpose(jacobian, dim0=1, dim1=2) + lambda_matrix = (lambda_val**2) * torch.eye(n=jacobian.shape[1], device=self._device) + delta_joint_pos = ( + jacobian_T @ torch.inverse(jacobian @ jacobian_T + lambda_matrix) @ delta_pose.unsqueeze(-1) + ) + delta_joint_pos = delta_joint_pos.squeeze(-1) + else: + raise ValueError(f"Unsupported inverse-kinematics method: {self.cfg.ik_method}") + + return delta_joint_pos diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/differential_ik_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/differential_ik_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..409ecc9429f5090c1340834319c8fa4e7590c34f --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/differential_ik_cfg.py @@ -0,0 +1,73 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from dataclasses import MISSING +from typing import TYPE_CHECKING, Literal + +from isaaclab.utils.configclass import configclass + +if TYPE_CHECKING: + from .differential_ik import DifferentialIKController + + +@configclass +class DifferentialIKControllerCfg: + """Configuration for differential inverse kinematics controller.""" + + class_type: type[DifferentialIKController] | str = "{DIR}.differential_ik:DifferentialIKController" + """The associated controller class.""" + + command_type: Literal["position", "pose"] = MISSING + """Type of task-space command to control the articulation's body. + + If "position", then the controller only controls the position of the articulation's body. + Otherwise, the controller controls the pose of the articulation's body. + """ + + use_relative_mode: bool = False + """Whether to use relative mode for the controller. Defaults to False. + + If True, then the controller treats the input command as a delta change in the position/pose. + Otherwise, the controller treats the input command as the absolute position/pose. + """ + + ik_method: Literal["pinv", "svd", "trans", "dls"] = MISSING + """Method for computing inverse of Jacobian.""" + + ik_params: dict[str, float] | None = None + """Parameters for the inverse-kinematics method. Defaults to None, in which case the default + parameters for the method are used. + + - Moore-Penrose pseudo-inverse ("pinv"): + - "k_val": Scaling of computed delta-joint positions (default: 1.0). + - Adaptive Singular Value Decomposition ("svd"): + - "k_val": Scaling of computed delta-joint positions (default: 1.0). + - "min_singular_value": Single values less than this are suppressed to zero (default: 1e-5). + - Jacobian transpose ("trans"): + - "k_val": Scaling of computed delta-joint positions (default: 1.0). + - Damped Moore-Penrose pseudo-inverse ("dls"): + - "lambda_val": Damping coefficient (default: 0.01). + """ + + def __post_init__(self): + # check valid input + if self.command_type not in ["position", "pose"]: + raise ValueError(f"Unsupported inverse-kinematics command: {self.command_type}.") + if self.ik_method not in ["pinv", "svd", "trans", "dls"]: + raise ValueError(f"Unsupported inverse-kinematics method: {self.ik_method}.") + # default parameters for different inverse kinematics approaches. + default_ik_params = { + "pinv": {"k_val": 1.0}, + "svd": {"k_val": 1.0, "min_singular_value": 1e-5}, + "trans": {"k_val": 1.0}, + "dls": {"lambda_val": 0.01}, + } + # update parameters for IK-method if not provided + ik_params = default_ik_params[self.ik_method].copy() + if self.ik_params is not None: + ik_params.update(self.ik_params) + self.ik_params = ik_params diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/joint_impedance.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/joint_impedance.py new file mode 100644 index 0000000000000000000000000000000000000000..0dee9da48988bd206cb4ccee2442790b00c52eed --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/joint_impedance.py @@ -0,0 +1,186 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +if TYPE_CHECKING: + from .joint_impedance_cfg import JointImpedanceControllerCfg + + +class JointImpedanceController: + """Joint impedance regulation control. + + Reference: + [1] https://ethz.ch/content/dam/ethz/special-interest/mavt/robotics-n-intelligent-systems/rsl-dam/documents/RobotDynamics2017/RD_HS2017script.pdf + """ + + def __init__(self, cfg: JointImpedanceControllerCfg, num_robots: int, dof_pos_limits: torch.Tensor, device: str): + """Initialize joint impedance controller. + + Args: + cfg: The configuration for the controller. + num_robots: The number of robots to control. + dof_pos_limits: The joint position limits for each robot. This is a tensor of shape + (num_robots, num_dof, 2) where the last dimension contains the lower and upper limits. + device: The device to use for computations. + + Raises: + ValueError: When the shape of :obj:`dof_pos_limits` is not (num_robots, num_dof, 2). + """ + # check valid inputs + if len(dof_pos_limits.shape) != 3: + raise ValueError(f"Joint position limits has shape '{dof_pos_limits.shape}'. Expected length of shape = 3.") + # store inputs + self.cfg = cfg + self.num_robots = num_robots + self.num_dof = dof_pos_limits.shape[1] # (num_robots, num_dof, 2) + self._device = device + + # create buffers + # -- commands + self._dof_pos_target = torch.zeros(self.num_robots, self.num_dof, device=self._device) + # -- offsets + self._dof_pos_offset = torch.zeros(self.num_robots, self.num_dof, device=self._device) + # -- limits + self._dof_pos_limits = dof_pos_limits + # -- positional gains + self._p_gains = torch.zeros(self.num_robots, self.num_dof, device=self._device) + self._p_gains[:] = torch.tensor(self.cfg.stiffness, device=self._device) + # -- velocity gains + self._d_gains = torch.zeros(self.num_robots, self.num_dof, device=self._device) + self._d_gains[:] = 2 * torch.sqrt(self._p_gains) * torch.tensor(self.cfg.damping_ratio, device=self._device) + # -- position offsets + if self.cfg.dof_pos_offset is not None: + self._dof_pos_offset[:] = torch.tensor(self.cfg.dof_pos_offset, device=self._device) + # -- position gain limits + self._p_gains_limits = torch.zeros_like(self._dof_pos_limits) + self._p_gains_limits[..., 0] = self.cfg.stiffness_limits[0] + self._p_gains_limits[..., 1] = self.cfg.stiffness_limits[1] + # -- damping ratio limits + self._damping_ratio_limits = torch.zeros_like(self._dof_pos_limits) + self._damping_ratio_limits[..., 0] = self.cfg.damping_ratio_limits[0] + self._damping_ratio_limits[..., 1] = self.cfg.damping_ratio_limits[1] + + """ + Properties. + """ + + @property + def num_actions(self) -> int: + """Dimension of the action space of controller.""" + # impedance mode + if self.cfg.impedance_mode == "fixed": + # joint positions + return self.num_dof + elif self.cfg.impedance_mode == "variable_kp": + # joint positions + stiffness + return self.num_dof * 2 + elif self.cfg.impedance_mode == "variable": + # joint positions + stiffness + damping + return self.num_dof * 3 + else: + raise ValueError(f"Invalid impedance mode: {self.cfg.impedance_mode}.") + + """ + Operations. + """ + + def initialize(self): + """Initialize the internals.""" + pass + + def reset_idx(self, robot_ids: torch.Tensor = None): + """Reset the internals.""" + pass + + def set_command(self, command: torch.Tensor): + """Set target end-effector pose command. + + Args: + command: The command to set. This is a tensor of shape (num_robots, num_actions) where + :obj:`num_actions` is the dimension of the action space of the controller. + """ + # check input size + if command.shape != (self.num_robots, self.num_actions): + raise ValueError( + f"Invalid command shape '{command.shape}'. Expected: '{(self.num_robots, self.num_actions)}'." + ) + # impedance mode + if self.cfg.impedance_mode == "fixed": + # joint positions + self._dof_pos_target[:] = command + elif self.cfg.impedance_mode == "variable_kp": + # split input command + dof_pos_command, stiffness = torch.tensor_split(command, 2, dim=-1) + # format command + stiffness = stiffness.clip_(min=self._p_gains_limits[0], max=self._p_gains_limits[1]) + # joint positions + stiffness + self._dof_pos_target[:] = dof_pos_command + self._p_gains[:] = stiffness + self._d_gains[:] = 2 * torch.sqrt(self._p_gains) # critically damped + elif self.cfg.impedance_mode == "variable": + # split input command + dof_pos_command, stiffness, damping_ratio = torch.tensor_split(command, 3, dim=-1) + # format command + stiffness = stiffness.clip_(min=self._p_gains_limits[0], max=self._p_gains_limits[1]) + damping_ratio = damping_ratio.clip_(min=self._damping_ratio_limits[0], max=self._damping_ratio_limits[1]) + # joint positions + stiffness + damping + self._dof_pos_target[:] = dof_pos_command + self._p_gains[:] = stiffness + self._d_gains[:] = 2 * torch.sqrt(self._p_gains) * damping_ratio + else: + raise ValueError(f"Invalid impedance mode: {self.cfg.impedance_mode}.") + + def compute( + self, + dof_pos: torch.Tensor, + dof_vel: torch.Tensor, + mass_matrix: torch.Tensor | None = None, + gravity: torch.Tensor | None = None, + ) -> torch.Tensor: + """Performs inference with the controller. + + Args: + dof_pos: The current joint positions. + dof_vel: The current joint velocities. + mass_matrix: The joint-space inertial matrix. Defaults to None. + gravity: The joint-space gravity vector. Defaults to None. + + Raises: + ValueError: When the command type is invalid. + + Returns: + The target joint torques commands. + """ + # resolve the command type + if self.cfg.command_type == "p_abs": + desired_dof_pos = self._dof_pos_target + self._dof_pos_offset + elif self.cfg.command_type == "p_rel": + desired_dof_pos = self._dof_pos_target + dof_pos + else: + raise ValueError(f"Invalid dof position command mode: {self.cfg.command_type}.") + # compute errors + desired_dof_pos = desired_dof_pos.clip_(min=self._dof_pos_limits[..., 0], max=self._dof_pos_limits[..., 1]) + dof_pos_error = desired_dof_pos - dof_pos + dof_vel_error = -dof_vel + # compute acceleration + des_dof_acc = self._p_gains * dof_pos_error + self._d_gains * dof_vel_error + # compute torques + # -- inertial compensation + if self.cfg.inertial_compensation: + # inverse dynamics control + desired_torques = mass_matrix @ des_dof_acc + else: + # decoupled spring-mass control + desired_torques = des_dof_acc + # -- gravity compensation (bias correction) + if self.cfg.gravity_compensation: + desired_torques += gravity + + return desired_torques diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/joint_impedance_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/joint_impedance_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..05a518043dd292caf143f24c77b7132112d2655c --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/joint_impedance_cfg.py @@ -0,0 +1,60 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import MISSING + +from isaaclab.utils.configclass import configclass + + +@configclass +class JointImpedanceControllerCfg: + """Configuration for joint impedance regulation controller.""" + + class_type: type | str = "isaaclab.controllers.joint_impedance:JointImpedanceController" + """The associated controller class.""" + + command_type: str = "p_abs" + """Type of command: p_abs (absolute) or p_rel (relative).""" + + dof_pos_offset: Sequence[float] | None = None + """Offset to DOF position command given to controller. (default: None). + + If None then position offsets are set to zero. + """ + + impedance_mode: str = MISSING + """Type of gains: "fixed", "variable", "variable_kp".""" + + inertial_compensation: bool = False + """Whether to perform inertial compensation (inverse dynamics).""" + + gravity_compensation: bool = False + """Whether to perform gravity compensation.""" + + stiffness: float | Sequence[float] = MISSING + """The positional gain for determining desired torques based on joint position error.""" + + damping_ratio: float | Sequence[float] | None = None + """The damping ratio is used in-conjunction with positional gain to compute desired torques + based on joint velocity error. + + The following math operation is performed for computing velocity gains: + :math:`d_gains = 2 * sqrt(p_gains) * damping_ratio`. + """ + + stiffness_limits: tuple[float, float] = (0, 300) + """Minimum and maximum values for positional gains. + + Note: Used only when :obj:`impedance_mode` is "variable" or "variable_kp". + """ + + damping_ratio_limits: tuple[float, float] = (0, 100) + """Minimum and maximum values for damping ratios used to compute velocity gains. + + Note: Used only when :obj:`impedance_mode` is "variable". + """ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/operational_space.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/operational_space.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ae5e942e7650e795ab59444f395393051601db --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/operational_space.py @@ -0,0 +1,549 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +from isaaclab.utils.math import ( + apply_delta_pose, + combine_frame_transforms, + compute_pose_error, + matrix_from_quat, + subtract_frame_transforms, +) + +if TYPE_CHECKING: + from .operational_space_cfg import OperationalSpaceControllerCfg + + +class OperationalSpaceController: + """Operational-space controller. + + Reference: + + 1. `A unified approach for motion and force control of robot manipulators: The operational space formulation `_ + by Oussama Khatib (Stanford University) + 2. `Robot Dynamics Lecture Notes `_ + by Marco Hutter (ETH Zurich) + """ + + def __init__(self, cfg: OperationalSpaceControllerCfg, num_envs: int, device: str): + """Initialize operational-space controller. + + Args: + cfg: The configuration for operational-space controller. + num_envs: The number of environments. + device: The device to use for computations. + + Raises: + ValueError: When invalid control command is provided. + """ + # store inputs + self.cfg = cfg + self.num_envs = num_envs + self._device = device + + # resolve tasks-pace target dimensions + self.target_list = list() + for command_type in self.cfg.target_types: + if command_type == "pose_rel": + self.target_list.append(6) + elif command_type == "pose_abs": + self.target_list.append(7) + elif command_type == "wrench_abs": + self.target_list.append(6) + else: + raise ValueError(f"Invalid control command: {command_type}.") + self.target_dim = sum(self.target_list) + + # create buffers + # -- selection matrices, which might be defined in the task reference frame different from the root frame + self._selection_matrix_motion_task = torch.diag_embed( + torch.tensor(self.cfg.motion_control_axes_task, dtype=torch.float, device=self._device) + .unsqueeze(0) + .repeat(self.num_envs, 1) + ) + self._selection_matrix_force_task = torch.diag_embed( + torch.tensor(self.cfg.contact_wrench_control_axes_task, dtype=torch.float, device=self._device) + .unsqueeze(0) + .repeat(self.num_envs, 1) + ) + # -- selection matrices in root frame + self._selection_matrix_motion_b = torch.zeros_like(self._selection_matrix_motion_task) + self._selection_matrix_force_b = torch.zeros_like(self._selection_matrix_force_task) + # -- commands + self._task_space_target_task = torch.zeros(self.num_envs, self.target_dim, device=self._device) + # -- Placeholders for motion/force control + self.desired_ee_pose_task = None + self.desired_ee_pose_b = None + self.desired_ee_wrench_task = None + self.desired_ee_wrench_b = None + # -- buffer for operational space mass matrix + self._os_mass_matrix_b = torch.zeros(self.num_envs, 6, 6, device=self._device) + # -- Placeholder for the inverse of joint space mass matrix + self._mass_matrix_inv = None + # -- motion control gains + self._motion_p_gains_task = torch.diag_embed( + torch.ones(self.num_envs, 6, device=self._device) + * torch.tensor(self.cfg.motion_stiffness_task, dtype=torch.float, device=self._device) + ) + # -- -- zero out the axes that are not motion controlled, as keeping them non-zero will cause other axes + # -- -- to act due to coupling + self._motion_p_gains_task[:] = self._selection_matrix_motion_task @ self._motion_p_gains_task[:] + self._motion_d_gains_task = torch.diag_embed( + 2 + * torch.diagonal(self._motion_p_gains_task, dim1=-2, dim2=-1).sqrt() + * torch.as_tensor(self.cfg.motion_damping_ratio_task, dtype=torch.float, device=self._device).reshape(1, -1) + ) + # -- -- motion control gains in root frame + self._motion_p_gains_b = torch.zeros_like(self._motion_p_gains_task) + self._motion_d_gains_b = torch.zeros_like(self._motion_d_gains_task) + # -- force control gains + if self.cfg.contact_wrench_stiffness_task is not None: + self._contact_wrench_p_gains_task = torch.diag_embed( + torch.ones(self.num_envs, 6, device=self._device) + * torch.tensor(self.cfg.contact_wrench_stiffness_task, dtype=torch.float, device=self._device) + ) + self._contact_wrench_p_gains_task[:] = ( + self._selection_matrix_force_task @ self._contact_wrench_p_gains_task[:] + ) + # -- -- force control gains in root frame + self._contact_wrench_p_gains_b = torch.zeros_like(self._contact_wrench_p_gains_task) + else: + self._contact_wrench_p_gains_task = None + self._contact_wrench_p_gains_b = None + # -- position gain limits + self._motion_p_gains_limits = torch.zeros(self.num_envs, 6, 2, device=self._device) + self._motion_p_gains_limits[..., 0], self._motion_p_gains_limits[..., 1] = ( + self.cfg.motion_stiffness_limits_task[0], + self.cfg.motion_stiffness_limits_task[1], + ) + # -- damping ratio limits + self._motion_damping_ratio_limits = torch.zeros_like(self._motion_p_gains_limits) + self._motion_damping_ratio_limits[..., 0], self._motion_damping_ratio_limits[..., 1] = ( + self.cfg.motion_damping_ratio_limits_task[0], + self.cfg.motion_damping_ratio_limits_task[1], + ) + # -- end-effector contact wrench + self._ee_contact_wrench_b = torch.zeros(self.num_envs, 6, device=self._device) + + # -- buffers for null-space control gains + self._nullspace_p_gain = torch.tensor(self.cfg.nullspace_stiffness, dtype=torch.float, device=self._device) + self._nullspace_d_gain = ( + 2 + * torch.sqrt(self._nullspace_p_gain) + * torch.tensor(self.cfg.nullspace_damping_ratio, dtype=torch.float, device=self._device) + ) + + """ + Properties. + """ + + @property + def action_dim(self) -> int: + """Dimension of the action space of controller.""" + # impedance mode + if self.cfg.impedance_mode == "fixed": + # task-space targets + return self.target_dim + elif self.cfg.impedance_mode == "variable_kp": + # task-space targets + stiffness + return self.target_dim + 6 + elif self.cfg.impedance_mode == "variable": + # task-space targets + stiffness + damping + return self.target_dim + 6 + 6 + else: + raise ValueError(f"Invalid impedance mode: {self.cfg.impedance_mode}.") + + """ + Operations. + """ + + def reset(self): + """Reset the internals.""" + self.desired_ee_pose_b = None + self.desired_ee_pose_task = None + self.desired_ee_wrench_b = None + self.desired_ee_wrench_task = None + + def set_command( + self, + command: torch.Tensor, + current_ee_pose_b: torch.Tensor | None = None, + current_task_frame_pose_b: torch.Tensor | None = None, + ): + """Set the task-space targets and impedance parameters. + + Args: + command (torch.Tensor): A concatenated tensor of shape (``num_envs``, ``action_dim``) containing task-space + targets (i.e., pose/wrench) and impedance parameters. + current_ee_pose_b (torch.Tensor, optional): Current end-effector pose, in root frame, of shape + (``num_envs``, 7), containing position and quaternion ``(x, y, z, w)``. Required for relative + commands. Defaults to None. + current_task_frame_pose_b: Current pose of the task frame, in root frame, in which the targets and the + (motion/wrench) control axes are defined. It is a tensor of shape (``num_envs``, 7), + containing position and the quaternion ``(x, y, z, w)``. Defaults to None. + + Format: + Task-space targets, ordered according to 'command_types': + + Absolute pose: shape (``num_envs``, 7), containing position and quaternion ``(x, y, z, w)``. + Relative pose: shape (``num_envs``, 6), containing delta position and rotation in axis-angle form. + Absolute wrench: shape (``num_envs``, 6), containing force and torque. + + Impedance parameters: stiffness for ``variable_kp``, or stiffness, followed by damping ratio for + ``variable``: + + Stiffness: shape (``num_envs``, 6) + Damping ratio: shape (``num_envs``, 6) + + Raises: + ValueError: When the command dimensions are invalid. + ValueError: When an invalid impedance mode is provided. + ValueError: When the current end-effector pose is not provided for the ``pose_rel`` command. + ValueError: When an invalid control command is provided. + """ + # Check the input dimensions + if command.shape != (self.num_envs, self.action_dim): + raise ValueError( + f"Invalid command shape '{command.shape}'. Expected: '{(self.num_envs, self.action_dim)}'." + ) + + # Resolve the impedance parameters + if self.cfg.impedance_mode == "fixed": + # task space targets (i.e., pose/wrench) + self._task_space_target_task[:] = command + elif self.cfg.impedance_mode == "variable_kp": + # split input command + task_space_command, stiffness = torch.split(command, [self.target_dim, 6], dim=-1) + # format command + stiffness = stiffness.clip_( + min=self._motion_p_gains_limits[..., 0], max=self._motion_p_gains_limits[..., 1] + ) + # task space targets + stiffness + self._task_space_target_task[:] = task_space_command.squeeze(dim=-1) + self._motion_p_gains_task[:] = torch.diag_embed(stiffness) + self._motion_p_gains_task[:] = self._selection_matrix_motion_task @ self._motion_p_gains_task[:] + self._motion_d_gains_task = torch.diag_embed( + 2 + * torch.diagonal(self._motion_p_gains_task, dim1=-2, dim2=-1).sqrt() + * torch.as_tensor(self.cfg.motion_damping_ratio_task, dtype=torch.float, device=self._device).reshape( + 1, -1 + ) + ) + elif self.cfg.impedance_mode == "variable": + # split input command + task_space_command, stiffness, damping_ratio = torch.split(command, [self.target_dim, 6, 6], dim=-1) + # format command + stiffness = stiffness.clip_( + min=self._motion_p_gains_limits[..., 0], max=self._motion_p_gains_limits[..., 1] + ) + damping_ratio = damping_ratio.clip_( + min=self._motion_damping_ratio_limits[..., 0], max=self._motion_damping_ratio_limits[..., 1] + ) + # task space targets + stiffness + damping + self._task_space_target_task[:] = task_space_command + self._motion_p_gains_task[:] = torch.diag_embed(stiffness) + self._motion_p_gains_task[:] = self._selection_matrix_motion_task @ self._motion_p_gains_task[:] + self._motion_d_gains_task[:] = torch.diag_embed( + 2 * torch.diagonal(self._motion_p_gains_task, dim1=-2, dim2=-1).sqrt() * damping_ratio + ) + else: + raise ValueError(f"Invalid impedance mode: {self.cfg.impedance_mode}.") + + if current_task_frame_pose_b is None: + # xyzw format: identity quat is [0, 0, 0, 1] + current_task_frame_pose_b = torch.tensor( + [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]] * self.num_envs, device=self._device + ) + + # Resolve the target commands + target_groups = torch.split(self._task_space_target_task, self.target_list, dim=1) + for command_type, target in zip(self.cfg.target_types, target_groups): + if command_type == "pose_rel": + # check input is provided + if current_ee_pose_b is None: + raise ValueError("Current pose is required for 'pose_rel' command.") + # Transform the current pose from base/root frame to task frame + current_ee_pos_task, current_ee_rot_task = subtract_frame_transforms( + current_task_frame_pose_b[:, :3], + current_task_frame_pose_b[:, 3:], + current_ee_pose_b[:, :3], + current_ee_pose_b[:, 3:], + ) + # compute targets in task frame + desired_ee_pos_task, desired_ee_rot_task = apply_delta_pose( + current_ee_pos_task, current_ee_rot_task, target + ) + self.desired_ee_pose_task = torch.cat([desired_ee_pos_task, desired_ee_rot_task], dim=-1) + elif command_type == "pose_abs": + # compute targets + self.desired_ee_pose_task = target.clone() + elif command_type == "wrench_abs": + # compute targets + self.desired_ee_wrench_task = target.clone() + else: + raise ValueError(f"Invalid control command: {command_type}.") + + # Rotation of task frame wrt root frame, converts a coordinate from task frame to root frame. + R_task_b = matrix_from_quat(current_task_frame_pose_b[:, 3:]) + # Rotation of root frame wrt task frame, converts a coordinate from root frame to task frame. + R_b_task = R_task_b.mT + + # Transform motion control stiffness gains from task frame to root frame + self._motion_p_gains_b[:, 0:3, 0:3] = R_task_b @ self._motion_p_gains_task[:, 0:3, 0:3] @ R_b_task + self._motion_p_gains_b[:, 3:6, 3:6] = R_task_b @ self._motion_p_gains_task[:, 3:6, 3:6] @ R_b_task + + # Transform motion control damping gains from task frame to root frame + self._motion_d_gains_b[:, 0:3, 0:3] = R_task_b @ self._motion_d_gains_task[:, 0:3, 0:3] @ R_b_task + self._motion_d_gains_b[:, 3:6, 3:6] = R_task_b @ self._motion_d_gains_task[:, 3:6, 3:6] @ R_b_task + + # Transform contact wrench gains from task frame to root frame (if applicable) + if self._contact_wrench_p_gains_task is not None and self._contact_wrench_p_gains_b is not None: + self._contact_wrench_p_gains_b[:, 0:3, 0:3] = ( + R_task_b @ self._contact_wrench_p_gains_task[:, 0:3, 0:3] @ R_b_task + ) + self._contact_wrench_p_gains_b[:, 3:6, 3:6] = ( + R_task_b @ self._contact_wrench_p_gains_task[:, 3:6, 3:6] @ R_b_task + ) + + # Transform selection matrices from target frame to base frame + self._selection_matrix_motion_b[:, 0:3, 0:3] = ( + R_task_b @ self._selection_matrix_motion_task[:, 0:3, 0:3] @ R_b_task + ) + self._selection_matrix_motion_b[:, 3:6, 3:6] = ( + R_task_b @ self._selection_matrix_motion_task[:, 3:6, 3:6] @ R_b_task + ) + self._selection_matrix_force_b[:, 0:3, 0:3] = ( + R_task_b @ self._selection_matrix_force_task[:, 0:3, 0:3] @ R_b_task + ) + self._selection_matrix_force_b[:, 3:6, 3:6] = ( + R_task_b @ self._selection_matrix_force_task[:, 3:6, 3:6] @ R_b_task + ) + + # Transform desired pose from task frame to root frame + if self.desired_ee_pose_task is not None: + self.desired_ee_pose_b = torch.zeros_like(self.desired_ee_pose_task) + self.desired_ee_pose_b[:, :3], self.desired_ee_pose_b[:, 3:] = combine_frame_transforms( + current_task_frame_pose_b[:, :3], + current_task_frame_pose_b[:, 3:], + self.desired_ee_pose_task[:, :3], + self.desired_ee_pose_task[:, 3:], + ) + + # Transform desired wrenches to root frame + if self.desired_ee_wrench_task is not None: + self.desired_ee_wrench_b = torch.zeros_like(self.desired_ee_wrench_task) + self.desired_ee_wrench_b[:, :3] = (R_task_b @ self.desired_ee_wrench_task[:, :3].unsqueeze(-1)).squeeze(-1) + self.desired_ee_wrench_b[:, 3:] = (R_task_b @ self.desired_ee_wrench_task[:, 3:].unsqueeze(-1)).squeeze( + -1 + ) + torch.cross(current_task_frame_pose_b[:, :3], self.desired_ee_wrench_b[:, :3], dim=-1) + + def compute( + self, + jacobian_b: torch.Tensor, + current_ee_pose_b: torch.Tensor | None = None, + current_ee_vel_b: torch.Tensor | None = None, + current_ee_force_b: torch.Tensor | None = None, + mass_matrix: torch.Tensor | None = None, + gravity: torch.Tensor | None = None, + current_joint_pos: torch.Tensor | None = None, + current_joint_vel: torch.Tensor | None = None, + nullspace_joint_pos_target: torch.Tensor | None = None, + ) -> torch.Tensor: + """Performs inference with the controller. + + Args: + jacobian_b: The Jacobian matrix of the end-effector in root frame. It is a tensor of shape + (``num_envs``, 6, ``num_DoF``). + current_ee_pose_b: The current end-effector pose in root frame. It is a tensor of shape + (``num_envs``, 7), which contains the position and quaternion ``(x, y, z, w)``. Defaults to ``None``. + current_ee_vel_b: The current end-effector velocity in root frame. It is a tensor of shape + (``num_envs``, 6), which contains the linear and angular velocities. Defaults to None. + current_ee_force_b: The current external force on the end-effector in root frame. It is a tensor of + shape (``num_envs``, 3), which contains the linear force. Defaults to ``None``. + mass_matrix: The joint-space mass/inertia matrix. It is a tensor of shape (``num_envs``, ``num_DoF``, + ``num_DoF``). Defaults to ``None``. + gravity: The joint-space gravity vector. It is a tensor of shape (``num_envs``, ``num_DoF``). Defaults + to ``None``. + current_joint_pos: The current joint positions. It is a tensor of shape (``num_envs``, ``num_DoF``). + Defaults to ``None``. + current_joint_vel: The current joint velocities. It is a tensor of shape (``num_envs``, ``num_DoF``). + Defaults to ``None``. + nullspace_joint_pos_target: The target joint positions the null space controller is trying to enforce, when + possible. It is a tensor of shape (``num_envs``, ``num_DoF``). + + Raises: + ValueError: When motion-control is enabled but the current end-effector pose or velocity is not provided. + ValueError: When inertial dynamics decoupling is enabled but the mass matrix is not provided. + ValueError: When the current end-effector pose is not provided for the ``pose_rel`` command. + ValueError: When closed-loop force control is enabled but the current end-effector force is not provided. + ValueError: When gravity compensation is enabled but the gravity vector is not provided. + ValueError: When null-space control is enabled but the system is not redundant. + ValueError: When dynamically consistent pseudo-inverse is enabled but the mass matrix inverse is not + provided. + ValueError: When null-space control is enabled but the current joint positions and velocities are not + provided. + ValueError: When target joint positions are provided for null-space control but their dimensions do not + match the current joint positions. + ValueError: When an invalid null-space control method is provided. + + Returns: + Tensor: The joint efforts computed by the controller. It is a tensor of shape (``num_envs``, ``num_DoF``). + """ + + # deduce number of DoF + num_DoF = jacobian_b.shape[2] + # create joint effort vector + joint_efforts = torch.zeros(self.num_envs, num_DoF, device=self._device) + + # compute joint efforts for motion-control + if self.desired_ee_pose_b is not None: + # check input is provided + if current_ee_pose_b is None or current_ee_vel_b is None: + raise ValueError("Current end-effector pose and velocity are required for motion control.") + # -- end-effector tracking error + pose_error_b = torch.cat( + compute_pose_error( + current_ee_pose_b[:, :3], + current_ee_pose_b[:, 3:], + self.desired_ee_pose_b[:, :3], + self.desired_ee_pose_b[:, 3:], + rot_error_type="axis_angle", + ), + dim=-1, + ) + velocity_error_b = -current_ee_vel_b # zero target velocity. The target is assumed to be stationary. + # -- desired end-effector acceleration (spring-damper system) + des_ee_acc_b = self._motion_p_gains_b @ pose_error_b.unsqueeze( + -1 + ) + self._motion_d_gains_b @ velocity_error_b.unsqueeze(-1) + # -- Inertial dynamics decoupling + if self.cfg.inertial_dynamics_decoupling: + # check input is provided + if mass_matrix is None: + raise ValueError("Mass matrix is required for inertial decoupling.") + # Compute operational space mass matrix + self._mass_matrix_inv = torch.inverse(mass_matrix) + if self.cfg.partial_inertial_dynamics_decoupling: + # Fill in the translational and rotational parts of the inertia separately, ignoring their coupling + self._os_mass_matrix_b[:, 0:3, 0:3] = torch.inverse( + jacobian_b[:, 0:3] @ self._mass_matrix_inv @ jacobian_b[:, 0:3].mT + ) + self._os_mass_matrix_b[:, 3:6, 3:6] = torch.inverse( + jacobian_b[:, 3:6] @ self._mass_matrix_inv @ jacobian_b[:, 3:6].mT + ) + else: + # Calculate the operational space mass matrix fully accounting for the couplings + self._os_mass_matrix_b[:] = torch.inverse(jacobian_b @ self._mass_matrix_inv @ jacobian_b.mT) + # (Generalized) operational space command forces + # F = (J M^(-1) J^T)^(-1) * \ddot(x_des) = M_task * \ddot(x_des) + os_command_forces_b = self._os_mass_matrix_b @ des_ee_acc_b + else: + # Task-space impedance control: command forces = \ddot(x_des). + # Please note that the definition of task-space impedance control varies in literature. + # This implementation ignores the inertial term. For inertial decoupling, + # use inertial_dynamics_decoupling=True. + os_command_forces_b = des_ee_acc_b + # -- joint-space commands + joint_efforts += (jacobian_b.mT @ self._selection_matrix_motion_b @ os_command_forces_b).squeeze(-1) + + # compute joint efforts for contact wrench/force control + if self.desired_ee_wrench_b is not None: + # -- task-space contact wrench + if self.cfg.contact_wrench_stiffness_task is not None: + # check input is provided + if current_ee_force_b is None: + raise ValueError("Current end-effector force is required for closed-loop force control.") + # We can only measure the force component at the contact, so only apply the feedback for only the force + # component, keep the control of moment components open loop + self._ee_contact_wrench_b[:, 0:3] = current_ee_force_b + self._ee_contact_wrench_b[:, 3:6] = self.desired_ee_wrench_b[:, 3:6] + # closed-loop control with feedforward term + os_contact_wrench_command_b = self.desired_ee_wrench_b.unsqueeze( + -1 + ) + self._contact_wrench_p_gains_b @ (self.desired_ee_wrench_b - self._ee_contact_wrench_b).unsqueeze( + -1 + ) + else: + # open-loop control + os_contact_wrench_command_b = self.desired_ee_wrench_b.unsqueeze(-1) + # -- joint-space commands + joint_efforts += (jacobian_b.mT @ self._selection_matrix_force_b @ os_contact_wrench_command_b).squeeze(-1) + + # add gravity compensation (bias correction) + if self.cfg.gravity_compensation: + # check input is provided + if gravity is None: + raise ValueError("Gravity vector is required for gravity compensation.") + # add gravity compensation + joint_efforts += gravity + + # Add null-space control + # -- Free null-space control + if self.cfg.nullspace_control == "none": + # No additional control is applied in the null space. + pass + else: + # Check if the system is redundant + if num_DoF <= 6: + raise ValueError("Null-space control is only applicable for redundant manipulators.") + + # Calculate the pseudo-inverse of the Jacobian + if self.cfg.inertial_dynamics_decoupling and not self.cfg.partial_inertial_dynamics_decoupling: + # Dynamically consistent pseudo-inverse allows decoupling of null space and task space + if self._mass_matrix_inv is None or mass_matrix is None: + raise ValueError("Mass matrix inverse is required for dynamically consistent pseudo-inverse") + jacobian_pinv_transpose = self._os_mass_matrix_b @ jacobian_b @ self._mass_matrix_inv + else: + # Moore-Penrose pseudo-inverse if full inertia matrix is not available (e.g., no/partial decoupling) + jacobian_pinv_transpose = torch.pinverse(jacobian_b).mT + + # Calculate the null-space projector + nullspace_jacobian_transpose = ( + torch.eye(n=num_DoF, device=self._device) - jacobian_b.mT @ jacobian_pinv_transpose + ) + + # Null space position control + if self.cfg.nullspace_control == "position": + # Check if the current joint positions and velocities are provided + if current_joint_pos is None or current_joint_vel is None: + raise ValueError("Current joint positions and velocities are required for null-space control.") + + # Calculate the joint errors for nullspace position control + if nullspace_joint_pos_target is None: + nullspace_joint_pos_target = torch.zeros_like(current_joint_pos) + # Check if the dimensions of the target nullspace joint positions match the current joint positions + elif nullspace_joint_pos_target.shape != current_joint_pos.shape: + raise ValueError( + f"The target nullspace joint positions shape '{nullspace_joint_pos_target.shape}' does not" + f"match the current joint positions shape '{current_joint_pos.shape}'." + ) + + joint_pos_error_nullspace = nullspace_joint_pos_target - current_joint_pos + joint_vel_error_nullspace = -current_joint_vel + + # Calculate the desired joint accelerations + joint_acc_nullspace = ( + self._nullspace_p_gain * joint_pos_error_nullspace + + self._nullspace_d_gain * joint_vel_error_nullspace + ).unsqueeze(-1) + + # Calculate the projected torques in null-space + if mass_matrix is not None: + tau_null = (nullspace_jacobian_transpose @ mass_matrix @ joint_acc_nullspace).squeeze(-1) + else: + tau_null = nullspace_jacobian_transpose @ joint_acc_nullspace + + # Add the null-space joint efforts to the total joint efforts + joint_efforts += tau_null + + else: + raise ValueError(f"Invalid null-space control method: {self.cfg.nullspace_control}.") + + return joint_efforts diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/operational_space_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/operational_space_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..22f9fa193781e65c3bbd6bfc42697a6e527e5e1f --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/operational_space_cfg.py @@ -0,0 +1,94 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import MISSING +from typing import TYPE_CHECKING + +from isaaclab.utils.configclass import configclass + +if TYPE_CHECKING: + from .operational_space import OperationalSpaceController + + +@configclass +class OperationalSpaceControllerCfg: + """Configuration for operational-space controller.""" + + class_type: type[OperationalSpaceController] | str = "{DIR}.operational_space:OperationalSpaceController" + """The associated controller class.""" + + target_types: Sequence[str] = MISSING + """Type of task-space targets. + + It has two sub-strings joined by underscore: + - type of task-space target: ``"pose"``, ``"wrench"`` + - reference for the task-space targets: ``"abs"`` (absolute), ``"rel"`` (relative, only for pose) + """ + + motion_control_axes_task: Sequence[int] = (1, 1, 1, 1, 1, 1) + """Motion direction to control in task reference frame. Mark as ``0/1`` for each axis.""" + + contact_wrench_control_axes_task: Sequence[int] = (0, 0, 0, 0, 0, 0) + """Contact wrench direction to control in task reference frame. Mark as 0/1 for each axis.""" + + inertial_dynamics_decoupling: bool = False + """Whether to perform inertial dynamics decoupling for motion control (inverse dynamics).""" + + partial_inertial_dynamics_decoupling: bool = False + """Whether to ignore the inertial coupling between the translational & rotational motions.""" + + gravity_compensation: bool = False + """Whether to perform gravity compensation.""" + + impedance_mode: str = "fixed" + """Type of gains for motion control: ``"fixed"``, ``"variable"``, ``"variable_kp"``.""" + + motion_stiffness_task: float | Sequence[float] = (100.0, 100.0, 100.0, 100.0, 100.0, 100.0) + """The positional gain for determining operational space command forces based on task-space pose error.""" + + motion_damping_ratio_task: float | Sequence[float] = (1.0, 1.0, 1.0, 1.0, 1.0, 1.0) + """The damping ratio is used in-conjunction with positional gain to compute operational space command forces + based on task-space velocity error. + + The following math operation is performed for computing velocity gains: + :math:`d_gains = 2 * sqrt(p_gains) * damping_ratio`. + """ + + motion_stiffness_limits_task: tuple[float, float] = (0, 1000) + """Minimum and maximum values for positional gains. + + Note: Used only when :obj:`impedance_mode` is ``"variable"`` or ``"variable_kp"``. + """ + + motion_damping_ratio_limits_task: tuple[float, float] = (0, 100) + """Minimum and maximum values for damping ratios used to compute velocity gains. + + Note: Used only when :obj:`impedance_mode` is ``"variable"``. + """ + + contact_wrench_stiffness_task: float | Sequence[float] | None = None + """The proportional gain for determining operational space command forces for closed-loop contact force control. + + If ``None``, then open-loop control of desired contact wrench is performed. + + Note: since only the linear forces could be measured at the moment, + only the first three elements are used for the feedback loop. + """ + + nullspace_control: str = "none" + """The null space control method for redundant manipulators: ``"none"``, ``"position"``. + + Note: ``"position"`` is used to drive the redundant manipulator to zero configuration by default. If + ``target_joint_pos`` is provided in the ``compute()`` method, it will be driven to this configuration. + """ + + nullspace_stiffness: float = 10.0 + """The stiffness for null space control.""" + + nullspace_damping_ratio: float = 1.0 + """The damping ratio for null space control.""" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e9c1756448a3bff18565385be14b13773fe75ddc --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Pink IK controller package for IsaacLab. + +This package provides integration between Pink inverse kinematics solver and IsaacLab. +""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9196dada08ffd264f50f84e7153a0dabea5f632e --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/__init__.pyi @@ -0,0 +1,32 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "NullSpacePostureTask", + "PinkIKController", + "PinkIKControllerCfg", + "DampingTaskCfg", + "FrameTaskCfg", + "LocalFrameTaskCfg", + "NullSpacePostureTaskCfg", + "PinkIKTaskCfg", + "DampingTask", + "FrameTask", + "LocalFrameTask", + "PinkKinematicsConfiguration", +] + +from .null_space_posture_task import NullSpacePostureTask +from .pink_ik import PinkIKController +from .pink_ik_cfg import PinkIKControllerCfg +from .pink_task_cfg import ( + DampingTaskCfg, + FrameTaskCfg, + LocalFrameTaskCfg, + NullSpacePostureTaskCfg, + PinkIKTaskCfg, +) +from .pink_tasks import DampingTask, FrameTask, LocalFrameTask +from .pink_kinematics_configuration import PinkKinematicsConfiguration diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/local_frame_task.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/local_frame_task.py new file mode 100644 index 0000000000000000000000000000000000000000..69413e5dbfdea29699889210d4a95c56050d4445 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/local_frame_task.py @@ -0,0 +1,20 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Deprecated compatibility shim for Pink task imports. + +Prefer importing from ``isaaclab.controllers.pink_ik.pink_tasks``. +""" + +from __future__ import annotations + +import warnings + +warnings.warn( + "`isaaclab.controllers.pink_ik.local_frame_task` is deprecated; " + "import from `isaaclab.controllers.pink_ik.pink_tasks` instead.", + DeprecationWarning, + stacklevel=2, +) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/null_space_posture_task.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/null_space_posture_task.py new file mode 100644 index 0000000000000000000000000000000000000000..86e2e1ea2e5a905a85b4a9c78be685293ff8cf8c --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/null_space_posture_task.py @@ -0,0 +1,271 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import numpy as np +import pinocchio as pin +import scipy.linalg.blas as blas +import scipy.linalg.lapack as lapack +from pink.configuration import Configuration +from pink.tasks import Task + + +class NullSpacePostureTask(Task): + r"""Pink-based task that adds a posture objective that is in the null space projection of other tasks. + + This task implements posture control in the null space of higher priority tasks + (typically end-effector pose tasks) within the Pink inverse kinematics framework. + + **Mathematical Formulation:** + + For details on Pink Inverse Kinematics optimization formulation visit: https://github.com/stephane-caron/pink + + **Null Space Posture Task Implementation:** + + This task consists of two components: + + 1. **Error Function**: The posture error is computed as: + + .. math:: + + \mathbf{e}(\mathbf{q}) = \mathbf{M} \cdot (\mathbf{q}^* - \mathbf{q}) + + where: + - :math:`\mathbf{q}^*` is the target joint configuration + - :math:`\mathbf{q}` is the current joint configuration + - :math:`\mathbf{M}` is a joint selection mask matrix + + 2. **Jacobian Matrix**: The task Jacobian is the null space projector: + + .. math:: + + \mathbf{J}_{\text{posture}}(\mathbf{q}) = \mathbf{N}(\mathbf{q}) = + \mathbf{I} -\mathbf{J}_{\text{primary}}^+ \mathbf{J}_{\text{primary}} + + where: + - :math:`\mathbf{J}_{\text{primary}}` is the combined Jacobian of all higher priority tasks + - :math:`\mathbf{J}_{\text{primary}}^+` is the pseudoinverse of the primary task Jacobian + - :math:`\mathbf{N}(\mathbf{q})` is the null space projector matrix + + For example, if there are two frame tasks (e.g., controlling the pose of two end-effectors), the combined Jacobian + :math:`\mathbf{J}_{\text{primary}}` is constructed by stacking the individual Jacobians for each frame vertically: + + .. math:: + + \mathbf{J}_{\text{primary}} = + \begin{bmatrix} + \mathbf{J}_1(\mathbf{q}) \\ + \mathbf{J}_2(\mathbf{q}) + \end{bmatrix} + + where :math:`\mathbf{J}_1(\mathbf{q})` and :math:`\mathbf{J}_2(\mathbf{q})` are the Jacobians for the + first and second frame tasks, respectively. + + The null space projector ensures that joint velocities in the null space produce zero velocity + for the primary tasks: :math:`\mathbf{J}_{\text{primary}} \cdot \dot{\mathbf{q}}_{\text{null}} = \mathbf{0}`. + + **Task Integration:** + + When integrated into the Pink framework, this task contributes to the optimization as: + + .. math:: + + \left\| + \mathbf{N}(\mathbf{q}) \mathbf{v} + \mathbf{M} \cdot (\mathbf{q}^* - \mathbf{q}) + \right\|_{W_{\text{posture}}}^2 + + This formulation allows the robot to maintain a desired posture while respecting the constraints + imposed by higher priority tasks (e.g., end-effector positioning). + + """ + + # Regularization factor for pseudoinverse computation to ensure numerical stability + PSEUDOINVERSE_DAMPING_FACTOR: float = 1e-9 + + def __init__(self, cfg) -> None: + r"""Initialize the null space posture task from a configuration object. + + This task maintains a desired joint posture in the null space of higher-priority + frame tasks. Joint selection allows excluding specific joints (e.g., wrist joints + in humanoid manipulation) to prevent large rotational ranges from overwhelming + errors in critical joints like shoulders and waist. + + Args: + cfg: A :class:`~isaaclab.controllers.pink_ik.pink_task_cfg.NullSpacePostureTaskCfg` + (or any object with the same attributes). + + - ``cost`` -- Task weighting factor (units: :math:`[\text{cost}] / [\text{rad}]`). + - ``lm_damping`` -- Levenberg-Marquardt regularization scale (unitless). + - ``gain`` -- Task gain :math:`\alpha \in [0, 1]` for low-pass filtering. + - ``controlled_frames`` -- Frame names whose Jacobians define the primary + tasks for null space projection. If empty, no projection is applied. + - ``controlled_joints`` -- Joint names to control. If empty, all actuated + joints are controlled. + """ + super().__init__(cost=float(cfg.cost), gain=float(cfg.gain), lm_damping=float(cfg.lm_damping)) + self.target_q: np.ndarray | None = None + self.controlled_frames: list[str] = list(getattr(cfg, "controlled_frames", None) or []) + self.controlled_joints: list[str] = list(getattr(cfg, "controlled_joints", None) or []) + self._joint_mask: np.ndarray | None = None + self._frame_names: list[str] | None = None + + def __repr__(self) -> str: + """Human-readable representation of the task.""" + return ( + f"NullSpacePostureTask(cost={self.cost}, gain={self.gain}, lm_damping={self.lm_damping}," + f" controlled_frames={self.controlled_frames}, controlled_joints={self.controlled_joints})" + ) + + def _build_joint_mapping(self, configuration: Configuration) -> None: + """Build joint mask and cache frequently used values. + + Creates a binary mask that selects which joints should be controlled + in the posture task. + + Args: + configuration: Robot configuration containing the model and joint information. + """ + # Create joint mask for full configuration size + self._joint_mask = np.zeros(configuration.model.nq) + + # Create dictionary for joint names to indices (exclude root joint) + joint_names = configuration.model.names.tolist()[1:] + + # Build joint mask efficiently + for i, joint_name in enumerate(joint_names): + if joint_name in self.controlled_joints: + self._joint_mask[i] = 1.0 + + # Cache frame names for performance + self._frame_names = list(self.controlled_frames) + + def set_target(self, target_q: np.ndarray) -> None: + """Set target posture configuration. + + Args: + target_q: Target vector in the configuration space. If the model + has a floating base, then this vector should include + floating-base coordinates (although they have no effect on the + posture task since only actuated joints are controlled). + """ + self.target_q = target_q.copy() + + def set_target_from_configuration(self, configuration: Configuration) -> None: + """Set target posture from a robot configuration. + + Args: + configuration: Robot configuration whose joint angles will be used + as the target posture. + """ + self.set_target(configuration.q) + + def compute_error(self, configuration: Configuration) -> np.ndarray: + r"""Compute posture task error. + + The error computation follows: + + .. math:: + + \mathbf{e}(\mathbf{q}) = \mathbf{M} \cdot (\mathbf{q}^* - \mathbf{q}) + + where :math:`\mathbf{M}` is the joint selection mask and :math:`\mathbf{q}^* - \mathbf{q}` + is computed using Pinocchio's difference function to handle joint angle wrapping. + + Args: + configuration: Robot configuration :math:`\mathbf{q}`. + + Returns: + Posture task error :math:`\mathbf{e}(\mathbf{q})` with the same dimension + as the configuration vector, but with zeros for non-controlled joints. + + Raises: + ValueError: If no posture target has been set. + """ + if self.target_q is None: + raise ValueError("No posture target has been set. Call set_target() first.") + + # Initialize joint mapping if needed + if self._joint_mask is None: + self._build_joint_mapping(configuration) + + # Compute configuration difference using Pinocchio's difference function + # This handles joint angle wrapping correctly + err = pin.difference( + configuration.model, + self.target_q, + configuration.q, + ) + + # Apply pre-computed joint mask to select only controlled joints + return self._joint_mask * err + + def compute_jacobian(self, configuration: Configuration) -> np.ndarray: + r"""Compute the null space projector Jacobian. + + The null space projector is defined as: + + .. math:: + + \mathbf{N}(\mathbf{q}) = \mathbf{I} - \mathbf{J}_{\text{primary}}^+ \mathbf{J}_{\text{primary}} + + where: + - :math:`\mathbf{J}_{\text{primary}}` is the combined Jacobian of all controlled frames + - :math:`\mathbf{J}_{\text{primary}}^+` is the pseudoinverse of the primary task Jacobian + - :math:`\mathbf{I}` is the identity matrix + + The null space projector ensures that joint velocities in the null space produce + zero velocity for the primary tasks: + :math:`\mathbf{J}_{\text{primary}} \cdot \dot{\mathbf{q}}_{\text{null}} = \mathbf{0}`. + + If no controlled frames are specified, returns the identity matrix. + + Args: + configuration: Robot configuration :math:`\mathbf{q}`. + + Returns: + Null space projector matrix :math:`\mathbf{N}(\mathbf{q})` with dimensions + :math:`n_q \times n_q` where :math:`n_q` is the number of configuration variables. + """ + # Initialize joint mapping if needed + if self._frame_names is None: + self._build_joint_mapping(configuration) + + # If no frame tasks are defined, return identity matrix (no null space projection) + if not self._frame_names: + return np.eye(configuration.model.nq) + + # Get Jacobians for all frame tasks and combine them + J_frame_tasks = [configuration.get_frame_jacobian(frame_name) for frame_name in self._frame_names] + J_combined = np.concatenate(J_frame_tasks, axis=0) + + # Compute null space projector: N = I - J^+ * J + # Use fast pseudoinverse computation with direct LAPACK/BLAS calls + m, n = J_combined.shape + + # Wide matrix (typical for robotics): use left pseudoinverse + # J^+ = J^T @ inv(J @ J^T + λ²I) + # This is faster because we invert an m×m matrix instead of n×n + + # Compute J @ J^T using BLAS (faster than numpy) + JJT = blas.dgemm(1.0, J_combined, J_combined.T) + np.fill_diagonal(JJT, JJT.diagonal() + self.PSEUDOINVERSE_DAMPING_FACTOR**2) + + # Use LAPACK's Cholesky factorization (dpotrf = Positive definite TRiangular Factorization) + L, info = lapack.dpotrf(JJT, lower=1, clean=False, overwrite_a=True) + + if info != 0: + # Fallback if not positive definite: use numpy's pseudoinverse + J_pinv = np.linalg.pinv(J_combined) + return np.eye(n) - J_pinv @ J_combined + + # Solve (J @ J^T + λ²I) @ X = J using LAPACK's triangular solver (dpotrs) + # This directly solves the system without computing the full inverse + X, _ = lapack.dpotrs(L, J_combined, lower=1) + + # Compute null space projector: N = I - J^T @ X + N_combined = np.eye(n) - J_combined.T @ X + + return N_combined diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_ik.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_ik.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc4958809cb49a9c570f24da1a9ec22c0552167 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_ik.py @@ -0,0 +1,299 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Pink IK controller implementation for IsaacLab. + +This module provides integration between Pink inverse kinematics solver and IsaacLab. +Pink is a differentiable inverse kinematics solver framework that provides task-space control capabilities. + +Reference: + Pink IK Solver: https://github.com/stephane-caron/pink +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, cast + +import numpy as np +import torch +from pink import solve_ik +from pink.tasks import Task +from qpsolvers.exceptions import SolverNotFound + +from isaaclab.assets import ArticulationCfg +from isaaclab.controllers import utils as controller_utils +from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.string import resolve_matching_names_values + +from .null_space_posture_task import NullSpacePostureTask +from .pink_kinematics_configuration import PinkKinematicsConfiguration +from .pink_task_cfg import PinkIKTaskCfg + +if TYPE_CHECKING: + from .pink_ik_cfg import PinkIKControllerCfg + + +_QP_SOLVER = "daqp" + + +class PinkIKController: + """Integration of Pink IK controller with Isaac Lab. + + The Pink IK controller solves differential inverse kinematics through weighted tasks. Each task is defined + by a residual function e(q) that is driven to zero (e.g., e(q) = p_target - p_ee(q) for end-effector positioning). + The controller computes joint velocities v satisfying J_e(q)v = -αe(q), where J_e(q) is the task Jacobian. + Multiple tasks are resolved through weighted optimization, formulating a quadratic program that minimizes + weighted task errors while respecting joint velocity limits. + + It supports user defined tasks, and we have provided a NullSpacePostureTask for maintaining desired + joint configurations. + + Reference: + Pink IK Solver: https://github.com/stephane-caron/pink + """ + + def __init__( + self, cfg: PinkIKControllerCfg, robot_cfg: ArticulationCfg, device: str, controlled_joint_indices: list[int] + ): + """Initialize the Pink IK Controller. + + Args: + cfg: The configuration for the Pink IK controller containing task definitions, solver parameters, + and joint configurations. + robot_cfg: The robot articulation configuration containing initial joint positions and robot + specifications. + device: The device to use for computations (e.g., 'cuda:0', 'cpu'). + controlled_joint_indices: A list of joint indices in the USD asset controlled by the Pink IK controller. + + Raises: + ValueError: When joint_names or all_joint_names are not provided in the configuration. + """ + if cfg.joint_names is None: + raise ValueError("joint_names must be provided in the configuration") + if cfg.all_joint_names is None: + raise ValueError("all_joint_names must be provided in the configuration") + + self.cfg = cfg + self.device = device + self.controlled_joint_indices = controlled_joint_indices + + # Validate consistency between controlled_joint_indices and configuration + self._validate_consistency(cfg, controlled_joint_indices) + + # Resolve URDF/mesh paths at runtime. If only usd_path is provided, convert USD→URDF first. + if cfg.urdf_path is None and cfg.usd_path is not None: + import tempfile + + urdf_output_dir = cfg.urdf_output_dir or tempfile.gettempdir() + urdf_path, mesh_path = controller_utils.convert_usd_to_urdf( + cfg.usd_path, urdf_output_dir, force_conversion=True + ) + else: + urdf_path = retrieve_file_path(cfg.urdf_path) if cfg.urdf_path else cfg.urdf_path + mesh_path = retrieve_file_path(cfg.mesh_path) if cfg.mesh_path else cfg.mesh_path + + if urdf_path is None: + raise ValueError("Either urdf_path or usd_path must be provided in the controller configuration") + + # Initialize the Kinematics model used by pink IK to control robot + self.pink_configuration = PinkKinematicsConfiguration( + urdf_path=urdf_path, + mesh_path=mesh_path, + controlled_joint_names=cfg.joint_names, + ) + + # Find the initial joint positions by matching Pink's joint names to robot_cfg.init_state.joint_pos, + # where the joint_pos keys may be regex patterns and the values are the initial positions. + # We want to assign to each Pink joint name the value from the first matching regex key in joint_pos. + pink_joint_names = self.pink_configuration.model.names.tolist()[1:] + joint_pos_dict = robot_cfg.init_state.joint_pos + + # Use resolve_matching_names_values to match Pink joint names to joint_pos values + indices, _, values = resolve_matching_names_values( + joint_pos_dict, pink_joint_names, preserve_order=False, strict=False + ) + self.init_joint_positions = np.zeros(len(pink_joint_names)) + self.init_joint_positions[indices] = np.array(values) + self._variable_input_tasks = [task_cfg.class_type(task_cfg) for task_cfg in cfg.variable_input_tasks] + self._fixed_input_tasks = [task_cfg.class_type(task_cfg) for task_cfg in cfg.fixed_input_tasks] + self.cfg.variable_input_tasks = cast(list[Task | PinkIKTaskCfg], self._variable_input_tasks) + self.cfg.fixed_input_tasks = cast(list[Task | PinkIKTaskCfg], self._fixed_input_tasks) + + for task in self._variable_input_tasks: + # If task is a NullSpacePostureTask, set the target to the initial joint positions + if isinstance(task, NullSpacePostureTask): + task.set_target(self.init_joint_positions) + continue + getattr(task, "set_target_from_configuration")(self.pink_configuration) + for task in self._fixed_input_tasks: + getattr(task, "set_target_from_configuration")(self.pink_configuration) + + # Create joint ordering mappings + self._setup_joint_ordering_mappings() + + def _validate_consistency(self, cfg: PinkIKControllerCfg, controlled_joint_indices: list[int]) -> None: + """Validate consistency between controlled_joint_indices and controller configuration. + + Args: + cfg: The Pink IK controller configuration. + controlled_joint_indices: List of joint indices in Isaac Lab joint space. + + Raises: + ValueError: If any consistency checks fail. + """ + # Check: Length consistency + if cfg.joint_names is None: + raise ValueError("cfg.joint_names cannot be None") + if len(controlled_joint_indices) != len(cfg.joint_names): + raise ValueError( + f"Length mismatch: controlled_joint_indices has {len(controlled_joint_indices)} elements " + f"but cfg.joint_names has {len(cfg.joint_names)} elements" + ) + + # Check: Joint name consistency - verify that the indices point to the expected joint names + if cfg.all_joint_names is None: + raise ValueError("cfg.all_joint_names cannot be None") + actual_joint_names = [cfg.all_joint_names[idx] for idx in controlled_joint_indices] + if actual_joint_names != cfg.joint_names: + mismatches = [] + for i, (actual, expected) in enumerate(zip(actual_joint_names, cfg.joint_names)): + if actual != expected: + mismatches.append( + f"Index {i}: index {controlled_joint_indices[i]} points to '{actual}' but expected '{expected}'" + ) + if mismatches: + raise ValueError( + "Joint name mismatch between controlled_joint_indices and cfg.joint_names:\n" + + "\n".join(mismatches) + ) + + def _setup_joint_ordering_mappings(self): + """Setup joint ordering mappings between Isaac Lab and Pink conventions.""" + pink_joint_names = self.pink_configuration.all_joint_names_pinocchio_order + isaac_lab_joint_names = self.cfg.all_joint_names + + if pink_joint_names is None: + raise ValueError("pink_joint_names should not be None") + if isaac_lab_joint_names is None: + raise ValueError("isaac_lab_joint_names should not be None") + + # Create reordering arrays for all joints + self.isaac_lab_to_pink_ordering = np.array( + [isaac_lab_joint_names.index(pink_joint) for pink_joint in pink_joint_names] + ) + self.pink_to_isaac_lab_ordering = np.array( + [pink_joint_names.index(isaac_lab_joint) for isaac_lab_joint in isaac_lab_joint_names] + ) + # Create reordering arrays for controlled joints only + pink_controlled_joint_names = self.pink_configuration.controlled_joint_names_pinocchio_order + isaac_lab_controlled_joint_names = self.cfg.joint_names + + if pink_controlled_joint_names is None: + raise ValueError("pink_controlled_joint_names should not be None") + if isaac_lab_controlled_joint_names is None: + raise ValueError("isaac_lab_controlled_joint_names should not be None") + + self.isaac_lab_to_pink_controlled_ordering = np.array( + [isaac_lab_controlled_joint_names.index(pink_joint) for pink_joint in pink_controlled_joint_names] + ) + self.pink_to_isaac_lab_controlled_ordering = np.array( + [pink_controlled_joint_names.index(isaac_lab_joint) for isaac_lab_joint in isaac_lab_controlled_joint_names] + ) + + def update_null_space_joint_targets(self, curr_joint_pos: np.ndarray): + """Update the null space joint targets. + + This method updates the target joint positions for null space posture tasks based on the current + joint configuration. This is useful for maintaining desired joint configurations when the primary + task allows redundancy. + + Args: + curr_joint_pos: The current joint positions of shape (num_joints,). + """ + for task in self._variable_input_tasks: + if isinstance(task, NullSpacePostureTask): + task.set_target(curr_joint_pos) + + def compute( + self, + curr_joint_pos: np.ndarray, + dt: float, + ) -> torch.Tensor: + """Compute the target joint positions based on current state and tasks. + + Performs inverse kinematics using the Pink solver to compute target joint positions that satisfy + the defined tasks. The solver uses quadratic programming to find optimal joint velocities that + minimize task errors while respecting constraints. + + Args: + curr_joint_pos: The current joint positions of shape (num_joints,). + dt: The time step for computing joint position changes in seconds. + + Returns: + The target joint positions as a tensor of shape (num_joints,) on the specified device. + If the IK solver fails, returns the current joint positions unchanged to maintain stability. + """ + # Get the current controlled joint positions + curr_controlled_joint_pos = [curr_joint_pos[i] for i in self.controlled_joint_indices] + + # Initialize joint positions for Pink, change from isaac_lab to pink/pinocchio joint ordering. + joint_positions_pink = curr_joint_pos[self.isaac_lab_to_pink_ordering] + + # Update Pink's robot configuration with the current joint positions + self.pink_configuration.update(joint_positions_pink) + + def _return_current_joint_positions(error: Exception) -> torch.Tensor: + if self.cfg.show_ik_warnings: + print( + "Warning: IK quadratic solver could not find a solution! Did not update the target joint" + f" positions.\nError: {error}" + ) + + if self.cfg.xr_enabled: + from isaaclab.ui.xr_widgets import XRVisualization + + XRVisualization.push_event("ik_error", {"error": error}) + return torch.tensor(curr_controlled_joint_pos, device=self.device, dtype=torch.float32) + + # Solve IK using Pink's solver + try: + velocity = solve_ik( + self.pink_configuration, + self._variable_input_tasks + self._fixed_input_tasks, + dt, + solver=_QP_SOLVER, + safety_break=self.cfg.fail_on_joint_limit_violation, + ) + assert not np.isnan(velocity).any(), "Solution to IK contains NaN." + joint_angle_changes = velocity * dt + except SolverNotFound as e: + raise RuntimeError( + f"Pink IK requires the '{_QP_SOLVER}' QP solver. Install the Pink IK stack with " + "``./isaaclab.sh -i`` or manually install ``pin pin-pink==3.3.0 daqp==0.8.5``." + ) from e + except TypeError as e: + if "primal_start" in str(e): + raise RuntimeError( + "Pink IK requires a DAQP version compatible with qpsolvers warm-start arguments. " + "Install the Pink IK stack with ``./isaaclab.sh -i`` or manually install " + "``pin pin-pink==3.3.0 daqp==0.8.5``." + ) from e + return _return_current_joint_positions(e) + except (AssertionError, Exception) as e: + return _return_current_joint_positions(e) + + # Reorder the joint angle changes back to Isaac Lab conventions + joint_vel_isaac_lab = torch.tensor( + joint_angle_changes[self.pink_to_isaac_lab_controlled_ordering], + device=self.device, + dtype=torch.float32, + ) + + # Add the velocity changes to the current joint positions to get the target joint positions + target_joint_pos = torch.add( + joint_vel_isaac_lab, torch.tensor(curr_controlled_joint_pos, device=self.device, dtype=torch.float32) + ) + + return target_joint_pos diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_ik_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_ik_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..d62c45ee30e281fb304ecd0d7bedbc8c1ea17aac --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_ik_cfg.py @@ -0,0 +1,105 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for Pink IK controller.""" + +from __future__ import annotations + +from dataclasses import field +from typing import TYPE_CHECKING + +from isaaclab.utils.configclass import configclass + +from .pink_task_cfg import PinkIKTaskCfg + +if TYPE_CHECKING: + from pink.tasks import Task + + +@configclass +class PinkIKControllerCfg: + """Configuration settings for the Pink IK Controller. + + The Pink IK controller can be found at: https://github.com/stephane-caron/pink + """ + + usd_path: str | None = None + """Path to the robot's USD file. When set and ``urdf_path`` is None, the controller will automatically + convert the USD to URDF at runtime using ``convert_usd_to_urdf``. Requires Isaac Sim at runtime. + """ + + urdf_output_dir: str | None = None + """Output directory for the USD-to-URDF conversion. Only used when ``usd_path`` is set and + ``urdf_path`` is None. Defaults to ``tempfile.gettempdir()`` if not provided. + """ + + urdf_path: str | None = None + """Path to the robot's URDF file. This file is used by Pinocchio's ``robot_wrapper.BuildFromURDF`` + to load the robot model. If not provided, the URDF is generated from ``usd_path`` at runtime. + """ + + mesh_path: str | None = None + """Path to the mesh files associated with the robot. These files are also loaded by Pinocchio's + ``robot_wrapper.BuildFromURDF``. + """ + + num_hand_joints: int = 0 + """The number of hand joints in the robot. + + The action space for the controller contains the ``pose_dim(7) * num_controlled_frames + num_hand_joints``. + The last ``num_hand_joints`` values of the action are the hand joint angles. + """ + + variable_input_tasks: list[Task | PinkIKTaskCfg] = field(default_factory=list) + """A list of tasks for the Pink IK controller. + + These tasks are controllable by the environment action. + + These tasks can be used to control the pose of a frame or the angles of joints. + For more details, visit: https://github.com/stephane-caron/pink + """ + + fixed_input_tasks: list[Task | PinkIKTaskCfg] = field(default_factory=list) + """ + A list of tasks for the Pink IK controller. These tasks are fixed and not controllable by the env action. + + These tasks can be used to fix the pose of a frame or the angles of joints to a desired configuration. + For more details, visit: https://github.com/stephane-caron/pink + """ + + joint_names: list[str] | None = None + """A list of joint names in the USD asset controlled by the Pink IK controller. + + This is required because the joint naming conventions differ between USD and URDF files. This value is + currently designed to be automatically populated by the action term in a manager based environment. + """ + + all_joint_names: list[str] | None = None + """A list of joint names in the USD asset. + + This is required because the joint naming conventions differ between USD and URDF files. This value is + currently designed to be automatically populated by the action term in a manager based environment. + """ + + articulation_name: str = "robot" + """The name of the articulation USD asset in the scene.""" + + base_link_name: str = "base_link" + """The name of the base link in the USD asset.""" + + show_ik_warnings: bool = True + """Show warning if IK solver fails to find a solution.""" + + fail_on_joint_limit_violation: bool = True + """Whether to fail on joint limit violation. + + If True, the Pink IK solver will fail and raise an error if any joint limit is violated during optimization. + The PinkIKController will handle the error by setting the last joint positions. + + If False, the solver will ignore joint limit violations and return the closest solution found. + """ + + xr_enabled: bool = False + """If True, the Pink IK controller will send information to the XRVisualization.""" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_kinematics_configuration.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_kinematics_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..b688172060523685d84fe4ee333c95b94f5eedaa --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_kinematics_configuration.py @@ -0,0 +1,187 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import numpy as np +import pinocchio as pin +from pink.configuration import Configuration +from pink.exceptions import FrameNotFound +from pinocchio.robot_wrapper import RobotWrapper + + +class PinkKinematicsConfiguration(Configuration): + """ + A configuration class that maintains both a "controlled" (reduced) model and a "full" model. + + This class extends the standard Pink Configuration to allow for selective joint control: + + - The "controlled" model/data/q represent the subset of joints being actively controlled + (e.g., a kinematic chain or arm). + - The "full" model/data/q represent the complete robot, including all joints. + + This is useful for scenarios where only a subset of joints are being optimized or controlled, but + full-model kinematics (e.g., for collision checking, full-body Jacobians, or visualization) are still required. + + The class ensures that both models are kept up to date, and provides methods to update both the controlled and full + configurations as needed. + """ + + def __init__( + self, + controlled_joint_names: list[str], + urdf_path: str, + mesh_path: str | None = None, + copy_data: bool = True, + forward_kinematics: bool = True, + ): + """ + Initialize PinkKinematicsConfiguration. + + + This constructor initializes the PinkKinematicsConfiguration, which maintains both a "controlled" + (reduced) model and a "full" model. The controlled model/data/q represent the subset of joints + being actively controlled, while the full model/data/q represent the complete robot. This is useful + for scenarios where only a subset of joints are being optimized or controlled, but full-model + kinematics are still required. + + Args: + urdf_path: Path to the robot URDF file. + mesh_path: Path to the mesh files for the robot. + controlled_joint_names: List of joint names to be actively controlled. + copy_data: If True, work on an internal copy of the input data. Defaults to True. + forward_kinematics: If True, compute forward kinematics from the configuration vector. Defaults to True. + """ + self._controlled_joint_names = controlled_joint_names + + # Build robot model with all joints + if mesh_path: + self.robot_wrapper = RobotWrapper.BuildFromURDF(urdf_path, mesh_path) + else: + self.robot_wrapper = RobotWrapper.BuildFromURDF(urdf_path) + self.full_model = self.robot_wrapper.model + self.full_data = self.robot_wrapper.data + self.full_q = self.robot_wrapper.q0 + + self._all_joint_names = self.full_model.names.tolist()[1:] + # controlled_joint_indices: indices in all_joint_names for joints that are in controlled_joint_names, + # preserving all_joint_names order + self._controlled_joint_indices = [ + idx for idx, joint_name in enumerate(self._all_joint_names) if joint_name in self._controlled_joint_names + ] + + # Build the reduced model with only the controlled joints + joints_to_lock = [] + for joint_name in self._all_joint_names: + if joint_name not in self._controlled_joint_names: + joints_to_lock.append(self.full_model.getJointId(joint_name)) + + if len(joints_to_lock) == 0: + # No joints to lock, controlled model is the same as full model + self.controlled_model = self.full_model + self.controlled_data = self.full_data + self.controlled_q = self.full_q + else: + self.controlled_model = pin.buildReducedModel(self.full_model, joints_to_lock, self.full_q) + self.controlled_data = self.controlled_model.createData() + self.controlled_q = self.full_q[self._controlled_joint_indices] + + # Pink will should only have the controlled model + super().__init__(self.controlled_model, self.controlled_data, self.controlled_q, copy_data, forward_kinematics) + + def update(self, q: np.ndarray | None = None) -> None: + """Update configuration to a new vector. + + Calling this function runs forward kinematics and computes + collision-pair distances, if applicable. + + Args: + q: New configuration vector. + """ + if q is not None and len(q) != len(self._all_joint_names): + raise ValueError("q must have the same length as the number of joints in the model") + if q is not None: + super().update(q[self._controlled_joint_indices]) + + q_readonly = q.copy() + q_readonly.setflags(write=False) + self.full_q = q_readonly + pin.computeJointJacobians(self.full_model, self.full_data, q) + pin.updateFramePlacements(self.full_model, self.full_data) + else: + super().update() + pin.computeJointJacobians(self.full_model, self.full_data, self.full_q) + pin.updateFramePlacements(self.full_model, self.full_data) + + def get_frame_jacobian(self, frame: str) -> np.ndarray: + r"""Compute the Jacobian matrix of a frame velocity. + + Denoting our frame by :math:`B` and the world frame by :math:`W`, the + Jacobian matrix :math:`{}_B J_{WB}` is related to the body velocity + :math:`{}_B v_{WB}` by: + + .. math:: + + {}_B v_{WB} = {}_B J_{WB} \dot{q} + + Args: + frame: Name of the frame, typically a link name from the URDF. + + Returns: + Jacobian :math:`{}_B J_{WB}` of the frame. + + When the robot model includes a floating base + (pin.JointModelFreeFlyer), the configuration vector :math:`q` consists + of: + + - ``q[0:3]``: position in [m] of the floating base in the inertial + frame, formatted as :math:`[p_x, p_y, p_z]`. + - ``q[3:7]``: unit quaternion for the orientation of the floating base + in the inertial frame, formatted as :math:`[q_x, q_y, q_z, q_w]`. + - ``q[7:]``: joint angles in [rad]. + """ + if not self.full_model.existFrame(frame): + raise FrameNotFound(frame, self.full_model.frames) + frame_id = self.full_model.getFrameId(frame) + J: np.ndarray = pin.getFrameJacobian(self.full_model, self.full_data, frame_id, pin.ReferenceFrame.LOCAL) + return J[:, self._controlled_joint_indices] + + def get_transform_frame_to_world(self, frame: str) -> pin.SE3: + """Get the pose of a frame in the current configuration. + + We override this method from the super class to solve the issue that in the default + Pink implementation, the frame placements do not take into account the non-controlled joints + being not at initial pose (which is a bad assumption when they are controlled by other + controllers like a lower body controller). + + Args: + frame: Name of a frame, typically a link name from the URDF. + + Returns: + Current transform from the given frame to the world frame. + + Raises: + FrameNotFound: if the frame name is not found in the robot model. + """ + frame_id = self.full_model.getFrameId(frame) + try: + return self.full_data.oMf[frame_id].copy() + except IndexError as index_error: + raise FrameNotFound(frame, self.full_model.frames) from index_error + + def check_limits(self, tol: float = 1e-6, safety_break: bool = True) -> None: + """Check if limits are violated only if safety_break is enabled""" + if safety_break: + super().check_limits(tol, safety_break) + + @property + def controlled_joint_names_pinocchio_order(self) -> list[str]: + """Get the names of the controlled joints in the order of the pinocchio model.""" + return [self._all_joint_names[i] for i in self._controlled_joint_indices] + + @property + def all_joint_names_pinocchio_order(self) -> list[str]: + """Get the names of all joints in the order of the pinocchio model.""" + return self._all_joint_names diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_task_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_task_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..bdab08b68862ffb061124dfd6c1acfed20ef1a05 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_task_cfg.py @@ -0,0 +1,122 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Task configuration objects for Pink IK.""" + +from __future__ import annotations + +from dataclasses import MISSING, field +from typing import Any + +from isaaclab.utils.configclass import configclass + + +@configclass +class PinkIKTaskCfg: + """Base task specification for deferred runtime construction. + + All Pink IK task configs inherit from this class. The :attr:`class_type` + attribute is resolved at runtime to instantiate the concrete task object. + """ + + class_type: str | type | None = None + """Task builder as ``"module.path:callable"`` or callable object.""" + + +@configclass +class FrameTaskCfg(PinkIKTaskCfg): + """Configuration for a :class:`~isaaclab.controllers.pink_ik.pink_tasks.FrameTask`. + + Tracks a desired end-effector pose expressed in the world frame. + """ + + frame: Any = MISSING + """Name of the robot frame to control (e.g. end-effector link).""" + + position_cost: Any = MISSING + """Cost weight(s) for position error — scalar or 3-element sequence.""" + + orientation_cost: Any = MISSING + """Cost weight(s) for orientation error — scalar or 3-element sequence.""" + + lm_damping: float = 0.0 + """Levenberg-Marquardt damping for numerical stability.""" + + gain: float = 1.0 + """Task gain that scales the overall task contribution.""" + + class_type: str | type | None = "{DIR}.pink_tasks:FrameTask" + """Default builder pointing to :class:`FrameTask`.""" + + +@configclass +class DampingTaskCfg(PinkIKTaskCfg): + """Configuration for a :class:`~isaaclab.controllers.pink_ik.pink_tasks.DampingTask`. + + Adds joint-velocity damping to the IK problem for numerical stability. + """ + + cost: Any = MISSING + """Scalar cost weight penalising joint velocities.""" + + class_type: str | type | None = "{DIR}.pink_tasks:DampingTask" + """Default builder pointing to :class:`DampingTask`.""" + + +@configclass +class LocalFrameTaskCfg(PinkIKTaskCfg): + """Configuration for a :class:`~isaaclab.controllers.pink_ik.pink_tasks.LocalFrameTask`. + + Tracks a desired pose expressed relative to a specified base-link frame + rather than the world frame. + """ + + frame: Any = MISSING + """Name of the robot frame to control (e.g. end-effector link).""" + + base_link_frame_name: Any = MISSING + """Reference frame for computing transforms and errors.""" + + position_cost: Any = MISSING + """Cost weight(s) for position error — scalar or 3-element sequence.""" + + orientation_cost: Any = MISSING + """Cost weight(s) for orientation error — scalar or 3-element sequence.""" + + lm_damping: float = 0.0 + """Levenberg-Marquardt damping for numerical stability.""" + + gain: float = 1.0 + """Task gain that scales the overall task contribution.""" + + class_type: str | type | None = "{DIR}.pink_tasks:LocalFrameTask" + """Default builder pointing to :class:`LocalFrameTask`.""" + + +@configclass +class NullSpacePostureTaskCfg(PinkIKTaskCfg): + """Configuration for a :class:`~isaaclab.controllers.pink_ik.null_space_posture_task.NullSpacePostureTask`. + + Regularises the IK solution toward a preferred joint posture in the + null-space of the primary tasks. + """ + + cost: Any = MISSING + """Scalar cost weight for the posture regularisation term.""" + + lm_damping: float = 0.0 + """Levenberg-Marquardt damping for numerical stability.""" + + gain: float = 1.0 + """Task gain that scales the overall task contribution.""" + + controlled_frames: list[str] = field(default_factory=list) + """Robot frames whose joints are included in the posture task.""" + + controlled_joints: list[str] = field(default_factory=list) + """Explicit list of joint names to include (overrides frame-based selection when non-empty).""" + + class_type: str | type | None = "{DIR}.null_space_posture_task:NullSpacePostureTask" + """Default builder pointing to :class:`NullSpacePostureTask`.""" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_tasks.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..1a81fbe3b53739bac0a37fbf03cef5b671f26626 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/pink_ik/pink_tasks.py @@ -0,0 +1,226 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from collections.abc import Sequence + +import numpy as np +import pinocchio as pin +from pink.tasks import DampingTask as PinkDampingTask +from pink.tasks.frame_task import FrameTask as PinkFrameTask + +from .pink_kinematics_configuration import PinkKinematicsConfiguration + + +class FrameTask(PinkFrameTask): + """Thin wrapper around Pink's :class:`~pink.tasks.frame_task.FrameTask`. + + Adds support for the ``class_type(cfg)`` construction pattern used by + Isaac Lab task configuration dataclasses, while remaining fully compatible + with the original string-based constructor. + """ + + def __init__( + self, + cfg_or_frame, + position_cost: float | Sequence[float] | None = None, + orientation_cost: float | Sequence[float] | None = None, + lm_damping: float = 0.0, + gain: float = 1.0, + ): + """Initialize the FrameTask. + + Args: + cfg_or_frame: Either a *string* naming the controlled frame, or a + configuration dataclass whose attributes (``frame``, + ``position_cost``, ``orientation_cost``, ``lm_damping``, + ``gain``) supply all parameters. + position_cost: Cost weight(s) for position error. A single float + applies uniform weighting; a sequence of 3 floats gives per-axis + weights. Required when *cfg_or_frame* is a string. + orientation_cost: Cost weight(s) for orientation error (same + convention as *position_cost*). Required when *cfg_or_frame* is + a string. + lm_damping: Levenberg-Marquardt damping factor for numerical + stability. Defaults to 0.0 (no damping). + gain: Task gain that scales the overall task contribution. + Defaults to 1.0. + """ + if isinstance(cfg_or_frame, str): + frame = cfg_or_frame + else: + cfg = cfg_or_frame + frame = cfg.frame + position_cost = cfg.position_cost + orientation_cost = cfg.orientation_cost + lm_damping = cfg.lm_damping + gain = cfg.gain + + if position_cost is None or orientation_cost is None: + raise ValueError("position_cost and orientation_cost must be provided") + + super().__init__( + frame, + position_cost=position_cost, + orientation_cost=orientation_cost, + lm_damping=lm_damping, + gain=gain, + ) + + +class DampingTask(PinkDampingTask): + """Thin wrapper around Pink's :class:`~pink.tasks.DampingTask`. + + Adds joint-velocity damping to the IK problem for numerical stability. + Accepts either a configuration dataclass (``class_type(cfg)`` pattern) or a + direct scalar cost value. + """ + + def __init__(self, cfg_or_cost, cost: float | None = None): + """Initialize the DampingTask. + + Args: + cfg_or_cost: Either a numeric cost value, or a configuration + dataclass with a ``cost`` attribute. + cost: Explicit cost override. When *cfg_or_cost* is numeric and + *cost* is also provided, *cost* takes precedence. + """ + if isinstance(cfg_or_cost, (int, float)): + _cost = float(cfg_or_cost if cost is None else cost) + else: + _cost = cfg_or_cost.cost + super().__init__(cost=_cost) + + +class LocalFrameTask(FrameTask): + """A task that computes pose error in a local (custom) frame. + + Inherits from :class:`FrameTask` but overrides error and Jacobian computation + to express them relative to a specified base-link frame rather than the world + frame. This allows control strategies where the reference frame can be chosen + independently (e.g. the robot base). + """ + + def __init__( + self, + frame, + base_link_frame_name: str | None = None, + position_cost: float | Sequence[float] | None = None, + orientation_cost: float | Sequence[float] | None = None, + lm_damping: float = 0.0, + gain: float = 1.0, + ): + """Initialize the LocalFrameTask. + + The first positional argument may be either a *string* (frame name) or a + configuration dataclass that carries all parameters. + + Args: + frame: Name of the frame to control (end-effector or target frame), + **or** a configuration object whose attributes mirror the remaining + arguments. + base_link_frame_name: Name of the base-link frame used as the + reference for computing transforms and errors. Required when + *frame* is a string. + position_cost: Cost weight(s) for position error. A single float + applies uniform weighting; a sequence of 3 floats gives per-axis + weights. + orientation_cost: Cost weight(s) for orientation error (same + convention as *position_cost*). + lm_damping: Levenberg-Marquardt damping factor for numerical + stability. Defaults to 0.0 (no damping). + gain: Task gain that scales the overall task contribution. + Defaults to 1.0. + """ + if isinstance(frame, str): + resolved_frame = frame + if base_link_frame_name is None: + raise ValueError("base_link_frame_name must be provided") + else: + cfg = frame + resolved_frame = cfg.frame + base_link_frame_name = cfg.base_link_frame_name + position_cost = cfg.position_cost + orientation_cost = cfg.orientation_cost + lm_damping = cfg.lm_damping + gain = cfg.gain + + if position_cost is None or orientation_cost is None: + raise ValueError("position_cost and orientation_cost must be provided") + + super().__init__(resolved_frame, position_cost, orientation_cost, lm_damping, gain) + self.base_link_frame_name = base_link_frame_name + self.transform_target_to_base = None + + def set_target(self, transform_target_to_base: pin.SE3) -> None: + """Set the task target pose relative to the base-link frame. + + Args: + transform_target_to_base: Desired transform from the target frame + to the base-link frame. + """ + self.transform_target_to_base = transform_target_to_base.copy() + + def set_target_from_configuration(self, configuration: PinkKinematicsConfiguration) -> None: + """Set the task target pose from the current robot configuration. + + The target is computed as the transform of :attr:`frame` relative to + :attr:`base_link_frame_name` in the given configuration. + + Args: + configuration: Robot configuration to read the current pose from. + """ + if not isinstance(configuration, PinkKinematicsConfiguration): + raise ValueError("configuration must be a PinkKinematicsConfiguration") + self.set_target(configuration.get_transform(self.frame, self.base_link_frame_name)) + + def compute_error(self, configuration: PinkKinematicsConfiguration) -> np.ndarray: + """Compute the error between current and target pose in the local frame. + + Args: + configuration: Robot configuration :math:`q`. + + Returns: + 6D error vector (3 position + 3 orientation) expressed in the + controlled frame. + """ + if not isinstance(configuration, PinkKinematicsConfiguration): + raise ValueError("configuration must be a PinkKinematicsConfiguration") + if self.transform_target_to_base is None: + raise ValueError(f"no target set for frame '{self.frame}'") + + transform_frame_to_base = configuration.get_transform(self.frame, self.base_link_frame_name) + transform_target_to_frame = transform_frame_to_base.actInv(self.transform_target_to_base) + + error_in_frame: np.ndarray = pin.log(transform_target_to_frame).vector + return error_in_frame + + def compute_jacobian(self, configuration: PinkKinematicsConfiguration) -> np.ndarray: + r"""Compute the frame task Jacobian expressed in the local frame. + + The task Jacobian :math:`J(q) \in \mathbb{R}^{6 \times n_v}` is the + derivative of the task error :math:`e(q) \in \mathbb{R}^6` with respect + to the configuration :math:`q`: + + .. math:: + + J(q) = -\text{Jlog}_6(T_{tb}) \; {}_b J_{0b}(q) + + See [Caron2023]_ for a full derivation and + :func:`pink.tasks.task.Task.compute_jacobian` for more context on task + Jacobians. + + Args: + configuration: Robot configuration :math:`q`. + + Returns: + Jacobian matrix :math:`J`, expressed locally in the frame. + """ + if self.transform_target_to_base is None: + raise Exception(f"no target set for frame '{self.frame}'") + transform_frame_to_base = configuration.get_transform(self.frame, self.base_link_frame_name) + transform_frame_to_target = self.transform_target_to_base.actInv(transform_frame_to_base) + jacobian_in_frame = configuration.get_frame_jacobian(self.frame) + J = -pin.Jlog6(transform_frame_to_target) @ jacobian_in_frame + return J diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/rmp_flow.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/rmp_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..fcfdcb4e0a1d646f0a4b35ccd2b6ee0cd92e94b1 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/rmp_flow.py @@ -0,0 +1,377 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import time + +import numpy as np +import torch + +import isaaclab.sim as sim_utils +from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.math import matrix_from_quat + +from .rmp_flow_cfg import RmpFlowControllerCfg # noqa: F401 +from .utils import import_lula, resolve_rmpflow_path + + +class _LulaRmpFlow: + """RMPFlow policy backed directly by the ``lula`` library. + + This mirrors the surface of ``isaacsim.robot_motion.motion_generation``'s ``RmpFlow`` that + :class:`RmpFlowController` depends on (construction, active/watched joints, end-effector target, + Euler integration of the policy acceleration), backed by the same ``lula`` library but without + going through the Isaac Sim Kit motion-generation extension. This keeps a single code path across + backends -- Kit and kitless (e.g. the Newton visualizer) -- since ``lula`` is importable in both. + It assumes IsaacLab conventions: a meter-scaled stage and an identity robot base pose (the + controller never relocates the base), and it does not manage obstacles or visuals. + + Note: + ``lula`` is deprecated as of Isaac Sim 6.0 and slated for removal in a future release; cuMotion + (``isaacsim.robot_motion.cumotion``) is the long-term replacement. See the migration notes at + :data:`isaaclab.controllers.utils._LULA_EXT_NAME`. + """ + + def __init__( + self, + robot_description_path: str, + urdf_path: str, + rmpflow_config_path: str, + end_effector_frame_name: str, + maximum_substep_size: float, + ignore_robot_state_updates: bool = False, + ) -> None: + """Load the robot description and world, then build the lula RMPFlow policy.""" + lula = import_lula() + + if maximum_substep_size <= 0: + raise ValueError("maximum_substep_size argument must be positive.") + + self._lula = lula + self.maximum_substep_size = maximum_substep_size + self.ignore_robot_state_updates = ignore_robot_state_updates + self.end_effector_frame_name = end_effector_frame_name + self._rmpflow_config_path = rmpflow_config_path + + self._robot_description = lula.load_robot(robot_description_path, urdf_path) + self._world = lula.create_world() + self._build_policy() + + self._robot_joint_positions: np.ndarray | None = None + self._robot_joint_velocities: np.ndarray | None = None + + def _build_policy(self) -> None: + """(Re)create the lula RMPFlow policy from the configured robot and config files.""" + config = self._lula.create_rmpflow_config( + self._rmpflow_config_path, + self._robot_description, + self.end_effector_frame_name, + self._world.add_world_view(), + ) + self._policy = self._lula.create_rmpflow(config) + + def get_active_joints(self) -> list[str]: + """Return the names of the joints the policy actively controls (its c-space coords).""" + rd = self._robot_description + return [rd.c_space_coord_name(i) for i in range(rd.num_c_space_coords())] + + def get_watched_joints(self) -> list[str]: + """Return the watched (non-controlled) joints; always empty since lula only watches active joints.""" + return [] + + def reset(self) -> None: + """Rebuild the policy and clear the cached internal joint state.""" + self._build_policy() + self._robot_joint_positions = None + self._robot_joint_velocities = None + + def set_end_effector_target(self, target_position=None, target_orientation=None) -> None: + """Set (or clear) the end-effector position/orientation attractors from the target pose.""" + # identity base pose + meter stage -> targets pass through unchanged + if target_position is None and target_orientation is None: + self._policy.clear_end_effector_position_attractor() + self._policy.clear_end_effector_orientation_attractor() + return + if target_position is not None: + self._policy.set_end_effector_position_attractor(np.asarray(target_position, dtype=np.float64)) + else: + self._policy.clear_end_effector_position_attractor() + if target_orientation is not None: + # lula expects a rotation matrix; IsaacLab quaternions are already (x, y, z, w) convention. + rot = matrix_from_quat(torch.as_tensor(target_orientation, dtype=torch.float64)).numpy() + self._policy.set_end_effector_orientation_attractor(self._lula.Rotation3(rot)) + else: + self._policy.clear_end_effector_orientation_attractor() + + def compute_joint_targets( + self, + active_joint_positions: np.ndarray, + active_joint_velocities: np.ndarray, + watched_joint_positions: np.ndarray, + watched_joint_velocities: np.ndarray, + frame_duration: float, + ) -> tuple[np.ndarray, np.ndarray]: + """Integrate the policy over one frame and return the next joint position/velocity targets.""" + if ( + self._robot_joint_positions is None + or self._robot_joint_velocities is None + or not self.ignore_robot_state_updates + ): + positions = np.array(active_joint_positions, dtype=np.float64) + velocities = np.array(active_joint_velocities, dtype=np.float64) + else: + positions = self._robot_joint_positions + velocities = self._robot_joint_velocities + + self._robot_joint_positions, self._robot_joint_velocities = self._euler_integration( + positions, velocities, frame_duration + ) + return self._robot_joint_positions, self._robot_joint_velocities + + def _evaluate_acceleration(self, joint_positions: np.ndarray, joint_velocities: np.ndarray) -> np.ndarray: + """Query the lula policy for the joint-space acceleration at the given state.""" + joint_positions = np.asarray(joint_positions, dtype=np.float64) + joint_velocities = np.asarray(joint_velocities, dtype=np.float64) + joint_accel = np.zeros_like(joint_positions) + self._policy.eval_accel(joint_positions, joint_velocities, joint_accel) + return joint_accel + + def _euler_integration( + self, joint_positions: np.ndarray, joint_velocities: np.ndarray, frame_duration: float + ) -> tuple[np.ndarray, np.ndarray]: + """Roll out the policy acceleration with fixed-substep Euler integration over the frame.""" + num_steps = int(np.ceil(frame_duration / self.maximum_substep_size)) + policy_timestep = frame_duration / num_steps + for _ in range(num_steps): + joint_accel = self._evaluate_acceleration(joint_positions, joint_velocities) + joint_positions = joint_positions + policy_timestep * joint_velocities + joint_velocities = joint_velocities + policy_timestep * joint_accel + return joint_positions, joint_velocities + + +class _LulaRmpFlowSmoothed(_LulaRmpFlow): + """Jerk-smoothed RMPFlow variant, ported from the Kit ``RmpFlowSmoothed`` policy. + + Adds wall-clock jerk monitoring on top of :class:`_LulaRmpFlow`: a large acceleration jump + triggers a speed reduction and medium jumps are truncated, which smooths motion on physical + robots. The smoothing math is pure NumPy, so this variant -- like the base policy -- runs without + the Isaac Sim Kit motion-generation extension. + """ + + def __init__(self, *args, **kwargs) -> None: + """Initialize the base policy and the jerk-smoothing state and tunables.""" + super().__init__(*args, **kwargs) + self._reset_smoothing_state() + # tunables (mirror the Kit ``RmpFlowSmoothed`` defaults) + self.min_time_between_jerk_reductions = 0.5 + self.min_speed_scalar = 0.2 + self.use_big_jerk_speed_scaling = True + self.big_jerk_limit = 10.0 + self.use_medium_jerk_truncation = True + self.max_medium_jerk = 7.0 + self.speed_scalar_alpha_blend = 0.985 + + def _reset_smoothing_state(self) -> None: + """Reset the speed scalar and cached acceleration/jerk-timing used for smoothing.""" + self.desired_speed_scalar = 1.0 + self.speed_scalar = 1.0 + self.time_at_last_jerk_reduction: float | None = None + self.qdd: np.ndarray | None = None + + def reset(self) -> None: + """Rebuild the policy (base reset) and clear the jerk-smoothing state.""" + super().reset() + self._reset_smoothing_state() + + def _eval_speed_scaled_accel(self, joint_positions: np.ndarray, joint_velocities: np.ndarray) -> np.ndarray: + """Evaluate acceleration with velocity/time rescaled by the current speed scalar.""" + qdd_eval = self._evaluate_acceleration(joint_positions, joint_velocities / self.speed_scalar) + qdd_eval *= self.speed_scalar**2 + return qdd_eval + + def _euler_integration( + self, joint_positions: np.ndarray, joint_velocities: np.ndarray, frame_duration: float + ) -> tuple[np.ndarray, np.ndarray]: + """Roll out the policy like the base class, but monitor and reduce/truncate jerk per substep.""" + num_steps = int(np.ceil(frame_duration / self.maximum_substep_size)) + step_dt = frame_duration / num_steps + + q = np.array(joint_positions, dtype=np.float64) + qd = np.array(joint_velocities, dtype=np.float64) + + # jerk monitoring is meant for physical robots, so it uses wall-clock time (matching Kit) + now = time.time() + + for _ in range(num_steps): + if self.qdd is None: + self.qdd = self._eval_speed_scaled_accel(q, qd) + continue + + jerk_reduction_performed = False + + # reduce speed to the minimum when a big jerk is experienced + if self.use_big_jerk_speed_scaling: + is_first = True + while True: + qdd_eval = self._eval_speed_scaled_accel(q, qd) + # only evaluate the reduction once; the loop re-evals qdd after the reduction + if not is_first: + break + if ( + self.time_at_last_jerk_reduction is not None + and (now - self.time_at_last_jerk_reduction) < self.min_time_between_jerk_reductions + ): + break + jerk = np.linalg.norm(qdd_eval - self.qdd) + if jerk > self.big_jerk_limit: + self.speed_scalar = self.min_speed_scalar + jerk_reduction_performed = True + is_first = False + + # truncate transient medium jerks + if self.use_medium_jerk_truncation: + qdd_eval = self._eval_speed_scaled_accel(q, qd) + jerk = np.linalg.norm(qdd_eval - self.qdd) + if jerk > self.max_medium_jerk: + direction = (qdd_eval - self.qdd) / jerk + qdd_eval = self.qdd + self.max_medium_jerk * direction + + if jerk_reduction_performed: + self.time_at_last_jerk_reduction = now + + self.qdd = qdd_eval + + a = self.speed_scalar_alpha_blend + self.speed_scalar = a * self.speed_scalar + (1.0 - a) * self.desired_speed_scalar + + q = q + step_dt * qd + qd = qd + step_dt * self.qdd + + return q, qd + + +class RmpFlowController: + """Wraps around RMPFlow from IsaacSim for batched environments.""" + + def __init__(self, cfg: RmpFlowControllerCfg, device: str): + """Initialize the controller. + + Args: + cfg: The configuration for the controller. + device: The device to use for computation. + """ + self.cfg = cfg + self._device = device + print(f"[INFO]: Loading RMPFlow controller URDF from: {self.cfg.urdf_file}") + + """ + Properties. + """ + + @property + def num_actions(self) -> int: + """Dimension of the action space of controller.""" + return 7 + + """ + Operations. + """ + + def initialize(self, num_robots: int, joint_names: list[str]): + """Initialize the controller. + + Args: + num_robots: Number of robot instances (environments). + joint_names: Ordered list of all joint names from the articulation. + """ + physics_dt = sim_utils.SimulationContext.instance().get_physics_dt() + self.num_robots = num_robots + self._physics_dt = physics_dt + + if self.cfg.name == "rmp_flow": + controller_cls = _LulaRmpFlow + elif self.cfg.name == "rmp_flow_smoothed": + controller_cls = _LulaRmpFlowSmoothed + else: + raise ValueError(f"Unsupported controller in Lula library: {self.cfg.name}") + + name_to_idx = {name: i for i, name in enumerate(joint_names)} + + self._rmpflow_policies: list[_LulaRmpFlow] = [] + self._active_indices: list[np.ndarray] = [] + self._watched_indices: list[np.ndarray] = [] + + for _ in range(num_robots): + local_urdf_file = retrieve_file_path(resolve_rmpflow_path(self.cfg.urdf_file), force_download=True) + local_collision_file = retrieve_file_path( + resolve_rmpflow_path(self.cfg.collision_file), force_download=True + ) + local_config_file = retrieve_file_path(resolve_rmpflow_path(self.cfg.config_file), force_download=True) + + rmpflow = controller_cls( + robot_description_path=local_collision_file, + urdf_path=local_urdf_file, + rmpflow_config_path=local_config_file, + end_effector_frame_name=self.cfg.frame_name, + maximum_substep_size=physics_dt / self.cfg.evaluations_per_frame, + ignore_robot_state_updates=self.cfg.ignore_robot_state_updates, + ) + + active_indices = np.array([name_to_idx[n] for n in rmpflow.get_active_joints()], dtype=np.intp) + watched_indices = np.array([name_to_idx[n] for n in rmpflow.get_watched_joints()], dtype=np.intp) + + self._rmpflow_policies.append(rmpflow) + self._active_indices.append(active_indices) + self._watched_indices.append(watched_indices) + + self.active_dof_names = self._rmpflow_policies[0].get_active_joints() + self.num_dof = len(self.active_dof_names) + + self._command = torch.zeros(self.num_robots, self.num_actions, device=self._device) + self.dof_pos_target = torch.zeros((self.num_robots, self.num_dof), device=self._device) + self.dof_vel_target = torch.zeros((self.num_robots, self.num_dof), device=self._device) + + def reset_idx(self, robot_ids: torch.Tensor | None = None): + """Reset the internals.""" + if robot_ids is None: + robot_ids = torch.arange(self.num_robots, device=self._device) + for index in robot_ids: + self._rmpflow_policies[index].reset() + + def set_command(self, command: torch.Tensor): + """Set target end-effector pose command.""" + self._command[:] = command + + def compute( + self, joint_positions: torch.Tensor, joint_velocities: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + """Performs inference with the controller. + + Args: + joint_positions: Current joint positions, shape ``[num_robots, num_joints]``. + joint_velocities: Current joint velocities, shape ``[num_robots, num_joints]``. + + Returns: + The target joint positions and velocity commands. + """ + command = self._command.cpu().numpy() + all_pos = joint_positions.cpu().numpy() + all_vel = joint_velocities.cpu().numpy() + + for i, rmpflow in enumerate(self._rmpflow_policies): + rmpflow.set_end_effector_target(target_position=command[i, 0:3], target_orientation=command[i, 3:7]) + active_pos = all_pos[i][self._active_indices[i]] + active_vel = all_vel[i][self._active_indices[i]] + watched_pos = all_pos[i][self._watched_indices[i]] + watched_vel = all_vel[i][self._watched_indices[i]] + + pos_targets, vel_targets = rmpflow.compute_joint_targets( + active_pos, active_vel, watched_pos, watched_vel, self._physics_dt + ) + self.dof_pos_target[i, :] = torch.from_numpy(pos_targets[:]).to(self.dof_pos_target) + self.dof_vel_target[i, :] = torch.from_numpy(vel_targets[:]).to(self.dof_vel_target) + + return self.dof_pos_target, self.dof_vel_target diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/rmp_flow_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/rmp_flow_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..a55954e6aafbe0ff6716c786873810ef48044610 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/rmp_flow_cfg.py @@ -0,0 +1,32 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for RMP-Flow controller.""" + +from __future__ import annotations + +from dataclasses import MISSING + +from isaaclab.utils.configclass import configclass + + +@configclass +class RmpFlowControllerCfg: + """Configuration for RMP-Flow controller (provided through LULA library).""" + + name: str = "rmp_flow" + """Name of the controller. Supported: "rmp_flow", "rmp_flow_smoothed". Defaults to "rmp_flow".""" + config_file: str = MISSING + """Path to the configuration file for the controller.""" + urdf_file: str = MISSING + """Path to the URDF model of the robot.""" + collision_file: str = MISSING + """Path to collision model description of the robot.""" + frame_name: str = MISSING + """Name of the robot frame for task space (must be present in the URDF).""" + evaluations_per_frame: float = MISSING + """Number of substeps during Euler integration inside LULA world model.""" + ignore_robot_state_updates: bool = False + """If true, then state of the world model inside controller is rolled out. Defaults to False.""" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/utils.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7905f178d75976ad271d54c117ec5e51adce2ea4 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/controllers/utils.py @@ -0,0 +1,242 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Helper functions for Isaac Lab controllers. + +This module provides utility functions to help with controller implementations. +""" + +import contextlib +import glob +import logging +import os +import re +import sys +import xml.etree.ElementTree as ET + +# import logger +logger = logging.getLogger(__name__) + +# NOTE: As of Isaac Sim 6.0, ``isaacsim.robot_motion.lula`` (and ``isaacsim.robot_motion.motion_generation``) +# are deprecated -- ``lula`` has been subsumed by cuMotion (``isaacsim.robot_motion.cumotion``), which is +# built on the new experimental motion-generation API and is the long-term replacement for RMPFlow here. +# ``lula`` is still shipped (under ``extsDeprecated`` in pip installs) so this controller keeps working, + +_LULA_EXT_NAME = "isaacsim.robot_motion.lula" +_RMPFLOW_EXT_PREFIX = "rmpflow_ext:" +_RMPFLOW_EXT_NAME = "isaacsim.robot_motion.motion_generation" + + +def convert_usd_to_urdf(usd_path: str, output_path: str, force_conversion: bool = True) -> tuple[str, str]: + """Convert a USD file to URDF format. + + Args: + usd_path: Path to the USD file to convert. + output_path: Directory to save the converted URDF and mesh files. + force_conversion: Whether to force the conversion even if the URDF and mesh files already exist. + Returns: + A tuple containing the paths to the URDF file and the mesh directory. + """ + from isaacsim.core.experimental.utils.app import enable_extension + + enable_extension("isaacsim.asset.exporter.urdf") + + urdf_output_dir = os.path.join(output_path, "urdf") + urdf_file_name = os.path.splitext(os.path.basename(usd_path))[0] + ".urdf" + urdf_output_path = os.path.join(urdf_output_dir, urdf_file_name) + urdf_meshes_output_dir = os.path.join(output_path, "meshes") + + if not os.path.exists(urdf_output_path) or not os.path.exists(urdf_meshes_output_dir) or force_conversion: + os.makedirs(urdf_output_dir, exist_ok=True) + os.makedirs(urdf_meshes_output_dir, exist_ok=True) + + from isaacsim.asset.exporter.urdf import UsdToUrdfConverter + + usd_to_urdf = UsdToUrdfConverter( + stage=usd_path, + root_prim_path=None, + mesh_dir_name="../meshes", + mesh_path_prefix="../meshes/", + visualize_collision_meshes=False, + ) + usd_to_urdf.convert(urdf_output_path) + + _sanitize_urdf_for_pinocchio(urdf_output_path) + return urdf_output_path, urdf_meshes_output_dir + + +def _sanitize_urdf_for_pinocchio(urdf_path: str) -> None: + """Fill Pinocchio-required non-kinematic joint-limit fields in exported URDFs.""" + tree = ET.parse(urdf_path) + changed = False + for limit in tree.iter("limit"): + for attr in ("effort", "velocity"): + if limit.get(attr) in {None, "inf", "+inf", "-inf"}: + limit.set(attr, "0.") + changed = True + if changed: + tree.write(urdf_path, encoding="unicode") + + +def change_revolute_to_fixed(urdf_path: str, fixed_joints: list[str], verbose: bool = False): + """Change revolute joints to fixed joints in a URDF file. + + This function modifies a URDF file by changing specified revolute joints to fixed joints. + This is useful when you want to disable certain joints in a robot model. + + Args: + urdf_path: Path to the URDF file to modify. + fixed_joints: List of joint names to convert from revolute to fixed. + verbose: Whether to print information about the changes being made. + """ + with open(urdf_path) as file: + content = file.read() + + for joint in fixed_joints: + old_str = f'' + new_str = f'' + if verbose: + logger.warning(f"Replacing {joint} with fixed joint") + logger.warning(old_str) + logger.warning(new_str) + if old_str not in content: + logger.warning(f"Error: Could not find revolute joint named '{joint}' in URDF file") + content = content.replace(old_str, new_str) + + with open(urdf_path, "w") as file: + file.write(content) + + +def change_revolute_to_fixed_regex(urdf_path: str, fixed_joints: list[str], verbose: bool = False): + """Change revolute joints to fixed joints in a URDF file. + + This function modifies a URDF file by changing specified revolute joints to fixed joints. + This is useful when you want to disable certain joints in a robot model. + + Args: + urdf_path: Path to the URDF file to modify. + fixed_joints: List of regular expressions matching joint names to convert from revolute to fixed. + verbose: Whether to print information about the changes being made. + """ + + with open(urdf_path) as file: + content = file.read() + + # Find all revolute joints in the URDF + revolute_joints = re.findall(r'', content) + + for joint in revolute_joints: + # Check if this joint matches any of the fixed joint patterns + should_fix = any(re.match(pattern, joint) for pattern in fixed_joints) + + if should_fix: + old_str = f'' + new_str = f'' + if verbose: + logger.warning(f"Replacing {joint} with fixed joint") + logger.warning(old_str) + logger.warning(new_str) + content = content.replace(old_str, new_str) + + with open(urdf_path, "w") as file: + file.write(content) + + +def resolve_rmpflow_path(path: str) -> str: + """Resolve a sentinel ``rmpflow_ext:`` path to an absolute filesystem path. + + Paths stored in :class:`~isaaclab.controllers.rmp_flow_cfg.RmpFlowControllerCfg` + that begin with ``"rmpflow_ext:"`` are relative to the + ``isaacsim.robot_motion.motion_generation`` extension directory. This avoids + importing ``isaacsim`` in the cfg file (which is loaded without Kit). + """ + if path.startswith(_RMPFLOW_EXT_PREFIX): + rel = path[len(_RMPFLOW_EXT_PREFIX) :] + # imported lazily so the module loads without Kit (e.g. the kitless Newton visualizer) + from isaacsim.core.experimental.utils.app import get_extension_path + + ext_dir = get_extension_path(_RMPFLOW_EXT_NAME) + return os.path.join(ext_dir, rel) + return path + + +def find_lula_prebundle_dir() -> str | None: + """Locate the ``pip_prebundle`` directory shipping the ``lula`` module, or ``None`` if not found. + + ``lula`` is prebundled inside the ``isaacsim.robot_motion.lula`` extension, under the Isaac Sim + install directory exposed via the ``ISAAC_PATH`` environment variable (importing ``isaacsim`` sets + it as a side effect). The extension lives under different sub-trees depending on the install: + ``exts/`` for binary installs, ``extscache/-`` for pip caches, and + ``extsDeprecated/`` for the Isaac Sim 6.0 pip packages (where the Kit resolver reports it as + unavailable even though the prebundled module is present). All layouts are searched. + """ + isaac_path = os.environ.get("ISAAC_PATH") + if not isaac_path: + with contextlib.suppress(ImportError): + import isaacsim # noqa: F401 (sets ``os.environ["ISAAC_PATH"]`` as a side effect) + isaac_path = os.environ.get("ISAAC_PATH") + if not isaac_path: + return None + candidates = [os.path.join(isaac_path, "exts", _LULA_EXT_NAME, "pip_prebundle")] + for parent in ("extscache", "extsDeprecated", "exts"): + candidates.extend(sorted(glob.glob(os.path.join(isaac_path, parent, f"{_LULA_EXT_NAME}*", "pip_prebundle")))) + for prebundle in candidates: + if os.path.isdir(prebundle): + return prebundle + return None + + +def import_lula(): + """Import and return the ``lula`` library, making it importable across backends. + + ``lula`` ships as a prebundled module of the ``isaacsim.robot_motion.lula`` Isaac Sim extension. + Resolution proceeds in order: import directly when the ``pip_prebundle`` paths are already on + :data:`sys.path` (e.g. when launched via ``isaaclab.sh``); otherwise locate the prebundle directory + and add it to :data:`sys.path` (works under both Kit and the kitless Newton visualizer); and only as + a last resort ask a running Kit app to enable the owning extension. The prebundle is tried before + :func:`enable_extension` on purpose -- in Isaac Sim 6.0 the extension is deprecated and unresolvable + by Kit, so enabling it first would log a spurious "failed to resolve extension dependencies" error + even though ``lula`` itself loads fine from the prebundle. + """ + try: + import lula + + return lula + except ModuleNotFoundError: + pass + + # Locate the prebundle and add it ourselves -- works under both Kit and kitless, and avoids asking + # Kit to enable the (in 6.0, deprecated and unresolvable) extension. + prebundle = find_lula_prebundle_dir() + if prebundle is not None and prebundle not in sys.path: + sys.path.insert(0, prebundle) + try: + import lula + + return lula + except ModuleNotFoundError: + pass + + # Last resort: under a running Kit app, enabling the owning extension registers its prebundle. + try: + from isaacsim.core.experimental.utils.app import enable_extension + except (ImportError, ModuleNotFoundError): + pass + else: + enable_extension(_LULA_EXT_NAME) + try: + import lula + + return lula + except ModuleNotFoundError: + pass + + raise ModuleNotFoundError( + "Could not import 'lula', which is required by the RMPFlow controller. It ships with the" + f" '{_LULA_EXT_NAME}' Isaac Sim extension, which was not found in this Isaac Sim install." + " The Isaac Sim 6.0 pip packages (early developer release) do not yet include this" + " extension; use a binary Isaac Sim install, or select a task that does not rely on" + " RMPFlow." + ) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f6830252e40d7234de453d2a2aaa7f100bde39be --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__init__.py @@ -0,0 +1,25 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-package providing interfaces to different teleoperation devices. + +Currently, the following categories of devices are supported: + +* **Keyboard**: Standard keyboard with WASD and arrow keys. +* **Spacemouse**: 3D mouse with 6 degrees of freedom. +* **Gamepad**: Gamepad with 2D two joysticks and buttons. Example: Xbox controller. +* **OpenXR**: Uses hand tracking of index/thumb tip avg to drive the target pose. Gripping is done with pinching. +* **Haply**: Haptic device (Inverse3 + VerseGrip) with position, orientation tracking and force feedback. + +All device interfaces inherit from the :class:`DeviceBase` class, which provides a +common interface for all devices. The device interface reads the input data when +the :meth:`DeviceBase.advance` method is called. It also provides the function :meth:`DeviceBase.add_callback` +to add user-defined callback functions to be called when a particular input is pressed from +the peripheral device. +""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..86835c0e71dbb8291cfff23412a84153f1389a19 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__init__.pyi @@ -0,0 +1,40 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "DeviceBase", + "DeviceCfg", + "DevicesCfg", + "Se2Gamepad", + "Se2GamepadCfg", + "Se3Gamepad", + "Se3GamepadCfg", + "HaplyDevice", + "HaplyDeviceCfg", + "Se2Keyboard", + "Se2KeyboardCfg", + "Se3Keyboard", + "Se3KeyboardCfg", + "ManusVive", + "ManusViveCfg", + "OpenXRDevice", + "OpenXRDeviceCfg", + "RetargeterBase", + "RetargeterCfg", + "Se2SpaceMouse", + "Se2SpaceMouseCfg", + "Se3SpaceMouse", + "Se3SpaceMouseCfg", + "create_teleop_device", +] + +from .device_base import DeviceBase, DeviceCfg, DevicesCfg +from .gamepad import Se2Gamepad, Se2GamepadCfg, Se3Gamepad, Se3GamepadCfg +from .haply import HaplyDevice, HaplyDeviceCfg +from .keyboard import Se2Keyboard, Se2KeyboardCfg, Se3Keyboard, Se3KeyboardCfg +from .openxr import ManusVive, ManusViveCfg, OpenXRDevice, OpenXRDeviceCfg +from .retargeter_base import RetargeterBase, RetargeterCfg +from .spacemouse import Se2SpaceMouse, Se2SpaceMouseCfg, Se3SpaceMouse, Se3SpaceMouseCfg +from .teleop_device_factory import create_teleop_device diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__pycache__/__init__.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f343bc6ea11ecc50bb97ee20f86088bebe47894c Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__pycache__/device_base.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__pycache__/device_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2ba10b00951daacc34716a75dda8b17381a3047 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__pycache__/device_base.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__pycache__/retargeter_base.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__pycache__/retargeter_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcc28dd1fee8a0c7e26dcb788369bf3153d5becb Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/__pycache__/retargeter_base.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/device_base.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/device_base.py new file mode 100644 index 0000000000000000000000000000000000000000..e175dc1ef500f757cf02cf55cd0e8f85bfcbb00e --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/device_base.py @@ -0,0 +1,163 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Base class for teleoperation interface.""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from collections.abc import Callable +from dataclasses import field +from enum import Enum +from typing import Any + +import torch + +from isaaclab.devices.retargeter_base import RetargeterBase, RetargeterCfg +from isaaclab.utils.configclass import configclass + + +@configclass +class DeviceCfg: + """Configuration for teleoperation devices.""" + + # Whether teleoperation should start active by default + teleoperation_active_default: bool = True + # Torch device string to place output tensors on + sim_device: str = "cpu" + # Retargeters that transform device data into robot commands + retargeters: list[RetargeterCfg] = field(default_factory=list) + # Concrete device class to construct for this config. Set by each device module. + class_type: type[DeviceBase] | None = None + + +@configclass +class DevicesCfg: + """Configuration for all supported teleoperation devices.""" + + devices: dict[str, DeviceCfg] = field(default_factory=dict) + + +class DeviceBase(ABC): + """An interface class for teleoperation devices. + + Derived classes have two implementation options: + + 1. Override _get_raw_data() and use the base advance() implementation: + This approach is suitable for devices that want to leverage the built-in + retargeting logic but only need to customize the raw data acquisition. + + 2. Override advance() completely: + This approach gives full control over the command generation process, + and _get_raw_data() can be ignored entirely. + """ + + def __init__(self, retargeters: list[RetargeterBase] | None = None): + """Initialize the teleoperation interface. + + Args: + retargeters: List of components that transform device data into robot commands. + If None or empty list, the device will output its native data format. + """ + # Initialize empty list if None is provided + self._retargeters = retargeters or [] + # Aggregate required features across all retargeters + self._required_features = set() + for retargeter in self._retargeters: + self._required_features.update(retargeter.get_requirements()) + + def __str__(self) -> str: + """Returns: A string identifier for the device.""" + return f"{self.__class__.__name__}" + + """ + Operations + """ + + @abstractmethod + def reset(self): + """Reset the internals.""" + raise NotImplementedError + + @abstractmethod + def add_callback(self, key: Any, func: Callable): + """Add additional functions to bind keyboard. + + Args: + key: The button to check against. + func: The function to call when key is pressed. The callback function should not + take any arguments. + """ + raise NotImplementedError + + def _get_raw_data(self) -> Any: + """Internal method to get the raw data from the device. + + This method is intended for internal use by the advance() implementation. + Derived classes can override this method to customize raw data acquisition + while still using the base class's advance() implementation. + + Returns: + Raw device data in a device-specific format + + Note: + This is an internal implementation detail. Clients should call advance() + instead of this method. + """ + raise NotImplementedError("Derived class must implement _get_raw_data() or override advance()") + + def advance(self) -> torch.Tensor: + """Process current device state and return control commands. + + This method retrieves raw data from the device and optionally applies + retargeting to convert it to robot commands. + + Derived classes can either: + 1. Override _get_raw_data() and use this base implementation, or + 2. Override this method completely for custom command processing + + Returns: + When no retargeters are configured, returns raw device data in its native format. + When retargeters are configured, returns a torch.Tensor containing the concatenated + outputs from all retargeters. + """ + raw_data = self._get_raw_data() + + # If no retargeters, return raw data directly (not as a tuple) + if not self._retargeters: + return raw_data + + # With multiple retargeters, return a tuple of outputs + # Concatenate retargeted outputs into a single tensor + return torch.cat([retargeter.retarget(raw_data) for retargeter in self._retargeters], dim=-1) + + # ----------------------------- + # Shared data layout helpers (for retargeters across devices) + # ----------------------------- + class TrackingTarget(Enum): + """Standard tracking targets shared across devices.""" + + HAND_LEFT = 0 + HAND_RIGHT = 1 + HEAD = 2 + CONTROLLER_LEFT = 3 + CONTROLLER_RIGHT = 4 + + class MotionControllerDataRowIndex(Enum): + """Rows in the motion-controller 2x7 array.""" + + POSE = 0 + INPUTS = 1 + + class MotionControllerInputIndex(Enum): + """Indices in the motion-controller input row.""" + + THUMBSTICK_X = 0 + THUMBSTICK_Y = 1 + TRIGGER = 2 + SQUEEZE = 3 + BUTTON_0 = 4 + BUTTON_1 = 5 + PADDING = 6 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2957e08ed47766a6e2eb334109255b536d5bb174 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Gamepad device for SE(2) and SE(3) control.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..95baa12dd562750fd0be7a54d0355cc1445b9894 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/__init__.pyi @@ -0,0 +1,16 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "Se2Gamepad", + "Se2GamepadCfg", + "Se3Gamepad", + "Se3GamepadCfg", +] + +from .se2_gamepad import Se2Gamepad +from .se2_gamepad_cfg import Se2GamepadCfg +from .se3_gamepad import Se3Gamepad +from .se3_gamepad_cfg import Se3GamepadCfg diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/se2_gamepad.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/se2_gamepad.py new file mode 100644 index 0000000000000000000000000000000000000000..46fa3ba58993bd32368bfac2decf4ae1df6f9075 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/se2_gamepad.py @@ -0,0 +1,208 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Gamepad controller for SE(2) control.""" + +from __future__ import annotations + +import weakref +from collections.abc import Callable +from typing import TYPE_CHECKING + +import numpy as np +import torch + +import carb +import carb.input +import omni + +from isaaclab.app.settings_manager import get_settings_manager + +from ..device_base import DeviceBase + +if TYPE_CHECKING: + from .se2_gamepad_cfg import Se2GamepadCfg + + +class Se2Gamepad(DeviceBase): + r"""A gamepad controller for sending SE(2) commands as velocity commands. + + This class is designed to provide a gamepad controller for mobile base (such as quadrupeds). + It uses the Omniverse gamepad interface to listen to gamepad events and map them to robot's + task-space commands. + + The command comprises of the base linear and angular velocity: :math:`(v_x, v_y, \omega_z)`. + + Key bindings: + ====================== ========================= ======================== + Command Key (+ve axis) Key (-ve axis) + ====================== ========================= ======================== + Move along x-axis left stick up left stick down + Move along y-axis left stick right left stick left + Rotate along z-axis right stick right right stick left + ====================== ========================= ======================== + + .. seealso:: + + The official documentation for the gamepad interface: `Carb Gamepad Interface `__. + + """ + + def __init__( + self, + cfg: Se2GamepadCfg, + ): + """Initialize the gamepad layer. + + Args: + v_x_sensitivity: Magnitude of linear velocity along x-direction scaling. Defaults to 1.0. + v_y_sensitivity: Magnitude of linear velocity along y-direction scaling. Defaults to 1.0. + omega_z_sensitivity: Magnitude of angular velocity along z-direction scaling. Defaults to 1.0. + dead_zone: Magnitude of dead zone for gamepad. An event value from the gamepad less than + this value will be ignored. Defaults to 0.01. + """ + # turn off simulator gamepad control + get_settings_manager().set_bool("/persistent/app/omniverse/gamepadCameraControl", False) + # store inputs + self.v_x_sensitivity = cfg.v_x_sensitivity + self.v_y_sensitivity = cfg.v_y_sensitivity + self.omega_z_sensitivity = cfg.omega_z_sensitivity + self.dead_zone = cfg.dead_zone + self._sim_device = cfg.sim_device + # acquire omniverse interfaces + self._appwindow = omni.appwindow.get_default_app_window() + self._input = carb.input.acquire_input_interface() + self._gamepad = self._appwindow.get_gamepad(0) + # note: Use weakref on callbacks to ensure that this object can be deleted when its destructor is called + self._gamepad_sub = self._input.subscribe_to_gamepad_events( + self._gamepad, + lambda event, *args, obj=weakref.proxy(self): obj._on_gamepad_event(event, *args), + ) + # bindings for gamepad to command + self._create_key_bindings() + # command buffers + # When using the gamepad, two values are provided for each axis. + # For example: when the left stick is moved down, there are two evens: `left_stick_down = 0.8` + # and `left_stick_up = 0.0`. If only the value of left_stick_up is used, the value will be 0.0, + # which is not the desired behavior. Therefore, we save both the values into the buffer and use + # the maximum value. + # (positive, negative), (x, y, yaw) + self._base_command_raw = np.zeros([2, 3]) + # dictionary for additional callbacks + self._additional_callbacks = dict() + + def __del__(self): + """Unsubscribe from gamepad events.""" + self._input.unsubscribe_to_gamepad_events(self._gamepad, self._gamepad_sub) + self._gamepad_sub = None + + def __str__(self) -> str: + """Returns: A string containing the information of joystick.""" + msg = f"Gamepad Controller for SE(2): {self.__class__.__name__}\n" + msg += f"\tDevice name: {self._input.get_gamepad_name(self._gamepad)}\n" + msg += "\t----------------------------------------------\n" + msg += "\tMove in X-Y plane: left stick\n" + msg += "\tRotate in Z-axis: right stick\n" + return msg + + """ + Operations + """ + + def reset(self): + # default flags + self._base_command_raw.fill(0.0) + + def add_callback(self, key: carb.input.GamepadInput, func: Callable): + """Add additional functions to bind gamepad. + + A list of available gamepad keys are present in the + `carb documentation `__. + + Args: + key: The gamepad button to check against. + func: The function to call when key is pressed. The callback function should not + take any arguments. + """ + self._additional_callbacks[key] = func + + def advance(self) -> torch.Tensor: + """Provides the result from gamepad event state. + + Returns: + A tensor containing the linear (x,y) and angular velocity (z). + """ + numpy_result = self._resolve_command_buffer(self._base_command_raw) + return torch.tensor(numpy_result, dtype=torch.float32, device=self._sim_device) + + """ + Internal helpers. + """ + + def _on_gamepad_event(self, event: carb.input.GamepadEvent, *args, **kwargs): + """Subscriber callback to when kit is updated. + + Reference: + https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref/input-devices/gamepad.html + """ + + # check if the event is a button press + cur_val = event.value + if abs(cur_val) < self.dead_zone: + cur_val = 0 + # -- left and right stick + if event.input in self._INPUT_STICK_VALUE_MAPPING: + direction, axis, value = self._INPUT_STICK_VALUE_MAPPING[event.input] + # change the value only if the stick is moved (soft press) + self._base_command_raw[direction, axis] = value * cur_val + + # additional callbacks + if event.input in self._additional_callbacks: + self._additional_callbacks[event.input]() + + # since no error, we are fine :) + return True + + def _create_key_bindings(self): + """Creates default key binding.""" + self._INPUT_STICK_VALUE_MAPPING = { + # forward command + carb.input.GamepadInput.LEFT_STICK_UP: (0, 0, self.v_x_sensitivity), + # backward command + carb.input.GamepadInput.LEFT_STICK_DOWN: (1, 0, self.v_x_sensitivity), + # right command + carb.input.GamepadInput.LEFT_STICK_RIGHT: (0, 1, self.v_y_sensitivity), + # left command + carb.input.GamepadInput.LEFT_STICK_LEFT: (1, 1, self.v_y_sensitivity), + # yaw command (positive) + carb.input.GamepadInput.RIGHT_STICK_RIGHT: (0, 2, self.omega_z_sensitivity), + # yaw command (negative) + carb.input.GamepadInput.RIGHT_STICK_LEFT: (1, 2, self.omega_z_sensitivity), + } + + def _resolve_command_buffer(self, raw_command: np.ndarray) -> np.ndarray: + """Resolves the command buffer. + + Args: + raw_command: The raw command from the gamepad. Shape is (2, 3) + This is a 2D array since gamepad dpad/stick returns two values corresponding to + the positive and negative direction. The first index is the direction (0: positive, 1: negative) + and the second index is value (absolute) of the command. + + Returns: + Resolved command. Shape is (3,) + """ + # compare the positive and negative value decide the sign of the value + # if the positive value is larger, the sign is positive (i.e. False, 0) + # if the negative value is larger, the sign is positive (i.e. True, 1) + command_sign = raw_command[1, :] > raw_command[0, :] + # extract the command value + command = raw_command.max(axis=0) + # apply the sign + # if the sign is positive, the value is already positive. + # if the sign is negative, the value is negative after applying the sign. + command[command_sign] *= -1 + + return command diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/se2_gamepad_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/se2_gamepad_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..f7156ae1f49c17827d21c59472f54e85fd7b03a7 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/se2_gamepad_cfg.py @@ -0,0 +1,28 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for SE(2) gamepad controller.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.configclass import configclass + +from ..device_base import DeviceCfg + +if TYPE_CHECKING: + from .se2_gamepad import Se2Gamepad + + +@configclass +class Se2GamepadCfg(DeviceCfg): + """Configuration for SE2 gamepad devices.""" + + v_x_sensitivity: float = 1.0 + v_y_sensitivity: float = 1.0 + omega_z_sensitivity: float = 1.0 + dead_zone: float = 0.01 + class_type: type[Se2Gamepad] | str = "{DIR}.se2_gamepad:Se2Gamepad" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/se3_gamepad.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/se3_gamepad.py new file mode 100644 index 0000000000000000000000000000000000000000..70e579c7c7d1b9c041be42c3e791c8d479eb1a16 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/se3_gamepad.py @@ -0,0 +1,262 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Gamepad controller for SE(3) control.""" + +from __future__ import annotations + +import weakref +from collections.abc import Callable +from typing import TYPE_CHECKING + +import numpy as np +import torch +from scipy.spatial.transform import Rotation + +import carb +import omni + +from isaaclab.app.settings_manager import get_settings_manager + +from ..device_base import DeviceBase + +if TYPE_CHECKING: + from .se3_gamepad_cfg import Se3GamepadCfg + + +class Se3Gamepad(DeviceBase): + """A gamepad controller for sending SE(3) commands as delta poses and binary command (open/close). + + This class is designed to provide a gamepad controller for a robotic arm with a gripper. + It uses the gamepad interface to listen to gamepad events and map them to the robot's + task-space commands. + + The command comprises of two parts: + + * delta pose: a 6D vector of (x, y, z, roll, pitch, yaw) in meters and radians. + * gripper: a binary command to open or close the gripper. + + Stick and Button bindings: + ============================ ========================= ========================= + Description Stick/Button (+ve axis) Stick/Button (-ve axis) + ============================ ========================= ========================= + Toggle gripper(open/close) X Button X Button + Move along x-axis Left Stick Up Left Stick Down + Move along y-axis Left Stick Left Left Stick Right + Move along z-axis Right Stick Up Right Stick Down + Rotate along x-axis D-Pad Left D-Pad Right + Rotate along y-axis D-Pad Down D-Pad Up + Rotate along z-axis Right Stick Left Right Stick Right + ============================ ========================= ========================= + + .. seealso:: + + The official documentation for the gamepad interface: `Carb Gamepad Interface `__. + + """ + + def __init__( + self, + cfg: Se3GamepadCfg, + ): + """Initialize the gamepad layer. + + Args: + cfg: Configuration object for gamepad settings. + """ + # turn off simulator gamepad control + get_settings_manager().set_bool("/persistent/app/omniverse/gamepadCameraControl", False) + # store inputs + self.pos_sensitivity = cfg.pos_sensitivity + self.rot_sensitivity = cfg.rot_sensitivity + self.dead_zone = cfg.dead_zone + self.gripper_term = cfg.gripper_term + self._sim_device = cfg.sim_device + # acquire omniverse interfaces + self._appwindow = omni.appwindow.get_default_app_window() + self._input = carb.input.acquire_input_interface() + self._gamepad = self._appwindow.get_gamepad(0) + # note: Use weakref on callbacks to ensure that this object can be deleted when its destructor is called + self._gamepad_sub = self._input.subscribe_to_gamepad_events( + self._gamepad, + lambda event, *args, obj=weakref.proxy(self): obj._on_gamepad_event(event, *args), + ) + # bindings for gamepad to command + self._create_key_bindings() + # command buffers + self._close_gripper = False + # When using the gamepad, two values are provided for each axis. + # For example: when the left stick is moved down, there are two evens: `left_stick_down = 0.8` + # and `left_stick_up = 0.0`. If only the value of left_stick_up is used, the value will be 0.0, + # which is not the desired behavior. Therefore, we save both the values into the buffer and use + # the maximum value. + # (positive, negative), (x, y, z, roll, pitch, yaw) + self._delta_pose_raw = np.zeros([2, 6]) + # dictionary for additional callbacks + self._additional_callbacks = dict() + + def __del__(self): + """Unsubscribe from gamepad events.""" + self._input.unsubscribe_to_gamepad_events(self._gamepad, self._gamepad_sub) + self._gamepad_sub = None + + def __str__(self) -> str: + """Returns: A string containing the information of joystick.""" + msg = f"Gamepad Controller for SE(3): {self.__class__.__name__}\n" + msg += f"\tDevice name: {self._input.get_gamepad_name(self._gamepad)}\n" + msg += "\t----------------------------------------------\n" + msg += "\tToggle gripper (open/close): X\n" + msg += "\tMove arm along x-axis: Left Stick Up/Down\n" + msg += "\tMove arm along y-axis: Left Stick Left/Right\n" + msg += "\tMove arm along z-axis: Right Stick Up/Down\n" + msg += "\tRotate arm along x-axis: D-Pad Right/Left\n" + msg += "\tRotate arm along y-axis: D-Pad Down/Up\n" + msg += "\tRotate arm along z-axis: Right Stick Left/Right\n" + return msg + + """ + Operations + """ + + def reset(self): + # default flags + self._close_gripper = False + self._delta_pose_raw.fill(0.0) + + def add_callback(self, key: carb.input.GamepadInput, func: Callable): + """Add additional functions to bind gamepad. + + A list of available gamepad keys are present in the + `carb documentation `__. + + Args: + key: The gamepad button to check against. + func: The function to call when key is pressed. The callback function should not + take any arguments. + """ + self._additional_callbacks[key] = func + + def advance(self) -> torch.Tensor: + """Provides the result from gamepad event state. + + Returns: + torch.Tensor: A 7-element tensor containing: + - delta pose: First 6 elements as [x, y, z, rx, ry, rz] in meters and radians. + - gripper command: Last element as a binary value (+1.0 for open, -1.0 for close). + """ + # -- resolve position command + delta_pos = self._resolve_command_buffer(self._delta_pose_raw[:, :3]) + # -- resolve rotation command + delta_rot = self._resolve_command_buffer(self._delta_pose_raw[:, 3:]) + # -- convert to rotation vector + rot_vec = Rotation.from_euler("XYZ", delta_rot).as_rotvec() + # return the command and gripper state + command = np.concatenate([delta_pos, rot_vec]) + if self.gripper_term: + gripper_value = -1.0 if self._close_gripper else 1.0 + command = np.append(command, gripper_value) + + return torch.tensor(command, dtype=torch.float32, device=self._sim_device) + + """ + Internal helpers. + """ + + def _on_gamepad_event(self, event, *args, **kwargs): + """Subscriber callback to when kit is updated. + + Reference: + https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref/input-devices/gamepad.html + """ + # check if the event is a button press + cur_val = event.value + if abs(cur_val) < self.dead_zone: + cur_val = 0 + # -- button + if event.input == carb.input.GamepadInput.X: + # toggle gripper based on the button pressed + if cur_val > 0.5: + self._close_gripper = not self._close_gripper + # -- left and right stick + if event.input in self._INPUT_STICK_VALUE_MAPPING: + direction, axis, value = self._INPUT_STICK_VALUE_MAPPING[event.input] + # change the value only if the stick is moved (soft press) + self._delta_pose_raw[direction, axis] = value * cur_val + # -- dpad (4 arrow buttons on the console) + if event.input in self._INPUT_DPAD_VALUE_MAPPING: + direction, axis, value = self._INPUT_DPAD_VALUE_MAPPING[event.input] + # change the value only if button is pressed on the DPAD + if cur_val > 0.5: + self._delta_pose_raw[direction, axis] = value + self._delta_pose_raw[1 - direction, axis] = 0 + else: + self._delta_pose_raw[:, axis] = 0 + # additional callbacks + if event.input in self._additional_callbacks: + self._additional_callbacks[event.input]() + + # since no error, we are fine :) + return True + + def _create_key_bindings(self): + """Creates default key binding.""" + # map gamepad input to the element in self._delta_pose_raw + # the first index is the direction (0: positive, 1: negative) + # the second index is the axis (0: x, 1: y, 2: z, 3: roll, 4: pitch, 5: yaw) + # the third index is the sensitivity of the command + self._INPUT_STICK_VALUE_MAPPING = { + # forward command + carb.input.GamepadInput.LEFT_STICK_UP: (0, 0, self.pos_sensitivity), + # backward command + carb.input.GamepadInput.LEFT_STICK_DOWN: (1, 0, self.pos_sensitivity), + # right command + carb.input.GamepadInput.LEFT_STICK_RIGHT: (0, 1, self.pos_sensitivity), + # left command + carb.input.GamepadInput.LEFT_STICK_LEFT: (1, 1, self.pos_sensitivity), + # upward command + carb.input.GamepadInput.RIGHT_STICK_UP: (0, 2, self.pos_sensitivity), + # downward command + carb.input.GamepadInput.RIGHT_STICK_DOWN: (1, 2, self.pos_sensitivity), + # yaw command (positive) + carb.input.GamepadInput.RIGHT_STICK_RIGHT: (0, 5, self.rot_sensitivity), + # yaw command (negative) + carb.input.GamepadInput.RIGHT_STICK_LEFT: (1, 5, self.rot_sensitivity), + } + + self._INPUT_DPAD_VALUE_MAPPING = { + # pitch command (positive) + carb.input.GamepadInput.DPAD_UP: (1, 4, self.rot_sensitivity * 0.8), + # pitch command (negative) + carb.input.GamepadInput.DPAD_DOWN: (0, 4, self.rot_sensitivity * 0.8), + # roll command (positive) + carb.input.GamepadInput.DPAD_RIGHT: (1, 3, self.rot_sensitivity * 0.8), + # roll command (negative) + carb.input.GamepadInput.DPAD_LEFT: (0, 3, self.rot_sensitivity * 0.8), + } + + def _resolve_command_buffer(self, raw_command: np.ndarray) -> np.ndarray: + """Resolves the command buffer. + + Args: + raw_command: The raw command from the gamepad. Shape is (2, 3) + This is a 2D array since gamepad dpad/stick returns two values corresponding to + the positive and negative direction. The first index is the direction (0: positive, 1: negative) + and the second index is value (absolute) of the command. + + Returns: + Resolved command. Shape is (3,) + """ + # compare the positive and negative value decide the sign of the value + # if the positive value is larger, the sign is positive (i.e. False, 0) + # if the negative value is larger, the sign is positive (i.e. True, 1) + delta_command_sign = raw_command[1, :] > raw_command[0, :] + # extract the command value + delta_command = raw_command.max(axis=0) + # apply the sign + # if the sign is positive, the value is already positive. + # if the sign is negative, the value is negative after applying the sign. + delta_command[delta_command_sign] *= -1 + + return delta_command diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/se3_gamepad_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/se3_gamepad_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..2d21e39807139f47d8107676840575afbd2f8463 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/gamepad/se3_gamepad_cfg.py @@ -0,0 +1,28 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for SE(3) gamepad controller.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.configclass import configclass + +from ..device_base import DeviceCfg + +if TYPE_CHECKING: + from .se3_gamepad import Se3Gamepad + + +@configclass +class Se3GamepadCfg(DeviceCfg): + """Configuration for SE3 gamepad devices.""" + + gripper_term: bool = True + dead_zone: float = 0.01 + pos_sensitivity: float = 1.0 + rot_sensitivity: float = 1.6 + class_type: type[Se3Gamepad] | str = "{DIR}.se3_gamepad:Se3Gamepad" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/haply/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/haply/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..be758d6029cf4ed177149b62eb510142a5081d1f --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/haply/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Haply device interface for teleoperation.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/haply/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/haply/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2a365e53194f43ac62bc06bdedd2a4cdc2516ceb --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/haply/__init__.pyi @@ -0,0 +1,11 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "HaplyDevice", + "HaplyDeviceCfg", +] + +from .se3_haply import HaplyDevice, HaplyDeviceCfg diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/haply/se3_haply.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/haply/se3_haply.py new file mode 100644 index 0000000000000000000000000000000000000000..871aee4689f3c73573a275675ef99e5792d9a091 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/haply/se3_haply.py @@ -0,0 +1,396 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Haply device controller for SE3 control with force feedback.""" + +from __future__ import annotations + +import asyncio +import json +import threading +import time +from collections.abc import Callable + +import numpy as np +import torch + +from isaaclab.utils.configclass import configclass + +try: + import websockets + + WEBSOCKETS_AVAILABLE = True +except ImportError: + WEBSOCKETS_AVAILABLE = False + +from ..device_base import DeviceBase, DeviceCfg +from ..retargeter_base import RetargeterBase + + +class HaplyDevice(DeviceBase): + """A Haply device controller for sending SE(3) commands with force feedback. + + This class provides an interface to Haply robotic devices (Inverse3 + VerseGrip) + for teleoperation. It communicates via WebSocket and supports: + + - Position tracking from Inverse3 device + - Orientation and button inputs from VerseGrip device + - Directional force feedback to Inverse3 + - Real-time data streaming at configurable rates + + The device provides raw data: + + * Position: 3D position (x, y, z) in meters from Inverse3 + * Orientation: Quaternion (x, y, z, w) from VerseGrip + * Buttons: Three buttons (a, b, c) from VerseGrip with state (pressed/not pressed) + + Note: All button logic (e.g., gripper control, reset, mode switching) should be + implemented in the application layer using the raw button states from advance(). + + Note: + Requires the Haply SDK to be running and accessible via WebSocket. + Install dependencies: pip install websockets + + """ + + def __init__(self, cfg: HaplyDeviceCfg, retargeters: list[RetargeterBase] | None = None): + """Initialize the Haply device interface. + + Args: + cfg: Configuration object for Haply device settings. + retargeters: Optional list of retargeting components that transform device data + into robot commands. If None or empty, the device outputs its native data format. + + Raises: + ImportError: If websockets module is not installed. + RuntimeError: If connection to Haply device fails. + """ + super().__init__(retargeters) + + if not WEBSOCKETS_AVAILABLE: + raise ImportError("websockets module is required for Haply device. Install with: pip install websockets") + + # Store configuration + self.websocket_uri = cfg.websocket_uri + self.pos_sensitivity = cfg.pos_sensitivity + self.data_rate = cfg.data_rate + self._sim_device = cfg.sim_device + self.limit_force = cfg.limit_force + + # Device status (True only when both Inverse3 and VerseGrip are connected) + self.connected = False + self._connected_lock = threading.Lock() + + # Device IDs (will be set after first message) + self.inverse3_device_id = None + self.verse_grip_device_id = None + + # Current data cache + self.cached_data = { + "position": np.zeros(3, dtype=np.float32), + "quaternion": np.array([0.0, 0.0, 1.0, 0.0], dtype=np.float32), + "buttons": {"a": False, "b": False, "c": False}, + "inverse3_connected": False, + "versegrip_connected": False, + } + + self.data_lock = threading.Lock() + + # Force feedback + self.feedback_force = {"x": 0.0, "y": 0.0, "z": 0.0} + self.force_lock = threading.Lock() + + self._additional_callbacks = dict() + + # Button state tracking + self._prev_buttons = {"a": False, "b": False, "c": False} + + # Connection monitoring + self.consecutive_timeouts = 0 + self.max_consecutive_timeouts = 10 # ~10 seconds at 1s timeout + self.timeout_warning_issued = False + + # Start WebSocket connection + self.running = True + self._websocket_thread = None + self._start_websocket_thread() + + # Wait for both devices to connect + timeout = 5.0 + start_time = time.time() + while (time.time() - start_time) < timeout: + with self._connected_lock: + if self.connected: + break + time.sleep(0.1) + + with self._connected_lock: + if not self.connected: + raise RuntimeError(f"Failed to connect both Inverse3 and VerseGrip devices within {timeout}s. ") + + def __del__(self): + """Cleanup on deletion: shutdown WebSocket connection and background thread.""" + if not hasattr(self, "running") or not self.running: + return + + self.running = False + + # Reset force feedback before closing + if hasattr(self, "force_lock") and hasattr(self, "feedback_force"): + with self.force_lock: + self.feedback_force = {"x": 0.0, "y": 0.0, "z": 0.0} + + # Explicitly wait for WebSocket thread to finish + if hasattr(self, "_websocket_thread") and self._websocket_thread is not None: + if self._websocket_thread.is_alive(): + self._websocket_thread.join(timeout=2.0) + if self._websocket_thread.is_alive(): + self._websocket_thread.daemon = True + + def __str__(self) -> str: + """Returns: A string containing the information of the device.""" + msg = f"Haply Device Controller: {self.__class__.__name__}\n" + msg += f"\tWebSocket URI: {self.websocket_uri}\n" + msg += f"\tInverse3 ID: {self.inverse3_device_id}\n" + msg += f"\tVerseGrip ID: {self.verse_grip_device_id}\n" + msg += "\t----------------------------------------------\n" + msg += "\tOutput: [x, y, z, qx, qy, qz, qw, btn_a, btn_b, btn_c]\n" + msg += "\tInverse3: Provides position (x, y, z) and force feedback\n" + msg += "\tVerseGrip: Provides orientation (quaternion) and buttons (a, b, c)" + return msg + + def reset(self): + """Reset the device internal state.""" + with self.force_lock: + self.feedback_force = {"x": 0.0, "y": 0.0, "z": 0.0} + + # Reset button state tracking + self._prev_buttons = {"a": False, "b": False, "c": False} + + def add_callback(self, key: str, func: Callable): + """Add additional functions to bind to button events. + + Args: + key: The button to check against. Valid values are "a", "b", "c". + func: The function to call when button is pressed. The callback function should not + take any arguments. + """ + if key not in ["a", "b", "c"]: + raise ValueError(f"Invalid button key: {key}. Valid keys are 'a', 'b', 'c'.") + self._additional_callbacks[key] = func + + def advance(self) -> torch.Tensor: + """Provides the result from Haply device state. + + Returns: + torch.Tensor: A tensor containing the raw device data: + - 10 elements: [x, y, z, qx, qy, qz, qw, button_a, button_b, button_c] + where (x, y, z) is position, (qx, qy, qz, qw) is quaternion orientation, + and buttons are 1.0 (pressed) or 0.0 (not pressed) + """ + with self.data_lock: + if not (self.cached_data["inverse3_connected"] and self.cached_data["versegrip_connected"]): + raise RuntimeError("Haply devices not connected. Both Inverse3 and VerseGrip must be connected.") + + # Safe copy within lock + position = self.cached_data["position"].copy() * self.pos_sensitivity + quaternion = self.cached_data["quaternion"].copy() + button_a = self.cached_data["buttons"].get("a", False) + button_b = self.cached_data["buttons"].get("b", False) + button_c = self.cached_data["buttons"].get("c", False) + + # Button callbacks execute OUTSIDE lock to prevent deadlock + for button_key, current_state in [("a", button_a), ("b", button_b), ("c", button_c)]: + prev_state = self._prev_buttons.get(button_key, False) + + if current_state and not prev_state: + if button_key in self._additional_callbacks: + self._additional_callbacks[button_key]() + + self._prev_buttons[button_key] = current_state + + button_states = np.array( + [ + 1.0 if button_a else 0.0, + 1.0 if button_b else 0.0, + 1.0 if button_c else 0.0, + ], + dtype=np.float32, + ) + + # Construct command tensor: [position(3), quaternion(4), buttons(3)] + command = np.concatenate([position, quaternion, button_states]) + + return torch.tensor(command, dtype=torch.float32, device=self._sim_device) + + def push_force(self, forces: torch.Tensor, position: torch.Tensor) -> None: + """Push force vector to Haply Inverse3 device. + + Overrides DeviceBase.push_force() to provide force feedback for Haply Inverse3. + Forces are clipped to [-limit_force, limit_force] range for safety. + + Args: + forces: Tensor of shape (N, 3) with forces [fx, fy, fz]. + position: Tensor of shape (N) with indices specifying which forces to use. + """ + # Check if forces is empty + if forces.shape[0] == 0: + raise ValueError("No forces provided") + + # Select forces using position indices + selected_forces = forces[position] if position.ndim > 0 else forces[position].unsqueeze(0) + force = selected_forces.sum(dim=0) + force = force.cpu().numpy() if force.is_cuda else force.numpy() + + fx = np.clip(force[0], -self.limit_force, self.limit_force) + fy = np.clip(force[1], -self.limit_force, self.limit_force) + fz = np.clip(force[2], -self.limit_force, self.limit_force) + + with self.force_lock: + self.feedback_force = {"x": float(fx), "y": float(fy), "z": float(fz)} + + def _start_websocket_thread(self): + """Start WebSocket connection thread.""" + + def websocket_thread(): + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + loop.run_until_complete(self._websocket_loop()) + + self._websocket_thread = threading.Thread(target=websocket_thread, daemon=False) + self._websocket_thread.start() + + async def _websocket_loop(self): + """WebSocket data reading and writing loop.""" + while self.running: + try: + async with websockets.connect(self.websocket_uri, ping_interval=None, ping_timeout=None) as ws: + first_message = True + + while self.running: + try: + response = await asyncio.wait_for(ws.recv(), timeout=1.0) + data = json.loads(response) + + self.consecutive_timeouts = 0 + if self.timeout_warning_issued: + self.timeout_warning_issued = False + + # Safe array access - no IndexError risk with ternary operator + inverse3_list = data.get("inverse3", []) + verse_grip_list = data.get("wireless_verse_grip", []) + inverse3_data = inverse3_list[0] if inverse3_list else {} + verse_grip_data = verse_grip_list[0] if verse_grip_list else {} + + if first_message: + first_message = False + if inverse3_data: + self.inverse3_device_id = inverse3_data.get("device_id") + if verse_grip_data: + self.verse_grip_device_id = verse_grip_data.get("device_id") + + with self.data_lock: + inverse3_connected = False + versegrip_connected = False + + if inverse3_data and "state" in inverse3_data: + cursor_pos = inverse3_data["state"].get("cursor_position", {}) + if cursor_pos: + self.cached_data["position"] = np.array( + [cursor_pos.get(k, 0.0) for k in ("x", "y", "z")], dtype=np.float32 + ) + inverse3_connected = True + + if verse_grip_data and "state" in verse_grip_data: + state = verse_grip_data["state"] + self.cached_data["buttons"] = { + k: state.get("buttons", {}).get(k, False) for k in ("a", "b", "c") + } + orientation = state.get("orientation", {}) + if orientation: + self.cached_data["quaternion"] = np.array( + [ + orientation.get(k, 1.0 if k == "w" else 0.0) + for k in ("x", "y", "z", "w") + ], + dtype=np.float32, + ) + versegrip_connected = True + + self.cached_data["inverse3_connected"] = inverse3_connected + self.cached_data["versegrip_connected"] = versegrip_connected + # Both devices required (AND logic): Inverse3 for position/force, + both_connected = inverse3_connected and versegrip_connected + + with self._connected_lock: + self.connected = both_connected + + # Send force feedback + if self.inverse3_device_id: + with self.force_lock: + current_force = self.feedback_force.copy() + + request_msg = { + "inverse3": [ + { + "device_id": self.inverse3_device_id, + "commands": {"set_cursor_force": {"values": current_force}}, + } + ] + } + await ws.send(json.dumps(request_msg)) + + await asyncio.sleep(1.0 / self.data_rate) + + except asyncio.TimeoutError: + self.consecutive_timeouts += 1 + + # Check if timeout + if ( + self.consecutive_timeouts >= self.max_consecutive_timeouts + and not self.timeout_warning_issued + ): + self.timeout_warning_issued = True + with self.data_lock: + self.cached_data["inverse3_connected"] = False + self.cached_data["versegrip_connected"] = False + with self._connected_lock: + self.connected = False + continue + except Exception as e: + print(f"[ERROR] Error in WebSocket receive loop: {e}") + break + + except Exception: + with self.data_lock: + self.cached_data["inverse3_connected"] = False + self.cached_data["versegrip_connected"] = False + with self._connected_lock: + self.connected = False + self.consecutive_timeouts = 0 + self.timeout_warning_issued = False + + if self.running: + await asyncio.sleep(2.0) + else: + break + + +@configclass +class HaplyDeviceCfg(DeviceCfg): + """Configuration for Haply device. + + Attributes: + websocket_uri: WebSocket URI for Haply SDK connection + pos_sensitivity: Position sensitivity scaling factor + data_rate: Data exchange rate in Hz + limit_force: Maximum force magnitude in Newtons (safety limit) + """ + + websocket_uri: str = "ws://localhost:10001" + pos_sensitivity: float = 1.0 + data_rate: float = 200.0 + limit_force: float = 2.0 + class_type: type[DeviceBase] = HaplyDevice diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a91b84fdd1f2d172574fa875aae1c71e7ae2f9 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Keyboard device for SE(2) and SE(3) control.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4d4f0f86906201cb924b38a4ae0d6847f4b97e5c --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__init__.pyi @@ -0,0 +1,16 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "Se2Keyboard", + "Se2KeyboardCfg", + "Se3Keyboard", + "Se3KeyboardCfg", +] + +from .se2_keyboard import Se2Keyboard +from .se2_keyboard_cfg import Se2KeyboardCfg +from .se3_keyboard import Se3Keyboard +from .se3_keyboard_cfg import Se3KeyboardCfg diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/__init__.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efcb591967ef40de31aed4392397a8d8faf982cd Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/se2_keyboard.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/se2_keyboard.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54f7e52fe7edfa0fa13692a81433b2e0ac34cea5 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/se2_keyboard.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/se2_keyboard_cfg.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/se2_keyboard_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03d67a123ae474c147b9de1228d2ac510fb19b2c Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/se2_keyboard_cfg.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/se3_keyboard.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/se3_keyboard.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..969a9d60cca71d301a9cbb0876ed6c00fab4381d Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/se3_keyboard.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/se3_keyboard_cfg.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/se3_keyboard_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0da979f1db1367a5da72c89f3e8a30b64499937 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/__pycache__/se3_keyboard_cfg.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/se2_keyboard.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/se2_keyboard.py new file mode 100644 index 0000000000000000000000000000000000000000..25563e925e9aac8a0f6a89471779c8c235dcea7c --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/se2_keyboard.py @@ -0,0 +1,177 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Keyboard controller for SE(2) control.""" + +from __future__ import annotations + +import weakref +from collections.abc import Callable +from typing import TYPE_CHECKING + +import numpy as np +import torch + +import carb +import omni + +from ..device_base import DeviceBase + +if TYPE_CHECKING: + from .se2_keyboard_cfg import Se2KeyboardCfg + + +class Se2Keyboard(DeviceBase): + r"""A keyboard controller for sending SE(2) commands as velocity commands. + + This class is designed to provide a keyboard controller for mobile base (such as quadrupeds). + It uses the Omniverse keyboard interface to listen to keyboard events and map them to robot's + task-space commands. + + The command comprises of the base linear and angular velocity: :math:`(v_x, v_y, \omega_z)`. + + Key bindings: + ====================== ========================= ======================== + Command Key (+ve axis) Key (-ve axis) + ====================== ========================= ======================== + Move along x-axis Numpad 8 / Arrow Up Numpad 2 / Arrow Down + Move along y-axis Numpad 4 / Arrow Right Numpad 6 / Arrow Left + Rotate along z-axis Numpad 7 / Z Numpad 9 / X + ====================== ========================= ======================== + + .. seealso:: + + The official documentation for the keyboard interface: `Carb Keyboard Interface `__. + + """ + + def __init__(self, cfg: Se2KeyboardCfg): + """Initialize the keyboard layer. + + Args: + v_x_sensitivity: Magnitude of linear velocity along x-direction scaling. Defaults to 0.8. + v_y_sensitivity: Magnitude of linear velocity along y-direction scaling. Defaults to 0.4. + omega_z_sensitivity: Magnitude of angular velocity along z-direction scaling. Defaults to 1.0. + """ + # store inputs + self.v_x_sensitivity = cfg.v_x_sensitivity + self.v_y_sensitivity = cfg.v_y_sensitivity + self.omega_z_sensitivity = cfg.omega_z_sensitivity + self._sim_device = cfg.sim_device + + # acquire omniverse interfaces + self._appwindow = omni.appwindow.get_default_app_window() + self._input = carb.input.acquire_input_interface() + self._keyboard = self._appwindow.get_keyboard() + # note: Use weakref on callbacks to ensure that this object can be deleted when its destructor is called + self._keyboard_sub = self._input.subscribe_to_keyboard_events( + self._keyboard, + lambda event, *args, obj=weakref.proxy(self): obj._on_keyboard_event(event, *args), + ) + # bindings for keyboard to command + self._create_key_bindings() + # command buffers + self._base_command = np.zeros(3) + # dictionary for additional callbacks + self._additional_callbacks = dict() + + def __del__(self): + """Release the keyboard interface.""" + self._input.unsubscribe_to_keyboard_events(self._keyboard, self._keyboard_sub) + self._keyboard_sub = None + + def __str__(self) -> str: + """Returns: A string containing the information of joystick.""" + msg = f"Keyboard Controller for SE(2): {self.__class__.__name__}\n" + msg += f"\tKeyboard name: {self._input.get_keyboard_name(self._keyboard)}\n" + msg += "\t----------------------------------------------\n" + msg += "\tReset all commands: L\n" + msg += "\tMove forward (along x-axis): Numpad 8 / Arrow Up\n" + msg += "\tMove backward (along x-axis): Numpad 2 / Arrow Down\n" + msg += "\tMove right (along y-axis): Numpad 4 / Arrow Right\n" + msg += "\tMove left (along y-axis): Numpad 6 / Arrow Left\n" + msg += "\tYaw positively (along z-axis): Numpad 7 / Z\n" + msg += "\tYaw negatively (along z-axis): Numpad 9 / X" + return msg + + """ + Operations + """ + + def reset(self): + # default flags + self._base_command.fill(0.0) + + def add_callback(self, key: str, func: Callable): + """Add additional functions to bind keyboard. + + A list of available keys are present in the + `carb documentation `__. + + Args: + key: The keyboard button to check against. + func: The function to call when key is pressed. The callback function should not + take any arguments. + """ + self._additional_callbacks[key] = func + + def advance(self) -> torch.Tensor: + """Provides the result from keyboard event state. + + Returns: + Tensor containing the linear (x,y) and angular velocity (z). + """ + return torch.tensor(self._base_command, dtype=torch.float32, device=self._sim_device) + + """ + Internal helpers. + """ + + def _on_keyboard_event(self, event, *args, **kwargs): + """Subscriber callback to when kit is updated. + + Reference: + https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref/input-devices/keyboard.html + """ + # apply the command when pressed + if event.type == carb.input.KeyboardEventType.KEY_PRESS: + if event.input.name == "L": + self.reset() + elif event.input.name in self._INPUT_KEY_MAPPING: + self._base_command += self._INPUT_KEY_MAPPING[event.input.name] + # remove the command when un-pressed + if event.type == carb.input.KeyboardEventType.KEY_RELEASE: + if event.input.name in self._INPUT_KEY_MAPPING: + self._base_command -= self._INPUT_KEY_MAPPING[event.input.name] + # additional callbacks + if event.type == carb.input.KeyboardEventType.KEY_PRESS: + if event.input.name in self._additional_callbacks: + self._additional_callbacks[event.input.name]() + + # since no error, we are fine :) + return True + + def _create_key_bindings(self): + """Creates default key binding.""" + self._INPUT_KEY_MAPPING = { + # forward command + "NUMPAD_8": np.asarray([1.0, 0.0, 0.0]) * self.v_x_sensitivity, + "UP": np.asarray([1.0, 0.0, 0.0]) * self.v_x_sensitivity, + # back command + "NUMPAD_2": np.asarray([-1.0, 0.0, 0.0]) * self.v_x_sensitivity, + "DOWN": np.asarray([-1.0, 0.0, 0.0]) * self.v_x_sensitivity, + # right command + "NUMPAD_4": np.asarray([0.0, 1.0, 0.0]) * self.v_y_sensitivity, + "LEFT": np.asarray([0.0, 1.0, 0.0]) * self.v_y_sensitivity, + # left command + "NUMPAD_6": np.asarray([0.0, -1.0, 0.0]) * self.v_y_sensitivity, + "RIGHT": np.asarray([0.0, -1.0, 0.0]) * self.v_y_sensitivity, + # yaw command (positive) + "NUMPAD_7": np.asarray([0.0, 0.0, 1.0]) * self.omega_z_sensitivity, + "Z": np.asarray([0.0, 0.0, 1.0]) * self.omega_z_sensitivity, + # yaw command (negative) + "NUMPAD_9": np.asarray([0.0, 0.0, -1.0]) * self.omega_z_sensitivity, + "X": np.asarray([0.0, 0.0, -1.0]) * self.omega_z_sensitivity, + } diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/se2_keyboard_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/se2_keyboard_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..0e3679f82b3139e7417e9876733d23bcef10de60 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/se2_keyboard_cfg.py @@ -0,0 +1,27 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for SE(2) keyboard controller.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.configclass import configclass + +from ..device_base import DeviceCfg + +if TYPE_CHECKING: + from .se2_keyboard import Se2Keyboard + + +@configclass +class Se2KeyboardCfg(DeviceCfg): + """Configuration for SE2 keyboard devices.""" + + v_x_sensitivity: float = 0.8 + v_y_sensitivity: float = 0.4 + omega_z_sensitivity: float = 1.0 + class_type: type[Se2Keyboard] | str = "{DIR}.se2_keyboard:Se2Keyboard" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/se3_keyboard.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/se3_keyboard.py new file mode 100644 index 0000000000000000000000000000000000000000..20e6dccf71740bd6f92db799e809314b9af0365e --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/se3_keyboard.py @@ -0,0 +1,204 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Keyboard controller for SE(3) control.""" + +from __future__ import annotations + +import weakref +from collections.abc import Callable +from typing import TYPE_CHECKING + +import numpy as np +import torch +from scipy.spatial.transform import Rotation + +import carb +import omni + +from ..device_base import DeviceBase + +if TYPE_CHECKING: + from .se3_keyboard_cfg import Se3KeyboardCfg + + +class Se3Keyboard(DeviceBase): + """A keyboard controller for sending SE(3) commands as delta poses and binary command (open/close). + + This class is designed to provide a keyboard controller for a robotic arm with a gripper. + It uses the Omniverse keyboard interface to listen to keyboard events and map them to robot's + task-space commands. + + The command comprises of two parts: + + * delta pose: a 6D vector of (x, y, z, roll, pitch, yaw) in meters and radians. + * gripper: a binary command to open or close the gripper. + + Key bindings: + ============================== ================= ================= + Description Key (+ve axis) Key (-ve axis) + ============================== ================= ================= + Toggle gripper (open/close) K + Move along x-axis W S + Move along y-axis A D + Move along z-axis Q E + Rotate along x-axis Z X + Rotate along y-axis T G + Rotate along z-axis C V + ============================== ================= ================= + + .. seealso:: + + The official documentation for the keyboard interface: `Carb Keyboard Interface `__. + + """ + + def __init__(self, cfg: Se3KeyboardCfg): + """Initialize the keyboard layer. + + Args: + cfg: Configuration object for keyboard settings. + """ + # store inputs + self.pos_sensitivity = cfg.pos_sensitivity + self.rot_sensitivity = cfg.rot_sensitivity + self.gripper_term = cfg.gripper_term + self._sim_device = cfg.sim_device + # acquire omniverse interfaces + self._appwindow = omni.appwindow.get_default_app_window() + self._input = carb.input.acquire_input_interface() + self._keyboard = self._appwindow.get_keyboard() + # note: Use weakref on callbacks to ensure that this object can be deleted when its destructor is called. + self._keyboard_sub = self._input.subscribe_to_keyboard_events( + self._keyboard, + lambda event, *args, obj=weakref.proxy(self): obj._on_keyboard_event(event, *args), + ) + # bindings for keyboard to command + self._create_key_bindings() + # command buffers + self._close_gripper = False + self._delta_pos = np.zeros(3) # (x, y, z) + self._delta_rot = np.zeros(3) # (roll, pitch, yaw) + # dictionary for additional callbacks + self._additional_callbacks = dict() + + def __del__(self): + """Release the keyboard interface.""" + self._input.unsubscribe_to_keyboard_events(self._keyboard, self._keyboard_sub) + self._keyboard_sub = None + + def __str__(self) -> str: + """Returns: A string containing the information of joystick.""" + msg = f"Keyboard Controller for SE(3): {self.__class__.__name__}\n" + msg += f"\tKeyboard name: {self._input.get_keyboard_name(self._keyboard)}\n" + msg += "\t----------------------------------------------\n" + msg += "\tToggle gripper (open/close): K\n" + msg += "\tMove arm along x-axis: W/S\n" + msg += "\tMove arm along y-axis: A/D\n" + msg += "\tMove arm along z-axis: Q/E\n" + msg += "\tRotate arm along x-axis: Z/X\n" + msg += "\tRotate arm along y-axis: T/G\n" + msg += "\tRotate arm along z-axis: C/V" + return msg + + """ + Operations + """ + + def reset(self): + # default flags + self._close_gripper = False + self._delta_pos = np.zeros(3) # (x, y, z) + self._delta_rot = np.zeros(3) # (roll, pitch, yaw) + + def add_callback(self, key: str, func: Callable): + """Add additional functions to bind keyboard. + + A list of available keys are present in the + `carb documentation `__. + + Args: + key: The keyboard button to check against. + func: The function to call when key is pressed. The callback function should not + take any arguments. + """ + self._additional_callbacks[key] = func + + def advance(self) -> torch.Tensor: + """Provides the result from keyboard event state. + + Returns: + torch.Tensor: A 7-element tensor containing: + - delta pose: First 6 elements as [x, y, z, rx, ry, rz] in meters and radians. + - gripper command: Last element as a binary value (+1.0 for open, -1.0 for close). + """ + # convert to rotation vector + rot_vec = Rotation.from_euler("XYZ", self._delta_rot).as_rotvec() + # return the command and gripper state + command = np.concatenate([self._delta_pos, rot_vec]) + if self.gripper_term: + gripper_value = -1.0 if self._close_gripper else 1.0 + command = np.append(command, gripper_value) + + return torch.tensor(command, dtype=torch.float32, device=self._sim_device) + + """ + Internal helpers. + """ + + def _on_keyboard_event(self, event, *args, **kwargs): + """Subscriber callback to when kit is updated. + + Reference: + https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref/input-devices/keyboard.html + """ + # apply the command when pressed + if event.type == carb.input.KeyboardEventType.KEY_PRESS: + if event.input.name == "L": + self.reset() + if event.input.name == "K": + self._close_gripper = not self._close_gripper + elif event.input.name in ["W", "S", "A", "D", "Q", "E"]: + self._delta_pos += self._INPUT_KEY_MAPPING[event.input.name] + elif event.input.name in ["Z", "X", "T", "G", "C", "V"]: + self._delta_rot += self._INPUT_KEY_MAPPING[event.input.name] + # remove the command when un-pressed + if event.type == carb.input.KeyboardEventType.KEY_RELEASE: + if event.input.name in ["W", "S", "A", "D", "Q", "E"]: + self._delta_pos -= self._INPUT_KEY_MAPPING[event.input.name] + elif event.input.name in ["Z", "X", "T", "G", "C", "V"]: + self._delta_rot -= self._INPUT_KEY_MAPPING[event.input.name] + # additional callbacks + if event.type == carb.input.KeyboardEventType.KEY_PRESS: + if event.input.name in self._additional_callbacks: + self._additional_callbacks[event.input.name]() + + # since no error, we are fine :) + return True + + def _create_key_bindings(self): + """Creates default key binding.""" + self._INPUT_KEY_MAPPING = { + # toggle: gripper command + "K": True, + # x-axis (forward) + "W": np.asarray([1.0, 0.0, 0.0]) * self.pos_sensitivity, + "S": np.asarray([-1.0, 0.0, 0.0]) * self.pos_sensitivity, + # y-axis (left-right) + "A": np.asarray([0.0, 1.0, 0.0]) * self.pos_sensitivity, + "D": np.asarray([0.0, -1.0, 0.0]) * self.pos_sensitivity, + # z-axis (up-down) + "Q": np.asarray([0.0, 0.0, 1.0]) * self.pos_sensitivity, + "E": np.asarray([0.0, 0.0, -1.0]) * self.pos_sensitivity, + # roll (around x-axis) + "Z": np.asarray([1.0, 0.0, 0.0]) * self.rot_sensitivity, + "X": np.asarray([-1.0, 0.0, 0.0]) * self.rot_sensitivity, + # pitch (around y-axis) + "T": np.asarray([0.0, 1.0, 0.0]) * self.rot_sensitivity, + "G": np.asarray([0.0, -1.0, 0.0]) * self.rot_sensitivity, + # yaw (around z-axis) + "C": np.asarray([0.0, 0.0, 1.0]) * self.rot_sensitivity, + "V": np.asarray([0.0, 0.0, -1.0]) * self.rot_sensitivity, + } diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/se3_keyboard_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/se3_keyboard_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..5279dc82a124082e13424e4bda701ed84f53d5a2 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/keyboard/se3_keyboard_cfg.py @@ -0,0 +1,28 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for SE(3) keyboard controller.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.configclass import configclass + +from ..device_base import DeviceCfg + +if TYPE_CHECKING: + from .se3_keyboard import Se3Keyboard + + +@configclass +class Se3KeyboardCfg(DeviceCfg): + """Configuration for SE3 keyboard devices.""" + + gripper_term: bool = True + pos_sensitivity: float = 0.4 + rot_sensitivity: float = 0.8 + retargeters: None = None + class_type: type[Se3Keyboard] | str = "{DIR}.se3_keyboard:Se3Keyboard" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c6f0d4c36ffbffc4ff533f1985350a83aa3ab69 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/__init__.py @@ -0,0 +1,20 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""OpenXR teleoperation devices (legacy). + +.. deprecated:: + This package has moved to :mod:`isaaclab_teleop.deprecated.openxr`. + Please migrate to :mod:`isaaclab_teleop` which provides the + :class:`~isaaclab_teleop.IsaacTeleopDevice` as a replacement. + + Imports from this package will continue to work for backwards + compatibility. Individual class constructors emit + :class:`DeprecationWarning` at instantiation time. +""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4e27974b747cc5b191127393f58fb4ecfce7ac73 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/__init__.pyi @@ -0,0 +1,18 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "XrAnchorRotationMode", + "XrCfg", + "remove_camera_configs", + "ManusVive", + "ManusViveCfg", + "OpenXRDevice", + "OpenXRDeviceCfg", +] + +from .xr_cfg import XrAnchorRotationMode, XrCfg, remove_camera_configs +from .manus_vive import ManusVive, ManusViveCfg +from .openxr_device import OpenXRDevice, OpenXRDeviceCfg diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/common.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/common.py new file mode 100644 index 0000000000000000000000000000000000000000..03b9ac7aa1a3bfb821b425624484ee6f8ff5e996 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/common.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to :mod:`isaaclab_teleop.deprecated.openxr.common`.""" + +from isaaclab_teleop.deprecated.openxr.common import * # noqa: F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/manus_vive.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/manus_vive.py new file mode 100644 index 0000000000000000000000000000000000000000..11cc93211dbff150f43688a0a11b3c9f67fde5f7 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/manus_vive.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to :mod:`isaaclab_teleop.deprecated.openxr.manus_vive`.""" + +from isaaclab_teleop.deprecated.openxr.manus_vive import * # noqa: F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/manus_vive_utils.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/manus_vive_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..580564ee6fda5f7f9f9e6702bef1ad9b95aa9a4f --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/manus_vive_utils.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to :mod:`isaaclab_teleop.deprecated.openxr.manus_vive_utils`.""" + +from isaaclab_teleop.deprecated.openxr.manus_vive_utils import * # noqa: F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/openxr_device.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/openxr_device.py new file mode 100644 index 0000000000000000000000000000000000000000..5ec8deb2536335b360753419e4bf715357b37801 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/openxr_device.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to :mod:`isaaclab_teleop.deprecated.openxr.openxr_device`.""" + +from isaaclab_teleop.deprecated.openxr.openxr_device import * # noqa: F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85e47be523a637c4290dd21a8d05b5a4e5706532 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to :mod:`isaaclab_teleop.deprecated.openxr.retargeters`.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c094ea29539be6ecf22a7eecadf3ab11942664ce --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/__init__.pyi @@ -0,0 +1,6 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_teleop.deprecated.openxr.retargeters import * diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/fourier/data/configs/dex-retargeting/fourier_hand_left_dexpilot.yml b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/fourier/data/configs/dex-retargeting/fourier_hand_left_dexpilot.yml new file mode 100644 index 0000000000000000000000000000000000000000..1e203d11e7e864734f144d22378a164f3ec2349d --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/fourier/data/configs/dex-retargeting/fourier_hand_left_dexpilot.yml @@ -0,0 +1,30 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +retargeting: + finger_tip_link_names: + - GR1T2_fourier_hand_6dof_L_thumb_distal_link + - GR1T2_fourier_hand_6dof_L_index_intermediate_link + - GR1T2_fourier_hand_6dof_L_middle_intermediate_link + - GR1T2_fourier_hand_6dof_L_ring_intermediate_link + - GR1T2_fourier_hand_6dof_L_pinky_intermediate_link + low_pass_alpha: 0.2 + scaling_factor: 1.2 + target_joint_names: + - L_index_proximal_joint + - L_middle_proximal_joint + - L_pinky_proximal_joint + - L_ring_proximal_joint + - L_index_intermediate_joint + - L_middle_intermediate_joint + - L_pinky_intermediate_joint + - L_ring_intermediate_joint + - L_thumb_proximal_yaw_joint + - L_thumb_proximal_pitch_joint + - L_thumb_distal_joint + - L_thumb_distal_joint + type: DexPilot + urdf_path: /tmp/GR1_T2_left_hand.urdf + wrist_link_name: l_hand_base_link diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/fourier/data/configs/dex-retargeting/fourier_hand_right_dexpilot.yml b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/fourier/data/configs/dex-retargeting/fourier_hand_right_dexpilot.yml new file mode 100644 index 0000000000000000000000000000000000000000..f67041bd9b60c9571d88d2db21b962cc7aa8d398 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/fourier/data/configs/dex-retargeting/fourier_hand_right_dexpilot.yml @@ -0,0 +1,29 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +retargeting: + finger_tip_link_names: + - GR1T2_fourier_hand_6dof_R_thumb_distal_link + - GR1T2_fourier_hand_6dof_R_index_intermediate_link + - GR1T2_fourier_hand_6dof_R_middle_intermediate_link + - GR1T2_fourier_hand_6dof_R_ring_intermediate_link + - GR1T2_fourier_hand_6dof_R_pinky_intermediate_link + low_pass_alpha: 0.2 + scaling_factor: 1.2 + target_joint_names: + - R_index_proximal_joint + - R_middle_proximal_joint + - R_pinky_proximal_joint + - R_ring_proximal_joint + - R_index_intermediate_joint + - R_middle_intermediate_joint + - R_pinky_intermediate_joint + - R_ring_intermediate_joint + - R_thumb_proximal_yaw_joint + - R_thumb_proximal_pitch_joint + - R_thumb_distal_joint + type: DexPilot + urdf_path: /tmp/GR1_T2_right_hand.urdf + wrist_link_name: r_hand_base_link diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/fourier/gr1_t2_dex_retargeting_utils.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/fourier/gr1_t2_dex_retargeting_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0d8c0deb93c2184177530396b669d0d0f2a41dc5 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/fourier/gr1_t2_dex_retargeting_utils.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to ``isaaclab_teleop.deprecated.openxr``.""" + +from isaaclab_teleop.deprecated.openxr.retargeters.humanoid.fourier.gr1_t2_dex_retargeting_utils import * # noqa: E501,F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/fourier/gr1t2_retargeter.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/fourier/gr1t2_retargeter.py new file mode 100644 index 0000000000000000000000000000000000000000..63929884c50d73820d6be5b4ee020a970cbd0d4d --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/fourier/gr1t2_retargeter.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to ``isaaclab_teleop.deprecated.openxr``.""" + +from isaaclab_teleop.deprecated.openxr.retargeters.humanoid.fourier.gr1t2_retargeter import * # noqa: F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/g1_lower_body_standing.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/g1_lower_body_standing.py new file mode 100644 index 0000000000000000000000000000000000000000..f548556a4a3ab1d8f435d160d3c63f20c73a4665 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/g1_lower_body_standing.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to ``isaaclab_teleop.deprecated.openxr``.""" + +from isaaclab_teleop.deprecated.openxr.retargeters.humanoid.unitree.g1_lower_body_standing import * # noqa: F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/g1_motion_controller_locomotion.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/g1_motion_controller_locomotion.py new file mode 100644 index 0000000000000000000000000000000000000000..d7514475f1e30239010a5067eae635ddc39d2ab2 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/g1_motion_controller_locomotion.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to ``isaaclab_teleop.deprecated.openxr``.""" + +from isaaclab_teleop.deprecated.openxr.retargeters.humanoid.unitree.g1_motion_controller_locomotion import * # noqa: E501,F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/inspire/data/configs/dex-retargeting/unitree_hand_left_dexpilot.yml b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/inspire/data/configs/dex-retargeting/unitree_hand_left_dexpilot.yml new file mode 100644 index 0000000000000000000000000000000000000000..de72352738fd2fb7366bf6f65091b05a8ef1d27b --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/inspire/data/configs/dex-retargeting/unitree_hand_left_dexpilot.yml @@ -0,0 +1,24 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +retargeting: + finger_tip_link_names: + - L_thumb_tip + - L_index_tip + - L_middle_tip + - L_ring_tip + - L_pinky_tip + low_pass_alpha: 0.2 + scaling_factor: 1.2 + target_joint_names: + - L_thumb_proximal_yaw_joint + - L_thumb_proximal_pitch_joint + - L_index_proximal_joint + - L_middle_proximal_joint + - L_ring_proximal_joint + - L_pinky_proximal_joint + type: DexPilot + urdf_path: /tmp/retarget_inspire_white_left_hand.urdf + wrist_link_name: L_hand_base_link diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/inspire/data/configs/dex-retargeting/unitree_hand_right_dexpilot.yml b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/inspire/data/configs/dex-retargeting/unitree_hand_right_dexpilot.yml new file mode 100644 index 0000000000000000000000000000000000000000..5d0406da4365b6534345c64ba839a326b0a91259 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/inspire/data/configs/dex-retargeting/unitree_hand_right_dexpilot.yml @@ -0,0 +1,24 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +retargeting: + finger_tip_link_names: + - R_thumb_tip + - R_index_tip + - R_middle_tip + - R_ring_tip + - R_pinky_tip + low_pass_alpha: 0.2 + scaling_factor: 1.2 + target_joint_names: + - R_thumb_proximal_yaw_joint + - R_thumb_proximal_pitch_joint + - R_index_proximal_joint + - R_middle_proximal_joint + - R_ring_proximal_joint + - R_pinky_proximal_joint + type: DexPilot + urdf_path: /tmp/retarget_inspire_white_right_hand.urdf + wrist_link_name: R_hand_base_link diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/inspire/g1_dex_retargeting_utils.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/inspire/g1_dex_retargeting_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0f37610e520304697671312cefe546b401c6f148 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/inspire/g1_dex_retargeting_utils.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to ``isaaclab_teleop.deprecated.openxr``.""" + +from isaaclab_teleop.deprecated.openxr.retargeters.humanoid.unitree.inspire.g1_dex_retargeting_utils import * # noqa: E501,F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/inspire/g1_upper_body_retargeter.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/inspire/g1_upper_body_retargeter.py new file mode 100644 index 0000000000000000000000000000000000000000..faee3be1a34184dc749dc24590843d7c1e61e629 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/inspire/g1_upper_body_retargeter.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to ``isaaclab_teleop.deprecated.openxr``.""" + +from isaaclab_teleop.deprecated.openxr.retargeters.humanoid.unitree.inspire.g1_upper_body_retargeter import * # noqa: E501,F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/data/configs/dex-retargeting/g1_hand_left_dexpilot.yml b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/data/configs/dex-retargeting/g1_hand_left_dexpilot.yml new file mode 100644 index 0000000000000000000000000000000000000000..0f9f5416e1ca66e089b78fb7c68c81ccb3642475 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/data/configs/dex-retargeting/g1_hand_left_dexpilot.yml @@ -0,0 +1,23 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +retargeting: + finger_tip_link_names: + - thumb_tip + - index_tip + - middle_tip + low_pass_alpha: 0.2 + scaling_factor: 1.0 + target_joint_names: + - left_hand_thumb_0_joint + - left_hand_thumb_1_joint + - left_hand_thumb_2_joint + - left_hand_middle_0_joint + - left_hand_middle_1_joint + - left_hand_index_0_joint + - left_hand_index_1_joint + type: DexPilot + urdf_path: /tmp/G1_left_hand.urdf + wrist_link_name: base_link diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/data/configs/dex-retargeting/g1_hand_right_dexpilot.yml b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/data/configs/dex-retargeting/g1_hand_right_dexpilot.yml new file mode 100644 index 0000000000000000000000000000000000000000..3908adcce0f6fa6c3b3d2286ae1967c010d935b1 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/data/configs/dex-retargeting/g1_hand_right_dexpilot.yml @@ -0,0 +1,23 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +retargeting: + finger_tip_link_names: + - thumb_tip + - index_tip + - middle_tip + low_pass_alpha: 0.2 + scaling_factor: 1.0 + target_joint_names: + - right_hand_thumb_0_joint + - right_hand_thumb_1_joint + - right_hand_thumb_2_joint + - right_hand_middle_0_joint + - right_hand_middle_1_joint + - right_hand_index_0_joint + - right_hand_index_1_joint + type: DexPilot + urdf_path: /tmp/G1_right_hand.urdf + wrist_link_name: base_link diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/g1_dex_retargeting_utils.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/g1_dex_retargeting_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bb9975b4a61579c119c70f7f38384790ef4bc6ae --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/g1_dex_retargeting_utils.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to ``isaaclab_teleop.deprecated.openxr``.""" + +from isaaclab_teleop.deprecated.openxr.retargeters.humanoid.unitree.trihand.g1_dex_retargeting_utils import * # noqa: E501,F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/g1_upper_body_motion_ctrl_gripper.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/g1_upper_body_motion_ctrl_gripper.py new file mode 100644 index 0000000000000000000000000000000000000000..dea31919b7476d77e420ceb7e0c4d888377eb242 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/g1_upper_body_motion_ctrl_gripper.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to ``isaaclab_teleop.deprecated.openxr``.""" + +from isaaclab_teleop.deprecated.openxr.retargeters.humanoid.unitree.trihand.g1_upper_body_motion_ctrl_gripper import * # noqa: E501,F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/g1_upper_body_motion_ctrl_retargeter.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/g1_upper_body_motion_ctrl_retargeter.py new file mode 100644 index 0000000000000000000000000000000000000000..f415f2de86fcdd17006d6542bd347dd4c054def6 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/g1_upper_body_motion_ctrl_retargeter.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to ``isaaclab_teleop.deprecated.openxr``.""" + +from isaaclab_teleop.deprecated.openxr.retargeters.humanoid.unitree.trihand.g1_upper_body_motion_ctrl_retargeter import * # noqa: E501,F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/g1_upper_body_retargeter.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/g1_upper_body_retargeter.py new file mode 100644 index 0000000000000000000000000000000000000000..d3c41e66a9dfb654c7367032521a4a400a038ce8 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/humanoid/unitree/trihand/g1_upper_body_retargeter.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to ``isaaclab_teleop.deprecated.openxr``.""" + +from isaaclab_teleop.deprecated.openxr.retargeters.humanoid.unitree.trihand.g1_upper_body_retargeter import * # noqa: E501,F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cc18f59367d3632155381e918ed800613e4d2bda --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to :mod:`isaaclab_teleop.deprecated.openxr.retargeters.manipulator`.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5895081bca646ba06f611337e1b3c5b800e912c7 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/__init__.pyi @@ -0,0 +1,6 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_teleop.deprecated.openxr.retargeters.manipulator import * diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/gripper_retargeter.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/gripper_retargeter.py new file mode 100644 index 0000000000000000000000000000000000000000..b3ac43b67ae06a03a42cd5aeacfd739ba136db03 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/gripper_retargeter.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to :mod:`isaaclab_teleop.deprecated.openxr.retargeters.manipulator.gripper_retargeter`.""" + +from isaaclab_teleop.deprecated.openxr.retargeters.manipulator.gripper_retargeter import * # noqa: F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/se3_abs_retargeter.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/se3_abs_retargeter.py new file mode 100644 index 0000000000000000000000000000000000000000..84fd44ffc2ede5bf3a3087f8d0c5270b2c64db14 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/se3_abs_retargeter.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to :mod:`isaaclab_teleop.deprecated.openxr.retargeters.manipulator.se3_abs_retargeter`.""" + +from isaaclab_teleop.deprecated.openxr.retargeters.manipulator.se3_abs_retargeter import * # noqa: F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/se3_rel_retargeter.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/se3_rel_retargeter.py new file mode 100644 index 0000000000000000000000000000000000000000..b93ccef8673b99072669b9c9e8f9f3d1cdddfb39 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/retargeters/manipulator/se3_rel_retargeter.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to :mod:`isaaclab_teleop.deprecated.openxr.retargeters.manipulator.se3_rel_retargeter`.""" + +from isaaclab_teleop.deprecated.openxr.retargeters.manipulator.se3_rel_retargeter import * # noqa: F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/xr_anchor_utils.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/xr_anchor_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4ff82f1eb3417f097bfc4e92b0c7474155df041e --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/xr_anchor_utils.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to :mod:`isaaclab_teleop.xr_anchor_utils`.""" + +from isaaclab_teleop.xr_anchor_utils import * # noqa: F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/xr_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/xr_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..ca98273452dc3aa2895111acd00c96bb608970e1 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/openxr/xr_cfg.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""".. deprecated:: Moved to :mod:`isaaclab_teleop.xr_cfg`.""" + +from isaaclab_teleop.xr_cfg import * # noqa: F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/retargeter_base.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/retargeter_base.py new file mode 100644 index 0000000000000000000000000000000000000000..e474cb620870aa01842a9cec07f203332133e578 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/retargeter_base.py @@ -0,0 +1,94 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +"""Base classes for legacy retargeting. + +.. deprecated:: + :class:`RetargeterBase` and :class:`RetargeterCfg` are deprecated. + Please use the IsaacTeleop retargeting engine via :mod:`isaaclab_teleop` + instead. See :class:`isaaclab_teleop.IsaacTeleopCfg` for pipeline-based + retargeting configuration. +""" + +import warnings +from abc import ABC, abstractmethod +from enum import Enum +from typing import Any + +from isaaclab.utils.configclass import configclass + + +@configclass +class RetargeterCfg: + """Base configuration for hand tracking retargeters. + + .. deprecated:: + Use the IsaacTeleop retargeting engine via :mod:`isaaclab_teleop` instead. + """ + + sim_device: str = "cpu" + # Concrete retargeter class to construct for this config. Set by each retargeter module. + retargeter_type: type[RetargeterBase] | None = None + + +class RetargeterBase(ABC): + """Base interface for input data retargeting. + + .. deprecated:: + Use the IsaacTeleop retargeting engine via :mod:`isaaclab_teleop` instead. + + This abstract class defines the interface for components that transform + raw device data into robot control commands. Implementations can handle + various types of transformations including: + - Hand joint data to end-effector poses + - Input device commands to robot movements + - Sensor data to control signals + """ + + def __init__(self, cfg: RetargeterCfg): + """Initialize the retargeter. + + Args: + cfg: Configuration for the retargeter + """ + warnings.warn( + "RetargeterBase is deprecated. Please use the IsaacTeleop retargeting engine via isaaclab_teleop instead.", + DeprecationWarning, + stacklevel=2, + ) + self._sim_device = cfg.sim_device + + class Requirement(Enum): + """Features a retargeter may require from a device's raw data feed.""" + + HAND_TRACKING = "hand_tracking" + HEAD_TRACKING = "head_tracking" + MOTION_CONTROLLER = "motion_controller" + + @abstractmethod + def retarget(self, data: Any) -> Any: + """Retarget input data to desired output format. + + Args: + data: Raw input data to be transformed + + Returns: + Retargeted data in implementation-specific format + """ + pass + + def get_requirements(self) -> list[RetargeterBase.Requirement]: + """Return the list of required data features for this retargeter. + + Defaults to requesting all available features for backward compatibility. + Implementations should override to narrow to only what they need. + """ + return [ + RetargeterBase.Requirement.HAND_TRACKING, + RetargeterBase.Requirement.HEAD_TRACKING, + RetargeterBase.Requirement.MOTION_CONTROLLER, + ] diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6f792b31546ce870f5b0e2f831c15699708971f0 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Spacemouse device for SE(2) and SE(3) control.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c0be51fd4b9700539225bb545279821ca0d84f48 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/__init__.pyi @@ -0,0 +1,16 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "Se2SpaceMouse", + "Se2SpaceMouseCfg", + "Se3SpaceMouse", + "Se3SpaceMouseCfg", +] + +from .se2_spacemouse import Se2SpaceMouse +from .se2_spacemouse_cfg import Se2SpaceMouseCfg +from .se3_spacemouse import Se3SpaceMouse +from .se3_spacemouse_cfg import Se3SpaceMouseCfg diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/se2_spacemouse.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/se2_spacemouse.py new file mode 100644 index 0000000000000000000000000000000000000000..07d26f66bd08005752638506183e6c9cfcb40724 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/se2_spacemouse.py @@ -0,0 +1,166 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Spacemouse controller for SE(2) control.""" + +from __future__ import annotations + +import threading +import time +from collections.abc import Callable +from typing import TYPE_CHECKING + +import hid +import numpy as np +import torch + +from isaaclab.utils.array import convert_to_torch + +from ..device_base import DeviceBase +from .utils import convert_buffer + +if TYPE_CHECKING: + from .se2_spacemouse_cfg import Se2SpaceMouseCfg + + +class Se2SpaceMouse(DeviceBase): + r"""A space-mouse controller for sending SE(2) commands as delta poses. + + This class implements a space-mouse controller to provide commands to mobile base. + It uses the `HID-API`_ which interfaces with USD and Bluetooth HID-class devices across multiple platforms. + + The command comprises of the base linear and angular velocity: :math:`(v_x, v_y, \omega_z)`. + + Note: + The interface finds and uses the first supported device connected to the computer. + + Currently tested for following devices: + + - SpaceMouse Compact: https://3dconnexion.com/de/product/spacemouse-compact/ + + .. _HID-API: https://github.com/libusb/hidapi + + """ + + def __init__(self, cfg: Se2SpaceMouseCfg): + """Initialize the spacemouse layer. + + Args: + cfg: Configuration for the spacemouse device. + """ + # store inputs + self.v_x_sensitivity = cfg.v_x_sensitivity + self.v_y_sensitivity = cfg.v_y_sensitivity + self.omega_z_sensitivity = cfg.omega_z_sensitivity + self._sim_device = cfg.sim_device + # acquire device interface + self._device = hid.device() + self._find_device() + # command buffers + self._base_command = np.zeros(3) + # dictionary for additional callbacks + self._additional_callbacks = dict() + # run a thread for listening to device updates + self._thread = threading.Thread(target=self._run_device) + self._thread.daemon = True + self._thread.start() + + def __del__(self): + """Destructor for the class.""" + self._thread.join() + + def __str__(self) -> str: + """Returns: A string containing the information of joystick.""" + msg = f"Spacemouse Controller for SE(2): {self.__class__.__name__}\n" + msg += f"\tManufacturer: {self._device.get_manufacturer_string()}\n" + msg += f"\tProduct: {self._device.get_product_string()}\n" + msg += "\t----------------------------------------------\n" + msg += "\tRight button: reset command\n" + msg += "\tMove mouse laterally: move base horizontally in x-y plane\n" + msg += "\tTwist mouse about z-axis: yaw base about a corresponding axis" + return msg + + """ + Operations + """ + + def reset(self): + # default flags + self._base_command.fill(0.0) + + def add_callback(self, key: str, func: Callable): + """Add additional functions to bind spacemouse. + + Args: + key: The keyboard button to check against. + func: The function to call when key is pressed. The callback function should not + take any arguments. + """ + self._additional_callbacks[key] = func + + def advance(self) -> torch.Tensor: + """Provides the result from spacemouse event state. + + Returns: + A 3D tensor containing the linear (x,y) and angular velocity (z). + """ + return convert_to_torch(self._base_command, device=self._sim_device) + + """ + Internal helpers. + """ + + def _find_device(self): + """Find the device connected to computer.""" + found = False + # implement a timeout for device search + for _ in range(5): + for device in hid.enumerate(): + if device["product_string"] == "SpaceMouse Compact": + # set found flag + found = True + vendor_id = device["vendor_id"] + product_id = device["product_id"] + # connect to the device + self._device.open(vendor_id, product_id) + # check if device found + if not found: + time.sleep(1.0) + else: + break + # no device found: return false + if not found: + raise OSError("No device found by SpaceMouse. Is the device connected?") + + def _run_device(self): + """Listener thread that keeps pulling new messages.""" + # keep running + while True: + # read the device data + data = self._device.read(13) + if data is not None: + # readings from 6-DoF sensor + if data[0] == 1: + # along y-axis + self._base_command[1] = self.v_y_sensitivity * convert_buffer(data[1], data[2]) + # along x-axis + self._base_command[0] = self.v_x_sensitivity * convert_buffer(data[3], data[4]) + elif data[0] == 2: + # along z-axis + self._base_command[2] = self.omega_z_sensitivity * convert_buffer(data[3], data[4]) + # readings from the side buttons + elif data[0] == 3: + # press left button + if data[1] == 1: + # additional callbacks + if "L" in self._additional_callbacks: + self._additional_callbacks["L"] + # right button is for reset + if data[1] == 2: + # reset layer + self.reset() + # additional callbacks + if "R" in self._additional_callbacks: + self._additional_callbacks["R"] diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/se2_spacemouse_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/se2_spacemouse_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..1a287317a3ba16ffc984d43dd5bb8ae666c1de20 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/se2_spacemouse_cfg.py @@ -0,0 +1,27 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for SE(2) space mouse controller.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.configclass import configclass + +from ..device_base import DeviceCfg + +if TYPE_CHECKING: + from .se2_spacemouse import Se2SpaceMouse + + +@configclass +class Se2SpaceMouseCfg(DeviceCfg): + """Configuration for SE2 space mouse devices.""" + + v_x_sensitivity: float = 0.8 + v_y_sensitivity: float = 0.4 + omega_z_sensitivity: float = 1.0 + class_type: type[Se2SpaceMouse] | str = "{DIR}.se2_spacemouse:Se2SpaceMouse" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/se3_spacemouse.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/se3_spacemouse.py new file mode 100644 index 0000000000000000000000000000000000000000..7a4491f8c6102f1a22a473d529bf2ad70b8d6f04 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/se3_spacemouse.py @@ -0,0 +1,208 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Spacemouse controller for SE(3) control.""" + +from __future__ import annotations + +import threading +import time +from collections.abc import Callable +from typing import TYPE_CHECKING + +import hid +import numpy as np +import torch +from scipy.spatial.transform import Rotation + +from ..device_base import DeviceBase +from .utils import convert_buffer + +if TYPE_CHECKING: + from .se3_spacemouse_cfg import Se3SpaceMouseCfg + + +class Se3SpaceMouse(DeviceBase): + """A space-mouse controller for sending SE(3) commands as delta poses. + + This class implements a space-mouse controller to provide commands to a robotic arm with a gripper. + It uses the `HID-API`_ which interfaces with USD and Bluetooth HID-class devices across multiple platforms [1]. + + The command comprises of two parts: + + * delta pose: a 6D vector of (x, y, z, roll, pitch, yaw) in meters and radians. + * gripper: a binary command to open or close the gripper. + + Note: + The interface finds and uses the first supported device connected to the computer. + + Currently tested for following devices: + + - SpaceMouse Compact: https://3dconnexion.com/de/product/spacemouse-compact/ + + .. _HID-API: https://github.com/libusb/hidapi + + """ + + def __init__(self, cfg: Se3SpaceMouseCfg): + """Initialize the space-mouse layer. + + Args: + cfg: Configuration object for space-mouse settings. + """ + # store inputs + self.pos_sensitivity = cfg.pos_sensitivity + self.rot_sensitivity = cfg.rot_sensitivity + self.gripper_term = cfg.gripper_term + self._sim_device = cfg.sim_device + # acquire device interface + self._device = hid.device() + self._find_device() + # read rotations + self._read_rotation = False + + # command buffers + self._close_gripper = False + self._delta_pos = np.zeros(3) # (x, y, z) + self._delta_rot = np.zeros(3) # (roll, pitch, yaw) + # dictionary for additional callbacks + self._additional_callbacks = dict() + # run a thread for listening to device updates + self._thread = threading.Thread(target=self._run_device) + self._thread.daemon = True + self._thread.start() + + def __del__(self): + """Destructor for the class.""" + self._thread.join() + + def __str__(self) -> str: + """Returns: A string containing the information of joystick.""" + msg = f"Spacemouse Controller for SE(3): {self.__class__.__name__}\n" + msg += f"\tManufacturer: {self._device.get_manufacturer_string()}\n" + msg += f"\tProduct: {self._device.get_product_string()}\n" + msg += "\t----------------------------------------------\n" + msg += "\tRight button: reset command\n" + msg += "\tLeft button: toggle gripper command (open/close)\n" + msg += "\tMove mouse laterally: move arm horizontally in x-y plane\n" + msg += "\tMove mouse vertically: move arm vertically\n" + msg += "\tTwist mouse about an axis: rotate arm about a corresponding axis" + return msg + + """ + Operations + """ + + def reset(self): + # default flags + self._close_gripper = False + self._delta_pos = np.zeros(3) # (x, y, z) + self._delta_rot = np.zeros(3) # (roll, pitch, yaw) + + def add_callback(self, key: str, func: Callable): + """Add additional functions to bind spacemouse. + + Args: + key: The keyboard button to check against. + func: The function to call when key is pressed. The callback function should not + take any arguments. + """ + self._additional_callbacks[key] = func + + def advance(self) -> torch.Tensor: + """Provides the result from spacemouse event state. + + Returns: + torch.Tensor: A 7-element tensor containing: + - delta pose: First 6 elements as [x, y, z, rx, ry, rz] in meters and radians. + - gripper command: Last element as a binary value (+1.0 for open, -1.0 for close). + """ + rot_vec = Rotation.from_euler("XYZ", self._delta_rot).as_rotvec() + command = np.concatenate([self._delta_pos, rot_vec]) + if self.gripper_term: + gripper_value = -1.0 if self._close_gripper else 1.0 + command = np.append(command, gripper_value) + + return torch.tensor(command, dtype=torch.float32, device=self._sim_device) + + """ + Internal helpers. + """ + + def _find_device(self): + """Find the device connected to computer.""" + found = False + # implement a timeout for device search + for _ in range(5): + for device in hid.enumerate(): + if ( + device["product_string"] == "SpaceMouse Compact" + or device["product_string"] == "SpaceMouse Wireless" + or device["product_string"] == "3Dconnexion Universal Receiver" + ): + # set found flag + found = True + vendor_id = device["vendor_id"] + product_id = device["product_id"] + # connect to the device + self._device.close() + self._device.open(vendor_id, product_id) + self._device_name = device["product_string"] + # check if device found + if not found: + time.sleep(1.0) + else: + break + # no device found: return false + if not found: + raise OSError("No device found by SpaceMouse. Is the device connected?") + + def _run_device(self): + """Listener thread that keeps pulling new messages.""" + # keep running + while True: + # read the device data + if self._device_name == "3Dconnexion Universal Receiver": + data = self._device.read(7 + 6) + else: + data = self._device.read(7) + if data is not None: + # readings from 6-DoF sensor + if self._device_name == "3Dconnexion Universal Receiver": + if data[0] == 1: + self._delta_pos[1] = self.pos_sensitivity * convert_buffer(data[1], data[2]) + self._delta_pos[0] = self.pos_sensitivity * convert_buffer(data[3], data[4]) + self._delta_pos[2] = self.pos_sensitivity * convert_buffer(data[5], data[6]) * -1.0 + + self._delta_rot[1] = self.rot_sensitivity * convert_buffer(data[1 + 6], data[2 + 6]) + self._delta_rot[0] = self.rot_sensitivity * convert_buffer(data[3 + 6], data[4 + 6]) + self._delta_rot[2] = self.rot_sensitivity * convert_buffer(data[5 + 6], data[6 + 6]) * -1.0 + else: + if data[0] == 1: + self._delta_pos[1] = self.pos_sensitivity * convert_buffer(data[1], data[2]) + self._delta_pos[0] = self.pos_sensitivity * convert_buffer(data[3], data[4]) + self._delta_pos[2] = self.pos_sensitivity * convert_buffer(data[5], data[6]) * -1.0 + elif data[0] == 2 and not self._read_rotation: + self._delta_rot[1] = self.rot_sensitivity * convert_buffer(data[1], data[2]) + self._delta_rot[0] = self.rot_sensitivity * convert_buffer(data[3], data[4]) + self._delta_rot[2] = self.rot_sensitivity * convert_buffer(data[5], data[6]) * -1.0 + # readings from the side buttons + if data[0] == 3: + # press left button + if data[1] == 1: + # close gripper + self._close_gripper = not self._close_gripper + # additional callbacks + if "L" in self._additional_callbacks: + self._additional_callbacks["L"]() + # right button is for reset + if data[1] == 2: + # reset layer + self.reset() + # additional callbacks + if "R" in self._additional_callbacks: + self._additional_callbacks["R"]() + if data[1] == 3: + self._read_rotation = not self._read_rotation diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/se3_spacemouse_cfg.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/se3_spacemouse_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..d6b8f1d4a2061dd2b6e791af73793d229e6e85d6 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/se3_spacemouse_cfg.py @@ -0,0 +1,28 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for SE(3) space mouse controller.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.configclass import configclass + +from ..device_base import DeviceCfg + +if TYPE_CHECKING: + from .se3_spacemouse import Se3SpaceMouse + + +@configclass +class Se3SpaceMouseCfg(DeviceCfg): + """Configuration for SE3 space mouse devices.""" + + gripper_term: bool = True + pos_sensitivity: float = 0.4 + rot_sensitivity: float = 0.8 + retargeters: None = None + class_type: type[Se3SpaceMouse] | str = "{DIR}.se3_spacemouse:Se3SpaceMouse" diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/utils.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..17510f70bce99ab1967fda9bdbf60577d44604e8 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/spacemouse/utils.py @@ -0,0 +1,78 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Helper functions for SpaceMouse.""" + +# MIT License +# +# Copyright (c) 2022 Stanford Vision and Learning Lab and UT Robot Perception and Learning Lab +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + + +def convert_buffer(b1, b2): + """Converts raw SpaceMouse readings to commands. + + Args: + b1: 8-bit byte + b2: 8-bit byte + + Returns: + Scaled value from Space-mouse message + """ + return _scale_to_control(_to_int16(b1, b2)) + + +""" +Private methods. +""" + + +def _to_int16(y1, y2): + """Convert two 8 bit bytes to a signed 16 bit integer. + + Args: + y1: 8-bit byte + y2: 8-bit byte + + Returns: + 16-bit integer + """ + x = (y1) | (y2 << 8) + if x >= 32768: + x = -(65536 - x) + return x + + +def _scale_to_control(x, axis_scale=350.0, min_v=-1.0, max_v=1.0): + """Normalize raw HID readings to target range. + + Args: + x: Raw reading from HID + axis_scale: (Inverted) scaling factor for mapping raw input value + min_v: Minimum limit after scaling + max_v: Maximum limit after scaling + + Returns: + Clipped, scaled input from HID + """ + x = x / axis_scale + return min(max(x, min_v), max_v) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/teleop_device_factory.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/teleop_device_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..01fc27c6d99983c76ab2cfaa6042af98437625d9 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/devices/teleop_device_factory.py @@ -0,0 +1,14 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Factory to create teleoperation devices from configuration. + +.. deprecated:: + This module has moved to :mod:`isaaclab_teleop.deprecated.teleop_device_factory`. + Please use :class:`isaaclab_teleop.IsaacTeleopDevice` instead of + :func:`create_teleop_device`. +""" + +from isaaclab_teleop.deprecated.teleop_device_factory import * # noqa: F401,F403 diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__init__.py b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..352fe10e2fd9c99d0e58460d830cf9514e4382fd --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__init__.py @@ -0,0 +1,47 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-package for environment definitions. + +Environments define the interface between the agent and the simulation. +In the simplest case, the environment provides the agent with the current +observations and executes the actions provided by the agent. However, the +environment can also provide additional information such as the current +reward, done flag, and information about the current episode. + +There are two types of environment designing workflows: + +* **Manager-based**: The environment is decomposed into individual components (or managers) + for different aspects (such as computing observations, applying actions, and applying + randomization. The users mainly configure the managers and the environment coordinates the + managers and calls their functions. +* **Direct**: The user implements all the necessary functionality directly into a single class + directly without the need for additional managers. + +Based on these workflows, there are the following environment classes for single and multi-agent RL: + +**Single-Agent RL:** + +* :class:`ManagerBasedEnv`: The manager-based workflow base environment which only provides the + agent with the current observations and executes the actions provided by the agent. +* :class:`ManagerBasedRLEnv`: The manager-based workflow RL task environment which besides the + functionality of the base environment also provides additional Markov Decision Process (MDP) + related information such as the current reward, done flag, and information. +* :class:`DirectRLEnv`: The direct workflow RL task environment which provides implementations for + implementing scene setup, computing dones, performing resets, and computing reward and observation. + +**Multi-Agent RL (MARL):** + +* :class:`DirectMARLEnv`: The direct workflow MARL task environment which provides implementations for + implementing scene setup, computing dones, performing resets, and computing reward and observation. + +For more information about the workflow design patterns, see the `Task Design Workflows`_ section. + +.. _`Task Design Workflows`: https://docs.isaacsim.omniverse.nvidia.com/latest/introduction/workflows.html +""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__init__.pyi b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..83e0945e6fef38646bb872c93af06bc54e70f613 --- /dev/null +++ b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__init__.pyi @@ -0,0 +1,50 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "mdp", + "ui", + "VecEnvObs", + "VecEnvStepReturn", + "ViewerCfg", + "DirectMARLEnv", + "DirectMARLEnvCfg", + "DirectRLEnv", + "DirectRLEnvCfg", + "ManagerBasedEnv", + "ManagerBasedEnvCfg", + "ManagerBasedRLEnv", + "ManagerBasedRLEnvCfg", + "ManagerBasedRLMimicEnv", + "multi_agent_to_single_agent", + "multi_agent_with_one_agent", + "DataGenConfig", + "SubTaskConfig", + "SubTaskConstraintType", + "SubTaskConstraintCoordinationScheme", + "SubTaskConstraintConfig", + "MimicEnvCfg", +] + +from . import mdp, ui +from .common import VecEnvObs, VecEnvStepReturn, ViewerCfg +from .direct_marl_env import DirectMARLEnv +from .direct_marl_env_cfg import DirectMARLEnvCfg +from .direct_rl_env import DirectRLEnv +from .direct_rl_env_cfg import DirectRLEnvCfg +from .manager_based_env import ManagerBasedEnv +from .manager_based_env_cfg import ManagerBasedEnvCfg +from .manager_based_rl_env import ManagerBasedRLEnv +from .manager_based_rl_env_cfg import ManagerBasedRLEnvCfg +from .manager_based_rl_mimic_env import ManagerBasedRLMimicEnv +from .utils.marl import multi_agent_to_single_agent, multi_agent_with_one_agent +from .mimic_env_cfg import ( + DataGenConfig, + SubTaskConfig, + SubTaskConstraintType, + SubTaskConstraintCoordinationScheme, + SubTaskConstraintConfig, + MimicEnvCfg, +) diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__pycache__/__init__.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81400085d136a3dd39fbe3b592c6ea476b81c3ab Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__pycache__/common.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ede2b6ad0c89a46844753298132f3867fbca7215 Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__pycache__/common.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__pycache__/direct_rl_env.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__pycache__/direct_rl_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e55c42b7b790b01d68f5836a19ee2cb1b0887ad Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__pycache__/direct_rl_env.cpython-312.pyc differ diff --git a/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__pycache__/direct_rl_env_cfg.cpython-312.pyc b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__pycache__/direct_rl_env_cfg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2977322353f680f986bdbea7d90295a4750ce36b Binary files /dev/null and b/simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/__pycache__/direct_rl_env_cfg.cpython-312.pyc differ