file_path
stringlengths
20
202
content
stringlengths
9
3.85M
size
int64
9
3.85M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
8
993
alphanum_fraction
float64
0.26
0.93
daniel-kun/omni/interface/omni/core/input/syntax_element.hpp
#ifndef OMNI_CORE_SYNTAX_ELEMENT_HPP #define OMNI_CORE_SYNTAX_ELEMENT_HPP #include <omni/core/core.hpp> #include <omni/core/input/syntax_suggestion.hpp> #include <vector> #include <memory> #include <set> namespace omni { namespace core { namespace input { class template_element; /** **/ class OMNI_CORE_API syntax_element { public: void setName (std::string const & name); std::string getName () const; virtual std::shared_ptr <template_element> templateElementAt (std::size_t templatePosition); virtual std::size_t templateElementCount () const; std::vector <syntax_suggestion> suggest (std::string input, std::size_t templateIndex = 0u); virtual std::vector <syntax_suggestion> suggestImpl (std::string input, std::size_t templatePosition, std::set <syntax_element *> alreadyVisistedElements) = 0; private: std::string _name; }; } // namespace input } // namespace core } // namespace omni #endif // include guard
955
C++
23.51282
163
0.719372
daniel-kun/omni/interface/omni/core/input/syntax_template_element.hpp
#ifndef OMNI_CORE_SYNTAX_TEMPLATE_ELEMENT_HPP #define OMNI_CORE_SYNTAX_TEMPLATE_ELEMENT_HPP #include <omni/core/core.hpp> #include <omni/core/input/template_element.hpp> #include <memory> namespace omni { namespace core { namespace input { class syntax_element; /** **/ class OMNI_CORE_API syntax_template_element : public template_element { public: syntax_template_element (syntax_element & parent, std::size_t templateIndex, std::shared_ptr <syntax_element> target); std::vector <std::string> suggest (std::string input) override; std::shared_ptr <syntax_element> dive (); std::shared_ptr <syntax_element> getSyntaxElement () const; void visit (template_visitor & visitor) override; private: std::shared_ptr <syntax_element> _target; }; } // namespace input } // namespace core } // namespace omni #endif // include guard
859
C++
22.243243
122
0.720605
daniel-kun/omni/interface/omni/core/input/repeater_template_element.hpp
#ifndef OMNI_CORE_REPEATER_TEMPLATE_ELEMENT_HPP #define OMNI_CORE_REPEATER_TEMPLATE_ELEMENT_HPP #include <omni/core/core.hpp> #include <omni/core/input/template_element.hpp> #include <memory> namespace omni { namespace core { namespace input { /** **/ class OMNI_CORE_API repeater_template_element : public template_element { public: repeater_template_element (std::shared_ptr <template_element> elementToBeRepeated); void visit (template_visitor & visitor) override; }; } // namespace input } // namespace core } // namespace omni #endif // include guard
571
C++
20.185184
87
0.742557
daniel-kun/omni/interface/omni/core/input/template_visitor.hpp
#ifndef OMNI_CORE_INPUT_TEMPLATE_VISITOR_HPP #define OMNI_CORE_INPUT_TEMPLATE_VISITOR_HPP #include <omni/core/core.hpp> namespace omni { namespace core { namespace input { class syntax_template_element; class variable_template_element; class regex_template_element; class fixed_template_element; class repeater_template_element; /** **/ class OMNI_CORE_API template_visitor { public: virtual void visitSyntaxTemplateElement (syntax_template_element & element) = 0; virtual void visitVariableTemplateElement (variable_template_element & element) = 0; virtual void visitRegexTemplateElement (regex_template_element & element) = 0; virtual void visitFixedTemplateElement (fixed_template_element & element) = 0; virtual void visitRepeaterTemplateElement (repeater_template_element & element) = 0; }; } // namespace input } // namespace core } // namespace omni #endif // include guard
924
C++
28.838709
90
0.753247
daniel-kun/omni/interface/omni/core/input/regex_template_element.hpp
#ifndef OMNI_CORE_REGEX_TEMPLATE_ELEMENT_HPP #define OMNI_CORE_REGEX_TEMPLATE_ELEMENT_HPP #include <omni/core/core.hpp> #include <omni/core/input/template_element.hpp> #include <string> namespace omni { namespace core { namespace input { /** **/ class OMNI_CORE_API regex_template_element : public template_element { public: regex_template_element (std::string regex); void visit (template_visitor & visitor) override; }; } // namespace input } // namespace core } // namespace omni #endif // include guard
522
C++
18.37037
70
0.727969
daniel-kun/omni/interface/omni/tests/test_utils.hpp
#ifndef OMNI_TESTS_TEST_UTILS_HPP #define OMNI_TESTS_TEST_UTILS_HPP #include <omni/tests/test_file_manager.hpp> #include <omni/core/model/function_call_expression.hpp> #include <omni/core/model/return_statement.hpp> #include <omni/core/not_implemented_error.hpp> #include <boost/format.hpp> #include <memory> #include <string> #include <vector> #ifdef WIN32 #include <Windows.h> #else #include <dlfcn.h> #endif namespace omni { namespace core { namespace model { class function; } } } namespace omni { namespace tests { boost::filesystem::path emitSharedLibraryWithFunction (std::shared_ptr <omni::core::model::function> func, omni::tests::test_file_manager & testFileManager, std::string const & fileBaseName, std::string & functionName); template <typename Return> Return runFunction (std::shared_ptr <omni::core::model::function> func, omni::tests::test_file_manager & testFileManager, std::string const & fileBaseName); bool checkMetaInfoChildren (const omni::core::model::meta_info & metaInfo, std::set <const omni::core::model::meta_info *> children); } // namespace tests } // namespace omni /** Runs the function `function' and returns it's result in a string representation. **/ template <typename Return> Return omni::tests::runFunction (std::shared_ptr <omni::core::model::function> func, omni::tests::test_file_manager & testFileManager, std::string const & fileBaseName) { std::string functionName; boost::filesystem::path sharedLibraryPath = emitSharedLibraryWithFunction (func, testFileManager, fileBaseName, functionName); boost::filesystem::path expPath = sharedLibraryPath; boost::filesystem::path libPath = sharedLibraryPath; testFileManager.getTestFileName (expPath.replace_extension (".exp").filename ().string ()); // To get rid of the temporary files after the test finishes testFileManager.getTestFileName (expPath.replace_extension (".lib").filename ().string ()); // To get rid of the temporary files after the test finishes boost::filesystem::path objectFilePath = sharedLibraryPath; boost::filesystem::path objectFilePath2 = sharedLibraryPath; typedef Return (* testFunc) (); #ifdef WIN32 HMODULE lib = ::LoadLibraryA (sharedLibraryPath.string ().c_str ()); // HMODULE nullModule = nullptr; // BOOST_CHECK_NE (lib, nullModule); if (lib != nullptr) { #pragma warning(push) #pragma warning(disable:4191) testFunc f = reinterpret_cast <testFunc> (::GetProcAddress(lib, functionName.c_str ())); #pragma warning(pop) // testFunc nullTestFunc = nullptr; // BOOST_CHECK_NE (f, nullTestFunc); if (f != nullptr) { Return result = (*f)(); ::FreeLibrary (lib); return result; } else { ::FreeLibrary (lib); throw omni::core::logic_error (__FILE__, __FUNCTION__, __LINE__, "Test function could not be found in temporarily created shared object file \"" + sharedLibraryPath.string () + "\"."); } } throw omni::core::logic_error (__FILE__, __FUNCTION__, __LINE__, "Test shared object could not be loaded: \"" + sharedLibraryPath.string () + "\"."); #else void * lib = dlopen (sharedLibraryPath.string ().c_str (), RTLD_NOW); if (lib != nullptr) { testFunc f = reinterpret_cast <testFunc> (dlsym (lib, functionName.c_str ())); if (f != nullptr) { Return result = (*f)(); int error = dlclose (lib); if (error != 0) { throw omni::core::logic_error (__FILE__, __FUNCTION__, __LINE__, (boost::format ("dlsym returned %1%.") % error).str ()); } return result; } else { int error = dlclose (lib); if (error != 0) { throw omni::core::logic_error (__FILE__, __FUNCTION__, __LINE__, (boost::format ("dlsym returned %1%.") % error).str ()); } throw omni::core::logic_error (__FILE__, __FUNCTION__, __LINE__, "Test function could not be found in temporarily created shared object file \"" + sharedLibraryPath.string () + "\"."); } } throw omni::core::logic_error (__FILE__, __FUNCTION__, __LINE__, "Test shared object could not be loaded: \"" + sharedLibraryPath.string () + "\"."); #endif } #endif // include guard
4,809
C++
40.465517
163
0.580994
daniel-kun/omni/interface/omni/tests/test_file_manager.hpp
#ifndef OMNI_TESTS_TEST_FILE_MANAGER_HPP #define OMNI_TESTS_TEST_FILE_MANAGER_HPP #include <boost/filesystem.hpp> #include <string> #include <vector> namespace omni { namespace tests { /** The test_file_manager keeps track of files created during test sessions and removes them after the test has finished. **/ class test_file_manager { public: ~ test_file_manager (); boost::filesystem::path getTestFileName (std::string const & fileName, bool autoDelete = true); private: std::vector <boost::filesystem::path> _files; }; } // namespace tests } // namespace omni #endif
638
C++
21.034482
103
0.670846
daniel-kun/omni/interface/rapidxml/rapidxml_utils.hpp
#ifndef RAPIDXML_UTILS_HPP_INCLUDED #define RAPIDXML_UTILS_HPP_INCLUDED // Copyright (C) 2006, 2009 Marcin Kalicinski // Version 1.13 // Revision $DateTime: 2009/05/13 01:46:17 $ //! \file rapidxml_utils.hpp This file contains high-level rapidxml utilities that can be useful //! in certain simple scenarios. They should probably not be used if maximizing performance is the main objective. #include "rapidxml.hpp" #include <vector> #include <string> #include <fstream> #include <stdexcept> namespace rapidxml { //! Represents data loaded from a file template<class Ch = char> class file { public: //! Loads file into the memory. Data will be automatically destroyed by the destructor. //! \param filename Filename to load. file(const char *filename) { using namespace std; // Open stream basic_ifstream<Ch> stream(filename, ios::binary); if (!stream) throw runtime_error(string("cannot open file ") + filename); stream.unsetf(ios::skipws); // Determine stream size stream.seekg(0, ios::end); size_t size = stream.tellg(); stream.seekg(0); // Load data and add terminating 0 m_data.resize(size + 1); stream.read(&m_data.front(), static_cast<streamsize>(size)); m_data[size] = 0; } //! Loads file into the memory. Data will be automatically destroyed by the destructor //! \param stream Stream to load from file(std::basic_istream<Ch> &stream) { using namespace std; // Load data and add terminating 0 stream.unsetf(ios::skipws); m_data.assign(istreambuf_iterator<Ch>(stream), istreambuf_iterator<Ch>()); if (stream.fail() || stream.bad()) throw runtime_error("error reading stream"); m_data.push_back(0); } //! Gets file data. //! \return Pointer to data of file. Ch *data() { return &m_data.front(); } //! Gets file data. //! \return Pointer to data of file. const Ch *data() const { return &m_data.front(); } //! Gets file data size. //! \return Size of file data, in characters. std::size_t size() const { return m_data.size(); } private: std::vector<Ch> m_data; // File data }; //! Counts children of node. Time complexity is O(n). //! \return Number of children of node template<class Ch> inline std::size_t count_children(xml_node<Ch> *node) { xml_node<Ch> *child = node->first_node(); std::size_t count = 0; while (child) { ++count; child = child->next_sibling(); } return count; } //! Counts attributes of node. Time complexity is O(n). //! \return Number of attributes of node template<class Ch> inline std::size_t count_attributes(xml_node<Ch> *node) { xml_attribute<Ch> *attr = node->first_attribute(); std::size_t count = 0; while (attr) { ++count; attr = attr->next_attribute(); } return count; } } #endif
3,417
C++
26.788618
114
0.546678
daniel-kun/omni/interface/rapidxml/rapidxml.hpp
#ifndef RAPIDXML_HPP_INCLUDED #define RAPIDXML_HPP_INCLUDED // Copyright (C) 2006, 2009 Marcin Kalicinski // Version 1.13 // Revision $DateTime: 2009/05/13 01:46:17 $ //! \file rapidxml.hpp This file contains rapidxml parser and DOM implementation // If standard library is disabled, user must provide implementations of required functions and typedefs #if !defined(RAPIDXML_NO_STDLIB) #include <cstdlib> // For std::size_t #include <cassert> // For assert #include <new> // For placement new #endif // On MSVC, disable "conditional expression is constant" warning (level 4). // This warning is almost impossible to avoid with certain types of templated code #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4127) // Conditional expression is constant #endif /////////////////////////////////////////////////////////////////////////// // RAPIDXML_PARSE_ERROR #if defined(RAPIDXML_NO_EXCEPTIONS) #define RAPIDXML_PARSE_ERROR(what, where) { parse_error_handler(what, where); assert(0); } namespace rapidxml { //! When exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, //! this function is called to notify user about the error. //! It must be defined by the user. //! <br><br> //! This function cannot return. If it does, the results are undefined. //! <br><br> //! A very simple definition might look like that: //! <pre> //! void %rapidxml::%parse_error_handler(const char *what, void *where) //! { //! std::cout << "Parse error: " << what << "\n"; //! std::abort(); //! } //! </pre> //! \param what Human readable description of the error. //! \param where Pointer to character data where error was detected. void parse_error_handler(const char *what, void *where); } #else #include <exception> // For std::exception #define RAPIDXML_PARSE_ERROR(what, where) throw parse_error(what, where) namespace rapidxml { //! Parse error exception. //! This exception is thrown by the parser when an error occurs. //! Use what() function to get human-readable error message. //! Use where() function to get a pointer to position within source text where error was detected. //! <br><br> //! If throwing exceptions by the parser is undesirable, //! it can be disabled by defining RAPIDXML_NO_EXCEPTIONS macro before rapidxml.hpp is included. //! This will cause the parser to call rapidxml::parse_error_handler() function instead of throwing an exception. //! This function must be defined by the user. //! <br><br> //! This class derives from <code>std::exception</code> class. class parse_error: public std::exception { public: //! Constructs parse error parse_error(const char *what, void *where) : m_what(what) , m_where(where) { } //! Gets human readable description of error. //! \return Pointer to null terminated description of the error. virtual const char *what() const throw() { return m_what; } //! Gets pointer to character data where error happened. //! Ch should be the same as char type of xml_document that produced the error. //! \return Pointer to location within the parsed string where error occured. template<class Ch> Ch *where() const { return reinterpret_cast<Ch *>(m_where); } private: const char *m_what; void *m_where; }; } #endif /////////////////////////////////////////////////////////////////////////// // Pool sizes #ifndef RAPIDXML_STATIC_POOL_SIZE // Size of static memory block of memory_pool. // Define RAPIDXML_STATIC_POOL_SIZE before including rapidxml.hpp if you want to override the default value. // No dynamic memory allocations are performed by memory_pool until static memory is exhausted. #define RAPIDXML_STATIC_POOL_SIZE (64 * 1024) #endif #ifndef RAPIDXML_DYNAMIC_POOL_SIZE // Size of dynamic memory block of memory_pool. // Define RAPIDXML_DYNAMIC_POOL_SIZE before including rapidxml.hpp if you want to override the default value. // After the static block is exhausted, dynamic blocks with approximately this size are allocated by memory_pool. #define RAPIDXML_DYNAMIC_POOL_SIZE (64 * 1024) #endif #ifndef RAPIDXML_ALIGNMENT // Memory allocation alignment. // Define RAPIDXML_ALIGNMENT before including rapidxml.hpp if you want to override the default value, which is the size of pointer. // All memory allocations for nodes, attributes and strings will be aligned to this value. // This must be a power of 2 and at least 1, otherwise memory_pool will not work. #define RAPIDXML_ALIGNMENT sizeof(void *) #endif namespace rapidxml { // Forward declarations template<class Ch> class xml_node; template<class Ch> class xml_attribute; template<class Ch> class xml_document; //! Enumeration listing all node types produced by the parser. //! Use xml_node::type() function to query node type. enum node_type { node_document, //!< A document node. Name and value are empty. node_element, //!< An element node. Name contains element name. Value contains text of first data node. node_data, //!< A data node. Name is empty. Value contains data text. node_cdata, //!< A CDATA node. Name is empty. Value contains data text. node_comment, //!< A comment node. Name is empty. Value contains comment text. node_declaration, //!< A declaration node. Name and value are empty. Declaration parameters (version, encoding and standalone) are in node attributes. node_doctype, //!< A DOCTYPE node. Name is empty. Value contains DOCTYPE text. node_pi //!< A PI node. Name contains target. Value contains instructions. }; /////////////////////////////////////////////////////////////////////// // Parsing flags //! Parse flag instructing the parser to not create data nodes. //! Text of first data node will still be placed in value of parent element, unless rapidxml::parse_no_element_values flag is also specified. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_no_data_nodes = 0x1; //! Parse flag instructing the parser to not use text of first data node as a value of parent element. //! Can be combined with other flags by use of | operator. //! Note that child data nodes of element node take precendence over its value when printing. //! That is, if element has one or more child data nodes <em>and</em> a value, the value will be ignored. //! Use rapidxml::parse_no_data_nodes flag to prevent creation of data nodes if you want to manipulate data using values of elements. //! <br><br> //! See xml_document::parse() function. const int parse_no_element_values = 0x2; //! Parse flag instructing the parser to not place zero terminators after strings in the source text. //! By default zero terminators are placed, modifying source text. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_no_string_terminators = 0x4; //! Parse flag instructing the parser to not translate entities in the source text. //! By default entities are translated, modifying source text. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_no_entity_translation = 0x8; //! Parse flag instructing the parser to disable UTF-8 handling and assume plain 8 bit characters. //! By default, UTF-8 handling is enabled. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_no_utf8 = 0x10; //! Parse flag instructing the parser to create XML declaration node. //! By default, declaration node is not created. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_declaration_node = 0x20; //! Parse flag instructing the parser to create comments nodes. //! By default, comment nodes are not created. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_comment_nodes = 0x40; //! Parse flag instructing the parser to create DOCTYPE node. //! By default, doctype node is not created. //! Although W3C specification allows at most one DOCTYPE node, RapidXml will silently accept documents with more than one. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_doctype_node = 0x80; //! Parse flag instructing the parser to create PI nodes. //! By default, PI nodes are not created. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_pi_nodes = 0x100; //! Parse flag instructing the parser to validate closing tag names. //! If not set, name inside closing tag is irrelevant to the parser. //! By default, closing tags are not validated. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_validate_closing_tags = 0x200; //! Parse flag instructing the parser to trim all leading and trailing whitespace of data nodes. //! By default, whitespace is not trimmed. //! This flag does not cause the parser to modify source text. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_trim_whitespace = 0x400; //! Parse flag instructing the parser to condense all whitespace runs of data nodes to a single space character. //! Trimming of leading and trailing whitespace of data is controlled by rapidxml::parse_trim_whitespace flag. //! By default, whitespace is not normalized. //! If this flag is specified, source text will be modified. //! Can be combined with other flags by use of | operator. //! <br><br> //! See xml_document::parse() function. const int parse_normalize_whitespace = 0x800; // Compound flags //! Parse flags which represent default behaviour of the parser. //! This is always equal to 0, so that all other flags can be simply ored together. //! Normally there is no need to inconveniently disable flags by anding with their negated (~) values. //! This also means that meaning of each flag is a <i>negation</i> of the default setting. //! For example, if flag name is rapidxml::parse_no_utf8, it means that utf-8 is <i>enabled</i> by default, //! and using the flag will disable it. //! <br><br> //! See xml_document::parse() function. const int parse_default = 0; //! A combination of parse flags that forbids any modifications of the source text. //! This also results in faster parsing. However, note that the following will occur: //! <ul> //! <li>names and values of nodes will not be zero terminated, you have to use xml_base::name_size() and xml_base::value_size() functions to determine where name and value ends</li> //! <li>entities will not be translated</li> //! <li>whitespace will not be normalized</li> //! </ul> //! See xml_document::parse() function. const int parse_non_destructive = parse_no_string_terminators | parse_no_entity_translation; //! A combination of parse flags resulting in fastest possible parsing, without sacrificing important data. //! <br><br> //! See xml_document::parse() function. const int parse_fastest = parse_non_destructive | parse_no_data_nodes; //! A combination of parse flags resulting in largest amount of data being extracted. //! This usually results in slowest parsing. //! <br><br> //! See xml_document::parse() function. const int parse_full = parse_declaration_node | parse_comment_nodes | parse_doctype_node | parse_pi_nodes | parse_validate_closing_tags; /////////////////////////////////////////////////////////////////////// // Internals //! \cond internal namespace internal { // Struct that contains lookup tables for the parser // It must be a template to allow correct linking (because it has static data members, which are defined in a header file). template<int Dummy> struct lookup_tables { static const unsigned char lookup_whitespace[256]; // Whitespace table static const unsigned char lookup_node_name[256]; // Node name table static const unsigned char lookup_text[256]; // Text table static const unsigned char lookup_text_pure_no_ws[256]; // Text table static const unsigned char lookup_text_pure_with_ws[256]; // Text table static const unsigned char lookup_attribute_name[256]; // Attribute name table static const unsigned char lookup_attribute_data_1[256]; // Attribute data table with single quote static const unsigned char lookup_attribute_data_1_pure[256]; // Attribute data table with single quote static const unsigned char lookup_attribute_data_2[256]; // Attribute data table with double quotes static const unsigned char lookup_attribute_data_2_pure[256]; // Attribute data table with double quotes static const unsigned char lookup_digits[256]; // Digits static const unsigned char lookup_upcase[256]; // To uppercase conversion table for ASCII characters }; // Find length of the string template<class Ch> inline std::size_t measure(const Ch *p) { const Ch *tmp = p; while (*tmp) ++tmp; return tmp - p; } // Compare strings for equality template<class Ch> inline bool compare(const Ch *p1, std::size_t size1, const Ch *p2, std::size_t size2, bool case_sensitive) { if (size1 != size2) return false; if (case_sensitive) { for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2) if (*p1 != *p2) return false; } else { for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2) if (lookup_tables<0>::lookup_upcase[static_cast<unsigned char>(*p1)] != lookup_tables<0>::lookup_upcase[static_cast<unsigned char>(*p2)]) return false; } return true; } } //! \endcond /////////////////////////////////////////////////////////////////////// // Memory pool //! This class is used by the parser to create new nodes and attributes, without overheads of dynamic memory allocation. //! In most cases, you will not need to use this class directly. //! However, if you need to create nodes manually or modify names/values of nodes, //! you are encouraged to use memory_pool of relevant xml_document to allocate the memory. //! Not only is this faster than allocating them by using <code>new</code> operator, //! but also their lifetime will be tied to the lifetime of document, //! possibly simplyfing memory management. //! <br><br> //! Call allocate_node() or allocate_attribute() functions to obtain new nodes or attributes from the pool. //! You can also call allocate_string() function to allocate strings. //! Such strings can then be used as names or values of nodes without worrying about their lifetime. //! Note that there is no <code>free()</code> function -- all allocations are freed at once when clear() function is called, //! or when the pool is destroyed. //! <br><br> //! It is also possible to create a standalone memory_pool, and use it //! to allocate nodes, whose lifetime will not be tied to any document. //! <br><br> //! Pool maintains <code>RAPIDXML_STATIC_POOL_SIZE</code> bytes of statically allocated memory. //! Until static memory is exhausted, no dynamic memory allocations are done. //! When static memory is exhausted, pool allocates additional blocks of memory of size <code>RAPIDXML_DYNAMIC_POOL_SIZE</code> each, //! by using global <code>new[]</code> and <code>delete[]</code> operators. //! This behaviour can be changed by setting custom allocation routines. //! Use set_allocator() function to set them. //! <br><br> //! Allocations for nodes, attributes and strings are aligned at <code>RAPIDXML_ALIGNMENT</code> bytes. //! This value defaults to the size of pointer on target architecture. //! <br><br> //! To obtain absolutely top performance from the parser, //! it is important that all nodes are allocated from a single, contiguous block of memory. //! Otherwise, cache misses when jumping between two (or more) disjoint blocks of memory can slow down parsing quite considerably. //! If required, you can tweak <code>RAPIDXML_STATIC_POOL_SIZE</code>, <code>RAPIDXML_DYNAMIC_POOL_SIZE</code> and <code>RAPIDXML_ALIGNMENT</code> //! to obtain best wasted memory to performance compromise. //! To do it, define their values before rapidxml.hpp file is included. //! \param Ch Character type of created nodes. template<class Ch = char> class memory_pool { public: //! \cond internal typedef void *(alloc_func)(std::size_t); // Type of user-defined function used to allocate memory typedef void (free_func)(void *); // Type of user-defined function used to free memory //! \endcond //! Constructs empty pool with default allocator functions. memory_pool() : m_alloc_func(0) , m_free_func(0) { init(); } //! Destroys pool and frees all the memory. //! This causes memory occupied by nodes allocated by the pool to be freed. //! Nodes allocated from the pool are no longer valid. ~memory_pool() { clear(); } //! Allocates a new node from the pool, and optionally assigns name and value to it. //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>. //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function //! will call rapidxml::parse_error_handler() function. //! \param type Type of node to create. //! \param name Name to assign to the node, or 0 to assign no name. //! \param value Value to assign to the node, or 0 to assign no value. //! \param name_size Size of name to assign, or 0 to automatically calculate size from name string. //! \param value_size Size of value to assign, or 0 to automatically calculate size from value string. //! \return Pointer to allocated node. This pointer will never be NULL. xml_node<Ch> *allocate_node(node_type type, const Ch *name = 0, const Ch *value = 0, std::size_t name_size = 0, std::size_t value_size = 0) { void *memory = allocate_aligned(sizeof(xml_node<Ch>)); xml_node<Ch> *node = new(memory) xml_node<Ch>(type); if (name) { if (name_size > 0) node->name(name, name_size); else node->name(name); } if (value) { if (value_size > 0) node->value(value, value_size); else node->value(value); } return node; } //! Allocates a new attribute from the pool, and optionally assigns name and value to it. //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>. //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function //! will call rapidxml::parse_error_handler() function. //! \param name Name to assign to the attribute, or 0 to assign no name. //! \param value Value to assign to the attribute, or 0 to assign no value. //! \param name_size Size of name to assign, or 0 to automatically calculate size from name string. //! \param value_size Size of value to assign, or 0 to automatically calculate size from value string. //! \return Pointer to allocated attribute. This pointer will never be NULL. xml_attribute<Ch> *allocate_attribute(const Ch *name = 0, const Ch *value = 0, std::size_t name_size = 0, std::size_t value_size = 0) { void *memory = allocate_aligned(sizeof(xml_attribute<Ch>)); xml_attribute<Ch> *attribute = new(memory) xml_attribute<Ch>; if (name) { if (name_size > 0) attribute->name(name, name_size); else attribute->name(name); } if (value) { if (value_size > 0) attribute->value(value, value_size); else attribute->value(value); } return attribute; } //! Allocates a char array of given size from the pool, and optionally copies a given string to it. //! If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>. //! If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function //! will call rapidxml::parse_error_handler() function. //! \param source String to initialize the allocated memory with, or 0 to not initialize it. //! \param size Number of characters to allocate, or zero to calculate it automatically from source string length; if size is 0, source string must be specified and null terminated. //! \return Pointer to allocated char array. This pointer will never be NULL. Ch *allocate_string(const Ch *source = 0, std::size_t size = 0) { assert(source || size); // Either source or size (or both) must be specified if (size == 0) size = internal::measure(source) + 1; Ch *result = static_cast<Ch *>(allocate_aligned(size * sizeof(Ch))); if (source) for (std::size_t i = 0; i < size; ++i) result[i] = source[i]; return result; } //! Clones an xml_node and its hierarchy of child nodes and attributes. //! Nodes and attributes are allocated from this memory pool. //! Names and values are not cloned, they are shared between the clone and the source. //! Result node can be optionally specified as a second parameter, //! in which case its contents will be replaced with cloned source node. //! This is useful when you want to clone entire document. //! \param source Node to clone. //! \param result Node to put results in, or 0 to automatically allocate result node //! \return Pointer to cloned node. This pointer will never be NULL. xml_node<Ch> *clone_node(const xml_node<Ch> *source, xml_node<Ch> *result = 0) { // Prepare result node if (result) { result->remove_all_attributes(); result->remove_all_nodes(); result->type(source->type()); } else result = allocate_node(source->type()); // Clone name and value result->name(source->name(), source->name_size()); result->value(source->value(), source->value_size()); // Clone child nodes and attributes for (xml_node<Ch> *child = source->first_node(); child; child = child->next_sibling()) result->append_node(clone_node(child)); for (xml_attribute<Ch> *attr = source->first_attribute(); attr; attr = attr->next_attribute()) result->append_attribute(allocate_attribute(attr->name(), attr->value(), attr->name_size(), attr->value_size())); return result; } //! Clears the pool. //! This causes memory occupied by nodes allocated by the pool to be freed. //! Any nodes or strings allocated from the pool will no longer be valid. void clear() { while (m_begin != m_static_memory) { char *previous_begin = reinterpret_cast<header *>(align(m_begin))->previous_begin; if (m_free_func) m_free_func(m_begin); else delete[] m_begin; m_begin = previous_begin; } init(); } //! Sets or resets the user-defined memory allocation functions for the pool. //! This can only be called when no memory is allocated from the pool yet, otherwise results are undefined. //! Allocation function must not return invalid pointer on failure. It should either throw, //! stop the program, or use <code>longjmp()</code> function to pass control to other place of program. //! If it returns invalid pointer, results are undefined. //! <br><br> //! User defined allocation functions must have the following forms: //! <br><code> //! <br>void *allocate(std::size_t size); //! <br>void free(void *pointer); //! </code><br> //! \param af Allocation function, or 0 to restore default function //! \param ff Free function, or 0 to restore default function void set_allocator(alloc_func *af, free_func *ff) { assert(m_begin == m_static_memory && m_ptr == align(m_begin)); // Verify that no memory is allocated yet m_alloc_func = af; m_free_func = ff; } private: struct header { char *previous_begin; }; void init() { m_begin = m_static_memory; m_ptr = align(m_begin); m_end = m_static_memory + sizeof(m_static_memory); } char *align(char *ptr) { std::size_t alignment = ((RAPIDXML_ALIGNMENT - (std::size_t(ptr) & (RAPIDXML_ALIGNMENT - 1))) & (RAPIDXML_ALIGNMENT - 1)); return ptr + alignment; } char *allocate_raw(std::size_t size) { // Allocate void *memory; if (m_alloc_func) // Allocate memory using either user-specified allocation function or global operator new[] { memory = m_alloc_func(size); assert(memory); // Allocator is not allowed to return 0, on failure it must either throw, stop the program or use longjmp } else { memory = new char[size]; #ifdef RAPIDXML_NO_EXCEPTIONS if (!memory) // If exceptions are disabled, verify memory allocation, because new will not be able to throw bad_alloc RAPIDXML_PARSE_ERROR("out of memory", 0); #endif } return static_cast<char *>(memory); } void *allocate_aligned(std::size_t size) { // Calculate aligned pointer char *result = align(m_ptr); // If not enough memory left in current pool, allocate a new pool if (result + size > m_end) { // Calculate required pool size (may be bigger than RAPIDXML_DYNAMIC_POOL_SIZE) std::size_t pool_size = RAPIDXML_DYNAMIC_POOL_SIZE; if (pool_size < size) pool_size = size; // Allocate std::size_t alloc_size = sizeof(header) + (2 * RAPIDXML_ALIGNMENT - 2) + pool_size; // 2 alignments required in worst case: one for header, one for actual allocation char *raw_memory = allocate_raw(alloc_size); // Setup new pool in allocated memory char *pool = align(raw_memory); header *new_header = reinterpret_cast<header *>(pool); new_header->previous_begin = m_begin; m_begin = raw_memory; m_ptr = pool + sizeof(header); m_end = raw_memory + alloc_size; // Calculate aligned pointer again using new pool result = align(m_ptr); } // Update pool and return aligned pointer m_ptr = result + size; return result; } char *m_begin; // Start of raw memory making up current pool char *m_ptr; // First free byte in current pool char *m_end; // One past last available byte in current pool char m_static_memory[RAPIDXML_STATIC_POOL_SIZE]; // Static raw memory alloc_func *m_alloc_func; // Allocator function, or 0 if default is to be used free_func *m_free_func; // Free function, or 0 if default is to be used }; /////////////////////////////////////////////////////////////////////////// // XML base //! Base class for xml_node and xml_attribute implementing common functions: //! name(), name_size(), value(), value_size() and parent(). //! \param Ch Character type to use template<class Ch = char> class xml_base { public: /////////////////////////////////////////////////////////////////////////// // Construction & destruction // Construct a base with empty name, value and parent xml_base() : m_name(0) , m_value(0) , m_parent(0) { } /////////////////////////////////////////////////////////////////////////// // Node data access //! Gets name of the node. //! Interpretation of name depends on type of node. //! Note that name will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse. //! <br><br> //! Use name_size() function to determine length of the name. //! \return Name of node, or empty string if node has no name. Ch *name() const { return m_name ? m_name : nullstr(); } //! Gets size of node name, not including terminator character. //! This function works correctly irrespective of whether name is or is not zero terminated. //! \return Size of node name, in characters. std::size_t name_size() const { return m_name ? m_name_size : 0; } //! Gets value of node. //! Interpretation of value depends on type of node. //! Note that value will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse. //! <br><br> //! Use value_size() function to determine length of the value. //! \return Value of node, or empty string if node has no value. Ch *value() const { return m_value ? m_value : nullstr(); } //! Gets size of node value, not including terminator character. //! This function works correctly irrespective of whether value is or is not zero terminated. //! \return Size of node value, in characters. std::size_t value_size() const { return m_value ? m_value_size : 0; } /////////////////////////////////////////////////////////////////////////// // Node modification //! Sets name of node to a non zero-terminated string. //! See \ref ownership_of_strings. //! <br><br> //! Note that node does not own its name or value, it only stores a pointer to it. //! It will not delete or otherwise free the pointer on destruction. //! It is reponsibility of the user to properly manage lifetime of the string. //! The easiest way to achieve it is to use memory_pool of the document to allocate the string - //! on destruction of the document the string will be automatically freed. //! <br><br> //! Size of name must be specified separately, because name does not have to be zero terminated. //! Use name(const Ch *) function to have the length automatically calculated (string must be zero terminated). //! \param name Name of node to set. Does not have to be zero terminated. //! \param size Size of name, in characters. This does not include zero terminator, if one is present. void name(const Ch *name, std::size_t size) { m_name = const_cast<Ch *>(name); m_name_size = size; } //! Sets name of node to a zero-terminated string. //! See also \ref ownership_of_strings and xml_node::name(const Ch *, std::size_t). //! \param name Name of node to set. Must be zero terminated. void name(const Ch *name) { this->name(name, internal::measure(name)); } //! Sets value of node to a non zero-terminated string. //! See \ref ownership_of_strings. //! <br><br> //! Note that node does not own its name or value, it only stores a pointer to it. //! It will not delete or otherwise free the pointer on destruction. //! It is reponsibility of the user to properly manage lifetime of the string. //! The easiest way to achieve it is to use memory_pool of the document to allocate the string - //! on destruction of the document the string will be automatically freed. //! <br><br> //! Size of value must be specified separately, because it does not have to be zero terminated. //! Use value(const Ch *) function to have the length automatically calculated (string must be zero terminated). //! <br><br> //! If an element has a child node of type node_data, it will take precedence over element value when printing. //! If you want to manipulate data of elements using values, use parser flag rapidxml::parse_no_data_nodes to prevent creation of data nodes by the parser. //! \param value value of node to set. Does not have to be zero terminated. //! \param size Size of value, in characters. This does not include zero terminator, if one is present. void value(const Ch *value, std::size_t size) { m_value = const_cast<Ch *>(value); m_value_size = size; } //! Sets value of node to a zero-terminated string. //! See also \ref ownership_of_strings and xml_node::value(const Ch *, std::size_t). //! \param value Vame of node to set. Must be zero terminated. void value(const Ch *value) { this->value(value, internal::measure(value)); } /////////////////////////////////////////////////////////////////////////// // Related nodes access //! Gets node parent. //! \return Pointer to parent node, or 0 if there is no parent. xml_node<Ch> *parent() const { return m_parent; } protected: // Return empty string static Ch *nullstr() { static Ch zero = Ch('\0'); return &zero; } Ch *m_name; // Name of node, or 0 if no name Ch *m_value; // Value of node, or 0 if no value std::size_t m_name_size; // Length of node name, or undefined of no name std::size_t m_value_size; // Length of node value, or undefined if no value xml_node<Ch> *m_parent; // Pointer to parent node, or 0 if none }; //! Class representing attribute node of XML document. //! Each attribute has name and value strings, which are available through name() and value() functions (inherited from xml_base). //! Note that after parse, both name and value of attribute will point to interior of source text used for parsing. //! Thus, this text must persist in memory for the lifetime of attribute. //! \param Ch Character type to use. template<class Ch = char> class xml_attribute: public xml_base<Ch> { friend class xml_node<Ch>; public: /////////////////////////////////////////////////////////////////////////// // Construction & destruction //! Constructs an empty attribute with the specified type. //! Consider using memory_pool of appropriate xml_document if allocating attributes manually. xml_attribute() { } /////////////////////////////////////////////////////////////////////////// // Related nodes access //! Gets document of which attribute is a child. //! \return Pointer to document that contains this attribute, or 0 if there is no parent document. xml_document<Ch> *document() const { if (xml_node<Ch> *node = this->parent()) { while (node->parent()) node = node->parent(); return node->type() == node_document ? static_cast<xml_document<Ch> *>(node) : 0; } else return 0; } //! Gets previous attribute, optionally matching attribute name. //! \param name Name of attribute to find, or 0 to return previous attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found attribute, or 0 if not found. xml_attribute<Ch> *previous_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_attribute<Ch> *attribute = m_prev_attribute; attribute; attribute = attribute->m_prev_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive)) return attribute; return 0; } else return this->m_parent ? m_prev_attribute : 0; } //! Gets next attribute, optionally matching attribute name. //! \param name Name of attribute to find, or 0 to return next attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found attribute, or 0 if not found. xml_attribute<Ch> *next_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_attribute<Ch> *attribute = m_next_attribute; attribute; attribute = attribute->m_next_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive)) return attribute; return 0; } else return this->m_parent ? m_next_attribute : 0; } private: xml_attribute<Ch> *m_prev_attribute; // Pointer to previous sibling of attribute, or 0 if none; only valid if parent is non-zero xml_attribute<Ch> *m_next_attribute; // Pointer to next sibling of attribute, or 0 if none; only valid if parent is non-zero }; /////////////////////////////////////////////////////////////////////////// // XML node //! Class representing a node of XML document. //! Each node may have associated name and value strings, which are available through name() and value() functions. //! Interpretation of name and value depends on type of the node. //! Type of node can be determined by using type() function. //! <br><br> //! Note that after parse, both name and value of node, if any, will point interior of source text used for parsing. //! Thus, this text must persist in the memory for the lifetime of node. //! \param Ch Character type to use. template<class Ch = char> class xml_node: public xml_base<Ch> { public: /////////////////////////////////////////////////////////////////////////// // Construction & destruction //! Constructs an empty node with the specified type. //! Consider using memory_pool of appropriate document to allocate nodes manually. //! \param type Type of node to construct. xml_node(node_type type) : m_type(type) , m_first_node(0) , m_first_attribute(0) { } /////////////////////////////////////////////////////////////////////////// // Node data access //! Gets type of node. //! \return Type of node. node_type type() const { return m_type; } /////////////////////////////////////////////////////////////////////////// // Related nodes access //! Gets document of which node is a child. //! \return Pointer to document that contains this node, or 0 if there is no parent document. xml_document<Ch> *document() const { xml_node<Ch> *node = const_cast<xml_node<Ch> *>(this); while (node->parent()) node = node->parent(); return node->type() == node_document ? static_cast<xml_document<Ch> *>(node) : 0; } //! Gets first child node, optionally matching node name. //! \param name Name of child to find, or 0 to return first child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found child, or 0 if not found. xml_node<Ch> *first_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_node<Ch> *child = m_first_node; child; child = child->next_sibling()) if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive)) return child; return 0; } else return m_first_node; } //! Gets last child node, optionally matching node name. //! Behaviour is undefined if node has no children. //! Use first_node() to test if node has children. //! \param name Name of child to find, or 0 to return last child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found child, or 0 if not found. xml_node<Ch> *last_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { assert(m_first_node); // Cannot query for last child if node has no children if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_node<Ch> *child = m_last_node; child; child = child->previous_sibling()) if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive)) return child; return 0; } else return m_last_node; } //! Gets previous sibling node, optionally matching node name. //! Behaviour is undefined if node has no parent. //! Use parent() to test if node has a parent. //! \param name Name of sibling to find, or 0 to return previous sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found sibling, or 0 if not found. xml_node<Ch> *previous_sibling(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { assert(this->m_parent); // Cannot query for siblings if node has no parent if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_node<Ch> *sibling = m_prev_sibling; sibling; sibling = sibling->m_prev_sibling) if (internal::compare(sibling->name(), sibling->name_size(), name, name_size, case_sensitive)) return sibling; return 0; } else return m_prev_sibling; } //! Gets next sibling node, optionally matching node name. //! Behaviour is undefined if node has no parent. //! Use parent() to test if node has a parent. //! \param name Name of sibling to find, or 0 to return next sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found sibling, or 0 if not found. xml_node<Ch> *next_sibling(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { assert(this->m_parent); // Cannot query for siblings if node has no parent if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_node<Ch> *sibling = m_next_sibling; sibling; sibling = sibling->m_next_sibling) if (internal::compare(sibling->name(), sibling->name_size(), name, name_size, case_sensitive)) return sibling; return 0; } else return m_next_sibling; } //! Gets first attribute of node, optionally matching attribute name. //! \param name Name of attribute to find, or 0 to return first attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found attribute, or 0 if not found. xml_attribute<Ch> *first_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_attribute<Ch> *attribute = m_first_attribute; attribute; attribute = attribute->m_next_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive)) return attribute; return 0; } else return m_first_attribute; } //! Gets last attribute of node, optionally matching attribute name. //! \param name Name of attribute to find, or 0 to return last attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters //! \return Pointer to found attribute, or 0 if not found. xml_attribute<Ch> *last_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const { if (name) { if (name_size == 0) name_size = internal::measure(name); for (xml_attribute<Ch> *attribute = m_last_attribute; attribute; attribute = attribute->m_prev_attribute) if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive)) return attribute; return 0; } else return m_first_attribute ? m_last_attribute : 0; } /////////////////////////////////////////////////////////////////////////// // Node modification //! Sets type of node. //! \param type Type of node to set. void type(node_type type) { m_type = type; } /////////////////////////////////////////////////////////////////////////// // Node manipulation //! Prepends a new child node. //! The prepended child becomes the first child, and all existing children are moved one position back. //! \param child Node to prepend. void prepend_node(xml_node<Ch> *child) { assert(child && !child->parent() && child->type() != node_document); if (first_node()) { child->m_next_sibling = m_first_node; m_first_node->m_prev_sibling = child; } else { child->m_next_sibling = 0; m_last_node = child; } m_first_node = child; child->m_parent = this; child->m_prev_sibling = 0; } //! Appends a new child node. //! The appended child becomes the last child. //! \param child Node to append. void append_node(xml_node<Ch> *child) { assert(child && !child->parent() && child->type() != node_document); if (first_node()) { child->m_prev_sibling = m_last_node; m_last_node->m_next_sibling = child; } else { child->m_prev_sibling = 0; m_first_node = child; } m_last_node = child; child->m_parent = this; child->m_next_sibling = 0; } //! Inserts a new child node at specified place inside the node. //! All children after and including the specified node are moved one position back. //! \param where Place where to insert the child, or 0 to insert at the back. //! \param child Node to insert. void insert_node(xml_node<Ch> *where, xml_node<Ch> *child) { assert(!where || where->parent() == this); assert(child && !child->parent() && child->type() != node_document); if (where == m_first_node) prepend_node(child); else if (where == 0) append_node(child); else { child->m_prev_sibling = where->m_prev_sibling; child->m_next_sibling = where; where->m_prev_sibling->m_next_sibling = child; where->m_prev_sibling = child; child->m_parent = this; } } //! Removes first child node. //! If node has no children, behaviour is undefined. //! Use first_node() to test if node has children. void remove_first_node() { assert(first_node()); xml_node<Ch> *child = m_first_node; m_first_node = child->m_next_sibling; if (child->m_next_sibling) child->m_next_sibling->m_prev_sibling = 0; else m_last_node = 0; child->m_parent = 0; } //! Removes last child of the node. //! If node has no children, behaviour is undefined. //! Use first_node() to test if node has children. void remove_last_node() { assert(first_node()); xml_node<Ch> *child = m_last_node; if (child->m_prev_sibling) { m_last_node = child->m_prev_sibling; child->m_prev_sibling->m_next_sibling = 0; } else m_first_node = 0; child->m_parent = 0; } //! Removes specified child from the node // \param where Pointer to child to be removed. void remove_node(xml_node<Ch> *where) { assert(where && where->parent() == this); assert(first_node()); if (where == m_first_node) remove_first_node(); else if (where == m_last_node) remove_last_node(); else { where->m_prev_sibling->m_next_sibling = where->m_next_sibling; where->m_next_sibling->m_prev_sibling = where->m_prev_sibling; where->m_parent = 0; } } //! Removes all child nodes (but not attributes). void remove_all_nodes() { for (xml_node<Ch> *node = first_node(); node; node = node->m_next_sibling) node->m_parent = 0; m_first_node = 0; } //! Prepends a new attribute to the node. //! \param attribute Attribute to prepend. void prepend_attribute(xml_attribute<Ch> *attribute) { assert(attribute && !attribute->parent()); if (first_attribute()) { attribute->m_next_attribute = m_first_attribute; m_first_attribute->m_prev_attribute = attribute; } else { attribute->m_next_attribute = 0; m_last_attribute = attribute; } m_first_attribute = attribute; attribute->m_parent = this; attribute->m_prev_attribute = 0; } //! Appends a new attribute to the node. //! \param attribute Attribute to append. void append_attribute(xml_attribute<Ch> *attribute) { assert(attribute && !attribute->parent()); if (first_attribute()) { attribute->m_prev_attribute = m_last_attribute; m_last_attribute->m_next_attribute = attribute; } else { attribute->m_prev_attribute = 0; m_first_attribute = attribute; } m_last_attribute = attribute; attribute->m_parent = this; attribute->m_next_attribute = 0; } //! Inserts a new attribute at specified place inside the node. //! All attributes after and including the specified attribute are moved one position back. //! \param where Place where to insert the attribute, or 0 to insert at the back. //! \param attribute Attribute to insert. void insert_attribute(xml_attribute<Ch> *where, xml_attribute<Ch> *attribute) { assert(!where || where->parent() == this); assert(attribute && !attribute->parent()); if (where == m_first_attribute) prepend_attribute(attribute); else if (where == 0) append_attribute(attribute); else { attribute->m_prev_attribute = where->m_prev_attribute; attribute->m_next_attribute = where; where->m_prev_attribute->m_next_attribute = attribute; where->m_prev_attribute = attribute; attribute->m_parent = this; } } //! Removes first attribute of the node. //! If node has no attributes, behaviour is undefined. //! Use first_attribute() to test if node has attributes. void remove_first_attribute() { assert(first_attribute()); xml_attribute<Ch> *attribute = m_first_attribute; if (attribute->m_next_attribute) { attribute->m_next_attribute->m_prev_attribute = 0; } else m_last_attribute = 0; attribute->m_parent = 0; m_first_attribute = attribute->m_next_attribute; } //! Removes last attribute of the node. //! If node has no attributes, behaviour is undefined. //! Use first_attribute() to test if node has attributes. void remove_last_attribute() { assert(first_attribute()); xml_attribute<Ch> *attribute = m_last_attribute; if (attribute->m_prev_attribute) { attribute->m_prev_attribute->m_next_attribute = 0; m_last_attribute = attribute->m_prev_attribute; } else m_first_attribute = 0; attribute->m_parent = 0; } //! Removes specified attribute from node. //! \param where Pointer to attribute to be removed. void remove_attribute(xml_attribute<Ch> *where) { assert(first_attribute() && where->parent() == this); if (where == m_first_attribute) remove_first_attribute(); else if (where == m_last_attribute) remove_last_attribute(); else { where->m_prev_attribute->m_next_attribute = where->m_next_attribute; where->m_next_attribute->m_prev_attribute = where->m_prev_attribute; where->m_parent = 0; } } //! Removes all attributes of node. void remove_all_attributes() { for (xml_attribute<Ch> *attribute = first_attribute(); attribute; attribute = attribute->m_next_attribute) attribute->m_parent = 0; m_first_attribute = 0; } private: /////////////////////////////////////////////////////////////////////////// // Restrictions // No copying xml_node(const xml_node &); void operator =(const xml_node &); /////////////////////////////////////////////////////////////////////////// // Data members // Note that some of the pointers below have UNDEFINED values if certain other pointers are 0. // This is required for maximum performance, as it allows the parser to omit initialization of // unneded/redundant values. // // The rules are as follows: // 1. first_node and first_attribute contain valid pointers, or 0 if node has no children/attributes respectively // 2. last_node and last_attribute are valid only if node has at least one child/attribute respectively, otherwise they contain garbage // 3. prev_sibling and next_sibling are valid only if node has a parent, otherwise they contain garbage node_type m_type; // Type of node; always valid xml_node<Ch> *m_first_node; // Pointer to first child node, or 0 if none; always valid xml_node<Ch> *m_last_node; // Pointer to last child node, or 0 if none; this value is only valid if m_first_node is non-zero xml_attribute<Ch> *m_first_attribute; // Pointer to first attribute of node, or 0 if none; always valid xml_attribute<Ch> *m_last_attribute; // Pointer to last attribute of node, or 0 if none; this value is only valid if m_first_attribute is non-zero xml_node<Ch> *m_prev_sibling; // Pointer to previous sibling of node, or 0 if none; this value is only valid if m_parent is non-zero xml_node<Ch> *m_next_sibling; // Pointer to next sibling of node, or 0 if none; this value is only valid if m_parent is non-zero }; /////////////////////////////////////////////////////////////////////////// // XML document //! This class represents root of the DOM hierarchy. //! It is also an xml_node and a memory_pool through public inheritance. //! Use parse() function to build a DOM tree from a zero-terminated XML text string. //! parse() function allocates memory for nodes and attributes by using functions of xml_document, //! which are inherited from memory_pool. //! To access root node of the document, use the document itself, as if it was an xml_node. //! \param Ch Character type to use. template<class Ch = char> class xml_document: public xml_node<Ch>, public memory_pool<Ch> { public: //! Constructs empty XML document xml_document() : xml_node<Ch>(node_document) { } //! Parses zero-terminated XML string according to given flags. //! Passed string will be modified by the parser, unless rapidxml::parse_non_destructive flag is used. //! The string must persist for the lifetime of the document. //! In case of error, rapidxml::parse_error exception will be thrown. //! <br><br> //! If you want to parse contents of a file, you must first load the file into the memory, and pass pointer to its beginning. //! Make sure that data is zero-terminated. //! <br><br> //! Document can be parsed into multiple times. //! Each new call to parse removes previous nodes and attributes (if any), but does not clear memory pool. //! \param text XML data to parse; pointer is non-const to denote fact that this data may be modified by the parser. template<int Flags> void parse(Ch *text) { assert(text); // Remove current contents this->remove_all_nodes(); this->remove_all_attributes(); // Parse BOM, if any parse_bom<Flags>(text); // Parse children while (1) { // Skip whitespace before node skip<whitespace_pred, Flags>(text); if (*text == 0) break; // Parse and append new child if (*text == Ch('<')) { ++text; // Skip '<' if (xml_node<Ch> *node = parse_node<Flags>(text)) this->append_node(node); } else RAPIDXML_PARSE_ERROR("expected <", text); } } //! Clears the document by deleting all nodes and clearing the memory pool. //! All nodes owned by document pool are destroyed. void clear() { this->remove_all_nodes(); this->remove_all_attributes(); memory_pool<Ch>::clear(); } private: /////////////////////////////////////////////////////////////////////// // Internal character utility functions // Detect whitespace character struct whitespace_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_whitespace[static_cast<unsigned char>(ch)]; } }; // Detect node name character struct node_name_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_node_name[static_cast<unsigned char>(ch)]; } }; // Detect attribute name character struct attribute_name_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_attribute_name[static_cast<unsigned char>(ch)]; } }; // Detect text character (PCDATA) struct text_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_text[static_cast<unsigned char>(ch)]; } }; // Detect text character (PCDATA) that does not require processing struct text_pure_no_ws_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_text_pure_no_ws[static_cast<unsigned char>(ch)]; } }; // Detect text character (PCDATA) that does not require processing struct text_pure_with_ws_pred { static unsigned char test(Ch ch) { return internal::lookup_tables<0>::lookup_text_pure_with_ws[static_cast<unsigned char>(ch)]; } }; // Detect attribute value character template<Ch Quote> struct attribute_value_pred { static unsigned char test(Ch ch) { if (Quote == Ch('\'')) return internal::lookup_tables<0>::lookup_attribute_data_1[static_cast<unsigned char>(ch)]; if (Quote == Ch('\"')) return internal::lookup_tables<0>::lookup_attribute_data_2[static_cast<unsigned char>(ch)]; return 0; // Should never be executed, to avoid warnings on Comeau } }; // Detect attribute value character template<Ch Quote> struct attribute_value_pure_pred { static unsigned char test(Ch ch) { if (Quote == Ch('\'')) return internal::lookup_tables<0>::lookup_attribute_data_1_pure[static_cast<unsigned char>(ch)]; if (Quote == Ch('\"')) return internal::lookup_tables<0>::lookup_attribute_data_2_pure[static_cast<unsigned char>(ch)]; return 0; // Should never be executed, to avoid warnings on Comeau } }; // Insert coded character, using UTF8 or 8-bit ASCII template<int Flags> static void insert_coded_character(Ch *&text, unsigned long code) { if (Flags & parse_no_utf8) { // Insert 8-bit ASCII character // Todo: possibly verify that code is less than 256 and use replacement char otherwise? text[0] = static_cast<unsigned char>(code); text += 1; } else { // Insert UTF8 sequence if (code < 0x80) // 1 byte sequence { text[0] = static_cast<unsigned char>(code); text += 1; } else if (code < 0x800) // 2 byte sequence { text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[0] = static_cast<unsigned char>(code | 0xC0); text += 2; } else if (code < 0x10000) // 3 byte sequence { text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[0] = static_cast<unsigned char>(code | 0xE0); text += 3; } else if (code < 0x110000) // 4 byte sequence { text[3] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; text[0] = static_cast<unsigned char>(code | 0xF0); text += 4; } else // Invalid, only codes up to 0x10FFFF are allowed in Unicode { RAPIDXML_PARSE_ERROR("invalid numeric character entity", text); } } } // Skip characters until predicate evaluates to true template<class StopPred, int Flags> static void skip(Ch *&text) { Ch *tmp = text; while (StopPred::test(*tmp)) ++tmp; text = tmp; } // Skip characters until predicate evaluates to true while doing the following: // - replacing XML character entity references with proper characters (&apos; &amp; &quot; &lt; &gt; &#...;) // - condensing whitespace sequences to single space character template<class StopPred, class StopPredPure, int Flags> static Ch *skip_and_expand_character_refs(Ch *&text) { // If entity translation, whitespace condense and whitespace trimming is disabled, use plain skip if (Flags & parse_no_entity_translation && !(Flags & parse_normalize_whitespace) && !(Flags & parse_trim_whitespace)) { skip<StopPred, Flags>(text); return text; } // Use simple skip until first modification is detected skip<StopPredPure, Flags>(text); // Use translation skip Ch *src = text; Ch *dest = src; while (StopPred::test(*src)) { // If entity translation is enabled if (!(Flags & parse_no_entity_translation)) { // Test if replacement is needed if (src[0] == Ch('&')) { switch (src[1]) { // &amp; &apos; case Ch('a'): if (src[2] == Ch('m') && src[3] == Ch('p') && src[4] == Ch(';')) { *dest = Ch('&'); ++dest; src += 5; continue; } if (src[2] == Ch('p') && src[3] == Ch('o') && src[4] == Ch('s') && src[5] == Ch(';')) { *dest = Ch('\''); ++dest; src += 6; continue; } break; // &quot; case Ch('q'): if (src[2] == Ch('u') && src[3] == Ch('o') && src[4] == Ch('t') && src[5] == Ch(';')) { *dest = Ch('"'); ++dest; src += 6; continue; } break; // &gt; case Ch('g'): if (src[2] == Ch('t') && src[3] == Ch(';')) { *dest = Ch('>'); ++dest; src += 4; continue; } break; // &lt; case Ch('l'): if (src[2] == Ch('t') && src[3] == Ch(';')) { *dest = Ch('<'); ++dest; src += 4; continue; } break; // &#...; - assumes ASCII case Ch('#'): if (src[2] == Ch('x')) { unsigned long code = 0; src += 3; // Skip &#x while (1) { unsigned char digit = internal::lookup_tables<0>::lookup_digits[static_cast<unsigned char>(*src)]; if (digit == 0xFF) break; code = code * 16 + digit; ++src; } insert_coded_character<Flags>(dest, code); // Put character in output } else { unsigned long code = 0; src += 2; // Skip &# while (1) { unsigned char digit = internal::lookup_tables<0>::lookup_digits[static_cast<unsigned char>(*src)]; if (digit == 0xFF) break; code = code * 10 + digit; ++src; } insert_coded_character<Flags>(dest, code); // Put character in output } if (*src == Ch(';')) ++src; else RAPIDXML_PARSE_ERROR("expected ;", src); continue; // Something else default: // Ignore, just copy '&' verbatim break; } } } // If whitespace condensing is enabled if (Flags & parse_normalize_whitespace) { // Test if condensing is needed if (whitespace_pred::test(*src)) { *dest = Ch(' '); ++dest; // Put single space in dest ++src; // Skip first whitespace char // Skip remaining whitespace chars while (whitespace_pred::test(*src)) ++src; continue; } } // No replacement, only copy character *dest++ = *src++; } // Return new end text = src; return dest; } /////////////////////////////////////////////////////////////////////// // Internal parsing functions // Parse BOM, if any template<int Flags> void parse_bom(Ch *&text) { // UTF-8? if (static_cast<unsigned char>(text[0]) == 0xEF && static_cast<unsigned char>(text[1]) == 0xBB && static_cast<unsigned char>(text[2]) == 0xBF) { text += 3; // Skup utf-8 bom } } // Parse XML declaration (<?xml...) template<int Flags> xml_node<Ch> *parse_xml_declaration(Ch *&text) { // If parsing of declaration is disabled if (!(Flags & parse_declaration_node)) { // Skip until end of declaration while (text[0] != Ch('?') || text[1] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } text += 2; // Skip '?>' return 0; } // Create declaration xml_node<Ch> *declaration = this->allocate_node(node_declaration); // Skip whitespace before attributes or ?> skip<whitespace_pred, Flags>(text); // Parse declaration attributes parse_node_attributes<Flags>(text, declaration); // Skip ?> if (text[0] != Ch('?') || text[1] != Ch('>')) RAPIDXML_PARSE_ERROR("expected ?>", text); text += 2; return declaration; } // Parse XML comment (<!--...) template<int Flags> xml_node<Ch> *parse_comment(Ch *&text) { // If parsing of comments is disabled if (!(Flags & parse_comment_nodes)) { // Skip until end of comment while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } text += 3; // Skip '-->' return 0; // Do not produce comment node } // Remember value start Ch *value = text; // Skip until end of comment while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } // Create comment node xml_node<Ch> *comment = this->allocate_node(node_comment); comment->value(value, text - value); // Place zero terminator after comment value if (!(Flags & parse_no_string_terminators)) *text = Ch('\0'); text += 3; // Skip '-->' return comment; } // Parse DOCTYPE template<int Flags> xml_node<Ch> *parse_doctype(Ch *&text) { // Remember value start Ch *value = text; // Skip to > while (*text != Ch('>')) { // Determine character type switch (*text) { // If '[' encountered, scan for matching ending ']' using naive algorithm with depth // This works for all W3C test files except for 2 most wicked case Ch('['): { ++text; // Skip '[' int depth = 1; while (depth > 0) { switch (*text) { case Ch('['): ++depth; break; case Ch(']'): --depth; break; case 0: RAPIDXML_PARSE_ERROR("unexpected end of data", text); } ++text; } break; } // Error on end of text case Ch('\0'): RAPIDXML_PARSE_ERROR("unexpected end of data", text); // Other character, skip it default: ++text; } } // If DOCTYPE nodes enabled if (Flags & parse_doctype_node) { // Create a new doctype node xml_node<Ch> *doctype = this->allocate_node(node_doctype); doctype->value(value, text - value); // Place zero terminator after value if (!(Flags & parse_no_string_terminators)) *text = Ch('\0'); text += 1; // skip '>' return doctype; } else { text += 1; // skip '>' return 0; } } // Parse PI template<int Flags> xml_node<Ch> *parse_pi(Ch *&text) { // If creation of PI nodes is enabled if (Flags & parse_pi_nodes) { // Create pi node xml_node<Ch> *pi = this->allocate_node(node_pi); // Extract PI target name Ch *name = text; skip<node_name_pred, Flags>(text); if (text == name) RAPIDXML_PARSE_ERROR("expected PI target", text); pi->name(name, text - name); // Skip whitespace between pi target and pi skip<whitespace_pred, Flags>(text); // Remember start of pi Ch *value = text; // Skip to '?>' while (text[0] != Ch('?') || text[1] != Ch('>')) { if (*text == Ch('\0')) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } // Set pi value (verbatim, no entity expansion or whitespace normalization) pi->value(value, text - value); // Place zero terminator after name and value if (!(Flags & parse_no_string_terminators)) { pi->name()[pi->name_size()] = Ch('\0'); pi->value()[pi->value_size()] = Ch('\0'); } text += 2; // Skip '?>' return pi; } else { // Skip to '?>' while (text[0] != Ch('?') || text[1] != Ch('>')) { if (*text == Ch('\0')) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } text += 2; // Skip '?>' return 0; } } // Parse and append data // Return character that ends data. // This is necessary because this character might have been overwritten by a terminating 0 template<int Flags> Ch parse_and_append_data(xml_node<Ch> *node, Ch *&text, Ch *contents_start) { // Backup to contents start if whitespace trimming is disabled if (!(Flags & parse_trim_whitespace)) text = contents_start; // Skip until end of data Ch *value = text, *end; if (Flags & parse_normalize_whitespace) end = skip_and_expand_character_refs<text_pred, text_pure_with_ws_pred, Flags>(text); else end = skip_and_expand_character_refs<text_pred, text_pure_no_ws_pred, Flags>(text); // Trim trailing whitespace if flag is set; leading was already trimmed by whitespace skip after > if (Flags & parse_trim_whitespace) { if (Flags & parse_normalize_whitespace) { // Whitespace is already condensed to single space characters by skipping function, so just trim 1 char off the end if (*(end - 1) == Ch(' ')) --end; } else { // Backup until non-whitespace character is found while (whitespace_pred::test(*(end - 1))) --end; } } // If characters are still left between end and value (this test is only necessary if normalization is enabled) // Create new data node if (!(Flags & parse_no_data_nodes)) { xml_node<Ch> *data = this->allocate_node(node_data); data->value(value, end - value); node->append_node(data); } // Add data to parent node if no data exists yet if (!(Flags & parse_no_element_values)) if (*node->value() == Ch('\0')) node->value(value, end - value); // Place zero terminator after value if (!(Flags & parse_no_string_terminators)) { Ch ch = *text; *end = Ch('\0'); return ch; // Return character that ends data; this is required because zero terminator overwritten it } // Return character that ends data return *text; } // Parse CDATA template<int Flags> xml_node<Ch> *parse_cdata(Ch *&text) { // If CDATA is disabled if (Flags & parse_no_data_nodes) { // Skip until end of cdata while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } text += 3; // Skip ]]> return 0; // Do not produce CDATA node } // Skip until end of cdata Ch *value = text; while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>')) { if (!text[0]) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } // Create new cdata node xml_node<Ch> *cdata = this->allocate_node(node_cdata); cdata->value(value, text - value); // Place zero terminator after value if (!(Flags & parse_no_string_terminators)) *text = Ch('\0'); text += 3; // Skip ]]> return cdata; } // Parse element node template<int Flags> xml_node<Ch> *parse_element(Ch *&text) { // Create element node xml_node<Ch> *element = this->allocate_node(node_element); // Extract element name Ch *name = text; skip<node_name_pred, Flags>(text); if (text == name) RAPIDXML_PARSE_ERROR("expected element name", text); element->name(name, text - name); // Skip whitespace between element name and attributes or > skip<whitespace_pred, Flags>(text); // Parse attributes, if any parse_node_attributes<Flags>(text, element); // Determine ending type if (*text == Ch('>')) { ++text; parse_node_contents<Flags>(text, element); } else if (*text == Ch('/')) { ++text; if (*text != Ch('>')) RAPIDXML_PARSE_ERROR("expected >", text); ++text; } else RAPIDXML_PARSE_ERROR("expected >", text); // Place zero terminator after name if (!(Flags & parse_no_string_terminators)) element->name()[element->name_size()] = Ch('\0'); // Return parsed element return element; } // Determine node type, and parse it template<int Flags> xml_node<Ch> *parse_node(Ch *&text) { // Parse proper node type switch (text[0]) { // <... default: // Parse and append element node return parse_element<Flags>(text); // <?... case Ch('?'): ++text; // Skip ? if ((text[0] == Ch('x') || text[0] == Ch('X')) && (text[1] == Ch('m') || text[1] == Ch('M')) && (text[2] == Ch('l') || text[2] == Ch('L')) && whitespace_pred::test(text[3])) { // '<?xml ' - xml declaration text += 4; // Skip 'xml ' return parse_xml_declaration<Flags>(text); } else { // Parse PI return parse_pi<Flags>(text); } // <!... case Ch('!'): // Parse proper subset of <! node switch (text[1]) { // <!- case Ch('-'): if (text[2] == Ch('-')) { // '<!--' - xml comment text += 3; // Skip '!--' return parse_comment<Flags>(text); } break; // <![ case Ch('['): if (text[2] == Ch('C') && text[3] == Ch('D') && text[4] == Ch('A') && text[5] == Ch('T') && text[6] == Ch('A') && text[7] == Ch('[')) { // '<![CDATA[' - cdata text += 8; // Skip '![CDATA[' return parse_cdata<Flags>(text); } break; // <!D case Ch('D'): if (text[2] == Ch('O') && text[3] == Ch('C') && text[4] == Ch('T') && text[5] == Ch('Y') && text[6] == Ch('P') && text[7] == Ch('E') && whitespace_pred::test(text[8])) { // '<!DOCTYPE ' - doctype text += 9; // skip '!DOCTYPE ' return parse_doctype<Flags>(text); } } // switch // Attempt to skip other, unrecognized node types starting with <! ++text; // Skip ! while (*text != Ch('>')) { if (*text == 0) RAPIDXML_PARSE_ERROR("unexpected end of data", text); ++text; } ++text; // Skip '>' return 0; // No node recognized } } // Parse contents of the node - children, data etc. template<int Flags> void parse_node_contents(Ch *&text, xml_node<Ch> *node) { // For all children and text while (1) { // Skip whitespace between > and node contents Ch *contents_start = text; // Store start of node contents before whitespace is skipped skip<whitespace_pred, Flags>(text); Ch next_char = *text; // After data nodes, instead of continuing the loop, control jumps here. // This is because zero termination inside parse_and_append_data() function // would wreak havoc with the above code. // Also, skipping whitespace after data nodes is unnecessary. after_data_node: // Determine what comes next: node closing, child node, data node, or 0? switch (next_char) { // Node closing or child node case Ch('<'): if (text[1] == Ch('/')) { // Node closing text += 2; // Skip '</' if (Flags & parse_validate_closing_tags) { // Skip and validate closing tag name Ch *closing_name = text; skip<node_name_pred, Flags>(text); if (!internal::compare(node->name(), node->name_size(), closing_name, text - closing_name, true)) RAPIDXML_PARSE_ERROR("invalid closing tag name", text); } else { // No validation, just skip name skip<node_name_pred, Flags>(text); } // Skip remaining whitespace after node name skip<whitespace_pred, Flags>(text); if (*text != Ch('>')) RAPIDXML_PARSE_ERROR("expected >", text); ++text; // Skip '>' return; // Node closed, finished parsing contents } else { // Child node ++text; // Skip '<' if (xml_node<Ch> *child = parse_node<Flags>(text)) node->append_node(child); } break; // End of data - error case Ch('\0'): RAPIDXML_PARSE_ERROR("unexpected end of data", text); // Data node default: next_char = parse_and_append_data<Flags>(node, text, contents_start); goto after_data_node; // Bypass regular processing after data nodes } } } // Parse XML attributes of the node template<int Flags> void parse_node_attributes(Ch *&text, xml_node<Ch> *node) { // For all attributes while (attribute_name_pred::test(*text)) { // Extract attribute name Ch *name = text; ++text; // Skip first character of attribute name skip<attribute_name_pred, Flags>(text); if (text == name) RAPIDXML_PARSE_ERROR("expected attribute name", name); // Create new attribute xml_attribute<Ch> *attribute = this->allocate_attribute(); attribute->name(name, text - name); node->append_attribute(attribute); // Skip whitespace after attribute name skip<whitespace_pred, Flags>(text); // Skip = if (*text != Ch('=')) RAPIDXML_PARSE_ERROR("expected =", text); ++text; // Add terminating zero after name if (!(Flags & parse_no_string_terminators)) attribute->name()[attribute->name_size()] = 0; // Skip whitespace after = skip<whitespace_pred, Flags>(text); // Skip quote and remember if it was ' or " Ch quote = *text; if (quote != Ch('\'') && quote != Ch('"')) RAPIDXML_PARSE_ERROR("expected ' or \"", text); ++text; // Extract attribute value and expand char refs in it Ch *value = text, *end; const int AttFlags = Flags & ~parse_normalize_whitespace; // No whitespace normalization in attributes if (quote == Ch('\'')) end = skip_and_expand_character_refs<attribute_value_pred<Ch('\'')>, attribute_value_pure_pred<Ch('\'')>, AttFlags>(text); else end = skip_and_expand_character_refs<attribute_value_pred<Ch('"')>, attribute_value_pure_pred<Ch('"')>, AttFlags>(text); // Set attribute value attribute->value(value, end - value); // Make sure that end quote is present if (*text != quote) RAPIDXML_PARSE_ERROR("expected ' or \"", text); ++text; // Skip quote // Add terminating zero after value if (!(Flags & parse_no_string_terminators)) attribute->value()[attribute->value_size()] = 0; // Skip whitespace after attribute value skip<whitespace_pred, Flags>(text); } } }; //! \cond internal namespace internal { // Whitespace (space \n \r \t) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_whitespace[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, // 0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 5 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 7 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // F }; // Node name (anything but space \n \r \t / > ? \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_node_name[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Text (i.e. PCDATA) (anything but < \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_text[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Text (i.e. PCDATA) that does not require processing when ws normalization is disabled // (anything but < \0 &) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_text_pure_no_ws[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Text (i.e. PCDATA) that does not require processing when ws normalizationis is enabled // (anything but < \0 & space \n \r \t) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_text_pure_with_ws[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute name (anything but space \n \r \t / < > = ? ! \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_name[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with single quote (anything but ' \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_data_1[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with single quote that does not require processing (anything but ' \0 &) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_data_1_pure[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with double quote (anything but " \0) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_data_2[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Attribute data with double quote that does not require processing (anything but " \0 &) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_attribute_data_2_pure[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F }; // Digits (dec and hex, 255 denotes end of numeric character reference) template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_digits[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 0 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 1 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 2 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,255,255,255,255,255,255, // 3 255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 4 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 5 255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 6 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 7 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 8 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 9 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // A 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // B 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // C 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // D 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // E 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255 // F }; // Upper case conversion template<int Dummy> const unsigned char lookup_tables<Dummy>::lookup_upcase[256] = { // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A B C D E F 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, // 0 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, // 1 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, // 2 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // 3 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, // 4 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, // 5 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, // 6 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123,124,125,126,127, // 7 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, // 8 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, // 9 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175, // A 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, // B 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207, // C 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223, // D 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239, // E 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255 // F }; } //! \endcond } // Undefine internal macros #undef RAPIDXML_PARSE_ERROR // On MSVC, restore warnings state #ifdef _MSC_VER #pragma warning(pop) #endif #endif
118,341
C++
44.568733
189
0.475397
daniel-kun/omni/interface/rapidxml/rapidxml_print.hpp
#ifndef RAPIDXML_PRINT_HPP_INCLUDED #define RAPIDXML_PRINT_HPP_INCLUDED // Copyright (C) 2006, 2009 Marcin Kalicinski // Version 1.13 // Revision $DateTime: 2009/05/13 01:46:17 $ //! \file rapidxml_print.hpp This file contains rapidxml printer implementation #include "rapidxml.hpp" // Only include streams if not disabled #ifndef RAPIDXML_NO_STREAMS #include <ostream> #include <iterator> #endif namespace rapidxml { /////////////////////////////////////////////////////////////////////// // Printing flags const int print_no_indenting = 0x1; //!< Printer flag instructing the printer to suppress indenting of XML. See print() function. /////////////////////////////////////////////////////////////////////// // Internal //! \cond internal namespace internal { /////////////////////////////////////////////////////////////////////////// // Internal character operations // Copy characters from given range to given output iterator template<class OutIt, class Ch> inline OutIt copy_chars(const Ch *begin, const Ch *end, OutIt out) { while (begin != end) *out++ = *begin++; return out; } // Copy characters from given range to given output iterator and expand // characters into references (&lt; &gt; &apos; &quot; &amp;) template<class OutIt, class Ch> inline OutIt copy_and_expand_chars(const Ch *begin, const Ch *end, Ch noexpand, OutIt out) { while (begin != end) { if (*begin == noexpand) { *out++ = *begin; // No expansion, copy character } else { switch (*begin) { case Ch('<'): *out++ = Ch('&'); *out++ = Ch('l'); *out++ = Ch('t'); *out++ = Ch(';'); break; case Ch('>'): *out++ = Ch('&'); *out++ = Ch('g'); *out++ = Ch('t'); *out++ = Ch(';'); break; case Ch('\''): *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('p'); *out++ = Ch('o'); *out++ = Ch('s'); *out++ = Ch(';'); break; case Ch('"'): *out++ = Ch('&'); *out++ = Ch('q'); *out++ = Ch('u'); *out++ = Ch('o'); *out++ = Ch('t'); *out++ = Ch(';'); break; case Ch('&'): *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('m'); *out++ = Ch('p'); *out++ = Ch(';'); break; default: *out++ = *begin; // No expansion, copy character } } ++begin; // Step to next character } return out; } // Fill given output iterator with repetitions of the same character template<class OutIt, class Ch> inline OutIt fill_chars(OutIt out, int n, Ch ch) { for (int i = 0; i < n; ++i) *out++ = ch; return out; } // Find character template<class Ch, Ch ch> inline bool find_char(const Ch *begin, const Ch *end) { while (begin != end) if (*begin++ == ch) return true; return false; } /////////////////////////////////////////////////////////////////////////// // Internal printing operations // Print node template<class OutIt, class Ch> inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { // Print proper node type switch (node->type()) { // Document case node_document: out = print_children(out, node, flags, indent); break; // Element case node_element: out = print_element_node(out, node, flags, indent); break; // Data case node_data: out = print_data_node(out, node, flags, indent); break; // CDATA case node_cdata: out = print_cdata_node(out, node, flags, indent); break; // Declaration case node_declaration: out = print_declaration_node(out, node, flags, indent); break; // Comment case node_comment: out = print_comment_node(out, node, flags, indent); break; // Doctype case node_doctype: out = print_doctype_node(out, node, flags, indent); break; // Pi case node_pi: out = print_pi_node(out, node, flags, indent); break; // Unknown default: assert(0); break; } // If indenting not disabled, add line break after node if (!(flags & print_no_indenting)) *out = Ch('\n'), ++out; // Return modified iterator return out; } // Print children of the node template<class OutIt, class Ch> inline OutIt print_children(OutIt out, const xml_node<Ch> *node, int flags, int indent) { for (xml_node<Ch> *child = node->first_node(); child; child = child->next_sibling()) out = print_node(out, child, flags, indent); return out; } // Print attributes of the node template<class OutIt, class Ch> inline OutIt print_attributes(OutIt out, const xml_node<Ch> *node, int flags) { for (xml_attribute<Ch> *attribute = node->first_attribute(); attribute; attribute = attribute->next_attribute()) { if (attribute->name() && attribute->value()) { // Print attribute name *out = Ch(' '), ++out; out = copy_chars(attribute->name(), attribute->name() + attribute->name_size(), out); *out = Ch('='), ++out; // Print attribute value using appropriate quote type if (find_char<Ch, Ch('"')>(attribute->value(), attribute->value() + attribute->value_size())) { *out = Ch('\''), ++out; out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('"'), out); *out = Ch('\''), ++out; } else { *out = Ch('"'), ++out; out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('\''), out); *out = Ch('"'), ++out; } } } return out; } // Print data node template<class OutIt, class Ch> inline OutIt print_data_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { assert(node->type() == node_data); if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out); return out; } // Print data node template<class OutIt, class Ch> inline OutIt print_cdata_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { assert(node->type() == node_cdata); if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'); ++out; *out = Ch('!'); ++out; *out = Ch('['); ++out; *out = Ch('C'); ++out; *out = Ch('D'); ++out; *out = Ch('A'); ++out; *out = Ch('T'); ++out; *out = Ch('A'); ++out; *out = Ch('['); ++out; out = copy_chars(node->value(), node->value() + node->value_size(), out); *out = Ch(']'); ++out; *out = Ch(']'); ++out; *out = Ch('>'); ++out; return out; } // Print element node template<class OutIt, class Ch> inline OutIt print_element_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { assert(node->type() == node_element); // Print element name and attributes, if any if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; out = copy_chars(node->name(), node->name() + node->name_size(), out); out = print_attributes(out, node, flags); // If node is childless if (node->value_size() == 0 && !node->first_node()) { // Print childless node tag ending *out = Ch('/'), ++out; *out = Ch('>'), ++out; } else { // Print normal node tag ending *out = Ch('>'), ++out; // Test if node contains a single data node only (and no other nodes) xml_node<Ch> *child = node->first_node(); if (!child) { // If node has no children, only print its value without indenting out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out); } else if (child->next_sibling() == 0 && child->type() == node_data) { // If node has a sole data child, only print its value without indenting out = copy_and_expand_chars(child->value(), child->value() + child->value_size(), Ch(0), out); } else { // Print all children with full indenting if (!(flags & print_no_indenting)) *out = Ch('\n'), ++out; out = print_children(out, node, flags, indent + 1); if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); } // Print node end *out = Ch('<'), ++out; *out = Ch('/'), ++out; out = copy_chars(node->name(), node->name() + node->name_size(), out); *out = Ch('>'), ++out; } return out; } // Print declaration node template<class OutIt, class Ch> inline OutIt print_declaration_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { // Print declaration start if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; *out = Ch('?'), ++out; *out = Ch('x'), ++out; *out = Ch('m'), ++out; *out = Ch('l'), ++out; // Print attributes out = print_attributes(out, node, flags); // Print declaration end *out = Ch('?'), ++out; *out = Ch('>'), ++out; return out; } // Print comment node template<class OutIt, class Ch> inline OutIt print_comment_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { assert(node->type() == node_comment); if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; *out = Ch('!'), ++out; *out = Ch('-'), ++out; *out = Ch('-'), ++out; out = copy_chars(node->value(), node->value() + node->value_size(), out); *out = Ch('-'), ++out; *out = Ch('-'), ++out; *out = Ch('>'), ++out; return out; } // Print doctype node template<class OutIt, class Ch> inline OutIt print_doctype_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { assert(node->type() == node_doctype); if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; *out = Ch('!'), ++out; *out = Ch('D'), ++out; *out = Ch('O'), ++out; *out = Ch('C'), ++out; *out = Ch('T'), ++out; *out = Ch('Y'), ++out; *out = Ch('P'), ++out; *out = Ch('E'), ++out; *out = Ch(' '), ++out; out = copy_chars(node->value(), node->value() + node->value_size(), out); *out = Ch('>'), ++out; return out; } // Print pi node template<class OutIt, class Ch> inline OutIt print_pi_node(OutIt out, const xml_node<Ch> *node, int flags, int indent) { assert(node->type() == node_pi); if (!(flags & print_no_indenting)) out = fill_chars(out, indent, Ch('\t')); *out = Ch('<'), ++out; *out = Ch('?'), ++out; out = copy_chars(node->name(), node->name() + node->name_size(), out); *out = Ch(' '), ++out; out = copy_chars(node->value(), node->value() + node->value_size(), out); *out = Ch('?'), ++out; *out = Ch('>'), ++out; return out; } } //! \endcond /////////////////////////////////////////////////////////////////////////// // Printing //! Prints XML to given output iterator. //! \param out Output iterator to print to. //! \param node Node to be printed. Pass xml_document to print entire document. //! \param flags Flags controlling how XML is printed. //! \return Output iterator pointing to position immediately after last character of printed text. template<class OutIt, class Ch> inline OutIt print(OutIt out, const xml_node<Ch> &node, int flags = 0) { return internal::print_node(out, &node, flags, 0); } #ifndef RAPIDXML_NO_STREAMS //! Prints XML to given output stream. //! \param out Output stream to print to. //! \param node Node to be printed. Pass xml_document to print entire document. //! \param flags Flags controlling how XML is printed. //! \return Output stream. template<class Ch> inline std::basic_ostream<Ch> &print(std::basic_ostream<Ch> &out, const xml_node<Ch> &node, int flags = 0) { print(std::ostream_iterator<Ch>(out), node, flags); return out; } //! Prints formatted XML to given output stream. Uses default printing flags. Use print() function to customize printing process. //! \param out Output stream to print to. //! \param node Node to be printed. //! \return Output stream. template<class Ch> inline std::basic_ostream<Ch> &operator <<(std::basic_ostream<Ch> &out, const xml_node<Ch> &node) { return print(out, node); } #endif } #endif
15,671
C++
36.137441
135
0.438389
daniel-kun/omni/interface/rapidxml/rapidxml_iterators.hpp
#ifndef RAPIDXML_ITERATORS_HPP_INCLUDED #define RAPIDXML_ITERATORS_HPP_INCLUDED // Copyright (C) 2006, 2009 Marcin Kalicinski // Version 1.13 // Revision $DateTime: 2009/05/13 01:46:17 $ //! \file rapidxml_iterators.hpp This file contains rapidxml iterators #include "rapidxml.hpp" namespace rapidxml { //! Iterator of child nodes of xml_node template<class Ch> class node_iterator { public: typedef typename xml_node<Ch> value_type; typedef typename xml_node<Ch> &reference; typedef typename xml_node<Ch> *pointer; typedef std::ptrdiff_t difference_type; typedef std::bidirectional_iterator_tag iterator_category; node_iterator() : m_node(0) { } node_iterator(xml_node<Ch> *node) : m_node(node->first_node()) { } reference operator *() const { assert(m_node); return *m_node; } pointer operator->() const { assert(m_node); return m_node; } node_iterator& operator++() { assert(m_node); m_node = m_node->next_sibling(); return *this; } node_iterator operator++(int) { node_iterator tmp = *this; ++this; return tmp; } node_iterator& operator--() { assert(m_node && m_node->previous_sibling()); m_node = m_node->previous_sibling(); return *this; } node_iterator operator--(int) { node_iterator tmp = *this; ++this; return tmp; } bool operator ==(const node_iterator<Ch> &rhs) { return m_node == rhs.m_node; } bool operator !=(const node_iterator<Ch> &rhs) { return m_node != rhs.m_node; } private: xml_node<Ch> *m_node; }; //! Iterator of child attributes of xml_node template<class Ch> class attribute_iterator { public: typedef typename xml_attribute<Ch> value_type; typedef typename xml_attribute<Ch> &reference; typedef typename xml_attribute<Ch> *pointer; typedef std::ptrdiff_t difference_type; typedef std::bidirectional_iterator_tag iterator_category; attribute_iterator() : m_attribute(0) { } attribute_iterator(xml_node<Ch> *node) : m_attribute(node->first_attribute()) { } reference operator *() const { assert(m_attribute); return *m_attribute; } pointer operator->() const { assert(m_attribute); return m_attribute; } attribute_iterator& operator++() { assert(m_attribute); m_attribute = m_attribute->next_attribute(); return *this; } attribute_iterator operator++(int) { attribute_iterator tmp = *this; ++this; return tmp; } attribute_iterator& operator--() { assert(m_attribute && m_attribute->previous_attribute()); m_attribute = m_attribute->previous_attribute(); return *this; } attribute_iterator operator--(int) { attribute_iterator tmp = *this; ++this; return tmp; } bool operator ==(const attribute_iterator<Ch> &rhs) { return m_attribute == rhs.m_attribute; } bool operator !=(const attribute_iterator<Ch> &rhs) { return m_attribute != rhs.m_attribute; } private: xml_attribute<Ch> *m_attribute; }; } #endif
3,918
C++
21.394286
70
0.504339
daniel-kun/omni/concepts/prototype/web/backend/README.md
[<img src="https://img.shields.io/travis/playframework/play-scala-starter-example.svg"/>](https://travis-ci.org/playframework/play-scala-starter-example) # Play Scala Starter This is a starter application that shows how Play works. Please see the documentation at https://www.playframework.com/documentation/latest/Home for more details. ## Running Run this using [sbt](http://www.scala-sbt.org/). If you downloaded this project from http://www.playframework.com/download then you'll find a prepackaged version of sbt in the project directory: ``` sbt run ``` And then go to http://localhost:9000 to see the running web application. There are several demonstration files available in this template. ## Controllers - HomeController.scala: Shows how to handle simple HTTP requests. - AsyncController.scala: Shows how to do asynchronous programming when handling a request. - CountController.scala: Shows how to inject a component into a controller and use the component when handling requests. ## Components - Module.scala: Shows how to use Guice to bind all the components needed by your application. - Counter.scala: An example of a component that contains state, in this case a simple counter. - ApplicationTimer.scala: An example of a component that starts when the application starts and stops when the application stops. ## Filters - Filters.scala: Creates the list of HTTP filters used by your application. - ExampleFilter.scala A simple filter that adds a header to every response.
1,536
Markdown
25.5
195
0.767578
daniel-kun/omni/concepts/prototype/web/backend/conf/logback.xml
<!-- https://www.playframework.com/documentation/latest/SettingsLogger --> <configuration> <conversionRule conversionWord="coloredLevel" converterClass="play.api.libs.logback.ColoredLevel" /> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${application.home:-.}/logs/application.log</file> <encoder> <pattern>%date [%level] from %logger in %thread - %message%n%xException</pattern> </encoder> </appender> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%coloredLevel %logger{15} - %message%n%xException{10}</pattern> </encoder> </appender> <appender name="ASYNCFILE" class="ch.qos.logback.classic.AsyncAppender"> <appender-ref ref="FILE" /> </appender> <appender name="ASYNCSTDOUT" class="ch.qos.logback.classic.AsyncAppender"> <appender-ref ref="STDOUT" /> </appender> <logger name="play" level="INFO" /> <logger name="application" level="DEBUG" /> <!-- Off these ones as they are annoying, and anyway we manage configuration ourselves --> <logger name="com.avaje.ebean.config.PropertyMapLoader" level="OFF" /> <logger name="com.avaje.ebeaninternal.server.core.XmlConfigLoader" level="OFF" /> <logger name="com.avaje.ebeaninternal.server.lib.BackgroundThread" level="OFF" /> <logger name="com.gargoylesoftware.htmlunit.javascript" level="OFF" /> <root level="WARN"> <appender-ref ref="ASYNCFILE" /> <appender-ref ref="ASYNCSTDOUT" /> </root> </configuration>
1,516
XML
35.119047
102
0.701847
Strevia/omni_warehouse/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "0.2.2" # The title and description fields are primarily for displaying extension info in UI title = "Warehouse Creator" description="A simple extension to randomly generate warehouse environments." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" # URL of the extension source repository. repository = "" icon = "data/icon.png" # One of categories for UI. category = "Warehouse Creator" # Keywords for the extension keywords = ["kit", "digitaltwin", "warehouse", "generate"] # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.usd" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "omni.warehouse_creator"
917
TOML
25.999999
105
0.736096
Strevia/omni_warehouse/config/extension.gen.toml
[package] archivePath = "./archives/omni.warehouse_creator-0.2.2.zip" repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/warehouse-creator-extension" [package.publish] date = 1676320297 kitVersion = "104.2+release.96.cda0f258.tc" buildNumber = "0.2.2+master.91.b2c8d76c.tc" repoName = "warehouse_creator"
372
TOML
32.909088
104
0.677419
Strevia/omni_warehouse/omni/warehouse_creator/__init__.py
from .python.scripts.__init__ import *
39
Python
18.999991
38
0.692308
Strevia/omni_warehouse/omni/warehouse_creator/python/scripts/recipes.py
import random, math NUCLEUS_SERVER = "http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/ArchVis/Industrial/" # This file contains dictionaries for different genration recipes - you can create your own here and expand the database! # You can also edit existing to see how your rules generate scenes! # Rule based placers (XYZ Locations based on Procedural or User-selected layout) # X = columns; distance between racks (675 is width of rack) // Y = height // Z = rows # R A C K S divisor = 2 def racks_procedural(): positions = [] ROWS = 13 for i in range(ROWS): positions.extend( [ (2800 - (i * 675), 0, 1888), (2800 - (i * 675), 0, 962), (2800 - (i * 675), 0, 513), (2800 - (i * 675), 0, -1034), (2800 - (i * 675), 0, -1820), ] ) totalSample = len(positions) minSample = math.floor(totalSample/divisor) sampleSize = random.randint(minSample,totalSample) filledRackPos = [] emptyRackPos = positions return filledRackPos, emptyRackPos def empty_racks_Umode(): positions = [] for i in range(9): if i < 5: positions.extend([(2800 - (i * 675), 0, 1888), (2800 - (i * 675), 0, -1820), (2800 - (i * 675), 0, -2225)]) else: positions.extend( [ (2800 - (i * 675), 0, 1888), (2800 - (i * 675), 0, 962), (2800 - (i * 675), 0, 513), (2800 - (i * 675), 0, -1034), (2800 - (i * 675), 0, -1820), ] ) totalSample = len(positions) minSample = math.floor(totalSample/divisor) sampleSize = random.randint(minSample,totalSample) filledRackPos = [positions.pop(random.randrange(len(positions))) for _ in range(sampleSize)] emptyRackPos = positions return filledRackPos, emptyRackPos def empty_racks_Lmode(): positions = [] for i in range(9): if i < 5: positions.extend([(2800 - (i * 675), 0, 1888), (2800 - (i * 675), 0, 962), (2800 - (i * 675), 0, 513)]) else: positions.extend( [ (2800 - (i * 675), 0, 1888), (2800 - (i * 675), 0, 962), (2800 - (i * 675), 0, 513), (2800 - (i * 675), 0, -1034), (2800 - (i * 675), 0, -1820), ] ) totalSample = len(positions) minSample = math.floor(totalSample/divisor) sampleSize = random.randint(minSample,totalSample) filledRackPos = [positions.pop(random.randrange(len(positions))) for _ in range(sampleSize)] emptyRackPos = positions return filledRackPos, emptyRackPos def empty_racks_Imode(): positions = [] for i in range(9): positions.extend( [ (2800 - (i * 675), 0, 962), (2800 - (i * 675), 0, 513), (2800 - (i * 675), 0, -1034) ] ) totalSample = len(positions) minSample = math.floor(totalSample/divisor) sampleSize = random.randint(minSample,totalSample) filledRackPos = [positions.pop(random.randrange(len(positions))) for _ in range(sampleSize)] emptyRackPos = positions return filledRackPos, emptyRackPos ## P I L E S def piles_placer_procedural(): positions = [] for i in range(9): positions.extend([(2744.5 - (i * 675), 0, 1384), (2947 - (i * 675), 0, 35), (2947 - (i * 675), 0, -1440)]) print("pile positions (procedural): ", positions) return positions def piles_placer_Umode(): positions = [] for i in range(9): if i < 5: positions.extend([(2744.5 - (i * 675), 0, 1384), (2947 - (i * 675), 0, -1440)]) else: positions.extend([(2744.5 - (i * 675), 0, 1384), (2947 - (i * 675), 0, 35), (2947 - (i * 675), 0, -1440)]) return positions def piles_placer_Imode(): positions = [] for i in range(9): positions.extend([(2744.5 - (i * 675), 0, 1384), (2947 - (i * 675), 0, 35), (2947 - (i * 675), 0, -1440)]) return positions def piles_placer_Lmode(): positions = [] for i in range(9): if i<5: positions.extend([(2744.5 - (i * 675), 0, 1384), (2947 - (i * 675), 0, 35)]) else: positions.extend([(2744.5 - (i * 675), 0, 1384), (2947 - (i * 675), 0, 35), (2947 - (i * 675), 0, -1440)]) return positions ## R A I L I N G S def railings_placer_procedural(): positions = [] for i in range(17): positions.extend([(3017 - (i * 337.5), 0, -119)]) return positions def railings_placer_Lmode(): positions = [] for i in range(17): positions.extend([(3017 - (i * 337.5), 0, -119)]) return positions def railings_placer_Umode(): positions = [] for i in range(9,17): positions.extend([(3017 - (i * 337.5), 0, -119)]) return positions def railings_placer_Imode(): positions = [] for i in range(17): positions.extend([(3017 - (i * 337.5), 0, -119)]) return positions # R O B O T / F O R K L I F T def robo_fork_placer_procedural(posXYZ): positions = [] for i in range(17): positions.extend([(posXYZ[0] - (i * 337.5), posXYZ[1], posXYZ[2])]) return positions def robo_fork_placer_Lmode(posXYZ): positions = [] for i in range(10,17): positions.extend([(posXYZ[0] - (i * 337.5), posXYZ[1], posXYZ[2])]) return positions def robo_fork_placer_Umode(posXYZ): positions = [] for i in range(9,17): positions.extend([(posXYZ[0] - (i * 337.5), posXYZ[1], posXYZ[2])]) return positions def robo_fork_placer_Imode(posXYZ): positions = [] for i in range(17): positions.extend([(posXYZ[0] - (i * 337.5), posXYZ[1], posXYZ[2])]) return positions # Store rack position data filledProcMode, emptyProcMode = racks_procedural() filledUMode, emptyUMode = empty_racks_Umode() filledLMode, emptyLMode = empty_racks_Lmode() filledIMode, emptyIMode = empty_racks_Imode() warehouse_recipe = { # First step is to identify what mode the generation is, we have 4 modes. By default, we will keep it at procedural. # If it is a customized generation, we can update this value to the layout type chosen from the UI # P.S : "procedural" mode is basically I-Shaped (Imode) with all objects selected "mode": "procedural", # Then, we point to asset paths, to pick one at random and spawn at specific positions "empty_racks": f"{NUCLEUS_SERVER}Shelves/", "filled_racks": f"{NUCLEUS_SERVER}Racks/", "piles": f"{NUCLEUS_SERVER}Piles/", "railings": f"{NUCLEUS_SERVER}Railing/", "forklift": f"http://omniverse-content-staging.s3-us-west-2.amazonaws.com/Assets/Isaac/2022.1/Isaac/Props/Forklift/", "robot": f"http://omniverse-content-staging.s3-us-west-2.amazonaws.com/Assets/Isaac/2022.1/Isaac/Robots/Transporter/", # we can also have stand-alone assets, that are directly spawned in specific positions "forklift_asset": ["forklift.usd"], "robot_asset": ["transporter.usd"], # We are also adding other assets from the paths above to choose from "empty_racks_asset": ["RackLargeEmpty_A1.usd", "RackLargeEmpty_A2.usd"], "filled_racks_asset": [ "RackLarge_A1.usd", "RackLarge_A2.usd", "RackLarge_A3.usd", "RackLarge_A4.usd", "RackLarge_A5.usd", "RackLarge_A6.usd", "RackLarge_A7.usd", "RackLarge_A8.usd", "RackLarge_A9.usd", ], "piles_asset": [ "WarehousePile_A1.usd", "WarehousePile_A2.usd", "WarehousePile_A3.usd", "WarehousePile_A4.usd", "WarehousePile_A5.usd", "WarehousePile_A6.usd", "WarehousePile_A7.usd", ], "railings_asset": ["MetalFencing_A1.usd", "MetalFencing_A2.usd", "MetalFencing_A3.usd"], # Now, we have a sample space of positions within the default warehouse shell these objects can go to. We can randomly # spawn prims into randomly selected positions from this sample space. These are either generated by placer functions, # or hardcoded for standalone assets # Empty and Filled racks both have similar dimensions, so we reuse the positions for racks "filled_racks_procedural": filledProcMode, "empty_racks_procedural": emptyProcMode, "filled_racks_Umode": filledUMode, "empty_racks_Umode": emptyUMode, "filled_racks_Lmode": filledLMode, "empty_racks_Lmode": emptyLMode, "filled_racks_Imode": filledIMode, "empty_racks_Imode": emptyIMode, # Piles (Rules doesnt change based on layout mode here. Feel free to update rules) "piles_procedural": piles_placer_procedural(), "piles_Umode": piles_placer_Umode(), "piles_Lmode": piles_placer_Lmode(), "piles_Imode": piles_placer_Imode(), # Railings (Similar to piles) "railings_procedural": railings_placer_procedural(), "railings_Umode": railings_placer_Umode(), "railings_Lmode": railings_placer_Lmode(), "railings_Imode": railings_placer_Imode(), # Forklift and Robot "forklift_procedural": robo_fork_placer_procedural((2500, 0, -333)), "forklift_Umode": robo_fork_placer_Umode((2500, 0, -333)), "forklift_Lmode": robo_fork_placer_Lmode((2500, 0, -333)), "forklift_Imode": robo_fork_placer_Imode((2500, 0, -333)), "robot_procedural": robo_fork_placer_procedural((3017, 8.2, -698)), "robot_Umode": robo_fork_placer_Umode((3017, 8.2, -698)), "robot_Lmode": robo_fork_placer_Lmode((3017, 8.2, -698)), "robot_Imode": robo_fork_placer_Imode((3017, 8.2, -698)), }
9,688
Python
36.554263
122
0.594034
Strevia/omni_warehouse/omni/warehouse_creator/python/scripts/extension.py
# Import necessary libraries import omni.ext from .warehouse_window_base import * # Main Class class WarehouseCreator(omni.ext.IExt): def on_startup(self, ext_id): self.wh_creator = WarehouseCreatorWindow() self.wh_creator._build_content() print("[omni.warehouse] WarehouseCreator started") def on_shutdown(self): self.wh_creator.destroy() print("[omni.warehouse] WarehouseCreator shutdown")
442
Python
28.533331
59
0.696833
Strevia/omni_warehouse/omni/warehouse_creator/python/scripts/warehouse_window_base.py
import os, platform import omni.ext import omni.ui as ui from omni.ui.workspace_utils import RIGHT from .warehouse_helpers import * import carb WINDOW_TITLE = "Warehouse Creator" class WarehouseCreatorWindow(): def __init__(self): # Render Setting; Enable ambient lighting self._system = platform.system() carb.settings.get_settings().set("/rtx/sceneDb/ambientLightIntensity", 1.5) if self._system == "Linux": carb.settings.get_settings().set("/rtx/indirectDiffuse/scalingFactor", 10.0) from os.path import dirname, abspath path = dirname(dirname(dirname(dirname(dirname(__file__))))) path = path + "/data/UI/" self.UI_IMAGE_SERVER = path self._usd_context = omni.usd.get_context() self._wh_helper = wh_helpers() # Main extension window (Width is 0 to fit the window to UI elements) self._window = ui.Window(WINDOW_TITLE, width=0, height=800) self._window.deferred_dock_in("Stage", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE) def destroy(self): # Render Setting; Disable ambient lighting (default) carb.settings.get_settings().set("/rtx/sceneDb/ambientLightIntensity", 0.0) carb.settings.get_settings().set("/rtx/indirectDiffuse/scalingFactor", 1.0) self._window = None # U S E R I N T E R F A C E def _build_content(self, runTestScript = False): # Elements within the window frame with self._window.frame: # General UI Styling style1 = { "Button:hovered": {"background_color": 0xFF00B976, "border_color": 0xFFFD761D}, "Button": {}, "Button.Label": {"color": 0xFF00B976}, "Button.Label:hovered": {"color": 0xFFFFFFFF}, } # UI elements in a main VStack with ui.VStack(style=style1): # Main title label titleLabel = ui.Label( "Warehouse Creator", style={"color": 0xFF00B976, "font_size": 35}, alignment=ui.Alignment.CENTER, height=0, ) titleDescriptionLabel = ui.Label( "\nWelcome to the Warehouse Creator Extension! Quickly get started with building your\nwarehouse scenes with a click of a button. For more detailed guide on quickly getting\nstarted with building scenes, checkout our official documentation here: \n\n", width=500, alignment=ui.Alignment.CENTER, ) # Quick Generation label quickgenLabel = ui.Label( "Option 1. Quick Generation", alignment=ui.Alignment.CENTER, width=500, style={"color": 0xFF00B976, "font_size": 25}, ) quickgenDescriptionLabel1 = ui.Label( "\nQuick Generation module allows you to quickly generate your warehouse scene w/o\nany parameters. You can choose to begin with a standalone warehouse shell, to bring\n in your own assets to populate your scene!\n\n", width=500, alignment=ui.Alignment.CENTER, ) # G E N E R A T E W A R E H O U S E S H E L L with ui.VStack(): shellImage = ui.Image( f"{self.UI_IMAGE_SERVER}shell.JPG", width=500, height=150, ) shellImage.fill_policy = shellImage.fill_policy.PRESERVE_ASPECT_CROP # Spawning warehouse shell when the button is clicked def generateShell(): self.layoutButton1.checked = False self.layoutButton2.checked = False self.layoutButton3.checked = False self.objectButton1.checked = False self.objectButton2.checked = False self.objectButton3.checked = False self.objectButton4.checked = False self.objectButton5.checked = False self.objectButton6.checked = False self._wh_helper.genShell() shellButton = ui.Button( "Generate Warehouse Shell", clicked_fn=lambda: generateShell(), width=500, height=40, tooltip="Generates an empty warehouse shell", ) quickgenDescriptionLabel2 = ui.Label( "\nYou can also quickly create a full, procedurally generated warehouse scene! Just click\non the button below to generate your scene now!\n\n", width=500, alignment=ui.Alignment.CENTER, ) # P R O C E D U R A L W A R E H O U S E G E N E R A T I O N with ui.VStack(): proceduralImage = ui.Image( f"{self.UI_IMAGE_SERVER}warehouse.JPG", width=500, height=150, ) proceduralImage.fill_policy = proceduralImage.fill_policy.PRESERVE_ASPECT_CROP def genProcedural(): self._wh_helper.clear_stage() self.layoutButton1.checked = False self.layoutButton2.checked = False self.layoutButton3.checked = False self.objectButton1.checked = False self.objectButton2.checked = False self.objectButton3.checked = False self.objectButton4.checked = False self.objectButton5.checked = False self.objectButton6.checked = False # Pass asset buttons self.objectButtons = [ self.objectButton1, self.objectButton2, self.objectButton3, self.objectButton4, self.objectButton5, self.objectButton6, ] self.mode = "procedural" self._wh_helper.gen_custom(True, self.mode, self.objectButtons) proceduralButton = ui.Button( "Procedurally Generate Warehouse", clicked_fn=lambda: genProcedural(), width=500, height=40, tooltip="Procedurally Generates a warehouse scene", ) clearDescription = ui.Label( "\nYou can clear the current scene and start a fresh stage by clicking the button below!\n\n", width=500, alignment=ui.Alignment.CENTER, ) clearButton1 = ui.Button( "Clear Stage", clicked_fn=lambda: self._wh_helper.clear_stage(), width=500, height=40, tooltip="Removes all assets on the stage", ) # C U S T O M W A RE H O U S E G E N E R A T I O N customgenLabel = ui.Label( "\nOption 2. Customized Generation", alignment=ui.Alignment.CENTER, width=500, style={"color": 0xFF00B976, "font_size": 25}, ) customgenDescriptionLabel1 = ui.Label( "\nCustomized Generation module allows you to set custom parameters to generate your\nwarehouse scene. You can choose what objects the generated scene contains, and the\nlayout you want the scene to be generated with!\n\n", width=500, alignment=ui.Alignment.CENTER, ) # Customized Warehouse Generation - layouts layoutLabel = ui.Label( "2.1 Select Preferred Layout", alignment=ui.Alignment.CENTER, width=500, style={"color": 0xFF00B976, "font_size": 20}, ) customgenDescriptionLabel2 = ui.Label( "\nTo begin, select the preferred layout from the standard layout options given below.\n\n", width=500, alignment=ui.Alignment.CENTER, ) # Layout selection with ui.VStack(width=500): # Layout labels with ui.HStack(width=500): layoutLabel1 = ui.Label( "U-Shaped Layout", alignment=ui.Alignment.CENTER, style={"color": 0xFF00B976} ) layoutLabel2 = ui.Label( "I-Shaped Layout", alignment=ui.Alignment.CENTER, style={"color": 0xFF00B976} ) layoutLabel3 = ui.Label( "L-Shaped Layout", alignment=ui.Alignment.CENTER, style={"color": 0xFF00B976} ) # Layout buttons with ui.HStack(width=500): self.layoutButton1 = ui.Button( width=166, height=150, tooltip="Generates a U-Shaped Layout", style={ "Button.Image": { "image_url": f"{self.UI_IMAGE_SERVER}U-Shaped_Warehouse.png", "alignment": ui.Alignment.CENTER, } }, clicked_fn=lambda: sel_layout(1), ) self.layoutButton2 = ui.Button( width=166, height=150, tooltip="Generates an I-Shaped Layout", style={ "Button.Image": { "image_url": f"{self.UI_IMAGE_SERVER}I-Shaped_Warehouse.png", "alignment": ui.Alignment.CENTER, } }, clicked_fn=lambda: sel_layout(2), ) self.layoutButton3 = ui.Button( width=166, height=150, tooltip="Generates an L-Shaped Layout", style={ "Button.Image": { "image_url": f"{self.UI_IMAGE_SERVER}L-Shaped_Warehouse.png", "alignment": ui.Alignment.CENTER, } }, clicked_fn=lambda: sel_layout(3), ) # Customized Warehouse Generation - objects objectsLabel = ui.Label( "\n2.2 Select Preferred Objects", alignment=ui.Alignment.CENTER, width=500, style={"color": 0xFF00B976, "font_size": 20}, ) customgenDescriptionLabel3 = ui.Label( "\nNow, select the preferred objects you want in your scene from the options given below.\n\n", width=500, alignment=ui.Alignment.CENTER, ) # Objects selection with ui.VStack(width=500): # Object labels row 1 with ui.HStack(width=500): objectsLabel1 = ui.Label( "Empty Racks", alignment=ui.Alignment.CENTER, style={"color": 0xFF00B976} ) objectsLabel2 = ui.Label( "Filled Racks", alignment=ui.Alignment.CENTER, style={"color": 0xFF00B976} ) objectsLabel3 = ui.Label("Piles", alignment=ui.Alignment.CENTER, style={"color": 0xFF00B976}) # Object buttons row 1 with ui.HStack(width=500): self.objectButton1 = ui.Button( width=166, height=150, tooltip="Generates empty racks", style={ "Button.Image": { "image_url": f"{self.UI_IMAGE_SERVER}objects-01.png", "alignment": ui.Alignment.CENTER, } }, clicked_fn=lambda: sel_object(self.objectButton1), ) self.objectButton2 = ui.Button( width=166, height=150, tooltip="Generates filled racks", style={ "Button.Image": { "image_url": f"{self.UI_IMAGE_SERVER}objects-02.png", "alignment": ui.Alignment.CENTER, } }, clicked_fn=lambda: sel_object(self.objectButton2), ) self.objectButton3 = ui.Button( width=166, height=150, tooltip="Generates random piles of items", style={ "Button.Image": { "image_url": f"{self.UI_IMAGE_SERVER}objects-03.png", "alignment": ui.Alignment.CENTER, } }, clicked_fn=lambda: sel_object(self.objectButton3), ) # Object labels row 2 with ui.HStack(width=500): objectsLabel4 = ui.Label( "\nRailings", alignment=ui.Alignment.CENTER, style={"color": 0xFF00B976} ) objectsLabel5 = ui.Label( "\nForklift", alignment=ui.Alignment.CENTER, style={"color": 0xFF00B976} ) objectsLabel6 = ui.Label("\nRobot", alignment=ui.Alignment.CENTER, style={"color": 0xFF00B976}) # Object buttons row 2 with ui.HStack(width=500): self.objectButton4 = ui.Button( width=166, height=150, tooltip="Generates safety railings", style={ "Button.Image": { "image_url": f"{self.UI_IMAGE_SERVER}objects-04.png", "alignment": ui.Alignment.CENTER, } }, clicked_fn=lambda: sel_object(self.objectButton4), ) self.objectButton5 = ui.Button( width=166, height=150, tooltip="Generates forklifts", style={ "Button.Image": { "image_url": f"{self.UI_IMAGE_SERVER}objects-05.png", "alignment": ui.Alignment.CENTER, } }, clicked_fn=lambda: sel_object(self.objectButton5), ) self.objectButton6 = ui.Button( width=166, height=150, tooltip="Generates transporter robots", style={ "Button.Image": { "image_url": f"{self.UI_IMAGE_SERVER}objects-06.png", "alignment": ui.Alignment.CENTER, } }, clicked_fn=lambda: sel_object(self.objectButton6), ) customgenDescriptionLabel4 = ui.Label( "\nNow, click on the button below to generate your own, customized warehouse scene!\n\n", width=500, alignment=ui.Alignment.CENTER, ) def genCustomWarehouse(mode): self.mode = mode self._wh_helper.clear_stage() # Pass asset buttons self.objectButtons = [ self.objectButton1, self.objectButton2, self.objectButton3, self.objectButton4, self.objectButton5, self.objectButton6, ] self._wh_helper.gen_custom(False, self.mode, self.objectButtons) customizedButton = ui.Button( "Generate Customized Warehouse", clicked_fn=lambda: genCustomWarehouse(self.mode), width=500, height=40, tooltip="Generates a warehouse scene based on custom parameters", ) clearButton2 = ui.Button( "Clear Stage", clicked_fn=lambda: self._wh_helper.clear_stage(), width=500, height=40, tooltip="Removes all assets on the stage", ) # S M A R T I M P O R T with ui.VStack(height=ui.Fraction(1)): smartImportLabel = ui.Label( "\nOption 3. Smart Import", alignment=ui.Alignment.CENTER, width=500, style={"color": 0xFF00B976, "font_size": 25}, ) smartImportDescriptionLabel1 = ui.Label( "\nSmart Import module allows you to instantly import your own assets - the smart way!\nSimply, select the asset type you are importing from the drop-down, copy and paste\nthe URL of the asset from the content navigator into the box below. Your asset is\nmagically imported in-place!\n\n", width=500, alignment=ui.Alignment.CENTER, ) importImage = ui.Image( f"{self.UI_IMAGE_SERVER}objects.JPG", width=500, height=150, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, alignment=ui.Alignment.CENTER_TOP, ) spacinglabel = ui.Label("") importCategoryDropdown = ui.ComboBox( 1, "Empty Rack", "Filled Rack", "Pile", "Railing", "Forklift", "Robot" ) spacinglabel = ui.Label("") with ui.HStack(): importPathString = ui.StringField(width=250, height=40, tooltip= "Paste URL asset path").model importButton = ui.Button( "Import", clicked_fn=lambda: self._wh_helper.smart_import(importPathString, importCategoryDropdown), width=250, height=40 ) ui.Spacer(height = 65) ########################## UI Helper Functions ############################################## def sel_layout(n): if n == 1: self.layoutButton1.checked = True self.layoutButton2.checked = False self.layoutButton3.checked = False self.mode = "Umode" if n == 2: self.layoutButton1.checked = False self.layoutButton2.checked = True self.layoutButton3.checked = False self.mode = "Imode" if n == 3: self.layoutButton1.checked = False self.layoutButton2.checked = False self.layoutButton3.checked = True self.mode = "Lmode" def sel_object(button): if button.checked == True: button.checked = False else: button.checked = True # Generate Procedural Scene if test script flag == True if runTestScript == True: print("<WarehouseCreatorWindow::runTestScript>: Starting Procedural Generation...") genProcedural() print("<WarehouseCreatorWindow::runTestScript>: Finished Procedural Generation.")
22,022
Python
46.980392
313
0.435337
Strevia/omni_warehouse/omni/warehouse_creator/python/scripts/warehouse_helpers.py
import os, platform import random import omni.ext import omni.ui as ui from omni.ui.workspace_utils import RIGHT from pxr import Usd, UsdGeom, UsdLux, Gf from .recipes import warehouse_recipe as wh_rec class wh_helpers(): def __init__(self): NUCLEUS_SERVER = "http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/ArchVis/Industrial/" isTest = False self._system = platform.system() self.mode = "procedural" self.objects = ["empty_racks", "filled_racks", "piles", "railings", "forklift", "robot"] self.objectDict = self.initAssetPositions() self.objDictList = list(self.objectDict) self.isaacSimScale = Gf.Vec3f(100, 100,100) # Shell info is hard-coded for now self.shell_path = f"{NUCLEUS_SERVER}Buildings/Warehouse/Warehouse01.usd" self.shell_translate = (0, 0, 55.60183) self.shell_rotate = (-90.0, 0.0, 0.0) self.shell_name = "WarehouseShell" def config_environment(self): for prim in self._stage.Traverse(): if '/Environment/' in str(prim): prim.SetActive(False) self.create_distant_light() def create_distant_light(self): environmentPath = '/Environment' lightPath = environmentPath + '/distantLight' prim = self._stage.DefinePrim(environmentPath, 'Xform') distLight = UsdLux.DistantLight.Define(self._stage, lightPath) distLight.AddRotateXYZOp().Set(Gf.Vec3f(315,0,0)) distLight.CreateColorTemperatureAttr(6500.0) if self._system == "Linux": distLight.CreateIntensityAttr(6500.0) else: distLight.CreateIntensityAttr(3000.0) distLight.CreateAngleAttr(1.0) lightApi = UsdLux.ShapingAPI.Apply(distLight.GetPrim()) lightApi.CreateShapingConeAngleAttr(180) # Spawning warehouse shell when the button is clicked def genShell(self): self.clear_stage() self.mode = "procedural" self.spawn_prim(self.shell_path, self.shell_translate, self.shell_rotate, self.shell_name) # Generate Warehouse w/ user-selected assets def gen_custom(self, isProcedural, mode, objectButtons): self.mode = mode # Create shell self.spawn_prim(self.shell_path, self.shell_translate, self.shell_rotate, self.shell_name) selected_obj = [] # Spawn all objects (procedural) or user-selected objects if isProcedural: selected_obj = self.objects else: for i in range(len(objectButtons)): if objectButtons[i].checked == True: identifier = { 0: "empty_racks", 1: "filled_racks", 2: "piles", 3: "railings", 4: "forklift", 5: "robot", } selected_obj.append(identifier.get(i)) objectUsdPathDict = {"empty_racks": [], "filled_racks":[], "piles":[], "railings":[], "forklift":[], "robot":[] } # Reserved spots are dependent on self.mode (i.e. layout) numForkLifts = len(wh_rec[self.objects[4] + "_" + self.mode]) spots2RsrvFL = numForkLifts - 1 numRobots = len(wh_rec[self.objects[5] + "_" + self.mode]) spots2RsrvRob = numRobots - 1 self.objParams = {"empty_racks": [(-90,-180,0), (1,1,1), 5], "filled_racks":[(-90,-180,0), (1,1,1), 5], "piles":[(-90,-90,0), (1,1,1), 5], "railings":[(-90,0,0), (1,1,1), 5], "forklift":[(-90, random.uniform(0, 90), 0), self.isaacSimScale, spots2RsrvFL], "robot":[(-90, random.uniform(0, 90), 0), self.isaacSimScale, spots2RsrvRob] } # Reserve spots for Smart Import feature for h in range(0,len(selected_obj)): for i in range(0, len(self.objDictList)): if selected_obj[h] == self.objDictList[i]: for j in wh_rec[selected_obj[h] + "_asset"]: objectUsdPathDict[self.objDictList[i]].append(wh_rec[selected_obj[h]] + j) rotation = self.objParams[self.objDictList[i]][0] scale = self.objParams[self.objDictList[i]][1] spots2Rsrv = self.objParams[self.objDictList[i]][2] self.objectDict[self.objDictList[i]] = self.reservePositions(objectUsdPathDict[self.objDictList[i]], selected_obj[h], rotation, scale, spots2Rsrv) # Function to reserve spots/positions for Smart Import feature (after initial generation of assets) def reservePositions(self, assets, asset_prefix, rotation = (0,0,0), scale = (1,1,1), spots2reserve = 5): if len(assets) > 0: rotate = rotation scale = scale all_translates = wh_rec[asset_prefix + "_" + self.mode] #Select all but 5 positions from available positions (reserved for Smart Import functionality) if spots2reserve >= len(all_translates) and len(all_translates) > 0: spots2reserve = len(all_translates) - 1 elif len(all_translates) == 0: spots2reserve = 0 reserved_positions = random.sample(all_translates, spots2reserve) translates = [t for t in all_translates if t not in reserved_positions] positions = reserved_positions for i in range(len(translates)): name = asset_prefix + str(i) path = random.choice(assets) translate = translates[i] self.spawn_prim(path, translate, rotate, name, scale) return positions # Smart Import def smart_import(self, pathString, importCategory): self.get_root() # Get chosen index from drop-down import_index = importCategory.model.get_item_value_model().get_value_as_int() selected = self.objDictList[import_index] #ToDo: should idx dropdown list path = pathString.get_value_as_string() scale = Gf.Vec3f(1.0, 1.0, 1.0) # Scale if contains Isaac Sim Path (these assets are typically in meters vs centimeters) if "isaac" in path.lower(): scale = self.isaacSimScale # If positions available, spawn selected asset notificationMsg = "No more available positions to spawn new asset" for idx in range(0,len(self.objectDict)): if selected in self.objDictList[idx]: if len(self.objectDict[self.objDictList[idx]]) != 0: translate = self.objectDict[self.objDictList[idx]].pop() break else: self.windowNum = self.notification_window("window", "Smart Import", notificationMsg) return pathName = os.path.basename(path).split(".")[0] if pathName == "transporter": pathName = "robot" existing_assets = [] world = self._stage.GetDefaultPrim() for i in world.GetChildren(): existing_assets.append(i.GetPath()) # If prim exists, add count suffix and spawn counter = 0 assetName = pathName + str(counter) while f"/World/{assetName}" in existing_assets: assetName = f"{pathName}" + str(counter) counter += 1 pathName = assetName rotate = (-90.0, 0.0, 0.0) self.spawn_prim(path, translate, rotate, pathName, scale) pathString.set_value("") # spawn_prim function takes in a path, XYZ position, orientation, a name and spawns the USD asset in path with # the input name in the given position and orientation inside the world prim as an XForm def spawn_prim(self, path, translate, rotate, name, scale=Gf.Vec3f(1.0, 1.0, 1.0)): world = self._stage.GetDefaultPrim() # Creating an XForm as a child to the world prim asset = UsdGeom.Xform.Define(self._stage, f"{str(world.GetPath())}/{name}") # Checking if asset already has a reference and clearing it asset.GetPrim().GetReferences().ClearReferences() # Adding USD in the path as reference to this XForm asset.GetPrim().GetReferences().AddReference(f"{path}") # Setting the Translate and Rotate UsdGeom.XformCommonAPI(asset).SetTranslate(translate) UsdGeom.XformCommonAPI(asset).SetRotate(rotate) UsdGeom.XformCommonAPI(asset).SetScale(scale) # Returning the Xform if needed return asset def initAssetPositions(self): dictAssetPositions = { "empty_racks": wh_rec["empty_racks" + "_" + self.mode], "filled_racks": wh_rec["filled_racks" + "_" + self.mode], "piles": wh_rec["piles" + "_" + self.mode], "railings": wh_rec["railings" + "_" + self.mode], "forklift": wh_rec["forklift" + "_" + self.mode], "robot": wh_rec["robot" + "_" + self.mode] } return dictAssetPositions # Clear stage function def clear_stage(self): #Removing all children of world except distant light self.get_root() world = self._stage.GetDefaultPrim() doesLightExist = self._stage.GetPrimAtPath('/Environment/distantLight').IsValid() # config environment if doesLightExist == False: self.config_environment() # clear scene for i in world.GetChildren(): if i.GetPath() == '/Environment/distantLight' or i.GetPath() == '/World': continue else: self._stage.RemovePrim(i.GetPath()) # Notification window def notification_window(self,windowNum, textWindow, textField): windowNum = ui.Window(textWindow, width=400, height=100) with windowNum.frame: with ui.VStack(): ui.Label(textField) return windowNum # gets stage def get_root(self): self._stage = omni.usd.get_context().get_stage()
10,256
Python
45.411765
166
0.581318
Strevia/omni_warehouse/omni/warehouse_creator/python/tests/tests_warehouse_creator.py
# from warnings import catch_warnings import omni.kit.test import omni.kit.app import carb import carb.events import carb.dictionary from omni.warehouse_creator import * from ..scripts.warehouse_window_base import * from ..scripts.warehouse_helpers import * class TestWarehouseCreator(omni.kit.test.AsyncTestCaseFailOnLogError): print("<tests_warehouse_creator.py>: Starting test script...") async def setUp(self): print("<TestWarehouseCreator::setUp>: WarehouseCreator starting...") self.wh_creator = WarehouseCreatorWindow() print("UI Window Created... Building Content...") self.wh_creator._build_content(True) print("<TestWarehouseCreator::setUp>: WarehouseCreator started.") async def tearDown(self): print("<TestWarehouseCreator::tearDown>: WarehouseCreator stopping...") self.wh_creator.destroy() print("<TestWarehouseCreator::tearDown>: WarehouseCreator shutdown.")
953
Python
37.159999
79
0.729276
Strevia/omni_warehouse/omni/warehouse_creator/python/tests/__init__.py
from .tests_warehouse_creator import *
39
Python
18.999991
38
0.794872
Strevia/omni_warehouse/docs/CHANGELOG.md
# Changelog ## [0.2.2] - 2023-02-13 - Create 2022.3.3 Release v0.2.2: Update lighting for Linux ## [0.2.1] - 2023-01-31 - Create 2022.3.3 Release v0.2.1: Update to scene configuration ## [0.2.0] - 2023-01-31 - Create 2022.3.3 Release v0.2.0: Configure Linux renderer setting; updated README ## [0.1.9] - 2023-01-30 - Create 2022.3.3 Release v0.1.9: Configure environment ## [0.1.8] - 2023-01-23 - Create 2022.3.3 Release v0.1.8: Update Kit-SDK to 104.2 ## [0.1.7] - 2022-11-21 - Create 2022.3.1 Release v0.1.7: Clean up ## [0.1.6] - 2022-11-20 - Create 2022.3.1 Release v0.1.6: Support for Linux compatibility and updated rack placement ## [0.1.5] - 2022-10-27 - Create 2022.3.0 Release v0.1.5: Render Settings: Enabled Ambient Light ## [0.1.4] - 2022-10-26 - Create 2022.3.0 Release v0.1.4: Code Clean-up ## [0.1.3] - 2022-09-23 - Create 2022.3.0 Release v0.1.3 ## [0.1.2] - 2022-08-31 - Beta Release v0.1.2 ## [0.1.1] - 2022-08-19 - Beta Release ## [0.1.0] - 2022-08-18 - Initial build.
1,002
Markdown
23.463414
92
0.648703
Strevia/omni_warehouse/docs/README.md
# Warehouse Creator Extension The Warehouse Creator is an Extension for Omniverse Create that allows you to quickly get started with building Warehouse Digital Twins in an automated way. It supports procedurally generating full warehouse scenes, as well as customized generation based on layouts and assets that you want in the scene. The extension works by spawning USD (Universal Scene Description) assets from Nucleus based on predefined asset-based rules. The pre-defined asset placement rules control the sample-space of the various positions, rotations, and scaling of the asset to be spawned. Based on user-defined parameters, assets are randomly chosen from Nucleus and placed in random positions from the sample space of positions defined by the placement rules. Occupied positions are recorded, and new assets are spawned in the unoccupied positions of the sample space. You can modify the assets and their paths to several types and locations based on preference – this allows you to use the extension to generate scenes with your own custom assets from their defined locations. # Getting Started ## Enable Extension via Extensions Manager The Extension can be enabled by: 1. Navigating to Window > Extensions Manager from the top-level menu 2. Searching for Warehouse Creator in the text field of the Extension Manager window, to reveal up the omni.warehouse_creator result. 3. Clicking the toggle to enable the Extension # Navigating the User Interface ## Warehouse Creator - User Interface The extension UI (User Interface) contains a vertically scrollable window that hosts several quick recipes to get started with building your warehouse scenes. The different recipes and descriptions are elucidated below: ### Option 1: Quick Generation Quick Generation module allows you to quickly generate your warehouse scene without any parameters. It contains two different options: ### Option 2: Customized Generation The Customized Generation option allows you to control different parameters for scene generation to generate scenes attuned to your need. ### Option 3: Smart Import Smart Import module allows you to instantly import your own assets - the smart way! Simply select the asset type you are importing from the drop-down, copy and paste the URL of the asset from the content navigator into the box below. Your asset will be imported in-place. Import assets that fall under the following asset categories: 1. Filled Racks 2. Empty Racks 3. Piles 4. Railings 5. Forklift 6. Robot Note: 1. URL paths containing the keyword "isaac" will be scaled by (100,100,100) as Isaac Sim assets are in meters versus the default OV units of centimeters. 2. Empty spaces are reserved for the Smart Import feature during initial generation of warehouse. When used, Smart Import will randomly choose a location from a list of reserved spaces to place an imported asset. ### Clear Stage Quickly clear the scene. Users can select this button to delete all existing assets from their scene. This function is also called each time you generate a scene with Option 1 or 2. # Customize Modify the current extension with your own customizations! ## Develop with VS Code ### Pre-requisites 1. Microsoft VS Code (free) 2. Omniverse Create (Omniverse Code also works) 3. Enabled Warehouse Creator Extension 4. Enabled Kit VS Code Debug Extension ### Configuring Omniverse 1. In Create, navigate to Extensions 2. Search for Warehouse Creator 3. Select Warehouse Creator Extension from list of available extensions 4. Select Open with VSCode Similarly, you will need to follow steps 1-3 to enable the "Kit Debug VSCode" Extension ### Configuring VS Code 1. In VS Code, you will need to create a session to connect and link the debugger to your Create's VS Code Debugger Extension 2. Navigate to Run -> Add Configuration 3. Select Python 4. Click on "Remote Attach". Once you've selected, enter the IP address and Port Number specified in the VS Code Debugger extension 5. Once configured, hit the "F5" on your keyboard or navigate to Run -> Start debugging to start a debugging session 6. Once connected, the Kit VS Code window in Create should show the debugger has attached 7. You should now be able to navigate to the source code, modify it, hit Ctrl + S to save, and see the changes take effect in the extension! 8. Source code files can be found in the following directory: "omni\warehouse_creator\python\scripts\" Note that if the code is not executable due to a syntax error, the extension will disappear from Omniverse until the code has been fixed and saved once again.
4,590
Markdown
57.858974
420
0.799564
perfectproducts/floorplan_generator_lite/README.md
# floorplan generator lite see http://www.synctwin.ai for more information on SyncTwin GmbH.
95
Markdown
22.999994
66
0.778947
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/floorplan_semantics.py
from .floorplan_model import FloorPlanImagePoint, FloorPlanModel from pxr import Usd, Kind, UsdGeom, Sdf, Gf, Tf class FloorPlanImagePointSemantics(): SCHEMA = "PointOfInterest" SCHEMA_VERSION = "1.0.0" DEFAULT_ROOT_PATH = "PointsOfInterest" def write(self, stage, poi:FloorPlanImagePoint, prim_path) : poi_path = prim_path if prim_path!="" else f"{FloorPlanImagePointSemantics.DEFAULT_ROOT_PATH}/{Tf.MakeValidIdentifier(poi.name)}" poi_prim = stage.DefinePrim(poi_path,'Xform') poi_prim.CreateAttribute("mfgstd:schema", Sdf.ValueTypeNames.String).Set(f"{FloorPlanImagePointSemantics.SCHEMA}#{FloorPlanImagePointSemantics.SCHEMA_VERSION}") poi_prim.CreateAttribute("mfgstd:properties:name", Sdf.ValueTypeNames.String).Set(poi.name) poi_prim.CreateAttribute("mfgstd:properties:point_type", Sdf.ValueTypeNames.String).Set(poi.point_type) xf = UsdGeom.Xformable(poi_prim) xf.AddTranslateOp().Set(Gf.Vec3f(poi.x, poi.y, 0)) return poi_path def read(self, stage : Usd.Stage, poi_path : str)->FloorPlanImagePoint: poi_prim = stage.GetPrimAtPath(poi_path) schema = str(poi_prim.GetAttribute("mfgstd:schema").Get()) if not schema.startswith(FloorPlanImagePointSemantics.SCHEMA): print("error reading schema") return None xf = UsdGeom.Xformable(poi_prim) mat = Gf.Transform(xf.GetLocalTransformation()) t = mat.GetTranslation() name = str(poi_prim.GetAttribute("mfgstd:properties:name").Get()) point_type = str(poi_prim.GetAttribute("mfgstd:properties:point_type").Get()) poi = FloorPlanImagePoint(name=name, point_type=point_type, x=t[0], y=t[1]) return poi class FloorPlanSemantics: SCHEMA = "Floorplan" SCHEMA_VERSION = "1.0.0" DEFAULT_ROOT_PATH = "/World/FloorPlan" def write(self, stage:Usd.Stage, model:FloorPlanModel, prim_path:str=""): root_path = FloorPlanSemantics.DEFAULT_ROOT_PATH if prim_path == "" else prim_path root_prim = stage.DefinePrim(root_path, "Xform") Usd.ModelAPI(root_prim).SetKind(Kind.Tokens.component) smantics_prim = root_prim #semantics prim might go to /semantics, for now root prim smantics_prim.CreateAttribute("mfgstd:schema", Sdf.ValueTypeNames.String).Set(f"{FloorPlanSemantics.SCHEMA}#{FloorPlanSemantics.SCHEMA_VERSION}") smantics_prim.CreateAttribute("mfgstd:properties:resolution_x", Sdf.ValueTypeNames.Int).Set(model.resolution_x) smantics_prim.CreateAttribute("mfgstd:properties:resolution_y", Sdf.ValueTypeNames.Int).Set(model.resolution_y) smantics_prim.CreateAttribute("mfgstd:properties:image_url", Sdf.ValueTypeNames.String).Set(model.image_url) xf = UsdGeom.Xformable(root_prim) xf.ClearXformOpOrder () origin = model.reference_origin() xf.AddTranslateOp().Set(Gf.Vec3f(-origin.x*model.scale_x, -origin.y*model.scale_y,0) ) xf.AddScaleOp().Set(Gf.Vec3f(model.scale_x, model.scale_y, min(model.scale_x, model.scale_y)) ) poi_path = f"{root_path}/{FloorPlanImagePointSemantics.DEFAULT_ROOT_PATH}" stage.DefinePrim(poi_path, "Scope") for key, poi in model.points_of_interest.items(): FloorPlanImagePointSemantics().write(stage, poi,f"{poi_path}/{Tf.MakeValidIdentifier(key)}") return root_path def read(self, stage:Usd.Stage, prim_path:str="")->FloorPlanModel: if not stage: return None root_path = FloorPlanSemantics.DEFAULT_ROOT_PATH if prim_path == "" else prim_path root_prim = stage.GetPrimAtPath(root_path) if not root_prim: return None schema = str(root_prim.GetAttribute("mfgstd:schema").Get()) if not schema.startswith(FloorPlanSemantics.SCHEMA): print("error reading schema") return None model = FloorPlanModel() model.resolution_x = int(root_prim.GetAttribute("mfgstd:properties:resolution_x").Get() ) model.resolution_y = int(root_prim.GetAttribute("mfgstd:properties:resolution_y").Get() ) model.image_url = str(root_prim.GetAttribute("mfgstd:properties:image_url").Get() ) xf = UsdGeom.Xformable(root_prim) xf = Gf.Transform(xf.GetLocalTransformation()) t = xf.GetTranslation() s = xf.GetScale() model.set_scale(s[0], s[1]) o = model.reference_origin() o.set(-t[0], -t[1]) pois_path = f"{root_path}/{FloorPlanImagePointSemantics.DEFAULT_ROOT_PATH}" pois_prim = stage.GetPrimAtPath(pois_path) for poi_prim in pois_prim.GetChildren(): point = FloorPlanImagePointSemantics().read(stage, poi_prim.GetPath()) if point: model.add_poi(point) return model
4,968
Python
51.305263
168
0.654388
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/extension.py
import omni.ext import omni.ui as ui import os from omni.kit.window.filepicker import FilePickerDialog from omni.kit.widget.filebrowser import FileBrowserItem from pxr import Gf, Kind, Sdf, Usd, UsdGeom, UsdShade, Tf from .floorplan_semantics import FloorPlanSemantics, FloorPlanImagePointSemantics from .floorplan_model import FloorPlanModel, FloorPlanImagePoint from .floorplan_simpleviz import FloorPlanSimpleViz from .utils.geo_utils import GeoUtils from omni.kit.pipapi import install import tempfile import gc from pdf2image import convert_from_path import tempfile # Python code to read image class FloorPlanGeneratorLite(omni.ext.IExt): def on_startup(self, ext_id): # get script path self._window = ui.Window("SyncTwin Floor Plan Generator Lite", width=400, height=700) self._usd_context = omni.usd.get_context() self._model = FloorPlanModel() self._selected_points = [] self._ref_edited = False self._in_create = False self._stage_listener = None # local script pah ext_manager = omni.kit.app.get_app().get_extension_manager() self._local_extension_path = f"{ext_manager.get_extension_path(ext_id)}/ai/synctwin/floorplan_generator_lite" # subscribe to selection change self._selection = self._usd_context.get_selection() self._sub_stage_event = self._usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event ) self.create_ui() self.clear() def create_ui(self): with self._window.frame: with ui.VStack(): self._img = ui.Image(f"{self._local_extension_path}/bitmaps/select_image.png") with ui.VStack(): self._create_button = ui.Button("create...", clicked_fn=lambda :self.create(), enabled=False) with ui.HStack(): ui.Label("Source", height=30, width=75) self._image_label = ui.Label("[select an image]", height=30) ui.Button( "...", height=30, width=30, tooltip="select plan image...", clicked_fn=lambda: self.show_image_selection_dialog() ) with ui.HStack(spacing=5): ui.Label("Resolution", width=70, height=30) args = [0,0] self._res_field = ui.MultiIntField(*args, h_spacing=5, enabled=False, height=25,min=1) with ui.HStack(spacing=5, height=30): ui.Label("Scale", width=70) args = [1.0,1.0] self._scale_field = ui.MultiFloatDragField(*args, h_spacing=5, height=25,min=0.0001) self.add_multifield_edit_cb(self._scale_field, lambda m:self.set_scale_x(m.get_value_as_float()), lambda m:self.set_scale_y(m.get_value_as_float())) with ui.HStack(spacing=5, height=30): ui.Label("Size", width=70) args = [1.0,1.0] self._size_field = ui.MultiFloatDragField(*args, h_spacing=5, height=25,min=0.0001) self.add_multifield_edit_cb(self._size_field, lambda m:self.set_size_x(m.get_value_as_float()), lambda m:self.set_size_y(m.get_value_as_float())) with ui.HStack(height=30): ui.Spacer() with ui.VStack(style={"margin_width": 0}, height=30, width=30): ui.Spacer() self._keep_ratio_check = ui.CheckBox( height=0 ) self._keep_ratio_check.model.set_value(True) ui.Spacer() ui.Label("keep aspect ratio", height=30) with ui.CollapsableFrame("Selected References"): with ui.VStack(): self._selection_info_label = ui.Label("[nothing selected]", height=25) with ui.HStack(spacing=5, height=30): ui.Label("Distance", width=70) self._ref_dist_field = ui.FloatField(height=25) self._ref_dist_field.model.add_end_edit_fn(lambda m:self.set_ref_dist(m.get_value_as_float())) ui.Spacer() def set_image_url(self, url): self._model.set_image_url(url) self.refresh() def on_image_file_selected(self, dialog, dirname:str, filename: str): print(f"selected {filename}") filepath = f"{dirname}/{filename}" if filename.endswith(".pdf"): is_remote = dirname.startswith("omniverse://") if is_remote: temp_dir = "c:/temp" temp_name= f"{temp_dir}/{filename}" r = omni.client.copy(filepath, temp_name, behavior=omni.client.CopyBehavior.OVERWRITE) print(f"copy tmp {temp_name} {r}") if r != omni.client.Result.OK: print("## could not copy file") return filepath = temp_name print("convert pdf...") path = f"{self._local_extension_path}/poppler-0.68.0/bin" if not path in os.environ["PATH"]: os.environ["PATH"] += os.pathsep + path basename = os.path.splitext(filename)[0].replace(".","_") if is_remote: output_folder = temp_dir else: output_folder = dirname outfile = f"{output_folder}/{basename}.png" images_from_path = convert_from_path(filepath, output_folder=output_folder) images_from_path[0].save(outfile) print(f"written to {outfile}") if is_remote: upload_file = f"{dirname}/{basename}.png" r = omni.client.copy(outfile, upload_file, behavior=omni.client.CopyBehavior.OVERWRITE) print(f"upload {r}") filepath = upload_file else: filepath = outfile self._image_file = filename self.set_image_url(filepath) dialog.hide() # we'd like to create the map immediately after image selection self.create() def show_image_selection_dialog(self): heading = "Select File..." dialog = FilePickerDialog( heading, allow_multi_selection=False, apply_button_label="select file", click_apply_handler=lambda filename, dirname: self.on_image_file_selected(dialog, dirname, filename), file_extension_options = [("*.png", "Images"), ("*.jpg", "Images"), ("*.pdf", "PDF documents")] ) dialog.show() def is_keep_ar_checked(self): return self._keep_ratio_check.model.get_value_as_bool() def set_scale_x(self, v): if v <= 0: return self._model.set_scale(v, v if self.is_keep_ar_checked() else self._model.scale_y) self.refresh() def set_scale_y(self, v): if v <= 0: return self._model.set_scale(v if self.is_keep_ar_checked() else self._model.scale_x, v) self.refresh() def set_size_x(self, v): if v <= 0: return self._model.set_size(v, v/self._model.aspect_ratio() if self.is_keep_ar_checked() else self._model.size_x) self.refresh() def set_size_y(self, v): if v <= 0: return self._model.set_size( v*self._model.aspect_ratio() if self.is_keep_ar_checked() else self._model.size_y, v) self.refresh() def set_ref_dist(self, v): if v <= 0: return self._ref_edited = True self.update_scale_from_selected_references() def set_selected_points(self, refs): if len(refs) != 2: self._selected_points = [] else: self._selected_points = refs self._ref_edited = False self.refresh() def update_scale_from_selected_references(self): dx = self._selected_points[0].distance_to(self._selected_points[1]) # these are image space points (-> pixels) x = self._ref_dist_field.model.get_value_as_float() sx = x/dx if sx != self._model.scale_x or sx != self._model.scale_y: self._model.set_scale(sx,sx) self.refresh() def _on_stage_event(self, event): #print(f'STAGE EVENT : stage event type int: {event.type}') if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): selection = self._selection.get_selected_prim_paths() stage = self._usd_context.get_stage() #print(f'== selection changed with {len(selection)} items') if selection and stage: sel_refs = [] for selected_path in selection: #print(f' item {selected_path}:') point = FloorPlanImagePointSemantics().read(stage, selected_path) if point: sel_refs.append(point) self.set_selected_points(sel_refs) elif event.type == int(omni.usd.StageEventType.CLOSED): if not self._in_create: self.clear() elif event.type == int(omni.usd.StageEventType.OPENED): if not self._in_create: context = omni.usd.get_context() # check stage = context.get_stage() model = FloorPlanSemantics().read(stage) if model: self._model = model self._stage_listener = Tf.Notice.Register( Usd.Notice.ObjectsChanged, self._notice_changed, stage) self.refresh() self.clear_dirty() def _notice_changed(self, notice, stage): for p in notice.GetChangedInfoOnlyPaths(): if FloorPlanImagePointSemantics.DEFAULT_ROOT_PATH in str(p.GetPrimPath()): self.set_dirty() break def get_multifield_floats(self, field): m =field.model v1 = m.get_item_value_model(m.get_item_children()[0]).get_value_as_float() v2 = m.get_item_value_model(m.get_item_children()[1]).get_value_as_float() return (v1,v2) def set_multifield(self, field, a, b)->bool: changed = False m =field.model v1 = m.get_item_value_model(m.get_item_children()[0]) if v1.get_value_as_float() != float(a): v1.set_value(a) changed = True v2 = m.get_item_value_model(m.get_item_children()[1]) if v2.get_value_as_float() != float(b): v2.set_value(b) changed = True return changed def add_multifield_edit_cb(self, field, cb_a, cb_b): m = field.model m.get_item_value_model(m.get_item_children()[0]).add_end_edit_fn(cb_a) m.get_item_value_model(m.get_item_children()[1]).add_end_edit_fn(cb_b) def clear(self): self._model = FloorPlanModel() self._selected_points = [] self._ref_edited = False self._in_create = False self._stage_listener = None self.clear_dirty() self.refresh() def refresh(self): if self._model.image_url: self._img.source_url = self._model.image_url self._has_image = True else: self._img.source_url = f"{self._local_extension_path}/bitmaps/select_image.png" self._has_image = False self._image_label.text = os.path.basename(self._model.image_url) self._image_label.tooltip = self._model.image_url changed = False changed |= self.set_multifield(self._res_field, self._model.resolution_x, self._model.resolution_y) changed |= self.set_multifield(self._scale_field, self._model.scale_x, self._model.scale_y) changed |= self.set_multifield(self._size_field, self._model.size_x, self._model.size_y) if changed and self._has_image: self.set_dirty() if not self._ref_edited: if len(self._selected_points) == 2: dx = self._selected_points[0].distance_to(self._selected_points[1]) self._ref_dist_field.model.set_value( dx*self._model.scale_x) self._selection_info_label.text = f"{self._selected_points[0].name}, {self._selected_points[1].name}" else: self._selection_info_label.text = "[select two reference points]" self._ref_dist_field.model.set_value(0) self._res_field.enabled = self._has_image self._scale_field.enabled = self._has_image self._size_field.enabled = self._has_image self._ref_dist_field.enabled = self._has_image def set_dirty(self): self._create_button.text = "create..." self._create_button.enabled = True def clear_dirty(self): self._create_button.text = "up to date" self._create_button.enabled = False def focus_selection(self): # omni.kit.viewport_legacy is optional dependancy try: import omni.kit.viewport_legacy viewport = omni.kit.viewport_legacy.get_viewport_interface() if viewport: window = viewport.get_viewport_window() window.focus_on_selected() except: pass def update_poi_from_usd(self): context = omni.usd.get_context() stage = context.get_stage() model = FloorPlanSemantics().read(stage) if model: self._model.points_of_interest = model.points_of_interest def create(self): self._in_create = True self.update_poi_from_usd() context = omni.usd.get_context() context.new_stage() stage = context.get_stage() gb = GeoUtils(stage) gb.create_lighting() self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage) UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) # get scale root_prim = FloorPlanSemantics().write(stage, self._model) floor_path = FloorPlanSimpleViz().write(stage, self._model, root_prim) stage.SetDefaultPrim(stage.GetPrimAtPath("/World")) omni.kit.commands.execute( "SelectPrimsCommand", old_selected_paths=[], new_selected_paths=[floor_path], expand_in_stage=True ) self.focus_selection() self._in_create = False self.clear_dirty() def on_shutdown(self): self._window = None gc.collect()
15,905
Python
40.421875
131
0.520151
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/floorplan_simpleviz.py
from pxr import Gf, Kind, Sdf, Usd, UsdGeom, UsdShade,Tf from .floorplan_model import FloorPlanModel from .utils.geo_utils import GeoUtils from .floorplan_semantics import FloorPlanImagePointSemantics # simple viz assumes known structure from semantics class FloorPlanSimpleViz: def __init__(self) -> None: self.point_radius = 2 def write(self, stage : Usd.Stage, model : FloorPlanModel, root_path:str): self._model = model map_root = stage.GetPrimAtPath(root_path) sx = self._model.resolution_x sy = self._model.resolution_y gb = GeoUtils(stage =stage) point_mat = gb.create_material(root_path, "point_material", (0, 0, 1)) gb.create_textured_rect_mesh(root_path, sx, sy, model.image_url) #--- create reference points poi_path = f"{root_path}/{FloorPlanImagePointSemantics.DEFAULT_ROOT_PATH}" for key, poi in model.points_of_interest.items(): prim_path = f"{poi_path}/{Tf.MakeValidIdentifier(key)}" xf = stage.GetPrimAtPath(prim_path) mesh_prim = stage.DefinePrim(f"{prim_path}/mesh", "Sphere") mesh_prim.GetAttribute("radius").Set(self.point_radius) UsdShade.MaterialBindingAPI(mesh_prim).Bind(point_mat) return root_path
1,360
Python
41.531249
82
0.630882
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/floorplan_model.py
from __future__ import annotations from weakref import ref from pydantic import BaseModel, Field from typing import List, Dict , Optional from pxr import Usd, Kind,Gf from PIL import Image import carb import omni.client import io class FloorPlanImagePoint(BaseModel): x : int = 0 y : int = 0 name:str= "" point_type : str = "" def set(self, x,y): self.x = x self.y = y def distance_to(self, point:FloorPlanImagePoint): return (Gf.Vec2f(point.x, point.y)-Gf.Vec2f(self.x,self.y)).GetLength() def component_distance_to(self, point:FloorPlanImagePoint): return (abs(point.x-self.x),abs(point.y-self.y)) class FloorPlanModel(BaseModel): size_y: float = 0 size_x: float = 0 resolution_x : int = 0 resolution_y : int = 0 image_url: str = "" scale_x: float = 1.0 scale_y: float = 1.0 points_of_interest : Dict[str, FloorPlanImagePoint] = dict() def poi(self, name, point_type) -> FloorPlanImagePoint: if not name: return None if not name in self.points_of_interest: self.points_of_interest[name] = FloorPlanImagePoint(name = name, point_type=point_type) return self.points_of_interest.get(name) def add_poi(self, point:FloorPlanImagePoint): if not point.name: print("no name") return self.points_of_interest[point.name] = point def reference_diff_x(self): return abs(self.reference_b().x-self.reference_a().x) def reference_diff_y(self): return abs(self.reference_b().y-self.reference_a().y) def reference_a(self): return self.poi("Reference_A", "Reference") def reference_origin(self): return self.poi("Origin", "Reference") def reference_b(self): return self.poi("Reference_B", "Reference") def set_image_url(self, url): result, _, content = omni.client.read_file(url) if result != omni.client.Result.OK: carb.log_error(f"Can't read image file {url}, error code: {result}") return img = Image.open(io.BytesIO(memoryview(content).tobytes())) sx, sy = img.size if sx == 0 or sy == 0: print("# invalid image") return self.image_url = url self.resolution_x = sx self.resolution_y = sy self.scale_x = 1.0 self.scale_y = 1.0 self.reference_a().set(0,0) self.reference_b().set(self.resolution_x, self.resolution_y) self.reference_origin().set(self.resolution_x/2, self.resolution_y/2) self._update_size() def set_scale(self, x, y): self.scale_x = x self.scale_y = y self._update_size() def set_size(self, x, y): self.size_x = x self.size_y= y self.aspect_ratio = self.size_x / self.size_y self.scale_x = self.size_x / self.resolution_x self.scale_y = self.size_y / self.resolution_y def _update_size(self): self.size_x = self.resolution_x * self.scale_x self.size_y = self.resolution_y * self.scale_y def aspect_ratio(self)->float: return self.size_x / self.size_y
3,244
Python
28.770642
99
0.59402
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/poppler-0.68.0/include/poppler/cpp/poppler-global.h
/* * Copyright (C) 2009-2010, Pino Toscano <pino@kde.org> * Copyright (C) 2010, Patrick Spendrin <ps_ml@gmx.de> * Copyright (C) 2014, Hans-Peter Deifel <hpdeifel@gmx.de> * * 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, 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. */ #ifndef POPPLER_GLOBAL_H #define POPPLER_GLOBAL_H #if defined(_WIN32) # define LIB_EXPORT __declspec(dllexport) # define LIB_IMPORT __declspec(dllimport) #else # define LIB_EXPORT # define LIB_IMPORT #endif #if defined(poppler_cpp_EXPORTS) # define POPPLER_CPP_EXPORT LIB_EXPORT #else # define POPPLER_CPP_EXPORT LIB_IMPORT #endif #include <iosfwd> #include <string> #include <vector> namespace poppler { /// \cond DOXYGEN_SKIP_THIS namespace detail { class POPPLER_CPP_EXPORT noncopyable { protected: noncopyable(); ~noncopyable(); private: noncopyable(const noncopyable &); const noncopyable& operator=(const noncopyable &); }; } typedef detail::noncopyable noncopyable; /// \endcond enum rotation_enum { rotate_0, rotate_90, rotate_180, rotate_270 }; enum page_box_enum { media_box, crop_box, bleed_box, trim_box, art_box }; enum permission_enum { perm_print, perm_change, perm_copy, perm_add_notes, perm_fill_forms, perm_accessibility, perm_assemble, perm_print_high_resolution }; enum case_sensitivity_enum { case_sensitive, case_insensitive }; typedef std::vector<char> byte_array; typedef unsigned int /* time_t */ time_type; // to disable warning only for this occurrence #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4251) /* class 'A' needs to have dll interface for to be used by clients of class 'B'. */ #endif class POPPLER_CPP_EXPORT ustring : public std::basic_string<unsigned short> { public: ustring(); ustring(size_type len, value_type ch); ~ustring(); byte_array to_utf8() const; std::string to_latin1() const; static ustring from_utf8(const char *str, int len = -1); static ustring from_latin1(const std::string &str); private: // forbid implicit std::string conversions ustring(const std::string &); operator std::string() const; ustring& operator=(const std::string &); }; #ifdef _MSC_VER #pragma warning(pop) #endif POPPLER_CPP_EXPORT time_type convert_date(const std::string &date); POPPLER_CPP_EXPORT std::ostream& operator<<(std::ostream& stream, const byte_array &array); typedef void(*debug_func)(const std::string &, void *); POPPLER_CPP_EXPORT void set_debug_error_function(debug_func debug_function, void *closure); } #endif
3,194
C
26.307692
114
0.711334
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/poppler-0.68.0/include/poppler/cpp/poppler-rectangle.h
/* * Copyright (C) 2009-2010, Pino Toscano <pino@kde.org> * * 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, 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. */ #ifndef POPPLER_RECTANGLE_H #define POPPLER_RECTANGLE_H #include "poppler-global.h" namespace poppler { template <typename T> class rectangle { public: rectangle() : x1(), y1(), x2(), y2() {} rectangle(T _x, T _y, T w, T h) : x1(_x), y1(_y), x2(x1 + w), y2(y1 + h) {} ~rectangle() {} bool is_empty() const { return (x1 == x2) && (y1 == y2); } T x() const { return x1; } T y() const { return y1; } T width() const { return x2 - x1; } T height() const { return y2 - y1; } T left() const { return x1; } T top() const { return y1; } T right() const { return x2; } T bottom() const { return y2; } void set_left(T value) { x1 = value; } void set_top(T value) { y1 = value; } void set_right(T value) { x2 = value; } void set_bottom(T value) { y2 = value; } private: T x1, y1, x2, y2; }; typedef rectangle<int> rect; typedef rectangle<double> rectf; POPPLER_CPP_EXPORT std::ostream& operator<<(std::ostream& stream, const rect &r); POPPLER_CPP_EXPORT std::ostream& operator<<(std::ostream& stream, const rectf &r); } #endif
1,950
C
21.952941
82
0.62359
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/poppler-0.68.0/include/poppler/cpp/poppler-font.h
/* * Copyright (C) 2009, Pino Toscano <pino@kde.org> * * 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, 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. */ #ifndef POPPLER_FONT_H #define POPPLER_FONT_H #include "poppler-global.h" #include <vector> namespace poppler { class document; class document_private; class font_info_private; class font_iterator; class font_iterator_private; class POPPLER_CPP_EXPORT font_info { public: enum type_enum { unknown, type1, type1c, type1c_ot, type3, truetype, truetype_ot, cid_type0, cid_type0c, cid_type0c_ot, cid_truetype, cid_truetype_ot }; font_info(); font_info(const font_info &fi); ~font_info(); std::string name() const; std::string file() const; bool is_embedded() const; bool is_subset() const; type_enum type() const; font_info& operator=(const font_info &fi); private: font_info(font_info_private &dd); font_info_private *d; friend class font_iterator; }; class POPPLER_CPP_EXPORT font_iterator : public poppler::noncopyable { public: ~font_iterator(); std::vector<font_info> next(); bool has_next() const; int current_page() const; private: font_iterator(int, document_private *dd); font_iterator_private *d; friend class document; }; } #endif
2,001
C
20.760869
82
0.668666
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/poppler-0.68.0/include/poppler/cpp/poppler-toc.h
/* * Copyright (C) 2009, Pino Toscano <pino@kde.org> * * 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, 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. */ #ifndef POPPLER_TOC_H #define POPPLER_TOC_H #include "poppler-global.h" #include <vector> namespace poppler { class toc_private; class toc_item; class toc_item_private; class POPPLER_CPP_EXPORT toc : public poppler::noncopyable { public: ~toc(); toc_item* root() const; private: toc(); toc_private *d; friend class toc_private; }; class POPPLER_CPP_EXPORT toc_item : public poppler::noncopyable { public: typedef std::vector<toc_item *>::const_iterator iterator; ~toc_item(); ustring title() const; bool is_open() const; std::vector<toc_item *> children() const; iterator children_begin() const; iterator children_end() const; private: toc_item(); toc_item_private *d; friend class toc; friend class toc_private; friend class toc_item_private; }; } #endif
1,608
C
20.453333
82
0.699627
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/poppler-0.68.0/include/poppler/cpp/poppler-version.h
/* * Copyright (C) 2009, Pino Toscano <pino@kde.org> * * 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, 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. */ #ifndef POPPLER_VERSION_H #define POPPLER_VERSION_H #include "poppler-global.h" #define POPPLER_VERSION "0.68.0" #define POPPLER_VERSION_MAJOR 0 #define POPPLER_VERSION_MINOR 68 #define POPPLER_VERSION_MICRO 0 namespace poppler { POPPLER_CPP_EXPORT std::string version_string(); POPPLER_CPP_EXPORT unsigned int version_major(); POPPLER_CPP_EXPORT unsigned int version_minor(); POPPLER_CPP_EXPORT unsigned int version_micro(); } #endif
1,207
C
29.199999
82
0.752278
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/poppler-0.68.0/include/poppler/cpp/poppler-document.h
/* * Copyright (C) 2009-2010, Pino Toscano <pino@kde.org> * Copyright (C) 2016 Jakub Alba <jakubalba@gmail.com> * * 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, 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. */ #ifndef POPPLER_DOCUMENT_H #define POPPLER_DOCUMENT_H #include "poppler-global.h" #include "poppler-font.h" namespace poppler { class document_private; class embedded_file; class page; class toc; class POPPLER_CPP_EXPORT document : public poppler::noncopyable { public: enum page_mode_enum { use_none, use_outlines, use_thumbs, fullscreen, use_oc, use_attach }; enum page_layout_enum { no_layout, single_page, one_column, two_column_left, two_column_right, two_page_left, two_page_right }; ~document(); bool is_locked() const; bool unlock(const std::string &owner_password, const std::string &user_password); page_mode_enum page_mode() const; page_layout_enum page_layout() const; void get_pdf_version(int *major, int *minor) const; std::vector<std::string> info_keys() const; ustring info_key(const std::string &key) const; bool set_info_key(const std::string &key, const ustring &val); time_type info_date(const std::string &key) const; bool set_info_date(const std::string &key, time_type val); ustring get_title() const; bool set_title(const ustring &title); ustring get_author() const; bool set_author(const ustring &author); ustring get_subject() const; bool set_subject(const ustring &subject); ustring get_keywords() const; bool set_keywords(const ustring &keywords); ustring get_creator() const; bool set_creator(const ustring &creator); ustring get_producer() const; bool set_producer(const ustring &producer); time_type get_creation_date() const; bool set_creation_date(time_type creation_date); time_type get_modification_date() const; bool set_modification_date(time_type mod_date); bool remove_info(); bool is_encrypted() const; bool is_linearized() const; bool has_permission(permission_enum which) const; ustring metadata() const; bool get_pdf_id(std::string *permanent_id, std::string *update_id) const; int pages() const; page* create_page(const ustring &label) const; page* create_page(int index) const; std::vector<font_info> fonts() const; font_iterator* create_font_iterator(int start_page = 0) const; toc* create_toc() const; bool has_embedded_files() const; std::vector<embedded_file *> embedded_files() const; bool save(const std::string &filename) const; bool save_a_copy(const std::string &filename) const; static document* load_from_file(const std::string &file_name, const std::string &owner_password = std::string(), const std::string &user_password = std::string()); static document* load_from_data(byte_array *file_data, const std::string &owner_password = std::string(), const std::string &user_password = std::string()); static document* load_from_raw_data(const char *file_data, int file_data_length, const std::string &owner_password = std::string(), const std::string &user_password = std::string()); private: document(document_private &dd); document_private *d; friend class document_private; }; } #endif
4,272
C
31.127819
90
0.64279
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/poppler-0.68.0/include/poppler/cpp/poppler-page-transition.h
/* * Copyright (C) 2009, Pino Toscano <pino@kde.org> * * 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, 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. */ #ifndef POPPLER_PAGE_TRANSITION_H #define POPPLER_PAGE_TRANSITION_H #include "poppler-global.h" class Object; namespace poppler { class page; class page_transition_private; class POPPLER_CPP_EXPORT page_transition { public: enum type_enum { replace = 0, split, blinds, box, wipe, dissolve, glitter, fly, push, cover, uncover, fade }; enum alignment_enum { horizontal = 0, vertical }; enum direction_enum { inward = 0, outward }; page_transition(const page_transition &pt); ~page_transition(); type_enum type() const; int duration() const; alignment_enum alignment() const; direction_enum direction() const; int angle() const; double scale() const; bool is_rectangular() const; page_transition& operator=(const page_transition &pt); private: page_transition(Object *params); page_transition_private *d; friend class page; }; } #endif
1,817
C
20.903614
82
0.657127
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/poppler-0.68.0/include/poppler/cpp/poppler-embedded-file.h
/* * Copyright (C) 2009-2010, Pino Toscano <pino@kde.org> * * 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, 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. */ #ifndef POPPLER_EMBEDDED_FILE_H #define POPPLER_EMBEDDED_FILE_H #include "poppler-global.h" #include <vector> namespace poppler { class embedded_file_private; class POPPLER_CPP_EXPORT embedded_file : public poppler::noncopyable { public: ~embedded_file(); bool is_valid() const; std::string name() const; ustring description() const; int size() const; time_type modification_date() const; time_type creation_date() const; byte_array checksum() const; std::string mime_type() const; byte_array data() const; private: embedded_file(embedded_file_private &dd); embedded_file_private *d; friend class embedded_file_private; }; } #endif
1,465
C
25.178571
82
0.717406
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/poppler-0.68.0/include/poppler/cpp/poppler-image.h
/* * Copyright (C) 2010, Pino Toscano <pino@kde.org> * Copyright (C) 2018, Zsombor Hollay-Horvath <hollay.horvath@gmail.com> * * 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, 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. */ #ifndef POPPLER_IMAGE_H #define POPPLER_IMAGE_H #include "poppler-global.h" #include "poppler-rectangle.h" namespace poppler { class image_private; class POPPLER_CPP_EXPORT image { public: enum format_enum { format_invalid, format_mono, format_rgb24, format_argb32, format_gray8, format_bgr24 }; image(); image(int iwidth, int iheight, format_enum iformat); image(char *idata, int iwidth, int iheight, format_enum iformat); image(const image &img); ~image(); bool is_valid() const; format_enum format() const; int width() const; int height() const; char *data(); const char *const_data() const; int bytes_per_row() const; image copy(const rect &r = rect()) const; bool save(const std::string &file_name, const std::string &out_format, int dpi = -1) const; static std::vector<std::string> supported_image_formats(); image& operator=(const image &img); private: void detach(); image_private *d; friend class image_private; }; } #endif
1,918
C
24.586666
95
0.680918
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/poppler-0.68.0/include/poppler/cpp/poppler-page.h
/* * Copyright (C) 2009-2010, Pino Toscano <pino@kde.org> * Copyright (C) 2018, Suzuki Toshiya <mpsuzuki@hiroshima-u.ac.jp> * Copyright (C) 2018, Albert Astals Cid <aacid@kde.org> * Copyright (C) 2018, Zsombor Hollay-Horvath <hollay.horvath@gmail.com> * Copyright (C) 2018, Aleksey Nikolaev <nae202@gmail.com> * * 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, 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. */ #ifndef POPPLER_PAGE_H #define POPPLER_PAGE_H #include "poppler-global.h" #include "poppler-rectangle.h" #include <memory> namespace poppler { struct text_box_data; class POPPLER_CPP_EXPORT text_box { friend class page; public: text_box(text_box&&); text_box& operator=(text_box&&); ~text_box(); ustring text() const; rectf bbox() const; /** \since 0.68 */ int rotation() const; /** Get a bbox for the i-th glyph This method returns a rectf of the bounding box for the i-th glyph in the text_box. \note The text_box object owns the rectf objects, the caller is not needed to free them. \warning For too large glyph index, rectf(0,0,0,0) is returned. The number of the glyphs and ustring codepoints might be different in some complex scripts. */ rectf char_bbox(size_t i) const; bool has_space_after() const; private: text_box(text_box_data *data); std::unique_ptr<text_box_data> m_data; }; class document; class document_private; class page_private; class page_transition; class POPPLER_CPP_EXPORT page : public poppler::noncopyable { public: enum orientation_enum { landscape, portrait, seascape, upside_down }; enum search_direction_enum { search_from_top, search_next_result, search_previous_result }; enum text_layout_enum { physical_layout, raw_order_layout }; ~page(); orientation_enum orientation() const; double duration() const; rectf page_rect(page_box_enum box = crop_box) const; ustring label() const; page_transition* transition() const; bool search(const ustring &text, rectf &r, search_direction_enum direction, case_sensitivity_enum case_sensitivity, rotation_enum rotation = rotate_0) const; ustring text(const rectf &rect = rectf()) const; ustring text(const rectf &rect, text_layout_enum layout_mode) const; /** Returns a list of text of the page This method returns a std::vector of text_box that contain all the text of the page, with roughly one text word of text per text_box item. For text written in western languages (left-to-right and up-to-down), the std::vector contains the text in the proper order. \since 0.63 \note The page object owns the text_box objects as unique_ptr, the caller is not needed to free them. \warning This method is not tested with Asian scripts */ std::vector<text_box> text_list() const; private: page(document_private *doc, int index); page_private *d; friend class page_private; friend class document; }; } #endif
3,828
C
25.964789
97
0.665622
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/poppler-0.68.0/include/poppler/cpp/poppler-page-renderer.h
/* * Copyright (C) 2010, Pino Toscano <pino@kde.org> * Copyright (C) 2018, Zsombor Hollay-Horvath <hollay.horvath@gmail.com> * * 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, 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. */ #ifndef POPPLER_PAGE_RENDERER_H #define POPPLER_PAGE_RENDERER_H #include "poppler-global.h" #include "poppler-image.h" namespace poppler { typedef unsigned int argb; class page; class page_renderer_private; class POPPLER_CPP_EXPORT page_renderer : public poppler::noncopyable { public: enum render_hint { antialiasing = 0x00000001, text_antialiasing = 0x00000002, text_hinting = 0x00000004 }; enum line_mode_enum { line_default, line_solid, line_shape }; page_renderer(); ~page_renderer(); argb paper_color() const; void set_paper_color(argb c); unsigned int render_hints() const; void set_render_hint(render_hint hint, bool on = true); void set_render_hints(unsigned int hints); image::format_enum image_format() const; void set_image_format(image::format_enum format); line_mode_enum line_mode() const; void set_line_mode(line_mode_enum mode); image render_page(const page *p, double xres = 72.0, double yres = 72.0, int x = -1, int y = -1, int w = -1, int h = -1, rotation_enum rotate = rotate_0) const; static bool can_render(); private: page_renderer_private *d; friend class page_renderer_private; }; } #endif
2,161
C
26.025
82
0.671448
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/utils/common.py
from pydantic import BaseModel class Location3d(BaseModel): x : float = 0.0 y : float = 0.0 z : float = 0.0 class RGBColor(BaseModel): red_value : float green_value : float blue_value : float
223
Python
14.999999
30
0.623318
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/ai/synctwin/floorplan_generator_lite/utils/geo_utils.py
from pxr import Gf, UsdGeom, Usd, Sdf, UsdShade import omni.usd as ou import unicodedata from .common import Location3d import re import omni.kit.actions.core class GeoUtils: def __init__(self, stage = None) -> None: self._stage = stage def open_or_create_stage(self, path, clear_exist=True) -> Usd.Stage: layer = Sdf.Layer.FindOrOpen(path) if not layer: layer = Sdf.Layer.CreateNew(path) elif clear_exist: layer.Clear() if layer: self._stage = Usd.Stage.Open(layer) return self._stage else: return None def create_lighting(self): # add lighting ar = omni.kit.actions.core.get_action_registry() set_lighting_mode_rig = ar.get_action("omni.kit.viewport.menubar.lighting", "set_lighting_mode_rig") set_lighting_mode_rig.execute(2) def create_material(self, material_path, name, diffuse_color) -> UsdShade.Material: material_path = ou.get_stage_next_free_path(self._stage, material_path, False) material = UsdShade.Material.Define(self._stage, material_path) shader_path = material_path + "/Shader" shader = UsdShade.Shader.Define(self._stage, shader_path) shader.CreateIdAttr("UsdPreviewSurface") shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(diffuse_color) material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface") return material def create_textured_rect_mesh(self, root_path, sx,sy, image_url): stage = self._stage billboard = UsdGeom.Mesh.Define(stage, f"{root_path}/mesh") left = 0 right = sx top = 0 bottom = sy billboard.CreatePointsAttr([(left, top, 0), (right, top, 0), (right, bottom, 0), (left, bottom, 0)]) billboard.CreateFaceVertexCountsAttr([4]) billboard.CreateFaceVertexIndicesAttr([0,1,2,3]) billboard.CreateExtentAttr([(left, top, 0), (right, bottom, 0)]) primvars_api = UsdGeom.PrimvarsAPI(billboard) texCoords = primvars_api.CreatePrimvar("primvars:st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying) texCoords.Set([(0, 0), (1, 0), (1,1), (0, 1)]) #-- material_path = f"{root_path}/map_material" material = UsdShade.Material.Define(stage, material_path) pbrShader = UsdShade.Shader.Define(stage, f'{material_path}/PBRShader') pbrShader.CreateIdAttr("UsdPreviewSurface") pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.4) pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0) material.CreateSurfaceOutput().ConnectToSource(pbrShader.ConnectableAPI(), "surface") #- stReader = UsdShade.Shader.Define(stage, f'{material_path}/stReader') stReader.CreateIdAttr('UsdPrimvarReader_float2') diffuseTextureSampler = UsdShade.Shader.Define(stage,f'{material_path}/diffuseTexture') diffuseTextureSampler.CreateIdAttr('UsdUVTexture') diffuseTextureSampler.CreateInput('file', Sdf.ValueTypeNames.Asset).Set(image_url) diffuseTextureSampler.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(stReader.ConnectableAPI(), 'result') diffuseTextureSampler.CreateOutput('rgb', Sdf.ValueTypeNames.Float3) pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(diffuseTextureSampler.ConnectableAPI() , 'rgb') #- stInput = material.CreateInput('frame:stPrimvarName', Sdf.ValueTypeNames.Token) stInput.Set('st') stReader.CreateInput('varname',Sdf.ValueTypeNames.Token).ConnectToSource(stInput) UsdShade.MaterialBindingAPI(billboard).Bind(material) def location_to_vec3f(pos3d:Location3d)->Gf.Vec3f: return Gf.Vec3f(pos3d.x, pos3d.y, pos3d.z)
4,097
Python
43.064516
127
0.642421
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.3.0" # The title and description fields are primarily for displaying extension info in UI title = "SyncTwin floorplan generator lite" description="a generator for floorplans" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "manufacturing" # Keywords for the extension keywords = ["kit", "manufacturing", "SyncTwin"] # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/logo.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.kit.actions.core" = {} # Main python module this extension provides [[python.module]] name = "ai.synctwin.floorplan_generator_lite" [python.pipapi] requirements = ['pdf2image'] use_online_index = true
1,091
TOML
27.736841
118
0.743355
perfectproducts/floorplan_generator_lite/exts/ai.synctwin.floorplan_generator_lite/docs/README.md
# floorplan generator lite easily create floorplans from bitmaps visit http://www.synctwin.ai ## about synctwin GmbH: synctwin GmbH is an industrial metaverse enabler for small and middlesized enterprises. We are a spinoff of ipolog GmbH and a member of the actano group.
283
Markdown
17.933332
87
0.777385
perfectproducts/mqtt_sample/README.md
# SyncTwin MQTT Example An example to control a digital twin asset with an MQTT subscription. ![screenshot](exts/ai.synctwin.mqtt_sample/data/preview.png) see a tutorial on the code here : https://medium.com/@mtw75/how-to-control-a-digital-twin-asset-with-mqtt-in-nvidia-omniverse-92382e92e4dc for more information visit https://www.synctwin.ai
351
Markdown
34.199997
138
0.783476
perfectproducts/mqtt_sample/exts/ai.synctwin.mqtt_sample/ai/synctwin/mqtt_sample/extension.py
import omni.ext import omni.ui as ui from paho.mqtt import client as mqtt_client import random from pxr import Usd, Kind, UsdGeom, Sdf, Gf, Tf class SyncTwinMqttSampleExtension(omni.ext.IExt): def load_usd_model(self): # load our forklift print("loading model...") self._usd_context.open_stage("http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Equipment/Forklifts/Forklift_A/Forklift_A01_PR_V_NVD_01.usd") def on_startup(self, ext_id): print("[ai.synctwin.mqtt_sample] ai synctwin mqtt_sample startup") # init data self.mqtt_topic_model = ui.SimpleStringModel("synctwin/mqtt_demo/forklift/fork_level") self.mqtt_broker_host_model = ui.SimpleStringModel("test.mosquitto.org") self.mqtt_broker_port_model = ui.SimpleStringModel("1883") self.mqtt_value_model = ui.SimpleFloatModel(0) self.mqtt_value_model.add_value_changed_fn(self.on_mqtt_value_changed) self.mqtt_connected_model = ui.SimpleBoolModel(False) self.target_prim_model = ui.SimpleStringModel("/World/Geometry/SM_Forklift_Fork_A01_01") self.current_fork_level = 0 # init ui self._usd_context = omni.usd.get_context() self._window = ui.Window("SyncTwin MQTT Sample", width=300, height=350) with self._window.frame: with ui.VStack(): ui.Button("load model",clicked_fn=self.load_usd_model) ui.Label("MQTT Broker") with ui.HStack(): ui.StringField(self.mqtt_broker_host_model) ui.StringField(self.mqtt_broker_port_model, width=ui.Percent(20)) ui.Label("Topic") ui.StringField(self.mqtt_topic_model) ui.Label("Target Prim") ui.StringField(self.target_prim_model) ui.Label("Value") ui.StringField(self.mqtt_value_model) self.status_label = ui.Label("- not connected -") ui.Button("connect MQTT", clicked_fn=self.connect_mqtt) # we want to know when model changes self._sub_stage_event = self._usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event ) # find our xf prim if model already present self.find_xf_prim() # and we need a callback on each frame to update our xf prim self._app_update_sub = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop( self._on_app_update_event, name="synctwin.mqtt_sample._on_app_update_event" ) # called on every frame, be careful what to put there def _on_app_update_event(self, evt): # if we have found the transform lets update the translation if self.xf: self.xf.ClearXformOpOrder() self.xf.AddTranslateOp().Set(Gf.Vec3f(0, 0, self.current_fork_level)) # called on load def _on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.OPENED): print("opened new model") self.find_xf_prim() # our model callback def on_mqtt_value_changed(self, model): self.current_fork_level = model.get_value_as_float() # find the prim to be transformed def find_xf_prim(self): # get prim from input stage = self._usd_context.get_stage() prim = stage.GetPrimAtPath(self.target_prim_model.get_value_as_string()) self.xf = UsdGeom.Xformable(prim) if self.xf: msg = "found xf." else: msg = "## xf not found." self.status_label.text = msg print(msg) # connect to mqtt broker def connect_mqtt(self): # this is called when a message arrives def on_message(client, userdata, msg): msg_content = msg.payload.decode() print(f"Received `{msg_content}` from `{msg.topic}` topic") # userdata is self userdata.mqtt_value_model.set_value(float(msg_content)) # called when connection to mqtt broker has been established def on_connect(client, userdata, flags, rc): print(f">> connected {client} {rc}") if rc == 0: self.status_label.text = "Connected to MQTT Broker!" # connect to our topic topic = userdata.mqtt_topic_model.get_value_as_string() print(f"subscribing topic {topic}") client.subscribe(topic) else: self.status_label.text = f"Failed to connect, return code {rc}" # let us know when we've subscribed def on_subscribe(client, userdata, mid, granted_qos): print(f"subscribed {mid} {granted_qos}") # now connect broker broker = self.mqtt_broker_host_model.get_value_as_string() port = self.mqtt_broker_port_model.get_value_as_int() client_id = f'python-mqtt-{random.randint(0, 1000)}' # Set Connecting Client ID client = mqtt_client.Client(client_id) client.user_data_set(self) client.on_connect = on_connect client.on_message = on_message client.on_subscribe = on_subscribe client.connect(broker, port) client.loop_start() return client def on_shutdown(self): print("[ai.synctwin.mqtt_sample] shutdown") self.client = None self._app_update_sub = None
5,796
Python
36.888889
206
0.579365
perfectproducts/mqtt_sample/exts/ai.synctwin.mqtt_sample/docs/README.md
# SyncTwin MQTT Example [ai.synctwin.mqtt_sample] This is an example to control a USD asset with an MQTT live connection for more info go to https://www.synctwin.ai
170
Markdown
23.428568
71
0.758824
gitLSW/robot-cloud/training/pack_task.py
import os import math import torch from gymnasium import spaces from omni.isaac.core.utils.extensions import enable_extension enable_extension("omni.isaac.universal_robots") # enable_extension("omni.isaac.sensor") from omni.isaac.core.utils.nucleus import get_assets_root_path # from omni.isaac.core.utils.prims import create_prim, get_prim_at_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.physx.scripts.utils import setRigidBody, setStaticCollider #, setColliderSubtree, setCollider, addCollisionGroup, setPhysics, removePhysics, removeRigidBody from omni.isaac.universal_robots.ur10 import UR10 from omni.isaac.core.prims import XFormPrim, XFormPrimView, RigidPrim, RigidPrimView from omni.isaac.core.robots.robot_view import RobotView # from omni.isaac.core.materials.physics_material import PhysicsMaterial from omniisaacgymenvs.rl_task import RLTask from scipy.spatial.transform import Rotation as R from pyquaternion import Quaternion FALLEN_PART_THRESHOLD = 0.2 ROBOT_POS = torch.tensor([0.0, 0.0, FALLEN_PART_THRESHOLD]) DEST_BOX_POS = torch.tensor([0, -0.65, FALLEN_PART_THRESHOLD]) START_TABLE_POS = torch.tensor([0, 0.8, FALLEN_PART_THRESHOLD]) START_TABLE_HEIGHT = 0.6 START_TABLE_CENTER = START_TABLE_POS + torch.tensor([0, 0, START_TABLE_HEIGHT / 2]) IDEAL_PACKAGING = [([-0.06, -0.19984, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.14044, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.07827, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.01597, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, 0.04664, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, 0.10918, 0.0803], [0.072, 0.99, 0, 0])] NUMBER_PARTS = len(IDEAL_PACKAGING) local_assets = os.getcwd() + '/assets' TASK_CFG = { "test": False, "device_id": 0, "headless": False, "multi_gpu": False, "sim_device": "gpu", "enable_livestream": False, "task": { "name": 'Pack_Task', # "physics_engine": "physx", "env": { "numEnvs": 625, "envSpacing": 4, "episodeLength": 300, # "enableDebugVis": False, # "controlFrequencyInv": 4 }, "sim": { "dt": 1.0 / 60.0, "gravity": [0.0, 0.0, -9.81], "substeps": 1, "use_gpu_pipeline": False, # Must be off for gripper to work "add_ground_plane": True, "add_distant_light": True, "use_fabric": True, "enable_scene_query_support": True, # Must be on for gripper to work "enable_cameras": False, "disable_contact_processing": False, # Must be off for gripper to work "use_flatcache": True, "default_physics_material": { "static_friction": 1.0, "dynamic_friction": 1.0, "restitution": 0.0 }, "physx": { ### Per-scene settings "use_gpu": True, "worker_thread_count": 4, "solver_type": 1, # 0: PGS, 1:TGS "bounce_threshold_velocity": 0.2, "friction_offset_threshold": 0.04, # A threshold of contact separation distance used to decide if a contact # point will experience friction forces. "friction_correlation_distance": 0.025, # Contact points can be merged into a single friction anchor if the # distance between the contacts is smaller than correlation distance. # disabling these can be useful for debugging "enable_sleeping": True, "enable_stabilization": True, # GPU buffers "gpu_max_rigid_contact_count": 512 * 1024, "gpu_max_rigid_patch_count": 80 * 1024, "gpu_found_lost_pairs_capacity": 1024, "gpu_found_lost_aggregate_pairs_capacity": 1024, "gpu_total_aggregate_pairs_capacity": 1024, "gpu_max_soft_body_contacts": 1024 * 1024, "gpu_max_particle_contacts": 1024 * 1024, "gpu_heap_capacity": 64 * 1024 * 1024, "gpu_temp_buffer_capacity": 16 * 1024 * 1024, "gpu_max_num_partitions": 8, "gpu_collision_stack_size": 64 * 1024 * 1024, ### Per-actor settings ( can override in actor_options ) "solver_position_iteration_count": 4, "solver_velocity_iteration_count": 1, "sleep_threshold": 0.0, # Mass-normalized kinetic energy threshold below which an actor may go to sleep. # Allowed range [0, max_float). "stabilization_threshold": 0.0, # Mass-normalized kinetic energy threshold below which an actor may # participate in stabilization. Allowed range [0, max_float). ### Per-body settings ( can override in actor_options ) "enable_gyroscopic_forces": False, "density": 1000.0, # density to be used for bodies that do not specify mass or density "max_depenetration_velocity": 100.0, ### Per-shape settings ( can override in actor_options ) "contact_offset": 0.02, "rest_offset": 0.001, } } } } class PackTask(RLTask): control_frequency_inv = 1 # kinematics_solver = None """ This class sets up a scene and calls a RL Policy, then evaluates the behaivior with rewards Args: offset (Optional[np.ndarray], optional): offset applied to all assets of the task. sim_s_step_freq (int): The amount of simulation steps within a SIMULATED second. """ def __init__(self, name, sim_config, env, offset=None) -> None: # self.observation_space = spaces.Dict({ # 'robot_state': spaces.Box(low=-2 * torch.pi, high=2 * torch.pi, shape=(6,)), # 'gripper_closed': spaces.Discrete(2), # # 'forces': spaces.Box(low=-1, high=1, shape=(8, 6)), # Forces on the Joints # 'box_state': spaces.Box(low=-3, high=3, shape=(NUMBER_PARTS, 2)), # Pos and Rot Distance of each part currently placed in Box compared to currently gripped part # 'part_pos_diff': spaces.Box(low=-3, high=3, shape=(3,)), # # 'part_rot_diff': spaces.Box(low=-1, high=1, shape=(3,)) # }) self._num_observations = 10 + 2 * NUMBER_PARTS self.observation_space = spaces.Dict({ 'obs': spaces.Box(low=-math.pi, high=math.pi, shape=(self._num_observations,), dtype=float) }) # End Effector Pose # self.action_space = spaces.Box(low=-1, high=1, shape=(7,), dtype=float) # Delta Gripper Pose & gripper open / close self._num_actions = 7 self.action_space = spaces.Box(low=-1, high=1, shape=(self._num_actions,), dtype=float) self.update_config(sim_config) # trigger __init__ of parent class super().__init__(name, env, offset) def cleanup(self): super().cleanup() def update_config(self, sim_config): self._sim_config = sim_config self._cfg = sim_config.config self._task_cfg = sim_config.task_config self.dt = self._task_cfg["sim"]["dt"] self._device = self._cfg["sim_device"] self._num_envs = self._task_cfg["env"]["numEnvs"] self._env_spacing = self._task_cfg["env"]["envSpacing"] self._max_episode_length = self._task_cfg["env"]["episodeLength"] # Robot turning ange of max speed is 191deg/s self._max_joint_rot_speed = torch.scalar_tensor((191.0 * torch.pi / 180) * self.dt).to(self._device) super().update_config(sim_config) def set_up_scene(self, scene) -> None: print('SETUP TASK', self.name) self.create_env0() super().set_up_scene(scene=scene, replicate_physics=True, filter_collisions=True, copy_from_source=False) # Clones env0 self._boxes_view = XFormPrimView(prim_paths_expr=f'{self.default_base_env_path}/.*/box', name='box_view', reset_xform_properties=False) scene.add(self._boxes_view) self._parts_views = [] for i in range(NUMBER_PARTS): parts_view = RigidPrimView(prim_paths_expr=f'{self.default_base_env_path}/.*/part_{i}', name=f'part_{i}_view', reset_xform_properties=False) scene.add(parts_view) self._parts_views.append(parts_view) self._robots_view = RobotView(prim_paths_expr=f'{self.default_base_env_path}/.*/robot', name='ur10_view') scene.add(self._robots_view) self._table_view = XFormPrimView(prim_paths_expr=f'{self.default_base_env_path}/.*/table', name='table_view', reset_xform_properties=False) scene.add(self._table_view) self._robots = [UR10(prim_path=robot_path, attach_gripper=True) for robot_path in self._robots_view.prim_paths] def create_env0(self): # This is the URL from which the Assets are downloaded # Make sure you started and connected to your localhost Nucleus Server via Omniverse !!! # assets_root_path = get_assets_root_path() env0_box_path = self.default_zero_env_path + '/box' # box_usd_path = assets_root_path + '/Isaac/Environments/Simple_Warehouse/Props/SM_CardBoxA_02.usd' box_usd_path = local_assets + '/SM_CardBoxA_02.usd' add_reference_to_stage(box_usd_path, env0_box_path) box = XFormPrim(prim_path=env0_box_path, position=DEST_BOX_POS, scale=[1, 1, 0.4]) setStaticCollider(box.prim, approximationShape='convexDecomposition') for i in range(NUMBER_PARTS): env0_part_path = f'{self.default_zero_env_path}/part_{i}' part_usd_path = local_assets + '/draexlmaier_part.usd' add_reference_to_stage(part_usd_path, env0_part_path) part = RigidPrim(prim_path=env0_part_path, position=START_TABLE_CENTER + torch.tensor([0, 0.1 * i - 0.23, 0.04]), orientation=[0, 1, 0, 0], # [-0.70711, 0.70711, 0, 0] mass=0.4) setRigidBody(part.prim, approximationShape='convexDecomposition', kinematic=False) # Kinematic True means immovable # The UR10e has 6 joints, each with a maximum: # turning angle of -360 deg to +360 deg # turning ange of max speed is 191deg/s # gripper_usd = assets_root_path + "/Isaac/Robots/UR10/Props/long_gripper.usd" env0_robot_path = self.default_zero_env_path + '/robot' robot = UR10(prim_path=env0_robot_path, name='UR10', # usd_path=f'{local_assets}/ur10.usd', # gripper_usd=gripper_usd, position=ROBOT_POS, attach_gripper=True) # robot.set_enabled_self_collisions(True) env0_table_path = f'{self.default_zero_env_path}/table' # table_path = assets_root_path + "/Isaac/Environments/Simple_Room/Props/table_low.usd" table_path = local_assets + '/table_low.usd' add_reference_to_stage(table_path, env0_table_path) table = XFormPrim(prim_path=env0_table_path, position=START_TABLE_POS, scale=[0.5, START_TABLE_HEIGHT, 0.4]) setStaticCollider(table.prim, approximationShape='convexDecomposition') def reset(self): super().reset() super().cleanup() for robot in self._robots: # if not robot.handles_initialized: robot.initialize() indices = torch.arange(self._num_envs, dtype=torch.int64).to(self._device) self.reset_envs(indices) def reset_envs(self, env_indices): self.progress_buf[env_indices] = 0 self.reset_buf[env_indices] = False self.reset_robots(env_indices) self.reset_parts(env_indices) def reset_robots(self, env_indices): default_pose = torch.tensor([-math.pi / 2, -math.pi / 2, -math.pi / 2, -math.pi / 2, math.pi / 2, 0]) self._robots_view.set_joint_positions(default_pose, indices=env_indices) def reset_parts(self, env_indices): table_pos = self._table_view.get_world_poses(indices=env_indices)[0].to(self._device) default_rots = torch.tensor([0, 1, 0, 0]).repeat(len(env_indices), 1) for i in range(NUMBER_PARTS): parts_offsets = torch.tensor([0, 0.1 * i - 0.23, START_TABLE_HEIGHT / 2 + 0.04]).repeat(len(env_indices), 1).to(self._device) self._parts_views[i].set_world_poses(positions=table_pos + parts_offsets, orientations=default_rots, indices=env_indices) # _placed_parts # [[part]] where each entry in the outer array is the placed parts for env at index # Returns: A 2D Array where each entry is the poses of the parts in the box def get_observations(self): def _shortest_rot_dist(quat_1, quat_2): part_quat = Quaternion(list(quat_1)) ideal_quat = Quaternion(list(quat_2)) return Quaternion.absolute_distance(part_quat, ideal_quat) boxes_pos = self._boxes_view.get_world_poses()[0] # Returns: [Array of all pos, Array of all rots] robots_states = self._robots_view.get_joint_positions() self.obs_buf[:, 1:7] = robots_states parts_pos = [] parts_rots = [] for parts_view in self._parts_views: curr_parts_pos, curr_parts_rots = parts_view.get_world_poses() curr_parts_pos -= boxes_pos parts_pos.append(curr_parts_pos) parts_rots.append(curr_parts_rots) parts_pos = torch.stack(parts_pos).transpose(0, 1) # Stacks and transposes the array parts_rots = torch.stack(parts_rots).transpose(0, 1) for env_index in range(self._num_envs): gripper = self._robots[env_index].gripper gripper_closed = gripper.is_closed() self.obs_buf[env_index, 0] = gripper_closed ideal_selection = IDEAL_PACKAGING.copy() gripper_pos = self._robots[env_index].gripper.get_world_pose()[0] gripper_pos -= boxes_pos[env_index] gripper_to_closest_part_dist = 10000000 gripper_to_closest_part_dir = None gripper_to_ideal_part_dist = 10000000 gripper_to_ideal_part_dir = None for part_index in range(NUMBER_PARTS): part_pos = parts_pos[env_index][part_index] part_rot = parts_rots[env_index][part_index] part_to_box_dist = torch.linalg.norm(part_pos) if 0.3 < part_to_box_dist: # Only parts that are not packed can be potential gripped parts gripper_to_part = part_pos - gripper_pos gripper_part_dist = torch.linalg.norm(gripper_to_part) if gripper_part_dist < gripper_to_closest_part_dist: gripper_to_closest_part_dist = gripper_part_dist gripper_to_closest_part_dir = gripper_to_part ideal_part = None min_dist = 10000000 # Find closest ideal part for ideal_part in ideal_selection: ideal_part_pos = torch.tensor(ideal_part[0]).to(self._device) dist = torch.linalg.norm(ideal_part_pos - part_pos) if dist < min_dist: ideal_part = ideal_part min_dist = dist if part_index == 0: # Only one check is needed gripper_to_ideal_part = ideal_part_pos - gripper_pos gripper_ideal_dist = torch.linalg.norm(gripper_to_ideal_part) if gripper_ideal_dist < gripper_to_ideal_part_dist: gripper_to_ideal_part_dist = gripper_ideal_dist gripper_to_ideal_part_dir = gripper_to_ideal_part rot_dist = _shortest_rot_dist(part_rot, ideal_part[1]) # Clip obs min_dist = min(min_dist, 3) rot_dist = min(rot_dist, torch.pi) # Record obs self.obs_buf[env_index, (10 + part_index)] = min_dist self.obs_buf[env_index, (10 + NUMBER_PARTS + part_index)] = rot_dist # Point to target self.obs_buf[env_index, 7:10] = gripper_to_ideal_part_dir if gripper_to_closest_part_dist < 0.05 and gripper_closed else gripper_to_closest_part_dir def pre_physics_step(self, actions) -> None: reset_env_indices = self.reset_buf.nonzero(as_tuple=False).squeeze(-1) if 0 < len(reset_env_indices): self.reset_envs(reset_env_indices) # Rotate Joints joint_rots = self._robots_view.get_joint_positions() joint_rots += torch.tensor(actions[:, 0:6]).to(self._device) * self._max_joint_rot_speed self._robots_view.set_joint_positions(positions=joint_rots) # Open or close Gripper for env_index in range(self._num_envs): gripper = self._robots[env_index].gripper is_closed = gripper.is_closed() gripper_action = actions[env_index, 6] if 0.9 < gripper_action and is_closed: gripper.open() elif gripper_action < -0.3 and not is_closed: gripper.close() # Calculate Rewards def calculate_metrics(self) -> None: targets_dirs = self.obs_buf[:, 7:10] targets_dists = torch.linalg.norm(targets_dirs, dim=1) # part_rot_diffs = self.obs_buf[:, 10:13] ideal_pos_dists = self.obs_buf[:, 10:(10 + NUMBER_PARTS)] ideal_rot_dists = self.obs_buf[:, (10 + NUMBER_PARTS):(10 + 2 * NUMBER_PARTS)] box_error_sum = ideal_pos_dists.square().sum(dim=1) + ideal_rot_dists.abs().sum(dim=1) self.rew_buf = -targets_dists.square() - box_error_sum def is_done(self): # any_flipped = False self.reset_buf.fill_(0) for parts_view in self._parts_views: parts_pos = parts_view.get_world_poses()[0] # Check if part has fallen self.reset_buf += (parts_pos[:, 2] < FALLEN_PART_THRESHOLD) # if _is_flipped(part_rot): # any_flipped = True # break self.reset_buf += (self._max_episode_length - 1 <= self.progress_buf) self.reset_buf = self.reset_buf >= 1 # Cast to bool # def _is_flipped(q1): # """ # Bestimmt, ob die Rotation von q0 zu q1 ein "Umfallen" darstellt, # basierend auf einem Winkel größer als 60 Grad zwischen der ursprünglichen # z-Achse und ihrer Rotation. # :param q0: Ursprüngliches Quaternion. # :param q1: Neues Quaternion. # :return: True, wenn der Winkel größer als 60 Grad ist, sonst False. # """ # q0 = torch.tensor([0, 1, 0, 0]) # # Initialer Vektor, parallel zur z-Achse # v0 = torch.tensor([0, 0, 1]) # # Konvertiere Quaternions in Rotation-Objekte # rotation0 = R.from_quat(q0) # rotation1 = R.from_quat(q1) # # Berechne die relative Rotation von q0 zu q1 # q_rel = rotation1 * rotation0.inv() # # Berechne den rotierten Vektor v1 # v1 = q_rel.apply(v0) # # Berechne den Winkel zwischen v0 und v1 # cos_theta = np.dot(v0, v1) / (np.linalg.norm(v0) * np.linalg.norm(v1)) # angle = np.arccos(np.clip(cos_theta, -1.0, 1.0)) * 180 / np.pi # # Prüfe, ob der Winkel größer als 60 Grad ist # return angle > 60
20,134
Python
44.657596
174
0.572862
gitLSW/robot-cloud/training/train_ddpg.py
import os import threading import torch import torch.nn as nn import wandb # import the skrl components to build the RL system from skrl.utils import set_seed from skrl.agents.torch.ddpg import DDPG, DDPG_DEFAULT_CONFIG from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, Model from skrl.resources.noises.torch import OrnsteinUhlenbeckNoise from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import ParallelTrainer from skrl.envs.wrappers.torch import OmniverseIsaacGymWrapper from omniisaacgymenvs.isaac_gym_env_utils import get_env_instance name = 'DDPG_Pack' # seed for reproducibility seed = set_seed() # define models (deterministic models) using mixins class DeterministicActor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ReLU(), nn.Linear(512, 1024), nn.ReLU6(), nn.Linear(1024, 512), nn.Tanh(), nn.Linear(512, 256), nn.Tanh(), nn.Linear(256, self.num_actions)) def compute(self, inputs, role): return self.net(inputs["states"]), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations + self.num_actions, 256), nn.ReLU(), nn.Linear(256, 512), nn.ReLU6(), nn.Linear(512, 512), nn.Tanh(), nn.Linear(512, 256), nn.Tanh(), nn.Linear(256, 1)) def compute(self, inputs, role): return self.net(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1)), {} # Load the Isaac Gym environment headless = True # set headless to False for rendering multi_threaded = headless env = get_env_instance(headless=headless, multi_threaded=multi_threaded, # Multithreaded doesn't work with UI open experience=f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.kit') from omniisaacgymenvs.sim_config import SimConfig, merge from pack_task_part_in_gripper import PackTask as Task, TASK_CFG TASK_CFG['name'] = name TASK_CFG["seed"] = seed TASK_CFG["headless"] = headless if not headless: TASK_CFG["task"]["env"]["numEnvs"] = 25 sim_config = SimConfig(TASK_CFG) task = Task(name=name, sim_config=sim_config, env=env) env.set_task(task=task, sim_params=sim_config.get_physics_params(), backend="torch", init_sim=True, rendering_dt=TASK_CFG['task']['sim']['dt']) if multi_threaded: env.initialize(action_queue=env.action_queue, data_queue=env.data_queue, timeout=30) # wrap the environment env = OmniverseIsaacGymWrapper(env) device = env.device # instantiate the agent's models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models = { 'policy': DeterministicActor(env.observation_space, env.action_space, device), 'target_policy': DeterministicActor(env.observation_space, env.action_space, device), 'critic': Critic(env.observation_space, env.action_space, device), 'target_critic': Critic(env.observation_space, env.action_space, device), } num_envs = TASK_CFG["task"]["env"]["numEnvs"] # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters ddpg_cfg = DDPG_DEFAULT_CONFIG.copy() ddpg_cfg = merge({ "exploration": { "noise": OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=0.5, device=device) }, "gradient_steps": 1, "batch_size": 4096, "discount_factor": 0.99, "polyak": 0.005, "actor_learning_rate": 5e-4, "critic_learning_rate": 5e-4, "random_timesteps": 80, "learning_starts": 80, "state_preprocessor": RunningStandardScaler, "state_preprocessor_kwargs": { "size": env.observation_space, "device": device }, "experiment": { "directory": "progress", # experiment's parent directory "experiment_name": name, # experiment name "write_interval": 200, # TensorBoard writing interval (iterations) "checkpoint_interval": 1000, # interval for checkpoints (iterations) "store_separately": False, # whether to store checkpoints separately "wandb": True, # whether to use Weights & Biases "wandb_kwargs": {} # wandb kwargs (see https://docs.wandb.ai/ref/python/init) } }, ddpg_cfg) run = wandb.init( project=name, config=ddpg_cfg, sync_tensorboard=True, # auto-upload sb3's tensorboard metrics # monitor_gym=True, # auto-upload the videos of agents playing the game # save_code=True, # optional ) # instantiate a memory as experience replay memory = RandomMemory(memory_size=100_000, num_envs=num_envs, device=device) agent = DDPG(models=models, memory=memory, cfg=ddpg_cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) try: agent.load("./progress/DDPG_Pack/checkpoints/best_agent.pt") except FileNotFoundError: print('Cloud not load agent. Created new Agent !') # Configure and instantiate the RL trainer cfg_trainer = {"timesteps": 50_000_000 // num_envs, "headless": headless} trainer = ParallelTrainer(cfg=cfg_trainer, env=env, agents=agent) if multi_threaded: # start training in a separate thread threading.Thread(target=trainer.train).start() env.run(trainer=None) # The TraimerMT can be None, cause it is only used to stop the Sim else: trainer.train()
6,451
Python
38.341463
143
0.647652
gitLSW/robot-cloud/training/pack_task_part_in_gripper.py
import os import math import torch from gymnasium import spaces from omni.isaac.core.utils.extensions import enable_extension enable_extension("omni.isaac.universal_robots") # enable_extension("omni.isaac.sensor") from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.prims import delete_prim, get_prim_object_type #, create_prim, get_prim_at_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.physx.scripts.utils import setRigidBody, setStaticCollider #, setColliderSubtree, setCollider, addCollisionGroup, setPhysics, removePhysics, removeRigidBody from omni.isaac.universal_robots.ur10 import UR10 from omni.isaac.core.prims import XFormPrim, XFormPrimView, RigidPrim, RigidPrimView from omni.isaac.core.robots.robot_view import RobotView # from omni.isaac.core.materials.physics_material import PhysicsMaterial from omniisaacgymenvs.rl_task import RLTask from scipy.spatial.transform import Rotation as R from pyquaternion import Quaternion FALLEN_PART_THRESHOLD = 0.2 ROBOT_POS = torch.tensor([0.0, 0.0, FALLEN_PART_THRESHOLD]) LIGHT_OFFSET = torch.tensor([0, 0, 2]) DEST_BOX_POS = torch.tensor([0, -0.65, FALLEN_PART_THRESHOLD]) IDEAL_PACKAGING = [([-0.06, -0.19984, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.14044, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.07827, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.01597, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, 0.04664, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, 0.10918, 0.0803], [0.072, 0.99, 0, 0])] NUMBER_PARTS = len(IDEAL_PACKAGING) local_assets = os.getcwd() + '/assets' TASK_CFG = { "test": False, "device_id": 0, "headless": False, "multi_gpu": False, "sim_device": "gpu", "enable_livestream": False, "task": { "name": 'Pack_Task', # "physics_engine": "physx", "env": { "numEnvs": 100, "envSpacing": 4, "episodeLength": 400, # The episode length is the max time for one part to be packed, not the whole box # "enableDebugVis": False, # "controlFrequencyInv": 4 }, "sim": { "dt": 1.0 / 60.0, "gravity": [0.0, 0.0, -9.81], "substeps": 1, "use_gpu_pipeline": False, # Must be off for gripper to work "add_ground_plane": True, "add_distant_light": True, "use_fabric": True, "enable_scene_query_support": True, # Must be on for gripper to work "enable_cameras": False, "disable_contact_processing": False, # Must be off for gripper to work "use_flatcache": True, "default_physics_material": { "static_friction": 1.0, "dynamic_friction": 1.0, "restitution": 0.0 }, "physx": { ### Per-scene settings "use_gpu": True, "worker_thread_count": 4, "solver_type": 1, # 0: PGS, 1:TGS "bounce_threshold_velocity": 0.2, "friction_offset_threshold": 0.04, # A threshold of contact separation distance used to decide if a contact # point will experience friction forces. "friction_correlation_distance": 0.025, # Contact points can be merged into a single friction anchor if the # distance between the contacts is smaller than correlation distance. # disabling these can be useful for debugging "enable_sleeping": True, "enable_stabilization": True, # GPU buffers "gpu_max_rigid_contact_count": 512 * 1024, "gpu_max_rigid_patch_count": 80 * 1024, "gpu_found_lost_pairs_capacity": 1024, "gpu_found_lost_aggregate_pairs_capacity": 1024, "gpu_total_aggregate_pairs_capacity": 1024, "gpu_max_soft_body_contacts": 1024 * 1024, "gpu_max_particle_contacts": 1024 * 1024, "gpu_heap_capacity": 64 * 1024 * 1024, "gpu_temp_buffer_capacity": 16 * 1024 * 1024, "gpu_max_num_partitions": 8, "gpu_collision_stack_size": 64 * 1024 * 1024, ### Per-actor settings ( can override in actor_options ) "solver_position_iteration_count": 4, "solver_velocity_iteration_count": 1, "sleep_threshold": 0.0, # Mass-normalized kinetic energy threshold below which an actor may go to sleep. # Allowed range [0, max_float). "stabilization_threshold": 0.0, # Mass-normalized kinetic energy threshold below which an actor may # participate in stabilization. Allowed range [0, max_float). ### Per-body settings ( can override in actor_options ) "enable_gyroscopic_forces": False, "density": 1000.0, # density to be used for bodies that do not specify mass or density "max_depenetration_velocity": 100.0, ### Per-shape settings ( can override in actor_options ) "contact_offset": 0.02, "rest_offset": 0.001, } } } } class PackTask(RLTask): control_frequency_inv = 1 # kinematics_solver = None """ This class sets up a scene and calls a RL Policy, then evaluates the behaivior with rewards Args: offset (Optional[np.ndarray], optional): offset applied to all assets of the task. sim_s_step_freq (int): The amount of simulation steps within a SIMULATED second. """ def __init__(self, name, sim_config, env, offset=None) -> None: self._num_observations = 10 + 2 * NUMBER_PARTS # self.observation_space = spaces.Dict({ 'obs': spaces.Box(low=-math.pi, high=math.pi, shape=(self._num_observations,), dtype=float) }) self._num_actions = 7 # gripper open / close & Delta 6 joint rots # self.action_space = spaces.Box(low=-1, high=1, shape=(self._num_actions,), dtype=float) self.update_config(sim_config) super().__init__(name, env, offset) def update_config(self, sim_config): self._sim_config = sim_config self._cfg = sim_config.config self._task_cfg = sim_config.task_config self.dt = self._task_cfg["sim"]["dt"] self._device = self._cfg["sim_device"] self._num_envs = self._task_cfg["env"]["numEnvs"] self._env_spacing = self._task_cfg["env"]["envSpacing"] self._max_episode_length = self._task_cfg["env"]["episodeLength"] # Robot turning ange of max speed is 191deg/s self._max_joint_rot_speed = torch.scalar_tensor((191.0 * torch.pi / 180) * self.dt).to(self._device) super().update_config(sim_config) def set_up_scene(self, scene) -> None: print('SETUP TASK', self.name) self.create_env0() super().set_up_scene(scene) # Clones env0 self._boxes_view = XFormPrimView(prim_paths_expr=f'{self.default_base_env_path}/.*/box', name='box_view', reset_xform_properties=False) scene.add(self._boxes_view) self._robots_view = RobotView(prim_paths_expr=f'{self.default_base_env_path}/.*/robot', name='ur10_view') scene.add(self._robots_view) self._grippers = RigidPrimView(prim_paths_expr=f'{self.default_base_env_path}/.*/robot/ee_link', name="gripper_view") scene.add(self._grippers) self._robots = [UR10(prim_path=robot_path, attach_gripper=True) for robot_path in self._robots_view.prim_paths] def create_env0(self): # This is the URL from which the Assets are downloaded # Make sure you started and connected to your localhost Nucleus Server via Omniverse !!! assets_root_path = get_assets_root_path() env0_box_path = self.default_zero_env_path + '/box' box_usd_path = assets_root_path + '/Isaac/Environments/Simple_Warehouse/Props/SM_CardBoxA_02.usd' box_usd_path = local_assets + '/SM_CardBoxA_02.usd' add_reference_to_stage(box_usd_path, env0_box_path) box = XFormPrim(prim_path=env0_box_path, position=DEST_BOX_POS, scale=[1, 1, 0.4]) setStaticCollider(box.prim, approximationShape='convexDecomposition') # The UR10e has 6 joints, each with a maximum: # turning angle of -360 deg to +360 deg # turning ange of max speed is 191deg/s env0_robot_path = self.default_zero_env_path + '/robot' robot = UR10(prim_path=env0_robot_path, name='UR10', position=ROBOT_POS, attach_gripper=True) robot.set_enabled_self_collisions(True) def cleanup(self): self._curr_parts = [None for _ in range(self._num_envs)] self._placed_parts = [[] for _ in range(self._num_envs)] super().cleanup() def reset(self): super().reset() self.cleanup() for env_index in range(self._num_envs): robot = self._robots[env_index] if not robot.handles_initialized: robot.initialize() self.reset_env(env_index) def reset_env(self, env_index): self.progress_buf[env_index] = 0 self.reset_buf[env_index] = False self.reset_robot(env_index) curr_part = self._curr_parts[env_index] if curr_part: delete_prim(curr_part.prim_path) self._curr_parts[env_index] = None for part in self._placed_parts[env_index]: delete_prim(part.prim_path) self._placed_parts[env_index] = [] self._curr_parts[env_index] = self.add_part(env_index) def reset_robot(self, env_index): robot = self._robots[env_index] default_pose = torch.tensor([math.pi / 2, -math.pi / 2, -math.pi / 2, -math.pi / 2, math.pi / 2, 0]) robot.set_joint_positions(positions=default_pose) robot.gripper.open() def add_part(self, env_index) -> None: # gripper = self._robots[env_index].gripper # part_pos = torch.tensor(gripper.get_world_pose()[0]) - torch.tensor([0, 0, 0.18], device=self._device) box_pos = self._boxes_view.get_world_poses()[0][env_index] part_pos = box_pos + torch.tensor([-0.12, -0.05, 0.48]).to(self._device) part_index = len(self._placed_parts[env_index]) part_path = f'{self.default_base_env_path}/env_{env_index}/parts/part_{part_index}' part_usd_path = local_assets + '/draexlmaier_part.usd' add_reference_to_stage(part_usd_path, part_path) part = RigidPrim(prim_path=part_path, name=f'env_{env_index}_part_{part_index}', position=part_pos, orientation=[0, 1, 0, 0], mass=0.4) # [-0.70711, 0.70711, 0, 0] if get_prim_object_type(part_path) != 'rigid_body': setRigidBody(part.prim, approximationShape='convexDecomposition', kinematic=False) # Kinematic True means immovable return part # _placed_parts # [[part]] where each entry in the outer array is the placed parts for env at index # Returns: A 2D Array where each entry is the poses of the parts in the box def get_observations(self): def _shortest_rot_dist(quat_1, quat_2): part_quat = Quaternion(list(quat_1)) ideal_quat = Quaternion(list(quat_2)) return Quaternion.absolute_distance(part_quat, ideal_quat) boxes_pos = self._boxes_view.get_world_poses()[0] # Returns: [Array of all pos, Array of all rots] # obs_dicts = [] for env_index in range(self._num_envs): # env_obs = { 'box_state': [] } robot = self._robots[env_index] gripper_closed = robot.gripper.is_closed() self.obs_buf[env_index, 0] = gripper_closed # env_obs['gripper_closed'] = gripper_closed robot_state = robot.get_joint_positions() self.obs_buf[env_index, 1:7] = robot_state ideal_selection = IDEAL_PACKAGING.copy() box_pos = boxes_pos[env_index] curr_part = self._curr_parts[env_index] eval_parts = self._placed_parts[env_index] + [curr_part] # box_state = [] # ideal_pose_for_curr_part = None for part_index in range(NUMBER_PARTS): if len(eval_parts) <= part_index: # The worst possible distance is 3m and 180deg self.obs_buf[env_index, (10 + part_index)] = torch.scalar_tensor(3) self.obs_buf[env_index, (10 + NUMBER_PARTS + part_index)] = torch.pi # env_obs['box_state'].append([3, torch.pi]) continue part_pos, part_rot = eval_parts[part_index].get_world_pose() part_pos -= box_pos ideal_part = None min_dist = 10000000 # Find closest ideal part for pot_part in ideal_selection: dist = torch.linalg.norm(torch.tensor(pot_part[0], device=self._device) - part_pos) if dist < min_dist: ideal_part = pot_part min_dist = dist rot_dist = _shortest_rot_dist(part_rot, ideal_part[1]) # Clip obs min_dist = min(min_dist, 3) rot_dist = min(rot_dist, torch.pi) # Record obs self.obs_buf[env_index, (10 + part_index)] = min_dist self.obs_buf[env_index, (10 + NUMBER_PARTS + part_index)] = rot_dist # env_obs['box_state'].append([min_dist, rot_dist]) if part_index == len(eval_parts) - 1: part_pos_diff = part_pos - torch.tensor(ideal_part[0]).to(self._device) # part_rot_euler = R.from_quat(part_rot.cpu()).as_euler('xyz', degrees=False) # ideal_rot_euler = R.from_quat(ideal_part[1]).as_euler('xyz', degrees=False) # part_rot_diff = torch.tensor(ideal_rot_euler - part_rot_euler) self.obs_buf[env_index, 7:10] = part_pos_diff # self.obs_buf[env_index, 10:13] = part_rot_diff # # env_obs['part_pos_diff'] = part_pos_diff # # env_obs['part_rot_diff'] = part_rot_diff # obs_dicts.append(env_obs) # The return is itrrelevant for Multi Threading: # The VecEnvMT Loop calls RLTask.post_physics_step to get all the data from one step. # RLTask.post_physics_step is simply returning self.obs_buf, self.rew_buf,... # post_physics_step calls # - get_observations() # - get_states() # - calculate_metrics() # - is_done() # - get_extras() # return obs_dicts return self.obs_buf[env_index] def pre_physics_step(self, actions) -> None: for env_index in range(self._num_envs): if self.reset_buf[env_index]: self.reset_env(env_index) continue # Rotate Joints robot = self._robots[env_index] gripper = robot.gripper env_step = self.progress_buf[env_index] if env_step <= 1: gripper.close() continue joint_rots = robot.get_joint_positions() joint_rots += actions[env_index, 0:6].to(self._device) * self._max_joint_rot_speed robot.set_joint_positions(positions=joint_rots) # Open or close Gripper is_closed = gripper.is_closed() gripper_action = actions[env_index, 6] if 0.9 < gripper_action and is_closed: gripper.open() elif gripper_action < -0.3 and not is_closed: gripper.close() # Calculate Rewards def calculate_metrics(self) -> None: pos_rew = 0 parts_to_ideal_pos = self.obs_buf[:, 7:10] parts_to_ideal_pos_dists = torch.linalg.norm(parts_to_ideal_pos, dim=1) # Move Parts # if len(self._placed_parts) + (1 if self._curr_parts[env_index] else 0) < NUMBER_PARTS: # TODO: ADD ROT DIST AS WELL AS A CONDITION next_part_env_indices = (parts_to_ideal_pos_dists < 0.003).nonzero(as_tuple=False).squeeze(-1) for env_index in next_part_env_indices: self._placed_parts[env_index].append(self._curr_parts[env_index]) self._curr_parts[env_index] = self.add_part(env_index) # A new part gets placed with each reset self.progress_buf[env_index] = 0 pos_rew += 200 # part_rot_diffs = self.obs_buf[:, 10:13] ideal_pos_dists = self.obs_buf[:, 10:(10 + NUMBER_PARTS)] ideal_rot_dists = self.obs_buf[:, (10 + NUMBER_PARTS):(10 + 2 * NUMBER_PARTS)] box_error_sum = ideal_pos_dists.square().sum(dim=1) + ideal_rot_dists.abs().sum(dim=1) self.rew_buf = -parts_to_ideal_pos_dists.square() - box_error_sum + pos_rew def is_done(self): # any_flipped = False self.reset_buf.fill_(0) for env_index in range(self._num_envs): part = self._curr_parts[env_index] if not part: continue part_pos = part.get_world_pose()[0] # Check if part has fallen self.reset_buf[env_index] += (part_pos[2] < FALLEN_PART_THRESHOLD - 0.05) # TODO: FIX THIS SHIT # if _is_flipped(part_rot): # any_flipped = True # break self.reset_buf += (self._max_episode_length - 1 <= self.progress_buf) self.reset_buf = self.reset_buf >= 1 # Cast to bool # def _is_flipped(q1): # """ # Bestimmt, ob die Rotation von q0 zu q1 ein "Umfallen" darstellt, # basierend auf einem Winkel größer als 60 Grad zwischen der ursprünglichen # z-Achse und ihrer Rotation. # :param q0: Ursprüngliches Quaternion. # :param q1: Neues Quaternion. # :return: True, wenn der Winkel größer als 60 Grad ist, sonst False. # """ # q0 = torch.tensor([0, 1, 0, 0]) # # Initialer Vektor, parallel zur z-Achse # v0 = torch.tensor([0, 0, 1]) # # Konvertiere Quaternions in Rotation-Objekte # rotation0 = R.from_quat(q0) # rotation1 = R.from_quat(q1) # # Berechne die relative Rotation von q0 zu q1 # q_rel = rotation1 * rotation0.inv() # # Berechne den rotierten Vektor v1 # v1 = q_rel.apply(v0) # # Berechne den Winkel zwischen v0 und v1 # cos_theta = np.dot(v0, v1) / (np.linalg.norm(v0) * np.linalg.norm(v1)) # angle = np.arccos(np.clip(cos_theta, -1.0, 1.0)) * 180 / np.pi # # Prüfe, ob der Winkel größer als 60 Grad ist # return angle > 60
19,174
Python
42.284424
166
0.569782
gitLSW/robot-cloud/training/omniisaacgymenvs/isaac_gym_env_utils.py
import asyncio import queue import torch from skrl import logger def get_env_instance(headless: bool = True, enable_livestream: bool = False, enable_viewport: bool = False, multi_threaded: bool = False, experience = None) -> "omni.isaac.gym.vec_env.VecEnvBase": """ Instantiate a VecEnvBase-based object compatible with OmniIsaacGymEnvs :param headless: Disable UI when running (default: ``True``) :type headless: bool, optional :param enable_livestream: Whether to enable live streaming (default: ``False``) :type enable_livestream: bool, optional :param enable_viewport: Whether to enable viewport (default: ``False``) :type enable_viewport: bool, optional :param multi_threaded: Whether to return a multi-threaded environment instance (default: ``False``) :type multi_threaded: bool, optional :return: Environment instance :rtype: omni.isaac.gym.vec_env.VecEnvBase Example:: from skrl.envs.wrappers.torch import wrap_env from skrl.utils.omniverse_isaacgym_utils import get_env_instance # get environment instance env = get_env_instance(headless=True) # parse sim configuration from omniisaacgymenvs.utils.config_utils.sim_config import SimConfig sim_config = SimConfig({"test": False, "device_id": 0, "headless": True, "multi_gpu": False, "sim_device": "gpu", "enable_livestream": False, "task": {"name": "CustomTask", "physics_engine": "physx", "env": {"numEnvs": 512, "envSpacing": 1.5, "enableDebugVis": False, "clipObservations": 1000.0, "clipActions": 1.0, "controlFrequencyInv": 4}, "sim": {"dt": 0.0083, # 1 / 120 "use_gpu_pipeline": True, "gravity": [0.0, 0.0, -9.81], "add_ground_plane": True, "use_flatcache": True, "enable_scene_query_support": False, "enable_cameras": False, "default_physics_material": {"static_friction": 1.0, "dynamic_friction": 1.0, "restitution": 0.0}, "physx": {"worker_thread_count": 4, "solver_type": 1, "use_gpu": True, "solver_position_iteration_count": 4, "solver_velocity_iteration_count": 1, "contact_offset": 0.005, "rest_offset": 0.0, "bounce_threshold_velocity": 0.2, "friction_offset_threshold": 0.04, "friction_correlation_distance": 0.025, "enable_sleeping": True, "enable_stabilization": True, "max_depenetration_velocity": 1000.0, "gpu_max_rigid_contact_count": 524288, "gpu_max_rigid_patch_count": 33554432, "gpu_found_lost_pairs_capacity": 524288, "gpu_found_lost_aggregate_pairs_capacity": 262144, "gpu_total_aggregate_pairs_capacity": 1048576, "gpu_max_soft_body_contacts": 1048576, "gpu_max_particle_contacts": 1048576, "gpu_heap_capacity": 33554432, "gpu_temp_buffer_capacity": 16777216, "gpu_max_num_partitions": 8}}}}) # import and setup custom task from custom_task import CustomTask task = CustomTask(name="CustomTask", sim_config=sim_config, env=env) env.set_task(task=task, sim_params=sim_config.get_physics_params(), backend="torch", init_sim=True) # wrap the environment env = wrap_env(env, "omniverse-isaacgym") """ from omni.isaac.gym.vec_env import TaskStopException, VecEnvBase, VecEnvMT from omni.isaac.gym.vec_env.vec_env_mt import TrainerMT class _OmniIsaacGymVecEnv(VecEnvBase): def step(self, actions): actions = torch.clamp(actions, -self._task.clip_actions, self._task.clip_actions).to(self._task.device).clone() self._task.pre_physics_step(actions) for _ in range(self._task.control_frequency_inv): self._world.step(render=self._render) self.sim_frame_count += 1 observations, rewards, dones, info = self._task.post_physics_step() return {"obs": torch.clamp(observations, -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone()}, \ rewards.to(self._task.rl_device).clone(), dones.to(self._task.rl_device).clone(), info.copy() def reset(self): self._task.reset() actions = torch.zeros((self.num_envs, self._task.num_actions), device=self._task.device) return self.step(actions)[0] class _OmniIsaacGymTrainerMT(TrainerMT): def run(self): pass def stop(self): pass class _OmniIsaacGymVecEnvMT(VecEnvMT): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.set_render_mode(-1 if kwargs['headless'] else 2) self.action_queue = queue.Queue(1) self.data_queue = queue.Queue(1) def run(self, trainer=None): asyncio.run(super().run(_OmniIsaacGymTrainerMT() if trainer is None else trainer)) def _parse_data(self, data): self._observations = torch.clamp(data["obs"], -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone() self._rewards = data["rew"].to(self._task.rl_device).clone() self._dones = data["reset"].to(self._task.rl_device).clone() self._info = data["extras"].copy() def step(self, actions): if self._stop: raise TaskStopException() actions = torch.clamp(actions, -self._task.clip_actions, self._task.clip_actions).clone() self.send_actions(actions) # Send actions data = self.get_data() # this waits until data queue has content and then calls _parse_data return {"obs": self._observations}, self._rewards, self._dones, self._info def reset(self): self._task.reset() actions = torch.zeros((self.num_envs, self._task.num_actions), device=self._task.device) return self.step(actions)[0] def close(self): # end stop signal to main thread self.send_actions(None) self.stop = True if multi_threaded: try: return _OmniIsaacGymVecEnvMT(headless=headless, enable_livestream=enable_livestream, enable_viewport=enable_viewport, experience=experience) except TypeError: logger.warning("Using an older version of Isaac Sim (2022.2.0 or earlier)") return _OmniIsaacGymVecEnvMT(headless=headless, experience=experience) else: try: return _OmniIsaacGymVecEnv(headless=headless, enable_livestream=enable_livestream, enable_viewport=enable_viewport, experience=experience) except TypeError: logger.warning("Using an older version of Isaac Sim (2022.2.0 or earlier)") return _OmniIsaacGymVecEnv(headless=headless, experience=experience) # Isaac Sim 2022.2.0 and earlier
9,114
Python
52.304093
152
0.475752
gitLSW/robot-cloud/remnants/SKRL_easy_pack_task.py
import os import math import random import torch from pxr import Gf, UsdLux, Sdf from gymnasium import spaces import omni.kit.commands from omni.isaac.core.utils.extensions import enable_extension # enable_extension("omni.importer.urdf") enable_extension("omni.isaac.universal_robots") enable_extension("omni.isaac.sensor") # from omni.importer.urdf import _urdf from omni.isaac.sensor import Camera from omni.isaac.universal_robots.ur10 import UR10 from omni.isaac.universal_robots import KinematicsSolver # from omni.isaac.universal_robots.controllers.pick_place_controller import PickPlaceController import omni.isaac.core.utils.prims as prims_utils from omni.isaac.core.prims import XFormPrim, XFormPrimView, RigidPrim, RigidPrimView from omni.isaac.core.materials.physics_material import PhysicsMaterial from omni.isaac.core.utils.prims import create_prim, get_prim_at_path from omni.isaac.core.tasks.base_task import BaseTask from omni.isaac.gym.tasks.rl_task import RLTaskInterface from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.core.utils.viewports import set_camera_view from omni.kit.viewport.utility import get_active_viewport import omni.isaac.core.objects as objs import omni.isaac.core.utils.numpy.rotations as rot_utils from omni.isaac.core.utils.rotations import lookat_to_quatf, gf_quat_to_np_array from omni.physx.scripts.utils import setRigidBody, setStaticCollider, setColliderSubtree, setCollider, addCollisionGroup, setPhysics, removePhysics, removeRigidBody from scipy.spatial.transform import Rotation as R from pyquaternion import Quaternion from omniisaacgymenvs.rl_task import RLTask from omni.isaac.core.robots.robot_view import RobotView from omni.isaac.cloner import GridCloner LEARNING_STARTS = 10 FALLEN_PART_THRESHOLD = 0.2 ROBOT_PATH = 'World/UR10e' ROBOT_POS = torch.tensor([0.0, 0.0, FALLEN_PART_THRESHOLD]) LIGHT_PATH = 'World/Light' LIGHT_OFFSET = torch.tensor([0, 0, 2]) DEST_BOX_PATH = "World/DestinationBox" DEST_BOX_POS = torch.tensor([0, -0.65, FALLEN_PART_THRESHOLD]) PART_PATH = 'World/Part' PART_OFFSET = torch.tensor([0, 0, 0.4]) # NUM_PARTS = 5 PART_PILLAR_PATH = "World/Pillar" MAX_STEP_PUNISHMENT = 300 START_TABLE_POS = torch.tensor([0.36, 0.8, 0]) START_TABLE_HEIGHT = 0.6 START_TABLE_CENTER = START_TABLE_POS + torch.tensor([0, 0, START_TABLE_HEIGHT]) IDEAL_PACKAGING = [([-0.06, -0.19984, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.14044, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.07827, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.01597, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, 0.04664, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, 0.10918, 0.0803], [0.072, 0.99, 0, 0])] NUMBER_PARTS = len(IDEAL_PACKAGING) local_assets = os.getcwd() + '/assets' TASK_CFG = { "test": False, "device_id": 0, "headless": False, "multi_gpu": False, "sim_device": "cpu", "enable_livestream": False, "task": { "name": 'Pack_Task', "physics_engine": "physx", "env": { "numEnvs": 100, "envSpacing": 1.5, "episodeLength": 100, # "enableDebugVis": False, # "controlFrequencyInv": 4 }, "sim": { "dt": 1 / 60, "use_gpu_pipeline": True, "gravity": [0.0, 0.0, -9.81], "add_ground_plane": True, "use_flatcache": True, "enable_scene_query_support": False, "enable_cameras": False, "default_physics_material": { "static_friction": 1.0, "dynamic_friction": 1.0, "restitution": 0.0 }, "physx": { "worker_thread_count": 4, "solver_type": 1, "use_gpu": True, "solver_position_iteration_count": 4, "solver_velocity_iteration_count": 1, "contact_offset": 0.005, "rest_offset": 0.0, "bounce_threshold_velocity": 0.2, "friction_offset_threshold": 0.04, "friction_correlation_distance": 0.025, "enable_sleeping": True, "enable_stabilization": True, "max_depenetration_velocity": 1000.0, "gpu_max_rigid_contact_count": 524288, "gpu_max_rigid_patch_count": 33554432, "gpu_found_lost_pairs_capacity": 524288, "gpu_found_lost_aggregate_pairs_capacity": 262144, "gpu_total_aggregate_pairs_capacity": 1048576, "gpu_max_soft_body_contacts": 1048576, "gpu_max_particle_contacts": 1048576, "gpu_heap_capacity": 33554432, "gpu_temp_buffer_capacity": 16777216, "gpu_max_num_partitions": 8 } } } } class PackTask(RLTask): control_frequency_inv = 1 # kinematics_solver = None """ This class sets up a scene and calls a RL Policy, then evaluates the behaivior with rewards Args: offset (Optional[np.ndarray], optional): offset applied to all assets of the task. sim_s_step_freq (int): The amount of simulation steps within a SIMULATED second. """ def __init__(self, name, sim_config, env, offset=None) -> None: # self.observation_space = spaces.Dict({ # 'robot_state': spaces.Box(low=-2 * torch.pi, high=2 * torch.pi, shape=(6,)), # 'gripper_closed': spaces.Discrete(2), # # 'forces': spaces.Box(low=-1, high=1, shape=(8, 6)), # Forces on the Joints # 'box_state': spaces.Box(low=-3, high=3, shape=(NUMBER_PARTS, 2)), # Pos and Rot Distance of each part currently placed in Box compared to currently gripped part # 'part_pos_diff': spaces.Box(low=-3, high=3, shape=(3,)), # 'part_rot_diff': spaces.Box(low=-1, high=1, shape=(3,)) # }) self._num_observations = 13 + 2 * NUMBER_PARTS # End Effector Pose # self.action_space = spaces.Box(low=-1, high=1, shape=(7,), dtype=float) # Delta Gripper Pose & gripper open / close self._num_actions = 7 self.update_config(sim_config) # trigger __init__ of parent class super().__init__(name, env, offset) def cleanup(self): super().cleanup() def update_config(self, sim_config): self._sim_config = sim_config self._cfg = sim_config.config self._task_cfg = sim_config.task_config self.dt = self._task_cfg["sim"]["dt"] self._device = self._cfg["sim_device"] self._num_envs = self._task_cfg["env"]["numEnvs"] self._env_spacing = self._task_cfg["env"]["envSpacing"] self._max_episode_length = self._task_cfg["env"]["episodeLength"] # Robot turning ange of max speed is 191deg/s self._max_joint_rot_speed = (191.0 * math.pi / 180) * self.dt super().update_config(sim_config) def set_up_scene(self, scene) -> None: print('SETUP TASK', self.name) self.create_env0() super().set_up_scene(scene) # Clones env0 self._boxes_view = XFormPrimView(prim_paths_expr=f'{self.default_base_env_path}/.*/box', name='box_view', reset_xform_properties=False) scene.add(self._boxes_view) # self._parts_views = [] # for i in range(NUMBER_PARTS): i=0 self._parts_view = RigidPrimView(prim_paths_expr=f'{self.default_base_env_path}/.*/part_{i}', name=f'part_{i}_view', reset_xform_properties=False) scene.add(self._parts_view) # self._parts_views.append(parts_view) self._robots_view = RobotView(prim_paths_expr=f'{self.default_base_env_path}/.*/robot', name='ur10_view') scene.add(self._robots_view) self._grippers = RigidPrimView(prim_paths_expr=f'{self.default_base_env_path}/.*/robot/ee_link', name="gripper_view") scene.add(self._grippers) self._curr_parts = [XFormPrim(prim_path=path) for path in self._parts_view.prim_paths] self._robots = [UR10(prim_path=robot_path, attach_gripper=True) for robot_path in self._robots_view.prim_paths] # # self.table = RigidPrim(rim_path=self._start_table_path, name='TABLE') # self._task_objects[self._start_table_path] = self.table def create_env0(self): # This is the URL from which the Assets are downloaded # Make sure you started and connected to your localhost Nucleus Server via Omniverse !!! assets_root_path = get_assets_root_path() env0_box_path = self.default_zero_env_path + '/box' box_usd_path = assets_root_path + '/Isaac/Environments/Simple_Warehouse/Props/SM_CardBoxA_02.usd' box_usd_path = local_assets + '/SM_CardBoxA_02.usd' add_reference_to_stage(box_usd_path, env0_box_path) box = XFormPrim(prim_path=env0_box_path, position=DEST_BOX_POS, scale=[1, 1, 0.4]) setStaticCollider(box.prim, approximationShape='convexDecomposition') # for i in range(NUMBER_PARTS): env0_part_path = f'{self.default_zero_env_path}/part_{i}' part_usd_path = local_assets + '/draexlmaier_part.usd' add_reference_to_stage(part_usd_path, env0_part_path) part = RigidPrim(prim_path=env0_part_path, position=START_TABLE_CENTER + torch.tensor([0, 0.06 * i - 0.2, 0.1]), orientation=[0, 1, 0, 0]) # [-0.70711, 0.70711, 0, 0] setRigidBody(part.prim, approximationShape='convexDecomposition', kinematic=False) # Kinematic True means immovable # The UR10e has 6 joints, each with a maximum: # turning angle of -360 deg to +360 deg # turning ange of max speed is 191deg/s env0_robot_path = self.default_zero_env_path + '/robot' robot = UR10(prim_path=env0_robot_path, name='UR10', position=ROBOT_POS, attach_gripper=True) robot.set_enabled_self_collisions(True) # env0_table_path = f'{self.default_zero_env_path}/table' # table_path = assets_root_path + "/Isaac/Environments/Simple_Room/Props/table_low.usd" # # table_path = local_assets + '/table_low.usd' # add_reference_to_stage(table_path, env0_table_path) # table = XFormPrim(prim_path=env0_table_path, position=START_TABLE_POS, scale=[0.5, START_TABLE_HEIGHT, 0.4]) # setRigidBody(table.prim, approximationShape='convexHull', kinematic=True) # Kinematic True means immovable def reset(self): super().reset() super().cleanup() self._placed_parts = [[] for _ in range(self._num_envs)] for env_index in range(self._num_envs): robot = self._robots[env_index] if not robot.handles_initialized: robot.initialize() self.reset_env(env_index) pos = torch.tensor([1, 0, 0]).to(torch.float32).repeat(self._num_envs, 1) rots = torch.tensor([0, 1, 0, 0]).to(torch.float32).repeat(self._num_envs, 1) self._parts_view.set_world_poses(pos, rots) def reset_env(self, env_index): self.progress_buf[env_index] = 0 self.reset_buf[env_index] = False self.reset_robot(env_index) def reset_robot(self, env_index): robot = self._robots[env_index] default_pose = torch.tensor([math.pi / 2, -math.pi / 2, -math.pi / 2, -math.pi / 2, math.pi / 2, 0]) robot.set_joint_positions(positions=default_pose) robot.gripper.open() def reset_part(self, env_index): gripper = self._robots[env_index].gripper part_pos = torch.tensor([gripper.get_world_pose()[0] - torch.tensor([-0.00147, 0.0154, 0.193], device=self._device)]) # part = self._curr_parts[env_index] # part.set_world_pose(part_pos, [-0.70711, 0.70711, 0, -0.06]) self._parts_view.set_world_poses(part_pos, torch.tensor([[-0.70711, 0.70711, 0, -0.06]]), [env_index]) # removePhysics(part.prim) # setRigidBody(part.prim, approximationShape='convexDecomposition', kinematic=False) # def next_part(self, env_index) -> None: # gripper = self._robots[env_index].gripper # gripper_pos = torch.tensor(gripper.get_world_pose()[0]) - torch.tensor([0, 0, 0.05], device=self._device) # env0_part_path = self.default_zero_env_path + '/part_0' # part_usd_path = local_assets + '/draexlmaier_part.usd' # add_reference_to_stage(part_usd_path, env0_part_path) # part = RigidPrim(prim_path=env0_part_path, # position=gripper_pos, # orientation=[0, 1, 0, 0], # mass=0.5) # self.world.scene.add(part) # self._placed_parts[env_index].append(self._curr_parts[env_index]) # self._curr_parts[env_index] = part # _placed_parts # [[part]] where each entry in the outer array is the placed parts for env at index # Returns: A 2D Array where each entry is the poses of the parts in the box def get_observations(self): def _shortest_rot_dist(quat_1, quat_2): part_quat = Quaternion(list(quat_1)) ideal_quat = Quaternion(list(quat_2)) return Quaternion.absolute_distance(part_quat, ideal_quat) boxes_pos = self._boxes_view.get_world_poses()[0] # Returns: [Array of all pos, Array of all rots] # obs_dicts = [] for env_index in range(self._num_envs): # env_obs = { 'box_state': [] } robot = self._robots[env_index] gripper_closed = robot.gripper.is_closed() self.obs_buf[env_index, 0] = gripper_closed # env_obs['gripper_closed'] = gripper_closed robot_state = robot.get_joint_positions() self.obs_buf[env_index, 1:7] = robot_state ideal_selection = IDEAL_PACKAGING.copy() box_pos = boxes_pos[env_index] curr_part = self._curr_parts[env_index] eval_parts = self._placed_parts[env_index] + [curr_part] # box_state = [] # ideal_pose_for_curr_part = None for part_index in range(NUMBER_PARTS): if len(eval_parts) <= part_index: # The worst possible distance is 3m and 180deg self.obs_buf[env_index, (13 + 2 * part_index)] = torch.scalar_tensor(3) self.obs_buf[env_index, (14 + 2 * part_index)] = torch.pi # env_obs['box_state'].append([3, torch.pi]) continue part_pos, part_rot = eval_parts[part_index].get_world_pose() part_pos -= box_pos ideal_part = None min_dist = 10000000 # Find closest ideal part for pot_part in ideal_selection: dist = torch.linalg.norm(torch.tensor(pot_part[0], device=self._device) - part_pos) if dist < min_dist: ideal_part = pot_part min_dist = dist rot_dist = _shortest_rot_dist(part_rot, ideal_part[1]) self.obs_buf[env_index, (13 + 2 * part_index)] = min_dist self.obs_buf[env_index, (14 + 2 * part_index)] = rot_dist # env_obs['box_state'].append([min_dist, rot_dist]) if part_index == len(eval_parts) - 1: part_pos_diff = part_pos - torch.tensor(ideal_part[0], device=self._device) part_rot_euler = R.from_quat(part_rot.cpu()).as_euler('xyz', degrees=False) ideal_rot_euler = R.from_quat(ideal_part[1]).as_euler('xyz', degrees=False) part_rot_diff = torch.tensor(ideal_rot_euler - part_rot_euler) self.obs_buf[env_index, 7:10] = part_pos_diff self.obs_buf[env_index, 10:13] = part_rot_diff # env_obs['part_pos_diff'] = part_pos_diff # env_obs['part_rot_diff'] = part_rot_diff # obs_dicts.append(env_obs) # The return is itrrelevant for Multi Threading: # The VecEnvMT Loop calls RLTask.post_physics_step to get all the data from one step. # RLTask.post_physics_step is simply returning self.obs_buf, self.rew_buf,... # post_physics_step calls # - get_observations() # - get_states() # - calculate_metrics() # - is_done() # - get_extras() # return obs_dicts return self.obs_buf[env_index] def pre_physics_step(self, actions) -> None: # reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1) # if len(reset_env_ids) > 0: # self.reset_idx(reset_env_ids) for env_index in range(self._num_envs): if self.reset_buf[env_index]: self.reset_env(env_index) continue # Rotate Joints robot = self._robots[env_index] gripper = robot.gripper env_step = self.progress_buf[env_index] if env_step == 1: # We cannot call this in the same step as reset robot since the world needs # to update once to update the gripper position to the new joint rotations self.reset_part(env_index) gripper.close() continue joint_rots = robot.get_joint_positions() joint_rots += torch.tensor(actions[env_index, 0:6]) * self._max_joint_rot_speed robot.set_joint_positions(positions=joint_rots) # Open or close Gripper # is_closed = gripper.is_closed() # gripper_action = actions[env_index, 6] # if 0.9 < gripper_action and is_closed: # gripper.open() # elif gripper_action < -0.3 and not is_closed: # gripper.close() # Calculate Rewards def calculate_metrics(self) -> None: pass # part_pos_diffs = self.obs_buf[:, 7:10] # part_rot_diffs = self.obs_buf[:, 10:13] # box_states = self.obs_buf[:, 13:(2 * NUMBER_PARTS)] # self.rew_buf = part_pos_diffs.squared().sum(dim=1) + part_rot_diffs.squared().sum(dim=1) + box_states.squared().sum(dim=1) # Terminate: Umgefallene Teile, Gefallene Teile # Success: # part_pos, part_rot = self.part.get_world_pose() # any_flipped = False # for part in self.placed_parts: # part_rot = part.get_world_pose()[1] # if _is_flipped(part_rot): # any_flipped = True # break # if part_pos[2] < FALLEN_PART_THRESHOLD or self.max_steps < self.step or any_flipped: # return -MAX_STEP_PUNISHMENT, True # box_state, _ = self.compute_box_state() # box_deviation = torch.sum(torch.square(box_state)) # # placed_parts.append(self.part) # return -box_deviation, False # gripper_pos = self.robot.gripper.get_world_pose()[0] # self.step += 1 # if self.step < LEARNING_STARTS: # return 0, False # done = False # reward= 0 # part_pos, part_rot = self.part.get_world_pose() # dest_box_pos = self.part.get_world_pose()[0] # part_to_dest = np.linalg.norm(dest_box_pos - part_pos) * 100 # In cm # print('PART TO BOX:', part_to_dest) # if 10 < part_to_dest: # reward -= part_to_dest # else: # Part reached box # # reward += (100 + self.max_steps - self.step) * MAX_STEP_PUNISHMENT # ideal_part = _get_closest_part(part_pos) # pos_error = np.linalg.norm(part_pos - ideal_part[0]) * 100 # rot_error = ((part_rot - ideal_part[1])**2).mean() # print('PART REACHED BOX:', part_to_dest) # # print('THIS MUST BE TRUE ABOUT THE PUNISHMENT:', pos_error + rot_error, '<', MAX_STEP_PUNISHMENT) # CHeck the average punishment of stage 0 to see how much it tapers off # reward -= pos_error + rot_error # # if not done and (part_pos[2] < 0.1 or self.max_steps <= self.step): # Part was dropped or time ran out means end # # reward -= (100 + self.max_steps - self.step) * MAX_STEP_PUNISHMENT # # done = True # if done: # print('END REWARD TASK', self.name, ':', reward) # return reward, done def is_done(self): self.reset_buf = self.progress_buf >= 50 def _is_flipped(q1): """ Bestimmt, ob die Rotation von q0 zu q1 ein "Umfallen" darstellt, basierend auf einem Winkel größer als 60 Grad zwischen der ursprünglichen z-Achse und ihrer Rotation. :param q0: Ursprüngliches Quaternion. :param q1: Neues Quaternion. :return: True, wenn der Winkel größer als 60 Grad ist, sonst False. """ q0 = torch.tensor([0, 1, 0, 0]) # Initialer Vektor, parallel zur z-Achse v0 = torch.tensor([0, 0, 1]) # Konvertiere Quaternions in Rotation-Objekte rotation0 = R.from_quat(q0) rotation1 = R.from_quat(q1) # Berechne die relative Rotation von q0 zu q1 q_rel = rotation1 * rotation0.inv() # Berechne den rotierten Vektor v1 v1 = q_rel.apply(v0) # Berechne den Winkel zwischen v0 und v1 cos_theta = np.dot(v0, v1) / (np.linalg.norm(v0) * np.linalg.norm(v1)) angle = np.arccos(np.clip(cos_theta, -1.0, 1.0)) * 180 / np.pi # Prüfe, ob der Winkel größer als 60 Grad ist return angle > 60
21,994
Python
41.298077
185
0.581204
gitLSW/robot-cloud/remnants/train_dreamer.py
import os import dreamerv3 from dreamerv3 import embodied from embodied.envs import from_gym from gym_env import DreamerEnv MODEL_NAME = "Dreamer" MAX_STEPS_PER_EPISODE = 300 SIM_STEP_FREQ_HZ = 60 # See configs.yaml for all options. config = embodied.Config(dreamerv3.configs['defaults']) config = config.update(dreamerv3.configs['small']) # config = config.update(dreamerv3.configs['medium']) # config = config.update(dreamerv3.configs['large']) #config = config.update(dreamerv3.configs['xlarge']) config = config.update({ 'logdir': './progress/' + MODEL_NAME, 'run.train_ratio': 64, 'run.log_every': 30, # Seconds 'batch_size': 8, 'batch_length': 16, 'jax.prealloc': True, 'jax.debug': True, 'encoder.mlp_keys': 'vector', 'decoder.mlp_keys': 'vector', 'encoder.cnn_keys': 'image', 'decoder.cnn_keys': 'image', 'run.eval_every' : 10000, #'jax.platform': 'cpu', }) config = embodied.Flags(config).parse() logdir = embodied.Path(config.logdir) step = embodied.Counter() logger = embodied.Logger(step, [ embodied.logger.TerminalOutput(), # embodied.logger.TerminalOutput(config.filter), embodied.logger.JSONLOutput(logdir, 'metrics.jsonl'), embodied.logger.TensorBoardOutput(logdir), embodied.logger.WandBOutput(r".*", 'qwertyasd', 'robot-cloud', MODEL_NAME, config), # embodied.logger.MLFlowOutput(logdir.name), ]) # Create Isaac environment and open Sim Window # env = GymEnv(headless=False, experience=f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.kit') # https://docs.omniverse.nvidia.com/isaacsim/latest/installation/manual_livestream_clients.html env = DreamerEnv(headless=False, experience=f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.kit', enable_livestream=False) from pack_task import PackTask # Cannot be imported before Sim has started task = PackTask(name="Pack", max_steps=MAX_STEPS_PER_EPISODE, sim_s_step_freq=SIM_STEP_FREQ_HZ) env.set_task(task, backend="numpy", rendering_dt=1 / SIM_STEP_FREQ_HZ) # env.reset() env = from_gym.FromGym(env, obs_key='image') env = dreamerv3.wrap_env(env, config) env = embodied.BatchEnv([env], parallel=False) print('Starting Training...') # env.act_space.discrete = True # act_space = { 'action': env.act_space } agent = dreamerv3.Agent(env.obs_space, env.act_space, step, config) replay = embodied.replay.Uniform(config.batch_length, config.replay_size, logdir / 'replay') args = embodied.Config(**config.run, logdir=config.logdir, batch_steps=config.batch_size * config.batch_length) print(args) embodied.run.train(agent, env, replay, logger, args) print('Finished Traing') # env.close()
2,632
Python
36.084507
123
0.718465
gitLSW/robot-cloud/remnants/ur16e.py
from typing import Optional import os from omni.isaac.core.robots.robot import Robot from omni.isaac.manipulators.grippers.surface_gripper import SurfaceGripper from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.core.utils.prims import get_prim_at_path from omni.isaac.core.prims.rigid_prim import RigidPrim from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.extensions import enable_extension, get_extension_path_from_name enable_extension('omni.isaac.motion_gneration') from omni.isaac.motion_generation import LulaKinematicsSolver, ArticulationKinematicsSolver from omni.isaac.motion_generation import interface_config_loader class UR16e(Robot): """[summary] Args: prim_path (str): [description] name (str, optional): [description]. Defaults to "ur10_robot". usd_path (Optional[str], optional): [description]. Defaults to None. position (Optional[np.ndarray], optional): [description]. Defaults to None. orientation (Optional[np.ndarray], optional): [description]. Defaults to None. end_effector_prim_name (Optional[str], optional): [description]. Defaults to None. attach_gripper (bool, optional): [description]. Defaults to False. gripper_usd (Optional[str], optional): [description]. Defaults to "default". Raises: NotImplementedError: [description] """ def __init__( self, prim_path: str, name: str = "ur10_robot", usd_path: Optional[str] = '/assets/ur16e.usd', position: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, gripper_usd: Optional[str] = "/assets/long_gripper.usd", ) -> None: prim = get_prim_at_path(prim_path) self._end_effector = None self._gripper = None # assets_root_path = get_assets_root_path() # usd_path = assets_root_path() + "/Isaac/Robots/UniversalRobots/ur16e/ur16e.usd" add_reference_to_stage(usd_path=usd_path, prim_path=prim_path) self._end_effector_prim_path = prim_path + "/Gripper" super().__init__(prim_path=prim_path, name=name, position=position, orientation=orientation, articulation_controller=None) # gripper_usd = assets_root_path + "/Isaac/Robots/UR10/Props/long_gripper.usd" add_reference_to_stage(usd_path=gripper_usd, prim_path=self._end_effector_prim_path) self._gripper = SurfaceGripper( end_effector_prim_path=self._end_effector_prim_path, translate=0.1611, direction="x" ) mg_extension_path = get_extension_path_from_name("omni.isaac.motion_generation") kinematics_config_dir = os.path.join(mg_extension_path, "motion_policy_configs") self._kinematics_solver = LulaKinematicsSolver( robot_description_path = kinematics_config_dir + "/universal_robots/ur16e/rmpflow/ur16e_robot_description.yaml", urdf_path = kinematics_config_dir + "/universal_robots/ur16e/ur16e.urdf" ) # Kinematics for supported robots can be loaded with a simpler equivalent print("Supported Robots with a Lula Kinematics Config:", interface_config_loader.get_supported_robots_with_lula_kinematics()) # kinematics_config = interface_config_loader.load_supported_lula_kinematics_solver_config("Franka") # self._kinematics_solver = LulaKinematicsSolver(**kinematics_config) print("Valid frame names at which to compute kinematics:", self._kinematics_solver.get_all_frame_names()) end_effector_name = "gripper" self._articulation_kinematics_solver = ArticulationKinematicsSolver(self._articulation,self._kinematics_solver, end_effector_name) @property def gripper(self) -> SurfaceGripper: return self._gripper def initialize(self, physics_sim_view=None) -> None: super().initialize(physics_sim_view) self._gripper.initialize(physics_sim_view=physics_sim_view, articulation_num_dofs=self.num_dof) self.disable_gravity() # self._end_effector = RigidPrim(prim_path=self._end_effector_prim_path, name=self.name + "_end_effector") # self._end_effector.initialize(physics_sim_view) return def post_reset(self) -> None: Robot.post_reset(self)
4,379
Python
46.096774
138
0.692396
gitLSW/robot-cloud/remnants/gym_env.py
from omni.isaac.gym.vec_env import VecEnvBase class GymEnv(VecEnvBase): """This class provides a base interface for connecting RL policies with task implementations. APIs provided in this interface follow the interface in gym.Env. This class also provides utilities for initializing simulation apps, creating the World, and registering a task. """ def __init__( self, headless: bool, sim_device: int = 0, enable_livestream: bool = False, enable_viewport: bool = False, launch_simulation_app: bool = True, experience: str = None, ) -> None: """Initializes RL and task parameters. Args: headless (bool): Whether to run training headless. sim_device (int): GPU device ID for running physics simulation. Defaults to 0. enable_livestream (bool): Whether to enable running with livestream. enable_viewport (bool): Whether to enable rendering in headless mode. launch_simulation_app (bool): Whether to launch the simulation app (required if launching from python). Defaults to True. experience (str): Path to the desired kit app file. Defaults to None, which will automatically choose the most suitable app file. """ super().__init__(headless, sim_device, enable_livestream, enable_viewport, launch_simulation_app, experience) def is_done(self) -> bool: """Returns True of the task is done. Raises: NotImplementedError: [description] """ raise False def step(self, actions): """Basic implementation for stepping simulation. Can be overriden by inherited Env classes to satisfy requirements of specific RL libraries. This method passes actions to task for processing, steps simulation, and computes observations, rewards, and resets. Args: actions (Union[numpy.ndarray, torch.Tensor]): Actions buffer from policy. Returns: observations(Union[numpy.ndarray, torch.Tensor]): Buffer of observation data. rewards(Union[numpy.ndarray, torch.Tensor]): Buffer of rewards data. dones(Union[numpy.ndarray, torch.Tensor]): Buffer of resets/dones data. info(dict): Dictionary of extras data. """ if not self._world.is_playing(): self.close() self._task.pre_physics_step(actions) self._world.step(render=self._render) self.sim_frame_count += 1 # if not self._world.is_playing(): # self.close() observations = self._task.get_observations() rewards, done = self._task.calculate_metrics() truncated = done * 0 info = {} return observations, rewards, done, truncated, info class DreamerEnv(GymEnv): def __init__( self, headless: bool, sim_device: int = 0, enable_livestream: bool = False, enable_viewport: bool = False, launch_simulation_app: bool = True, experience: str = None, ) -> None: super().__init__(headless, sim_device, enable_livestream, enable_viewport, launch_simulation_app, experience) def step(self, actions): observations, rewards, done, truncated, info = super().step(actions) return observations, rewards, done, info def reset(self, seed=None, options=None): observations, info = super().reset(seed, options) return observations
3,536
Python
36.231579
141
0.632353
gitLSW/robot-cloud/remnants/run_sim.py
import os from omni.isaac.kit import SimulationApp sim = SimulationApp({"headless": False}, experience=f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.kit') from omni.isaac.core.world import World world = World(stage_units_in_meters=1.0, backend='numpy') world.scene.add_default_ground_plane() from pack_task import PackTask # Cannot be imported before Sim has started sim_s_step_freq = 60 task = PackTask(name="Pack", max_steps=100000, sim_s_step_freq=sim_s_step_freq) world.add_task(task) world.reset() while True: world.step(render=True)
550
Python
29.611109
106
0.750909
gitLSW/robot-cloud/remnants/skrl-tutorial/test_quat.py
from pyquaternion import Quaternion from scipy.spatial.transform import Rotation as R import numpy as np for _ in range(3000): q1 = Quaternion.random().unit q2 = Quaternion.random().unit q_diff = q1 * q2.inverse q_diff_e = R.from_quat(q_diff.elements).as_euler('xyz', degrees=True) e1 = R.from_quat(q1.elements).as_euler('xyz', degrees=True) e2 = R.from_quat(q2.elements).as_euler('xyz', degrees=True) e_diff = e1 - e2 print(q_diff_e == e_diff, q_diff_e, e_diff)
500
Python
26.833332
73
0.664
gitLSW/robot-cloud/remnants/parallel-training/parallel_ppo.py
import os import numpy as np from gym_env_mt import GymEnvMT from stable_baselines3 import PPO, DDPG # from stable_baselines3.common.noise import NormalActionNoise, OrnsteinUhlenbeckActionNoise from stable_baselines3.common.vec_env import DummyVecEnv, subproc_vec_env import wandb from wandb.integration.sb3 import WandbCallback MAX_STEPS_PER_EPISODE = 300 SIM_STEP_FREQ_HZ = 60 # Create Isaac environment and open Sim Window env = GymEnvMT(max_steps = MAX_STEPS_PER_EPISODE, sim_s_step_freq = SIM_STEP_FREQ_HZ, headless=False, experience=f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.kit') spacing = 5 offsets = [] tasks_per_side_1 = 1 tasks_per_side_2 = 1 NUM_ENVS = tasks_per_side_1 * tasks_per_side_2 for i in range(tasks_per_side_1): for j in range(tasks_per_side_2): offsets.append([i * spacing, j * spacing, 0]) task_envs = env.init_tasks(offsets, backend="numpy") def make_env(env): return lambda: env env = DummyVecEnv([make_env(task_env) for task_env in task_envs]) # The noise objects for DDPG # n_actions = env.action_space.shape[-1] # action_noise = NormalActionNoise(mean=np.zeros(n_actions), sigma=0.1 * np.ones(n_actions)) ddpg_config = { # 'learning_starts': 0, # 'action_noise': action_noise, 'learning_rate': 0.001, # 'tau': 0.005, # 'gamma': 0.99, # 'learning_starts': 0, # 'train_freq': MAX_STEPS_PER_EPISODE * NUM_ENVS, # How many steps until models get updated 'batch_size': 256, # 'buffer_size': MAX_STEPS_PER_EPISODE * NUM_ENVS, 'verbose': 1 } name = 'ppo-pack' run = wandb.init( project=name, config=ddpg_config, sync_tensorboard=True, # auto-upload sb3's tensorboard metrics # monitor_gym=True, # auto-upload the videos of agents playing the game # save_code=True, # optional ) ddpg_config['tensorboard_log'] = f"./progress/runs/{run.id}" model = None try: model = PPO.load(f"progress/{name}", env, print_system_info=True, custom_objects=ddpg_config) # model.set_parameters(params) except FileNotFoundError: print('Failed to load model') finally: model = PPO("MultiInputPolicy", env, **ddpg_config) while (True): model.learn(total_timesteps=MAX_STEPS_PER_EPISODE * 2, log_interval=NUM_ENVS, tb_log_name='DDPG', callback=WandbCallback( model_save_path=f"models/{run.id}", verbose=2, )) print('Saving model') model.save("progress/ddpg") run.finish() print('Finished Traing') # env.close()
2,506
Python
28.845238
101
0.678771
gitLSW/robot-cloud/remnants/parallel-training/pack_task_table.py
import os import math import random import numpy as np from pxr import Gf, UsdLux, Sdf from gymnasium import spaces from omni.isaac.core.utils.extensions import enable_extension # enable_extension("omni.importer.urdf") enable_extension("omni.isaac.universal_robots") enable_extension("omni.isaac.sensor") # from omni.importer.urdf import _urdf from omni.isaac.sensor import Camera from omni.isaac.universal_robots.ur10 import UR10 # from omni.isaac.universal_robots.controllers.pick_place_controller import PickPlaceController from omni.isaac.core.prims import XFormPrim, RigidPrim, GeometryPrim from omni.isaac.core.materials.physics_material import PhysicsMaterial from omni.isaac.core.utils.prims import create_prim, get_prim_at_path from omni.isaac.core.tasks.base_task import BaseTask from omni.isaac.gym.tasks.rl_task import RLTaskInterface from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.core.utils.viewports import set_camera_view from omni.kit.viewport.utility import get_active_viewport import omni.isaac.core.objects as objs import omni.isaac.core.utils.numpy.rotations as rot_utils from omni.isaac.core.utils.rotations import lookat_to_quatf, gf_quat_to_np_array from omni.physx.scripts.utils import setRigidBody, setStaticCollider, setCollider, addCollisionGroup # MESH_APPROXIMATIONS = { # "none": PhysxSchema.PhysxTriangleMeshCollisionAPI, # "convexHull": PhysxSchema.PhysxConvexHullCollisionAPI, # "convexDecomposition": PhysxSchema.PhysxConvexDecompositionCollisionAPI, # "meshSimplification": PhysxSchema.PhysxTriangleMeshSimplificationCollisionAPI, # "convexMeshSimplification": PhysxSchema.PhysxTriangleMeshSimplificationCollisionAPI, # "boundingCube": None, # "boundingSphere": None, # "sphereFill": PhysxSchema.PhysxSphereFillCollisionAPI, # "sdf": PhysxSchema.PhysxSDFMeshCollisionAPI, # } LEARNING_STARTS = 10 ENV_PATH = "World/Env" ROBOT_PATH = 'World/UR10e' ROBOT_POS = np.array([0.0, 0.0, 0.0]) LIGHT_PATH = 'World/Light' LIGHT_OFFSET = np.array([0, 0, 2]) # 5.45, 3, 0 START_TABLE_PATH = "World/StartTable" START_TABLE_POS = np.array([0.36, 0.8, 0]) START_TABLE_HEIGHT = 0.6 START_TABLE_CENTER = START_TABLE_POS + np.array([0, 0, START_TABLE_HEIGHT]) DEST_BOX_PATH = "World/DestinationBox" DEST_BOX_POS = np.array([0, -0.65, 0]) PARTS_PATH = 'World/Parts' PARTS_SOURCE = START_TABLE_CENTER + np.array([0, 0, 0.05]) # NUM_PARTS = 5 IMG_RESOLUTION = (128, 128) CAMERA_PATH = 'World/Camera' CAM_TARGET_OFFSET = (2.5, 2) # Distance and Height CAM_MEAN_ANGLE = math.pi # Box=math.pi / 2, Table=3 * math.pi / 2 # CAMERA_POS_START = np.array([-2, 2, 2.5]) # CAMERA_POS_DEST = np.array([2, -2, 2.5]) MAX_STEP_PUNISHMENT = 300 IDEAL_PACKAGING = [([-0.06, -0.19984, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.14044, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.07827, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.01597, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, 0.04664, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, 0.10918, 0.0803], [0.072, 0.99, 0, 0])] # Seed Env or DDPG will always be the same !! class PackTask(BaseTask): """ This class sets up a scene and calls a RL Policy, then evaluates the behaivior with rewards Args: offset (Optional[np.ndarray], optional): offset applied to all assets of the task. sim_s_step_freq (int): The amount of simulation steps within a SIMULATED second. """ def __init__(self, name, max_steps, offset=None, sim_s_step_freq: int = 60) -> None: self._env_path = f"/{name}/{ENV_PATH}" self._light_path = {"/{name}/{LIGHT_PATH}"} self._robot_path = f"/{name}/{ROBOT_PATH}" self._start_table_path = f"/{name}/{START_TABLE_PATH}" self._dest_box_path = f"/{name}/{DEST_BOX_PATH}" self._parts_path = f"/{name}/{PARTS_PATH}" self._camera_path = f"/{name}/{CAMERA_PATH}" # self._num_observations = 1 # self._num_actions = 1 self._device = "cpu" self.num_envs = 1 # Robot turning ange of max speed is 191deg/s self.__joint_rot_max = (191.0 * math.pi / 180) / sim_s_step_freq self.max_steps = max_steps self.observation_space = spaces.Dict({ # The NN will see the Robot via a single video feed that can run from one of two camera positions # The NN will receive this feed in rgb, depth and image segmented to highlight objects of interest 'image': spaces.Box(low=0, high=1, shape=(*IMG_RESOLUTION, 7)), # The Robot also receives the shape rotations of all 6 joints and the gripper state # the gripper state is -1 when open and 1 when closed 'vector': spaces.Box(low=-1, high=1, shape=(7,)), }) # The NN outputs the change in rotation for each joint as a fraction of the max rot speed per timestep (=__joint_rot_max) self.action_space = spaces.Box(low=-1, high=1, shape=(7,), dtype=float) # trigger __init__ of parent class BaseTask.__init__(self, name=name, offset=offset) def set_up_scene(self, scene) -> None: print('SETUP TASK', self.name) super().set_up_scene(scene) local_assets = os.getcwd() + '/assets' # This is the URL from which the Assets are downloaded # Make sure you started and connected to your localhost Nucleus Server via Omniverse !!! # assets_root_path = get_assets_root_path() # _ = XFormPrim(prim_path=self._env_path, position=-np.array([5, 4.5, 0])) # warehouse_path = assets_root_path + "/Isaac/Environments/Simple_Warehouse/warehouse_multiple_shelves.usd" # add_reference_to_stage(warehouse_path, self._env_path) self.light = create_prim( '/World/Light_' + self.name, "SphereLight", position=ROBOT_POS + LIGHT_OFFSET + self._offset, attributes={ "inputs:radius": 0.01, "inputs:intensity": 3e7, "inputs:color": (1.0, 1.0, 1.0) } ) # table_path = assets_root_path + "/Isaac/Environments/Simple_Room/Props/table_low.usd" table_path = local_assets + '/table_low.usd' self.table = XFormPrim(prim_path=self._start_table_path, position=START_TABLE_POS, scale=[0.5, START_TABLE_HEIGHT, 0.4]) add_reference_to_stage(table_path, self._start_table_path) setRigidBody(self.table.prim, approximationShape='convexHull', kinematic=True) # Kinematic True means immovable # self.table = RigidPrim(rim_path=self._start_table_path, name='TABLE') self._task_objects[self._start_table_path] = self.table # box_path = assets_root_path + "/Isaac/Environments/Simple_Warehouse/Props/SM_CardBoxA_02.usd" box_path = local_assets + '/SM_CardBoxA_02.usd' self.box = XFormPrim(prim_path=self._dest_box_path, position=DEST_BOX_POS, scale=[1, 1, 0.4]) add_reference_to_stage(box_path, self._dest_box_path) setRigidBody(self.box.prim, approximationShape='convexDecomposition', kinematic=True) # Kinematic True means immovable self._task_objects[self._dest_box_path] = self.box # The UR10e has 6 joints, each with a maximum: # turning angle of -360 deg to +360 deg # turning ange of max speed is 191deg/s self.robot = UR10(prim_path=self._robot_path, name='UR16e', position=ROBOT_POS, attach_gripper=True) self._task_objects[self._robot_path] = self.robot # self.robot.set_joints_default_state(positions=torch.tensor([-math.pi / 2, -math.pi / 2, -math.pi / 2, -math.pi / 2, math.pi / 2, 0])) i = 0 part_usd_path = local_assets + '/draexlmaier_part.usd' part_path = f'{self._parts_path}/Part_{i}' self.part = XFormPrim(prim_path=part_path, position=PARTS_SOURCE, orientation=[0, 1, 0, 0]) add_reference_to_stage(part_usd_path, part_path) setRigidBody(self.part.prim, approximationShape='convexDecomposition', kinematic=False) # Kinematic True means immovable self._task_objects[part_path] = self.part cam_start_pos = self.__get_cam_pos(ROBOT_POS, *CAM_TARGET_OFFSET, mean_angle=CAM_MEAN_ANGLE) self._camera = Camera( prim_path=self._camera_path, frequency=20, resolution=IMG_RESOLUTION ) self._camera.set_focal_length(2.0) self.__move_camera(position=cam_start_pos, target=ROBOT_POS) self._task_objects[self._camera_path] = self._camera # viewport = get_active_viewport() # viewport.set_active_camera(self._camera_path) # set_camera_view(eye=ROBOT_POS + np.array([1.5, 6, 1.5]), target=ROBOT_POS, camera_prim_path="/OmniverseKit_Persp") self._move_task_objects_to_their_frame() def reset(self): # super().cleanup() # if not self.robot.handles_initialized(): self.robot.initialize() self._camera.initialize() self._camera.add_distance_to_image_plane_to_frame() # depth cam self._camera.add_instance_id_segmentation_to_frame() # simulated segmentation NN robot_pos = ROBOT_POS + self._offset cam_start_pos = self.__get_cam_pos(robot_pos, *CAM_TARGET_OFFSET, mean_angle=CAM_MEAN_ANGLE) self.__move_camera(position=cam_start_pos, target=robot_pos) self.step = 0 self.stage = 0 # self.part.set_world_pose(PARTS_SOURCE + self._offset) default_pose = np.array([-math.pi / 2, -math.pi / 2, -math.pi / 2, -math.pi / 2, math.pi / 2, 0, -1]) self.robot.gripper.open() self.robot.set_joint_positions(positions=default_pose[0:6]) return { 'image': np.zeros((*IMG_RESOLUTION, 7)), 'vector': default_pose } def __move_camera(self, position, target): # USD Frame flips target and position, so they have to be flipped here quat = gf_quat_to_np_array(lookat_to_quatf(camera=Gf.Vec3f(*target), target=Gf.Vec3f(*position), up=Gf.Vec3f(0, 0, 1))) self._camera.set_world_pose(position=position, orientation=quat, camera_axes='usd') def __get_cam_pos(self, center, distance, height, mean_angle = None): angle = None if mean_angle: angle = np.random.normal(mean_angle, math.sqrt(math.pi / 16)) # Normal Distribution with mean mean_angle and sd=sqrt(10deg) else: angle = random.random() * 2 * math.pi pos = np.array([distance, 0]) rot_matr = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]) pos = np.matmul(pos, rot_matr) pos = np.array([*pos, height]) return center + pos def get_observations(self): frame = self._camera.get_current_frame() img_rgba = frame['rgba'] # Shape: (Width, Height, 4) img_rgb = img_rgba[:, :, :3] / 255.0 # Remove alpha from rgba and scale between 0-1 img_depth = frame['distance_to_image_plane'] # Shape: (Width, Height) if img_depth is not None: img_depth = np.clip(img_depth, 0, 2) / 2.0 # Clip depth at 2m and scale between 0-1 img_depth = img_depth[:, :, np.newaxis] # img_depth = np.expand_dims(img_depth, axis=-1) else: img_depth = np.zeros((*IMG_RESOLUTION, 1)) # Segmentation img_seg_dict = frame['instance_id_segmentation'] one_hot_img_seg = img_seg = np.zeros((*IMG_RESOLUTION, 3)) if img_seg_dict: img_seg_info_dict = img_seg_dict['info']['idToLabels'] # Dict: [pixel label: prim path] img_seg = img_seg_dict['data'] # Shape: (Width, Height) # Vectorised One-Hot-Encoding for label, path in img_seg_info_dict.items(): label = int(label) mask = (img_seg == label) # creates a bool matrix of an element wise comparison if path == self._robot_path: one_hot_img_seg[:, :, 0] = mask elif path.startswith(self._parts_path): one_hot_img_seg[:, :, 1] = mask elif path == self._dest_box_path: one_hot_img_seg[:, :, 2] = mask # TODO: CHECK IF get_joint_positions ACCURATELY HANDLES ROTATIONS ABOVE 360deg AND NORMALIZE FOR MAX ROBOT ROTATION (+/-360deg) robot_state = np.append(self.robot.get_joint_positions() / 2 * math.pi, 2 * float(self.robot.gripper.is_closed()) - 1) return { 'image': np.concatenate([img_rgb, img_depth, one_hot_img_seg], axis=-1), 'vector': robot_state } def pre_physics_step(self, actions) -> None: if self.step < LEARNING_STARTS: return # Rotate Joints joint_rots = self.robot.get_joint_positions() joint_rots += np.array(actions[0:6]) * self.__joint_rot_max self.robot.set_joint_positions(positions=joint_rots) # Open or close Gripper gripper = self.robot.gripper is_closed = gripper.is_closed() gripper_action = actions[6] if 0.9 < gripper_action and not is_closed: gripper.close() elif gripper_action < -0.9 and is_closed: gripper.open() # Calculate Rewards stage = 0 step = 0 def calculate_metrics(self) -> None: gripper_pos = self.robot.gripper.get_world_pose()[0] self.step += 1 if self.step < LEARNING_STARTS: return 0, False done = False reward= 0 part_pos, part_rot = self.part.get_world_pose() if self.stage == 0: gripper_to_part = np.linalg.norm(part_pos - gripper_pos) * 100 # In cm reward -= gripper_to_part if START_TABLE_HEIGHT + 0.03 < part_pos[2]: # Part was picked up reward += MAX_STEP_PUNISHMENT self.stage = 1 elif self.stage == 1: dest_box_pos = self.part.get_world_pose()[0] part_to_dest = np.linalg.norm(dest_box_pos - part_pos) * 100 # In cm print('PART TO BOX:', part_to_dest) if 10 < part_to_dest: reward -= part_to_dest else: # Part reached box # reward += (100 + self.max_steps - self.step) * MAX_STEP_PUNISHMENT ideal_part = self._get_closest_part(part_pos) pos_error = np.linalg.norm(part_pos - ideal_part[0]) * 100 rot_error = ((part_rot - ideal_part[1])**2).mean() print('PART REACHED BOX:', part_to_dest) # print('THIS MUST BE TRUE ABOUT THE PUNISHMENT:', pos_error + rot_error, '<', MAX_STEP_PUNISHMENT) # CHeck the average punishment of stage 0 to see how much it tapers off reward -= pos_error + rot_error done = True # End successfully if all parts are in the Box # if self.part # self.reset() # done = True if not done and (part_pos[2] < 0.1 or self.max_steps <= self.step): # Part was dropped or time ran out means end reward -= (100 + self.max_steps - self.step) * MAX_STEP_PUNISHMENT # self.reset() done = True if done: print('END REWARD TASK', self.name, ':', reward) return reward, done def _get_closest_part(self, pos): pos -= self.box.get_world_pose()[0] closest_part = None min_dist = 10000000 for part in IDEAL_PACKAGING: dist = np.linalg.norm(part[0] - pos) if dist < min_dist: closest_part = part min_dist = dist return closest_part
16,079
Python
41.88
187
0.603334
gitLSW/robot-cloud/remnants/parallel-training/train_dreamer_mt.py
import os import dreamerv3 from dreamerv3 import embodied from embodied.envs import from_gym from gym_env_mt import GymEnvMT from functools import partial as bind name = "test" MAX_STEPS_PER_EPISODE = 300 # See configs.yaml for all options. config = embodied.Config(dreamerv3.configs['defaults']) config = config.update(dreamerv3.configs['small']) # config = config.update(dreamerv3.configs['medium']) # config = config.update(dreamerv3.configs['large']) #config = config.update(dreamerv3.configs['xlarge']) config = config.update({ 'logdir': './logdir/' + name, 'run.train_ratio': 64, 'run.log_every': 30, # Seconds 'batch_size': 8, 'batch_length': 16, 'jax.prealloc': False, 'encoder.mlp_keys': 'vector', 'decoder.mlp_keys': 'vector', 'encoder.cnn_keys': 'image', 'decoder.cnn_keys': 'image', 'run.eval_every' : 10000, #'jax.platform': 'cpu', }) config = embodied.Flags(config).parse() logdir = embodied.Path(config.logdir) step = embodied.Counter() logger = embodied.Logger(step, [ embodied.logger.TerminalOutput(), embodied.logger.JSONLOutput(logdir, 'metrics.jsonl'), embodied.logger.TensorBoardOutput(logdir), #embodied.logger.WandBOutput(r".*",logdir, config), # WandBOutputMy(r".*",logdir, config, name), # embodied.logger.MLFlowOutput(logdir.name), ]) # Create Isaac environment and open Sim Window env = GymEnvMT(max_steps = MAX_STEPS_PER_EPISODE, sim_s_step_freq = 60, headless=False, experience=f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.kit') spacing = 5 offsets = [[spacing, spacing, 0], [spacing, 0, 0], [spacing, -spacing, 0], [0, spacing, 0], [0, 0, 0], [0, -spacing, 0], [-spacing, spacing, 0], [-spacing, 0, 0], [-spacing, -spacing, 0]] task_envs = env.init_tasks(offsets, backend="numpy") # env.reset() def make_env(task_env): task_env = from_gym.FromGym(task_env, obs_key='image') task_env = dreamerv3.wrap_env(task_env, config) return task_env ctors = [] for task_env in task_envs: ctor = lambda : make_env(task_env) ctor = bind(embodied.Parallel, ctor, config.envs.parallel) ctors.append(ctor) task_envs = [ctor() for ctor in ctors] env = embodied.BatchEnv(task_envs, parallel=True) print('Starting Training...') # env.act_space.discrete = True # act_space = { 'action': env.act_space } agent = dreamerv3.Agent(env.obs_space, env.act_space, step, config) replay = embodied.replay.Uniform(config.batch_length, config.replay_size, logdir / 'replay') args = embodied.Config(**config.run, logdir=config.logdir, batch_steps=config.batch_size * config.batch_length) print(args) embodied.run.train(agent, env, replay, logger, args) print('Finished Traing') # env.close()
2,766
Python
33.160493
111
0.677151
gitLSW/robot-cloud/remnants/parallel-training/parallel_ddpg.py
import os import numpy as np from gym_env_mt import GymEnvMT from stable_baselines3 import DDPG from stable_baselines3.common.noise import NormalActionNoise, OrnsteinUhlenbeckActionNoise from stable_baselines3.common.vec_env import DummyVecEnv, subproc_vec_env import wandb from wandb.integration.sb3 import WandbCallback MAX_STEPS_PER_EPISODE = 300 SIM_STEP_FREQ_HZ = 60 # Create Isaac environment and open Sim Window env = GymEnvMT(max_steps = MAX_STEPS_PER_EPISODE, sim_s_step_freq = SIM_STEP_FREQ_HZ, headless=False, experience=f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.kit') spacing = 5 offsets = [] tasks_per_side_1 = 50 tasks_per_side_2 = 50 # USE GRIP CLONER INSTEAD !!! # CHECK THSI FROM OmniIsaacGymEnvs RLTask: # self._cloner = GridCloner(spacing=self._env_spacing) # self._cloner.define_base_env(self.default_base_env_path) # stage = omni.usd.get_context().get_stage() # UsdGeom.Xform.Define(stage, self.default_zero_env_path) # if self._task_cfg["sim"].get("add_ground_plane", True): # self._ground_plane_path = "/World/defaultGroundPlane" # collision_filter_global_paths.append(self._ground_plane_path) # scene.add_default_ground_plane(prim_path=self._ground_plane_path) # prim_paths = self._cloner.generate_paths("/World/envs/env", self._num_envs) # self._env_pos = self._cloner.clone( # source_prim_path="/World/envs/env_0", prim_paths=prim_paths, replicate_physics=replicate_physics, copy_from_source=copy_from_source # ) # self._env_pos = torch.tensor(np.array(self._env_pos), device=self._device, dtype=torch.float) # if filter_collisions: # self._cloner.filter_collisions( # self._env.world.get_physics_context().prim_path, # "/World/collisions", # prim_paths, # collision_filter_global_paths, # ) from omni.isaac.cloner import GridCloner NUM_ENVS = tasks_per_side_1 * tasks_per_side_2 for i in range(tasks_per_side_1): for j in range(tasks_per_side_2): offsets.append([i * spacing, j * spacing, 0]) task_envs = env.init_tasks(offsets, backend="numpy") def make_env(env): return lambda: env env = DummyVecEnv([make_env(task_env) for task_env in task_envs]) # The noise objects for DDPG n_actions = env.action_space.shape[-1] action_noise = NormalActionNoise(mean=np.zeros(n_actions), sigma=0.1 * np.ones(n_actions)) ddpg_config = { 'learning_starts': 0, 'action_noise': action_noise, 'learning_rate': 0.001, 'tau': 0.005, 'gamma': 0.99, 'learning_starts': 0, 'train_freq': MAX_STEPS_PER_EPISODE * NUM_ENVS, # How many steps until models get updated 'batch_size': 256, 'buffer_size': MAX_STEPS_PER_EPISODE * NUM_ENVS, 'verbose': 1 } name = 'ddpg-pack' run = wandb.init( project=name, config=ddpg_config, sync_tensorboard=True, # auto-upload sb3's tensorboard metrics # monitor_gym=True, # auto-upload the videos of agents playing the game # save_code=True, # optional ) ddpg_config['tensorboard_log'] = f"./progress/runs/{run.id}" model = None try: model = DDPG.load(f"progress/{name}", env, print_system_info=True, custom_objects=ddpg_config) # model.set_parameters(params) except FileNotFoundError: print('Failed to load model') finally: model = DDPG("MultiInputPolicy", env, **ddpg_config) while (True): model.learn(total_timesteps=MAX_STEPS_PER_EPISODE * 2, log_interval=NUM_ENVS, tb_log_name='DDPG', callback=WandbCallback( model_save_path=f"models/{run.id}", verbose=2, )) print('Saving model') model.save("progress/ddpg") run.finish() print('Finished Traing') # env.close()
3,818
Python
32.79646
145
0.660555
gitLSW/robot-cloud/remnants/parallel-training/run_parallel_sim.py
import os import numpy as np from gym_env_mt import GymEnvMT MAX_STEPS_PER_EPISODE = 500 # Create Isaac environment and open Sim Window env = GymEnvMT(max_steps = MAX_STEPS_PER_EPISODE, sim_s_step_freq = 60, headless=False, experience=f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.kit') spacing = 5 offsets = [[spacing, spacing, 0], [spacing, 0, 0], [spacing, -spacing, 0], [0, spacing, 0], [0, 0, 0], [0, -spacing, 0], [-spacing, spacing, 0], [-spacing, 0, 0], [-spacing, -spacing, 0]] task_envs = env.init_tasks(offsets, backend="numpy") while True: for task in task_envs: task.step(np.ones(7))
681
Python
33.099998
80
0.60793
gitLSW/robot-cloud/remnants/parallel-training/pack_task_easy.py
import os import math import random import numpy as np from pxr import Gf, UsdLux, Sdf from gymnasium import spaces from omni.isaac.core.utils.extensions import enable_extension # enable_extension("omni.importer.urdf") enable_extension("omni.isaac.universal_robots") enable_extension("omni.isaac.sensor") # from omni.importer.urdf import _urdf from omni.isaac.sensor import Camera from omni.isaac.universal_robots.ur10 import UR10 from omni.isaac.universal_robots import KinematicsSolver # from omni.isaac.universal_robots.controllers.pick_place_controller import PickPlaceController import omni.isaac.core.utils.prims as prims_utils from omni.isaac.core.prims import XFormPrim, RigidPrim, GeometryPrim from omni.isaac.core.materials.physics_material import PhysicsMaterial from omni.isaac.core.utils.prims import create_prim, get_prim_at_path from omni.isaac.core.tasks.base_task import BaseTask from omni.isaac.gym.tasks.rl_task import RLTaskInterface from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.core.utils.viewports import set_camera_view from omni.kit.viewport.utility import get_active_viewport import omni.isaac.core.objects as objs import omni.isaac.core.utils.numpy.rotations as rot_utils from omni.isaac.core.utils.rotations import lookat_to_quatf, gf_quat_to_np_array from omni.physx.scripts.utils import setRigidBody, setStaticCollider, setCollider, addCollisionGroup from scipy.spatial.transform import Rotation as R from pyquaternion import Quaternion # MESH_APPROXIMATIONS = { # "none": PhysxSchema.PhysxTriangleMeshCollisionAPI, # "convexHull": PhysxSchema.PhysxConvexHullCollisionAPI, # "convexDecomposition": PhysxSchema.PhysxConvexDecompositionCollisionAPI, # "meshSimplification": PhysxSchema.PhysxTriangleMeshSimplificationCollisionAPI, # "convexMeshSimplification": PhysxSchema.PhysxTriangleMeshSimplificationCollisionAPI, # "boundingCube": None, # "boundingSphere": None, # "sphereFill": PhysxSchema.PhysxSphereFillCollisionAPI, # "sdf": PhysxSchema.PhysxSDFMeshCollisionAPI, # } LEARNING_STARTS = 10 ENV_PATH = "World/Env" FALLEN_PART_THRESHOLD = 0.2 ROBOT_PATH = 'World/UR10e' ROBOT_POS = np.array([0.0, 0.0, FALLEN_PART_THRESHOLD]) LIGHT_PATH = 'World/Light' LIGHT_OFFSET = np.array([0, 0, 2]) DEST_BOX_PATH = "World/DestinationBox" DEST_BOX_POS = np.array([0, -0.65, FALLEN_PART_THRESHOLD]) PART_PATH = 'World/Part' PART_SOURCE = DEST_BOX_POS + np.array([0, 0, 1.4]) # NUM_PARTS = 5 PART_PILLAR_PATH = "World/Pillar" MAX_STEP_PUNISHMENT = 300 IDEAL_PACKAGING = [([-0.06, -0.19984, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.14044, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.07827, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, -0.01597, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, 0.04664, 0.0803], [0.072, 0.99, 0, 0]), ([-0.06, 0.10918, 0.0803], [0.072, 0.99, 0, 0])] NUMBER_PARTS = len(IDEAL_PACKAGING) # Seed Env or DDPG will always be the same !! class PackTask(BaseTask): kinematics_solver = None """ This class sets up a scene and calls a RL Policy, then evaluates the behaivior with rewards Args: offset (Optional[np.ndarray], optional): offset applied to all assets of the task. sim_s_step_freq (int): The amount of simulation steps within a SIMULATED second. """ def __init__(self, name, max_steps, offset=None, sim_s_step_freq: int = 60) -> None: self._env_path = f"/{name}/{ENV_PATH}" self._light_path = {"/{name}/{LIGHT_PATH}"} self._robot_path = f"/{name}/{ROBOT_PATH}" self._dest_box_path = f"/{name}/{DEST_BOX_PATH}" self._part_path = f"/{name}/{PART_PATH}" self._pillar_path = f"/{name}/{PART_PILLAR_PATH}" # self._num_observations = 1 # self._num_actions = 1 self._device = "cpu" self.num_envs = 1 # Robot turning ange of max speed is 191deg/s self.__joint_rot_max = (191.0 * math.pi / 180) / sim_s_step_freq self.max_steps = max_steps self.observation_space = spaces.Dict({ 'gripper_closed': spaces.Discrete(2), # 'forces': spaces.Box(low=-1, high=1, shape=(8, 6)), # Forces on the Joints 'box_state': spaces.Box(low=-3, high=3, shape=(NUMBER_PARTS, 2)), # Pos and Rot Distance of each part currently placed in Box compared to currently gripped part 'part_state': spaces.Box(low=-3, high=3, shape=(6,)) }) # End Effector Pose self.action_space = spaces.Box(low=-1, high=1, shape=(7,), dtype=float) # Delta Gripper Pose & gripper open / close # trigger __init__ of parent class BaseTask.__init__(self, name=name, offset=offset) def set_up_scene(self, scene) -> None: print('SETUP TASK', self.name) super().set_up_scene(scene) local_assets = os.getcwd() + '/assets' # This is the URL from which the Assets are downloaded # Make sure you started and connected to your localhost Nucleus Server via Omniverse !!! # assets_root_path = get_assets_root_path() # _ = XFormPrim(prim_path=self._env_path, position=-np.array([5, 4.5, 0])) # warehouse_path = assets_root_path + "/Isaac/Environments/Simple_Warehouse/warehouse_multiple_shelves.usd" # add_reference_to_stage(warehouse_path, self._env_path) # self.light = create_prim( # '/World/Light_' + self.name, # "SphereLight", # position=ROBOT_POS + LIGHT_OFFSET + self._offset, # attributes={ # "inputs:radius": 0.01, # "inputs:intensity": 3e6, # "inputs:color": (1.0, 1.0, 1.0) # } # ) # box_path = assets_root_path + "/Isaac/Environments/Simple_Warehouse/Props/SM_CardBoxA_02.usd" box_path = local_assets + '/SM_CardBoxA_02.usd' self.box = XFormPrim(prim_path=self._dest_box_path, position=DEST_BOX_POS, scale=[1, 1, 0.4]) add_reference_to_stage(box_path, self._dest_box_path) setRigidBody(self.box.prim, approximationShape='convexDecomposition', kinematic=True) # Kinematic True means immovable self._task_objects[self._dest_box_path] = self.box # The UR10e has 6 joints, each with a maximum: # turning angle of -360 deg to +360 deg # turning ange of max speed is 191deg/s self.robot = UR10(prim_path=self._robot_path, name='UR10', position=ROBOT_POS, attach_gripper=True) self._task_objects[self._robot_path] = self.robot # self.robot.set_joints_default_state(positions=torch.tensor([-math.pi / 2, -math.pi / 2, -math.pi / 2, -math.pi / 2, math.pi / 2, 0])) self.part_pillar = objs.FixedCuboid( name=self._pillar_path, prim_path=self._pillar_path, position=[0, 0, -100], scale=np.array([1, 1, 1]) ) scene.add(self.part_pillar) self._task_objects[self._pillar_path] = self.part_pillar part_usd_path = local_assets + '/draexlmaier_part.usd' self.part = XFormPrim(prim_path=self._part_path, position=PART_SOURCE, orientation=[0, 1, 0, 0]) add_reference_to_stage(part_usd_path, self._part_path) setRigidBody(self.part.prim, approximationShape='convexDecomposition', kinematic=False) # Kinematic True means immovable self._task_objects[self._part_path] = self.part # set_camera_view(eye=ROBOT_POS + np.array([1.5, 6, 1.5]), target=ROBOT_POS, camera_prim_path="/OmniverseKit_Persp") self._move_task_objects_to_their_frame() def reset(self): # super().cleanup() if not self.robot.handles_initialized: self.robot.initialize() default_pose = np.array([math.pi / 2, -math.pi / 2, -math.pi / 2, -math.pi / 2, math.pi / 2, 0]) self.robot.set_joint_positions(positions=default_pose) if not self.kinematics_solver: self.kinematics_solver = KinematicsSolver(robot_articulation=self.robot, attach_gripper=True) self.step = 0 gripper_pos = np.array(self.robot.gripper.get_world_pose()[0]) - np.array([0, 0, 0.25]) self.part_pillar.set_world_pose([gripper_pos[0], gripper_pos[1], gripper_pos[2] / 2]) self.part_pillar.set_local_scale([1, 1, gripper_pos[2]]) self.part.set_world_pose(gripper_pos, [0, 1, 0, 0]) # gripper_pos, gripper_rot = self.robot.gripper.get_world_pose() # gripper_pos -= self.robot.get_world_pose()[0] # self.robot.gripper.open() # np.concatenate((gripper_pos, gripper_rot, [-1]), axis=0) box_state, current_ideal_pose = self.compute_box_state() part_pos, part_rot = self.part.get_world_pose() part_pos -= self.box.get_world_pose()[0] part_rot_euler = R.from_quat(part_rot).as_euler('xyz',degrees=False) ideal_rot_euler = R.from_quat(current_ideal_pose[1]).as_euler('xyz',degrees=False) part_pos_diff = current_ideal_pose[0] - part_pos part_rot_diff = ideal_rot_euler - part_rot_euler return { 'gripper_closed': False, 'box_state': box_state, 'part_state': np.concatenate((part_pos_diff, part_rot_diff), axis=0) } placed_parts = [] def get_observations(self): # gripper = self.robot.gripper # gripper_pos, gripper_rot = gripper.get_world_pose() # gripper_pos -= self.robot.get_world_pose()[0] # gripper_pose_kin = self.kinematics_solver.compute_end_effector_pose() # gripper_closed = 2 * float(gripper.is_closed()) - 1 # # 'gripper_state': np.concatenate((gripper_pos, gripper_rot, [gripper_closed]), axis=0), # # TODO: Was sollen wir verwenden ??!! # print('COMPARE:') # print(gripper_pose_kin) # print((gripper_pos, gripper_rot)) # forces = self.robot.get_measured_joint_forces() box_state, current_ideal_pose = self.compute_box_state() part_pos, part_rot = self.part.get_world_pose() part_pos -= self.box.get_world_pose()[0] part_rot_euler = R.from_quat(part_rot).as_euler('xyz',degrees=False) ideal_rot_euler = R.from_quat(current_ideal_pose[1]).as_euler('xyz',degrees=False) part_pos_diff = current_ideal_pose[0] - part_pos part_rot_diff = ideal_rot_euler - part_rot_euler return { 'gripper_closed': self.robot.gripper.is_closed(), 'box_state': box_state, # 'forces': forces, 'part_state': np.concatenate((part_pos_diff, part_rot_diff), axis=0) } # Returns: A 2D Array where each entry is the poses of the parts in the box def compute_box_state(self): box_state = [] ideal_selection = IDEAL_PACKAGING.copy() parts = self.placed_parts + [self.part] current_ideal_pose = None for i in range(NUMBER_PARTS): if len(parts) <= i: box_state.append([3, math.pi]) continue part = parts[i] part_pos, part_rot= part.get_world_pose() part_pos -= self.box.get_world_pose()[0] ideal_part = None min_dist = 10000000 # Find closest ideal part for sel_part in ideal_selection: dist = np.linalg.norm(sel_part[0] - part_pos) if dist < min_dist: ideal_part = sel_part min_dist = dist if i == len(parts) - 1: current_ideal_pose = ideal_part ideal_selection.remove(ideal_part) rot_dist = _shortest_rot_dist(part_rot, ideal_part[1]) box_state.append([min_dist, rot_dist]) return box_state, current_ideal_pose def pre_physics_step(self, actions) -> None: gripper = self.robot.gripper if self.step == LEARNING_STARTS - 1: gripper.close() return # elif self.step == LEARNING_STARTS: # self.part_pillar.set_world_pose([0, 0, -100]) # return elif self.step < LEARNING_STARTS: return # Rotate Joints gripper_pos = actions[0:3] gripper_rot_euler = actions[3:6] gripper_action = actions[6] gripper_rot = R.from_euler('xyz', gripper_rot_euler, degrees=False).as_quat() movement, success = self.kinematics_solver.compute_inverse_kinematics(gripper_pos, gripper_rot) # print('success', success) if success: self.robot.apply_action(movement) # is_closed = gripper.is_closed() # if 0.9 < gripper_action and not is_closed: # gripper.close() # elif gripper_action < -0.9 and is_closed: # gripper.open() # def is_done(self): # return False # Calculate Rewards step = 0 def calculate_metrics(self) -> None: self.step += 1 # Terminate: Umgefallene Teile, Gefallene Teile # Success: part_pos, part_rot = self.part.get_world_pose() any_flipped = False for part in self.placed_parts: part_rot = part.get_world_pose()[1] if _is_flipped(part_rot): any_flipped = True break if part_pos[2] < FALLEN_PART_THRESHOLD or self.max_steps < self.step or any_flipped: return -MAX_STEP_PUNISHMENT, True box_state, _ = self.compute_box_state() box_deviation = np.sum(np.square(box_state)) # placed_parts.append(self.part) return -box_deviation, False # gripper_pos = self.robot.gripper.get_world_pose()[0] # self.step += 1 # if self.step < LEARNING_STARTS: # return 0, False # done = False # reward= 0 # part_pos, part_rot = self.part.get_world_pose() # dest_box_pos = self.part.get_world_pose()[0] # part_to_dest = np.linalg.norm(dest_box_pos - part_pos) * 100 # In cm # print('PART TO BOX:', part_to_dest) # if 10 < part_to_dest: # reward -= part_to_dest # else: # Part reached box # # reward += (100 + self.max_steps - self.step) * MAX_STEP_PUNISHMENT # ideal_part = _get_closest_part(part_pos) # pos_error = np.linalg.norm(part_pos - ideal_part[0]) * 100 # rot_error = ((part_rot - ideal_part[1])**2).mean() # print('PART REACHED BOX:', part_to_dest) # # print('THIS MUST BE TRUE ABOUT THE PUNISHMENT:', pos_error + rot_error, '<', MAX_STEP_PUNISHMENT) # CHeck the average punishment of stage 0 to see how much it tapers off # reward -= pos_error + rot_error # # if not done and (part_pos[2] < 0.1 or self.max_steps <= self.step): # Part was dropped or time ran out means end # # reward -= (100 + self.max_steps - self.step) * MAX_STEP_PUNISHMENT # # done = True # if done: # print('END REWARD TASK', self.name, ':', reward) # return reward, done def _is_flipped(q1): """ Bestimmt, ob die Rotation von q0 zu q1 ein "Umfallen" darstellt, basierend auf einem Winkel größer als 60 Grad zwischen der ursprünglichen z-Achse und ihrer Rotation. :param q0: Ursprüngliches Quaternion. :param q1: Neues Quaternion. :return: True, wenn der Winkel größer als 60 Grad ist, sonst False. """ q0 = np.array([0, 1, 0, 0]) # Initialer Vektor, parallel zur z-Achse v0 = np.array([0, 0, 1]) # Konvertiere Quaternions in Rotation-Objekte rotation0 = R.from_quat(q0) rotation1 = R.from_quat(q1) # Berechne die relative Rotation von q0 zu q1 q_rel = rotation1 * rotation0.inv() # Berechne den rotierten Vektor v1 v1 = q_rel.apply(v0) # Berechne den Winkel zwischen v0 und v1 cos_theta = np.dot(v0, v1) / (np.linalg.norm(v0) * np.linalg.norm(v1)) angle = np.arccos(np.clip(cos_theta, -1.0, 1.0)) * 180 / np.pi # Prüfe, ob der Winkel größer als 60 Grad ist return angle > 60 def _shortest_rot_dist(quat_1, quat_2): part_quat = Quaternion(quat_1) ideal_quat = Quaternion(quat_2) return Quaternion.absolute_distance(part_quat, ideal_quat)
16,525
Python
38.917874
185
0.609682
gitLSW/robot-cloud/remnants/parallel-training/gym_env_mt.py
import carb import uuid from omni.isaac.gym.vec_env import VecEnvBase import gymnasium as gym class GymTaskEnv(gym.Env): """ This class provides a fascade for Gym, so Tasks can be treated like they were envirments. """ def __init__(self, task, gymEnvMT) -> None: self._env = gymEnvMT self.id = task.name self._task = task self.observation_space = task.observation_space self.action_space = task.action_space def reset(self, seed=None, options=None): return self._env.reset(self._task, seed) def step(self, actions): return self._env.step(actions, self._task) class GymEnvMT(VecEnvBase): _tasks = [] _stepped_tasks = [] """ This class handles the Interaction between the different GymTaskEnvs and Isaac """ def __init__( self, headless: bool, sim_device: int = 0, enable_livestream: bool = False, enable_viewport: bool = False, launch_simulation_app: bool = True, experience: str = None, sim_s_step_freq: float = 60.0, max_steps: int = 2000 ) -> None: """Initializes RL and task parameters. Args: headless (bool): Whether to run training headless. sim_device (int): GPU device ID for running physics simulation. Defaults to 0. enable_livestream (bool): Whether to enable running with livestream. enable_viewport (bool): Whether to enable rendering in headless mode. launch_simulation_app (bool): Whether to launch the simulation app (required if launching from python). Defaults to True. experience (str): Path to the desired kit app file. Defaults to None, which will automatically choose the most suitable app file. """ self.max_steps = max_steps self.rendering_dt = 1 / sim_s_step_freq super().__init__(headless, sim_device, enable_livestream, enable_viewport, launch_simulation_app, experience) def step(self, actions, task): """Basic implementation for stepping simulation. Can be overriden by inherited Env classes to satisfy requirements of specific RL libraries. This method passes actions to task for processing, steps simulation, and computes observations, rewards, and resets. Args: actions (Union[numpy.ndarray, torch.Tensor]): Actions buffer from policy. Returns: observations(Union[numpy.ndarray, torch.Tensor]): Buffer of observation data. rewards(Union[numpy.ndarray, torch.Tensor]): Buffer of rewards data. dones(Union[numpy.ndarray, torch.Tensor]): Buffer of resets/dones data. info(dict): Dictionary of extras data. """ if task.name in self._stepped_tasks: # Stop thread until all envs have stepped raise ValueError(f"Task {task.name} was already stepped in this timestep") self._stepped_tasks.append(task.name) task.pre_physics_step(actions) if (len(self._stepped_tasks) == len(self._tasks)): self._world.step(render=self._render) self._stepped_tasks = [] self.sim_frame_count += 1 if not self._world.is_playing(): self.close() info = {} observations = task.get_observations() rewards, done = task.calculate_metrics() truncated = done * 0 return observations, rewards, done, truncated, info def reset(self, task, seed=None): """Resets the task and updates observations. Args: seed (Optional[int]): Seed. Returns: observations(Union[numpy.ndarray, torch.Tensor]): Buffer of observation data. # info(dict): Dictionary of extras data. """ if seed is not None: print('RESET GRANDCHILD CLASS UNTESTED') seed = self.seed(seed) super(GymEnvMT.__bases__[0], self).reset(seed=seed) obs = task.reset() info = {} # Cannot advance world as resets can happen at any time # self._world.step(render=self._render) return obs, info # np.zeros(self.observation_space) tasks_initialized = False def init_tasks(self, offsets, backend="numpy", sim_params=None, init_sim=True) -> None: """Creates a World object and adds Task to World. Initializes and registers task to the environment interface. Triggers task start-up. Args: task (RLTask): The task to register to the env. backend (str): Backend to use for task. Can be "numpy" or "torch". Defaults to "numpy". sim_params (dict): Simulation parameters for physics settings. Defaults to None. init_sim (Optional[bool]): Automatically starts simulation. Defaults to True. rendering_dt (Optional[float]): dt for rendering. Defaults to 1/60s. """ if self.tasks_initialized: return [GymTaskEnv(task, self) for task in self._tasks] else: self.tasks_initialized = True from omni.isaac.core.world import World # parse device based on sim_param settings if sim_params and "sim_device" in sim_params: device = sim_params["sim_device"] else: device = "cpu" physics_device_id = carb.settings.get_settings().get_as_int("/physics/cudaDevice") gpu_id = 0 if physics_device_id < 0 else physics_device_id if sim_params and "use_gpu_pipeline" in sim_params: # GPU pipeline must use GPU simulation if sim_params["use_gpu_pipeline"]: device = "cuda:" + str(gpu_id) elif sim_params and "use_gpu" in sim_params: if sim_params["use_gpu"]: device = "cuda:" + str(gpu_id) self._world = World( stage_units_in_meters=1.0, rendering_dt=self.rendering_dt, backend=backend, sim_params=sim_params, device=device ) # self._world._current_tasks = dict() from pack_task_easy import PackTask from omni.isaac.core.utils.viewports import set_camera_view self._world.scene.add_default_ground_plane() for i, offset in enumerate(offsets): task = PackTask(f"Task_{i}", self.max_steps, offset, 1 / self.rendering_dt) self._world.add_task(task) self._tasks.append(task) self._num_envs = len(self._tasks) first_task = next(iter(self._tasks)) self.observation_space = first_task.observation_space self.action_space = first_task.action_space if sim_params and "enable_viewport" in sim_params: self._render = sim_params["enable_viewport"] if init_sim: self._world.reset() for task in self._tasks: task.reset() set_camera_view(eye=[-4, -4, 6], target=offsets[len(offsets) - 1], camera_prim_path="/OmniverseKit_Persp") return [GymTaskEnv(task, self) for task in self._tasks] def set_task(self, task, backend="numpy", sim_params=None, init_sim=True) -> None: # Not available for multi task raise NotImplementedError() def update_task_params(self): # Not available for multi task raise NotImplementedError()
7,479
Python
36.58794
141
0.603423
gitLSW/robot-cloud/remnants/dependency_fixes/dreamer_setup.py
import os import pathlib import setuptools from setuptools import find_namespace_packages path = os.getcwd() + '/temp' setuptools.setup( name='dreamerv3', version='1.5.0', description='Mastering Diverse Domains through World Models', author='Danijar Hafner', url='http://github.com/danijar/dreamerv3', long_description=pathlib.Path(path + '/README.md').read_text(), long_description_content_type='text/markdown', packages=find_namespace_packages(exclude=['example.py']), include_package_data=True, install_requires=pathlib.Path(path + '/requirements.txt').read_text().splitlines(), classifiers=[ 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering :: Artificial Intelligence', ], )
866
Python
33.679999
87
0.684758
gitLSW/robot-cloud/remnants/dependency_fixes/logger.py
import collections import concurrent.futures import datetime import json import os import re import time import numpy as np from . import path class Logger: def __init__(self, step, outputs, multiplier=1): assert outputs, 'Provide a list of logger outputs.' self.step = step self.outputs = outputs self.multiplier = multiplier self._last_step = None self._last_time = None self._metrics = [] def add(self, mapping, prefix=None): step = int(self.step) * self.multiplier for name, value in dict(mapping).items(): name = f'{prefix}/{name}' if prefix else name value = np.asarray(value) if len(value.shape) not in (0, 1, 2, 3, 4): raise ValueError( f"Shape {value.shape} for name '{name}' cannot be " "interpreted as scalar, histogram, image, or video.") self._metrics.append((step, name, value)) def scalar(self, name, value): self.add({name: value}) def image(self, name, value): self.add({name: value}) def video(self, name, value): self.add({name: value}) def write(self, fps=False): if fps: value = self._compute_fps() if value is not None: self.scalar('fps', value) if not self._metrics: return for output in self.outputs: output(tuple(self._metrics)) self._metrics.clear() def _compute_fps(self): step = int(self.step) * self.multiplier if self._last_step is None: self._last_time = time.time() self._last_step = step return None steps = step - self._last_step duration = time.time() - self._last_time self._last_time += duration self._last_step = step return steps / duration class AsyncOutput: def __init__(self, callback, parallel=True): self._callback = callback self._parallel = parallel if parallel: self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) self._future = None def __call__(self, summaries): if self._parallel: self._future and self._future.result() self._future = self._executor.submit(self._callback, summaries) else: self._callback(summaries) class TerminalOutput: def __init__(self, pattern=r'.*', name=None): self._pattern = re.compile(pattern) self._name = name try: import rich.console self._console = rich.console.Console() except ImportError: self._console = None def __call__(self, summaries): step = max(s for s, _, _, in summaries) scalars = {k: float(v) for _, k, v in summaries if len(v.shape) == 0} scalars = {k: v for k, v in scalars.items() if self._pattern.search(k)} formatted = {k: self._format_value(v) for k, v in scalars.items()} if self._console: if self._name: self._console.rule(f'[green bold]{self._name} (Step {step})') else: self._console.rule(f'[green bold]Step {step}') self._console.print(' [blue]/[/blue] '.join( f'{k} {v}' for k, v in formatted.items())) print('') else: message = ' / '.join(f'{k} {v}' for k, v in formatted.items()) message = f'[{step}] {message}' if self._name: message = f'[{self._name}] {message}' print(message, flush=True) def _format_value(self, value): value = float(value) if value == 0: return '0' elif 0.01 < abs(value) < 10000: value = f'{value:.2f}' value = value.rstrip('0') value = value.rstrip('0') value = value.rstrip('.') return value else: value = f'{value:.1e}' value = value.replace('.0e', 'e') value = value.replace('+0', '') value = value.replace('+', '') value = value.replace('-0', '-') return value class JSONLOutput(AsyncOutput): def __init__( self, logdir, filename='metrics.jsonl', pattern=r'.*', parallel=True): super().__init__(self._write, parallel) self._filename = filename self._pattern = re.compile(pattern) self._logdir = path.Path(logdir) self._logdir.mkdirs() def _write(self, summaries): bystep = collections.defaultdict(dict) for step, name, value in summaries: if len(value.shape) == 0 and self._pattern.search(name): bystep[step][name] = float(value) lines = ''.join([ json.dumps({'step': step, **scalars}) + '\n' for step, scalars in bystep.items()]) with (self._logdir / self._filename).open('a') as f: f.write(lines) class TensorBoardOutput(AsyncOutput): def __init__(self, logdir, fps=20, maxsize=1e9, parallel=True): super().__init__(self._write, parallel) self._logdir = str(logdir) if self._logdir.startswith('/gcs/'): self._logdir = self._logdir.replace('/gcs/', 'gs://') self._fps = fps self._writer = None self._maxsize = self._logdir.startswith('gs://') and maxsize if self._maxsize: self._checker = concurrent.futures.ThreadPoolExecutor(max_workers=1) self._promise = None def _write(self, summaries): import tensorflow as tf reset = False if self._maxsize: result = self._promise and self._promise.result() # print('Current TensorBoard event file size:', result) reset = (self._promise and result >= self._maxsize) self._promise = self._checker.submit(self._check) if not self._writer or reset: print('Creating new TensorBoard event file writer.') self._writer = tf.summary.create_file_writer( self._logdir, flush_millis=1000, max_queue=10000) self._writer.set_as_default() for step, name, value in summaries: try: if len(value.shape) == 0: tf.summary.scalar(name, value, step) elif len(value.shape) == 1: if len(value) > 1024: value = value.copy() np.random.shuffle(value) value = value[:1024] tf.summary.histogram(name, value, step) elif len(value.shape) == 2: tf.summary.image(name, value, step) elif len(value.shape) == 3: tf.summary.image(name, value, step) elif len(value.shape) == 4: self._video_summary(name, value, step) except Exception: print('Error writing summary:', name) raise self._writer.flush() def _check(self): import tensorflow as tf events = tf.io.gfile.glob(self._logdir.rstrip('/') + '/events.out.*') return tf.io.gfile.stat(sorted(events)[-1]).length if events else 0 def _video_summary(self, name, video, step): import tensorflow as tf import tensorflow.compat.v1 as tf1 name = name if isinstance(name, str) else name.decode('utf-8') if np.issubdtype(video.dtype, np.floating): video = np.clip(255 * video, 0, 255).astype(np.uint8) try: video = video[:, :, :, :3] T, H, W, C = video.shape summary = tf1.Summary() image = tf1.Summary.Image(height=H, width=W, colorspace=C) image.encoded_image_string = _encode_gif(video, self._fps) summary.value.add(tag=name, image=image) tf.summary.experimental.write_raw_pb(summary.SerializeToString(), step) except (IOError, OSError) as e: print('GIF summaries require ffmpeg in $PATH.', e) tf.summary.image(name, video, step) class WandBOutput: def __init__(self, pattern, username, project_name, model_name, config): self._pattern = re.compile(pattern) import wandb wandb.init( project=project_name, name=model_name, entity=username, # sync_tensorboard=True, config=dict(config), ) self._wandb = wandb def __call__(self, summaries): bystep = collections.defaultdict(dict) wandb = self._wandb for step, name, value in summaries: if len(value.shape) == 0 and self._pattern.search(name): bystep[step][name] = float(value) elif len(value.shape) == 1: bystep[step][name] = wandb.Histogram(value) elif len(value.shape) == 2: value = np.clip(255 * value, 0, 255).astype(np.uint8) value = np.transpose(value, [2, 0, 1]) bystep[step][name] = wandb.Image(value) elif len(value.shape) == 3: value = np.clip(255 * value, 0, 255).astype(np.uint8) value = np.transpose(value, [2, 0, 1]) bystep[step][name] = wandb.Image(value) elif len(value.shape) == 4: value = value[:, :, :, :3] # Sanity check that the channeld dimension is last assert value.shape[3] in [1, 3, 4], f"Invalid shape: {value.shape}" value = np.transpose(value, [0, 3, 1, 2]) # If the video is a float, convert it to uint8 if np.issubdtype(value.dtype, np.floating): value = np.clip(255 * value, 0, 255).astype(np.uint8) bystep[step][name] = wandb.Video(value) for step, metrics in bystep.items(): self._wandb.log(metrics, step=step) class MLFlowOutput: def __init__(self, run_name=None, resume_id=None, config=None, prefix=None): import mlflow self._mlflow = mlflow self._prefix = prefix self._setup(run_name, resume_id, config) def __call__(self, summaries): bystep = collections.defaultdict(dict) for step, name, value in summaries: if len(value.shape) == 0 and self._pattern.search(name): name = f'{self._prefix}/{name}' if self._prefix else name bystep[step][name] = float(value) for step, metrics in bystep.items(): self._mlflow.log_metrics(metrics, step=step) def _setup(self, run_name, resume_id, config): tracking_uri = os.environ.get('MLFLOW_TRACKING_URI', 'local') run_name = run_name or os.environ.get('MLFLOW_RUN_NAME') resume_id = resume_id or os.environ.get('MLFLOW_RESUME_ID') print('MLFlow Tracking URI:', tracking_uri) print('MLFlow Run Name: ', run_name) print('MLFlow Resume ID: ', resume_id) if resume_id: runs = self._mlflow.search_runs(None, f'tags.resume_id="{resume_id}"') assert len(runs), ('No runs to resume found.', resume_id) self._mlflow.start_run(run_name=run_name, run_id=runs['run_id'].iloc[0]) for key, value in config.items(): self._mlflow.log_param(key, value) else: tags = {'resume_id': resume_id or ''} self._mlflow.start_run(run_name=run_name, tags=tags) def _encode_gif(frames, fps): from subprocess import Popen, PIPE h, w, c = frames[0].shape pxfmt = {1: 'gray', 3: 'rgb24'}[c] cmd = ' '.join([ 'ffmpeg -y -f rawvideo -vcodec rawvideo', f'-r {fps:.02f} -s {w}x{h} -pix_fmt {pxfmt} -i - -filter_complex', '[0:v]split[x][z];[z]palettegen[y];[x]fifo[x];[x][y]paletteuse', f'-r {fps:.02f} -f gif -']) proc = Popen(cmd.split(' '), stdin=PIPE, stdout=PIPE, stderr=PIPE) for image in frames: proc.stdin.write(image.tobytes()) out, err = proc.communicate() if proc.returncode: raise IOError('\n'.join([' '.join(cmd), err.decode('utf8')])) del proc return out
10,907
Python
32.563077
78
0.610159
RoboticExplorationLab/Deep-ILC/main.py
import argparse import datetime import numpy as np import itertools from dmc_grad import DMControlEnvWrapper from envs.cartpole import Cartpole from envs.airplane import YakPlane from envs.quadrotor import Quadrotor from envs.rex_quadrotor import RexQuadrotor from envs.acrobot import AcrobotEnv from envs.cheetah import CheetahEnv from envs.hopper import HopperEnv from envs.ant import AntEnv import torch from sac import SAC from tensorboardX import SummaryWriter from replay_memory import ReplayMemory from utils import compute_jacobian_online, compute_jacobian_batch from pretrain import pretrain_sac import ipdb import time import sys from rl_plotter.logger import Logger parser = argparse.ArgumentParser(description='PyTorch Soft Actor-Critic Args') parser.add_argument('--env-name', default="rexquadrotor", help='Choose environment (cartpole, acrobot, rexquadrotor, halfcheetah, hopper, DmcCheetah, DmcHopper)') parser.add_argument('--policy', default="Gaussian", help='Policy Type: Gaussian | Deterministic (default: Gaussian)') parser.add_argument('--eval', type=bool, default=True, help='Evaluates a policy a policy every 10 episode (default: True)') parser.add_argument('--gamma', type=float, default=0.99, metavar='G', help='discount factor for reward (default: 0.99)') parser.add_argument('--tau', type=float, default=0.005, metavar='G', help='target smoothing coefficient(τ) (default: 0.005)') parser.add_argument('--lr', type=float, default=0.0003, metavar='G', help='learning rate (default: 0.0003)') parser.add_argument('--alpha', type=float, default=0.2, metavar='G', help='Temperature parameter α determines the relative importance of the entropy\ term against the reward (default: 0.2)') parser.add_argument('--automatic_entropy_tuning', type=bool, default=False, metavar='G', help='Automaically adjust α (default: False)') parser.add_argument('--seed', type=int, default=123456, metavar='N', help='random seed (default: 123456)') parser.add_argument('--batch_size', type=int, default=256, metavar='N', help='batch size (default: 256)') parser.add_argument('--num_steps', type=int, default=1000001, metavar='N', help='maximum number of steps (default: 1000000)') parser.add_argument('--hidden_sizePi', type=int, default=256, metavar='N', help='hidden size (default: 256)') parser.add_argument('--hidden_sizeQ', type=int, default=256, metavar='N', help='hidden size (default: 256)') parser.add_argument('--updates_per_step', type=int, default=1, metavar='N', help='model updates per simulator step (default: 1)') parser.add_argument('--start_steps', type=int, default=1000, metavar='N', help='Steps sampling random actions (default: 10000)') parser.add_argument('--target_update_interval', type=int, default=1, metavar='N', help='Value target update per no. of updates per step (default: 1)') parser.add_argument('--replay_size', type=int, default=1000000, metavar='N', help='size of replay buffer (default: 10000000)') parser.add_argument('--cuda', action="store_true", help='run on CUDA (default: False)') parser.add_argument('--eval_interval', type=int, default=40, help='evaluation interval (default: 40 episodes)') parser.add_argument('--exp_name', type=str, default='scratch_training_test', help='name of the experiment') parser.add_argument('--offline', action="store_true", help='Train with offline data (i.e without collecting any experiences) (default: False)') parser.add_argument('--jacobian', action="store_true", help='Train with approximate model jacobians (default: False)') parser.add_argument('--pretrain', action="store_true", help='Pretrain the model in the approximate model(default: False)') parser.add_argument('--pretrain_jacobian', action="store_true", help='Pretrain the model in the approximate model with model jacobians (default: False)') parser.add_argument('--load', action="store_true", help='Load the model saved with exp-name (default: False)') parser.add_argument('--test', action="store_true", help='Run without logging or saving (default: False)') parser.add_argument('--zeroth', action="store_true", help='Train with zeroth order jacobians from the approximate model (default: False)') parser.add_argument('--jac_s_coeff', type=float, default=1.0, help='Coefficient for the state jacobian loss (default: 1.0)') args = parser.parse_args() args.dflex_env = False args.dmc_env = False device = torch.device("cuda" if args.cuda else "cpu") if args.env_name == 'cartpole': T = 100 dt = 0.05 env = Cartpole(mc=1.8, mp=0.6, b=0.08, deadband=0.05, mu=0.6, device=device, dt=dt, max_steps=T) #Cartpole(mu=0.4, device=device) env_nom = Cartpole(b=0.0, deadband=0.0, u_max=np.inf, mu=0.0, device=device, dt=dt, max_steps=T) elif args.env_name == 'acrobot': T = 100 dt = 0.05 env_nom = AcrobotEnv(1, device=device, dt=dt, T=T) env = AcrobotEnv(1, device=device, dt=dt, T=T, l1=1.2, m1=1.2) elif args.env_name == 'quadrotor': env = Quadrotor(mass=0.75, J=([[0.0026, 0.0003, 0.0], [0.0003, 0.0026, 0.0], [0.0, 0.0, 0.005]]), motor_dist=0.2, kf=0.95, km=0.026, cross_A_x = 0.3, cross_A_y = 0.3, cross_A_z = 0.65, cd=[0.4, 0.4, 0.4], max_steps=100, dt=0.05) env_nom = Quadrotor(max_steps=100, dt=0.05) elif args.env_name == 'rexquadrotor': env_nom = RexQuadrotor() env = RexQuadrotor(mass=1.1*2.0, J=[[0.0165, 0.0, 0.0], [0.0, 0.0165, 0.0],[0.0, 0.0, 0.0234]], kf=1.1*0.0244101, km=1.1*0.00029958, bf=0.9*(-30.48576), bm=0.9*(-0.367697), cd=[0.3, 0.3, 0.3]) elif args.env_name == 'airplane': env = YakPlane(m=0.075*1.5, b=0.45*0.85, lin=True, max_steps=50, dt=0.04) dtype = torch.float32 if args.zeroth: dtype = torch.double env_nom = YakPlane(m=0.075*1.2, b=0.45*0.95, lin=True, max_steps=50, dt=0.04, dtype=dtype) elif args.env_name == 'halfcheetah': env_params = { 'density' : 1000.0, 'stiffness' : 0.0, 'damping' : 0.7, 'contact_ke': 1.e+5, 'contact_kd': 5.e+3, 'contact_kf': 1.e+3, 'contact_mu': 0.7, 'limit_ke' : 1.e+3, 'limit_kd' : 1.e+1, 'armature' : 0.1} env = CheetahEnv(num_envs = 1, \ device = 'cpu', \ render = False, \ seed = args.seed, \ episode_length=1000, \ stochastic_init = True, \ MM_caching_frequency = 16, \ no_grad=False, env_params=env_params) env_nom = CheetahEnv(num_envs = 1, \ device = 'cpu', \ render = False, \ seed = args.seed, \ episode_length=1000, \ stochastic_init = True, \ MM_caching_frequency = 16, \ no_grad=False) args.dflex_env = True elif args.env_name == 'hopper': env_params = { 'density' : 1000.0, 'stiffness' : 0.0, 'damping' : 1.6, 'contact_ke': 1.e+5, 'contact_kd': 5.e+3, 'contact_kf': 1.e+3, 'contact_mu': 0.72, 'limit_ke' : 1.e+3, 'limit_kd' : 1.e+1, 'armature' : 1.0} env = HopperEnv(num_envs = 1, \ device = 'cpu', \ render = False, \ seed = args.seed, \ episode_length=1000, \ stochastic_init = True, \ MM_caching_frequency = 16, \ no_grad=False, env_params=env_params) env_nom = HopperEnv(num_envs = 1, \ device = 'cpu', \ render = False, \ seed = args.seed, \ episode_length=1000, \ stochastic_init = True, \ MM_caching_frequency = 16, \ no_grad=False) args.dflex_env = True elif args.env_name == 'DmcCheetah': from dm_control import suite args.dmc_env = True env = DMControlEnvWrapper(domain_name='cheetah', task_name='run') env_nom = DMControlEnvWrapper(domain_name='cheetah', task_name='run') args.jac_s_coeff = 0.0 # Access the MuJoCo model model = env.dm_control_env.physics.model # Change damping coefficients for all joints model.dof_damping = model.dof_damping*0.7 # Change contact stiffness coefficients # model.actuator_gainprm = model.actuator_gainprm # Change friction coefficients model.geom_friction = model.geom_friction*0.7 if args.offline: data = np.load('data') else: data = None torch.manual_seed(args.seed) np.random.seed(args.seed) # Agent agent = SAC(env.observation_space.shape[0], env.action_space, args) # Saving and Loading save_path = 'runs/SAC_{}_{}'.format(args.env_name,args.exp_name) ckpt_save_path = save_path+'/checkpoint' args.ckpt_save_path = ckpt_save_path if args.load: if args.jacobian: save_path+= '/ft_jac_up2/' args.exp_name += '_ft_jac_up2/' else: save_path+= '/ft_rl/' args.exp_name += '_ft_rl/' if args.load: agent.load_nets(ckpt_save_path) # Tensorboard if not args.test: writer = SummaryWriter(save_path+f'/seed{args.seed}/') config = {'args' : args} logger = Logger(log_dir="./rl_plotter_logs", exp_name=args.exp_name, env_name=args.env_name, seed=args.seed, config=config) else: writer = None # Memory if args.offline: state, action, next_state = torch.tensor(data['state']).to(device).float(), torch.tensor(data['action']).to(device).float(), torch.tensor(data['next_state']).to(device).float() data['jac_ssa'][i], data['grad_rsa'][i] = compute_jacobians_batch(state, action, next_state, env_nom, args) memory = ReplayMemory(args.replay_size, args.seed, data) # Training Loop total_numsteps = 0 updates = 0 if args.pretrain: pretrain_sac(agent, env_nom, writer, args, data) agent.refresh_optim() agent.reset_agent_to_best() sys.exit() test_init = False for i_episode in itertools.count(1): episode_reward = 0 episode_steps = 0 done = False states_arr = [] actions_arr = [] state = env.reset() while not done and not test_init: states_arr.append(state) if args.start_steps > total_numsteps and not args.pretrain and not args.load: action = env.action_space.sample() # Sample random action else: action = agent.select_action(state) # Sample action from policy if len(memory) > args.batch_size: # Number of updates per step in environment for i in range(args.updates_per_step): # Update parameters of all the networks if args.jacobian: critic_1_loss, critic_2_loss, policy_loss, ent_loss, alpha, stats = agent.update_parameters_jac(memory, args.batch_size, updates) else: critic_1_loss, critic_2_loss, policy_loss, ent_loss, alpha = agent.update_parameters(memory, args.batch_size, updates) if not args.test: writer.add_scalar('loss/critic_1', critic_1_loss, updates) writer.add_scalar('loss/critic_2', critic_2_loss, updates) writer.add_scalar('loss/policy', policy_loss, updates) writer.add_scalar('loss/entropy_loss', ent_loss, updates) writer.add_scalar('entropy_temprature/alpha', alpha, updates) if args.jacobian: writer.add_scalar('loss/jac_act', stats['jac_a_loss'], updates) writer.add_scalar('loss/jac_state', stats['jac_s_loss'], updates) writer.add_scalar('loss/critic_loss', stats['critic_loss'], updates) if 'act_coeff' in stats: writer.add_scalar('entropy_temprature/act_coeff', stats['act_coeff'], updates) writer.add_scalar('entropy_temprature/state_coeff', stats['state_coeff'], updates) writer.add_scalar('grads/grad_q', stats['grad_q'], updates) writer.add_scalar('grads/grad_action', stats['grad_action'], updates) writer.add_scalar('grads/grad_state', stats['grad_state'], updates) writer.add_scalar('grads/policy', stats['policy_grad'], updates) writer.add_scalar('grads/critic_grad', stats['critic_grad'], updates) writer.add_scalar('grads/nq_jac_state', stats['nq_jac_state'].abs().mean(), updates) writer.add_scalar('grads/nq_jac_action', stats['nq_jac_act'].abs().mean(), updates) writer.add_scalar('grads_qf/nq_st_med', stats['nq_jac_state'].abs().mean(dim=-1).median(), updates) writer.add_scalar('grads_qf/nq_act_med', stats['nq_jac_act'].abs().mean(dim=-1).median(), updates) writer.add_scalar('grads_qf/nq_st_max', stats['nq_jac_state'].abs().mean(dim=-1).max(), updates) writer.add_scalar('grads_qf/nq_act_max', stats['nq_jac_act'].abs().mean(dim=-1).max(), updates) updates += 1 with torch.no_grad(): next_state, reward, done, info = env.step(action) # Step episode_steps += 1 total_numsteps += 1 episode_reward += reward # Ignore the "done" signal if it comes from hitting the time horizon. # (https://github.com/openai/spinningup/blob/master/spinup/algos/sac/sac.py) mask = 1 if (episode_steps == env._max_episode_steps and not info["done_inf"]) else float(not done) if not args.offline: # jac/grads are set to 0 when args.jacobian is False or done_inf is True jac_ssa, grad_rsa = compute_jacobian_online(state, action, next_state, env_nom, args, info['done_inf']) memory.push(state, action, reward, next_state, mask, jac_ssa, grad_rsa) # Append transition to memory state = next_state actions_arr.append(action) if total_numsteps > args.num_steps: break if not args.test and not test_init: writer.add_scalar('reward/train', episode_reward, i_episode) if i_episode % 1 == 0: print("Episode: {}, total numsteps: {}, episode steps: {}, reward: {}".format(i_episode, total_numsteps, episode_steps, round(episode_reward, 2))) if (i_episode-1) % args.eval_interval == 0 and args.eval is True: test_init=False avg_reward = 0. episodes = 40 avg_num_steps = 0.0 episode_reward_list = [] for _ in range(episodes): state = env.reset() episode_reward = 0 done = False num_steps = 0 while not done: action = agent.select_action(state, evaluate=True) with torch.no_grad(): next_state, reward, done, _ = env.step(action) episode_reward += reward num_steps +=1 state = next_state episode_reward_list.append(episode_reward) avg_reward += episode_reward avg_num_steps += num_steps avg_reward /= episodes avg_num_steps /= episodes if not args.test: writer.add_scalar('avg_reward/test', avg_reward, i_episode) logger.update(score=episode_reward_list, total_steps=total_numsteps) print("----------------------------------------") print("Test Episodes: {}, Avg. Reward: {}, Avg. Numsteps: {}".format(episodes, round(avg_reward, 2), avg_num_steps)) print("----------------------------------------") env.close()
16,756
Python
44.535326
180
0.569348
RoboticExplorationLab/Deep-ILC/replay_memory.py
import random import numpy as np import ipdb class ReplayMemory: def __init__(self, capacity, seed, data=None): random.seed(seed) self.buffer = [] if data is not None: for i in range(data['state'].shape[0]): self.buffer.append((data['state'][i], data['action'][i], data['reward'][i], data['next_state'][i], data['mask'][i], data['jac_ssa'][i], data['grad_rsa'][i])) self.capacity = max(capacity, len(self.buffer)) self.position = len(self.buffer) def push(self, state, action, reward, next_state, done, jac_ssa, grad_rsa): if len(self.buffer) < self.capacity: self.buffer.append(None) self.buffer[self.position] = (state, action, reward, next_state, done, jac_ssa, grad_rsa) self.position = (self.position + 1) % self.capacity def sample(self, batch_size): batch = random.sample(self.buffer, batch_size) state, action, reward, next_state, done, jac_ssa, grad_rsa = map(np.stack, zip(*batch)) return state, action, reward, next_state, done def sample_jac(self, batch_size): batch = random.sample(self.buffer, batch_size) state, action, reward, next_state, done, jac_ssa, grad_rsa = map(np.stack, zip(*batch)) return state, action, reward, next_state, done, jac_ssa, grad_rsa def __len__(self): return len(self.buffer) def save_buffer(self, env_name, suffix="", save_path=None): if not os.path.exists('checkpoints/'): os.makedirs('checkpoints/') if save_path is None: save_path = "checkpoints/sac_buffer_{}_{}".format(env_name, suffix) print('Saving buffer to {}'.format(save_path)) with open(save_path, 'wb') as f: pickle.dump(self.buffer, f) def load_buffer(self, save_path): print('Loading buffer from {}'.format(save_path)) with open(save_path, "rb") as f: self.buffer = pickle.load(f) self.position = len(self.buffer) % self.capacity
2,043
Python
39.078431
173
0.603035
RoboticExplorationLab/Deep-ILC/utils.py
import math import numpy as np import torch from torch.autograd.functional import jacobian from dmc_grad import * import ipdb class Spaces: def __init__(self,shape, high=0, low=0): self.shape = shape self.high = torch.tensor(high) self.low = torch.tensor(low) def sample(self,): return torch.rand(self.shape)*(self.high-self.low) + self.low class Spaces_np: def __init__(self,shape, high=0, low=0): self.shape = shape self.high = high self.low = low def sample(self,): return np.random.rand(*self.shape)*(self.high-self.low) + self.low def create_log_gaussian(mean, log_std, t): quadratic = -((0.5 * (t - mean) / (log_std.exp())).pow(2)) l = mean.shape log_z = log_std z = l[-1] * math.log(2 * math.pi) log_p = quadratic.sum(dim=-1) - log_z.sum(dim=-1) - 0.5 * z return log_p def logsumexp(inputs, dim=None, keepdim=False): if dim is None: inputs = inputs.view(-1) dim = 0 s, _ = torch.max(inputs, dim=dim, keepdim=True) outputs = s + (inputs - s).exp().sum(dim=dim, keepdim=True).log() if not keepdim: outputs = outputs.squeeze(dim) return outputs def soft_update(target, source, tau): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau) def hard_update(target, source): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(param.data) def rk4(derivs, y0, t): """ Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta. This is a toy implementation which may be useful if you find yourself stranded on a system w/o scipy. Otherwise use :func:`scipy.integrate`. Args: derivs: the derivative of the system and has the signature ``dy = derivs(yi)`` y0: initial state vector t: sample times args: additional arguments passed to the derivative function kwargs: additional keyword arguments passed to the derivative function Example 1 :: ## 2D system def derivs(x): d1 = x[0] + 2*x[1] d2 = -3*x[0] + 4*x[1] return (d1, d2) dt = 0.0005 t = arange(0.0, 2.0, dt) y0 = (1,2) yout = rk4(derivs6, y0, t) If you have access to scipy, you should probably be using the scipy.integrate tools rather than this function. This would then require re-adding the time variable to the signature of derivs. Returns: yout: Runge-Kutta approximation of the ODE """ yout = [] yout.append(y0) for i in np.arange(len(t) - 1): thist = t[i] dt = t[i + 1] - thist dt2 = dt / 2.0 y0 = yout[i] k1 = derivs(y0) k2 = derivs(y0 + dt2 * k1) k3 = derivs(y0 + dt2 * k2) k4 = derivs(y0 + dt * k3) yout.append(y0 + dt / 6.0 * (k1 + 2 * k2 + 2 * k3 + k4)) # We only care about the final timestep and we cleave off action value which will be zero return yout[-1] def euler(derivs, y0, t): yout = [] yout.append(y0) for i in np.arange(len(t) - 1): thist = t[i] dt = t[i + 1] - thist y0 = yout[i] k1 = derivs(y0) yout.append(y0 + dt * k1) # We only care about the final timestep and we cleave off action value which will be zero return yout[-1] def compute_jacobian_batch(state, action, next_state, env, args, done_inf, args_jacobian=True): if not args_jacobian or done_inf: state_dim = state.shape[-1] act_dim = action.shape[-1] bsz = state.shape[0] return torch.zeros((bsz, state_dim, state_dim+act_dim)).to(state), torch.zeros((bsz, state_dim+act_dim)).to(state) def func(inp): x = inp[:, :state.shape[-1]] u = inp[:, state.shape[-1]:] ns, _, _, _ = env.stepx(x, u) ns_rew = ns + (next_state - ns).detach().clone() rew = env.reward(ns_rew, u).unsqueeze(-1) return torch.cat([ns, rew], dim=-1).sum(dim=0) jac_full = jacobian(func, torch.cat([state, action], dim=-1), vectorize=True).permute(1,0,2) jac_ssa = jac_full[:,:-1] grad_rsa = jac_full[:,-1] return jac_ssa, grad_rsa def compute_jacobian_dflex(state, action, next_state, env, args, done_inf, args_jacobian=True): state_dim = state.shape[-1] act_dim = action.shape[-1] if not args_jacobian or done_inf: return torch.zeros((1, state_dim, state_dim+act_dim)).to(state), torch.zeros((1, state_dim+act_dim)).to(state) def func(x, u): ns, _, _, _ = env.stepx(x, u) ns_rew = ns[-1:] + (next_state - ns[-1:]).detach().clone() rew = env.reward(ns_rew, u[-1:]).unsqueeze(-1) idx = list(np.arange(ns.shape[-1])) out = ns[:-1][idx,idx].sum() + rew.sum() return out x = torch.cat([state]*(state_dim+1), dim=0).requires_grad_(True) u = torch.cat([action]*(state_dim+1), dim=0).requires_grad_(True) jac_full = torch.autograd.grad(func(x, u), [x, u]) jac_full = torch.cat(jac_full, dim=-1) jac_ssa = jac_full[:-1].unsqueeze(0) grad_rsa = jac_full[-1].unsqueeze(0) return jac_ssa, grad_rsa def compute_jacobian_zeroth(state, action, next_state, env, args, done_inf, args_jacobian=True): state_dim = state.shape[-1] action_dim = action.shape[-1] if not args_jacobian or done_inf: return torch.zeros((1, state_dim, state_dim+action_dim)).to(state), torch.zeros((1, state_dim+action_dim)).to(state) def func(x, u): ns, _, _, _ = env.stepx(x, u) ns_rew = ns + (next_state - ns[-1:]).detach().clone() rew = env.reward(ns_rew, u[-1:]).unsqueeze(-1) idx = list(np.arange(ns.shape[-1])) out = torch.cat([ns, rew],dim=-1) return out eps = 1e-6 eps_state = torch.cat([torch.eye(state_dim), -torch.eye(state_dim), torch.zeros(2*action_dim+1, state_dim)], dim=0)*eps eps_action = torch.cat([torch.zeros(2*state_dim, action_dim), torch.eye(action_dim), -torch.eye(action_dim), torch.zeros(1, action_dim)], dim=0)*eps x = torch.cat([state]*(2*(state_dim+action_dim)+1), dim=0) + eps_state u = torch.cat([action]*(2*(state_dim+action_dim)+1), dim=0) + eps_action out = func(x, u) jac_state = (out[:state_dim] - out[state_dim:2*state_dim])/(2*eps) jac_action = (out[2*state_dim:2*state_dim+action_dim] - out[2*state_dim+action_dim:-1])/(2*eps) jac_full = torch.cat([jac_state, jac_action], dim=0).t().to(state).detach() jac_ssa = jac_full[:-1].unsqueeze(0) grad_rsa = jac_full[-1].unsqueeze(0) return jac_ssa, grad_rsa def compute_jacobian_online(state, action, next_state, env, args, done_inf, args_jacobian=None, args_zeroth=None): if args_jacobian is None: args_jacobian = args.jacobian if args_zeroth is None: args_zeroth = args.zeroth if state.dtype == np.float64 or state.dtype == np.float32: state = torch.FloatTensor(state).to(env.device) action = torch.FloatTensor(action).to(env.device) next_state = torch.FloatTensor(next_state).to(env.device) if args.dmc_env: jac_ssa, grad_rsa = compute_jacobian_dmc(state.unsqueeze(0), action.unsqueeze(0), next_state.unsqueeze(0), env, args, done_inf, args_jacobian) elif args.dflex_env: jac_ssa, grad_rsa = compute_jacobian_dflex(state.unsqueeze(0), action.unsqueeze(0), next_state.unsqueeze(0), env, args, done_inf, args_jacobian) else: if args_zeroth: jac_ssa, grad_rsa = compute_jacobian_zeroth(state.unsqueeze(0), action.unsqueeze(0), next_state.unsqueeze(0), env, args, done_inf, args_jacobian) else: jac_ssa, grad_rsa = compute_jacobian_batch(state.unsqueeze(0), action.unsqueeze(0), next_state.unsqueeze(0), env, args, done_inf, args_jacobian) return jac_ssa[0].cpu().numpy(), grad_rsa[0].cpu().numpy() def deg2rad(deg): return (deg%360)*(2*np.pi)/360 def quatrot(q, r): qv = q[:, 1:] qs = q[:, 0:1] r = r.expand_as(qv) if q.dtype != r.dtype: r = r.to(q) cross_product = torch.cross(qv, r, dim=-1) qr = (qs**2 - (qv*qv).sum(dim=-1, keepdim=True)) * r + 2 * qv * (qv * r).sum(dim=-1, keepdim=True) + 2 * qs * cross_product return qr def getqvx(qv, bsz): qvx = torch.zeros((bsz, 3, 3)).to(qv) qvx[:, 0, 1] = -qv[:, 2] qvx[:, 0, 2] = qv[:, 1] qvx[:, 1, 2] = -qv[:, 0] qvx = qvx - (qvx.transpose(1,2)) return qvx def getLq(qv, qs, qvx, bsz): Lq = torch.zeros((bsz, 4, 4)).to(qv) Lq[:, 0, 0] += qs Lq[:, 0, 1:] += -qv Lq[:, 1:, 0] += qv Lq[:, 1:, 1:] += qs.unsqueeze(-1).unsqueeze(-1) + qvx return Lq def getRq(qv, qs, qvx, bsz): Rq = torch.zeros((bsz, 4, 4)).to(qv) Rq[:, 0, 0] += qs Rq[:, 0, 1:] += -qv Rq[:, 1:, 0] += qv Rq[:, 1:, 1:] += qs.unsqueeze(-1).unsqueeze(-1) - qvx return Rq def quatinv(q): q[1:] = -q[1:] return q def w2qdotkinematics_quat(q, w): qs = q[:, 0] qv = q[:, 1:] bsz = q.shape[0] qvx = getqvx(qv, bsz) Lq = getLq(qv, qs, qvx, bsz) qw = (Lq[:, :, 1:] * w.unsqueeze(1)).sum(dim=-1)/2 return qdot def Polynomial(coeffs, a): exp = torch.arange(len(coeffs)).unsqueeze(0).to(a) basis = a.unsqueeze(-1)**exp out = (coeffs.unsqueeze(0)*basis).sum(dim=-1) return out # "Rotate by angle of attack" def arotate(a,r): sa,ca = torch.sin(a), torch.cos(a) zeros, ones = torch.zeros_like(a), torch.ones_like(a) R1 = torch.stack([ca, zeros, -sa], dim=-1) R2 = torch.stack([zeros, ones, zeros], dim=-1) R3 = torch.stack([sa, zeros, ca], dim=-1) R = torch.stack([R1, R2, R3], dim=1) out = (R*r.unsqueeze(1)).sum(dim=-1) return out # "Rotate by sideslip angle" def brotate(b,r): sb,cb = torch.sin(b), torch.cos(b) zeros, ones = torch.zeros_like(b), torch.ones_like(b) # R = @SMatrix [ # cb -sb 0; # sb cb 0; # 0 0 1] R1 = torch.stack([cb, -sb, zeros], dim=-1) R2 = torch.stack([sb, cb, zeros], dim=-1) R3 = torch.stack([zeros, zeros, ones], dim=-1) R = torch.stack([R1, R2, R3], dim=1) out = (R*r.unsqueeze(1)).sum(dim=-1) return out def mrp2rot(m): q = mrp2quat(m) R = quat2rot(q) return R def mrp2quat(m): sqmag=torch.sum(m*m, dim=-1).unsqueeze(-1) q = torch.cat([1-sqmag, 2*m], dim=-1)/(1+sqmag) return q def quat2mrp(q): m=q[:,1:]/(1 + q[:,0].unsqueeze(-1)) return m def quat2rot(quaternions): """ Convert rotations given as quaternions to rotation matrices. Args: quaternions: quaternions with real part first, as tensor of shape (..., 4). Returns: Rotation matrices as tensor of shape (..., 3, 3). """ r, i, j, k = torch.unbind(quaternions, -1) two_s = 2.0 / (quaternions * quaternions).sum(-1) o = torch.stack( ( 1 - two_s * (j * j + k * k), two_s * (i * j - k * r), two_s * (i * k + j * r), two_s * (i * j + k * r), 1 - two_s * (i * i + k * k), two_s * (j * k - i * r), two_s * (i * k - j * r), two_s * (j * k + i * r), 1 - two_s * (i * i + j * j), ), -1, ) return o.reshape(quaternions.shape[:-1] + (3, 3)) def euler_to_quaternion(e, order=['x','y','z']): """ Convert Euler angles to quaternions. """ original_shape = list(e.shape) original_shape[-1] = 4 e = e.reshape(-1, 3) x = e[:, 0] y = e[:, 1] z = e[:, 2] rx = torch.stack((torch.cos(x/2), torch.sin(x/2), torch.zeros_like(x), torch.zeros_like(x)), axis=1) ry = torch.stack((torch.cos(y/2), torch.zeros_like(y), torch.sin(y/2), torch.zeros_like(y)), axis=1) rz = torch.stack((torch.cos(z/2), torch.zeros_like(z), torch.zeros_like(z), torch.sin(z/2)), axis=1) result = None for coord in order: if coord == 'x': r = rx elif coord == 'y': r = ry elif coord == 'z': r = rz else: raise if result is None: result = r else: result = qmul(result, r) # Reverse antipodal representation to have a non-negative "w" # if order in ['xyz']: result *= -1 return result.reshape(original_shape) def qmul(q, r): """ Multiply quaternion(s) q with quaternion(s) r. Expects two equally-sized tensors of shape (*, 4), where * denotes any number of dimensions. Returns q*r as a tensor of shape (*, 4). """ assert q.shape[-1] == 4 assert r.shape[-1] == 4 original_shape = q.shape # Compute outer product terms = torch.bmm(r.view(-1, 4, 1), q.view(-1, 1, 4)) w = terms[:, 0, 0] - terms[:, 1, 1] - terms[:, 2, 2] - terms[:, 3, 3] x = terms[:, 0, 1] + terms[:, 1, 0] - terms[:, 2, 3] + terms[:, 3, 2] y = terms[:, 0, 2] + terms[:, 1, 3] + terms[:, 2, 0] - terms[:, 3, 1] z = terms[:, 0, 3] - terms[:, 1, 2] + terms[:, 2, 1] + terms[:, 3, 0] return torch.stack((w, x, y, z), dim=1).view(original_shape) def w2pdotkinematics_mrp(p, w): # From Fundamentals of Spacecraft Attitude Determination and Control, eq (3.24) # here A = (I(3) + 2*(skew(p)^2 + skew(p))/(1+p'p)) * (1+p'p) # = √R * (1 + p'p) # where √R*√R = (√R')*(√R') = RotMatrix(p) # p = params(p) A1 = torch.stack([1 + p[:,0]**2 - p[:,1]**2 - p[:,2]**2, 2*(p[:,0]*p[:,1] - p[:,2]), 2*(p[:,0]*p[:,2] + p[:,1])], dim=-1) A2 = torch.stack([2*(p[:,1]*p[:,0] + p[:,2]), 1-p[:,0]**2+p[:,1]**2-p[:,2]**2, 2*(p[:,1]*p[:,2] - p[:,0])], dim=-1) A3 = torch.stack([2*(p[:,2]*p[:,0] - p[:,1]), 2*(p[:,2]*p[:,1] + p[:,0]), 1-p[:,0]**2-p[:,1]**2+p[:,2]**2], dim=-1) A = torch.stack([A1, A2, A3], dim=1) return 0.25*(A*w.unsqueeze(1)).sum(dim=-1) def angle_normalize(x, low=-math.pi, high=math.pi): return (((x - low) % (high-low)) + low)
14,092
Python
33.457213
157
0.554002
RoboticExplorationLab/Deep-ILC/model.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Normal LOG_SIG_MAX = 2 LOG_SIG_MIN = -20 epsilon = 1e-6 # Initialize Policy weights def weights_init_(m): if isinstance(m, nn.Linear): torch.nn.init.xavier_uniform_(m.weight, gain=1) torch.nn.init.constant_(m.bias, 0) class ValueNetwork(nn.Module): def __init__(self, num_inputs, hidden_dim): super(ValueNetwork, self).__init__() self.linear1 = nn.Linear(num_inputs, hidden_dim) self.linear2 = nn.Linear(hidden_dim, hidden_dim) self.linear3 = nn.Linear(hidden_dim, 1) self.apply(weights_init_) def forward(self, state): x = F.relu(self.linear1(state)) x = F.relu(self.linear2(x)) x = self.linear3(x) return x class QNetwork(nn.Module): def __init__(self, num_inputs, num_actions, hidden_dim): super(QNetwork, self).__init__() # Q1 architecture self.linear1 = nn.Linear(num_inputs + num_actions, hidden_dim) self.linear2 = nn.Linear(hidden_dim, hidden_dim) self.linear3 = nn.Linear(hidden_dim, 1) # Q2 architecture self.linear4 = nn.Linear(num_inputs + num_actions, hidden_dim) self.linear5 = nn.Linear(hidden_dim, hidden_dim) self.linear6 = nn.Linear(hidden_dim, 1) self.num_inputs = num_inputs self.num_actions = num_actions self.hidden_dim = hidden_dim self.apply(weights_init_) def forward(self, state, action): xu = torch.cat([state, action], 1) x1 = torch.tanh(self.linear1(xu)) x1 = torch.tanh(self.linear2(x1)) x1 = self.linear3(x1) x2 = torch.tanh(self.linear4(xu)) x2 = torch.tanh(self.linear5(x2)) x2 = self.linear6(x2) return x1, x2 class GaussianPolicy(nn.Module): def __init__(self, num_inputs, num_actions, hidden_dim, action_space=None): super(GaussianPolicy, self).__init__() self.linear1 = nn.Linear(num_inputs, hidden_dim) self.linear2 = nn.Linear(hidden_dim, hidden_dim) self.mean_linear = nn.Linear(hidden_dim, num_actions) self.log_std_linear = nn.Linear(hidden_dim, num_actions) self.apply(weights_init_) # action rescaling if action_space is None: self.action_scale = torch.tensor(1.) self.action_bias = torch.tensor(0.) else: self.action_scale = torch.FloatTensor( (action_space.high - action_space.low) / 2.) self.action_bias = torch.FloatTensor( (action_space.high + action_space.low) / 2.) def forward(self, state): x = F.relu(self.linear1(state)) x = F.relu(self.linear2(x)) mean = self.mean_linear(x) log_std = self.log_std_linear(x) log_std = torch.clamp(log_std, min=LOG_SIG_MIN, max=LOG_SIG_MAX) return mean, log_std def sample(self, state): mean, log_std = self.forward(state) std = log_std.exp() normal = Normal(mean, std) x_t = normal.rsample() # for reparameterization trick (mean + std * N(0,1)) y_t = torch.tanh(x_t) action = y_t * self.action_scale + self.action_bias log_prob = normal.log_prob(x_t) # Enforcing Action Bound log_prob -= torch.log(self.action_scale * (1 - y_t.pow(2)) + epsilon) log_prob = log_prob.sum(1, keepdim=True) mean = torch.tanh(mean) * self.action_scale + self.action_bias return action, log_prob, mean def to(self, device): self.action_scale = self.action_scale.to(device) self.action_bias = self.action_bias.to(device) return super(GaussianPolicy, self).to(device) class DeterministicPolicy(nn.Module): def __init__(self, num_inputs, num_actions, hidden_dim, action_space=None): super(DeterministicPolicy, self).__init__() self.linear1 = nn.Linear(num_inputs, hidden_dim) self.linear2 = nn.Linear(hidden_dim, hidden_dim) self.mean = nn.Linear(hidden_dim, num_actions) self.noise = torch.Tensor(num_actions) self.apply(weights_init_) # action rescaling if action_space is None: self.action_scale = 1. self.action_bias = 0. else: self.action_scale = torch.FloatTensor( (action_space.high - action_space.low) / 2.) self.action_bias = torch.FloatTensor( (action_space.high + action_space.low) / 2.) def forward(self, state): x = F.relu(self.linear1(state)) x = F.relu(self.linear2(x)) mean = torch.tanh(self.mean(x)) * self.action_scale + self.action_bias return mean def sample(self, state): mean = self.forward(state) noise = self.noise.normal_(0., std=0.1) noise = noise.clamp(-0.25, 0.25) action = mean + noise return action, torch.tensor(0.), mean def to(self, device): self.action_scale = self.action_scale.to(device) self.action_bias = self.action_bias.to(device) self.noise = self.noise.to(device) return super(DeterministicPolicy, self).to(device)
5,253
Python
32.679487
84
0.598706
RoboticExplorationLab/Deep-ILC/sac.py
import os import torch import torch.nn.functional as F from torch.optim import Adam from utils import soft_update, hard_update from model import GaussianPolicy, QNetwork, DeterministicPolicy import copy import ipdb class SAC(object): def __init__(self, num_inputs, action_space, args): self.gamma = args.gamma self.tau = args.tau self.alpha = args.alpha self.state_dim = num_inputs self.args = args self.policy_type = args.policy self.target_update_interval = args.target_update_interval self.automatic_entropy_tuning = args.automatic_entropy_tuning self.device = torch.device("cuda" if args.cuda else "cpu") self.critic = QNetwork(num_inputs, action_space.shape[0], args.hidden_sizeQ).to(device=self.device) self.critic_optim = Adam(self.critic.parameters(), lr=args.lr) self.critic_target = QNetwork(num_inputs, action_space.shape[0], args.hidden_sizeQ).to(self.device) hard_update(self.critic_target, self.critic) self.act_running_median = None self.state_running_median = None if self.policy_type == "Gaussian": # Target Entropy = −dim(A) (e.g. , -6 for HalfCheetah-v2) as given in the paper if self.automatic_entropy_tuning is True: self.target_entropy = -torch.prod(torch.Tensor(action_space.shape).to(self.device)).item() self.log_alpha = torch.zeros(1, requires_grad=True, device=self.device) self.alpha_optim = Adam([self.log_alpha], lr=args.lr) self.policy = GaussianPolicy(num_inputs, action_space.shape[0], args.hidden_sizePi, action_space).to(self.device) self.policy_optim = Adam(self.policy.parameters(), lr=args.lr) else: self.alpha = 0 self.automatic_entropy_tuning = False self.policy = DeterministicPolicy(num_inputs, action_space.shape[0], args.hidden_sizePi, action_space).to(self.device) self.policy_optim = Adam(self.policy.parameters(), lr=args.lr) def select_action(self, state, evaluate=False): state = torch.FloatTensor(state).to(self.device).unsqueeze(0) if evaluate is False: action, _, _ = self.policy.sample(state) else: _, _, action = self.policy.sample(state) return action.detach().cpu().numpy()[0] def update_parameters(self, memory, batch_size, updates): # Sample a batch from memory state_batch, action_batch, reward_batch, next_state_batch, mask_batch = memory.sample(batch_size=batch_size) state_batch = torch.FloatTensor(state_batch).to(self.device) next_state_batch = torch.FloatTensor(next_state_batch).to(self.device) action_batch = torch.FloatTensor(action_batch).to(self.device) reward_batch = torch.FloatTensor(reward_batch).to(self.device).unsqueeze(1) mask_batch = torch.FloatTensor(mask_batch).to(self.device).unsqueeze(1) with torch.no_grad(): next_state_action, next_state_log_pi, _ = self.policy.sample(next_state_batch) qf1_next_target, qf2_next_target = self.critic_target(next_state_batch, next_state_action) min_qf_next_target = torch.min(qf1_next_target, qf2_next_target) - self.alpha * next_state_log_pi next_q_value = reward_batch + mask_batch * self.gamma * (min_qf_next_target) qf1, qf2 = self.critic(state_batch, action_batch) # Two Q-functions to mitigate positive bias in the policy improvement step qf1_loss = F.mse_loss(qf1, next_q_value) # JQ = 𝔼(st,at)~D[0.5(Q1(st,at) - r(st,at) - γ(𝔼st+1~p[V(st+1)]))^2] qf2_loss = F.mse_loss(qf2, next_q_value) # JQ = 𝔼(st,at)~D[0.5(Q1(st,at) - r(st,at) - γ(𝔼st+1~p[V(st+1)]))^2] qf_loss = qf1_loss + qf2_loss self.critic_optim.zero_grad() qf_loss.backward() self.critic_optim.step() pi, log_pi, _ = self.policy.sample(state_batch) qf1_pi, qf2_pi = self.critic(state_batch, pi) min_qf_pi = torch.min(qf1_pi, qf2_pi) policy_loss = ((self.alpha * log_pi) - min_qf_pi).mean() # Jπ = 𝔼st∼D,εt∼N[α * logπ(f(εt;st)|st) − Q(st,f(εt;st))] self.policy_optim.zero_grad() policy_loss.backward() self.policy_optim.step() if self.automatic_entropy_tuning: alpha_loss = -(self.log_alpha * (log_pi + self.target_entropy).detach()).mean() self.alpha_optim.zero_grad() alpha_loss.backward() self.alpha_optim.step() self.alpha = self.log_alpha.exp() alpha_tlogs = self.alpha.clone() # For TensorboardX logs else: alpha_loss = torch.tensor(0.).to(self.device) alpha_tlogs = torch.tensor(self.alpha) # For TensorboardX logs if updates % self.target_update_interval == 0: soft_update(self.critic_target, self.critic, self.tau) return qf1_loss.item(), qf2_loss.item(), policy_loss.item(), alpha_loss.item(), alpha_tlogs.item() def compute_action_grad_loss(self, out, targ): diff = torch.abs(out - targ) median = diff.median(dim=0)[0].detach().clone().unsqueeze(0) if self.act_running_median is None: self.act_running_median = median else: self.act_running_median = 0.95*self.act_running_median + 0.05*median median = self.act_running_median mask = (diff < 2*median).float() cost = torch.square(out - targ)*mask + diff*4*median*(1-mask) cost = torch.mean(cost) return cost, mask.sum() def compute_state_grad_loss(self, out, targ): diff = torch.abs(out - targ) median = diff.median(dim=0)[0].detach().clone().unsqueeze(0) if self.state_running_median is None: self.state_running_median = median else: self.state_running_median = 0.95*self.state_running_median + 0.05*median median = self.state_running_median mask = (diff < 2*median).float() cost = torch.square(out - targ)*mask + diff*4*median*(1-mask) cost = torch.mean(cost) return cost, mask.sum() def jac_loss(self, qf_grad, targ_grad, mask): qf_grad_state, qf_grad_act = qf_grad[0], qf_grad[1] targ_grad_state, targ_grad_act = targ_grad[:, :self.state_dim], targ_grad[:, self.state_dim:] jac_s_loss, jacs_mask_num = self.compute_state_grad_loss(qf_grad_state*mask, targ_grad_state*mask) jac_a_loss, jaca_mask_num = self.compute_action_grad_loss(qf_grad_act*mask, targ_grad_act*mask) return jac_s_loss, jac_a_loss, jacs_mask_num, jaca_mask_num def update_parameters_jac(self, memory, batch_size, updates): # Sample a batch from memory state_batch, action_batch, reward_batch, next_state_batch, mask_batch, jac_ssa, grad_rsa = memory.sample_jac(batch_size=batch_size) state_batch = torch.FloatTensor(state_batch).to(self.device).requires_grad_(True) next_state_batch = torch.FloatTensor(next_state_batch).to(self.device).requires_grad_(True) action_batch = torch.FloatTensor(action_batch).to(self.device).requires_grad_(True) reward_batch = torch.FloatTensor(reward_batch).to(self.device).unsqueeze(1) mask_batch = torch.FloatTensor(mask_batch).to(self.device).unsqueeze(1) state_act_jac = torch.FloatTensor(jac_ssa).to(self.device) rew_grads_batch = torch.FloatTensor(grad_rsa).to(self.device) stats = {} with torch.no_grad(): next_state_action, next_state_log_pi, _ = self.policy.sample(next_state_batch) qf1_next_target, qf2_next_target = self.critic_target(next_state_batch, next_state_action) min_qf_next_target = torch.min(qf1_next_target, qf2_next_target) - self.alpha * next_state_log_pi next_q_value = reward_batch + mask_batch * self.gamma * (min_qf_next_target) next_q_grad = rew_grads_batch + mask_batch * self.gamma * (torch.autograd.grad(min_qf_next_target.sum(), next_state_batch)[0].unsqueeze(-1)*state_act_jac).sum(dim=1) next_q_grad = next_q_grad.detach().clone() next_q_value = next_q_value.detach().clone() qf1, qf2 = self.critic(state_batch, action_batch) # Two Q-functions to mitigate positive bias in the policy improvement step qf1_loss = F.mse_loss(qf1, next_q_value) # JQ = 𝔼(st,at)~D[0.5(Q1(st,at) - r(st,at) - γ(𝔼st+1~p[V(st+1)]))^2] qf2_loss = F.mse_loss(qf2, next_q_value) # JQ = 𝔼(st,at)~D[0.5(Q1(st,at) - r(st,at) - γ(𝔼st+1~p[V(st+1)]))^2] qf_loss = qf1_loss + qf2_loss qf1_jac = torch.autograd.grad(qf1.sum(), [state_batch, action_batch], retain_graph=True, create_graph=True) qf2_jac = torch.autograd.grad(qf2.sum(), [state_batch, action_batch], retain_graph=True, create_graph=True) jac_s_loss1, jac_a_loss1, _, _ = self.jac_loss(qf1_jac, next_q_grad, mask_batch) jac_s_loss2, jac_a_loss2, jacs2_mask_num, jaca2_mask_num = self.jac_loss(qf2_jac, next_q_grad, mask_batch) jac_s_loss = jac_s_loss1 + jac_s_loss2 jac_a_loss = jac_a_loss1 + jac_a_loss2 if updates % 20 ==0: grad_q = torch.autograd.grad(qf_loss, self.critic.linear2.weight, retain_graph=True)[0].norm() grad_action = torch.autograd.grad(jac_a_loss, self.critic.linear2.weight, retain_graph=True)[0].norm() #_unmask grad_state = torch.autograd.grad(jac_s_loss, self.critic.linear2.weight, retain_graph=True)[0].norm() #_unmask if updates ==0: self.act_coeff = grad_q/grad_action self.state_coeff = grad_q/grad_state else: self.act_coeff = 0.3*self.act_coeff + 0.7*(grad_q/grad_action) self.state_coeff = 0.3*self.state_coeff + 0.7*(grad_q/grad_state) stats['grad_q'] = grad_q.item() stats['grad_action'] = grad_action.item() stats['grad_state'] = grad_state.item() stats['act_coeff'] = self.act_coeff.item() stats['state_coeff'] = self.state_coeff.item() critic_loss = qf_loss + jac_a_loss*self.act_coeff/2 + self.args.jac_s_coeff*jac_s_loss*self.state_coeff/2 stats['jac_s_loss'] = jac_s_loss.item() stats['jac_a_loss'] = jac_a_loss.item() stats['critic_loss'] = critic_loss.item() stats['qf_loss'] = qf_loss.item() stats['nq_jac_state'] = next_q_grad[:,:self.state_dim].data.cpu() stats['nq_jac_act'] = next_q_grad[:,self.state_dim:].data.cpu() self.critic_optim.zero_grad() critic_loss.backward() stats['critic_grad'] = self.critic.linear2.weight.grad.data.norm().item() self.critic_optim.step() pi, log_pi, _ = self.policy.sample(state_batch) qf1_pi, qf2_pi = self.critic(state_batch, pi) min_qf_pi = torch.min(qf1_pi, qf2_pi) policy_loss = ((self.alpha * log_pi) - min_qf_pi).mean() # Jπ = 𝔼st∼D,εt∼N[α * logπ(f(εt;st)|st) − Q(st,f(εt;st))] self.policy_optim.zero_grad() policy_loss.backward() stats['policy_grad'] = self.policy.linear2.weight.grad.data.norm().item() self.policy_optim.step() if self.automatic_entropy_tuning: alpha_loss = -(self.log_alpha * (log_pi + self.target_entropy).detach()).mean() self.alpha_optim.zero_grad() alpha_loss.backward() self.alpha_optim.step() self.alpha = self.log_alpha.exp() alpha_tlogs = self.alpha.clone() # For TensorboardX logs else: alpha_loss = torch.tensor(0.).to(self.device) alpha_tlogs = torch.tensor(self.alpha) # For TensorboardX logs if updates % self.target_update_interval == 0: soft_update(self.critic_target, self.critic, self.tau) return qf1_loss.item(), qf2_loss.item(), policy_loss.item(), alpha_loss.item(), alpha_tlogs.item(), stats # Save model parameters def save_checkpoint(self, env_name, suffix="", ckpt_path=None): if ckpt_path is None: ckpt_path = "checkpoints/sac_checkpoint_{}_{}".format(env_name, suffix) print('Saving models to {}'.format(ckpt_path)) torch.save({'policy_state_dict': self.policy.state_dict(), 'critic_state_dict': self.critic.state_dict(), 'critic_target_state_dict': self.critic_target.state_dict(), 'critic_optimizer_state_dict': self.critic_optim.state_dict(), 'policy_optimizer_state_dict': self.policy_optim.state_dict()}, ckpt_path) def refresh_optim(self): self.critic_optim = Adam(self.critic.parameters(), lr=self.args.lr) self.policy_optim = Adam(self.policy.parameters(), lr=self.args.lr) def save_best(self, env_name, ckpt_path=None): print('Saving models to {}'.format(ckpt_path)) torch.save({'policy_state_dict': self.best_policy.state_dict(), 'critic_state_dict': self.best_critic.state_dict(), 'critic_target_state_dict': self.best_critic_target.state_dict()}, ckpt_path) def reset_agent_to_best(self): self.critic = copy.deepcopy(self.best_critic) self.policy = copy.deepcopy(self.best_policy) self.critic_target = copy.deepcopy(self.best_critic_target) # Load model parameters def load_checkpoint(self, ckpt_path, evaluate=False): print('Loading models from {}'.format(ckpt_path)) if ckpt_path is not None: checkpoint = torch.load(ckpt_path) self.policy.load_state_dict(checkpoint['policy_state_dict']) self.critic.load_state_dict(checkpoint['critic_state_dict']) self.critic_target.load_state_dict(checkpoint['critic_target_state_dict']) self.critic_optim.load_state_dict(checkpoint['critic_optimizer_state_dict']) self.policy_optim.load_state_dict(checkpoint['policy_optimizer_state_dict']) if evaluate: self.policy.eval() self.critic.eval() self.critic_target.eval() else: self.policy.train() self.critic.train() self.critic_target.train() # Load model parameters def load_nets(self, ckpt_path, evaluate=False): print('Loading models from {}'.format(ckpt_path)) if ckpt_path is not None: checkpoint = torch.load(ckpt_path) self.policy.load_state_dict(checkpoint['policy_state_dict']) self.critic.load_state_dict(checkpoint['critic_state_dict']) self.critic_target.load_state_dict(checkpoint['critic_target_state_dict']) if evaluate: self.policy.eval() self.critic.eval() self.critic_target.eval() else: self.policy.train() self.critic.train() self.critic_target.train()
14,992
Python
48.157377
173
0.615328
RoboticExplorationLab/Deep-ILC/deepilc.yml
name: deepilc channels: - pytorch - conda-forge - defaults dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - asttokens=2.0.8=pyhd8ed1ab_0 - backcall=0.2.0=pyh9f0ad1d_0 - backports=1.0=py_2 - backports.functools_lru_cache=1.6.4=pyhd8ed1ab_0 - blas=1.0=mkl - brotlipy=0.7.0=py38h27cfd23_1003 - bzip2=1.0.8=h7b6447c_0 - ca-certificates=2022.6.15=ha878542_0 - certifi=2022.6.15=py38h578d9bd_0 - cffi=1.15.1=py38h74dc2b5_0 - charset-normalizer=2.0.4=pyhd3eb1b0_0 - cryptography=37.0.1=py38h9ce1e76_0 - cudatoolkit=11.3.1=h2bc3f7f_2 - cudatoolkit-dev=11.4.0=h5e8e339_5 - decorator=5.1.1=pyhd8ed1ab_0 - executing=0.10.0=pyhd8ed1ab_0 - ffmpeg=4.3=hf484d3e_0 - freetype=2.11.0=h70c0345_0 - giflib=5.2.1=h7b6447c_0 - gmp=6.2.1=h295c915_3 - gnutls=3.6.15=he1e5248_0 - idna=3.3=pyhd3eb1b0_0 - intel-openmp=2021.4.0=h06a4308_3561 - ipython=8.4.0=py38h578d9bd_0 - jedi=0.18.1=pyhd8ed1ab_2 - jpeg=9e=h7f8727e_0 - lame=3.100=h7b6447c_0 - lcms2=2.12=h3be6417_0 - ld_impl_linux-64=2.38=h1181459_1 - lerc=3.0=h295c915_0 - libdeflate=1.8=h7f8727e_5 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libiconv=1.16=h7f8727e_2 - libidn2=2.3.2=h7f8727e_0 - libpng=1.6.37=hbc83047_0 - libstdcxx-ng=11.2.0=h1234567_1 - libtasn1=4.16.0=h27cfd23_0 - libtiff=4.4.0=hecacb30_0 - libunistring=0.9.10=h27cfd23_0 - libuv=1.40.0=h7b6447c_0 - libwebp=1.2.2=h55f646e_0 - libwebp-base=1.2.2=h7f8727e_0 - lz4-c=1.9.3=h295c915_1 - matplotlib-inline=0.1.6=pyhd8ed1ab_0 - mkl=2021.4.0=h06a4308_640 - mkl-service=2.4.0=py38h7f8727e_0 - mkl_fft=1.3.1=py38hd3c417c_0 - mkl_random=1.2.2=py38h51133e4_0 - ncurses=6.3=h5eee18b_3 - nettle=3.7.3=hbbd107a_1 - numpy=1.23.1=py38h6c91a56_0 - numpy-base=1.23.1=py38ha15fc14_0 - openh264=2.1.1=h4ff587b_0 - openssl=1.1.1q=h7f8727e_0 - parso=0.8.3=pyhd8ed1ab_0 - pexpect=4.8.0=pyh9f0ad1d_2 - pickleshare=0.7.5=py_1003 - pillow=9.2.0=py38hace64e9_1 - pip=22.1.2=py38h06a4308_0 - prompt-toolkit=3.0.30=pyha770c72_0 - ptyprocess=0.7.0=pyhd3deb0d_0 - pure_eval=0.2.2=pyhd8ed1ab_0 - pycparser=2.21=pyhd3eb1b0_0 - pygments=2.13.0=pyhd8ed1ab_0 - pyopenssl=22.0.0=pyhd3eb1b0_0 - pysocks=1.7.1=py38h06a4308_0 - python=3.8.13=h12debd9_0 - python_abi=3.8=2_cp38 - pytorch=1.12.1=py3.8_cuda11.3_cudnn8.3.2_0 - pytorch-mutex=1.0=cuda - readline=8.1.2=h7f8727e_1 - requests=2.28.1=py38h06a4308_0 - setuptools=61.2.0=py38h06a4308_0 - six=1.16.0=pyhd3eb1b0_1 - sqlite=3.39.2=h5082296_0 - stack_data=0.4.0=pyhd8ed1ab_0 - tk=8.6.12=h1ccaba5_0 - torchvision=0.13.1=py38_cu113 - traitlets=5.3.0=pyhd8ed1ab_0 - typing_extensions=4.3.0=py38h06a4308_0 - urllib3=1.26.11=py38h06a4308_0 - wcwidth=0.2.5=pyh9f0ad1d_2 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.2.5=h7f8727e_1 - zlib=1.2.12=h7f8727e_2 - zstd=1.5.2=ha4553b6_0 - pip: - absl-py==1.2.0 - aiosignal==1.2.0 - attrs==22.1.0 - cachetools==5.2.0 - click==8.0.4 - cloudpickle==2.1.0 - contourpy==1.0.5 - cycler==0.11.0 - distlib==0.3.6 - dm-control==1.0.8 - dm-env==1.5 - dm-tree==0.1.7 - filelock==3.8.0 - fonttools==4.38.0 - freetype-py==2.3.0 - frozenlist==1.3.1 - glfw==2.5.5 - google-auth==2.10.0 - google-auth-oauthlib==0.4.6 - grpcio==1.43.0 - gym==0.25.1 - gym-notices==0.0.8 - gymnasium==0.26.3 - gymnasium-notices==0.0.1 - imageio==2.21.1 - importlib-metadata==4.12.0 - importlib-resources==5.9.0 - ipdb==0.13.9 - jsonschema==4.16.0 - kiwisolver==1.4.4 - labmaze==1.0.5 - lxml==4.9.1 - markdown==3.4.1 - markupsafe==2.1.1 - matplotlib==3.6.1 - msgpack==1.0.4 - mujoco==2.3.0 - networkx==2.2 - ninja==1.10.2.3 - oauthlib==3.2.0 - packaging==21.3 - pandas==1.5.1 - pkgutil-resolve-name==1.3.10 - platformdirs==2.5.2 - protobuf==3.20.0 - psutil==5.9.1 - pyasn1==0.4.8 - pyasn1-modules==0.2.8 - pycollada==0.6 - pyglet==1.5.26 - pyopengl==3.1.6 - pyparsing==2.4.7 - pyrender==0.1.45 - pyrsistent==0.18.1 - python-dateutil==2.8.2 - pytz==2022.5 - pyyaml==6.0 - ray==2.0.0 - requests-oauthlib==1.3.1 - rl-plotter==2.4.0 - rsa==4.9 - scipy==1.9.0 - setproctitle==1.3.2 - tensorboard==2.8.0 - tensorboard-data-server==0.6.1 - tensorboard-plugin-wit==1.8.1 - tensorboardx==2.5 - toml==0.10.2 - tqdm==4.64.1 - trimesh==3.13.5 - urdfpy==0.0.22 - usd-core==22.3 - virtualenv==20.16.5 - werkzeug==2.2.2 - zipp==3.8.1 prefix: /home/sgurumur/miniconda3/envs/deepilc
4,867
YAML
26.977011
52
0.601397
RoboticExplorationLab/Deep-ILC/dmc_grad.py
import numpy as np from dm_control import suite import concurrent.futures from collections import OrderedDict from dm_env.specs import Array import numpy as np import torch import mujoco class Space: def __init__(self, shape, dtype, low=np.inf, high=np.inf): self.low = low self.high = high self.shape = shape self.dtype = dtype def sample(self): return np.random.uniform(self.low, self.high, self.shape) class DMControlEnvWrapper: def __init__(self, domain_name, task_name): self.dm_control_env = suite.load(domain_name, task_name) self.action_space = self._convert_to_space(self.dm_control_env.action_spec()) self.observation_space = self._convert_to_space(self.dm_control_env.observation_spec()) self._max_episode_steps = int(self.dm_control_env._step_limit) self.device = 'cpu' def _convert_to_space(self, spec): if isinstance(spec, Array): return Space( low=spec.minimum, high=spec.maximum, shape=spec.shape, dtype=spec.dtype ) elif isinstance(spec, OrderedDict): return Space(shape=np.array([sum([spec[item].shape[0] for item in spec])]), dtype=spec['position'].dtype) else: raise NotImplementedError("Conversion for spec {} not implemented.".format(type(spec))) def _convert_to_observation(self, time_step): return np.concatenate([v for v in time_step.observation.values()]) def reset(self): time_step = self.dm_control_env.reset() return self._convert_to_observation(time_step) def step(self, action): time_step = self.dm_control_env.step(action) obs = self._convert_to_observation(time_step) reward = time_step.reward done = time_step.last() info = {'done_inf' : False} return obs, reward, done, info def create_env(): return suite.load(domain_name='cheetah', task_name='run') def compute_reward(env, state, action): env.physics.set_state(state) env.physics.set_control(action) reward = env.task.get_reward(env.physics) return reward def compute_reward_perturbed(args): env, state, action, epsilon, idx, perturbation_type = args perturbed_state = state.copy() perturbed_action = action.copy() if perturbation_type == 'state': perturbed_state[idx] += epsilon else: perturbed_action[idx] += epsilon env.physics.set_state(perturbed_state) env.physics.set_control(perturbed_action) reward = compute_reward(env, perturbed_state, perturbed_action) return reward def compute_jacobian_dmc(states, actions, true_next_states, env, args, done_inf, args_jacobian): state = states[0].cpu().numpy() action = actions[0].cpu().numpy() true_next_state = true_next_states[0].cpu().numpy() envs = [env.dm_control_env] state = np.concatenate([np.zeros(1), state]) true_next_state = np.concatenate([np.zeros(1), true_next_state]) df_dx, df_du, dr_dx, dr_du = mujoco_jacs(state, action, true_next_state, envs) df_dx = torch.tensor(df_dx[1:, 1:]).t() df_du = torch.tensor(df_du[:,1:]).t() dr_dx = torch.tensor(dr_dx[1:]) dr_du = torch.tensor(dr_du) jac_ssa = torch.cat([df_dx, df_du], dim=-1).to(states).unsqueeze(0) grad_rsa = torch.cat([dr_dx, dr_du], dim=-1).to(actions).unsqueeze(0) return jac_ssa, grad_rsa def mujoco_jacs(state, action, true_next_state, envs): env = envs[0] data = env.physics.data._data model = env.physics.model._model nv = model.nv nu = model.nu num_states = 2*nv num_actions = nu qpos = state[:nv].copy() qvel = state[nv:].copy() data.qpos = qpos data.qvel = qvel data.ctrl = action.copy() df_dx = np.zeros((2*nv, 2*nv)) df_du = np.zeros((2*nv, nu)) epsilon = 1e-6 flg_centered = True mujoco.mjd_transitionFD(model, data, epsilon, flg_centered, df_dx, df_du, None, None) perturbation_type = 'state' future_results = [compute_reward_perturbed((env, true_next_state, action, epsilon, i, perturbation_type)) for i in range(num_states)] reward_pos = future_results future_results = [compute_reward_perturbed((env, true_next_state, action, -epsilon, i, perturbation_type)) for i in range(num_states)] reward_neg = future_results dr_dx = (np.array(reward_pos) - np.array(reward_neg)) / (2 * epsilon) perturbation_type = 'action' future_results = [compute_reward_perturbed((env, true_next_state, action, epsilon, i, perturbation_type)) for i in range(num_actions)] reward_pos = future_results future_results = [compute_reward_perturbed((env, true_next_state, action, -epsilon, i, perturbation_type)) for i in range(num_actions)] reward_neg = future_results dr_du = (np.array(reward_pos) - np.array(reward_neg)) / (2 * epsilon) dr_du = dr_du + dr_dx.dot(df_du) dr_dx = dr_dx.dot(df_dx) return df_dx.transpose(), df_du.transpose(), dr_dx, dr_du
5,059
Python
36.761194
139
0.641233
RoboticExplorationLab/Deep-ILC/pretrain.py
import numpy as np import itertools import torch from replay_memory import ReplayMemory from utils import compute_jacobian_online, compute_jacobian_batch import ipdb import copy def pretrain_sac(agent, env, writer, args, data): memory = ReplayMemory(args.replay_size, args.seed, data) total_numsteps = 0 updates = 0 best_reward = -1e8 best_i_episode = 0 for i_episode in itertools.count(1): episode_reward = 0 episode_steps = 0 done = False state = env.reset() while not done: if args.start_steps > total_numsteps: action = env.action_space.sample() # Sample random action else: action = agent.select_action(state) # Sample action from policy if len(memory) > args.batch_size: # Number of updates per step in environment for i in range(args.updates_per_step): # Update parameters of all the networks if args.pretrain_jacobian: critic_1_loss, critic_2_loss, policy_loss, ent_loss, alpha, stats = agent.update_parameters_jac(memory, args.batch_size, updates) else: critic_1_loss, critic_2_loss, policy_loss, ent_loss, alpha = agent.update_parameters(memory, args.batch_size, updates) if not args.test: writer.add_scalar('loss_pt/critic_1', critic_1_loss, updates) writer.add_scalar('loss_pt/critic_2', critic_2_loss, updates) writer.add_scalar('loss_pt/policy', policy_loss, updates) writer.add_scalar('loss_pt/entropy_loss', ent_loss, updates) writer.add_scalar('entropy_temprature/alpha_pt', alpha, updates) if args.pretrain_jacobian: writer.add_scalar('loss_pt/jac_act', stats['jac_a_loss'], updates) writer.add_scalar('loss_pt/jac_state', stats['jac_s_loss'], updates) writer.add_scalar('loss_pt/critic_loss', stats['critic_loss'], updates) writer.add_scalar('grads_pt/policy', stats['policy_grad'], updates) writer.add_scalar('grads_pt/critic_grad', stats['critic_grad'], updates) writer.add_scalar('grads_pt/nq_jac_state', stats['nq_jac_state'].abs().mean(), updates) writer.add_scalar('grads_pt/nq_jac_action', stats['nq_jac_act'].abs().mean(), updates) writer.add_scalar('grads_qf_pt/nq_st_med', stats['nq_jac_state'].abs().mean(dim=-1).median(), updates) writer.add_scalar('grads_qf_pt/nq_act_med', stats['nq_jac_act'].abs().mean(dim=-1).median(), updates) writer.add_scalar('grads_qf_pt/nq_st_max', stats['nq_jac_state'].abs().mean(dim=-1).max(), updates) writer.add_scalar('grads_qf_pt/nq_act_max', stats['nq_jac_act'].abs().mean(dim=-1).max(), updates) updates += 1 with torch.no_grad(): next_state, reward, done, info = env.step(action) episode_steps += 1 total_numsteps += 1 episode_reward += reward # Ignore the "done" signal if it comes from hitting the time horizon. # (https://github.com/openai/spinningup/blob/master/spinup/algos/sac/sac.py) mask = 1 if episode_steps == env._max_episode_steps else float(not done) if not args.offline: jac_ssa, grad_rsa = compute_jacobian_online(state, action, next_state, env, args, info['done_inf'], args_jacobian=args.pretrain_jacobian) memory.push(state, action, reward, next_state, mask, jac_ssa, grad_rsa) # Append transition to memory state = next_state if total_numsteps > args.num_steps: break if not args.test: writer.add_scalar('reward_pt/train', episode_reward, i_episode) if i_episode % 5 == 0: print("Episode: {}, total numsteps: {}, episode steps: {}, reward: {}".format(i_episode, total_numsteps, episode_steps, round(episode_reward, 2))) if (i_episode-1) % args.eval_interval == 0 and args.eval is True: avg_reward = 0. episodes = 2 avg_num_steps = 0.0 episode_reward_list = [] for _ in range(episodes): state = env.reset() episode_reward = 0 done = False num_steps = 0 while not done: action = agent.select_action(state, evaluate=True) with torch.no_grad(): next_state, reward, done, _ = env.step(action) episode_reward += reward num_steps +=1 state = next_state episode_reward_list.append(episode_reward) avg_reward += episode_reward avg_num_steps += num_steps avg_reward /= episodes avg_num_steps /= episodes if avg_reward > best_reward and not args.test: agent.best_policy = copy.deepcopy(agent.policy) agent.best_critic = copy.deepcopy(agent.critic) agent.best_critic_target = copy.deepcopy(agent.critic_target) best_i_episode = i_episode best_reward = avg_reward print("Updating and saving best policy/critic!") agent.save_best(env_name = args.env_name, ckpt_path=args.ckpt_save_path) if not args.test: writer.add_scalar('avg_reward_pt/test', avg_reward, i_episode) print("----------------------------------------") print("Test Episodes: {}, Avg. Reward: {}, Avg. Numsteps: {}".format(episodes, round(avg_reward, 2), avg_num_steps), episode_reward_list) print("----------------------------------------") if best_i_episode < i_episode - 320: break
6,171
Python
50.008264
158
0.539783
RoboticExplorationLab/Deep-ILC/README.md
# Deep off-policy ILC This repository contains the implementation for the paper [Deep off-policy Iterative Learning Control](https://openreview.net/forum?id=Bi0E3lbvnU) (L4DC 2023). The paper proposes an update equation for the value-function gradients to speed up actor critic methods in reinforcement learning. This update is inspired by iterative learning control (ILC) approaches that use approximate simulator gradients to speed up optimization. The value-gradient update leads to a significant improvement in sample efficiency and sometimes better performance both when learning from scratch or fine-tuning a pre-trained policy in a new environment. We add this update to soft actor-critic (SAC) and demonstrate improvements. #### Prerequisites - In the project folder, create a virtual environment in Anaconda: ``` conda env create -f deepilc.yml conda activate deepilc ``` - dflex ``` cd dflex pip install -e . ``` ## Training Running the following command to train rexquadrotor with VG-SAC. ``` python main.py --env-name rexquadrotor --jacobian --cuda ``` Use the following flags to train the model with different settings: ``` --env-name : {cartpole, acrobot, rexquadrotor, halfcheetah, hopper, DmcCheetah, DmcHopper} --jacobian : Train with approximate model jacobians --pretrain : Pretrain the model in the approximate model(default: False) --pretrain_jacobian : Pretrain the model in the approximate model with model jacobians (default: False) --zeroth : Train with zeroth order jacobians from the approximate model (default: False) ``` ## Citation If you find our paper or code is useful, please consider citing: ``` @inproceedings{ gurumurthy2023valuegradien, title={Deep Off-policy Iterative Learning Control}, author={Swaminathan Gurumurthy and J Zico Kolter and Zachary Manchester}, booktitle={5th Annual Learning for Dynamics {\&} Control Conference}, year={2023}, url={https://openreview.net/forum?id=Bi0E3lbvnU} } ``` ## Acknowledgements The code for the SAC implementation in the repo has been adapted from https://github.com/pranz24/pytorch-soft-actor-critic . The code for various environments used in the repo have been adapted from https://github.com/NVlabs/DiffRL, https://github.com/bjack205/BilinearControl.jl and https://github.com/sgillen/ssac
2,318
Markdown
38.982758
549
0.773512
RoboticExplorationLab/Deep-ILC/envs/cheetah.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from envs.dflex_env import DFlexEnv import math import torch import os import sys import copy sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import dflex as df import numpy as np np.set_printoptions(precision=5, linewidth=256, suppress=True) try: from pxr import Usd except ModuleNotFoundError: print("No pxr package") from env_utils import load_utils as lu from env_utils import torch_utils as tu class CheetahEnv(DFlexEnv): def __init__(self, render=False, device='cuda:0', num_envs=4096, seed=0, episode_length=1000, no_grad=True, stochastic_init=False, MM_caching_frequency = 1, early_termination = False, env_params=None): num_obs = 17 num_act = 6 num_envs = num_envs*(2*num_obs+2*num_act+1) self._max_episode_steps = episode_length super(CheetahEnv, self).__init__(num_envs, num_obs, num_act, episode_length, MM_caching_frequency, seed, no_grad, render, device) if env_params is None: self.env_params = {'density' : 1000.0, 'stiffness' : 0.0, 'damping' : 1.0, 'contact_ke': 2.e+4, 'contact_kd': 1.e+3, 'contact_kf': 1.e+3, 'contact_mu': 1., 'limit_ke' : 1.e+3, 'limit_kd' : 1.e+1, 'armature' : 0.1} else: self.env_params = env_params self.stochastic_init = stochastic_init self.early_termination = early_termination self.init_sim() # other parameters self.action_strength = 200.0 self.action_penalty = -0.1 #----------------------- # set up Usd renderer if (self.visualize): self.stage = Usd.Stage.CreateNew("outputs/" + "Cheetah_" + str(self.num_envs) + ".usd") self.renderer = df.render.UsdRenderer(self.model, self.stage) self.renderer.draw_points = True self.renderer.draw_springs = True self.renderer.draw_shapes = True self.render_time = 0.0 def init_sim(self): self.builder = df.sim.ModelBuilder() self.dt = 1.0/60.0 self.sim_substeps = 16 self.sim_dt = self.dt self.ground = True self.num_joint_q = 9 self.num_joint_qd = 9 self.x_unit_tensor = tu.to_torch([1, 0, 0], dtype=torch.float, device=self.device, requires_grad=False).repeat((self.num_envs, 1)) self.y_unit_tensor = tu.to_torch([0, 1, 0], dtype=torch.float, device=self.device, requires_grad=False).repeat((self.num_envs, 1)) self.z_unit_tensor = tu.to_torch([0, 0, 1], dtype=torch.float, device=self.device, requires_grad=False).repeat((self.num_envs, 1)) self.start_rotation = torch.tensor([0.], device = self.device, requires_grad = False) # initialize some data used later on # todo - switch to z-up self.up_vec = self.y_unit_tensor.clone() self.potentials = tu.to_torch([0.], device=self.device, requires_grad=False).repeat(self.num_envs) self.prev_potentials = self.potentials.clone() self.start_pos = [] self.start_joint_q = [0., 0., 0., 0., 0., 0.] self.start_joint_target = [0., 0., 0., 0., 0., 0.] start_height = -0.2 asset_folder = os.path.join(os.path.dirname(__file__), 'assets') for i in range(self.num_environments): link_start = len(self.builder.joint_type) lu.parse_mjcf(os.path.join(asset_folder, "half_cheetah.xml"), self.builder, density=self.env_params['density'],#1000.0, stiffness=self.env_params['stiffness'],#0.0, damping=self.env_params['damping'],#1.0, contact_ke=self.env_params['contact_ke'],#2.e+4, contact_kd=self.env_params['contact_kd'],#1.e+3, contact_kf=self.env_params['contact_kf'],#1.e+3, contact_mu=self.env_params['contact_mu'],#1., limit_ke=self.env_params['limit_ke'],#1.e+3, limit_kd=self.env_params['limit_kd'],#1.e+1, armature=self.env_params['armature'],#0.1, radians=True, load_stiffness=True) self.builder.joint_X_pj[link_start] = df.transform((0.0, 1.0, 0.0), df.quat_from_axis_angle((1.0, 0.0, 0.0), -math.pi*0.5)) # base transform self.start_pos.append([0.0, start_height]) # set joint targets to rest pose in mjcf self.builder.joint_q[i*self.num_joint_q + 3:i*self.num_joint_q + 9] = [0., 0., 0., 0., 0., 0.] self.builder.joint_target[i*self.num_joint_q + 3:i*self.num_joint_q + 9] = [0., 0., 0., 0., 0., 0.] self.start_pos = tu.to_torch(self.start_pos, device=self.device) self.start_joint_q = tu.to_torch(self.start_joint_q, device=self.device) self.start_joint_target = tu.to_torch(self.start_joint_target, device=self.device) # finalize model self.model = self.builder.finalize(self.device) self.model.ground = self.ground self.model.gravity = torch.tensor((0.0, -9.81, 0.0), dtype=torch.float32, device=self.device) self.integrator = df.sim.SemiImplicitIntegrator() self.state = self.model.state() if (self.model.ground): self.model.collide(self.state) def render(self, mode = 'human'): if self.visualize: self.render_time += self.dt self.renderer.update(self.state, self.render_time) render_interval = 1 if (self.num_frames == render_interval): try: self.stage.Save() except: print("USD save error") self.num_frames -= render_interval def step(self, actions): numpy_out = False if actions.dtype==np.float32 or action.dtype==np.float64: actions = torch.tensor(actions).to(self.obs_buf)#self.device) numpy_out = True actions = torch.stack([actions]*self.num_envs, dim=0) actions = actions.view((self.num_envs, self.num_actions)) actions = torch.clip(actions, -1., 1.) self.actions = actions.clone() self.state.joint_act.view(self.num_envs, -1)[:, 3:] = actions * self.action_strength self.state = self.integrator.forward(self.model, self.state, self.sim_dt, self.sim_substeps, self.MM_caching_frequency) self.sim_time += self.sim_dt self.reset_buf = torch.zeros_like(self.reset_buf) self.progress_buf += 1 self.num_frames += 1 self.calculateObservations() self.calculateReward() env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1) if self.no_grad == False: self.obs_buf_before_reset = self.obs_buf.clone() self.extras = { 'obs_before_reset': self.obs_buf_before_reset, 'episode_end': self.termination_buf, } self.extras['done_inf']= False if len(env_ids) > 0: self.reset(env_ids) self.render() if numpy_out: return self.obs_buf.detach().cpu().numpy()[0], self.rew_buf[0].item(), self.reset_buf[0].item(), self.extras return self.obs_buf[0], self.rew_buf[0], self.reset_buf[0], self.extras def stepx(self, obs, actions): num_envs = obs.shape[0] state_copy = self.copy_state() state_copy.joint_q = torch.cat([torch.zeros((num_envs,1)), obs[:, :8]], dim=-1).reshape(-1) state_copy.joint_qd = obs[:,8:].reshape(-1) actions = actions.view((num_envs, self.num_actions)) actions = torch.clip(actions, -1., 1.) state_copy.joint_act = torch.cat([torch.zeros((num_envs, 3)), actions * self.action_strength], dim=-1) state_copy = self.integrator.forward(self.model, state_copy, self.sim_dt, self.sim_substeps, self.MM_caching_frequency) obs_buf = self.calculateObservationsx(state_copy, num_envs) rew_buf = self.reward(obs_buf, actions) return obs_buf, rew_buf, self.reset_buf, self.extras def reset(self, env_ids = None, force_reset = True): if env_ids is None: if force_reset == True: env_ids = torch.arange(self.num_envs, dtype=torch.long, device=self.device) if env_ids is not None: # clone the state to avoid gradient error self.state.joint_q = self.state.joint_q.clone() self.state.joint_qd = self.state.joint_qd.clone() # fixed start state self.state.joint_q.view(self.num_envs, -1)[env_ids, 0:2] = self.start_pos[env_ids, :].clone() self.state.joint_q.view(self.num_envs, -1)[env_ids, 2] = self.start_rotation.clone() self.state.joint_q.view(self.num_envs, -1)[env_ids, 3:] = self.start_joint_q.clone() self.state.joint_qd.view(self.num_envs, -1)[env_ids, :] = 0. # randomization if self.stochastic_init: self.state.joint_q.view(self.num_envs, -1)[env_ids, 0:2] = self.state.joint_q.view(self.num_envs, -1)[env_ids, 0:2] + 0.1 * (torch.rand(size=(len(env_ids), 2), device=self.device) - 0.5) * 2. self.state.joint_q.view(self.num_envs, -1)[env_ids, 2] = (torch.rand(len(env_ids), device = self.device) - 0.5) * 0.2 self.state.joint_q.view(self.num_envs, -1)[env_ids, 3:] = self.state.joint_q.view(self.num_envs, -1)[env_ids, 3:] + 0.1 * (torch.rand(size=(len(env_ids), self.num_joint_q - 3), device = self.device) - 0.5) * 2. self.state.joint_qd.view(self.num_envs, -1)[env_ids, :] = 0.5 * (torch.rand(size=(len(env_ids), self.num_joint_qd), device=self.device) - 0.5) # clear action self.actions = self.actions.clone() self.actions[env_ids, :] = torch.zeros((len(env_ids), self.num_actions), device = self.device, dtype = torch.float) self.progress_buf[env_ids] = 0 self.calculateObservations() return self.obs_buf.detach().cpu().numpy()[0] ''' cut off the gradient from the current state to previous states ''' def clear_grad(self, checkpoint = None): with torch.no_grad(): if checkpoint is None: checkpoint = {} checkpoint['joint_q'] = self.state.joint_q.clone() checkpoint['joint_qd'] = self.state.joint_qd.clone() checkpoint['actions'] = self.actions.clone() checkpoint['progress_buf'] = self.progress_buf.clone() current_joint_q = checkpoint['joint_q'].clone() current_joint_qd = checkpoint['joint_qd'].clone() self.state = self.model.state() self.state.joint_q = current_joint_q self.state.joint_qd = current_joint_qd self.actions = checkpoint['actions'].clone() self.progress_buf = checkpoint['progress_buf'].clone() # self.state.joint_q.requires_grad_(True) # self.state.joint_qd.requires_grad_(True) ''' This function starts collecting a new trajectory from the current states but cuts off the computation graph to the previous states. It has to be called every time the algorithm starts an episode and it returns the observation vectors ''' def initialize_trajectory(self): self.clear_grad() self.calculateObservations() return self.obs_buf def copy_state(self): state = self.model.state() return state def get_checkpoint(self): checkpoint = {} checkpoint['joint_q'] = self.state.joint_q.clone() checkpoint['joint_qd'] = self.state.joint_qd.clone() checkpoint['actions'] = self.actions.clone() checkpoint['progress_buf'] = self.progress_buf.clone() return checkpoint def calculateObservations(self): self.obs_buf = torch.cat([self.state.joint_q.view(self.num_envs, -1)[:, 1:], self.state.joint_qd.view(self.num_envs, -1)], dim = -1) return self.obs_buf def calculateReward(self): progress_reward = self.obs_buf[:, 8] self.rew_buf = progress_reward + torch.sum(self.actions ** 2, dim = -1) * self.action_penalty # reset agents self.reset_buf = torch.where(self.progress_buf > self.episode_length - 1, torch.ones_like(self.reset_buf), self.reset_buf) def reward(self, state, action): progress_reward = state[:, 8] reward = progress_reward + torch.sum(action ** 2, dim = -1) * self.action_penalty return reward def calculateObservationsx(self, state, num_envs): obs_buf = torch.cat([state.joint_q.view(num_envs, -1)[:, 1:], state.joint_qd.view(num_envs, -1)], dim = -1) return obs_buf
13,510
Python
41.221875
226
0.582828
RoboticExplorationLab/Deep-ILC/envs/rex_quadrotor.py
import numpy as np import torch from utils import rk4, deg2rad, Spaces, Spaces_np, w2pdotkinematics_mrp, quat2mrp, euler_to_quaternion, mrp2quat, quatrot, mrp2rot import ipdb class RexQuadrotor: # think about mrp vs quat for various things - play with Q cost def __init__(self, mass=2.0, J=[[0.01566089, 0.00000318037, 0.0],[0.00000318037, 0.01562078, 0.0], [0.0, 0.0, 0.02226868]], gravity=[0,0,-9.81], motor_dist=0.28, kf=0.0244101, bf=-30.48576, km=0.00029958, bm=-0.367697, quad_min_throttle = 1148.0, quad_max_throttle = 1832.0, ned=False, cross_A_x=0.25, cross_A_y=0.25, cross_A_z=0.5, cd=[0.0, 0.0, 0.0], max_steps=100, dt=0.05, device=torch.device('cpu')): self.m = mass J = np.array(J) if len(J.shape) == 1: self.J = torch.diag(torch.FloatTensor(J)).unsqueeze(0).to(device) else: self.J = torch.FloatTensor(J).unsqueeze(0).to(device) self.Jinv = torch.linalg.inv(self.J).to(device) self.g = torch.FloatTensor(gravity).to(device).unsqueeze(0) self.motor_dist = motor_dist self.kf = kf self.km = km self.bf = bf self.bm = bm self.Bf = torch.zeros((1,3)).to(device) self.Bf[0,2] = 4*bf self.quad_min_throttle = quad_min_throttle self.quad_max_throttle = quad_max_throttle self.ned = ned self.cross_A_x = cross_A_x self.cross_A_y = cross_A_y self.cross_A_z = cross_A_z self.cross_A = torch.FloatTensor(np.array([cross_A_x, cross_A_y, cross_A_y])).to(device).unsqueeze(0) self.state_dim = 3 + 3*3 self.control_dim = 4 self._max_episode_steps = max_steps self.num_steps = 0 self.bsz = 1 self.dt = dt self.cd = torch.tensor(cd).unsqueeze(0).to(device) self.ss = torch.tensor([[1.,1,0], [1.,-1,0], [-1.,-1,0], [-1.,1,0]]).to(device).unsqueeze(0) self.ss = self.ss/self.ss.norm(dim=-1).unsqueeze(-1) self.Qlqr = torch.tensor([10.0]*3 + [10.0]*3 + [1.0]*6).to(device).unsqueeze(0) self.Rlqr = torch.tensor([1e-4]*self.control_dim).to(device).unsqueeze(0) self.observation_space = Spaces_np((self.state_dim,)) self.act_scale = 100.0 self.action_space = Spaces_np((self.control_dim,), np.array([18.3]*self.control_dim), np.array([11.5]*self.control_dim)) #12.0 self.device = device self.x_window = torch.tensor([5.0,5.0,5.0,deg2rad(70),deg2rad(70),deg2rad(70),0.5,0.5,0.5,0.25,0.25,0.25]).to(device) self.targ_pos = torch.zeros(self.state_dim) def forces(self, x, u): m = x[:, 3:6] q = mrp2quat(-m) F = torch.sum(self.kf*u, dim=-1) g = self.g F = torch.stack([torch.zeros_like(F), torch.zeros_like(F), F], dim=-1) df = -torch.sign(m)*0.5*1.27*(m*m)*self.cd*self.cross_A f = F + df + quatrot(q, self.m * g) + self.Bf return f def moments(self, x, u): L = self.motor_dist zeros = torch.zeros_like(u) F = torch.maximum(self.kf*u, zeros) M = self.km*u tau1 = zeros[:,0] tau2 = zeros[:,0] tau3 = M[:,0]-M[:,1]+M[:,2]-M[:,3] torque = torch.stack([tau1, tau2, tau3], dim=-1) ss = self.ss if self.ss.dtype != x.dtype: ss = self.ss.to(x) torque += torch.cross(self.motor_dist * ss, torch.stack([zeros, zeros, self.kf * u + self.bf], dim=-1), dim=-1).sum(dim=1) return torque def wrenches(self, x, u): F = self.forces(x, u) M = self.moments(x, u) return F, M def parse_state(self, x): r = x[:, :3] m = x[:, 3:6] # mrp2quat? v = x[:, 6:9] w = x[:, 9:] return r, m, v, w def dynamics(self, x, u): u = self.act_scale * u p, m, v, w = self.parse_state(x) # possibly do mrp2quat q = mrp2quat(m) F, tau = self.wrenches(x, u) mdot = w2pdotkinematics_mrp(m, w) pdot = quatrot(q, v) vdot = F/self.m - torch.cross(w, v) wdot = (self.Jinv*(tau - torch.cross(w, (self.J*(w.unsqueeze(1))).sum(dim=-1), dim=-1)).unsqueeze(1)).sum(dim=-1) return torch.cat([pdot, mdot, vdot, wdot], dim=-1) def step(self, u): self.num_steps += 1 done_inf = False if u.dtype == np.float64 or u.dtype == np.float32: u = torch.tensor(u).to(self.x) if len(u.shape)==1: u = u.unsqueeze(0) dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) reward = self.reward(self.x, u).cpu().numpy().squeeze() if torch.isnan(self.x).sum() or torch.isinf(self.x).sum() or np.isinf(reward) or np.isnan(reward) or reward < -500: x = self.reset() done_inf = True reward = 0 x_out = self.x.squeeze().detach().cpu().numpy() else: dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) reward = self.reward(self.x, u).cpu().numpy() if torch.isnan(self.x).sum() or torch.isinf(self.x).sum() or np.isinf(reward.sum()) or np.isnan(reward.sum()) or reward.sum() < -500: x = self.reset() done_inf = True reward = np.array([0.0]) x_out = self.x.detach().cpu().numpy() elif u.dtype == torch.float32 or u.dtype==torch.float64: dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) reward = self.reward(self.x, u) if torch.isnan(self.x).sum() or torch.isinf(self.x).sum() or torch.isinf(reward.sum()) or torch.isnan(reward.sum()) or reward.sum() < -500: x = self.reset() done_inf = True reward = torch.tensor([0.0]).to(self.x) x_out = self.x done = self.num_steps >= self._max_episode_steps or done_inf if np.isinf(reward) or np.isnan(reward): ipdb.set_trace() return x_out, reward, done, {'done_inf':done_inf} def stepx(self, x, u): done_inf = False if u.dtype == np.float64 or u.dtype == np.float32: u = torch.tensor(u).to(self.x) x = torch.tensor(x).to(self.x) if len(u.shape)==1: u = u.unsqueeze(0) x = x.unsqueeze(0) dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) reward = self.reward(x, u).cpu().numpy().squeeze() if torch.isnan(x).sum() or torch.isinf(x).sum(): self.reset() done_inf = True reward = -1000 x = self.x x_out = x.squeeze().detach().cpu().numpy() else: dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) reward = self.reward(x, u).cpu().numpy() if torch.isnan(x).sum() or torch.isinf(x).sum(): self.reset() done_inf = True reward = np.array([-1000]) x = self.x x_out = x.detach().cpu().numpy() elif u.dtype == torch.float32 or u.dtype==torch.float64: dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) reward = self.reward(x, u) if torch.isnan(x).sum() or torch.isinf(x).sum(): self.reset() done_inf = True reward = torch.tensor([-1000]).to(self.x) x = self.x x_out = x done = self.num_steps >= self._max_episode_steps or done_inf return x_out, reward, done, {'done_inf':done_inf} def reward(self, x, u): cost = (((x - self.targ_pos)**2)*self.Qlqr/2).sum(dim=-1)/100 + ((u**2)*self.Rlqr/2).sum(dim=-1)/10 mask = (cost > 500) rew = torch.exp(-cost/2+2) rew[mask] = -cost[mask] # if torch.isnan(rew).sum() or torch.isinf(rew).sum(): # ipdb.set_trace() return rew def reset_torch(self, bsz=None, x_window=None): self.num_steps = 0 if x_window is None: x_window = self.x_window elif len(x_window.shape) == 1: x_window = x_window.unsqueeze(0) if bsz is None: bsz = self.bsz self.x = (torch.rand((bsz, self.state_dim))*2-1)*self.x_window self.x = torch.cat([self.x[:,:3], quat2mrp(euler_to_quaternion(self.x[:, 3:6])), self.x[:, 6:]], dim=-1) #quat2mrp return self.x def reset(self, bsz=None, x_window=None): self.num_steps = 0 x = self.reset_torch(bsz, x_window).detach().cpu().numpy().squeeze() return x
9,049
Python
42.932039
151
0.511548
RoboticExplorationLab/Deep-ILC/envs/quadrotor.py
import numpy as np import torch from utils import rk4, deg2rad, Spaces, Spaces_np, w2pdotkinematics_mrp, quat2mrp, euler_to_quaternion, mrp2quat, quatrot import ipdb class Quadrotor: # think about mrp vs quat for various things - play with Q cost def __init__(self, mass=0.5, J=[0.0023, 0.0023, 0.004], gravity=[0,0,-9.81], motor_dist=0.1750, kf=1.0, km=0.0245, bodyframe=False, ned=False, cross_A_x=0.25, cross_A_y=0.25, cross_A_z=0.25, cd=[0.0, 0.0, 0.0], max_steps=100, dt=0.05, device=torch.device('cpu')): self.m = mass J = np.array(J) if len(J.shape) == 1: self.J = torch.diag(torch.FloatTensor(J)).unsqueeze(0).to(device) else: self.J = torch.FloatTensor(J).unsqueeze(0).to(device) self.Jinv = torch.linalg.inv(self.J).to(device) self.g = torch.tensor(gravity).to(device).unsqueeze(0) self.motor_dist = motor_dist self.kf = kf self.km = km self.bodyframe = bodyframe self.ned = ned self.cross_A_x = cross_A_x self.cross_A_y = cross_A_y self.cross_A_z = cross_A_z self.cross_A = torch.tensor(np.array([cross_A_x, cross_A_y, cross_A_y])).to(device).unsqueeze(0) self.state_dim = 3 + 3*3 self.control_dim = 4 self._max_episode_steps = max_steps self.num_steps = 0 self.bsz = 1 self.dt = dt self.cd = torch.tensor(cd).unsqueeze(0).to(device) self.Qlqr = torch.tensor([10.0]*3 + [10.0]*3 + [1.0]*6).to(device).unsqueeze(0) self.Rlqr = torch.tensor([1e-4]*self.control_dim).to(device).unsqueeze(0) self.observation_space = Spaces_np((self.state_dim,)) self.action_space = Spaces_np((self.control_dim,), np.array([12.0]*self.control_dim), np.array([0.0]*self.control_dim)) #12.0 self.device = device self.x_window = torch.tensor([5.0,5.0,5.0,deg2rad(70),deg2rad(70),deg2rad(70),1.0,1.0,1.0,0.5,0.5,0.5]).to(device) self.targ_pos = torch.zeros(self.state_dim) def forces(self, x, u): q = x[:, 3:7] F = torch.sum(torch.maximum(self.kf*u, torch.zeros_like(u)), dim=-1) g = self.g if self.ned: F = -F g = -g F = torch.stack([torch.zeros_like(F), torch.zeros_like(F), F], dim=-1) df = -torch.sign(x[:,3:6])*0.5*1.27*(x[:,3:6]**2)*self.cd*self.cross_A f = self.m*g + quatrot(q,F) + df # need to check q*F return f def moments(self, x, u): L = self.motor_dist F = torch.maximum(self.kf*u, torch.zeros_like(u)) M = self.km*u tau1 = L*(F[:,1]-F[:,3]) tau2 = L*(F[:,2]-F[:,0]) tau3 = M[:,0]-M[:,1]+M[:,2]-M[:,3] if self.ned: tau2 = -tau2 tau3 = -tau3 tau = torch.stack([tau1, tau2, tau3], dim=-1) return tau def wrenches(self, x, u): F = self.forces(x, u) M = self.moments(x, u) return F, M def parse_state(self, x): r = x[:, :3] m = x[:, 3:6] # mrp2quat? v = x[:, 6:9] w = x[:, 9:] return r, m, v, w def dynamics(self, x, u): r, m, v, w = self.parse_state(x) # possibly do mrp2quat q = mrp2quat(m) F, tau = self.wrenches(x, u) mdot = w2pdotkinematics_mrp(m, w) if self.bodyframe: xdot = quatrot(q, v) # quaternion multiplication (check!) vdot = quatrot(qinv(q), F/m) - torch.cross(w, v, dim=-1) else: xdot = v vdot = F/m ipdb.set_trace() wdot = (self.Jinv*(tau - torch.cross(w, (self.J*(w.unsqueeze(1))).sum(dim=-1), dim=-1)).unsqueeze(1)).sum(dim=-1) return torch.cat([xdot, mdot, vdot, wdot], dim=-1) def step(self, u): self.num_steps += 1 if u.dtype == np.float64 or u.dtype == np.float32: u = torch.tensor(u).to(self.x) if len(u.shape)==1: u = u.unsqueeze(0) dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) reward = self.reward(self.x, u).cpu().numpy().squeeze() x_out = self.x.squeeze().detach().cpu().numpy() else: dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) reward = self.reward(self.x, u).cpu().numpy() x_out = self.x.detach().cpu().numpy() elif u.dtype == torch.float32 or u.dtype==torch.float64: dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) reward = self.reward(self.x, u) x_out = self.x done = self.num_steps >= self._max_episode_steps return x_out, reward, done, {} def stepx(self, x, u): if u.dtype == np.float64 or u.dtype == np.float32: u = torch.tensor(u).to(self.x) x = torch.tensor(x).to(self.x) if len(u.shape)==1: u = u.unsqueeze(0) x = x.unsqueeze(0) dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) reward = self.reward(x, u).cpu().numpy().squeeze() x_out = x.squeeze().detach().cpu().numpy() else: dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) reward = self.reward(x, u).cpu().numpy() x_out = x.detach().cpu().numpy() elif u.dtype == torch.float32 or u.dtype==torch.float64: dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) reward = self.reward(x, u) x_out = x done = self.num_steps >= self._max_episode_steps return x_out, reward, done, {} def reward(self, x, u): cost = (((x - self.targ_pos)**2)*self.Qlqr/2).sum(dim=-1) + ((u**2)*self.Rlqr/2).sum(dim=-1) return -cost + 1 def reset_torch(self, bsz=None, x_window=None): self.num_steps = 0 if x_window is None: x_window = self.x_window elif len(x_window.shape) == 1: x_window = x_window.unsqueeze(0) if bsz is None: bsz = self.bsz self.x = (torch.rand((bsz, self.state_dim))*2-1)*self.x_window #+ self.targ_pos self.x = torch.cat([self.x[:,:3], quat2mrp(euler_to_quaternion(self.x[:, 3:6])), self.x[:, 6:]], dim=-1) #quat2mrp return self.x def reset(self, bsz=None, x_window=None): self.num_steps = 0 x = self.reset_torch(bsz, x_window).detach().cpu().numpy().squeeze() return x
6,732
Python
40.819876
267
0.521242
RoboticExplorationLab/Deep-ILC/envs/ant.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from envs.dflex_env import DFlexEnv import math import torch import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import ipdb import dflex as df import numpy as np np.set_printoptions(precision=5, linewidth=256, suppress=True) try: from pxr import Usd except ModuleNotFoundError: print("No pxr package") from env_utils import load_utils as lu from env_utils import torch_utils as tu class AntEnv(DFlexEnv): def __init__(self, render=False, device='cuda:0', num_envs=4096, seed=0, episode_length=1000, no_grad=True, stochastic_init=False, MM_caching_frequency = 1, early_termination = True): num_obs = 37 num_act = 8 num_envs = num_envs*(num_obs+1) self._max_episode_steps = episode_length super(AntEnv, self).__init__(num_envs, num_obs, num_act, episode_length, MM_caching_frequency, seed, no_grad, render, device) self.stochastic_init = stochastic_init self.early_termination = early_termination self.progress_buf_mask = torch.zeros_like(self.progress_buf) self.ep_lens = torch.zeros_like(self.progress_buf) + 10 self.init_sim() # other parameters self.termination_height = 0.27 self.action_strength = 200.0 self.action_penalty = 0.0 self.joint_vel_obs_scaling = 0.1 #----------------------- # set up Usd renderer if (self.visualize): self.stage = Usd.Stage.CreateNew("outputs/" + "Ant_" + str(self.num_envs) + ".usd") self.renderer = df.render.UsdRenderer(self.model, self.stage) self.renderer.draw_points = True self.renderer.draw_springs = True self.renderer.draw_shapes = True self.render_time = 0.0 def init_sim(self): self.builder = df.sim.ModelBuilder() self.dt = 1.0/60.0 self.sim_substeps = 16 self.sim_dt = self.dt self.ground = True self.num_joint_q = 15 self.num_joint_qd = 14 self.x_unit_tensor = tu.to_torch([1, 0, 0], dtype=torch.float, device=self.device, requires_grad=False).repeat((self.num_envs, 1)) self.y_unit_tensor = tu.to_torch([0, 1, 0], dtype=torch.float, device=self.device, requires_grad=False).repeat((self.num_envs, 1)) self.z_unit_tensor = tu.to_torch([0, 0, 1], dtype=torch.float, device=self.device, requires_grad=False).repeat((self.num_envs, 1)) self.start_rot = df.quat_from_axis_angle((1.0, 0.0, 0.0), -math.pi*0.5) self.start_rotation = tu.to_torch(self.start_rot, device=self.device, requires_grad=False) # initialize some data used later on # todo - switch to z-up self.up_vec = self.y_unit_tensor.clone() self.heading_vec = self.x_unit_tensor.clone() self.inv_start_rot = tu.quat_conjugate(self.start_rotation).repeat((self.num_envs, 1)) self.basis_vec0 = self.heading_vec.clone() self.basis_vec1 = self.up_vec.clone() self.targets = tu.to_torch([10000.0, 0.0, 0.0], device=self.device, requires_grad=False).repeat((self.num_envs, 1)) self.start_pos = [] self.start_joint_q = [0.0, 1.0, 0.0, -1.0, 0.0, -1.0, 0.0, 1.0] self.start_joint_target = [0.0, 1.0, 0.0, -1.0, 0.0, -1.0, 0.0, 1.0] if self.visualize: self.env_dist = 2.5 else: self.env_dist = 0. # set to zero for training for numerical consistency start_height = 0.75 asset_folder = os.path.join(os.path.dirname(__file__), 'assets') for i in range(self.num_environments): lu.parse_mjcf(os.path.join(asset_folder, "ant.xml"), self.builder, density=1000.0, stiffness=0.0, damping=1.0, contact_ke=4.e+4, contact_kd=1.e+4, contact_kf=3.e+3, contact_mu=0.75, limit_ke=1.e+3, limit_kd=1.e+1, armature=0.05) # base transform start_pos_z = i*self.env_dist self.start_pos.append([0.0, start_height, start_pos_z]) self.builder.joint_q[i*self.num_joint_q:i*self.num_joint_q + 3] = self.start_pos[-1] self.builder.joint_q[i*self.num_joint_q + 3:i*self.num_joint_q + 7] = self.start_rot # set joint targets to rest pose in mjcf self.builder.joint_q[i*self.num_joint_q + 7:i*self.num_joint_q + 15] = [0.0, 1.0, 0.0, -1.0, 0.0, -1.0, 0.0, 1.0] self.builder.joint_target[i*self.num_joint_q + 7:i*self.num_joint_q + 15] = [0.0, 1.0, 0.0, -1.0, 0.0, -1.0, 0.0, 1.0] self.start_pos = tu.to_torch(self.start_pos, device=self.device) self.start_joint_q = tu.to_torch(self.start_joint_q, device=self.device) self.start_joint_target = tu.to_torch(self.start_joint_target, device=self.device) # finalize model self.model = self.builder.finalize(self.device) self.model.ground = self.ground self.model.gravity = torch.tensor((0.0, -9.81, 0.0), dtype=torch.float32, device=self.device) self.integrator = df.sim.SemiImplicitIntegrator() self.state = self.model.state() if (self.model.ground): self.model.collide(self.state) def render(self, mode = 'human'): if self.visualize: self.render_time += self.dt self.renderer.update(self.state, self.render_time) render_interval = 1 if (self.num_frames == render_interval): try: self.stage.Save() except: print("USD save error") self.num_frames -= render_interval def step(self, actions, force_done_ids=None): numpy_out = False if actions.dtype==np.float32 or action.dtype==np.float64: actions = torch.tensor(actions).to(self.obs_buf)#self.device) numpy_out = True actions = torch.stack([actions]*self.num_envs, dim=0) actions = actions.view((self.num_envs, self.num_actions)) actions = torch.clip(actions, -1., 1.) self.actions = actions.clone() self.state.joint_act.view(self.num_envs, -1)[:, 6:] = actions * self.action_strength self.state = self.integrator.forward(self.model, self.state, self.sim_dt, self.sim_substeps, self.MM_caching_frequency) self.sim_time += self.sim_dt self.reset_buf = torch.zeros_like(self.reset_buf) self.progress_buf += 1 self.num_frames += 1 self.progress_buf_mask *= 0 self.calculateObservations() self.calculateReward() env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1) self.obs_buf_before_reset = self.obs_buf.clone() self.extras = { 'obs_before_reset': self.obs_buf_before_reset, 'episode_end': self.termination_buf } self.extras['done_inf']= False if len(env_ids) > 0: self.reset(env_ids) self.render() if numpy_out: return self.obs_buf.detach().cpu().numpy()[0], self.rew_buf[0].item(), self.reset_buf[0].item(), self.extras return self.obs_buf[0], self.rew_buf[0], self.reset_buf[0], self.extras def stepx(self, obs, actions): num_envs = obs.shape[0] state_copy = self.copy_state() state_copy.joint_q = torch.cat([torch.zeros((num_envs,1)), obs[:, :8]], dim=-1).reshape(-1) state_copy.joint_qd = obs[:,8:].reshape(-1) actions = actions.view((num_envs, self.num_actions)) actions = torch.clip(actions, -1., 1.) state_copy.joint_act = torch.cat([torch.zeros((num_envs, 3)), actions * self.action_strength], dim=-1) state_copy = self.integrator.forward(self.model, state_copy, self.sim_dt, self.sim_substeps, self.MM_caching_frequency) obs_buf = self.calculateObservationsx(state_copy, actions, num_envs) rew_buf = self.reward(obs_buf, actions) return obs_buf, rew_buf, self.reset_buf, self.extras def reset(self, env_ids = None, force_reset = True, eplenupdate=True): if env_ids is None: if force_reset == True: env_ids = torch.arange(self.num_envs, dtype=torch.long, device=self.device) if env_ids is not None: # clone the state to avoid gradient error self.state.joint_q = self.state.joint_q.clone().contiguous() self.state.joint_qd = self.state.joint_qd.clone().contiguous() # fixed start state self.state.joint_q.view(self.num_envs, -1)[env_ids, 0:3] = self.start_pos[env_ids, :].clone() self.state.joint_q.view(self.num_envs, -1)[env_ids, 3:7] = self.start_rotation.unsqueeze(0).expand(len(env_ids),-1).clone() self.state.joint_q.view(self.num_envs, -1)[env_ids, 7:] = self.start_joint_q.unsqueeze(0).expand(len(env_ids),-1).clone() self.state.joint_qd.view(self.num_envs, -1)[env_ids, :] = 0. # randomization if self.stochastic_init: self.state.joint_q.view(self.num_envs, -1)[env_ids, 0:3] = self.state.joint_q.view(self.num_envs, -1)[env_ids, 0:3] + 0.1 * (torch.rand(size=(len(env_ids), 3), device=self.device) - 0.5) * 2. angle = (torch.rand(len(env_ids), device = self.device) - 0.5) * np.pi / 12. axis = torch.nn.functional.normalize(torch.rand((len(env_ids), 3), device = self.device) - 0.5) self.state.joint_q.view(self.num_envs, -1)[env_ids, 3:7] = tu.quat_mul(self.state.joint_q.view(self.num_envs, -1)[env_ids, 3:7], tu.quat_from_angle_axis(angle, axis)) self.state.joint_q.view(self.num_envs, -1)[env_ids, 7:] = self.state.joint_q.view(self.num_envs, -1)[env_ids, 7:] + 0.2 * (torch.rand(size=(len(env_ids), self.num_joint_q - 7), device = self.device) - 0.5) * 2. self.state.joint_qd.view(self.num_envs, -1)[env_ids, :] = 0.5 * (torch.rand(size=(len(env_ids), 14), device=self.device) - 0.5) # clear action self.actions = self.actions.clone() self.actions[env_ids, :] = torch.zeros((len(env_ids), self.num_actions), device = self.device, dtype = torch.float) self.progress_buf_mask[env_ids] = self.progress_buf[env_ids].clone() if eplenupdate: self.ep_lens = torch.cat([self.progress_buf[env_ids].clone(), self.ep_lens], dim=0)[:200] self.progress_buf[env_ids] = 0 self.calculateObservations() return self.obs_buf.detach().cpu().numpy()[0] def copy_state(self): state = self.model.state() return state ''' cut off the gradient from the current state to previous states ''' def clear_grad(self, checkpoint = None): with torch.no_grad(): if checkpoint is None: checkpoint = {} checkpoint['joint_q'] = self.state.joint_q.clone() checkpoint['joint_qd'] = self.state.joint_qd.clone() checkpoint['actions'] = self.actions.clone() checkpoint['progress_buf'] = self.progress_buf.clone() current_joint_q = checkpoint['joint_q'].clone() current_joint_qd = checkpoint['joint_qd'].clone() self.state = self.model.state() self.state.joint_q = current_joint_q self.state.joint_qd = current_joint_qd self.actions = checkpoint['actions'].clone() self.progress_buf = checkpoint['progress_buf'].clone() self.state.joint_q.requires_grad_(True) self.state.joint_qd.requires_grad_(True) ''' This function starts collecting a new trajectory from the current states but cuts off the computation graph to the previous states. It has to be called every time the algorithm starts an episode and it returns the observation vectors ''' def initialize_trajectory(self): self.clear_grad() self.calculateObservations() return self.obs_buf def get_checkpoint(self): checkpoint = {} checkpoint['joint_q'] = self.state.joint_q.clone() checkpoint['joint_qd'] = self.state.joint_qd.clone() checkpoint['actions'] = self.actions.clone() checkpoint['progress_buf'] = self.progress_buf.clone() return checkpoint def calculateObservations(self, state=None, actions=None): update_self_obs = False if state is None: state = self.state actions = self.actions update_self_obs = True torso_pos = state.joint_q.view(self.num_envs, -1)[:, 0:3] torso_rot = state.joint_q.view(self.num_envs, -1)[:, 3:7] lin_vel = state.joint_qd.view(self.num_envs, -1)[:, 3:6] ang_vel = state.joint_qd.view(self.num_envs, -1)[:, 0:3] # convert the linear velocity of the torso from twist representation to the velocity of the center of mass in world frame lin_vel = lin_vel - torch.cross(torso_pos, ang_vel, dim = -1) to_target = self.targets + self.start_pos - torso_pos to_target[:, 1] = 0.0 target_dirs = tu.normalize(to_target) torso_quat = tu.quat_mul(torso_rot, self.inv_start_rot) up_vec = tu.quat_rotate(torso_quat, self.basis_vec1) heading_vec = tu.quat_rotate(torso_quat, self.basis_vec0) obs_buf = torch.cat([torso_pos[:, 1:2], # 0 torso_rot, # 1:5 lin_vel, # 5:8 ang_vel, # 8:11 state.joint_q.view(self.num_envs, -1)[:, 7:], # 11:19 self.joint_vel_obs_scaling * state.joint_qd.view(self.num_envs, -1)[:, 6:], # 19:27 up_vec[:, 1:2], # 27 (heading_vec * target_dirs).sum(dim = -1).unsqueeze(-1), # 28 actions.clone()], # 29:37 dim = -1) if update_self_obs: self.obs_buf = obs_buf return obs_buf def calculateReward(self): up_reward = 0.1 * self.obs_buf[:, 27] heading_reward = self.obs_buf[:, 28] height_reward = self.obs_buf[:, 0] - self.termination_height progress_reward = self.obs_buf[:, 5] self.rew_buf = progress_reward + up_reward + heading_reward + height_reward + torch.sum(self.actions ** 2, dim = -1) * self.action_penalty # reset agents if self.early_termination: self.reset_buf = torch.where(self.obs_buf[:, 0] < self.termination_height, torch.ones_like(self.reset_buf), self.reset_buf) self.reset_buf = torch.where(self.progress_buf > self.episode_length - 1, torch.ones_like(self.reset_buf), self.reset_buf) def reward(self, obs_buf, action): up_reward = 0.1 * obs_buf[:, 27] heading_reward = obs_buf[:, 28] height_reward = obs_buf[:, 0] - self.termination_height progress_reward = obs_buf[:, 5] rew_buf = progress_reward + up_reward + heading_reward + height_reward + torch.sum(action ** 2, dim = -1) * self.action_penalty return rew_buf def calculateObservationsx(self, state=None, actions=None, num_envs=1): update_self_obs = False bsz = actions.shape[0] torso_pos = state.joint_q.view(bsz, -1)[:, 0:3] torso_rot = state.joint_q.view(bsz, -1)[:, 3:7] lin_vel = state.joint_qd.view(bsz, -1)[:, 3:6] ang_vel = state.joint_qd.view(bsz, -1)[:, 0:3] # convert the linear velocity of the torso from twist representation to the velocity of the center of mass in world frame lin_vel = lin_vel - torch.cross(torso_pos, ang_vel, dim = -1) to_target = self.targets[:1] + self.start_pos[:1] - torso_pos to_target[:, 1] = 0.0 target_dirs = tu.normalize(to_target) torso_quat = tu.quat_mul(torso_rot, self.inv_start_rot[:1].expand(bsz, -1)) up_vec = tu.quat_rotate(torso_quat, self.basis_vec1[:1].expand(bsz, -1)) heading_vec = tu.quat_rotate(torso_quat, self.basis_vec0[:1].expand(bsz, -1)) obs_buf = torch.cat([torso_pos[:, 1:2], # 0 torso_rot, # 1:5 lin_vel, # 5:8 ang_vel, # 8:11 state.joint_q.view(bsz, -1)[:, 7:], # 11:19 self.joint_vel_obs_scaling * state.joint_qd.view(bsz, -1)[:, 6:], # 19:27 up_vec[:, 1:2], # 27 (heading_vec * target_dirs).sum(dim = -1).unsqueeze(-1), # 28 actions.clone()], # 29:37 dim = -1) return obs_buf
17,385
Python
41.928395
226
0.578315
RoboticExplorationLab/Deep-ILC/envs/cartpole.py
import numpy as np import torch from utils import rk4, deg2rad, Spaces, Spaces_np import ipdb class Cartpole: def __init__(self, mc=1.0, mp=0.2, l=0.5, g=9.81, b=0.01, sig=5, mu=0.0, deadband=0.0, u_max=np.inf, max_steps=50, dt = 0.05, targ_pos=torch.tensor([0,np.pi,0,0]), x_window=[1, deg2rad(180), 0.5, 0.5], device=torch.device('cpu')): self.mc = mc self.mp = mp self.l = l self.g = g self.b = b self.sig = sig self.mu = mu self.dt = dt self.deadband = deadband self.u_max = u_max self.state_dim = 4 self.control_dim = 1 self._max_episode_steps = max_steps self.num_steps = 0 self.bsz = 1 self.x_window = torch.tensor(x_window).to(device).unsqueeze(0) self.targ_pos = torch.tensor(targ_pos).to(device).unsqueeze(0) self.Qlqr = torch.tensor([0.2,2.0,1e-2,1e-2]).to(device).unsqueeze(0)/10 self.Rlqr = torch.tensor([1e-3]).to(device).unsqueeze(0) self.observation_space = Spaces_np((4,)) self.action_space = Spaces_np((1,), np.array([40.0]), np.array([-40.0])) self.term_rew = -10 self.clip_rew = -10 self.device = device def normalize_theta(self, x=None): if x is None: x = self.x theta = x[:, 1] + (-torch.div(x[:, 1], (2*np.pi), rounding_mode='trunc')*(2*np.pi) + (x[:,1]<0).float()*(2*np.pi)).detach() x[:, 1] = theta return x def step(self, u): self.num_steps += 1 done_inf = False if u.dtype == np.float64 or u.dtype == np.float32: u = torch.tensor(u).to(self.x) if len(u.shape)==1: u = u.unsqueeze(0) dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) self.normalize_theta() reward = self.reward(self.x, u).detach().cpu().numpy().squeeze() if reward < self.clip_rew: x = self.reset() done_inf = True x_out = self.x.squeeze().detach().cpu().numpy() else: dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) self.normalize_theta() reward = self.reward(self.x, u).cpu().numpy() if reward.sum() < self.clip_rew: x = self.reset() done_inf = True x_out = self.x.detach().cpu().numpy() elif u.dtype == torch.float32 or u.dtype==torch.float64: dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) self.normalize_theta() reward = self.reward(self.x, u) if reward.sum() < self.clip_rew: x = self.reset() done_inf = True x_out = self.x done = self.num_steps >= self._max_episode_steps or done_inf return x_out, reward, done, {'done_inf':done_inf} def stepx(self, x, u): if u.dtype == np.float64 or u.dtype == np.float32: u = torch.tensor(u).to(self.x) x = torch.tensor(x).to(self.x) if len(u.shape)==1: u = u.unsqueeze(0) x = x.unsqueeze(0) dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) x = self.normalize_theta(x) reward = self.reward(x, u).cpu().numpy().squeeze() x_out = x.squeeze().detach().cpu().numpy() else: dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) x = self.normalize_theta(x) reward = self.reward(x, u).cpu().numpy() x_out = x.detach().cpu().numpy() elif u.dtype == torch.float32 or u.dtype==torch.float64: dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) x = self.normalize_theta(x) reward = self.reward(x, u) x_out = x done = self.num_steps >= self._max_episode_steps return x_out, reward, done, {'done_inf':False} def dynamics(self, x, u): mc = self.mc # mass of the cart in kg (10) mp = self.mp # mass of the pole (point mass at the end) in kg l = self.l # length of the pole in m g = self.g # gravity m/s^2 q = x[:,:2] qd = x[:,2:4] s = torch.sin(q[:,1]) c = torch.cos(q[:,1]) ones = torch.ones_like(c) zeros = torch.zeros_like(c) H = torch.stack([ torch.stack([(mc+mp)*ones, mp*l*c], dim=-1), torch.stack([mp*l*c, mp*l*l*ones], dim=-1)], dim=1) C = torch.stack([ torch.stack([zeros, -mp*qd[:,1]*l*s], dim=-1), torch.stack([zeros, zeros], dim=-1)], dim=1) G = torch.stack([zeros, mp*g*l*s], dim=-1) B = torch.stack([ones, zeros], dim=-1) # Friction Fn = (mc + mp) * g # normal force (approximate) sig = self.sig mu = self.mu cart_friction = torch.tanh(sig * qd[:,0]) * mu * Fn # approximate coloumb friction viscous_friction = self.b * qd # viscous friction friction = torch.stack([cart_friction + viscous_friction[:,0], viscous_friction[:,1]], dim=-1) # Control deadband = self.deadband u_max = self.u_max u_true = torch.sign(u)*torch.clamp(u.abs(), deadband, u_max) qdd = -(torch.linalg.inv(H)*((C*qd.unsqueeze(1)).sum(dim=-1) + G + friction - B*u_true[:,:1]).unsqueeze(1)).sum(dim=-1) return torch.cat([qd, qdd], dim=-1) def reward(self, x, u): err_state = (x - self.targ_pos) theta = err_state[:, 1] + (-torch.div(err_state[:, 1], (2*np.pi), rounding_mode='trunc')*(2*np.pi) + (err_state[:,1]<0).float()*(2*np.pi)).detach() # Look at the shortest path to the desired state i.e. desired angle mask = (theta > np.pi).float() theta = (1-mask)*theta + mask*(theta - 2*np.pi) err_state = torch.stack([err_state[:, 0], theta, err_state[:, 2], err_state[:, 3]], dim=1) cost = torch.sum(err_state * self.Qlqr * err_state, dim=1) #+ torch.sum(u * 1.0e-3 * u, dim=1) return -cost + 1 def reset_torch(self, bsz=None, x_window=None): self.num_steps = 0 if x_window is None: x_window = self.x_window elif len(x_window.shape) == 1: x_window = x_window.unsqueeze(0) if bsz is None: bsz = self.bsz self.x = (torch.rand((bsz, self.state_dim))*2-1)*x_window + self.targ_pos return self.x def reset(self, bsz=None, x_window=None): self.num_steps = 0 x = self.reset_torch(bsz, x_window).detach().cpu().numpy().squeeze() return x
6,981
Python
40.808383
234
0.506518
RoboticExplorationLab/Deep-ILC/envs/dflex_env.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import numpy as np import torch import dflex as df import xml.etree.ElementTree as ET from gym import spaces class DFlexEnv: def __init__(self, num_envs, num_obs, num_act, episode_length, MM_caching_frequency = 1, seed=0, no_grad=True, render=False, device='cuda:0'): self.seed = seed self.no_grad = no_grad df.config.no_grad = self.no_grad self.episode_length = episode_length self.device = device self.visualize = render self.sim_time = 0.0 self.num_frames = 0 # record the number of frames for rendering self.num_environments = num_envs self.num_agents = 1 self.MM_caching_frequency = MM_caching_frequency # initialize observation and action space self.num_observations = num_obs self.num_actions = num_act self.obs_space = spaces.Box(np.ones(self.num_observations) * -np.Inf, np.ones(self.num_observations) * np.Inf) self.act_space = spaces.Box(np.ones(self.num_actions) * -1., np.ones(self.num_actions) * 1.) # allocate buffers self.obs_buf = torch.zeros( (self.num_envs, self.num_observations), device=self.device, dtype=torch.float, requires_grad=False) self.rew_buf = torch.zeros( self.num_envs, device=self.device, dtype=torch.float, requires_grad=False) self.reset_buf = torch.ones( self.num_envs, device=self.device, dtype=torch.long, requires_grad=False) # end of the episode self.termination_buf = torch.zeros( self.num_envs, device=self.device, dtype=torch.long, requires_grad=False) self.progress_buf = torch.zeros( self.num_envs, device=self.device, dtype=torch.long, requires_grad=False) self.actions = torch.zeros( (self.num_envs, self.num_actions), device = self.device, dtype = torch.float, requires_grad = False) self.extras = {} def get_number_of_agents(self): return self.num_agents @property def observation_space(self): return self.obs_space @property def action_space(self): return self.act_space @property def num_envs(self): return self.num_environments @property def num_acts(self): return self.num_actions @property def num_obs(self): return self.num_observations def get_state(self): return self.state.joint_q.clone(), self.state.joint_qd.clone() def reset_with_state(self, init_joint_q, init_joint_qd, env_ids=None, force_reset=True): if env_ids is None: if force_reset == True: env_ids = torch.arange(self.num_envs, dtype=torch.long, device=self.device) if env_ids is not None: # fixed start state self.state.joint_q = self.state.joint_q.clone() self.state.joint_qd = self.state.joint_qd.clone() self.state.joint_q.view(self.num_envs, -1)[env_ids, :] = init_joint_q.view(-1, self.num_joint_q)[env_ids, :].clone() self.state.joint_qd.view(self.num_envs, -1)[env_ids, :] = init_joint_qd.view(-1, self.num_joint_qd)[env_ids, :].clone() self.progress_buf[env_ids] = 0 self.calculateObservations() return self.obs_buf
3,847
Python
33.981818
146
0.641799
RoboticExplorationLab/Deep-ILC/envs/acrobot.py
import numpy as np import torch import math from numpy import sin, cos, pi import ipdb from matplotlib import pyplot as plt from utils import * class AcrobotEnv(torch.nn.Module): """ Acrobot is a 2-link pendulum with only the second joint actuated. Initially, both links point downwards. The goal is to swing the end-effector at a height at least the length of one link above the base. Both links can swing freely and can pass by each other, i.e., they don't collide when they have the same angle. **STATE:** The state consists of the sin() and cos() of the two rotational joint angles and the joint angular velocities : [cos(theta1) sin(theta1) cos(theta2) sin(theta2) thetaDot1 thetaDot2]. For the first link, an angle of 0 corresponds to the link pointing downwards. The angle of the second link is relative to the angle of the first link. An angle of 0 corresponds to having the same angle between the two links. A state of [1, 0, 1, 0, ..., ...] means that both links point downwards. **ACTIONS:** The action is either applying +1, 0 or -1 torque on the joint between the two pendulum links. .. note:: The dynamics equations were missing some terms in the NIPS paper which are present in the book. R. Sutton confirmed in personal correspondence that the experimental results shown in the paper and the book were generated with the equations shown in the book. However, there is the option to run the domain with the paper equations by setting book_or_nips = 'nips' **REFERENCE:** .. seealso:: R. Sutton: Generalization in Reinforcement Learning: Successful Examples Using Sparse Coarse Coding (NIPS 1996) .. seealso:: R. Sutton and A. G. Barto: Reinforcement learning: An introduction. Cambridge: MIT press, 1998. .. warning:: This version of the domain uses the Runge-Kutta method for integrating the system dynamics and is more realistic, but also considerably harder than the original version which employs Euler integration, see the AcrobotLegacy class. """ metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": 15} # dt = 0.05 # dt = 0.01 MAX_VEL_1 = 4 * pi MAX_VEL_2 = 9 * pi AVAIL_TORQUE = torch.tensor([-1.0, 0.0, +1]) torque_noise_max = 0.0 #: use dynamics equations from the nips paper or the book book_or_nips = "book" action_arrow = None domain_fig = None actions_num = 1 num_obs = 4 num_act = 1 def __init__(self, batch_size=64, device=torch.device('cpu'), continuous=True, dt=0.01, T=400, l1=1.0, m1=1.0): super().__init__() self.viewer = None high = np.array( [1.0, 1.0, 1.0, 1.0, self.MAX_VEL_1, self.MAX_VEL_2], dtype=np.float32 ) low = -high self.continuous = continuous self.actions_disc = torch.arange(-6,7,3.0).unsqueeze(-1).to(device) self.state = None self.device = device self.bsz = self.batch_size = batch_size self.gs = torch.zeros((1,4)).to(device) self.gs[0,0] += np.pi/2 self.init_state = torch.zeros((1,4)).to(device) self.init_state[0,0] -= np.pi/2 self.observation_space = Spaces_np((4,)) self.action_space = Spaces_np((1,), np.array([25,]), np.array([-25,])) self.env_name = 'acrobot_' self.action_coeffs = 0.05 self.dt = dt self.num_steps = 0 self.T = T self.LINK_LENGTH_1 = l1 # [m] self.LINK_LENGTH_2 = 1.0 # [m] self.LINK_MASS_1 = m1 #: [kg] mass of link 1 self.LINK_MASS_2 = 1.0 #: [kg] mass of link 2 self.LINK_COM_POS_1 = 0.5 #: [m] position of the center of mass of link 1 self.LINK_COM_POS_2 = 0.5 #: [m] position of the center of mass of link 2 self.LINK_MOI = 1.0 #: moments of inertia for both links self.LINK_i1=.2 self.LINK_i2=.8 self.normalize = True self.x_window = torch.tensor([np.pi, np.pi, self.MAX_VEL_1/4, self.MAX_VEL_2/9]).unsqueeze(0).to(self.device) self.state_dim = self.num_obs self.control_dim = self.num_act self._max_episode_steps = T self.term_rew = 0.0 def step(self, u): self.num_steps += 1 num_steps_rew = self.term_rew done_inf = False if u.dtype == np.float64 or u.dtype == np.float32: u = torch.tensor(u).to(self.x) if len(u.shape)==1: u = u.unsqueeze(0) dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) self.x = self.postprocess_state(self.x) reward = self.reward(self.x, u).cpu().numpy().squeeze() if (-torch.cos(self.x[:, 0]) - torch.cos(self.x[:, 1] + self.x[:, 0])).item() > 1.0: x = self.reset() done_inf = True reward = -self.term_rew# np.minimum(reward, -num_steps_rew) x_out = self.x.squeeze().detach().cpu().numpy() else: dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) self.x = self.postprocess_state(self.x) reward = self.reward(self.x, u).cpu().numpy() if (-torch.cos(self.x[:, 0]) - torch.cos(self.x[:, 1] + self.x[:, 0])).item() > 1.0: x = self.reset() done_inf = True reward = np.array([-self.term_rew]) x_out = self.x.detach().cpu().numpy() elif u.dtype == torch.float32 or u.dtype==torch.float64: dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) self.x = self.postprocess_state(self.x) reward = self.reward(self.x, u) if (-torch.cos(self.x[:, 0]) - torch.cos(self.x[:, 1] + self.x[:, 0])).item() > 1.0: x = self.reset() done_inf = True reward = torch.tensor([-self.term_rew]).to(self.x) x_out = self.x done_inf = done = self.num_steps >= self._max_episode_steps or done_inf if np.isinf(reward) or np.isnan(reward): ipdb.set_trace() return x_out, reward, done, {'done_inf':done_inf} def stepx(self, x, u): done_inf = False if u.dtype == np.float64 or u.dtype == np.float32: u = torch.tensor(u).to(self.x) x = torch.tensor(x).to(self.x) if len(u.shape)==1: u = u.unsqueeze(0) x = x.unsqueeze(0) dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) reward = self.reward(x, u).cpu().numpy().squeeze() x_out = x.squeeze().detach().cpu().numpy() else: dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) reward = self.reward(x, u).cpu().numpy() x_out = x.detach().cpu().numpy() elif u.dtype == torch.float32 or u.dtype==torch.float64: dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) reward = self.reward(x, u) x_out = x done_inf = done = self.num_steps >= self._max_episode_steps or done_inf return x_out, reward, done, {'done_inf':done_inf} def postprocess_state(self, ns): if self.normalize: ns_th0 = angle_normalize(ns[:, 0], 0, 2*math.pi) ns_th1 = angle_normalize(ns[:, 1], -math.pi, math.pi) else: ns_th0 = ns[:, 0] ns_th1 = ns[:, 1] ns_vel2 = torch.clamp(ns[:, 2], -self.MAX_VEL_1, self.MAX_VEL_1) ns_vel3 = torch.clamp(ns[:, 3], -self.MAX_VEL_2, self.MAX_VEL_2) ns = torch.stack([ns_th0, ns_th1, ns_vel2, ns_vel3], dim=1) return ns def reward(self, ns, u): reward = torch.sin(ns[:, 0]) + torch.sin(ns[:, 0] + ns[:, 1]) return reward def reset_torch(self, bsz=None, x_window=None): self.num_steps = 0 if x_window is None: x_window = self.x_window elif len(x_window.shape) == 1: x_window = x_window.unsqueeze(0) if bsz is None: bsz = self.bsz self.x = (torch.rand((bsz, 4))*2-1).to(self.device)*x_window self.x[:, 0] += np.pi return self.x def reset(self, bsz=None, x_window=None): self.num_steps = 0 x = self.reset_torch(bsz, x_window).detach().cpu().numpy().squeeze() return x def _get_obs(self): s = self.state return np.array( [cos(s[0]), sin(s[0]), cos(s[1]), sin(s[1]), s[2], s[3]], dtype=np.float32 ) def dynamics(self, x, u): m1 = self.LINK_MASS_1 m2 = self.LINK_MASS_2 l1 = self.LINK_LENGTH_1 lc1 = self.LINK_COM_POS_1 lc2 = self.LINK_COM_POS_2 i1 = self.LINK_i1 i2 = self.LINK_i2 g = 9.8 s0 = x act = u tau = act[:,0] th1 = s0[:, 0] th2 = s0[:, 1] th1d = s0[:, 2] th2d = s0[:, 3] g = 9.8 TAU = torch.stack([torch.zeros_like(tau),tau], dim=1).unsqueeze(-1) m11 = m1*lc1**2 + m2*(l1**2 + lc2**2 + 2*l1*lc2*torch.cos(th2)) + i1 + i2 m22 = m2*lc2**2 + i2 m12 = m2*(lc2**2 + l1*lc2*torch.cos(th2)) + i2 M = torch.stack([torch.stack([m11, m12], dim=-1), torch.stack([m12, m22*torch.ones_like(m12)], dim=-1)], dim=-2) # print("1:M:", M) h1 = -m2*l1*lc2*torch.sin(th2)*th2d**2 - 2*m2*l1*lc2*torch.sin(th2)*th2d*th1d h2 = m2*l1*lc2*torch.sin(th2)*th1d**2 H = torch.stack([h1,h2],dim=-1).unsqueeze(-1) # print("1:H:", H) phi1 = (m1*lc1+m2*l1)*g*torch.cos(th1) + m2*lc2*g*torch.cos(th1+th2) phi2 = m2*lc2*g*torch.cos(th1+th2) PHI = torch.stack([phi1, phi2], dim=-1).unsqueeze(-1) # print("1:PHI:", PHI) d2th = torch.linalg.solve(M,(TAU - H - PHI)).squeeze(-1) # print("1:d2th:", d2th) return torch.stack([th1d, th2d, d2th[:,0], d2th[:,1]], dim=1) def get_frame(self, s, ax=None): p1 = [-self.LINK_LENGTH_1 * cos(s[0]), self.LINK_LENGTH_1 * sin(s[0])] p2 = [ p1[0] - self.LINK_LENGTH_2 * cos(s[0] + s[1]), p1[1] + self.LINK_LENGTH_2 * sin(s[0] + s[1]), ] bound = self.LINK_LENGTH_1 + self.LINK_LENGTH_2 + 0.2 if ax is None: fig, ax = plt.subplots(figsize=(2*bound,2*bound)) else: fig = ax.get_figure() ax.plot((0,p1[0]), (0, p1[1]), color='k') ax.plot((p1[0],p2[0]), (p1[1], p2[1]), color='k') ax.set_xlim((-bound*1.1, bound*1.1)) ax.set_ylim((-bound*1.1, bound*1.1)) return fig, ax def render(self, mode="human"): from gym.envs.classic_control import rendering s = self.state if self.viewer is None: self.viewer = rendering.Viewer(500, 500) bound = self.LINK_LENGTH_1 + self.LINK_LENGTH_2 + 0.2 # 2.2 for default self.viewer.set_bounds(-bound, bound, -bound, bound) if s is None: return None p1 = [-self.LINK_LENGTH_1 * cos(s[0]), self.LINK_LENGTH_1 * sin(s[0])] p2 = [ p1[0] - self.LINK_LENGTH_2 * cos(s[0] + s[1]), p1[1] + self.LINK_LENGTH_2 * sin(s[0] + s[1]), ] xys = np.array([[0, 0], p1, p2])[:, ::-1] thetas = [s[0] - pi / 2, s[0] + s[1] - pi / 2] link_lengths = [self.LINK_LENGTH_1, self.LINK_LENGTH_2] self.viewer.draw_line((-2.2, 1), (2.2, 1)) for ((x, y), th, llen) in zip(xys, thetas, link_lengths): l, r, t, b = 0, llen, 0.1, -0.1 jtransform = rendering.Transform(rotation=th, translation=(x, y)) link = self.viewer.draw_polygon([(l, b), (l, t), (r, t), (r, b)]) link.add_attr(jtransform) link.set_color(0, 0.8, 0.8) circ = self.viewer.draw_circle(0.1) circ.set_color(0.8, 0.8, 0) circ.add_attr(jtransform) return self.viewer.render(return_rgb_array=mode == "rgb_array")
12,445
Python
38.015674
120
0.534914
RoboticExplorationLab/Deep-ILC/envs/airplane.py
import numpy as np import torch from utils import rk4, deg2rad, Spaces, Spaces_np, mrp2rot, Polynomial, arotate, brotate, w2pdotkinematics_mrp import ipdb class YakPlane: # reset, action limits (probably in dynamics 0-255), cost weights # check input/output against julia version # also check jacobians/gradients # finite horizon task with quadratic objective? # need an objective that only has gradients zero at origin or optimum # early termination -1000 reward -> # correct termination -> 0 value -> very good # but might incentivise bad behavior ? # maybe better to not mask terminal state? # might be a good idea to try both! # other vals for term rew # sample along trajectory? # autotuning, reduce alpha etc. # fake jacaobian # might need huber loss etc.. # other rewards for tracking? # only compute rew on position # problem is that we need a supervised target at the end - # problem is definitely with the reward/state rep/ def __init__(self, g=9.81, rho=1.2, m=0.075, J=[4.8944e-04, 6.3778e-04, 7.9509e-04], Jm=.007*(.0075**2) + .002*(.14**2)/12, b=45/100, l_in=6/100, cr=13.5/100, ct=8/100, ep_ail=0.63, trim_ail=106, g_ail=(15*np.pi/180)/100, b_elev =16/100, cr_elev=6/100, ct_elev=4/100, r_elev=22/100, ep_elev = 0.88, #flap effectiveness (Phillips P.41) trim_elev = 106, #control input for zero deflection g_elev = (20*np.pi/180)/100, #maps control input to deflection angle b_rud = 10.5/100, cr_rud = 7/100, ct_rud = 3.5/100, r_rud = 24/100, #rudder moment arm (m) z_rud = 2/100, #height of rudder center of pressure (m) ep_rud = 0.76, #flap effectiveness (Phillips P.41) trim_rud = 106, #control input for zero deflection g_rud = (35*np.pi/180)/100, #maps from control input to deflection angle trim_thr = 24, #control input for zero thrust (deadband) g_thr = 0.006763, #maps control input to Newtons of thrust g_mot = 3000*2*np.pi/60*7/255, lin=False, dt = 0.05, max_steps = 50, device=torch.device('cpu'), dtype=torch.float): #maps control input to motor rad/sec # , device=torch.device('cpu')): self.g = g self.rho = rho self.m = m J = torch.tensor(J).to(device).to(dtype) self.J = torch.diag(J).unsqueeze(0) self.Jinv = torch.diag(1/J).unsqueeze(0) self.Jm = Jm self.b = b self.l_in = l_in self.cr = cr self.ct = ct self.cm = (ct + cr)/2 self.S = b*self.cm self.S_in = 2*l_in*cr self.S_out = self.S-self.S_in self.Rt = ct/cr self.r_ail = (b/6)*(1+2*self.Rt)/(1+self.Rt) self.ep_ail = ep_ail self.trim_ail = trim_ail self.g_ail = g_ail self.b_elev = b_elev self.cr_elev = cr_elev self.ct_elev = ct_elev self.cm_elev = (ct_elev + cr_elev)/2 #mean elevator chord (m) self.S_elev = self.b_elev*self.cm_elev #planform area of elevator (m^2) self.Ra_elev = (self.b_elev**2)/self.S_elev #wing aspect ratio (dimensionless) self.r_elev = r_elev self.ep_elev = ep_elev self.trim_elev = trim_elev self.g_elev = g_elev self.b_rud = b_rud self.cr_rud = cr_rud self.ct_rud = ct_rud self.cm_rud = (ct_rud + cr_rud)/2 #mean rudder chord (m) self.S_rud = b_rud*self.cm_rud #planform area of rudder (m^2) self.Ra_rud = (b_rud**2)/self.S_rud #wing aspect ratio (dimensionless) self.r_rud = r_rud self.z_rud = z_rud self.ep_rud = ep_rud self.trim_rud = trim_rud self.g_rud = g_rud self.trim_thr = trim_thr self.g_thr = g_thr self.g_mot = g_mot self.lin = lin self.r_ailvec = torch.tensor([0, self.r_ail, 0]).to(device).unsqueeze(0).to(dtype) self.l_invec = torch.tensor([0, self.l_in, 0]).to(device).unsqueeze(0).to(dtype) self.r_elevvec = torch.tensor([-self.r_elev, 0, 0]).to(device).unsqueeze(0).to(dtype) self.rudvec = torch.tensor([-self.r_rud, 0, -self.z_rud]).to(device).unsqueeze(0).to(dtype) self.state_dim = 12 self.control_dim = 4 self._max_episode_steps = max_steps self.num_steps = 0 self.bsz = 1 # Initial condition p0 = [0.997156, 0., 0.075366] # initial orientation x0 = torch.tensor([-5,0,1.5]+ p0 + [5,0,0] + [0,0,0]).to(device).unsqueeze(0).to(dtype) self.x0 = x0 # Final condition xf = x0.clone() pf = torch.tensor([5,0,1.5]).to(device).to(dtype) xf[0,:3] = pf xf[:, 6] = 0.0 self.targ_pos = xf.to(dtype) x_window = [0.5]*3 self.x_window = torch.tensor(x_window).to(device).unsqueeze(0).to(dtype) self.Qlqr = torch.tensor([1.0]*3 + [0.2]*3 + [0.1]*3 + [0.2]*3).to(device).unsqueeze(0).to(dtype) self.Rlqr = torch.tensor([1e-4]*self.control_dim).to(device).unsqueeze(0).to(dtype) self.observation_space = Spaces_np((self.state_dim,)) self.action_space = Spaces_np((self.control_dim,), np.array([255.0]*self.control_dim), np.array([0.0]*self.control_dim)) self.device = device self.dt = dt self.clip_rew = -50 self.term_rew = 0#200 self.ref_traj = torch.tensor(np.load('../BilinearControl.jl/data/airplane_ref.npy')) def step(self, u): self.num_steps += 1 done_inf = False if u.dtype == np.float64 or u.dtype == np.float32: u = torch.tensor(u).to(self.x) if len(u.shape)==1: u = u.unsqueeze(0) dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) reward = self.reward(self.x, u).cpu().numpy().squeeze() if torch.isnan(self.x).sum() or torch.isinf(self.x).sum() or np.isinf(reward) or np.isnan(reward) or reward < self.clip_rew: x = self.reset() done_inf = True reward = -self.term_rew x_out = self.x.squeeze().detach().cpu().numpy() else: dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) reward = self.reward(self.x, u).cpu().numpy() if torch.isnan(self.x).sum() or torch.isinf(self.x).sum() or np.isinf(reward.sum()) or np.isnan(reward.sum()) or reward.sum() < self.clip_rew: x = self.reset() done_inf = True reward = np.array([-self.term_rew]) x_out = self.x.detach().cpu().numpy() elif u.dtype == torch.float32 or u.dtype==torch.float64: dynamics = lambda y: self.dynamics(y, u) self.x = rk4(dynamics, self.x, [0, self.dt]) reward = self.reward(self.x, u) if torch.isnan(self.x).sum() or torch.isinf(self.x).sum() or torch.isinf(reward.sum()) or torch.isnan(reward.sum()) or reward.sum() < self.clip_rew: x = self.reset() done_inf = True reward = torch.tensor([-self.term_rew]).to(self.x) x_out = self.x done_inf = done = self.num_steps >= self._max_episode_steps or done_inf if np.isinf(reward) or np.isnan(reward): ipdb.set_trace() return x_out, reward, done, {'done_inf':done_inf} def stepx(self, x, u): done_inf = False if u.dtype == np.float64 or u.dtype == np.float32: u = torch.tensor(u).to(self.x) x = torch.tensor(x).to(self.x) if len(u.shape)==1: u = u.unsqueeze(0) x = x.unsqueeze(0) dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) reward = self.reward(x, u).cpu().numpy().squeeze() if torch.isnan(x).sum() or torch.isinf(x).sum(): self.reset() done_inf = True reward = -self.term_rew x = self.x x_out = x.squeeze().detach().cpu().numpy() else: dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) reward = self.reward(x, u).cpu().numpy() if torch.isnan(x).sum() or torch.isinf(x).sum(): self.reset() done_inf = True reward = np.array([-self.term_rew]) x = self.x x_out = x.detach().cpu().numpy() elif u.dtype == torch.float32 or u.dtype==torch.float64: dynamics = lambda y: self.dynamics(y, u) x = rk4(dynamics, x, [0, self.dt]) reward = self.reward(x, u) if torch.isnan(x).sum() or torch.isinf(x).sum(): self.reset() done_inf = True reward = torch.tensor([-self.term_rew]).to(self.x) x = self.x x_out = x done_inf = done = self.num_steps >= self._max_episode_steps or done_inf return x_out, reward, done, {'done_inf':done_inf} def propwash(self, thr): if not self.lin: zeros = torch.zeros_like(thr) trim_thr = 24; # control input for zero thrust (deadband) thr_mask = thr > trim_thr v = torch.stack([5.568*(thr**0.199) - 8.859, zeros, zeros], dim=-1)*(thr_mask).float() else: zeros = torch.zeros_like(thr) v = torch.stack([0.06*thr, zeros, zeros], dim=-1) return v def dynamics(self, x, u): r = x[:,:3] q = x[:,3:6] v = x[:,6:9] w = x[:,9:] Q = mrp2rot(q) # control input thr = u[:,0]; #Throttle command (0-255 as sent to RC controller) ail = u[:,1]; #Aileron command (0-255 as sent to RC controller) elev = u[:,2]; #Elevator command (0-255 as sent to RC controller) rud = u[:,3]; #Rudder command (0-255 as sent to RC controller) #Note that body coordinate frame is: # x: points forward out nose # y: points out right wing tip # z: points down # ------- Input Checks -------- # thr = torch.clamp(thr, 0, 255) ail = torch.clamp(ail, 0, 255) elev = torch.clamp(elev, 0, 255) rud = torch.clamp(rud, 0, 255) # ---------- Map Control Inputs to Angles ---------- # delta_ail = (ail-self.trim_ail)*self.g_ail delta_elev = (elev-self.trim_elev)*self.g_elev delta_rud = (rud-self.trim_rud)*self.g_rud # ---------- Aerodynamic Forces (body frame) ---------- # v_body = (Q*v.unsqueeze(-1)).sum(1) #body-frame velocity v_rout = v_body + torch.cross(w, self.r_ailvec) v_lout = v_body + torch.cross(w, -self.r_ailvec) v_rin = v_body + torch.cross(w, self.l_invec) + self.propwash(thr) v_lin = v_body + torch.cross(w, -self.l_invec) + self.propwash(thr) v_elev = v_body + torch.cross(w, self.r_elevvec) + self.propwash(thr) v_rud = v_body + torch.cross(w, self.rudvec) + self.propwash(thr) # --- Outboard Wing Sections --- # a_rout = torch.atan2(v_rout[:, 2], v_rout[:, 0]); a_lout = torch.atan2(v_lout[:, 2], v_rout[:, 0]); a_eff_rout = a_rout + self.ep_ail*delta_ail; #effective angle of attack a_eff_lout = a_lout - self.ep_ail*delta_ail; #effective angle of attack zeros = torch.zeros_like(a_rout) F_rout = -self.p_dyn(v_rout).unsqueeze(-1)*.5*self.S_out*torch.stack([self.Cd_wing(a_eff_rout), zeros, self.Cl_wing(a_eff_rout)], dim=-1) F_lout = -self.p_dyn(v_lout).unsqueeze(-1)*.5*self.S_out*torch.stack([self.Cd_wing(a_eff_lout), zeros, self.Cl_wing(a_eff_lout)], dim=-1) F_rout = arotate(a_rout,F_rout); #rotate to body frame F_lout = arotate(a_lout,F_lout); #rotate to body frame # --- Inboard Wing Sections (Includes Propwash) --- # a_rin = torch.atan2(v_rin[:, 2], v_rin[:, 0]) a_lin = torch.atan2(v_lin[:, 2], v_lin[:, 0]) a_eff_rin = a_rin + self.ep_ail*delta_ail; #effective angle of attack a_eff_lin = a_lin - self.ep_ail*delta_ail; #effective angle of attack F_rin = -self.p_dyn(v_rin).unsqueeze(-1)*.5*self.S_in*torch.stack([self.Cd_wing(a_eff_rin), zeros, self.Cl_wing(a_eff_rin)], dim=-1) F_lin = -self.p_dyn(v_lin).unsqueeze(-1)*.5*self.S_in*torch.stack([self.Cd_wing(a_eff_lin), zeros, self.Cl_wing(a_eff_lin)], dim=-1) F_rin = arotate(a_rin,F_rin); #rotate to body frame F_lin = arotate(a_lin,F_lin); #rotate to body frame # --- Elevator --- # a_elev = torch.atan2(v_elev[:, 2], v_elev[:, 0]) a_eff_elev = a_elev + self.ep_elev*delta_elev #effective angle of attack F_elev = -self.p_dyn(v_elev).unsqueeze(-1)*self.S_elev*torch.stack([self.Cd_elev( a_eff_elev), zeros, self.Cl_plate(a_eff_elev)], dim=-1); F_elev = arotate(a_elev,F_elev); #rotate to body frame # --- Rudder --- # a_rud = torch.atan2(v_rud[:, 1], v_rud[:, 0]) a_eff_rud = a_rud - self.ep_rud*delta_rud; #effective angle of attack F_rud = -self.p_dyn(v_rud).unsqueeze(-1)*self.S_rud * torch.stack([self.Cd_rud(a_eff_rud), self.Cl_plate(a_eff_rud), zeros], dim=-1); F_rud = brotate(a_rud,F_rud); #rotate to body frame # --- Thrust --- # thr_mask = (thr > self.trim_thr).float().unsqueeze(-1) zeros = torch.zeros_like(thr) F_thr = torch.stack([(thr-self.trim_thr)*self.g_thr, zeros, zeros], dim=-1) w_mot = torch.stack([self.g_mot*thr, zeros, zeros], dim=-1)*(thr_mask) # ---------- Aerodynamic Torques (body frame) ---------- # T_rout = torch.cross(torch.tensor([0, self.r_ail, 0]).to(thr).unsqueeze(0),F_rout) T_lout = torch.cross(torch.tensor([0, -self.r_ail, 0]).to(thr).unsqueeze(0),F_lout) T_rin = torch.cross(torch.tensor([0, self.l_in, 0]).to(thr).unsqueeze(0),F_rin) T_lin = torch.cross(torch.tensor([0, -self.l_in, 0]).to(thr).unsqueeze(0),F_lin) T_elev = torch.cross(torch.tensor([-self.r_elev, 0, 0]).to(thr).unsqueeze(0),F_elev) T_rud = torch.cross(torch.tensor([-self.r_rud, 0, -self.z_rud]).to(thr).unsqueeze(0),F_rud) # ---------- Add Everything Together ---------- # F_aero = F_rout + F_lout + F_rin + F_lin + F_elev + F_rud + F_thr; F = (Q*F_aero.unsqueeze(dim=1)).sum(dim=-1) - torch.tensor([0, 0, self.m*self.g]).to(thr).unsqueeze(0) T = T_rout + T_lout + T_rin + T_lin + T_elev + T_rud + torch.cross(((self.J*w.unsqueeze(1)).sum(dim=-1) + (self.Jm*w_mot.unsqueeze(1)).sum(dim=-1)),w) rdot = v qdot = w2pdotkinematics_mrp(q, w) vdot = F/self.m wdot = (self.Jinv*T.unsqueeze(dim=1)).sum(dim=-1) ns = torch.cat([rdot, qdot, vdot, wdot], dim=-1) return torch.cat([rdot, qdot, vdot, wdot], dim=-1) def reward(self, x, u): nearest_x_id = torch.argmin((x[:,:3].unsqueeze(1) - self.ref_traj[:,:3].unsqueeze(0)).norm(dim=-1), dim=1) nearest_x_id = torch.min(nearest_x_id, torch.tensor(self.num_steps)) nearest_x = self.ref_traj[nearest_x_id] targ_pos = nearest_x cost = (((x - self.targ_pos)**2)*self.Qlqr/2).sum(dim=-1)/10# + ((u**2)*self.Rlqr/2).sum(dim=-1)/10 mask = cost > -self.clip_rew rew = torch.exp(-cost/2+2) rew[mask] = -cost[mask] return rew def reset_torch(self, bsz=None, x_window=None): self.num_steps = 0 if x_window is None: x_window = self.x_window elif len(x_window.shape) == 1: x_window = x_window.unsqueeze(0) if bsz is None: bsz = self.bsz self.x = self.x0.clone() self.x[:,:3] = (torch.rand((bsz, 3))*2-1)*x_window return self.x def reset(self, bsz=None, x_window=None): self.num_steps = 0 x = self.reset_torch(bsz, x_window).detach().cpu().numpy().squeeze() return x #"Dynamic pressure" def p_dyn(self, v): return 0.5*self.rho*((v*v).sum(dim=-1)) """ Lift coefficient (alpha in radians) 3rd order polynomial fit to glide-test data Good to about ±20° """ def Cl_wing(self, a): if not self.lin: a = torch.clamp(a, -0.5*np.pi, 0.5*np.pi) cl = -27.52*a**3 - .6353*a**2 + 6.089*a Cl_coef = torch.tensor(list(reversed([-9.781885297556400, 38.779513049043175, -52.388499489940138, 19.266141214863080, 15.435976905745736, -13.127972418509980, -1.155316115022734, 3.634063117174400, -0.000000000000001]))).to(a) cl = Polynomial(Cl_coef,a) else: a = torch.clamp(a, -0.5*np.pi, 0.5*np.pi) cl = 2*np.pi*a # flat plate cl = 6*a return cl """ Lift coefficient (alpha in radians) Ideal flat plate model used for wing and rudder """ def Cl_plate(self,a): a = torch.clamp(a, -0.5*np.pi, 0.5*np.pi) return 2*np.pi*a """ Drag coefficient (alpha in radians) 2nd order polynomial fit to glide-test data Good to about ±20° """ def Cd_wing(self, a): if not self.lin: a = torch.clamp(a, -0.5*np.pi, 0.5*np.pi) cd = 2.08*(a**2) + .0612 Cd_coef = torch.tensor(list(reversed([5.006504698588220, -15.506103756150457, 11.861112337513331, 5.809973499615182, -8.905261747777024, -0.745202453390095, 3.835222476977072, 0.003598511005068, 0.064645268865914]))).to(a) cd = Polynomial(Cd_coef, a) else: a = torch.clamp(a, -0.5*np.pi, 0.5*np.pi) cd = 0.05 + a**2 return cd """ Drag coefficient (alpha in radians) Induced drag for a tapered finite wing From phillips P.55 """ def Cd_elev(self, a): a = torch.clamp(a, -0.5*np.pi, 0.5*np.pi) cd = (4*np.pi*(a**2))/self.Ra_elev return cd """ Drag coefficient (alpha in radians) Induced drag for a tapered finite wing From Phillips P.55 """ def Cd_rud(self, a): a = torch.clamp(a, -0.5*np.pi, 0.5*np.pi) cd = (4*np.pi*(a**2))/self.Ra_rud; return cd
18,703
Python
42.296296
239
0.540181
RoboticExplorationLab/Deep-ILC/envs/assets/hopper.xml
<mujoco model="hopper"> <compiler angle="radian" /> <option integrator="RK4" /> <size njmax="500" nconmax="100" /> <visual> <map znear="0.02" /> </visual> <default class="main"> <joint limited="true" armature="1" damping="1" /> <geom condim="1" solimp="0.8 0.8 0.01 0.5 2" margin="0.001" material="geom" rgba="0.8 0.6 0.4 1" /> <general ctrllimited="true" ctrlrange="-0.4 0.4" /> </default> <asset> <texture type="skybox" builtin="gradient" rgb1="0.4 0.5 0.6" rgb2="0 0 0" width="100" height="600" /> <texture type="cube" name="texgeom" builtin="flat" mark="cross" rgb1="0.8 0.6 0.4" rgb2="0.8 0.6 0.4" markrgb="1 1 1" width="127" height="762" /> <texture type="2d" name="texplane" builtin="checker" rgb1="0 0 0" rgb2="0.8 0.8 0.8" width="100" height="100" /> <material name="MatPlane" texture="texplane" texrepeat="60 60" specular="1" shininess="1" reflectance="0.5" /> <material name="geom" texture="texgeom" texuniform="true" /> </asset> <worldbody> <geom name="floor" size="20 20 0.125" type="plane" condim="3" material="MatPlane" rgba="0.8 0.9 0.8 1" /> <light pos="0 0 1.3" dir="0 0 -1" directional="true" cutoff="100" exponent="1" diffuse="1 1 1" specular="0.1 0.1 0.1" /> <body name="torso" pos="0 0 1.25"> <joint name="rootx" pos="0 0 -1.25" axis="1 0 0" type="slide" limited="false" armature="0" damping="0" /> <joint name="rootz" pos="0 0 0" axis="0 0 1" type="slide" ref="1.25" limited="false" armature="0" damping="0" /> <joint name="rooty" pos="0 0 0" axis="0 1 0" limited="false" type="hinge" armature="0" damping="0" /> <geom name="torso_geom" size="0.05 0.2" type="capsule" friction="0.9 0.005 0.0001" /> <body name="thigh" pos="0 0 -0.2"> <joint name="thigh_joint" pos="0 0 0" type="hinge" axis="0 -1 0" range="-2.61799 0" /> <geom name="thigh_geom" size="0.05 0.225" pos="0 0 -0.225" type="capsule" friction="0.9 0.005 0.0001" /> <body name="leg" pos="0 0 -0.7"> <joint name="leg_joint" pos="0 0 0.25" type="hinge" axis="0 -1 0" range="-2.61799 0" /> <geom name="leg_geom" size="0.04 0.25" type="capsule" friction="0.9 0.005 0.0001" /> <body name="foot" pos="0.0 0 -0.25"> <joint name="foot_joint" pos="0 0 0.0" type="hinge" axis="0 -1 0" range="-0.785398 0.785398" /> <geom name="foot_geom" size="0.06 0.195" pos="0.06 0 0.0" quat="0.707107 0 -0.707107 0" type="capsule" friction="2 0.005 0.0001" /> </body> </body> </body> </body> </worldbody> <actuator> <general joint="thigh_joint" ctrlrange="-1 1" gear="200 0 0 0 0 0" /> <general joint="leg_joint" ctrlrange="-1 1" gear="200 0 0 0 0 0" /> <general joint="foot_joint" ctrlrange="-1 1" gear="200 0 0 0 0 0" /> </actuator> </mujoco>
3,049
XML
62.541665
155
0.544441
RoboticExplorationLab/Deep-ILC/envs/assets/half_cheetah.xml
<!-- Cheetah Model The state space is populated with joints in the order that they are defined in this file. The actuators also operate on joints. State-Space (name/joint/parameter): - rootx slider position (m) - rootz slider position (m) - rooty hinge angle (rad) - bthigh hinge angle (rad) - bshin hinge angle (rad) - bfoot hinge angle (rad) - fthigh hinge angle (rad) - fshin hinge angle (rad) - ffoot hinge angle (rad) - rootx slider velocity (m/s) - rootz slider velocity (m/s) - rooty hinge angular velocity (rad/s) - bthigh hinge angular velocity (rad/s) - bshin hinge angular velocity (rad/s) - bfoot hinge angular velocity (rad/s) - fthigh hinge angular velocity (rad/s) - fshin hinge angular velocity (rad/s) - ffoot hinge angular velocity (rad/s) Actuators (name/actuator/parameter): - bthigh hinge torque (N m) - bshin hinge torque (N m) - bfoot hinge torque (N m) - fthigh hinge torque (N m) - fshin hinge torque (N m) - ffoot hinge torque (N m) --> <mujoco model="cheetah"> <compiler angle="radian" coordinate="local" inertiafromgeom="true" settotalmass="14"/> <default> <joint armature=".1" damping=".01" limited="true" solimplimit="0 .8 .03" solreflimit=".02 1" stiffness="8"/> <geom conaffinity="0" condim="3" contype="1" friction="0.8 .1 .1" rgba="0.8 0.6 .4 1" solimp="0.0 0.8 0.01" solref="0.02 1"/> <motor ctrllimited="true" ctrlrange="-1 1"/> </default> <size nstack="300000" nuser_geom="1"/> <option gravity="0 0 -9.81" timestep="0.01"/> <worldbody> <body name="torso" pos="0 0 0"> <joint armature="0" axis="1 0 0" damping="0" limited="false" name="ignorex" pos="0 0 0" stiffness="0" type="slide"/> <joint armature="0" axis="0 0 1" damping="0" limited="false" name="ignorez" pos="0 0 0" stiffness="0" type="slide"/> <joint armature="0" axis="0 1 0" damping="0" limited="false" name="ignorey" pos="0 0 0" stiffness="0" type="hinge"/> <geom fromto="-.5 0 0 .5 0 0" name="torso" size="0.046" type="capsule"/> <geom axisangle="0 1 0 .87" name="head" pos=".6 0 .1" size="0.046 .15" type="capsule"/> <!-- <site name='tip' pos='.15 0 .11'/>--> <body name="bthigh" pos="-.5 0 0"> <joint axis="0 1 0" damping="6" name="bthigh" pos="0 0 0" range="-.52 1.05" stiffness="240" type="hinge"/> <geom axisangle="0 1 0 -3.8" name="bthigh" pos=".1 0 -.13" size="0.046 .145" type="capsule"/> <body name="bshin" pos=".16 0 -.25"> <joint axis="0 1 0" damping="4.5" name="bshin" pos="0 0 0" range="-.785 .785" stiffness="180" type="hinge"/> <geom axisangle="0 1 0 -2.03" name="bshin" pos="-.14 0 -.07" rgba="0.9 0.6 0.6 1" size="0.046 .15" type="capsule"/> <body name="bfoot" pos="-.28 0 -.14"> <joint axis="0 1 0" damping="3" name="bfoot" pos="0 0 0" range="-.4 .785" stiffness="120" type="hinge"/> <geom axisangle="0 1 0 -.27" name="bfoot" pos=".03 0 -.097" rgba="0.9 0.6 0.6 1" size="0.046 .094" type="capsule"/> <inertial mass="10"/> </body> </body> </body> <body name="fthigh" pos=".5 0 0"> <joint axis="0 1 0" damping="4.5" name="fthigh" pos="0 0 0" range="-1.5 0.8" stiffness="180" type="hinge"/> <geom axisangle="0 1 0 .52" name="fthigh" pos="-.07 0 -.12" size="0.046 .133" type="capsule"/> <body name="fshin" pos="-.14 0 -.24"> <joint axis="0 1 0" damping="3" name="fshin" pos="0 0 0" range="-1.2 1.1" stiffness="120" type="hinge"/> <geom axisangle="0 1 0 -.6" name="fshin" pos=".065 0 -.09" rgba="0.9 0.6 0.6 1" size="0.046 .106" type="capsule"/> <body name="ffoot" pos=".13 0 -.18"> <joint axis="0 1 0" damping="1.5" name="ffoot" pos="0 0 0" range="-3.1 -0.3" stiffness="60" type="hinge"/> <geom axisangle="0 1 0 -.6" name="ffoot" pos=".045 0 -.07" rgba="0.9 0.6 0.6 1" size="0.046 .07" type="capsule"/> <inertial mass="10"/> </body> </body> </body> </body> </worldbody> <actuator> <motor gear="120" joint="bthigh" name="bthigh"/> <motor gear="90" joint="bshin" name="bshin"/> <motor gear="60" joint="bfoot" name="bfoot"/> <motor gear="120" joint="fthigh" name="fthigh"/> <motor gear="60" joint="fshin" name="fshin"/> <motor gear="30" joint="ffoot" name="ffoot"/> </actuator> </mujoco>
4,788
XML
52.808988
129
0.540518
RoboticExplorationLab/Deep-ILC/envs/assets/ant.xml
<mujoco model="ant"> <compiler angle="degree" coordinate="local" inertiafromgeom="true"/> <option integrator="RK4" timestep="0.01"/> <custom> <numeric data="0.0 0.0 0.55 1.0 0.0 0.0 0.0 0.0 1.0 0.0 -1.0 0.0 -1.0 0.0 1.0" name="init_qpos"/> </custom> <default> <joint armature="0.001" damping="1" limited="true"/> <geom conaffinity="0" condim="3" density="5.0" friction="1.5 0.1 0.1" margin="0.01" rgba="0.97 0.38 0.06 1"/> </default> <worldbody> <body name="torso" pos="0 0 0.75"> <geom name="torso_geom" pos="0 0 0" size="0.25" type="sphere"/> <geom fromto="0.0 0.0 0.0 0.2 0.2 0.0" name="aux_1_geom" size="0.08" type="capsule" rgba=".999 .2 .1 1"/> <geom fromto="0.0 0.0 0.0 -0.2 0.2 0.0" name="aux_2_geom" size="0.08" type="capsule"/> <geom fromto="0.0 0.0 0.0 -0.2 -0.2 0.0" name="aux_3_geom" size="0.08" type="capsule"/> <geom fromto="0.0 0.0 0.0 0.2 -0.2 0.0" name="aux_4_geom" size="0.08" type="capsule" rgba=".999 .2 .02 1"/> <joint armature="0" damping="0" limited="false" margin="0.01" name="root" pos="0 0 0" type="free"/> <body name="front_left_leg" pos="0.2 0.2 0"> <joint axis="0 0 1" name="hip_1" pos="0.0 0.0 0.0" range="-40 40" type="hinge"/> <geom fromto="0.0 0.0 0.0 0.2 0.2 0.0" name="left_leg_geom" size="0.08" type="capsule" rgba=".999 .2 .1 1"/> <body pos="0.2 0.2 0" name="front_left_foot"> <joint axis="-1 1 0" name="ankle_1" pos="0.0 0.0 0.0" range="30 100" type="hinge"/> <geom fromto="0.0 0.0 0.0 0.4 0.4 0.0" name="left_ankle_geom" size="0.08" type="capsule" rgba=".999 .2 .1 1"/> </body> </body> <body name="front_right_leg" pos="-0.2 0.2 0"> <joint axis="0 0 1" name="hip_2" pos="0.0 0.0 0.0" range="-40 40" type="hinge"/> <geom fromto="0.0 0.0 0.0 -0.2 0.2 0.0" name="right_leg_geom" size="0.08" type="capsule"/> <body pos="-0.2 0.2 0" name="front_right_foot"> <joint axis="1 1 0" name="ankle_2" pos="0.0 0.0 0.0" range="-100 -30" type="hinge"/> <geom fromto="0.0 0.0 0.0 -0.4 0.4 0.0" name="right_ankle_geom" size="0.08" type="capsule"/> </body> </body> <body name="left_back_leg" pos="-0.2 -0.2 0"> <joint axis="0 0 1" name="hip_3" pos="0.0 0.0 0.0" range="-40 40" type="hinge"/> <geom fromto="0.0 0.0 0.0 -0.2 -0.2 0.0" name="back_leg_geom" size="0.08" type="capsule"/> <body pos="-0.2 -0.2 0" name="left_back_foot"> <joint axis="-1 1 0" name="ankle_3" pos="0.0 0.0 0.0" range="-100 -30" type="hinge"/> <geom fromto="0.0 0.0 0.0 -0.4 -0.4 0.0" name="third_ankle_geom" size="0.08" type="capsule"/> </body> </body> <body name="right_back_leg" pos="0.2 -0.2 0"> <joint axis="0 0 1" name="hip_4" pos="0.0 0.0 0.0" range="-40 40" type="hinge"/> <geom fromto="0.0 0.0 0.0 0.2 -0.2 0.0" name="rightback_leg_geom" size="0.08" type="capsule" rgba=".999 .2 .1 1"/> <body pos="0.2 -0.2 0" name="right_back_foot"> <joint axis="1 1 0" name="ankle_4" pos="0.0 0.0 0.0" range="30 100" type="hinge"/> <geom fromto="0.0 0.0 0.0 0.4 -0.4 0.0" name="fourth_ankle_geom" size="0.08" type="capsule" rgba=".999 .2 .1 1"/> </body> </body> </body> </worldbody> <actuator> <motor ctrllimited="true" ctrlrange="-1.0 1.0" joint="hip_4" gear="150"/> <motor ctrllimited="true" ctrlrange="-1.0 1.0" joint="ankle_4" gear="150"/> <motor ctrllimited="true" ctrlrange="-1.0 1.0" joint="hip_1" gear="150"/> <motor ctrllimited="true" ctrlrange="-1.0 1.0" joint="ankle_1" gear="150"/> <motor ctrllimited="true" ctrlrange="-1.0 1.0" joint="hip_2" gear="150"/> <motor ctrllimited="true" ctrlrange="-1.0 1.0" joint="ankle_2" gear="150"/> <motor ctrllimited="true" ctrlrange="-1.0 1.0" joint="hip_3" gear="150"/> <motor ctrllimited="true" ctrlrange="-1.0 1.0" joint="ankle_3" gear="150"/> </actuator> </mujoco>
4,043
XML
61.215384
125
0.550829
RoboticExplorationLab/Deep-ILC/envs/assets/snu/human.xml
<Skeleton name="Human"> <Node name="Pelvis" parent="None" > <Body type="Box" mass="15.0" size="0.2083 0.1454 0.1294" contact="Off" color="0.6 0.6 1.5 1.0" obj="Pelvis.obj"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0.0 0.9809 -0.0308 "/> </Body> <Joint type="Free" bvh="Character1_Hips"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0.0 0.9809 -0.0308 "/> </Joint> </Node> <Node name="FemurR" parent="Pelvis" > <Body type="Box" mass="7.0" size="0.1271 0.4043 0.1398" contact="Off" color="0.3 0.3 1.5 1.0" obj="R_Femur.obj"> <Transformation linear="0.9998 -0.0174 -0.0024 -0.0175 -0.9997 -0.0172 -0.21 0.0172 -0.9998 " translation="-0.0959 0.7241 -0.0227 "/> </Body> <Joint type="Ball" bvh="Character1_RightUpLeg" lower="-2.0 -2.0 -2.0" upper="2.0 2.0 2.0"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="-0.0903 0.9337 -0.0116 "/> </Joint> </Node> <Node name="TibiaR" parent="FemurR" > <Body type="Box" mass="3.0" size="0.1198 0.4156 0.1141 " contact="Off" color="0.3 0.3 1.5 1.0" obj="R_Tibia.obj"> <Transformation linear="0.9994 0.0348 -0.0030 0.0349 -0.9956 0.0871 0.0 -0.0872 -0.9962 " translation="-0.0928 0.3018 -0.0341 "/> </Body> <Joint type="Revolute" axis ="1.0 0.0 0.0" bvh="Character1_RightLeg" lower="0.0" upper="2.3"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="-0.0995 0.5387 -0.0103 "/> </Joint> </Node> <Node name="TalusR" parent="TibiaR" endeffector="True"> <Body type="Box" mass="0.6" size="0.0756 0.0498 0.1570" contact="On" color="0.3 0.3 1.5 1.0" obj="R_Talus.obj"> <Transformation linear="0.9779 0.0256 0.2073 0.0199 -0.9994 0.0295 0.2079 -0.0247 -0.9778 " translation="-0.0826 0.0403 -0.0242 "/> </Body> <Joint type="Ball" bvh="Character1_RightFoot" lower="-1.0 -1.0 -1.0" upper="1.0 1.0 1.0"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="-0.08 0.0776 -0.0419"/> </Joint> </Node> <Node name="FootThumbR" parent="TalusR" > <Body type="Box" mass="0.2" size="0.0407 0.0262 0.0563 " contact="On" color="0.3 0.3 1.5 1.0" obj="R_FootThumb.obj"> <Transformation linear="0.9847 -0.0097 0.1739 -0.0129 -0.9998 0.0177 0.1737 -0.0196 -0.9846 " translation="-0.0765 0.0268 0.0938 "/> </Body> <Joint type="Revolute" axis ="1.0 0.0 0.0" lower="-0.6" upper="0.6"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="-0.0781 0.0201 0.0692"/> </Joint> </Node> <Node name="FootPinkyR" parent="TalusR" > <Body type="Box" mass="0.2" size="0.0422 0.0238 0.0529 " contact="On" color="0.3 0.3 1.5 1.0" obj="R_FootPinky.obj"> <Transformation linear="0.9402 0.0126 0.3405 0.0083 -0.9999 0.0142 0.3407 -0.0105 -0.9401 " translation="-0.1244 0.0269 0.0810 "/> </Body> <Joint type="Revolute" axis ="1.0 0.0 0.0" lower="-0.6" upper="0.6"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="-0.1227 0.0142 0.0494"/> </Joint> </Node> <Node name="FemurL" parent="Pelvis" > <Body type="Box" mass="7.0" size="0.1271 0.4043 0.1398" contact="Off" color="0.6 0.6 1.5 1.0" obj="L_Femur.obj"> <Transformation linear="0.9998 -0.0174 -0.0024 0.0175 0.9997 0.0172 0.21 -0.0172 0.9998 " translation="0.0959 0.7241 -0.0227 "/> </Body> <Joint type="Ball" bvh="Character1_LeftUpLeg" lower="-2.0 -2.0 -2.0" upper="2.0 2.0 2.0"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0.0903 0.9337 -0.0116 "/> </Joint> </Node> <Node name="TibiaL" parent="FemurL" > <Body type="Box" mass="3.0" size="0.1198 0.4156 0.1141 " contact="Off" color="0.6 0.6 1.5 1.0" obj="L_Tibia.obj"> <Transformation linear="0.9994 0.0348 -0.0030 -0.0349 0.9956 -0.0871 -0.0 0.0872 0.9962 " translation="0.0928 0.3018 -0.0341 "/> </Body> <Joint type="Revolute" axis ="1.0 0.0 0.0" bvh="Character1_LeftLeg" lower="0.0" upper="2.3"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0.0995 0.5387 -0.0103 "/> </Joint> </Node> <Node name="TalusL" parent="TibiaL" endeffector="True"> <Body type="Box" mass="0.6" size="0.0756 0.0498 0.1570" contact="On" color="0.6 0.6 1.5 1.0" obj="L_Talus.obj"> <Transformation linear="0.9779 0.0256 0.2073 -0.0199 0.9994 -0.0295 -0.2079 0.0247 0.9778 " translation="0.0826 0.0403 -0.0242 "/> </Body> <Joint type="Ball" bvh="Character1_LeftFoot" lower="-1.0 -1.0 -1.0" upper="1.0 1.0 1.0"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0.08 0.0776 -0.0419 "/> </Joint> </Node> <Node name="FootThumbL" parent="TalusL" > <Body type="Box" mass="0.2" size="0.0407 0.0262 0.0563 " contact="On" color="0.6 0.6 1.5 1.0" obj="L_FootThumb.obj"> <Transformation linear="0.9402 0.0126 0.3405 -0.0083 0.9999 -0.0142 -0.3407 0.0105 0.9401 " translation="0.1244 0.0269 0.0810 "/> </Body> <Joint type="Revolute" axis ="1.0 0.0 0.0" lower="-0.6" upper="0.6"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0.1215 0.0116 0.0494 "/> </Joint> </Node> <Node name="FootPinkyL" parent="TalusL" > <Body type="Box" mass="0.2" size="0.0422 0.0238 0.0529 " contact="On" color="0.6 0.6 1.5 1.0" obj="L_FootPinky.obj"> <Transformation linear="0.9847 -0.0097 0.1739 0.0129 0.9998 -0.0177 -0.1737 0.0196 0.9846 " translation="0.0765 0.0268 0.0938 "/> </Body> <Joint type="Revolute" axis ="1.0 0.0 0.0" lower="-0.6" upper="0.6"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0.0756 0.0118 0.0676 "/> </Joint> </Node> <Node name="Spine" parent="Pelvis" > <Body type="Box" mass="5.0" size="0.1170 0.0976 0.0984" contact="Off" color="0.6 0.6 1.5 1.0" obj="Spine.obj"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 " translation="0.0 1.1204 -0.0401 "/> </Body> <Joint type="Ball" bvh="Character1_Spine" lower="-0.4 -0.4 -0.2 " upper="0.4 0.4 0.2 "> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0. 1.0675 -0.0434 "/> </Joint> </Node> <Node name="Torso" parent="Spine" > <Body type="Box" mass="10.0" size="0.1798 0.2181 0.1337" contact="Off" color="0.6 0.6 1.5 1.0" obj="Torso.obj"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 -0.0092 0.0 0.0092 1.0 " translation="0.0 1.3032 -0.0398 "/> </Body> <Joint type="Ball" bvh="Character1_Spine1" lower="-0.4 -0.4 -0.2 " upper="0.4 0.4 0.2 "> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0. 1.1761 -0.0498 "/> </Joint> </Node> <Node name="Neck" parent="Torso" > <Body type="Box" mass="2.0" size="0.0793 0.0728 0.0652" contact="Off" color="0.6 0.6 1.5 1.0" obj="Neck.obj"> <Transformation linear="1.0 0.0 0.0 0.0 0.9732 -0.2301 0.0 0.2301 0.9732 " translation="0.0 1.5297 -0.0250 "/> </Body> <Joint type="Ball" bvh="Character1_Neck" lower="-0.4 -0.4 -0.4 " upper="0.6 0.6 1.5 "> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0. 1.4844 -0.0436 "/> </Joint> </Node> <Node name="Head" parent="Neck" endeffector="True"> <Body type="Box" mass="2.0" size="0.1129 0.1144 0.1166" contact="Off" color="0.6 0.6 1.5 1.0" obj="Skull.obj"> <Transformation linear="1.0 0.0 0.0 0.0 0.9895 -0.1447 0.0 0.1447 0.9895 " translation="0.0 1.6527 -0.0123 "/> </Body> <Joint type="Ball" lower="-0.4 -0.4 -0.4 " upper="0.6 0.6 1.5 "> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0. 1.5652 -0.0086 "/> </Joint> </Node> <Node name="ShoulderR" parent="Torso" > <Body type="Box" mass="1.0" size="0.1635 0.0634 0.0645" contact="Off" color="0.3 0.3 1.5 1.0" obj="R_Shoulder.obj"> <Transformation linear="0.9985 -0.0048 0.0549 -0.0047 -1.0 -0.0011 0.0549 0.0008 -0.9985 " translation="-0.0981 1.4644 -0.0391 "/> </Body> <Joint type="Ball" bvh="Character1_RightShoulder" lower="-0.5 -0.5 -0.5" upper="0.5 0.5 0.5"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="-0.0147 1.4535 -0.0381 "/> </Joint> </Node> <Node name="ArmR" parent="ShoulderR" > <Body type="Box" mass="1.0" size="0.3329 0.0542 0.0499" contact="Off" color="0.3 0.3 1.5 1.0" obj="R_Humerus.obj"> <Transformation linear="0.9960 0.0361 -0.0812 -0.0669 -0.2971 -0.952500 -0.0585 0.9542 -0.2936 " translation="-0.3578 1.4522 -0.0235 "/> </Body> <Joint type="Ball" bvh="Character1_RightArm" lower="-2.0 -2.0 -2.0" upper="2.0 2.0 2.0"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="-0.1995 1.4350 -0.0353 "/> </Joint> </Node> <Node name="ForeArmR" parent="ArmR" > <Body type="Box" mass="0.5" size="0.2630 0.0506 0.0513" contact="Off" color="0.3 0.3 1.5 1.0" obj="R_Radius.obj"> <Transformation linear="0.9929 0.0823 -0.0856 -0.0517 -0.3492 -0.9356 -0.1069 0.9334 -0.3424 " translation="-0.6674 1.4699 -0.0059 "/> </Body> <Joint type="Revolute" axis="0.0 1.0 0.0" bvh="Character1_RightForeArm" lower="0.0" upper="2.3"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="-0.5234 1.4607 -0.0105 "/> </Joint> </Node> <Node name="HandR" parent="ForeArmR" endeffector="True"> <Body type="Box" mass="0.2" size="0.1306 0.0104 0.0846" contact="Off" color="0.3 0.3 1.5 1.0" obj="R_Hand.obj"> <Transformation linear="0.9712 0.2357 -0.0353 0.2243 -0.9540 -0.1990 -0.0806 0.1853 -0.9794 " translation="-0.8810 1.4647 0.0315 "/> </Body> <Joint type="Ball" bvh="Character1_RightHand" lower="-0.7 -0.7 -0.7 " upper="0.7 0.7 0.7"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="-0.8102 1.469 0.0194 "/> </Joint> </Node> <Node name="ShoulderL" parent="Torso" > <Body type="Box" mass="1.0" size="0.1635 0.0634 0.0645" contact="Off" color="0.6 0.6 1.5 1.0" obj="L_Shoulder.obj"> <Transformation linear="0.9985 -0.0048 0.0549 0.0047 1.0000 0.0011 -0.0549 -0.0008 0.9985 " translation="0.0981 1.4644 -0.0391 "/> </Body> <Joint type="Ball" bvh="Character1_LeftShoulder" lower="-0.5 -0.5 -0.5" upper="0.5 0.5 0.5"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0.0147 1.4535 -0.0381"/> </Joint> </Node> <Node name="ArmL" parent="ShoulderL" > <Body type="Box" mass="1.0" size="0.3329 0.0542 0.0499" contact="Off" color="0.6 0.6 1.5 1.0" obj="L_Humerus.obj"> <Transformation linear="0.9960 0.0361 -0.0812 0.0669 0.2971 0.9525 0.0585 -0.9542 0.2936 " translation="0.3578 1.4522 -0.0235 "/> </Body> <Joint type="Ball" bvh="Character1_LeftArm" lower="-2.0 -2.0 -2.0" upper="2.0 2.0 2.0"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0.1995 1.4350 -0.0353"/> </Joint> </Node> <Node name="ForeArmL" parent="ArmL" > <Body type="Box" mass="0.5" size="0.2630 0.0506 0.0513" contact="Off" color="0.6 0.6 1.5 1.0" obj="L_Radius.obj"> <Transformation linear="0.9929 0.0823 -0.0856 0.0517 0.3492 0.9356 0.1069 -0.9334 0.3424 " translation="0.6674 1.4699 -0.0059 "/> </Body> <Joint type="Revolute" axis="0.0 1.0 0.0" bvh="Character1_LeftForeArm" lower="-2.3" upper="0.0"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0.5234 1.4607 -0.0105"/> </Joint> </Node> <Node name="HandL" parent="ForeArmL" endeffector="True"> <Body type="Box" mass="0.2" size="0.1306 0.0104 0.0846" contact="Off" color="0.6 0.6 1.5 1.0" obj="L_Hand.obj"> <Transformation linear="0.9712 0.2357 -0.0353 -0.2243 0.9540 0.1990 0.0806 -0.1853 0.9794 " translation="0.8813 1.4640 0.0315 "/> </Body> <Joint type="Ball" bvh="Character1_LeftHand" lower="-0.7 -0.7 -0.7 " upper="0.7 0.7 0.7"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0.8102 1.4694 0.0194"/> </Joint> </Node> </Skeleton>
12,775
XML
65.541666
148
0.570176
RoboticExplorationLab/Deep-ILC/envs/assets/snu/muscle284.xml
<Muscle> <Unit name="L_Abductor_Pollicis_Longus" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ForeArmL" p="0.629400 1.471000 -0.014000 " /> <Waypoint body="ForeArmL" p="0.732300 1.488400 0.018000 " /> <Waypoint body="ForeArmL" p="0.786300 1.491600 0.024800 " /> <Waypoint body="HandL" p="0.822700 1.472900 0.061900 " /> </Unit> <Unit name="R_Abductor_Pollicis_Longus" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ForeArmR" p="-0.629400 1.471000 -0.014000 " /> <Waypoint body="ForeArmR" p="-0.732300 1.488400 0.018000 " /> <Waypoint body="ForeArmR" p="-0.786300 1.491600 0.024800 " /> <Waypoint body="HandR" p="-0.822700 1.472900 0.061900 " /> </Unit> <Unit name="L_Adductor_Brevis" f0="151.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.031900 0.919600 0.041600 " /> <Waypoint body="FemurL" p="0.083100 0.833800 0.004900 " /> <Waypoint body="FemurL" p="0.110400 0.826200 -0.008400 " /> </Unit> <Unit name="R_Adductor_Brevis" f0="151.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.031900 0.919600 0.041600 " /> <Waypoint body="FemurR" p="-0.083100 0.833800 0.004900 " /> <Waypoint body="FemurR" p="-0.110400 0.826200 -0.008400 " /> </Unit> <Unit name="L_Adductor_Brevis1" f0="151.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.014100 0.911600 0.042700 " /> <Waypoint body="FemurL" p="0.076700 0.756500 -0.000700 " /> <Waypoint body="FemurL" p="0.104000 0.730500 0.002500 " /> </Unit> <Unit name="R_Adductor_Brevis1" f0="151.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.014100 0.911600 0.042700 " /> <Waypoint body="FemurR" p="-0.076700 0.756500 -0.000700 " /> <Waypoint body="FemurR" p="-0.104000 0.730500 0.002500 " /> </Unit> <Unit name="L_Adductor_Longus" f0="199.750000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.030200 0.921600 0.042700 " /> <Waypoint body="FemurL" p="0.100300 0.738600 0.002700 " /> <Waypoint body="FemurL" p="0.109600 0.701000 0.001400 " /> </Unit> <Unit name="R_Adductor_Longus" f0="199.750000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.030200 0.921600 0.042700 " /> <Waypoint body="FemurR" p="-0.100300 0.738600 0.002700 " /> <Waypoint body="FemurR" p="-0.109600 0.701000 0.001400 " /> </Unit> <Unit name="L_Adductor_Longus1" f0="199.750000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.014000 0.914800 0.048900 " /> <Waypoint body="FemurL" p="0.050500 0.729800 0.005100 " /> <Waypoint body="FemurL" p="0.099100 0.634300 0.001400 " /> </Unit> <Unit name="R_Adductor_Longus1" f0="199.750000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.014000 0.914800 0.048900 " /> <Waypoint body="FemurR" p="-0.050500 0.729800 0.005100 " /> <Waypoint body="FemurR" p="-0.099100 0.634300 0.001400 " /> </Unit> <Unit name="L_Adductor_Magnus" f0="259.380000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.022300 0.891300 0.013400 " /> <Waypoint body="FemurL" p="0.106400 0.837500 -0.017200 " /> <Waypoint body="FemurL" p="0.133800 0.833900 -0.017600 " /> </Unit> <Unit name="R_Adductor_Magnus" f0="259.380000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.022300 0.891300 0.013400 " /> <Waypoint body="FemurR" p="-0.106400 0.837500 -0.017200 " /> <Waypoint body="FemurR" p="-0.133800 0.833900 -0.017600 " /> </Unit> <Unit name="L_Adductor_Magnus1" f0="259.380000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.023500 0.881300 0.013000 " /> <Waypoint body="FemurL" p="0.097700 0.800600 -0.023300 " /> <Waypoint body="FemurL" p="0.124400 0.759600 -0.002000 " /> </Unit> <Unit name="R_Adductor_Magnus1" f0="259.380000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.023500 0.881300 0.013000 " /> <Waypoint body="FemurR" p="-0.097700 0.800600 -0.023300 " /> <Waypoint body="FemurR" p="-0.124400 0.759600 -0.002000 " /> </Unit> <Unit name="L_Adductor_Magnus2" f0="259.380000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.035600 0.870400 -0.025800 " /> <Waypoint body="FemurL" p="0.069900 0.809100 -0.024200 " /> <Waypoint body="FemurL" p="0.102600 0.745100 -0.024800 " /> <Waypoint body="FemurL" p="0.116600 0.719600 0.001200 " /> </Unit> <Unit name="R_Adductor_Magnus2" f0="259.380000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.035600 0.870400 -0.025800 " /> <Waypoint body="FemurR" p="-0.069900 0.809100 -0.024200 " /> <Waypoint body="FemurR" p="-0.102600 0.745100 -0.024800 " /> <Waypoint body="FemurR" p="-0.116600 0.719600 0.001200 " /> </Unit> <Unit name="L_Adductor_Magnus3" f0="259.380000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.047500 0.869700 -0.043600 " /> <Waypoint body="FemurL" p="0.074400 0.781900 -0.034000 " /> <Waypoint body="FemurL" p="0.102400 0.704000 -0.022500 " /> <Waypoint body="FemurL" p="0.105400 0.641800 -0.002200 " /> </Unit> <Unit name="R_Adductor_Magnus3" f0="259.380000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.047500 0.869700 -0.043600 " /> <Waypoint body="FemurR" p="-0.074400 0.781900 -0.034000 " /> <Waypoint body="FemurR" p="-0.102400 0.704000 -0.022500 " /> <Waypoint body="FemurR" p="-0.105400 0.641800 -0.002200 " /> </Unit> <Unit name="L_Adductor_Magnus4" f0="259.380000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.068700 0.877200 -0.056000 " /> <Waypoint body="Pelvis" p="0.063000 0.844300 -0.048200 " /> <Waypoint body="FemurL" p="0.063700 0.641200 -0.031400 " /> <Waypoint body="FemurL" p="0.065300 0.555500 -0.028900 " /> </Unit> <Unit name="R_Adductor_Magnus4" f0="259.380000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.068700 0.877200 -0.056000 " /> <Waypoint body="Pelvis" p="-0.063000 0.844300 -0.048200 " /> <Waypoint body="FemurR" p="-0.063700 0.641200 -0.031400 " /> <Waypoint body="FemurR" p="-0.065300 0.555500 -0.028900 " /> </Unit> <Unit name="L_Anconeous" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmL" p="0.506400 1.482400 -0.009500 " /> <Waypoint body="ForeArmL" p="0.537100 1.479700 -0.026300 " /> <Waypoint body="ForeArmL" p="0.571200 1.468800 -0.029500 " /> </Unit> <Unit name="R_Anconeous" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmR" p="-0.506400 1.482400 -0.009500 " /> <Waypoint body="ForeArmR" p="-0.537100 1.479700 -0.026300 " /> <Waypoint body="ForeArmR" p="-0.571200 1.468800 -0.029500 " /> </Unit> <Unit name="L_Bicep_Brachii_Long_Head" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.169300 1.443700 -0.036900 " /> <Waypoint body="ArmL" p="0.177900 1.421700 -0.033000 " /> <Waypoint body="ArmL" p="0.181000 1.432000 -0.018300 " /> <Waypoint body="ArmL" p="0.191100 1.434300 -0.008400 " /> <Waypoint body="ArmL" p="0.214500 1.434800 -0.007100 " /> <Waypoint body="ArmL" p="0.259100 1.434100 -0.002400 " /> <Waypoint body="ForeArmL" p="0.529000 1.448300 0.025000 " /> <Waypoint body="ForeArmL" p="0.583200 1.462500 0.001900 " /> </Unit> <Unit name="R_Bicep_Brachii_Long_Head" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.169300 1.443700 -0.036900 " /> <Waypoint body="ArmR" p="-0.177900 1.421700 -0.033000 " /> <Waypoint body="ArmR" p="-0.181000 1.432000 -0.018300 " /> <Waypoint body="ArmR" p="-0.191100 1.434300 -0.008400 " /> <Waypoint body="ArmR" p="-0.214500 1.434800 -0.007100 " /> <Waypoint body="ArmR" p="-0.259100 1.434100 -0.002400 " /> <Waypoint body="ForeArmR" p="-0.529000 1.448300 0.025000 " /> <Waypoint body="ForeArmR" p="-0.583200 1.462500 0.001900 " /> </Unit> <Unit name="L_Bicep_Brachii_Short_Head" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.168400 1.434700 -0.007400 " /> <Waypoint body="ArmL" p="0.252000 1.411300 -0.007700 " /> <Waypoint body="ArmL" p="0.489000 1.425300 0.023400 " /> <Waypoint body="ForeArmL" p="0.585400 1.461400 -0.001300 " /> </Unit> <Unit name="R_Bicep_Brachii_Short_Head" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.168400 1.434700 -0.007400 " /> <Waypoint body="ArmR" p="-0.252000 1.411300 -0.007700 " /> <Waypoint body="ArmR" p="-0.489000 1.425300 0.023400 " /> <Waypoint body="ForeArmR" p="-0.585400 1.461400 -0.001300 " /> </Unit> <Unit name="L_Bicep_Femoris_Longus" f0="705.200000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.070900 0.900200 -0.063600 " /> <Waypoint body="FemurL" p="0.096500 0.854800 -0.046300 " /> <Waypoint body="FemurL" p="0.139900 0.574300 -0.029200 " /> <Waypoint body="FemurL" p="0.144100 0.541600 -0.032800 " /> <Waypoint body="TibiaL" p="0.138200 0.488800 -0.038800 " /> </Unit> <Unit name="R_Bicep_Femoris_Longus" f0="705.200000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.070900 0.900200 -0.063600 " /> <Waypoint body="FemurR" p="-0.096500 0.854800 -0.046300 " /> <Waypoint body="FemurR" p="-0.139900 0.574300 -0.029200 " /> <Waypoint body="FemurR" p="-0.144100 0.541600 -0.032800 " /> <Waypoint body="TibiaR" p="-0.138200 0.488800 -0.038800 " /> </Unit> <Unit name="L_Bicep_Femoris_Short" f0="157.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurL" p="0.118200 0.729800 0.000200 " /> <Waypoint body="FemurL" p="0.143500 0.545000 -0.029700 " /> <Waypoint body="TibiaL" p="0.139800 0.489100 -0.034100 " /> </Unit> <Unit name="R_Bicep_Femoris_Short" f0="157.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurR" p="-0.118200 0.729800 0.000200 " /> <Waypoint body="FemurR" p="-0.143500 0.545000 -0.029700 " /> <Waypoint body="TibiaR" p="-0.139800 0.489100 -0.034100 " /> </Unit> <Unit name="L_Bicep_Femoris_Short1" f0="157.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurL" p="0.111800 0.618400 0.001900 " /> <Waypoint body="FemurL" p="0.141600 0.532000 -0.019900 " /> <Waypoint body="TibiaL" p="0.137900 0.488500 -0.030700 " /> </Unit> <Unit name="R_Bicep_Femoris_Short1" f0="157.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurR" p="-0.111800 0.618400 0.001900 " /> <Waypoint body="FemurR" p="-0.141600 0.532000 -0.019900 " /> <Waypoint body="TibiaR" p="-0.137900 0.488500 -0.030700 " /> </Unit> <Unit name="L_Brachialis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmL" p="0.332100 1.460400 -0.019000 " /> <Waypoint body="ArmL" p="0.350000 1.471800 -0.008100 " /> <Waypoint body="ArmL" p="0.496300 1.460600 0.017500 " /> <Waypoint body="ForeArmL" p="0.557200 1.461900 -0.011000 " /> </Unit> <Unit name="R_Brachialis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmR" p="-0.332100 1.460400 -0.019000 " /> <Waypoint body="ArmR" p="-0.350000 1.471800 -0.008100 " /> <Waypoint body="ArmR" p="-0.496300 1.460600 0.017500 " /> <Waypoint body="ForeArmR" p="-0.557200 1.461900 -0.011000 " /> </Unit> <Unit name="L_Brachioradialis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmL" p="0.442800 1.465200 -0.020900 " /> <Waypoint body="ArmL" p="0.465100 1.490300 -0.008200 " /> <Waypoint body="ArmL" p="0.499700 1.478900 0.025100 " /> <Waypoint body="ForeArmL" p="0.561800 1.460900 0.037700 " /> <Waypoint body="ForeArmL" p="0.708600 1.474300 0.036200 " /> <Waypoint body="ForeArmL" p="0.786700 1.488000 0.030200 " /> </Unit> <Unit name="R_Brachioradialis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmR" p="-0.442800 1.465200 -0.020900 " /> <Waypoint body="ArmR" p="-0.465100 1.490300 -0.008200 " /> <Waypoint body="ArmR" p="-0.499700 1.478900 0.025100 " /> <Waypoint body="ForeArmR" p="-0.561800 1.460900 0.037700 " /> <Waypoint body="ForeArmR" p="-0.708600 1.474300 0.036200 " /> <Waypoint body="ForeArmR" p="-0.786700 1.488000 0.030200 " /> </Unit> <Unit name="L_Coracobrachialis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.168100 1.432600 -0.008300 " /> <Waypoint body="ArmL" p="0.228900 1.407100 -0.019200 " /> <Waypoint body="ArmL" p="0.312100 1.429100 -0.019400 " /> <Waypoint body="ArmL" p="0.338600 1.441800 -0.016700 " /> </Unit> <Unit name="R_Coracobrachialis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.168100 1.432600 -0.008300 " /> <Waypoint body="ArmR" p="-0.228900 1.407100 -0.019200 " /> <Waypoint body="ArmR" p="-0.312100 1.429100 -0.019400 " /> <Waypoint body="ArmR" p="-0.338600 1.441800 -0.016700 " /> </Unit> <Unit name="L_Deltoid" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.143200 1.466200 -0.019000 " /> <Waypoint body="ShoulderL" p="0.160700 1.447600 0.001500 " /> <Waypoint body="ArmL" p="0.221300 1.411900 0.013700 " /> <Waypoint body="ArmL" p="0.268700 1.443100 0.014100 " /> <Waypoint body="ArmL" p="0.299600 1.446200 -0.010700 " /> </Unit> <Unit name="R_Deltoid" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.143200 1.466200 -0.019000 " /> <Waypoint body="ShoulderR" p="-0.160700 1.447600 0.001500 " /> <Waypoint body="ArmR" p="-0.221300 1.411900 0.013700 " /> <Waypoint body="ArmR" p="-0.268700 1.443100 0.014100 " /> <Waypoint body="ArmR" p="-0.299600 1.446200 -0.010700 " /> </Unit> <Unit name="L_Deltoid1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.197700 1.465900 -0.025700 " /> <Waypoint body="ArmL" p="0.186600 1.450500 -0.008600 " /> <Waypoint body="ArmL" p="0.227700 1.467700 0.006400 " /> <Waypoint body="ArmL" p="0.278600 1.469800 0.007400 " /> <Waypoint body="ArmL" p="0.318300 1.452900 -0.008100 " /> </Unit> <Unit name="R_Deltoid1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.197700 1.465900 -0.025700 " /> <Waypoint body="ArmR" p="-0.186600 1.450500 -0.008600 " /> <Waypoint body="ArmR" p="-0.227700 1.467700 0.006400 " /> <Waypoint body="ArmR" p="-0.278600 1.469800 0.007400 " /> <Waypoint body="ArmR" p="-0.318300 1.452900 -0.008100 " /> </Unit> <Unit name="L_Deltoid2" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.203700 1.459300 -0.052000 " /> <Waypoint body="ShoulderL" p="0.193300 1.466900 -0.038600 " /> <Waypoint body="ArmL" p="0.236700 1.485800 -0.026200 " /> <Waypoint body="ArmL" p="0.295100 1.477600 -0.016200 " /> <Waypoint body="ArmL" p="0.324100 1.456900 -0.011200 " /> </Unit> <Unit name="R_Deltoid2" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.203700 1.459300 -0.052000 " /> <Waypoint body="ShoulderR" p="-0.193300 1.466900 -0.038600 " /> <Waypoint body="ArmR" p="-0.236700 1.485800 -0.026200 " /> <Waypoint body="ArmR" p="-0.295100 1.477600 -0.016200 " /> <Waypoint body="ArmR" p="-0.324100 1.456900 -0.011200 " /> </Unit> <Unit name="L_Extensor_Carpi_Radialis_Longus" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmL" p="0.478900 1.470500 -0.017300 " /> <Waypoint body="ArmL" p="0.501100 1.489700 -0.001000 " /> <Waypoint body="ForeArmL" p="0.552500 1.490000 0.029900 " /> <Waypoint body="ForeArmL" p="0.720600 1.483000 0.027900 " /> <Waypoint body="ForeArmL" p="0.782100 1.488200 0.013300 " /> <Waypoint body="HandL" p="0.829300 1.485400 0.038500 " /> </Unit> <Unit name="R_Extensor_Carpi_Radialis_Longus" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmR" p="-0.478900 1.470500 -0.017300 " /> <Waypoint body="ArmR" p="-0.501100 1.489700 -0.001000 " /> <Waypoint body="ForeArmR" p="-0.552500 1.490000 0.029900 " /> <Waypoint body="ForeArmR" p="-0.720600 1.483000 0.027900 " /> <Waypoint body="ForeArmR" p="-0.782100 1.488200 0.013300 " /> <Waypoint body="HandR" p="-0.829300 1.485400 0.038500 " /> </Unit> <Unit name="L_Extensor_Carpi_Ulnaris" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmL" p="0.518600 1.483100 -0.006700 " /> <Waypoint body="ForeArmL" p="0.559300 1.490700 -0.017100 " /> <Waypoint body="ForeArmL" p="0.652300 1.470700 -0.029700 " /> <Waypoint body="ForeArmL" p="0.785500 1.449400 0.000900 " /> <Waypoint body="HandL" p="0.825500 1.477700 0.001000 " /> </Unit> <Unit name="R_Extensor_Carpi_Ulnaris" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmR" p="-0.518600 1.483100 -0.006700 " /> <Waypoint body="ForeArmR" p="-0.559300 1.490700 -0.017100 " /> <Waypoint body="ForeArmR" p="-0.652300 1.470700 -0.029700 " /> <Waypoint body="ForeArmR" p="-0.785500 1.449400 0.000900 " /> <Waypoint body="HandR" p="-0.825500 1.477700 0.001000 " /> </Unit> <Unit name="L_Extensor_Digiti_Minimi" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmL" p="0.520400 1.483700 -0.005400 " /> <Waypoint body="ForeArmL" p="0.548300 1.490000 -0.007600 " /> <Waypoint body="ForeArmL" p="0.783200 1.463200 -0.003600 " /> <Waypoint body="HandL" p="0.821600 1.482100 0.001400 " /> <Waypoint body="HandL" p="0.884700 1.462100 -0.005200 " /> <Waypoint body="HandL" p="0.927800 1.443100 -0.002500 " /> </Unit> <Unit name="R_Extensor_Digiti_Minimi" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmR" p="-0.520400 1.483700 -0.005400 " /> <Waypoint body="ForeArmR" p="-0.548300 1.490000 -0.007600 " /> <Waypoint body="ForeArmR" p="-0.783200 1.463200 -0.003600 " /> <Waypoint body="HandR" p="-0.821600 1.482100 0.001400 " /> <Waypoint body="HandR" p="-0.884700 1.462100 -0.005200 " /> <Waypoint body="HandR" p="-0.927800 1.443100 -0.002500 " /> </Unit> <Unit name="L_Extensor_Digitorum_Longus" f0="172.700000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.123300 0.482800 -0.012800 " /> <Waypoint body="TibiaL" p="0.124900 0.447400 -0.025500 " /> <Waypoint body="TibiaL" p="0.094400 0.112800 -0.025500 " /> <Waypoint body="TalusL" p="0.091900 0.084400 -0.015300 " /> <Waypoint body="TalusL" p="0.090000 0.027700 0.067600 " /> <Waypoint body="FootThumbL" p="0.092000 0.021200 0.096100 " /> <Waypoint body="FootThumbL" p="0.093800 0.013000 0.112100 " /> </Unit> <Unit name="R_Extensor_Digitorum_Longus" f0="172.700000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.123300 0.482800 -0.012800 " /> <Waypoint body="TibiaR" p="-0.124900 0.447400 -0.025500 " /> <Waypoint body="TibiaR" p="-0.094400 0.112800 -0.025500 " /> <Waypoint body="TalusR" p="-0.091900 0.084400 -0.015300 " /> <Waypoint body="TalusR" p="-0.090000 0.027700 0.067600 " /> <Waypoint body="FootThumbR" p="-0.092000 0.021200 0.096100 " /> <Waypoint body="FootThumbR" p="-0.093800 0.013000 0.112100 " /> </Unit> <Unit name="L_Extensor_Digitorum_Longus1" f0="172.700000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.128600 0.491900 -0.010000 " /> <Waypoint body="TibiaL" p="0.133600 0.407000 -0.020000 " /> <Waypoint body="TibiaL" p="0.097300 0.113900 -0.023900 " /> <Waypoint body="TalusL" p="0.098400 0.080700 -0.011500 " /> <Waypoint body="TalusL" p="0.104700 0.024500 0.061600 " /> <Waypoint body="FootPinkyL" p="0.107400 0.019500 0.079600 " /> <Waypoint body="FootPinkyL" p="0.112000 0.010600 0.103200 " /> </Unit> <Unit name="R_Extensor_Digitorum_Longus1" f0="172.700000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.128600 0.491900 -0.010000 " /> <Waypoint body="TibiaR" p="-0.133600 0.407000 -0.020000 " /> <Waypoint body="TibiaR" p="-0.097300 0.113900 -0.023900 " /> <Waypoint body="TalusR" p="-0.098400 0.080700 -0.011500 " /> <Waypoint body="TalusR" p="-0.104700 0.024500 0.061600 " /> <Waypoint body="FootPinkyR" p="-0.107400 0.019500 0.079600 " /> <Waypoint body="FootPinkyR" p="-0.112000 0.010600 0.103200 " /> </Unit> <Unit name="L_Extensor_Digitorum_Longus2" f0="172.700000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.127100 0.488400 -0.009500 " /> <Waypoint body="TibiaL" p="0.140800 0.406700 -0.014400 " /> <Waypoint body="TibiaL" p="0.098500 0.113700 -0.024500 " /> <Waypoint body="TalusL" p="0.101300 0.077500 -0.010600 " /> <Waypoint body="FootPinkyL" p="0.118000 0.026000 0.054300 " /> <Waypoint body="FootPinkyL" p="0.121400 0.022400 0.068700 " /> <Waypoint body="FootPinkyL" p="0.125200 0.012900 0.084600 " /> </Unit> <Unit name="R_Extensor_Digitorum_Longus2" f0="172.700000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.127100 0.488400 -0.009500 " /> <Waypoint body="TibiaR" p="-0.140800 0.406700 -0.014400 " /> <Waypoint body="TibiaR" p="-0.098500 0.113700 -0.024500 " /> <Waypoint body="TalusR" p="-0.101300 0.077500 -0.010600 " /> <Waypoint body="FootPinkyR" p="-0.118000 0.026000 0.054300 " /> <Waypoint body="FootPinkyR" p="-0.121400 0.022400 0.068700 " /> <Waypoint body="FootPinkyR" p="-0.125200 0.012900 0.084600 " /> </Unit> <Unit name="L_Extensor_Digitorum_Longus3" f0="172.700000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.130000 0.493100 -0.011700 " /> <Waypoint body="TibiaL" p="0.131500 0.407000 -0.033100 " /> <Waypoint body="TibiaL" p="0.103700 0.082400 -0.017500 " /> <Waypoint body="TalusL" p="0.114200 0.059400 0.000900 " /> <Waypoint body="TalusL" p="0.130700 0.028300 0.039500 " /> <Waypoint body="FootPinkyL" p="0.137100 0.009300 0.074500 " /> </Unit> <Unit name="R_Extensor_Digitorum_Longus3" f0="172.700000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.130000 0.493100 -0.011700 " /> <Waypoint body="TibiaR" p="-0.131500 0.407000 -0.033100 " /> <Waypoint body="TibiaR" p="-0.103700 0.082400 -0.017500 " /> <Waypoint body="TalusR" p="-0.114200 0.059400 0.000900 " /> <Waypoint body="TalusR" p="-0.130700 0.028300 0.039500 " /> <Waypoint body="FootPinkyR" p="-0.137100 0.009300 0.074500 " /> </Unit> <Unit name="L_Extensor_Digitorum1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmL" p="0.519300 1.487900 -0.001600 " /> <Waypoint body="ForeArmL" p="0.745800 1.482600 0.005500 " /> <Waypoint body="ForeArmL" p="0.782100 1.478400 0.002300 " /> <Waypoint body="HandL" p="0.824700 1.491700 0.026300 " /> <Waypoint body="HandL" p="0.895700 1.481400 0.034000 " /> <Waypoint body="HandL" p="0.960600 1.441800 0.044200 " /> </Unit> <Unit name="R_Extensor_Digitorum1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmR" p="-0.519300 1.487900 -0.001600 " /> <Waypoint body="ForeArmR" p="-0.745800 1.482600 0.005500 " /> <Waypoint body="ForeArmR" p="-0.782100 1.478400 0.002300 " /> <Waypoint body="HandR" p="-0.824700 1.491700 0.026300 " /> <Waypoint body="HandR" p="-0.895700 1.481400 0.034000 " /> <Waypoint body="HandR" p="-0.960600 1.441800 0.044200 " /> </Unit> <Unit name="L_Extensor_Hallucis_Longus" f0="165.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.115100 0.380600 -0.028300 " /> <Waypoint body="TibiaL" p="0.097000 0.119900 -0.023000 " /> <Waypoint body="TalusL" p="0.083400 0.082500 -0.015100 " /> <Waypoint body="TalusL" p="0.072400 0.063500 0.027400 " /> <Waypoint body="TalusL" p="0.065600 0.031800 0.071700 " /> <Waypoint body="FootThumbL" p="0.060600 0.012900 0.112800 " /> </Unit> <Unit name="R_Extensor_Hallucis_Longus" f0="165.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.115100 0.380600 -0.028300 " /> <Waypoint body="TibiaR" p="-0.097000 0.119900 -0.023000 " /> <Waypoint body="TalusR" p="-0.083400 0.082500 -0.015100 " /> <Waypoint body="TalusR" p="-0.072400 0.063500 0.027400 " /> <Waypoint body="TalusR" p="-0.065600 0.031800 0.071700 " /> <Waypoint body="FootThumbR" p="-0.060600 0.012900 0.112800 " /> </Unit> <Unit name="L_Extensor_Pollicis_Brevis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ForeArmL" p="0.700700 1.470500 0.008700 " /> <Waypoint body="ForeArmL" p="0.791900 1.490900 0.019900 " /> <Waypoint body="HandL" p="0.816700 1.482000 0.054200 " /> <Waypoint body="HandL" p="0.855900 1.457500 0.079600 " /> </Unit> <Unit name="R_Extensor_Pollicis_Brevis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ForeArmR" p="-0.700700 1.470500 0.008700 " /> <Waypoint body="ForeArmR" p="-0.791900 1.490900 0.019900 " /> <Waypoint body="HandR" p="-0.816700 1.482000 0.054200 " /> <Waypoint body="HandR" p="-0.855900 1.457500 0.079600 " /> </Unit> <Unit name="L_Extensor_Pollicis_Longus" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ForeArmL" p="0.671800 1.469500 -0.007300 " /> <Waypoint body="ForeArmL" p="0.770900 1.479600 0.005500 " /> <Waypoint body="HandL" p="0.815100 1.490300 0.039500 " /> <Waypoint body="HandL" p="0.847400 1.466000 0.075500 " /> <Waypoint body="HandL" p="0.877000 1.446000 0.087800 " /> </Unit> <Unit name="R_Extensor_Pollicis_Longus" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ForeArmR" p="-0.671800 1.469500 -0.007300 " /> <Waypoint body="ForeArmR" p="-0.770900 1.479600 0.005500 " /> <Waypoint body="HandR" p="-0.815100 1.490300 0.039500 " /> <Waypoint body="HandR" p="-0.847400 1.466000 0.075500 " /> <Waypoint body="HandR" p="-0.877000 1.446000 0.087800 " /> </Unit> <Unit name="L_Flexor_Carpi_Radialis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmL" p="0.518400 1.426200 -0.016200 " /> <Waypoint body="ForeArmL" p="0.741200 1.458600 0.027000 " /> <Waypoint body="ForeArmL" p="0.784600 1.465300 0.028700 " /> <Waypoint body="HandL" p="0.832400 1.474100 0.039100 " /> </Unit> <Unit name="R_Flexor_Carpi_Radialis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmR" p="-0.518400 1.426200 -0.016200 " /> <Waypoint body="ForeArmR" p="-0.741200 1.458600 0.027000 " /> <Waypoint body="ForeArmR" p="-0.784600 1.465300 0.028700 " /> <Waypoint body="HandR" p="-0.832400 1.474100 0.039100 " /> </Unit> <Unit name="L_Flexor_Carpi_Ulnaris" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmL" p="0.525500 1.425600 -0.022000 " /> <Waypoint body="ForeArmL" p="0.581900 1.436100 -0.034700 " /> <Waypoint body="ForeArmL" p="0.759400 1.450100 0.006800 " /> <Waypoint body="HandL" p="0.805300 1.467100 0.009900 " /> </Unit> <Unit name="R_Flexor_Carpi_Ulnaris" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmR" p="-0.525500 1.425600 -0.022000 " /> <Waypoint body="ForeArmR" p="-0.581900 1.436100 -0.034700 " /> <Waypoint body="ForeArmR" p="-0.759400 1.450100 0.006800 " /> <Waypoint body="HandR" p="-0.805300 1.467100 0.009900 " /> </Unit> <Unit name="L_Flexor_Digiti_Minimi_Brevis_Foot" f0="50.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FootPinkyL" p="0.136400 0.011200 0.049600 " /> <Waypoint body="TalusL" p="0.120100 0.023600 -0.009200 " /> </Unit> <Unit name="R_Flexor_Digiti_Minimi_Brevis_Foot" f0="50.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FootPinkyR" p="-0.136400 0.011200 0.049600 " /> <Waypoint body="TalusR" p="-0.120100 0.023600 -0.009200 " /> </Unit> <Unit name="L_Flexor_Digitorum_Longus" f0="137.200000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.089500 0.398600 -0.020400 " /> <Waypoint body="TibiaL" p="0.062700 0.111200 -0.055500 " /> <Waypoint body="TalusL" p="0.063700 0.040400 -0.022200 " /> <Waypoint body="TalusL" p="0.083100 0.032200 -0.001400 " /> <Waypoint body="TalusL" p="0.086700 0.009400 0.059100 " /> <Waypoint body="FootThumbL" p="0.092700 0.008800 0.108400 " /> </Unit> <Unit name="R_Flexor_Digitorum_Longus" f0="137.200000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.089500 0.398600 -0.020400 " /> <Waypoint body="TibiaR" p="-0.062700 0.111200 -0.055500 " /> <Waypoint body="TalusR" p="-0.063700 0.040400 -0.022200 " /> <Waypoint body="TalusR" p="-0.083100 0.032200 -0.001400 " /> <Waypoint body="TalusR" p="-0.086700 0.009400 0.059100 " /> <Waypoint body="FootThumbR" p="-0.092700 0.008800 0.108400 " /> </Unit> <Unit name="L_Flexor_Digitorum_Longus1" f0="137.200000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.089500 0.398600 -0.020400 " /> <Waypoint body="TibiaL" p="0.065700 0.111000 -0.056200 " /> <Waypoint body="TalusL" p="0.064900 0.040300 -0.023900 " /> <Waypoint body="TalusL" p="0.085000 0.031700 -0.008900 " /> <Waypoint body="TalusL" p="0.101600 0.007000 0.053000 " /> <Waypoint body="FootPinkyL" p="0.110200 0.009200 0.099700 " /> </Unit> <Unit name="R_Flexor_Digitorum_Longus1" f0="137.200000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.089500 0.398600 -0.020400 " /> <Waypoint body="TibiaR" p="-0.065700 0.111000 -0.056200 " /> <Waypoint body="TalusR" p="-0.064900 0.040300 -0.023900 " /> <Waypoint body="TalusR" p="-0.085000 0.031700 -0.008900 " /> <Waypoint body="TalusR" p="-0.101600 0.007000 0.053000 " /> <Waypoint body="FootPinkyR" p="-0.110200 0.009200 0.099700 " /> </Unit> <Unit name="L_Flexor_Digitorum_Longus2" f0="137.200000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.089600 0.389300 -0.023100 " /> <Waypoint body="TibiaL" p="0.066600 0.115900 -0.056200 " /> <Waypoint body="TalusL" p="0.063400 0.043000 -0.025700 " /> <Waypoint body="TalusL" p="0.091200 0.030200 -0.006400 " /> <Waypoint body="TalusL" p="0.115100 0.008900 0.042100 " /> <Waypoint body="FootPinkyL" p="0.124100 0.009500 0.083100 " /> </Unit> <Unit name="R_Flexor_Digitorum_Longus2" f0="137.200000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.089600 0.389300 -0.023100 " /> <Waypoint body="TibiaR" p="-0.066600 0.115900 -0.056200 " /> <Waypoint body="TalusR" p="-0.063400 0.043000 -0.025700 " /> <Waypoint body="TalusR" p="-0.091200 0.030200 -0.006400 " /> <Waypoint body="TalusR" p="-0.115100 0.008900 0.042100 " /> <Waypoint body="FootPinkyR" p="-0.124100 0.009500 0.083100 " /> </Unit> <Unit name="L_Flexor_Digitorum_Longus3" f0="137.200000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.083900 0.388100 -0.018800 " /> <Waypoint body="TibiaL" p="0.068200 0.120700 -0.056400 " /> <Waypoint body="TalusL" p="0.059800 0.051000 -0.027300 " /> <Waypoint body="TalusL" p="0.106800 0.026000 -0.001100 " /> <Waypoint body="TalusL" p="0.130900 0.008800 0.039000 " /> <Waypoint body="FootPinkyL" p="0.136400 0.007100 0.070500 " /> </Unit> <Unit name="R_Flexor_Digitorum_Longus3" f0="137.200000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.083900 0.388100 -0.018800 " /> <Waypoint body="TibiaR" p="-0.068200 0.120700 -0.056400 " /> <Waypoint body="TalusR" p="-0.059800 0.051000 -0.027300 " /> <Waypoint body="TalusR" p="-0.106800 0.026000 -0.001100 " /> <Waypoint body="TalusR" p="-0.130900 0.008800 0.039000 " /> <Waypoint body="FootPinkyR" p="-0.136400 0.007100 0.070500 " /> </Unit> <Unit name="L_Flexor_Digitorum_Profundus2" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ForeArmL" p="0.594200 1.465300 -0.009100 " /> <Waypoint body="ForeArmL" p="0.651800 1.456600 0.000400 " /> <Waypoint body="ForeArmL" p="0.783100 1.459500 0.023800 " /> <Waypoint body="HandL" p="0.828300 1.470900 0.028400 " /> <Waypoint body="HandL" p="0.955500 1.442100 0.043300 " /> </Unit> <Unit name="R_Flexor_Digitorum_Profundus2" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ForeArmR" p="-0.594200 1.465300 -0.009100 " /> <Waypoint body="ForeArmR" p="-0.651800 1.456600 0.000400 " /> <Waypoint body="ForeArmR" p="-0.783100 1.459500 0.023800 " /> <Waypoint body="HandR" p="-0.828300 1.470900 0.028400 " /> <Waypoint body="HandR" p="-0.955500 1.442100 0.043300 " /> </Unit> <Unit name="L_Flexor_Hallucis" f0="218.400000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.119700 0.393000 -0.038900 " /> <Waypoint body="TibiaL" p="0.074600 0.107600 -0.058000 " /> <Waypoint body="TalusL" p="0.061400 0.067100 -0.063500 " /> <Waypoint body="TalusL" p="0.067800 0.046700 -0.042800 " /> <Waypoint body="TalusL" p="0.064900 0.011400 0.057700 " /> <Waypoint body="FootThumbL" p="0.061700 0.008000 0.107200 " /> </Unit> <Unit name="R_Flexor_Hallucis" f0="218.400000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.119700 0.393000 -0.038900 " /> <Waypoint body="TibiaR" p="-0.074600 0.107600 -0.058000 " /> <Waypoint body="TalusR" p="-0.061400 0.067100 -0.063500 " /> <Waypoint body="TalusR" p="-0.067800 0.046700 -0.042800 " /> <Waypoint body="TalusR" p="-0.064900 0.011400 0.057700 " /> <Waypoint body="FootThumbR" p="-0.061700 0.008000 0.107200 " /> </Unit> <Unit name="L_Flexor_Hallucis1" f0="218.400000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.119700 0.393000 -0.038900 " /> <Waypoint body="TibiaL" p="0.074600 0.107600 -0.058000 " /> <Waypoint body="TalusL" p="0.061400 0.067100 -0.063500 " /> <Waypoint body="TalusL" p="0.067800 0.046700 -0.042800 " /> <Waypoint body="TalusL" p="0.064900 0.011400 0.057700 " /> <Waypoint body="FootThumbL" p="0.061700 0.008000 0.107200 " /> </Unit> <Unit name="R_Flexor_Hallucis1" f0="218.400000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.119700 0.393000 -0.038900 " /> <Waypoint body="TibiaR" p="-0.074600 0.107600 -0.058000 " /> <Waypoint body="TalusR" p="-0.061400 0.067100 -0.063500 " /> <Waypoint body="TalusR" p="-0.067800 0.046700 -0.042800 " /> <Waypoint body="TalusR" p="-0.064900 0.011400 0.057700 " /> <Waypoint body="FootThumbR" p="-0.061700 0.008000 0.107200 " /> </Unit> <Unit name="L_Flexor_Pollicis_Longus" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ForeArmL" p="0.677200 1.471300 0.022400 " /> <Waypoint body="ForeArmL" p="0.784600 1.465900 0.028100 " /> <Waypoint body="HandL" p="0.813900 1.469600 0.030800 " /> <Waypoint body="HandL" p="0.830500 1.466600 0.057100 " /> <Waypoint body="HandL" p="0.878900 1.445600 0.083700 " /> </Unit> <Unit name="R_Flexor_Pollicis_Longus" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ForeArmR" p="-0.677200 1.471300 0.022400 " /> <Waypoint body="ForeArmR" p="-0.784600 1.465900 0.028100 " /> <Waypoint body="HandR" p="-0.813900 1.469600 0.030800 " /> <Waypoint body="HandR" p="-0.830500 1.466600 0.057100 " /> <Waypoint body="HandR" p="-0.878900 1.445600 0.083700 " /> </Unit> <Unit name="L_Gastrocnemius_Lateral_Head" f0="606.400000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurL" p="0.126400 0.562000 -0.005900 " /> <Waypoint body="FemurL" p="0.121900 0.554700 -0.038300 " /> <Waypoint body="TibiaL" p="0.126200 0.505900 -0.066200 " /> <Waypoint body="TibiaL" p="0.112000 0.302400 -0.091700 " /> </Unit> <Unit name="R_Gastrocnemius_Lateral_Head" f0="606.400000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurR" p="-0.126400 0.562000 -0.005900 " /> <Waypoint body="FemurR" p="-0.121900 0.554700 -0.038300 " /> <Waypoint body="TibiaR" p="-0.126200 0.505900 -0.066200 " /> <Waypoint body="TibiaR" p="-0.112000 0.302400 -0.091700 " /> </Unit> <Unit name="L_Gastrocnemius_Medial_Head" f0="1308.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurL" p="0.075000 0.567300 -0.014400 " /> <Waypoint body="FemurL" p="0.095200 0.550700 -0.046600 " /> <Waypoint body="TibiaL" p="0.092400 0.505800 -0.069100 " /> <Waypoint body="TibiaL" p="0.060300 0.273200 -0.059200 " /> </Unit> <Unit name="R_Gastrocnemius_Medial_Head" f0="1308.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurR" p="-0.075000 0.567300 -0.014400 " /> <Waypoint body="FemurR" p="-0.095200 0.550700 -0.046600 " /> <Waypoint body="TibiaR" p="-0.092400 0.505800 -0.069100 " /> <Waypoint body="TibiaR" p="-0.060300 0.273200 -0.059200 " /> </Unit> <Unit name="L_Gluteus_Maximus" f0="370.520000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.053900 1.035800 -0.096200 " /> <Waypoint body="Pelvis" p="0.111500 1.013300 -0.089300 " /> <Waypoint body="FemurL" p="0.153100 0.939700 -0.046600 " /> <Waypoint body="FemurL" p="0.148200 0.872600 -0.016900 " /> </Unit> <Unit name="R_Gluteus_Maximus" f0="370.520000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.053900 1.035800 -0.096200 " /> <Waypoint body="Pelvis" p="-0.111500 1.013300 -0.089300 " /> <Waypoint body="FemurR" p="-0.153100 0.939700 -0.046600 " /> <Waypoint body="FemurR" p="-0.148200 0.872600 -0.016900 " /> </Unit> <Unit name="L_Gluteus_Maximus1" f0="370.520000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.038200 0.988600 -0.099300 " /> <Waypoint body="Pelvis" p="0.103800 0.968800 -0.110800 " /> <Waypoint body="FemurL" p="0.155300 0.900100 -0.049300 " /> <Waypoint body="FemurL" p="0.141600 0.845900 -0.011300 " /> </Unit> <Unit name="R_Gluteus_Maximus1" f0="370.520000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.038200 0.988600 -0.099300 " /> <Waypoint body="Pelvis" p="-0.103800 0.968800 -0.110800 " /> <Waypoint body="FemurR" p="-0.155300 0.900100 -0.049300 " /> <Waypoint body="FemurR" p="-0.141600 0.845900 -0.011300 " /> </Unit> <Unit name="L_Gluteus_Maximus2" f0="370.520000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.029700 0.949800 -0.094300 " /> <Waypoint body="Pelvis" p="0.051700 0.942200 -0.120100 " /> <Waypoint body="Pelvis" p="0.122100 0.906900 -0.097000 " /> <Waypoint body="FemurL" p="0.149300 0.840100 -0.036100 " /> <Waypoint body="FemurL" p="0.134200 0.818200 -0.008900 " /> </Unit> <Unit name="R_Gluteus_Maximus2" f0="370.520000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.029700 0.949800 -0.094300 " /> <Waypoint body="Pelvis" p="-0.051700 0.942200 -0.120100 " /> <Waypoint body="Pelvis" p="-0.122100 0.906900 -0.097000 " /> <Waypoint body="FemurR" p="-0.149300 0.840100 -0.036100 " /> <Waypoint body="FemurR" p="-0.134200 0.818200 -0.008900 " /> </Unit> <Unit name="L_Gluteus_Maximus3" f0="370.520000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.035200 0.919200 -0.080700 " /> <Waypoint body="Pelvis" p="0.066500 0.880800 -0.111700 " /> <Waypoint body="FemurL" p="0.124400 0.851200 -0.076200 " /> <Waypoint body="FemurL" p="0.130200 0.789300 -0.001200 " /> </Unit> <Unit name="R_Gluteus_Maximus3" f0="370.520000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.035200 0.919200 -0.080700 " /> <Waypoint body="Pelvis" p="-0.066500 0.880800 -0.111700 " /> <Waypoint body="FemurR" p="-0.124400 0.851200 -0.076200 " /> <Waypoint body="FemurR" p="-0.130200 0.789300 -0.001200 " /> </Unit> <Unit name="L_Gluteus_Maximus4" f0="370.520000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.045000 0.896000 -0.064800 " /> <Waypoint body="Pelvis" p="0.064500 0.848700 -0.073000 " /> <Waypoint body="FemurL" p="0.115600 0.809100 -0.040200 " /> <Waypoint body="FemurL" p="0.129100 0.772300 0.002800 " /> </Unit> <Unit name="R_Gluteus_Maximus4" f0="370.520000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.045000 0.896000 -0.064800 " /> <Waypoint body="Pelvis" p="-0.064500 0.848700 -0.073000 " /> <Waypoint body="FemurR" p="-0.115600 0.809100 -0.040200 " /> <Waypoint body="FemurR" p="-0.129100 0.772300 0.002800 " /> </Unit> <Unit name="L_Gluteus_Medius" f0="549.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.129500 1.013800 0.028700 " /> <Waypoint body="FemurL" p="0.157200 0.945600 -0.005300 " /> <Waypoint body="FemurL" p="0.157400 0.923400 -0.006700 " /> </Unit> <Unit name="R_Gluteus_Medius" f0="549.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.129500 1.013800 0.028700 " /> <Waypoint body="FemurR" p="-0.157200 0.945600 -0.005300 " /> <Waypoint body="FemurR" p="-0.157400 0.923400 -0.006700 " /> </Unit> <Unit name="L_Gluteus_Medius1" f0="549.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.128200 1.067300 -0.029900 " /> <Waypoint body="FemurL" p="0.155500 0.950900 -0.026500 " /> <Waypoint body="FemurL" p="0.165600 0.891400 -0.008800 " /> </Unit> <Unit name="R_Gluteus_Medius1" f0="549.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.128200 1.067300 -0.029900 " /> <Waypoint body="FemurR" p="-0.155500 0.950900 -0.026500 " /> <Waypoint body="FemurR" p="-0.165600 0.891400 -0.008800 " /> </Unit> <Unit name="L_Gluteus_Medius2" f0="549.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.079200 1.064500 -0.069600 " /> <Waypoint body="Pelvis" p="0.122200 1.028400 -0.073600 " /> <Waypoint body="FemurL" p="0.159000 0.918600 -0.029900 " /> <Waypoint body="FemurL" p="0.159700 0.891200 -0.021000 " /> </Unit> <Unit name="R_Gluteus_Medius2" f0="549.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.079200 1.064500 -0.069600 " /> <Waypoint body="Pelvis" p="-0.122200 1.028400 -0.073600 " /> <Waypoint body="FemurR" p="-0.159000 0.918600 -0.029900 " /> <Waypoint body="FemurR" p="-0.159700 0.891200 -0.021000 " /> </Unit> <Unit name="L_Gluteus_Medius3" f0="549.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.061100 1.008700 -0.087500 " /> <Waypoint body="Pelvis" p="0.088300 0.988400 -0.082900 " /> <Waypoint body="FemurL" p="0.139700 0.936300 -0.048200 " /> <Waypoint body="FemurL" p="0.147400 0.899400 -0.033100 " /> </Unit> <Unit name="R_Gluteus_Medius3" f0="549.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.061100 1.008700 -0.087500 " /> <Waypoint body="Pelvis" p="-0.088300 0.988400 -0.082900 " /> <Waypoint body="FemurR" p="-0.139700 0.936300 -0.048200 " /> <Waypoint body="FemurR" p="-0.147400 0.899400 -0.033100 " /> </Unit> <Unit name="L_Gluteus_Minimus" f0="198.333333" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.068600 0.992600 -0.066800 " /> <Waypoint body="Pelvis" p="0.097800 0.971500 -0.059200 " /> <Waypoint body="FemurL" p="0.152300 0.932100 -0.011500 " /> <Waypoint body="FemurL" p="0.160700 0.905400 -0.004900 " /> </Unit> <Unit name="R_Gluteus_Minimus" f0="198.333333" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.068600 0.992600 -0.066800 " /> <Waypoint body="Pelvis" p="-0.097800 0.971500 -0.059200 " /> <Waypoint body="FemurR" p="-0.152300 0.932100 -0.011500 " /> <Waypoint body="FemurR" p="-0.160700 0.905400 -0.004900 " /> </Unit> <Unit name="L_Gluteus_Minimus1" f0="198.333333" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.098200 1.046000 -0.041700 " /> <Waypoint body="Pelvis" p="0.125700 1.015900 -0.040000 " /> <Waypoint body="FemurL" p="0.156400 0.933100 -0.001700 " /> <Waypoint body="FemurL" p="0.158300 0.893000 0.002200 " /> </Unit> <Unit name="R_Gluteus_Minimus1" f0="198.333333" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.098200 1.046000 -0.041700 " /> <Waypoint body="Pelvis" p="-0.125700 1.015900 -0.040000 " /> <Waypoint body="FemurR" p="-0.156400 0.933100 -0.001700 " /> <Waypoint body="FemurR" p="-0.158300 0.893000 0.002200 " /> </Unit> <Unit name="L_Gluteus_Minimus2" f0="198.333333" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.133400 1.037300 0.009000 " /> <Waypoint body="FemurL" p="0.154800 0.933000 0.005900 " /> <Waypoint body="FemurL" p="0.151600 0.897400 0.004600 " /> </Unit> <Unit name="R_Gluteus_Minimus2" f0="198.333333" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.133400 1.037300 0.009000 " /> <Waypoint body="FemurR" p="-0.154800 0.933000 0.005900 " /> <Waypoint body="FemurR" p="-0.151600 0.897400 0.004600 " /> </Unit> <Unit name="L_Gracilis" f0="137.300000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.011300 0.903100 0.030700 " /> <Waypoint body="FemurL" p="0.048900 0.529700 -0.042600 " /> <Waypoint body="TibiaL" p="0.061600 0.479800 -0.021700 " /> <Waypoint body="TibiaL" p="0.077600 0.465700 -0.003300 " /> </Unit> <Unit name="R_Gracilis" f0="137.300000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.011300 0.903100 0.030700 " /> <Waypoint body="FemurR" p="-0.048900 0.529700 -0.042600 " /> <Waypoint body="TibiaR" p="-0.061600 0.479800 -0.021700 " /> <Waypoint body="TibiaR" p="-0.077600 0.465700 -0.003300 " /> </Unit> <Unit name="L_Inferior_Gemellus" f0="50.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.066200 0.885700 -0.062100 " /> <Waypoint body="FemurL" p="0.124300 0.908300 -0.046900 " /> <Waypoint body="FemurL" p="0.135700 0.908900 -0.033200 " /> </Unit> <Unit name="R_Inferior_Gemellus" f0="50.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.066200 0.885700 -0.062100 " /> <Waypoint body="FemurR" p="-0.124300 0.908300 -0.046900 " /> <Waypoint body="FemurR" p="-0.135700 0.908900 -0.033200 " /> </Unit> <Unit name="L_Infraspinatus1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.091600 1.368800 -0.127100 " /> <Waypoint body="ShoulderL" p="0.187000 1.423800 -0.075700 " /> <Waypoint body="ShoulderL" p="0.203800 1.458100 -0.046900 " /> <Waypoint body="ShoulderL" p="0.198000 1.461500 -0.027000 " /> </Unit> <Unit name="R_Infraspinatus1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.091600 1.368800 -0.127100 " /> <Waypoint body="ShoulderR" p="-0.187000 1.423800 -0.075700 " /> <Waypoint body="ShoulderR" p="-0.203800 1.458100 -0.046900 " /> <Waypoint body="ShoulderR" p="-0.198000 1.461500 -0.027000 " /> </Unit> <Unit name="L_Latissimus_Dorsi" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.000000 1.311400 -0.126600 " /> <Waypoint body="ShoulderL" p="0.115800 1.327800 -0.129300 " /> <Waypoint body="ShoulderL" p="0.152500 1.353400 -0.094600 " /> <Waypoint body="ArmL" p="0.244800 1.415400 -0.039800 " /> <Waypoint body="ArmL" p="0.224400 1.432000 -0.016800 " /> </Unit> <Unit name="R_Latissimus_Dorsi" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.000000 1.311400 -0.126600 " /> <Waypoint body="ShoulderR" p="-0.115800 1.327800 -0.129300 " /> <Waypoint body="ShoulderR" p="-0.152500 1.353400 -0.094600 " /> <Waypoint body="ArmR" p="-0.244800 1.415400 -0.039800 " /> <Waypoint body="ArmR" p="-0.224400 1.432000 -0.016800 " /> </Unit> <Unit name="L_Latissimus_Dorsi3" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Spine" p="0.000600 1.103500 -0.092000 " /> <Waypoint body="Torso" p="0.101200 1.233200 -0.119000 " /> <Waypoint body="Torso" p="0.153700 1.300700 -0.098800 " /> <Waypoint body="ArmL" p="0.279500 1.420700 -0.045900 " /> <Waypoint body="ArmL" p="0.264300 1.422600 -0.024800 " /> <Waypoint body="ArmL" p="0.250400 1.435600 -0.016200 " /> </Unit> <Unit name="R_Latissimus_Dorsi3" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Spine" p="-0.000600 1.103500 -0.092000 " /> <Waypoint body="Torso" p="-0.101200 1.233200 -0.119000 " /> <Waypoint body="Torso" p="-0.153700 1.300700 -0.098800 " /> <Waypoint body="ArmR" p="-0.279500 1.420700 -0.045900 " /> <Waypoint body="ArmR" p="-0.264300 1.422600 -0.024800 " /> <Waypoint body="ArmR" p="-0.250400 1.435600 -0.016200 " /> </Unit> <Unit name="L_Latissimus_Dorsi5" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.077400 1.063600 -0.076000 " /> <Waypoint body="Torso" p="0.117900 1.178400 -0.077500 " /> <Waypoint body="Torso" p="0.169200 1.298600 -0.060000 " /> <Waypoint body="ArmL" p="0.282700 1.416800 -0.032700 " /> <Waypoint body="ArmL" p="0.259200 1.435500 -0.017400 " /> </Unit> <Unit name="R_Latissimus_Dorsi5" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.077400 1.063600 -0.076000 " /> <Waypoint body="Torso" p="-0.117900 1.178400 -0.077500 " /> <Waypoint body="Torso" p="-0.169200 1.298600 -0.060000 " /> <Waypoint body="ArmR" p="-0.282700 1.416800 -0.032700 " /> <Waypoint body="ArmR" p="-0.259200 1.435500 -0.017400 " /> </Unit> <Unit name="L_Longissimus_Capitis3" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.026200 1.428700 -0.102300 " /> <Waypoint body="Torso" p="0.030500 1.500200 -0.074800 " /> <Waypoint body="Neck" p="0.031100 1.565300 -0.039000 " /> <Waypoint body="Head" p="0.057000 1.608800 -0.017300 " /> </Unit> <Unit name="R_Longissimus_Capitis3" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.026200 1.428700 -0.102300 " /> <Waypoint body="Torso" p="-0.030500 1.500200 -0.074800 " /> <Waypoint body="Neck" p="-0.031100 1.565300 -0.039000 " /> <Waypoint body="Head" p="-0.057000 1.608800 -0.017300 " /> </Unit> <Unit name="L_Longissimus_Thoracis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.003600 0.898800 -0.072600 " /> <Waypoint body="Pelvis" p="0.020100 1.003800 -0.104000 " /> <Waypoint body="Spine" p="0.020800 1.092300 -0.080300 " /> <Waypoint body="Torso" p="0.029200 1.198600 -0.095400 " /> <Waypoint body="Torso" p="0.034500 1.274000 -0.119600 " /> <Waypoint body="Torso" p="0.036400 1.393700 -0.115200 " /> <Waypoint body="Torso" p="0.034300 1.454000 -0.093800 " /> <Waypoint body="Neck" p="0.032000 1.501100 -0.040400 " /> </Unit> <Unit name="R_Longissimus_Thoracis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.003600 0.898800 -0.072600 " /> <Waypoint body="Pelvis" p="-0.020100 1.003800 -0.104000 " /> <Waypoint body="Spine" p="-0.020800 1.092300 -0.080300 " /> <Waypoint body="Torso" p="-0.029200 1.198600 -0.095400 " /> <Waypoint body="Torso" p="-0.034500 1.274000 -0.119600 " /> <Waypoint body="Torso" p="-0.036400 1.393700 -0.115200 " /> <Waypoint body="Torso" p="-0.034300 1.454000 -0.093800 " /> <Waypoint body="Neck" p="-0.032000 1.501100 -0.040400 " /> </Unit> <Unit name="L_Longus_Capitis2" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Neck" p="0.019100 1.526900 -0.012500 " /> <Waypoint body="Neck" p="0.010400 1.588100 0.011300 " /> <Waypoint body="Head" p="0.002100 1.622700 0.010300 " /> </Unit> <Unit name="R_Longus_Capitis2" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Neck" p="-0.019100 1.526900 -0.012500 " /> <Waypoint body="Neck" p="-0.010400 1.588100 0.011300 " /> <Waypoint body="Head" p="-0.002100 1.622700 0.010300 " /> </Unit> <Unit name="L_Multifidus" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.009100 0.923600 -0.091700 " /> <Waypoint body="Pelvis" p="0.011100 0.974800 -0.110600 " /> <Waypoint body="Pelvis" p="0.011700 1.013300 -0.100100 " /> <Waypoint body="Spine" p="0.009300 1.107200 -0.077700 " /> <Waypoint body="Torso" p="0.005600 1.179500 -0.085200 " /> <Waypoint body="Torso" p="0.000500 1.284600 -0.120700 " /> </Unit> <Unit name="R_Multifidus" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.009100 0.923600 -0.091700 " /> <Waypoint body="Pelvis" p="-0.011100 0.974800 -0.110600 " /> <Waypoint body="Pelvis" p="-0.011700 1.013300 -0.100100 " /> <Waypoint body="Spine" p="-0.009300 1.107200 -0.077700 " /> <Waypoint body="Torso" p="-0.005600 1.179500 -0.085200 " /> <Waypoint body="Torso" p="-0.000500 1.284600 -0.120700 " /> </Unit> <Unit name="L_Obturator_Externus" f0="50.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.021200 0.911400 0.024700 " /> <Waypoint body="Pelvis" p="0.068400 0.894500 -0.028500 " /> <Waypoint body="FemurL" p="0.138000 0.909800 -0.026500 " /> </Unit> <Unit name="R_Obturator_Externus" f0="50.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.021200 0.911400 0.024700 " /> <Waypoint body="Pelvis" p="-0.068400 0.894500 -0.028500 " /> <Waypoint body="FemurR" p="-0.138000 0.909800 -0.026500 " /> </Unit> <Unit name="L_Obturator_Internus" f0="50.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.018500 0.905800 0.013900 " /> <Waypoint body="Pelvis" p="0.051600 0.905300 -0.058800 " /> <Waypoint body="Pelvis" p="0.074000 0.904600 -0.070500 " /> <Waypoint body="FemurL" p="0.138600 0.914000 -0.030600 " /> </Unit> <Unit name="R_Obturator_Internus" f0="50.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.018500 0.905800 0.013900 " /> <Waypoint body="Pelvis" p="-0.051600 0.905300 -0.058800 " /> <Waypoint body="Pelvis" p="-0.074000 0.904600 -0.070500 " /> <Waypoint body="FemurR" p="-0.138600 0.914000 -0.030600 " /> </Unit> <Unit name="L_Omohyoid" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.125400 1.456800 -0.062000 " /> <Waypoint body="ShoulderL" p="0.111000 1.479500 -0.032300 " /> <Waypoint body="Torso" p="0.046600 1.491300 0.000000 " /> <Waypoint body="ShoulderL" p="0.018300 1.506200 0.025200 " /> <Waypoint body="Head" p="0.013200 1.560100 0.043100 " /> </Unit> <Unit name="R_Omohyoid" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.125400 1.456800 -0.062000 " /> <Waypoint body="ShoulderR" p="-0.111000 1.479500 -0.032300 " /> <Waypoint body="Torso" p="-0.046600 1.491300 0.000000 " /> <Waypoint body="ShoulderR" p="-0.018300 1.506200 0.025200 " /> <Waypoint body="Head" p="-0.013200 1.560100 0.043100 " /> </Unit> <Unit name="L_Palmaris_Longus" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmL" p="0.522100 1.424400 -0.018800 " /> <Waypoint body="ForeArmL" p="0.643800 1.433500 0.000000 " /> <Waypoint body="ForeArmL" p="0.784200 1.459100 0.025400 " /> <Waypoint body="HandL" p="0.886300 1.461800 0.033000 " /> </Unit> <Unit name="R_Palmaris_Longus" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmR" p="-0.522100 1.424400 -0.018800 " /> <Waypoint body="ForeArmR" p="-0.643800 1.433500 0.000000 " /> <Waypoint body="ForeArmR" p="-0.784200 1.459100 0.025400 " /> <Waypoint body="HandR" p="-0.886300 1.461800 0.033000 " /> </Unit> <Unit name="L_Pectineus" f0="177.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.040400 0.927800 0.032700 " /> <Waypoint body="Pelvis" p="0.057200 0.917900 0.046900 " /> <Waypoint body="FemurL" p="0.101100 0.836800 -0.007700 " /> <Waypoint body="FemurL" p="0.112200 0.830300 -0.004200 " /> </Unit> <Unit name="R_Pectineus" f0="177.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.040400 0.927800 0.032700 " /> <Waypoint body="Pelvis" p="-0.057200 0.917900 0.046900 " /> <Waypoint body="FemurR" p="-0.101100 0.836800 -0.007700 " /> <Waypoint body="FemurR" p="-0.112200 0.830300 -0.004200 " /> </Unit> <Unit name="L_Pectoralis_Major" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.054800 1.462800 0.020200 " /> <Waypoint body="Torso" p="0.102100 1.436100 0.043400 " /> <Waypoint body="Torso" p="0.151800 1.405700 0.027600 " /> <Waypoint body="ArmL" p="0.244900 1.401200 0.003200 " /> <Waypoint body="ArmL" p="0.274200 1.446800 -0.009800 " /> </Unit> <Unit name="R_Pectoralis_Major" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.054800 1.462800 0.020200 " /> <Waypoint body="Torso" p="-0.102100 1.436100 0.043400 " /> <Waypoint body="Torso" p="-0.151800 1.405700 0.027600 " /> <Waypoint body="ArmR" p="-0.244900 1.401200 0.003200 " /> <Waypoint body="ArmR" p="-0.274200 1.446800 -0.009800 " /> </Unit> <Unit name="L_Pectoralis_Major2" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.004300 1.367700 0.077300 " /> <Waypoint body="Torso" p="0.076600 1.371900 0.084300 " /> <Waypoint body="Torso" p="0.146000 1.374200 0.050500 " /> <Waypoint body="ArmL" p="0.248300 1.409600 -0.002500 " /> <Waypoint body="ArmL" p="0.247700 1.443900 -0.011600 " /> </Unit> <Unit name="R_Pectoralis_Major2" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.004300 1.367700 0.077300 " /> <Waypoint body="Torso" p="-0.076600 1.371900 0.084300 " /> <Waypoint body="Torso" p="-0.146000 1.374200 0.050500 " /> <Waypoint body="ArmR" p="-0.248300 1.409600 -0.002500 " /> <Waypoint body="ArmR" p="-0.247700 1.443900 -0.011600 " /> </Unit> <Unit name="L_Pectoralis_Minor1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.085500 1.347400 0.079900 " /> <Waypoint body="Torso" p="0.114400 1.373600 0.059700 " /> <Waypoint body="ShoulderL" p="0.159200 1.448100 -0.017700 " /> </Unit> <Unit name="R_Pectoralis_Minor1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.085500 1.347400 0.079900 " /> <Waypoint body="Torso" p="-0.114400 1.373600 0.059700 " /> <Waypoint body="ShoulderR" p="-0.159200 1.448100 -0.017700 " /> </Unit> <Unit name="L_Peroneus_Brevis" f0="305.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.117900 0.283900 -0.044900 " /> <Waypoint body="TibiaL" p="0.112200 0.109700 -0.067800 " /> <Waypoint body="TalusL" p="0.101900 0.067700 -0.069000 " /> <Waypoint body="TalusL" p="0.116900 0.024300 -0.015100 " /> </Unit> <Unit name="R_Peroneus_Brevis" f0="305.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.117900 0.283900 -0.044900 " /> <Waypoint body="TibiaR" p="-0.112200 0.109700 -0.067800 " /> <Waypoint body="TalusR" p="-0.101900 0.067700 -0.069000 " /> <Waypoint body="TalusR" p="-0.116900 0.024300 -0.015100 " /> </Unit> <Unit name="L_Peroneus_Longus" f0="653.300000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.140500 0.479500 -0.026300 " /> <Waypoint body="TibiaL" p="0.152700 0.366000 -0.037900 " /> <Waypoint body="TibiaL" p="0.115600 0.103700 -0.063600 " /> <Waypoint body="TalusL" p="0.104900 0.059000 -0.068700 " /> <Waypoint body="TalusL" p="0.111800 0.039900 -0.041200 " /> <Waypoint body="TalusL" p="0.085000 0.037700 -0.011400 " /> <Waypoint body="TalusL" p="0.072100 0.036600 0.025000 " /> </Unit> <Unit name="R_Peroneus_Longus" f0="653.300000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.140500 0.479500 -0.026300 " /> <Waypoint body="TibiaR" p="-0.152700 0.366000 -0.037900 " /> <Waypoint body="TibiaR" p="-0.115600 0.103700 -0.063600 " /> <Waypoint body="TalusR" p="-0.104900 0.059000 -0.068700 " /> <Waypoint body="TalusR" p="-0.111800 0.039900 -0.041200 " /> <Waypoint body="TalusR" p="-0.085000 0.037700 -0.011400 " /> <Waypoint body="TalusR" p="-0.072100 0.036600 0.025000 " /> </Unit> <Unit name="L_Peroneus_Tertius" f0="45.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.107500 0.133200 -0.052300 " /> <Waypoint body="TibiaL" p="0.112000 0.081900 -0.026000 " /> <Waypoint body="TalusL" p="0.118900 0.034800 0.002500 " /> </Unit> <Unit name="R_Peroneus_Tertius" f0="45.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.107500 0.133200 -0.052300 " /> <Waypoint body="TibiaR" p="-0.112000 0.081900 -0.026000 " /> <Waypoint body="TalusR" p="-0.118900 0.034800 0.002500 " /> </Unit> <Unit name="L_Peroneus_Tertius1" f0="45.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.107500 0.133200 -0.052300 " /> <Waypoint body="TibiaL" p="0.112000 0.081900 -0.026000 " /> <Waypoint body="TalusL" p="0.118900 0.034800 0.002500 " /> </Unit> <Unit name="R_Peroneus_Tertius1" f0="45.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.107500 0.133200 -0.052300 " /> <Waypoint body="TibiaR" p="-0.112000 0.081900 -0.026000 " /> <Waypoint body="TalusR" p="-0.118900 0.034800 0.002500 " /> </Unit> <Unit name="L_Piriformis" f0="148.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.031600 0.981400 -0.089800 " /> <Waypoint body="FemurL" p="0.137200 0.930900 -0.025700 " /> </Unit> <Unit name="R_Piriformis" f0="148.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.031600 0.981400 -0.089800 " /> <Waypoint body="FemurR" p="-0.137200 0.930900 -0.025700 " /> </Unit> <Unit name="L_Piriformis1" f0="148.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.016000 0.936300 -0.088100 " /> <Waypoint body="FemurL" p="0.139700 0.920500 -0.022800 " /> </Unit> <Unit name="R_Piriformis1" f0="148.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.016000 0.936300 -0.088100 " /> <Waypoint body="FemurR" p="-0.139700 0.920500 -0.022800 " /> </Unit> <Unit name="L_Plantaris" f0="50.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurL" p="0.119300 0.565800 -0.013200 " /> <Waypoint body="FemurL" p="0.111500 0.549400 -0.037000 " /> <Waypoint body="TibiaL" p="0.106800 0.498000 -0.049400 " /> <Waypoint body="TibiaL" p="0.073700 0.102800 -0.079600 " /> <Waypoint body="TalusL" p="0.075100 0.037300 -0.098000 " /> </Unit> <Unit name="R_Plantaris" f0="50.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurR" p="-0.119300 0.565800 -0.013200 " /> <Waypoint body="FemurR" p="-0.111500 0.549400 -0.037000 " /> <Waypoint body="TibiaR" p="-0.106800 0.498000 -0.049400 " /> <Waypoint body="TibiaR" p="-0.073700 0.102800 -0.079600 " /> <Waypoint body="TalusR" p="-0.075100 0.037300 -0.098000 " /> </Unit> <Unit name="L_Platysma1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.089300 1.451000 0.033000 " /> <Waypoint body="ShoulderL" p="0.047400 1.475800 0.018700 " /> <Waypoint body="Neck" p="0.030800 1.542500 0.022700 " /> <Waypoint body="Head" p="0.028400 1.555400 0.037200 " /> <Waypoint body="Head" p="0.033500 1.562100 0.068400 " /> </Unit> <Unit name="R_Platysma1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.089300 1.451000 0.033000 " /> <Waypoint body="ShoulderR" p="-0.047400 1.475800 0.018700 " /> <Waypoint body="Neck" p="-0.030800 1.542500 0.022700 " /> <Waypoint body="Head" p="-0.028400 1.555400 0.037200 " /> <Waypoint body="Head" p="-0.033500 1.562100 0.068400 " /> </Unit> <Unit name="L_Popliteus" f0="50.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurL" p="0.137300 0.540300 -0.012900 " /> <Waypoint body="FemurL" p="0.136300 0.526900 -0.033300 " /> <Waypoint body="TibiaL" p="0.116500 0.500900 -0.042900 " /> <Waypoint body="TibiaL" p="0.080500 0.455000 -0.018800 " /> </Unit> <Unit name="R_Popliteus" f0="50.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurR" p="-0.137300 0.540300 -0.012900 " /> <Waypoint body="FemurR" p="-0.136300 0.526900 -0.033300 " /> <Waypoint body="TibiaR" p="-0.116500 0.500900 -0.042900 " /> <Waypoint body="TibiaR" p="-0.080500 0.455000 -0.018800 " /> </Unit> <Unit name="L_Psoas_Major" f0="239.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.014600 1.222700 -0.048100 " /> <Waypoint body="Pelvis" p="0.092000 1.073400 -0.031100 " /> <Waypoint body="Pelvis" p="0.087100 0.931100 0.044900 " /> <Waypoint body="FemurL" p="0.094500 0.881500 0.001300 " /> <Waypoint body="FemurL" p="0.109600 0.850500 -0.015600 " /> </Unit> <Unit name="R_Psoas_Major" f0="239.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.014600 1.222700 -0.048100 " /> <Waypoint body="Pelvis" p="-0.092000 1.073400 -0.031100 " /> <Waypoint body="Pelvis" p="-0.087100 0.931100 0.044900 " /> <Waypoint body="FemurR" p="-0.094500 0.881500 0.001300 " /> <Waypoint body="FemurR" p="-0.109600 0.850500 -0.015600 " /> </Unit> <Unit name="L_Psoas_Major1" f0="239.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Spine" p="0.021400 1.132400 -0.037200 " /> <Waypoint body="Pelvis" p="0.068300 1.033300 -0.020900 " /> <Waypoint body="Pelvis" p="0.074400 0.930400 0.043900 " /> <Waypoint body="FemurL" p="0.092400 0.877400 -0.007300 " /> <Waypoint body="FemurL" p="0.109800 0.856700 -0.009200 " /> </Unit> <Unit name="R_Psoas_Major1" f0="239.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Spine" p="-0.021400 1.132400 -0.037200 " /> <Waypoint body="Pelvis" p="-0.068300 1.033300 -0.020900 " /> <Waypoint body="Pelvis" p="-0.074400 0.930400 0.043900 " /> <Waypoint body="FemurR" p="-0.092400 0.877400 -0.007300 " /> <Waypoint body="FemurR" p="-0.109800 0.856700 -0.009200 " /> </Unit> <Unit name="L_Psoas_Major2" f0="239.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Spine" p="0.018400 1.048500 -0.037400 " /> <Waypoint body="Pelvis" p="0.053600 1.010400 -0.032900 " /> <Waypoint body="Pelvis" p="0.068500 0.929500 0.036600 " /> <Waypoint body="FemurL" p="0.092400 0.879400 0.001500 " /> <Waypoint body="FemurL" p="0.108500 0.856300 -0.014800 " /> </Unit> <Unit name="R_Psoas_Major2" f0="239.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Spine" p="-0.018400 1.048500 -0.037400 " /> <Waypoint body="Pelvis" p="-0.053600 1.010400 -0.032900 " /> <Waypoint body="Pelvis" p="-0.068500 0.929500 0.036600 " /> <Waypoint body="FemurR" p="-0.092400 0.879400 0.001500 " /> <Waypoint body="FemurR" p="-0.108500 0.856300 -0.014800 " /> </Unit> <Unit name="L_Psoas_Minor" f0="239.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.011300 1.221400 -0.045600 " /> <Waypoint body="Spine" p="0.055300 1.120100 -0.011600 " /> <Waypoint body="Pelvis" p="0.063300 0.999200 -0.005400 " /> <Waypoint body="Pelvis" p="0.057800 0.938700 0.019800 " /> </Unit> <Unit name="R_Psoas_Minor" f0="239.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.011300 1.221400 -0.045600 " /> <Waypoint body="Spine" p="-0.055300 1.120100 -0.011600 " /> <Waypoint body="Pelvis" p="-0.063300 0.999200 -0.005400 " /> <Waypoint body="Pelvis" p="-0.057800 0.938700 0.019800 " /> </Unit> <Unit name="L_Quadratus_Femoris" f0="254.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.085900 0.917600 -0.043300 " /> <Waypoint body="Pelvis" p="0.108700 0.897900 -0.049000 " /> <Waypoint body="FemurL" p="0.136100 0.879700 -0.028600 " /> </Unit> <Unit name="R_Quadratus_Femoris" f0="254.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.085900 0.917600 -0.043300 " /> <Waypoint body="Pelvis" p="-0.108700 0.897900 -0.049000 " /> <Waypoint body="FemurR" p="-0.136100 0.879700 -0.028600 " /> </Unit> <Unit name="L_Quadratus_Lumborum1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.077300 1.068600 -0.069300 " /> <Waypoint body="Torso" p="0.047900 1.184700 -0.083700 " /> </Unit> <Unit name="R_Quadratus_Lumborum1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.077300 1.068600 -0.069300 " /> <Waypoint body="Torso" p="-0.047900 1.184700 -0.083700 " /> </Unit> <Unit name="L_Rectus_Femoris" f0="424.400000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.107500 0.980300 0.014400 " /> <Waypoint body="FemurL" p="0.116500 0.941600 0.031000 " /> <Waypoint body="FemurL" p="0.104500 0.602800 0.043200 " /> <Waypoint body="TibiaL" p="0.110800 0.542200 0.034900 " /> </Unit> <Unit name="R_Rectus_Femoris" f0="424.400000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.107500 0.980300 0.014400 " /> <Waypoint body="FemurR" p="-0.116500 0.941600 0.031000 " /> <Waypoint body="FemurR" p="-0.104500 0.602800 0.043200 " /> <Waypoint body="TibiaR" p="-0.110800 0.542200 0.034900 " /> </Unit> <Unit name="L_Rectus_Femoris1" f0="424.400000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.105900 0.973500 0.016500 " /> <Waypoint body="FemurL" p="0.106500 0.926300 0.031800 " /> <Waypoint body="FemurL" p="0.081600 0.606600 0.043100 " /> <Waypoint body="TibiaL" p="0.075700 0.539900 0.032000 " /> </Unit> <Unit name="R_Rectus_Femoris1" f0="424.400000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.105900 0.973500 0.016500 " /> <Waypoint body="FemurR" p="-0.106500 0.926300 0.031800 " /> <Waypoint body="FemurR" p="-0.081600 0.606600 0.043100 " /> <Waypoint body="TibiaR" p="-0.075700 0.539900 0.032000 " /> </Unit> <Unit name="L_Rhomboid_Major2" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.000000 1.426100 -0.119400 " /> <Waypoint body="Torso" p="0.040400 1.408500 -0.128600 " /> <Waypoint body="ShoulderL" p="0.086800 1.391200 -0.123400 " /> </Unit> <Unit name="R_Rhomboid_Major2" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.000000 1.426100 -0.119400 " /> <Waypoint body="Torso" p="-0.040400 1.408500 -0.128600 " /> <Waypoint body="ShoulderR" p="-0.086800 1.391200 -0.123400 " /> </Unit> <Unit name="L_Rhomboid_Minor" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Neck" p="0.000000 1.507800 -0.087400 " /> <Waypoint body="Torso" p="0.022900 1.494400 -0.088100 " /> <Waypoint body="ShoulderL" p="0.090700 1.461100 -0.089900 " /> </Unit> <Unit name="R_Rhomboid_Minor" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Neck" p="-0.000000 1.507800 -0.087400 " /> <Waypoint body="Torso" p="-0.022900 1.494400 -0.088100 " /> <Waypoint body="ShoulderR" p="-0.090700 1.461100 -0.089900 " /> </Unit> <Unit name="L_Sartorius" f0="113.500000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.124100 1.009800 0.031400 " /> <Waypoint body="FemurL" p="0.035200 0.707300 0.026000 " /> <Waypoint body="TibiaL" p="0.054400 0.496500 -0.022400 " /> <Waypoint body="TibiaL" p="0.090700 0.453900 0.009200 " /> </Unit> <Unit name="R_Sartorius" f0="113.500000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.124100 1.009800 0.031400 " /> <Waypoint body="FemurR" p="-0.035200 0.707300 0.026000 " /> <Waypoint body="TibiaR" p="-0.054400 0.496500 -0.022400 " /> <Waypoint body="TibiaR" p="-0.090700 0.453900 0.009200 " /> </Unit> <Unit name="L_Scalene_Anterior1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.058400 1.467000 -0.005800 " /> <Waypoint body="Neck" p="0.035000 1.504000 -0.009500 " /> <Waypoint body="Neck" p="0.018300 1.523600 -0.017300 " /> </Unit> <Unit name="R_Scalene_Anterior1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.058400 1.467000 -0.005800 " /> <Waypoint body="Neck" p="-0.035000 1.504000 -0.009500 " /> <Waypoint body="Neck" p="-0.018300 1.523600 -0.017300 " /> </Unit> <Unit name="L_Scalene_Middle4" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.055600 1.481100 -0.034400 " /> <Waypoint body="Neck" p="0.039900 1.548400 -0.010800 " /> <Waypoint body="Neck" p="0.026700 1.571200 -0.006000 " /> </Unit> <Unit name="R_Scalene_Middle4" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.055600 1.481100 -0.034400 " /> <Waypoint body="Neck" p="-0.039900 1.548400 -0.010800 " /> <Waypoint body="Neck" p="-0.026700 1.571200 -0.006000 " /> </Unit> <Unit name="L_Semimembranosus" f0="581.350000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.075100 0.901700 -0.057400 " /> <Waypoint body="Pelvis" p="0.070100 0.846200 -0.039100 " /> <Waypoint body="FemurL" p="0.053400 0.544300 -0.049600 " /> <Waypoint body="TibiaL" p="0.056700 0.511900 -0.042000 " /> <Waypoint body="TibiaL" p="0.062100 0.490300 -0.029700 " /> </Unit> <Unit name="R_Semimembranosus" f0="581.350000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.075100 0.901700 -0.057400 " /> <Waypoint body="Pelvis" p="-0.070100 0.846200 -0.039100 " /> <Waypoint body="FemurR" p="-0.053400 0.544300 -0.049600 " /> <Waypoint body="TibiaR" p="-0.056700 0.511900 -0.042000 " /> <Waypoint body="TibiaR" p="-0.062100 0.490300 -0.029700 " /> </Unit> <Unit name="L_Semimembranosus1" f0="581.350000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.078400 0.905300 -0.053300 " /> <Waypoint body="FemurL" p="0.093700 0.862300 -0.034300 " /> <Waypoint body="FemurL" p="0.104400 0.560200 -0.047900 " /> <Waypoint body="FemurL" p="0.081200 0.527200 -0.056200 " /> <Waypoint body="TibiaL" p="0.082000 0.495000 -0.042200 " /> </Unit> <Unit name="R_Semimembranosus1" f0="581.350000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.078400 0.905300 -0.053300 " /> <Waypoint body="FemurR" p="-0.093700 0.862300 -0.034300 " /> <Waypoint body="FemurR" p="-0.104400 0.560200 -0.047900 " /> <Waypoint body="FemurR" p="-0.081200 0.527200 -0.056200 " /> <Waypoint body="TibiaR" p="-0.082000 0.495000 -0.042200 " /> </Unit> <Unit name="L_Semispinalis_Capitis1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.026000 1.431100 -0.100400 " /> <Waypoint body="Neck" p="0.014600 1.512500 -0.066300 " /> <Waypoint body="Neck" p="0.010900 1.566200 -0.054700 " /> <Waypoint body="Head" p="0.008700 1.614700 -0.069800 " /> </Unit> <Unit name="R_Semispinalis_Capitis1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.026000 1.431100 -0.100400 " /> <Waypoint body="Neck" p="-0.014600 1.512500 -0.066300 " /> <Waypoint body="Neck" p="-0.010900 1.566200 -0.054700 " /> <Waypoint body="Head" p="-0.008700 1.614700 -0.069800 " /> </Unit> <Unit name="L_Semitendinosus" f0="301.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.068000 0.894100 -0.065200 " /> <Waypoint body="Pelvis" p="0.088100 0.853300 -0.046300 " /> <Waypoint body="FemurL" p="0.085600 0.565300 -0.061100 " /> <Waypoint body="TibiaL" p="0.070400 0.494600 -0.047500 " /> <Waypoint body="TibiaL" p="0.065500 0.471600 -0.026400 " /> <Waypoint body="TibiaL" p="0.079800 0.448400 -0.003800 " /> </Unit> <Unit name="R_Semitendinosus" f0="301.900000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.068000 0.894100 -0.065200 " /> <Waypoint body="Pelvis" p="-0.088100 0.853300 -0.046300 " /> <Waypoint body="FemurR" p="-0.085600 0.565300 -0.061100 " /> <Waypoint body="TibiaR" p="-0.070400 0.494600 -0.047500 " /> <Waypoint body="TibiaR" p="-0.065500 0.471600 -0.026400 " /> <Waypoint body="TibiaR" p="-0.079800 0.448400 -0.003800 " /> </Unit> <Unit name="L_Serratus_Anterior2" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.090100 1.410200 -0.117700 " /> <Waypoint body="ShoulderL" p="0.104600 1.410000 -0.100000 " /> <Waypoint body="Torso" p="0.131200 1.404600 -0.043300 " /> <Waypoint body="Torso" p="0.120600 1.412000 -0.023900 " /> </Unit> <Unit name="R_Serratus_Anterior2" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.090100 1.410200 -0.117700 " /> <Waypoint body="ShoulderR" p="-0.104600 1.410000 -0.100000 " /> <Waypoint body="Torso" p="-0.131200 1.404600 -0.043300 " /> <Waypoint body="Torso" p="-0.120600 1.412000 -0.023900 " /> </Unit> <Unit name="L_Serratus_Anterior4" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.093900 1.348200 -0.128300 " /> <Waypoint body="Torso" p="0.115300 1.354700 -0.095600 " /> <Waypoint body="Torso" p="0.142600 1.328400 -0.011900 " /> <Waypoint body="Torso" p="0.126400 1.312800 0.047600 " /> </Unit> <Unit name="R_Serratus_Anterior4" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.093900 1.348200 -0.128300 " /> <Waypoint body="Torso" p="-0.115300 1.354700 -0.095600 " /> <Waypoint body="Torso" p="-0.142600 1.328400 -0.011900 " /> <Waypoint body="Torso" p="-0.126400 1.312800 0.047600 " /> </Unit> <Unit name="L_Soleus" f0="1792.950000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.087500 0.468500 -0.023700 " /> <Waypoint body="TibiaL" p="0.087000 0.419000 -0.059200 " /> <Waypoint body="TibiaL" p="0.071100 0.150700 -0.060800 " /> <Waypoint body="TibiaL" p="0.073400 0.098300 -0.077500 " /> <Waypoint body="TalusL" p="0.072900 0.029900 -0.095200 " /> </Unit> <Unit name="R_Soleus" f0="1792.950000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.087500 0.468500 -0.023700 " /> <Waypoint body="TibiaR" p="-0.087000 0.419000 -0.059200 " /> <Waypoint body="TibiaR" p="-0.071100 0.150700 -0.060800 " /> <Waypoint body="TibiaR" p="-0.073400 0.098300 -0.077500 " /> <Waypoint body="TalusR" p="-0.072900 0.029900 -0.095200 " /> </Unit> <Unit name="L_Soleus1" f0="1792.950000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.136600 0.490900 -0.045500 " /> <Waypoint body="TibiaL" p="0.130800 0.393000 -0.075700 " /> <Waypoint body="TalusL" p="0.085300 0.086300 -0.085500 " /> <Waypoint body="TalusL" p="0.087600 0.029800 -0.098200 " /> </Unit> <Unit name="R_Soleus1" f0="1792.950000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.136600 0.490900 -0.045500 " /> <Waypoint body="TibiaR" p="-0.130800 0.393000 -0.075700 " /> <Waypoint body="TalusR" p="-0.085300 0.086300 -0.085500 " /> <Waypoint body="TalusR" p="-0.087600 0.029800 -0.098200 " /> </Unit> <Unit name="L_Splenius_Capitis1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Neck" p="0.000000 1.502100 -0.086200 " /> <Waypoint body="Neck" p="0.022400 1.555700 -0.056700 " /> <Waypoint body="Head" p="0.039100 1.595500 -0.048600 " /> <Waypoint body="Head" p="0.060600 1.639000 -0.045600 " /> </Unit> <Unit name="R_Splenius_Capitis1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Neck" p="-0.000000 1.502100 -0.086200 " /> <Waypoint body="Neck" p="-0.022400 1.555700 -0.056700 " /> <Waypoint body="Head" p="-0.039100 1.595500 -0.048600 " /> <Waypoint body="Head" p="-0.060600 1.639000 -0.045600 " /> </Unit> <Unit name="L_Splenius_Cervicis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.000000 1.406700 -0.120100 " /> <Waypoint body="Torso" p="0.035700 1.496300 -0.079500 " /> <Waypoint body="Neck" p="0.039800 1.546300 -0.039200 " /> <Waypoint body="Neck" p="0.037500 1.591800 -0.005600 " /> </Unit> <Unit name="R_Splenius_Cervicis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.000000 1.406700 -0.120100 " /> <Waypoint body="Torso" p="-0.035700 1.496300 -0.079500 " /> <Waypoint body="Neck" p="-0.039800 1.546300 -0.039200 " /> <Waypoint body="Neck" p="-0.037500 1.591800 -0.005600 " /> </Unit> <Unit name="L_Splenius_Cervicis1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.000000 1.344600 -0.125800 " /> <Waypoint body="Torso" p="0.033000 1.415500 -0.112900 " /> <Waypoint body="Torso" p="0.048700 1.492700 -0.070600 " /> <Waypoint body="Neck" p="0.042000 1.540600 -0.028700 " /> <Waypoint body="Neck" p="0.027000 1.571000 -0.006300 " /> </Unit> <Unit name="R_Splenius_Cervicis1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.000000 1.344600 -0.125800 " /> <Waypoint body="Torso" p="-0.033000 1.415500 -0.112900 " /> <Waypoint body="Torso" p="-0.048700 1.492700 -0.070600 " /> <Waypoint body="Neck" p="-0.042000 1.540600 -0.028700 " /> <Waypoint body="Neck" p="-0.027000 1.571000 -0.006300 " /> </Unit> <Unit name="L_Sternocleidomastoid1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.056800 1.465000 0.017500 " /> <Waypoint body="Neck" p="0.054600 1.572800 -0.030900 " /> <Waypoint body="Head" p="0.049000 1.638500 -0.060800 " /> </Unit> <Unit name="R_Sternocleidomastoid1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.056800 1.465000 0.017500 " /> <Waypoint body="Neck" p="-0.054600 1.572800 -0.030900 " /> <Waypoint body="Head" p="-0.049000 1.638500 -0.060800 " /> </Unit> <Unit name="L_Subclavian" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.053000 1.448900 0.021900 " /> <Waypoint body="ShoulderL" p="0.136800 1.460600 -0.024200 " /> </Unit> <Unit name="R_Subclavian" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.053000 1.448900 0.021900 " /> <Waypoint body="ShoulderR" p="-0.136800 1.460600 -0.024200 " /> </Unit> <Unit name="L_Subscapularis1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.094400 1.384800 -0.119400 " /> <Waypoint body="ShoulderL" p="0.153300 1.419200 -0.040900 " /> <Waypoint body="ArmL" p="0.203200 1.406600 -0.016300 " /> <Waypoint body="ArmL" p="0.201300 1.413300 -0.017700 " /> </Unit> <Unit name="R_Subscapularis1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.094400 1.384800 -0.119400 " /> <Waypoint body="ShoulderR" p="-0.153300 1.419200 -0.040900 " /> <Waypoint body="ArmR" p="-0.203200 1.406600 -0.016300 " /> <Waypoint body="ArmR" p="-0.201300 1.413300 -0.017700 " /> </Unit> <Unit name="L_Superior_Gemellus" f0="50.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.061300 0.918700 -0.059200 " /> <Waypoint body="Pelvis" p="0.090400 0.922400 -0.061300 " /> <Waypoint body="FemurL" p="0.140200 0.921300 -0.024800 " /> </Unit> <Unit name="R_Superior_Gemellus" f0="50.000000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.061300 0.918700 -0.059200 " /> <Waypoint body="Pelvis" p="-0.090400 0.922400 -0.061300 " /> <Waypoint body="FemurR" p="-0.140200 0.921300 -0.024800 " /> </Unit> <Unit name="L_Supraspinatus" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.093300 1.467600 -0.081400 " /> <Waypoint body="ShoulderL" p="0.169200 1.460100 -0.044700 " /> <Waypoint body="ArmL" p="0.177300 1.434600 -0.027700 " /> <Waypoint body="ArmL" p="0.182700 1.440100 -0.022100 " /> </Unit> <Unit name="R_Supraspinatus" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.093300 1.467600 -0.081400 " /> <Waypoint body="ShoulderR" p="-0.169200 1.460100 -0.044700 " /> <Waypoint body="ArmR" p="-0.177300 1.434600 -0.027700 " /> <Waypoint body="ArmR" p="-0.182700 1.440100 -0.022100 " /> </Unit> <Unit name="L_Tensor_Fascia_Lata" f0="77.500000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.137300 1.062800 -0.023900 " /> <Waypoint body="FemurL" p="0.162800 0.923700 -0.024600 " /> <Waypoint body="FemurL" p="0.159900 0.811900 -0.004500 " /> <Waypoint body="FemurL" p="0.141700 0.555800 0.005600 " /> <Waypoint body="TibiaL" p="0.132200 0.482000 -0.007900 " /> </Unit> <Unit name="R_Tensor_Fascia_Lata" f0="77.500000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.137300 1.062800 -0.023900 " /> <Waypoint body="FemurR" p="-0.162800 0.923700 -0.024600 " /> <Waypoint body="FemurR" p="-0.159900 0.811900 -0.004500 " /> <Waypoint body="FemurR" p="-0.141700 0.555800 0.005600 " /> <Waypoint body="TibiaR" p="-0.132200 0.482000 -0.007900 " /> </Unit> <Unit name="L_Tensor_Fascia_Lata1" f0="77.500000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.135400 1.030700 0.019200 " /> <Waypoint body="FemurL" p="0.115400 0.920800 0.055100 " /> <Waypoint body="FemurL" p="0.144300 0.607000 0.025000 " /> <Waypoint body="TibiaL" p="0.110600 0.542300 0.034200 " /> </Unit> <Unit name="R_Tensor_Fascia_Lata1" f0="77.500000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.135400 1.030700 0.019200 " /> <Waypoint body="FemurR" p="-0.115400 0.920800 0.055100 " /> <Waypoint body="FemurR" p="-0.144300 0.607000 0.025000 " /> <Waypoint body="TibiaR" p="-0.110600 0.542300 0.034200 " /> </Unit> <Unit name="L_Tensor_Fascia_Lata2" f0="77.500000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.142900 1.049200 0.003200 " /> <Waypoint body="FemurL" p="0.159000 0.917700 0.021900 " /> <Waypoint body="FemurL" p="0.134600 0.557100 0.015600 " /> <Waypoint body="TibiaL" p="0.121600 0.477400 0.004900 " /> </Unit> <Unit name="R_Tensor_Fascia_Lata2" f0="77.500000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.142900 1.049200 0.003200 " /> <Waypoint body="FemurR" p="-0.159000 0.917700 0.021900 " /> <Waypoint body="FemurR" p="-0.134600 0.557100 0.015600 " /> <Waypoint body="TibiaR" p="-0.121600 0.477400 0.004900 " /> </Unit> <Unit name="L_Teres_Major" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.100000 1.336900 -0.131100 " /> <Waypoint body="ShoulderL" p="0.159000 1.374300 -0.101300 " /> <Waypoint body="ArmL" p="0.250600 1.431000 -0.052200 " /> <Waypoint body="ArmL" p="0.243500 1.430100 -0.021200 " /> </Unit> <Unit name="R_Teres_Major" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.100000 1.336900 -0.131100 " /> <Waypoint body="ShoulderR" p="-0.159000 1.374300 -0.101300 " /> <Waypoint body="ArmR" p="-0.250600 1.431000 -0.052200 " /> <Waypoint body="ArmR" p="-0.243500 1.430100 -0.021200 " /> </Unit> <Unit name="L_Tibialis_Anterior" f0="673.700000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.130300 0.488500 -0.010100 " /> <Waypoint body="TibiaL" p="0.072200 0.103100 -0.014000 " /> <Waypoint body="TalusL" p="0.055900 0.061300 -0.009100 " /> <Waypoint body="TalusL" p="0.066100 0.037300 0.024200 " /> </Unit> <Unit name="R_Tibialis_Anterior" f0="673.700000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.130300 0.488500 -0.010100 " /> <Waypoint body="TibiaR" p="-0.072200 0.103100 -0.014000 " /> <Waypoint body="TalusR" p="-0.055900 0.061300 -0.009100 " /> <Waypoint body="TalusR" p="-0.066100 0.037300 0.024200 " /> </Unit> <Unit name="L_Tibialis_Posterior" f0="905.600000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaL" p="0.104800 0.472500 -0.023600 " /> <Waypoint body="TibiaL" p="0.084700 0.137800 -0.050400 " /> <Waypoint body="TibiaL" p="0.053700 0.091000 -0.052300 " /> <Waypoint body="TalusL" p="0.059000 0.048800 -0.021300 " /> <Waypoint body="TalusL" p="0.089900 0.039200 0.010000 " /> </Unit> <Unit name="R_Tibialis_Posterior" f0="905.600000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="TibiaR" p="-0.104800 0.472500 -0.023600 " /> <Waypoint body="TibiaR" p="-0.084700 0.137800 -0.050400 " /> <Waypoint body="TibiaR" p="-0.053700 0.091000 -0.052300 " /> <Waypoint body="TalusR" p="-0.059000 0.048800 -0.021300 " /> <Waypoint body="TalusR" p="-0.089900 0.039200 0.010000 " /> </Unit> <Unit name="L_Triceps_Lateral_Head" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmL" p="0.243900 1.452400 -0.032900 " /> <Waypoint body="ArmL" p="0.319200 1.484700 -0.046100 " /> <Waypoint body="ArmL" p="0.488700 1.477900 -0.024200 " /> <Waypoint body="ForeArmL" p="0.523500 1.467000 -0.027000 " /> </Unit> <Unit name="R_Triceps_Lateral_Head" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmR" p="-0.243900 1.452400 -0.032900 " /> <Waypoint body="ArmR" p="-0.319200 1.484700 -0.046100 " /> <Waypoint body="ArmR" p="-0.488700 1.477900 -0.024200 " /> <Waypoint body="ForeArmR" p="-0.523500 1.467000 -0.027000 " /> </Unit> <Unit name="L_Triceps_Long_Head" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderL" p="0.174200 1.411500 -0.063300 " /> <Waypoint body="ArmL" p="0.256000 1.443300 -0.060300 " /> <Waypoint body="ArmL" p="0.341900 1.464700 -0.075600 " /> <Waypoint body="ArmL" p="0.475900 1.462800 -0.048200 " /> <Waypoint body="ForeArmL" p="0.517200 1.462700 -0.033400 " /> </Unit> <Unit name="R_Triceps_Long_Head" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ShoulderR" p="-0.174200 1.411500 -0.063300 " /> <Waypoint body="ArmR" p="-0.256000 1.443300 -0.060300 " /> <Waypoint body="ArmR" p="-0.341900 1.464700 -0.075600 " /> <Waypoint body="ArmR" p="-0.475900 1.462800 -0.048200 " /> <Waypoint body="ForeArmR" p="-0.517200 1.462700 -0.033400 " /> </Unit> <Unit name="L_Triceps_Medial_Head" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmL" p="0.292100 1.442600 -0.033800 " /> <Waypoint body="ArmL" p="0.435900 1.428200 -0.036500 " /> <Waypoint body="ForeArmL" p="0.518300 1.454400 -0.028300 " /> </Unit> <Unit name="R_Triceps_Medial_Head" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="ArmR" p="-0.292100 1.442600 -0.033800 " /> <Waypoint body="ArmR" p="-0.435900 1.428200 -0.036500 " /> <Waypoint body="ForeArmR" p="-0.518300 1.454400 -0.028300 " /> </Unit> <Unit name="L_Vastus_Intermedius" f0="512.100000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurL" p="0.114500 0.871100 0.000900 " /> <Waypoint body="FemurL" p="0.096900 0.811600 0.033600 " /> <Waypoint body="FemurL" p="0.082200 0.604300 0.036300 " /> <Waypoint body="TibiaL" p="0.079500 0.545000 0.026800 " /> </Unit> <Unit name="R_Vastus_Intermedius" f0="512.100000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurR" p="-0.114500 0.871100 0.000900 " /> <Waypoint body="FemurR" p="-0.096900 0.811600 0.033600 " /> <Waypoint body="FemurR" p="-0.082200 0.604300 0.036300 " /> <Waypoint body="TibiaR" p="-0.079500 0.545000 0.026800 " /> </Unit> <Unit name="L_Vastus_Intermedius1" f0="512.100000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurL" p="0.124000 0.871400 0.002600 " /> <Waypoint body="FemurL" p="0.130600 0.790100 0.032900 " /> <Waypoint body="FemurL" p="0.118200 0.650700 0.036700 " /> <Waypoint body="TibiaL" p="0.095000 0.557500 0.032300 " /> </Unit> <Unit name="R_Vastus_Intermedius1" f0="512.100000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurR" p="-0.124000 0.871400 0.002600 " /> <Waypoint body="FemurR" p="-0.130600 0.790100 0.032900 " /> <Waypoint body="FemurR" p="-0.118200 0.650700 0.036700 " /> <Waypoint body="TibiaR" p="-0.095000 0.557500 0.032300 " /> </Unit> <Unit name="L_Vastus_Lateralis" f0="1127.700000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurL" p="0.148900 0.915000 0.001000 " /> <Waypoint body="FemurL" p="0.133900 0.882600 0.016900 " /> <Waypoint body="FemurL" p="0.105300 0.588000 0.039300 " /> <Waypoint body="TibiaL" p="0.088600 0.549500 0.035000 " /> </Unit> <Unit name="R_Vastus_Lateralis" f0="1127.700000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurR" p="-0.148900 0.915000 0.001000 " /> <Waypoint body="FemurR" p="-0.133900 0.882600 0.016900 " /> <Waypoint body="FemurR" p="-0.105300 0.588000 0.039300 " /> <Waypoint body="TibiaR" p="-0.088600 0.549500 0.035000 " /> </Unit> <Unit name="L_Vastus_Lateralis1" f0="1127.700000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurL" p="0.159500 0.905200 -0.002200 " /> <Waypoint body="FemurL" p="0.153200 0.859200 -0.000000 " /> <Waypoint body="FemurL" p="0.136300 0.597400 0.008600 " /> <Waypoint body="TibiaL" p="0.102300 0.540500 0.035900 " /> </Unit> <Unit name="R_Vastus_Lateralis1" f0="1127.700000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurR" p="-0.159500 0.905200 -0.002200 " /> <Waypoint body="FemurR" p="-0.153200 0.859200 -0.000000 " /> <Waypoint body="FemurR" p="-0.136300 0.597400 0.008600 " /> <Waypoint body="TibiaR" p="-0.102300 0.540500 0.035900 " /> </Unit> <Unit name="L_Vastus_Medialis" f0="721.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurL" p="0.118600 0.871200 0.002900 " /> <Waypoint body="FemurL" p="0.039000 0.680200 0.013200 " /> <Waypoint body="FemurL" p="0.043200 0.604100 0.004100 " /> <Waypoint body="TibiaL" p="0.074700 0.541400 0.024100 " /> </Unit> <Unit name="R_Vastus_Medialis" f0="721.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurR" p="-0.118600 0.871200 0.002900 " /> <Waypoint body="FemurR" p="-0.039000 0.680200 0.013200 " /> <Waypoint body="FemurR" p="-0.043200 0.604100 0.004100 " /> <Waypoint body="TibiaR" p="-0.074700 0.541400 0.024100 " /> </Unit> <Unit name="L_Vastus_Medialis1" f0="721.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurL" p="0.119100 0.867000 0.003500 " /> <Waypoint body="FemurL" p="0.080700 0.669600 0.048800 " /> <Waypoint body="TibiaL" p="0.087600 0.551300 0.035800 " /> </Unit> <Unit name="R_Vastus_Medialis1" f0="721.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurR" p="-0.119100 0.867000 0.003500 " /> <Waypoint body="FemurR" p="-0.080700 0.669600 0.048800 " /> <Waypoint body="TibiaR" p="-0.087600 0.551300 0.035800 " /> </Unit> <Unit name="L_Vastus_Medialis2" f0="721.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurL" p="0.118600 0.871200 0.002900 " /> <Waypoint body="FemurL" p="0.057800 0.647400 0.037200 " /> <Waypoint body="TibiaL" p="0.076800 0.546900 0.031200 " /> </Unit> <Unit name="R_Vastus_Medialis2" f0="721.850000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="FemurR" p="-0.118600 0.871200 0.002900 " /> <Waypoint body="FemurR" p="-0.057800 0.647400 0.037200 " /> <Waypoint body="TibiaR" p="-0.076800 0.546900 0.031200 " /> </Unit> <Unit name="L_iliacus" f0="207.300000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.068000 1.047100 -0.061100 " /> <Waypoint body="Pelvis" p="0.077600 0.942100 0.018000 " /> <Waypoint body="FemurL" p="0.094000 0.880500 -0.015000 " /> <Waypoint body="FemurL" p="0.111200 0.853400 -0.020900 " /> </Unit> <Unit name="R_iliacus" f0="207.300000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.068000 1.047100 -0.061100 " /> <Waypoint body="Pelvis" p="-0.077600 0.942100 0.018000 " /> <Waypoint body="FemurR" p="-0.094000 0.880500 -0.015000 " /> <Waypoint body="FemurR" p="-0.111200 0.853400 -0.020900 " /> </Unit> <Unit name="L_iliacus1" f0="207.300000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.116900 1.069700 -0.032400 " /> <Waypoint body="Pelvis" p="0.084100 0.973000 0.013000 " /> <Waypoint body="Pelvis" p="0.086800 0.917100 0.029700 " /> <Waypoint body="FemurL" p="0.099600 0.877100 -0.009200 " /> <Waypoint body="FemurL" p="0.118700 0.867700 -0.022800 " /> </Unit> <Unit name="R_iliacus1" f0="207.300000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.116900 1.069700 -0.032400 " /> <Waypoint body="Pelvis" p="-0.084100 0.973000 0.013000 " /> <Waypoint body="Pelvis" p="-0.086800 0.917100 0.029700 " /> <Waypoint body="FemurR" p="-0.099600 0.877100 -0.009200 " /> <Waypoint body="FemurR" p="-0.118700 0.867700 -0.022800 " /> </Unit> <Unit name="L_iliacus2" f0="207.300000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.128500 1.033500 0.022400 " /> <Waypoint body="Pelvis" p="0.099900 0.973000 0.031300 " /> <Waypoint body="FemurL" p="0.102000 0.908800 0.014700 " /> <Waypoint body="FemurL" p="0.109200 0.863700 -0.013300 " /> </Unit> <Unit name="R_iliacus2" f0="207.300000" lm="1.000000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.128500 1.033500 0.022400 " /> <Waypoint body="Pelvis" p="-0.099900 0.973000 0.031300 " /> <Waypoint body="FemurR" p="-0.102000 0.908800 0.014700 " /> <Waypoint body="FemurR" p="-0.109200 0.863700 -0.013300 " /> </Unit> <Unit name="L_iliocostalis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.003600 0.898900 -0.073600 " /> <Waypoint body="Pelvis" p="0.025200 1.026700 -0.101000 " /> <Waypoint body="Spine" p="0.052800 1.110900 -0.079000 " /> <Waypoint body="Torso" p="0.058200 1.174400 -0.093400 " /> <Waypoint body="Torso" p="0.063900 1.239200 -0.126200 " /> <Waypoint body="Torso" p="0.050100 1.433400 -0.104800 " /> <Waypoint body="Torso" p="0.041100 1.491600 -0.062400 " /> <Waypoint body="Neck" p="0.022400 1.538000 -0.010700 " /> </Unit> <Unit name="R_iliocostalis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.003600 0.898900 -0.073600 " /> <Waypoint body="Pelvis" p="-0.025200 1.026700 -0.101000 " /> <Waypoint body="Spine" p="-0.052800 1.110900 -0.079000 " /> <Waypoint body="Torso" p="-0.058200 1.174400 -0.093400 " /> <Waypoint body="Torso" p="-0.063900 1.239200 -0.126200 " /> <Waypoint body="Torso" p="-0.050100 1.433400 -0.104800 " /> <Waypoint body="Torso" p="-0.041100 1.491600 -0.062400 " /> <Waypoint body="Neck" p="-0.022400 1.538000 -0.010700 " /> </Unit> <Unit name="L_Rectus_Abdominis1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.022100 0.922600 0.050800 " /> <Waypoint body="Pelvis" p="0.040200 1.029200 0.086100 " /> <Waypoint body="Torso" p="0.060100 1.110900 0.089400 " /> <Waypoint body="Torso" p="0.063500 1.170800 0.092300 " /> <Waypoint body="Torso" p="0.076200 1.304200 0.092900 " /> </Unit> <Unit name="R_Rectus_Abdominis1" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.022100 0.922600 0.050800 " /> <Waypoint body="Pelvis" p="-0.040200 1.029200 0.086100 " /> <Waypoint body="Torso" p="-0.060100 1.110900 0.089400 " /> <Waypoint body="Torso" p="-0.063500 1.170800 0.092300 " /> <Waypoint body="Torso" p="-0.076200 1.304200 0.092900 " /> </Unit> <Unit name="L_Serratus_Posterior_Inferior" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Spine" p="0.000000 1.139400 -0.092000 " /> <Waypoint body="Torso" p="0.072300 1.156800 -0.084000 " /> <Waypoint body="Torso" p="0.080500 1.162800 -0.075700 " /> </Unit> <Unit name="R_Serratus_Posterior_Inferior" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Spine" p="-0.000000 1.139400 -0.092000 " /> <Waypoint body="Torso" p="-0.072300 1.156800 -0.084000 " /> <Waypoint body="Torso" p="-0.080500 1.162800 -0.075700 " /> </Unit> <Unit name="L_Transversus_Abdominis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.054100 1.043200 -0.092800 " /> <Waypoint body="Torso" p="0.063200 1.172600 -0.079300 " /> </Unit> <Unit name="R_Transversus_Abdominis" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.054100 1.043200 -0.092800 " /> <Waypoint body="Torso" p="-0.063200 1.172600 -0.079300 " /> </Unit> <Unit name="L_Transversus_Abdominis2" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.135600 1.040700 0.017800 " /> <Waypoint body="Torso" p="0.111200 1.137900 -0.011800 " /> </Unit> <Unit name="R_Transversus_Abdominis2" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.135600 1.040700 0.017800 " /> <Waypoint body="Torso" p="-0.111200 1.137900 -0.011800 " /> </Unit> <Unit name="L_Transversus_Abdominis4" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="0.016000 0.927700 0.053500 " /> <Waypoint body="Torso" p="0.038900 1.181000 0.093000 " /> <Waypoint body="Torso" p="0.021000 1.297800 0.093300 " /> </Unit> <Unit name="R_Transversus_Abdominis4" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Pelvis" p="-0.016000 0.927700 0.053500 " /> <Waypoint body="Torso" p="-0.038900 1.181000 0.093000 " /> <Waypoint body="Torso" p="-0.021000 1.297800 0.093300 " /> </Unit> <Unit name="L_Trapezius" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.000000 1.179900 -0.096800 " /> <Waypoint body="Torso" p="0.034800 1.279400 -0.128000 " /> <Waypoint body="Torso" p="0.080500 1.345200 -0.135600 " /> <Waypoint body="ShoulderL" p="0.131400 1.447600 -0.102400 " /> </Unit> <Unit name="R_Trapezius" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.000000 1.179900 -0.096800 " /> <Waypoint body="Torso" p="-0.034800 1.279400 -0.128000 " /> <Waypoint body="Torso" p="-0.080500 1.345200 -0.135600 " /> <Waypoint body="ShoulderR" p="-0.131400 1.447600 -0.102400 " /> </Unit> <Unit name="L_Trapezius3" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="0.000000 1.437300 -0.119300 " /> <Waypoint body="ShoulderL" p="0.085900 1.476100 -0.103200 " /> <Waypoint body="ShoulderL" p="0.122700 1.472800 -0.092500 " /> <Waypoint body="ShoulderL" p="0.145500 1.455600 -0.091900 " /> </Unit> <Unit name="R_Trapezius3" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Torso" p="-0.000000 1.437300 -0.119300 " /> <Waypoint body="ShoulderR" p="-0.085900 1.476100 -0.103200 " /> <Waypoint body="ShoulderR" p="-0.122700 1.472800 -0.092500 " /> <Waypoint body="ShoulderR" p="-0.145500 1.455600 -0.091900 " /> </Unit> <Unit name="L_Trapezius5" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Neck" p="0.000000 1.563000 -0.063600 " /> <Waypoint body="Neck" p="0.039300 1.549500 -0.062400 " /> <Waypoint body="ShoulderL" p="0.113300 1.496700 -0.064900 " /> <Waypoint body="ShoulderL" p="0.198900 1.460800 -0.056900 " /> </Unit> <Unit name="R_Trapezius5" f0="1000.000000" lm="1.200000" lt="0.200000" pen_angle="0.000000" lmax="-0.100000"> <Waypoint body="Neck" p="-0.000000 1.563000 -0.063600 " /> <Waypoint body="Neck" p="-0.039300 1.549500 -0.062400 " /> <Waypoint body="ShoulderR" p="-0.113300 1.496700 -0.064900 " /> <Waypoint body="ShoulderR" p="-0.198900 1.460800 -0.056900 " /> </Unit> </Muscle>
120,105
XML
66.36175
133
0.602073
RoboticExplorationLab/Deep-ILC/envs/assets/snu/ground.xml
<Skeleton name="Ground"> <Node name="ground" parent="None" > <Body type="Box" mass="15.0" size="1000.0 1.0 1000.0" contact="On" color="1.2 1.2 1.2 1.0"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0.0 -0.49958 0.0"/> </Body> <Joint type="Weld"> <Transformation linear="1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0" translation="0.0 0.0 0.0"/> </Joint> </Node> </Skeleton>
457
XML
40.63636
105
0.538293
RoboticExplorationLab/Deep-ILC/dflex/setup.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import setuptools setuptools.setup( name="dflex", version="0.0.1", author="NVIDIA", author_email="mmacklin@nvidia.com", description="Differentiable Multiphysics for Python", long_description="", long_description_content_type="text/markdown", # url="https://github.com/pypa/sampleproject", packages=setuptools.find_packages(), package_data={"": ["*.h"]}, classifiers=[ "Programming Language :: Python :: 3", "Operating System :: OS Independent", ], install_requires=["ninja", "torch"], )
983
Python
35.444443
76
0.713123
RoboticExplorationLab/Deep-ILC/dflex/README.md
# A Differentiable Multiphysics Engine for PyTorch dFlex is a physics engine for Python. It is written entirely in PyTorch and supports reverse mode differentiation w.r.t. to any simulation inputs. It includes a USD-based visualization library (`dflex.render`), which can generate time-sampled USD files, or update an existing stage on-the-fly. ## Prerequisites * Python 3.6 * PyTorch 1.4.0 or higher * Pixar USD lib (for visualization) Pre-built USD Python libraries can be downloaded from https://developer.nvidia.com/usd, once they are downloaded you should follow the instructions to add them to your PYTHONPATH environment variable. ## Using the built-in backend By default dFlex uses the built-in PyTorch cpp-extensions mechanism to compile auto-generated simulation kernels. - Windows users should ensure they have Visual Studio 2019 installed ## Setup and Running To use the engine you can import first the simulation module: ```python import dflex.sim ``` To build physical models there is a helper class available in `dflex.sim.ModelBuilder`. This can be used to create models programmatically from Python. For example, to create a chain of particles: ```python builder = dflex.sim.ModelBuilder() # anchor point (zero mass) builder.add_particle((0, 1.0, 0.0), (0.0, 0.0, 0.0), 0.0) # build chain for i in range(1,10): builder.add_particle((i, 1.0, 0.0), (0.0, 0.0, 0.0), 1.0) builder.add_spring(i-1, i, 1.e+3, 0.0, 0) # add ground plane builder.add_shape_plane((0.0, 1.0, 0.0, 0.0), 0) ``` Once you have built your model you must convert it to a finalized PyTorch simulation data structure using `finalize()`: ```python model = builder.finalize('cpu') ``` The model object represents static (non-time varying) data such as constraints, collision shapes, etc. The model is stored in PyTorch tensors, allowing differentiation with respect to both model and state. ## Time Stepping To advance the simulation forward in time (forward dynamics), we use an `integrator` object. dFlex currently offers semi-implicit and fully implicit (planned), via. the `dflex.sim.ExplicitIntegrator`, and `dflex.sim.ImplicitIntegrator` classes as follows: ```python sim_dt = 1.0/60.0 sim_steps = 100 integrator = dflex.sim.ExplicitIntegrator() for i in range(0, sim_steps): state = integrator.forward(model, state, sim_dt) ``` ## Rendering To visualize the scene dFlex supports a USD-based update via. the `dflex.render.UsdRenderer` class. To create a renderer you must first create the USD stage, and the physical model. ```python import dflex.render stage = Usd.Stage.CreateNew("test.usda") renderer = dflex.render.UsdRenderer(model, stage) renderer.draw_points = True renderer.draw_springs = True renderer.draw_shapes = True ``` Each frame the renderer should be updated with the current model state and the current elapsed simulation time: ```python renderer.update(state, sim_time) ``` ## Contact Miles Macklin (mmacklin@nvidia.com)
3,065
Markdown
32.326087
255
0.730832
RoboticExplorationLab/Deep-ILC/dflex/extension/dflex.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """dFlex Kit extension Allows setting up, training, and running inference on dFlex optimization environments. """ import os import subprocess import carb import carb.input import math import numpy as np import omni.kit.ui import omni.appwindow import omni.kit.editor import omni.timeline import omni.usd import omni.ui as ui from pathlib import Path ICON_PATH = Path(__file__).parent.parent.joinpath("icons") from pxr import Usd, UsdGeom, Sdf, Gf import torch from omni.kit.settings import create_setting_widget, create_setting_widget_combo, SettingType, get_settings_interface KIT_GREEN = 0xFF8A8777 LABEL_PADDING = 120 DARK_WINDOW_STYLE = { "Button": {"background_color": 0xFF292929, "margin": 3, "padding": 3, "border_radius": 2}, "Button.Label": {"color": 0xFFCCCCCC}, "Button:hovered": {"background_color": 0xFF9E9E9E}, "Button:pressed": {"background_color": 0xC22A8778}, "VStack::main_v_stack": {"secondary_color": 0x0, "margin_width": 10, "margin_height": 0}, "VStack::frame_v_stack": {"margin_width": 15, "margin_height": 10}, "Rectangle::frame_background": {"background_color": 0xFF343432, "border_radius": 5}, "Field::models": {"background_color": 0xFF23211F, "font_size": 14, "color": 0xFFAAAAAA, "border_radius": 4.0}, "Frame": {"background_color": 0xFFAAAAAA}, "Label": {"font_size": 14, "color": 0xFF8A8777}, "Label::status": {"font_size": 14, "color": 0xFF8AFF77} } CollapsableFrame_style = { "CollapsableFrame": { "background_color": 0xFF343432, "secondary_color": 0xFF343432, "color": 0xFFAAAAAA, "border_radius": 4.0, "border_color": 0x0, "border_width": 0, "font_size": 14, "padding": 0, }, "HStack::header": {"margin": 5}, "CollapsableFrame:hovered": {"secondary_color": 0xFF3A3A3A}, "CollapsableFrame:pressed": {"secondary_color": 0xFF343432}, } experiment = None class Extension: def __init__(self): self.MENU_SHOW_WINDOW = "Window/dFlex" self.MENU_INSERT_REFERENCE = "Utilities/Insert Reference" self._editor_window = None self._window_Frame = None self.time = 0.0 self.plot = None self.log = None self.status = None self.mode = 'stopped' self.properties = {} # add some helper menus self.menus = [] def on_shutdown(self): self._editor_window = None self.menus = [] #self.input.unsubscribe_to_keyboard_events(self.appwindow.get_keyboard(), self.key_sub) def on_startup(self): self.appwindow = omni.appwindow.get_default_app_window() self.editor = omni.kit.editor.get_editor_interface() self.input = carb.input.acquire_input_interface() self.timeline = omni.timeline.get_timeline_interface() self.usd_context = omni.usd.get_context() # event subscriptions self.stage_sub = self.usd_context.get_stage_event_stream().create_subscription_to_pop(self.on_stage, name="dFlex") self.update_sub = self.editor.subscribe_to_update_events(self.on_update) #self.key_sub = self.input.subscribe_to_keyboard_events(self.appwindow.get_keyboard(), self.on_key) self.menus.append(omni.kit.ui.get_editor_menu().add_item(self.MENU_SHOW_WINDOW, self.ui_on_menu, True, 11)) self.menus.append(omni.kit.ui.get_editor_menu().add_item(self.MENU_INSERT_REFERENCE, self.ui_on_menu)) self.reload() self.build_ui() def format(self, s): return s.replace("_", " ").title() def add_float_field(self, label, x, low=0.0, high=1.0): with ui.HStack(): ui.Label(self.format(label), width=120) self.add_property(label, ui.FloatSlider(name="value", width=150, min=low, max=high), x) def add_int_field(self, label, x, low=0, high=100): with ui.HStack(): ui.Label(self.format(label), width=120) self.add_property(label, ui.IntSlider(name="value", width=150, min=low, max=high), x) def add_combo_field(self, label, i, options): with ui.HStack(): ui.Label(self.format(label), width=120) ui.ComboBox(i, *options, width=150) # todo: how does the model work for combo boxes in omni.ui def add_bool_field(self, label, b): with ui.HStack(): ui.Label(self.format(label), width=120) self.add_property(label, ui.CheckBox(width=10), b) def add_property(self, label, widget, value): self.properties[label] = widget widget.model.set_value(value) def ui_on_menu(self, menu, value): if menu == self.MENU_SHOW_WINDOW: if self.window: if value: self.window.show() else: self.window.hide() omni.kit.ui.get_editor_menu().set_value(self.STAGE_SCRIPT_WINDOW_MENU, value) if menu == self.MENU_INSERT_REFERENCE: self.file_pick = omni.kit.ui.FilePicker("Select USD File", file_type=omni.kit.ui.FileDialogSelectType.FILE) self.file_pick.set_file_selected_fn(self.ui_on_select_ref_fn) self.file_pick.show(omni.kit.ui.FileDialogDataSource.LOCAL) def ui_on_select_ref_fn(self, real_path): file = os.path.normpath(real_path) name = os.path.basename(file) stem = os.path.splitext(name)[0] stage = self.usd_context.get_stage() stage_path = stage.GetRootLayer().realPath base = os.path.commonpath([real_path, stage_path]) rel_path = os.path.relpath(real_path, base) over = stage.OverridePrim('/' + stem) over.GetReferences().AddReference(rel_path) def ui_on_select_script_fn(self): # file picker self.file_pick = omni.kit.ui.FilePicker("Select Python Script", file_type=omni.kit.ui.FileDialogSelectType.FILE) self.file_pick.set_file_selected_fn(self.set_stage_script) self.file_pick.add_filter("Python Files (*.py)", ".*.py") self.file_pick.show(omni.kit.ui.FileDialogDataSource.LOCAL) def ui_on_clear_script_fn(self, widget): self.clear_stage_script() def ui_on_select_network_fn(self): # file picker self.file_pick = omni.kit.ui.FilePicker("Select Model", file_type=omni.kit.ui.FileDialogSelectType.FILE) self.file_pick.set_file_selected_fn(self.set_network) self.file_pick.add_filter("PyTorch Files (*.pt)", ".*.pt") self.file_pick.show(omni.kit.ui.FileDialogDataSource.LOCAL) # build panel def build_ui(self): stage = self.usd_context.get_stage() self._editor_window = ui.Window("dFlex", width=450, height=800) self._editor_window.frame.set_style(DARK_WINDOW_STYLE) with self._editor_window.frame: with ui.VStack(): self._window_Frame = ui.ScrollingFrame( name="canvas", horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ) with self._window_Frame: with ui.VStack(spacing=6, name="main_v_stack"): ui.Spacer(height=5) with ui.CollapsableFrame(title="Experiment", height=60, style=CollapsableFrame_style): with ui.VStack(spacing=4, name="frame_v_stack"): with ui.HStack(): ui.Label("Script", name="label", width=120) s = "" if (self.get_stage_script() != None): s = self.get_stage_script() ui.StringField(name="models", tooltip="Training Python script").model.set_value(self.get_stage_script()) ui.Button("", image_url="resources/icons/folder.png", width=15, image_width=15, clicked_fn=self.ui_on_select_script_fn) ui.Button("Clear", width=15, clicked_fn=self.clear_stage_script) ui.Button("Reload", width=15, clicked_fn=self.reload) with ui.HStack(): ui.Label("Hot Reload", width=100) ui.CheckBox(width=10).model.set_value(False) if (experiment): with ui.CollapsableFrame(height=60, title="Simulation Settings", style=CollapsableFrame_style): with ui.VStack(spacing=4, name="frame_v_stack"): self.add_int_field("sim_substeps", 4, 1, 100) self.add_float_field("sim_duration", 5.0, 0.0, 30.0) with ui.CollapsableFrame(title="Training Settings", height=60, style=CollapsableFrame_style): with ui.VStack(spacing=4, name="frame_v_stack"): self.add_int_field("train_iters", 64, 1, 100) self.add_float_field("train_rate", 0.1, 0.0, 10.0) self.add_combo_field("train_optimizer", 0, ["GD", "SGD", "L-BFGS"]) with ui.CollapsableFrame(title="Actions", height=10, style=CollapsableFrame_style): with ui.VStack(spacing=4, name="frame_v_stack"): with ui.HStack(): ui.Label("Network", name="label", width=120) s = "" if (self.get_network() != None): s = self.get_network() ui.StringField(name="models", tooltip="Pretrained PyTorch network").model.set_value(s) ui.Button("", image_url="resources/icons/folder.png", width=15, image_width=15, clicked_fn=self.ui_on_select_network_fn) ui.Button("Clear", width=15, clicked_fn=self.clear_network) with ui.HStack(): p = (1.0/6.0)*100.0 ui.Button("Run", width=ui.Percent(p), clicked_fn=self.run) ui.Button("Train", width=ui.Percent(p), clicked_fn=self.train) ui.Button("Stop", width=ui.Percent(p), clicked_fn=self.stop) ui.Button("Reset", width=ui.Percent(p), clicked_fn=self.reset) self.add_bool_field("record", True) with ui.HStack(): ui.Label("Status: ", width=120) self.status = ui.Label("", name="status", width=200) with ui.CollapsableFrame(title="Loss", style=CollapsableFrame_style): data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0] self.plot = ui.Plot(ui.Type.LINE, -1.0, 1.0, *data, height=200, style={"color": 0xff00ffFF}) # with ui.ScrollingFrame( # name="log", # horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, # height=200, # width=ui.Percent(95) # ): with ui.CollapsableFrame(title="Log", style=CollapsableFrame_style): with ui.VStack(spacing=4, name="frame_v_stack"): self.log = ui.Label("", height=200) def reload(self): path = self.get_stage_script() if (path): # read code to string file = open(path) code = file.read() file.close() # run it in the local environment exec(code, globals(), globals()) self.build_ui() # methods for storing script in stage metadata def get_stage_script(self): stage = self.usd_context.get_stage() custom_data = stage.GetEditTarget().GetLayer().customLayerData print(custom_data) if "script" in custom_data: return custom_data["script"] else: return None def set_stage_script(self, real_path): path = os.path.normpath(real_path) print("Setting stage script to: " + str(path)) stage = self.usd_context.get_stage() with Sdf.ChangeBlock(): custom_data = stage.GetEditTarget().GetLayer().customLayerData custom_data["script"] = path stage.GetEditTarget().GetLayer().customLayerData = custom_data # rebuild ui self.build_ui() def clear_stage_script(self): stage = self.usd_context.get_stage() with Sdf.ChangeBlock(): custom_data = stage.GetEditTarget().GetLayer().customLayerData if "script" in custom_data: del custom_data["script"] stage.GetEditTarget().GetLayer().customLayerData = custom_data self.build_ui() def set_network(self, real_path): path = os.path.normpath(real_path) experiment.network_file = path self.build_ui() def get_network(self): return experiment.network_file def clear_network(self): experiment.network_file = None self.build_ui() def on_key(self, event, *args, **kwargs): # if event.keyboard == self.appwindow.get_keyboard(): # if event.type == carb.input.KeyboardEventType.KEY_PRESS: # if event.input == carb.input.KeyboardInput.ESCAPE: # self.stop() # return True pass def on_stage(self, stage_event): if stage_event.type == int(omni.usd.StageEventType.OPENED): self.build_ui() self.reload() def on_update(self, dt): if (experiment): stage = self.usd_context.get_stage() stage.SetStartTimeCode(0.0) stage.SetEndTimeCode(experiment.render_time*60.0) stage.SetTimeCodesPerSecond(60.0) # pass parameters to the experiment if ('record' in self.properties): experiment.record = self.properties['record'].model.get_value_as_bool() # experiment.train_rate = self.get_property('train_rate') # experiment.train_iters = self.get_property('train_iters') # experiment.sim_duration = self.get_property('sim_duration') # experiment.sim_substeps = self.get_property('sim_substeps') if (self.mode == 'training'): experiment.train() # update error plot if (self.plot): self.plot.scale_min = np.min(experiment.train_loss) self.plot.scale_max = np.max(experiment.train_loss) self.plot.set_data(*experiment.train_loss) elif (self.mode == 'inference'): experiment.run() # update stage time (allow scrubbing while stopped) if (self.mode != 'stopped'): self.timeline.set_current_time(experiment.render_time*60.0) # update log if (self.log): self.log.text = df.util.log_output def set_status(self, str): self.status.text = str def train(self): experiment.reset() self.mode = 'training' # update status self.set_status('Training in progress, press [ESC] to cancel') def run(self): experiment.reset() self.mode = 'inference' # update status self.set_status('Inference in progress, press [ESC] to cancel') def stop(self): self.mode = 'stopped' # update status self.set_status('Stopped') def reset(self): experiment.reset() self.stop() def get_extension(): return Extension()
16,913
Python
35.689805
160
0.549814
RoboticExplorationLab/Deep-ILC/dflex/dflex/mat33.h
#pragma once //---------------------------------------------------------- // mat33 struct mat33 { inline CUDA_CALLABLE mat33(float3 c0, float3 c1, float3 c2) { data[0][0] = c0.x; data[1][0] = c0.y; data[2][0] = c0.z; data[0][1] = c1.x; data[1][1] = c1.y; data[2][1] = c1.z; data[0][2] = c2.x; data[1][2] = c2.y; data[2][2] = c2.z; } inline CUDA_CALLABLE mat33(float m00=0.0f, float m01=0.0f, float m02=0.0f, float m10=0.0f, float m11=0.0f, float m12=0.0f, float m20=0.0f, float m21=0.0f, float m22=0.0f) { data[0][0] = m00; data[1][0] = m10; data[2][0] = m20; data[0][1] = m01; data[1][1] = m11; data[2][1] = m21; data[0][2] = m02; data[1][2] = m12; data[2][2] = m22; } CUDA_CALLABLE float3 get_row(int index) const { return (float3&)data[index]; } CUDA_CALLABLE void set_row(int index, const float3& v) { (float3&)data[index] = v; } CUDA_CALLABLE float3 get_col(int index) const { return float3(data[0][index], data[1][index], data[2][index]); } CUDA_CALLABLE void set_col(int index, const float3& v) { data[0][index] = v.x; data[1][index] = v.y; data[2][index] = v.z; } // row major storage assumed to be compatible with PyTorch float data[3][3]; }; #ifdef CUDA inline __device__ void atomic_add(mat33 * addr, mat33 value) { atomicAdd(&((addr -> data)[0][0]), value.data[0][0]); atomicAdd(&((addr -> data)[1][0]), value.data[1][0]); atomicAdd(&((addr -> data)[2][0]), value.data[2][0]); atomicAdd(&((addr -> data)[0][1]), value.data[0][1]); atomicAdd(&((addr -> data)[1][1]), value.data[1][1]); atomicAdd(&((addr -> data)[2][1]), value.data[2][1]); atomicAdd(&((addr -> data)[0][2]), value.data[0][2]); atomicAdd(&((addr -> data)[1][2]), value.data[1][2]); atomicAdd(&((addr -> data)[2][2]), value.data[2][2]); } #endif inline CUDA_CALLABLE void adj_mat33(float3 c0, float3 c1, float3 c2, float3& a0, float3& a1, float3& a2, const mat33& adj_ret) { // column constructor a0 += adj_ret.get_col(0); a1 += adj_ret.get_col(1); a2 += adj_ret.get_col(2); } inline CUDA_CALLABLE void adj_mat33(float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22, float& a00, float& a01, float& a02, float& a10, float& a11, float& a12, float& a20, float& a21, float& a22, const mat33& adj_ret) { printf("todo\n"); } inline CUDA_CALLABLE float index(const mat33& m, int row, int col) { return m.data[row][col]; } inline CUDA_CALLABLE mat33 add(const mat33& a, const mat33& b) { mat33 t; for (int i=0; i < 3; ++i) { for (int j=0; j < 3; ++j) { t.data[i][j] = a.data[i][j] + b.data[i][j]; } } return t; } inline CUDA_CALLABLE mat33 mul(const mat33& a, float b) { mat33 t; for (int i=0; i < 3; ++i) { for (int j=0; j < 3; ++j) { t.data[i][j] = a.data[i][j]*b; } } return t; } inline CUDA_CALLABLE float3 mul(const mat33& a, const float3& b) { float3 r = a.get_col(0)*b.x + a.get_col(1)*b.y + a.get_col(2)*b.z; return r; } inline CUDA_CALLABLE mat33 mul(const mat33& a, const mat33& b) { mat33 t; for (int i=0; i < 3; ++i) { for (int j=0; j < 3; ++j) { for (int k=0; k < 3; ++k) { t.data[i][j] += a.data[i][k]*b.data[k][j]; } } } return t; } inline CUDA_CALLABLE mat33 transpose(const mat33& a) { mat33 t; for (int i=0; i < 3; ++i) { for (int j=0; j < 3; ++j) { t.data[i][j] = a.data[j][i]; } } return t; } inline CUDA_CALLABLE float determinant(const mat33& m) { return dot(float3(m.data[0]), cross(float3(m.data[1]), float3(m.data[2]))); } inline CUDA_CALLABLE mat33 outer(const float3& a, const float3& b) { return mat33(a*b.x, a*b.y, a*b.z); } inline CUDA_CALLABLE mat33 skew(const float3& a) { mat33 out(0.0f, -a.z, a.y, a.z, 0.0f, -a.x, -a.y, a.x, 0.0f); return out; } inline void CUDA_CALLABLE adj_index(const mat33& m, int row, int col, mat33& adj_m, int& adj_row, int& adj_col, float adj_ret) { adj_m.data[row][col] += adj_ret; } inline CUDA_CALLABLE void adj_add(const mat33& a, const mat33& b, mat33& adj_a, mat33& adj_b, const mat33& adj_ret) { for (int i=0; i < 3; ++i) { for (int j=0; j < 3; ++j) { adj_a.data[i][j] += adj_ret.data[i][j]; adj_b.data[i][j] += adj_ret.data[i][j]; } } } inline CUDA_CALLABLE void adj_mul(const mat33& a, float b, mat33& adj_a, float& adj_b, const mat33& adj_ret) { for (int i=0; i < 3; ++i) { for (int j=0; j < 3; ++j) { adj_a.data[i][j] += b*adj_ret.data[i][j]; adj_b += a.data[i][j]*adj_ret.data[i][j]; } } } inline CUDA_CALLABLE void adj_mul(const mat33& a, const float3& b, mat33& adj_a, float3& adj_b, const float3& adj_ret) { adj_a += outer(adj_ret, b); adj_b += mul(transpose(a), adj_ret); } inline CUDA_CALLABLE void adj_mul(const mat33& a, const mat33& b, mat33& adj_a, mat33& adj_b, const mat33& adj_ret) { adj_a += mul(adj_ret, transpose(b)); adj_b += mul(transpose(a), adj_ret); } inline CUDA_CALLABLE void adj_transpose(const mat33& a, mat33& adj_a, const mat33& adj_ret) { adj_a += transpose(adj_ret); } inline CUDA_CALLABLE void adj_determinant(const mat33& m, mat33& adj_m, float adj_ret) { (float3&)adj_m.data[0] += cross(m.get_row(1), m.get_row(2))*adj_ret; (float3&)adj_m.data[1] += cross(m.get_row(2), m.get_row(0))*adj_ret; (float3&)adj_m.data[2] += cross(m.get_row(0), m.get_row(1))*adj_ret; } inline CUDA_CALLABLE void adj_skew(const float3& a, float3& adj_a, const mat33& adj_ret) { mat33 out(0.0f, -a.z, a.y, a.z, 0.0f, -a.x, -a.y, a.x, 0.0f); adj_a.x += adj_ret.data[2][1] - adj_ret.data[1][2]; adj_a.y += adj_ret.data[0][2] - adj_ret.data[2][0]; adj_a.z += adj_ret.data[1][0] - adj_ret.data[0][1]; }
6,549
C
24.192308
126
0.505726
RoboticExplorationLab/Deep-ILC/dflex/dflex/spatial.h
#pragma once //--------------------------------------------------------------------------------- // Represents a twist in se(3) struct spatial_vector { float3 w; float3 v; CUDA_CALLABLE inline spatial_vector(float a, float b, float c, float d, float e, float f) : w(a, b, c), v(d, e, f) {} CUDA_CALLABLE inline spatial_vector(float3 w=float3(), float3 v=float3()) : w(w), v(v) {} CUDA_CALLABLE inline spatial_vector(float a) : w(a, a, a), v(a, a, a) {} CUDA_CALLABLE inline float operator[](int index) const { assert(index < 6); return (&w.x)[index]; } CUDA_CALLABLE inline float& operator[](int index) { assert(index < 6); return (&w.x)[index]; } }; CUDA_CALLABLE inline spatial_vector operator - (spatial_vector a) { return spatial_vector(-a.w, -a.v); } CUDA_CALLABLE inline spatial_vector add(const spatial_vector& a, const spatial_vector& b) { return { a.w + b.w, a.v + b.v }; } CUDA_CALLABLE inline spatial_vector sub(const spatial_vector& a, const spatial_vector& b) { return { a.w - b.w, a.v - b.v }; } CUDA_CALLABLE inline spatial_vector mul(const spatial_vector& a, float s) { return { a.w*s, a.v*s }; } CUDA_CALLABLE inline float spatial_dot(const spatial_vector& a, const spatial_vector& b) { return dot(a.w, b.w) + dot(a.v, b.v); } CUDA_CALLABLE inline spatial_vector spatial_cross(const spatial_vector& a, const spatial_vector& b) { float3 w = cross(a.w, b.w); float3 v = cross(a.v, b.w) + cross(a.w, b.v); return spatial_vector(w, v); } CUDA_CALLABLE inline spatial_vector spatial_cross_dual(const spatial_vector& a, const spatial_vector& b) { float3 w = cross(a.w, b.w) + cross(a.v, b.v); float3 v = cross(a.w, b.v); return spatial_vector(w, v); } CUDA_CALLABLE inline float3 spatial_top(const spatial_vector& a) { return a.w; } CUDA_CALLABLE inline float3 spatial_bottom(const spatial_vector& a) { return a.v; } // adjoint methods CUDA_CALLABLE inline void adj_spatial_vector( float a, float b, float c, float d, float e, float f, float& adj_a, float& adj_b, float& adj_c, float& adj_d, float& adj_e,float& adj_f, const spatial_vector& adj_ret) { adj_a += adj_ret.w.x; adj_b += adj_ret.w.y; adj_c += adj_ret.w.z; adj_d += adj_ret.v.x; adj_e += adj_ret.v.y; adj_f += adj_ret.v.z; } CUDA_CALLABLE inline void adj_spatial_vector(const float3& w, const float3& v, float3& adj_w, float3& adj_v, const spatial_vector& adj_ret) { adj_w += adj_ret.w; adj_v += adj_ret.v; } CUDA_CALLABLE inline void adj_add(const spatial_vector& a, const spatial_vector& b, spatial_vector& adj_a, spatial_vector& adj_b, const spatial_vector& adj_ret) { adj_add(a.w, b.w, adj_a.w, adj_b.w, adj_ret.w); adj_add(a.v, b.v, adj_a.v, adj_b.v, adj_ret.v); } CUDA_CALLABLE inline void adj_sub(const spatial_vector& a, const spatial_vector& b, spatial_vector& adj_a, spatial_vector& adj_b, const spatial_vector& adj_ret) { adj_sub(a.w, b.w, adj_a.w, adj_b.w, adj_ret.w); adj_sub(a.v, b.v, adj_a.v, adj_b.v, adj_ret.v); } CUDA_CALLABLE inline void adj_mul(const spatial_vector& a, float s, spatial_vector& adj_a, float& adj_s, const spatial_vector& adj_ret) { adj_mul(a.w, s, adj_a.w, adj_s, adj_ret.w); adj_mul(a.v, s, adj_a.v, adj_s, adj_ret.v); } CUDA_CALLABLE inline void adj_spatial_dot(const spatial_vector& a, const spatial_vector& b, spatial_vector& adj_a, spatial_vector& adj_b, const float& adj_ret) { adj_dot(a.w, b.w, adj_a.w, adj_b.w, adj_ret); adj_dot(a.v, b.v, adj_a.v, adj_b.v, adj_ret); } CUDA_CALLABLE inline void adj_spatial_cross(const spatial_vector& a, const spatial_vector& b, spatial_vector& adj_a, spatial_vector& adj_b, const spatial_vector& adj_ret) { adj_cross(a.w, b.w, adj_a.w, adj_b.w, adj_ret.w); adj_cross(a.v, b.w, adj_a.v, adj_b.w, adj_ret.v); adj_cross(a.w, b.v, adj_a.w, adj_b.v, adj_ret.v); } CUDA_CALLABLE inline void adj_spatial_cross_dual(const spatial_vector& a, const spatial_vector& b, spatial_vector& adj_a, spatial_vector& adj_b, const spatial_vector& adj_ret) { adj_cross(a.w, b.w, adj_a.w, adj_b.w, adj_ret.w); adj_cross(a.v, b.v, adj_a.v, adj_b.v, adj_ret.w); adj_cross(a.w, b.v, adj_a.w, adj_b.v, adj_ret.v); } CUDA_CALLABLE inline void adj_spatial_top(const spatial_vector& a, spatial_vector& adj_a, const float3& adj_ret) { adj_a.w += adj_ret; } CUDA_CALLABLE inline void adj_spatial_bottom(const spatial_vector& a, spatial_vector& adj_a, const float3& adj_ret) { adj_a.v += adj_ret; } #ifdef CUDA inline __device__ void atomic_add(spatial_vector* addr, const spatial_vector& value) { atomic_add(&addr->w, value.w); atomic_add(&addr->v, value.v); } #endif //--------------------------------------------------------------------------------- // Represents a rigid body transformation struct spatial_transform { float3 p; quat q; CUDA_CALLABLE inline spatial_transform(float3 p=float3(), quat q=quat()) : p(p), q(q) {} CUDA_CALLABLE inline spatial_transform(float) {} // helps uniform initialization }; CUDA_CALLABLE inline spatial_transform spatial_transform_identity() { return spatial_transform(float3(), quat_identity()); } CUDA_CALLABLE inline float3 spatial_transform_get_translation(const spatial_transform& t) { return t.p; } CUDA_CALLABLE inline quat spatial_transform_get_rotation(const spatial_transform& t) { return t.q; } CUDA_CALLABLE inline spatial_transform spatial_transform_multiply(const spatial_transform& a, const spatial_transform& b) { return { rotate(a.q, b.p) + a.p, mul(a.q, b.q) }; } /* CUDA_CALLABLE inline spatial_transform spatial_transform_inverse(const spatial_transform& t) { quat q_inv = inverse(t.q); return spatial_transform(-rotate(q_inv, t.p), q_inv); } */ CUDA_CALLABLE inline float3 spatial_transform_vector(const spatial_transform& t, const float3& x) { return rotate(t.q, x); } CUDA_CALLABLE inline float3 spatial_transform_point(const spatial_transform& t, const float3& x) { return t.p + rotate(t.q, x); } // Frank & Park definition 3.20, pg 100 CUDA_CALLABLE inline spatial_vector spatial_transform_twist(const spatial_transform& t, const spatial_vector& x) { float3 w = rotate(t.q, x.w); float3 v = rotate(t.q, x.v) + cross(t.p, w); return spatial_vector(w, v); } CUDA_CALLABLE inline spatial_vector spatial_transform_wrench(const spatial_transform& t, const spatial_vector& x) { float3 v = rotate(t.q, x.v); float3 w = rotate(t.q, x.w) + cross(t.p, v); return spatial_vector(w, v); } CUDA_CALLABLE inline spatial_transform add(const spatial_transform& a, const spatial_transform& b) { return { a.p + b.p, a.q + b.q }; } CUDA_CALLABLE inline spatial_transform sub(const spatial_transform& a, const spatial_transform& b) { return { a.p - b.p, a.q - b.q }; } CUDA_CALLABLE inline spatial_transform mul(const spatial_transform& a, float s) { return { a.p*s, a.q*s }; } // adjoint methods CUDA_CALLABLE inline void adj_add(const spatial_transform& a, const spatial_transform& b, spatial_transform& adj_a, spatial_transform& adj_b, const spatial_transform& adj_ret) { adj_add(a.p, b.p, adj_a.p, adj_b.p, adj_ret.p); adj_add(a.q, b.q, adj_a.q, adj_b.q, adj_ret.q); } CUDA_CALLABLE inline void adj_sub(const spatial_transform& a, const spatial_transform& b, spatial_transform& adj_a, spatial_transform& adj_b, const spatial_transform& adj_ret) { adj_sub(a.p, b.p, adj_a.p, adj_b.p, adj_ret.p); adj_sub(a.q, b.q, adj_a.q, adj_b.q, adj_ret.q); } CUDA_CALLABLE inline void adj_mul(const spatial_transform& a, float s, spatial_transform& adj_a, float& adj_s, const spatial_transform& adj_ret) { adj_mul(a.p, s, adj_a.p, adj_s, adj_ret.p); adj_mul(a.q, s, adj_a.q, adj_s, adj_ret.q); } #ifdef CUDA inline __device__ void atomic_add(spatial_transform* addr, const spatial_transform& value) { atomic_add(&addr->p, value.p); atomic_add(&addr->q, value.q); } #endif CUDA_CALLABLE inline void adj_spatial_transform(const float3& p, const quat& q, float3& adj_p, quat& adj_q, const spatial_transform& adj_ret) { adj_p += adj_ret.p; adj_q += adj_ret.q; } CUDA_CALLABLE inline void adj_spatial_transform_identity(const spatial_transform& adj_ret) { // nop } CUDA_CALLABLE inline void adj_spatial_transform_get_translation(const spatial_transform& t, spatial_transform& adj_t, const float3& adj_ret) { adj_t.p += adj_ret; } CUDA_CALLABLE inline void adj_spatial_transform_get_rotation(const spatial_transform& t, spatial_transform& adj_t, const quat& adj_ret) { adj_t.q += adj_ret; } /* CUDA_CALLABLE inline void adj_spatial_transform_inverse(const spatial_transform& t, spatial_transform& adj_t, const spatial_transform& adj_ret) { //quat q_inv = inverse(t.q); //return spatial_transform(-rotate(q_inv, t.p), q_inv); quat q_inv = inverse(t.q); float3 p = rotate(q_inv, t.p); float3 np = -p; quat adj_q_inv = 0.0f; quat adj_q = 0.0f; float3 adj_p = 0.0f; float3 adj_np = 0.0f; adj_spatial_transform(np, q_inv, adj_np, adj_q_inv, adj_ret); adj_p = -adj_np; adj_rotate(q_inv, t.p, adj_q_inv, adj_t.p, adj_p); adj_inverse(t.q, adj_t.q, adj_q_inv); } */ CUDA_CALLABLE inline void adj_spatial_transform_multiply(const spatial_transform& a, const spatial_transform& b, spatial_transform& adj_a, spatial_transform& adj_b, const spatial_transform& adj_ret) { // translational part adj_rotate(a.q, b.p, adj_a.q, adj_b.p, adj_ret.p); adj_a.p += adj_ret.p; // rotational part adj_mul(a.q, b.q, adj_a.q, adj_b.q, adj_ret.q); } CUDA_CALLABLE inline void adj_spatial_transform_vector(const spatial_transform& t, const float3& x, spatial_transform& adj_t, float3& adj_x, const float3& adj_ret) { adj_rotate(t.q, x, adj_t.q, adj_x, adj_ret); } CUDA_CALLABLE inline void adj_spatial_transform_point(const spatial_transform& t, const float3& x, spatial_transform& adj_t, float3& adj_x, const float3& adj_ret) { adj_rotate(t.q, x, adj_t.q, adj_x, adj_ret); adj_t.p += adj_ret; } CUDA_CALLABLE inline void adj_spatial_transform_twist(const spatial_transform& a, const spatial_vector& s, spatial_transform& adj_a, spatial_vector& adj_s, const spatial_vector& adj_ret) { printf("todo, %s, %d\n", __FILE__, __LINE__); // float3 w = rotate(t.q, x.w); // float3 v = rotate(t.q, x.v) + cross(t.p, w); // return spatial_vector(w, v); } CUDA_CALLABLE inline void adj_spatial_transform_wrench(const spatial_transform& t, const spatial_vector& x, spatial_transform& adj_t, spatial_vector& adj_x, const spatial_vector& adj_ret) { printf("todo, %s, %d\n", __FILE__, __LINE__); // float3 v = rotate(t.q, x.v); // float3 w = rotate(t.q, x.w) + cross(t.p, v); // return spatial_vector(w, v); } /* // should match model.py #define JOINT_PRISMATIC 0 #define JOINT_REVOLUTE 1 #define JOINT_FIXED 2 #define JOINT_FREE 3 CUDA_CALLABLE inline spatial_transform spatial_jcalc(int type, float* joint_q, float3 axis, int start) { if (type == JOINT_REVOLUTE) { float q = joint_q[start]; spatial_transform X_jc = spatial_transform(float3(), quat_from_axis_angle(axis, q)); return X_jc; } else if (type == JOINT_PRISMATIC) { float q = joint_q[start]; spatial_transform X_jc = spatial_transform(axis*q, quat_identity()); return X_jc; } else if (type == JOINT_FREE) { float px = joint_q[start+0]; float py = joint_q[start+1]; float pz = joint_q[start+2]; float qx = joint_q[start+3]; float qy = joint_q[start+4]; float qz = joint_q[start+5]; float qw = joint_q[start+6]; spatial_transform X_jc = spatial_transform(float3(px, py, pz), quat(qx, qy, qz, qw)); return X_jc; } // JOINT_FIXED return spatial_transform(float3(), quat_identity()); } CUDA_CALLABLE inline void adj_spatial_jcalc(int type, float* q, float3 axis, int start, int& adj_type, float* adj_q, float3& adj_axis, int& adj_start, const spatial_transform& adj_ret) { if (type == JOINT_REVOLUTE) { adj_quat_from_axis_angle(axis, q[start], adj_axis, adj_q[start], adj_ret.q); } else if (type == JOINT_PRISMATIC) { adj_mul(axis, q[start], adj_axis, adj_q[start], adj_ret.p); } else if (type == JOINT_FREE) { adj_q[start+0] += adj_ret.p.x; adj_q[start+1] += adj_ret.p.y; adj_q[start+2] += adj_ret.p.z; adj_q[start+3] += adj_ret.q.x; adj_q[start+4] += adj_ret.q.y; adj_q[start+5] += adj_ret.q.z; adj_q[start+6] += adj_ret.q.w; } } */ struct spatial_matrix { float data[6][6] = { { 0 } }; CUDA_CALLABLE inline spatial_matrix(float f=0.0f) { } CUDA_CALLABLE inline spatial_matrix( float a00, float a01, float a02, float a03, float a04, float a05, float a10, float a11, float a12, float a13, float a14, float a15, float a20, float a21, float a22, float a23, float a24, float a25, float a30, float a31, float a32, float a33, float a34, float a35, float a40, float a41, float a42, float a43, float a44, float a45, float a50, float a51, float a52, float a53, float a54, float a55) { data[0][0] = a00; data[0][1] = a01; data[0][2] = a02; data[0][3] = a03; data[0][4] = a04; data[0][5] = a05; data[1][0] = a10; data[1][1] = a11; data[1][2] = a12; data[1][3] = a13; data[1][4] = a14; data[1][5] = a15; data[2][0] = a20; data[2][1] = a21; data[2][2] = a22; data[2][3] = a23; data[2][4] = a24; data[2][5] = a25; data[3][0] = a30; data[3][1] = a31; data[3][2] = a32; data[3][3] = a33; data[3][4] = a34; data[3][5] = a35; data[4][0] = a40; data[4][1] = a41; data[4][2] = a42; data[4][3] = a43; data[4][4] = a44; data[4][5] = a45; data[5][0] = a50; data[5][1] = a51; data[5][2] = a52; data[5][3] = a53; data[5][4] = a54; data[5][5] = a55; } }; inline CUDA_CALLABLE float index(const spatial_matrix& m, int row, int col) { return m.data[row][col]; } inline CUDA_CALLABLE spatial_matrix add(const spatial_matrix& a, const spatial_matrix& b) { spatial_matrix out; for (int i=0; i < 6; ++i) for (int j=0; j < 6; ++j) out.data[i][j] = a.data[i][j] + b.data[i][j]; return out; } inline CUDA_CALLABLE spatial_vector mul(const spatial_matrix& a, const spatial_vector& b) { spatial_vector out; for (int i=0; i < 6; ++i) for (int j=0; j < 6; ++j) out[i] += a.data[i][j]*b[j]; return out; } inline CUDA_CALLABLE spatial_matrix mul(const spatial_matrix& a, const spatial_matrix& b) { spatial_matrix out; for (int i=0; i < 6; ++i) { for (int j=0; j < 6; ++j) { for (int k=0; k < 6; ++k) { out.data[i][j] += a.data[i][k]*b.data[k][j]; } } } return out; } inline CUDA_CALLABLE spatial_matrix transpose(const spatial_matrix& a) { spatial_matrix out; for (int i=0; i < 6; i++) for (int j=0; j < 6; j++) out.data[i][j] = a.data[j][i]; return out; } inline CUDA_CALLABLE spatial_matrix outer(const spatial_vector& a, const spatial_vector& b) { spatial_matrix out; for (int i=0; i < 6; i++) for (int j=0; j < 6; j++) out.data[i][j] = a[i]*b[j]; return out; } CUDA_CALLABLE void print(spatial_transform t); CUDA_CALLABLE void print(spatial_matrix m); inline CUDA_CALLABLE spatial_matrix spatial_adjoint(const mat33& R, const mat33& S) { spatial_matrix adT; // T = [R 0] // [skew(p)*R R] // diagonal blocks for (int i=0; i < 3; ++i) { for (int j=0; j < 3; ++j) { adT.data[i][j] = R.data[i][j]; adT.data[i+3][j+3] = R.data[i][j]; } } // lower off diagonal for (int i=0; i < 3; ++i) { for (int j=0; j < 3; ++j) { adT.data[i+3][j] = S.data[i][j]; } } return adT; } inline CUDA_CALLABLE void adj_spatial_adjoint(const mat33& R, const mat33& S, mat33& adj_R, mat33& adj_S, const spatial_matrix& adj_ret) { // diagonal blocks for (int i=0; i < 3; ++i) { for (int j=0; j < 3; ++j) { adj_R.data[i][j] += adj_ret.data[i][j]; adj_R.data[i][j] += adj_ret.data[i+3][j+3]; } } // lower off diagonal for (int i=0; i < 3; ++i) { for (int j=0; j < 3; ++j) { adj_S.data[i][j] += adj_ret.data[i+3][j]; } } } /* // computes adj_t^-T*I*adj_t^-1 (tensor change of coordinates), Frank & Park, section 8.2.3, pg 290 inline CUDA_CALLABLE spatial_matrix spatial_transform_inertia(const spatial_transform& t, const spatial_matrix& I) { spatial_transform t_inv = spatial_transform_inverse(t); float3 r1 = rotate(t_inv.q, float3(1.0, 0.0, 0.0)); float3 r2 = rotate(t_inv.q, float3(0.0, 1.0, 0.0)); float3 r3 = rotate(t_inv.q, float3(0.0, 0.0, 1.0)); mat33 R(r1, r2, r3); mat33 S = mul(skew(t_inv.p), R); spatial_matrix T = spatial_adjoint(R, S); // first quadratic form, for derivation of the adjoint see https://people.maths.ox.ac.uk/gilesm/files/AD2008.pdf, section 2.3.2 return mul(mul(transpose(T), I), T); } */ inline CUDA_CALLABLE void adj_add(const spatial_matrix& a, const spatial_matrix& b, spatial_matrix& adj_a, spatial_matrix& adj_b, const spatial_matrix& adj_ret) { adj_a += adj_ret; adj_b += adj_ret; } inline CUDA_CALLABLE void adj_mul(const spatial_matrix& a, const spatial_vector& b, spatial_matrix& adj_a, spatial_vector& adj_b, const spatial_vector& adj_ret) { adj_a += outer(adj_ret, b); adj_b += mul(transpose(a), adj_ret); } inline CUDA_CALLABLE void adj_mul(const spatial_matrix& a, const spatial_matrix& b, spatial_matrix& adj_a, spatial_matrix& adj_b, const spatial_matrix& adj_ret) { adj_a += mul(adj_ret, transpose(b)); adj_b += mul(transpose(a), adj_ret); } inline CUDA_CALLABLE void adj_transpose(const spatial_matrix& a, spatial_matrix& adj_a, const spatial_matrix& adj_ret) { adj_a += transpose(adj_ret); } inline CUDA_CALLABLE void adj_spatial_transform_inertia( const spatial_transform& xform, const spatial_matrix& I, const spatial_transform& adj_xform, const spatial_matrix& adj_I, spatial_matrix& adj_ret) { //printf("todo, %s, %d\n", __FILE__, __LINE__); } inline void CUDA_CALLABLE adj_index(const spatial_matrix& m, int row, int col, spatial_matrix& adj_m, int& adj_row, int& adj_col, float adj_ret) { adj_m.data[row][col] += adj_ret; } #ifdef CUDA inline __device__ void atomic_add(spatial_matrix* addr, const spatial_matrix& value) { for (int i=0; i < 6; ++i) { for (int j=0; j < 6; ++j) { atomicAdd(&addr->data[i][j], value.data[i][j]); } } } #endif CUDA_CALLABLE inline int row_index(int stride, int i, int j) { return i*stride + j; } // builds spatial Jacobian J which is an (joint_count*6)x(dof_count) matrix CUDA_CALLABLE inline void spatial_jacobian( const spatial_vector* S, const int* joint_parents, const int* joint_qd_start, int joint_start, // offset of the first joint for the articulation int joint_count, int J_start, float* J) { const int articulation_dof_start = joint_qd_start[joint_start]; const int articulation_dof_end = joint_qd_start[joint_start + joint_count]; const int articulation_dof_count = articulation_dof_end-articulation_dof_start; // shift output pointers const int S_start = articulation_dof_start; S += S_start; J += J_start; for (int i=0; i < joint_count; ++i) { const int row_start = i * 6; int j = joint_start + i; while (j != -1) { const int joint_dof_start = joint_qd_start[j]; const int joint_dof_end = joint_qd_start[j+1]; const int joint_dof_count = joint_dof_end-joint_dof_start; // fill out each row of the Jacobian walking up the tree //for (int col=dof_start; col < dof_end; ++col) for (int dof=0; dof < joint_dof_count; ++dof) { const int col = (joint_dof_start-articulation_dof_start) + dof; J[row_index(articulation_dof_count, row_start+0, col)] = S[col].w.x; J[row_index(articulation_dof_count, row_start+1, col)] = S[col].w.y; J[row_index(articulation_dof_count, row_start+2, col)] = S[col].w.z; J[row_index(articulation_dof_count, row_start+3, col)] = S[col].v.x; J[row_index(articulation_dof_count, row_start+4, col)] = S[col].v.y; J[row_index(articulation_dof_count, row_start+5, col)] = S[col].v.z; } j = joint_parents[j]; } } } CUDA_CALLABLE inline void adj_spatial_jacobian( const spatial_vector* S, const int* joint_parents, const int* joint_qd_start, const int joint_start, const int joint_count, const int J_start, const float* J, // adjs spatial_vector* adj_S, int* adj_joint_parents, int* adj_joint_qd_start, int& adj_joint_start, int& adj_joint_count, int& adj_J_start, const float* adj_J) { const int articulation_dof_start = joint_qd_start[joint_start]; const int articulation_dof_end = joint_qd_start[joint_start + joint_count]; const int articulation_dof_count = articulation_dof_end-articulation_dof_start; // shift output pointers const int S_start = articulation_dof_start; S += S_start; J += J_start; adj_S += S_start; adj_J += J_start; for (int i=0; i < joint_count; ++i) { const int row_start = i * 6; int j = joint_start + i; while (j != -1) { const int joint_dof_start = joint_qd_start[j]; const int joint_dof_end = joint_qd_start[j+1]; const int joint_dof_count = joint_dof_end-joint_dof_start; // fill out each row of the Jacobian walking up the tree //for (int col=dof_start; col < dof_end; ++col) for (int dof=0; dof < joint_dof_count; ++dof) { const int col = (joint_dof_start-articulation_dof_start) + dof; adj_S[col].w.x += adj_J[row_index(articulation_dof_count, row_start+0, col)]; adj_S[col].w.y += adj_J[row_index(articulation_dof_count, row_start+1, col)]; adj_S[col].w.z += adj_J[row_index(articulation_dof_count, row_start+2, col)]; adj_S[col].v.x += adj_J[row_index(articulation_dof_count, row_start+3, col)]; adj_S[col].v.y += adj_J[row_index(articulation_dof_count, row_start+4, col)]; adj_S[col].v.z += adj_J[row_index(articulation_dof_count, row_start+5, col)]; } j = joint_parents[j]; } } } CUDA_CALLABLE inline void spatial_mass(const spatial_matrix* I_s, int joint_start, int joint_count, int M_start, float* M) { const int stride = joint_count*6; for (int l=0; l < joint_count; ++l) { for (int i=0; i < 6; ++i) { for (int j=0; j < 6; ++j) { M[M_start + row_index(stride, l*6 + i, l*6 + j)] = I_s[joint_start + l].data[i][j]; } } } } CUDA_CALLABLE inline void adj_spatial_mass( const spatial_matrix* I_s, const int joint_start, const int joint_count, const int M_start, const float* M, spatial_matrix* adj_I_s, int& adj_joint_start, int& adj_joint_count, int& adj_M_start, const float* adj_M) { const int stride = joint_count*6; for (int l=0; l < joint_count; ++l) { for (int i=0; i < 6; ++i) { for (int j=0; j < 6; ++j) { adj_I_s[joint_start + l].data[i][j] += adj_M[M_start + row_index(stride, l*6 + i, l*6 + j)]; } } } }
24,501
C
28.099762
198
0.594057
RoboticExplorationLab/Deep-ILC/dflex/dflex/mat22.h
#pragma once //---------------------------------------------------------- // mat22 struct mat22 { inline CUDA_CALLABLE mat22(float m00=0.0f, float m01=0.0f, float m10=0.0f, float m11=0.0f) { data[0][0] = m00; data[1][0] = m10; data[0][1] = m01; data[1][1] = m11; } // row major storage assumed to be compatible with PyTorch float data[2][2]; }; #ifdef CUDA inline __device__ void atomic_add(mat22 * addr, mat22 value) { // *addr += value; atomicAdd(&((addr -> data)[0][0]), value.data[0][0]); atomicAdd(&((addr -> data)[0][1]), value.data[0][1]); atomicAdd(&((addr -> data)[1][0]), value.data[1][0]); atomicAdd(&((addr -> data)[1][1]), value.data[1][1]); } #endif inline CUDA_CALLABLE void adj_mat22(float m00, float m01, float m10, float m11, float& adj_m00, float& adj_m01, float& adj_m10, float& adj_m11, const mat22& adj_ret) { printf("todo\n"); } inline CUDA_CALLABLE float index(const mat22& m, int row, int col) { return m.data[row][col]; } inline CUDA_CALLABLE mat22 add(const mat22& a, const mat22& b) { mat22 t; for (int i=0; i < 2; ++i) { for (int j=0; j < 2; ++j) { t.data[i][j] = a.data[i][j] + b.data[i][j]; } } return t; } inline CUDA_CALLABLE mat22 mul(const mat22& a, float b) { mat22 t; for (int i=0; i < 2; ++i) { for (int j=0; j < 2; ++j) { t.data[i][j] = a.data[i][j]*b; } } return t; } inline CUDA_CALLABLE mat22 mul(const mat22& a, const mat22& b) { mat22 t; for (int i=0; i < 2; ++i) { for (int j=0; j < 2; ++j) { for (int k=0; k < 2; ++k) { t.data[i][j] += a.data[i][k]*b.data[k][j]; } } } return t; } inline CUDA_CALLABLE mat22 transpose(const mat22& a) { mat22 t; for (int i=0; i < 2; ++i) { for (int j=0; j < 2; ++j) { t.data[i][j] = a.data[j][i]; } } return t; } inline CUDA_CALLABLE float determinant(const mat22& m) { return m.data[0][0]*m.data[1][1] - m.data[1][0]*m.data[0][1]; } inline void CUDA_CALLABLE adj_index(const mat22& m, int row, int col, mat22& adj_m, int& adj_row, int& adj_col, float adj_ret) { adj_m.data[row][col] += adj_ret; } inline CUDA_CALLABLE void adj_add(const mat22& a, const mat22& b, mat22& adj_a, mat22& adj_b, const mat22& adj_ret) { for (int i=0; i < 2; ++i) { for (int j=0; j < 2; ++j) { adj_a.data[i][j] = adj_ret.data[i][j]; adj_b.data[i][j] = adj_ret.data[i][j]; } } } inline CUDA_CALLABLE void adj_mul(const mat22& a, const mat22& b, mat22& adj_a, mat22& adj_b, const mat22& adj_ret) { printf("todo\n"); } inline CUDA_CALLABLE void adj_transpose(const mat22& a, mat22& adj_a, const mat22& adj_ret) { printf("todo\n"); } inline CUDA_CALLABLE void adj_determinant(const mat22& m, mat22& adj_m, float adj_ret) { adj_m.data[0][0] += m.data[1][1]*adj_ret; adj_m.data[1][1] += m.data[0][0]*adj_ret; adj_m.data[0][1] -= m.data[1][0]*adj_ret; adj_m.data[1][0] -= m.data[0][1]*adj_ret; }
3,206
C
21.744681
165
0.515908
RoboticExplorationLab/Deep-ILC/dflex/dflex/vec2.h
#pragma once struct float2 { float x; float y; };
58
C
7.42857
13
0.586207
RoboticExplorationLab/Deep-ILC/dflex/dflex/util.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import timeit import math import numpy as np import gc import torch import cProfile log_output = "" def log(s): print(s) global log_output log_output = log_output + s + "\n" # short hands def length(a): return np.linalg.norm(a) def length_sq(a): return np.dot(a, a) # NumPy has no normalize() method.. def normalize(v): norm = np.linalg.norm(v) if norm == 0.0: return v return v / norm def skew(v): return np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]]) # math utils def quat(i, j, k, w): return np.array([i, j, k, w]) def quat_identity(): return np.array((0.0, 0.0, 0.0, 1.0)) def quat_inverse(q): return np.array((-q[0], -q[1], -q[2], q[3])) def quat_from_axis_angle(axis, angle): v = np.array(axis) half = angle * 0.5 w = math.cos(half) sin_theta_over_two = math.sin(half) v *= sin_theta_over_two return np.array((v[0], v[1], v[2], w)) # rotate a vector def quat_rotate(q, x): x = np.array(x) axis = np.array((q[0], q[1], q[2])) return x * (2.0 * q[3] * q[3] - 1.0) + np.cross(axis, x) * q[3] * 2.0 + axis * np.dot(axis, x) * 2.0 # multiply two quats def quat_multiply(a, b): return np.array((a[3] * b[0] + b[3] * a[0] + a[1] * b[2] - b[1] * a[2], a[3] * b[1] + b[3] * a[1] + a[2] * b[0] - b[2] * a[0], a[3] * b[2] + b[3] * a[2] + a[0] * b[1] - b[0] * a[1], a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2])) # convert to mat33 def quat_to_matrix(q): c1 = quat_rotate(q, np.array((1.0, 0.0, 0.0))) c2 = quat_rotate(q, np.array((0.0, 1.0, 0.0))) c3 = quat_rotate(q, np.array((0.0, 0.0, 1.0))) return np.array([c1, c2, c3]).T def quat_rpy(roll, pitch, yaw): cy = math.cos(yaw * 0.5) sy = math.sin(yaw * 0.5) cr = math.cos(roll * 0.5) sr = math.sin(roll * 0.5) cp = math.cos(pitch * 0.5) sp = math.sin(pitch * 0.5) w = (cy * cr * cp + sy * sr * sp) x = (cy * sr * cp - sy * cr * sp) y = (cy * cr * sp + sy * sr * cp) z = (sy * cr * cp - cy * sr * sp) return (x, y, z, w) def quat_from_matrix(m): tr = m[0, 0] + m[1, 1] + m[2, 2] h = 0.0 if(tr >= 0.0): h = math.sqrt(tr + 1.0) w = 0.5 * h h = 0.5 / h x = (m[2, 1] - m[1, 2]) * h y = (m[0, 2] - m[2, 0]) * h z = (m[1, 0] - m[0, 1]) * h else: i = 0; if(m[1, 1] > m[0, 0]): i = 1; if(m[2, 2] > m[i, i]): i = 2; if (i == 0): h = math.sqrt((m[0, 0] - (m[1, 1] + m[2, 2])) + 1.0) x = 0.5 * h h = 0.5 / h y = (m[0, 1] + m[1, 0]) * h z = (m[2, 0] + m[0, 2]) * h w = (m[2, 1] - m[1, 2]) * h elif (i == 1): h = sqrtf((m[1, 1] - (m[2, 2] + m[0, 0])) + 1.0) y = 0.5 * h h = 0.5 / h z = (m[1, 2] + m[2, 1]) * h x = (m[0, 1] + m[1, 0]) * h w = (m[0, 2] - m[2, 0]) * h elif (i == 2): h = sqrtf((m[2, 2] - (m[0, 0] + m[1, 1])) + 1.0) z = 0.5 * h h = 0.5 / h x = (m[2, 0] + m[0, 2]) * h y = (m[1, 2] + m[2, 1]) * h w = (m[1, 0] - m[0, 1]) * h return normalize(quat(x, y, z, w)) # rigid body transform def transform(x, r): return (np.array(x), np.array(r)) def transform_identity(): return (np.array((0.0, 0.0, 0.0)), quat_identity()) # se(3) -> SE(3), Park & Lynch pg. 105, screw in [w, v] normalized form def transform_exp(s, angle): w = np.array(s[0:3]) v = np.array(s[3:6]) if (length(w) < 1.0): r = quat_identity() else: r = quat_from_axis_angle(w, angle) t = v * angle + (1.0 - math.cos(angle)) * np.cross(w, v) + (angle - math.sin(angle)) * np.cross(w, np.cross(w, v)) return (t, r) def transform_inverse(t): q_inv = quat_inverse(t[1]) return (-quat_rotate(q_inv, t[0]), q_inv) def transform_vector(t, v): return quat_rotate(t[1], v) def transform_point(t, p): return np.array(t[0]) + quat_rotate(t[1], p) def transform_multiply(t, u): return (quat_rotate(t[1], u[0]) + t[0], quat_multiply(t[1], u[1])) # flatten an array of transforms (p,q) format to a 7-vector def transform_flatten(t): return np.array([*t[0], *t[1]]) # expand a 7-vec to a tuple of arrays def transform_expand(t): return (np.array(t[0:3]), np.array(t[3:7])) # convert array of transforms to a array of 7-vecs def transform_flatten_list(xforms): exp = lambda t: transform_flatten(t) return list(map(exp, xforms)) def transform_expand_list(xforms): exp = lambda t: transform_expand(t) return list(map(exp, xforms)) def transform_inertia(m, I, p, q): R = quat_to_matrix(q) # Steiner's theorem return R * I * R.T + m * (np.dot(p, p) * np.eye(3) - np.outer(p, p)) # spatial operators # AdT def spatial_adjoint(t): R = quat_to_matrix(t[1]) w = skew(t[0]) A = np.zeros((6, 6)) A[0:3, 0:3] = R A[3:6, 0:3] = np.dot(w, R) A[3:6, 3:6] = R return A # (AdT)^-T def spatial_adjoint_dual(t): R = quat_to_matrix(t[1]) w = skew(t[0]) A = np.zeros((6, 6)) A[0:3, 0:3] = R A[0:3, 3:6] = np.dot(w, R) A[3:6, 3:6] = R return A # AdT*s def transform_twist(t_ab, s_b): return np.dot(spatial_adjoint(t_ab), s_b) # AdT^{-T}*s def transform_wrench(t_ab, f_b): return np.dot(spatial_adjoint_dual(t_ab), f_b) # transform spatial inertia (6x6) in b frame to a frame def transform_spatial_inertia(t_ab, I_b): t_ba = transform_inverse(t_ab) # todo: write specialized method I_a = np.dot(np.dot(spatial_adjoint(t_ba).T, I_b), spatial_adjoint(t_ba)) return I_a def translate_twist(p_ab, s_b): w = s_b[0:3] v = np.cross(p_ab, s_b[0:3]) + s_b[3:6] return np.array((*w, *v)) def translate_wrench(p_ab, s_b): w = s_b[0:3] + np.cross(p_ab, s_b[3:6]) v = s_b[3:6] return np.array((*w, *v)) def spatial_vector(v=(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)): return np.array(v) # ad_V pg. 289 L&P, pg. 25 Featherstone def spatial_cross(a, b): w = np.cross(a[0:3], b[0:3]) v = np.cross(a[3:6], b[0:3]) + np.cross(a[0:3], b[3:6]) return np.array((*w, *v)) # ad_V^T pg. 290 L&P, pg. 25 Featurestone, note this does not includes the sign flip in the definition def spatial_cross_dual(a, b): w = np.cross(a[0:3], b[0:3]) + np.cross(a[3:6], b[3:6]) v = np.cross(a[0:3], b[3:6]) return np.array((*w, *v)) def spatial_dot(a, b): return np.dot(a, b) def spatial_outer(a, b): return np.outer(a, b) def spatial_matrix(): return np.zeros((6, 6)) def spatial_matrix_from_inertia(I, m): G = spatial_matrix() G[0:3, 0:3] = I G[3, 3] = m G[4, 4] = m G[5, 5] = m return G # solves x = I^(-1)b def spatial_solve(I, b): return np.dot(np.linalg.inv(I), b) def rpy2quat(roll, pitch, yaw): cy = math.cos(yaw * 0.5) sy = math.sin(yaw * 0.5) cr = math.cos(roll * 0.5) sr = math.sin(roll * 0.5) cp = math.cos(pitch * 0.5) sp = math.sin(pitch * 0.5) w = cy * cr * cp + sy * sr * sp x = cy * sr * cp - sy * cr * sp y = cy * cr * sp + sy * sr * cp z = sy * cr * cp - cy * sr * sp return (x, y, z, w) # helper to retrive body angular velocity from a twist v_s in se(3) def get_body_angular_velocity(v_s): return v_s[0:3] # helper to compute velocity of a point p on a body given it's spatial twist v_s def get_body_linear_velocity(v_s, p): dpdt = v_s[3:6] + torch.cross(v_s[0:3], p) return dpdt # helper to build a body twist given the angular and linear velocity of # the center of mass specified in the world frame, returns the body # twist with respect to the origin (v_s) def get_body_twist(w_m, v_m, p_m): lin = v_m + torch.cross(p_m, w_m) return (*w_m, *lin) # timer utils class ScopedTimer: indent = -1 enabled = True def __init__(self, name, active=True, detailed=False): self.name = name self.active = active and self.enabled self.detailed = detailed def __enter__(self): if (self.active): self.start = timeit.default_timer() ScopedTimer.indent += 1 if (self.detailed): self.cp = cProfile.Profile() self.cp.clear() self.cp.enable() def __exit__(self, exc_type, exc_value, traceback): if (self.detailed): self.cp.disable() self.cp.print_stats(sort='tottime') if (self.active): elapsed = (timeit.default_timer() - self.start) * 1000.0 indent = "" for i in range(ScopedTimer.indent): indent += "\t" log("{}{} took {:.2f} ms".format(indent, self.name, elapsed)) ScopedTimer.indent -= 1 # code snippet for invoking cProfile # cp = cProfile.Profile() # cp.enable() # for i in range(1000): # self.state = self.integrator.forward(self.model, self.state, self.sim_dt) # cp.disable() # cp.print_stats(sort='tottime') # exit(0) # represent an edge between v0, v1 with connected faces f0, f1, and opposite vertex o0, and o1 # winding is such that first tri can be reconstructed as {v0, v1, o0}, and second tri as { v1, v0, o1 } class MeshEdge: def __init__(self, v0, v1, o0, o1, f0, f1): self.v0 = v0 # vertex 0 self.v1 = v1 # vertex 1 self.o0 = o0 # opposite vertex 1 self.o1 = o1 # opposite vertex 2 self.f0 = f0 # index of tri1 self.f1 = f1 # index of tri2 class MeshAdjacency: def __init__(self, indices, num_tris): # map edges (v0, v1) to faces (f0, f1) self.edges = {} self.indices = indices for index, tri in enumerate(indices): self.add_edge(tri[0], tri[1], tri[2], index) self.add_edge(tri[1], tri[2], tri[0], index) self.add_edge(tri[2], tri[0], tri[1], index) def add_edge(self, i0, i1, o, f): # index1, index2, index3, index of triangle key = (min(i0, i1), max(i0, i1)) edge = None if key in self.edges: edge = self.edges[key] if (edge.f1 != -1): print("Detected non-manifold edge") return else: # update other side of the edge edge.o1 = o edge.f1 = f else: # create new edge with opposite yet to be filled edge = MeshEdge(i0, i1, o, -1, f, -1) self.edges[key] = edge def opposite_vertex(self, edge): pass def mem_report(): '''Report the memory usage of the tensor.storage in pytorch Both on CPUs and GPUs are reported''' def _mem_report(tensors, mem_type): '''Print the selected tensors of type There are two major storage types in our major concern: - GPU: tensors transferred to CUDA devices - CPU: tensors remaining on the system memory (usually unimportant) Args: - tensors: the tensors of specified type - mem_type: 'CPU' or 'GPU' in current implementation ''' total_numel = 0 total_mem = 0 visited_data = [] for tensor in tensors: if tensor.is_sparse: continue # a data_ptr indicates a memory block allocated data_ptr = tensor.storage().data_ptr() if data_ptr in visited_data: continue visited_data.append(data_ptr) numel = tensor.storage().size() total_numel += numel element_size = tensor.storage().element_size() mem = numel*element_size /1024/1024 # 32bit=4Byte, MByte total_mem += mem element_type = type(tensor).__name__ size = tuple(tensor.size()) # print('%s\t\t%s\t\t%.2f' % ( # element_type, # size, # mem) ) print('Type: %s Total Tensors: %d \tUsed Memory Space: %.2f MBytes' % (mem_type, total_numel, total_mem) ) gc.collect() LEN = 65 objects = gc.get_objects() #print('%s\t%s\t\t\t%s' %('Element type', 'Size', 'Used MEM(MBytes)') ) tensors = [obj for obj in objects if torch.is_tensor(obj)] cuda_tensors = [t for t in tensors if t.is_cuda] host_tensors = [t for t in tensors if not t.is_cuda] _mem_report(cuda_tensors, 'GPU') _mem_report(host_tensors, 'CPU') print('='*LEN)
13,134
Python
23.056777
118
0.522994
RoboticExplorationLab/Deep-ILC/dflex/dflex/adjoint.h
#pragma once #include <cmath> #include <stdio.h> #ifdef CPU #define CUDA_CALLABLE #define __device__ #define __host__ #define __constant__ #elif defined(CUDA) #define CUDA_CALLABLE __device__ #include <cuda.h> #include <cuda_runtime_api.h> #define check_cuda(code) { check_cuda_impl(code, __FILE__, __LINE__); } void check_cuda_impl(cudaError_t code, const char* file, int line) { if (code != cudaSuccess) { printf("CUDA Error: %s %s %d\n", cudaGetErrorString(code), file, line); } } void print_device() { int currentDevice; cudaError_t err = cudaGetDevice(&currentDevice); cudaDeviceProp props; err = cudaGetDeviceProperties(&props, currentDevice); if (err != cudaSuccess) printf("CUDA error: %d\n", err); else printf("%s\n", props.name); } #endif #ifdef _WIN32 #define __restrict__ __restrict #endif #define FP_CHECK 0 namespace df { template <typename T> CUDA_CALLABLE float cast_float(T x) { return (float)(x); } template <typename T> CUDA_CALLABLE int cast_int(T x) { return (int)(x); } template <typename T> CUDA_CALLABLE void adj_cast_float(T x, T& adj_x, float adj_ret) { adj_x += adj_ret; } template <typename T> CUDA_CALLABLE void adj_cast_int(T x, T& adj_x, int adj_ret) { adj_x += adj_ret; } // avoid namespacing of float type for casting to float type, this is to avoid wp::float(x), which is not valid in C++ #define float(x) cast_float(x) #define adj_float(x, adj_x, adj_ret) adj_cast_float(x, adj_x, adj_ret) #define int(x) cast_int(x) #define adj_int(x, adj_x, adj_ret) adj_cast_int(x, adj_x, adj_ret) #define kEps 0.0f // basic ops for integer types inline CUDA_CALLABLE int mul(int a, int b) { return a*b; } inline CUDA_CALLABLE int div(int a, int b) { return a/b; } inline CUDA_CALLABLE int add(int a, int b) { return a+b; } inline CUDA_CALLABLE int sub(int a, int b) { return a-b; } inline CUDA_CALLABLE int mod(int a, int b) { return a % b; } inline CUDA_CALLABLE void adj_mul(int a, int b, int& adj_a, int& adj_b, int adj_ret) { } inline CUDA_CALLABLE void adj_div(int a, int b, int& adj_a, int& adj_b, int adj_ret) { } inline CUDA_CALLABLE void adj_add(int a, int b, int& adj_a, int& adj_b, int adj_ret) { } inline CUDA_CALLABLE void adj_sub(int a, int b, int& adj_a, int& adj_b, int adj_ret) { } inline CUDA_CALLABLE void adj_mod(int a, int b, int& adj_a, int& adj_b, int adj_ret) { } // basic ops for float types inline CUDA_CALLABLE float mul(float a, float b) { return a*b; } inline CUDA_CALLABLE float div(float a, float b) { return a/b; } inline CUDA_CALLABLE float add(float a, float b) { return a+b; } inline CUDA_CALLABLE float sub(float a, float b) { return a-b; } inline CUDA_CALLABLE float min(float a, float b) { return a<b?a:b; } inline CUDA_CALLABLE float max(float a, float b) { return a>b?a:b; } inline CUDA_CALLABLE float leaky_min(float a, float b, float r) { return min(a, b); } inline CUDA_CALLABLE float leaky_max(float a, float b, float r) { return max(a, b); } inline CUDA_CALLABLE float clamp(float x, float a, float b) { return min(max(a, x), b); } inline CUDA_CALLABLE float step(float x) { return x < 0.0 ? 1.0 : 0.0; } inline CUDA_CALLABLE float sign(float x) { return x < 0.0 ? -1.0 : 1.0; } inline CUDA_CALLABLE float abs(float x) { return fabsf(x); } inline CUDA_CALLABLE float nonzero(float x) { return x == 0.0 ? 0.0 : 1.0; } inline CUDA_CALLABLE float acos(float x) { return std::acos(std::min(std::max(x, -1.0f), 1.0f)); } inline CUDA_CALLABLE float sin(float x) { return std::sin(x); } inline CUDA_CALLABLE float cos(float x) { return std::cos(x); } inline CUDA_CALLABLE float sqrt(float x) { return std::sqrt(x); } inline CUDA_CALLABLE void adj_mul(float a, float b, float& adj_a, float& adj_b, float adj_ret) { adj_a += b*adj_ret; adj_b += a*adj_ret; } inline CUDA_CALLABLE void adj_div(float a, float b, float& adj_a, float& adj_b, float adj_ret) { adj_a += adj_ret/b; adj_b -= adj_ret*(a/b)/b; } inline CUDA_CALLABLE void adj_add(float a, float b, float& adj_a, float& adj_b, float adj_ret) { adj_a += adj_ret; adj_b += adj_ret; } inline CUDA_CALLABLE void adj_sub(float a, float b, float& adj_a, float& adj_b, float adj_ret) { adj_a += adj_ret; adj_b -= adj_ret; } // inline CUDA_CALLABLE bool lt(float a, float b) { return a < b; } // inline CUDA_CALLABLE bool gt(float a, float b) { return a > b; } // inline CUDA_CALLABLE bool lte(float a, float b) { return a <= b; } // inline CUDA_CALLABLE bool gte(float a, float b) { return a >= b; } // inline CUDA_CALLABLE bool eq(float a, float b) { return a == b; } // inline CUDA_CALLABLE bool neq(float a, float b) { return a != b; } // inline CUDA_CALLABLE bool adj_lt(float a, float b, float & adj_a, float & adj_b, bool & adj_ret) { } // inline CUDA_CALLABLE bool adj_gt(float a, float b, float & adj_a, float & adj_b, bool & adj_ret) { } // inline CUDA_CALLABLE bool adj_lte(float a, float b, float & adj_a, float & adj_b, bool & adj_ret) { } // inline CUDA_CALLABLE bool adj_gte(float a, float b, float & adj_a, float & adj_b, bool & adj_ret) { } // inline CUDA_CALLABLE bool adj_eq(float a, float b, float & adj_a, float & adj_b, bool & adj_ret) { } // inline CUDA_CALLABLE bool adj_neq(float a, float b, float & adj_a, float & adj_b, bool & adj_ret) { } inline CUDA_CALLABLE void adj_min(float a, float b, float& adj_a, float& adj_b, float adj_ret) { if (a < b) adj_a += adj_ret; else adj_b += adj_ret; } inline CUDA_CALLABLE void adj_max(float a, float b, float& adj_a, float& adj_b, float adj_ret) { if (a > b) adj_a += adj_ret; else adj_b += adj_ret; } inline CUDA_CALLABLE void adj_leaky_min(float a, float b, float r, float& adj_a, float& adj_b, float& adj_r, float adj_ret) { if (a < b) adj_a += adj_ret; else { adj_a += r*adj_ret; adj_b += adj_ret; } } inline CUDA_CALLABLE void adj_leaky_max(float a, float b, float r, float& adj_a, float& adj_b, float& adj_r, float adj_ret) { if (a > b) adj_a += adj_ret; else { adj_a += r*adj_ret; adj_b += adj_ret; } } inline CUDA_CALLABLE void adj_clamp(float x, float a, float b, float& adj_x, float& adj_a, float& adj_b, float adj_ret) { if (x < a) adj_a += adj_ret; else if (x > b) adj_b += adj_ret; else adj_x += adj_ret; } inline CUDA_CALLABLE void adj_step(float x, float& adj_x, float adj_ret) { // nop } inline CUDA_CALLABLE void adj_nonzero(float x, float& adj_x, float adj_ret) { // nop } inline CUDA_CALLABLE void adj_sign(float x, float& adj_x, float adj_ret) { // nop } inline CUDA_CALLABLE void adj_abs(float x, float& adj_x, float adj_ret) { if (x < 0.0) adj_x -= adj_ret; else adj_x += adj_ret; } inline CUDA_CALLABLE void adj_acos(float x, float& adj_x, float adj_ret) { float d = sqrt(1.0-x*x); if (d > 0.0) adj_x -= (1.0/d)*adj_ret; } inline CUDA_CALLABLE void adj_sin(float x, float& adj_x, float adj_ret) { adj_x += std::cos(x)*adj_ret; } inline CUDA_CALLABLE void adj_cos(float x, float& adj_x, float adj_ret) { adj_x -= std::sin(x)*adj_ret; } inline CUDA_CALLABLE void adj_sqrt(float x, float& adj_x, float adj_ret) { adj_x += 0.5f*(1.0/std::sqrt(x))*adj_ret; } template <typename T> CUDA_CALLABLE inline T select(bool cond, const T& a, const T& b) { return cond?b:a; } template <typename T> CUDA_CALLABLE inline void adj_select(bool cond, const T& a, const T& b, bool& adj_cond, T& adj_a, T& adj_b, const T& adj_ret) { if (cond) adj_b += adj_ret; else adj_a += adj_ret; } // some helpful operator overloads (just for C++ use, these are not adjointed) template <typename T> CUDA_CALLABLE T& operator += (T& a, const T& b) { a = add(a, b); return a; } template <typename T> CUDA_CALLABLE T& operator -= (T& a, const T& b) { a = sub(a, b); return a; } template <typename T> CUDA_CALLABLE T operator*(const T& a, float s) { return mul(a, s); } template <typename T> CUDA_CALLABLE T operator/(const T& a, float s) { return div(a, s); } template <typename T> CUDA_CALLABLE T operator+(const T& a, const T& b) { return add(a, b); } template <typename T> CUDA_CALLABLE T operator-(const T& a, const T& b) { return sub(a, b); } // for single thread CPU only static int s_threadIdx; inline CUDA_CALLABLE int tid() { #ifdef CPU return s_threadIdx; #elif defined(CUDA) return blockDim.x * blockIdx.x + threadIdx.x; #endif } #include "vec2.h" #include "vec3.h" #include "mat22.h" #include "mat33.h" #include "matnn.h" #include "quat.h" #include "spatial.h" //-------------- template<typename T> inline CUDA_CALLABLE T load(T* buf, int index) { assert(buf); return buf[index]; } template<typename T> inline CUDA_CALLABLE void store(T* buf, int index, T value) { // allow NULL buffers for case where gradients are not required if (buf) { buf[index] = value; } } #ifdef CUDA template<typename T> inline __device__ void atomic_add(T* buf, T value) { atomicAdd(buf, value); } #endif template<typename T> inline __device__ void atomic_add(T* buf, int index, T value) { if (buf) { // CPU mode is sequential so just add #ifdef CPU buf[index] += value; #elif defined(CUDA) atomic_add(buf + index, value); #endif } } template<typename T> inline __device__ void atomic_sub(T* buf, int index, T value) { if (buf) { // CPU mode is sequential so just add #ifdef CPU buf[index] -= value; #elif defined(CUDA) atomic_add(buf + index, -value); #endif } } template <typename T> inline CUDA_CALLABLE void adj_load(T* buf, int index, T* adj_buf, int& adj_index, const T& adj_output) { // allow NULL buffers for case where gradients are not required if (adj_buf) { #ifdef CPU adj_buf[index] += adj_output; // does not need to be atomic if single-threaded #elif defined(CUDA) atomic_add(adj_buf, index, adj_output); #endif } } template <typename T> inline CUDA_CALLABLE void adj_store(T* buf, int index, T value, T* adj_buf, int& adj_index, T& adj_value) { adj_value += adj_buf[index]; // doesn't need to be atomic because it's used to load from a buffer onto the stack } template<typename T> inline CUDA_CALLABLE void adj_atomic_add(T* buf, int index, T value, T* adj_buf, int& adj_index, T& adj_value) { if (adj_buf) { // cannot be atomic because used locally adj_value += adj_buf[index]; } } template<typename T> inline CUDA_CALLABLE void adj_atomic_sub(T* buf, int index, T value, T* adj_buf, int& adj_index, T& adj_value) { if (adj_buf) { // cannot be atomic because used locally adj_value -= adj_buf[index]; } } //------------------------- // Texture methods inline CUDA_CALLABLE float sdf_sample(float3 x) { return 0.0; } inline CUDA_CALLABLE float3 sdf_grad(float3 x) { return float3(); } inline CUDA_CALLABLE void adj_sdf_sample(float3 x, float3& adj_x, float adj_ret) { } inline CUDA_CALLABLE void adj_sdf_grad(float3 x, float3& adj_x, float3& adj_ret) { } inline CUDA_CALLABLE void print(int i) { printf("%d\n", i); } inline CUDA_CALLABLE void print(float i) { printf("%f\n", i); } inline CUDA_CALLABLE void print(float3 i) { printf("%f %f %f\n", i.x, i.y, i.z); } inline CUDA_CALLABLE void print(quat i) { printf("%f %f %f %f\n", i.x, i.y, i.z, i.w); } inline CUDA_CALLABLE void print(mat22 m) { printf("%f %f\n%f %f\n", m.data[0][0], m.data[0][1], m.data[1][0], m.data[1][1]); } inline CUDA_CALLABLE void print(mat33 m) { printf("%f %f %f\n%f %f %f\n%f %f %f\n", m.data[0][0], m.data[0][1], m.data[0][2], m.data[1][0], m.data[1][1], m.data[1][2], m.data[2][0], m.data[2][1], m.data[2][2]); } inline CUDA_CALLABLE void print(spatial_transform t) { printf("(%f %f %f) (%f %f %f %f)\n", t.p.x, t.p.y, t.p.z, t.q.x, t.q.y, t.q.z, t.q.w); } inline CUDA_CALLABLE void print(spatial_vector v) { printf("(%f %f %f) (%f %f %f)\n", v.w.x, v.w.y, v.w.z, v.v.x, v.v.y, v.v.z); } inline CUDA_CALLABLE void print(spatial_matrix m) { printf("%f %f %f %f %f %f\n" "%f %f %f %f %f %f\n" "%f %f %f %f %f %f\n" "%f %f %f %f %f %f\n" "%f %f %f %f %f %f\n" "%f %f %f %f %f %f\n", m.data[0][0], m.data[0][1], m.data[0][2], m.data[0][3], m.data[0][4], m.data[0][5], m.data[1][0], m.data[1][1], m.data[1][2], m.data[1][3], m.data[1][4], m.data[1][5], m.data[2][0], m.data[2][1], m.data[2][2], m.data[2][3], m.data[2][4], m.data[2][5], m.data[3][0], m.data[3][1], m.data[3][2], m.data[3][3], m.data[3][4], m.data[3][5], m.data[4][0], m.data[4][1], m.data[4][2], m.data[4][3], m.data[4][4], m.data[4][5], m.data[5][0], m.data[5][1], m.data[5][2], m.data[5][3], m.data[5][4], m.data[5][5]); } inline CUDA_CALLABLE void adj_print(int i, int& adj_i) { printf("%d adj: %d\n", i, adj_i); } inline CUDA_CALLABLE void adj_print(float i, float& adj_i) { printf("%f adj: %f\n", i, adj_i); } inline CUDA_CALLABLE void adj_print(float3 i, float3& adj_i) { printf("%f %f %f adj: %f %f %f \n", i.x, i.y, i.z, adj_i.x, adj_i.y, adj_i.z); } inline CUDA_CALLABLE void adj_print(quat i, quat& adj_i) { } inline CUDA_CALLABLE void adj_print(mat22 m, mat22& adj_m) { } inline CUDA_CALLABLE void adj_print(mat33 m, mat33& adj_m) { } inline CUDA_CALLABLE void adj_print(spatial_transform t, spatial_transform& adj_t) {} inline CUDA_CALLABLE void adj_print(spatial_vector t, spatial_vector& adj_t) {} inline CUDA_CALLABLE void adj_print(spatial_matrix t, spatial_matrix& adj_t) {} } // namespace df
13,946
C
29.05819
144
0.608992
RoboticExplorationLab/Deep-ILC/dflex/dflex/config.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import os no_grad = False # disable adjoint tracking check_grad = False # will perform numeric gradient checking after each launch verify_fp = False # verify inputs and outputs are finite after each launch
650
Python
49.076919
82
0.783077
RoboticExplorationLab/Deep-ILC/dflex/dflex/quat.h
#pragma once struct quat { // imaginary part float x; float y; float z; // real part float w; inline CUDA_CALLABLE quat(float x=0.0f, float y=0.0f, float z=0.0f, float w=0.0) : x(x), y(y), z(z), w(w) {} explicit inline CUDA_CALLABLE quat(const float3& v, float w=0.0f) : x(v.x), y(v.y), z(v.z), w(w) {} }; #ifdef CUDA inline __device__ void atomic_add(quat * addr, quat value) { atomicAdd(&(addr -> x), value.x); atomicAdd(&(addr -> y), value.y); atomicAdd(&(addr -> z), value.z); atomicAdd(&(addr -> w), value.w); } #endif inline CUDA_CALLABLE void adj_quat(float x, float y, float z, float w, float& adj_x, float& adj_y, float& adj_z, float& adj_w, quat adj_ret) { adj_x += adj_ret.x; adj_y += adj_ret.y; adj_z += adj_ret.z; adj_w += adj_ret.w; } inline CUDA_CALLABLE void adj_quat(const float3& v, float w, float3& adj_v, float& adj_w, quat adj_ret) { adj_v.x += adj_ret.x; adj_v.y += adj_ret.y; adj_v.z += adj_ret.z; adj_w += adj_ret.w; } // foward methods inline CUDA_CALLABLE quat quat_from_axis_angle(const float3& axis, float angle) { float half = angle*0.5f; float w = cosf(half); float sin_theta_over_two = sinf(half); float3 v = axis*sin_theta_over_two; return quat(v.x, v.y, v.z, w); } inline CUDA_CALLABLE quat quat_identity() { return quat(0.0f, 0.0f, 0.0f, 1.0f); } inline CUDA_CALLABLE float dot(const quat& a, const quat& b) { return a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w; } inline CUDA_CALLABLE float length(const quat& q) { return sqrtf(dot(q, q)); } inline CUDA_CALLABLE quat normalize(const quat& q) { float l = length(q); if (l > kEps) { float inv_l = 1.0f/l; return quat(q.x*inv_l, q.y*inv_l, q.z*inv_l, q.w*inv_l); } else { return quat(0.0f, 0.0f, 0.0f, 1.0f); } } inline CUDA_CALLABLE quat inverse(const quat& q) { return quat(-q.x, -q.y, -q.z, q.w); } inline CUDA_CALLABLE quat add(const quat& a, const quat& b) { return quat(a.x+b.x, a.y+b.y, a.z+b.z, a.w+b.w); } inline CUDA_CALLABLE quat sub(const quat& a, const quat& b) { return quat(a.x-b.x, a.y-b.y, a.z-b.z, a.w-b.w);} inline CUDA_CALLABLE quat mul(const quat& a, const quat& b) { return quat(a.w*b.x + b.w*a.x + a.y*b.z - b.y*a.z, a.w*b.y + b.w*a.y + a.z*b.x - b.z*a.x, a.w*b.z + b.w*a.z + a.x*b.y - b.x*a.y, a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z); } inline CUDA_CALLABLE quat mul(const quat& a, float s) { return quat(a.x*s, a.y*s, a.z*s, a.w*s); } inline CUDA_CALLABLE float3 rotate(const quat& q, const float3& x) { return x*(2.0f*q.w*q.w-1.0f) + cross(float3(&q.x), x)*q.w*2.0f + float3(&q.x)*dot(float3(&q.x), x)*2.0f; } inline CUDA_CALLABLE float3 rotate_inv(const quat& q, const float3& x) { return x*(2.0f*q.w*q.w-1.0f) - cross(float3(&q.x), x)*q.w*2.0f + float3(&q.x)*dot(float3(&q.x), x)*2.0f; } inline CUDA_CALLABLE float index(const quat& a, int idx) { #if FP_CHECK if (idx < 0 || idx > 3) { printf("quat index %d out of bounds at %s %d", idx, __FILE__, __LINE__); exit(1); } #endif return (&a.x)[idx]; } inline CUDA_CALLABLE void adj_index(const quat& a, int idx, quat& adj_a, int & adj_idx, float & adj_ret) { #if FP_CHECK if (idx < 0 || idx > 3) { printf("quat index %d out of bounds at %s %d", idx, __FILE__, __LINE__); exit(1); } #endif (&adj_a.x)[idx] += adj_ret; } // backward methods inline CUDA_CALLABLE void adj_quat_from_axis_angle(const float3& axis, float angle, float3& adj_axis, float& adj_angle, const quat& adj_ret) { float3 v = float3(adj_ret.x, adj_ret.y, adj_ret.z); float s = sinf(angle*0.5f); float c = cosf(angle*0.5f); quat dqda = quat(axis.x*c, axis.y*c, axis.z*c, -s)*0.5f; adj_axis += v*s; adj_angle += dot(dqda, adj_ret); } inline CUDA_CALLABLE void adj_quat_identity(const quat& adj_ret) { // nop } inline CUDA_CALLABLE void adj_dot(const quat& a, const quat& b, quat& adj_a, quat& adj_b, const float adj_ret) { adj_a += b*adj_ret; adj_b += a*adj_ret; } inline CUDA_CALLABLE void adj_length(const quat& a, quat& adj_a, const float adj_ret) { adj_a += normalize(a)*adj_ret; } inline CUDA_CALLABLE void adj_normalize(const quat& q, quat& adj_q, const quat& adj_ret) { float l = length(q); if (l > kEps) { float l_inv = 1.0f/l; adj_q += adj_ret*l_inv - q*(l_inv*l_inv*l_inv*dot(q, adj_ret)); } } inline CUDA_CALLABLE void adj_inverse(const quat& q, quat& adj_q, const quat& adj_ret) { adj_q.x -= adj_ret.x; adj_q.y -= adj_ret.y; adj_q.z -= adj_ret.z; adj_q.w += adj_ret.w; } // inline void adj_normalize(const quat& a, quat& adj_a, const quat& adj_ret) // { // float d = length(a); // if (d > kEps) // { // float invd = 1.0f/d; // quat ahat = normalize(a); // adj_a += (adj_ret - ahat*(dot(ahat, adj_ret))*invd); // //if (!isfinite(adj_a)) // // printf("%s:%d - adj_normalize((%f %f %f), (%f %f %f), (%f, %f, %f))\n", __FILE__, __LINE__, a.x, a.y, a.z, adj_a.x, adj_a.y, adj_a.z, adj_ret.x, adj_ret.y, adj_ret.z); // } // } inline CUDA_CALLABLE void adj_add(const quat& a, const quat& b, quat& adj_a, quat& adj_b, const quat& adj_ret) { adj_a += adj_ret; adj_b += adj_ret; } inline CUDA_CALLABLE void adj_sub(const quat& a, const quat& b, quat& adj_a, quat& adj_b, const quat& adj_ret) { adj_a += adj_ret; adj_b -= adj_ret; } inline CUDA_CALLABLE void adj_mul(const quat& a, const quat& b, quat& adj_a, quat& adj_b, const quat& adj_ret) { // shorthand const quat& r = adj_ret; adj_a += quat(b.w*r.x - b.x*r.w + b.y*r.z - b.z*r.y, b.w*r.y - b.y*r.w - b.x*r.z + b.z*r.x, b.w*r.z + b.x*r.y - b.y*r.x - b.z*r.w, b.w*r.w + b.x*r.x + b.y*r.y + b.z*r.z); adj_b += quat(a.w*r.x - a.x*r.w - a.y*r.z + a.z*r.y, a.w*r.y - a.y*r.w + a.x*r.z - a.z*r.x, a.w*r.z - a.x*r.y + a.y*r.x - a.z*r.w, a.w*r.w + a.x*r.x + a.y*r.y + a.z*r.z); } inline CUDA_CALLABLE void adj_mul(const quat& a, float s, quat& adj_a, float& adj_s, const quat& adj_ret) { adj_a += adj_ret*s; adj_s += dot(a, adj_ret); } inline CUDA_CALLABLE void adj_rotate(const quat& q, const float3& p, quat& adj_q, float3& adj_p, const float3& adj_ret) { const float3& r = adj_ret; { float t2 = p.z*q.z*2.0f; float t3 = p.y*q.w*2.0f; float t4 = p.x*q.w*2.0f; float t5 = p.x*q.x*2.0f; float t6 = p.y*q.y*2.0f; float t7 = p.z*q.y*2.0f; float t8 = p.x*q.z*2.0f; float t9 = p.x*q.y*2.0f; float t10 = p.y*q.x*2.0f; adj_q.x += r.z*(t3+t8)+r.x*(t2+t6+p.x*q.x*4.0f)+r.y*(t9-p.z*q.w*2.0f); adj_q.y += r.y*(t2+t5+p.y*q.y*4.0f)+r.x*(t10+p.z*q.w*2.0f)-r.z*(t4-p.y*q.z*2.0f); adj_q.z += r.y*(t4+t7)+r.z*(t5+t6+p.z*q.z*4.0f)-r.x*(t3-p.z*q.x*2.0f); adj_q.w += r.x*(t7+p.x*q.w*4.0f-p.y*q.z*2.0f)+r.y*(t8+p.y*q.w*4.0f-p.z*q.x*2.0f)+r.z*(-t9+t10+p.z*q.w*4.0f); } { float t2 = q.w*q.w; float t3 = t2*2.0f; float t4 = q.w*q.z*2.0f; float t5 = q.x*q.y*2.0f; float t6 = q.w*q.y*2.0f; float t7 = q.w*q.x*2.0f; float t8 = q.y*q.z*2.0f; adj_p.x += r.y*(t4+t5)+r.x*(t3+(q.x*q.x)*2.0f-1.0f)-r.z*(t6-q.x*q.z*2.0f); adj_p.y += r.z*(t7+t8)-r.x*(t4-t5)+r.y*(t3+(q.y*q.y)*2.0f-1.0f); adj_p.z += -r.y*(t7-t8)+r.z*(t3+(q.z*q.z)*2.0f-1.0f)+r.x*(t6+q.x*q.z*2.0f); } } inline CUDA_CALLABLE void adj_rotate_inv(const quat& q, const float3& p, quat& adj_q, float3& adj_p, const float3& adj_ret) { const float3& r = adj_ret; { float t2 = p.z*q.w*2.0f; float t3 = p.z*q.z*2.0f; float t4 = p.y*q.w*2.0f; float t5 = p.x*q.w*2.0f; float t6 = p.x*q.x*2.0f; float t7 = p.y*q.y*2.0f; float t8 = p.y*q.z*2.0f; float t9 = p.z*q.x*2.0f; float t10 = p.x*q.y*2.0f; adj_q.x += r.y*(t2+t10)+r.x*(t3+t7+p.x*q.x*4.0f)-r.z*(t4-p.x*q.z*2.0f); adj_q.y += r.z*(t5+t8)+r.y*(t3+t6+p.y*q.y*4.0f)-r.x*(t2-p.y*q.x*2.0f); adj_q.z += r.x*(t4+t9)+r.z*(t6+t7+p.z*q.z*4.0f)-r.y*(t5-p.z*q.y*2.0f); adj_q.w += r.x*(t8+p.x*q.w*4.0f-p.z*q.y*2.0f)+r.y*(t9+p.y*q.w*4.0f-p.x*q.z*2.0f)+r.z*(t10-p.y*q.x*2.0f+p.z*q.w*4.0f); } { float t2 = q.w*q.w; float t3 = t2*2.0f; float t4 = q.w*q.z*2.0f; float t5 = q.w*q.y*2.0f; float t6 = q.x*q.z*2.0f; float t7 = q.w*q.x*2.0f; adj_p.x += r.z*(t5+t6)+r.x*(t3+(q.x*q.x)*2.0f-1.0f)-r.y*(t4-q.x*q.y*2.0f); adj_p.y += r.y*(t3+(q.y*q.y)*2.0f-1.0f)+r.x*(t4+q.x*q.y*2.0f)-r.z*(t7-q.y*q.z*2.0f); adj_p.z += -r.x*(t5-t6)+r.z*(t3+(q.z*q.z)*2.0f-1.0f)+r.y*(t7+q.y*q.z*2.0f); } }
8,985
C
26.993769
184
0.522315