### Install Isaac Gym Source: https://github.com/lecar-lab/abs/blob/main/training/legged_gym/README.md Installs the Isaac Gym Python package after downloading and installing the Isaac Gym Preview 3 application. It also provides a command to run a sample example. ```bash cd isaacgym/python && pip install -e . cd examples && python 1080_balls_of_solitude.py ``` -------------------------------- ### Install Unitree SDK Executables and Libraries Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/CMakeLists.txt This CMake installation directive specifies where to place the built targets. Executables like `example_position` and libraries are installed into designated directories (`bin/unitree` and `lib/unitree` respectively). This ensures that the compiled SDK and its examples are correctly deployed for use. ```cmake # install install(TARGETS example_position example_velocity example_torque example_walk example_joystick DESTINATION bin/unitree) install(DIRECTORY lib/cpp/${ARCH}/ DESTINATION lib/unitree USE_SOURCE_PERMISSIONS) ``` -------------------------------- ### Install rsl_rl (PPO Implementation) Source: https://github.com/lecar-lab/abs/blob/main/training/legged_gym/README.md Clones the rsl_rl repository and installs it as an editable package. This library provides a PPO implementation for reinforcement learning. ```bash git clone https://github.com/leggedrobotics/rsl_rl cd rsl_rl && pip install -e . ``` -------------------------------- ### Install pybind11 using CMake Build Tools Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/compiling.rst Demonstrates how to build and install pybind11 using CMake's build and install commands. This is a standard way to prepare pybind11 for use with `find_package`. It supports both classic CMake and newer CMake versions with build directories. ```bash # Classic CMake cd pybind11 mkdir build cd build cmake .. make install # CMake 3.15+ cd pybind11 cmake -S . -B build cmake --build build -j 2 # Build on 2 cores cmake --install build ``` -------------------------------- ### Install legged_gym Source: https://github.com/lecar-lab/abs/blob/main/training/legged_gym/README.md Clones the legged_gym repository and installs it as an editable package, making its environments and utilities available for use. ```bash git clone cd legged_gym && pip install -e . ``` -------------------------------- ### Install pybind11 using Pip (PyPI) Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/installing.rst Install pybind11 directly from the Python Package Index (PyPI) using pip. This is a standard method for Python projects. The '[global]' option provides a system-wide installation, which is generally recommended only for virtual environments. ```bash pip install pybind11 ``` ```bash pip install "pybind11[global]" ``` -------------------------------- ### Install pybind11 using vcpkg Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/installing.rst Download and install pybind11 using the vcpkg dependency manager from Microsoft. This process involves cloning vcpkg, bootstrapping it, integrating it with your system, and then installing the pybind11 package. ```bash git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install vcpkg install pybind11 ``` -------------------------------- ### Install RSL RL with Pip Source: https://github.com/lecar-lab/abs/blob/main/training/rsl_rl/README.md Installs the RSL RL library from its GitHub repository using pip. This command clones the repository, navigates into the directory, and then installs the package in editable mode. Ensure you have Git and pip installed. ```shell git clone https://github.com/leggedrobotics/rsl_rl cd rsl_rl pip install -e . ``` -------------------------------- ### Python: Import pybind11 setup helpers with submodule Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/compiling.rst Demonstrates how to import pybind11 setup helpers when pybind11 is included as a submodule in the project's 'extern' directory. This approach manipulates sys.path to make the submodule importable. It's a workaround for specific project structures. ```python DIR = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(DIR, "extern", "pybind11")) from pybind11.setup_helpers import Pybind11Extension # noqa: E402 del sys.path[-1] ``` -------------------------------- ### Library Creation and Installation with Pybind11 Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/tests/test_cmake_build/subdirectory_embed/CMakeLists.txt Defines a shared library target 'test_embed_lib' for embedding, linked against Pybind11. It then specifies installation rules for this library, including its export configuration, and installs the export definitions to a specific CMake directory. ```cmake # Test custom export group -- PYBIND11_EXPORT_NAME add_library(test_embed_lib ../embed.cpp) target_link_libraries(test_embed_lib PRIVATE pybind11::embed) install( TARGETS test_embed_lib EXPORT test_export ARCHIVE DESTINATION bin LIBRARY DESTINATION lib RUNTIME DESTINATION lib) install(EXPORT test_export DESTINATION lib/cmake/test_export/test_export-Targets.cmake) ``` -------------------------------- ### Install Python 3.8 Library Source: https://github.com/lecar-lab/abs/blob/main/training/legged_gym/README.md Provides the command to install a missing Python 3.8 shared library, which is a common troubleshooting step for import errors related to Python versions. ```bash sudo apt install libpython3.8 ``` -------------------------------- ### C++ Header and Namespace Convention for pybind11 Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/basics.rst This C++ code defines the standard include and namespace convention used in pybind11 examples. It includes the main pybind11 header and sets up a namespace alias 'py' for 'pybind11'. This setup is assumed for brevity in subsequent code examples. ```cpp #include namespace py = pybind11; ``` -------------------------------- ### Install PyTorch with CUDA Source: https://github.com/lecar-lab/abs/blob/main/training/legged_gym/README.md Installs a specific version of PyTorch (1.10.0) with CUDA 11.3 support, which is a prerequisite for Isaac Gym. ```bash pip3 install torch==1.10.0+cu113 torchvision==0.11.1+cu113 torchaudio==0.10.0+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html ``` -------------------------------- ### Install ABS Dependencies Source: https://github.com/lecar-lab/abs/blob/main/README.md Installs the `rsl_rl` and `legged_gym` Python packages using pip for editable installs. Also ensures compatibility with specific versions of `numpy` and `setuptools` and installs `tensorboard` for visualization. ```text pip install -e rsl_rl pip install -e legged_gym pip install numpy==1.21 pip install tensorboard pip install setuptools==59.5.0 ``` -------------------------------- ### Install Isaac Gym Source: https://github.com/lecar-lab/abs/blob/main/README.md Installs the Isaac Gym preview 4 release, a simulation environment for robotics. After unzipping the files, it's installed using pip and can be verified by running a sample Python script. ```text cd isaacgym/python && pip install -e . cd examples && python 1080_balls_of_solitude.py ``` -------------------------------- ### Binding Static Properties with py::class_ in C++ (v2.1) Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/upgrade.rst Illustrates how static properties can be bound to classes using py::class_ in C++ starting from pybind11 v2.1. The example shows the old syntax which emitted a deprecation warning and the new, preferred syntax where the `py::metaclass()` attribute is no longer required for static properties. It also includes an example for advanced usage with a custom metaclass. ```cpp // old -- emits a deprecation warning py::class_(m, "Foo", py::metaclass()) .def_property_readonly_static("foo", ...); // new -- static properties work without the attribute py::class_(m, "Foo") .def_property_readonly_static("foo", ...); // new -- advanced feature, override pybind11's default metaclass py::class_(m, "Bar", py::metaclass(custom_python_type)) ... ``` -------------------------------- ### Python Usage of Split pybind11 Module Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/faq.rst Shows how to import and use functions from a pybind11 module that has been split into multiple C++ source files. This example assumes the module is named 'example' and demonstrates calling functions defined in different initialization files. ```pycon >>> import example >>> example.add(1, 2) 3 >>> example.sub(1, 1) 0 ``` -------------------------------- ### Python Version File Example Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/release.rst Sets the version string for the Python package, which must align with the C++ version macros. This file is used for packaging and distribution on PyPI. ```python PYBIND11_VERSION_MAJOR = X PYBIND11_VERSION_MINOR = Y PYBIND11_VERSION_PATCH = Z ``` -------------------------------- ### Install pybind11 using Homebrew Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/installing.rst Install pybind11 using the Homebrew package manager on macOS or Linuxbrew on Linux. This provides a straightforward way to install the library globally on your system. ```bash brew install pybind11 ``` -------------------------------- ### Build Unitree Legged SDK C++ Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/README.md Standard build process for the C++ version of the Unitree Legged SDK using CMake and Make. Assumes necessary dependencies are installed. ```bash mkdir build cd build cmake .. make ``` -------------------------------- ### Install Pybind11 Package Configuration Files Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/CMakeLists.txt This snippet handles the installation of Pybind11's package configuration files. It configures `ProjectConfig.cmake` and `ProjectConfigVersion.cmake`, ensuring compatibility across different CMake versions. The necessary files are then installed to the appropriate destination. ```cmake if(PYBIND11_INSTALL) install(DIRECTORY ${PYBIND11_INCLUDE_DIR}/pybind11 DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) # GNUInstallDirs "DATADIR" wrong here; CMake search path wants "share". set(PYBIND11_CMAKECONFIG_INSTALL_DIR "share/cmake/${PROJECT_NAME}" CACHE STRING "install path for pybind11Config.cmake") configure_package_config_file( tools/${PROJECT_NAME}Config.cmake.in "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" INSTALL_DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR}) if(CMAKE_VERSION VERSION_LESS 3.14) # Remove CMAKE_SIZEOF_VOID_P from ConfigVersion.cmake since the library does # not depend on architecture specific settings or libraries. set(_PYBIND11_CMAKE_SIZEOF_VOID_P ${CMAKE_SIZEOF_VOID_P}) unset(CMAKE_SIZEOF_VOID_P) write_basic_package_version_file( ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake VERSION ${PROJECT_VERSION} COMPATIBILITY AnyNewerVersion) set(CMAKE_SIZEOF_VOID_P ${_PYBIND11_CMAKE_SIZEOF_VOID_P}) else() # CMake 3.14+ natively supports header-only libraries write_basic_package_version_file( ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake VERSION ${PROJECT_VERSION} COMPATIBILITY AnyNewerVersion ARCH_INDEPENDENT) endif() install( FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake tools/FindPythonLibsNew.cmake tools/pybind11Common.cmake tools/pybind11Tools.cmake tools/pybind11NewTools.cmake DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR}) if(NOT PYBIND11_EXPORT_NAME) set(PYBIND11_EXPORT_NAME "${PROJECT_NAME}Targets") endif() install(TARGETS pybind11_headers EXPORT "${PYBIND11_EXPORT_NAME}") install( EXPORT "${PYBIND11_EXPORT_NAME}" NAMESPACE "pybind11::" DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR}) # Uninstall target if(PYBIND11_MASTER_PROJECT) configure_file("${CMAKE_CURRENT_SOURCE_DIR}/tools/cmake_uninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY) add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) endif() endif() ``` -------------------------------- ### Pybind11 Deprecation Warning Example (Text) Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/upgrade.rst Shows an example of the compile-time deprecation warning message generated by pybind11 when using old-style constructors (placement-new) or pickling methods. This warning appears at module initialization time in debug builds. ```text pybind11-bound class 'mymodule.Foo' is using an old-style placement-new '__init__' which has been deprecated. See the upgrade guide in pybind11's docs. ``` -------------------------------- ### Binding Factory Functions as Constructors (C++) Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/advanced/classes.rst This C++ code snippet illustrates how to bind a static factory function `Example::create` as a constructor for the `Example` class in Python using pybind11. It also shows binding lambdas that return unique_ptrs or raw pointers, and regular C++ constructors. ```cpp class Example { private: Example(int); // private constructor public: // Factory function: static Example create(int a) { return Example(a); } }; py::class_(m, "Example") .def(py::init(&Example::create)); ``` ```cpp class Example { private: Example(int); // private constructor public: // Factory function - returned by value: static Example create(int a) { return Example(a); } // These constructors are publicly callable: Example(double); Example(int, int); Example(std::string); }; py::class_(m, "Example") // Bind the factory function as a constructor: .def(py::init(&Example::create)) // Bind a lambda function returning a pointer wrapped in a holder: .def(py::init([](std::string arg) { return std::unique_ptr(new Example(arg)); })) // Return a raw pointer: .def(py::init([](int a, int b) { return new Example(a, b); })) // You can mix the above with regular C++ constructor bindings as well: .def(py::init()); ``` -------------------------------- ### CMake Project and PyTorch Setup Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/CMakeLists_.txt Initializes the CMake project and finds the required PyTorch library. It sets the project name and ensures PyTorch is available for use in subsequent build steps. This is a prerequisite for features that rely on PyTorch. ```cmake cmake_minimum_required(VERSION 2.8.3) project(unitree_legged_sdk) find_package(Torch REQUIRED) ``` -------------------------------- ### Initial pybind11 Bindings (Non-extensible) Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/advanced/classes.rst Standard pybind11 bindings for the 'Animal' and 'Dog' C++ classes and the 'call_go' function. This setup does not allow for extending 'Animal' from Python due to the lack of a trampoline class. ```cpp PYBIND11_MODULE(example, m) { py::class_(m, "Animal") .def("go", &Animal::go); py::class_(m, "Dog") .def(py::init<>()); m.def("call_go", &call_go); } ``` -------------------------------- ### Compile Pybind11 Extension on macOS Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/compiling.rst This command compiles a C++ example file into a Python extension module on macOS. It includes optimization flags, shared library creation, C++11 standard, ignores undefined symbols, and dynamically links Python libraries. ```bash c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix` ``` -------------------------------- ### Python Keyword-Only Argument Example (Python) Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/advanced/functions.rst Illustrates the syntax for keyword-only arguments in Python 3. Arguments following an asterisk (`*`) in the function definition must be explicitly passed by keyword. ```python def f(a, *, b): pass f(a=1, b=2) # good f(b=2, a=1) # good f(1, b=2) # good f(1, 2) # TypeError: f() takes 1 positional argument but 2 were given ``` -------------------------------- ### C++ Function Signature for Pybind11 Example Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/faq.rst Provides the demangled C++ function signature corresponding to the complex mangled name generated by pybind11. This clarifies the structure of the function involved in the symbol name example and demonstrates the underlying C++ types. ```cpp pybind11::cpp_function::cpp_function, std::__1::allocator >, std::__1::allocator, std::__1::allocator > > >&, pybind11::name, pybind11::sibling, pybind11::is_method, char [28]>(void (Example2::*)(std::__1::vector, std::__1::allocator >, std::__1::allocator, std::__1::allocator > > >&), pybind11::name const&, pybind11::sibling const&, pybind11::is_method const&, char const (&) [28]) ``` -------------------------------- ### Python Interaction with 'Pet' Object Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/classes.rst This is an example of an interactive Python session demonstrating the usage of the pybind11-bound 'Pet' class. It shows object creation, method calls, and attribute access. ```pycon >>> import example >>> p = example.Pet('Molly') >>> print(p) >>> p.getName() u'Molly' >>> p.setName('Charly') >>> p.getName() u'Charly' ``` -------------------------------- ### String Formatting with py::str::format() in pybind11 Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/changelog.rst Provides an example of using the py::str::format() method and the _s literal for formatted string creation in pybind11, similar to Python's f-strings or .format(). ```cpp py::str s = "1 + 2 = { }"_s.format(3); ``` -------------------------------- ### Python Class Inheritance with pybind11 Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/advanced/classes.rst Example demonstrating how a derived Python class should call the base class constructor and define its own methods when using pybind11. It highlights the importance of calling the base `__init__` to avoid `TypeError`. ```python class Dachshund(Dog): def __init__(self, name): Dog.__init__(self) # Without this, a TypeError is raised. self.name = name def bark(self): return "yap!" ``` -------------------------------- ### Manual Packaging and Upload Script Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/release.rst A bash script demonstrating the manual process for building and uploading Python package distributions (SDists and wheels) using the 'build' and 'twine' tools. It first installs the build tool, then creates the distributions, and finally uploads them to a package repository. ```bash python3 -m pip install build python3 -m build PYBIND11_SDIST_GLOBAL=1 python3 -m build twine upload dist/* ``` -------------------------------- ### Setup.py Extension with Automatic C++ Standard Detection Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/compiling.rst Sets up a Python extension with pybind11, enabling automatic detection of the highest supported C++ standard via the build_ext command override. This ensures optimal compiler flags are used. Dependencies include setuptools, pybind11, and pybind11.setup_helpers.build_ext. ```python from glob import glob from setuptools import setup from pybind11.setup_helpers import Pybind11Extension, build_ext ext_modules = [ Pybind11Extension( "python_example", sorted(glob("src/*.cpp")), ), ] setup( ..., cmdclass={"build_ext": build_ext}, ext_modules=ext_modules ) ``` -------------------------------- ### Get Pybind11 and Python Include Paths Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/compiling.rst This command retrieves the necessary include paths for pybind11 and Python headers, assuming pybind11 is installed via pip or conda. It's crucial for compiling C++ code that interfaces with Python. ```bash python3 -m pybind11 --includes ``` -------------------------------- ### Pybind11 Integration and Target Configuration Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/tests/test_cmake_build/subdirectory_embed/CMakeLists.txt Configures Pybind11 for use within the project, setting installation options and export names. It then defines an executable target 'test_subdirectory_embed' linked against the Pybind11 embed library and sets its output name. A custom target 'check_subdirectory_embed' is also created for testing. ```cmake set(PYBIND11_INSTALL ON CACHE BOOL "") set(PYBIND11_EXPORT_NAME test_export) add_subdirectory(${PYBIND11_PROJECT_DIR} pybind11) # Test basic target functionality add_executable(test_subdirectory_embed ../embed.cpp) target_link_libraries(test_subdirectory_embed PRIVATE pybind11::embed) set_target_properties(test_subdirectory_embed PROPERTIES OUTPUT_NAME test_cmake_build) add_custom_target(check_subdirectory_embed $ ${PROJECT_SOURCE_DIR}/../test.py) ``` -------------------------------- ### Setup.py Extension with Pybind11 Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/compiling.rst Configures a Python extension module using pybind11's Pybind11Extension class within setup.py. It automatically handles C++ compilation and linking. Dependencies include setuptools and pybind11. ```python from glob import glob from setuptools import setup from pybind11.setup_helpers import Pybind11Extension ext_modules = [ Pybind11Extension( "python_example", sorted(glob("src/*.cpp")), # Sort source files for reproducibility ), ] setup( ..., ext_modules=ext_modules ) ``` -------------------------------- ### Compile Test Cases with Bash (Linux/macOS) Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/basics.rst This code snippet outlines the steps to compile and run pybind11 test cases on Linux and macOS using CMake. It requires 'python-dev' or 'python3-dev' and 'cmake' to be installed. The commands create a build directory, configure the build with CMake, and then compile and execute the tests. ```bash mkdir build cd build cmake .. make check -j 4 ``` -------------------------------- ### Parallel Compilation Helper for Setup.py Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/compiling.rst Integrates pybind11's ParallelCompile helper into setup.py for optional multithreaded builds of C++ extensions. It uses an environment variable to control the number of build threads. This can speed up compilation on multi-core systems. Dependencies include pybind11.setup_helpers. ```python from pybind11.setup_helpers import ParallelCompile # Optional multithreaded build ParallelCompile("NPY_NUM_BUILD_JOBS").install() setup(...) ``` -------------------------------- ### Install pybind11 using Conda Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/installing.rst Install pybind11 using the conda package manager from the conda-forge channel. This is a common approach for managing scientific and C++ dependencies within the Anaconda ecosystem. ```bash conda install -c conda-forge pybind11 ``` -------------------------------- ### Classic setup_requires for Pybind11 Dependency Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/compiling.rst Illustrates using the classic 'setup_requires' keyword argument in setup.py to manage pybind11 as a build-time dependency. This approach ensures compatibility with older Pip versions by handling potential import errors during the first setup.py pass. Dependencies include setuptools and pybind11. ```python try: from pybind11.setup_helpers import Pybind11Extension except ImportError: from setuptools import Extension as Pybind11Extension ``` -------------------------------- ### Compile Test Cases with Batch (Windows) Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/basics.rst This snippet shows how to compile and run pybind11 test cases on Windows using CMake and Visual Studio 2015 or newer. It requires CMake to be installed. The commands create a build directory, configure the build, and then use CMake to build and run the 'check' target in a Release configuration. ```batch mkdir build cd build cmake .. cmake --build . --config Release --target check ``` -------------------------------- ### C++ Function Declaration and Binding Example Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/advanced/functions.rst Demonstrates a C++ function returning a pointer and its pybind11 binding. It highlights the potential crash when using the default 'automatic' return value policy and shows the correct way to bind it using 'return_value_policy::reference' to avoid ownership issues. ```cpp /* Function declaration */ Data *get_data() { return _data; /* (pointer to a static data structure) */ } ... /* Binding code */ m.def("get_data", &get_data); // <-- KABOOM, will cause crash when called from Python m.def("get_data", &get_data, return_value_policy::reference); ``` -------------------------------- ### Install PyTorch Source: https://github.com/lecar-lab/abs/blob/main/README.md Installs PyTorch with CUDA support for GPU acceleration. Specifies version compatibility for a specific CUDA version (cu116) and provides an alternative for older CUDA versions (cu113). ```text conda create -n xxx python=3.8 # or use virtual environment/docker pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116 # used version during this work: torch==2.0.1 torchvision==0.15.2 torchaudio==2.0.2 # for older cuda ver: pip3 install torch==1.10.0+cu113 torchvision==0.11.1+cu113 torchaudio==0.10.0+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html ``` -------------------------------- ### Compile C++ pybind11 Module with GCC (Linux) Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/basics.rst This bash command compiles a C++ file ('example.cpp') into a Python extension module using pybind11 on Linux with GCC. It uses flags for optimization, warnings, shared library creation, C++11 standard, and position-independent code. It also dynamically includes necessary Python headers and specifies the output file name based on the Python version. ```bash c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix` ``` -------------------------------- ### Integrate pybind11 using find_package in CMake Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/compiling.rst Finds and integrates an installed pybind11 package into a CMake project. This method requires pybind11 to be installed on the system. It allows the use of pybind11's build system components, such as the `pybind11_add_module` macro. ```cmake cmake_minimum_required(VERSION 3.4...3.18) project(example LANGUAGES CXX) find_package(pybind11 REQUIRED) pybind11_add_module(example example.cpp) ``` -------------------------------- ### C++ Symbol Mangling Example in Pybind11 Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/faq.rst Illustrates a deeply nested and long mangled C++ symbol generated by pybind11 due to template metaprogramming. This example highlights the verbosity of symbol names and the need for symbol visibility control. ```none _​_​Z​N​8​p​y​b​i​n​d​1​1​1​2​c​p​p​_​f​u​n​c​t​i​o​n​C​1​I​v​8​E​x​a​m​p​l​e​2​J​R​N​S​t​3​_​_​1​6​v​e​c​t​o​r​I​N​S​3​_​1​2​b​a​s​i​c​_​s​t​r​i​n​g​I​w​N​S​3​_​1​1​c​h​a​r​_​t​r​a​i​t​s​I​w​E​E​N​S​3​_​9​a​l​l​o​c​a​t​o​r​I​w​E​E​E​E​N​S​8​_​I​S​A​_​E​E​E​E​J​N​S​_​4​n​a​m​e​E​N​S​_​7​s​i​b​l​i​n​g​E​N​S​_​9​i​s​_​m​e​t​h​o​d​E​A​2​8​_​c​E​E​E​M​T​0​_​F​T​_​D​p​T​1​_​E​D​p​R​K​T​2​_​ ``` ```cpp __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_ ``` -------------------------------- ### Register New Environment Source: https://github.com/lecar-lab/abs/blob/main/training/legged_gym/README.md Demonstrates how to register a new environment class with its configuration classes in the task registry. This is essential for making custom environments usable by the training and playing scripts. ```python from isaacgym_anymal.envs import task_registry from my_env_folder.my_env import MyEnv from my_env_folder.my_env_config import MyEnvCfg, MyEnvCfgPPO task_registry.register("my_env_name", MyEnv, MyEnvCfg, MyEnvCfgPPO) ``` -------------------------------- ### Custom Constructors with Lambdas in pybind11 Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/changelog.rst Shows how to define custom constructors for C++ classes exposed to Python using pybind11. This example utilizes lambdas and `std::make_unique` to create instances, offering flexibility beyond existing C++ constructors. It assumes a `struct Example` is defined. ```cpp struct Example { Example(std::string); }; py::class_(m, "Example") .def(py::init()) // existing constructor .def(py::init([](int n) { // custom constructor return std::make_unique(std::to_string(n)); })); ``` -------------------------------- ### Pybind11 Custom Constructors (C++) Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/upgrade.rst Illustrates the transition from deprecated placement-new style custom constructors to the new, safer py::init() API in pybind11. The new approach enhances type safety and prevents common initialization errors. It supports returning raw pointers, unique pointers, or values. ```cpp // old -- deprecated (runtime warning shown only in debug mode) py::class(m, "Foo") .def("__init__", [](Foo &self, ...) { new (&self) Foo(...); // uses placement-new }); // new py::class(m, "Foo") .def(py::init([](...) { // Note: no `self` argument return new Foo(...); // return by raw pointer // or: return std::make_unique(...); // return by holder // or: return Foo(...); // return by value (move constructor) })); ``` -------------------------------- ### Building a Python Extension Module with Pybind11 CMake Targets Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/compiling.rst Example of how to build a Python extension module using Pybind11's CMake interface targets. This demonstrates linking against pybind11::module, pybind11::lto, and pybind11::windows_extras, along with using helper functions for extension and stripping. ```cmake cmake_minimum_required(VERSION 3.4) project(example LANGUAGES CXX) find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11) add_library(example MODULE main.cpp) target_link_libraries(example PRIVATE pybind11::module pybind11::lto pybind11::windows_extras) pybind11_extension(example) pybind11_strip(example) set_target_properties(example PROPERTIES CXX_VISIBILITY_PRESET "hidden" CUDA_VISIBILITY_PRESET "hidden") ``` -------------------------------- ### Use Shorthand Notation for Named Arguments in C++ Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/basics.rst Presents a concise syntax for defining named arguments in C++ bindings for pybind11 using C++11 literals. The `_a` suffix, after `using namespace pybind11::literals;`, simplifies the definition of arguments. ```cpp // shorthand using namespace pybind11::literals; m.def("add2", &add, "i"_a, "j"_a); ``` -------------------------------- ### Set and Get Window Text using Wide Strings in C++ Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/advanced/cast/strings.rst Demonstrates C++ functions to set and get window text using `std::wstring`. The `set_window_text` function converts a Python `str` to UTF-16 for `SetWindowText`, and `get_window_text` retrieves UTF-16 text from a window and converts it back to a Python `str`. Requires the Windows SDK and pybind11. ```c++ #define UNICODE #include m.def("set_window_text", [](HWND hwnd, std::wstring s) { // Call SetWindowText with null-terminated UTF-16 string ::SetWindowText(hwnd, s.c_str()); } ); m.def("get_window_text", [](HWND hwnd) { const int buffer_size = ::GetWindowTextLength(hwnd) + 1; auto buffer = std::make_unique< wchar_t[] >(buffer_size); ::GetWindowText(hwnd, buffer.data(), buffer_size); std::wstring text(buffer.get()); // wstring will be converted to Python str return text; } ); ``` -------------------------------- ### CMake: List pybind11 Header Files Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/CMakeLists.txt Specifies the list of header files that constitute the pybind11 library. This list is used for installation and for verifying that all necessary headers are present. ```cmake set(PYBIND11_HEADERS include/pybind11/detail/class.h include/pybind11/detail/common.h include/pybind11/detail/descr.h include/pybind11/detail/init.h include/pybind11/detail/internals.h include/pybind11/detail/typeid.h include/pybind11/attr.h include/pybind11/buffer_info.h include/pybind11/cast.h include/pybind11/chrono.h include/pybind11/common.h include/pybind11/complex.h include/pybind11/options.h include/pybind11/eigen.h include/pybind11/embed.h include/pybind11/eval.h include/pybind11/iostream.h include/pybind11/functional.h include/pybind11/numpy.h include/pybind11/operators.h include/pybind11/pybind11.h include/pybind11/pytypes.h include/pybind11/stl.h include/pybind11/stl_bind.h) ``` -------------------------------- ### Build Unitree Legged SDK Python Wrapper Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/README.md Build instructions for the Python wrapper of the Unitree Legged SDK. Requires setting the PYTHON_BUILD flag during CMake configuration. Includes potential troubleshooting steps for missing headers or libraries. ```bash cmake -DPYTHON_BUILD=TRUE .. # If pybind11 headers are not found, add: # include_directories(${CMAKE_CURRENT_SOURCE_DIR}/third-party/pybind11/include) at line 14 in python_wrapper/CMakeLists.txt # If msgpack.hpp is not found, run: # sudo apt install libmsgpack* ``` -------------------------------- ### Define C++ Struct 'Pet' for pybind11 Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/classes.rst This snippet defines a simple C++ struct 'Pet' with a name member and methods to get and set the name. This struct will be exposed to Python. ```cpp struct Pet { Pet(const std::string &name) : name(name) { } void setName(const std::string &name_) { name = name_; } const std::string &getName() const { return name; } std::string name; }; ``` -------------------------------- ### pybind11: Deprecated vs. New py::object API Syntax (C++) Source: https://github.com/lecar-lab/abs/blob/main/deployment/src/python_wrapper/third-party/pybind11/docs/upgrade.rst This section illustrates the transition from deprecated py::object API calls to their modern equivalents in pybind11. It covers object invocation, string conversion, type checking, pointer casting, attribute checking, and key containment. ```cpp // Old: obj.call(args...) // New: obj(args...) // Old: obj.str() // New: py::str(obj) // Old: auto l = py::list(obj); l.check() // New: py::isinstance(obj) // Old: py::object(ptr, true) // New: py::reinterpret_borrow(ptr) // Old: py::object(ptr, false) // New: py::reinterpret_steal(ptr) // Old: if (obj.attr("foo")) // New: if (py::hasattr(obj, "foo")) // Old: if (obj["bar"]) // New: if (obj.contains("bar")) ```