code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
import copy import os import re try: from lxml import etree as lxml_etree except ImportError: lxml_etree = None else: # `lxml.etree._Attrib` doesn't extend `Mapping` and thus our `is_dict_like` # doesn't recognize it unless we register it ourselves. Fixed in lxml 4.9.2: # https://bugs.launchpad.net/lxml/+bug/1981760 from collections.abc import MutableMapping Attrib = getattr(lxml_etree, '_Attrib', None) if Attrib and not isinstance(Attrib, MutableMapping): MutableMapping.register(Attrib) del Attrib, MutableMapping from robot.api import logger from robot.api.deco import keyword from robot.libraries.BuiltIn import BuiltIn from robot.utils import (asserts, ET, ETSource, is_bytes, is_falsy, is_string, is_truthy, plural_or_not as s) from robot.version import get_version should_be_equal = asserts.assert_equal should_match = BuiltIn().should_match class XML: """Robot Framework library for verifying and modifying XML documents. As the name implies, _XML_ is a library for verifying contents of XML files. In practice, it is a pretty thin wrapper on top of Python's [http://docs.python.org/library/xml.etree.elementtree.html|ElementTree XML API]. The library has the following main usages: - Parsing an XML file, or a string containing XML, into an XML element structure and finding certain elements from it for for further analysis (e.g. `Parse XML` and `Get Element` keywords). - Getting text or attributes of elements (e.g. `Get Element Text` and `Get Element Attribute`). - Directly verifying text, attributes, or whole elements (e.g `Element Text Should Be` and `Elements Should Be Equal`). - Modifying XML and saving it (e.g. `Set Element Text`, `Add Element` and `Save XML`). == Table of contents == %TOC% = Parsing XML = XML can be parsed into an element structure using `Parse XML` keyword. The XML to be parsed can be specified using a path to an XML file or as a string or bytes that contain XML directly. The keyword returns the root element of the structure, which then contains other elements as its children and their children. Possible comments and processing instructions in the source XML are removed. XML is not validated during parsing even if has a schema defined. How possible doctype elements are handled otherwise depends on the used XML module and on the platform. The standard ElementTree strips doctypes altogether but when `using lxml` they are preserved when XML is saved. The element structure returned by `Parse XML`, as well as elements returned by keywords such as `Get Element`, can be used as the ``source`` argument with other keywords. In addition to an already parsed XML structure, other keywords also accept paths to XML files and strings containing XML similarly as `Parse XML`. Notice that keywords that modify XML do not write those changes back to disk even if the source would be given as a path to a file. Changes must always be saved explicitly using `Save XML` keyword. When the source is given as a path to a file, the forward slash character (``/``) can be used as the path separator regardless the operating system. On Windows also the backslash works, but in the data it needs to be escaped by doubling it (``\\\\``). Using the built-in variable ``${/}`` naturally works too. Note: Support for XML as bytes is new in Robot Framework 3.2. = Using lxml = By default, this library uses Python's standard [http://docs.python.org/library/xml.etree.elementtree.html|ElementTree] module for parsing XML, but it can be configured to use [http://lxml.de|lxml] module instead when `importing` the library. The resulting element structure has same API regardless which module is used for parsing. The main benefits of using lxml is that it supports richer xpath syntax than the standard ElementTree and enables using `Evaluate Xpath` keyword. It also preserves the doctype and possible namespace prefixes saving XML. = Example = The following simple example demonstrates parsing XML and verifying its contents both using keywords in this library and in _BuiltIn_ and _Collections_ libraries. How to use xpath expressions to find elements and what attributes the returned elements contain are discussed, with more examples, in `Finding elements with xpath` and `Element attributes` sections. In this example, as well as in many other examples in this documentation, ``${XML}`` refers to the following example XML document. In practice ``${XML}`` could either be a path to an XML file or it could contain the XML itself. | <example> | <first id="1">text</first> | <second id="2"> | <child/> | </second> | <third> | <child>more text</child> | <second id="child"/> | <child><grandchild/></child> | </third> | <html> | <p> | Text with <b>bold</b> and <i>italics</i>. | </p> | </html> | </example> | ${root} = | `Parse XML` | ${XML} | | | | `Should Be Equal` | ${root.tag} | example | | | | ${first} = | `Get Element` | ${root} | first | | | `Should Be Equal` | ${first.text} | text | | | | `Dictionary Should Contain Key` | ${first.attrib} | id | | | `Element Text Should Be` | ${first} | text | | | | `Element Attribute Should Be` | ${first} | id | 1 | | | `Element Attribute Should Be` | ${root} | id | 1 | xpath=first | | `Element Attribute Should Be` | ${XML} | id | 1 | xpath=first | Notice that in the example three last lines are equivalent. Which one to use in practice depends on which other elements you need to get or verify. If you only need to do one verification, using the last line alone would suffice. If more verifications are needed, parsing the XML with `Parse XML` only once would be more efficient. = Finding elements with xpath = ElementTree, and thus also this library, supports finding elements using xpath expressions. ElementTree does not, however, support the full xpath standard. The supported xpath syntax is explained below and [https://docs.python.org/library/xml.etree.elementtree.html#xpath-support| ElementTree documentation] provides more details. In the examples ``${XML}`` refers to the same XML structure as in the earlier example. If lxml support is enabled when `importing` the library, the whole [http://www.w3.org/TR/xpath/|xpath 1.0 standard] is supported. That includes everything listed below but also lot of other useful constructs. == Tag names == When just a single tag name is used, xpath matches all direct child elements that have that tag name. | ${elem} = | `Get Element` | ${XML} | third | | `Should Be Equal` | ${elem.tag} | third | | | @{children} = | `Get Elements` | ${elem} | child | | `Length Should Be` | ${children} | 2 | | == Paths == Paths are created by combining tag names with a forward slash (``/``). For example, ``parent/child`` matches all ``child`` elements under ``parent`` element. Notice that if there are multiple ``parent`` elements that all have ``child`` elements, ``parent/child`` xpath will match all these ``child`` elements. | ${elem} = | `Get Element` | ${XML} | second/child | | `Should Be Equal` | ${elem.tag} | child | | | ${elem} = | `Get Element` | ${XML} | third/child/grandchild | | `Should Be Equal` | ${elem.tag} | grandchild | | == Wildcards == An asterisk (``*``) can be used in paths instead of a tag name to denote any element. | @{children} = | `Get Elements` | ${XML} | */child | | `Length Should Be` | ${children} | 3 | | == Current element == The current element is denoted with a dot (``.``). Normally the current element is implicit and does not need to be included in the xpath. == Parent element == The parent element of another element is denoted with two dots (``..``). Notice that it is not possible to refer to the parent of the current element. | ${elem} = | `Get Element` | ${XML} | */second/.. | | `Should Be Equal` | ${elem.tag} | third | | == Search all sub elements == Two forward slashes (``//``) mean that all sub elements, not only the direct children, are searched. If the search is started from the current element, an explicit dot is required. | @{elements} = | `Get Elements` | ${XML} | .//second | | `Length Should Be` | ${elements} | 2 | | | ${b} = | `Get Element` | ${XML} | html//b | | `Should Be Equal` | ${b.text} | bold | | == Predicates == Predicates allow selecting elements using also other criteria than tag names, for example, attributes or position. They are specified after the normal tag name or path using syntax ``path[predicate]``. The path can have wildcards and other special syntax explained earlier. What predicates the standard ElementTree supports is explained in the table below. | = Predicate = | = Matches = | = Example = | | @attrib | Elements with attribute ``attrib``. | second[@id] | | @attrib="value" | Elements with attribute ``attrib`` having value ``value``. | *[@id="2"] | | position | Elements at the specified position. Position can be an integer (starting from 1), expression ``last()``, or relative expression like ``last() - 1``. | third/child[1] | | tag | Elements with a child element named ``tag``. | third/child[grandchild] | Predicates can also be stacked like ``path[predicate1][predicate2]``. A limitation is that possible position predicate must always be first. = Element attributes = All keywords returning elements, such as `Parse XML`, and `Get Element`, return ElementTree's [http://docs.python.org/library/xml.etree.elementtree.html#element-objects|Element objects]. These elements can be used as inputs for other keywords, but they also contain several useful attributes that can be accessed directly using the extended variable syntax. The attributes that are both useful and convenient to use in the data are explained below. Also other attributes, including methods, can be accessed, but that is typically better to do in custom libraries than directly in the data. The examples use the same ``${XML}`` structure as the earlier examples. == tag == The tag of the element. | ${root} = | `Parse XML` | ${XML} | | `Should Be Equal` | ${root.tag} | example | == text == The text that the element contains or Python ``None`` if the element has no text. Notice that the text _does not_ contain texts of possible child elements nor text after or between children. Notice also that in XML whitespace is significant, so the text contains also possible indentation and newlines. To get also text of the possible children, optionally whitespace normalized, use `Get Element Text` keyword. | ${1st} = | `Get Element` | ${XML} | first | | `Should Be Equal` | ${1st.text} | text | | | ${2nd} = | `Get Element` | ${XML} | second/child | | `Should Be Equal` | ${2nd.text} | ${NONE} | | | ${p} = | `Get Element` | ${XML} | html/p | | `Should Be Equal` | ${p.text} | \\n${SPACE*6}Text with${SPACE} | == tail == The text after the element before the next opening or closing tag. Python ``None`` if the element has no tail. Similarly as with ``text``, also ``tail`` contains possible indentation and newlines. | ${b} = | `Get Element` | ${XML} | html/p/b | | `Should Be Equal` | ${b.tail} | ${SPACE}and${SPACE} | == attrib == A Python dictionary containing attributes of the element. | ${2nd} = | `Get Element` | ${XML} | second | | `Should Be Equal` | ${2nd.attrib['id']} | 2 | | | ${3rd} = | `Get Element` | ${XML} | third | | `Should Be Empty` | ${3rd.attrib} | | | = Handling XML namespaces = ElementTree and lxml handle possible namespaces in XML documents by adding the namespace URI to tag names in so called Clark Notation. That is inconvenient especially with xpaths, and by default this library strips those namespaces away and moves them to ``xmlns`` attribute instead. That can be avoided by passing ``keep_clark_notation`` argument to `Parse XML` keyword. Alternatively `Parse XML` supports stripping namespace information altogether by using ``strip_namespaces`` argument. The pros and cons of different approaches are discussed in more detail below. == How ElementTree handles namespaces == If an XML document has namespaces, ElementTree adds namespace information to tag names in [http://www.jclark.com/xml/xmlns.htm|Clark Notation] (e.g. ``{http://ns.uri}tag``) and removes original ``xmlns`` attributes. This is done both with default namespaces and with namespaces with a prefix. How it works in practice is illustrated by the following example, where ``${NS}`` variable contains this XML document: | <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" | xmlns="http://www.w3.org/1999/xhtml"> | <xsl:template match="/"> | <html></html> | </xsl:template> | </xsl:stylesheet> | ${root} = | `Parse XML` | ${NS} | keep_clark_notation=yes | | `Should Be Equal` | ${root.tag} | {http://www.w3.org/1999/XSL/Transform}stylesheet | | `Element Should Exist` | ${root} | {http://www.w3.org/1999/XSL/Transform}template/{http://www.w3.org/1999/xhtml}html | | `Should Be Empty` | ${root.attrib} | As you can see, including the namespace URI in tag names makes xpaths really long and complex. If you save the XML, ElementTree moves namespace information back to ``xmlns`` attributes. Unfortunately it does not restore the original prefixes: | <ns0:stylesheet xmlns:ns0="http://www.w3.org/1999/XSL/Transform"> | <ns0:template match="/"> | <ns1:html xmlns:ns1="http://www.w3.org/1999/xhtml"></ns1:html> | </ns0:template> | </ns0:stylesheet> The resulting output is semantically same as the original, but mangling prefixes like this may still not be desirable. Notice also that the actual output depends slightly on ElementTree version. == Default namespace handling == Because the way ElementTree handles namespaces makes xpaths so complicated, this library, by default, strips namespaces from tag names and moves that information back to ``xmlns`` attributes. How this works in practice is shown by the example below, where ``${NS}`` variable contains the same XML document as in the previous example. | ${root} = | `Parse XML` | ${NS} | | `Should Be Equal` | ${root.tag} | stylesheet | | `Element Should Exist` | ${root} | template/html | | `Element Attribute Should Be` | ${root} | xmlns | http://www.w3.org/1999/XSL/Transform | | `Element Attribute Should Be` | ${root} | xmlns | http://www.w3.org/1999/xhtml | xpath=template/html | Now that tags do not contain namespace information, xpaths are simple again. A minor limitation of this approach is that namespace prefixes are lost. As a result the saved output is not exactly same as the original one in this case either: | <stylesheet xmlns="http://www.w3.org/1999/XSL/Transform"> | <template match="/"> | <html xmlns="http://www.w3.org/1999/xhtml"></html> | </template> | </stylesheet> Also this output is semantically same as the original. If the original XML had only default namespaces, the output would also look identical. == Namespaces when using lxml == This library handles namespaces same way both when `using lxml` and when not using it. There are, however, differences how lxml internally handles namespaces compared to the standard ElementTree. The main difference is that lxml stores information about namespace prefixes and they are thus preserved if XML is saved. Another visible difference is that lxml includes namespace information in child elements got with `Get Element` if the parent element has namespaces. == Stripping namespaces altogether == Because namespaces often add unnecessary complexity, `Parse XML` supports stripping them altogether by using ``strip_namespaces=True``. When this option is enabled, namespaces are not shown anywhere nor are they included if XML is saved. == Attribute namespaces == Attributes in XML documents are, by default, in the same namespaces as the element they belong to. It is possible to use different namespaces by using prefixes, but this is pretty rare. If an attribute has a namespace prefix, ElementTree will replace it with Clark Notation the same way it handles elements. Because stripping namespaces from attributes could cause attribute conflicts, this library does not handle attribute namespaces at all. Thus the following example works the same way regardless how namespaces are handled. | ${root} = | `Parse XML` | <root id="1" ns:id="2" xmlns:ns="http://my.ns"/> | | `Element Attribute Should Be` | ${root} | id | 1 | | `Element Attribute Should Be` | ${root} | {http://my.ns}id | 2 | = Boolean arguments = Some keywords accept arguments that are handled as Boolean values true or false. If such an argument is given as a string, it is considered false if it is an empty string or equal to ``FALSE``, ``NONE``, ``NO``, ``OFF`` or ``0``, case-insensitively. Other strings are considered true regardless their value, and other argument types are tested using the same [http://docs.python.org/library/stdtypes.html#truth|rules as in Python]. True examples: | `Parse XML` | ${XML} | keep_clark_notation=True | # Strings are generally true. | | `Parse XML` | ${XML} | keep_clark_notation=yes | # Same as the above. | | `Parse XML` | ${XML} | keep_clark_notation=${TRUE} | # Python ``True`` is true. | | `Parse XML` | ${XML} | keep_clark_notation=${42} | # Numbers other than 0 are true. | False examples: | `Parse XML` | ${XML} | keep_clark_notation=False | # String ``false`` is false. | | `Parse XML` | ${XML} | keep_clark_notation=no | # Also string ``no`` is false. | | `Parse XML` | ${XML} | keep_clark_notation=${EMPTY} | # Empty string is false. | | `Parse XML` | ${XML} | keep_clark_notation=${FALSE} | # Python ``False`` is false. | Considering ``OFF`` and ``0`` false is new in Robot Framework 3.1. == Pattern matching == Some keywords, for example `Elements Should Match`, support so called [http://en.wikipedia.org/wiki/Glob_(programming)|glob patterns] where: | ``*`` | matches any string, even an empty string | | ``?`` | matches any single character | | ``[chars]`` | matches one character in the bracket | | ``[!chars]`` | matches one character not in the bracket | | ``[a-z]`` | matches one character from the range in the bracket | | ``[!a-z]`` | matches one character not from the range in the bracket | Unlike with glob patterns normally, path separator characters ``/`` and ``\\`` and the newline character ``\\n`` are matches by the above wildcards. Support for brackets like ``[abc]`` and ``[!a-z]`` is new in Robot Framework 3.1 """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = get_version() def __init__(self, use_lxml=False): """Import library with optionally lxml mode enabled. This library uses Python's standard [http://docs.python.org/library/xml.etree.elementtree.html|ElementTree] module for parsing XML by default. If ``use_lxml`` argument is given a true value (see `Boolean arguments`), the [http://lxml.de|lxml] module is used instead. See the `Using lxml` section for benefits provided by lxml. Using lxml requires that the lxml module is installed on the system. If lxml mode is enabled but the module is not installed, this library emits a warning and reverts back to using the standard ElementTree. """ use_lxml = is_truthy(use_lxml) if use_lxml and lxml_etree: self.etree = lxml_etree self.modern_etree = True self.lxml_etree = True else: self.etree = ET self.modern_etree = ET.VERSION >= '1.3' self.lxml_etree = False if use_lxml and not lxml_etree: logger.warn('XML library reverted to use standard ElementTree ' 'because lxml module is not installed.') self._ns_stripper = NameSpaceStripper(self.etree, self.lxml_etree) def parse_xml(self, source, keep_clark_notation=False, strip_namespaces=False): """Parses the given XML file or string into an element structure. The ``source`` can either be a path to an XML file or a string containing XML. In both cases the XML is parsed into ElementTree [http://docs.python.org/library/xml.etree.elementtree.html#element-objects|element structure] and the root element is returned. Possible comments and processing instructions in the source XML are removed. As discussed in `Handling XML namespaces` section, this keyword, by default, removes namespace information ElementTree has added to tag names and moves it into ``xmlns`` attributes. This typically eases handling XML documents with namespaces considerably. If you do not want that to happen, or want to avoid the small overhead of going through the element structure when your XML does not have namespaces, you can disable this feature by giving ``keep_clark_notation`` argument a true value (see `Boolean arguments`). If you want to strip namespace information altogether so that it is not included even if XML is saved, you can give a true value to ``strip_namespaces`` argument. Examples: | ${root} = | Parse XML | <root><child/></root> | | ${xml} = | Parse XML | ${CURDIR}/test.xml | keep_clark_notation=True | | ${xml} = | Parse XML | ${CURDIR}/test.xml | strip_namespaces=True | Use `Get Element` keyword if you want to get a certain element and not the whole structure. See `Parsing XML` section for more details and examples. """ if isinstance(source, os.PathLike): source = str(source) with ETSource(source) as source: tree = self.etree.parse(source) if self.lxml_etree: strip = (lxml_etree.Comment, lxml_etree.ProcessingInstruction) lxml_etree.strip_elements(tree, *strip, **dict(with_tail=False)) root = tree.getroot() if not is_truthy(keep_clark_notation): self._ns_stripper.strip(root, preserve=is_falsy(strip_namespaces)) return root def get_element(self, source, xpath='.'): """Returns an element in the ``source`` matching the ``xpath``. The ``source`` can be a path to an XML file, a string containing XML, or an already parsed XML element. The ``xpath`` specifies which element to find. See the `introduction` for more details about both the possible sources and the supported xpath syntax. The keyword fails if more, or less, than one element matches the ``xpath``. Use `Get Elements` if you want all matching elements to be returned. Examples using ``${XML}`` structure from `Example`: | ${element} = | Get Element | ${XML} | second | | ${child} = | Get Element | ${element} | child | `Parse XML` is recommended for parsing XML when the whole structure is needed. It must be used if there is a need to configure how XML namespaces are handled. Many other keywords use this keyword internally, and keywords modifying XML are typically documented to both to modify the given source and to return it. Modifying the source does not apply if the source is given as a string. The XML structure parsed based on the string and then modified is nevertheless returned. """ elements = self.get_elements(source, xpath) if len(elements) != 1: self._raise_wrong_number_of_matches(len(elements), xpath) return elements[0] def _raise_wrong_number_of_matches(self, count, xpath, message=None): if not message: message = self._wrong_number_of_matches(count, xpath) raise AssertionError(message) def _wrong_number_of_matches(self, count, xpath): if not count: return "No element matching '%s' found." % xpath if count == 1: return "One element matching '%s' found." % xpath return "Multiple elements (%d) matching '%s' found." % (count, xpath) def get_elements(self, source, xpath): """Returns a list of elements in the ``source`` matching the ``xpath``. The ``source`` can be a path to an XML file, a string containing XML, or an already parsed XML element. The ``xpath`` specifies which element to find. See the `introduction` for more details. Elements matching the ``xpath`` are returned as a list. If no elements match, an empty list is returned. Use `Get Element` if you want to get exactly one match. Examples using ``${XML}`` structure from `Example`: | ${children} = | Get Elements | ${XML} | third/child | | Length Should Be | ${children} | 2 | | | ${children} = | Get Elements | ${XML} | first/child | | Should Be Empty | ${children} | | | """ if isinstance(source, (str, bytes, os.PathLike)): source = self.parse_xml(source) finder = ElementFinder(self.etree, self.modern_etree, self.lxml_etree) return finder.find_all(source, xpath) def get_child_elements(self, source, xpath='.'): """Returns the child elements of the specified element as a list. The element whose children to return is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. All the direct child elements of the specified element are returned. If the element has no children, an empty list is returned. Examples using ``${XML}`` structure from `Example`: | ${children} = | Get Child Elements | ${XML} | | | Length Should Be | ${children} | 4 | | | ${children} = | Get Child Elements | ${XML} | xpath=first | | Should Be Empty | ${children} | | | """ return list(self.get_element(source, xpath)) def get_element_count(self, source, xpath='.'): """Returns and logs how many elements the given ``xpath`` matches. Arguments ``source`` and ``xpath`` have exactly the same semantics as with `Get Elements` keyword that this keyword uses internally. See also `Element Should Exist` and `Element Should Not Exist`. """ count = len(self.get_elements(source, xpath)) logger.info("%d element%s matched '%s'." % (count, s(count), xpath)) return count def element_should_exist(self, source, xpath='.', message=None): """Verifies that one or more element match the given ``xpath``. Arguments ``source`` and ``xpath`` have exactly the same semantics as with `Get Elements` keyword. Keyword passes if the ``xpath`` matches one or more elements in the ``source``. The default error message can be overridden with the ``message`` argument. See also `Element Should Not Exist` as well as `Get Element Count` that this keyword uses internally. """ count = self.get_element_count(source, xpath) if not count: self._raise_wrong_number_of_matches(count, xpath, message) def element_should_not_exist(self, source, xpath='.', message=None): """Verifies that no element match the given ``xpath``. Arguments ``source`` and ``xpath`` have exactly the same semantics as with `Get Elements` keyword. Keyword fails if the ``xpath`` matches any element in the ``source``. The default error message can be overridden with the ``message`` argument. See also `Element Should Exist` as well as `Get Element Count` that this keyword uses internally. """ count = self.get_element_count(source, xpath) if count: self._raise_wrong_number_of_matches(count, xpath, message) def get_element_text(self, source, xpath='.', normalize_whitespace=False): """Returns all text of the element, possibly whitespace normalized. The element whose text to return is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. This keyword returns all the text of the specified element, including all the text its children and grandchildren contain. If the element has no text, an empty string is returned. The returned text is thus not always the same as the `text` attribute of the element. By default all whitespace, including newlines and indentation, inside the element is returned as-is. If ``normalize_whitespace`` is given a true value (see `Boolean arguments`), then leading and trailing whitespace is stripped, newlines and tabs converted to spaces, and multiple spaces collapsed into one. This is especially useful when dealing with HTML data. Examples using ``${XML}`` structure from `Example`: | ${text} = | Get Element Text | ${XML} | first | | Should Be Equal | ${text} | text | | | ${text} = | Get Element Text | ${XML} | second/child | | Should Be Empty | ${text} | | | | ${paragraph} = | Get Element | ${XML} | html/p | | ${text} = | Get Element Text | ${paragraph} | normalize_whitespace=yes | | Should Be Equal | ${text} | Text with bold and italics. | See also `Get Elements Texts`, `Element Text Should Be` and `Element Text Should Match`. """ element = self.get_element(source, xpath) text = ''.join(self._yield_texts(element)) if is_truthy(normalize_whitespace): text = self._normalize_whitespace(text) return text def _yield_texts(self, element, top=True): if element.text: yield element.text for child in element: for text in self._yield_texts(child, top=False): yield text if element.tail and not top: yield element.tail def _normalize_whitespace(self, text): return ' '.join(text.split()) def get_elements_texts(self, source, xpath, normalize_whitespace=False): """Returns text of all elements matching ``xpath`` as a list. The elements whose text to return is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Elements` keyword. The text of the matched elements is returned using the same logic as with `Get Element Text`. This includes optional whitespace normalization using the ``normalize_whitespace`` option. Examples using ``${XML}`` structure from `Example`: | @{texts} = | Get Elements Texts | ${XML} | third/child | | Length Should Be | ${texts} | 2 | | | Should Be Equal | @{texts}[0] | more text | | | Should Be Equal | @{texts}[1] | ${EMPTY} | | """ return [self.get_element_text(elem, normalize_whitespace=normalize_whitespace) for elem in self.get_elements(source, xpath)] def element_text_should_be(self, source, expected, xpath='.', normalize_whitespace=False, message=None): """Verifies that the text of the specified element is ``expected``. The element whose text is verified is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. The text to verify is got from the specified element using the same logic as with `Get Element Text`. This includes optional whitespace normalization using the ``normalize_whitespace`` option. The keyword passes if the text of the element is equal to the ``expected`` value, and otherwise it fails. The default error message can be overridden with the ``message`` argument. Use `Element Text Should Match` to verify the text against a pattern instead of an exact value. Examples using ``${XML}`` structure from `Example`: | Element Text Should Be | ${XML} | text | xpath=first | | Element Text Should Be | ${XML} | ${EMPTY} | xpath=second/child | | ${paragraph} = | Get Element | ${XML} | xpath=html/p | | Element Text Should Be | ${paragraph} | Text with bold and italics. | normalize_whitespace=yes | """ text = self.get_element_text(source, xpath, normalize_whitespace) should_be_equal(text, expected, message, values=False) def element_text_should_match(self, source, pattern, xpath='.', normalize_whitespace=False, message=None): """Verifies that the text of the specified element matches ``expected``. This keyword works exactly like `Element Text Should Be` except that the expected value can be given as a pattern that the text of the element must match. Pattern matching is similar as matching files in a shell with ``*``, ``?`` and ``[chars]`` acting as wildcards. See the `Pattern matching` section for more information. Examples using ``${XML}`` structure from `Example`: | Element Text Should Match | ${XML} | t??? | xpath=first | | ${paragraph} = | Get Element | ${XML} | xpath=html/p | | Element Text Should Match | ${paragraph} | Text with * and *. | normalize_whitespace=yes | """ text = self.get_element_text(source, xpath, normalize_whitespace) should_match(text, pattern, message, values=False) @keyword(types=None) def get_element_attribute(self, source, name, xpath='.', default=None): """Returns the named attribute of the specified element. The element whose attribute to return is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. The value of the attribute ``name`` of the specified element is returned. If the element does not have such element, the ``default`` value is returned instead. Examples using ``${XML}`` structure from `Example`: | ${attribute} = | Get Element Attribute | ${XML} | id | xpath=first | | Should Be Equal | ${attribute} | 1 | | | | ${attribute} = | Get Element Attribute | ${XML} | xx | xpath=first | default=value | | Should Be Equal | ${attribute} | value | | | See also `Get Element Attributes`, `Element Attribute Should Be`, `Element Attribute Should Match` and `Element Should Not Have Attribute`. """ return self.get_element(source, xpath).get(name, default) def get_element_attributes(self, source, xpath='.'): """Returns all attributes of the specified element. The element whose attributes to return is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. Attributes are returned as a Python dictionary. It is a copy of the original attributes so modifying it has no effect on the XML structure. Examples using ``${XML}`` structure from `Example`: | ${attributes} = | Get Element Attributes | ${XML} | first | | Dictionary Should Contain Key | ${attributes} | id | | | ${attributes} = | Get Element Attributes | ${XML} | third | | Should Be Empty | ${attributes} | | | Use `Get Element Attribute` to get the value of a single attribute. """ return dict(self.get_element(source, xpath).attrib) def element_attribute_should_be(self, source, name, expected, xpath='.', message=None): """Verifies that the specified attribute is ``expected``. The element whose attribute is verified is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. The keyword passes if the attribute ``name`` of the element is equal to the ``expected`` value, and otherwise it fails. The default error message can be overridden with the ``message`` argument. To test that the element does not have a certain attribute, Python ``None`` (i.e. variable ``${NONE}``) can be used as the expected value. A cleaner alternative is using `Element Should Not Have Attribute`. Examples using ``${XML}`` structure from `Example`: | Element Attribute Should Be | ${XML} | id | 1 | xpath=first | | Element Attribute Should Be | ${XML} | id | ${NONE} | | See also `Element Attribute Should Match` and `Get Element Attribute`. """ attr = self.get_element_attribute(source, name, xpath) should_be_equal(attr, expected, message, values=False) def element_attribute_should_match(self, source, name, pattern, xpath='.', message=None): """Verifies that the specified attribute matches ``expected``. This keyword works exactly like `Element Attribute Should Be` except that the expected value can be given as a pattern that the attribute of the element must match. Pattern matching is similar as matching files in a shell with ``*``, ``?`` and ``[chars]`` acting as wildcards. See the `Pattern matching` section for more information. Examples using ``${XML}`` structure from `Example`: | Element Attribute Should Match | ${XML} | id | ? | xpath=first | | Element Attribute Should Match | ${XML} | id | c*d | xpath=third/second | """ attr = self.get_element_attribute(source, name, xpath) if attr is None: raise AssertionError("Attribute '%s' does not exist." % name) should_match(attr, pattern, message, values=False) def element_should_not_have_attribute(self, source, name, xpath='.', message=None): """Verifies that the specified element does not have attribute ``name``. The element whose attribute is verified is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. The keyword fails if the specified element has attribute ``name``. The default error message can be overridden with the ``message`` argument. Examples using ``${XML}`` structure from `Example`: | Element Should Not Have Attribute | ${XML} | id | | Element Should Not Have Attribute | ${XML} | xxx | xpath=first | See also `Get Element Attribute`, `Get Element Attributes`, `Element Text Should Be` and `Element Text Should Match`. """ attr = self.get_element_attribute(source, name, xpath) if attr is not None: raise AssertionError(message or "Attribute '%s' exists and " "has value '%s'." % (name, attr)) def elements_should_be_equal(self, source, expected, exclude_children=False, normalize_whitespace=False): """Verifies that the given ``source`` element is equal to ``expected``. Both ``source`` and ``expected`` can be given as a path to an XML file, as a string containing XML, or as an already parsed XML element structure. See `introduction` for more information about parsing XML in general. The keyword passes if the ``source`` element and ``expected`` element are equal. This includes testing the tag names, texts, and attributes of the elements. By default also child elements are verified the same way, but this can be disabled by setting ``exclude_children`` to a true value (see `Boolean arguments`). All texts inside the given elements are verified, but possible text outside them is not. By default texts must match exactly, but setting ``normalize_whitespace`` to a true value makes text verification independent on newlines, tabs, and the amount of spaces. For more details about handling text see `Get Element Text` keyword and discussion about elements' `text` and `tail` attributes in the `introduction`. Examples using ``${XML}`` structure from `Example`: | ${first} = | Get Element | ${XML} | first | | Elements Should Be Equal | ${first} | <first id="1">text</first> | | ${p} = | Get Element | ${XML} | html/p | | Elements Should Be Equal | ${p} | <p>Text with <b>bold</b> and <i>italics</i>.</p> | normalize_whitespace=yes | | Elements Should Be Equal | ${p} | <p>Text with</p> | exclude | normalize | The last example may look a bit strange because the ``<p>`` element only has text ``Text with``. The reason is that rest of the text inside ``<p>`` actually belongs to the child elements. This includes the ``.`` at the end that is the `tail` text of the ``<i>`` element. See also `Elements Should Match`. """ self._compare_elements(source, expected, should_be_equal, exclude_children, normalize_whitespace) def elements_should_match(self, source, expected, exclude_children=False, normalize_whitespace=False): """Verifies that the given ``source`` element matches ``expected``. This keyword works exactly like `Elements Should Be Equal` except that texts and attribute values in the expected value can be given as patterns. Pattern matching is similar as matching files in a shell with ``*``, ``?`` and ``[chars]`` acting as wildcards. See the `Pattern matching` section for more information. Examples using ``${XML}`` structure from `Example`: | ${first} = | Get Element | ${XML} | first | | Elements Should Match | ${first} | <first id="?">*</first> | See `Elements Should Be Equal` for more examples. """ self._compare_elements(source, expected, should_match, exclude_children, normalize_whitespace) def _compare_elements(self, source, expected, comparator, exclude_children, normalize_whitespace): normalizer = self._normalize_whitespace \ if is_truthy(normalize_whitespace) else None comparator = ElementComparator(comparator, normalizer, exclude_children) comparator.compare(self.get_element(source), self.get_element(expected)) def set_element_tag(self, source, tag, xpath='.'): """Sets the tag of the specified element. The element whose tag to set is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. The resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. Examples using ``${XML}`` structure from `Example`: | Set Element Tag | ${XML} | newTag | | Should Be Equal | ${XML.tag} | newTag | | Set Element Tag | ${XML} | xxx | xpath=second/child | | Element Should Exist | ${XML} | second/xxx | | Element Should Not Exist | ${XML} | second/child | Can only set the tag of a single element. Use `Set Elements Tag` to set the tag of multiple elements in one call. """ source = self.get_element(source) self.get_element(source, xpath).tag = tag return source def set_elements_tag(self, source, tag, xpath='.'): """Sets the tag of the specified elements. Like `Set Element Tag` but sets the tag of all elements matching the given ``xpath``. """ source = self.get_element(source) for elem in self.get_elements(source, xpath): self.set_element_tag(elem, tag) return source @keyword(types=None) def set_element_text(self, source, text=None, tail=None, xpath='.'): """Sets text and/or tail text of the specified element. The element whose text to set is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. The resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. Element's text and tail text are changed only if new ``text`` and/or ``tail`` values are given. See `Element attributes` section for more information about `text` and `tail` in general. Examples using ``${XML}`` structure from `Example`: | Set Element Text | ${XML} | new text | xpath=first | | Element Text Should Be | ${XML} | new text | xpath=first | | Set Element Text | ${XML} | tail=& | xpath=html/p/b | | Element Text Should Be | ${XML} | Text with bold&italics. | xpath=html/p | normalize_whitespace=yes | | Set Element Text | ${XML} | slanted | !! | xpath=html/p/i | | Element Text Should Be | ${XML} | Text with bold&slanted!! | xpath=html/p | normalize_whitespace=yes | Can only set the text/tail of a single element. Use `Set Elements Text` to set the text/tail of multiple elements in one call. """ source = self.get_element(source) element = self.get_element(source, xpath) if text is not None: element.text = text if tail is not None: element.tail = tail return source @keyword(types=None) def set_elements_text(self, source, text=None, tail=None, xpath='.'): """Sets text and/or tail text of the specified elements. Like `Set Element Text` but sets the text or tail of all elements matching the given ``xpath``. """ source = self.get_element(source) for elem in self.get_elements(source, xpath): self.set_element_text(elem, text, tail) return source def set_element_attribute(self, source, name, value, xpath='.'): """Sets attribute ``name`` of the specified element to ``value``. The element whose attribute to set is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. The resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. It is possible to both set new attributes and to overwrite existing. Use `Remove Element Attribute` or `Remove Element Attributes` for removing them. Examples using ``${XML}`` structure from `Example`: | Set Element Attribute | ${XML} | attr | value | | Element Attribute Should Be | ${XML} | attr | value | | Set Element Attribute | ${XML} | id | new | xpath=first | | Element Attribute Should Be | ${XML} | id | new | xpath=first | Can only set an attribute of a single element. Use `Set Elements Attribute` to set an attribute of multiple elements in one call. """ if not name: raise RuntimeError('Attribute name can not be empty.') source = self.get_element(source) self.get_element(source, xpath).attrib[name] = value return source def set_elements_attribute(self, source, name, value, xpath='.'): """Sets attribute ``name`` of the specified elements to ``value``. Like `Set Element Attribute` but sets the attribute of all elements matching the given ``xpath``. """ source = self.get_element(source) for elem in self.get_elements(source, xpath): self.set_element_attribute(elem, name, value) return source def remove_element_attribute(self, source, name, xpath='.'): """Removes attribute ``name`` from the specified element. The element whose attribute to remove is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. The resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. It is not a failure to remove a non-existing attribute. Use `Remove Element Attributes` to remove all attributes and `Set Element Attribute` to set them. Examples using ``${XML}`` structure from `Example`: | Remove Element Attribute | ${XML} | id | xpath=first | | Element Should Not Have Attribute | ${XML} | id | xpath=first | Can only remove an attribute from a single element. Use `Remove Elements Attribute` to remove an attribute of multiple elements in one call. """ source = self.get_element(source) attrib = self.get_element(source, xpath).attrib if name in attrib: attrib.pop(name) return source def remove_elements_attribute(self, source, name, xpath='.'): """Removes attribute ``name`` from the specified elements. Like `Remove Element Attribute` but removes the attribute of all elements matching the given ``xpath``. """ source = self.get_element(source) for elem in self.get_elements(source, xpath): self.remove_element_attribute(elem, name) return source def remove_element_attributes(self, source, xpath='.'): """Removes all attributes from the specified element. The element whose attributes to remove is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. The resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. Use `Remove Element Attribute` to remove a single attribute and `Set Element Attribute` to set them. Examples using ``${XML}`` structure from `Example`: | Remove Element Attributes | ${XML} | xpath=first | | Element Should Not Have Attribute | ${XML} | id | xpath=first | Can only remove attributes from a single element. Use `Remove Elements Attributes` to remove all attributes of multiple elements in one call. """ source = self.get_element(source) self.get_element(source, xpath).attrib.clear() return source def remove_elements_attributes(self, source, xpath='.'): """Removes all attributes from the specified elements. Like `Remove Element Attributes` but removes all attributes of all elements matching the given ``xpath``. """ source = self.get_element(source) for elem in self.get_elements(source, xpath): self.remove_element_attributes(elem) return source def add_element(self, source, element, index=None, xpath='.'): """Adds a child element to the specified element. The element to whom to add the new element is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. The resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. The ``element`` to add can be specified as a path to an XML file or as a string containing XML, or it can be an already parsed XML element. The element is copied before adding so modifying either the original or the added element has no effect on the other . The element is added as the last child by default, but a custom index can be used to alter the position. Indices start from zero (0 = first position, 1 = second position, etc.), and negative numbers refer to positions at the end (-1 = second last position, -2 = third last, etc.). Examples using ``${XML}`` structure from `Example`: | Add Element | ${XML} | <new id="x"><c1/></new> | | Add Element | ${XML} | <c2/> | xpath=new | | Add Element | ${XML} | <c3/> | index=1 | xpath=new | | ${new} = | Get Element | ${XML} | new | | Elements Should Be Equal | ${new} | <new id="x"><c1/><c3/><c2/></new> | Use `Remove Element` or `Remove Elements` to remove elements. """ source = self.get_element(source) parent = self.get_element(source, xpath) element = self.copy_element(element) if index is None: parent.append(element) else: parent.insert(int(index), element) return source def remove_element(self, source, xpath='', remove_tail=False): """Removes the element matching ``xpath`` from the ``source`` structure. The element to remove from the ``source`` is specified with ``xpath`` using the same semantics as with `Get Element` keyword. The resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. The keyword fails if ``xpath`` does not match exactly one element. Use `Remove Elements` to remove all matched elements. Element's tail text is not removed by default, but that can be changed by giving ``remove_tail`` a true value (see `Boolean arguments`). See `Element attributes` section for more information about `tail` in general. Examples using ``${XML}`` structure from `Example`: | Remove Element | ${XML} | xpath=second | | Element Should Not Exist | ${XML} | xpath=second | | Remove Element | ${XML} | xpath=html/p/b | remove_tail=yes | | Element Text Should Be | ${XML} | Text with italics. | xpath=html/p | normalize_whitespace=yes | """ source = self.get_element(source) self._remove_element(source, self.get_element(source, xpath), remove_tail) return source def remove_elements(self, source, xpath='', remove_tail=False): """Removes all elements matching ``xpath`` from the ``source`` structure. The elements to remove from the ``source`` are specified with ``xpath`` using the same semantics as with `Get Elements` keyword. The resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. It is not a failure if ``xpath`` matches no elements. Use `Remove Element` to remove exactly one element. Element's tail text is not removed by default, but that can be changed by using ``remove_tail`` argument similarly as with `Remove Element`. Examples using ``${XML}`` structure from `Example`: | Remove Elements | ${XML} | xpath=*/child | | Element Should Not Exist | ${XML} | xpath=second/child | | Element Should Not Exist | ${XML} | xpath=third/child | """ source = self.get_element(source) for element in self.get_elements(source, xpath): self._remove_element(source, element, remove_tail) return source def _remove_element(self, root, element, remove_tail=False): parent = self._find_parent(root, element) if not is_truthy(remove_tail): self._preserve_tail(element, parent) parent.remove(element) def _find_parent(self, root, element): for parent in root.iter(): for child in parent: if child is element: return parent raise RuntimeError('Cannot remove root element.') def _preserve_tail(self, element, parent): if not element.tail: return index = list(parent).index(element) if index == 0: parent.text = (parent.text or '') + element.tail else: sibling = parent[index-1] sibling.tail = (sibling.tail or '') + element.tail def clear_element(self, source, xpath='.', clear_tail=False): """Clears the contents of the specified element. The element to clear is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. The resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. Clearing the element means removing its text, attributes, and children. Element's tail text is not removed by default, but that can be changed by giving ``clear_tail`` a true value (see `Boolean arguments`). See `Element attributes` section for more information about tail in general. Examples using ``${XML}`` structure from `Example`: | Clear Element | ${XML} | xpath=first | | ${first} = | Get Element | ${XML} | xpath=first | | Elements Should Be Equal | ${first} | <first/> | | Clear Element | ${XML} | xpath=html/p/b | clear_tail=yes | | Element Text Should Be | ${XML} | Text with italics. | xpath=html/p | normalize_whitespace=yes | | Clear Element | ${XML} | | Elements Should Be Equal | ${XML} | <example/> | Use `Remove Element` to remove the whole element. """ source = self.get_element(source) element = self.get_element(source, xpath) tail = element.tail element.clear() if not is_truthy(clear_tail): element.tail = tail return source def copy_element(self, source, xpath='.'): """Returns a copy of the specified element. The element to copy is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. If the copy or the original element is modified afterwards, the changes have no effect on the other. Examples using ``${XML}`` structure from `Example`: | ${elem} = | Get Element | ${XML} | xpath=first | | ${copy1} = | Copy Element | ${elem} | | ${copy2} = | Copy Element | ${XML} | xpath=first | | Set Element Text | ${XML} | new text | xpath=first | | Set Element Attribute | ${copy1} | id | new | | Elements Should Be Equal | ${elem} | <first id="1">new text</first> | | Elements Should Be Equal | ${copy1} | <first id="new">text</first> | | Elements Should Be Equal | ${copy2} | <first id="1">text</first> | """ return copy.deepcopy(self.get_element(source, xpath)) def element_to_string(self, source, xpath='.', encoding=None): """Returns the string representation of the specified element. The element to convert to a string is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. The string is returned as Unicode by default. If ``encoding`` argument is given any value, the string is returned as bytes in the specified encoding. The resulting string never contains the XML declaration. See also `Log Element` and `Save XML`. """ source = self.get_element(source, xpath) string = self.etree.tostring(source, encoding='UTF-8').decode('UTF-8') string = re.sub(r'^<\?xml .*\?>', '', string).strip() if encoding: string = string.encode(encoding) return string def log_element(self, source, level='INFO', xpath='.'): """Logs the string representation of the specified element. The element specified with ``source`` and ``xpath`` is first converted into a string using `Element To String` keyword internally. The resulting string is then logged using the given ``level``. The logged string is also returned. """ string = self.element_to_string(source, xpath) logger.write(string, level) return string def save_xml(self, source, path, encoding='UTF-8'): """Saves the given element to the specified file. The element to save is specified with ``source`` using the same semantics as with `Get Element` keyword. The file where the element is saved is denoted with ``path`` and the encoding to use with ``encoding``. The resulting file always contains the XML declaration. The resulting XML file may not be exactly the same as the original: - Comments and processing instructions are always stripped. - Possible doctype and namespace prefixes are only preserved when `using lxml`. - Other small differences are possible depending on the ElementTree or lxml version. Use `Element To String` if you just need a string representation of the element. """ path = os.path.abspath(str(path) if isinstance(path, os.PathLike) else path.replace('/', os.sep)) elem = self.get_element(source) tree = self.etree.ElementTree(elem) config = {'encoding': encoding} if self.modern_etree: config['xml_declaration'] = True if self.lxml_etree: elem = self._ns_stripper.unstrip(elem) # https://bugs.launchpad.net/lxml/+bug/1660433 if tree.docinfo.doctype: config['doctype'] = tree.docinfo.doctype tree = self.etree.ElementTree(elem) with open(path, 'wb') as output: if 'doctype' in config: output.write(self.etree.tostring(tree, **config)) else: tree.write(output, **config) logger.info('XML saved to <a href="file://%s">%s</a>.' % (path, path), html=True) def evaluate_xpath(self, source, expression, context='.'): """Evaluates the given xpath expression and returns results. The element in which context the expression is executed is specified using ``source`` and ``context`` arguments. They have exactly the same semantics as ``source`` and ``xpath`` arguments have with `Get Element` keyword. The xpath expression to evaluate is given as ``expression`` argument. The result of the evaluation is returned as-is. Examples using ``${XML}`` structure from `Example`: | ${count} = | Evaluate Xpath | ${XML} | count(third/*) | | Should Be Equal | ${count} | ${3} | | ${text} = | Evaluate Xpath | ${XML} | string(descendant::second[last()]/@id) | | Should Be Equal | ${text} | child | | ${bold} = | Evaluate Xpath | ${XML} | boolean(preceding-sibling::*[1] = 'bold') | context=html/p/i | | Should Be Equal | ${bold} | ${True} | This keyword works only if lxml mode is taken into use when `importing` the library. """ if not self.lxml_etree: raise RuntimeError("'Evaluate Xpath' keyword only works in lxml mode.") return self.get_element(source, context).xpath(expression) class NameSpaceStripper: def __init__(self, etree, lxml_etree=False): self.etree = etree self.lxml_tree = lxml_etree def strip(self, elem, preserve=True, current_ns=None, top=True): if elem.tag.startswith('{') and '}' in elem.tag: ns, elem.tag = elem.tag[1:].split('}', 1) if preserve and ns != current_ns: elem.attrib['xmlns'] = ns current_ns = ns elif current_ns: elem.attrib['xmlns'] = '' current_ns = None for child in elem: self.strip(child, preserve, current_ns, top=False) if top and not preserve and self.lxml_tree: self.etree.cleanup_namespaces(elem) def unstrip(self, elem, current_ns=None, copied=False): if not copied: elem = copy.deepcopy(elem) ns = elem.attrib.pop('xmlns', current_ns) if ns: elem.tag = '{%s}%s' % (ns, elem.tag) for child in elem: self.unstrip(child, ns, copied=True) return elem class ElementFinder: def __init__(self, etree, modern=True, lxml=False): self.etree = etree self.modern = modern self.lxml = lxml def find_all(self, elem, xpath): xpath = self._get_xpath(xpath) if xpath == '.': # ET < 1.3 does not support '.' alone. return [elem] if not self.lxml: return elem.findall(xpath) finder = self.etree.ETXPath(xpath) return finder(elem) def _get_xpath(self, xpath): if not xpath: raise RuntimeError('No xpath given.') if self.modern: return xpath try: return str(xpath) except UnicodeError: if not xpath.replace('/', '').isalnum(): logger.warn('XPATHs containing non-ASCII characters and ' 'other than tag names do not always work with ' 'Python versions prior to 2.7. Verify results ' 'manually and consider upgrading to 2.7.') return xpath class ElementComparator: def __init__(self, comparator, normalizer=None, exclude_children=False): self._comparator = comparator self._normalizer = normalizer or (lambda text: text) self._exclude_children = is_truthy(exclude_children) def compare(self, actual, expected, location=None): if not location: location = Location(actual.tag) self._compare_tags(actual, expected, location) self._compare_attributes(actual, expected, location) self._compare_texts(actual, expected, location) if location.is_not_root: self._compare_tails(actual, expected, location) if not self._exclude_children: self._compare_children(actual, expected, location) def _compare_tags(self, actual, expected, location): self._compare(actual.tag, expected.tag, 'Different tag name', location, should_be_equal) def _compare(self, actual, expected, message, location, comparator=None): if location.is_not_root: message = "%s at '%s'" % (message, location.path) if not comparator: comparator = self._comparator comparator(actual, expected, message) def _compare_attributes(self, actual, expected, location): self._compare(sorted(actual.attrib), sorted(expected.attrib), 'Different attribute names', location, should_be_equal) for key in actual.attrib: self._compare(actual.attrib[key], expected.attrib[key], "Different value for attribute '%s'" % key, location) def _compare_texts(self, actual, expected, location): self._compare(self._text(actual.text), self._text(expected.text), 'Different text', location) def _text(self, text): return self._normalizer(text or '') def _compare_tails(self, actual, expected, location): self._compare(self._text(actual.tail), self._text(expected.tail), 'Different tail text', location) def _compare_children(self, actual, expected, location): self._compare(len(actual), len(expected), 'Different number of child elements', location, should_be_equal) for act, exp in zip(actual, expected): self.compare(act, exp, location.child(act.tag)) class Location: def __init__(self, path, is_root=True): self.path = path self.is_not_root = not is_root self._children = {} def child(self, tag): if tag not in self._children: self._children[tag] = 1 else: self._children[tag] += 1 tag += '[%d]' % self._children[tag] return Location('%s/%s' % (self.path, tag), is_root=False)
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/libraries/XML.py
0.770983
0.520618
XML.py
pypi
import sys from typing import Callable, Generic, overload, TypeVar, Type, Union T = TypeVar('T') V = TypeVar('V') A = TypeVar('A') class setter(Generic[T, V, A]): """Modify instance attributes only when they are set, not when they are get. Usage:: @setter def source(self, source: str|Path) -> Path: return source if isinstance(source, Path) else Path(source) The setter method is called when the attribute is assigned like:: instance.source = 'example.txt' and the returned value is stored in the instance in an attribute like ``_setter__source``. When the attribute is accessed, the stored value is returned. The above example is equivalent to using the standard ``property`` as follows. The main benefit of using ``setter`` is that it avoids a dummy getter method:: @property def source(self) -> Path: return self._source @source.setter def source(self, source: src|Path): self._source = source if isinstance(source, Path) else Path(source) When using ``setter`` with ``__slots__``, the special ``_setter__xxx`` attributes needs to be added to ``__slots__`` as well. The provided :class:`SetterAwareType` metaclass can take care of that automatically. """ def __init__(self, method: Callable[[T, V], A]): self.method = method self.attr_name = '_setter__' + method.__name__ self.__doc__ = method.__doc__ @overload def __get__(self, instance: None, owner: Type[T]) -> 'setter': ... @overload def __get__(self, instance: T, owner: Type[T]) -> A: ... def __get__(self, instance: Union[T, None], owner: Type[T]) -> Union[A, 'setter']: if instance is None: return self try: return getattr(instance, self.attr_name) except AttributeError: raise AttributeError(self.method.__name__) def __set__(self, instance: T, value: V): if instance is not None: setattr(instance, self.attr_name, self.method(instance, value)) class SetterAwareType(type): """Metaclass for adding attributes used by :class:`setter` to ``__slots__``.""" def __new__(cls, name, bases, dct): if '__slots__' in dct: slots = list(dct['__slots__']) for item in dct.values(): if isinstance(item, setter): slots.append(item.attr_name) dct['__slots__'] = slots return type.__new__(cls, name, bases, dct) if sys.version_info < (3, 7): def __getitem__(self, item): return self
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/utils/setter.py
0.681303
0.262684
setter.py
pypi
import getopt import glob import os import re import shlex import sys import string import warnings from pathlib import Path from robot.errors import DataError, Information, FrameworkError from robot.version import get_full_version from .encoding import console_decode, system_decode from .filereader import FileReader from .misc import plural_or_not from .robottypes import is_falsy, is_integer, is_string def cmdline2list(args, escaping=False): if isinstance(args, Path): return [str(args)] lexer = shlex.shlex(args, posix=True) if is_falsy(escaping): lexer.escape = '' lexer.escapedquotes = '"\'' lexer.commenters = '' lexer.whitespace_split = True try: return list(lexer) except ValueError as err: raise ValueError("Parsing '%s' failed: %s" % (args, err)) class ArgumentParser: _opt_line_re = re.compile(r''' ^\s{1,4} # 1-4 spaces in the beginning of the line ((-\S\s)*) # all possible short options incl. spaces (group 1) --(\S{2,}) # required long option (group 3) (\s\S+)? # optional value (group 4) (\s\*)? # optional '*' telling option allowed multiple times (group 5) ''', re.VERBOSE) def __init__(self, usage, name=None, version=None, arg_limits=None, validator=None, env_options=None, auto_help=True, auto_version=True, auto_pythonpath='DEPRECATED', auto_argumentfile=True): """Available options and tool name are read from the usage. Tool name is got from the first row of the usage. It is either the whole row or anything before first ' -- '. """ if not usage: raise FrameworkError('Usage cannot be empty') self.name = name or usage.splitlines()[0].split(' -- ')[0].strip() self.version = version or get_full_version() self._usage = usage self._arg_limit_validator = ArgLimitValidator(arg_limits) self._validator = validator self._auto_help = auto_help self._auto_version = auto_version if auto_pythonpath == 'DEPRECATED': auto_pythonpath = False else: warnings.warn("ArgumentParser option 'auto_pythonpath' is deprecated " "since Robot Framework 5.0.") self._auto_pythonpath = auto_pythonpath self._auto_argumentfile = auto_argumentfile self._env_options = env_options self._short_opts = '' self._long_opts = [] self._multi_opts = [] self._flag_opts = [] self._short_to_long = {} self._expected_args = () self._create_options(usage) def parse_args(self, args): """Parse given arguments and return options and positional arguments. Arguments must be given as a list and are typically sys.argv[1:]. Options are returned as a dictionary where long options are keys. Value is a string for those options that can be given only one time (if they are given multiple times the last value is used) or None if the option is not used at all. Value for options that can be given multiple times (denoted with '*' in the usage) is a list which contains all the given values and is empty if options are not used. Options not taken arguments have value False when they are not set and True otherwise. Positional arguments are returned as a list in the order they are given. If 'check_args' is True, this method will automatically check that correct number of arguments, as parsed from the usage line, are given. If the last argument in the usage line ends with the character 's', the maximum number of arguments is infinite. Possible errors in processing arguments are reported using DataError. Some options have a special meaning and are handled automatically if defined in the usage and given from the command line: --argumentfile can be used to automatically read arguments from a specified file. When --argumentfile is used, the parser always allows using it multiple times. Adding '*' to denote that is thus recommend. A special value 'stdin' can be used to read arguments from stdin instead of a file. --pythonpath can be used to add extra path(s) to sys.path. This functionality was deprecated in Robot Framework 5.0. --help and --version automatically generate help and version messages. Version is generated based on the tool name and version -- see __init__ for information how to set them. Help contains the whole usage given to __init__. Possible <VERSION> text in the usage is replaced with the given version. Both help and version are wrapped to Information exception. """ args = self._get_env_options() + list(args) args = [system_decode(a) for a in args] if self._auto_argumentfile: args = self._process_possible_argfile(args) opts, args = self._parse_args(args) if self._auto_argumentfile and opts.get('argumentfile'): raise DataError("Using '--argumentfile' option in shortened format " "like '--argumentf' is not supported.") opts, args = self._handle_special_options(opts, args) self._arg_limit_validator(args) if self._validator: opts, args = self._validator(opts, args) return opts, args def _get_env_options(self): if self._env_options: options = os.getenv(self._env_options) if options: return cmdline2list(options) return [] def _handle_special_options(self, opts, args): if self._auto_help and opts.get('help'): self._raise_help() if self._auto_version and opts.get('version'): self._raise_version() if self._auto_pythonpath and opts.get('pythonpath'): sys.path = self._get_pythonpath(opts['pythonpath']) + sys.path for auto, opt in [(self._auto_help, 'help'), (self._auto_version, 'version'), (self._auto_pythonpath, 'pythonpath'), (self._auto_argumentfile, 'argumentfile')]: if auto and opt in opts: opts.pop(opt) return opts, args def _parse_args(self, args): args = [self._normalize_long_option(a) for a in args] try: opts, args = getopt.getopt(args, self._short_opts, self._long_opts) except getopt.GetoptError as err: raise DataError(err.msg) return self._process_opts(opts), self._glob_args(args) def _normalize_long_option(self, opt): if not opt.startswith('--'): return opt if '=' not in opt: return '--%s' % opt.lower().replace('-', '') opt, value = opt.split('=', 1) return '--%s=%s' % (opt.lower().replace('-', ''), value) def _process_possible_argfile(self, args): options = ['--argumentfile'] for short_opt, long_opt in self._short_to_long.items(): if long_opt == 'argumentfile': options.append('-'+short_opt) return ArgFileParser(options).process(args) def _process_opts(self, opt_tuple): opts = self._get_default_opts() for name, value in opt_tuple: name = self._get_name(name) if name in self._multi_opts: opts[name].append(value) elif name in self._flag_opts: opts[name] = True elif name.startswith('no') and name[2:] in self._flag_opts: opts[name[2:]] = False else: opts[name] = value return opts def _get_default_opts(self): defaults = {} for opt in self._long_opts: opt = opt.rstrip('=') if opt.startswith('no') and opt[2:] in self._flag_opts: continue defaults[opt] = [] if opt in self._multi_opts else None return defaults def _glob_args(self, args): temp = [] for path in args: paths = sorted(glob.glob(path)) if paths: temp.extend(paths) else: temp.append(path) return temp def _get_name(self, name): name = name.lstrip('-') try: return self._short_to_long[name] except KeyError: return name def _create_options(self, usage): for line in usage.splitlines(): res = self._opt_line_re.match(line) if res: self._create_option(short_opts=[o[1] for o in res.group(1).split()], long_opt=res.group(3).lower().replace('-', ''), takes_arg=bool(res.group(4)), is_multi=bool(res.group(5))) def _create_option(self, short_opts, long_opt, takes_arg, is_multi): self._verify_long_not_already_used(long_opt, not takes_arg) for sopt in short_opts: if sopt in self._short_to_long: self._raise_option_multiple_times_in_usage('-' + sopt) self._short_to_long[sopt] = long_opt if is_multi: self._multi_opts.append(long_opt) if takes_arg: long_opt += '=' short_opts = [sopt+':' for sopt in short_opts] else: if long_opt.startswith('no'): long_opt = long_opt[2:] self._long_opts.append('no' + long_opt) self._flag_opts.append(long_opt) self._long_opts.append(long_opt) self._short_opts += (''.join(short_opts)) def _verify_long_not_already_used(self, opt, flag=False): if flag: if opt.startswith('no'): opt = opt[2:] self._verify_long_not_already_used(opt) self._verify_long_not_already_used('no' + opt) elif opt in [o.rstrip('=') for o in self._long_opts]: self._raise_option_multiple_times_in_usage('--' + opt) def _get_pythonpath(self, paths): if is_string(paths): paths = [paths] temp = [] for path in self._split_pythonpath(paths): temp.extend(glob.glob(path)) return [os.path.abspath(path) for path in temp if path] def _split_pythonpath(self, paths): # paths may already contain ':' as separator tokens = ':'.join(paths).split(':') if os.sep == '/': return tokens # Fix paths split like 'c:\temp' -> 'c', '\temp' ret = [] drive = '' for item in tokens: item = item.replace('/', '\\') if drive and item.startswith('\\'): ret.append('%s:%s' % (drive, item)) drive = '' continue if drive: ret.append(drive) drive = '' if len(item) == 1 and item in string.ascii_letters: drive = item else: ret.append(item) if drive: ret.append(drive) return ret def _raise_help(self): usage = self._usage if self.version: usage = usage.replace('<VERSION>', self.version) raise Information(usage) def _raise_version(self): raise Information('%s %s' % (self.name, self.version)) def _raise_option_multiple_times_in_usage(self, opt): raise FrameworkError("Option '%s' multiple times in usage" % opt) class ArgLimitValidator: def __init__(self, arg_limits): self._min_args, self._max_args = self._parse_arg_limits(arg_limits) def _parse_arg_limits(self, arg_limits): if arg_limits is None: return 0, sys.maxsize if is_integer(arg_limits): return arg_limits, arg_limits if len(arg_limits) == 1: return arg_limits[0], sys.maxsize return arg_limits[0], arg_limits[1] def __call__(self, args): if not (self._min_args <= len(args) <= self._max_args): self._raise_invalid_args(self._min_args, self._max_args, len(args)) def _raise_invalid_args(self, min_args, max_args, arg_count): min_end = plural_or_not(min_args) if min_args == max_args: expectation = "%d argument%s" % (min_args, min_end) elif max_args != sys.maxsize: expectation = "%d to %d arguments" % (min_args, max_args) else: expectation = "at least %d argument%s" % (min_args, min_end) raise DataError("Expected %s, got %d." % (expectation, arg_count)) class ArgFileParser: def __init__(self, options): self._options = options def process(self, args): while True: path, replace = self._get_index(args) if not path: break args[replace] = self._get_args(path) return args def _get_index(self, args): for opt in self._options: start = opt + '=' if opt.startswith('--') else opt for index, arg in enumerate(args): normalized_arg = ( '--' + arg.lower().replace('-', '') if opt.startswith('--') else arg ) # Handles `--argumentfile foo` and `-A foo` if normalized_arg == opt and index + 1 < len(args): return args[index+1], slice(index, index+2) # Handles `--argumentfile=foo` and `-Afoo` if normalized_arg.startswith(start): return arg[len(start):], slice(index, index+1) return None, -1 def _get_args(self, path): if path.upper() != 'STDIN': content = self._read_from_file(path) else: content = self._read_from_stdin() return self._process_file(content) def _read_from_file(self, path): try: with FileReader(path) as reader: return reader.read() except (IOError, UnicodeError) as err: raise DataError("Opening argument file '%s' failed: %s" % (path, err)) def _read_from_stdin(self): return console_decode(sys.__stdin__.read()) def _process_file(self, content): args = [] for line in content.splitlines(): line = line.strip() if line.startswith('-'): args.extend(self._split_option(line)) elif line and not line.startswith('#'): args.append(line) return args def _split_option(self, line): separator = self._get_option_separator(line) if not separator: return [line] option, value = line.split(separator, 1) if separator == ' ': value = value.strip() return [option, value] def _get_option_separator(self, line): if ' ' not in line and '=' not in line: return None if '=' not in line: return ' ' if ' ' not in line: return '=' return ' ' if line.index(' ') < line.index('=') else '='
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/utils/argumentparser.py
0.467332
0.175609
argumentparser.py
pypi
from collections.abc import Iterable, Mapping from collections import UserString from io import IOBase from os import PathLike from typing import Any, TypeVar try: from types import UnionType except ImportError: # Python < 3.10 UnionType = () from typing import Union try: from typing import TypedDict except ImportError: # Python < 3.8 typeddict_types = () else: typeddict_types = (type(TypedDict('Dummy', {})),) try: from typing_extensions import TypedDict as ExtTypedDict except ImportError: pass else: typeddict_types += (type(ExtTypedDict('Dummy', {})),) from .platform import PY_VERSION TRUE_STRINGS = {'TRUE', 'YES', 'ON', '1'} FALSE_STRINGS = {'FALSE', 'NO', 'OFF', '0', 'NONE', ''} def is_integer(item): return isinstance(item, int) def is_number(item): return isinstance(item, (int, float)) def is_bytes(item): return isinstance(item, (bytes, bytearray)) def is_string(item): return isinstance(item, str) def is_pathlike(item): return isinstance(item, PathLike) def is_list_like(item): if isinstance(item, (str, bytes, bytearray, UserString, IOBase)): return False return isinstance(item, Iterable) def is_dict_like(item): return isinstance(item, Mapping) def is_union(item, allow_tuple=False): return (isinstance(item, UnionType) or getattr(item, '__origin__', None) is Union or (allow_tuple and isinstance(item, tuple))) def type_name(item, capitalize=False): """Return "non-technical" type name for objects and types. For example, 'integer' instead of 'int' and 'file' instead of 'TextIOWrapper'. """ if getattr(item, '__origin__', None): item = item.__origin__ if hasattr(item, '_name') and item._name: # Union, Any, etc. from typing have real name in _name and __name__ is just # generic `SpecialForm`. Also, pandas.Series has _name but it's None. name = item._name elif is_union(item): name = 'Union' elif isinstance(item, IOBase): name = 'file' else: typ = type(item) if not isinstance(item, type) else item named_types = {str: 'string', bool: 'boolean', int: 'integer', type(None): 'None', dict: 'dictionary'} name = named_types.get(typ, typ.__name__.strip('_')) # Generics from typing. With newer versions we get "real" type via __origin__. if PY_VERSION < (3, 7): if name in ('List', 'Set', 'Tuple'): name = name.lower() elif name == 'Dict': name = 'dictionary' return name.capitalize() if capitalize and name.islower() else name def type_repr(typ, nested=True): """Return string representation for types. Aims to look as much as the source code as possible. For example, 'List[Any]' instead of 'typing.List[typing.Any]'. """ if typ is type(None): return 'None' if typ is Ellipsis: return '...' if typ is Any: # Needed with Python 3.6, with newer `Any._name` exists. return 'Any' if is_union(typ): return ' | '.join(type_repr(a) for a in typ.__args__) if nested else 'Union' name = _get_type_name(typ) if nested and has_args(typ): args = ', '.join(type_repr(a) for a in typ.__args__) return f'{name}[{args}]' return name def _get_type_name(typ): for attr in '__name__', '_name': name = getattr(typ, attr, None) if name: return name return str(typ) def has_args(type): """Helper to check has type valid ``__args__``. ``__args__`` contains TypeVars when accessed directly from ``typing.List`` and other such types with Python 3.7-3.8. With Python 3.6 ``__args__`` is None in that case and with Python 3.9+ it doesn't exist at all. When using like ``List[int].__args__``, everything works the same way regardless the version. This helper can be removed in favor of using ``hasattr(type, '__args__')`` when we support only Python 3.9 and newer. """ args = getattr(type, '__args__', None) return args and not all(isinstance(a, TypeVar) for a in args) def is_truthy(item): """Returns `True` or `False` depending on is the item considered true or not. Validation rules: - If the value is a string, it is considered false if it is `'FALSE'`, `'NO'`, `'OFF'`, `'0'`, `'NONE'` or `''`, case-insensitively. - Other strings are considered true. - Other values are handled by using the standard `bool()` function. Designed to be used also by external test libraries that want to handle Boolean values similarly as Robot Framework itself. See also :func:`is_falsy`. """ if is_string(item): return item.upper() not in FALSE_STRINGS return bool(item) def is_falsy(item): """Opposite of :func:`is_truthy`.""" return not is_truthy(item)
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/utils/robottypes.py
0.843605
0.243316
robottypes.py
pypi
import os import sys import importlib import inspect from robot.errors import DataError from .error import get_error_details from .robotpath import abspath, normpath from .robotinspect import is_init from .robottypes import type_name class Importer: """Utility that can import modules and classes based on names and paths. Imported classes can optionally be instantiated automatically. """ def __init__(self, type=None, logger=None): """ :param type: Type of the thing being imported. Used in error and log messages. :param logger: Logger to be notified about successful imports and other events. Currently only needs the ``info`` method, but other level specific methods may be needed in the future. If not given, logging is disabled. """ self._type = type or '' self._logger = logger or NoLogger() self._importers = (ByPathImporter(logger), NonDottedImporter(logger), DottedImporter(logger)) self._by_path_importer = self._importers[0] def import_class_or_module(self, name_or_path, instantiate_with_args=None, return_source=False): """Imports Python class or module based on the given name or path. :param name_or_path: Name or path of the module or class to import. :param instantiate_with_args: When arguments are given, imported classes are automatically initialized using them. :param return_source: When true, returns a tuple containing the imported module or class and a path to it. By default, returns only the imported module or class. The class or module to import can be specified either as a name, in which case it must be in the module search path, or as a path to the file or directory implementing the module. See :meth:`import_class_or_module_by_path` for more information about importing classes and modules by path. Classes can be imported from the module search path using name like ``modulename.ClassName``. If the class name and module name are same, using just ``CommonName`` is enough. When importing a class by a path, the class name and the module name must match. Optional arguments to use when creating an instance are given as a list. Starting from Robot Framework 4.0, both positional and named arguments are supported (e.g. ``['positional', 'name=value']``) and arguments are converted automatically based on type hints and default values. If arguments needed when creating an instance are initially embedded into the name or path like ``Example:arg1:arg2``, separate :func:`~robot.utils.text.split_args_from_name_or_path` function can be used to split them before calling this method. Use :meth:`import_module` if only a module needs to be imported. """ try: imported, source = self._import(name_or_path) self._log_import_succeeded(imported, name_or_path, source) imported = self._instantiate_if_needed(imported, instantiate_with_args) except DataError as err: self._raise_import_failed(name_or_path, err) else: return self._handle_return_values(imported, source, return_source) def import_module(self, name_or_path): """Imports Python module based on the given name or path. :param name_or_path: Name or path of the module to import. The module to import can be specified either as a name, in which case it must be in the module search path, or as a path to the file or directory implementing the module. See :meth:`import_class_or_module_by_path` for more information about importing modules by path. Use :meth:`import_class_or_module` if it is desired to get a class from the imported module automatically. New in Robot Framework 6.0. """ try: imported, source = self._import(name_or_path, get_class=False) self._log_import_succeeded(imported, name_or_path, source) except DataError as err: self._raise_import_failed(name_or_path, err) else: return imported def _import(self, name, get_class=True): for importer in self._importers: if importer.handles(name): return importer.import_(name, get_class) def _handle_return_values(self, imported, source, return_source=False): if not return_source: return imported if source and os.path.exists(source): source = self._sanitize_source(source) return imported, source def _sanitize_source(self, source): source = normpath(source) if os.path.isdir(source): candidate = os.path.join(source, '__init__.py') elif source.endswith('.pyc'): candidate = source[:-4] + '.py' else: return source return candidate if os.path.exists(candidate) else source def import_class_or_module_by_path(self, path, instantiate_with_args=None): """Import a Python module or class using a file system path. :param path: Path to the module or class to import. :param instantiate_with_args: When arguments are given, imported classes are automatically initialized using them. When importing a Python file, the path must end with :file:`.py` and the actual file must also exist. Use :meth:`import_class_or_module` to support importing also using name, not only path. See the documentation of that function for more information about creating instances automatically. """ try: imported, source = self._by_path_importer.import_(path) self._log_import_succeeded(imported, imported.__name__, source) return self._instantiate_if_needed(imported, instantiate_with_args) except DataError as err: self._raise_import_failed(path, err) def _log_import_succeeded(self, item, name, source): import_type = '%s ' % self._type.lower() if self._type else '' item_type = 'module' if inspect.ismodule(item) else 'class' location = ("'%s'" % source) if source else 'unknown location' self._logger.info("Imported %s%s '%s' from %s." % (import_type, item_type, name, location)) def _raise_import_failed(self, name, error): prefix = f'Importing {self._type.lower()}' if self._type else 'Importing' raise DataError(f"{prefix} '{name}' failed: {error.message}") def _instantiate_if_needed(self, imported, args): if args is None: return imported if inspect.isclass(imported): return self._instantiate_class(imported, args) if args: raise DataError("Modules do not take arguments.") return imported def _instantiate_class(self, imported, args): spec = self._get_arg_spec(imported) try: positional, named = spec.resolve(args) except ValueError as err: raise DataError(err.args[0]) try: return imported(*positional, **dict(named)) except: raise DataError('Creating instance failed: %s\n%s' % get_error_details()) def _get_arg_spec(self, imported): # Avoid cyclic import. Yuck. from robot.running.arguments import ArgumentSpec, PythonArgumentParser init = getattr(imported, '__init__', None) name = imported.__name__ if not is_init(init): return ArgumentSpec(name, self._type) return PythonArgumentParser(self._type).parse(init, name) class _Importer: def __init__(self, logger): self._logger = logger def _import(self, name, fromlist=None): if name in sys.builtin_module_names: raise DataError('Cannot import custom module with same name as ' 'Python built-in module.') importlib.invalidate_caches() try: return __import__(name, fromlist=fromlist) except: message, traceback = get_error_details(full_traceback=False) path = '\n'.join(f' {p}' for p in sys.path) raise DataError(f'{message}\n{traceback}\nPYTHONPATH:\n{path}') def _verify_type(self, imported): if inspect.isclass(imported) or inspect.ismodule(imported): return imported raise DataError('Expected class or module, got %s.' % type_name(imported)) def _get_class_from_module(self, module, name=None): klass = getattr(module, name or module.__name__, None) return klass if inspect.isclass(klass) else None def _get_source(self, imported): try: source = inspect.getfile(imported) except TypeError: return None return abspath(source) if source else None class ByPathImporter(_Importer): _valid_import_extensions = ('.py', '') def handles(self, path): return os.path.isabs(path) def import_(self, path, get_class=True): self._verify_import_path(path) self._remove_wrong_module_from_sys_modules(path) imported = self._import_by_path(path) if get_class: imported = self._get_class_from_module(imported) or imported return self._verify_type(imported), path def _verify_import_path(self, path): if not os.path.exists(path): raise DataError('File or directory does not exist.') if not os.path.isabs(path): raise DataError('Import path must be absolute.') if not os.path.splitext(path)[1] in self._valid_import_extensions: raise DataError('Not a valid file or directory to import.') def _remove_wrong_module_from_sys_modules(self, path): importing_from, name = self._split_path_to_module(path) importing_package = os.path.splitext(path)[1] == '' if self._wrong_module_imported(name, importing_from, importing_package): del sys.modules[name] self._logger.info("Removed module '%s' from sys.modules to import " "fresh module." % name) def _split_path_to_module(self, path): module_dir, module_file = os.path.split(abspath(path)) module_name = os.path.splitext(module_file)[0] return module_dir, module_name def _wrong_module_imported(self, name, importing_from, importing_package): if name not in sys.modules: return False source = getattr(sys.modules[name], '__file__', None) if not source: # play safe return True imported_from, imported_package = self._get_import_information(source) return (normpath(importing_from, case_normalize=True) != normpath(imported_from, case_normalize=True) or importing_package != imported_package) def _get_import_information(self, source): imported_from, imported_file = self._split_path_to_module(source) imported_package = imported_file == '__init__' if imported_package: imported_from = os.path.dirname(imported_from) return imported_from, imported_package def _import_by_path(self, path): module_dir, module_name = self._split_path_to_module(path) sys.path.insert(0, module_dir) try: return self._import(module_name) finally: sys.path.remove(module_dir) class NonDottedImporter(_Importer): def handles(self, name): return '.' not in name def import_(self, name, get_class=True): imported = self._import(name) if get_class: imported = self._get_class_from_module(imported) or imported return self._verify_type(imported), self._get_source(imported) class DottedImporter(_Importer): def handles(self, name): return '.' in name def import_(self, name, get_class=True): parent_name, lib_name = name.rsplit('.', 1) parent = self._import(parent_name, fromlist=[str(lib_name)]) try: imported = getattr(parent, lib_name) except AttributeError: raise DataError("Module '%s' does not contain '%s'." % (parent_name, lib_name)) if get_class: imported = self._get_class_from_module(imported, lib_name) or imported return self._verify_type(imported), self._get_source(imported) class NoLogger: error = warn = info = debug = trace = lambda self, *args, **kws: None
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/utils/importer.py
0.638948
0.340321
importer.py
pypi
import difflib from robot.utils import seq2str class RecommendationFinder: def __init__(self, normalizer=None): self.normalizer = normalizer or (lambda x: x) def find_and_format(self, name, candidates, message, max_matches=10, check_missing_argument_separator=False): recommendations = self.find(name, candidates, max_matches) if recommendations: return self.format(message, recommendations) if check_missing_argument_separator and name: recommendation = self._check_missing_argument_separator(name, candidates) if recommendation: return f'{message} {recommendation}' return message def find(self, name, candidates, max_matches=10): """Return a list of close matches to `name` from `candidates`.""" if not name or not candidates: return [] norm_name = self.normalizer(name) norm_candidates = self._get_normalized_candidates(candidates) cutoff = self._calculate_cutoff(norm_name) norm_matches = difflib.get_close_matches( norm_name, norm_candidates, n=max_matches, cutoff=cutoff ) return self._get_original_candidates(norm_matches, norm_candidates) def format(self, message, recommendations): """Add recommendations to the given message. The recommendation string looks like:: <message> Did you mean: <recommendations[0]> <recommendations[1]> <recommendations[2]> """ if recommendations: message += " Did you mean:" for rec in recommendations: message += "\n %s" % rec return message def _get_normalized_candidates(self, candidates): norm_candidates = {} for cand in sorted(candidates): norm = self.normalizer(cand) norm_candidates.setdefault(norm, []).append(cand) return norm_candidates def _get_original_candidates(self, norm_matches, norm_candidates): candidates = [] for match in norm_matches: candidates.extend(norm_candidates[match]) return candidates def _calculate_cutoff(self, string, min_cutoff=0.5, max_cutoff=0.85, step=0.03): """Calculate a cutoff depending on string length. Default values determined by manual tuning until the results "look right". """ cutoff = min_cutoff + len(string) * step return min(cutoff, max_cutoff) def _check_missing_argument_separator(self, name, candidates): name = self.normalizer(name) candidates = self._get_normalized_candidates(candidates) matches = [c for c in candidates if name.startswith(c)] if not matches: return None candidates = self._get_original_candidates(matches, candidates) return (f"Did you try using keyword {seq2str(candidates, lastsep=' or ')} " f"and forgot to use enough whitespace between keyword and arguments?")
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/utils/recommendations.py
0.838746
0.298312
recommendations.py
pypi
import os import sys from .encodingsniffer import get_console_encoding, get_system_encoding from .misc import isatty from .robottypes import is_string from .unic import safe_str CONSOLE_ENCODING = get_console_encoding() SYSTEM_ENCODING = get_system_encoding() PYTHONIOENCODING = os.getenv('PYTHONIOENCODING') def console_decode(string, encoding=CONSOLE_ENCODING): """Decodes bytes from console encoding to Unicode. Uses the system console encoding by default, but that can be configured using the `encoding` argument. In addition to the normal encodings, it is possible to use case-insensitive values `CONSOLE` and `SYSTEM` to use the system console and system encoding, respectively. If `string` is already Unicode, it is returned as-is. """ if is_string(string): return string encoding = {'CONSOLE': CONSOLE_ENCODING, 'SYSTEM': SYSTEM_ENCODING}.get(encoding.upper(), encoding) try: return string.decode(encoding) except UnicodeError: return safe_str(string) def console_encode(string, encoding=None, errors='replace', stream=sys.__stdout__, force=False): """Encodes the given string so that it can be used in the console. If encoding is not given, determines it based on the given stream and system configuration. In addition to the normal encodings, it is possible to use case-insensitive values `CONSOLE` and `SYSTEM` to use the system console and system encoding, respectively. Decodes bytes back to Unicode by default, because Python 3 APIs in general work with strings. Use `force=True` if that is not desired. """ if not is_string(string): string = safe_str(string) if encoding: encoding = {'CONSOLE': CONSOLE_ENCODING, 'SYSTEM': SYSTEM_ENCODING}.get(encoding.upper(), encoding) else: encoding = _get_console_encoding(stream) if encoding.upper() != 'UTF-8': encoded = string.encode(encoding, errors) return encoded if force else encoded.decode(encoding) return string.encode(encoding, errors) if force else string def _get_console_encoding(stream): encoding = getattr(stream, 'encoding', None) if isatty(stream): return encoding or CONSOLE_ENCODING if PYTHONIOENCODING: return PYTHONIOENCODING return encoding or SYSTEM_ENCODING def system_decode(string): return string if is_string(string) else safe_str(string) def system_encode(string): return string if is_string(string) else safe_str(string)
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/utils/encoding.py
0.405684
0.156362
encoding.py
pypi
import re from .robottypes import is_integer from .unic import safe_str def printable_name(string, code_style=False): """Generates and returns printable name from the given string. Examples: 'simple' -> 'Simple' 'name with spaces' -> 'Name With Spaces' 'more spaces' -> 'More Spaces' 'Cases AND spaces' -> 'Cases AND Spaces' '' -> '' If 'code_style' is True: 'mixedCAPSCamel' -> 'Mixed CAPS Camel' 'camelCaseName' -> 'Camel Case Name' 'under_score_name' -> 'Under Score Name' 'under_and space' -> 'Under And Space' 'miXed_CAPS_nAMe' -> 'MiXed CAPS NAMe' '' -> '' """ if code_style and '_' in string: string = string.replace('_', ' ') parts = string.split() if code_style and len(parts) == 1 \ and not (string.isalpha() and string.islower()): parts = _split_camel_case(parts[0]) return ' '.join(part[0].upper() + part[1:] for part in parts) def _split_camel_case(string): tokens = [] token = [] for prev, char, next in zip(' ' + string, string, string[1:] + ' '): if _is_camel_case_boundary(prev, char, next): if token: tokens.append(''.join(token)) token = [char] else: token.append(char) if token: tokens.append(''.join(token)) return tokens def _is_camel_case_boundary(prev, char, next): if prev.isdigit(): return not char.isdigit() if char.isupper(): return next.islower() or prev.isalpha() and not prev.isupper() return char.isdigit() def plural_or_not(item): count = item if is_integer(item) else len(item) return '' if count in (1, -1) else 's' def seq2str(sequence, quote="'", sep=', ', lastsep=' and '): """Returns sequence in format `'item 1', 'item 2' and 'item 3'`.""" sequence = [f'{quote}{safe_str(item)}{quote}' for item in sequence] if not sequence: return '' if len(sequence) == 1: return sequence[0] last_two = lastsep.join(sequence[-2:]) return sep.join(sequence[:-2] + [last_two]) def seq2str2(sequence): """Returns sequence in format `[ item 1 | item 2 | ... ]`.""" if not sequence: return '[ ]' return '[ %s ]' % ' | '.join(safe_str(item) for item in sequence) def test_or_task(text: str, rpa: bool): """Replace 'test' with 'task' in the given `text` depending on `rpa`. If given text is `test`, `test` or `task` is returned directly. Otherwise, pattern `{test}` is searched from the text and occurrences replaced with `test` or `task`. In both cases matching the word `test` is case-insensitive and the returned `test` or `task` has exactly same case as the original. """ def replace(test): if not rpa: return test upper = [c.isupper() for c in test] return ''.join(c.upper() if up else c for c, up in zip('task', upper)) if text.upper() == 'TEST': return replace(text) return re.sub('{(test)}', lambda m: replace(m.group(1)), text, flags=re.IGNORECASE) def isatty(stream): # first check if buffer was detached if hasattr(stream, 'buffer') and stream.buffer is None: return False if not hasattr(stream, 'isatty'): return False try: return stream.isatty() except ValueError: # Occurs if file is closed. return False def parse_re_flags(flags=None): result = 0 if not flags: return result for flag in flags.split('|'): try: re_flag = getattr(re, flag.upper().strip()) except AttributeError: raise ValueError(f'Unknown regexp flag: {flag}') else: if isinstance(re_flag, re.RegexFlag): result |= re_flag else: raise ValueError(f'Unknown regexp flag: {flag}') return result class classproperty(property): """Property that works with classes in addition to instances. Only supports getters. Setters and deleters cannot work with classes due to how the descriptor protocol works, and they are thus explicitly disabled. Metaclasses must be used if they are needed. """ def __init__(self, fget, fset=None, fdel=None, doc=None): if fset: self.setter(fset) if fdel: self.deleter(fset) super().__init__(fget) if doc: self.__doc__ = doc def __get__(self, instance, owner): return self.fget(owner) def setter(self, fset): raise TypeError('Setters are not supported.') def deleter(self, fset): raise TypeError('Deleters are not supported.')
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/utils/misc.py
0.691081
0.267552
misc.py
pypi
import re from .robottypes import is_string _CONTROL_WORDS = frozenset(('ELSE', 'ELSE IF', 'AND', 'WITH NAME', 'AS')) _SEQUENCES_TO_BE_ESCAPED = ('\\', '${', '@{', '%{', '&{', '*{', '=') def escape(item): if not is_string(item): return item if item in _CONTROL_WORDS: return '\\' + item for seq in _SEQUENCES_TO_BE_ESCAPED: if seq in item: item = item.replace(seq, '\\' + seq) return item def glob_escape(item): # Python 3.4+ has `glob.escape()` but it has special handling for drives # that we don't want. for char in '[*?': if char in item: item = item.replace(char, '[%s]' % char) return item class Unescaper: _escape_sequences = re.compile(r''' (\\+) # escapes (n|r|t # n, r, or t |x[0-9a-fA-F]{2} # x+HH |u[0-9a-fA-F]{4} # u+HHHH |U[0-9a-fA-F]{8} # U+HHHHHHHH )? # optionally ''', re.VERBOSE) def __init__(self): self._escape_handlers = { '': lambda value: value, 'n': lambda value: '\n', 'r': lambda value: '\r', 't': lambda value: '\t', 'x': self._hex_to_unichr, 'u': self._hex_to_unichr, 'U': self._hex_to_unichr } def _hex_to_unichr(self, value): ordinal = int(value, 16) # No Unicode code points above 0x10FFFF if ordinal > 0x10FFFF: return 'U' + value # `chr` only supports ordinals up to 0xFFFF on narrow Python builds. # This may not be relevant anymore. if ordinal > 0xFFFF: return eval(r"'\U%08x'" % ordinal) return chr(ordinal) def unescape(self, item): if not (is_string(item) and '\\' in item): return item return self._escape_sequences.sub(self._handle_escapes, item) def _handle_escapes(self, match): escapes, text = match.groups() half, is_escaped = divmod(len(escapes), 2) escapes = escapes[:half] text = text or '' if is_escaped: marker, value = text[:1], text[1:] text = self._escape_handlers[marker](value) return escapes + text unescape = Unescaper().unescape def split_from_equals(string): from robot.variables import VariableIterator if not is_string(string) or '=' not in string: return string, None variables = VariableIterator(string, ignore_errors=True) if not variables and '\\' not in string: return tuple(string.split('=', 1)) try: index = _find_split_index(string, variables) except ValueError: return string, None return string[:index], string[index+1:] def _find_split_index(string, variables): relative_index = 0 for before, match, string in variables: try: return _find_split_index_from_part(before) + relative_index except ValueError: relative_index += len(before) + len(match) return _find_split_index_from_part(string) + relative_index def _find_split_index_from_part(string): index = 0 while '=' in string[index:]: index += string[index:].index('=') if _not_escaping(string[:index]): return index index += 1 raise ValueError def _not_escaping(name): backslashes = len(name) - len(name.rstrip('\\')) return backslashes % 2 == 0
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/utils/escaping.py
0.636692
0.210401
escaping.py
pypi
import functools from robot.errors import DataError try: from docutils.core import publish_doctree from docutils.parsers.rst import directives from docutils.parsers.rst import roles from docutils.parsers.rst.directives import register_directive from docutils.parsers.rst.directives.body import CodeBlock from docutils.parsers.rst.directives.misc import Include except ImportError: raise DataError("Using reStructuredText test data requires having " "'docutils' module version 0.9 or newer installed.") class RobotDataStorage: def __init__(self, doctree): if not hasattr(doctree, '_robot_data'): doctree._robot_data = [] self._robot_data = doctree._robot_data def add_data(self, rows): self._robot_data.extend(rows) def get_data(self): return '\n'.join(self._robot_data) def has_data(self): return bool(self._robot_data) class RobotCodeBlock(CodeBlock): def run(self): if 'robotframework' in self.arguments: store = RobotDataStorage(self.state_machine.document) store.add_data(self.content) return [] register_directive('code', RobotCodeBlock) register_directive('code-block', RobotCodeBlock) register_directive('sourcecode', RobotCodeBlock) relevant_directives = (RobotCodeBlock, Include) @functools.wraps(directives.directive) def directive(*args, **kwargs): directive_class, messages = directive.__wrapped__(*args, **kwargs) if directive_class not in relevant_directives: # Skipping unknown or non-relevant directive entirely directive_class = (lambda *args, **kwargs: []) return directive_class, messages @functools.wraps(roles.role) def role(*args, **kwargs): role_function = role.__wrapped__(*args, **kwargs) if role_function is None: # role is unknown, ignore role_function = (lambda *args, **kwargs: [], []) return role_function directives.directive = directive roles.role = role def read_rest_data(rstfile): doctree = publish_doctree( rstfile.read(), source_path=rstfile.name, settings_overrides={ 'input_encoding': 'UTF-8', 'report_level': 4 }) store = RobotDataStorage(doctree) return store.get_data()
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/utils/restreader.py
0.52683
0.267056
restreader.py
pypi
from collections.abc import Iterator from io import StringIO from pathlib import Path from typing import TextIO, Union from .robottypes import is_bytes, is_pathlike, is_string Source = Union[Path, str, TextIO] class FileReader: # FIXME: Rename to SourceReader """Utility to ease reading different kind of source files. Supports different sources where to read the data: - The source can be a path to a file, either as a string or as a ``pathlib.Path`` instance. The file itself must be UTF-8 encoded. - Alternatively the source can be an already opened file object, including a StringIO or BytesIO object. The file can contain either Unicode text or UTF-8 encoded bytes. - The third options is giving the source as Unicode text directly. This requires setting ``accept_text=True`` when creating the reader. In all cases bytes are automatically decoded to Unicode and possible BOM removed. """ def __init__(self, source: Source, accept_text: bool = False): self.file, self._opened = self._get_file(source, accept_text) def _get_file(self, source: Source, accept_text: bool) -> 'tuple[TextIO, bool]': path = self._get_path(source, accept_text) if path: file = open(path, 'rb') opened = True elif is_string(source): file = StringIO(source) opened = True else: file = source opened = False return file, opened def _get_path(self, source: Source, accept_text: bool): if is_pathlike(source): return str(source) if not is_string(source): return None if not accept_text: return source if '\n' in source: return None path = Path(source) try: is_path = path.is_absolute() or path.exists() except OSError: # Can happen on Windows w/ Python < 3.10. is_path = False return source if is_path else None @property def name(self) -> str: return getattr(self.file, 'name', '<in-memory file>') def __enter__(self): return self def __exit__(self, *exc_info): if self._opened: self.file.close() def read(self) -> str: return self._decode(self.file.read()) def readlines(self) -> 'Iterator[str]': first_line = True for line in self.file.readlines(): yield self._decode(line, remove_bom=first_line) first_line = False def _decode(self, content: 'str|bytes', remove_bom: bool = True) -> str: if is_bytes(content): content = content.decode('UTF-8') if remove_bom and content.startswith('\ufeff'): content = content[1:] if '\r\n' in content: content = content.replace('\r\n', '\n') return content
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/utils/filereader.py
0.651355
0.26839
filereader.py
pypi
import re import fnmatch from typing import Iterable, Iterator, Sequence from .normalizing import normalize from .robottypes import is_string def eq(str1: str, str2: str, ignore: Sequence[str] = (), caseless: bool = True, spaceless: bool = True) -> bool: str1 = normalize(str1, ignore, caseless, spaceless) str2 = normalize(str2, ignore, caseless, spaceless) return str1 == str2 class Matcher: def __init__(self, pattern: str, ignore: Sequence[str] = (), caseless: bool = True, spaceless: bool = True, regexp: bool = False): self.pattern = pattern if caseless or spaceless or ignore: self._normalize = lambda s: normalize(s, ignore, caseless, spaceless) else: self._normalize = lambda s: s self._regexp = self._compile(self._normalize(pattern), regexp=regexp) def _compile(self, pattern, regexp=False): if not regexp: pattern = fnmatch.translate(pattern) return re.compile(pattern, re.DOTALL) def match(self, string: str) -> bool: return self._regexp.match(self._normalize(string)) is not None def match_any(self, strings: Iterable[str]) -> bool: return any(self.match(s) for s in strings) def __bool__(self) -> bool: return bool(self._normalize(self.pattern)) class MultiMatcher(Iterable[Matcher]): def __init__(self, patterns: Iterable[str] = (), ignore: Sequence[str] = (), caseless: bool = True, spaceless: bool = True, match_if_no_patterns: bool = False, regexp: bool = False): self.matchers = [Matcher(pattern, ignore, caseless, spaceless, regexp) for pattern in self._ensure_iterable(patterns)] self.match_if_no_patterns = match_if_no_patterns def _ensure_iterable(self, patterns): if patterns is None: return () if is_string(patterns): return (patterns,) return patterns def match(self, string: str) -> bool: if self.matchers: return any(m.match(string) for m in self.matchers) return self.match_if_no_patterns def match_any(self, strings: Iterable[str]) -> bool: return any(self.match(s) for s in strings) def __len__(self) -> int: return len(self.matchers) def __iter__(self) -> Iterator[Matcher]: return iter(self.matchers)
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/utils/match.py
0.802401
0.310198
match.py
pypi
import os import os.path import sys from urllib.request import pathname2url as path_to_url from robot.errors import DataError from .encoding import system_decode from .platform import WINDOWS from .robottypes import is_string from .unic import safe_str if WINDOWS: CASE_INSENSITIVE_FILESYSTEM = True else: try: CASE_INSENSITIVE_FILESYSTEM = os.listdir('/tmp') == os.listdir('/TMP') except OSError: CASE_INSENSITIVE_FILESYSTEM = False def normpath(path, case_normalize=False): """Replacement for os.path.normpath with some enhancements. 1. Convert non-Unicode paths to Unicode using the file system encoding. 2. NFC normalize Unicode paths (affects mainly OSX). 3. Optionally lower-case paths on case-insensitive file systems. That includes Windows and also OSX in default configuration. 4. Turn ``c:`` into ``c:\\`` on Windows instead of keeping it as ``c:``. """ if not is_string(path): path = system_decode(path) path = safe_str(path) # Handles NFC normalization on OSX path = os.path.normpath(path) if case_normalize and CASE_INSENSITIVE_FILESYSTEM: path = path.lower() if WINDOWS and len(path) == 2 and path[1] == ':': return path + '\\' return path def abspath(path, case_normalize=False): """Replacement for os.path.abspath with some enhancements and bug fixes. 1. Non-Unicode paths are converted to Unicode using file system encoding. 2. Optionally lower-case paths on case-insensitive file systems. That includes Windows and also OSX in default configuration. 3. Turn ``c:`` into ``c:\\`` on Windows instead of ``c:\\current\\path``. """ path = normpath(path, case_normalize) return normpath(os.path.abspath(path), case_normalize) def get_link_path(target, base): """Returns a relative path to ``target`` from ``base``. If ``base`` is an existing file, then its parent directory is considered to be the base. Otherwise ``base`` is assumed to be a directory. The returned path is URL encoded. On Windows returns an absolute path with ``file:`` prefix if the target is on a different drive. """ path = _get_link_path(target, base) url = path_to_url(path) if os.path.isabs(path): url = 'file:' + url return url def _get_link_path(target, base): target = abspath(target) base = abspath(base) if os.path.isfile(base): base = os.path.dirname(base) if base == target: return '.' base_drive, base_path = os.path.splitdrive(base) # Target and base on different drives if os.path.splitdrive(target)[0] != base_drive: return target common_len = len(_common_path(base, target)) if base_path == os.sep: return target[common_len:] if common_len == len(base_drive) + len(os.sep): common_len -= len(os.sep) dirs_up = os.sep.join([os.pardir] * base[common_len:].count(os.sep)) path = os.path.join(dirs_up, target[common_len + len(os.sep):]) return os.path.normpath(path) def _common_path(p1, p2): """Returns the longest path common to p1 and p2. Rationale: as os.path.commonprefix is character based, it doesn't consider path separators as such, so it may return invalid paths: commonprefix(('/foo/bar/', '/foo/baz.txt')) -> '/foo/ba' (instead of /foo) """ # os.path.dirname doesn't normalize leading double slash # https://github.com/robotframework/robotframework/issues/3844 if p1.startswith('//'): p1 = '/' + p1.lstrip('/') if p2.startswith('//'): p2 = '/' + p2.lstrip('/') while p1 and p2: if p1 == p2: return p1 if len(p1) > len(p2): p1 = os.path.dirname(p1) else: p2 = os.path.dirname(p2) return '' def find_file(path, basedir='.', file_type=None): path = os.path.normpath(path.replace('/', os.sep)) if os.path.isabs(path): ret = _find_absolute_path(path) else: ret = _find_relative_path(path, basedir) if ret: return ret raise DataError(f"{file_type or 'File'} '{path}' does not exist.") def _find_absolute_path(path): if _is_valid_file(path): return path return None def _find_relative_path(path, basedir): for base in [basedir] + sys.path: if not (base and os.path.isdir(base)): continue if not is_string(base): base = system_decode(base) ret = os.path.abspath(os.path.join(base, path)) if _is_valid_file(ret): return ret return None def _is_valid_file(path): return os.path.isfile(path) or \ (os.path.isdir(path) and os.path.isfile(os.path.join(path, '__init__.py')))
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/utils/robotpath.py
0.442637
0.217462
robotpath.py
pypi
from .robottypes import type_name from .unic import safe_str def fail(msg=None): """Fail test immediately with the given message.""" _report_failure(msg) def assert_false(expr, msg=None): """Fail the test if the expression is True.""" if expr: _report_failure(msg) def assert_true(expr, msg=None): """Fail the test unless the expression is True.""" if not expr: _report_failure(msg) def assert_not_none(obj, msg=None, values=True): """Fail the test if given object is None.""" _msg = 'is None' if obj is None: if msg is None: msg = _msg elif values is True: msg = '%s: %s' % (msg, _msg) _report_failure(msg) def assert_none(obj, msg=None, values=True): """Fail the test if given object is not None.""" _msg = '%r is not None' % obj if obj is not None: if msg is None: msg = _msg elif values is True: msg = '%s: %s' % (msg, _msg) _report_failure(msg) def assert_raises(exc_class, callable_obj, *args, **kwargs): """Fail unless an exception of class exc_class is thrown by callable_obj. callable_obj is invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. If a correct exception is raised, the exception instance is returned by this method. """ try: callable_obj(*args, **kwargs) except exc_class as err: return err else: if hasattr(exc_class,'__name__'): exc_name = exc_class.__name__ else: exc_name = str(exc_class) _report_failure('%s not raised' % exc_name) def assert_raises_with_msg(exc_class, expected_msg, callable_obj, *args, **kwargs): """Similar to fail_unless_raises but also checks the exception message.""" try: callable_obj(*args, **kwargs) except exc_class as err: assert_equal(expected_msg, str(err), 'Correct exception but wrong message') else: if hasattr(exc_class,'__name__'): exc_name = exc_class.__name__ else: exc_name = str(exc_class) _report_failure('%s not raised' % exc_name) def assert_equal(first, second, msg=None, values=True, formatter=safe_str): """Fail if given objects are unequal as determined by the '==' operator.""" if not first == second: _report_inequality(first, second, '!=', msg, values, formatter) def assert_not_equal(first, second, msg=None, values=True, formatter=safe_str): """Fail if given objects are equal as determined by the '==' operator.""" if first == second: _report_inequality(first, second, '==', msg, values, formatter) def assert_almost_equal(first, second, places=7, msg=None, values=True): """Fail if the two objects are unequal after rounded to given places. inequality is determined by object's difference rounded to the given number of decimal places (default 7) and comparing to zero. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit). """ if round(second - first, places) != 0: extra = 'within %r places' % places _report_inequality(first, second, '!=', msg, values, extra=extra) def assert_not_almost_equal(first, second, places=7, msg=None, values=True): """Fail if the two objects are unequal after rounded to given places. Equality is determined by object's difference rounded to to the given number of decimal places (default 7) and comparing to zero. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit). """ if round(second-first, places) == 0: extra = 'within %r places' % places _report_inequality(first, second, '==', msg, values, extra=extra) def _report_failure(msg): if msg is None: raise AssertionError() raise AssertionError(msg) def _report_inequality(obj1, obj2, delim, msg=None, values=False, formatter=safe_str, extra=None): if not msg: msg = _format_message(obj1, obj2, delim, formatter) elif values: msg = '%s: %s' % (msg, _format_message(obj1, obj2, delim, formatter)) if values and extra: msg += ' ' + extra raise AssertionError(msg) def _format_message(obj1, obj2, delim, formatter=safe_str): str1 = formatter(obj1) str2 = formatter(obj2) if delim == '!=' and str1 == str2: return '%s (%s) != %s (%s)' % (str1, type_name(obj1), str2, type_name(obj2)) return '%s %s %s' % (str1, delim, str2)
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/utils/asserts.py
0.685107
0.297075
asserts.py
pypi
import re from collections.abc import Iterable, Iterator, Mapping, Sequence from typing import Any, MutableMapping, overload, TypeVar V = TypeVar('V') Self = TypeVar('Self', bound='NormalizedDict') @overload def normalize(string: str, ignore: 'Sequence[str]' = (), caseless: bool = True, spaceless: bool = True) -> str: ... @overload def normalize(string: bytes, ignore: 'Sequence[bytes]' = (), caseless: bool = True, spaceless: bool = True) -> bytes: ... # TODO: Remove bytes support in RF 7.0. There shouldn't be needs for that with Python 3. def normalize(string, ignore=(), caseless=True, spaceless=True): """Normalize the ``string`` according to the given spec. By default, string is turned to lower case and all whitespace is removed. Additional characters can be removed by giving them in ``ignore`` list. """ empty = '' if isinstance(string, str) else b'' if isinstance(ignore, bytes): # Iterating bytes in Python3 yields integers. ignore = [bytes([i]) for i in ignore] if spaceless: string = empty.join(string.split()) if caseless: string = string.lower() ignore = [i.lower() for i in ignore] # both if statements below enhance performance a little if ignore: for ign in ignore: if ign in string: string = string.replace(ign, empty) return string def normalize_whitespace(string): return re.sub(r'\s', ' ', string, flags=re.UNICODE) class NormalizedDict(MutableMapping[str, V]): """Custom dictionary implementation automatically normalizing keys.""" def __init__(self, initial: 'Mapping[str, V]|Iterable[tuple[str, V]]|None' = None, ignore: 'Sequence[str]' = (), caseless: bool = True, spaceless: bool = True): """Initialized with possible initial value and normalizing spec. Initial values can be either a dictionary or an iterable of name/value pairs. Normalizing spec has exact same semantics as with the :func:`normalize` function. """ self._data: 'dict[str, V]' = {} self._keys: 'dict[str, str]' = {} self._normalize = lambda s: normalize(s, ignore, caseless, spaceless) if initial: self.update(initial) @property def normalized_keys(self) -> 'tuple[str, ...]': return tuple(self._keys) def __getitem__(self, key: str) -> V: return self._data[self._normalize(key)] def __setitem__(self, key: str, value: V): norm_key = self._normalize(key) self._data[norm_key] = value self._keys.setdefault(norm_key, key) def __delitem__(self, key: str): norm_key = self._normalize(key) del self._data[norm_key] del self._keys[norm_key] def __iter__(self) -> 'Iterator[str]': return (self._keys[norm_key] for norm_key in sorted(self._keys)) def __len__(self) -> int: return len(self._data) def __str__(self) -> str: items = ', '.join(f'{key!r}: {self[key]!r}' for key in self) return f'{{{items}}}' def __repr__(self) -> str: name = type(self).__name__ params = str(self) if self else '' return f'{name}({params})' def __eq__(self, other: Any) -> bool: if not isinstance(other, Mapping): return False if not isinstance(other, NormalizedDict): other = NormalizedDict(other) return self._data == other._data def copy(self: Self) -> Self: copy = type(self)() copy._data = self._data.copy() copy._keys = self._keys.copy() copy._normalize = self._normalize return copy # Speed-ups. Following methods are faster than default implementations. def __contains__(self, key: str) -> bool: return self._normalize(key) in self._data def clear(self): self._data.clear() self._keys.clear()
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/utils/normalizing.py
0.711832
0.437343
normalizing.py
pypi
import inspect from itertools import chain from pathlib import Path from typing import cast, Iterable, Iterator, Union from robot.errors import DataError from robot.utils import classproperty, is_list_like, Importer, normalize LanguageLike = Union['Language', str, Path] LanguagesLike = Union['Languages', LanguageLike, Iterable[LanguageLike], None] class Languages: """Stores languages and unifies translations. Example:: languages = Languages('de', add_english=False) print(languages.settings) languages = Languages(['pt-BR', 'Finnish', 'MyLang.py']) for lang in languages: print(lang.name, lang.code) """ def __init__(self, languages: 'Iterable[LanguageLike]|LanguageLike|None' = (), add_english: bool = True): """ :param languages: Initial language or list of languages. Languages can be given as language codes or names, paths or names of language modules to load, or as :class:`Language` instances. :param add_english: If True, English is added automatically. :raises: :class:`~robot.errors.DataError` if a given language is not found. :meth:`add_language` can be used to add languages after initialization. """ self.languages: 'list[Language]' = [] self.headers: 'dict[str, str]' = {} self.settings: 'dict[str, str]' = {} self.bdd_prefixes: 'set[str]' = set() self.true_strings: 'set[str]' = {'True', '1'} self.false_strings: 'set[str]' = {'False', '0', 'None', ''} for lang in self._get_languages(languages, add_english): self._add_language(lang) def reset(self, languages: Iterable[LanguageLike] = (), add_english: bool = True): """Resets the instance to the given languages.""" self.__init__(languages, add_english) def add_language(self, lang: LanguageLike): """Add new language. :param lang: Language to add. Can be a language code or name, name or path of a language module to load, or a :class:`Language` instance. :raises: :class:`~robot.errors.DataError` if the language is not found. Language codes and names are passed to by :meth:`Language.from_name`. Language modules are imported and :class:`Language` subclasses in them loaded. """ if isinstance(lang, Language): languages = [lang] elif isinstance(lang, Path) or self._exists(Path(lang)): languages = self._import_language_module(Path(lang)) else: try: languages = [Language.from_name(lang)] except ValueError as err1: try: languages = self._import_language_module(lang) except DataError as err2: raise DataError(f'{err1} {err2}') from None for lang in languages: self._add_language(lang) def _exists(self, path: Path): try: return path.exists() except OSError: # Can happen on Windows w/ Python < 3.10. return False def _add_language(self, lang: 'Language'): if lang in self.languages: return self.languages.append(lang) self.headers.update({n.title(): lang.headers[n] for n in lang.headers if n}) self.settings.update({n.title(): lang.settings[n] for n in lang.settings if n}) self.bdd_prefixes |= {p.title() for p in lang.bdd_prefixes} self.true_strings |= {s.title() for s in lang.true_strings} self.false_strings |= {s.title() for s in lang.false_strings} def _get_languages(self, languages, add_english=True) -> 'list[Language]': languages = self._resolve_languages(languages, add_english) available = self._get_available_languages() returned: 'list[Language]' = [] for lang in languages: if isinstance(lang, Language): returned.append(lang) elif isinstance(lang, Path): returned.extend(self._import_language_module(lang)) else: normalized = normalize(lang, ignore='-') if normalized in available: returned.append(available[normalized]()) else: returned.extend(self._import_language_module(lang)) return returned def _resolve_languages(self, languages, add_english=True): if not languages: languages = [] elif is_list_like(languages): languages = list(languages) else: languages = [languages] if add_english: languages.append(En()) # The English singular forms are added for backwards compatibility self.headers = { 'Setting': 'Settings', 'Variable': 'Variables', 'Test Case': 'Test Cases', 'Task': 'Tasks', 'Keyword': 'Keywords', 'Comment': 'Comments' } return languages def _get_available_languages(self) -> 'dict[str, type[Language]]': available = {} for lang in Language.__subclasses__(): available[normalize(cast(str, lang.code), ignore='-')] = lang available[normalize(cast(str, lang.name))] = lang if '' in available: available.pop('') return available def _import_language_module(self, name_or_path) -> 'list[Language]': def is_language(member): return (inspect.isclass(member) and issubclass(member, Language) and member is not Language) if isinstance(name_or_path, Path): name_or_path = name_or_path.absolute() elif self._exists(Path(name_or_path)): name_or_path = Path(name_or_path).absolute() module = Importer('language file').import_module(name_or_path) return [value() for _, value in inspect.getmembers(module, is_language)] def __iter__(self) -> 'Iterator[Language]': return iter(self.languages) class Language: """Base class for language definitions. New translations can be added by extending this class and setting class attributes listed below. Language :attr:`code` is got based on the class name and :attr:`name` based on the docstring. """ settings_header = None variables_header = None test_cases_header = None tasks_header = None keywords_header = None comments_header = None library_setting = None resource_setting = None variables_setting = None name_setting = None documentation_setting = None metadata_setting = None suite_setup_setting = None suite_teardown_setting = None test_setup_setting = None task_setup_setting = None test_teardown_setting = None task_teardown_setting = None test_template_setting = None task_template_setting = None test_timeout_setting = None task_timeout_setting = None test_tags_setting = None task_tags_setting = None keyword_tags_setting = None tags_setting = None setup_setting = None teardown_setting = None template_setting = None timeout_setting = None arguments_setting = None given_prefixes = [] when_prefixes = [] then_prefixes = [] and_prefixes = [] but_prefixes = [] true_strings = [] false_strings = [] @classmethod def from_name(cls, name) -> 'Language': """Return language class based on given `name`. Name can either be a language name (e.g. 'Finnish' or 'Brazilian Portuguese') or a language code (e.g. 'fi' or 'pt-BR'). Matching is case and space insensitive and the hyphen is ignored when matching language codes. Raises `ValueError` if no matching language is found. """ normalized = normalize(name, ignore='-') for lang in cls.__subclasses__(): if normalized == normalize(lang.__name__): return lang() if lang.__doc__ and normalized == normalize(lang.__doc__.splitlines()[0]): return lang() raise ValueError(f"No language with name '{name}' found.") @classproperty def code(cls) -> str: """Language code like 'fi' or 'pt-BR'. Got based on the class name. If the class name is two characters (or less), the code is just the name in lower case. If it is longer, a hyphen is added and the remainder of the class name is upper-cased. This special property can be accessed also directly from the class. """ if cls is Language: return cls.__dict__['code'] code = cast(type, cls).__name__.lower() if len(code) < 3: return code return f'{code[:2]}-{code[2:].upper()}' @classproperty def name(cls) -> str: """Language name like 'Finnish' or 'Brazilian Portuguese'. Got from the first line of the class docstring. This special property can be accessed also directly from the class. """ if cls is Language: return cls.__dict__['name'] return cls.__doc__.splitlines()[0] if cls.__doc__ else '' @property def headers(self) -> 'dict[str|None, str]': return { self.settings_header: En.settings_header, self.variables_header: En.variables_header, self.test_cases_header: En.test_cases_header, self.tasks_header: En.tasks_header, self.keywords_header: En.keywords_header, self.comments_header: En.comments_header } @property def settings(self) -> 'dict[str|None, str]': return { self.library_setting: En.library_setting, self.resource_setting: En.resource_setting, self.variables_setting: En.variables_setting, self.name_setting: En.name_setting, self.documentation_setting: En.documentation_setting, self.metadata_setting: En.metadata_setting, self.suite_setup_setting: En.suite_setup_setting, self.suite_teardown_setting: En.suite_teardown_setting, self.test_setup_setting: En.test_setup_setting, self.task_setup_setting: En.task_setup_setting, self.test_teardown_setting: En.test_teardown_setting, self.task_teardown_setting: En.task_teardown_setting, self.test_template_setting: En.test_template_setting, self.task_template_setting: En.task_template_setting, self.test_timeout_setting: En.test_timeout_setting, self.task_timeout_setting: En.task_timeout_setting, self.test_tags_setting: En.test_tags_setting, self.task_tags_setting: En.task_tags_setting, self.keyword_tags_setting: En.keyword_tags_setting, self.tags_setting: En.tags_setting, self.setup_setting: En.setup_setting, self.teardown_setting: En.teardown_setting, self.template_setting: En.template_setting, self.timeout_setting: En.timeout_setting, self.arguments_setting: En.arguments_setting, } @property def bdd_prefixes(self) -> 'set[str]': return set(chain(self.given_prefixes, self.when_prefixes, self.then_prefixes, self.and_prefixes, self.but_prefixes)) def __eq__(self, other): return isinstance(other, type(self)) def __hash__(self): return hash(type(self)) class En(Language): """English""" settings_header = 'Settings' variables_header = 'Variables' test_cases_header = 'Test Cases' tasks_header = 'Tasks' keywords_header = 'Keywords' comments_header = 'Comments' library_setting = 'Library' resource_setting = 'Resource' variables_setting = 'Variables' name_setting = 'Name' documentation_setting = 'Documentation' metadata_setting = 'Metadata' suite_setup_setting = 'Suite Setup' suite_teardown_setting = 'Suite Teardown' test_setup_setting = 'Test Setup' task_setup_setting = 'Task Setup' test_teardown_setting = 'Test Teardown' task_teardown_setting = 'Task Teardown' test_template_setting = 'Test Template' task_template_setting = 'Task Template' test_timeout_setting = 'Test Timeout' task_timeout_setting = 'Task Timeout' test_tags_setting = 'Test Tags' task_tags_setting = 'Task Tags' keyword_tags_setting = 'Keyword Tags' setup_setting = 'Setup' teardown_setting = 'Teardown' template_setting = 'Template' tags_setting = 'Tags' timeout_setting = 'Timeout' arguments_setting = 'Arguments' given_prefixes = ['Given'] when_prefixes = ['When'] then_prefixes = ['Then'] and_prefixes = ['And'] but_prefixes = ['But'] true_strings = ['True', 'Yes', 'On'] false_strings = ['False', 'No', 'Off'] class Cs(Language): """Czech""" settings_header = 'Nastavení' variables_header = 'Proměnné' test_cases_header = 'Testovací případy' tasks_header = 'Úlohy' keywords_header = 'Klíčová slova' comments_header = 'Komentáře' library_setting = 'Knihovna' resource_setting = 'Zdroj' variables_setting = 'Proměnná' name_setting = 'Název' documentation_setting = 'Dokumentace' metadata_setting = 'Metadata' suite_setup_setting = 'Příprava sady' suite_teardown_setting = 'Ukončení sady' test_setup_setting = 'Příprava testu' test_teardown_setting = 'Ukončení testu' test_template_setting = 'Šablona testu' test_timeout_setting = 'Časový limit testu' test_tags_setting = 'Štítky testů' task_setup_setting = 'Příprava úlohy' task_teardown_setting = 'Ukončení úlohy' task_template_setting = 'Šablona úlohy' task_timeout_setting = 'Časový limit úlohy' task_tags_setting = 'Štítky úloh' keyword_tags_setting = 'Štítky klíčových slov' tags_setting = 'Štítky' setup_setting = 'Příprava' teardown_setting = 'Ukončení' template_setting = 'Šablona' timeout_setting = 'Časový limit' arguments_setting = 'Argumenty' given_prefixes = ['Pokud'] when_prefixes = ['Když'] then_prefixes = ['Pak'] and_prefixes = ['A'] but_prefixes = ['Ale'] true_strings = ['Pravda', 'Ano', 'Zapnuto'] false_strings = ['Nepravda', 'Ne', 'Vypnuto', 'Nic'] class Nl(Language): """Dutch""" settings_header = 'Instellingen' variables_header = 'Variabelen' test_cases_header = 'Testgevallen' tasks_header = 'Taken' keywords_header = 'Sleutelwoorden' comments_header = 'Opmerkingen' library_setting = 'Bibliotheek' resource_setting = 'Resource' variables_setting = 'Variabele' name_setting = 'Naam' documentation_setting = 'Documentatie' metadata_setting = 'Metadata' suite_setup_setting = 'Suite Preconditie' suite_teardown_setting = 'Suite Postconditie' test_setup_setting = 'Test Preconditie' test_teardown_setting = 'Test Postconditie' test_template_setting = 'Test Sjabloon' test_timeout_setting = 'Test Time-out' test_tags_setting = 'Test Labels' task_setup_setting = 'Taak Preconditie' task_teardown_setting = 'Taak Postconditie' task_template_setting = 'Taak Sjabloon' task_timeout_setting = 'Taak Time-out' task_tags_setting = 'Taak Labels' keyword_tags_setting = 'Sleutelwoord Labels' tags_setting = 'Labels' setup_setting = 'Preconditie' teardown_setting = 'Postconditie' template_setting = 'Sjabloon' timeout_setting = 'Time-out' arguments_setting = 'Parameters' given_prefixes = ['Stel', 'Gegeven'] when_prefixes = ['Als'] then_prefixes = ['Dan'] and_prefixes = ['En'] but_prefixes = ['Maar'] true_strings = ['Waar', 'Ja', 'Aan'] false_strings = ['Onwaar', 'Nee', 'Uit', 'Geen'] class Bs(Language): """Bosnian""" settings_header = 'Postavke' variables_header = 'Varijable' test_cases_header = 'Test Cases' tasks_header = 'Taskovi' keywords_header = 'Keywords' comments_header = 'Komentari' library_setting = 'Biblioteka' resource_setting = 'Resursi' variables_setting = 'Varijable' documentation_setting = 'Dokumentacija' metadata_setting = 'Metadata' suite_setup_setting = 'Suite Postavke' suite_teardown_setting = 'Suite Teardown' test_setup_setting = 'Test Postavke' test_teardown_setting = 'Test Teardown' test_template_setting = 'Test Template' test_timeout_setting = 'Test Timeout' test_tags_setting = 'Test Tagovi' task_setup_setting = 'Task Postavke' task_teardown_setting = 'Task Teardown' task_template_setting = 'Task Template' task_timeout_setting = 'Task Timeout' task_tags_setting = 'Task Tagovi' keyword_tags_setting = 'Keyword Tagovi' tags_setting = 'Tagovi' setup_setting = 'Postavke' teardown_setting = 'Teardown' template_setting = 'Template' timeout_setting = 'Timeout' arguments_setting = 'Argumenti' given_prefixes = ['Uslovno'] when_prefixes = ['Kada'] then_prefixes = ['Tada'] and_prefixes = ['I'] but_prefixes = ['Ali'] class Fi(Language): """Finnish""" settings_header = 'Asetukset' variables_header = 'Muuttujat' test_cases_header = 'Testit' tasks_header = 'Tehtävät' keywords_header = 'Avainsanat' comments_header = 'Kommentit' library_setting = 'Kirjasto' resource_setting = 'Resurssi' variables_setting = 'Muuttujat' documentation_setting = 'Dokumentaatio' metadata_setting = 'Metatiedot' name_setting = "Nimi" suite_setup_setting = 'Setin Alustus' suite_teardown_setting = 'Setin Alasajo' test_setup_setting = 'Testin Alustus' task_setup_setting = 'Tehtävän Alustus' test_teardown_setting = 'Testin Alasajo' task_teardown_setting = 'Tehtävän Alasajo' test_template_setting = 'Testin Malli' task_template_setting = 'Tehtävän Malli' test_timeout_setting = 'Testin Aikaraja' task_timeout_setting = 'Tehtävän Aikaraja' test_tags_setting = 'Testin Tagit' task_tags_setting = 'Tehtävän Tagit' keyword_tags_setting = 'Avainsanan Tagit' tags_setting = 'Tagit' setup_setting = 'Alustus' teardown_setting = 'Alasajo' template_setting = 'Malli' timeout_setting = 'Aikaraja' arguments_setting = 'Argumentit' given_prefixes = ['Oletetaan'] when_prefixes = ['Kun'] then_prefixes = ['Niin'] and_prefixes = ['Ja'] but_prefixes = ['Mutta'] true_strings = ['Tosi', 'Kyllä', 'Päällä'] false_strings = ['Epätosi', 'Ei', 'Pois'] class Fr(Language): """French""" settings_header = 'Paramètres' variables_header = 'Variables' test_cases_header = 'Unités de test' tasks_header = 'Tâches' keywords_header = 'Mots-clés' comments_header = 'Commentaires' library_setting = 'Bibliothèque' resource_setting = 'Ressource' variables_setting = 'Variable' name_setting = 'Nom' documentation_setting = 'Documentation' metadata_setting = 'Méta-donnée' suite_setup_setting = 'Mise en place de suite' suite_teardown_setting = 'Démontage de suite' test_setup_setting = 'Mise en place de test' test_teardown_setting = 'Démontage de test' test_template_setting = 'Modèle de test' test_timeout_setting = 'Délai de test' test_tags_setting = 'Étiquette de test' task_setup_setting = 'Mise en place de tâche' task_teardown_setting = 'Démontage de test' task_template_setting = 'Modèle de tâche' task_timeout_setting = 'Délai de tâche' task_tags_setting = 'Étiquette de tâche' keyword_tags_setting = 'Etiquette de mot-clé' tags_setting = 'Étiquette' setup_setting = 'Mise en place' teardown_setting = 'Démontage' template_setting = 'Modèle' timeout_setting = "Délai d'attente" arguments_setting = 'Arguments' given_prefixes = ['Étant donné'] when_prefixes = ['Lorsque'] then_prefixes = ['Alors'] and_prefixes = ['Et'] but_prefixes = ['Mais'] true_strings = ['Vrai', 'Oui', 'Actif'] false_strings = ['Faux', 'Non', 'Désactivé', 'Aucun'] class De(Language): """German""" settings_header = 'Einstellungen' variables_header = 'Variablen' test_cases_header = 'Testfälle' tasks_header = 'Aufgaben' keywords_header = 'Schlüsselwörter' comments_header = 'Kommentare' library_setting = 'Bibliothek' resource_setting = 'Ressource' variables_setting = 'Variablen' name_setting = 'Name' documentation_setting = 'Dokumentation' metadata_setting = 'Metadaten' suite_setup_setting = 'Suitevorbereitung' suite_teardown_setting = 'Suitenachbereitung' test_setup_setting = 'Testvorbereitung' test_teardown_setting = 'Testnachbereitung' test_template_setting = 'Testvorlage' test_timeout_setting = 'Testzeitlimit' test_tags_setting = 'Testmarker' task_setup_setting = 'Aufgabenvorbereitung' task_teardown_setting = 'Aufgabennachbereitung' task_template_setting = 'Aufgabenvorlage' task_timeout_setting = 'Aufgabenzeitlimit' task_tags_setting = 'Aufgabenmarker' keyword_tags_setting = 'Schlüsselwortmarker' tags_setting = 'Marker' setup_setting = 'Vorbereitung' teardown_setting = 'Nachbereitung' template_setting = 'Vorlage' timeout_setting = 'Zeitlimit' arguments_setting = 'Argumente' given_prefixes = ['Angenommen'] when_prefixes = ['Wenn'] then_prefixes = ['Dann'] and_prefixes = ['Und'] but_prefixes = ['Aber'] true_strings = ['Wahr', 'Ja', 'An', 'Ein'] false_strings = ['Falsch', 'Nein', 'Aus', 'Unwahr'] class PtBr(Language): """Brazilian Portuguese""" settings_header = 'Configurações' variables_header = 'Variáveis' test_cases_header = 'Casos de Teste' tasks_header = 'Tarefas' keywords_header = 'Palavras-Chave' comments_header = 'Comentários' library_setting = 'Biblioteca' resource_setting = 'Recurso' variables_setting = 'Variável' name_setting = 'Nome' documentation_setting = 'Documentação' metadata_setting = 'Metadados' suite_setup_setting = 'Configuração da Suíte' suite_teardown_setting = 'Finalização de Suíte' test_setup_setting = 'Inicialização de Teste' test_teardown_setting = 'Finalização de Teste' test_template_setting = 'Modelo de Teste' test_timeout_setting = 'Tempo Limite de Teste' test_tags_setting = 'Test Tags' task_setup_setting = 'Inicialização de Tarefa' task_teardown_setting = 'Finalização de Tarefa' task_template_setting = 'Modelo de Tarefa' task_timeout_setting = 'Tempo Limite de Tarefa' task_tags_setting = 'Task Tags' keyword_tags_setting = 'Keyword Tags' tags_setting = 'Etiquetas' setup_setting = 'Inicialização' teardown_setting = 'Finalização' template_setting = 'Modelo' timeout_setting = 'Tempo Limite' arguments_setting = 'Argumentos' given_prefixes = ['Dado'] when_prefixes = ['Quando'] then_prefixes = ['Então'] and_prefixes = ['E'] but_prefixes = ['Mas'] true_strings = ['Verdadeiro', 'Verdade', 'Sim', 'Ligado'] false_strings = ['Falso', 'Não', 'Desligado', 'Desativado', 'Nada'] class Pt(Language): """Portuguese""" settings_header = 'Definições' variables_header = 'Variáveis' test_cases_header = 'Casos de Teste' tasks_header = 'Tarefas' keywords_header = 'Palavras-Chave' comments_header = 'Comentários' library_setting = 'Biblioteca' resource_setting = 'Recurso' variables_setting = 'Variável' name_setting = 'Nome' documentation_setting = 'Documentação' metadata_setting = 'Metadados' suite_setup_setting = 'Inicialização de Suíte' suite_teardown_setting = 'Finalização de Suíte' test_setup_setting = 'Inicialização de Teste' test_teardown_setting = 'Finalização de Teste' test_template_setting = 'Modelo de Teste' test_timeout_setting = 'Tempo Limite de Teste' test_tags_setting = 'Etiquetas de Testes' task_setup_setting = 'Inicialização de Tarefa' task_teardown_setting = 'Finalização de Tarefa' task_template_setting = 'Modelo de Tarefa' task_timeout_setting = 'Tempo Limite de Tarefa' task_tags_setting = 'Etiquetas de Tarefas' keyword_tags_setting = 'Etiquetas de Palavras-Chave' tags_setting = 'Etiquetas' setup_setting = 'Inicialização' teardown_setting = 'Finalização' template_setting = 'Modelo' timeout_setting = 'Tempo Limite' arguments_setting = 'Argumentos' given_prefixes = ['Dado'] when_prefixes = ['Quando'] then_prefixes = ['Então'] and_prefixes = ['E'] but_prefixes = ['Mas'] true_strings = ['Verdadeiro', 'Verdade', 'Sim', 'Ligado'] false_strings = ['Falso', 'Não', 'Desligado', 'Desativado', 'Nada'] class Th(Language): """Thai""" settings_header = 'การตั้งค่า' variables_header = 'กำหนดตัวแปร' test_cases_header = 'การทดสอบ' tasks_header = 'งาน' keywords_header = 'คำสั่งเพิ่มเติม' comments_header = 'คำอธิบาย' library_setting = 'ชุดคำสั่งที่ใช้' resource_setting = 'ไฟล์ที่ใช้' variables_setting = 'ชุดตัวแปร' documentation_setting = 'เอกสาร' metadata_setting = 'รายละเอียดเพิ่มเติม' suite_setup_setting = 'กำหนดค่าเริ่มต้นของชุดการทดสอบ' suite_teardown_setting = 'คืนค่าของชุดการทดสอบ' test_setup_setting = 'กำหนดค่าเริ่มต้นของการทดสอบ' task_setup_setting = 'กำหนดค่าเริ่มต้นของงาน' test_teardown_setting = 'คืนค่าของการทดสอบ' task_teardown_setting = 'คืนค่าของงาน' test_template_setting = 'โครงสร้างของการทดสอบ' task_template_setting = 'โครงสร้างของงาน' test_timeout_setting = 'เวลารอของการทดสอบ' task_timeout_setting = 'เวลารอของงาน' test_tags_setting = 'กลุ่มของการทดสอบ' task_tags_setting = 'กลุ่มของงาน' keyword_tags_setting = 'กลุ่มของคำสั่งเพิ่มเติม' setup_setting = 'กำหนดค่าเริ่มต้น' teardown_setting = 'คืนค่า' template_setting = 'โครงสร้าง' tags_setting = 'กลุ่ม' timeout_setting = 'หมดเวลา' arguments_setting = 'ค่าที่ส่งเข้ามา' given_prefixes = ['กำหนดให้'] when_prefixes = ['เมื่อ'] then_prefixes = ['ดังนั้น'] and_prefixes = ['และ'] but_prefixes = ['แต่'] class Pl(Language): """Polish""" settings_header = 'Ustawienia' variables_header = 'Zmienne' test_cases_header = 'Przypadki Testowe' tasks_header = 'Zadania' keywords_header = 'Słowa Kluczowe' comments_header = 'Komentarze' library_setting = 'Biblioteka' resource_setting = 'Zasób' variables_setting = 'Zmienne' name_setting = 'Nazwa' documentation_setting = 'Dokumentacja' metadata_setting = 'Metadane' suite_setup_setting = 'Inicjalizacja Zestawu' suite_teardown_setting = 'Ukończenie Zestawu' test_setup_setting = 'Inicjalizacja Testu' test_teardown_setting = 'Ukończenie Testu' test_template_setting = 'Szablon Testu' test_timeout_setting = 'Limit Czasowy Testu' test_tags_setting = 'Znaczniki Testu' task_setup_setting = 'Inicjalizacja Zadania' task_teardown_setting = 'Ukończenie Zadania' task_template_setting = 'Szablon Zadania' task_timeout_setting = 'Limit Czasowy Zadania' task_tags_setting = 'Znaczniki Zadania' keyword_tags_setting = 'Znaczniki Słowa Kluczowego' tags_setting = 'Znaczniki' setup_setting = 'Inicjalizacja' teardown_setting = 'Ukończenie' template_setting = 'Szablon' timeout_setting = 'Limit Czasowy' arguments_setting = 'Argumenty' given_prefixes = ['Zakładając', 'Zakładając, że', 'Mając'] when_prefixes = ['Jeżeli', 'Jeśli', 'Gdy', 'Kiedy'] then_prefixes = ['Wtedy'] and_prefixes = ['Oraz', 'I'] but_prefixes = ['Ale'] true_strings = ['Prawda', 'Tak', 'Włączone'] false_strings = ['Fałsz', 'Nie', 'Wyłączone', 'Nic'] class Uk(Language): """Ukrainian""" settings_header = 'Налаштування' variables_header = 'Змінні' test_cases_header = 'Тест-кейси' tasks_header = 'Завдань' keywords_header = 'Ключових слова' comments_header = 'Коментарів' library_setting = 'Бібліотека' resource_setting = 'Ресурс' variables_setting = 'Змінна' documentation_setting = 'Документація' metadata_setting = 'Метадані' suite_setup_setting = 'Налаштування Suite' suite_teardown_setting = 'Розбірка Suite' test_setup_setting = 'Налаштування тесту' test_teardown_setting = 'Розбирання тестy' test_template_setting = 'Тестовий шаблон' test_timeout_setting = 'Час тестування' test_tags_setting = 'Тестові теги' task_setup_setting = 'Налаштування завдання' task_teardown_setting = 'Розбір завдання' task_template_setting = 'Шаблон завдання' task_timeout_setting = 'Час очікування завдання' task_tags_setting = 'Теги завдань' keyword_tags_setting = 'Теги ключових слів' tags_setting = 'Теги' setup_setting = 'Встановлення' teardown_setting = 'Cпростовувати пункт за пунктом' template_setting = 'Шаблон' timeout_setting = 'Час вийшов' arguments_setting = 'Аргументи' given_prefixes = ['Дано'] when_prefixes = ['Коли'] then_prefixes = ['Тоді'] and_prefixes = ['Та'] but_prefixes = ['Але'] class Es(Language): """Spanish""" settings_header = 'Configuraciones' variables_header = 'Variables' test_cases_header = 'Casos de prueba' tasks_header = 'Tareas' keywords_header = 'Palabras clave' comments_header = 'Comentarios' library_setting = 'Biblioteca' resource_setting = 'Recursos' variables_setting = 'Variable' name_setting = 'Nombre' documentation_setting = 'Documentación' metadata_setting = 'Metadatos' suite_setup_setting = 'Configuración de la Suite' suite_teardown_setting = 'Desmontaje de la Suite' test_setup_setting = 'Configuración de prueba' test_teardown_setting = 'Desmontaje de la prueba' test_template_setting = 'Plantilla de prueba' test_timeout_setting = 'Tiempo de espera de la prueba' test_tags_setting = 'Etiquetas de la prueba' task_setup_setting = 'Configuración de tarea' task_teardown_setting = 'Desmontaje de tareas' task_template_setting = 'Plantilla de tareas' task_timeout_setting = 'Tiempo de espera de las tareas' task_tags_setting = 'Etiquetas de las tareas' keyword_tags_setting = 'Etiquetas de palabras clave' tags_setting = 'Etiquetas' setup_setting = 'Configuración' teardown_setting = 'Desmontaje' template_setting = 'Plantilla' timeout_setting = 'Tiempo agotado' arguments_setting = 'Argumentos' given_prefixes = ['Dado'] when_prefixes = ['Cuando'] then_prefixes = ['Entonces'] and_prefixes = ['Y'] but_prefixes = ['Pero'] true_strings = ['Verdadero', 'Si', 'On'] false_strings = ['Falso', 'No', 'Off', 'Ninguno'] class Ru(Language): """Russian""" settings_header = 'Настройки' variables_header = 'Переменные' test_cases_header = 'Заголовки тестов' tasks_header = 'Задача' keywords_header = 'Ключевые слова' comments_header = 'Комментарии' library_setting = 'Библиотека' resource_setting = 'Ресурс' variables_setting = 'Переменные' documentation_setting = 'Документация' metadata_setting = 'Метаданные' suite_setup_setting = 'Инициализация комплекта тестов' suite_teardown_setting = 'Завершение комплекта тестов' test_setup_setting = 'Инициализация теста' test_teardown_setting = 'Завершение теста' test_template_setting = 'Шаблон теста' test_timeout_setting = 'Лимит выполнения теста' test_tags_setting = 'Теги тестов' task_setup_setting = 'Инициализация задания' task_teardown_setting = 'Завершение задания' task_template_setting = 'Шаблон задания' task_timeout_setting = 'Лимит задания' task_tags_setting = 'Метки заданий' keyword_tags_setting = 'Метки ключевых слов' tags_setting = 'Метки' setup_setting = 'Инициализация' teardown_setting = 'Завершение' template_setting = 'Шаблон' timeout_setting = 'Лимит' arguments_setting = 'Аргументы' given_prefixes = ['Дано'] when_prefixes = ['Когда'] then_prefixes = ['Тогда'] and_prefixes = ['И'] but_prefixes = ['Но'] class ZhCn(Language): """Chinese Simplified""" settings_header = '设置' variables_header = '变量' test_cases_header = '用例' tasks_header = '任务' keywords_header = '关键字' comments_header = '备注' library_setting = '程序库' resource_setting = '资源文件' variables_setting = '变量文件' documentation_setting = '说明' metadata_setting = '元数据' suite_setup_setting = '用例集启程' suite_teardown_setting = '用例集终程' test_setup_setting = '用例启程' test_teardown_setting = '用例终程' test_template_setting = '用例模板' test_timeout_setting = '用例超时' test_tags_setting = '用例标签' task_setup_setting = '任务启程' task_teardown_setting = '任务终程' task_template_setting = '任务模板' task_timeout_setting = '任务超时' task_tags_setting = '任务标签' keyword_tags_setting = '关键字标签' tags_setting = '标签' setup_setting = '启程' teardown_setting = '终程' template_setting = '模板' timeout_setting = '超时' arguments_setting = '参数' given_prefixes = ['假定'] when_prefixes = ['当'] then_prefixes = ['那么'] and_prefixes = ['并且'] but_prefixes = ['但是'] true_strings = ['真', '是', '开'] false_strings = ['假', '否', '关', '空'] class ZhTw(Language): """Chinese Traditional""" settings_header = '設置' variables_header = '變量' test_cases_header = '案例' tasks_header = '任務' keywords_header = '關鍵字' comments_header = '備註' library_setting = '函式庫' resource_setting = '資源文件' variables_setting = '變量文件' documentation_setting = '說明' metadata_setting = '元數據' suite_setup_setting = '測試套啟程' suite_teardown_setting = '測試套終程' test_setup_setting = '測試啟程' test_teardown_setting = '測試終程' test_template_setting = '測試模板' test_timeout_setting = '測試逾時' test_tags_setting = '測試標籤' task_setup_setting = '任務啟程' task_teardown_setting = '任務終程' task_template_setting = '任務模板' task_timeout_setting = '任務逾時' task_tags_setting = '任務標籤' keyword_tags_setting = '關鍵字標籤' tags_setting = '標籤' setup_setting = '啟程' teardown_setting = '終程' template_setting = '模板' timeout_setting = '逾時' arguments_setting = '参数' given_prefixes = ['假定'] when_prefixes = ['當'] then_prefixes = ['那麼'] and_prefixes = ['並且'] but_prefixes = ['但是'] true_strings = ['真', '是', '開'] false_strings = ['假', '否', '關', '空'] class Tr(Language): """Turkish""" settings_header = 'Ayarlar' variables_header = 'Değişkenler' test_cases_header = 'Test Durumları' tasks_header = 'Görevler' keywords_header = 'Anahtar Kelimeler' comments_header = 'Yorumlar' library_setting = 'Kütüphane' resource_setting = 'Kaynak' variables_setting = 'Değişkenler' documentation_setting = 'Dokümantasyon' metadata_setting = 'Üstveri' suite_setup_setting = 'Takım Kurulumu' suite_teardown_setting = 'Takım Bitişi' test_setup_setting = 'Test Kurulumu' task_setup_setting = 'Görev Kurulumu' test_teardown_setting = 'Test Bitişi' task_teardown_setting = 'Görev Bitişi' test_template_setting = 'Test Taslağı' task_template_setting = 'Görev Taslağı' test_timeout_setting = 'Test Zaman Aşımı' task_timeout_setting = 'Görev Zaman Aşımı' test_tags_setting = 'Test Etiketleri' task_tags_setting = 'Görev Etiketleri' keyword_tags_setting = 'Anahtar Kelime Etiketleri' setup_setting = 'Kurulum' teardown_setting = 'Bitiş' template_setting = 'Taslak' tags_setting = 'Etiketler' timeout_setting = 'Zaman Aşımı' arguments_setting = 'Argümanlar' given_prefixes = ['Diyelim ki'] when_prefixes = ['Eğer ki'] then_prefixes = ['O zaman'] and_prefixes = ['Ve'] but_prefixes = ['Ancak'] true_strings = ['Doğru', 'Evet', 'Açik'] false_strings = ['Yanliş', 'Hayir', 'Kapali'] class Sv(Language): """Swedish""" settings_header = 'Inställningar' variables_header = 'Variabler' test_cases_header = 'Testfall' tasks_header = 'Taskar' keywords_header = 'Nyckelord' comments_header = 'Kommentarer' library_setting = 'Bibliotek' resource_setting = 'Resurs' variables_setting = 'Variabel' name_setting = 'Namn' documentation_setting = 'Dokumentation' metadata_setting = 'Metadata' suite_setup_setting = 'Svit konfigurering' suite_teardown_setting = 'Svit nedrivning' test_setup_setting = 'Test konfigurering' test_teardown_setting = 'Test nedrivning' test_template_setting = 'Test mall' test_timeout_setting = 'Test timeout' test_tags_setting = 'Test taggar' task_setup_setting = 'Task konfigurering' task_teardown_setting = 'Task nedrivning' task_template_setting = 'Task mall' task_timeout_setting = 'Task timeout' task_tags_setting = 'Arbetsuppgift taggar' keyword_tags_setting = 'Nyckelord taggar' tags_setting = 'Taggar' setup_setting = 'Konfigurering' teardown_setting = 'Nedrivning' template_setting = 'Mall' timeout_setting = 'Timeout' arguments_setting = 'Argument' given_prefixes = ['Givet'] when_prefixes = ['När'] then_prefixes = ['Då'] and_prefixes = ['Och'] but_prefixes = ['Men'] true_strings = ['Sant', 'Ja', 'På'] false_strings = ['Falskt', 'Nej', 'Av', 'Ingen'] class Bg(Language): """Bulgarian""" settings_header = 'Настройки' variables_header = 'Променливи' test_cases_header = 'Тестови случаи' tasks_header = 'Задачи' keywords_header = 'Ключови думи' comments_header = 'Коментари' library_setting = 'Библиотека' resource_setting = 'Ресурс' variables_setting = 'Променлива' documentation_setting = 'Документация' metadata_setting = 'Метаданни' suite_setup_setting = 'Първоначални настройки на комплекта' suite_teardown_setting = 'Приключване на комплекта' test_setup_setting = 'Първоначални настройки на тестове' test_teardown_setting = 'Приключване на тестове' test_template_setting = 'Шаблон за тестове' test_timeout_setting = 'Таймаут за тестове' test_tags_setting = 'Етикети за тестове' task_setup_setting = 'Първоначални настройки на задачи' task_teardown_setting = 'Приключване на задачи' task_template_setting = 'Шаблон за задачи' task_timeout_setting = 'Таймаут за задачи' task_tags_setting = 'Етикети за задачи' keyword_tags_setting = 'Етикети за ключови думи' tags_setting = 'Етикети' setup_setting = 'Първоначални настройки' teardown_setting = 'Приключване' template_setting = 'Шаблон' timeout_setting = 'Таймаут' arguments_setting = 'Аргументи' given_prefixes = ['В случай че'] when_prefixes = ['Когато'] then_prefixes = ['Тогава'] and_prefixes = ['И'] but_prefixes = ['Но'] true_strings = ['Вярно', 'Да', 'Включен'] false_strings = ['Невярно', 'Не', 'Изключен', 'Нищо'] class Ro(Language): """Romanian""" settings_header = 'Setari' variables_header = 'Variabile' test_cases_header = 'Cazuri De Test' tasks_header = 'Sarcini' keywords_header = 'Cuvinte Cheie' comments_header = 'Comentarii' library_setting = 'Librarie' resource_setting = 'Resursa' variables_setting = 'Variabila' name_setting = 'Nume' documentation_setting = 'Documentatie' metadata_setting = 'Metadate' suite_setup_setting = 'Configurare De Suita' suite_teardown_setting = 'Configurare De Intrerupere' test_setup_setting = 'Setare De Test' test_teardown_setting = 'Inrerupere De Test' test_template_setting = 'Sablon De Test' test_timeout_setting = 'Timp Expirare Test' test_tags_setting = 'Taguri De Test' task_setup_setting = 'Configuarare activitate' task_teardown_setting = 'Intrerupere activitate' task_template_setting = 'Sablon de activitate' task_timeout_setting = 'Timp de expirare activitate' task_tags_setting = 'Etichete activitate' keyword_tags_setting = 'Etichete metode' tags_setting = 'Etichete' setup_setting = 'Setare' teardown_setting = 'Intrerupere' template_setting = 'Sablon' timeout_setting = 'Expirare' arguments_setting = 'Argumente' given_prefixes = ['Fie ca'] when_prefixes = ['Cand'] then_prefixes = ['Atunci'] and_prefixes = ['Si'] but_prefixes = ['Dar'] true_strings = ['Adevarat', 'Da', 'Cand'] false_strings = ['Fals', 'Nu', 'Oprit', 'Niciun'] class It(Language): """Italian""" settings_header = 'Impostazioni' variables_header = 'Variabili' test_cases_header = 'Casi Di Test' tasks_header = 'Attività' keywords_header = 'Parole Chiave' comments_header = 'Commenti' library_setting = 'Libreria' resource_setting = 'Risorsa' variables_setting = 'Variabile' name_setting = 'Nome' documentation_setting = 'Documentazione' metadata_setting = 'Metadati' suite_setup_setting = 'Configurazione Suite' suite_teardown_setting = 'Distruzione Suite' test_setup_setting = 'Configurazione Test' test_teardown_setting = 'Distruzione Test' test_template_setting = 'Modello Test' test_timeout_setting = 'Timeout Test' test_tags_setting = 'Tag Del Test' task_setup_setting = 'Configurazione Attività' task_teardown_setting = 'Distruzione Attività' task_template_setting = 'Modello Attività' task_timeout_setting = 'Timeout Attività' task_tags_setting = 'Tag Attività' keyword_tags_setting = 'Tag Parola Chiave' tags_setting = 'Tag' setup_setting = 'Configurazione' teardown_setting = 'Distruzione' template_setting = 'Template' timeout_setting = 'Timeout' arguments_setting = 'Parametri' given_prefixes = ['Dato'] when_prefixes = ['Quando'] then_prefixes = ['Allora'] and_prefixes = ['E'] but_prefixes = ['Ma'] true_strings = ['Vero', 'Sì', 'On'] false_strings = ['Falso', 'No', 'Off', 'Nessuno'] class Hi(Language): """Hindi""" settings_header = 'स्थापना' variables_header = 'चर' test_cases_header = 'नियत कार्य प्रवेशिका' tasks_header = 'कार्य प्रवेशिका' keywords_header = 'कुंजीशब्द' comments_header = 'टिप्पणी' library_setting = 'कोड़ प्रतिबिंब संग्रह' resource_setting = 'संसाधन' variables_setting = 'चर' documentation_setting = 'प्रलेखन' metadata_setting = 'अधि-आंकड़ा' suite_setup_setting = 'जांच की शुरुवात' suite_teardown_setting = 'परीक्षण कार्य अंत' test_setup_setting = 'परीक्षण कार्य प्रारंभ' test_teardown_setting = 'परीक्षण कार्य अंत' test_template_setting = 'परीक्षण ढांचा' test_timeout_setting = 'परीक्षण कार्य समय समाप्त' test_tags_setting = 'जाँचका उपनाम' task_setup_setting = 'परीक्षण कार्य प्रारंभ' task_teardown_setting = 'परीक्षण कार्य अंत' task_template_setting = 'परीक्षण ढांचा' task_timeout_setting = 'कार्य समयबाह्य' task_tags_setting = 'कार्यका उपनाम' keyword_tags_setting = 'कुंजीशब्द का उपनाम' tags_setting = 'निशान' setup_setting = 'व्यवस्थापना' teardown_setting = 'विमोचन' template_setting = 'साँचा' timeout_setting = 'समय समाप्त' arguments_setting = 'प्राचल' given_prefixes = ['दिया हुआ'] when_prefixes = ['जब'] then_prefixes = ['तब'] and_prefixes = ['और'] but_prefixes = ['परंतु'] true_strings = ['यथार्थ', 'निश्चित', 'हां', 'पर'] false_strings = ['गलत', 'नहीं', 'हालाँकि', 'यद्यपि', 'नहीं', 'हैं'] class Vi(Language): """Vietnamese New in Robot Framework 6.1. """ settings_header = 'Cài Đặt' variables_header = 'Các biến số' test_cases_header = 'Các kịch bản kiểm thử' tasks_header = 'Các nghiệm vụ' keywords_header = 'Các từ khóa' comments_header = 'Các chú thích' library_setting = 'Thư viện' resource_setting = 'Tài nguyên' variables_setting = 'Biến số' name_setting = 'Tên' documentation_setting = 'Tài liệu hướng dẫn' metadata_setting = 'Dữ liệu tham chiếu' suite_setup_setting = 'Tiền thiết lập bộ kịch bản kiểm thử' suite_teardown_setting = 'Hậu thiết lập bộ kịch bản kiểm thử' test_setup_setting = 'Tiền thiết lập kịch bản kiểm thử' test_teardown_setting = 'Hậu thiết lập kịch bản kiểm thử' test_template_setting = 'Mẫu kịch bản kiểm thử' test_timeout_setting = 'Thời gian chờ kịch bản kiểm thử' test_tags_setting = 'Các nhãn kịch bản kiểm thử' task_setup_setting = 'Tiền thiểt lập nhiệm vụ' task_teardown_setting = 'Hậu thiết lập nhiệm vụ' task_template_setting = 'Mẫu nhiễm vụ' task_timeout_setting = 'Thời gian chờ nhiệm vụ' task_tags_setting = 'Các nhãn nhiệm vụ' keyword_tags_setting = 'Các từ khóa nhãn' tags_setting = 'Các thẻ' setup_setting = 'Tiền thiết lập' teardown_setting = 'Hậu thiết lập' template_setting = 'Mẫu' timeout_setting = 'Thời gian chờ' arguments_setting = 'Các đối số' given_prefixes = ['Đã cho'] when_prefixes = ['Khi'] then_prefixes = ['Thì'] and_prefixes = ['Và'] but_prefixes = ['Nhưng'] true_strings = ['Đúng', 'Vâng', 'Mở'] false_strings = ['Sai', 'Không', 'Tắt', 'Không Có Gì']
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/conf/languages.py
0.834407
0.225993
languages.py
pypi
class JsonWriter: def __init__(self, output, separator=''): self._writer = JsonDumper(output) self._separator = separator def write_json(self, prefix, data, postfix=';\n', mapping=None, separator=True): self._writer.write(prefix) self._writer.dump(data, mapping) self._writer.write(postfix) self._write_separator(separator) def write(self, string, postfix=';\n', separator=True): self._writer.write(string + postfix) self._write_separator(separator) def _write_separator(self, separator): if separator and self._separator: self._writer.write(self._separator) class JsonDumper: def __init__(self, output): self.write = output.write self._dumpers = (MappingDumper(self), IntegerDumper(self), TupleListDumper(self), StringDumper(self), NoneDumper(self), DictDumper(self)) def dump(self, data, mapping=None): for dumper in self._dumpers: if dumper.handles(data, mapping): dumper.dump(data, mapping) return raise ValueError('Dumping %s not supported.' % type(data)) class _Dumper: _handled_types = None def __init__(self, jsondumper): self._dump = jsondumper.dump self._write = jsondumper.write def handles(self, data, mapping): return isinstance(data, self._handled_types) def dump(self, data, mapping): raise NotImplementedError class StringDumper(_Dumper): _handled_types = str _search_and_replace = [('\\', '\\\\'), ('"', '\\"'), ('\t', '\\t'), ('\n', '\\n'), ('\r', '\\r'), ('</', '\\x3c/')] def dump(self, data, mapping): self._write('"%s"' % (self._escape(data) if data else '')) def _escape(self, string): for search, replace in self._search_and_replace: if search in string: string = string.replace(search, replace) return string class IntegerDumper(_Dumper): # Handles also bool _handled_types = int def dump(self, data, mapping): self._write(str(data).lower()) class DictDumper(_Dumper): _handled_types = dict def dump(self, data, mapping): write = self._write dump = self._dump write('{') last_index = len(data) - 1 for index, key in enumerate(sorted(data)): dump(key, mapping) write(':') dump(data[key], mapping) if index < last_index: write(',') write('}') class TupleListDumper(_Dumper): _handled_types = (tuple, list) def dump(self, data, mapping): write = self._write dump = self._dump write('[') last_index = len(data) - 1 for index, item in enumerate(data): dump(item, mapping) if index < last_index: write(',') write(']') class MappingDumper(_Dumper): def handles(self, data, mapping): try: return mapping and data in mapping except TypeError: return False def dump(self, data, mapping): self._write(mapping[data]) class NoneDumper(_Dumper): def handles(self, data, mapping): return data is None def dump(self, data, mapping): self._write('null')
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/htmldata/jsonwriter.py
0.656878
0.180215
jsonwriter.py
pypi
from abc import ABC, abstractmethod from typing import Any, Iterable, Iterator, overload, Sequence from robot.utils import normalize, NormalizedDict, Matcher class Tags(Sequence[str]): __slots__ = ['_tags', '_reserved'] def __init__(self, tags: Iterable[str] = ()): if isinstance(tags, Tags): self._tags, self._reserved = tags._tags, tags._reserved else: self._tags, self._reserved = self._init_tags(tags) def robot(self, name: str) -> bool: """Check do tags contain a reserved tag in format `robot:<name>`. This is same as `'robot:<name>' in tags` but considerably faster. """ return name in self._reserved def _init_tags(self, tags) -> 'tuple[tuple[str, ...], tuple[str, ...]]': if not tags: return (), () if isinstance(tags, str): tags = (tags,) return self._normalize(tags) def _normalize(self, tags): nd = NormalizedDict([(str(t), None) for t in tags], ignore='_') if '' in nd: del nd[''] if 'NONE' in nd: del nd['NONE'] reserved = tuple(tag[6:] for tag in nd.normalized_keys if tag[:6] == 'robot:') return tuple(nd), reserved def add(self, tags: Iterable[str]): self.__init__(tuple(self) + tuple(Tags(tags))) def remove(self, tags: Iterable[str]): match = TagPatterns(tags).match self.__init__([t for t in self if not match(t)]) def match(self, tags: Iterable[str]) -> bool: return TagPatterns(tags).match(self) def __contains__(self, tags: Iterable[str]) -> bool: return self.match(tags) def __len__(self) -> int: return len(self._tags) def __iter__(self) -> Iterator[str]: return iter(self._tags) def __str__(self) -> str: tags = ', '.join(self) return f'[{tags}]' def __repr__(self) -> str: return repr(list(self)) def __eq__(self, other: Any) -> bool: if not isinstance(other, Iterable): return False if not isinstance(other, Tags): other = Tags(other) self_normalized = [normalize(tag, ignore='_') for tag in self] other_normalized = [normalize(tag, ignore='_') for tag in other] return sorted(self_normalized) == sorted(other_normalized) @overload def __getitem__(self, index: int) -> str: ... @overload def __getitem__(self, index: slice) -> 'Tags': ... def __getitem__(self, index: 'int|slice') -> 'str|Tags': if isinstance(index, slice): return Tags(self._tags[index]) return self._tags[index] def __add__(self, other: Iterable[str]) -> 'Tags': return Tags(tuple(self) + tuple(Tags(other))) class TagPatterns(Sequence['TagPattern']): def __init__(self, patterns: Iterable[str]): self._patterns = tuple(TagPattern.from_string(p) for p in Tags(patterns)) def match(self, tags: Iterable[str]) -> bool: if not self._patterns: return False tags = normalize_tags(tags) return any(p.match(tags) for p in self._patterns) def __contains__(self, tag: str) -> bool: return self.match(tag) def __len__(self) -> int: return len(self._patterns) def __iter__(self) -> Iterator['TagPattern']: return iter(self._patterns) def __getitem__(self, index: int) -> 'TagPattern': return self._patterns[index] def __str__(self) -> str: patterns = ', '.join(str(pattern) for pattern in self) return f'[{patterns}]' class TagPattern(ABC): @classmethod def from_string(cls, pattern: str) -> 'TagPattern': pattern = pattern.replace(' ', '') if 'NOT' in pattern: must_match, *must_not_match = pattern.split('NOT') return NotTagPattern(must_match, must_not_match) if 'OR' in pattern: return OrTagPattern(pattern.split('OR')) if 'AND' in pattern or '&' in pattern: return AndTagPattern(pattern.replace('&', 'AND').split('AND')) return SingleTagPattern(pattern) @abstractmethod def match(self, tags: Iterable[str]) -> bool: raise NotImplementedError @abstractmethod def __iter__(self) -> Iterator['TagPattern']: raise NotImplementedError @abstractmethod def __str__(self) -> str: raise NotImplementedError class SingleTagPattern(TagPattern): def __init__(self, pattern: str): # Normalization is handled here, not in Matcher, for performance reasons. # This way we can normalize tags only once. self._matcher = Matcher(normalize(pattern, ignore='_'), caseless=False, spaceless=False) def match(self, tags: Iterable[str]) -> bool: tags = normalize_tags(tags) return self._matcher.match_any(tags) def __iter__(self) -> Iterator['TagPattern']: yield self def __str__(self) -> str: return self._matcher.pattern def __bool__(self) -> bool: return bool(self._matcher) class AndTagPattern(TagPattern): def __init__(self, patterns: Iterable[str]): self._patterns = tuple(TagPattern.from_string(p) for p in patterns) def match(self, tags: Iterable[str]) -> bool: tags = normalize_tags(tags) return all(p.match(tags) for p in self._patterns) def __iter__(self) -> Iterator['TagPattern']: return iter(self._patterns) def __str__(self) -> str: return ' AND '.join(str(pattern) for pattern in self) class OrTagPattern(TagPattern): def __init__(self, patterns: Iterable[str]): self._patterns = tuple(TagPattern.from_string(p) for p in patterns) def match(self, tags: Iterable[str]) -> bool: tags = normalize_tags(tags) return any(p.match(tags) for p in self._patterns) def __iter__(self) -> Iterator['TagPattern']: return iter(self._patterns) def __str__(self) -> str: return ' OR '.join(str(pattern) for pattern in self) class NotTagPattern(TagPattern): def __init__(self, must_match: str, must_not_match: Iterable[str]): self._first = TagPattern.from_string(must_match) self._rest = OrTagPattern(must_not_match) def match(self, tags: Iterable[str]) -> bool: tags = normalize_tags(tags) return ((self._first.match(tags) or not self._first) and not self._rest.match(tags)) def __iter__(self) -> Iterator['TagPattern']: yield self._first yield from self._rest def __str__(self) -> str: return ' NOT '.join(str(pattern) for pattern in self).lstrip() def normalize_tags(tags: Iterable[str]) -> Iterable[str]: """Performance optimization to normalize tags only once.""" if isinstance(tags, NormalizedTags): return tags if isinstance(tags, str): tags = [tags] return NormalizedTags([normalize(t, ignore='_') for t in tags]) class NormalizedTags(list): pass
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/model/tags.py
0.920068
0.291157
tags.py
pypi
from itertools import chain import re from robot.utils import NormalizedDict from .stats import CombinedTagStat, TagStat from .tags import TagPatterns class TagStatistics: """Container for tag statistics.""" def __init__(self, combined_stats): #: Dictionary, where key is the name of the tag as a string and value #: is an instance of :class:`~robot.model.stats.TagStat`. self.tags = NormalizedDict(ignore='_') #: List of :class:`~robot.model.stats.CombinedTagStat` objects. self.combined = combined_stats def visit(self, visitor): visitor.visit_tag_statistics(self) def __iter__(self): return iter(sorted(chain(self.combined, self.tags.values()))) class TagStatisticsBuilder: def __init__(self, included=None, excluded=None, combined=None, docs=None, links=None): self._included = TagPatterns(included) self._excluded = TagPatterns(excluded) self._reserved = TagPatterns('robot:*') self._info = TagStatInfo(docs, links) self.stats = TagStatistics(self._info.get_combined_stats(combined)) def add_test(self, test): self._add_tags_to_statistics(test) self._add_to_combined_statistics(test) def _add_tags_to_statistics(self, test): for tag in test.tags: if self._is_included(tag) and not self._suppress_reserved(tag): if tag not in self.stats.tags: self.stats.tags[tag] = self._info.get_stat(tag) self.stats.tags[tag].add_test(test) def _is_included(self, tag): if self._included and tag not in self._included: return False return tag not in self._excluded def _suppress_reserved(self, tag): return tag in self._reserved and tag not in self._included def _add_to_combined_statistics(self, test): for stat in self.stats.combined: if stat.match(test.tags): stat.add_test(test) class TagStatInfo: def __init__(self, docs=None, links=None): self._docs = [TagStatDoc(*doc) for doc in docs or []] self._links = [TagStatLink(*link) for link in links or []] def get_stat(self, tag): return TagStat(tag, self.get_doc(tag), self.get_links(tag)) def get_combined_stats(self, combined=None): return [self._get_combined_stat(*comb) for comb in combined or []] def _get_combined_stat(self, pattern, name=None): name = name or pattern return CombinedTagStat(pattern, name, self.get_doc(name), self.get_links(name)) def get_doc(self, tag): return ' & '.join(doc.text for doc in self._docs if doc.match(tag)) def get_links(self, tag): return [link.get_link(tag) for link in self._links if link.match(tag)] class TagStatDoc: def __init__(self, pattern, doc): self._matcher = TagPatterns(pattern) self.text = doc def match(self, tag): return self._matcher.match(tag) class TagStatLink: _match_pattern_tokenizer = re.compile(r'(\*|\?+)') def __init__(self, pattern, link, title): self._regexp = self._get_match_regexp(pattern) self._link = link self._title = title.replace('_', ' ') def match(self, tag): return self._regexp.match(tag) is not None def get_link(self, tag): match = self._regexp.match(tag) if not match: return None link, title = self._replace_groups(self._link, self._title, match) return link, title def _replace_groups(self, link, title, match): for index, group in enumerate(match.groups()): placefolder = '%%%d' % (index+1) link = link.replace(placefolder, group) title = title.replace(placefolder, group) return link, title def _get_match_regexp(self, pattern): pattern = '^%s$' % ''.join(self._yield_match_pattern(pattern)) return re.compile(pattern, re.IGNORECASE) def _yield_match_pattern(self, pattern): for token in self._match_pattern_tokenizer.split(pattern): if token.startswith('?'): yield '(%s)' % ('.'*len(token)) elif token == '*': yield '(.*)' else: yield re.escape(token)
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/model/tagstatistics.py
0.795221
0.241076
tagstatistics.py
pypi
import sys from typing import Any, cast, Sequence, TypeVar, TYPE_CHECKING if sys.version_info >= (3, 8): from typing import Literal from robot.utils import setter from .body import Body, BodyItem, BodyItemParent, BaseBranches from .keyword import Keywords from .modelobject import DataDict from .visitor import SuiteVisitor if TYPE_CHECKING: from robot.model import Keyword, Message IT = TypeVar('IT', bound='IfBranch|TryBranch') class Branches(BaseBranches['Keyword', 'For', 'While', 'If', 'Try', 'Return', 'Continue', 'Break', 'Message', 'Error', IT]): pass @Body.register class For(BodyItem): """Represents ``FOR`` loops. :attr:`flavor` specifies the flavor, and it can be ``IN``, ``IN RANGE``, ``IN ENUMERATE`` or ``IN ZIP``. """ type = BodyItem.FOR body_class = Body repr_args = ('variables', 'flavor', 'values', 'start', 'mode', 'fill') __slots__ = ['variables', 'flavor', 'values', 'start', 'mode', 'fill'] def __init__(self, variables: Sequence[str] = (), flavor: "Literal['IN', 'IN RANGE', 'IN ENUMERATE', 'IN ZIP']" = 'IN', values: Sequence[str] = (), start: 'str|None' = None, mode: 'str|None' = None, fill: 'str|None' = None, parent: BodyItemParent = None): self.variables = tuple(variables) self.flavor = flavor self.values = tuple(values) self.start = start self.mode = mode self.fill = fill self.parent = parent self.body = () @setter def body(self, body: 'Sequence[BodyItem|DataDict]') -> Body: return self.body_class(self, body) @property def keywords(self): """Deprecated since Robot Framework 4.0. Use :attr:`body` instead.""" return Keywords(self, self.body) @keywords.setter def keywords(self, keywords): Keywords.raise_deprecation_error() def visit(self, visitor: SuiteVisitor): visitor.visit_for(self) def __str__(self): parts = ['FOR', *self.variables, self.flavor, *self.values] for name, value in [('start', self.start), ('mode', self.mode), ('fill', self.fill)]: if value is not None: parts.append(f'{name}={value}') return ' '.join(parts) def _include_in_repr(self, name: str, value: Any) -> bool: return name not in ('start', 'mode', 'fill') or value is not None def to_dict(self) -> DataDict: data = {'type': self.type, 'variables': self.variables, 'flavor': self.flavor, 'values': self.values} for name, value in [('start', self.start), ('mode', self.mode), ('fill', self.fill)]: if value is not None: data[name] = value data['body'] = self.body.to_dicts() return data @Body.register class While(BodyItem): """Represents ``WHILE`` loops.""" type = BodyItem.WHILE body_class = Body repr_args = ('condition', 'limit', 'on_limit', 'on_limit_message') __slots__ = ['condition', 'limit', 'on_limit', 'on_limit_message'] def __init__(self, condition: 'str|None' = None, limit: 'str|None' = None, on_limit: 'str|None' = None, on_limit_message: 'str|None' = None, parent: BodyItemParent = None): self.condition = condition self.on_limit = on_limit self.limit = limit self.on_limit_message = on_limit_message self.parent = parent self.body = () @setter def body(self, body: 'Sequence[BodyItem|DataDict]') -> Body: return self.body_class(self, body) def visit(self, visitor: SuiteVisitor): visitor.visit_while(self) def __str__(self) -> str: parts = ['WHILE'] if self.condition is not None: parts.append(self.condition) if self.limit is not None: parts.append(f'limit={self.limit}') if self.on_limit is not None: parts.append(f'limit={self.on_limit}') if self.on_limit_message is not None: parts.append(f'on_limit_message={self.on_limit_message}') return ' '.join(parts) def _include_in_repr(self, name: str, value: Any) -> bool: return name == 'condition' or value is not None def to_dict(self) -> DataDict: data: DataDict = {'type': self.type} for name, value in [('condition', self.condition), ('limit', self.limit), ('on_limit', self.on_limit), ('on_limit_message', self.on_limit_message)]: if value is not None: data[name] = value data['body'] = self.body.to_dicts() return data class IfBranch(BodyItem): """Represents individual ``IF``, ``ELSE IF`` or ``ELSE`` branch.""" body_class = Body repr_args = ('type', 'condition') __slots__ = ['type', 'condition'] def __init__(self, type: str = BodyItem.IF, condition: 'str|None' = None, parent: BodyItemParent = None): self.type = type self.condition = condition self.parent = parent self.body = () @setter def body(self, body: 'Sequence[BodyItem|DataDict]') -> Body: return self.body_class(self, body) @property def id(self) -> str: """Branch id omits IF/ELSE root from the parent id part.""" if not self.parent: return 'k1' if not self.parent.parent: return self._get_id(self.parent) return self._get_id(self.parent.parent) def __str__(self) -> str: if self.type == self.IF: return f'IF {self.condition}' if self.type == self.ELSE_IF: return f'ELSE IF {self.condition}' return 'ELSE' def visit(self, visitor: SuiteVisitor): visitor.visit_if_branch(self) def to_dict(self) -> DataDict: data = {'type': self.type} if self.condition: data['condition'] = self.condition data['body'] = self.body.to_dicts() return data @Body.register class If(BodyItem): """IF/ELSE structure root. Branches are stored in :attr:`body`.""" type = BodyItem.IF_ELSE_ROOT branch_class = IfBranch branches_class = Branches[branch_class] __slots__ = [] def __init__(self, parent: BodyItemParent = None): self.parent = parent self.body = () @setter def body(self, branches: 'Sequence[BodyItem|DataDict]') -> branches_class: return self.branches_class(self.branch_class, self, branches) @property def id(self) -> None: """Root IF/ELSE id is always ``None``.""" return None def visit(self, visitor: SuiteVisitor): visitor.visit_if(self) def to_dict(self) -> DataDict: return {'type': self.type, 'body': self.body.to_dicts()} class TryBranch(BodyItem): """Represents individual ``TRY``, ``EXCEPT``, ``ELSE`` or ``FINALLY`` branch.""" body_class = Body repr_args = ('type', 'patterns', 'pattern_type', 'variable') __slots__ = ['type', 'patterns', 'pattern_type', 'variable'] def __init__(self, type: str = BodyItem.TRY, patterns: Sequence[str] = (), pattern_type: 'str|None' = None, variable: 'str|None' = None, parent: BodyItemParent = None): if (patterns or pattern_type or variable) and type != BodyItem.EXCEPT: raise TypeError(f"'{type}' branches do not accept patterns or variables.") self.type = type self.patterns = tuple(patterns) self.pattern_type = pattern_type self.variable = variable self.parent = parent self.body = () @setter def body(self, body: 'Sequence[BodyItem|DataDict]') -> Body: return self.body_class(self, body) @property def id(self) -> str: """Branch id omits TRY/EXCEPT root from the parent id part.""" if not self.parent: return 'k1' if not self.parent.parent: return self._get_id(self.parent) return self._get_id(self.parent.parent) def __str__(self) -> str: if self.type != BodyItem.EXCEPT: return self.type parts = ['EXCEPT', *self.patterns] if self.pattern_type: parts.append(f'type={self.pattern_type}') if self.variable: parts.extend(['AS', self.variable]) return ' '.join(parts) def _include_in_repr(self, name: str, value: Any) -> bool: return bool(value) def visit(self, visitor: SuiteVisitor): visitor.visit_try_branch(self) def to_dict(self) -> DataDict: data: DataDict = {'type': self.type} if self.type == self.EXCEPT: data['patterns'] = self.patterns if self.pattern_type: data['pattern_type'] = self.pattern_type if self.variable: data['variable'] = self.variable data['body'] = self.body.to_dicts() return data @Body.register class Try(BodyItem): """TRY/EXCEPT structure root. Branches are stored in :attr:`body`.""" type = BodyItem.TRY_EXCEPT_ROOT branch_class = TryBranch branches_class = Branches[branch_class] __slots__ = [] def __init__(self, parent: BodyItemParent = None): self.parent = parent self.body = () @setter def body(self, branches: 'Sequence[TryBranch|DataDict]') -> branches_class: return self.branches_class(self.branch_class, self, branches) @property def try_branch(self) -> TryBranch: if self.body and self.body[0].type == BodyItem.TRY: return cast(TryBranch, self.body[0]) raise TypeError("No 'TRY' branch or 'TRY' branch is not first.") @property def except_branches(self) -> 'list[TryBranch]': return [cast(TryBranch, branch) for branch in self.body if branch.type == BodyItem.EXCEPT] @property def else_branch(self) -> 'TryBranch|None': for branch in self.body: if branch.type == BodyItem.ELSE: return cast(TryBranch, branch) return None @property def finally_branch(self): if self.body and self.body[-1].type == BodyItem.FINALLY: return cast(TryBranch, self.body[-1]) return None @property def id(self) -> None: """Root TRY/EXCEPT id is always ``None``.""" return None def visit(self, visitor: SuiteVisitor): visitor.visit_try(self) def to_dict(self) -> DataDict: return {'type': self.type, 'body': self.body.to_dicts()} @Body.register class Return(BodyItem): """Represents ``RETURN``.""" type = BodyItem.RETURN repr_args = ('values',) __slots__ = ['values'] def __init__(self, values: Sequence[str] = (), parent: BodyItemParent = None): self.values = tuple(values) self.parent = parent def visit(self, visitor: SuiteVisitor): visitor.visit_return(self) def to_dict(self) -> DataDict: return {'type': self.type, 'values': self.values} @Body.register class Continue(BodyItem): """Represents ``CONTINUE``.""" type = BodyItem.CONTINUE __slots__ = [] def __init__(self, parent: BodyItemParent = None): self.parent = parent def visit(self, visitor: SuiteVisitor): visitor.visit_continue(self) def to_dict(self) -> DataDict: return {'type': self.type} @Body.register class Break(BodyItem): """Represents ``BREAK``.""" type = BodyItem.BREAK __slots__ = [] def __init__(self, parent: BodyItemParent = None): self.parent = parent def visit(self, visitor: SuiteVisitor): visitor.visit_break(self) def to_dict(self) -> DataDict: return {'type': self.type} @Body.register class Error(BodyItem): """Represents syntax error in data. For example, an invalid setting like ``[Setpu]`` or ``END`` in wrong place. """ type = BodyItem.ERROR repr_args = ('values',) __slots__ = ['values'] def __init__(self, values: Sequence[str] = (), parent: BodyItemParent = None): self.values = tuple(values) self.parent = parent def visit(self, visitor: SuiteVisitor): visitor.visit_error(self) def to_dict(self) -> DataDict: return {'type': self.type, 'values': self.values}
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/model/control.py
0.715722
0.186354
control.py
pypi
from robot.utils import (Sortable, elapsed_time_to_string, html_escape, is_string, normalize) from .tags import TagPattern class Stat(Sortable): """Generic statistic object used for storing all the statistic values.""" def __init__(self, name): #: Human readable identifier of the object these statistics #: belong to. `All Tests` for #: :class:`~robot.model.totalstatistics.TotalStatistics`, #: long name of the suite for #: :class:`~robot.model.suitestatistics.SuiteStatistics` #: or name of the tag for #: :class:`~robot.model.tagstatistics.TagStatistics` self.name = name #: Number of passed tests. self.passed = 0 #: Number of failed tests. self.failed = 0 #: Number of skipped tests. self.skipped = 0 #: Number of milliseconds it took to execute. self.elapsed = 0 self._norm_name = normalize(name, ignore='_') def get_attributes(self, include_label=False, include_elapsed=False, exclude_empty=True, values_as_strings=False, html_escape=False): attrs = {'pass': self.passed, 'fail': self.failed, 'skip': self.skipped} attrs.update(self._get_custom_attrs()) if include_label: attrs['label'] = self.name if include_elapsed: attrs['elapsed'] = elapsed_time_to_string(self.elapsed, include_millis=False) if exclude_empty: attrs = dict((k, v) for k, v in attrs.items() if v not in ('', None)) if values_as_strings: attrs = dict((k, str(v) if v is not None else '') for k, v in attrs.items()) if html_escape: attrs = dict((k, self._html_escape(v)) for k, v in attrs.items()) return attrs def _get_custom_attrs(self): return {} def _html_escape(self, item): return html_escape(item) if is_string(item) else item @property def total(self): return self.passed + self.failed + self.skipped def add_test(self, test): self._update_stats(test) self._update_elapsed(test) def _update_stats(self, test): if test.passed: self.passed += 1 elif test.skipped: self.skipped += 1 else: self.failed += 1 def _update_elapsed(self, test): self.elapsed += test.elapsedtime @property def _sort_key(self): return self._norm_name def __bool__(self): return not self.failed def visit(self, visitor): visitor.visit_stat(self) class TotalStat(Stat): """Stores statistic values for a test run.""" type = 'total' class SuiteStat(Stat): """Stores statistics values for a single suite.""" type = 'suite' def __init__(self, suite): Stat.__init__(self, suite.longname) #: Identifier of the suite, e.g. `s1-s2`. self.id = suite.id #: Number of milliseconds it took to execute this suite, #: including sub-suites. self.elapsed = suite.elapsedtime self._name = suite.name def _get_custom_attrs(self): return {'id': self.id, 'name': self._name} def _update_elapsed(self, test): pass def add_stat(self, other): self.passed += other.passed self.failed += other.failed self.skipped += other.skipped class TagStat(Stat): """Stores statistic values for a single tag.""" type = 'tag' def __init__(self, name, doc='', links=None, combined=None): Stat.__init__(self, name) #: Documentation of tag as a string. self.doc = doc #: List of tuples in which the first value is the link URL and #: the second is the link title. An empty list by default. self.links = links or [] #: Pattern as a string if the tag is combined, ``None`` otherwise. self.combined = combined @property def info(self): """Returns additional information of the tag statistics are about. Either `combined` or an empty string. """ if self.combined: return 'combined' return '' def _get_custom_attrs(self): return {'doc': self.doc, 'links': self._get_links_as_string(), 'info': self.info, 'combined': self.combined} def _get_links_as_string(self): return ':::'.join('%s:%s' % (title, url) for url, title in self.links) @property def _sort_key(self): return (not self.combined, self._norm_name) class CombinedTagStat(TagStat): def __init__(self, pattern, name=None, doc='', links=None): TagStat.__init__(self, name or pattern, doc, links, combined=pattern) self.pattern = TagPattern.from_string(pattern) def match(self, tags): return self.pattern.match(tags)
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/model/stats.py
0.924598
0.29883
stats.py
pypi
from robot.utils import seq2str from robot.errors import DataError from .visitor import SuiteVisitor class SuiteConfigurer(SuiteVisitor): def __init__(self, name=None, doc=None, metadata=None, set_tags=None, include_tags=None, exclude_tags=None, include_suites=None, include_tests=None, empty_suite_ok=False): self.name = name self.doc = doc self.metadata = metadata self.set_tags = set_tags or [] self.include_tags = include_tags self.exclude_tags = exclude_tags self.include_suites = include_suites self.include_tests = include_tests self.empty_suite_ok = empty_suite_ok @property def add_tags(self): return [t for t in self.set_tags if not t.startswith('-')] @property def remove_tags(self): return [t[1:] for t in self.set_tags if t.startswith('-')] def visit_suite(self, suite): self._set_suite_attributes(suite) self._filter(suite) suite.set_tags(self.add_tags, self.remove_tags) def _set_suite_attributes(self, suite): if self.name: suite.name = self.name if self.doc: suite.doc = self.doc if self.metadata: suite.metadata.update(self.metadata) def _filter(self, suite): name = suite.name suite.filter(self.include_suites, self.include_tests, self.include_tags, self.exclude_tags) if not (suite.has_tests or self.empty_suite_ok): self._raise_no_tests_or_tasks_error(name, suite.rpa) def _raise_no_tests_or_tasks_error(self, name, rpa): parts = [{False: 'tests', True: 'tasks', None: 'tests or tasks'}[rpa], self._get_test_selector_msgs(), self._get_suite_selector_msg()] raise DataError("Suite '%s' contains no %s." % (name, ' '.join(p for p in parts if p))) def _get_test_selector_msgs(self): parts = [] for explanation, selector in [('matching tags', self.include_tags), ('not matching tags', self.exclude_tags), ('matching name', self.include_tests)]: if selector: parts.append(self._format_selector_msg(explanation, selector)) return seq2str(parts, quote='') def _format_selector_msg(self, explanation, selector): if len(selector) == 1 and explanation[-1] == 's': explanation = explanation[:-1] return '%s %s' % (explanation, seq2str(selector, lastsep=' or ')) def _get_suite_selector_msg(self): if not self.include_suites: return '' return self._format_selector_msg('in suites', self.include_suites)
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/model/configurer.py
0.712632
0.183191
configurer.py
pypi
from typing import Sequence, TYPE_CHECKING from robot.utils import setter from .tags import TagPatterns from .namepatterns import SuiteNamePatterns, TestNamePatterns from .visitor import SuiteVisitor if TYPE_CHECKING: from .keyword import Keyword from .testcase import TestCase from .testsuite import TestSuite class EmptySuiteRemover(SuiteVisitor): def __init__(self, preserve_direct_children: bool = False): self.preserve_direct_children = preserve_direct_children def end_suite(self, suite: 'TestSuite'): if suite.parent or not self.preserve_direct_children: suite.suites = [s for s in suite.suites if s.test_count] def visit_test(self, test: 'TestCase'): pass def visit_keyword(self, keyword: 'Keyword'): pass class Filter(EmptySuiteRemover): def __init__(self, include_suites: 'SuiteNamePatterns|Sequence[str]|None' = None, include_tests: 'TestNamePatterns|Sequence[str]|None' = None, include_tags: 'TagPatterns|Sequence[str]|None' = None, exclude_tags: 'TagPatterns|Sequence[str]|None' = None): super().__init__() self.include_suites = include_suites self.include_tests = include_tests self.include_tags = include_tags self.exclude_tags = exclude_tags @setter def include_suites(self, suites) -> 'SuiteNamePatterns|None': return self._patterns_or_none(suites, SuiteNamePatterns) @setter def include_tests(self, tests) -> 'TestNamePatterns|None': return self._patterns_or_none(tests, TestNamePatterns) @setter def include_tags(self, tags) -> 'TagPatterns|None': return self._patterns_or_none(tags, TagPatterns) @setter def exclude_tags(self, tags) -> 'TagPatterns|None': return self._patterns_or_none(tags, TagPatterns) def _patterns_or_none(self, items, pattern_class): if items is None or isinstance(items, pattern_class): return items return pattern_class(items) def start_suite(self, suite: 'TestSuite'): if not self: return False if hasattr(suite, 'starttime'): suite.starttime = suite.endtime = None if self.include_suites is not None: if self.include_suites.match(suite.name, suite.longname): suite.visit(Filter(include_tests=self.include_tests, include_tags=self.include_tags, exclude_tags=self.exclude_tags)) return False suite.tests = [] return True if self.include_tests is not None: suite.tests = [t for t in suite.tests if self.include_tests.match(t.name, t.longname)] if self.include_tags is not None: suite.tests = [t for t in suite.tests if self.include_tags.match(t.tags)] if self.exclude_tags is not None: suite.tests = [t for t in suite.tests if not self.exclude_tags.match(t.tags)] return bool(suite.suites) def __bool__(self) -> bool: return bool(self.include_suites is not None or self.include_tests is not None or self.include_tags is not None or self.exclude_tags is not None)
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/model/filter.py
0.817356
0.203332
filter.py
pypi
from functools import total_ordering from typing import (Any, Iterable, Iterator, MutableSequence, overload, TYPE_CHECKING, Type, TypeVar) from robot.utils import copy_signature, KnownAtRuntime, type_name from .modelobject import DataDict if TYPE_CHECKING: from .visitor import SuiteVisitor T = TypeVar('T') Self = TypeVar('Self', bound='ItemList') @total_ordering class ItemList(MutableSequence[T]): """List of items of a certain enforced type. New items can be created using the :meth:`create` method and existing items added using the common list methods like :meth:`append` or :meth:`insert`. In addition to the common type, items can have certain common and automatically assigned attributes. Starting from Robot Framework 6.1, items can be added as dictionaries and actual items are generated based on them automatically. If the type has a ``from_dict`` class method, it is used, and otherwise dictionary data is passed to the type as keyword arguments. """ __slots__ = ['_item_class', '_common_attrs', '_items'] # TypeVar T needs to be applied to a variable to be compatible with @copy_signature item_type: Type[T] = KnownAtRuntime def __init__(self, item_class: Type[T], common_attrs: 'dict[str, Any]|None' = None, items: 'Iterable[T|DataDict]' = ()): self._item_class = item_class self._common_attrs = common_attrs self._items: 'list[T]' = [] if items: self.extend(items) @copy_signature(item_type) def create(self, *args, **kwargs) -> T: """Create a new item using the provided arguments.""" return self.append(self._item_class(*args, **kwargs)) def append(self, item: 'T|DataDict') -> T: item = self._check_type_and_set_attrs(item) self._items.append(item) return item def _check_type_and_set_attrs(self, item: 'T|DataDict') -> T: if not isinstance(item, self._item_class): if isinstance(item, dict): item = self._item_from_dict(item) else: raise TypeError(f'Only {type_name(self._item_class)} objects ' f'accepted, got {type_name(item)}.') if self._common_attrs: for attr, value in self._common_attrs.items(): setattr(item, attr, value) return item def _item_from_dict(self, data: DataDict) -> T: if hasattr(self._item_class, 'from_dict'): return self._item_class.from_dict(data) # type: ignore return self._item_class(**data) def extend(self, items: 'Iterable[T|DataDict]'): self._items.extend(self._check_type_and_set_attrs(i) for i in items) def insert(self, index: int, item: 'T|DataDict'): item = self._check_type_and_set_attrs(item) self._items.insert(index, item) def index(self, item: T, *start_and_end) -> int: return self._items.index(item, *start_and_end) def clear(self): self._items = [] def visit(self, visitor: 'SuiteVisitor'): for item in self: item.visit(visitor) # type: ignore def __iter__(self) -> Iterator[T]: index = 0 while index < len(self._items): yield self._items[index] index += 1 @overload def __getitem__(self, index: int) -> T: ... @overload def __getitem__(self: Self, index: slice) -> Self: ... def __getitem__(self, index): if isinstance(index, slice): return self._create_new_from(self._items[index]) return self._items[index] def _create_new_from(self: Self, items: Iterable[T]) -> Self: # Cannot pass common_attrs directly to new object because all # subclasses don't have compatible __init__. new = type(self)(self._item_class) new._common_attrs = self._common_attrs new.extend(items) return new @overload def __setitem__(self, index: int, item: 'T|DataDict'): ... @overload def __setitem__(self, index: slice, item: 'Iterable[T|DataDict]'): ... def __setitem__(self, index, item): if isinstance(index, slice): self._items[index] = [self._check_type_and_set_attrs(i) for i in item] else: self._items[index] = self._check_type_and_set_attrs(item) def __delitem__(self, index: 'int|slice'): del self._items[index] def __contains__(self, item: object) -> bool: return item in self._items def __len__(self) -> int: return len(self._items) def __str__(self) -> str: return str(list(self)) def __repr__(self) -> str: class_name = type(self).__name__ item_name = self._item_class.__name__ return f'{class_name}(item_class={item_name}, items={self._items})' def count(self, item: T) -> int: return self._items.count(item) def sort(self, **config): self._items.sort(**config) def reverse(self): self._items.reverse() def __reversed__(self) -> Iterator[T]: index = 0 while index < len(self._items): yield self._items[len(self._items) - index - 1] index += 1 def __eq__(self, other: object) -> bool: return (isinstance(other, ItemList) and self._is_compatible(other) and self._items == other._items) def _is_compatible(self, other) -> bool: return (self._item_class is other._item_class and self._common_attrs == other._common_attrs) def __lt__(self, other: 'ItemList[T]') -> bool: if not isinstance(other, ItemList): raise TypeError(f'Cannot order ItemList and {type_name(other)}.') if not self._is_compatible(other): raise TypeError('Cannot order incompatible ItemLists.') return self._items < other._items def __add__(self: Self, other: 'ItemList[T]') -> Self: if not isinstance(other, ItemList): raise TypeError(f'Cannot add ItemList and {type_name(other)}.') if not self._is_compatible(other): raise TypeError('Cannot add incompatible ItemLists.') return self._create_new_from(self._items + other._items) def __iadd__(self: Self, other: Iterable[T]) -> Self: if isinstance(other, ItemList) and not self._is_compatible(other): raise TypeError('Cannot add incompatible ItemLists.') self.extend(other) return self def __mul__(self: Self, count: int) -> Self: return self._create_new_from(self._items * count) def __imul__(self: Self, count: int) -> Self: self._items *= count return self def __rmul__(self: Self, count: int) -> Self: return self * count def to_dicts(self) -> 'list[DataDict]': """Return list of items converted to dictionaries. Items are converted to dictionaries using the ``to_dict`` method, if they have it, or the built-in ``vars()``. New in Robot Framework 6.1. """ if not hasattr(self._item_class, 'to_dict'): return [vars(item) for item in self] return [item.to_dict() for item in self] # type: ignore
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/model/itemlist.py
0.900653
0.273926
itemlist.py
pypi
from typing import TYPE_CHECKING if TYPE_CHECKING: from robot.model import (Break, BodyItem, Continue, Error, For, If, IfBranch, Keyword, Message, Return, TestCase, TestSuite, Try, TryBranch, While) from robot.result import ForIteration, WhileIteration class SuiteVisitor: """Abstract class to ease traversing through the suite structure. See the :mod:`module level <robot.model.visitor>` documentation for more information and an example. """ def visit_suite(self, suite: 'TestSuite'): """Implements traversing through suites. Can be overridden to allow modifying the passed in ``suite`` without calling :meth:`start_suite` or :meth:`end_suite` nor visiting child suites, tests or setup and teardown at all. """ if self.start_suite(suite) is not False: if suite.has_setup: suite.setup.visit(self) suite.suites.visit(self) suite.tests.visit(self) if suite.has_teardown: suite.teardown.visit(self) self.end_suite(suite) def start_suite(self, suite: 'TestSuite') -> 'bool|None': """Called when a suite starts. Default implementation does nothing. Can return explicit ``False`` to stop visiting. """ pass def end_suite(self, suite: 'TestSuite'): """Called when a suite ends. Default implementation does nothing.""" pass def visit_test(self, test: 'TestCase'): """Implements traversing through tests. Can be overridden to allow modifying the passed in ``test`` without calling :meth:`start_test` or :meth:`end_test` nor visiting the body of the test. """ if self.start_test(test) is not False: if test.has_setup: test.setup.visit(self) test.body.visit(self) if test.has_teardown: test.teardown.visit(self) self.end_test(test) def start_test(self, test: 'TestCase') -> 'bool|None': """Called when a test starts. Default implementation does nothing. Can return explicit ``False`` to stop visiting. """ pass def end_test(self, test: 'TestCase'): """Called when a test ends. Default implementation does nothing.""" pass def visit_keyword(self, keyword: 'Keyword'): """Implements traversing through keywords. Can be overridden to allow modifying the passed in ``kw`` without calling :meth:`start_keyword` or :meth:`end_keyword` nor visiting the body of the keyword """ if self.start_keyword(keyword) is not False: self._possible_body(keyword) self._possible_teardown(keyword) self.end_keyword(keyword) def _possible_body(self, item: 'BodyItem'): if hasattr(item, 'body'): item.body.visit(self) # type: ignore def _possible_teardown(self, item: 'BodyItem'): if getattr(item, 'has_teardown', False): item.teardown.visit(self) # type: ignore def start_keyword(self, keyword: 'Keyword') -> 'bool|None': """Called when a keyword starts. By default, calls :meth:`start_body_item` which, by default, does nothing. Can return explicit ``False`` to stop visiting. """ return self.start_body_item(keyword) def end_keyword(self, keyword: 'Keyword'): """Called when a keyword ends. By default, calls :meth:`end_body_item` which, by default, does nothing. """ self.end_body_item(keyword) def visit_for(self, for_: 'For'): """Implements traversing through FOR loops. Can be overridden to allow modifying the passed in ``for_`` without calling :meth:`start_for` or :meth:`end_for` nor visiting body. """ if self.start_for(for_) is not False: for_.body.visit(self) self.end_for(for_) def start_for(self, for_: 'For') -> 'bool|None': """Called when a FOR loop starts. By default, calls :meth:`start_body_item` which, by default, does nothing. Can return explicit ``False`` to stop visiting. """ return self.start_body_item(for_) def end_for(self, for_: 'For'): """Called when a FOR loop ends. By default, calls :meth:`end_body_item` which, by default, does nothing. """ self.end_body_item(for_) def visit_for_iteration(self, iteration: 'ForIteration'): """Implements traversing through single FOR loop iteration. This is only used with the result side model because on the running side there are no iterations. Can be overridden to allow modifying the passed in ``iteration`` without calling :meth:`start_for_iteration` or :meth:`end_for_iteration` nor visiting body. """ if self.start_for_iteration(iteration) is not False: iteration.body.visit(self) self.end_for_iteration(iteration) def start_for_iteration(self, iteration: 'ForIteration') -> 'bool|None': """Called when a FOR loop iteration starts. By default, calls :meth:`start_body_item` which, by default, does nothing. Can return explicit ``False`` to stop visiting. """ return self.start_body_item(iteration) def end_for_iteration(self, iteration: 'ForIteration'): """Called when a FOR loop iteration ends. By default, calls :meth:`end_body_item` which, by default, does nothing. """ self.end_body_item(iteration) def visit_if(self, if_: 'If'): """Implements traversing through IF/ELSE structures. Notice that ``if_`` does not have any data directly. Actual IF/ELSE branches are in its ``body`` and they are visited separately using :meth:`visit_if_branch`. Can be overridden to allow modifying the passed in ``if_`` without calling :meth:`start_if` or :meth:`end_if` nor visiting branches. """ if self.start_if(if_) is not False: if_.body.visit(self) self.end_if(if_) def start_if(self, if_: 'If') -> 'bool|None': """Called when an IF/ELSE structure starts. By default, calls :meth:`start_body_item` which, by default, does nothing. Can return explicit ``False`` to stop visiting. """ return self.start_body_item(if_) def end_if(self, if_: 'If'): """Called when an IF/ELSE structure ends. By default, calls :meth:`end_body_item` which, by default, does nothing. """ self.end_body_item(if_) def visit_if_branch(self, branch: 'IfBranch'): """Implements traversing through single IF/ELSE branch. Can be overridden to allow modifying the passed in ``branch`` without calling :meth:`start_if_branch` or :meth:`end_if_branch` nor visiting body. """ if self.start_if_branch(branch) is not False: branch.body.visit(self) self.end_if_branch(branch) def start_if_branch(self, branch: 'IfBranch') -> 'bool|None': """Called when an IF/ELSE branch starts. By default, calls :meth:`start_body_item` which, by default, does nothing. Can return explicit ``False`` to stop visiting. """ return self.start_body_item(branch) def end_if_branch(self, branch: 'IfBranch'): """Called when an IF/ELSE branch ends. By default, calls :meth:`end_body_item` which, by default, does nothing. """ self.end_body_item(branch) def visit_try(self, try_: 'Try'): """Implements traversing through TRY/EXCEPT structures. This method is used with the TRY/EXCEPT root element. Actual TRY, EXCEPT, ELSE and FINALLY branches are visited separately using :meth:`visit_try_branch`. """ if self.start_try(try_) is not False: try_.body.visit(self) self.end_try(try_) def start_try(self, try_: 'Try') -> 'bool|None': """Called when a TRY/EXCEPT structure starts. By default, calls :meth:`start_body_item` which, by default, does nothing. Can return explicit ``False`` to stop visiting. """ return self.start_body_item(try_) def end_try(self, try_: 'Try'): """Called when a TRY/EXCEPT structure ends. By default, calls :meth:`end_body_item` which, by default, does nothing. """ self.end_body_item(try_) def visit_try_branch(self, branch: 'TryBranch'): """Visits individual TRY, EXCEPT, ELSE and FINALLY branches.""" if self.start_try_branch(branch) is not False: branch.body.visit(self) self.end_try_branch(branch) def start_try_branch(self, branch: 'TryBranch') -> 'bool|None': """Called when TRY, EXCEPT, ELSE or FINALLY branches start. By default, calls :meth:`start_body_item` which, by default, does nothing. Can return explicit ``False`` to stop visiting. """ return self.start_body_item(branch) def end_try_branch(self, branch: 'TryBranch'): """Called when TRY, EXCEPT, ELSE and FINALLY branches end. By default, calls :meth:`end_body_item` which, by default, does nothing. """ self.end_body_item(branch) def visit_while(self, while_: 'While'): """Implements traversing through WHILE loops. Can be overridden to allow modifying the passed in ``while_`` without calling :meth:`start_while` or :meth:`end_while` nor visiting body. """ if self.start_while(while_) is not False: while_.body.visit(self) self.end_while(while_) def start_while(self, while_: 'While') -> 'bool|None': """Called when a WHILE loop starts. By default, calls :meth:`start_body_item` which, by default, does nothing. Can return explicit ``False`` to stop visiting. """ return self.start_body_item(while_) def end_while(self, while_: 'While'): """Called when a WHILE loop ends. By default, calls :meth:`end_body_item` which, by default, does nothing. """ self.end_body_item(while_) def visit_while_iteration(self, iteration: 'WhileIteration'): """Implements traversing through single WHILE loop iteration. This is only used with the result side model because on the running side there are no iterations. Can be overridden to allow modifying the passed in ``iteration`` without calling :meth:`start_while_iteration` or :meth:`end_while_iteration` nor visiting body. """ if self.start_while_iteration(iteration) is not False: iteration.body.visit(self) self.end_while_iteration(iteration) def start_while_iteration(self, iteration: 'WhileIteration') -> 'bool|None': """Called when a WHILE loop iteration starts. By default, calls :meth:`start_body_item` which, by default, does nothing. Can return explicit ``False`` to stop visiting. """ return self.start_body_item(iteration) def end_while_iteration(self, iteration: 'WhileIteration'): """Called when a WHILE loop iteration ends. By default, calls :meth:`end_body_item` which, by default, does nothing. """ self.end_body_item(iteration) def visit_return(self, return_: 'Return'): """Visits a RETURN elements.""" if self.start_return(return_) is not False: self._possible_body(return_) self.end_return(return_) def start_return(self, return_: 'Return') -> 'bool|None': """Called when a RETURN element starts. By default, calls :meth:`start_body_item` which, by default, does nothing. Can return explicit ``False`` to stop visiting. """ return self.start_body_item(return_) def end_return(self, return_: 'Return'): """Called when a RETURN element ends. By default, calls :meth:`end_body_item` which, by default, does nothing. """ self.end_body_item(return_) def visit_continue(self, continue_: 'Continue'): """Visits CONTINUE elements.""" if self.start_continue(continue_) is not False: self._possible_body(continue_) self.end_continue(continue_) def start_continue(self, continue_: 'Continue') -> 'bool|None': """Called when a CONTINUE element starts. By default, calls :meth:`start_body_item` which, by default, does nothing. Can return explicit ``False`` to stop visiting. """ return self.start_body_item(continue_) def end_continue(self, continue_: 'Continue'): """Called when a CONTINUE element ends. By default, calls :meth:`end_body_item` which, by default, does nothing. """ self.end_body_item(continue_) def visit_break(self, break_: 'Break'): """Visits BREAK elements.""" if self.start_break(break_) is not False: self._possible_body(break_) self.end_break(break_) def start_break(self, break_: 'Break') -> 'bool|None': """Called when a BREAK element starts. By default, calls :meth:`start_body_item` which, by default, does nothing. Can return explicit ``False`` to stop visiting. """ return self.start_body_item(break_) def end_break(self, break_: 'Break'): """Called when a BREAK element ends. By default, calls :meth:`end_body_item` which, by default, does nothing. """ self.end_body_item(break_) def visit_error(self, error: 'Error'): """Visits body items resulting from invalid syntax. Examples include syntax like ``END`` or ``ELSE`` in wrong place and invalid setting like ``[Invalid]``. """ if self.start_error(error) is not False: self._possible_body(error) self.end_error(error) def start_error(self, error: 'Error') -> 'bool|None': """Called when a ERROR element starts. By default, calls :meth:`start_body_item` which, by default, does nothing. Can return explicit ``False`` to stop visiting. """ return self.start_body_item(error) def end_error(self, error: 'Error'): """Called when a ERROR element ends. By default, calls :meth:`end_body_item` which, by default, does nothing. """ self.end_body_item(error) def visit_message(self, message: 'Message'): """Implements visiting messages. Can be overridden to allow modifying the passed in ``msg`` without calling :meth:`start_message` or :meth:`end_message`. """ if self.start_message(message) is not False: self.end_message(message) def start_message(self, message: 'Message') -> 'bool|None': """Called when a message starts. By default, calls :meth:`start_body_item` which, by default, does nothing. Can return explicit ``False`` to stop visiting. """ return self.start_body_item(message) def end_message(self, message: 'Message'): """Called when a message ends. By default, calls :meth:`end_body_item` which, by default, does nothing. """ self.end_body_item(message) def start_body_item(self, item: 'BodyItem') -> 'bool|None': """Called, by default, when keywords, messages or control structures start. More specific :meth:`start_keyword`, :meth:`start_message`, `:meth:`start_for`, etc. can be implemented to visit only keywords, messages or specific control structures. Can return explicit ``False`` to stop visiting. Default implementation does nothing. """ pass def end_body_item(self, item: 'BodyItem'): """Called, by default, when keywords, messages or control structures end. More specific :meth:`end_keyword`, :meth:`end_message`, `:meth:`end_for`, etc. can be implemented to visit only keywords, messages or specific control structures. Default implementation does nothing. """ pass
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/model/visitor.py
0.927314
0.402686
visitor.py
pypi
from collections.abc import Iterator from robot.utils import test_or_task from .stats import TotalStat from .visitor import SuiteVisitor class TotalStatistics: """Container for total statistics.""" def __init__(self, rpa: bool = False): #: Instance of :class:`~robot.model.stats.TotalStat` for all the tests. self._stat = TotalStat(test_or_task('All {Test}s', rpa)) self._rpa = rpa def visit(self, visitor): visitor.visit_total_statistics(self._stat) def __iter__(self) -> 'Iterator[TotalStat]': yield self._stat @property def total(self) -> int: return self._stat.total @property def passed(self) -> int: return self._stat.passed @property def skipped(self) -> int: return self._stat.skipped @property def failed(self) -> int: return self._stat.failed def add_test(self, test): self._stat.add_test(test) @property def message(self) -> str: """String representation of the statistics. For example:: 2 tests, 1 passed, 1 failed """ # TODO: should this message be highlighted in console test_or_task = 'test' if not self._rpa else 'task' total, end, passed, failed, skipped = self._get_counts() template = '%d %s%s, %d passed, %d failed' if skipped: return ((template + ', %d skipped') % (total, test_or_task, end, passed, failed, skipped)) return template % (total, test_or_task, end, passed, failed) def _get_counts(self): ending = 's' if self.total != 1 else '' return self.total, ending, self.passed, self.failed, self.skipped class TotalStatisticsBuilder(SuiteVisitor): def __init__(self, suite=None, rpa=False): self.stats = TotalStatistics(rpa) if suite: suite.visit(self) def add_test(self, test): self.stats.add_test(test) def visit_test(self, test): self.add_test(test) def visit_keyword(self, kw): pass
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/model/totalstatistics.py
0.806815
0.393269
totalstatistics.py
pypi
from typing import cast, Sequence, Type, TYPE_CHECKING import warnings from .body import Body, BodyItem, BodyItemParent from .itemlist import ItemList from .modelobject import DataDict if TYPE_CHECKING: from .visitor import SuiteVisitor @Body.register class Keyword(BodyItem): """Base model for a single keyword. Extended by :class:`robot.running.model.Keyword` and :class:`robot.result.model.Keyword`. """ repr_args = ('name', 'args', 'assign') __slots__ = ['_name', 'args', 'assign', 'type'] def __init__(self, name: 'str|None' = '', args: Sequence[str] = (), assign: Sequence[str] = (), type: str = BodyItem.KEYWORD, parent: BodyItemParent = None): self.name = name self.args = tuple(args) self.assign = tuple(assign) self.type = type self.parent = parent @property def name(self) -> 'str|None': return self._name @name.setter def name(self, name: 'str|None'): self._name = name @property def id(self) -> 'str|None': if not self: return None return super().id def visit(self, visitor: 'SuiteVisitor'): """:mod:`Visitor interface <robot.model.visitor>` entry-point.""" if self: visitor.visit_keyword(self) def __bool__(self) -> bool: return self.name is not None def __str__(self) -> str: parts = list(self.assign) + [self.name] + list(self.args) return ' '.join(str(p) for p in parts) def to_dict(self) -> DataDict: data: DataDict = {'name': self.name} if self.args: data['args'] = self.args if self.assign: data['assign'] = self.assign return data # FIXME: Remote in RF 7. class Keywords(ItemList[BodyItem]): """A list-like object representing keywords in a suite, a test or a keyword. Read-only and deprecated since Robot Framework 4.0. """ __slots__ = [] deprecation_message = ( "'keywords' attribute is read-only and deprecated since Robot Framework 4.0. " "Use 'body', 'setup' or 'teardown' instead." ) def __init__(self, parent: BodyItemParent = None, keywords: Sequence[BodyItem] = ()): warnings.warn(self.deprecation_message, UserWarning) ItemList.__init__(self, object, {'parent': parent}) if keywords: ItemList.extend(self, keywords) @property def setup(self) -> 'Keyword|None': if self and self[0].type == 'SETUP': return cast(Keyword, self[0]) return None @setup.setter def setup(self, kw): self.raise_deprecation_error() def create_setup(self, *args, **kwargs): self.raise_deprecation_error() @property def teardown(self) -> 'Keyword|None': if self and self[-1].type == 'TEARDOWN': return cast(Keyword, self[-1]) return None @teardown.setter def teardown(self, kw: Keyword): self.raise_deprecation_error() def create_teardown(self, *args, **kwargs): self.raise_deprecation_error() @property def all(self) -> 'Keywords': """Iterates over all keywords, including setup and teardown.""" return self @property def normal(self) -> 'list[BodyItem]': """Iterates over normal keywords, omitting setup and teardown.""" return [kw for kw in self if kw.type not in ('SETUP', 'TEARDOWN')] def __setitem__(self, index: int, item: Keyword): self.raise_deprecation_error() def create(self, *args, **kwargs): self.raise_deprecation_error() def append(self, item: Keyword): self.raise_deprecation_error() def extend(self, items: Sequence[Keyword]): self.raise_deprecation_error() def insert(self, index: int, item: Keyword): self.raise_deprecation_error() def pop(self, *index: int): self.raise_deprecation_error() def remove(self, item: Keyword): self.raise_deprecation_error() def clear(self): self.raise_deprecation_error() def __delitem__(self, index: int): self.raise_deprecation_error() def sort(self): self.raise_deprecation_error() def reverse(self): self.raise_deprecation_error() @classmethod def raise_deprecation_error(cls: 'Type[Keywords]'): raise AttributeError(cls.deprecation_message)
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/model/keyword.py
0.885841
0.190178
keyword.py
pypi
import copy import json from pathlib import Path from typing import Any, Dict, overload, TextIO, Type, TypeVar from robot.errors import DataError from robot.utils import get_error_message, SetterAwareType, type_name T = TypeVar('T', bound='ModelObject') DataDict = Dict[str, Any] class ModelObject(metaclass=SetterAwareType): repr_args = () __slots__ = [] @classmethod def from_dict(cls: Type[T], data: DataDict) -> T: """Create this object based on data in a dictionary. Data can be got from the :meth:`to_dict` method or created externally. """ try: return cls().config(**data) except (AttributeError, TypeError) as err: raise DataError(f"Creating '{full_name(cls)}' object from dictionary " f"failed: {err}") @classmethod def from_json(cls: Type[T], source: 'str|bytes|TextIO|Path') -> T: """Create this object based on JSON data. The data is given as the ``source`` parameter. It can be: - a string (or bytes) containing the data directly, - an open file object where to read the data, or - a path (``pathlib.Path`` or string) to a UTF-8 encoded file to read. The JSON data is first converted to a Python dictionary and the object created using the :meth:`from_dict` method. Notice that the ``source`` is considered to be JSON data if it is a string and contains ``{``. If you need to use ``{`` in a file system path, pass it in as a ``pathlib.Path`` instance. """ try: data = JsonLoader().load(source) except (TypeError, ValueError) as err: raise DataError(f'Loading JSON data failed: {err}') return cls.from_dict(data) def to_dict(self) -> DataDict: """Serialize this object into a dictionary. The object can be later restored by using the :meth:`from_dict` method. """ raise NotImplementedError @overload def to_json(self, file: None = None, *, ensure_ascii: bool = False, indent: int = 0, separators: 'tuple[str, str]' = (',', ':')) -> str: ... @overload def to_json(self, file: 'TextIO|Path|str', *, ensure_ascii: bool = False, indent: int = 0, separators: 'tuple[str, str]' = (',', ':')) -> None: ... def to_json(self, file: 'None|TextIO|Path|str' = None, *, ensure_ascii: bool = False, indent: int = 0, separators: 'tuple[str, str]' = (',', ':')) -> 'None|str': """Serialize this object into JSON. The object is first converted to a Python dictionary using the :meth:`to_dict` method and then the dictionary is converted to JSON. The ``file`` parameter controls what to do with the resulting JSON data. It can be: - ``None`` (default) to return the data as a string, - an open file object where to write the data, or - a path (``pathlib.Path`` or string) to a file where to write the data using UTF-8 encoding. JSON formatting can be configured using optional parameters that are passed directly to the underlying json__ module. Notice that the defaults differ from what ``json`` uses. __ https://docs.python.org/3/library/json.html """ return JsonDumper(ensure_ascii=ensure_ascii, indent=indent, separators=separators).dump(self.to_dict(), file) def config(self: T, **attributes) -> T: """Configure model object with given attributes. ``obj.config(name='Example', doc='Something')`` is equivalent to setting ``obj.name = 'Example'`` and ``obj.doc = 'Something'``. New in Robot Framework 4.0. """ for name, value in attributes.items(): try: orig = getattr(self, name) except AttributeError: raise AttributeError(f"'{full_name(self)}' object does not have " f"attribute '{name}'") # Preserve tuples. Main motivation is converting lists with `from_json`. if isinstance(orig, tuple) and not isinstance(value, tuple): try: value = tuple(value) except TypeError: raise TypeError(f"'{full_name(self)}' object attribute '{name}' " f"is 'tuple', got '{type_name(value)}'.") try: setattr(self, name, value) except AttributeError as err: # Ignore error setting attribute if the object already has it. # Avoids problems with `from_dict` with body items having # un-settable `type` attribute that is needed in dict data. if value != orig: raise AttributeError(f"Setting attribute '{name}' failed: {err}") return self def copy(self: T, **attributes) -> T: """Return a shallow copy of this object. :param attributes: Attributes to be set to the returned copy. For example, ``obj.copy(name='New name')``. See also :meth:`deepcopy`. The difference between ``copy`` and ``deepcopy`` is the same as with the methods having same names in the copy__ module. __ https://docs.python.org/3/library/copy.html """ return copy.copy(self).config(**attributes) def deepcopy(self: T, **attributes) -> T: """Return a deep copy of this object. :param attributes: Attributes to be set to the returned copy. For example, ``obj.deepcopy(name='New name')``. See also :meth:`copy`. The difference between ``deepcopy`` and ``copy`` is the same as with the methods having same names in the copy__ module. __ https://docs.python.org/3/library/copy.html """ return copy.deepcopy(self).config(**attributes) def __repr__(self) -> str: arguments = [(name, getattr(self, name)) for name in self.repr_args] args_repr = ', '.join(f'{name}={value!r}' for name, value in arguments if self._include_in_repr(name, value)) return f"{full_name(self)}({args_repr})" def _include_in_repr(self, name: str, value: Any) -> bool: return True def full_name(obj_or_cls): cls = type(obj_or_cls) if not isinstance(obj_or_cls, type) else obj_or_cls parts = cls.__module__.split('.') + [cls.__name__] if len(parts) > 1 and parts[0] == 'robot': parts[2:-1] = [] return '.'.join(parts) class JsonLoader: def load(self, source: 'str|bytes|TextIO|Path') -> DataDict: try: data = self._load(source) except (json.JSONDecodeError, TypeError): raise ValueError(f'Invalid JSON data: {get_error_message()}') if not isinstance(data, dict): raise TypeError(f"Expected dictionary, got {type_name(data)}.") return data def _load(self, source): if self._is_path(source): with open(source, encoding='UTF-8') as file: return json.load(file) if hasattr(source, 'read'): return json.load(source) return json.loads(source) def _is_path(self, source): if isinstance(source, Path): return True if not isinstance(source, str) or '{' in source: return False try: return Path(source).is_file() except OSError: # Can happen on Windows w/ Python < 3.10. return False class JsonDumper: def __init__(self, **config): self.config = config @overload def dump(self, data: DataDict, output: None = None) -> str: ... @overload def dump(self, data: DataDict, output: 'TextIO|Path|str') -> None: ... def dump(self, data: DataDict, output: 'None|TextIO|Path|str' = None) -> 'None|str': if not output: return json.dumps(data, **self.config) elif isinstance(output, (str, Path)): with open(output, 'w', encoding='UTF-8') as file: json.dump(data, file, **self.config) elif hasattr(output, 'write'): json.dump(data, output, **self.config) else: raise TypeError(f"Output should be None, path or open file, " f"got {type_name(output)}.")
/robotframework-6.1.1.zip/robotframework-6.1.1/src/robot/model/modelobject.py
0.841305
0.539105
modelobject.py
pypi
import re from pygments.lexer import Lexer from pygments.token import Token __version__ = '1.1' HEADING = Token.Generic.Heading SETTING = Token.Keyword.Namespace IMPORT = Token.Name.Namespace TC_KW_NAME = Token.Generic.Subheading KEYWORD = Token.Name.Function ARGUMENT = Token.String VARIABLE = Token.Name.Variable COMMENT = Token.Comment SEPARATOR = Token.Punctuation SYNTAX = Token.Punctuation GHERKIN = Token.Generic.Emph ERROR = Token.Error def normalize(string, remove='', strip=True): string = string.lower() for char in remove: if char in string: string = string.replace(char, '') return string if not strip else string.strip() class RobotFrameworkLexer(Lexer): """ For `Robot Framework <http://robotframework.org>`_ test data. Supports both space and pipe separated plain text formats. """ name = 'RobotFramework' aliases = ['RobotFramework', 'robotframework'] filenames = ['*.robot'] mimetypes = ['text/x-robotframework'] def __init__(self, **options): options['tabsize'] = 2 options['encoding'] = 'UTF-8' Lexer.__init__(self, **options) def get_tokens_unprocessed(self, text): row_tokenizer = RowTokenizer() var_tokenizer = VariableTokenizer() index = 0 for row in text.splitlines(): for value, token in row_tokenizer.tokenize(row): for value, token in var_tokenizer.tokenize(value, token): if value: if isinstance(value, bytes): value = value.decode('UTF-8') yield index, token, value index += len(value) class VariableTokenizer(object): def tokenize(self, string, token): var = VariableSplitter(string, identifiers='$@%&') if var.start < 0 or token in (COMMENT, ERROR): yield string, token return for value, token in self._tokenize(var, string, token): if value: yield value, token def _tokenize(self, var, string, orig_token): before = string[:var.start] yield before, orig_token yield var.identifier + '{', SYNTAX for value, token in self.tokenize(var.base, VARIABLE): yield value, token yield '}', SYNTAX for item in var.items: yield '[', SYNTAX for value, token in self.tokenize(item, VARIABLE): yield value, token yield ']', SYNTAX for value, token in self.tokenize(string[var.end:], orig_token): yield value, token class RowTokenizer(object): def __init__(self): testcases = TestCaseTable() settings = SettingTable(testcases.set_default_template) variables = VariableTable() keywords = KeywordTable() comments = CommentTable() self._table = comments self._tables = {'settings': settings, 'setting': settings, 'variables': variables, 'variable': variables, 'test cases': testcases, 'test case': testcases, 'tasks': testcases, 'task': testcases, 'keywords': keywords, 'keyword': keywords, 'comments': comments, 'comment': comments} self._splitter = RowSplitter() def tokenize(self, row): commented = False heading = False for index, value in enumerate(self._splitter.split(row)): # First value, and every second after that, is a separator. index, separator = divmod(index-1, 2) if value.startswith('#'): commented = True elif index == 0 and value.startswith('*'): self._table = self._start_table(value) heading = True for value, token in self._tokenize(value, index, commented, separator, heading): yield value, token self._table.end_row() def _start_table(self, header): name = normalize(header, remove='*') return self._tables.get(name, UnknownTable()) def _tokenize(self, value, index, commented, separator, heading): if commented: yield value, COMMENT elif separator: yield value, SEPARATOR elif heading: token = HEADING if self._in_valid_table() else ERROR yield value, token else: for value, token in self._table.tokenize(value, index): yield value, token def _in_valid_table(self): return not isinstance(self._table, UnknownTable) class RowSplitter(object): _space_splitter = re.compile('( {2,})') _pipe_splitter = re.compile('((?:^| +)\|(?: +|$))') def split(self, row): splitter = self._split_from_spaces \ if not row.startswith('| ') else self._split_from_pipes for value in splitter(row): yield value yield '\n' def _split_from_spaces(self, row): yield '' # Start with (pseudo)separator similarly as with pipes for value in self._space_splitter.split(row): yield value def _split_from_pipes(self, row): _, separator, rest = self._pipe_splitter.split(row, 1) yield separator while self._pipe_splitter.search(rest): cell, separator, rest = self._pipe_splitter.split(rest, 1) yield cell yield separator yield rest class Tokenizer(object): _tokens = None def __init__(self): self._index = 0 def tokenize(self, value): values_and_tokens = self._tokenize(value, self._index) self._index += 1 if isinstance(values_and_tokens, type(Token)): values_and_tokens = [(value, values_and_tokens)] return values_and_tokens def _tokenize(self, value, index): index = min(index, len(self._tokens) - 1) return self._tokens[index] def _is_assign(self, value): if value.endswith('='): value = value[:-1].strip() var = VariableSplitter(value, identifiers='$@&') return var.start == 0 and var.end == len(value) class Comment(Tokenizer): _tokens = (COMMENT,) class Setting(Tokenizer): _tokens = (SETTING, ARGUMENT) _keyword_settings = ('suite setup', 'suite teardown', 'test setup', 'test teardown', 'test template', 'task setup', 'task teardown', 'task template') _import_settings = ('library', 'resource', 'variables') _other_settings = ('documentation', 'metadata', 'force tags', 'default tags', 'test timeout', 'task timeout') _custom_tokenizer = None def __init__(self, template_setter=None): Tokenizer.__init__(self) self._template_setter = template_setter def _tokenize(self, value, index): if index == 1 and self._template_setter: self._template_setter(value) if index == 0: normalized = normalize(value) if normalized in self._keyword_settings: self._custom_tokenizer = KeywordCall(support_assign=False) elif normalized in self._import_settings: self._custom_tokenizer = ImportSetting() elif normalized not in self._other_settings: return ERROR elif self._custom_tokenizer: return self._custom_tokenizer.tokenize(value) return Tokenizer._tokenize(self, value, index) class ImportSetting(Tokenizer): _tokens = (IMPORT, ARGUMENT) class TestCaseSetting(Setting): _keyword_settings = ('setup', 'teardown', 'template') _import_settings = () _other_settings = ('documentation', 'tags', 'timeout') def _tokenize(self, value, index): if index == 0: token = Setting._tokenize(self, value[1:-1], index) return [('[', SYNTAX), (value[1:-1], token), (']', SYNTAX)] return Setting._tokenize(self, value, index) class KeywordSetting(TestCaseSetting): _keyword_settings = ('teardown',) _other_settings = ('documentation', 'arguments', 'return', 'timeout', 'tags') class Variable(Tokenizer): _tokens = (SYNTAX, ARGUMENT) def _tokenize(self, value, index): if index == 0 and not self._is_assign(value): return ERROR return Tokenizer._tokenize(self, value, index) class KeywordCall(Tokenizer): _tokens = (KEYWORD, ARGUMENT) def __init__(self, support_assign=True): Tokenizer.__init__(self) self._keyword_found = not support_assign self._assigns = 0 def _tokenize(self, value, index): if not self._keyword_found and self._is_assign(value): self._assigns += 1 return SYNTAX # VariableTokenizer tokenizes this later. if self._keyword_found: return Tokenizer._tokenize(self, value, index - self._assigns) self._keyword_found = True return GherkinTokenizer().tokenize(value, KEYWORD) class GherkinTokenizer(object): _gherkin_prefix = re.compile('^(Given|When|Then|And) ', re.IGNORECASE) def tokenize(self, value, token): match = self._gherkin_prefix.match(value) if not match: return [(value, token)] end = match.end() return [(value[:end], GHERKIN), (value[end:], token)] class TemplatedKeywordCall(Tokenizer): _tokens = (ARGUMENT,) class ForLoop(Tokenizer): def __init__(self): Tokenizer.__init__(self) self._started = False self._in_arguments = False def _tokenize(self, value, index): if not self._started: self._started = True return SYNTAX if self._in_arguments: return ARGUMENT # Possible variables tokenized later if self._is_separator(value): self._in_arguments = True return SYNTAX if self._is_variale(value): return SYNTAX # Tokenized later return ERROR def _is_separator(self, value): return value in ('IN', 'IN RANGE', 'IN ENUMERATE', 'IN ZIP') def _is_variale(self, value): return value[:2] == '${' or value[-1:] == '}' class _Table(object): _tokenizer_class = None def __init__(self, prev_tokenizer=None): self._tokenizer = self._tokenizer_class() self._prev_tokenizer = prev_tokenizer self._prev_values_on_row = [] def tokenize(self, value, index): if self._continues(value, index): self._tokenizer = self._prev_tokenizer yield value, SYNTAX else: for value_and_token in self._tokenize(value, index): yield value_and_token self._prev_values_on_row.append(value) def _continues(self, value, index): return value == '...' and all(self._is_empty(t) for t in self._prev_values_on_row) def _is_empty(self, value): return value in ('', '\\') def _tokenize(self, value, index): return self._tokenizer.tokenize(value) def end_row(self): self.__init__(prev_tokenizer=self._tokenizer) class CommentTable(_Table): _tokenizer_class = Comment def _continues(self, value, index): return False class UnknownTable(CommentTable): pass class VariableTable(_Table): _tokenizer_class = Variable class SettingTable(_Table): _tokenizer_class = Setting def __init__(self, template_setter, prev_tokenizer=None): _Table.__init__(self, prev_tokenizer) self._template_setter = template_setter def _tokenize(self, value, index): if index == 0 and normalize(value) == 'test template': self._tokenizer = Setting(self._template_setter) return _Table._tokenize(self, value, index) def end_row(self): self.__init__(self._template_setter, prev_tokenizer=self._tokenizer) class TestCaseTable(_Table): _setting_class = TestCaseSetting _test_template = None _default_template = None @property def _tokenizer_class(self): if self._test_template or (self._default_template and self._test_template is not False): return TemplatedKeywordCall return KeywordCall def _continues(self, value, index): return index > 0 and _Table._continues(self, value, index) def _tokenize(self, value, index): if index == 0: if value: self._test_template = None return GherkinTokenizer().tokenize(value, TC_KW_NAME) if index == 1 and self._is_setting(value): if self._is_template(value): self._test_template = False self._tokenizer = self._setting_class(self.set_test_template) else: self._tokenizer = self._setting_class() if index == 1 and self._is_for_loop(value): self._tokenizer = ForLoop() if index == 1 and (value == 'END' or self._is_empty(value)): return [(value, SYNTAX)] return _Table._tokenize(self, value, index) def _is_setting(self, value): return value.startswith('[') and value.endswith(']') def _is_template(self, value): return normalize(value[1:-1]) == 'template' def _is_for_loop(self, value): return (value == 'FOR' or value.startswith(':') and normalize(value, remove=': ') == 'for') def set_test_template(self, template): self._test_template = self._is_template_set(template) def set_default_template(self, template): self._default_template = self._is_template_set(template) def _is_template_set(self, template): return normalize(template) not in ('', '\\', 'none', '${empty}') class KeywordTable(TestCaseTable): _tokenizer_class = KeywordCall _setting_class = KeywordSetting def _is_template(self, value): return False # Following code copied from Robot Framework 3.1.1. class VariableSplitter(object): def __init__(self, string, identifiers='$@%&*'): self.identifier = None self.base = None self.items = [] self.start = -1 self.end = -1 self._identifiers = identifiers self._may_have_internal_variables = False self._max_end = len(string) if self._split(string): self._finalize() def get_replaced_variable(self, replacer): if self._may_have_internal_variables: base = replacer.replace_string(self.base) else: base = self.base # This omits possible variable items. return '%s{%s}' % (self.identifier, base) def is_variable(self): return bool(self.identifier and self.base and self.start == 0 and self.end == self._max_end) def is_list_variable(self): return bool(self.identifier == '@' and self.base and self.start == 0 and self.end == self._max_end and not self.items) def is_dict_variable(self): return bool(self.identifier == '&' and self.base and self.start == 0 and self.end == self._max_end and not self.items) def _finalize(self): self.identifier = self._variable_chars[0] self.base = ''.join(self._variable_chars[2:-1]) self.end = self.start + len(self._variable_chars) if self.items: self.end += len(''.join(self.items)) + 2 * len(self.items) def _split(self, string): start_index, max_index = self._find_variable(string) if start_index == -1: return False self.start = start_index self._open_curly = 1 self._state = self._variable_state self._variable_chars = [string[start_index], '{'] self._item_chars = [] self._string = string start_index += 2 for index, char in enumerate(string[start_index:], start=start_index): try: self._state(char, index) except StopIteration: break if index == max_index and not self._scanning_item(): break return True def _scanning_item(self): return self._state in (self._waiting_item_state, self._item_state) def _find_variable(self, string): max_end_index = string.rfind('}') if max_end_index == -1: return -1, -1 if self._is_escaped(string, max_end_index): return self._find_variable(string[:max_end_index]) start_index = self._find_start_index(string, 1, max_end_index) if start_index == -1: return -1, -1 return start_index, max_end_index def _find_start_index(self, string, start, end): while True: index = string.find('{', start, end) - 1 if index < 0: return -1 if self._start_index_is_ok(string, index): return index start = index + 2 def _start_index_is_ok(self, string, index): return (string[index] in self._identifiers and not self._is_escaped(string, index)) def _is_escaped(self, string, index): escaped = False while index > 0 and string[index-1] == '\\': index -= 1 escaped = not escaped return escaped def _variable_state(self, char, index): self._variable_chars.append(char) if char == '}' and not self._is_escaped(self._string, index): self._open_curly -= 1 if self._open_curly == 0: if not self._can_have_item(): raise StopIteration self._state = self._waiting_item_state elif char in self._identifiers: self._state = self._internal_variable_start_state def _can_have_item(self): return self._variable_chars[0] in '$@&' def _internal_variable_start_state(self, char, index): self._state = self._variable_state if char == '{': self._variable_chars.append(char) self._open_curly += 1 self._may_have_internal_variables = True else: self._variable_state(char, index) def _waiting_item_state(self, char, index): if char != '[': raise StopIteration self._state = self._item_state def _item_state(self, char, index): if char != ']': self._item_chars.append(char) return self.items.append(''.join(self._item_chars)) self._item_chars = [] # Don't support nested item access with olf @ and & syntax. # In RF 3.2 old syntax is to be deprecated and in RF 3.3 it # will be reassigned to mean using variable in list/dict context. if self._variable_chars[0] in '@&': raise StopIteration self._state = self._waiting_item_state
/robotframeworklexer-1.1-py3-none-any.whl/robotframeworklexer.py
0.608012
0.166675
robotframeworklexer.py
pypi
import json import time from functools import partial from typing import Callable from robothub import StreamHandle __all__ = [ 'get_default_color_callback', 'get_default_nn_callback', 'get_default_depth_callback', ] def get_default_color_callback(stream_handle: StreamHandle) -> Callable: """ Returns a default callback for color streams. :param stream_handle: StreamHandle instance to publish the data to. """ return partial(_default_encoded_callback, stream_handle) def get_default_nn_callback(stream_handle: StreamHandle) -> Callable: """ Returns a default callback for NN streams. :param stream_handle: StreamHandle instance to publish the data to. """ return partial(_default_nn_callback, stream_handle) def get_default_depth_callback(stream_handle: StreamHandle) -> Callable: """ Returns a default callback for depth streams. :param stream_handle: StreamHandle instance to publish the data to. """ return partial(_default_encoded_callback, stream_handle) def _default_encoded_callback(stream_handle: StreamHandle, packet): """ Default callback for encoded streams. :param stream_handle: StreamHandle instance to publish the data to. :param packet: Packet instance containing the data. """ timestamp = int(time.time() * 1_000) frame_bytes = bytes(packet.imgFrame.getData()) stream_handle.publish_video_data(frame_bytes, timestamp, None) def _default_nn_callback(stream_handle: StreamHandle, packet): """ Default callback for NN streams. :param stream_handle: StreamHandle instance to publish the data to. :param packet: Packet instance containing the data. """ visualizer = packet.visualizer metadata = None if visualizer: metadata = json.loads(visualizer.serialize()) visualizer.reset() # temp fix to replace None value that causes errors on frontend if not metadata['config']['detection']['color']: metadata['config']['detection']['color'] = [255, 0, 0] timestamp = int(time.time() * 1_000) frame_bytes = bytes(packet.imgFrame.getData()) stream_handle.publish_video_data(frame_bytes, timestamp, metadata)
/robothub_depthai-0.2.2-py3-none-any.whl/robothub_depthai/callbacks.py
0.888384
0.217441
callbacks.py
pypi
import time from typing import List, Optional, Union, Dict, Tuple import depthai as dai import numpy as np import robothub_core from depthai_sdk import OakCamera from depthai_sdk.components import Component, CameraComponent, StereoComponent, NNComponent from depthai_sdk.oak_outputs.xout.xout_base import StreamXout from depthai_sdk.oak_outputs.xout.xout_h26x import XoutH26x from depthai_sdk.visualize.objects import VisText, VisLine from robothub_oak.types import BoundingBox __all__ = ['LiveView', 'LIVE_VIEWS'] def _create_stream_handle(camera_serial: str, unique_key: str, name: str): if unique_key not in robothub_core.STREAMS.streams: color_stream_handle = robothub_core.STREAMS.create_video(camera_serial, unique_key, name) else: color_stream_handle = robothub_core.STREAMS.streams[unique_key] return color_stream_handle def _publish_data(stream_handle: robothub_core.StreamHandle, h264_frame, rectangles: List[BoundingBox], rectangle_labels: List[str], texts: List[VisText], lines: List[VisLine], frame_width: int, frame_height: int): timestamp = int(time.perf_counter_ns() / 1e6) metadata = { "platform": "robothub", "frame_shape": [frame_height, frame_width], "config": { "output": { "img_scale": 1.0, "show_fps": False, "clickable": True }, "detection": { "thickness": 1, "fill_transparency": 0.05, "box_roundness": 0, "color": [0, 255, 0], "bbox_style": 0, "line_width": 0.5, "line_height": 0.5, "hide_label": False, "label_position": 0, "label_padding": 10 }, 'text': { 'font_color': [255, 255, 0], 'font_transparency': 0.5, 'font_scale': 1.0, 'font_thickness': 2, 'bg_transparency': 0.5, 'bg_color': [0, 0, 0] } }, "objects": [ { "type": "detections", "detections": [] } ] } # Bounding boxes for roi, label in zip(rectangles, rectangle_labels): xmin, ymin, xmax, ymax = roi metadata['objects'][0]['detections'].append( {'bbox': [xmin, ymin, xmax, ymax], 'label': label, 'color': [0, 255, 255]} ) # Texts for text in texts: metadata["objects"].append(text.prepare().serialize()) # Lines for line in lines: metadata["objects"].append(line.prepare().serialize()) # Publish stream_handle.publish_video_data(bytes(h264_frame), timestamp, metadata) class LiveView: def __init__(self, name: str, unique_key: str, device_mxid: str, frame_width: int, frame_height: int): """ :param name: Name of the Live View. :param unique_key: Live View identifier. :param device_mxid: MXID of the device that is streaming the Live View. :param frame_width: Frame width. :param frame_height: Frame height. """ self.frame_width = frame_width self.frame_height = frame_height self.device_mxid = device_mxid self.unique_key = unique_key self.name = name self.stream_handle = _create_stream_handle(camera_serial=device_mxid, unique_key=unique_key, name=name) # Objects self.texts: List[VisText] = [] self.rectangles: List[BoundingBox] = [] self.labels: List[str] = [] self.lines: List[VisLine] = [] @staticmethod def create(device: OakCamera, component: Union[CameraComponent, StereoComponent], name: str, unique_key: str = None, manual_publish: bool = False ) -> 'LiveView': """ Creates a Live View for a given component. :param device: OakCamera instance. :param component: Component to create a Live View for. Either a CameraComponent, StereoComponent or NNComponent. :param name: Name of the Live View. :param unique_key: Live View identifier. :param manual_publish: If True, the Live View will not be automatically published. Use LiveView.publish() to publish the Live View. """ output = None is_h264 = LiveView.is_encoder_enabled(component) if not is_h264: output = LiveView.h264_output(device, component) elif not is_h264 and not isinstance(component, CameraComponent): raise ValueError(f'Component {component.__class__.__name__} must have h264 encoding ' f'enabled to be used with LiveView.') w, h = LiveView.get_stream_size(component) device_mxid = device.device.getMxId() unique_key = unique_key or f'{device_mxid}_{component.__class__.__name__.lower()}_encoded' live_view = LiveView(name=name, unique_key=unique_key, device_mxid=device_mxid, frame_width=w, frame_height=h) if not manual_publish: device.callback(output or component.out.encoded, live_view.h264_callback) LIVE_VIEWS[unique_key] = live_view return live_view @staticmethod def h264_output(device: OakCamera, component: CameraComponent): fps = 30 if isinstance(component, StereoComponent): fps = component._fps elif isinstance(component, CameraComponent): fps = component.get_fps() encoder = device.pipeline.createVideoEncoder() encoder_profile = dai.VideoEncoderProperties.Profile.H264_MAIN encoder.setDefaultProfilePreset(fps, encoder_profile) encoder.input.setQueueSize(1) encoder.input.setBlocking(False) encoder.setKeyframeFrequency(int(fps)) encoder.setBitrate(1500 * 1000) encoder.setRateControlMode(dai.VideoEncoderProperties.RateControlMode.CBR) encoder.setNumFramesPool(3) component.node.video.link(encoder.input) def encoded(pipeline, device): xout = XoutH26x( frames=StreamXout(encoder.id, encoder.bitstream), color=True, profile=encoder_profile, fps=encoder.getFrameRate(), frame_shape=component.node.getResolution() ) xout.name = component._source return component._create_xout(pipeline, xout) return encoded @staticmethod def is_encoder_enabled(component: Component) -> bool: """ Checks if the component has h264 encoding enabled. :param component: Component to check. :return: True if the component has h264 encoding enabled, False otherwise. :raises ValueError: If the component is not a CameraComponent or StereoComponent. """ if not isinstance(component, CameraComponent) and not isinstance(component, StereoComponent): raise ValueError(f'Component {component.__class__.__name__} must be a CameraComponent or StereoComponent.') encoder = component.encoder if encoder and encoder.getProfile() != dai.VideoEncoderProperties.Profile.H264_MAIN: return False return True @staticmethod def get_stream_size(component) -> Tuple[int, int]: if isinstance(component, CameraComponent): return component.stream_size elif isinstance(component, StereoComponent): return component.left.stream_size elif isinstance(component, NNComponent): return component._input.stream_size @staticmethod def get(unique_key: str = None, name: str = None): if name is not None: return LiveView.get_by_name(name) elif unique_key is not None: return LiveView.get_by_unique_key(unique_key) else: raise ValueError('Either name or unique_key must be specified.') @staticmethod def get_by_name(name: str) -> Optional['LiveView']: for live_view in LIVE_VIEWS.values(): if live_view.name == name: return live_view return None @staticmethod def get_by_unique_key(unique_key: str) -> Optional['LiveView']: if unique_key not in LIVE_VIEWS: raise ValueError(f'Live View with unique_key {unique_key} does not exist.') return LIVE_VIEWS[unique_key] def add_rectangle(self, rectangle: BoundingBox, label: str) -> None: self.rectangles.append(rectangle) self.labels.append(label) def add_text(self, text: str, coords: Tuple[int, int], size: int = None, color: Tuple[int, int, int] = None, thickness: int = None, outline: bool = True, background_color: Tuple[int, int, int] = None, background_transparency: float = 0.5) -> None: obj = VisText(text, coords, size, color, thickness, outline, background_color, background_transparency) self.texts.append(obj) def add_line(self, pt1: Tuple[int, int], pt2: Tuple[int, int], color: Tuple[int, int, int] = None, thickness: int = None ) -> None: obj = VisLine(pt1, pt2, color, thickness) self.lines.append(obj) def publish(self, h264_frame: Union[np.array, List]) -> None: _publish_data(stream_handle=self.stream_handle, h264_frame=h264_frame, rectangles=self.rectangles, rectangle_labels=self.labels, texts=self.texts, lines=self.lines, frame_width=self.frame_width, frame_height=self.frame_height) self._reset_overlays() def h264_callback(self, h264_packet): self.publish(h264_frame=h264_packet.frame) def _reset_overlays(self): self.rectangles.clear() self.labels.clear() self.lines.clear() self.texts.clear() LIVE_VIEWS: Dict[str, LiveView] = dict()
/robothub_oak-2.1.0-py3-none-any.whl/robothub_oak/live_view.py
0.873363
0.264672
live_view.py
pypi
import logging import zipfile from io import BytesIO from typing import Union, Optional, List import cv2 import numpy as np import robothub_core __all__ = ['send_image_event', 'send_frame_event_with_zipped_images'] logger = logging.getLogger(__name__) def _log_event_status(result: bool, event_id): if result: logger.info(f"Event {event_id}: sent successfully.") else: logger.info(f'Event {event_id}: failed to send.') def send_image_event(image: Union[np.ndarray, bytes], title: str, device_id: str = None, metadata: Optional[dict] = None, tags: List[str] = None, mjpeg_quality=98, encode=False ) -> Optional[str]: """Send a single image frame event to RH.""" try: if encode: _, image = cv2.imencode(".jpg", image, [int(cv2.IMWRITE_JPEG_QUALITY), mjpeg_quality]) event = robothub_core.EVENTS.prepare() event.add_frame(bytes(image), device_id) event.set_title(title) if metadata: event.set_metadata(metadata) if tags: event.add_tags(tags) robothub_core.EVENTS.upload(event) _log_event_status(True, event.id) return event.id except Exception as e: logger.error(f'Failed to send event: {e}') _log_event_status(False, "None") return None def send_frame_event_with_zipped_images(cv_frame, files, title: str, device_id: str, tags: List[str] = None, metadata: Optional[dict] = None, encode: bool = False, mjpeg_quality=98 ) -> Optional[str]: """Send a collection of images as a single event to RH.""" try: encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), mjpeg_quality] if encode: _, cv_frame = cv2.imencode('.jpg', cv_frame, encode_param) event = robothub_core.EVENTS.prepare() event.add_frame(bytes(cv_frame), device_id) event.set_title(title) if tags: event.set_tags(tags) if metadata: event.set_metadata(metadata) logger.debug(f'Total files: {len(files)}') with BytesIO() as zip_buffer: with zipfile.ZipFile(zip_buffer, 'w') as zip_file: for idx, file in enumerate(files): if encode: _, encoded = cv2.imencode('.jpg', file, encode_param) else: encoded = file # Convert the numpy array to bytes image_bytes = encoded.tobytes() # Add the bytes to the zip file with a unique filename filename = f'image_{idx}.jpeg' zip_file.writestr(filename, image_bytes) # event.add_file(bytes(encoded), name=f"image_{idx}.jpeg") # Get the bytes of the zip file zip_bytes = zip_buffer.getvalue() event.add_file(zip_bytes, name=f'images.zip') robothub_core.EVENTS.upload(event) _log_event_status(True, event.id) return event.id except Exception as e: logger.error(f'Failed to send event: {e}') _log_event_status(False, 'None') return None
/robothub_oak-2.1.0-py3-none-any.whl/robothub_oak/events.py
0.747892
0.182571
events.py
pypi
import base64 import json import os import time import uuid import warnings from contextlib import contextmanager from datetime import datetime, timedelta from pathlib import Path import urllib.request from urllib.error import HTTPError, URLError import depthai import paho_socket as mqtt_client import numpy as np class RobotHubPublishException(Exception): pass class RobotHubConnectionException(Exception): pass class Config: _rawConfig = {} _defaults = {} def __getattr__(self, key): try: return self._rawConfig[key] except KeyError: return self._defaults.get(key) def readConfig(self, raw): self._rawConfig = json.loads(raw) def addDefaults(self, **kwargs): self._defaults = {**self._defaults, **kwargs} def frameNorm(frame, bbox): normVals = np.full(len(bbox), frame.shape[0]) normVals[::2] = frame.shape[1] return (np.clip(np.array(bbox), 0, 1) * normVals).astype(int) class Detection: id = None position = None first_update = None last_update = None label = None latest_bbox = None bboxes = [] frames = [] _custom = {} def __init__(self, position, label, bbox): self.id = str(uuid.uuid4()) self.label = label self.first_update = datetime.now() self.update(position, bbox) def update(self, position, bbox): self.position = position self.last_update = datetime.now() self.latest_bbox = bbox self.bboxes.append(bbox) def parse_frame(self, frame): bbox = frameNorm(frame, [self.latest_bbox[0], self.latest_bbox[1], self.latest_bbox[2], self.latest_bbox[3]]) self.frames.append(frame[bbox[1]:bbox[3], bbox[0]:bbox[2]]) def add_field(self, name, data): self._custom[name] = data def get_payload(self): return json.dumps({ "id": self.id, "label": self.label, "start": self.first_update.astimezone().replace(microsecond=0).isoformat(), "end": self.last_update.astimezone().replace(microsecond=0).isoformat(), **self._custom, }, ensure_ascii=False) @property def active(self): return datetime.now() - self.last_update < timedelta(seconds=5) @property def completed(self): return datetime.now() - self.first_update > timedelta(seconds=15) or not self.active def __str__(self): return f"Detection<{self.label} {self.id} - {self.last_update.strftime('%H:%M:%S.%f')} (entries: {len(self.bboxes)})>" def __repr__(self): return self.__str__() def dist(a, b): return np.linalg.norm(np.array(a) - np.array(b)) def get_pos(entry): if hasattr(entry, 'spatialCoordinates'): x = entry.spatialCoordinates.x / 1000 y = entry.spatialCoordinates.y / 1000 z = entry.spatialCoordinates.z / 1000 else: x = abs(entry.xmax - entry.xmin) / 2 y = abs(entry.ymax - entry.ymin) / 2 z = 0 return [x, y, z] class DetectionParser: #: list: Contains active detections (still detected by NN) active = [] #: list: Contains inactive detections (were not detected by NN for specified period of time and are assumed "lost") inactive = [] def __init__(self, class_whitelist=None, matching_threshold=1.5, confidence_threshold=0.8): """ This class is responsible for extracting detections from NN data and matching the same ones across multiple detections. Args: class_whitelist (list, Optional): A list of class identifiers, specifying which classes are taken upon consideration while matching matching_threshold (float, Optional): Defines the maximum distance between a detection being classified as a new one or matched with the existing one confidence_threshold (float, Optional): Defines the minimum confidence the nn result should have to be parsed """ self.matching_threshold = matching_threshold self.confidence_threshold = confidence_threshold self.class_whitelist = class_whitelist def parse(self, data): """ Consumes the NN data and either creates new Detections or updates the existing ones. Args: data (list): A list containing NN packets produced by device """ for entry in data: bbox = [entry.xmin, entry.ymin, entry.xmax, entry.ymax] if entry.confidence < self.confidence_threshold: continue if self.class_whitelist is not None and entry.label in self.class_whitelist: continue new_position = get_pos(entry) for detection in self.active: if detection.label == entry.label and dist(detection.position, new_position) < self.matching_threshold: detection.update(new_position, bbox) break else: self.active.append(Detection(new_position, entry. label, bbox)) self.active = list(filter(lambda detection: self.inactive.append(detection) if not detection.active else True, self.active)) print(self.active) def feed_frame(self, frame): """ Sends a frame to all active detections for parsing Args: frame (numpy.ndarray): A frame object """ for detection in self.active: detection.parse_frame(frame) def has_completed(self): """ Allows checking whether any of the detections are ready to be sent Returns: bool: True if there is at least one completed detection """ return any(filter(lambda detection: detection.completed, self.active)) def get_completed(self): """ Returns a list of detections that are ready to be sent Returns: list: list of detection objects that are completed """ return list(filter(lambda detection: detection.completed, self.active)) def remove_detection(self, detection): """ Removes a detection from active or inactive list Args: detection (robothub_sdk.Detection): A detection object to be removed """ if detection in self.active: self.active.remove(detection) if detection in self.inactive: self.inactive.remove(detection) class RobotHubClient: #: str: unique identifier of the application app_id = None #: str: Contains device identifier on which the application can be executed device_id = os.environ['MX_ID'] if 'MX_ID' in os.environ else None #: paho_socket.Client: Contains device identifiers on which the application can be executed client = None #: Config: Contains config supplied by Agent config = Config() _config_path = None _broker_path = None def __init__(self, broker_path=None, config_path=None): """ This class is responsible for managing connection between Agent and App. Args: broker_path (pathlib.Path, Optional): Path to Agent MQTT UNIX socket config_path (pathlib.Path, Optional): Path to initial JSON configuration file Raises: RobotHubConnectionException: If the path to Agent MQTT UNIX socket was not found automatically """ if broker_path is not None: parsed = Path(broker_path).resolve().absolute() if parsed.exists(): self._broker_path = parsed if config_path is not None: parsed = Path(config_path).resolve().absolute() if parsed.exists(): self._config_path = parsed if self._config_path is None: primary_path = Path('/initial-configuration.json') if primary_path.exists(): self._config_path = primary_path else: t = "Unable to resolve initial config file location - configuration not loaded. This issue can be solved by providing `config_path` param" warnings.warn(t) if self._config_path is not None: with self._config_path.open() as f: self.config.readConfig(json.load(f)) if self._broker_path is None: primary_path = Path('/broker').resolve().absolute() secondary_path = (Path(__file__).parent.parent.parent.parent.parent.parent / "agent" / "dist" / "socket" / "broker.sock").resolve().absolute() if primary_path.exists(): self._broker_path = primary_path elif secondary_path.exists(): self._broker_path = secondary_path else: raise RobotHubConnectionException("Unable to resolve broker path. Please provide `broker_path` parameter with socket path") self.app_id = os.environ.get('APP_ID', str(uuid.uuid4())) self.device_ids = os.environ.get('APP_DEVICES') # START MQTT def _on_connect(self, client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") self.client.on_message = self._on_message else: raise RobotHubConnectionException(f"Failed to connect - non-zero return code: {rc}", ) self.client.subscribe(f"{self.app_id}/#", 0) def _on_disconnect(self, client, userdata, rc): print(f"Disconnected from MQTT Broker with result code {rc}") def _on_message(self, client, userdata, msg): data = msg.payload.decode() print(f"Received `{data}` from `{msg.topic}` topic") if msg.topic == f'{self.app_id}/configuration': self.config.readConfig(data) def _send_message(self, topic, msg, *args, **kwargs): if self.client is None: raise RobotHubPublishException(f"Failed to send message to topic {topic} - client not initialized") if not self.client.is_connected(): raise RobotHubPublishException(f"Failed to send message to topic {topic} - client not connected") ret = self.client.publish(topic, msg, *args, **kwargs)[0] if ret != 0: raise RobotHubPublishException(f"Failed to send message to topic {topic} - non-zero return code: {ret}") else: print(f"Send message to {topic} topic") def _send_request(self, url, payload): req = urllib.request.Request(url) req.add_header('Content-Type', 'application/json; charset=utf-8') try: urllib.request.urlopen(req, payload.encode('utf-8')) except HTTPError as e: # do something RobotHubPublishException(f"Failed to send message to URL {url} - non-zero return code: {e.code}") print('Error code: ', e.code) except URLError as e: # do something RobotHubPublishException(f"Failed to send message to URL {url} - reason: {e.reason}") print('Reason: ', e.reason) print(f"Send message to {url} topic with payload {payload}") def connect(self): """ Starts a connection to the Agent Raises: RobotHubConnectionException: Raised if a connection was not successful """ self.client = mqtt_client.Client(client_id=self.app_id) self.client.will_set(f'offline/{self.app_id}', json.dumps({'appId': self.app_id})) self.client.on_connect = self._on_connect self.client.on_disconnect = self._on_disconnect self.client.sock_connect(str(self._broker_path)) self.client.reconnect_delay_set(min_delay=1, max_delay=16) self.client.loop_start() def disconnect(self): """ Terminates a connection to the Agent (if was started) """ if self.client is None: warnings.warn("Client not connected - nothing to disconnect!") else: self.client.loop_stop() # END MQTT @contextmanager def claim_device(self, pipeline): """ Connects to configured device Returns: device (depthai.Device): connected Device object """ foundDevice = False deviceInfo = None while self.device_id is not None and not foundDevice: (foundDevice, deviceInfo) = depthai.Device.getDeviceByMxId(self.device_id) if not foundDevice: self._send_message(f'error/{self.app_id}', f'Device {self.device_id} not found') time.sleep(0.5) with depthai.Device(pipeline, deviceInfo) as device: self._send_message(f'online/{self.app_id}', json.dumps({ 'appId': self.app_id, 'streams': [ {'name': 'rgb', 'type': 'video', 'fps': 25, 'description': f'Main RGB camera 1080p@25', 'enabled': False}, {'name': 'left', 'type': 'video', 'fps': 25, 'description': f'Left mono camera 480p@25', 'enabled': False}, {'name': 'right', 'type': 'video', 'fps': 25, 'description': f'Right mono camera 480p@25', 'enabled': False}, ] }), retain=True) yield device def report_device(self, device: depthai.Device): """ Sends the device configuration to the Agent Args: device (depthai.Device): Device object to report """ info = device.getDeviceInfo() eeprom = device.readCalibration().getEepromData() # Announce device to the agent payload = json.dumps({ "serialNumber": self.device_id, "state": info.state.value, "protocol": info.desc.protocol.value, "platform": info.desc.platform.value, "boardName": eeprom.boardName, "boardRev": eeprom.boardRev, }) self._send_message(f'device/{self.app_id}', payload, retain=True) def send_detection(self, detection): """ Sends the :class:`robothub_sdk.Detection` object to the Agent """ payload = detection.get_payload() if self.config.detections_url is not None: self._send_request(self.config.detections_url, payload) else: self._send_message("online/detections", payload) def send_error(self, msg): """ Sends the specified error message to the Agent """ self._send_message(f'error/{self.app_id}', msg) def send_statistics(self, statistics: depthai.SystemInformation): """ Sends the usage metrics to the Agent """ payload = json.dumps({ "serialNumber": self.device_id, "cssUsage": int(statistics.leonCssCpuUsage.average * 100), "mssUsage": int(statistics.leonMssCpuUsage.average * 100), "ddrMemFree": statistics.ddrMemoryUsage.remaining, "ddrMemTotal": statistics.ddrMemoryUsage.total, "cmxMemFree": statistics.cmxMemoryUsage.remaining, "cmxMemTotal": statistics.cmxMemoryUsage.total, "cssTemperature": int(statistics.chipTemperature.css), "mssTemperature": int(statistics.chipTemperature.mss), "upaTemperature": int(statistics.chipTemperature.upa), "dssTemperature": int(statistics.chipTemperature.dss), "temperature": int(statistics.chipTemperature.average), }) self._send_message(f'system/{self.app_id}', payload) def send_preview(self, name, frame=None, encoded=None): """ Sends a preview frame to the Agent Args: name (str): Name of the preview frame (numpy.ndarray, Optional): Frame object to be sent as a preview encoded (bytes, Optional): Bytes object to be sent as a preview (for encoded streams) """ if frame is None and encoded is None: raise RobotHubPublishException("Both \"frame\" and \"encoded\" params left empty, you need to provide one of these") self._send_message(f"stream/{self.app_id}/{name}", frame.tobytes() if frame is not None else encoded)
/robothub-sdk-0.0.3.tar.gz/robothub-sdk-0.0.3/src/robothub_sdk/__init__.py
0.70202
0.23092
__init__.py
pypi
import json import logging import os import re from dataclasses import dataclass from typing import List, Union, Optional import matplotlib.pyplot as plt import numpy as np import pybullet as p import pybullet_data import torch from robotic_manipulator_rloa.environment.environment import Environment, EnvironmentConfiguration from robotic_manipulator_rloa.utils.exceptions import ( EnvironmentNotInitialized, NAFAgentNotInitialized, ConfigurationIncomplete, InvalidHyperParameter, InvalidNAFAgentParameter ) from robotic_manipulator_rloa.utils.logger import get_global_logger, Logger from robotic_manipulator_rloa.naf_components.naf_algorithm import NAFAgent # Mute matplotlib and PIL logs plt.set_loglevel('critical') logging.getLogger('PIL').setLevel(logging.WARNING) # Initialize framework logger logger = get_global_logger() Logger.set_logger_setup() @dataclass class HyperParameters: """ Data Class for the storage of the required hyper-parameters. """ buffer_size: int = 100000 batch_size: int = 128 gamma: float = 0.99 tau: float = 0.001 learning_rate: float = 0.001 update_freq: int = 1 num_updates: int = 1 class ManipulatorFramework: def __init__(self) -> None: """ Main class of the package. Initializes the required hyper-parameters to their default value. """ self.env: Union[Environment, None] = None self.naf_agent: Union[NAFAgent, None] = None self._hyperparameters: Union[HyperParameters, None] = None self._initialize_hyperparameters() logger.info('The Framework has been initialized with the default hyperparameters configuration') logger.debug('* Custom hyperparameters can be set via the set_hyperparameter() method') logger.debug('* All the required hyperparameters can be printed via the get_required_hyperparameters() method') logger.debug('* Load a manipulator via the initialize_environment() method to start with the training ' 'configuration') def _initialize_hyperparameters(self) -> None: """ Initializes the hyper-parameters with their default values. """ self._hyperparameters = HyperParameters(buffer_size=100000, batch_size=128, gamma=0.99, tau=0.001, learning_rate=0.001, update_freq=1, num_updates=1) @staticmethod def set_log_level(log_level: int) -> None: """ Set Log Level for the Logger. Args: log_level: Log level to be set.\n Valid values: 10 (DEBUG), 20 (INFO), 30 (WARNING), 40 (ERROR), 50 (CRITICAL) """ level_name_mappings = {10: 'DEBUG', 20: 'INFO', 30: 'WARNING', 40: 'ERROR', 50: 'CRITICAL'} # Set Log level if log_level in [10, 20, 30, 40, 50]: logger.info(f'Log Level has been set to {logger.level} ({level_name_mappings[logger.level]})') logger.setLevel(log_level) else: logger.error( f'The Log level provided is invalid, so the previous Log Level is maintained ({logger.level}))') logger.error('Valid values: 10 (DEBUG), 20 (INFO), 30 (WARNING), 40 (ERROR), 50 (CRITICAL)') @staticmethod def get_required_hyperparameters() -> None: """ Returns a list with the required hyper-parameters. This function does not imply any logic, as it is only intended to help the user to know what hyper-parameters can be set. The required hyper-parameters are shown as DEBUG logs, so if the Log level is set to INFO or higher the function will not return anything. """ if logger.level > 10: logger.error('get_required_hyperparameters() only shows information for DEBUG log level. ' 'Try running this method after setting the log level to DEBUG by calling ' 'set_log_level(10) class method') return hyperparameters_info_map = { 'Buffer Size': 'https://www.tensorflow.org/agents/tutorials/5_replay_buffers_tutorial?hl=es-419', 'Batch Size': 'https://www.kaggle.com/general/276990', 'Gamma (discount factor)': 'https://arxiv.org/pdf/2007.02040.pdf', 'Tau': 'https://arxiv.org/abs/1603.00748', 'Learning Rate': 'https://machinelearningmastery.com/understand-the-dynamics-of-learning-rate-on-deep' '-learning-neural-networks/', 'Update Frequency': 'https://medium.com/towards-data-science/applied-reinforcement-learning-v-normalized' '-advantage-function-naf-for-continuous-control-62ad143d3095', 'Number of Updates': 'https://medium.com/towards-data-science/applied-reinforcement-learning-v-normalized' '-advantage-function-naf-for-continuous-control-62ad143d3095'} logger.debug('Required Hyperparameters:') for hyperparam, info in hyperparameters_info_map.items(): logger.debug('{:<25} (see {:<10})'.format(hyperparam, info)) @staticmethod def plot_training_rewards(episode: int, mean_range: int = 50) -> None: """ Plots the mean reward of each batch of {mean_range} episodes for the "scores.txt" file stored in the checkpoints/ folder, corresponding to the episode received as parameter. Args: episode: Episode number from which to plot the results. The episode provided must be one of the checkpoints generated in the /checkpoints directory. mean_range: Range of episodes on which the mean is calculated. If the execution lasted for 200 episodes, and the mean_range is set to 50, 4 metric points will be generated. Raises: FileNotFoundError: Raises if the episode provided is not present as a directory in the /checkpoints directory generated after executing a training. """ try: with open(f'checkpoints/{episode}/scores.txt', 'r') as f: file = f.read() scores = json.loads(file) except FileNotFoundError as err: logger.error(f'File "scores.txt" located in checkpoints/{episode}/ folder was not found') raise err counter, cummulative_reward, values_to_plot = 0, list(), list() for episode, result in scores.items(): cummulative_reward.append(result[0]) counter += 1 if counter % mean_range == 0: mean = sum(cummulative_reward) / len(cummulative_reward) values_to_plot.append(mean) cummulative_reward = list() plt.plot(range(len(values_to_plot)), values_to_plot) plt.show() def set_hyperparameter(self, hyperparameter: str, value: Union[float, int]) -> None: """ Sets the specified value on the given hyper-parameter. Checking are performed to ensure that the new value for the hyper-parameter is a valid value. Args: hyperparameter: Name of the hyper-parameter to be updated. Allowed names are:\n - buffer_size/buffersize/BUFFER_SIZE/BUFFERSIZE\n - batch_size/batchsize/BATCH_SIZE/BATCHSIZE\n - gamma/GAMMA\n - tau/TAU\n - learning_rate/learningrate/LEARNING_RATE/LEARNINGRATE\n - update_freq/updatefreq/UPDATE_FREQ/UPDATEFREQ\n - num_update/numupdate/NUMUPDATE/NUM_UPDATE\n value: New value for the given hyper-parameter. Raises: InvalidHyperParameter: The hyperparameter received has an invalid value/type, or the hyperparameter name received is not one of the accepted values. """ # Set BUFFER SIZE if re.match(r'^(buffer_size|buffersize|BUFFER_SIZE|BUFFERSIZE)$', hyperparameter): if not (isinstance(value, int) and value > 0): raise InvalidHyperParameter('Buffer Size is not an int or has a value lower than 0') self._hyperparameters.buffer_size = value logger.info(f'Hyperparameter {hyperparameter} has been set to {value}') # Set BATCH SIZE elif re.match(r'^(batch_size|batchsize|BATCH_SIZE|BATCHSIZE)$', hyperparameter): if not (isinstance(value, int) and value > 0): raise InvalidHyperParameter('Batch Size is not an int or has a value lower than 0') self._hyperparameters.batch_size = value logger.info(f'Hyperparameter {hyperparameter} has been set to {value}') # Set GAMMA elif re.match(r'^(gamma|GAMMA)$', hyperparameter): if not (isinstance(value, (int, float)) and 0 < value < 1): raise InvalidHyperParameter('Gamma is not a float or its value is out of range (0, 1)') self._hyperparameters.gamma = value logger.info(f'Hyperparameter {hyperparameter} has been set to {value}') # Set TAU elif re.match(r'^(tau|TAU)$', hyperparameter): if not (isinstance(value, (int, float)) and 0 <= value <= 1): raise InvalidHyperParameter('Tau is not a float or its value is out of range [0, 1]') self._hyperparameters.tau = value logger.info(f'Hyperparameter {hyperparameter} has been set to {value}') # Set LEARNING RATE elif re.match(r'^(learning_rate|learningrate|LEARNING_RATE|LEARNINGRATE)$', hyperparameter): if not (isinstance(value, (int, float)) and value > 0): raise InvalidHyperParameter('Learning Rate is not a float or has a value lower than 0') self._hyperparameters.learning_rate = value logger.info(f'Hyperparameter {hyperparameter} has been set to {value}') # Set UPDATE EVERY elif re.match(r'^(update_freq|updatefreq|UPDATE_FREQ|UPDATEFREQ)$', hyperparameter): if not (isinstance(value, int) and value > 0): raise InvalidHyperParameter('Update Frequency is not an int or has a value lower than 0') self._hyperparameters.update_freq = value logger.info(f'Hyperparameter {hyperparameter} has been set to {value}') # Set NUPDATE elif re.match(r'^(num_update|numupdate|NUMUPDATE|NUM_UPDATE)$', hyperparameter): if not (isinstance(value, int) and value > 0): raise InvalidHyperParameter('Buffer Size is not an int or has a value lower than 0') self._hyperparameters.num_updates = value logger.info(f'Hyperparameter {hyperparameter} has been set to {value}') else: raise InvalidHyperParameter( 'The hyperparameter name passed as parameter is not valid. Valid hyperparameters are: ' '["buffer_size", "batch_size", "gamma", "tau", "learning_rate", "update_freq", "num_update"]') def load_pretrained_parameters_from_weights_file(self, parameters_file_path: str) -> None: """ Loads a pretrained network's weights into the current networks. The weights are loaded from the path provided in the {parameters_file_path} parameter. As the weights are loaded in the neural networks contained in the NAFAgent class, the method will raise an error if either the Environment or the NAFAgent class are not initialized. Args: parameters_file_path: Path to the .p file where the weights are stored. Raises: EnvironmentNotInitialized: The Environment class has not been initialized. NAFAgentNotInitialized: The NAFAgentNotInitialized class has not been initialized. MissingWeightsFile: The .p file path provided does not exist. """ if not self.env: raise EnvironmentNotInitialized if not self.naf_agent: raise NAFAgentNotInitialized self.naf_agent.initialize_pretrained_agent_from_weights_file(parameters_file_path) def load_pretrained_parameters_from_episode(self, episode: int) -> None: """ Loads previously trained weights into the current networks. The pretrained weights are retrieved from the checkpoints generated on a training execution, so the episode provided must be present in the checkpoints/ folder. As the weights are loaded in the neural networks contained in the NAFAgent class, the method will raise an error if either the Environment or the NAFAgent class are not initialized. Args: episode: Episode in the /checkpoints folder from which to retrieve the pretrained weights. Raises: EnvironmentNotInitialized: The Environment class has not been initialized. NAFAgentNotInitialized: The NAFAgentNotInitialized class has not been initialized. MissingWeightsFile: The weights.p file does not exist in the folder provided. """ if not self.env: raise EnvironmentNotInitialized if not self.naf_agent: raise NAFAgentNotInitialized self.naf_agent.initialize_pretrained_agent_from_episode(episode) def get_environment_configuration(self) -> None: """ Shows the Environment configuration as logs on stdout. """ if not self.env: logger.error("Environment is not initialized yet, can't show configuration") return logger.info('Environment Configuration:') logger.info(f'* Manipulator File: {self.env.manipulator_file}') logger.info(f'* End Effector index: {self.env.endeffector_index}') logger.info(f'* List of fixed Joints: {self.env.fixed_joints}') logger.info(f'* List of Joints involved in training: {self.env.involved_joints}') logger.info(f'* Position of the Target: {self.env.target_pos}') logger.info(f'* Position of the Obstacle: {self.env.obstacle_pos}') logger.info(f'* Initial position of joints: {self.env.initial_joint_positions}') logger.info(f'* Initial variation range of joints: {self.env.initial_positions_variation_range}') logger.info(f'* Max Force to be applied on joints: {self.env.max_force}') logger.info(f'* Visualize mode: {self.env.visualize}') logger.info(f'* Instance of the Environment: {self.env}') def get_nafagent_configuration(self) -> None: """ Shows the NAFAgent configuration as logs on stdout. """ if not self.naf_agent: logger.error("NAFAgent is not initialized yet, can't show configuration") return logger.info('NAFAgent Configuration:') logger.info(f'* Environment Instance: {self.naf_agent.environment}') logger.info(f'* State Size: {self.naf_agent.state_size}') logger.info(f'* Action Size: {self.naf_agent.action_size}') logger.info(f'* Size of layers of the Neural Network: {self.naf_agent.layer_size}') logger.info(f'* Batch Size: {self.naf_agent.batch_size}') logger.info(f'* Buffer Size: {self.naf_agent.buffer_size}') logger.info(f'* Learning Rate: {self.naf_agent.learning_rate}') logger.info(f'* Tau: {self.naf_agent.tau}') logger.info(f'* Gamma: {self.naf_agent.gamma}') logger.info(f'* Update Frequency: {self.naf_agent.update_freq}') logger.info(f'* Number of Updates: {self.naf_agent.num_updates}') logger.info(f'* Checkpoint frequency: {self.naf_agent.checkpoint_frequency}') logger.info(f'* Device: {self.naf_agent.device}') def test_trained_model(self, n_episodes: int, frames: int) -> None: """ Tests a previously trained agent through the execution of {n_episodes} test episodes, for {frames} timesteps each. When the test concludes, the results of the test are logged on terminal. Args: n_episodes: Number of test episodes to execute. frames: Number of timesteps per test episode. Raises: ConfigurationIncomplete: Either the Environment class or the NAFAgent class are not initialized. """ # Check if Environment and NAFAgent initialized if not self.naf_agent or not self.env: raise ConfigurationIncomplete # Initialize Test result's history results, num_collisions = list(), 0 for _ in range(n_episodes): state = self.env.reset() for frame in range(frames): action = self.naf_agent.act(state) next_state, reward, done = self.env.step(action) state = next_state if done: if reward == 250: results.append((True, frame)) break else: results.append((False, frame)) num_collisions += 1 break if frame == frames - 1 and not done: results.append((False, frame)) break logger.info('Test Episode number {ep} completed\n'.format(ep=_ + 1)) logger.info('RESULTS OF THE TEST:') for i, result in enumerate(results): logger.info(f'Results of Iteration {i + 1}: COMPLETED: {result[0]}. FRAMES: {result[1]}') logger.info(f'Number of successful executions: ' f'{[res[0] for res in results].count(True)}/{len(results)} ' f'({([res[0] for res in results].count(True) / len(results)) * 100}%)') logger.info(f'Average number of frames required to complete an episode: ' f'{np.mean(np.array([res[1] for res in results if res[0]]))}') logger.info(f'Number of episodes terminated because of collisions: {num_collisions}') def initialize_environment( self, manipulator_file: str, endeffector_index: int, fixed_joints: List[int], involved_joints: List[int], target_position: List[float], obstacle_position: List[float], initial_joint_positions: List[float] = None, initial_positions_variation_range: List[float] = None, max_force: float = 200., visualize: bool = True) -> None: """ Initialize the Environment by creating an instance of the Environment class. Args: manipulator_file: Path to the manipulator's URDF or SDF file. endeffector_index: Index of the manipulator's end-effector. fixed_joints: List containing the indices of every joint not involved in the training. involved_joints: List containing the indices of every joint involved in the training. target_position: List containing the position of the target object, as 3D Cartesian coordinates. obstacle_position: List containing the position of the obstacle, as 3D Cartesian coordinates. initial_joint_positions: List containing as many items as the number of joints of the manipulator. Each item in the list corresponds to the initial position wanted for the joint with that same index. initial_positions_variation_range: List containing as many items as the number of joints of the manipulator. Each item in the list corresponds to the variation range wanted for the joint with that same index. max_force: Maximum force to be applied on the joints. visualize: Visualization mode. Raises: InvalidEnvironmentParameter: One or more parameters provided for the Environment initialization are invalid. InvalidManipulatorFile: The URDF/SDF file provided does not exist or cannot be loaded into the Pybullet Environment. """ logger.debug('Initializing Pybullet Environment...') environment_config = EnvironmentConfiguration( endeffector_index=endeffector_index, fixed_joints=fixed_joints, involved_joints=involved_joints, target_position=target_position, obstacle_position=obstacle_position, initial_joint_positions=initial_joint_positions, initial_positions_variation_range=initial_positions_variation_range, max_force=max_force, visualize=visualize) self.env = Environment(manipulator_file=manipulator_file, environment_config=environment_config) logger.info('Pybullet Environment successfully initialized') logger.debug(f'* The NAF Agent can now be initialized via the initialize_naf_agent() method') def delete_environment(self) -> None: """ Deletes the existing Environment instance, and disconnects the current Pybullet instance. """ if not self.env: logger.error('No existing instance of Environment found') return p.disconnect(self.env.physics_client) self.env = None logger.info('Environment instance has been successfully removed') def initialize_naf_agent(self, checkpoint_frequency: int = 500, seed: int = 0) -> None: """ Initialize the NAF Agent by creating an instance of the NAFAgent class. Args: checkpoint_frequency: Number of episodes required to generate a checkpoint. seed: Random seed. Raises: EnvironmentNotInitialized: Environment class has not been initialized. InvalidNAFAgentParameter: Either "checkpoint_frequency" or "seed" parameters have an invalid value/type. """ if not self.env: raise EnvironmentNotInitialized if not isinstance(checkpoint_frequency, int) or not isinstance(seed, int): raise InvalidNAFAgentParameter('Checkpoint Frequency or Seed received is not an integer') logger.debug('Initializing NAF Agent...') device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") self.naf_agent = NAFAgent(environment=self.env, state_size=self.env.observation_space.shape[0], action_size=self.env.action_space.shape[0], layer_size=256, batch_size=self._hyperparameters.batch_size, buffer_size=self._hyperparameters.buffer_size, learning_rate=self._hyperparameters.learning_rate, tau=self._hyperparameters.tau, gamma=self._hyperparameters.gamma, update_freq=self._hyperparameters.update_freq, num_updates=self._hyperparameters.num_updates, checkpoint_frequency=checkpoint_frequency, device=device, seed=seed) logger.info('NAF Agent successfully initialized') logger.debug('* The Robotic Manipulator training can now be launched via the run_training() method') def delete_naf_agent(self) -> None: """ Deletes the existing NAFAgent instance. """ if not self.naf_agent: logger.error('No existing instance of NAFAgent found') return self.naf_agent = None logger.info('NAFAgent instance has been successfully removed') def run_training(self, episodes: int, frames: Optional[int] = 500, verbose: bool = True): """ Execute a training on the configured Environment with the configured NAF Agent. The training is executed for {episodes}, and for {frames} timesteps per episode. Args: episodes: Maximum number of episodes to execute. frames: Maximum number of timesteps to execute per episode. verbose: Verbose mode.\n - If set to True, each timestep will log information about the current state, the action chosen from that state, the current reward and the cummulative reward until that timestep. In addition, each time an episode ends information about the total reward obtained, the number of frames required to complete the episode, the mean reward obtained along the episode and the execution time of the episode are logged.\n - If set to False, each time an episode ends information about the total reward obtained, the number of frames required to complete the episode, the mean reward obtained along the episode and the execution time of the episode are logged.\n It is recommended to use the verbose mode only in a development/debugging context, since logging information for each timestep greatly reduces the visibility of what is happening during the training. Raises: ConfigurationIncomplete: Either NAFAgent or Environment has not been initialized. """ if not self.naf_agent or not self.env: raise ConfigurationIncomplete self.naf_agent.run(frames, episodes, verbose) def run_demo_training(self, demo_type: str, verbose: bool = False) -> None: """ Run a demo from a preconfigured Environment and NAFAgent, which shows how the framework works. The training is executed for 20 episodes. Do not expect good results, as this is just a demo of the training configuration process and the number of episodes is not enough to achieve a good performance in the manipulator. Args: demo_type: Valid values:\n - 'kuka_training': training with the KUKA IIWA Robotic Manipulator.\n - 'xarm6_training': training with the XArm6 Robotic Manipulator.\n verbose: Verbose mode. Verbose mode functionality is applied on the same way as for the run_training() method. """ logger.warning('Both the demo testing and the demo training are executed with the Log level ' 'set to DEBUG, so that the framework can be understood at a low level.') old_level = logger.level logger.setLevel(10) # CHECK EXISTENT ENVIRONMENT AND NAF AGENT # Overwrite previous Environment configuration if present if self.env: overwrite_env = input('Environment instance found. Overwrite? [Y/n] ').lower() == 'y' if not overwrite_env: logger.info('Demo could not run due to the presence of a user-configured Environment instance') return self.delete_environment() # Overwrite previous NAFAgent configuration if present if self.naf_agent: overwrite_naf_agent = input('NAFAgent instance found. Overwrite? [Y/n] ').lower() == 'y' if not overwrite_naf_agent: logger.info('Demo could not run due to the presence of a user-configured NAFAgent instance') return self.delete_naf_agent() # START DEMO if demo_type == 'kuka_training': logger.info('Initializing demo Environment instance...') self.initialize_environment(manipulator_file='kuka_iiwa/kuka_with_gripper2.sdf', endeffector_index=13, fixed_joints=[6, 7, 8, 9, 10, 11, 12, 13], involved_joints=[0, 1, 2, 3, 4, 5], target_position=[0.4, 0.85, 0.71], obstacle_position=[0.45, 0.55, 0.55], initial_joint_positions=[0.9, 0.45, 0, 0, 0, 0], initial_positions_variation_range=[0, 0, 0, 0, 0, 0], visualize=True) logger.info('Initializing demo NAFAgent instance...') self.initialize_naf_agent() logger.info('Running training for 20 episodes. Do not expect good results, ' 'this is just a demo of the training configuration process') self.run_training(20, 400, verbose=verbose) # Reset Environment and NAFAgent self.delete_environment() self.delete_naf_agent() elif demo_type == 'xarm6_training': logger.info('Initializing demo Environment instance...') xarm_path = os.path.join(pybullet_data.getDataPath(), 'xarm/xarm6_with_gripper.urdf') self.initialize_environment(manipulator_file=xarm_path, endeffector_index=12, fixed_joints=[0, 7, 8, 9, 10, 11, 12, 13], involved_joints=[1, 2, 3, 4, 5, 6], target_position=[0.3, 0.47, 0.61], obstacle_position=[0.25, 0.27, 0.5], initial_joint_positions=[0., 1., 0., -2.3, 0., 0., 0.], initial_positions_variation_range=[0, 0, 0, 0.3, 1, 1, 1], visualize=True) logger.info('Initializing demo NAFAgent instance...') self.initialize_naf_agent() logger.info('Running training for 20 episodes. Do not expect good results, ' 'this is just a demo of the confiuration process') self.run_training(20, 400, verbose=verbose) # Reset Environment and NAFAgent self.delete_environment() self.delete_naf_agent() else: logger.error('Incorrect demo type!') # Reset log level logger.setLevel(old_level) logger.warning('Log level has been reset to its original value') def run_demo_testing(self, demo_type: str) -> None: """ Run a demo testing from a preconfigured Environment and NAFAgent, which shows how a robotic manipulator learns with the framework. The demo loads pretrained weights and executes 50 test episodes. Args: demo_type: Valid values:\n - 'kuka_testing': testing with the KUKA IIWA Robotic Manipulator.\n - 'xarm6_testing': testing with the XArm6 Robotic Manipulator.\n """ logger.warning('Both the demo testing and the demo training are executed with the Log level ' 'set to DEBUG, so that the framework can be understood at a low level.') old_level = logger.level logger.setLevel(10) # CHECK EXISTENT ENVIRONMENT AND NAF AGENT # Overwrite previous Environment configuration if present if self.env: overwrite_env = input('Environment instance found. Overwrite? [Y/n] ').lower() == 'y' if not overwrite_env: logger.info('Demo could not run due to the presence of a user-configured Environment instance') return self.delete_environment() # Overwrite previous NAFAgent configuration if present if self.naf_agent: overwrite_naf_agent = input('NAFAgent instance found. Overwrite? [Y/n] ').lower() == 'y' if not overwrite_naf_agent: logger.info('Demo could not run due to the presence of a user-configured NAFAgent instance') return self.delete_naf_agent() # START DEMO if demo_type == 'kuka_testing': logger.info('Initializing demo Environment instance...') kuka_path = os.path.join(pybullet_data.getDataPath(), 'kuka_iiwa/kuka_with_gripper2.sdf') self.initialize_environment(manipulator_file=kuka_path, endeffector_index=13, fixed_joints=[6, 7, 8, 9, 10, 11, 12, 13], involved_joints=[0, 1, 2, 3, 4, 5], target_position=[0.4, 0.85, 0.71], obstacle_position=[0.45, 0.55, 0.55], initial_joint_positions=[0.9, 0.45, 0, 0, 0, 0], initial_positions_variation_range=[0, 0, .5, .5, .5, .5]) logger.info('Initializing demo NAFAgent instance...') self.initialize_naf_agent() logger.info('Loading demo pretrained parameters') self.load_pretrained_parameters_from_weights_file(os.path.dirname( os.path.realpath(__file__)) + '/naf_components/demo_weights/weights_kuka.p') logger.info('Running 50 test episodes...') self.test_trained_model(50, 750) # Reset Environment and NAFAgent self.delete_environment() self.delete_naf_agent() elif demo_type == 'xarm6_testing': logger.info('Initializing demo Environment instance...') xarm_path = os.path.join(pybullet_data.getDataPath(), 'xarm/xarm6_with_gripper.urdf') self.initialize_environment(manipulator_file=xarm_path, endeffector_index=12, fixed_joints=[0, 7, 8, 9, 10, 11, 12, 13], involved_joints=[1, 2, 3, 4, 5, 6], target_position=[0.3, 0.47, 0.61], obstacle_position=[0.25, 0.27, 0.5], initial_joint_positions=[0., 1., 0., -2.3, 0., 0., 0.], initial_positions_variation_range=[0, 0, 0, 0.3, 1, 1, 1], max_force=200, visualize=True) logger.info('Initializing demo NAFAgent instance...') self.initialize_naf_agent() logger.info('Loading demo pretrained parameters') self.load_pretrained_parameters_from_weights_file( os.path.dirname(os.path.realpath(__file__)) + '/naf_components/demo_weights/weights_xarm6.p') logger.info('Running 50 test episodes...') self.test_trained_model(50, 750) # Reset Environment and NAFAgent self.delete_environment() self.delete_naf_agent() else: logger.error('Incorrect demo type!') # Reset log level logger.setLevel(old_level) logger.warning('Log level has been reset to its original value')
/robotic-manipulator-rloa-1.0.0.tar.gz/robotic-manipulator-rloa-1.0.0/robotic_manipulator_rloa/rl_framework.py
0.847432
0.319281
rl_framework.py
pypi
from dataclasses import dataclass from typing import List import numpy as np import pybullet as p from numpy.typing import NDArray @dataclass class CollisionObject: """ Dataclass which contains the UID of the manipulator/body and the link number of the joint from which to calculate distances to other bodies. """ body: str link: int class CollisionDetector: def __init__(self, collision_object: CollisionObject, obstacle_ids: List[str]): """ Calculates distances between bodies' joints. Args: collision_object: CollisionObject instance, which indicates the body/joint from which to calculate distances/collisions. obstacle_ids: Obstacle body UID. Distances are calculated from the joint/body given in the "collision_object" parameter to the "obstacle_ids" bodies. """ self.obstacles = obstacle_ids self.collision_object = collision_object def compute_distances(self, max_distance: float = 10.0) -> NDArray: """ Compute the closest distances from the joint given by the CollisionObject instance in self.collision_object to the bodies defined in self.obstacles. Args: max_distance: Bodies farther apart than this distance are not queried by PyBullet, the return value for the distance between such bodies will be max_distance. Returns: A numpy array of distances, one per pair of collision objects. """ distances = list() for obstacle in self.obstacles: # Compute the shortest distances between the collision-object and the given obstacle closest_points = p.getClosestPoints( self.collision_object.body, obstacle, distance=max_distance, linkIndexA=self.collision_object.link ) # If bodies are above max_distance apart, nothing is returned, so # we just saturate at max_distance. Otherwise, take the minimum if len(closest_points) == 0: distances.append(max_distance) else: distances.append(np.min([point[8] for point in closest_points])) return np.array(distances) def compute_collisions_in_manipulator(self, affected_joints: List[int], max_distance: float = 10.) -> NDArray: """ Compute collisions between manipulator's parts. Args: affected_joints: Joints to consider when calculating distances. max_distance: Maximum distance to be considered. Distances further than this will be ignored, and the "max_distance" value will be returned. Returns: Array where each element corresponds to the distances from a given joint to the other joints. """ distances = list() for joint_ind in affected_joints: # Collisions with the previous and next joints are omitted, as they will be always in contact if (self.collision_object.link == joint_ind) or \ (joint_ind == self.collision_object.link - 1) or \ (joint_ind == self.collision_object.link + 1): continue # pragma: no cover # Compute the shortest distances between all object pairs closest_points = p.getClosestPoints( self.collision_object.body, self.collision_object.body, distance=max_distance, linkIndexA=self.collision_object.link, linkIndexB=joint_ind ) # If bodies are above max_distance apart, nothing is returned, so # we just saturate at max_distance. Otherwise, take the minimum if len(closest_points) == 0: distances.append(max_distance) else: distances.append(np.min([point[8] for point in closest_points])) return np.array(distances)
/robotic-manipulator-rloa-1.0.0.tar.gz/robotic-manipulator-rloa-1.0.0/robotic_manipulator_rloa/utils/collision_detector.py
0.958363
0.626895
collision_detector.py
pypi
import random from collections import deque, namedtuple from typing import Tuple import numpy as np import torch from numpy.typing import NDArray # deque is a Doubly Ended Queue, provides O(1) complexity for pop and append actions # namedtuple is a tuple that can be accessed by both its index and attributes class ReplayBuffer: def __init__(self, buffer_size: int, batch_size: int, device: torch.device, seed: int): """ Buffer to store experience tuples. Each experience has the following structure: (state, action, reward, next_state, done) Args: buffer_size: Maximum size for the buffer. Higher buffer size imply higher RAM consumption. batch_size: Number of experiences to be retrieved from the ReplayBuffer per batch. device: CUDA device. seed: Random seed. """ self.device = device self.memory = deque(maxlen=buffer_size) self.batch_size = batch_size self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"]) random.seed(seed) def add(self, state: NDArray, action: NDArray, reward: float, next_state: NDArray, done: int) -> None: """ Add a new experience to the Replay Buffer. Args: state: NDArray of the current state. action: NDArray of the action taken from state {state}. reward: Reward obtained after performing action {action} from state {state}. next_state: NDArray of the state reached after performing action {action} from state {state}. done: Integer (0 or 1) indicating whether the next_state is a terminal state. """ # Create namedtuple object from the experience exp = self.experience(state, action, reward, next_state, done) # Add the experience object to memory self.memory.append(exp) def sample(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """ Randomly sample a batch of experiences from memory. Returns: Tuple of 5 elements, which are (states, actions, rewards, next_states, dones). Each element in the tuple is a torch Tensor composed of {batch_size} items. """ # Randomly sample a batch of experiences experiences = random.sample(self.memory, k=self.batch_size) states = torch.from_numpy( np.stack([e.state if not isinstance(e.state, tuple) else e.state[0] for e in experiences])).float().to( self.device) actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).long().to(self.device) rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(self.device) next_states = torch.from_numpy(np.stack([e.next_state for e in experiences if e is not None])).float().to( self.device) dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to( self.device) return states, actions, rewards, next_states, dones def __len__(self) -> int: """ Return the current size of the Replay Buffer Returns: Size of Replay Buffer """ return len(self.memory)
/robotic-manipulator-rloa-1.0.0.tar.gz/robotic-manipulator-rloa-1.0.0/robotic_manipulator_rloa/utils/replay_buffer.py
0.941399
0.572544
replay_buffer.py
pypi
from __future__ import annotations from typing import Optional class FrameworkException(Exception): def __init__(self, message: str) -> None: """ Creates new FrameworkException. Base class that must be extended by any custom exception. Args: message: Info about the exception. """ Exception.__init__(self, message) self.message = message def __str__(self) -> str: """ Returns the string representation of the object """ return self.__class__.__name__ + ': ' + self.message def set_message(self, value: str) -> FrameworkException: """ Set the message to be printed on terminal. Args: value: Message with info about exception. Returns: FrameworkException """ self.message = value return self class InvalidManipulatorFile(FrameworkException): """ Exception raised when the URDF/SDF file received cannot be loaded with Pybullet's loadURDF/loadSDF methods. """ message = 'The URDF/SDF file received is not valid' def __init__(self, message: Optional[str] = None) -> None: if message: self.message = message FrameworkException.__init__(self, self.message) class InvalidHyperParameter(FrameworkException): """ Exception raised when the user tries to set an invalid value on a hyper-parameter """ message = 'The hyperparameter received is not valid' def __init__(self, message: Optional[str] = None) -> None: if message: self.message = message FrameworkException.__init__(self, self.message) class InvalidEnvironmentParameter(FrameworkException): """ Exception raised when the Environment is initialized with invalid parameter/parameters. """ message = 'The Environment parameter received is not valid' def __init__(self, message: Optional[str] = None) -> None: if message: self.message = message FrameworkException.__init__(self, self.message) class InvalidNAFAgentParameter(FrameworkException): """ Exception raised when the NAFAgent is initialized with invalid parameter/parameters. """ message = 'The NAF Agent parameter received is not valid' def __init__(self, message: Optional[str] = None) -> None: if message: self.message = message FrameworkException.__init__(self, self.message) class EnvironmentNotInitialized(FrameworkException): """ Exception raised when the Environment has not yet been initialized and the user tries to call a method which requires the Environment to be initialized. """ message = 'The Environment is not yet initialized. The environment can be initialized via the ' \ 'initialize_environment() method' def __init__(self, message: Optional[str] = None) -> None: if message: self.message = message FrameworkException.__init__(self, self.message) class NAFAgentNotInitialized(FrameworkException): """ Exception raised when the NAFAgent has not yet been initialized and the user tries to call a method which requires the NAFAgent to be initialized. """ message = 'The NAF Agent is not yet initialized. The agent can be initialized via the ' \ 'initialize_naf_agent() method' def __init__(self, message: Optional[str] = None) -> None: if message: self.message = message FrameworkException.__init__(self, self.message) class MissingWeightsFile(FrameworkException): """ Exception raised when the user loads pretrained weights from an invalid location. """ message = 'The weight file provided does not exist' def __init__(self, message: Optional[str] = None) -> None: if message: self.message = message FrameworkException.__init__(self, self.message) class ConfigurationIncomplete(FrameworkException): """ Exception raised when either the Environment, the NAFAgent or both have not been initialized yet, and the user tries to execute a training by calling the run_training() method. """ message = 'The configuration for the training is incomplete. Either the Environment, the ' \ 'NAF Agent or both are not yet initialized. The environment can be initialized via the ' \ 'initialize_environment() method, and the agent can be initialized via the ' \ 'initialize_naf_agent() method' def __init__(self, message: Optional[str] = None) -> None: if message: self.message = message FrameworkException.__init__(self, self.message)
/robotic-manipulator-rloa-1.0.0.tar.gz/robotic-manipulator-rloa-1.0.0/robotic_manipulator_rloa/utils/exceptions.py
0.943893
0.192388
exceptions.py
pypi
import random from typing import List, Tuple import numpy as np import pybullet as p import pybullet_data from numpy.typing import NDArray from robotic_manipulator_rloa.utils.logger import get_global_logger from robotic_manipulator_rloa.utils.exceptions import ( InvalidManipulatorFile, InvalidEnvironmentParameter ) from robotic_manipulator_rloa.utils.collision_detector import CollisionObject, CollisionDetector logger = get_global_logger() class EnvironmentConfiguration: def __init__(self, endeffector_index: int, fixed_joints: List[int], involved_joints: List[int], target_position: List[float], obstacle_position: List[float], initial_joint_positions: List[float] = None, initial_positions_variation_range: List[float] = None, max_force: float = 200., visualize: bool = True): """ Validates each of the parameters required for the Environment class initialization. Args: endeffector_index: Index of the manipulator's end-effector. fixed_joints: List containing the indices of every joint not involved in the training. involved_joints: List containing the indices of every joint involved in the training. target_position: List containing the position of the target object, as 3D Cartesian coordinates. obstacle_position: List containing the position of the obstacle, as 3D Cartesian coordinates. initial_joint_positions: List containing as many items as the number of joints of the manipulator. Each item in the list corresponds to the initial position wanted for the joint with that same index. initial_positions_variation_range: List containing as many items as the number of joints of the manipulator. Each item in the list corresponds to the variation range wanted for the joint with that same index. max_force: Maximum force to be applied on the joints. visualize: Visualization mode. """ self._validate_endeffector_index(endeffector_index) self._validate_fixed_joints(fixed_joints) self._validate_involved_joints(involved_joints) self._validate_target_position(target_position) self._validate_obstacle_position(obstacle_position) self._validate_initial_joint_positions(initial_joint_positions) self._validate_initial_positions_variation_range(initial_positions_variation_range) self._validate_max_force(max_force) self._validate_visualize(visualize) def _validate_endeffector_index(self, endeffector_index: int) -> None: """ Validates the "endeffector_index" parameter. Args: endeffector_index: int Raises: InvalidEnvironmentParameter """ if not isinstance(endeffector_index, int): raise InvalidEnvironmentParameter('End Effector index received is not an integer') self.endeffector_index = endeffector_index def _validate_fixed_joints(self, fixed_joints: List[int]) -> None: """ Validates the "fixed_joints" parameter Args: fixed_joints: list of integers Raises: InvalidEnvironmentParameter """ if not isinstance(fixed_joints, list): raise InvalidEnvironmentParameter('Fixed Joints received is not a list') for val in fixed_joints: if not isinstance(val, int): raise InvalidEnvironmentParameter('An item inside the Fixed Joints list is not an integer') self.fixed_joints = fixed_joints def _validate_involved_joints(self, involved_joints: List[int]) -> None: """ Validates the "involved_joints" parameter Args: involved_joints: list of integers Raises: InvalidEnvironmentParameter """ if not isinstance(involved_joints, list): raise InvalidEnvironmentParameter('Involved Joints received is not a list') for val in involved_joints: if not isinstance(val, int): raise InvalidEnvironmentParameter('An item inside the Involved Joints list is not an integer') self.involved_joints = involved_joints def _validate_target_position(self, target_position: List[float]) -> None: """ Validates the "target_position" parameter Args: target_position: list of floats Raises: InvalidEnvironmentParameter """ if not isinstance(target_position, list): raise InvalidEnvironmentParameter('Target Position received is not a list') for val in target_position: if not isinstance(val, (int, float)): raise InvalidEnvironmentParameter('An item inside the Target Position list is not a float') self.target_position = target_position def _validate_obstacle_position(self, obstacle_position: List[float]) -> None: """ Validates the "obstacle_position" parameter Args: obstacle_position: list of floats Raises: InvalidEnvironmentParameter """ if not isinstance(obstacle_position, list): raise InvalidEnvironmentParameter('Obstacle Position received is not a list') for val in obstacle_position: if not isinstance(val, (int, float)): raise InvalidEnvironmentParameter('An item inside the Obstacle Position list is not a float') self.obstacle_position = obstacle_position def _validate_initial_joint_positions(self, initial_joint_positions: List[float]) -> None: """ Validates the "initial_joint_positions" parameter Args: initial_joint_positions: list of floats Raises: InvalidEnvironmentParameter """ if initial_joint_positions is None: self.initial_joint_positions = None return if not isinstance(initial_joint_positions, list): raise InvalidEnvironmentParameter('Initial Joint Positions received is not a list') for val in initial_joint_positions: if not isinstance(val, (int, float)): raise InvalidEnvironmentParameter('An item inside the Initial Joint Positions list is not a float') self.initial_joint_positions = initial_joint_positions def _validate_initial_positions_variation_range(self, initial_positions_variation_range: List[float]) -> None: """ Validates the "initial_positions_variation_range" parameter Args: initial_positions_variation_range: list of floats Raises: InvalidEnvironmentParameter """ if initial_positions_variation_range is None: self.initial_positions_variation_range = None return if not isinstance(initial_positions_variation_range, list): raise InvalidEnvironmentParameter('Initial Positions Variation Range received is not a list') for val in initial_positions_variation_range: if not isinstance(val, (float, int)): raise InvalidEnvironmentParameter('An item inside the Initial Positions Variation Range ' 'list is not a float') self.initial_positions_variation_range = initial_positions_variation_range def _validate_max_force(self, max_force: float) -> None: """ Validates the "max_force" parameter Args: max_force: float Raises: InvalidEnvironmentParameter """ if not isinstance(max_force, (int, float)): raise InvalidEnvironmentParameter('Maximum Force value received is not a float') self.max_force = max_force def _validate_visualize(self, visualize: bool) -> None: """ Validates the "visualize" parameter Args: visualize: bool Raises: InvalidEnvironmentParameter """ if not isinstance(visualize, bool): raise InvalidEnvironmentParameter('Visualize value received is not a boolean') self.visualize = visualize class Environment: def __init__(self, manipulator_file: str, environment_config: EnvironmentConfiguration): """ Creates the Pybullet environment used along the training. Args: manipulator_file: Path to the URDF or SDF file from which to load the Robotic Manipulator. environment_config: Instance of the EnvironmentConfiguration class with all its attributes set. Raises: InvalidManipulatorFile: The URDF/SDF file doesn't exist, is invalid or has an invalid extension. """ self.manipulator_file = manipulator_file self.visualize = environment_config.visualize # Initialize pybullet self.physics_client = p.connect(p.GUI if environment_config.visualize else p.DIRECT) p.setGravity(0, 0, -9.81) p.setRealTimeSimulation(0) p.setAdditionalSearchPath(pybullet_data.getDataPath()) self.target_pos = environment_config.target_position self.obstacle_pos = environment_config.obstacle_position self.max_force = environment_config.max_force # Maximum force to be applied (DEFAULT=200) self.initial_joint_positions = environment_config.initial_joint_positions self.initial_positions_variation_range = environment_config.initial_positions_variation_range self.endeffector_index = environment_config.endeffector_index # Index of the Manipulator's End-Effector self.fixed_joints = environment_config.fixed_joints # List of indexes for the joints to be fixed self.involved_joints = environment_config.involved_joints # List of indexes of joints involved in the training # Load Manipulator from URDF/SDF file logger.debug(f'Loading URDF/SDF file {manipulator_file} for Robot Manipulator...') if not isinstance(manipulator_file, str): raise InvalidManipulatorFile('The filename provided is not a string') try: if manipulator_file.endswith('.urdf'): self.manipulator_uid = p.loadURDF(manipulator_file) elif manipulator_file.endswith('.sdf'): self.manipulator_uid = p.loadSDF(manipulator_file)[0] else: raise InvalidManipulatorFile('The file extension is neither .sdf nor .urdf') except p.error as err: logger.critical(err) raise InvalidManipulatorFile self.num_joints = p.getNumJoints(self.manipulator_uid) logger.debug(f'Robot Manipulator URDF/SDF file {manipulator_file} has been successfully loaded. ' f'The Robot Manipulator has {self.num_joints} joints, and its joints, ' f'together with the information of each, are:') data = list() for joint_ind in range(self.num_joints): joint_info = p.getJointInfo(self.manipulator_uid, joint_ind) data.append((joint_ind, joint_info[1].decode("utf-8"), joint_info[9], joint_info[8], joint_info[13])) # Print Joints info self.print_table(data) # Create obstacle with the shape of a sphere, and the target object with square shape self.obstacle = p.loadURDF('sphere_small.urdf', basePosition=self.obstacle_pos, useFixedBase=1, globalScaling=2.5) self.target = p.loadURDF('cube_small.urdf', basePosition=self.target_pos, useFixedBase=1, globalScaling=1) logger.debug(f'Both the obstacle and the target object have been generated in positions {self.obstacle_pos} ' f'and {self.target_pos} respectively') # 9 elements correspond to the 3 vector indicating the position of the target, end effector and obstacle # The other elements are the two arrays of the involved joint's position and velocities self._observation_space = np.zeros((9 + 2 * len(self.involved_joints),)) self._action_space = np.zeros((len(self.involved_joints),)) def reset(self, verbose: bool = True) -> NDArray: """ Resets the environment to a initial state.\n - If "initial_joint_positions" and "initial_positions_variation_range" are not set, all joints will be reset to the 0 position.\n - If only "initial_joint_positions" is set, the joints will be reset to those positions.\n - If only "initial_positions_variation_range" is set, the joints will be reset to 0 plus the variation noise.\n - If both "initial_joint_positions" and "initial_positions_variation_range" are set, the joints will be reset to the positions specified plus the variation noise. Args: verbose: Boolean indicating whether to print context information or not. Returns: New state reached after reset. """ if verbose: logger.info('Resetting Environment...') # Reset the robot's base position and orientation p.resetBasePositionAndOrientation(self.manipulator_uid, [0.000000, 0.000000, 0.000000], [0.000000, 0.000000, 0.000000, 1.000000]) if not self.initial_joint_positions and not self.initial_positions_variation_range: initial_state = [0 for _ in range(self.num_joints)] elif self.initial_joint_positions: if self.initial_positions_variation_range: initial_state = [random.uniform(pos - var, pos + var) for pos, var in zip(self.initial_joint_positions, self.initial_positions_variation_range)] else: initial_state = self.initial_joint_positions else: initial_state = [random.uniform(0 - var, 0 + var) for var in self.initial_positions_variation_range] for joint_index, pos in enumerate(initial_state): p.setJointMotorControl2(self.manipulator_uid, joint_index, controlMode=p.POSITION_CONTROL, targetPosition=pos) for _ in range(50): p.stepSimulation(self.physics_client) # Generate first state, and return it # The states are defined as {joint_pos, joint_vel, end-effector_pos, target_pos, obstacle_pos}, where # both joint_pos and joint_vel are arrays with the pos and vel of each joint new_state = self.get_state() if verbose: logger.info('Environment Reset') return new_state def is_terminal_state(self, target_threshold: float = 0.05, obstacle_threshold: float = 0., consider_autocollision: bool = False) -> int: """ Calculates if a terminal state is reached. Args: target_threshold: Threshold which delimits the terminal state. If the end-effector is closer to the target position than the threshold value, then a terminal state is reached. obstacle_threshold: Threshold which delimits the terminal state. If the end-effector is closer to the obstacle position than the threshold value, then a terminal state is reached. consider_autocollision: If set to True, the collision of any of the joints and parts of the manipulator with any other joint or part will be considered a terminal state. Returns: Integer (0 or 1) indicating whether the new state reached is a terminal state or not. """ # If the manipulator has a collision with the obstacle, the episode terminates if self.get_manipulator_obstacle_collisions(threshold=obstacle_threshold): logger.info('Collision detected, terminating episode...') return 1 # If the position of the end-effector is the same as the one of the target position, episode terminates if self.get_endeffector_target_collision(threshold=target_threshold)[0]: logger.info('The goal state has been reached, terminating episode...') return 1 # If the manipulator collides with itself, a terminal state is reached if consider_autocollision: self_distances = self.get_manipulator_collisions_with_itself() for distances in self_distances.values(): if (distances < 0).any(): logger.info('Auto-Collision detected, terminating episode...') return 1 return 0 def get_reward(self, consider_autocollision: bool = False) -> float: """ Computes the reward from the given state. Returns: Rewards:\n - If the end effector reaches the target position, a reward of +250 is returned.\n - If the end effector collides with the obstacle or with itself*, a reward of -1000 is returned.\n - Otherwise, the negative value of the distance from end effector to the target is returned.\n * The manipulator's collisions with itself are only considered if "consider_autocollision" parameter is set to True. """ # Auto-Collision is only calculated if requested self_collision = False if consider_autocollision: self_distances = self.get_manipulator_collisions_with_itself() for distances in self_distances.values(): if (distances < 0).any(): self_collision = True endeffector_target_collision, endeffector_target_dist = self.get_endeffector_target_collision(threshold=0.05) if endeffector_target_collision: return 250 elif self.get_manipulator_obstacle_collisions(threshold=0) or self_collision: return -1000 else: return -1 * float(endeffector_target_dist) def get_manipulator_obstacle_collisions(self, threshold: float) -> bool: """ Calculates if there is a collision between the manipulator and the obstacle. Args: threshold: If the distance between the end effector and the obstacle is below the "threshold", then it is considered a collision. Returns: Boolean indicating whether a collision occurred. """ joint_distances = list() for joint_ind in range(self.num_joints): end_effector_collision_obj = CollisionObject(body=self.manipulator_uid, link=joint_ind) collision_detector = CollisionDetector(collision_object=end_effector_collision_obj, obstacle_ids=[self.obstacle]) dist = collision_detector.compute_distances() joint_distances.append(dist[0]) joint_distances = np.array(joint_distances) return (joint_distances < threshold).any() def get_manipulator_collisions_with_itself(self) -> dict: """ Calculates the distances between each of the manipulator's joints and the other joints. Returns: Dictionary where each key is the index of a joint, and where each value is an array with the distances from that joint to any other joint in the manipulator. """ joint_distances = dict() for joint_ind in range(self.num_joints): joint_collision_obj = CollisionObject(body=self.manipulator_uid, link=joint_ind) collision_detector = CollisionDetector(collision_object=joint_collision_obj, obstacle_ids=[]) distances = collision_detector.compute_collisions_in_manipulator( affected_joints=[_ for _ in range(self.num_joints)], # all joints are taken into account max_distance=10 ) joint_distances[f'joint_{joint_ind}'] = distances return joint_distances def get_endeffector_target_collision(self, threshold: float) -> Tuple[bool, float]: """ Calculates if there are any collisions between the end effector and the target. Args: threshold: If the distance between the end effector and the target is below {threshold}, then it is considered a collision. Returns: Tuple where the first element is a boolean indicating whether a collision occurred, adn where the second is the distance from end effector to target minus the threshold. """ kuka_end_effector = CollisionObject(body=self.manipulator_uid, link=self.endeffector_index) collision_detector = CollisionDetector(collision_object=kuka_end_effector, obstacle_ids=[self.target]) dist = collision_detector.compute_distances() return (dist < threshold).any(), dist - threshold def get_state(self) -> NDArray: """ Retrieves information from the environment's current state. Returns: State as (joint_pos, joint_vel, end-effector_pos, target_pos, obstacle_pos):\n - The positions of the target, obstacle and end effector are given as 3D cartesian coordinates.\n - The joint positions and joint velocities are given as arrays of length equal to the number of joint involved in the training. """ joint_pos, joint_vel = list(), list() for joint_index in range(len(self.involved_joints)): joint_pos.append(p.getJointState(self.manipulator_uid, joint_index)[0]) joint_vel.append(p.getJointState(self.manipulator_uid, joint_index)[1]) end_effector_pos = p.getLinkState(self.manipulator_uid, self.endeffector_index)[0] end_effector_pos = list(end_effector_pos) state = np.hstack([np.array(joint_pos), np.array(joint_vel), np.array(end_effector_pos), np.array(self.target_pos), np.array(self.obstacle_pos)]) return state.astype(float) def step(self, action: NDArray) -> Tuple[NDArray, float, int]: """ Applies the action on the Robot's joints, so that each joint reaches the desired velocity for each involved joint. Args: action: Array where each element corresponds to the velocity to be applied on the joint with that same index. Returns: (new_state, reward, done) """ # Apply velocities on the involved joints according to action for joint_index, vel in zip(self.involved_joints, action): p.setJointMotorControl2(self.manipulator_uid, joint_index, p.VELOCITY_CONTROL, targetVelocity=vel, force=self.max_force) # Create constraint for fixed joints (maintain joint on fixed position) for joint_ind in self.fixed_joints: p.setJointMotorControl2(self.manipulator_uid, joint_ind, p.POSITION_CONTROL, targetPosition=0) # Perform actions on simulation p.stepSimulation(physicsClientId=self.physics_client) reward = self.get_reward() new_state = self.get_state() done = self.is_terminal_state() return new_state, reward, done @staticmethod def print_table(data: List[Tuple[int, str, float, float, tuple]]) -> None: """ Prints a table such that the elements received in the "data" parameter are displayed under "Index", "Name", "Upper Limit", "Lower Limit" and "Axis" columns. It is used to print the Manipulator's joint's information in an ordered manner. Args: data: List where each element contains all the information about a given joint. Each element on the list will be a tuple containing (index, name, upper_limit, lower_limit, axis). """ logger.debug('{:<6} {:<35} {:<15} {:<15} {:<15}'.format('Index', 'Name', 'Upper Limit', 'Lower Limit', 'Axis')) for index, name, up_limit, lo_limit, axis in data: logger.debug('{:<6} {:<35} {:<15} {:<15} {:<15}'.format(index, name, up_limit, lo_limit, str(axis))) @property def observation_space(self) -> np.ndarray: """ Getter for the observation space of the environment. Returns: Numpy array of zeros with same shape as the environment's states. """ return self._observation_space @property def action_space(self) -> np.ndarray: """ Getter for the action space of the environment. Returns: Numpy array of zeros with same shape as the environment's actions. """ return self._action_space
/robotic-manipulator-rloa-1.0.0.tar.gz/robotic-manipulator-rloa-1.0.0/robotic_manipulator_rloa/environment/environment.py
0.891025
0.58261
environment.py
pypi
import torch import torch.nn.functional as F from torch import nn, einsum from typing import List, Optional, Callable, Tuple from beartype import beartype from einops import pack, unpack, repeat, reduce, rearrange from einops.layers.torch import Rearrange, Reduce from functools import partial from classifier_free_guidance_pytorch import TextConditioner, AttentionTextConditioner, classifier_free_guidance # helpers def exists(val): return val is not None def default(val, d): return val if exists(val) else d def cast_tuple(val, length = 1): return val if isinstance(val, tuple) else ((val,) * length) def pack_one(x, pattern): return pack([x], pattern) def unpack_one(x, ps, pattern): return unpack(x, ps, pattern)[0] # sinusoidal positions def posemb_sincos_1d(seq, dim, temperature = 10000, device = None, dtype = torch.float32): n = torch.arange(seq, device = device) omega = torch.arange(dim // 2, device = device) / (dim // 2 - 1) omega = 1. / (temperature ** omega) n = n[:, None] * omega[None, :] pos_emb = torch.cat((n.sin(), n.cos()), dim = 1) return pos_emb.type(dtype) # helper classes class Residual(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x): return self.fn(x) + x class LayerNorm(nn.Module): def __init__(self, dim): super().__init__() self.gamma = nn.Parameter(torch.ones(dim)) self.register_buffer("beta", torch.zeros(dim)) def forward(self, x): return F.layer_norm(x, x.shape[-1:], self.gamma, self.beta) class FeedForward(nn.Module): def __init__(self, dim, mult = 4, dropout = 0.): super().__init__() inner_dim = int(dim * mult) self.norm = LayerNorm(dim) self.net = nn.Sequential( nn.Linear(dim, inner_dim), nn.GELU(), nn.Dropout(dropout), nn.Linear(inner_dim, dim), nn.Dropout(dropout) ) def forward(self, x, cond_fn = None): x = self.norm(x) if exists(cond_fn): # adaptive layernorm x = cond_fn(x) return self.net(x) # MBConv class SqueezeExcitation(nn.Module): def __init__(self, dim, shrinkage_rate = 0.25): super().__init__() hidden_dim = int(dim * shrinkage_rate) self.gate = nn.Sequential( Reduce('b c h w -> b c', 'mean'), nn.Linear(dim, hidden_dim, bias = False), nn.SiLU(), nn.Linear(hidden_dim, dim, bias = False), nn.Sigmoid(), Rearrange('b c -> b c 1 1') ) def forward(self, x): return x * self.gate(x) class MBConvResidual(nn.Module): def __init__(self, fn, dropout = 0.): super().__init__() self.fn = fn self.dropsample = Dropsample(dropout) def forward(self, x): out = self.fn(x) out = self.dropsample(out) return out + x class Dropsample(nn.Module): def __init__(self, prob = 0): super().__init__() self.prob = prob def forward(self, x): device = x.device if self.prob == 0. or (not self.training): return x keep_mask = torch.FloatTensor((x.shape[0], 1, 1, 1), device = device).uniform_() > self.prob return x * keep_mask / (1 - self.prob) def MBConv( dim_in, dim_out, *, downsample, expansion_rate = 4, shrinkage_rate = 0.25, dropout = 0. ): hidden_dim = int(expansion_rate * dim_out) stride = 2 if downsample else 1 net = nn.Sequential( nn.Conv2d(dim_in, hidden_dim, 1), nn.BatchNorm2d(hidden_dim), nn.GELU(), nn.Conv2d(hidden_dim, hidden_dim, 3, stride = stride, padding = 1, groups = hidden_dim), nn.BatchNorm2d(hidden_dim), nn.GELU(), SqueezeExcitation(hidden_dim, shrinkage_rate = shrinkage_rate), nn.Conv2d(hidden_dim, dim_out, 1), nn.BatchNorm2d(dim_out) ) if dim_in == dim_out and not downsample: net = MBConvResidual(net, dropout = dropout) return net # attention related classes class Attention(nn.Module): def __init__( self, dim, dim_head = 32, dropout = 0., window_size = 7 ): super().__init__() assert (dim % dim_head) == 0, 'dimension should be divisible by dimension per head' self.norm = LayerNorm(dim) self.heads = dim // dim_head self.scale = dim_head ** -0.5 self.to_qkv = nn.Linear(dim, dim * 3, bias = False) self.attend = nn.Sequential( nn.Softmax(dim = -1), nn.Dropout(dropout) ) self.to_out = nn.Sequential( nn.Linear(dim, dim, bias = False), nn.Dropout(dropout) ) # relative positional bias self.rel_pos_bias = nn.Embedding((2 * window_size - 1) ** 2, self.heads) pos = torch.arange(window_size) grid = torch.stack(torch.meshgrid(pos, pos, indexing = 'ij')) grid = rearrange(grid, 'c i j -> (i j) c') rel_pos = rearrange(grid, 'i ... -> i 1 ...') - rearrange(grid, 'j ... -> 1 j ...') rel_pos += window_size - 1 rel_pos_indices = (rel_pos * torch.tensor([2 * window_size - 1, 1])).sum(dim = -1) self.register_buffer('rel_pos_indices', rel_pos_indices, persistent = False) def forward(self, x): batch, height, width, window_height, window_width, _, device, h = *x.shape, x.device, self.heads x = self.norm(x) # flatten x = rearrange(x, 'b x y w1 w2 d -> (b x y) (w1 w2) d') # project for queries, keys, values q, k, v = self.to_qkv(x).chunk(3, dim = -1) # split heads q, k, v = map(lambda t: rearrange(t, 'b n (h d ) -> b h n d', h = h), (q, k, v)) # scale q = q * self.scale # sim sim = einsum('b h i d, b h j d -> b h i j', q, k) # add positional bias bias = self.rel_pos_bias(self.rel_pos_indices) sim = sim + rearrange(bias, 'i j h -> h i j') # attention attn = self.attend(sim) # aggregate out = einsum('b h i j, b h j d -> b h i d', attn, v) # merge heads out = rearrange(out, 'b h (w1 w2) d -> b w1 w2 (h d)', w1 = window_height, w2 = window_width) # combine heads out out = self.to_out(out) return rearrange(out, '(b x y) ... -> b x y ...', x = height, y = width) class MaxViT(nn.Module): def __init__( self, *, num_classes, dim, depth, dim_head = 32, dim_conv_stem = None, window_size = 7, mbconv_expansion_rate = 4, mbconv_shrinkage_rate = 0.25, dropout = 0.1, channels = 3 ): super().__init__() assert isinstance(depth, tuple), 'depth needs to be tuple if integers indicating number of transformer blocks at that stage' # convolutional stem dim_conv_stem = default(dim_conv_stem, dim) self.conv_stem = nn.Sequential( nn.Conv2d(channels, dim_conv_stem, 3, stride = 2, padding = 1), nn.Conv2d(dim_conv_stem, dim_conv_stem, 3, padding = 1) ) # variables num_stages = len(depth) dims = tuple(map(lambda i: (2 ** i) * dim, range(num_stages))) dims = (dim_conv_stem, *dims) dim_pairs = tuple(zip(dims[:-1], dims[1:])) self.layers = nn.ModuleList([]) # shorthand for window size for efficient block - grid like attention w = window_size # iterate through stages cond_hidden_dims = [] for ind, ((layer_dim_in, layer_dim), layer_depth) in enumerate(zip(dim_pairs, depth)): for stage_ind in range(layer_depth): is_first = stage_ind == 0 stage_dim_in = layer_dim_in if is_first else layer_dim cond_hidden_dims.append(stage_dim_in) block = nn.Sequential( MBConv( stage_dim_in, layer_dim, downsample = is_first, expansion_rate = mbconv_expansion_rate, shrinkage_rate = mbconv_shrinkage_rate ), Rearrange('b d (x w1) (y w2) -> b x y w1 w2 d', w1 = w, w2 = w), # block-like attention Residual(Attention(dim = layer_dim, dim_head = dim_head, dropout = dropout, window_size = w)), Residual(FeedForward(dim = layer_dim, dropout = dropout)), Rearrange('b x y w1 w2 d -> b d (x w1) (y w2)'), Rearrange('b d (w1 x) (w2 y) -> b x y w1 w2 d', w1 = w, w2 = w), # grid-like attention Residual(Attention(dim = layer_dim, dim_head = dim_head, dropout = dropout, window_size = w)), Residual(FeedForward(dim = layer_dim, dropout = dropout)), Rearrange('b x y w1 w2 d -> b d (w1 x) (w2 y)'), ) self.layers.append(block) embed_dim = dims[-1] self.embed_dim = dims[-1] self.cond_hidden_dims = cond_hidden_dims # mlp head out self.mlp_head = nn.Sequential( Reduce('b d h w -> b d', 'mean'), LayerNorm(embed_dim), nn.Linear(embed_dim, num_classes) ) @beartype def forward( self, x, texts: Optional[List[str]] = None, cond_fns: Optional[Tuple[Callable, ...]] = None, cond_drop_prob = 0., return_embeddings = False ): x = self.conv_stem(x) if not exists(cond_fns): cond_fns = (None,) * len(self.layers) for stage, cond_fn in zip(self.layers, cond_fns): if exists(cond_fn): x = cond_fn(x) x = stage(x) if return_embeddings: return x return self.mlp_head(x) # attention class TransformerAttention(nn.Module): def __init__( self, dim, causal = False, dim_head = 64, dim_context = None, heads = 8, norm_context = False, dropout = 0.1 ): super().__init__() self.heads = heads self.scale = dim_head ** -0.5 self.causal = causal inner_dim = dim_head * heads dim_context = default(dim_context, dim) self.norm = LayerNorm(dim) self.context_norm = LayerNorm(dim_context) if norm_context else nn.Identity() self.attn_dropout = nn.Dropout(dropout) self.to_q = nn.Linear(dim, inner_dim, bias = False) self.to_kv = nn.Linear(dim_context, dim_head * 2, bias = False) self.to_out = nn.Sequential( nn.Linear(inner_dim, dim, bias = False), nn.Dropout(dropout) ) def forward( self, x, context = None, mask = None, attn_bias = None, attn_mask = None, cond_fn: Optional[Callable] = None ): b = x.shape[0] if exists(context): context = self.context_norm(context) kv_input = default(context, x) x = self.norm(x) if exists(cond_fn): # adaptive layer-norm x = cond_fn(x) q, k, v = self.to_q(x), *self.to_kv(kv_input).chunk(2, dim = -1) q = rearrange(q, 'b n (h d) -> b h n d', h = self.heads) q = q * self.scale sim = einsum('b h i d, b j d -> b h i j', q, k) if exists(attn_bias): sim = sim + attn_bias if exists(attn_mask): sim = sim.masked_fill(~attn_mask, -torch.finfo(sim.dtype).max) if exists(mask): mask = rearrange(mask, 'b j -> b 1 1 j') sim = sim.masked_fill(~mask, -torch.finfo(sim.dtype).max) if self.causal: i, j = sim.shape[-2:] causal_mask = torch.ones((i, j), dtype = torch.bool, device = x.device).triu(j - i + 1) sim = sim.masked_fill(causal_mask, -torch.finfo(sim.dtype).max) attn = sim.softmax(dim = -1) attn = self.attn_dropout(attn) out = einsum('b h i j, b j d -> b h i d', attn, v) out = rearrange(out, 'b h n d -> b n (h d)') return self.to_out(out) @beartype class Transformer(nn.Module): def __init__( self, dim, dim_head = 64, heads = 8, depth = 6, attn_dropout = 0., ff_dropout = 0. ): super().__init__() self.layers = nn.ModuleList([]) for _ in range(depth): self.layers.append(nn.ModuleList([ TransformerAttention(dim = dim, heads = heads, dropout = attn_dropout), FeedForward(dim = dim, dropout = ff_dropout) ])) def forward( self, x, cond_fns: Optional[Tuple[Callable, ...]] = None, attn_mask = None ): if not exists(cond_fns): cond_fns = (None,) * len(self.layers * 2) cond_fns = iter(cond_fns) for attn, ff in self.layers: x = attn(x, attn_mask = attn_mask, cond_fn = next(cond_fns)) + x x = ff(x, cond_fn = next(cond_fns)) + x return x # token learner module class TokenLearner(nn.Module): """ https://arxiv.org/abs/2106.11297 using the 1.1 version with the MLP (2 dense layers with gelu) for generating attention map """ def __init__( self, *, dim, ff_mult = 2, num_output_tokens = 8, num_layers = 2 ): super().__init__() inner_dim = dim * ff_mult * num_output_tokens self.num_output_tokens = num_output_tokens self.net = nn.Sequential( nn.Conv2d(dim * num_output_tokens, inner_dim, 1, groups = num_output_tokens), nn.GELU(), nn.Conv2d(inner_dim, num_output_tokens, 1, groups = num_output_tokens), ) def forward(self, x): x, ps = pack_one(x, '* c h w') x = repeat(x, 'b c h w -> b (g c) h w', g = self.num_output_tokens) attn = self.net(x) attn = rearrange(attn, 'b g h w -> b 1 g h w') x = rearrange(x, 'b (g c) h w -> b c g h w', g = self.num_output_tokens) x = reduce(x * attn, 'b c g h w -> b c g', 'mean') x = unpack_one(x, ps, '* c n') return x # Robotic Transformer @beartype class RT1(nn.Module): def __init__( self, *, vit: MaxViT, num_actions = 11, action_bins = 256, depth = 6, heads = 8, dim_head = 64, token_learner_ff_mult = 2, token_learner_num_layers = 2, token_learner_num_output_tokens = 8, cond_drop_prob = 0.2, use_attn_conditioner = False, conditioner_kwargs: dict = dict() ): super().__init__() self.vit = vit self.num_vit_stages = len(vit.cond_hidden_dims) conditioner_klass = AttentionTextConditioner if use_attn_conditioner else TextConditioner self.conditioner = conditioner_klass( hidden_dims = (*tuple(vit.cond_hidden_dims), *((vit.embed_dim,) * depth * 2)), hiddens_channel_first = (*((True,) * self.num_vit_stages), *((False,) * depth * 2)), cond_drop_prob = cond_drop_prob, **conditioner_kwargs ) self.token_learner = TokenLearner( dim = vit.embed_dim, ff_mult = token_learner_ff_mult, num_output_tokens = token_learner_num_output_tokens, num_layers = token_learner_num_layers ) self.num_learned_tokens = token_learner_num_output_tokens self.transformer_depth = depth self.transformer = Transformer( dim = vit.embed_dim, dim_head = dim_head, heads = heads, depth = depth ) self.cond_drop_prob = cond_drop_prob self.to_logits = nn.Sequential( LayerNorm(vit.embed_dim), nn.Linear(vit.embed_dim, num_actions * action_bins), Rearrange('... (a b) -> ... a b', b = action_bins) ) @classifier_free_guidance def forward( self, video, texts: Optional[List[str]] = None, cond_drop_prob = 0. ): depth = self.transformer_depth cond_drop_prob = default(cond_drop_prob, self.cond_drop_prob) frames, device = video.shape[2], video.device cond_fns = self.conditioner( texts, cond_drop_prob = cond_drop_prob, repeat_batch = (*((frames,) * self.num_vit_stages), *((1,) * self.transformer_depth * 2)) ) vit_cond_fns, transformer_cond_fns = cond_fns[:-(depth * 2)], cond_fns[-(depth * 2):] video = rearrange(video, 'b c f h w -> b f c h w') images, packed_shape = pack_one(video, '* c h w') tokens = self.vit( images, texts = texts, cond_fns = vit_cond_fns, cond_drop_prob = cond_drop_prob, return_embeddings = True ) tokens = unpack_one(tokens, packed_shape, '* c h w') learned_tokens = self.token_learner(tokens) learned_tokens = rearrange(learned_tokens, 'b f c n -> b (f n) c') # causal attention mask attn_mask = torch.ones((frames, frames), dtype = torch.bool, device = device).triu(1) attn_mask = repeat(attn_mask, 'i j -> (i r1) (j r2)', r1 = self.num_learned_tokens, r2 = self.num_learned_tokens) # sinusoidal positional embedding pos_emb = posemb_sincos_1d(frames, learned_tokens.shape[-1], dtype = learned_tokens.dtype, device = learned_tokens.device) learned_tokens = learned_tokens + repeat(pos_emb, 'n d -> (n r) d', r = self.num_learned_tokens) # attention attended_tokens = self.transformer(learned_tokens, cond_fns = transformer_cond_fns, attn_mask = ~attn_mask) pooled = reduce(attended_tokens, 'b (f n) d -> b f d', 'mean', f = frames) logits = self.to_logits(pooled) return logits
/robotic-transformer-pytorch-0.0.16.tar.gz/robotic-transformer-pytorch-0.0.16/robotic_transformer_pytorch/robotic_transformer_pytorch.py
0.951346
0.493226
robotic_transformer_pytorch.py
pypi
import ctypes from functools import partial from numpy import sum from pypot.creatures import AbstractPoppyCreature from .primitives.dance import Dance from .primitives.mirror import Mirror from .primitives.rest_pos import Pos class RoboticiaFirst(AbstractPoppyCreature): @classmethod def setup(cls, robot): robot._primitive_manager._filter = partial(sum, axis=0) for m in robot.motors: m.goto_behavior = 'dummy' m.moving_speed = 0 robot.attach_primitive(Dance(robot), 'dance') robot.attach_primitive(Mirror(robot,50), 'mirror') robot.attach_primitive(Pos(robot), 'pos') if robot.simulated: cls.vrep_hack(robot) cls.add_vrep_methods(robot) @classmethod def vrep_hack(cls, robot): # fix vrep orientation bug wrong_motor = [robot.m3, robot.m2] for m in wrong_motor: m.direct = not m.direct #m.offset = -m.offset # use minjerk to simulate speed in vrep for m in robot.motors: m.goto_behavior = 'minjerk' @classmethod def add_vrep_methods(cls, robot): from pypot.vrep.controller import VrepController from pypot.vrep.io import remote_api def set_vrep_force(robot, vector_force, shape_name): """ Set a force to apply on the robot. """ vrep_io = next(c for c in robot._controllers if isinstance(c, VrepController)).io raw_bytes = (ctypes.c_ubyte * len(shape_name)).from_buffer_copy(shape_name) vrep_io.call_remote_api('simxSetStringSignal', 'shape', raw_bytes, sending=True) packedData = remote_api.simxPackFloats(vector_force) raw_bytes = (ctypes.c_ubyte * len(packedData)).from_buffer_copy(packedData) vrep_io.call_remote_api('simxSetStringSignal', 'force', raw_bytes, sending=True) robot.set_vrep_force = partial(set_vrep_force, robot)
/roboticia-first-1.0.2.tar.gz/roboticia-first-1.0.2/roboticia_first/roboticia_first.py
0.424651
0.235845
roboticia_first.py
pypi
import os import sys import numpy import ctypes from functools import partial from pypot.creatures import AbstractPoppyCreature from pypot.robot.controller import SensorsController from pypot.robot.sensor import Sensor from pypot.sensor import ArduinoSensor from .primitives.leg import Leg from .primitives.start_posture import StartPosture class ForceSensor(Sensor): """ Define a phidget force sensor """ def __init__(self, name, arduino): Sensor.__init__(self, name) self._arduino = arduino def __repr__(self): return ('<ForceSensor name={self.name} ' 'force = {self.force}>').format(self=self) def close(self): self._arduino.close() @property def force(self): return self._arduino.sensor_dict[self.name] class VrepForceSensor(Sensor): """ Define a vrep force sensor """ def __init__(self, name): Sensor.__init__(self, name) self.force = 0.0 def __repr__(self): return ('<ForceSensor name={self.name} ' 'force = {self.force}>').format(self=self) class VrepForceController(SensorsController): """ Update the value of the force sensor read in Vrep """ def setup(self): """ Forces a first update to trigger V-REP streaming. """ self.update() def update(self): """ Update the value of the force sensor. """ for s in self.sensors: s.force = self.io.call_remote_api('simxReadForceSensor', self.io.get_object_handle(s.name), streaming=True)[1][2]*100 class RoboticiaQuattro(AbstractPoppyCreature): @classmethod def setup(cls, robot): robot.attach_primitive(Leg(robot,'leg1'), 'leg_1') robot.attach_primitive(Leg(robot,'leg2'), 'leg_2') robot.attach_primitive(Leg(robot,'leg3'), 'leg_3') robot.attach_primitive(Leg(robot,'leg4'), 'leg_4') robot.attach_primitive(StartPosture(robot,3), 'start_posture') if robot.simulated : from pypot.vrep.controller import VrepController vrep_io = next(c for c in robot._controllers if isinstance(c, VrepController)).io sensors = [VrepForceSensor(name) for name in ('f1','f2','f3','f4')] vfc = VrepForceController(vrep_io, sensors) vfc.start() robot._sensors.extend(vfc.sensors) for s in vfc.sensors : setattr(robot, s.name, s) cls.vrep_hack(robot) cls.add_vrep_methods(robot) else : arduino = ArduinoSensor('arduino','/dev/ttyUSB0',115200) arduino.start() sensors = [ForceSensor(name, arduino) for name in ('f1','f2','f3','f4')] robot._sensors.extend(sensors) for s in sensors : setattr(robot, s.name, s) for m in robot.motors : m.pid = (6.0,10.0,0.0) @classmethod def vrep_hack(cls, robot): # fix vrep orientation bug wrong_motor = [robot.m13,robot.m23,robot.m33,robot.m43] for m in wrong_motor: m.direct = not m.direct m.offset = -m.offset @classmethod def add_vrep_methods(cls, robot): from pypot.vrep.io import remote_api def set_vrep_force(robot, vector_force, shape_name): """ Set a force to apply on the robot. """ raw_bytes = (ctypes.c_ubyte * len(shape_name)).from_buffer_copy(shape_name) vrep_io.call_remote_api('simxSetStringSignal', 'shape', raw_bytes, sending=True) packedData = remote_api.simxPackFloats(vector_force) raw_bytes = (ctypes.c_ubyte * len(packedData)).from_buffer_copy(packedData) vrep_io.call_remote_api('simxSetStringSignal', 'force', raw_bytes, sending=True) robot.set_vrep_force = partial(set_vrep_force, robot)
/roboticia-quattro-1.0.3.tar.gz/roboticia-quattro-1.0.3/roboticia_quattro/roboticia_quattro.py
0.53777
0.180269
roboticia_quattro.py
pypi
## Roboticia-quattro : Tutorial 1 - the leg primitive ### How to move the legs using Pypot Primitives Instanciate the robot : ``` from pypot.creatures import RoboticiaQuattro ``` If you want to open your robot in the Vrep simulator (http://www.coppeliarobotics.com/) : ``` robot = RoboticiaQuattro(simulator='vrep') ``` If you are lucky enough to have a real robot (http://www.roboticia.com) : ``` robot = RoboticiaQuattro() ``` Your robot have motors and sensors : ``` robot.motors robot.sensors ``` For a real robot, when starting a robot, the motors are compliant. You need to make your robot stiff : ``` robot.compliant = False ``` Go to the start position for your robot : ``` robot.m12.goto_position(-20,3) robot.m22.goto_position(-20,3) robot.m32.goto_position(20,3) robot.m42.goto_position(20,3) robot.m13.goto_position(20,3) robot.m23.goto_position(20,3) robot.m33.goto_position(-20,3) robot.m43.goto_position(-20,3) ``` Obviously you can access the motors and change angles, but if you do so without any control, pretty sure your robot will fall ! ``` robot.m12.goto_position(-80,2) ``` In a vrep simulated environnement you can restart the simulation : ``` robot.reset_simulation() ``` It is why, you need a model to control the legs. For the inverse kinematic model of the leg, we are using the cosinus law. Each leg is like a triangle, and thanks to the cosinus law you can resolve the triangle : https://en.wikipedia.org/wiki/Law_of_cosines ``` import math as mt import time def AK_side(side_a,side_b,side_c): """ Take the 3 side of a triangle and return the angles """ try : alpha = mt.acos((side_b**2 + side_c**2 - side_a**2)/(2*side_b*side_c)) beta = mt.acos((side_a**2 + side_c**2 - side_b**2)/(2*side_a*side_c)) gamma = mt.pi - alpha - beta except ValueError : return (False,0,0,0) else : return (True,alpha,beta,gamma) def AK_angle(side_a,side_b,gamma): """ Take 2 sides and 1 angle of a triangle and return the missing angles and sides """ side_c = mt.sqrt (side_a**2 + side_b**2 - 2*side_a*side_b*mt.cos(gamma)) alpha = mt.acos((side_b**2 + side_c**2 - side_a**2)/(2*side_b*side_c)) beta= mt.pi - alpha - gamma return (side_c,alpha,beta) ``` The Leg primitive will now make the link between 4 attributes of the leg (h, d, b, f) and the right angles for the 3 motors. The loop is updated at a given frequency. In our example, we use an update frequncy of 50 Hz. ``` from pypot.primitive import LoopPrimitive class Leg(LoopPrimitive): def __init__(self,robot,leg,refresh_freq=50): self.robot = robot LoopPrimitive.__init__(self, robot,refresh_freq) # you should never access directly to the motors in a primitive, because this is the goal of the Primitives manager # to manage this acces for all the primitives : https://poppy-project.github.io/pypot/primitive.html fake_motors = getattr(self.robot, leg) self.knee = fake_motors[2] self.hip = fake_motors[1] self.hip_lateral = fake_motors[0] self.motors = fake_motors # size of segment's leg self.shin = 63 self.thigh = 55 self.pelvis = 38 @property def get_pos(self): (side_c,alpha,beta) = AK_angle(self.thigh,self.shin,mt.pi-abs(mt.radians(self.knee.present_position))) # what knee flexion flex = mt.copysign(1,self.knee.present_position) # calcul de l'angle beta_2 entre side_c et la veticale beta_2 = mt.radians(self.hip.present_position)+beta*flex theta = mt.radians(self.hip_lateral.present_position) high_leg = mt.cos(beta_2)*side_c+self.pelvis high = mt.cos(theta)*high_leg distance = mt.sin(beta_2)*side_c balance = mt.sin(theta)*high_leg return (high,distance,flex,balance) def set_pos(self,h,d,b): high_leg = mt.sqrt(h**2+b**2) side_c = mt.sqrt((high_leg-self.pelvis)**2+d**2) beta_2 = mt.asin(d/side_c) (status,alpha,beta,gamma) = AK_side(self.thigh,self.shin,side_c) angle_hip = mt.degrees(beta_2 - beta*self.f) angle_knee = self.f*mt.degrees(mt.pi - gamma) angle_hip_lateral = mt.degrees(mt.asin(b/high_leg)) return(status,angle_hip_lateral, angle_hip, angle_knee) def h_limit(self,d): pass def d_limit(self,h): pass def setup(self): (self.h,self.d,self.f,self.b) = self.get_pos def update(self): (status,angle_hip_lateral, angle_hip, angle_knee) = self.set_pos(self.h,self.d,self.b) if status : self.hip.goal_position = angle_hip self.knee.goal_position = angle_knee self.hip_lateral.goal_position = angle_hip_lateral else : print('invalid range') self.setup() def move(self,speed,cycle,*args): if cycle == 'go': if len(args)>0 and self.d+speed > args[0] : #multiplier par le signe de la vitesse pour gérer les vitesses négatives self.d = args[0] return True else : self.d += speed return False if cycle == 'back': if self.h-speed > args[0] and self.d-speed > args[1] : self.d -= speed self.h -= speed return False if self.d-speed > args[1] : self.h = args[0] self.d -= speed return False if self.h+speed < args[2] : self.d = args[1] self.h += speed return False else : self.h = args[2] return True if cycle == 'balance': if len(args)>0 and mt.copysign(1,speed)*(self.b+speed) > mt.copysign(1,speed)*args[0] : #multiplier par le signe de la vitesse pour gérer les vitesses négatives self.b = args[0] return True else : self.b += speed return False if cycle=='release': if self.h-speed < limit : #multiplier par le signe de la vitesse pour gérer les vitesses négatives self.h = limit return True else : self.h -= speed return False ``` Attach one primitive for each leg to the robot : ``` robot.attach_primitive(Leg(robot,'leg1'), 'leg_1') robot.attach_primitive(Leg(robot,'leg2'), 'leg_2') robot.attach_primitive(Leg(robot,'leg3'), 'leg_3') robot.attach_primitive(Leg(robot,'leg4'), 'leg_4') ``` Now start the primitives to start the control of the legs : ``` robot.leg_1.start() robot.leg_2.start() robot.leg_3.start() robot.leg_4.start() ``` You are now able to choose for each leg (in millimeters) : * h : the high of the leg * d : the distance between horizontal of the hip and the foot (front or rear) * b : the balance on right or left * f : the knee flexion (1 or -1) ``` # move aside the legs robot.leg_1.b = -20 robot.leg_3.b = -20 robot.leg_2.b = 20 robot.leg_4.b = 20 # get down robot.leg_1.h = 100 robot.leg_3.h = 100 robot.leg_2.h = 100 robot.leg_4.h = 100 # get up robot.leg_1.h = 150 robot.leg_3.h = 150 robot.leg_2.h = 150 robot.leg_4.h = 150 ``` Try to jump : ``` for i in range(5): robot.leg_1.h = 100 robot.leg_3.h = 100 robot.leg_2.h = 100 robot.leg_4.h = 100 time.sleep(0.5) robot.leg_1.h = 150 robot.leg_3.h = 150 robot.leg_2.h = 150 robot.leg_4.h = 150 time.sleep(0.5) ``` Because motors can delivered high power, you can check the temperatue of the motors. Motors will get disable above to 60°C. ``` for m in robot.motors : print('Motor {} : {}'.format(m.name, m.present_temperature)) for i in range(3): robot.leg_1.h = 120 robot.leg_3.h = 120 robot.leg_2.h = 120 robot.leg_4.h = 120 #go ahead robot.leg_1.d = -50 robot.leg_3.d = -50 robot.leg_2.d = -50 robot.leg_4.d = -50 time.sleep(0.5) # jump robot.leg_1.d = 50 robot.leg_3.d = 50 robot.leg_2.d = 50 robot.leg_4.d = 50 time.sleep(0.5) robot.leg_1.stop() robot.leg_2.stop() robot.leg_3.stop() robot.leg_4.stop() ``` In a vrep simulated environnement you always stop and restart the simulation : ``` robot.stop_simulation() robot.start_simulation() ``` To close your robot properly : ``` robot.close() ``` In case of trouble, for example if your robot doesnt' answer to command, you can restart the python kernel : Menu > Kernel > Restart
/roboticia-quattro-1.0.3.tar.gz/roboticia-quattro-1.0.3/roboticia_quattro/tutorial/Roboticia_quattro_tutorial_1.ipynb
0.514644
0.97801
Roboticia_quattro_tutorial_1.ipynb
pypi
import math as mt from pypot.primitive import LoopPrimitive class Leg(LoopPrimitive): def __init__(self,robot,leg,refresh_freq=50): LoopPrimitive.__init__(self, robot,refresh_freq) # you should never access directly to the motors in a primitive, because this is the goal of the Primitives manager # to manage this acces for all the primitives : https://poppy-project.github.io/pypot/primitive.html fake_motors = getattr(self.robot, leg) self.knee = fake_motors[2] self.hip = fake_motors[1] self.hip_lateral = fake_motors[0] self.motors = fake_motors # size of segment's leg self.shin = 63 self.thigh = 55 self.pelvis = 38 def __repr__(self): return ('<Primitive name={self.name}>').format(self=self) @classmethod def AK_side(cls, side_a,side_b,side_c): """ Take the 3 side of a triangle and return the angles """ try : alpha = mt.acos((side_b**2 + side_c**2 - side_a**2)/(2*side_b*side_c)) beta = mt.acos((side_a**2 + side_c**2 - side_b**2)/(2*side_a*side_c)) gamma = mt.pi - alpha - beta except ValueError : return (False,0,0,0) else : return (True,alpha,beta,gamma) @classmethod def AK_angle(cls, side_a,side_b,gamma): """ Take 2 sides and 1 angle of a triangle and return the missing angles and sides """ side_c = mt.sqrt (side_a**2 + side_b**2 - 2*side_a*side_b*mt.cos(gamma)) alpha = mt.acos((side_b**2 + side_c**2 - side_a**2)/(2*side_b*side_c)) beta= mt.pi - alpha - gamma return (side_c,alpha,beta) @property def get_pos(self): (side_c,alpha,beta) = Leg.AK_angle(self.thigh,self.shin,mt.pi-abs(mt.radians(self.knee.present_position))) # what knee flexion flex = mt.copysign(1,self.knee.present_position) # calcul de l'angle beta_2 entre side_c et la veticale beta_2 = mt.radians(self.hip.present_position)+beta*flex theta = mt.radians(self.hip_lateral.present_position) high_leg = mt.cos(beta_2)*side_c+self.pelvis high = mt.cos(theta)*high_leg distance = mt.sin(beta_2)*side_c balance = mt.sin(theta)*high_leg return (high,distance,flex,balance) def set_pos(self,h,d,b): high_leg = mt.sqrt(h**2+b**2) side_c = mt.sqrt((high_leg-self.pelvis)**2+d**2) beta_2 = mt.asin(d/side_c) (status,alpha,beta,gamma) = Leg.AK_side(self.thigh,self.shin,side_c) angle_hip = mt.degrees(beta_2 - beta*self.f) angle_knee = self.f*mt.degrees(mt.pi - gamma) angle_hip_lateral = mt.degrees(mt.asin(b/high_leg)) return(status,angle_hip_lateral, angle_hip, angle_knee) def h_limit(self,d): pass def d_limit(self,h): pass def setup(self): (self.h,self.d,self.f,self.b) = self.get_pos def update(self): (status,angle_hip_lateral, angle_hip, angle_knee) = self.set_pos(self.h,self.d,self.b) if status : self.hip.goal_position = angle_hip self.knee.goal_position = angle_knee self.hip_lateral.goal_position = angle_hip_lateral else : print('invalid range') self.setup() def move(self,speed,cycle,*args): if cycle == 'go': if len(args)>0 and self.d+speed > args[0] : #multiplier par le signe de la vitesse pour gérer les vitesses négatives self.d = args[0] return True else : self.d += speed return False if cycle == 'back': if self.h-speed > args[0] and self.d-speed > args[1] : self.d -= speed self.h -= speed return False if self.d-speed > args[1] : self.h = args[0] self.d -= speed return False if self.h+speed < args[2] : self.d = args[1] self.h += speed return False else : self.h = args[2] return True if cycle == 'balance': if len(args)>0 and mt.copysign(1,speed)*(self.b+speed) > mt.copysign(1,speed)*args[0] : #multiplier par le signe de la vitesse pour gérer les vitesses négatives self.b = args[0] return True else : self.b += speed return False if cycle=='release': if self.h-speed < limit : #multiplier par le signe de la vitesse pour gérer les vitesses négatives self.h = limit return True else : self.h -= speed return False
/roboticia-quattro-1.0.3.tar.gz/roboticia-quattro-1.0.3/roboticia_quattro/primitives/leg.py
0.59972
0.422326
leg.py
pypi
# Record, Save and Play Moves on Poppy Ergo Jr This notebook intends to show you how to: * **record** movements using physical demonstrations, * **replay** those movements and sequence them, * **save** them to the hard drive and reload them. An illustration can be seen in the following video: ``` from IPython.display import YouTubeVideo YouTubeVideo('DJHOopBgPqs') ``` You will need a working and correctly setup Poppy Ergo Jr to follow this notebook. As we will use physical demonstration, you can not use a simulated robot. Yet the same methods could be used on simulation if you are using other kind of demonstration (e.g. programatically). ``` # Import some matplolib and numpy shortcuts for Jupyter notebook %matplotlib inline from __future__ import print_function import numpy as np import matplotlib.pyplot as plt ``` ## Connect to your Poppy Ergo Jr Using the usual Python code: ``` from pypot.creatures import PoppyErgoJr poppy = PoppyErgoJr() ``` We then put it in its rest position. We will use it as our working base: ``` poppy.rest_posture.start() ``` ## Record movements First, we need to import the *MoveRecorder* object that can be used to record any movements on a Poppy robot. It works with all robots including the Poppy Ergo Jr. ``` from pypot.primitive.move import MoveRecorder ``` To create this recorder we need some extra information: * on which **robot** to record the movements * at which **frequency** the positions need to be retrieved (50Hz is a good default values) * which **motors** are we actually recording (you can record a movement on a subpart of your robot) ``` recorder = MoveRecorder(poppy, 50, poppy.tip) ``` As you can see we used the motor group *poppy.tip* as the list of motors to be recorded. It is equivalent to use the list of motors *[poppy.m4, poppy.m5, poppy.m6]*. ``` poppy.tip == [poppy.m4, poppy.m5, poppy.m6] ``` Before actually recording a movement, we need to set the used motors compliant so they can be freely moved: ``` for m in poppy.tip: m.compliant = True ``` Now the tip of the Poppy Ergo Jr should be free while the base is still stiff. **Even if the motors are free, they can still be used as sensor**. This means that you can record their present position even if you make them move by hand. The recorder can be start and stop when you want. In the interval the positions of every selected motors will be recorded at the predefined frequency. So, prepare yourself to record your cool move! To start the record: ``` recorder.start() ``` Now move the robot! When you are done, you can stop the record: ``` recorder.stop() ``` The move you just recorded can be accessed via: ``` recorder.move ``` You can get the number of key frames that have been recorded: ``` print('{} key frames have been recorded.'.format(len(recorder.move.positions()))) ``` Let's store this move in a variable (we copy it to not erase it when we will do another record): ``` from copy import deepcopy my_first_move = deepcopy(recorder.move) ``` You can also plot a move to see what it looks like: ``` ax = axes() my_first_move.plot(ax) ``` Now, let's record another move. This time we will record for 10 seconds and on the whole robot. You can easily do that using the following code: First we recreate a recorder object with all motors. We also turn all motors compliant: ``` recorder = MoveRecorder(poppy, 50, poppy.motors) for m in poppy.motors: m.compliant = True ``` And then record for 10 seconds: ``` import time recorder.start() time.sleep(10) recorder.stop() ``` Now that the record is done, we also store it: ``` my_second_move = deepcopy(recorder.move) ``` ## Play recorded moves First, we put back the robot in its rest position to avoid sudden movement: ``` poppy.rest_posture.start() ``` Replaying move is really similar. First you need to create the *MovePlayer* object: ``` from pypot.primitive.move import MovePlayer ``` It requires: * the **robot** which will play the move * the **move** to play For instance, if we want to replay the first move we recorded: ``` player = MovePlayer(poppy, my_first_move) ``` And to play it: ``` player.start() ``` Once it's done, you can use the same code for the other move: ``` player = MovePlayer(poppy, my_second_move) player.start() ``` You can sequence moves by using the *wait_to_stop* method that will wait for the end of a move: ``` for move in [my_first_move, my_second_move]: player = MovePlayer(poppy, move) player.start() player.wait_to_stop() ``` Those movements can also be played in parallel. You will have to make sure that the movements can be combined otherwise pypot will simply add the different motor positions, possibly resulting in some unexpected moves. To avoid this problem make sure the moves you record are working on different sub sets of motors. ## Save/Load moves To keep the moves you have recorded from one session to the other, the best solution is to store them on the hard drive of your robot. This can be done using the *save* method of a move: ``` with open('my-first-demo.move', 'w') as f: my_first_move.save(f) ``` If you look at the file, you will see a list (possibly quite long) of "positions". These positions are basically: * a **timestamp** (time in seconds since the beginning of the move) * the list of motors name with: * the **present position** * the **present speed** Here are the first 20 lines of the first move we recorded: ``` !head -n 20 my-first-demo.move ``` This representation can be really heavy and quite cumbersome to work with. We plan to use a better representation in a future, such as one based on parametrized curve. **Contributions on this topic are welcomed!** A move can be loaded from the disk using the opposite *load* method. It requires to import the *Move* object: ``` from pypot.primitive.move import Move with open('my-first-demo.move') as f: my_loaded_move = Move.load(f) ``` ## Using demonstration in artistic context Now you have all the tools needed to create choregraphies with Poppy Ergo Jr. To get inspiration, you can have a look at the amazing work of Thomas Peyruse with Poppy Humanoid: https://forum.poppy-project.org/t/danse-contemporaine-school-of-moon/1567 ``` from IPython.display import YouTubeVideo YouTubeVideo('https://youtu.be/Hy56H2AZ_XI?list=PLdX8RO6QsgB6YCzezJHoYuRToFOhYk3Sf') ``` Or the *ENTRE NOUS* project of Emmanuelle Grangier: https://forum.poppy-project.org/t/projet-entre-nous-performance-choregraphique-et-sonore/1714 ``` from IPython.display import YouTubeVideo YouTubeVideo('hEBdz97FhS8') ```
/roboticia-uno-2.0.2.tar.gz/roboticia-uno-2.0.2/samples/notebooks/Record, Save and Play Moves on Poppy Ergo Jr.ipynb
0.412648
0.977968
Record, Save and Play Moves on Poppy Ergo Jr.ipynb
pypi
# Discover your Poppy Ergo Jr This notebook will guide you in your very first steps with Poppy Ergo Jr in Python. What you will see in this notebook: 1. Instantiate your robot 2. Access motors, send motor commands 3. Read sensor value 4. Start high level behaviors ![Poppy Ergo Jr](http://docs.poppy-project.org/en/assembly-guides/ergo-jr/img/ergo_tools.gif) *We assume here that you are connected to a physical Poppy Ergo Jr. It also need to be assembled and configured (you can referer to the [documentation](http://docs.poppy-project.org) if you haven't done in yet). You can use any tool. For the sensor section, you will also need to have connected the camera.* ``` # Import some matplolib and numpy shortcuts for Jupyter notebook %matplotlib inline from __future__ import print_function import numpy as np import matplotlib.pyplot as plt ``` ## Instantiate your robot To start using your robot in Python, you first need to instantiate it. You can do that by running the following code: ``` from pypot.creatures import PoppyErgoJr poppy = PoppyErgoJr() # If you want to use the robot with the camera unpluged, # you have to pass the argument camera='dummy # poppy = PoppyErgoJr(camera='dummy') # If you want to use a simulated robot in the 3D web viewer aka "poppy simu" # poppy = PoppyErgoJr(simulator='poppy-simu') # then go to http://simu.poppy-project.org/poppy-ergo-jr/ and check "synchroniser" # If you want to use the robot with V-REP simulator, open V-REP and execute : # poppy = PoppyErgoJr(simulator='vrep') # You can also change the end effector tools if you precise the V-REP scene # poppy = PoppyErgoJr(simulator='vrep', scene="poppy_ergo_jr_holder.ttt") # poppy = PoppyErgoJr(simulator='vrep', scene="poppy_ergo_jr_empty.ttt") ``` This creates a [Robot](http://poppy-project.github.io/pypot/pypot.robot.html#pypot.robot.robot.Robot) object that can be used to access the motors and sensors. It handles all the low-level communication for you, so you do not need to know anything about the serial protocol used to make a motor turn. The *motors* and *sensors* fields of the Robot are automatically synced to match the state of their hardware equivalent. Before doing anything else, we will initalize everything by asking the robot to go to its rest position (the code below will be described in more detailed later): ``` poppy.rest_posture.start() ``` ## Access motors In a Poppy Ergo Jr, the motor are defined as illustrated below: <img src="http://docs.poppy-project.org/en/assembly-guides/ergo-jr/img/assembly/motors.png" alt="Motors list" height="200"> From the [Robot](http://poppy-project.github.io/pypot/pypot.robot.html#pypot.robot.robot.Robot) object, you can directly retrieve the list of motors connected: ``` poppy.motors ``` As you can see *poppy.motors* holds a list of all motors. You can retrieve all motors name: ``` for m in poppy.motors: print(m.name) ``` Each of them can be access directly from its name. For instance: ``` poppy.m1 ``` ### Read values from the motors From the motor object you can access its registers. The main ones are: * **present_position**: the current position of the motor in degrees * **present_speed**: the current speed of the motor in degrees per second * **present_load**: the current workload of the motor (in percentage of max load) * **present_temperature**: the temperature of the motor in celsius * **angle_limit**: the reachable limits of the motor (in degrees) They can be accessed directly: ``` poppy.m1.present_temperature ``` Or, to get the present position for all motors: ``` [m.present_position for m in poppy.motors] ``` It's important to understand the *poppy.m1.present_position* is automatically updated with the real motor position (at 50Hz). Similarly for other registers, the update frequency may vary depending on its importance. For instance, the temperature is only refreshed at 1Hz as it is not fluctuating that quickly. ### Send motor commands On top of the registers presented above, they are additional ones used to send commands. For instance, the position of the motor is split in two different registers: * the read-only **present_position** of the motor * the read-write **goal_position** which sends to the motor a target position that it will try to reach. If you want to set a new position for a motor, you write: ``` poppy.m1.goal_position = 20 ``` You should see the robot turn of 20 degrees. Sending motor command is as simple as that. To make it turn to the other side: ``` poppy.m1.goal_position = -20 ``` In the examples above, the motor turned as fast as possible (its default mode). You can change its *moving_speed* (i.e. its maximum possible speed): ``` poppy.m1.moving_speed = 50 ``` Now the motor *m1* can not move faster than 50 degrees per second. If we ask to move again, you should see the difference: ``` poppy.m1.goal_position = 90 ``` The main write registers are: * **goal_position**: target position in degrees * **moving_speed**: maximum reachable speed in degrees per second * **compliant** (explained below) The dynamixel servo motors have two modes: * **stiff**: the normal mode for motors where they can be controlled * **compliant**: a mode where the motors can be freely moved by hand. This is particularly useful for phyisical human-robot interaction You can make them switch from one mode to the other using the *compliant* register. For instance, you can turn the motor *m6* compliant via: ``` poppy.m6.compliant = True ``` You should now be able to move this motors by hand. This is particularly useful for programming your robot by demonstration (see the dedicated notebook). And to turn it stiff again: ``` poppy.m6.compliant = False ``` ### Control motors LED The XL-320 motors used in the Poppy Ergo Jr robot have a small colored LED. You can change its color programatically directly using pypot. This can be a great way to make your robot more lively, customized and expressive. If you want to turn on the LED of the first motor and make it green you simply have to run: ``` poppy.m1.led = 'green' ``` And to turn it off again: ``` poppy.m1.led = 'off' ``` Obviously you can also do some more complex LED blinking. For instance: ``` import time for m in poppy.motors: time.sleep(0.5) m.led = 'yellow' time.sleep(1.0) m.led = 'off' ``` You can retrieve all available LED colors using: ``` from pypot.dynamixel.conversion import XL320LEDColors print(list(XL320LEDColors)) ``` ## Read sensors Reading sensor is exactly the same as reading registers from your robot. The sensors can be accessed via: ``` poppy.sensors ``` Here, we have 2 sensors: * a camera * a marker detector They can be accessed via their name: ``` poppy.camera ``` You can retrieve all the existing registers of a sensor: ``` poppy.camera.registers ``` And for instance to retrieve and displayed an image from the camera: ``` img = poppy.camera.frame plt.imshow(img) ``` Similarly to motors, the sensors values are automatically synchronized in background with the physical sensors. If you run again the previous code, you will see a more recent image: ``` plt.imshow(poppy.camera.frame) ``` ## High level behaviors The Poppy Ergo Jr robot comes with a set of pre-defined behaviors. They can be specific postures - such as the rest posture used at the beginning - or a dance, ... You can find the exhaustive list using the *primitives* accessor: ``` [p.name for p in poppy.primitives] ``` Those behaviors (or primitives in "poppy terms") can be started, stopped, paused, etc... ``` poppy.tetris_posture.start() ``` You can make the Poppy Ergo Jr dance for 10 seconds: ``` import time poppy.dance.start() time.sleep(10) poppy.dance.stop() ``` ## Going further Now that you have learnt the basis of what you can do with a Poppy Ergo Jr, there is much more to discover: * how to record/replay move by demonstration * how to define your own high-level behavior (e.g. a visual servoing of the tip of the robot using blob detection) * used your Poppy Ergo Jr as a connected device and make it communaticate with the rest of the world using HTTP requests * ... You can find other examples in the [docs](http://docs.poppy-project.org) or in the notebook folder next to this one.
/roboticia-uno-2.0.2.tar.gz/roboticia-uno-2.0.2/samples/notebooks/Discover your Poppy Ergo Jr.ipynb
0.452778
0.969032
Discover your Poppy Ergo Jr.ipynb
pypi
from pypot.primitive import Primitive, LoopPrimitive from pypot.primitive.utils import SimplePosture, Sinus class BasePosture(SimplePosture): @property def target_position(self): return {m.name: 0. for m in self.robot.motors} class RestPosture(SimplePosture): @property def leds(self): return {m: 'blue' for m in self.robot.motors} @property def target_position(self): return { 'm1': 0., 'm2': -90., 'm3': 35., 'm4': 0., 'm5': 55., 'm6': -5., } class CuriousPosture(SimplePosture): @property def target_position(self): return { 'm1': 0., 'm2': -15., 'm3': 40., 'm4': 0., 'm5': -35., 'm6': -60. } @property def leds(self): return {m: 'pink' for m in self.robot.motors} class TetrisPosture(SimplePosture): @property def target_position(self): return { 'm1': 0., 'm2': -90., 'm3': 90., 'm4': 0., 'm5': -90., 'm6': -90. } @property def leds(self): return {m: 'yellow' for m in self.robot.motors} class IdlePosture(SimplePosture): @property def target_position(self): return { 'm1': 0.0, 'm2': -110., 'm3': 65.0, 'm4': 0.0, 'm5': 34.0, 'm6': 20.0, } @property def leds(self): return {m: 'blue' for m in self.robot.motors} class IdleBreathing(LoopPrimitive): def setup(self): self.idle = IdlePosture(self.robot, 1.0) self.idle.start() self.idle.wait_to_stop() self.sinus = [ Sinus(self.robot, 10., [self.robot.m3, ], amp=5, freq=.1, offset=self.robot.m3.present_position), Sinus(self.robot, 10., [self.robot.m5], amp=10, freq=.1, offset=self.robot.m5.present_position, phase=3.14), ] import time time.sleep(2) [s.start() for s in self.sinus] for m in self.robot.motors: m.led = 'blue' def update(self): pass def teardown(self): for m in self.robot.motors: m.led = 'off' [s.stop() for s in self.sinus] self.idle.start() self.idle.wait_to_stop() class SafePowerUp(Primitive): def run(self): idle_prim = IdlePosture(self.robot, 3.0) idle_prim.start() idle_prim.wait_to_stop() def teardown(self): for m in self.robot.motors: m.moving_speed = 0.
/roboticia-uno-2.0.2.tar.gz/roboticia-uno-2.0.2/roboticia_uno/primitives/postures.py
0.7586
0.384277
postures.py
pypi
import sympy from sympy import Matrix, cos, sin, eye version = '1.0.1' def Rx(th): """Create a symbolic Rx rotation matrix. Theta should be in radians if it is numeric.""" R = Matrix([[1,0,0],\ [0,cos(th),-sin(th)],\ [0,sin(th),cos(th)]]) return R def HT(R, Px=0, Py=0, Pz=0): """Create an HT arbitrary matrix based on an arbitrary rotation matrix R and optional Px, Py, and Pz translations.""" T = eye(4) T[0:3,0:3] = R T[0,3] = Px T[1,3] = Py T[2,3] = Pz return T def HTx(alpha, Px=0, Py=0, Pz=0): """Create an HT matrix based on an Rx rotation and optional Px, Py, and Pz translations. Alpha should be in radians if it is numeric.""" R = Rx(alpha) T = HT(R, Px, Py, Pz) return T def Ry(th): """Create a symbolic Ry rotation matrix. Theta should be in radians if it is numeric.""" R = Matrix([[cos(th),0, sin(th)],\ [0,1,0],\ [-sin(th),0,cos(th)]]) return R def Rz(th): """Create a symbolic Rz rotation matrix. Theta should be in radians if it is numeric.""" R = Matrix([[cos(th),-sin(th),0],\ [sin(th),cos(th),0],\ [0,0,1]]) return R def HTz(theta, Px=0, Py=0, Pz=0): """Create an HT matrix based on an Rz rotation and optional Px, Py, and Pz translations.""" R = Rz(theta) T = HT(R, Px, Py, Pz) return T def DH(alpha, a, theta, d): """Note that this function uses sin and cos from sympy, which expect inputs in radians. This is not really an issue for symbolic variables, but if you want alpha=90 degrees, use pi/2 (for example). Also be sure to use pi from sympy so that sin(pi/2)=1, cos(pi/2)=0, and so on.""" T = Matrix([[cos(theta),-sin(theta), 0, a], \ [sin(theta)*cos(alpha), cos(theta)*cos(alpha),-sin(alpha),-sin(alpha)*d], \ [sin(theta)*sin(alpha), cos(theta)*sin(alpha), cos(alpha), cos(alpha)*d],\ [0,0,0,1]]) return T def HTinv_sym(T_in): R = T_in[0:3,0:3] P = T_in[0:3,-1] Rinv = R.T Pinv = -Rinv*P temp = Rinv.row_join(Pinv) Tinv = temp.col_join(sympy.Matrix([[0,0,0,1]])) return Tinv
/robotics_sympy-1.0.1.zip/robotics_sympy-1.0.1/robotics_sympy/__init__.py
0.863852
0.705886
__init__.py
pypi
import swift import spatialgeometry as sg import roboticstoolbox as rtb import spatialmath as sm import numpy as np import qpsolvers as qp # Launch the simulator Swift env = swift.Swift() env.launch() # Create a Panda robot object panda = rtb.models.Panda() # Set joint angles to ready configuration panda.q = panda.qr # Number of joint in the panda which we are controlling n = 7 # Make two obstacles with velocities s0 = sg.Sphere(radius=0.05, pose=sm.SE3(0.52, 0.4, 0.3)) s0.v = [0, -0.2, 0, 0, 0, 0] s1 = sg.Sphere(radius=0.05, pose=sm.SE3(0.1, 0.35, 0.65)) s1.v = [0, -0.2, 0, 0, 0, 0] collisions = [s0, s1] # Make a target target = sg.Sphere(radius=0.02, pose=sm.SE3(0.6, -0.2, 0.0)) # Add the Panda and shapes to the simulator env.add(panda) env.add(s0) env.add(s1) env.add(target) # Set the desired end-effector pose to the location of target Tep = panda.fkine(panda.q) Tep.A[:3, 3] = target.T[:3, -1] # Tep.A[2, 3] += 0.1 def step(): # The pose of the Panda's end-effector Te = panda.fkine(panda.q) # Transform from the end-effector to desired pose eTep = Te.inv() * Tep # Spatial error e = np.sum(np.abs(np.r_[eTep.t, eTep.rpy() * np.pi / 180])) # Calulate the required end-effector spatial velocity for the robot # to approach the goal. Gain is set to 1.0 v, arrived = rtb.p_servo(Te, Tep, 0.5, 0.01) # Gain term (lambda) for control minimisation Y = 0.01 # Quadratic component of objective function Q = np.eye(n + 6) # Joint velocity component of Q Q[:n, :n] *= Y # Slack component of Q Q[n:, n:] = (1 / e) * np.eye(6) # The equality contraints Aeq = np.c_[panda.jacobe(panda.q), np.eye(6)] beq = v.reshape((6,)) # The inequality constraints for joint limit avoidance Ain = np.zeros((n + 6, n + 6)) bin = np.zeros(n + 6) # The minimum angle (in radians) in which the joint is allowed to approach # to its limit ps = 0.05 # The influence angle (in radians) in which the velocity damper # becomes active pi = 0.9 # Form the joint limit velocity damper Ain[:n, :n], bin[:n] = panda.joint_velocity_damper(ps, pi, n) # For each collision in the scene for collision in collisions: # Form the velocity damper inequality contraint for each collision # object on the robot to the collision in the scene c_Ain, c_bin = panda.link_collision_damper( collision, panda.q[:n], 0.3, 0.05, 1.0, start=panda.link_dict["panda_link1"], end=panda.link_dict["panda_hand"], ) # If there are any parts of the robot within the influence distance # to the collision in the scene if c_Ain is not None and c_bin is not None: c_Ain = np.c_[c_Ain, np.zeros((c_Ain.shape[0], 6))] # Stack the inequality constraints Ain = np.r_[Ain, c_Ain] bin = np.r_[bin, c_bin] # Linear component of objective function: the manipulability Jacobian c = np.r_[-panda.jacobm(panda.q).reshape((n,)), np.zeros(6)] # The lower and upper bounds on the joint velocity and slack variable lb = -np.r_[panda.qdlim[:n], 10 * np.ones(6)] ub = np.r_[panda.qdlim[:n], 10 * np.ones(6)] # Solve for the joint velocities dq qd = qp.solve_qp(Q, c, Ain, bin, Aeq, beq, lb=lb, ub=ub) # Apply the joint velocities to the Panda panda.qd[:n] = qd[:n] # Step the simulator by 50 ms env.step(0.01) return arrived def run(): arrived = False while not arrived: arrived = step() step() run()
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/examples/neo.py
0.720073
0.635731
neo.py
pypi
import swift import spatialgeometry as sg import roboticstoolbox as rtb import spatialmath as sm import numpy as np import qpsolvers as qp import math def transform_between_vectors(a, b): # Finds the shortest rotation between two vectors using angle-axis, # then outputs it as a 4x4 transformation matrix a = a / np.linalg.norm(a) b = b / np.linalg.norm(b) angle = np.arccos(np.dot(a, b)) axis = np.cross(a, b) return sm.SE3.AngleAxis(angle, axis) # Launch the simulator Swift env = swift.Swift() env.launch() # Create a Fetch and Camera robot object fetch = rtb.models.Fetch() fetch_camera = rtb.models.FetchCamera() # Set joint angles to zero configuration fetch.q = fetch.qz fetch_camera.q = fetch_camera.qz # Make target object obstacles with velocities target = sg.Sphere(radius=0.05, base=sm.SE3(-2.0, 0.0, 0.5)) # Make line of sight object to visualize where the camera is looking sight_base = sm.SE3.Ry(np.pi / 2) * sm.SE3(0.0, 0.0, 2.5) centroid_sight = sg.Cylinder( radius=0.001, length=5.0, base=fetch_camera.fkine(fetch_camera.q).A @ sight_base.A, ) # Add the Fetch and other shapes to the simulator env.add(fetch) env.add(fetch_camera) env.add(centroid_sight) env.add(target) # Set the desired end-effector pose to the location of target Tep = fetch.fkine(fetch.q) Tep.A[:3, :3] = sm.SE3.Rz(np.pi).R Tep.A[:3, 3] = target.T[:3, -1] env.step() n_base = 2 n_arm = 8 n_camera = 2 n = n_base + n_arm + n_camera def step(): # Find end-effector pose in world frame wTe = fetch.fkine(fetch.q).A # Find camera pose in world frame wTc = fetch_camera.fkine(fetch_camera.q).A # Find transform between end-effector and goal eTep = np.linalg.inv(wTe) @ Tep.A # Find transform between camera and goal cTep = np.linalg.inv(wTc) @ Tep.A # Spatial error between end-effector and target et = np.sum(np.abs(eTep[:3, -1])) # Weighting function used for objective function def w_lambda(et, alpha, gamma): return alpha * np.power(et, gamma) # Quadratic component of objective function Q = np.eye(n + 10) Q[: n_base + n_arm, : n_base + n_arm] *= 0.01 # Robotic manipulator Q[:n_base, :n_base] *= w_lambda(et, 1.0, -1.0) # Mobile base Q[n_base + n_arm : n, n_base + n_arm : n] *= 0.01 # Camera Q[n : n + 3, n : n + 3] *= w_lambda(et, 1000.0, -2.0) # Slack arm linear Q[n + 3 : n + 6, n + 3 : n + 6] *= w_lambda(et, 0.01, -5.0) # Slack arm angular Q[n + 6 : -1, n + 6 : -1] *= 100 # Slack camera Q[-1, -1] *= w_lambda(et, 1000.0, 3.0) # Slack self-occlusion # Calculate target velocities for end-effector to reach target v_manip, _ = rtb.p_servo(wTe, Tep, 1.5) v_manip[3:] *= 1.3 # Calculate target angular velocity for camera to rotate towards target head_rotation = transform_between_vectors(np.array([1, 0, 0]), cTep[:3, 3]) v_camera, _ = rtb.p_servo(sm.SE3(), head_rotation, 25) # The equality contraints to achieve velocity targets Aeq = np.c_[fetch.jacobe(fetch.q), np.zeros((6, 2)), np.eye(6), np.zeros((6, 4))] beq = v_manip.reshape((6,)) jacobe_cam = fetch_camera.jacobe(fetch_camera.q)[3:, :] Aeq_cam = np.c_[ jacobe_cam[:, :3], np.zeros((3, 7)), jacobe_cam[:, 3:], np.zeros((3, 6)), np.eye(3), np.zeros((3, 1)), ] Aeq = np.r_[Aeq, Aeq_cam] beq = np.r_[beq, v_camera[3:].reshape((3,))] # The inequality constraints for joint limit avoidance Ain = np.zeros((n + 10, n + 10)) bin = np.zeros(n + 10) # The minimum angle (in radians) in which the joint is allowed to approach # to its limit ps = 0.1 # The influence angle (in radians) in which the velocity damper # becomes active pi = 0.9 # Form the joint limit velocity damper Ain[: fetch.n, : fetch.n], bin[: fetch.n] = fetch.joint_velocity_damper( ps, pi, fetch.n ) Ain_torso, bin_torso = fetch_camera.joint_velocity_damper(0.0, 0.05, fetch_camera.n) Ain[2, 2] = Ain_torso[2, 2] bin[2] = bin_torso[2] Ain_cam, bin_cam = fetch_camera.joint_velocity_damper(ps, pi, fetch_camera.n) Ain[n_base + n_arm : n, n_base + n_arm : n] = Ain_cam[3:, 3:] bin[n_base + n_arm : n] = bin_cam[3:] # Create line of sight object between camera and object c_Ain, c_bin = fetch.vision_collision_damper( target, camera=fetch_camera, camera_n=2, q=fetch.q[: fetch.n], di=0.3, ds=0.2, xi=1.0, end=fetch.link_dict["gripper_link"], start=fetch.link_dict["shoulder_pan_link"], ) if c_Ain is not None and c_bin is not None: c_Ain = np.c_[ c_Ain, np.zeros((c_Ain.shape[0], 9)), -np.ones((c_Ain.shape[0], 1)) ] Ain = np.r_[Ain, c_Ain] bin = np.r_[bin, c_bin] # Linear component of objective function: the manipulability Jacobian c = np.concatenate( ( np.zeros(n_base), # -fetch.jacobm(start=fetch.links[3]).reshape((n_arm,)), np.zeros(n_arm), np.zeros(n_camera), np.zeros(10), ) ) # Get base to face end-effector kε = 0.5 bTe = fetch.fkine(fetch.q, include_base=False).A θε = math.atan2(bTe[1, -1], bTe[0, -1]) ε = kε * θε c[0] = -ε # The lower and upper bounds on the joint velocity and slack variable lb = -np.r_[ fetch.qdlim[: fetch.n], fetch_camera.qdlim[3 : fetch_camera.n], 100 * np.ones(9), 0, ] ub = np.r_[ fetch.qdlim[: fetch.n], fetch_camera.qdlim[3 : fetch_camera.n], 100 * np.ones(9), 100, ] # Solve for the joint velocities dq qd = qp.solve_qp(Q, c, Ain, bin, Aeq, beq, lb=lb, ub=ub) qd_cam = np.concatenate((qd[:3], qd[fetch.n : fetch.n + 2])) qd = qd[: fetch.n] if et > 0.5: qd *= 0.7 / et qd_cam *= 0.7 / et else: qd *= 1.4 qd_cam *= 1.4 arrived = et < 0.02 fetch.qd = qd fetch_camera.qd = qd_cam centroid_sight.T = fetch_camera.fkine(fetch_camera.q).A @ sight_base.A return arrived arrived = False while not arrived: arrived = step() env.step(0.01)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/examples/fetch_vision.py
0.829527
0.566618
fetch_vision.py
pypi
import swift import roboticstoolbox as rtb import spatialgeometry as sg import spatialmath as sm import qpsolvers as qp import numpy as np import math def step_robot(r: rtb.ERobot, Tep): wTe = r.fkine(r.q) eTep = np.linalg.inv(wTe) @ Tep # Spatial error et = np.sum(np.abs(eTep[:3, -1])) # Gain term (lambda) for control minimisation Y = 0.01 # Quadratic component of objective function Q = np.eye(r.n + 6) # Joint velocity component of Q Q[: r.n, : r.n] *= Y Q[:2, :2] *= 1.0 / et # Slack component of Q Q[r.n :, r.n :] = (1.0 / et) * np.eye(6) v, _ = rtb.p_servo(wTe, Tep, 1.5) v[3:] *= 1.3 # The equality contraints Aeq = np.c_[r.jacobe(r.q), np.eye(6)] beq = v.reshape((6,)) # The inequality constraints for joint limit avoidance Ain = np.zeros((r.n + 6, r.n + 6)) bin = np.zeros(r.n + 6) # The minimum angle (in radians) in which the joint is allowed to approach # to its limit ps = 0.1 # The influence angle (in radians) in which the velocity damper # becomes active pi = 0.9 # Form the joint limit velocity damper Ain[: r.n, : r.n], bin[: r.n] = r.joint_velocity_damper(ps, pi, r.n) # Linear component of objective function: the manipulability Jacobian c = np.concatenate( (np.zeros(2), -r.jacobm(start=r.links[4]).reshape((r.n - 2,)), np.zeros(6)) ) # Get base to face end-effector kε = 0.5 bTe = r.fkine(r.q, include_base=False).A θε = math.atan2(bTe[1, -1], bTe[0, -1]) ε = kε * θε c[0] = -ε # The lower and upper bounds on the joint velocity and slack variable lb = -np.r_[r.qdlim[: r.n], 10 * np.ones(6)] ub = np.r_[r.qdlim[: r.n], 10 * np.ones(6)] # Solve for the joint velocities dq qd = qp.solve_qp(Q, c, Ain, bin, Aeq, beq, lb=lb, ub=ub) qd = qd[: r.n] if et > 0.5: qd *= 0.7 / et else: qd *= 1.4 if et < 0.02: return True, qd else: return False, qd env = swift.Swift() env.launch(realtime=True) ax_goal = sg.Axes(0.1) env.add(ax_goal) frankie = rtb.models.Frankie() frankie.q = frankie.qr env.add(frankie) arrived = False dt = 0.025 # Behind env.set_camera_pose([-2, 3, 0.7], [-2, 0.0, 0.5]) wTep = frankie.fkine(frankie.q) * sm.SE3.Rz(np.pi) wTep.A[:3, :3] = np.diag([-1, 1, -1]) wTep.A[0, -1] -= 4.0 wTep.A[2, -1] -= 0.25 ax_goal.T = wTep env.step() while not arrived: arrived, frankie.qd = step_robot(frankie, wTep.A) env.step(dt) # Reset bases base_new = frankie.fkine(frankie._q, end=frankie.links[2]) frankie._T = base_new.A frankie.q[:2] = 0 env.hold()
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/examples/holistic_mm_non_holonomic.py
0.705176
0.613266
holistic_mm_non_holonomic.py
pypi
import roboticstoolbox as rtb import swift import spatialmath as sm import numpy as np """ This is an implementation of the controller from: J. Baur, J. Pfaff, H. Ulbrich, and T. Villgrattner, “Design and development of a redundant modular multipurpose agricultural manipulator,” in 2012 IEEE/ASME International Conference on Advanced Intelligent Mechatronics (AIM), 2012, pp. 823–830. """ # Launch the simulator Swift env = swift.Swift() env.launch() # Create a Panda robot object panda = rtb.models.Panda() # Set joint angles to ready configuration panda.q = panda.qr # Add the Panda to the simulator env.add(panda) # Number of joint in the panda which we are controlling n = 7 # Set the desired end-effector pose Tep = panda.fkine(panda.q) * sm.SE3(0.3, 0.2, 0.3) arrived = False while not arrived: # The pose of the Panda's end-effector Te = panda.fkine(panda.q) # The manipulator Jacobian in the end-effecotr frame Je = panda.jacobe(panda.q) # Calulate the required end-effector spatial velocity for the robot # to approach the goal. Gain is set to 1.0 v, arrived = rtb.p_servo(Te, Tep, 1.0) # Gain term (lambda) for control minimisation Y = 0.01 # The manipulability Jacobian Jm = panda.jacobm(panda.q) # The minimum angle (in radians) in which the joint is allowed to approach # to its limit ps = 0.05 # The influence angle (in radians) in which the velocity damper # becomes active pi = 0.9 # Add cost to going in the direction of joint limits, if they are within # the influence distance b = np.zeros((n, 1)) for i in range(n): if panda.q[i] - panda.qlim[0, i] <= pi: b[i, 0] = -1 * \ np.power(((panda.q[i] - panda.qlim[0, i]) - pi), 2) \ / np.power((ps - pi), 2) if panda.qlim[1, i] - panda.q[i] <= pi: b[i, 0] = 1 * \ np.power(((panda.qlim[1, i] - panda.q[i]) - pi), 2) \ / np.power((ps - pi), 2) # Project the gradient of manipulability into the null-space of the # differential kinematics null = ( np.eye(n) - np.linalg.pinv(Je) @ Je ) @ (Jm - b) # Solve for the joint velocities dq qd = np.linalg.pinv(Je) @ v + 1 / Y * null.flatten() # Apply the joint velocities to the Panda panda.qd[:n] = qd[:n] # Step the simulator by 50 ms env.step(0.05)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/examples/baur.py
0.747247
0.51013
baur.py
pypi
import swift import roboticstoolbox as rtb import spatialgeometry as sg import spatialmath as sm import qpsolvers as qp import numpy as np import math def step_robot(r: rtb.ERobot, Tep): wTe = r.fkine(r.q) eTep = np.linalg.inv(wTe) @ Tep # Spatial error et = np.sum(np.abs(eTep[:3, -1])) # Gain term (lambda) for control minimisation Y = 0.01 # Quadratic component of objective function Q = np.eye(r.n + 6) # Joint velocity component of Q Q[: r.n, : r.n] *= Y Q[:3, :3] *= 1.0 / et # Slack component of Q Q[r.n :, r.n :] = (1.0 / et) * np.eye(6) v, _ = rtb.p_servo(wTe, Tep, 1.5) v[3:] *= 1.3 # The equality contraints Aeq = np.c_[r.jacobe(r.q), np.eye(6)] beq = v.reshape((6,)) # The inequality constraints for joint limit avoidance Ain = np.zeros((r.n + 6, r.n + 6)) bin = np.zeros(r.n + 6) # The minimum angle (in radians) in which the joint is allowed to approach # to its limit ps = 0.1 # The influence angle (in radians) in which the velocity damper # becomes active pi = 0.9 # Form the joint limit velocity damper Ain[: r.n, : r.n], bin[: r.n] = r.joint_velocity_damper(ps, pi, r.n) # Linear component of objective function: the manipulability Jacobian c = np.concatenate( (np.zeros(3), -r.jacobm(start=r.links[5]).reshape((r.n - 3,)), np.zeros(6)) ) # Get base to face end-effector kε = 0.5 bTe = r.fkine(r.q, include_base=False).A θε = math.atan2(bTe[1, -1], bTe[0, -1]) ε = kε * θε c[0] = -ε # The lower and upper bounds on the joint velocity and slack variable lb = -np.r_[r.qdlim[: r.n], 10 * np.ones(6)] ub = np.r_[r.qdlim[: r.n], 10 * np.ones(6)] # Solve for the joint velocities dq qd = qp.solve_qp(Q, c, Ain, bin, Aeq, beq, lb=lb, ub=ub) qd = qd[: r.n] if et > 0.5: qd *= 0.7 / et else: qd *= 1.4 if et < 0.02: return True, qd else: return False, qd env = swift.Swift() env.launch(realtime=True) ax_goal = sg.Axes(0.1) env.add(ax_goal) frankie = rtb.models.FrankieOmni() frankie.q = frankie.qr env.add(frankie) arrived = False dt = 0.025 # Behind env.set_camera_pose([-2, 3, 0.7], [-2, 0.0, 0.5]) wTep = frankie.fkine(frankie.q) * sm.SE3.Rz(np.pi) wTep.A[:3, :3] = np.diag([-1, 1, -1]) wTep.A[0, -1] -= 4.0 wTep.A[2, -1] -= 0.25 ax_goal.T = wTep env.step() while not arrived: arrived, frankie.qd = step_robot(frankie, wTep.A) env.step(dt) # Reset bases base_new = frankie.fkine(frankie._q, end=frankie.links[3]).A frankie._T = base_new frankie.q[:3] = 0 env.hold()
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/examples/holistic_mm_omni.py
0.706798
0.609292
holistic_mm_omni.py
pypi
from swift import Swift import spatialmath.base.symbolic as sym from roboticstoolbox import ETS as ET from roboticstoolbox import * from spatialmath import * from spatialgeometry import * from math import pi import numpy as np # # III.SPATIAL MATHEMATICS from spatialmath.base import * T = transl(0.5, 0.0, 0.0) @ rpy2tr(0.1, 0.2, 0.3, order="xyz") @ trotx(-90, "deg") print(T) T = SE3(0.5, 0.0, 0.0) * SE3.RPY([0.1, 0.2, 0.3], order="xyz") * SE3.Rx(-90, unit="deg") print(T) T.eul() T.R T.plot(color="red", label="2") UnitQuaternion.Rx(0.3) UnitQuaternion.AngVec(0.3, [1, 0, 0]) R = SE3.Rx(np.linspace(0, pi / 2, num=100)) len(R) # # IV. ROBOTICS TOOLBOX # ## A. Robot models # robot length values (metres) d1 = 0.352 a1 = 0.070 a2 = 0.360 d4 = 0.380 d6 = 0.065 robot = DHRobot( [ RevoluteDH(d=d1, a=a1, alpha=-pi / 2), RevoluteDH(a=a2), RevoluteDH(alpha=pi / 2), ], name="my IRB140", ) print(robot) puma = models.DH.Puma560() T = puma.fkine([0.1, 0.2, 0.3, 0.4, 0.5, 0.6]) sol = puma.ikine_LM(T) print(sol) puma.plot(sol.q, block=False) puma.ikine_a(T, config="lun") # Puma dimensions (m), see RVC2 Fig. 7.4 for details l1 = 0.672 l2 = -0.2337 l3 = 0.4318 l4 = 0.0203 l5 = 0.0837 l6 = 0.4318 e = ( ET.tz(l1) * ET.rz() * ET.ty(l2) * ET.ry() * ET.tz(l3) * ET.tx(l4) * ET.ty(l5) * ET.ry() * ET.tz(l6) * ET.rz() * ET.ry() * ET.rz() ) robot = ERobot(e) print(robot) panda = models.URDF.Panda() print(panda) # ## B. Trajectories traj = jtraj(puma.qz, puma.qr, 100) qplot(traj.q) t = np.arange(0, 2, 0.010) T0 = SE3(0.6, -0.5, 0.3) T1 = SE3(0.4, 0.5, 0.2) Ts = ctraj(T0, T1, t) len(Ts) sol = puma.ikine_LM(Ts) sol.q.shape # ## C. Symbolic manipulation phi, theta, psi = sym.symbol("φ, ϴ, ψ") rpy2r(phi, theta, psi) q = sym.symbol("q_:6") # q = (q_1, q_2, ... q_5) T = puma.fkine(q) puma = models.DH.Puma560(symbolic=True) T = puma.fkine(q) T.t[0] puma = models.DH.Puma560(symbolic=False) J = puma.jacob0(puma.qn) J = puma.jacobe(puma.qn) # ## D. Differential kinematics J = puma.jacob0(puma.qr) np.linalg.matrix_rank(J) jsingu(J) H = panda.hessian0(panda.qz) H.shape puma.manipulability(puma.qn) puma.manipulability(puma.qn, method="asada") puma.manipulability(puma.qn, axes="trans") panda.jacobm(panda.qr) # ## E. Dynamics tau = puma.rne(puma.qn, np.zeros((6,)), np.zeros((6,))) J = puma.inertia(puma.qn) C = puma.coriolis(puma.qn, 0.1 * np.ones((6,))) g = puma.gravload(puma.qn) qdd = puma.accel(puma.qn, tau, np.zeros((6,))) # # V. NEW CAPABILITY # ## B. Collision checking obstacle = Box([1, 1, 1], base=SE3(1, 0, 0)) iscollision0 = panda.collided(panda.q, obstacle) # boolean iscollision1 = panda.links[0].collided(obstacle) d, p1, p2 = panda.closest_point(panda.q, obstacle) print(d, p1, p2) d, p1, p2 = panda.links[0].closest_point(obstacle) print(d, p1, p2) # ## C. Interfaces panda.plot(panda.qr, block=False) backend = Swift() backend.launch() # create graphical world backend.add(panda) # add robot to the world panda.q = panda.qr # update the robot backend.step() # display the world #
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/examples/icra2021.py
0.463687
0.421611
icra2021.py
pypi
import numpy as np from spatialmath import SE3 import roboticstoolbox as rtb import timeit from ansitable import ANSITable, Column import traceback # change for the robot IK under test, must set: # * robot, the DHRobot object # * T, the end-effector pose # * q0, the initial joint angles for solution example = 'puma' # 'panda' if example == 'puma': # Puma robot case robot = rtb.models.DH.Puma560() q = robot.qn q0 = robot.qz T = robot.fkine(q) elif example == 'panda': # Panda robot case robot = rtb.models.DH.Panda() T = SE3(0.7, 0.2, 0.1) * SE3.OA([0, 1, 0], [0, 0, -1]) q0 = robot.qz solvers = [ 'Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG', ## Jacobian is required 'L-BFGS-B', 'TNC', 'COBYLA', 'SLSQP', 'trust-constr', 'dogleg', 'trust-ncg', 'trust-exact', 'trust-krylov', ] # setup to run timeit setup = ''' from __main__ import robot, T, q0 ''' N = 10 # setup results table table = ANSITable( Column("Solver", headalign="^", colalign='<'), Column("Time (ms)", headalign="^", fmt="{:.2g}", colalign='>'), Column("Error", headalign="^", fmt="{:.3g}", colalign='>'), border="thick") # test the IK methods for solver in solvers: print('Testing:', solver) # test the method, don't pass q0 to the analytic function try: sol = robot.ikine_min(T, q0=q0, qlim=True, method=solver) except Exception as e: print('***', solver, ' failed') print(e) continue # print error message if there is one if not sol.success: print(' failed:', sol.reason) # evalute the error err = np.linalg.norm(T - robot.fkine(sol.q)) print(' error', err) if N > 0: # noqa # evaluate the execution time t = timeit.timeit(stmt=f"robot.ikine_min(T, q0=q0, qlim=True, method='{solver}')", setup=setup, number=N) else: t = 0 # add it to the output table table.row(f"`{solver}`", t/N*1e3, err) # pretty print the results table.print() print(table.markdown())
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/examples/ikine_evaluate2.py
0.406155
0.361954
ikine_evaluate2.py
pypi
import swift import roboticstoolbox as rtb import spatialmath as sm import numpy as np import qpsolvers as qp """ This is an implementation of the controller from: J. Haviland and P. Corke, “A purely-reactive manipulability-maximising motion controller,” arXiv preprint arXiv:2002.11901,2020. """ # Launch the simulator Swift env = swift.Swift() # Launch the sim in chrome as only chrome supports webm videos env.launch('google-chrome') # Create a Panda robot object panda = rtb.models.Panda() # Set joint angles to ready configuration panda.q = panda.qr # Add the Panda to the simulator env.add(panda) # The timestep for the simulation, 25ms dt = 0.025 # Start recording with a framerate of 1/dt and # call the video panda_swift_recording # Export video as a webm file (this only works in Chrome) env.start_recording('panda_swift_recording', 1 / dt) # To export as a gif replace the above line with # env.start_recording('panda_swift_recording', 1 / dt, format='gif') # To export as a tar folder of jpg captures replace with # env.start_recording('panda_swift_recording', 1 / dt, format='jpg') # To export as a tar folder of png captures replace with # env.start_recording('panda_swift_recording', 1 / dt, format='png') # Number of joint in the panda which we are controlling n = 7 # Set the desired end-effector pose Tep = panda.fkine(panda.q) * sm.SE3(0.3, 0.2, 0.3) arrived = False while not arrived: # The pose of the Panda's end-effector Te = panda.fkine(panda.q) # Transform from the end-effector to desired pose eTep = Te.inv() * Tep # Spatial error e = np.sum(np.abs(np.r_[eTep.t, eTep.rpy() * np.pi / 180])) # Calulate the required end-effector spatial velocity for the robot # to approach the goal. Gain is set to 1.0 v, arrived = rtb.p_servo(Te, Tep, 1.0) # Gain term (lambda) for control minimisation Y = 0.01 # Quadratic component of objective function Q = np.eye(n + 6) # Joint velocity component of Q Q[:n, :n] *= Y # Slack component of Q Q[n:, n:] = (1 / e) * np.eye(6) # The equality contraints Aeq = np.c_[panda.jacobe(panda.q), np.eye(6)] beq = v.reshape((6,)) # The inequality constraints for joint limit avoidance Ain = np.zeros((n + 6, n + 6)) bin = np.zeros(n + 6) # The minimum angle (in radians) in which the joint is allowed to approach # to its limit ps = 0.05 # The influence angle (in radians) in which the velocity damper # becomes active pi = 0.9 # Form the joint limit velocity damper Ain[:n, :n], bin[:n] = panda.joint_velocity_damper(ps, pi, n) # Linear component of objective function: the manipulability Jacobian c = np.r_[-panda.jacobm().reshape((n,)), np.zeros(6)] # The lower and upper bounds on the joint velocity and slack variable lb = -np.r_[panda.qdlim[:n], 10 * np.ones(6)] ub = np.r_[panda.qdlim[:n], 10 * np.ones(6)] # Solve for the joint velocities dq qd = qp.solve_qp(Q, c, Ain, bin, Aeq, beq, lb=lb, ub=ub) # Apply the joint velocities to the Panda panda.qd[:n] = qd[:n] # Step the simulator by 50 ms env.step(dt) # Stop recording and save the video (to the downloads folder) env.stop_recording()
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/examples/swift_recording.py
0.744378
0.586878
swift_recording.py
pypi
import numpy as np import roboticstoolbox as rtb import spatialmath as sm import fknm import time import swift import spatialgeometry as sg import sys from ansitable import ANSITable from numpy import ndarray from spatialmath import SE3 from typing import Union, overload, List, Set # Our robot and ETS robot = rtb.models.Panda() ets = robot.ets() ### Experiment parameters # Number of problems to solve problems = 10000 # Cartesion DoF priority matrix we = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) # random valid q values which will define Tep q_rand = ets.random_q(problems) # Our desired end-effector poses Tep = np.zeros((problems, 4, 4)) for i in range(problems): Tep[i] = ets.eval(q_rand[i]) # Maximum iterations allowed in a search ilimit = 30 # Maximum searches allowed per problem slimit = 100 # Solution tolerance tol = 1e-6 # Reject solutions with invalid joint limits reject_jl = True class IK: def __init__(self, name, solve, problems=problems): # Solver attributes self.name = name self.solve = solve # Solver results self.iterations = np.zeros(problems) self.searches = np.zeros(problems) self.residual = np.zeros(problems) self.success = np.zeros(problems) self.total_iterations = 0 self.total_searches = 0 solvers = [ # IK( # "Newton Raphson", # lambda Tep: ets.ik_nr( # Tep, # q0=None, # ilimit=ilimit, # slimit=slimit, # tol=tol, # reject_jl=reject_jl, # we=we, # use_pinv=False, # pinv_damping=0.0, # ), # ), # IK( # "Gauss Newton", # lambda Tep: ets.ik_gn( # Tep, # q0=None, # ilimit=ilimit, # slimit=slimit, # tol=tol, # reject_jl=reject_jl, # we=we, # use_pinv=False, # pinv_damping=0.0, # ), # ), IK( "Newton Raphson Pinv", lambda Tep: ets.ik_nr( Tep, q0=None, ilimit=ilimit, slimit=slimit, tol=tol, reject_jl=reject_jl, we=we, use_pinv=True, pinv_damping=0.0, ), ), IK( "Gauss Newton Pinv", lambda Tep: ets.ik_gn( Tep, q0=None, ilimit=ilimit, slimit=slimit, tol=tol, reject_jl=reject_jl, we=we, use_pinv=True, pinv_damping=0.0, ), ), IK( "LM Chan 0.1", lambda Tep: ets.ik_lm_chan( Tep, q0=None, ilimit=ilimit, slimit=slimit, tol=tol, reject_jl=reject_jl, we=we, λ=0.1, ), ), # IK( # "LM Chan 1.0", # lambda Tep: ets.ik_lm_chan( # Tep, # q0=None, # ilimit=ilimit, # slimit=slimit, # tol=tol, # reject_jl=reject_jl, # we=we, # λ=1.0, # ), # ), # IK( # "LM Wampler", # lambda Tep: ets.ik_lm_wampler( # Tep, # q0=None, # ilimit=ilimit, # slimit=slimit, # tol=tol, # reject_jl=reject_jl, # we=we, # λ=1e-2, # ), # ), IK( "LM Wampler 1e-4", lambda Tep: ets.ik_lm_wampler( Tep, q0=None, ilimit=ilimit, slimit=slimit, tol=tol, reject_jl=reject_jl, we=we, λ=1e-4, ), ), # IK( # "LM Wampler 1e-6", # lambda Tep: ets.ik_lm_wampler( # Tep, # q0=None, # ilimit=ilimit, # slimit=slimit, # tol=tol, # reject_jl=reject_jl, # we=we, # λ=1e-6, # ), # ), # IK( # "LM Sugihara 0.001", # lambda Tep: ets.ik_lm_sugihara( # Tep, # q0=None, # ilimit=ilimit, # slimit=slimit, # tol=tol, # reject_jl=reject_jl, # we=we, # λ=0.001, # ), # ), # IK( # "LM Sugihara 0.01", # lambda Tep: ets.ik_lm_sugihara( # Tep, # q0=None, # ilimit=ilimit, # slimit=slimit, # tol=tol, # reject_jl=reject_jl, # we=we, # λ=0.01, # ), # ), IK( "LM Sugihara 0.1", lambda Tep: ets.ik_lm_sugihara( Tep, q0=None, ilimit=ilimit, slimit=slimit, tol=tol, reject_jl=reject_jl, we=we, λ=0.1, ), ), ] for i in range(problems): print(i + 1) for solver in solvers: _, success, iterations, searches, residual = solver.solve(Tep[i]) if success: solver.success[i] = success solver.iterations[i] = iterations solver.searches[i] = searches solver.residual[i] = residual solver.total_iterations += solver.iterations[i] solver.total_searches += solver.searches[i] else: solver.success[i] = np.nan solver.iterations[i] = np.nan solver.searches[i] = np.nan solver.residual[i] = np.nan print(f"\nNumerical Inverse Kinematics Methods Compared over {problems} problems\n") table = ANSITable( "Method", "sLimit/iLimit", "Mean Steps", "Median Steps", "Infeasible", "Infeasible %", "Mean Attempts", # "Median Attempts", "Max Attempts", border="thin", ) for solver in solvers: table.row( solver.name, f"{slimit}, {ilimit}", np.round(np.nanmean(solver.iterations), 2), np.nanmedian(solver.iterations), np.sum(np.isnan(solver.success)), np.round(np.sum(np.isnan(solver.success)) / problems * 100.0, 2), np.round(np.nanmean(solver.searches), 2), np.nanmax(solver.searches), ) table.print()
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/examples/ik_exp.py
0.588298
0.316448
ik_exp.py
pypi
import swift import roboticstoolbox as rtb import spatialmath as sm import numpy as np import qpsolvers as qp """ This is an implementation of the controller from: J. Haviland and P. Corke, “A purely-reactive manipulability-maximising motion controller,” arXiv preprint arXiv:2002.11901,2020. """ # Launch the simulator Swift env = swift.Swift() env.launch() # Create a Panda robot object panda = rtb.models.Panda() # Set joint angles to ready configuration panda.q = panda.qr # Add the Panda to the simulator env.add(panda) # Number of joint in the panda which we are controlling n = 7 # Set the desired end-effector pose Tep = panda.fkine(panda.q) * sm.SE3(0.3, 0.2, 0.3) arrived = False while not arrived: # The pose of the Panda's end-effector Te = panda.fkine(panda.q) # Transform from the end-effector to desired pose eTep = Te.inv() * Tep # Spatial error e = np.sum(np.abs(np.r_[eTep.t, eTep.rpy() * np.pi / 180])) # Calulate the required end-effector spatial velocity for the robot # to approach the goal. Gain is set to 1.0 v, arrived = rtb.p_servo(Te, Tep, 1.0) # Gain term (lambda) for control minimisation Y = 0.01 # Quadratic component of objective function Q = np.eye(n + 6) # Joint velocity component of Q Q[:n, :n] *= Y # Slack component of Q Q[n:, n:] = (1 / e) * np.eye(6) # The equality contraints Aeq = np.c_[panda.jacobe(panda.q), np.eye(6)] beq = v.reshape((6,)) # The inequality constraints for joint limit avoidance Ain = np.zeros((n + 6, n + 6)) bin = np.zeros(n + 6) # The minimum angle (in radians) in which the joint is allowed to approach # to its limit ps = 0.05 # The influence angle (in radians) in which the velocity damper # becomes active pi = 0.9 # Form the joint limit velocity damper Ain[:n, :n], bin[:n] = panda.joint_velocity_damper(ps, pi, n) # Linear component of objective function: the manipulability Jacobian c = np.r_[-panda.jacobm().reshape((n,)), np.zeros(6)] # The lower and upper bounds on the joint velocity and slack variable lb = -np.r_[panda.qdlim[:n], 10 * np.ones(6)] ub = np.r_[panda.qdlim[:n], 10 * np.ones(6)] # Solve for the joint velocities dq qd = qp.solve_qp(Q, c, Ain, bin, Aeq, beq, lb=lb, ub=ub) # Apply the joint velocities to the Panda panda.qd[:n] = qd[:n] # Step the simulator by 50 ms env.step(0.05)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/examples/mmc.py
0.792946
0.549761
mmc.py
pypi
import numpy as np from math import pi, sqrt, inf quadrotor = {} quadrotor["nrotors"] = 4 # 4 rotors quadrotor["g"] = 9.81 # g Gravity quadrotor["rho"] = 1.184 # rho Density of air quadrotor["muv"] = 1.5e-5 # muv Viscosity of air # Airframe quadrotor["M"] = 4 # M Mass Ixx = 0.082 Iyy = 0.082 Izz = 0.149 # 0.160 quadrotor["J"] = np.diag([Ixx, Iyy, Izz]) # I Flyer rotational inertia matrix 3x3 quadrotor["h"] = -0.007 # h Height of rotors above CoG quadrotor["d"] = 0.315 # d Length of flyer arms # Rotor quadrotor["nb"] = 2 # b Number of blades per rotor quadrotor["r"] = 0.165 # r Rotor radius quadrotor["c"] = 0.018 # c Blade chord quadrotor["e"] = 0.0 # e Flapping hinge offset quadrotor["Mb"] = 0.005 # Mb Rotor blade mass quadrotor["Mc"] = 0.010 # Mc Estimated hub clamp mass quadrotor["ec"] = 0.004 # ec Blade root clamp displacement quadrotor["Ib"] = ( quadrotor["Mb"] * (quadrotor["r"] - quadrotor["ec"]) ** 2 / 4 ) # Ib Rotor blade rotational inertia quadrotor["Ic"] = ( quadrotor["Mc"] * (quadrotor["ec"]) ** 2 / 4 ) # Ic Estimated root clamp inertia quadrotor["mb"] = quadrotor["g"] * ( quadrotor["Mc"] * quadrotor["ec"] / 2 + quadrotor["Mb"] * quadrotor["r"] / 2 ) # mb Static blade moment quadrotor["Ir"] = quadrotor["nb"] * ( quadrotor["Ib"] + quadrotor["Ic"] ) # Ir Total rotor inertia quadrotor["Ct"] = 0.0048 # Ct Non-dim. thrust coefficient quadrotor["Cq"] = quadrotor["Ct"] * sqrt( quadrotor["Ct"] / 2 ) # Cq Non-dim. torque coefficient quadrotor["sigma"] = ( quadrotor["c"] * quadrotor["nb"] / (pi * quadrotor["r"]) ) # sigma Rotor solidity ratio quadrotor["thetat"] = 6.8 * (pi / 180) # thetat Blade tip angle quadrotor["theta0"] = 14.6 * (pi / 180) # theta0 Blade root angle quadrotor["theta1"] = ( quadrotor["thetat"] - quadrotor["theta0"] ) # theta1 Blade twist angle quadrotor["theta75"] = ( quadrotor["theta0"] + 0.75 * quadrotor["theta1"] ) # theta76 3/4 blade angle try: quadrotor["thetai"] = quadrotor["thetat"] * ( quadrotor["r"] / quadrotor["e"] ) # thetai Blade ideal root approximation except ZeroDivisionError: quadrotor["thetai"] = inf quadrotor["a"] = 5.5 # a Lift slope gradient # derived constants quadrotor["A"] = pi * quadrotor["r"] ** 2 # A Rotor disc area quadrotor["gamma"] = ( quadrotor["rho"] * quadrotor["a"] * quadrotor["c"] * quadrotor["r"] ** 4 / (quadrotor["Ib"] + quadrotor["Ic"]) ) # gamma Lock number quadrotor["b"] = ( quadrotor["Ct"] * quadrotor["rho"] * quadrotor["A"] * quadrotor["r"] ** 2 ) # T = b w^2 quadrotor["k"] = ( quadrotor["Cq"] * quadrotor["rho"] * quadrotor["A"] * quadrotor["r"] ** 3 ) # Q = k w^2 quadrotor["verbose"] = False
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/blocks/quad_model.py
0.568895
0.408985
quad_model.py
pypi
from roboticstoolbox.robot.Link import Link import numpy as np from roboticstoolbox.robot.Robot import Robot import spatialmath as sm class YuMi(Robot): """ Class that imports an ABB YuMi URDF model ``YuMi()`` is a class which imports an ABB YuMi (IRB14000) robot definition from a URDF file. The model describes its kinematic and graphical characteristics. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.URDF.YuMi() >>> print(robot) Defined joint configurations are: - qz, zero joint angle configuration, 'L' shaped configuration - qr, vertical 'READY' configuration :reference: - `https://github.com/OrebroUniversity/yumi <https://github.com/OrebroUniversity/yumi>`_ .. codeauthor:: Jesse Haviland .. sectionauthor:: Peter Corke """ def __init__(self): links, name, urdf_string, urdf_filepath = self.URDF_read( "yumi_description/urdf/yumi.urdf" ) # We wish to add an intermediate link between gripper_r_base and # @gripper_r_finger_r/l # This is because gripper_r_base contains a revolute joint which is # a part of the core kinematic chain and not the gripper. # So we wish for gripper_r_base to be part of the robot and # @gripper_r_finger_r/l to be in the gripper underneath a parent Link gripper_r_base = links[16] gripper_l_base = links[19] # Find the finger links r_gripper_links = [link for link in links if link.parent == gripper_r_base] l_gripper_links = [link for link in links if link.parent == gripper_l_base] # New intermediate links r_gripper = Link(name="r_gripper", parent=gripper_l_base) l_gripper = Link(name="l_gripper", parent=gripper_r_base) links.append(r_gripper) links.append(l_gripper) # Set the finger link parent to be the new gripper base link for g_link in r_gripper_links: g_link._parent = r_gripper for g_link in l_gripper_links: g_link._parent = l_gripper super().__init__( links, name=name, manufacturer="ABB", gripper_links=[r_gripper, l_gripper], urdf_string=urdf_string, urdf_filepath=urdf_filepath, ) # Set the default tool transform for the end-effectors self.grippers[0].tool = sm.SE3.Tz(0.13) self.grippers[1].tool = sm.SE3.Tz(0.13) self.qr = np.array( [ 0, -0.3, 0, -2.2, 0, 2.0, np.pi / 4, 0, -0.3, 0, -2.2, 0, 2.0, np.pi / 4, ] ) self.qz = np.zeros(14) self.q1 = np.array([0, -0.4, 0, 0, 0, 0, 0, 0, -0.4, 0, 0, 0, 0, 0]) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) self.addconfiguration("q1", self.q1) if __name__ == "__main__": # pragma nocover robot = YuMi() print(robot)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/URDF/YuMi.py
0.795142
0.487307
YuMi.py
pypi
import numpy as np from roboticstoolbox.robot.Robot import Robot from math import pi class Puma560(Robot): """ Class that imports a Puma 560 URDF model ``Puma560()`` is a class which imports a Unimation Puma560 robot definition from a URDF file. The model describes its kinematic and graphical characteristics. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.URDF.Puma560() >>> print(robot) Defined joint configurations are: - qz, zero joint angle configuration, 'L' shaped configuration - qr, vertical 'READY' configuration - qs, arm is stretched out in the x-direction - qn, arm is at a nominal non-singular configuration .. warning:: This file has been modified so that the zero-angle pose is the same as the DH model in the toolbox. ``j3`` rotation is changed from -𝜋/2 to 𝜋/2. Dimensions are also slightly different. Both models include the pedestal height. .. note:: The original file is from https://github.com/nimasarli/puma560_description/blob/master/urdf/puma560_robot.urdf.xacro .. codeauthor:: Jesse Haviland .. sectionauthor:: Peter Corke """ def __init__(self): links, name, urdf_string, urdf_filepath = self.URDF_read( "puma560_description/urdf/puma560_robot.urdf.xacro" ) super().__init__( links, name=name, urdf_string=urdf_string, urdf_filepath=urdf_filepath, ) self.manufacturer = "Unimation" # self.ee_link = self.ets[9] # ready pose, arm up self.qr = np.array([0, pi / 2, -pi / 2, 0, 0, 0]) self.qz = np.zeros(6) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) # zero angles, upper arm horizontal, lower up straight up self.addconfiguration_attr("qz", np.array([0, 0, 0, 0, 0, 0])) # reference pose, arm to the right, elbow up self.addconfiguration_attr( "ru", np.array([-0.0000, 0.7854, 3.1416, -0.0000, 0.7854, 0.0000]) ) # reference pose, arm to the right, elbow up self.addconfiguration_attr( "rd", np.array([-0.0000, -0.8335, 0.0940, -3.1416, 0.8312, 3.1416]) ) # reference pose, arm to the left, elbow up self.addconfiguration_attr( "lu", np.array([2.6486, -3.9270, 0.0940, 2.5326, 0.9743, 0.3734]) ) # reference pose, arm to the left, elbow down self.addconfiguration_attr( "ld", np.array([2.6486, -2.3081, 3.1416, 0.6743, 0.8604, 2.6611]) ) # straight and horizontal self.addconfiguration_attr("qs", np.array([0, 0, -pi / 2, 0, 0, 0])) # nominal table top picking pose self.addconfiguration_attr("qn", np.array([0, pi / 4, pi, 0, pi / 4, 0])) if __name__ == "__main__": # pragma nocover robot = Puma560() print(robot) print(robot.ee_links)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/URDF/Puma560.py
0.882028
0.495361
Puma560.py
pypi
import numpy as np from roboticstoolbox.robot.ET import ET from roboticstoolbox.robot.ETS import ETS from roboticstoolbox.robot.Robot import Robot from roboticstoolbox.robot.Link import Link class Frankie(Robot): """ A class representing the Franka Emika Panda robot arm. ETS taken from [1] based on https://frankaemika.github.io/docs/control_parameters.html :param et_list: List of elementary transforms which represent the robot kinematics :type et_list: list of etb.robot.et :param q_idx: List of indexes within the ets_list which correspond to joints :type q_idx: list of int :param name: Name of the robot :type name: str, optional :param manufacturer: Manufacturer of the robot :type manufacturer: str, optional :param base: Location of the base is the world frame :type base: float np.ndarray(4,4), optional :param tool: Offset of the flange of the robot to the end-effector :type tool: float np.ndarray(4,4), optional :param qz: The zero joint angle configuration of the robot :type qz: float np.ndarray(7,) :param qr: The ready state joint angle configuration of the robot :type qr: float np.ndarray(7,) References: [1] Kinematic Derivatives using the Elementary Transform Sequence, J. Haviland and P. Corke """ def __init__(self): deg = np.pi / 180 mm = 1e-3 tool_offset = (103) * mm b0 = Link(ETS(ET.Rz()), name="base0", parent=None) b1 = Link(ETS(ET.tx()), name="base1", parent=b0) l0 = Link(ET.tz(0.333) * ET.Rz(), name="link0", parent=b1) l1 = Link(ET.Rx(-90 * deg) * ET.Rz(), name="link1", parent=l0) l2 = Link(ET.Rx(90 * deg) * ET.tz(0.316) * ET.Rz(), name="link2", parent=l1) l3 = Link(ET.tx(0.0825) * ET.Rx(90 * deg) * ET.Rz(), name="link3", parent=l2) l4 = Link( ET.tx(-0.0825) * ET.Rx(-90 * deg) * ET.tz(0.384) * ET.Rz(), name="link4", parent=l3, ) l5 = Link(ET.Rx(90 * deg) * ET.Rz(), name="link5", parent=l4) l6 = Link( ET.tx(0.088) * ET.Rx(90 * deg) * ET.tz(0.107) * ET.Rz(), name="link6", parent=l5, ) ee = Link(ET.tz(tool_offset) * ET.Rz(-np.pi / 4), name="ee", parent=l6) elinks = [b0, b1, l0, l1, l2, l3, l4, l5, l6, ee] super(Frankie, self).__init__( elinks, name="Frankie", manufacturer="Franka Emika, Omron", keywords=("mobile",), ) self.qr = np.array([0, 0, 0, -0.3, 0, -2.2, 0, 2.0, np.pi / 4]) self.qz = np.zeros(9) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) if __name__ == "__main__": # pragma nocover robot = Frankie() print(robot)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/ETS/Frankie.py
0.85036
0.613526
Frankie.py
pypi
from roboticstoolbox import ET as ET from roboticstoolbox import Robot import numpy as np class Puma560(Robot): """ Create model of Franka-Emika Panda manipulator ``puma = Puma560()`` creates a robot object representing the classic Unimation Puma560 robot arm. This robot is represented using the elementary transform sequence (ETS). .. note:: - The model has different joint offset conventions compared to ``DH.Puma560()``. For this robot: - Zero joint angles ``qz`` is the vertical configuration, corresponding to ``qr`` with ``DH.Puma560()`` - ``qbent`` is the bent configuration, corresponding to ``qz`` with ``DH.Puma560()`` :references: - "A Simple and Systematic Approach to Assigning Denavit–Hartenberg Parameters,", P. I. Corke, in IEEE Transactions on Robotics, vol. 23, no. 3, pp. 590-594, June 2007, doi: 10.1109/TRO.2007.896765. - https://petercorke.com/robotics/a-simple-and-systematic-approach-to-assigning-denavit-hartenberg-parameters """ # noqa def __init__(self): # Puma dimensions (m) l1 = 0.672 l2 = -0.2337 l3 = 0.4318 l4 = 0.0203 l5 = 0.0837 l6 = 0.4318 e = ( ET.tz(l1) * ET.Rz() * ET.ty(l2) * ET.Ry() * ET.tz(l3) * ET.tx(l4) * ET.ty(l5) * ET.Ry() * ET.tz(l6) * ET.Rz() * ET.Ry() * ET.Rz() * ET.tx(0.2) ) super().__init__( e, name="Puma560", manufacturer="Unimation", comment="ETS-based model" ) self.qr = np.array([0, -np.pi / 2, np.pi / 2, 0, 0, 0]) self.qz = np.zeros(6) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) if __name__ == "__main__": # pragma nocover robot = Puma560() print(robot)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/ETS/Puma560.py
0.844537
0.487612
Puma560.py
pypi
import numpy as np from roboticstoolbox.robot.ET import ET from roboticstoolbox.robot.ETS import ETS from roboticstoolbox.robot.Robot import Robot from roboticstoolbox.robot.Link import Link class XYPanda(Robot): """ Create model of Franka-Emika Panda manipulator on an XY platform xypanda = XYPanda() creates a robot object representing the Franka-Emika Panda robot arm mounted on an XY platform. This robot is represented using the elementary transform sequence (ETS). ETS taken from [1] based on https://frankaemika.github.io/docs/control_parameters.html :references: - Kinematic Derivatives using the Elementary Transform Sequence, J. Haviland and P. Corke """ def __init__(self, workspace=5): """ Create model of Franka-Emika Panda manipulator on an XY platform. :param workspace: workspace limits in the x and y directions, defaults to 5 :type workspace: float, optional The XY part of the robot has a range -``workspace`` to ``workspace``. """ deg = np.pi / 180 mm = 1e-3 tool_offset = (103) * mm lx = Link( ETS(ET.tx()), name="link-x", parent=None, qlim=[-workspace, workspace] ) ly = Link(ETS(ET.ty()), name="link-y", parent=lx, qlim=[-workspace, workspace]) l0 = Link(ET.tz(0.333) * ET.Rz(), name="link0", parent=ly) l1 = Link(ET.Rx(-90 * deg) * ET.Rz(), name="link1", parent=l0) l2 = Link(ET.Rx(90 * deg) * ET.tz(0.316) * ET.Rz(), name="link2", parent=l1) l3 = Link(ET.tx(0.0825) * ET.Rx(90, "deg") * ET.Rz(), name="link3", parent=l2) l4 = Link( ET.tx(-0.0825) * ET.Rx(-90, "deg") * ET.tz(0.384) * ET.Rz(), name="link4", parent=l3, ) l5 = Link(ET.Rx(90, "deg") * ET.Rz(), name="link5", parent=l4) l6 = Link( ET.tx(0.088) * ET.Rx(90, "deg") * ET.tz(0.107) * ET.Rz(), name="link6", parent=l5, ) ee = Link(ET.tz(tool_offset) * ET.Rz(-np.pi / 4), name="ee", parent=l6) elinks = [lx, ly, l0, l1, l2, l3, l4, l5, l6, ee] super().__init__(elinks, name="XYPanda", manufacturer="Franka Emika") self.qr = np.array([0, 0, 0, -0.3, 0, -2.2, 0, 2.0, np.pi / 4]) self.qz = np.zeros(9) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) if __name__ == "__main__": # pragma nocover robot = XYPanda() print(robot)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/ETS/XYPanda.py
0.753194
0.561034
XYPanda.py
pypi
import numpy as np from roboticstoolbox.robot.ET import ET from roboticstoolbox.robot.ETS import ETS from roboticstoolbox.robot.Robot import Robot from roboticstoolbox.robot.Link import Link import spatialgeometry as sg import spatialmath as sm class Omni(Robot): """ A class an omnidirectional mobile robot. :param et_list: List of elementary transforms which represent the robot kinematics :type et_list: list of etb.robot.et :param q_idx: List of indexes within the ets_list which correspond to joints :type q_idx: list of int :param name: Name of the robot :type name: str, optional :param manufacturer: Manufacturer of the robot :type manufacturer: str, optional :param base: Location of the base is the world frame :type base: float np.ndarray(4,4), optional :param tool: Offset of the flange of the robot to the end-effector :type tool: float np.ndarray(4,4), optional :param qz: The zero joint angle configuration of the robot :type qz: float np.ndarray(7,) :param qr: The ready state joint angle configuration of the robot :type qr: float np.ndarray(7,) References: [1] Kinematic Derivatives using the Elementary Transform Sequence, J. Haviland and P. Corke """ def __init__(self): l, w, h = 0.55, 0.40, 0.35 b0 = Link(ETS(ET.Rz()), name="base0", parent=None, qlim=[-1000, 1000]) b1 = Link(ETS(ET.tx()), name="base1", parent=b0, qlim=[-1000, 1000]) b2 = Link(ETS(ET.ty()), name="base2", parent=b1, qlim=[-1000, 1000]) g0 = Link(name="gripper", parent=b2) b2.geometry = sg.Cuboid( [l, w, h], base=sm.SE3(0, 0, h / 2), color=(163, 157, 134) ) elinks = [b0, b1, b2, g0] super(Omni, self).__init__( elinks, name="Omni", manufacturer="Jesse", keywords=("mobile",), gripper_links=g0, ) self.qr = np.array([0, 0, 0]) self.qz = np.zeros(3) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) if __name__ == "__main__": # pragma nocover robot = Omni() print(robot)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/ETS/Omni.py
0.821152
0.572842
Omni.py
pypi
from roboticstoolbox import DHRobot, RevoluteDH from math import pi import numpy as np class KR5(DHRobot): """ Class that models a Kuka KR5 manipulator ``KR5()`` is a class which models a Kuka KR5 robot and describes its kinematic characteristics using standard DH conventions. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.DH.KR5() >>> print(robot) Defined joint configurations are: - qk1, nominal working position 1 - qk2, nominal working position 2 - qk3, nominal working position 3 .. note:: - SI units of metres are used. - Includes an 11.5cm tool in the z-direction :references: - https://github.com/4rtur1t0/ARTE/blob/master/robots/KUKA/KR5_arc/parameters.m .. codeauthor:: Gautam Sinha, Indian Institute of Technology, Kanpur (original MATLAB version) .. codeauthor:: Samuel Drew .. codeauthor:: Peter Corke """ # noqa def __init__(self): deg = pi / 180 # Updated values form ARTE git. Old values left as comments L1 = RevoluteDH( a=0.18, d=0.4, alpha=-pi / 2, qlim=[-155 * deg, 155 * deg] # alpha=pi / 2, ) L2 = RevoluteDH( a=0.6, d=0, alpha=0, qlim=[-180 * deg, 65 * deg] # d=0.135, # alpha=pi, ) L3 = RevoluteDH( a=0.12, d=0, # d=0.135, alpha=pi / 2, # alpha=-pi / 2, qlim=[-15 * deg, 158 * deg], ) L4 = RevoluteDH( a=0.0, d=-0.62, # d=0.62, alpha=-pi / 2, # alpha=pi / 2, qlim=[-350 * deg, 350 * deg], ) L5 = RevoluteDH( a=0.0, d=0.0, alpha=pi / 2, qlim=[-130 * deg, 130 * deg] # alpha=-pi / 2, ) L6 = RevoluteDH(a=0, d=-0.115, alpha=pi, qlim=[-350 * deg, 350 * deg]) L = [L1, L2, L3, L4, L5, L6] # Create SerialLink object super().__init__( L, # meshdir="KUKA/KR5_arc", name="KR5", manufacturer="KUKA", meshdir="meshes/KUKA/KR5_arc", ) self.qr = np.array([pi / 4, pi / 3, pi / 4, pi / 6, pi / 4, pi / 6]) self.qz = np.zeros(6) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) self.addconfiguration_attr( "qk1", np.array([pi / 4, pi / 3, pi / 4, pi / 6, pi / 4, pi / 6]) ) self.addconfiguration_attr( "qk2", np.array([pi / 4, pi / 3, pi / 6, pi / 3, pi / 4, pi / 6]) ) self.addconfiguration_attr( "qk3", np.array([pi / 6, pi / 3, pi / 6, pi / 3, pi / 6, pi / 3]) ) if __name__ == "__main__": # pragma nocover robot = KR5() print(robot)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/DH/KR5.py
0.879445
0.458955
KR5.py
pypi
import numpy as np from roboticstoolbox import DHRobot, RevoluteDH from spatialmath import SE3 class UR10(DHRobot): """ Class that models a Universal Robotics UR10 manipulator :param symbolic: use symbolic constants :type symbolic: bool ``UR10()`` is an object which models a Unimation Puma560 robot and describes its kinematic and dynamic characteristics using standard DH conventions. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.DH.UR10() >>> print(robot) Defined joint configurations are: - qz, zero joint angle configuration - qr, arm horizontal along x-axis .. note:: - SI units are used. :References: - `Parameters for calculations of kinematics and dynamics <https://www.universal-robots.com/articles/ur/parameters-for-calculations-of-kinematics-and-dynamics>`_ :sealso: :func:`UR3`, :func:`UR5` .. codeauthor:: Peter Corke """ # noqa def __init__(self, symbolic=False): if symbolic: import spatialmath.base.symbolic as sym zero = sym.zero() pi = sym.pi() else: from math import pi zero = 0.0 deg = pi / 180 inch = 0.0254 # robot length values (metres) a = [0, -0.612, -0.5723, 0, 0, 0] d = [0.1273, 0, 0, 0.163941, 0.1157, 0.0922] alpha = [pi / 2, zero, zero, pi / 2, -pi / 2, zero] # mass data, no inertia available mass = [7.1, 12.7, 4.27, 2.000, 2.000, 0.365] center_of_mass = [ [0.021, 0, 0.027], [0.38, 0, 0.158], [0.24, 0, 0.068], [0.0, 0.007, 0.018], [0.0, 0.007, 0.018], [0, 0, -0.026], ] links = [] for j in range(6): link = RevoluteDH( d=d[j], a=a[j], alpha=alpha[j], m=mass[j], r=center_of_mass[j], G=1 ) links.append(link) super().__init__( links, name="UR10", manufacturer="Universal Robotics", keywords=("dynamics", "symbolic"), symbolic=symbolic, ) self.qr = np.array([180, 0, 0, 0, 90, 0]) * deg self.qz = np.zeros(6) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) if __name__ == "__main__": # pragma nocover ur10 = UR10(symbolic=False) print(ur10) # print(ur10.dyntable())
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/DH/UR10.py
0.81648
0.649547
UR10.py
pypi
from math import pi, sin, cos import numpy as np from roboticstoolbox import DHRobot, RevoluteDH from spatialmath import SE3 class Mico(DHRobot): """ Class that models a Kinova Mico manipulator :param symbolic: use symbolic constants :type symbolic: bool ``Mico()`` is an object which models a Kinova Mico robot and describes its kinematic characteristics using standard DH conventions. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.DH.Puma560() >>> print(robot) Defined joint configurations are: - qz, zero joint angle configuration, 'L' shaped configuration - qr, vertical 'READY' configuration - qs, arm is stretched out in the x-direction - qn, arm is at a nominal non-singular configuration .. note:: - SI units are used. :references: - "DH Parameters of Mico" Version 1.0.8, July 25, 2013. :seealso: :func:`Mico` """ def __init__(self, symbolic=False): if symbolic: import spatialmath.base.symbolic as sym zero = sym.zero() pi = sym.pi() else: from math import pi zero = 0.0 deg = pi / 180 # robot length values (metres) D1 = 0.2755 D2 = 0.2900 D3 = 0.1233 D4 = 0.0741 D5 = 0.0741 D6 = 0.1600 e2 = 0.0070 # alternate parameters aa = 30 * deg ca = cos(aa) sa = sin(aa) c2a = cos(2 * aa) s2a = sin(2 * aa) d4b = D3 + sa / s2a * D4 d5b = sa / s2a * D4 + sa / s2a * D5 d6b = sa / s2a * D5 + D6 # and build a serial link manipulator # offsets from the table on page 4, "Mico" angles are the passed joint # angles. "DH Algo" are the result after adding the joint angle offset. super().__init__( [ RevoluteDH(alpha=pi / 2, a=0, d=D1, flip=True), RevoluteDH(alpha=pi, a=D2, d=0, offset=-pi / 2), RevoluteDH(alpha=pi / 2, a=0, d=-e2, offset=pi / 2), RevoluteDH(alpha=2 * aa, a=0, d=-d4b), RevoluteDH(alpha=2 * aa, a=0, d=-d5b, offset=-pi), RevoluteDH(alpha=pi, a=0, d=-d6b, offset=100 * deg), ], name="Mico", manufacturer="Kinova", keywords=("symbolic",), ) self.qr = np.array([270, 180, 180, 0, 0, 0]) * deg self.qz = np.zeros(6) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) if __name__ == "__main__": # pragma nocover mico = Mico(symbolic=False) print(mico)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/DH/Mico.py
0.892226
0.541409
Mico.py
pypi
from roboticstoolbox import DHRobot, RevoluteDH from math import pi import numpy as np class Ball(DHRobot): """ Class that models a ball manipulator :param N: number of links, defaults to 10 :type N: int, optional :param symbolic: [description], defaults to False :type symbolic: bool, optional The ball robot is an *abstract* robot with an arbitrary number of joints. At zero joint angles it is straight along the x-axis, and as the joint angles are increased (equally) it wraps up into a 3D ball shape. - ``Ball()`` is an object which describes the kinematic characteristics of a ball robot using standard DH conventions. - ``Ball(N)`` as above, but models a robot with ``N`` joints. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.DH.Ball() >>> print(robot) Defined joint configurations are: - qz, zero joint angles - q1, ball shaped configuration :references: - "A divide and conquer articulated-body algorithm for parallel O(log(n)) calculation of rigid body dynamics, Part 2", Int. J. Robotics Research, 18(9), pp 876-892. :seealso: :func:`Hyper`, :func:`Ball` .. codeauthor:: Peter Corke """ def __init__(self, N=10): links = [] q1 = [] for i in range(N): links.append(RevoluteDH(a=0.1, alpha=pi / 2)) # and build a serial link manipulator super(Ball, self).__init__(links, name="ball") self.qr = np.array([_fract(i) for i in range(N)]) self.qz = np.zeros(N) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) def _fract(i): # i is "i-1" as per the paper theta1 = 1 theta2 = -2 / 3 if i == 0: return theta1 elif i % 3 == 1: return theta1 elif i % 3 == 2: return theta2 elif i % 3 == 0: return _fract(i / 3) if __name__ == "__main__": # pragma nocover ball = Ball() print(ball)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/DH/Ball.py
0.924615
0.661882
Ball.py
pypi
import numpy as np from roboticstoolbox import DHRobot, RevoluteDH from spatialmath import SE3 class UR3(DHRobot): """ Class that models a Universal Robotics UR3 manipulator :param symbolic: use symbolic constants :type symbolic: bool ``UR3()`` is an object which models a Unimation Puma560 robot and describes its kinematic and dynamic characteristics using standard DH conventions. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.DH.UR3() >>> print(robot) Defined joint configurations are: - qz, zero joint angle configuration - qr, arm horizontal along x-axis .. note:: - SI units are used. :References: - `Parameters for calculations of kinematics and dynamics <https://www.universal-robots.com/articles/ur/parameters-for-calculations-of-kinematics-and-dynamics>`_ :sealso: :func:`UR5`, :func:`UR10` .. codeauthor:: Peter Corke """ # noqa def __init__(self, symbolic=False): if symbolic: import spatialmath.base.symbolic as sym zero = sym.zero() pi = sym.pi() else: from math import pi zero = 0.0 deg = pi / 180 inch = 0.0254 # robot length values (metres) a = [0, -0.24365, -0.21325, 0, 0, 0] d = [0.1519, 0, 0, 0.11235, 0.08535, 0.0819] alpha = [pi / 2, zero, zero, pi / 2, -pi / 2, zero] # mass data, no inertia available mass = [2, 3.42, 1.26, 0.8, 0.8, 0.35] center_of_mass = [ [0, -0.02, 0], [0.13, 0, 0.1157], [0.05, 0, 0.0238], [0, 0, 0.01], [0, 0, 0.01], [0, 0, -0.02], ] links = [] for j in range(6): link = RevoluteDH( d=d[j], a=a[j], alpha=alpha[j], m=mass[j], r=center_of_mass[j], G=1 ) links.append(link) super().__init__( links, name="UR3", manufacturer="Universal Robotics", keywords=("dynamics", "symbolic"), symbolic=symbolic, ) self.qr = np.array([180, 0, 0, 0, 90, 0]) * deg self.qz = np.zeros(6) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) if __name__ == "__main__": # pragma nocover ur3 = UR3(symbolic=False) print(ur3) # print(ur3.dyntable())
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/DH/UR3.py
0.814828
0.671336
UR3.py
pypi
import numpy as np from math import pi from roboticstoolbox import DHRobot, RevoluteDH from spatialmath import SE3 class Baxter(DHRobot): """ Class that models a Baxter manipulator :param symbolic: use symbolic constants :type symbolic: bool ``Baxter()`` is an object which models the left arm of the two 7-joint arms of a Rethink Robotics Baxter robot using standard DH conventions. ``Baxter(which)`` as above but models the specified arm and ``which`` is either 'left' or 'right'. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.DH.Baxter() >>> print(robot) Defined joint configurations are: - qz, zero joint angle configuration - qr, vertical 'READY' configuration - qs, arm is stretched out in the X direction - qd, lower arm horizontal as per data sheet .. note:: SI units are used. .. warning:: The base transform is set to reflect the pose of the arm's shoulder with respect to the base. Changing the base attribute of the arm will overwrite this, IT DOES NOT CHANGE THE POSE OF BAXTER's base. Instead do ``baxter.base = newbase * baxter.base``. :References: - "Kinematics Modeling and Experimental Verification of Baxter Robot" Z. Ju, C. Yang, H. Ma, Chinese Control Conf, 2015. .. codeauthor:: Peter Corke """ # noqa def __init__(self, arm="left"): links = [ RevoluteDH(d=0.27, a=0.069, alpha=-pi / 2), RevoluteDH(d=0, a=0, alpha=pi / 2, offset=pi / 2), RevoluteDH(d=0.102 + 0.262, a=0.069, alpha=-pi / 2), RevoluteDH(d=0, a=0, alpha=pi / 2), RevoluteDH(d=0.103 + 0.271, a=0.010, alpha=-pi / 2), RevoluteDH(d=0, a=0, alpha=pi / 2), RevoluteDH(d=0.28, a=0, alpha=0), ] super().__init__( links, name=f"Baxter-{arm}", manufacturer="Rethink Robotics", ) self.qr = np.array([0, -pi / 2, -pi / 2, 0, 0, 0, 0]) self.qz = np.zeros(7) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) # straight and horizontal self.addconfiguration_attr("qs", np.array([0, 0, -pi / 2, 0, 0, 0, 0])) # nominal table top picking pose self.addconfiguration_attr("qn", np.array([0, pi / 4, pi / 2, 0, pi / 4, 0, 0])) if arm == "left": self.base = SE3(0.064614, 0.25858, 0.119) * SE3.Rz(pi / 4) else: self.base = SE3(0.063534, -0.25966, 0.119) * SE3.Rz(-pi / 4) if __name__ == "__main__": # pragma nocover baxter = Baxter("left") print(baxter.name, baxter.base) # baxter.plot(baxter.qz, block=False) # baxter = Baxter('right') # print(baxter) # baxter.plot(baxter.qz)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/DH/Baxter.py
0.730963
0.553505
Baxter.py
pypi
import numpy as np from roboticstoolbox import DHRobot, RevoluteMDH from spatialmath import SE3 class AL5D(DHRobot): """ Class that models a Lynxmotion AL5D manipulator :param symbolic: use symbolic constants :type symbolic: bool ``AL5D()`` is an object which models a Lynxmotion AL5D robot and describes its kinematic and dynamic characteristics using modified DH conventions. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.DH.AL5D() >>> print(robot) Defined joint configurations are: - qz, zero joint angle configuration .. note:: - SI units are used. :References: - 'Reference of the robot <http://www.lynxmotion.com/c-130-al5d.aspx>'_ .. codeauthor:: Tassos Natsakis """ # noqa def __init__(self, symbolic=False): if symbolic: import spatialmath.base.symbolic as sym # zero = sym.zero() pi = sym.pi() else: from math import pi # zero = 0.0 # robot length values (metres) a = [0, 0.002, 0.14679, 0.17751] d = [-0.06858, 0, 0, 0] alpha = [pi, pi / 2, pi, pi] offset = [pi / 2, pi, -0.0427, -0.0427 - pi / 2] # mass data as measured # mass = [0.187, 0.044, 0.207, 0.081] # center of mass as calculated through CAD model center_of_mass = [ [0.01724, -0.00389, 0.00468], [0.07084, 0.00000, 0.00190], [0.05615, -0.00251, -0.00080], [0.04318, 0.00735, -0.00523], ] # moments of inertia are practically zero moments_of_inertia = [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], ] joint_limits = [ [-pi / 2, pi / 2], [-pi / 2, pi / 2], [-pi / 2, pi / 2], [-pi / 2, pi / 2], ] links = [] for j in range(3): link = RevoluteMDH( d=d[j], a=a[j], alpha=alpha[j], offset=offset[j], r=center_of_mass[j], I=moments_of_inertia[j], G=1, B=0, Tc=[0, 0], qlim=joint_limits[j], ) links.append(link) tool = SE3(0.07719, 0, 0) super().__init__( links, name="AL5D", manufacturer="Lynxmotion", keywords=("dynamics", "symbolic"), symbolic=symbolic, tool=tool, ) # zero angles self.addconfiguration("home", np.array([pi / 2, pi / 2, pi / 2, pi / 2])) if __name__ == "__main__": # pragma nocover al5d = AL5D(symbolic=False) print(al5d) # print(al5d.dyntable())
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/DH/AL5D.py
0.743168
0.67842
AL5D.py
pypi
import numpy as np from spatialmath.base import trotz, transl from roboticstoolbox import DHRobot, RevoluteDH class LWR4(DHRobot): """ Class that models a LWR-IV manipulator ``LWR4()`` is a class which models a Kuka LWR-IV robot and describes its kinematic characteristics using standard DH conventions. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.DH.LWR4() >>> print(robot) Defined joint configurations are: - qz, zero joint angle configuration, 'L' shaped configuration - qr, vertical 'READY' configuration - qs, arm is stretched out in the X direction - qn, arm is at a nominal non-singular configuration .. note:: SI units are used. :references: - http://www.diag.uniroma1.it/~deluca/rob1_en/09_Exercise_DH_KukaLWR4.pdf .. codeauthor:: Peter Corke """ # noqa def __init__(self): # deg = np.pi/180 mm = 1e-3 tool_offset = (103) * mm flange = 0 * mm # d7 = (58.4)*mm # This Kuka model is defined using modified # Denavit-Hartenberg parameters L = [ RevoluteDH(a=0.0, d=0, alpha=np.pi / 2, qlim=np.array([-2.8973, 2.8973])), RevoluteDH( a=0.0, d=0.0, alpha=-np.pi / 2, qlim=np.array([-1.7628, 1.7628]) ), RevoluteDH( a=0.0, d=0.40, alpha=-np.pi / 2, qlim=np.array([-2.8973, 2.8973]) ), RevoluteDH( a=0.0, d=0.0, alpha=np.pi / 2, qlim=np.array([-3.0718, -0.0698]) ), RevoluteDH( a=0.0, d=0.39, alpha=np.pi / 2, qlim=np.array([-2.8973, 2.8973]) ), RevoluteDH( a=0.0, d=0.0, alpha=-np.pi / 2, qlim=np.array([-0.0175, 3.7525]) ), RevoluteDH(a=0.0, d=flange, alpha=0.0, qlim=np.array([-2.8973, 2.8973])), ] tool = transl(0, 0, tool_offset) @ trotz(-np.pi / 4) super().__init__(L, name="LWR-IV", manufacturer="Kuka", tool=tool) # tool = xyzrpy_to_trans(0, 0, d7, 0, 0, -np.pi/4) self.qr = np.array(7) self.qz = np.zeros(7) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) if __name__ == "__main__": # pragma nocover robot = LWR4() print(robot)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/DH/LWR4.py
0.753104
0.441854
LWR4.py
pypi
from roboticstoolbox import DHRobot, RevoluteDH from math import pi import numpy as np class IRB140(DHRobot): """ Class that models an ABB IRB140 manipulator ``IRB140()`` is a class which models a Unimation Puma560 robot and describes its kinematic and dynamic characteristics using standard DH conventions. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.DH.IRB140() >>> print(robot) Defined joint configurations are: - qz, zero joint angle configuration - qr, vertical 'READY' configuration - qd, lower arm horizontal as per data sheet .. note:: SI units of metres are used. :references: - "IRB 140 data sheet", ABB Robotics. - "Utilizing the Functional Work Space Evaluation Tool for Assessing a System Design and Reconfiguration Alternatives" A. Djuric and R. J. Urbanic - https://github.com/4rtur1t0/ARTE/blob/master/robots/ABB/IRB140/parameters.m .. codeauthor:: Peter Corke """ # noqa def __init__(self): deg = pi / 180 # robot length values (metres) d1 = 0.352 a1 = 0.070 a2 = 0.360 d4 = 0.380 d6 = 0.065 # Create Links # Updated values form ARTE git. Old values left as comments L = [ RevoluteDH( d=d1, a=a1, alpha=-pi / 2, m=34655.36e-3, r=np.array([27.87, 43.12, -89.03]) * 1e-3, I=np.array( [ 512052539.74, 1361335.88, 51305020.72, 1361335.88, 464074688.59, 70335556.04, 51305020.72, 70335556.04, 462745526.12, ] ) * 1e-9, qlim=[-180 * deg, 180 * deg], ), RevoluteDH( d=0, a=a2, alpha=0, m=15994.59e-3, r=np.array([198.29, 9.73, 92.43]) * 1e03, I=np.array( [ 94817914.40, -3859712.77, 37932017.01, -3859712.77, 328604163.24, -1088970.86, 37932017.01, -1088970.86, 277463004.88, ] ) * 1e-9, qlim=[-100 * deg, 100 * deg], ), RevoluteDH( d=0, a=0, alpha=-pi / 2, # alpha=pi/2, m=20862.05e-3, r=np.array([-4.56, -79.96, -5.86]), I=np.array( [ 500060915.95, -1863252.17, 934875.78, -1863252.17, 75152670.69, -15204130.09, 934875.78, -15204130.09, 515424754.34, ] ) * 1e-9, qlim=[-220 * deg, 60 * deg], ), RevoluteDH( d=d4, a=0, alpha=pi / 2, qlim=[-200 * deg, 200 * deg] # alpha=-pi/2, ), RevoluteDH( d=0, a=0, alpha=-pi / 2, qlim=[-120 * deg, 120 * deg] # alpha=pi/2, ), RevoluteDH(d=d6, a=0, alpha=0, qlim=[-400 * deg, 400 * deg]), # alpha=pi/2, ] super().__init__( L, # basemesh="ABB/IRB140/link0.stl", name="IRB 140", manufacturer="ABB", meshdir="meshes/ABB/IRB140", ) self.qr = np.array([0, -90 * deg, 90 * deg, 0, 90 * deg, -90 * deg]) self.qz = np.zeros(6) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) self.addconfiguration_attr( "qd", np.array([0, -90 * deg, 180 * deg, 0, 0, -90 * deg]) ) if __name__ == "__main__": # pragma nocover robot = IRB140() print(robot)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/DH/IRB140.py
0.874594
0.527803
IRB140.py
pypi
import numpy as np from roboticstoolbox import DHRobot, RevoluteDH class Sawyer(DHRobot): """ Class that models a Sawyer manipulator :param symbolic: use symbolic constants :type symbolic: bool ``Sawyer()`` is an object which models a Rethink Sawyer robot and describes its kinematic characteristics using standard DH conventions. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.DH.Sawyer() >>> print(robot) Defined joint configurations are: - qz, zero joint angle configuration, 'L' shaped configuration :references: -`Layeghi, Daniel. “Dynamic and Kinematic Modelling of the Sawyer Arm ” Google Sites, 20 Nov. 2017 <https://sites.google.com/site/daniellayeghi/daily-work-and-writing/major-project-2>`_ .. note:: SI units of metres are used. """ def __init__(self, symbolic=False): if symbolic: import spatialmath.base.symbolic as sym # zero = sym.zero() pi = sym.pi() else: from math import pi # zero = 0.0 # deg = pi / 180 mm = 1e-3 # kinematic parameters a = np.r_[81, 0, 0, 0, 0, 0, 0] * mm d = np.r_[317, 192.5, 400, 168.5, 400, 136.3, 133.75] * mm alpha = [-pi / 2, -pi / 2, -pi / 2, -pi / 2, -pi / 2, -pi / 2, 0] links = [] for j in range(7): link = RevoluteDH(d=d[j], a=a[j], alpha=alpha[j]) links.append(link) super().__init__( links, name="Sawyer", manufacturer="Rethink Robotics", keywords=( "redundant", "symbolic", ), symbolic=symbolic, ) self.qr = np.zeros(7) self.qz = np.zeros(7) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) if __name__ == "__main__": # pragma nocover sawyer = Sawyer(symbolic=False) print(sawyer)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/DH/Sawyer.py
0.834069
0.533094
Sawyer.py
pypi
import numpy as np from spatialmath.base import trotz, transl from roboticstoolbox import DHRobot, RevoluteMDH class Panda(DHRobot): """ A class representing the Panda robot arm. ``Panda()`` is a class which models a Franka-Emika Panda robot and describes its kinematic characteristics using modified DH conventions. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.DH.Panda() >>> print(robot) .. note:: - SI units of metres are used. - The model includes a tool offset. :references: - https://frankaemika.github.io/docs/control_parameters.html .. codeauthor:: Samuel Drew .. codeauthor:: Peter Corke """ def __init__(self): # deg = np.pi/180 mm = 1e-3 tool_offset = (103) * mm flange = (107) * mm # d7 = (58.4)*mm # This Panda model is defined using modified # Denavit-Hartenberg parameters L = [ RevoluteMDH( a=0.0, d=0.333, alpha=0.0, qlim=np.array([-2.8973, 2.8973]), m=4.970684, I=[ 7.03370e-01, 7.06610e-01, 9.11700e-03, -1.39000e-04, 1.91690e-02, 6.77200e-03, ], G=1, ), RevoluteMDH( a=0.0, d=0.0, alpha=-np.pi / 2, qlim=np.array([-1.7628, 1.7628]), m=0.646926, I=[ 7.96200e-03, 2.81100e-02, 2.59950e-02, -3.92500e-03, 7.04000e-04, 1.02540e-02, ], G=1, ), RevoluteMDH( a=0.0, d=0.316, alpha=np.pi / 2, qlim=np.array([-2.8973, 2.8973]), m=3.228604, I=[ 3.72420e-02, 3.61550e-02, 1.08300e-02, -4.76100e-03, -1.28050e-02, -1.13960e-02, ], G=1, ), RevoluteMDH( a=0.0825, d=0.0, alpha=np.pi / 2, qlim=np.array([-3.0718, -0.0698]), m=3.587895, I=[ 2.58530e-02, 1.95520e-02, 2.83230e-02, 7.79600e-03, 8.64100e-03, -1.33200e-03, ], G=1, ), RevoluteMDH( a=-0.0825, d=0.384, alpha=-np.pi / 2, qlim=np.array([-2.8973, 2.8973]), m=1.225946, I=[ 3.55490e-02, 2.94740e-02, 8.62700e-03, -2.11700e-03, 2.29000e-04, -4.03700e-03, ], G=1, ), RevoluteMDH( a=0.0, d=0.0, alpha=np.pi / 2, qlim=np.array([-0.0175, 3.7525]), m=1.666555, I=[ 1.96400e-03, 4.35400e-03, 5.43300e-03, 1.09000e-04, 3.41000e-04, -1.15800e-03, ], G=1, ), RevoluteMDH( a=0.088, d=flange, alpha=np.pi / 2, qlim=np.array([-2.8973, 2.8973]), m=7.35522e-01, I=[ 1.25160e-02, 1.00270e-02, 4.81500e-03, -4.28000e-04, -7.41000e-04, -1.19600e-03, ], G=1, ), ] tool = transl(0, 0, tool_offset) @ trotz(-np.pi / 4) super().__init__( L, name="Panda", manufacturer="Franka Emika", meshdir="meshes/FRANKA-EMIKA/Panda", tool=tool, ) self.qr = np.array([0, -0.3, 0, -2.2, 0, 2.0, np.pi / 4]) self.qz = np.zeros(7) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) if __name__ == "__main__": # pragma nocover panda = Panda() print(panda)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/DH/Panda.py
0.730097
0.391813
Panda.py
pypi
import numpy as np from roboticstoolbox import DHRobot, RevoluteDH class Coil(DHRobot): """ Create model of a coil manipulator :param N: number of links, defaults to 10 :type N: int, optional :param symbolic: [description], defaults to False :type symbolic: bool, optional The coil robot is an *abstract* robot with an arbitrary number of joints that folds into a helix shape. At zero joint angles it is straight along the x-axis, and as the joint angles are increased (equally) it wraps up into a 3D helix shape. - ``Coil()`` is an object which describes the kinematic characteristics of a coil robot using standard DH conventions. - ``Coil(N)`` as above, but models a robot with ``N`` joints. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.DH.Coil() >>> print(robot) Defined joint configurations are: - qz, zero joint angle configuration :references: - "A divide and conquer articulated-body algorithm for parallel O(log(n)) calculation of rigid body dynamics, Part 2", Int. J. Robotics Research, 18(9), pp 876-892. :seealso: :func:`Hyper`, :func:`Ball` .. codeauthor:: Peter Corke """ # noqa def __init__(self, N=10, symbolic=False): if symbolic: import spatialmath.base.symbolic as sym pi = sym.pi() else: from math import pi a = 1 / N links = [] for i in range(N): links.append(RevoluteDH(a=a, alpha=5 * pi / N)) super().__init__( links, name="Coil" + str(N), keywords=("symbolic",), symbolic=symbolic ) self.qr = np.array(np.ones(N) * 10 * pi / N) self.qz = np.zeros(N) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) if __name__ == "__main__": # pragma nocover coil = Coil(N=10, symbolic=False) print(coil) # print(coil.fkine(coil.qz)) # print(coil.fkine(coil.qf))
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/DH/Coil.py
0.847999
0.709535
Coil.py
pypi
import numpy as np from roboticstoolbox import DHRobot, RevoluteDH from spatialmath import SE3 class UR5(DHRobot): """ Class that models a Universal Robotics UR5 manipulator :param symbolic: use symbolic constants :type symbolic: bool ``UR5()`` is an object which models a Unimation Puma560 robot and describes its kinematic and dynamic characteristics using standard DH conventions. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.DH.UR5() >>> print(robot) Defined joint configurations are: - qz, zero joint angle configuration - qr, arm horizontal along x-axis .. note:: - SI units are used. :References: - `Parameters for calculations of kinematics and dynamics <https://www.universal-robots.com/articles/ur/parameters-for-calculations-of-kinematics-and-dynamics>`_ :sealso: :func:`UR4`, :func:`UR10` .. codeauthor:: Peter Corke """ # noqa def __init__(self, symbolic=False): if symbolic: import spatialmath.base.symbolic as sym zero = sym.zero() pi = sym.pi() else: from math import pi zero = 0.0 deg = pi / 180 inch = 0.0254 # robot length values (metres) a = [0, -0.42500, -0.39225, 0, 0, 0] d = [0.089459, 0, 0, 0.10915, 0.09465, 0.0823] alpha = [pi / 2, zero, zero, pi / 2, -pi / 2, zero] # mass data, no inertia available mass = [3.7000, 8.3930, 2.33, 1.2190, 1.2190, 0.1897] center_of_mass = [ [0, -0.02561, 0.00193], [0.2125, 0, 0.11336], [0.15, 0, 0.0265], [0, -0.0018, 0.01634], [0, -0.0018, 0.01634], [0, 0, -0.001159], ] links = [] for j in range(6): link = RevoluteDH( d=d[j], a=a[j], alpha=alpha[j], m=mass[j], r=center_of_mass[j], G=1 ) links.append(link) super().__init__( links, name="UR5", manufacturer="Universal Robotics", keywords=("dynamics", "symbolic"), symbolic=symbolic, ) self.qr = np.array([180, 0, 0, 0, 90, 0]) * deg self.qz = np.zeros(6) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) if __name__ == "__main__": # pragma nocover ur5 = UR5(symbolic=False) print(ur5) # print(ur5.dyntable())
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/DH/UR5.py
0.819965
0.684844
UR5.py
pypi
from math import pi import numpy as np from roboticstoolbox import DHRobot, RevoluteDH from spatialmath import SE3 class Orion5(DHRobot): """ Class that models a RAWR robotics Orion5 manipulator ``Orion5()`` is a class which models a RAWR Robotics Orion5 robot and describes its kinematic characteristics using standard DH conventions. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> robot = rtb.models.DH.Orion5() >>> print(robot) Defined joint configurations are: - qz, zero angles, all folded up - qv, stretched out vertically - qh, arm horizontal, hand down .. note:: - SI units of metres are used. - Robot has only 4 DoF. :references: - https://rawrobotics.com.au/orion5 - https://drive.google.com/file/d/0B6_9_-ZgiRdTNkVqMEkxN2RSc2c/view .. codeauthor:: Aditya Dua .. codeauthor:: Peter Corke """ def __init__(self, base=None): mm = 1e-3 deg = pi / 180 # details from h = 53.0 * mm r = 30.309 * mm l2 = 170.384 * mm l3 = 136.307 * mm l4 = 86.00 * mm c = 40.0 * mm # tool_offset = l4 + c # Turret, Shoulder, Elbow, Wrist, Claw links = [ RevoluteDH(d=h, a=0, alpha=90 * deg), # Turret RevoluteDH(d=0, a=l2, alpha=0, qlim=[10 * deg, 122.5 * deg]), # Shoulder RevoluteDH(d=0, a=-l3, alpha=0, qlim=[20 * deg, 340 * deg]), # Elbow RevoluteDH(d=0, a=l4 + c, alpha=0, qlim=[45 * deg, 315 * deg]), # Wrist ] super().__init__( links, name="Orion 5", manufacturer="RAWR Robotics", base=SE3(r, 0, 0), tool=SE3.Ry(90, "deg"), ) self.qr = np.array([0, 0, 180, 90]) * deg self.qz = np.zeros(4) self.addconfiguration("qr", self.qr) self.addconfiguration("qz", self.qz) # stretched out vertically self.addconfiguration_attr("qv", np.r_[0, 90, 180, 180] * deg) # arm horizontal, hand down self.addconfiguration_attr("qh", np.r_[0, 0, 180, 90] * deg) if __name__ == "__main__": # pragma nocover orion = Orion5() print(orion)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/models/DH/Orion5.py
0.852506
0.485966
Orion5.py
pypi
import numpy as np from spatialmath import Twist3, SE3 from spatialmath.base import skew from roboticstoolbox.robot import Link, Robot class PoELink(Link): """ Product of exponential link class This is a subclass of the base Link class. :seealso: :class:`Link` """ def __init__(self, twist, name=None): super().__init__() self.S = Twist3(twist) self.name = name def __repr__(self): s = f"PoELink({np.array2string(self.S.S, separator=',')}" if self.name is not None: s += f', name="{self.name}"' s += ")" return s def __str__(self): s = f"{self.__class__.__name__}[twist={self.S}" if self.name is not None: s += f', name="{self.name}"' s += "]" return s class PoERevolute(PoELink): def __init__(self, axis, point, **kwargs): """ Construct revolute product of exponential link :param axis: axis of rotation :type axis: array_like(3) :param point: point on axis of rotation :type point: array_like(3) Construct a link and revolute joint for a PoE Robot. :seealso: :class:`Link` :class:`Robot` """ super().__init__(Twist3.UnitRevolute(axis, point), **kwargs) class PoEPrismatic(PoELink): def __init__(self, axis, **kwargs): """ Construct prismatic product of exponential link :param axis: direction of motion :type axis: array_like(3) Construct a link and prismatic joint for a PoE Robot. :seealso: :class:`Link` :class:`Robot` """ super().__init__(Twist3.UnitPrismatic(axis), **kwargs) class PoERobot(Robot): def __init__(self, links, T0, **kwargs): """ Product of exponential robot class :param links: robot links :type links: list of ``PoELink`` :param T0: end effector pose for zero joint coordinates :type T0: SE3 This is a subclass of the abstract base Robot class that provides only forward kinematics and world-frame Jacobian. :seealso: :class:`PoEPrismatic` :class:`PoERevolute` """ self._n = len(links) super().__init__(links, **kwargs) self.T0 = T0 def __str__(self): """ Pretty prints the PoE Model of the robot. :return: Pretty print of the robot model :rtype: str """ s = "PoERobot:\n" for j, link in enumerate(self): s += f" {j}: {link.S}\n" s += f" T0: {self.T0.strline()}" return s def __repr__(self): s = "PoERobot([\n" s += "\n".join([" " + repr(link) + "," for link in self]) s += "\n ],\n" s += f" T0=SE3({np.array_repr(self.T0.A)}),\n" s += f" name=\"{self.name}\",\n" s += ")" return s def nbranches(self): return 0 def fkine(self, q): """ Forward kinematics :param q: joint configuration :type q: array_like(n) :return: end effector pose :rtype: SE3 """ T = None for link, qk in zip(self, q): if T is None: T = link.S.exp(qk) else: T *= link.S.exp(qk) return T * self.T0 # T = reduce(lambda x, y: x * y, # [link.A(qk) for link, qk in zip(self, q)]) def jacob0(self, q): """ Jacobian in world frame :param q: joint configuration :type q: array_like(n) :return: Jacobian matrix :rtype: ndarray(6,n) """ columns = [] T = SE3() for link, qk in zip(self, q): columns.append(T.Ad() @ link.S.S) T *= link.S.exp(qk) T *= self.T0 J = np.column_stack(columns) # convert Jacobian from velocity twist to spatial velocity Jsv = np.eye(6) Jsv[:3, 3:] = -skew(T.t) return Jsv @ J def jacobe(self, q): """ Jacobian in end-effector frame :param q: joint configuration :type q: array_like(n) :return: Jacobian matrix :rtype: ndarray(6,n) """ columns = [] T = SE3() for link, qk in zip(self, q): columns.append(T.Ad() @ link.S.S) T *= link.S.exp(qk) T *= self.T0 J = np.column_stack(columns) # convert velocity twist from world frame to EE frame return T.inv().Ad() @ J def ets(self): return NotImplemented if __name__ == "__main__": # pragma nocover T0 = SE3.Trans(2, 0, 0) # rotate about z-axis, through (0,0,0) link1 = PoERevolute([0, 0, 1], [0, 0, 0], name="foo") # rotate about z-axis, through (1,0,0) link2 = PoERevolute([0, 0, 1], [1, 0, 0]) # end-effector pose when q=[0,0] TE0 = SE3.Trans(2, 0, 0) print(repr(link1)) print(link1) robot = PoERobot([link1, link2], T0) q = [0, np.pi / 2] # q = [0, 0] # robot.fkine(q).printline() # print(robot.jacob0(q)) # print(robot.jacobe(q)) print(repr(robot)) print(robot)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/robot/PoERobot.py
0.845353
0.452415
PoERobot.py
pypi
import numpy as np from roboticstoolbox.tools.types import ArrayLike, NDArray from typing import Any, Callable, Generic, List, Set, TypeVar, Union, Dict, Tuple, Type from typing_extensions import Protocol, Self from roboticstoolbox.robot.Link import Link, BaseLink from roboticstoolbox.robot.Gripper import Gripper from roboticstoolbox.robot.ETS import ETS from spatialmath import SE3 import roboticstoolbox as rtb class KinematicsProtocol(Protocol): @property def _T(self) -> NDArray: ... def ets( self, start: Union[Link, Gripper, str, None] = None, end: Union[Link, Gripper, str, None] = None, ) -> ETS: ... class RobotProto(Protocol): @property def links(self) -> List[BaseLink]: ... @property def n(self) -> int: ... @property def q(self) -> NDArray: ... @property def name(self) -> str: ... @name.setter def name(self, new_name: str): ... @property def gravity(self) -> NDArray: ... def dynchanged(self): ... def jacobe( self, q: ArrayLike, end: Union[str, BaseLink, Gripper, None] = None, start: Union[str, BaseLink, Gripper, None] = None, tool: Union[NDArray, SE3, None] = None, ) -> NDArray: ... def jacob0( self, q: ArrayLike, end: Union[str, BaseLink, Gripper, None] = None, start: Union[str, BaseLink, Gripper, None] = None, tool: Union[NDArray, SE3, None] = None, ) -> NDArray: ... def copy(self) -> Self: ... def accel(self, q, qd, torque, gravity=None) -> NDArray: ... def nofriction(self, coulomb: bool, viscous: bool) -> Self: ... def _fdyn( self, t: float, x: NDArray, torqfun: Callable[[Any], NDArray], targs: Dict, ) -> NDArray: ... def rne( self, q: NDArray, qd: NDArray, qdd: NDArray, symbolic: bool = False, gravity: Union[None, ArrayLike] = None, ) -> NDArray: ... def gravload( self, q: Union[None, ArrayLike] = None, gravity: Union[None, ArrayLike] = None ): ... def pay( self, W: ArrayLike, q: Union[NDArray, None] = None, J: Union[NDArray, None] = None, frame: int = 1, ): ...
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/robot/RobotProto.py
0.853898
0.356251
RobotProto.py
pypi
import numpy as np from abc import ABC, abstractmethod from typing import Tuple, Union import roboticstoolbox as rtb from dataclasses import dataclass from spatialmath import SE3 from roboticstoolbox.tools.types import ArrayLike try: import qpsolvers as qp _qp = True except ImportError: # pragma nocover _qp = False @dataclass class IKSolution: """ A dataclass for representing an IK solution Attributes ---------- q The joint coordinates of the solution (ndarray). Note that these will not be valid if failed to find a solution success True if a valid solution was found iterations How many iterations were performed searches How many searches were performed residual The final error value from the cost function reason The reason the IK problem failed if applicable .. versionchanged:: 1.0.3 Added IKSolution dataclass to replace the IKsolution named tuple """ q: np.ndarray success: bool iterations: int = 0 searches: int = 0 residual: float = 0.0 reason: str = "" def __iter__(self): return iter( ( self.q, self.success, self.iterations, self.searches, self.residual, self.reason, ) ) def __str__(self): if self.q is not None: q_str = np.array2string( self.q, separator=", ", formatter={ "float": lambda x: "{:.4g}".format(0 if abs(x) < 1e-6 else x) }, ) # np.round(self.q, 4) else: q_str = None if self.iterations == 0 and self.searches == 0: # Check for analytic if self.success: return f"IKSolution: q={q_str}, success=True" else: return f"IKSolution: q={q_str}, success=False, reason={self.reason}" else: # Otherwise it is a numeric solution if self.success: return ( f"IKSolution: q={q_str}, success=True," f" iterations={self.iterations}, searches={self.searches}," f" residual={self.residual:.3g}" ) else: return ( f"IKSolution: q={q_str}, success=False, reason={self.reason}," f" iterations={self.iterations}, searches={self.searches}," f" residual={np.round(self.residual, 4):.3g}" ) class IKSolver(ABC): """ An abstract super class for numerical inverse kinematics (IK) This class provides basic functionality to perform numerical IK. Superclasses can inherit this class and implement the `solve` method and redefine any other methods necessary. Parameters ---------- name The name of the IK algorithm ilimit How many iterations are allowed within a search before a new search is started slimit How many searches are allowed before being deemed unsuccessful tol Maximum allowed residual error E mask A 6 vector which assigns weights to Cartesian degrees-of-freedom error priority joint_limits Reject solutions with joint limit violations seed A seed for the private RNG used to generate random joint coordinate vectors See Also -------- IK_NR Implements this class using the Newton-Raphson method IK_GN Implements this class using the Gauss-Newton method IK_LM Implements this class using the Levemberg-Marquadt method IK_QP Implements this class using a quadratic programming approach .. versionchanged:: 1.0.3 Added the abstract super class IKSolver """ def __init__( self, name: str = "IK Solver", ilimit: int = 30, slimit: int = 100, tol: float = 1e-6, mask: Union[ArrayLike, None] = None, joint_limits: bool = True, seed: Union[int, None] = None, ): # Solver parameters self.name = name self.slimit = slimit self.ilimit = ilimit self.tol = tol # Random number generator self._private_random = np.random.default_rng(seed=seed) if mask is None: mask = np.ones(6) self.We = np.diag(mask) # type: ignore self.joint_limits = joint_limits def solve( self, ets: "rtb.ETS", Tep: Union[SE3, np.ndarray], q0: Union[ArrayLike, None] = None, ) -> IKSolution: """ Solves the IK problem This method will attempt to solve the IK problem and obtain joint coordinates which result the the end-effector pose `Tep`. Parameters ---------- ets The ETS representing the manipulators kinematics Tep The desired end-effector pose q0 The initial joint coordinate vector Returns ------- q The joint coordinates of the solution (ndarray). Note that these will not be valid if failed to find a solution success True if a valid solution was found iterations How many iterations were performed searches How many searches were performed residual The final error value from the cost function jl_valid True if q is inbounds of the robots joint limits reason The reason the IK problem failed if applicable """ # Get the largest jindex in the ETS. If this is greater than ETS.n # then we need to pad the q vector with zeros max_jindex: int = 0 for j in ets.joints(): if j.jindex > max_jindex: # type: ignore max_jindex = j.jindex # type: ignore q0_method = np.zeros((self.slimit, max_jindex + 1)) if q0 is None: q0_method[:, ets.jindices] = self._random_q(ets, self.slimit) elif not isinstance(q0, np.ndarray): q0 = np.array(q0) if q0 is not None and q0.ndim == 1: q0_method[:, ets.jindices] = self._random_q(ets, self.slimit) q0_method[0, ets.jindices] = q0 if q0 is not None and q0.ndim == 2: q0_method[:, ets.jindices] = self._random_q(ets, self.slimit) q0_method[: q0.shape[0], ets.jindices] = q0 q0 = q0_method traj = False methTep: np.ndarray if isinstance(Tep, SE3): if len(Tep) > 1: traj = True methTep = np.empty((len(Tep), 4, 4)) for i, T in enumerate(Tep): methTep[i] = T.A else: methTep = Tep.A elif Tep.ndim == 3: traj = True methTep = Tep elif Tep.shape != (4, 4): raise ValueError("Tep must be a 4x4 SE3 matrix") else: methTep = Tep if traj: q = np.empty((methTep.shape[0], ets.n)) success = True interations = 0 searches = 0 residual = np.inf reason = "" for i, T in enumerate(methTep): sol = self._solve(ets, T, q0) q[i] = sol.q if not sol.success: success = False reason = sol.reason interations += sol.iterations searches += sol.searches if sol.residual < residual: residual = sol.residual return IKSolution( q=q, success=success, iterations=interations, searches=searches, residual=residual, reason=reason, ) else: sol = self._solve(ets, methTep, q0) return sol def _solve(self, ets: "rtb.ETS", Tep: np.ndarray, q0: np.ndarray) -> IKSolution: # Iteration count i = 0 total_i = 0 # Error flags found_with_limits = False linalg_error = 0 # Initialise variables E = 0.0 q = q0[0] for search in range(self.slimit): q = q0[search].copy() i = 0 while i < self.ilimit: i += 1 # Attempt a step try: E, q[ets.jindices] = self.step(ets, Tep, q) except np.linalg.LinAlgError: # Abandon search and try again linalg_error += 1 break # Check if we have arrived if E < self.tol: # Wrap q to be within +- 180 deg # If your robot has larger than 180 deg range on a joint # this line should be modified in incorporate the extra range q = (q + np.pi) % (2 * np.pi) - np.pi # Check if we have violated joint limits jl_valid = self._check_jl(ets, q) if not jl_valid and self.joint_limits: # Abandon search and try again found_with_limits = True break else: return IKSolution( q=q[ets.jindices], success=True, iterations=total_i + i, searches=search + 1, residual=E, reason="Success", ) total_i += i # If we make it here, then we have failed reason = "iteration and search limit reached" if linalg_error: reason += f", {linalg_error} numpy.LinAlgError encountered" if found_with_limits: reason += ", solution found but violates joint limits" return IKSolution( q=q, success=False, iterations=total_i, searches=self.slimit, residual=E, reason=reason, ) def error(self, Te: np.ndarray, Tep: np.ndarray) -> Tuple[np.ndarray, float]: r""" Calculates the error between Te and Tep Calculates the engle axis error between current end-effector pose Te and the desired end-effector pose Tep. Also calulates the quadratic error E which is weighted by the diagonal matrix We. .. math:: E = \frac{1}{2} \vec{e}^{\top} \mat{W}_e \vec{e} where :math:`\vec{e} \in \mathbb{R}^6` is the angle-axis error. Parameters ---------- Te The current end-effector pose Tep The desired end-effector pose Returns ------- e angle-axis error (6 vector) E The quadratic error weighted by We """ e = rtb.angle_axis(Te, Tep) E = 0.5 * e @ self.We @ e return e, E @abstractmethod def step( self, ets: "rtb.ETS", Tep: np.ndarray, q: np.ndarray ) -> Tuple[float, np.ndarray]: """ Abstract step method Superclasses will implement this method to perform a step of the implemented IK algorithm Parameters ---------- ets The ETS representing the manipulators kinematics Tep The desired end-effector pose q The current joint coordinate vector Raises ------ numpy.LinAlgError If a step is impossible due to a linear algebra error Returns ------- E The new error value q The new joint coordinate vector """ pass # pragma: nocover def _random_q(self, ets: "rtb.ETS", i: int = 1) -> np.ndarray: """ Generate a random valid joint configuration using a private RNG Generates a random q vector within the joint limits defined by `ets.qlim`. Parameters ---------- ets The ETS representing the manipulators kinematics i number of configurations to generate Returns ------- q An `i x n` ndarray of random valid joint configurations, where n is the number of joints in the `ets` """ if i == 1: q = np.zeros((1, ets.n)) for i in range(ets.n): q[0, i] = self._private_random.uniform(ets.qlim[0, i], ets.qlim[1, i]) else: q = np.zeros((i, ets.n)) for j in range(i): for i in range(ets.n): q[j, i] = self._private_random.uniform( ets.qlim[0, i], ets.qlim[1, i] ) return q def _check_jl(self, ets: "rtb.ETS", q: np.ndarray) -> bool: """ Checks if the joints are within their respective limits Parameters ---------- ets the ETS q the current joint coordinate vector Returns ------- True if joints within feasible limits otherwise False """ # Loop through the joints in the ETS for i in range(ets.n): # Get the corresponding joint limits ql0 = ets.qlim[0, i] ql1 = ets.qlim[1, i] # Check if q exceeds the limits if q[i] < ql0 or q[i] > ql1: return False # If we make it here, all the joints are fine return True def _null_Σ(ets: "rtb.ETS", q: np.ndarray, ps: float, pi: Union[np.ndarray, float]): """ Formulates a relationship between joint limits and the joint velocity. When this is projected into the null-space of the differential kinematics to attempt to avoid exceeding joint limits :param q: The joint coordinates of the robot :param ps: The minimum angle/distance (in radians or metres) in which the joint is allowed to approach to its limit :param pi: The influence angle/distance (in radians or metres) in which the velocity damper becomes active :return: Σ """ if isinstance(pi, float): pi = pi * np.ones(ets.n) # Add cost to going in the direction of joint limits, if they are within # the influence distance Σ = np.zeros((ets.n, 1)) for i in range(ets.n): qi = q[i] ql0 = ets.qlim[0, i] ql1 = ets.qlim[1, i] if qi - ql0 <= pi[i]: Σ[i, 0] = -np.power(((qi - ql0) - pi[i]), 2) / np.power((ps - pi[i]), 2) if ql1 - qi <= pi[i]: Σ[i, 0] = np.power(((ql1 - qi) - pi[i]), 2) / np.power((ps - pi[i]), 2) return -Σ def _calc_qnull( ets: "rtb.ETS", q: np.ndarray, J: np.ndarray, λΣ: float, λm: float, ps: float, pi: Union[np.ndarray, float], ): """ Calculates the desired null-space motion according to the gains λΣ and λm. This is a helper method that is used within the `step` method of an IK solver :return: qnull - the desired null-space motion """ qnull_grad = np.zeros(ets.n) qnull = np.zeros(ets.n) # Add the joint limit avoidance if the gain is above 0 if λΣ > 0: Σ = _null_Σ(ets, q, ps, pi) qnull_grad += (1.0 / λΣ * Σ).flatten() # Add the manipulability maximisation if the gain is above 0 if λm > 0: Jm = ets.jacobm(q) qnull_grad += (1.0 / λm * Jm).flatten() # Calculate the null-space motion if λΣ > 0 or λΣ > 0: null_space = np.eye(ets.n) - np.linalg.pinv(J) @ J qnull = null_space @ qnull_grad return qnull.flatten() class IK_NR(IKSolver): """ Newton-Raphson Numerical Inverse Kinematics Solver A class which provides functionality to perform numerical inverse kinematics (IK) using the Newton-Raphson method. See `step` method for mathematical description. Note ---- When using this class with redundant robots (>6 DoF), `pinv` must be set to `True` Parameters ---------- name The name of the IK algorithm ilimit How many iterations are allowed within a search before a new search is started slimit How many searches are allowed before being deemed unsuccessful tol Maximum allowed residual error E mask A 6 vector which assigns weights to Cartesian degrees-of-freedom error priority joint_limits Reject solutions with joint limit violations seed A seed for the private RNG used to generate random joint coordinate vectors pinv If True, will use the psuedoinverse in the `step` method instead of the normal inverse kq The gain for joint limit avoidance. Setting to 0.0 will remove this completely from the solution km The gain for maximisation. Setting to 0.0 will remove this completely from the solution ps The minimum angle/distance (in radians or metres) in which the joint is allowed to approach to its limit pi The influence angle/distance (in radians or metres) in null space motion becomes active Examples -------- The following example gets the ``ets`` of a ``panda`` robot object, instantiates the IK_NR solver class using default parameters, makes a goal pose ``Tep``, and then solves for the joint coordinates which result in the pose ``Tep`` using the ``solve`` method. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> panda = rtb.models.Panda().ets() >>> solver = rtb.IK_NR(pinv=True) >>> Tep = panda.fkine([0, -0.3, 0, -2.2, 0, 2, 0.7854]) >>> solver.solve(panda, Tep) Notes ----- When using the NR method, the initial joint coordinates :math:`q_0`, should correspond to a non-singular manipulator pose, since it uses the manipulator Jacobian. When the the problem is solvable, it converges very quickly. However, this method frequently fails to converge on the goal. This class supports null-space motion to assist with maximising manipulability and avoiding joint limits. These are enabled by setting kq and km to non-zero values. References ---------- - J. Haviland, and P. Corke. "Manipulator Differential Kinematics Part I: Kinematics, Velocity, and Applications." arXiv preprint arXiv:2207.01796 (2022). - J. Haviland, and P. Corke. "Manipulator Differential Kinematics Part II: Acceleration and Advanced Applications." arXiv preprint arXiv:2207.01794 (2022). See Also -------- IKSolver An abstract super class for numerical IK solvers IK_GN Implements the IKSolver class using the Gauss-Newton method IK_LM Implements the IKSolver class using the Levemberg-Marquadt method IK_QP Implements the IKSolver class using a quadratic programming approach .. versionchanged:: 1.0.3 Added the Newton-Raphson IK solver class """ # noqa def __init__( self, name: str = "IK Solver", ilimit: int = 30, slimit: int = 100, tol: float = 1e-6, mask: Union[ArrayLike, None] = None, joint_limits: bool = True, seed: Union[int, None] = None, pinv: bool = False, kq: float = 0.0, km: float = 0.0, ps: float = 0.0, pi: Union[np.ndarray, float] = 0.3, **kwargs, ): super().__init__( name=name, ilimit=ilimit, slimit=slimit, tol=tol, mask=mask, joint_limits=joint_limits, seed=seed, **kwargs, ) self.pinv = pinv self.kq = kq self.km = km self.ps = ps self.pi = pi self.name = f"NR (pinv={pinv})" if self.kq > 0.0: self.name += " Σ" if self.km > 0.0: self.name += " Jm" def step( self, ets: "rtb.ETS", Tep: np.ndarray, q: np.ndarray ) -> Tuple[float, np.ndarray]: r""" Performs a single iteration of the Newton-Raphson optimisation method .. math:: \vec{q}_{k+1} = \vec{q}_k + {^0\mat{J}(\vec{q}_k)}^{-1} \vec{e}_k Parameters ---------- ets The ETS representing the manipulators kinematics Tep The desired end-effector pose q The current joint coordinate vector Raises ------ numpy.LinAlgError If a step is impossible due to a linear algebra error Returns ------- E The new error value q The new joint coordinate vector """ Te = ets.eval(q) e, E = self.error(Te, Tep) J = ets.jacob0(q) # Null-space motion qnull = _calc_qnull( ets=ets, q=q, J=J, λΣ=self.kq, λm=self.km, ps=self.ps, pi=self.pi ) if self.pinv: q[ets.jindices] += np.linalg.pinv(J) @ e + qnull else: q[ets.jindices] += np.linalg.inv(J) @ e + qnull return E, q[ets.jindices] class IK_LM(IKSolver): """ Levemberg-Marquadt Numerical Inverse Kinematics Solver A class which provides functionality to perform numerical inverse kinematics (IK) using the Levemberg-Marquadt method. See ``step`` method for mathematical description. Parameters ---------- name The name of the IK algorithm ilimit How many iterations are allowed within a search before a new search is started slimit How many searches are allowed before being deemed unsuccessful tol Maximum allowed residual error E mask A 6 vector which assigns weights to Cartesian degrees-of-freedom error priority joint_limits Reject solutions with joint limit violations seed A seed for the private RNG used to generate random joint coordinate vectors k Sets the gain value for the damping matrix Wn in the ``step`` method. See notes method One of "chan", "sugihara" or "wampler". Defines which method is used to calculate the damping matrix Wn in the ``step`` method kq The gain for joint limit avoidance. Setting to 0.0 will remove this completely from the solution km The gain for maximisation. Setting to 0.0 will remove this completely from the solution ps The minimum angle/distance (in radians or metres) in which the joint is allowed to approach to its limit pi The influence angle/distance (in radians or metres) in null space motion becomes active Examples -------- The following example gets the ``ets`` of a ``panda`` robot object, instantiates the IK_LM solver class using default parameters, makes a goal pose ``Tep``, and then solves for the joint coordinates which result in the pose ``Tep`` using the `solve` method. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> panda = rtb.models.Panda().ets() >>> solver = rtb.IK_LM() >>> Tep = panda.fkine([0, -0.3, 0, -2.2, 0, 2, 0.7854]) >>> solver.solve(panda, Tep) Notes ----- The value for the ``k`` kwarg will depend on the ``method`` chosen and the arm you are using. Use the following as a rough guide ``chan, k = 1.0 - 0.01``, ``wampler, k = 0.01 - 0.0001``, and ``sugihara, k = 0.1 - 0.0001`` When using the this method, the initial joint coordinates :math:`q_0`, should correspond to a non-singular manipulator pose, since it uses the manipulator Jacobian. This class supports null-space motion to assist with maximising manipulability and avoiding joint limits. These are enabled by setting kq and km to non-zero values. References ---------- - J. Haviland, and P. Corke. "Manipulator Differential Kinematics Part I: Kinematics, Velocity, and Applications." arXiv preprint arXiv:2207.01796 (2022). - J. Haviland, and P. Corke. "Manipulator Differential Kinematics Part II: Acceleration and Advanced Applications." arXiv preprint arXiv:2207.01794 (2022). See Also -------- IKSolver An abstract super class for numerical IK solvers IK_NR Implements the IKSolver class using the Newton-Raphson method IK_GN Implements the IKSolver class using the Gauss-Newton method IK_QP Implements the IKSolver class using a quadratic programming approach .. versionchanged:: 1.0.3 Added the Levemberg-Marquadt IK solver class """ # noqa def __init__( self, name: str = "IK Solver", ilimit: int = 30, slimit: int = 100, tol: float = 1e-6, mask: Union[ArrayLike, None] = None, joint_limits: bool = True, seed: Union[int, None] = None, k: float = 1.0, method="chan", kq: float = 0.0, km: float = 0.0, ps: float = 0.0, pi: Union[np.ndarray, float] = 0.3, **kwargs, ): super().__init__( name=name, ilimit=ilimit, slimit=slimit, tol=tol, mask=mask, joint_limits=joint_limits, seed=seed, **kwargs, ) if method.lower().startswith("sugi"): self.method = 1 method_name = "Sugihara" elif method.lower().startswith("wamp"): self.method = 2 method_name = "Wampler" else: self.method = 0 method_name = "Chan" self.k = k self.kq = kq self.km = km self.ps = ps self.pi = pi self.name = f"LM ({method_name} λ={k})" if self.kq > 0.0: self.name += " Σ" if self.km > 0.0: self.name += " Jm" def step(self, ets: "rtb.ETS", Tep: np.ndarray, q: np.ndarray): r""" Performs a single iteration of the Levenberg-Marquadt optimisation The operation is defined by the choice of `method` when instantiating the class. The next step is deined as .. math:: \vec{q}_{k+1} &= \vec{q}_k + \left( \mat{A}_k \right)^{-1} \bf{g}_k \\ % \mat{A}_k &= {\mat{J}(\vec{q}_k)}^\top \mat{W}_e \ {\mat{J}(\vec{q}_k)} + \mat{W}_n where :math:`\mat{W}_n = \text{diag}(\vec{w_n})(\vec{w_n} \in \mathbb{R}^n_{>0})` is a diagonal damping matrix. The damping matrix ensures that :math:`\mat{A}_k` is non-singular and positive definite. The performance of the LM method largely depends on the choice of :math:`\mat{W}_n`. **Chan's Method** Chan proposed .. math:: \mat{W}_n = λ E_k \mat{1}_n where λ is a constant which reportedly does not have much influence on performance. Use the kwarg `k` to adjust the weighting term λ. **Sugihara's Method** Sugihara proposed .. math:: \mat{W}_n = E_k \mat{1}_n + \text{diag}(\hat{\vec{w}}_n) where :math:`\hat{\vec{w}}_n \in \mathbb{R}^n`, :math:`\hat{w}_{n_i} = l^2 \sim 0.01 l^2`, and :math:`l` is the length of a typical link within the manipulator. We provide the variable `k` as a kwarg to adjust the value of :math:`w_n`. **Wampler's Method** Wampler proposed :math:`\vec{w_n}` to be a constant. This is set through the `k` kwarg. Parameters ---------- ets The ETS representing the manipulators kinematics Tep The desired end-effector pose q The current joint coordinate vector Raises ------ numpy.LinAlgError If a step is impossible due to a linear algebra error Returns ------- E The new error value q The new joint coordinate vector """ # noqa Te = ets.eval(q) e, E = self.error(Te, Tep) if self.method == 1: # Sugihara's method Wn = E * np.eye(ets.n) + self.k * np.eye(ets.n) elif self.method == 2: # Wampler's method Wn = self.k * np.eye(ets.n) else: # Chan's method Wn = self.k * E * np.eye(ets.n) J = ets.jacob0(q) g = J.T @ self.We @ e # Null-space motion qnull = _calc_qnull( ets=ets, q=q, J=J, λΣ=self.kq, λm=self.km, ps=self.ps, pi=self.pi ) q[ets.jindices] += np.linalg.inv(J.T @ self.We @ J + Wn) @ g + qnull return E, q[ets.jindices] class IK_GN(IKSolver): """ Gauss-Newton Numerical Inverse Kinematics Solver A class which provides functionality to perform numerical inverse kinematics (IK) using the Gauss-Newton method. See `step` method for mathematical description. Note ---- When using this class with redundant robots (>6 DoF), ``pinv`` must be set to ``True`` Parameters ---------- name The name of the IK algorithm ilimit How many iterations are allowed within a search before a new search is started slimit How many searches are allowed before being deemed unsuccessful tol Maximum allowed residual error E mask A 6 vector which assigns weights to Cartesian degrees-of-freedom error priority joint_limits Reject solutions with joint limit violations seed A seed for the private RNG used to generate random joint coordinate vectors pinv If True, will use the psuedoinverse in the `step` method instead of the normal inverse kq The gain for joint limit avoidance. Setting to 0.0 will remove this completely from the solution km The gain for maximisation. Setting to 0.0 will remove this completely from the solution ps The minimum angle/distance (in radians or metres) in which the joint is allowed to approach to its limit pi The influence angle/distance (in radians or metres) in null space motion becomes active Examples -------- The following example gets the ``ets`` of a ``panda`` robot object, instantiates the `IK_GN` solver class using default parameters, makes a goal pose ``Tep``, and then solves for the joint coordinates which result in the pose ``Tep`` using the `solve` method. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> panda = rtb.models.Panda().ets() >>> solver = rtb.IK_GN(pinv=True) >>> Tep = panda.fkine([0, -0.3, 0, -2.2, 0, 2, 0.7854]) >>> solver.solve(panda, Tep) Notes ----- When using the this method, the initial joint coordinates :math:`q_0`, should correspond to a non-singular manipulator pose, since it uses the manipulator Jacobian. When the the problem is solvable, it converges very quickly. This class supports null-space motion to assist with maximising manipulability and avoiding joint limits. These are enabled by setting kq and km to non-zero values. References ---------- - J. Haviland, and P. Corke. "Manipulator Differential Kinematics Part I: Kinematics, Velocity, and Applications." arXiv preprint arXiv:2207.01796 (2022). - J. Haviland, and P. Corke. "Manipulator Differential Kinematics Part II: Acceleration and Advanced Applications." arXiv preprint arXiv:2207.01794 (2022). See Also -------- IKSolver An abstract super class for numerical IK solvers IK_NR Implements IKSolver using the Newton-Raphson method IK_LM Implements IKSolver using the Levemberg-Marquadt method IK_QP Implements IKSolver using a quadratic programming approach .. versionchanged:: 1.0.3 Added the Gauss-Newton IK solver class """ # noqa def __init__( self, name: str = "IK Solver", ilimit: int = 30, slimit: int = 100, tol: float = 1e-6, mask: Union[ArrayLike, None] = None, joint_limits: bool = True, seed: Union[int, None] = None, pinv: bool = False, kq: float = 0.0, km: float = 0.0, ps: float = 0.0, pi: Union[np.ndarray, float] = 0.3, **kwargs, ): super().__init__( name=name, ilimit=ilimit, slimit=slimit, tol=tol, mask=mask, joint_limits=joint_limits, seed=seed, **kwargs, ) self.pinv = pinv self.kq = kq self.km = km self.ps = ps self.pi = pi self.name = f"GN (pinv={pinv})" if self.kq > 0.0: self.name += " Σ" if self.km > 0.0: self.name += " Jm" def step( self, ets: "rtb.ETS", Tep: np.ndarray, q: np.ndarray ) -> Tuple[float, np.ndarray]: r""" Performs a single iteration of the Gauss-Newton optimisation method The next step is defined as .. math:: \vec{q}_{k+1} &= \vec{q}_k + \left( {\mat{J}(\vec{q}_k)}^\top \mat{W}_e \ {\mat{J}(\vec{q}_k)} \right)^{-1} \bf{g}_k \\ \bf{g}_k &= {\mat{J}(\vec{q}_k)}^\top \mat{W}_e \vec{e}_k where :math:`\mat{J} = {^0\mat{J}}` is the base-frame manipulator Jacobian. If :math:`\mat{J}(\vec{q}_k)` is non-singular, and :math:`\mat{W}_e = \mat{1}_n`, then the above provides the pseudoinverse solution. However, if :math:`\mat{J}(\vec{q}_k)` is singular, the above can not be computed and the GN solution is infeasible. Parameters ---------- ets The ETS representing the manipulators kinematics Tep The desired end-effector pose q The current joint coordinate vector Raises ------ numpy.LinAlgError If a step is impossible due to a linear algebra error Returns ------- E The new error value q The new joint coordinate vector """ # noqa Te = ets.eval(q) e, E = self.error(Te, Tep) J = ets.jacob0(q) # Null-space motion qnull = _calc_qnull( ets=ets, q=q, J=J, λΣ=self.kq, λm=self.km, ps=self.ps, pi=self.pi ) if self.pinv: q[ets.jindices] += np.linalg.pinv(J) @ e + qnull else: q[ets.jindices] += np.linalg.inv(J) @ e + qnull return E, q[ets.jindices] class IK_QP(IKSolver): """ Quadratic Progamming Numerical Inverse Kinematics Solver A class which provides functionality to perform numerical inverse kinematics (IK) using a quadratic progamming approach. See `step` method for mathematical description. Parameters ---------- name The name of the IK algorithm ilimit How many iterations are allowed within a search before a new search is started slimit How many searches are allowed before being deemed unsuccessful tol Maximum allowed residual error E mask A 6 vector which assigns weights to Cartesian degrees-of-freedom error priority joint_limits Reject solutions with joint limit violations seed A seed for the private RNG used to generate random joint coordinate vectors kj A gain for joint velocity norm minimisation ks A gain which adjusts the cost of slack (intentional error) kq The gain for joint limit avoidance. Setting to 0.0 will remove this completely from the solution km The gain for maximisation. Setting to 0.0 will remove this completely from the solution ps The minimum angle/distance (in radians or metres) in which the joint is allowed to approach to its limit pi The influence angle/distance (in radians or metres) in null space motion becomes active Raises ------ ImportError If the package ``qpsolvers`` is not installed Examples -------- The following example gets the ``ets`` of a ``panda`` robot object, instantiates the `IK_QP` solver class using default parameters, makes a goal pose ``Tep``, and then solves for the joint coordinates which result in the pose ``Tep`` using the `solve` method. .. runblock:: pycon >>> import roboticstoolbox as rtb >>> panda = rtb.models.Panda().ets() >>> solver = rtb.IK_QP() >>> Tep = panda.fkine([0, -0.3, 0, -2.2, 0, 2, 0.7854]) >>> solver.solve(panda, Tep) Notes ----- When using the this method, the initial joint coordinates :math:`q_0`, should correspond to a non-singular manipulator pose, since it uses the manipulator Jacobian. When the the problem is solvable, it converges very quickly. References ---------- - J. Haviland, and P. Corke. "Manipulator Differential Kinematics Part II: Acceleration and Advanced Applications." arXiv preprint arXiv:2207.01794 (2022). See Also -------- IKSolver An abstract super class for numerical IK solvers IK_NR Implements IKSolver class using the Newton-Raphson method IK_GN Implements IKSolver class using the Gauss-Newton method IK_LM Implements IKSolver class using the Levemberg-Marquadt method .. versionchanged:: 1.0.3 Added the Quadratic Programming IK solver class """ # noqa def __init__( self, name: str = "IK Solver", ilimit: int = 30, slimit: int = 100, tol: float = 1e-6, mask: Union[ArrayLike, None] = None, joint_limits: bool = True, seed: Union[int, None] = None, kj=0.01, ks=1.0, kq: float = 0.0, km: float = 0.0, ps: float = 0.0, pi: Union[np.ndarray, float] = 0.3, **kwargs, ): if not _qp: # pragma: nocover raise ImportError( "the package qpsolvers is required for this class. \nInstall using 'pip" " install qpsolvers'" ) super().__init__( name=name, ilimit=ilimit, slimit=slimit, tol=tol, mask=mask, joint_limits=joint_limits, seed=seed, **kwargs, ) self.kj = kj self.ks = ks self.kq = kq self.km = km self.ps = ps self.pi = pi self.name = "QP)" if self.kq > 0.0: self.name += " Σ" if self.km > 0.0: self.name += " Jm" def step( self, ets: "rtb.ETS", Tep: np.ndarray, q: np.ndarray ) -> Tuple[float, np.ndarray]: r""" Performs a single iteration of the Gauss-Newton optimisation method The next step is defined as .. math:: \vec{q}_{k+1} = \vec{q}_{k} + \dot{\vec{q}}. where the QP is defined as .. math:: \min_x \quad f_o(\vec{x}) &= \frac{1}{2} \vec{x}^\top \mathcal{Q} \vec{x}+ \mathcal{C}^\top \vec{x}, \\ \text{subject to} \quad \mathcal{J} \vec{x} &= \vec{\nu}, \\ \mathcal{A} \vec{x} &\leq \mathcal{B}, \\ \vec{x}^- &\leq \vec{x} \leq \vec{x}^+ with .. math:: \vec{x} &= \begin{pmatrix} \dvec{q} \\ \vec{\delta} \end{pmatrix} \in \mathbb{R}^{(n+6)} \\ \mathcal{Q} &= \begin{pmatrix} \lambda_q \mat{1}_{n} & \mathbf{0}_{6 \times 6} \\ \mathbf{0}_{n \times n} & \lambda_\delta \mat{1}_{6} \end{pmatrix} \in \mathbb{R}^{(n+6) \times (n+6)} \\ \mathcal{J} &= \begin{pmatrix} \mat{J}(\vec{q}) & \mat{1}_{6} \end{pmatrix} \in \mathbb{R}^{6 \times (n+6)} \\ \mathcal{C} &= \begin{pmatrix} \mat{J}_m \\ \bf{0}_{6 \times 1} \end{pmatrix} \in \mathbb{R}^{(n + 6)} \\ \mathcal{A} &= \begin{pmatrix} \mat{1}_{n \times n + 6} \\ \end{pmatrix} \in \mathbb{R}^{(l + n) \times (n + 6)} \\ \mathcal{B} &= \eta \begin{pmatrix} \frac{\rho_0 - \rho_s} {\rho_i - \rho_s} \\ \vdots \\ \frac{\rho_n - \rho_s} {\rho_i - \rho_s} \end{pmatrix} \in \mathbb{R}^{n} \\ \vec{x}^{-, +} &= \begin{pmatrix} \dvec{q}^{-, +} \\ \vec{\delta}^{-, +} \end{pmatrix} \in \mathbb{R}^{(n+6)}, where :math:`\vec{\delta} \in \mathbb{R}^6` is the slack vector, :math:`\lambda_\delta \in \mathbb{R}^+` is a gain term which adjusts the cost of the norm of the slack vector in the optimiser, :math:`\dvec{q}^{-,+}` are the minimum and maximum joint velocities, and :math:`\dvec{\delta}^{-,+}` are the minimum and maximum slack velocities. Parameters ---------- ets The ETS representing the manipulators kinematics Tep The desired end-effector pose q The current joint coordinate vector Raises ------ numpy.LinAlgError If a step is impossible due to a linear algebra error Returns ------- E The new error value q The new joint coordinate vector """ # noqa Te = ets.eval(q) e, E = self.error(Te, Tep) J = ets.jacob0(q) if isinstance(self.pi, float): self.pi = self.pi * np.ones(ets.n) # Quadratic component of objective function Q = np.eye(ets.n + 6) # Joint velocity component of Q Q[: ets.n, : ets.n] *= self.kj # Slack component of Q Q[ets.n :, ets.n :] = self.ks * (1 / np.sum(np.abs(e))) * np.eye(6) # The equality contraints Aeq = np.concatenate((J, np.eye(6)), axis=1) beq = e.reshape((6,)) # The inequality constraints for joint limit avoidance if self.kq > 0.0: Ain = np.zeros((ets.n + 6, ets.n + 6)) bin = np.zeros(ets.n + 6) # Form the joint limit velocity damper Ain_l = np.zeros((ets.n, ets.n)) Bin_l = np.zeros(ets.n) for i in range(ets.n): ql0 = ets.qlim[0, i] ql1 = ets.qlim[1, i] if ql1 - q[i] <= self.pi[i]: Bin_l[i] = ((ql1 - q[i]) - self.ps) / (self.pi[i] - self.ps) Ain_l[i, i] = 1 if q[i] - ql0 <= self.pi[i]: Bin_l[i] = -(((ql0 - q[i]) + self.ps) / (self.pi[i] - self.ps)) Ain_l[i, i] = -1 Ain[: ets.n, : ets.n] = Ain_l bin[: ets.n] = (1.0 / self.kq) * Bin_l else: Ain = None bin = None # Manipulability maximisation if self.km > 0.0: Jm = ets.jacobm(q).reshape((ets.n,)) c = np.concatenate(((1.0 / self.km) * -Jm, np.zeros(6))) else: c = np.zeros(ets.n + 6) xd = qp.solve_qp(Q, c, Ain, bin, Aeq, beq, lb=None, ub=None, solver="quadprog") if xd is None: # pragma: nocover raise np.linalg.LinAlgError("QP Unsolvable") q += xd[: ets.n] return E, q if __name__ == "__main__": # pragma nocover sol = IKSolution( np.array([1, 2, 3]), success=True, iterations=10, searches=100, residual=0.1 ) a, b, c, d, e = sol print(a, b, c, d, e)
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/robot/IK.py
0.901811
0.419113
IK.py
pypi
from abc import ABC import numpy as np import scipy as sp from math import pi, sin, cos import matplotlib.pyplot as plt from spatialmath import base import roboticstoolbox as rtb class LandmarkMap: """ Map of planar point landmarks :param map: map or number of landmarks :type map: ndarray(2, N) or int :param workspace: workspace or map bounds, defaults to 10 :type workspace: scalar, array_like(2), array_like(4), optional :param verbose: display debug information, defaults to True :type verbose: bool, optional :param seed: random number seed, defaults to 0 :type seed: int, optional :return: a landmark map object :rtype: LandmarkMap A LandmarkMap object represents a rectangular 2D environment with a number of point landmarks. The landmarks can be specified explicitly or be uniform randomly positioned inside a region defined by the workspace. The workspace can be numeric: ============== ======= ======= ``workspace`` x-range y-range ============== ======= ======= A (scalar) -A:A -A:A [A, B] A:B A:B [A, B, C, D] A:B C:D ============== ======= ======= or any object that has a ``workspace`` attribute. Example: .. runblock:: pycon >>> from roboticstoolbox import LandmarkMap >>> map = LandmarkMap(20) >>> print(map) >>> print(map[3]) # coordinates of landmark 3 The object is an iterator that returns consecutive landmark coordinates. :Reference: Robotics, Vision & Control, Chap 6, Peter Corke, Springer 2011 See also :class:`~roboticstoolbox.mobile.sensors.RangeBearingSensor` :class:`~roboticstoolbox.mobile.EKF` """ def __init__(self, map, workspace=10, verbose=True, seed=0): try: self._workspace = workspace.workspace except: self._workspace = base.expand_dims(workspace) if base.ismatrix(map, (2, None)): self._map = map self._nlandmarks = map.shape[1] elif isinstance(map, int): self._nlandmarks = map random = np.random.default_rng(seed) x = random.uniform(self._workspace[0], self._workspace[1], self._nlandmarks) y = random.uniform(self._workspace[2], self._workspace[3], self._nlandmarks) self._map = np.c_[x, y].T else: raise ValueError("bad type for map") self._verbose = verbose def __str__(self): # s = M.char() is a string showing map parameters in # a compact human readable format. ws = self._workspace s = f"LandmarkMap object with {self._nlandmarks} landmarks, workspace=" s += f"({ws[0]}: {ws[1]}, {ws[2]}: {ws[3]})" return s def __repr__(self): return str(self) def __len__(self): """ Number of landmarks in map :return: number of landmarks in the map :rtype: int """ return self._nlandmarks @property def landmarks(self): """ xy-coordinates of all landmarks :return: xy-coordinates for landmark points :rtype: ndarray(2, n) """ return self._map @property def workspace(self): """ Size of map workspace :return: workspace bounds [xmin, xmax, ymin, ymax] :rtype: ndarray(4) Returns the bounds of the workspace as specified by constructor option ``workspace``. """ return self._workspace def __getitem__(self, k): """ Get landmark coordinates from map :param k: landmark index :type k: int :return: coordinate :math:`(x,y)` of k'th landmark :rtype: ndarray(2) """ return self._map[:, k] def plot(self, labels=False, block=None, **kwargs): """ Plot landmark map :param labels: number the points on the plot, defaults to False :type labels: bool, optional :param block: block until figure is closed, defaults to False :type block: bool, optional :param kwargs: :meth:`~matplotlib.axes.Axes.plot` options Plot landmark points using Matplotlib options. Default style is black crosses. """ ax = base.plotvol2(self._workspace) ax.set_aspect("equal") ax.set_xlabel("x") ax.set_ylabel("y") if len(kwargs) == 0: kwargs = { "linewidth": 0, "marker": "x", "color": "black", "linestyle": "None", } if "label" not in kwargs: kwargs["label"] = "landmark" # plt.plot(self._map[0,:], self._map[1,:], , **kwargs) if labels: labels = "#{}" else: labels = None base.plot_point(self._map, text=labels, **kwargs) plt.grid(True) if block is not None: plt.show(block=block) if __name__ == "__main__": import unittest
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/mobile/landmarkmap.py
0.9292
0.692824
landmarkmap.py
pypi
import numpy as np import matplotlib.pyplot as plt from spatialmath import base import scipy.ndimage as sp from abc import ABC import spatialmath.base as smb from spatialmath.geom2d import Polygon2 class BaseMap(ABC): def __init__(self, workspace=None, name=None, **unused): """ Abstract base class for maps :param workspace: dimensions of 2D plot area, defaults to (-10:10) x (-10:10), see :func:`~spatialmath.base.graphics.plotvol2` :type workspace: float, array_like(2), array_like(4) :param name: nae of the map, defaults to None :type name: str, optional The workspace can be specified in several ways: ============== ======= ======= ``workspace`` x-range y-range ============== ======= ======= A (scalar) -A:A -A:A [A, B] A:B A:B [A, B, C, D] A:B C:D ============== ======= ======= """ if workspace is not None: workspace = smb.expand_dims(workspace) self._workspace = workspace self.dx = workspace[1] - workspace[0] self.dy = workspace[3] - workspace[2] self._name = name class BaseOccupancyGrid(BaseMap): def __init__(self, grid=None, origin=(0, 0), value=0, cellsize=1, **kwargs): """ Occupancy grid (superclass) :param grid: occupancy grid as a NumPy array :type grid: ndarray(N,M) :param value: initial value of cells :type value: any, optional :param origin: world coordinates of the grid element [0,0], defaults to (0, 0) :type origin: array_like(2), optional :param cellsize: cell size, defaults to 1 :type cellsize: float, optional :param kwargs: options passed to :class:`~roboticstoolbox.mobile.OccGrid.BaseMap` This object supports a user-defined coordinate system and grid size. World coordinates are converted to grid coordinates to lookup the occupancy status. The grid can be initialized by: - a 2D NumPy array - specifying ``workspace`` and ``value`` arguments """ super().__init__(**kwargs) if grid is not None: self._grid = grid self._origin = smb.getvector(origin, 2) elif self._workspace is not None: self._grid = np.full( np.floor(np.r_[self.dx, self.dy] / cellsize).astype(int) + 1, value ) self._origin = np.r_[self._workspace[0], self._workspace[2]] self._cellsize = cellsize def copy(self): """ Copy an occupancy grid (superclass) :return: copy of the ocupancy grid :rtype: OccGrid """ return self.__class__( self._grid.copy(), cellsize=self._cellsize, origin=self._origin, name=self._name, ) def __repr__(self): return str(self) def __str__(self): """ Compact string description of occupancy grid (superclass) :return: summary of occupancy grid characteristics :rtype: str """ s = self.__class__.__name__ if self._name is not None: s += f"[{self._name}]" s += f": {self._grid.shape[1]} x {self._grid.shape[0]}" s += f", cell size={self._cellsize}" s += f", x = [{self.xmin}, {self.xmax}], y = [{self.ymin}, {self.ymax}]" return s @property def grid(self): """ Occupancy grid as a NumPy array (superclass) :return: binary occupancy grid :rtype: ndarray(N,M) of bool If :meth:`inflate` has been called, this will return the inflated occupancy grid. """ return self._grid @property def xmin(self): """ Minimum x-coordinate of this grid (superclass) :return: minimum world x-coordinate :rtype: float """ return self._origin[0] @property def xmax(self): """ Maximum x-coordinate of this grid (superclass) :return: maximum world x-coordinate :rtype: float """ return (self._grid.shape[1] - 1) * self._cellsize + self._origin[0] @property def ymin(self): """ Minimum y-coordinate of this grid (superclass) :return: minimum world y-coordinate :rtype: float """ return self._origin[1] @property def ymax(self): """ Maximum y-coordinate of this grid (superclass) :return: maximum world y-coordinate :rtype: float """ return (self._grid.shape[0] - 1) * self._cellsize + self._origin[1] @property def shape(self): """ Shape of the occupancy grid array (superclass) :return: shape of the occupancy grid array :rtype: 2-tuple This is the shape of the NumPy array that holds the occupancy grid. """ return self._grid.shape @property def maxdim(self): """ Maximum dimension of grid in world coordinates (superclass) :return: maximum side length of the occupancy grid :rtype: float """ return max(self.grid.shape) * self._cellsize @property def workspace(self): """ Bounds of the occupancy grid in world coordinates (superclass) :return: workspace bounds [xmin, xmax, ymin, ymax] :rtype: ndarray(4) Returns the bounds of the occupancy grid in world coordinates. """ return np.r_[self.xmin, self.xmax, self.ymin, self.ymax] @property def name(self): """ Occupancy grid name (superclass) :return: name of the occupancy grid :rtype: str """ return self._name @name.setter def name(self, name): """ Set occupancy grid name (superclass) :param name: new name of the occupancy grid :type name: str """ self._name = name def set(self, region, value): """ Set region of map (superclass) :param region: The region [xmin, ymin, xmax, ymax] :type region: array_like(4) :param value: value to set cells to :type value: int, bool, float """ bl = self.w2g([region[0], region[2]]) tr = self.w2g([region[1], region[3]]) self.grid[bl[1] : tr[1] + 1, bl[0] : tr[0] + 1] = value def g2w(self, p): """ Convert grid coordinate to world coordinate (superclass) :param p: grid coordinate (column, row) :type p: array_like(2) :return: world coordinate (x, y) :rtype: ndarray(2) The grid cell size and offset are used to convert occupancy grid coordinate ``p`` to a world coordinate. """ p = smb.getvector(p, 2) return p * self._cellsize + self._origin def w2g(self, p): """ Convert world coordinate to grid coordinate (superclass) :param p: world coordinate (x, y) :type p: array_like(2) :return: grid coordinate (column, row) :rtype: ndarray(2) The grid cell size and offset are used to convert ``p`` to an occupancy grid coordinate. The grid coordinate is rounded and cast to integer value. No check is made on the validity of the coordinate. """ return (np.round((p - self._origin) / self._cellsize)).astype(int) def plot(self, map=None, ax=None, block=None, **kwargs): """ Plot the occupancy grid (superclass) :param map: array which is plotted instead of the grid, must be same size as the occupancy grid,defaults to None :type map: ndarray(N,M), optional :param ax: matplotlib axes to plot into, defaults to None :type ax: Axes2D, optional :param block: block until plot is dismissed, defaults to None :type block: bool, optional :param kwargs: arguments passed to ``imshow`` The grid is plotted as an image but with axes in world coordinates. The grid is a NumPy boolean array which has values 0 (false=unoccupied) and 1 (true=occupied). Passing a `cmap` option to imshow can be used to control the displayed color of free space and obstacles. """ ax = smb.axes_logic(ax, 2) if map is None: map = self._grid kwargs["extent"] = self.workspace ax.imshow(map, origin="lower", interpolation=None, **kwargs) ax.set_xlabel("x") ax.set_ylabel("y") if block is not None: plt.show(block=block) def line_w(self, p1, p2): """ Get index of cells along a line segment (superclass) :param p1: start :type p1: array_like(2) :param p2: end :type p2: array_like(2) :return: index into grid :rtype: ndarray(N) Get the indices of cells along a line segment defined by the end points given in world coordinates. The returned indices can be applied to a raveled view of the grid. :seealso: :meth:`ravel` :meth:`w2g` """ gp1 = self.w2g(p1) gp2 = self.w2g(p2) return self._line(gp1, gp2) def _line(self, p1, p2): x, y = smb.bresenham(p1, p2) z = np.ravel_multi_index(np.vstack((y, x)), self.grid.shape) return z @property def ravel(self): """ Ravel the grid (superclass) :return: 1D view of the occupancy grid :rtype: ndarray(N) """ return self._grid.reshape(-1) class BinaryOccupancyGrid(BaseOccupancyGrid): def __init__(self, grid=None, **kwargs): """ Create a binary occupancy grid instance :param grid: occupancy grid as a NumPy array :type grid: ndarray(N,M) :param size: cell size, defaults to 1 :type size: float, optional :param origin: world coordinates of the grid element [0,0], defaults to (0, 0) :type origin: array_like(2), optional :param kwargs: options passed to :class:`BaseMap` The array is kept internally as a bool array. Cells are set to True (occupied) corresponding to input values > 0. This object supports a user-defined coordinate system and grid size. World coordinates are converted to grid coordinates to lookup the occupancy status. Example: .. runblock:: pycon >>> from roboticstoolbox import BinaryOccupancyGrid >>> import numpy as np >>> og = BinaryOccupancyGrid(np.zeros((5,5))) >>> print(og) >>> og = BinaryOccupancyGrid(workspace=[-5,5], cellsize=0.1, value=0) >>> print(og) :seealso: :class:`OccupancyGrid` """ if grid is not None: if isinstance(grid, np.ndarray): grid = grid.astype(bool) elif isinstance(grid, BinaryOccupancyGrid): grid = grid.grid else: raise ValueError("argument must be NumPy array or BinaryOccupancyGrid") super().__init__(grid=grid, **kwargs) def __str__(self): s = super().__str__() ncells = np.prod(self._grid.shape) nobs = self._grid.sum() s += f", {nobs/ncells*100:.1f}% occupied" return s def isoccupied(self, p): """ Test if coordinate is occupied :param p: world coordinate (x, y) :type p: array_like(2) :return: occupancy status of corresponding grid cell :rtype: bool The grid cell size and offset are used to convert ``p`` to an occupancy grid coordinate. The grid coordinate is rounded and cast to integer value. If the coordinate is outside the bounds of the occupancy grid it is considered to be occupied. :seealso: :meth:`w2g` """ c, r = self.w2g(p) try: return self._grid[r, c] except IndexError: return True def inflate(self, radius): """ Inflate obstales :param radius: radius of circular structuring element in world units :type radius: float A circular structuring element is created and used to dilate the stored occupancy grid. Successive calls to ``inflate`` will compound the inflation. :seealso: :func:`scipy.ndimage.binary_dilation` """ # Generate a circular structuring element r = round(radius / self._cellsize) Y, X = np.meshgrid(np.arange(-r, r + 1), np.arange(-r, r + 1)) SE = X**2 + Y**2 <= r**2 SE = SE.astype(int) # do the inflation using SciPy self._grid = sp.binary_dilation(self._grid, SE) class OccupancyGrid(BaseOccupancyGrid): """ General occupancy grid The elements of the array are floats and can represent occupancy probability or traversal cost. Example: .. runblock:: pycon >>> from roboticstoolbox import OccupancyGrid >>> import numpy as np >>> og = OccupancyGrid(np.zeros((5,5))) >>> print(og) >>> og = OccupancyGrid(workspace=[-5,5], cellsize=0.1, value=0.5) >>> print(og) :seealso: :class:`BinaryOccupancyGrid` """ def __str__(self): s = super().__str__() g = self._grid s += f", dtype {g.dtype}" s += f", min {g.min()}, max {g.max()}, mean {g.mean()}" return s class PolygonMap(BaseMap): def __init__(self, workspace=None, polygons=[]): """ Polygonal obstacle map :param workspace: dimensions of 2D plot area, defaults to (-10:10) x (-10:10), see :func:`~spatialmath.base.graphics.plotvol2` :type workspace: float, array_like(2), array_like(4) :param polygons: obstacle polygons, defaults to [] :type polygons: list, optional The obstacle polygons are specified as instances of :class:`~spatialmath.geom2d.Polygon2` or ndarray(2,N). The workspace can be specified in several ways: ============== ======= ======= ``workspace`` x-range y-range ============== ======= ======= A (scalar) -A:A -A:A [A, B] A:B A:B [A, B, C, D] A:B C:D ============== ======= ======= Workspace is used only to set plot bounds. """ super().__init__(workspace=workspace) self.polygons = polygons def add(self, polygon): """ Add a polygon to map :param polygon: a polygon :type polygon: :class:`~spatialmath.geom2d.Polygon2` or ndarray(2,N) """ if isinstance(polygon, Polygon2): self.polygons.append(polygon) # lgtm [py/modification-of-default-value] else: self.polygons.append( Polygon2(polygon) ) # lgtm [py/modification-of-default-value] def iscollision(self, polygon): """ Test for collision :param polygon: a polygon :type polygon: :class:`~spatialmath.geom2d.Polygon2` or ndarray(2,N) :return: collision :rtype: bool The ``polygon`` is tested against polygons in the map, and returns True on the first collision. :seealso: :meth:`add` :class:`~spatialmath.geom2d.Polygon2` """ return polygon.intersects(self.polygons) def plot(self, block=None): smb.plotvol2(self.workspace) for polygon in self.polygons: polygon.plot(color="r") if block is not None: plt.show(block=block) def isoccupied(self, p): """ Test if point lies inside an obstacle :param p: a 2D point :type p: array_like(2) :return: enclosure :rtype: bool The point is tested for enclosure by polygons in the map, and returns True on the first enclosure. """ for polygon in self.polygons: if polygon.contains(p): return True return False @property def workspace(self): """ Bounds of the occupancy grid :return: workspace bounds [xmin, xmax, ymin, ymax] :rtype: ndarray(4) Returns the bounds of the occupancy grid. """ return self._workspace if __name__ == "__main__": # g = np.zeros((100, 100)) # g[20:30, 50:80] = 1 # og = OccGrid(g, size=0.1, origin=(2,4),name='bob') # print(og) # print(og.xmin, og.xmax, og.ymin, og.ymax) # print(og.isoccupied((8.5, 6.5))) # print(og.isoccupied((6, 6))) # print(og.isoccupied((500, 500))) # og.plot(block=False) # og2 = og.copy() # print(og2) # og2.inflate(0.5) # plt.figure() # og2.plot(block=True) # g = np.zeros((10,10)) # g[2:3, 4:5] = 1 # og = BinaryOccupancyGrid(g) # print(og) # r = og.ravel # print(r[24]) # og = BinaryOccupancyGrid(workspace=[2,3,4,5], cellsize=0.2) # print(og) # og = BinaryOccupancyGrid(workspace=[2,3,4,5], cellsize=0.2, value=True) # print(og) # og = OccupancyGrid(workspace=[2,3,4,5], cellsize=0.2, value=3) # print(og) # og = OccupancyGrid(workspace=[2,3,4,5], cellsize=0.2, value=3.0) # print(og) map = PolygonMap(workspace=[0, 10]) map.add([(5, 50), (5, 6), (6, 6), (6, 50)]) map.add([(5, 4), (5, -50), (6, -50), (6, 4)]) map.plot() og = BinaryOccupancyGrid(workspace=[-5, 5, -5, 5], value=False) # np.set_printoptions(linewidth=300) # og = BinaryOccupancyGrid(workspace=[-10, 10, -10, 10], value=False) # print(og) # og.set([1,10, -10, 10], True) # print(og.grid) # print(og.isoccupied((0,0)))
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/mobile/OccGrid.py
0.938195
0.714429
OccGrid.py
pypi
import numpy as np from spatialmath import base def jacobian_numerical(f, x, dx=1e-8, N=0): r""" Numerically compute Jacobian of function :param f: the function, returns an m-vector :type f: callable :param x: function argument :type x: ndarray(n) :param dx: the numerical perturbation, defaults to 1e-8 :type dx: float, optional :param N: function returns SE(N) matrix, defaults to 0 :type N: int, optional :return: Jacobian matrix :rtype: ndarray(m,n) Computes a numerical approximation to the Jacobian for ``f(x)`` where :math:`f: \mathbb{R}^n \mapsto \mathbb{R}^m`. Uses first-order difference :math:`J[:,i] = (f(x + dx) - f(x)) / dx`. If ``N`` is 2 or 3, then it is assumed that the function returns an SE(N) matrix which is converted into a Jacobian column comprising the translational Jacobian followed by the rotational Jacobian. """ Jcol = [] J0 = f(x) I = np.eye(len(x)) f0 = f(x) for i in range(len(x)): fi = f(x + I[:,i] * dx) Ji = (fi - f0) / dx if N > 0: t = Ji[:N,N] r = base.vex(Ji[:N,:N] @ J0[:N,:N].T) Ji = np.r_[t, r] Jcol.append(Ji) return np.c_[Jcol].T def hessian_numerical(J, x, dx=1e-8): r""" Numerically compute Hessian of Jacobian function :param J: the Jacobian function, returns an ndarray(m,n) :type J: callable :param x: function argument :type x: ndarray(n) :param dx: the numerical perturbation, defaults to 1e-8 :type dx: float, optional :return: Hessian matrix :rtype: ndarray(m,n,n) Computes a numerical approximation to the Hessian for ``J(x)`` where :math:`f: \mathbb{R}^n \mapsto \mathbb{R}^{m \times n}` Uses first-order difference :math:`H[:,:,i] = (J(x + dx) - J(x)) / dx`. """ I = np.eye(len(x)) Hcol = [] J0 = J(x) for i in range(len(x)): Ji = J(x + I[:,i] * dx) Hi = (Ji - J0) / dx Hcol.append(Hi) return np.stack(Hcol, axis=2) if __name__ == "__main__": import roboticstoolbox as rtb np.set_printoptions(linewidth=120, formatter={'float': lambda x: f"{x:8.4g}" if abs(x) > 1e-10 else f"{0:8.4g}"}) robot = rtb.models.DH.Puma560() q = robot.qn J = jacobian_numerical(lambda q: robot.fkine(q).A, q, N=3) print(J) print(robot.jacob0(q)) H = hessian_numerical(robot.jacob0, q) print(H) print(robot.ets().hessian0(q))
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/tools/numerical.py
0.881072
0.859605
numerical.py
pypi
import numpy as np from spatialmath import SE3, base import math from typing import Union from roboticstoolbox.fknm import Angle_Axis ArrayLike = Union[list, np.ndarray, tuple, set] def angle_axis(T, Td): try: e = Angle_Axis(T, Td) except BaseException: e = angle_axis_python(T, Td) return e def angle_axis_python(T, Td): e = np.empty(6) e[:3] = Td[:3, -1] - T[:3, -1] R = Td[:3, :3] @ T[:3, :3].T li = np.array([R[2, 1] - R[1, 2], R[0, 2] - R[2, 0], R[1, 0] - R[0, 1]]) if base.iszerovec(li): # diagonal matrix case if np.trace(R) > 0: # (1,1,1) case a = np.zeros((3,)) else: a = np.pi / 2 * (np.diag(R) + 1) else: # non-diagonal matrix case ln = base.norm(li) a = math.atan2(ln, np.trace(R) - 1) * li / ln e[3:] = a return e def p_servo( wTe, wTep, gain: Union[float, ArrayLike] = 1.0, threshold=0.1, method="rpy" ): """ Position-based servoing. Returns the end-effector velocity which will cause the robot to approach the desired pose. :param wTe: The current pose of the end-effecor in the base frame. :type wTe: SE3 or ndarray :param wTep: The desired pose of the end-effecor in the base frame. :type wTep: SE3 or ndarray :param gain: The gain for the controller. Can be vector corresponding to each axis, or scalar corresponding to all axes. :type gain: float, or array-like :param threshold: The threshold or tolerance of the final error between the robot's pose and desired pose :type threshold: float :param method: The method used to calculate the error. Default is 'rpy' - error in the end-effector frame. 'angle-axis' - error in the base frame using angle-axis method. :type method: string: 'rpy' or 'angle-axis' :returns v: The velocity of the end-effecotr which will casue the robot to approach wTep :rtype v: ndarray(6) :returns arrived: True if the robot is within the threshold of the final pose :rtype arrived: bool """ if isinstance(wTe, SE3): wTe = wTe.A if isinstance(wTep, SE3): wTep = wTep.A if method == "rpy": # Pose difference eTep = np.linalg.inv(wTe) @ wTep e = np.empty(6) # Translational error e[:3] = eTep[:3, -1] # Angular error e[3:] = base.tr2rpy(eTep, unit="rad", order="zyx", check=False) else: e = angle_axis(wTe, wTep) if base.isscalar(gain): k = gain * np.eye(6) else: k = np.diag(gain) v = k @ e arrived = True if np.sum(np.abs(e)) < threshold else False return v, arrived
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/tools/p_servo.py
0.912582
0.661021
p_servo.py
pypi
# Authors: Stuart Glaser, William Woodall, Robert Haschke # Maintainer: Morgan Quigley <morgan@osrfoundation.org> import xml.dom.minidom def first_child_element(elt): c = elt.firstChild while c and c.nodeType != xml.dom.Node.ELEMENT_NODE: c = c.nextSibling return c def next_sibling_element(node): c = node.nextSibling while c and c.nodeType != xml.dom.Node.ELEMENT_NODE: c = c.nextSibling return c def replace_node(node, by, content_only=False): parent = node.parentNode if by is not None: if not isinstance(by, list): by = [by] # insert new content before node for doc in by: if content_only: c = doc.firstChild while c: n = c.nextSibling parent.insertBefore(c, node) c = n else: parent.insertBefore(doc, node) # remove node parent.removeChild(node) def attribute(tag, a): """ Helper function to fetch a single attribute value from tag :param tag (xml.dom.Element): DOM element node :param a (str): attribute name :return: attribute value if present, otherwise None """ if tag.hasAttribute(a): # getAttribute returns empty string for non-existent attributes, # which makes it impossible to distinguish with empty values return tag.getAttribute(a) else: return None def opt_attrs(tag, attrs): """ Helper routine for fetching optional tag attributes :param tag (xml.dom.Element): DOM element node :param attrs [str]: list of attributes to fetch """ return [attribute(tag, a) for a in attrs] def reqd_attrs(tag, attrs): """ Helper routine for fetching required tag attributes :param tag (xml.dom.Element): DOM element node :param attrs [str]: list of attributes to fetch :raise RuntimeError: if required attribute is missing """ result = opt_attrs(tag, attrs) for (res, name) in zip(result, attrs): if res is None: raise RuntimeError("%s: missing attribute '%s'" % (tag.nodeName, name)) # pragma: no cover # noqa return result # Better pretty printing of xml # Taken from # http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace/ # noqa def fixed_writexml(self, writer, indent="", addindent="", newl=""): # pragma: no cover # noqa # indent = current indentation # addindent = indentation to add to higher levels # newl = newline string writer.write(indent + "<" + self.tagName) attrs = self._get_attributes() a_names = sorted(attrs.keys()) for a_name in a_names: writer.write(" %s=\"" % a_name) xml.dom.minidom._write_data(writer, attrs[a_name].value) writer.write("\"") if self.childNodes: if len(self.childNodes) == 1 \ and self.childNodes[0].nodeType == xml.dom.minidom.Node.TEXT_NODE: writer.write(">") self.childNodes[0].writexml(writer, "", "", "") writer.write("</%s>%s" % (self.tagName, newl)) return writer.write(">%s" % newl) for node in self.childNodes: # skip whitespace-only text nodes if node.nodeType == xml.dom.minidom.Node.TEXT_NODE and \ (not node.data or node.data.isspace()): continue node.writexml(writer, indent + addindent, addindent, newl) writer.write("%s</%s>%s" % (indent, self.tagName, newl)) else: writer.write("/>%s" % newl) # replace minidom's function with ours xml.dom.minidom.Element.writexml = fixed_writexml
/roboticstoolbox_python-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/roboticstoolbox/tools/xacro/xmlutils.py
0.622918
0.251393
xmlutils.py
pypi
import re class Map(object): """ An immutabel representation of the map of a maze.""" def __init__(self): self.height = 0 self.width = 0 self.extras = [] self.extras_type = {} self.paints_black = [] self.paints_black_type = {} self.paints_white = [] self.paints_white_type = {} self.tiles = [] self.tiles_type = {} self.startposses = [] self.beacons = [] def start_positions(self): return list(self.startposses) def start_beacons(self): return list(self.beacons) def contains_pos(self, pos): return pos[0]>=0 and pos[0]<self.width and pos[1]>=0 and pos[1]<self.height def available_pos(self, pos): return pos not in self.tiles def toMazeMap(self): result = {} mapLines = [] for y in range(0, self.height): line = [] for x in range(0, self.width): coord = (x,y) if coord in self.tiles_type: line.append(self.tiles_type[coord]) else: if coord in self.beacons: line.append("*") else: if coord in self.startposses: line.append("@") else: line.append(" ") mapLines.append(line) result["mapLines"] = mapLines paintLines = [] for item in self.paints_white: for t in self.paints_white_type[item]: cell = {} cell["x"] = item[0] cell["y"] = item[1] cell["type"] = t cell["color"] = "w" paintLines.append(cell) for item in self.paints_black: for t in self.paints_black_type[item]: cell = {} cell["x"] = item[0] cell["y"] = item[1] cell["type"] = t cell["color"] = "b" paintLines.append(cell) result["paintLines"] = paintLines extraLines = [] for item in self.extras: cell = {} cell["x"] = item[0] cell["y"] = item[1] cell["id"] = self.extras_type[item] extraLines.append(cell) result["extraLines"] = extraLines robotLines = [] for item in self.startposses: cell = {} cell["id"] = "Robo" cell["x"] = item[0] cell["y"] = item[1] robotLines.append(cell) result["robotLines"] = robotLines beaconLines = [] for item in self.beacons: cell = {} cell["x"] = item[0] cell["y"] = item[1] cell["type"] = "beacon" cell["id"] = f"[{item[0]},{item[1]}]" beaconLines.append(cell) result["beaconLines"] = beaconLines return result @classmethod def fromfile(cls, file): with open(file) as f: return cls.fromlist(f) @classmethod def fromstring(cls, string): list = string.split("\n") return cls.fromlist(list) @classmethod def fromlist(cls, list): builder = MapBuilder() reader = MapReader(list, builder) reader.read() return builder.build() class MapBuilder(object): def __init__(self): self.height = 0 self.width = 0 self.extras = [] self.extras_type = {} self.paints_black = [] self.paints_black_type = {} self.paints_white = [] self.paints_white_type = {} self.tiles = [] self.tiles_type = {} self.startposses = [] self.beacons = [] def extra(self,type,x,y): self.extras.append((x,y)) self.extras_type[(x,y)] = type def paint(self, color, type, x, y): pos = (x,y) if color == "b": self.paints_black.append(pos) if pos in self.paints_black_type: self.paints_black_type[pos].append(type) else: self.paints_black_type[pos] = [type] else: self.paints_white.append(pos) if pos in self.paints_white_type: self.paints_white_type[pos].append(type) else: self.paints_white_type[pos] = [type] def beacon(self, x, y): self.coord(x,y) self.beacons.append((x,y)) def startpos(self, x, y): self.coord(x,y) self.startposses.append((x,y)) def tile(self, x, y, t): self.coord(x,y) self.tiles.append((x,y)) self.tiles_type[(x,y)] = t def coord(self, x, y): if self.width < x: self.width = x if self.height < y: self.height = y def build(self): mapper = Map() mapper.width = self.width+1 mapper.height = self.height+1 mapper.extras = self.extras mapper.extras_type = self.extras_type mapper.paints_black = self.paints_black mapper.paints_black_type = self.paints_black_type mapper.paints_white = self.paints_white mapper.paints_white_type = self.paints_white_type mapper.tiles = self.tiles mapper.tiles_type = self.tiles_type mapper.startposses = self.startposses mapper.beacons = self.beacons return mapper class MapReader(object): def __init__(self, f, builder): self.f = f self.builder = builder self.blokline = re.compile(r"""(\S+):""") self.extraline = re.compile(r"""(\S+)@(\d+),(\d+)""") self.paintline = re.compile(r"""\s*([wb])\s*,\s*([.\-|])\s*,\s*(\d+)\s*,\s*(\d+)\s*""") self.section = None self.nextx = 0 self.nexty = 0 def read(self): for line in self.f: if not line.startswith("#"): blockhead = self.blokline.match(line) if blockhead: section = blockhead.group(1) if section == 'extra': self.section = 'extra' elif section == 'map': self.section = 'map' elif section == 'paint': self.section = 'paint' else: if self.section == "extra": self.extra_line(line) elif self.section == "map": self.map_line(line) elif self.section == 'paint': self.paint_line(line) def extra_line(self, line): extramatch = self.extraline.match(line) if extramatch: type = extramatch.group(1) x = int(extramatch.group(2)) y = int(extramatch.group(3)) self.builder.extra(type,x,y) def map_line(self, line): self.nextx = 0 for ch in line: if ch == '@': self.builder.startpos(self.nextx, self.nexty) elif ch == '*': self.builder.beacon(self.nextx, self.nexty) elif ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": self.builder.tile(self.nextx, self.nexty, ch) self.nextx = self.nextx + 1 self.nexty = self.nexty + 1 def paint_line(self, line): all = re.findall("\((.*?)\)", line) for item in all: paintmatch = self.paintline.match(item) if paintmatch: color = paintmatch.group(1) type = paintmatch.group(2) x = int(paintmatch.group(3)) y = int(paintmatch.group(4)) self.builder.paint(color,type,x,y)
/robotjes_client-0.0.1a5-py3-none-any.whl/robotjes/sim/map.py
0.493897
0.193376
map.py
pypi
class Semantics: def __init__(self): self.opers = { "clear": self.check, "obstacle": self.check, "beacon": self.check, "white": self.check, "black": self.check, "nopaint": self.check, "robot": self.check, "maxEats": self.maxEats, "robotHasBeacon": self.robotHasBeacon, "robotHasBumped": self.robotHasBumped, "minWhitePaintUsed": self.minWhitePaintUsed, "minBlackPaintUsed": self.minBlackPaintUsed, "putDown": self.true, "pickUp": self.true, } def eval(self, identifier, args, world): if identifier in self.opers: oper = self.opers[identifier] return oper(identifier, args, world) else: print(f"unknown Semantics: {identifier}") return True def check(self, identifier, args, world): # note that the identifier name need to match the constants defined in world.py if len(args) < 2: return False pos = (args[0], args[1]) return world.check_pos(pos, identifier) def maxEats(self, identifier, args, world): if len(args) != 1: return False return world.get("eats") < args[0] def robotHasBeacon(self, identifier, args, world): owned_beacons = 0 for bot in world.bots.values(): owned_beacons = owned_beacons + len(bot.beacons) return owned_beacons > 0 def robotHasBumped(self, identifier, args, world): return world.get("robotHasBumped") > 0 def minWhitePaintUsed(self, identifier, args, world): if len(args) != 1: return False return world.profile["whitePaintUsed"] >= args[0] def minBlackPaintUsed(self, identifier, args, world): if len(args) != 1: return False return world.profile["blackPaintUsed"] >= args[0] def true(self, identifier, args, world): return True ROBO_SEMANTICS = Semantics()
/robotjes_client-0.0.1a5-py3-none-any.whl/robotjes/sim/success/semantics.py
0.666388
0.518363
semantics.py
pypi
import pyparsing as pp class OrCondition(object): def __init__(self, tokens): self.terms = [x for x in tokens if not isinstance(x, str)] def eval(self, world, semantics): for term in self.terms: if term.eval(world, semantics): return True return False class AndCondition(object): def __init__(self, tokens): self.terms = [x for x in tokens if not isinstance(x, str)] def eval(self, world, semantics): for term in self.terms: if not term.eval(world, semantics): return False return True class NotCondition(object): def __init__(self, tokens): if len(tokens) == 1: self.negated = False self.condition = tokens[0] else: self.negated = True self.condition = tokens[1] def eval(self, world, semantics): result = self.condition.eval(world, semantics) return result != self.negated class Condition(object): def __init__(self, tokens): self.identifier = tokens[0] self.args = [x.number for x in tokens[1:]] def eval(self, world, semantics): return semantics.eval(self.identifier.name, self.args, world) class Number(object): def __init__(self, nums): self.number = int(nums[0]) def eval(self, world, semantics): return True def __str__(self): return self.number class Identifier(object): def __init__(self, name): self.name = name[0] def eval(self, world, semantics): return True def __str__(self): return self.name def language_def(): and_ = pp.CaselessLiteral("and") or_ = pp.CaselessLiteral("or") not_ = pp.CaselessLiteral("not") number = (pp.Word(pp.nums)).setParseAction(Number) functionname = pp.Word(pp.alphanums + '_').setParseAction(Identifier) functionbody = pp.Forward() functionbody <<= functionname + (pp.Suppress("(") + pp.Optional(pp.delimitedList(number),'') + pp.Suppress(")")) condition = functionbody | functionname condition.setParseAction(Condition) not_condition = (not_ + condition | condition).setParseAction(NotCondition) and_condition = (not_condition + pp.ZeroOrMore(and_ + not_condition)).setParseAction(AndCondition) or_condition = (and_condition + pp.ZeroOrMore(or_ + and_condition)).setParseAction(OrCondition) expression = or_condition return expression ROBO_LANGUAGE = language_def()
/robotjes_client-0.0.1a5-py3-none-any.whl/robotjes/sim/success/language.py
0.647018
0.260187
language.py
pypi
from asciimatics.scene import Scene from asciimatics.screen import Screen from asciimatics.widgets import Frame, Text, Layout class PlayerDisplay: # controller object def __init__(self, headerline): self.model = PlayerModel(headerline) self.view = PlayerScreen(self.model) def close(self): self.view.close() def has_key(self): return self.view.has_key def timer(self): if self.view.screen.has_resized(): self.view.close() self.view = PlayerScreen(self.model) self.view.timer() def create_robo(self, game_tick, robo_id): pass def robo_status(self, game_tick, robo_id, robo_status): self.model.set_robo_status(game_tick, robo_id, robo_status) self.view.update(game_tick, 'robo', robo_id) def issue_command(self, game_tick, robo_id, cmd, reply): pass class PlayerModel: # model object def __init__(self, headerline): self.headerline = headerline self.game_tick = -1 self.cur_robo_status = {} # { # 'pos': [7, 11], # 'load': 0, # 'dir': 180, # 'recording': [ # [304, 'forward', [1], True], # [305, 'right', [1], True], # [306, 'forward', [1], True]], # 'fog_of_war': { # 'left': [None, None, None, False], # 'front': [None, None, None, False], # 'right': [None, None, None, False] # } # } def set_robo_status(self, game_tick, robo_id, robo_status): self.game_tick = game_tick self.cur_robo_status[robo_id] = robo_status class PlayerScreen: # main screen/view/windows object def __init__(self, model): self.model = model self.last_event = None self.has_key = False Screen.wrapper(self.populate, catch_interrupt=True) def populate(self, screen): self.screen = screen self.robo_view = RoboView(self.screen, self.model) self.scenes = [] self.effects = [ self.robo_view ] self.scenes.append(Scene(self.effects, -1)) self.screen.set_scenes(self.scenes) def update(self, game_tick, type, *args): if type == 'robo': self.robo_view.upd(args) else: pass def close(self): self.screen.close() def timer(self): self.last_event = self.screen.get_event() if not self.has_key and self.last_event: self.has_key = True self.screen.draw_next_frame() class RoboView(Frame): def __init__(self, screen, model): super(RoboView, self).__init__(screen, screen.height * 1 // 3, screen.width, x=0, y=screen.height * 1 // 3, on_load=self.upd, hover_focus=False, title="Robos") self.model = model self.position_field = Text("", "position") self.dir_field = Text("", "direction") self.load_field = Text("", "load") layout = Layout([1, 1, 1], fill_frame=True) self.add_layout(layout) layout.add_widget(self.position_field, 0) layout.add_widget(self.dir_field, 1) layout.add_widget(self.load_field, 2) self.set_theme('monochrome') self.fix() def upd(self, *args): if self.model.cur_robo_status and len(args)>0 and len(args[0])>0: robo_id = args[0][0] robo_status = self.model.cur_robo_status if robo_id in robo_status and len(robo_status[robo_id])>0: self.position_field.value = str(self.model.cur_robo_status[robo_id]['pos']) self.dir_field.value = str(self.model.cur_robo_status[robo_id]['dir']) self.load_field.value = str(self.model.cur_robo_status[robo_id]['load'])
/robotjes_client-0.0.1a5-py3-none-any.whl/robotjes/client/aui/player_screen.py
0.554229
0.202049
player_screen.py
pypi
from asciimatics.scene import Scene from asciimatics.screen import Screen from asciimatics.widgets import Frame, Text, Layout class ViewerDisplay: # controller object def __init__(self): self.model = PlayerModel() self.view = PlayerScreen(self.model) def close(self): self.view.close() def has_key(self): return self.view.has_key def timer(self): if self.view.screen.has_resized(): self.view.close() self.view = PlayerScreen(self.model) self.view.timer() def game_status(self, game_tick, game_status): self.model.set_game_status(game_tick, game_status) self.view.update(game_tick, 'game') def player_status(self, game_tick, player_status): self.model.set_player_status(game_tick, player_status) self.view.update(game_tick, 'player') def robo_status(self, game_tick, robo_id, robo_status): self.model.set_robo_status(game_tick, robo_id, robo_status) self.view.update(game_tick, 'robo', robo_id) class PlayerModel: # model object def __init__(self): self.game_tick = -1 self.cur_game_status = None self.cur_player_status = None self.cur_robo_status = {} # { # 'game_id': '240cc20b-96f5-4b61-b88e-06f930006c6c', # 'game_name': 'the_game', # 'status': { # 'game_tick': 405, # 'isStarted': True, # 'isStopped': False, # 'isSuccess': True # } # } def set_game_status(self, game_tick, game_status): self.game_tick = game_tick self.cur_game_status = game_status # { # 'player_id': 'd6e023e8-8adb-4482-a07e-8f8e1328a3da', # 'robos': ... # } def set_player_status(self, game_tick, player_status): self.game_tick = game_tick self.cur_player_status = player_status # { # 'pos': [7, 11], # 'load': 0, # 'dir': 180, # 'recording': [ # [304, 'forward', [1], True], # [305, 'right', [1], True], # [306, 'forward', [1], True]], # 'fog_of_war': { # 'left': [None, None, None, False], # 'front': [None, None, None, False], # 'right': [None, None, None, False] # } # } def set_robo_status(self, game_tick, robo_id, robo_status): self.game_tick = game_tick self.cur_robo_status[robo_id] = robo_status class PlayerScreen: # main screen/view/windows object def __init__(self, model): self.model = model self.last_event = None self.has_key = False Screen.wrapper(self.populate, catch_interrupt=True) def populate(self, screen): self.screen = screen self.game_view = GameView(self.screen, self.model) self.player_view = PlayerView(self.screen, self.model) self.robo_view = RoboView(self.screen, self.model) self.scenes = [] self.effects = [ self.game_view, self.player_view, self.robo_view ] self.scenes.append(Scene(self.effects, -1)) self.screen.set_scenes(self.scenes) def update(self, game_tick, type, *args): if type == 'game': self.game_view.upd(args) elif type == 'player': self.player_view.upd(args) elif type == 'robo': self.robo_view.upd(args) else: pass def close(self): self.screen.close() def timer(self): self.last_event = self.screen.get_event() if not self.has_key and self.last_event: self.has_key = True self.screen.draw_next_frame() class GameView(Frame): def __init__(self, screen, model): super(GameView, self).__init__(screen, screen.height * 1 // 3, screen.width * 1 // 2, x=0, y=0, on_load=self.upd, hover_focus=True, title="Game") self.model = model self.gameid_field = Text("", "gameid") self.gamename_field = Text("", "gamename") self.gametick_field = Text("", "gametick") layout = Layout([4,1,1], fill_frame=True) self.add_layout(layout) layout.add_widget(self.gameid_field, 0) layout.add_widget(self.gamename_field, 1) layout.add_widget(self.gametick_field, 2) self.set_theme('monochrome') self.fix() def upd(self, *args): if self.model.cur_game_status: self.gameid_field.value = self.model.cur_game_status['game_id'] self.gamename_field.value = self.model.cur_game_status['game_name'] self.gametick_field.value = str(self.model.cur_game_status['status']['game_tick']) class PlayerView(Frame): def __init__(self, screen, model): super(PlayerView, self).__init__(screen, screen.height * 1 // 3, screen.width * 1 // 2, x=screen.width//2, y=0, on_load=self.upd, hover_focus=True, title="Player") self.model = model self.playerid_field = Text("", "playerid") self.playername_field = Text("", "playername") layout = Layout([1,1], fill_frame=True) self.add_layout(layout) layout.add_widget(self.playerid_field, 0) layout.add_widget(self.playername_field, 1) self.set_theme('monochrome') self.fix() def upd(self, *args): if self.model.cur_player_status: self.playerid_field.value = self.model.cur_player_status['player_id'] self.playername_field.value = self.model.cur_player_status['player_name'] # { # 'pos': [7, 11], # 'load': 0, # 'dir': 180, # 'recording': [ # [304, 'forward', [1], True], # [305, 'right', [1], True], # [306, 'forward', [1], True]], # 'fog_of_war': { # 'left': [None, None, None, False], # 'front': [None, None, None, False], # 'right': [None, None, None, False] # } # } class RoboView(Frame): def __init__(self, screen, model): super(RoboView, self).__init__(screen, screen.height * 1 // 3, screen.width, x=0, y=screen.height * 1 // 3, on_load=self.upd, hover_focus=False, title="Robos") self.model = model self.position_field = Text("", "position") self.dir_field = Text("", "direction") self.load_field = Text("", "load") layout = Layout([1, 1, 1], fill_frame=True) self.add_layout(layout) layout.add_widget(self.position_field, 0) layout.add_widget(self.dir_field, 1) layout.add_widget(self.load_field, 2) self.set_theme('monochrome') self.fix() def upd(self, *args): if self.model.cur_robo_status and len(args)>0 and len(args[0])>0: robo_id = args[0][0] robo_status = self.model.cur_robo_status if robo_id in robo_status and len(robo_status[robo_id])>0: self.position_field.value = str(self.model.cur_robo_status[robo_id]['pos']) self.dir_field.value = str(self.model.cur_robo_status[robo_id]['dir']) self.load_field.value = str(self.model.cur_robo_status[robo_id]['load'])
/robotjes_client-0.0.1a5-py3-none-any.whl/robotjes/client/aui/viewer_screen.py
0.473414
0.214239
viewer_screen.py
pypi
import uuid import sys class Robo(object): """ Manipulate a Robot using these instructions.""" OBSERVATIONS = { 'leftIsClear': ['left', 'clear'], 'leftIsObstacle': ['left', 'obstacle'], 'leftIsBeacon': ['left', 'beacon'], 'leftIsRobo': ['left', 'robot'], 'leftIsBlack': ['left', 'black'], 'leftIsWhite': ['left', 'white'], 'frontIsClear': ['front', 'clear'], 'frontIsObstacle': ['front', 'obstacle'], 'frontIsBeacon': ['front', 'beacon'], 'frontIsRobo': ['front', 'robot'], 'frontIsBlack': ['front', 'black'], 'frontIsWhite': ['front', 'white'], 'rightIsClear': ['right', 'clear'], 'rightIsObstacle': ['right', 'obstacle'], 'rightIsBeacon': ['right', 'beacon'], 'rightIsRobo': ['right', 'robot'], 'rightIsBlack': ['right', 'black'], 'rightIsWhite': ['right', 'white'] } def __init__(self, requestor, id=str(uuid.uuid4())): self.requestor = requestor self.id = id self.is_running = True def _set_id(self, robo_id): self.id = robo_id # A result looks like this (at least in run-simulation, still need to do cli_remote_player. cli_local_player) # [[6, '06264681-6bac-4a91-9a88-73f70ae1f942', 'right', 2], # ([[True, 0], # [True, 270], # {'dir': 270, # 'fog_of_war': {'front': [None, None, None, False], # 'left': [None, None, None, False], # 'right': [None, None, None, False]}, # 'load': 0, # 'pos': (7, 11), # 'recording': [[1, 'message', ['starting'], True], # [2, 'right', [2], True]]c # } # ], # ) # ] def _handle_result(self, result): player_result = result[2] robo_status = result[1] if not player_result['active']: self.is_running = False return robo_status def _handle_boolean_result(self, result): if not self.is_running: self.stop() return result[0] def forward(self, steps=1): """do a number of steps forward.""" result = self.requestor.execute([self.id, 'forward', int(steps)]) return self._handle_result(result) def backward(self, steps=1): """do a number of steps backward.""" result = self.requestor.execute([self.id, 'backward', int(steps)]) return self._handle_result(result) def left(self, steps=1): """turn left a number steps.""" result = self.requestor.execute([self.id, 'left', int(steps)]) return self._handle_result(result) def right(self, steps=1): """turn right a number steps.""" result = self.requestor.execute([self.id, 'right', int(steps)]) return self._handle_result(result) def pickUp(self): """pick up a beacon that is right in front.""" result = self.requestor.execute([self.id, 'pickUp']) return self._handle_result(result) def putDown(self): """put down a beacon right in front.""" result = self.requestor.execute([self.id, 'putDown']) return self._handle_result(result) def eatUp(self): """pick up a beacon that is right in front and eat/destroy it.""" result = self.requestor.execute([self.id, 'eatUp']) return self._handle_result(result) def paintWhite(self): """start painting white.""" result = self.requestor.execute([self.id, 'paintWhite']) return self._handle_result(result) def paintBlack(self): """start painting black.""" result = self.requestor.execute([self.id, 'paintBlack']) return self._handle_result(result) def stopPainting(self): """stop painting.""" result = self.requestor.execute([self.id, 'stopPainting']) return self._handle_result(result) def leftIsClear(self): """test if the position to the left is clear.""" result = self.requestor.execute([self.id, 'leftIsClear']) return self._handle_boolean_result(result) def leftIsObstacle(self): """test if the position to the left is not clear.""" result = self.requestor.execute([self.id, 'leftIsObstacle']) return self._handle_boolean_result(result) def leftIsBeacon(self): """test if the position to the left contains a beacon.""" result = self.requestor.execute([self.id, 'leftIsBeacon']) return self._handle_boolean_result(result) def leftIsRobot(self): """test if the position to the left contains a robot.""" result = self.requestor.execute([self.id, 'leftIsRobot']) return self._handle_boolean_result(result) def leftIsWhite(self): """test if the position to the left is painted white.""" result = self.requestor.execute([self.id, 'leftIsWhite']) return self._handle_boolean_result(result) def leftIsBlack(self): """test if the position to the left is painted black.""" result = self.requestor.execute([self.id, 'leftIsBlack']) return self._handle_boolean_result(result) def frontIsClear(self): """test if the position in front is clear.""" result = self.requestor.execute([self.id, 'frontIsClear']) return self._handle_boolean_result(result) def frontIsObstacle(self): """test if the position in front is not clear.""" result = self.requestor.execute([self.id, 'frontIsObstacle']) return self._handle_boolean_result(result) def frontIsBeacon(self): """test if the position in front contains a beacon.""" result = self.requestor.execute([self.id, 'frontIsBeacon']) return self._handle_boolean_result(result) def frontIsRobot(self): """test if the position in front contains a robot.""" result = self.requestor.execute([self.id, 'frontIsRobot']) return self._handle_boolean_result(result) def frontIsWhite(self): """test if the position in front is painted white.""" result = self.requestor.execute([self.id, 'frontIsWhite']) return self._handle_boolean_result(result) def frontIsBlack(self): """test if the position in front is painted black.""" result = self.requestor.execute([self.id, 'frontIsBlack']) return self._handle_boolean_result(result) def rightIsClear(self): result = self.requestor.execute([self.id, 'rightIsClear']) return self._handle_boolean_result(result) def rightIsObstacle(self): result = self.requestor.execute([self.id, 'rightIsObstacle']) return self._handle_boolean_result(result) def rightIsBeacon(self): result = self.requestor.execute([self.id, 'rightIsBeacon']) return self._handle_boolean_result(result) def rightIsRobot(self): result = self.requestor.execute([self.id, 'rightIsRobot']) return self._handle_boolean_result(result) def rightIsWhite(self): result = self.requestor.execute([self.id, 'rightIsWhite']) return self._handle_boolean_result(result) def rightIsBlack(self): result = self.requestor.execute([self.id, 'rightIsBlack']) return self._handle_boolean_result(result) def message(self, message): self.requestor.execute([self.id, 'message', message]) def error(self, message): self.requestor.execute([self.id, 'error', message]) def stop(self): # self.requestor.execute([]) sys.exit("robo break") def active(self): return self.is_running @staticmethod def is_observation(cmd): return cmd and isinstance(cmd, list) and len(cmd) >= 3 and cmd[2] in Robo.OBSERVATIONS @staticmethod def observation(status, cmd): (selector, type) = Robo.OBSERVATIONS[cmd[2]] if status and selector in status['fog_of_war']: lst = status['fog_of_war'][selector] # lst -> [tile, paint, robot, beacon] # -> None|t, None|p, None|id, None|True] if type == 'clear': return lst[0] is None and lst[2] is None and lst[3] is None elif type == 'obstacle': return lst[0] is not None or lst[2] is not None or lst[3] is not None elif type == 'beacon': return lst[3] is not None elif type == 'robot': return lst[2] is not None elif type == 'black': return lst[1] == 'black' elif type == 'white': return lst[1] == 'white' else: raise Exception(f"illegal status type{type}") else: return False
/robotjes_client-0.0.1a5-py3-none-any.whl/robotjes/bot/robo.py
0.702734
0.472136
robo.py
pypi
``` *** Settings *** Library JupyterLibrary Suite setup Suite setup *** Variables *** ${BROWSER} firefox ${test1} SEPARATOR=\n ... *** Test Cases *** ... ... Works are equal ... \ \ Should be equal\ \ hello\ \ hello ${test2} SEPARATOR=\n ... *** Test Cases *** ... ... Works are equal ... \ \ Should be equal\ \ hello\ \ world *** Keywords *** Suite Setup ${server}= Wait for new jupyter server to be ready jupyter-lab ${url}= Get jupyter server url ${server} ${token}= Get jupyter server token ${server} Open browser ${url}?token=${token} browser=${BROWSER} alias=default Set window size 1200 900 Wait until page contains Robot Framework Sleep 1s Launch a new JupyterLab Document Robot Framework Notebook Suite Teardown Close all browsers Terminate all jupyter servers *** Test cases *** Test passing in notebook Click element css:button[title="Cut the selected cells"] Click element css:button[title="Cut the selected cells"] Click element css:DIV.CodeMirror-code > PRE.CodeMirror-line Press keys css:DIV.CodeMirror-code > PRE.CodeMirror-line ${test1} Press keys css:DIV.CodeMirror-code > PRE.CodeMirror-line SHIFT+ENTER Wait until element is visible link:Log Wait until element is visible link:Report Page should not contain FAIL *** Test cases *** Test failing in notebook Click element css:button[title="Cut the selected cells"] Click element css:button[title="Cut the selected cells"] Click element css:DIV.CodeMirror-code > PRE.CodeMirror-line Press keys css:DIV.CodeMirror-code > PRE.CodeMirror-line ${test2} Press keys css:DIV.CodeMirror-code > PRE.CodeMirror-line SHIFT+ENTER Wait until element is visible link:Log Wait until element is visible link:Report Page should contain FAIL *** Settings *** Suite teardown Suite teardown ```
/robotkernel-1.6a1.tar.gz/robotkernel-1.6a1/atest/Test Robot Notebook.ipynb
0.467089
0.155816
Test Robot Notebook.ipynb
pypi
# WhiteLibrary Support RobotKernel can include dedicated support for selected libraries. One of these libraries is [WhiteLibrary](https://github.com/Omenia/robotframework-whitelibrary) – the current library of choice for testing and automating Windows applications. ``` *** Settings *** Library WhiteLibrary ``` ## State management RobotKernel remembers the current WhiteLibrary context between executions. That's why it is possible to launch and attach application once and then move on to work on keywors testing or automating that application. ``` *** Keywords *** Attach Notepad window Launch application notepad.exe Attach application by name notepad Attach window title:Nimetön – Muistio ``` ## Element picker RobotKernel has also an interactive built-in element picker to help selecting elements for WhiteLibrary keywords. This element picker is activated by typing the special pseudo selector prefix ``ae:`` (*automation element*) and pressing `<TAB>` (similarly to triggering autocompletion suggestions in Jupyter Notebook and JupyterLab). Once picker is activated, it changes mouse pointer into crosshair. After the desired element is clicked with that crosshair pointer, RobotKernel will suggest supported selector completions (like *text:*, *id:* or *class_name:*). ``` *** Keywords *** Input into Notepad [Arguments] ${text}=Here be dragons Input text to textbox class_name=Edit ${text}\n ``` Because not all elements, like menu items for example, can be selected with a simple click, there is one more thing: **long press selection**. Once mouse button is kept pressed for a few seconds, single click is emulated to the underlying element. This should be enough to let the menu be opened. Then it is possible to keep the mouse button pressed, move its pointer above the desired menu element, wait a second to see the menu item focused, and finally release the mouse button to get supported selectors for the element. ``` *** Keywords *** Clear notepad Click menu button text=Muokkaa Click menu button text=Valitse kaikki Click menu button text=Muokkaa Click menu button text=Poista *** Keywords *** Save file [Arguments] ${filename}=hello-world.txt Click menu button text=Tiedosto Click menu button text=Tallenna nimellä... Input text to textbox text=Tiedostonimi: ${filename} Select listbox value text=Koodaus: Unicode Click button text=Tallenna ``` ## OpenCV template grabber and matcher Finally, RobotKernel ships with an experimental image recognition based Windows automation support based on [OpenCV computer vision library](https://opencv.org/), if that's available on the current Python environment. ``` *** Settings *** Library WhiteLibrary Library robotkernel.WhiteLibraryCompanion ``` The special keyword library **robotkernel.WhiteLibraryCompanion** provides a single keyword: **Click template** with arguments **template** and **similarity** (with default value 0.95 to require exact match). The magic is hidden within the keyword argument **template** as follows: 1. type ``Click template template=`` and 2. press ``<TAB>``. Once again the mouse cursor is changed into crosshair, but this time it expects a rectangular area to be painted with dragging the default mouse button pressed. Once the mouse button is released: 1. a screenshot is captured from the painted area 2. it is saved in to the current working directory of Jupyter process and 3. ``template=`` part of the keyword is replaced with ``template=${EXECDIR}\\[TIMESTAMP].png`` and now the keyword is ready to be called. Call of the keyword captures screenshot of the current default screen, looks for captured area using OpenCV matchTemplate and click the center of the found match using WhiteLibrary mouse automation functions. ``` *** Keywords *** Open calc Launch application calc.exe Attach window Laskin 1 Click template template=${EXECDIR}\\1554037865.png + Click template template=${EXECDIR}\\1554037877.png 2 Click template template=${EXECDIR}\\1554037888.png ```
/robotkernel-1.6a1.tar.gz/robotkernel-1.6a1/docs/notebooks/08 Interactive WhiteLibrary.ipynb
0.419886
0.852199
08 Interactive WhiteLibrary.ipynb
pypi
# What is the JupyterLab? (Adapted from the official [What is the Jupyter Notebook](https://github.com/jupyter/notebook/blob/master/docs/source/examples/Notebook/What%20is%20the%20Jupyter%20Notebook.ipynb) notebook.) ## Introduction The JupyterLab is an **interactive computing environment** that enables its users to author notebook documents that include: - Live code - Narrative text - Images - Interactive widgets - Plots These documents provide a **complete and self-contained record of a computation** that can be converted to various formats and shared with others using email, [Dropbox](https://www.dropbox.com/), version control systems (like git/[GitHub](https://github.com)) or [nbviewer.jupyter.org](http://nbviewer.jupyter.org). ### Components The Jupyter Notebook combines three components: * **The notebook web application**: An interactive web application for writing and running code interactively and authoring notebook documents. * **Kernels**: Separate processes started by the notebook web application that runs users' code in a given language and returns output back to the notebook web application. The kernel also handles things like computations for interactive widgets, tab completion and introspection. * **Notebook documents**: Self-contained documents that contain a representation of all content visible in the notebook web application, including inputs and outputs of the executions, narrative text, equations, images, and rich media representations of objects. Each notebook document has its own kernel. ## Notebook web application The notebook web application enables users to: * **Edit code in the browser**, with automatic syntax highlighting, indentation, and tab completion/introspection. * **Run code from the browser**, with the results of executions attached to the code which generated them. * See the results of executions with **rich media representations**, such as HTML, LaTeX, PNG, SVG, PDF, etc. * Author **narrative text** using the [Markdown](https://daringfireball.net/projects/markdown/) markup language. * Create and use **interactive JavaScript widgets**, which bind interactive user interface controls and visualizations to reactive kernel side executions. ## Kernels Through [Jupyter's kernel and messaging architecture](https://jupyter.readthedocs.io/en/latest/architecture/how_jupyter_ipython_work.html), the Notebook allows code to be run in a range of different programming languages. For each notebook document that a user opens, the web application starts a kernel that runs the code for that notebook. Each kernel is capable of running code in a single programming language and there are kernels available in the following languages: * Python(https://github.com/ipython/ipython) * Julia (https://github.com/JuliaLang/IJulia.jl) * R (https://github.com/IRkernel/IRkernel) * Ruby (https://github.com/minrk/iruby) * Haskell (https://github.com/gibiansky/IHaskell) * Scala (https://github.com/Bridgewater/scala-notebook) * node.js (https://gist.github.com/Carreau/4279371) * Go (https://github.com/takluyver/igo) * Robot Framework (https://github.com/robots-from-jupyter/robotkernel/) The default kernel runs Python code. The notebook provides a simple way for users to pick which of these kernels is used for a given notebook. Each of these kernels communicate with the notebook web application and web browser using [a JSON over ZeroMQ/WebSockets message protocol](https://jupyter-client.readthedocs.io/en/latest/messaging.html#messaging). Most users don't need to know about these details, but it helps to understand that "kernels run code." ## Notebook documents Notebook documents contain the **inputs and outputs** of an interactive session as well as **narrative text** that accompanies the code but is not meant for execution. **Rich output** generated by running code, including HTML, images, video, and plots, is embeddeed in the notebook, which makes it a complete and self-contained record of a computation. When you run the notebook web application on your computer, notebook documents are just **files on your local filesystem with a `.ipynb` extension**. This allows you to use familiar workflows for organizing your notebooks into folders and sharing them with others. Notebooks consist of a **linear sequence of cells**. There are two basic cell types: * **Code cells:** Input and output of live code that is run in the kernel * **Markdown cells:** Narrative text or headings of hierarchical organization Internally, notebook documents are **[JSON](https://en.wikipedia.org/wiki/JSON) data** with **binary values [base64](http://en.wikipedia.org/wiki/Base64)** encoded. This allows them to be **read and manipulated programmatically** by any programming language. Because JSON is a text format, notebook documents are version control friendly. **Notebooks can be exported** to different static formats including HTML, reStructeredText, LaTeX, PDF, and slide shows ([reveal.js](http://lab.hakim.se/reveal-js/)) using Jupyter's `nbconvert` utility. Furthermore, any notebook document available from a **public URL on or GitHub can be shared** via [nbviewer](http://nbviewer.jupyter.org). This service loads the notebook document from the URL and renders it as a static web page. The resulting web page may thus be shared with others **without their needing to install the JupyterLab**.
/robotkernel-1.6a1.tar.gz/robotkernel-1.6a1/docs/notebooks/00 What is the Jupyter Notebook.ipynb
0.877431
0.965996
00 What is the Jupyter Notebook.ipynb
pypi
# Prototyping Keywords RobotKernel allows fast execution of individual keywords with or without arguments through Jupyter widgets. This is **ideal for keyword prototyping or manually invoked automation**. ## Executable keywords Every time a cell with `*** Keywords ***`, but without tasks or tests cases, is executed for the first time, **input fields** for keyword arguments **and buttons** for keyword execution **are being rendered below the cell**. **To toggle visibility of the widgets, simply execute the cell again, unchanged.** (Note: Currently these widgets won't get saved properly with notebook files so they should be hidden before saving the notebook.) ## Re-executable keyword example ``` *** Keywords *** Increment suite variable [Arguments] ${increment}=1 ${value}= Get variable value ${global value} 0 ${value}= Evaluate ${value} + ${increment} Set suite variable ${global value} ${value} [Return] ${value} ``` For example, the above keyword **Increment suite variable** will render a single input field for its argument and a button to execute the keyword with the argument value being read from the input field. Because **RobotKernel keeps the state of custom suite level variables between executions**, the keyword above allows incrementing a suite level variable with custom amount as long as the kernel is being restarted. ## Example for Windows Here's a more complex example about automating Windows with WhiteLibrary. The example, which is written for Windows in Finnish language, defines keywords for opening Notepad application, inserting given texts into notepad window and saving the results with given filename. ``` *** Settings *** Library WhiteLibrary *** Tasks *** Attach Notepad window Launch application notepad.exe Attach application by name notepad Attach window Nimetön – Muistio *** Keywords *** Input into Notepad [Arguments] ${text}=Here be dragons Input text to textbox class_name=Edit ${text}\n Clear notepad Click menu button text=Muokkaa Click menu button text=Valitse kaikki Click menu button text=Muokkaa Click menu button text=Poista Save file [Arguments] ${filename}=hello-world.txt Click menu button text=Tiedosto Click menu button text=Tallenna nimellä... Input text to textbox text=Tiedostonimi: ${filename} Select listbox value text=Koodaus: Unicode Click button text=Tallenna ```
/robotkernel-1.6a1.tar.gz/robotkernel-1.6a1/docs/notebooks/07 Prototyping Keywords.ipynb
0.409103
0.815637
07 Prototyping Keywords.ipynb
pypi
# Running Code First and foremost, the JupyterLab is an interactive environment for writing and running code. JupyterLab is capable of running code in a wide range of languages. However, each notebook is associated with a single kernel. **This notebook is associated with the IPython kernel. Therefore this notebook runs Python code.** ## Code cells allow you to enter and run code Run an active code cell and advance using `Shift + Enter` or pressing the <span class="jp-RunIcon jp-Icon jp-Icon-16 jp-ToolbarButtonComponent-icon"></span> button in the toolbar above: ``` a = 10 a ``` As seen above, the state is preserved by kernel between cells: the first cell assigns a value `10` to a variable `a`, and the second cell returns it. By convention, the return value of the last line of code cell is displayed after the execution. These are the main keyboard shortcuts for running code cells: * `Ctrl + Shift` run the current cell and advance. * `Ctrl + Enter` run the current cell but don't advance. * `Alt + Enter` runs the current cell and insert a cell below. Please, see the **Run** and **Kernel** menus for all available cell execution options. In addition, while editing any cell: * `Ctrl + Shift + -` splits the code cell in half. And while navigating the cells: * `Shift + m` merges the selected cells. ## Display functions allow you to display result The implicitly available `display` function may be called to display values at any point of the execution: ``` display("The current value of 'a':") a ``` IPython, the core of JupyterLab, includes [helper methods for formatting many kind of values](https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html) for `display` or implicitly displayed return values. For example, the code below displays an SVG image: ``` from IPython.display import SVG SVG(""" <svg width="122" height="30"> <rect width="122" height="30" rx="10" style="fill:green"/> <text x="10" y="20" style="fill:white">Hello World!</text> </svg> """) ``` ## Output is asynchronous All output is displayed asynchronously as it is generated in the Kernel. If you execute the next cell, depending on the Kernel, you may see the output one piece at a time, not all at the end. ``` import time for i in range(8): display(i) time.sleep(0.5) ``` ## Managing the Kernel Code is run in a separate process called the Kernel. The Kernel can be interrupted or restarted. Try running the following cell and then hit the <span class='jp-StopIcon jp-Icon jp-Icon-16 jp-ToolbarButtonComponent-icon'></span> button in the toolbar above to interrupt the kernel. ``` import time time.sleep(30) ``` When the Kernel dies unexpectedly, you will be prompted to restart it. `i , i` is the keyboard shortcut for interrupting the Kernel. ## Restarting the kernels The kernel maintains the state of a notebook's computations. You can reset this state by restarting the kernel. This is done by clicking on the <span class='jp-RefreshIcon jp-Icon jp-Icon-16 jp-ToolbarButtonComponent-icon'></span> in the toolbar above. `0 , 0` is the keyboard shortcut for restarting the Kernel. ## Execution will stop on exception When multiple cell executions are on queue, the execution will stop at the first cell raising an exception. ``` assert False, 'This line always raises AssertionError' print('And this line can only be executed manually.') ```
/robotkernel-1.6a1.tar.gz/robotkernel-1.6a1/docs/notebooks/01 Running Code.ipynb
0.414306
0.96796
01 Running Code.ipynb
pypi
# RobotnikMQ Utilities for safe, efficient, and scalable infrastructure using RabbitMQ ## Usage TODO ## Installation & Setup To install robotnikmq with [`pip`](https://pip.pypa.io/en/stable/) execute the following: ```bash pip install robotnikmq ``` ### Configuration RobotnikMQ can be configured globally, on a per-user, or on a per-application basis. When certain functions of the RobotnikMQ library are called without a provided configuration, it will attempt to find a configuration first for the application in the current working directory `./robotnikmq.yaml`, then for the user in `~/.config/robotnikmq/robotnikmq.yaml` and then for the system in `/etc/robotnikmq/robotnikmq.yaml`. An error will be raised if a configuration is not provided and neither of those files exist. The RobotnikMQ configuration is primarily a list of servers organized into tiers. If a given system or user can be expected to connect to the same cluster the vast majority of the time, then you can/should use a per-user or global configuration. Otherwise, simply have your application configure its own RobotnikMQ configuration (see **Usage** section). The configuration file itself should look something like this: ```yaml tiers: - - ca_cert: /home/eugene/Development/robotnikmq/tests/integration/vagrant/pki/robotnik-ca.crt cert: /home/eugene/Development/robotnikmq/tests/integration/vagrant/pki/issued/rabbitmq-vm/rabbitmq-vm.crt host: 127.0.0.1 key: /home/eugene/Development/robotnikmq/tests/integration/vagrant/pki/issued/rabbitmq-vm/rabbitmq-vm.key password: '' port: 1 user: '' vhost: '' - ca_cert: /home/eugene/Development/robotnikmq/tests/integration/vagrant/pki/robotnik-ca.crt cert: /home/eugene/Development/robotnikmq/tests/integration/vagrant/pki/issued/rabbitmq-vm/rabbitmq-vm.crt host: '1' key: /home/eugene/Development/robotnikmq/tests/integration/vagrant/pki/issued/rabbitmq-vm/rabbitmq-vm.key password: '1' port: 1 user: '1' vhost: '1' - - ca_cert: /home/eugene/Development/robotnikmq/tests/integration/vagrant/pki/robotnik-ca.crt cert: /home/eugene/Development/robotnikmq/tests/integration/vagrant/pki/issued/rabbitmq-vm/rabbitmq-vm.crt host: 127.0.0.1 key: /home/eugene/Development/robotnikmq/tests/integration/vagrant/pki/issued/rabbitmq-vm/rabbitmq-vm.key password: hackme port: 5671 user: robotnik vhost: /robotnik ``` In the example above, you should be able to see two tiers of servers, the first has two server configurations that are intentionally broken for testing purposes, while the second has a valid configuration (this is the configuration that is used for unit-testing). The idea is that RobotnikMQ will first attempt to connect to all servers in the first tier in a random order, then if all of them fail, it will attempt to connect to all the servers in the second tier, and so on. This is intended to allow both load-balancing on different servers and for redundancy in case some of those servers fail. You can also configure only one tier with one server, or just a list of tiers, each of which have one server in them. This way, the secondary and tertiary servers would only be used if there is something wrong with the primary. ## Development ### Standards - Be excellent to each other - Code coverage must be at 100% for all new code, or a good reason must be provided for why a given bit of code is not covered. - Example of an acceptable reason: "There is a bug in the code coverage tool and it says its missing this, but its not". - Example of unacceptable reason: "This is just exception handling, its too annoying to cover it". - The code must pass the following analytics tools. Similar exceptions are allowable as in rule 2. - `pylint --disable=C0103,C0111,W1203,R0903,R0913 --max-line-length=120 ...` - `flake8 --max-line-length=120 ...` - `mypy --ignore-missing-imports --follow-imports=skip --strict-optional ...` - All incoming information from users, clients, and configurations should be validated. - All internal arguments passing should be typechecked during testing with [`typeguard.typechecked`](https://typeguard.readthedocs.io/en/latest/userguide.html#using-the-decorator) or [the import hook](https://typeguard.readthedocs.io/en/latest/userguide.html#using-the-import-hook). ### Development Setup Using [pdm](https://pdm.fming.dev/) install from inside the repo directory: ```bash pdm install ``` This will install all dependencies (including dev requirements) in a [PEP582-compliant project](https://pdm.fming.dev/latest/usage/pep582/) which you can always run specific commands with `pdm run ...`. #### IDE Setup **Sublime Text 3** ```bash curl -sSL https://gitlab.com/-/snippets/2385805/raw/main/pdm.sublime-project.py | pdm run python > robotnikmq.sublime-project ``` **VSCodium/VSCode** I recommend installing the [pdm-vscode](https://github.com/frostming/pdm-vscode) plug-in: ```bash sudo pdm plugin add pdm-vscode ``` ## Testing All testing should be done with `pytest` which is installed with the `dev` requirements. To run all the unit tests, execute the following from the repo directory: ```bash pdm run pytest ``` This should produce a coverage report in `/path/to/dewey-api/htmlcov/` While developing, you can use [`watchexec`](https://github.com/watchexec/watchexec) to monitor the file system for changes and re-run the tests: ```bash watchexec -r -e py,yaml pdm run pytest ``` To run a specific test file: ```bash pdm run pytest tests/unit/test_core.py ``` To run a specific test: ```bash pdm run pytest tests/unit/test_core.py::test_hello ``` For more information on testing, see the `pytest.ini` file as well as the [documentation](https://docs.pytest.org/en/stable/). ### Integration Testing For integration testing, this code uses [testcontainers-rabbitmq](https://testcontainers-python.readthedocs.io/en/latest/rabbitmq/README.html). In order to enable this, you will need to install docker, and ensure that your user has the ability to interact with the docker service: ```bash sudo apt install docker sudo groupadd docker # may fail if the docker group already exists sudo usermod -aG docker $USER newgrp docker docker run hello-world # verify that everything is working well ```
/robotnikmq-0.7.1.tar.gz/robotnikmq-0.7.1/README.md
0.447219
0.929568
README.md
pypi
import collections.abc import copy import typing import pydantic StrSequence = typing.Union[list[str], tuple[str, ...], set[str]] class MetadataChangeset(pydantic.BaseModel): # Add each tag in this sequence if it doesn't exist put_tags: typing.Optional[StrSequence] = None # Remove each tag in this sequence if it exists remove_tags: typing.Optional[StrSequence] = None # Add each field in this dict if it doesn't exist, else overwrite the existing value # Expands dot notation to nested objects put_fields: typing.Optional[dict[str, typing.Any]] = None # Remove each field in this sequence if it exists # Expands dot notation to nested objects remove_fields: typing.Optional[StrSequence] = None def apply_field_updates( self, existing_metadata: dict[str, typing.Any] ) -> dict[str, typing.Any]: updated_metadata = copy.deepcopy(existing_metadata) if self.put_fields: for key, value in self.put_fields.items(): self.__set_nested(updated_metadata, key, value) if self.remove_fields: for key in self.remove_fields: self.__del_nested(updated_metadata, key) return updated_metadata def apply_tag_updates(self, existing_tags: list[str]) -> StrSequence: updated_tags = existing_tags.copy() if self.put_tags: for tag in self.put_tags: if tag not in updated_tags: updated_tags.append(tag) if self.remove_tags: updated_tags = [tag for tag in updated_tags if tag not in self.remove_tags] return updated_tags def combine(self, other: "MetadataChangeset") -> "MetadataChangeset": return self.copy(update=other.dict(exclude_unset=True, exclude_none=True)) def is_empty(self) -> bool: return not any( [ self.put_tags, self.remove_tags, self.put_fields, self.remove_fields, ] ) def __set_nested( self, obj: dict[str, typing.Any], key: str, value: typing.Any ) -> None: """ Set nested path to value using dot notation """ keys = key.split(".") subobj = obj for key in keys[:-1]: if isinstance(subobj, collections.abc.MutableSequence): key = int(key) if key >= len(subobj): raise IndexError(f"Index {key} out of range for {subobj}") subobj = subobj[key] else: subobj = subobj.setdefault(key, {}) if isinstance(subobj, collections.abc.MutableMapping): subobj[keys[-1]] = value elif isinstance(subobj, collections.abc.MutableSequence): subobj.insert(int(keys[-1]), value) def __del_nested(self, obj: dict[str, typing.Any], key: str) -> None: """ Delete a value from nested path using dot notation """ def __key_in_collection( key: typing.Union[str, int], collection: collections.abc.Collection ) -> bool: if isinstance(collection, collections.abc.MutableSequence): key = int(key) return key < len(collection) else: return key in collection def __del_from_collection( key: typing.Union[str, int], collection: collections.abc.Collection ) -> None: if not __key_in_collection(key, collection): return if isinstance(collection, collections.abc.MutableMapping): del collection[key] elif isinstance(collection, collections.abc.MutableSequence): collection.pop(int(key)) keys = key.split(".") path: list[ tuple[ # subobj typing.Union[ collections.abc.MutableMapping, collections.abc.MutableMapping ], # key typing.Optional[typing.Union[str, int]], # parent_obj typing.Optional[ typing.Union[ collections.abc.MutableMapping, collections.abc.MutableMapping ] ], ] ] = [(obj, None, None)] for key in keys[:-1]: sub_obj, _, _ = path[-1] if isinstance(sub_obj, collections.abc.MutableSequence): key = int(key) if not __key_in_collection(key, sub_obj): return path.append((sub_obj[key], key, sub_obj)) __del_from_collection(keys[-1], path[-1][0]) # remove any now empty collections, working backwards for _, key_path, parent_obj in reversed(path): if key_path is None or parent_obj is None: # root object return if isinstance(parent_obj, collections.abc.MutableSequence): key_path = int(key_path) if not __key_in_collection(key_path, parent_obj): return if not len(parent_obj[key_path]): __del_from_collection(key_path, parent_obj) class UpdateCondition(pydantic.BaseModel): """ A condition to be applied to an update operation, succeeding only if the condition evaluates to True at update-time. `value` is compared to the resource's current value of `key` using `comparator`. This is a severely constrainted subset of the conditions supported by DynamoDB. See: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html """ key: str value: typing.Any # Comparators are tied to convenience methods exposed on boto3.dynamodb.conditions.Attr. See: # https://github.com/boto/boto3/blob/5ad1a624111ed25efc81f425113fa51150516bb4/boto3/dynamodb/conditions.py#L246 comparator: typing.Literal["eq", "ne"]
/roboto_sdk-0.1.27.tar.gz/roboto_sdk-0.1.27/src/roboto_sdk/updates.py
0.70253
0.232648
updates.py
pypi
import collections.abc import decimal import enum import json import typing import pydantic from .serde import safe_dict_drill class Comparator(str, enum.Enum): """The comparator to use when comparing a field to a value.""" Equals = "EQUALS" NotEquals = "NOT_EQUALS" GreaterThan = "GREATER_THAN" GreaterThanOrEqual = "GREATER_THAN_OR_EQUAL" LessThan = "LESS_THAN" LessThanOrEqual = "LESS_THAN_OR_EQUAL" Contains = "CONTAINS" NotContains = "NOT_CONTAINS" IsNull = "IS_NULL" IsNotNull = "IS_NOT_NULL" Exists = "EXISTS" NotExists = "NOT_EXISTS" BeginsWith = "BEGINS_WITH" class Condition(pydantic.BaseModel): """A filter for any arbitrary attribute for a Roboto resource.""" field: str comparator: Comparator value: typing.Optional[typing.Union[str, bool, int, float, decimal.Decimal]] = None @pydantic.validator("value") def parse(cls, v): if v is None: return None try: return json.loads(v) except json.decoder.JSONDecodeError: return v def matches(self, target: dict) -> bool: value = safe_dict_drill(target, self.field.split(".")) if self.comparator in [Comparator.NotExists, Comparator.IsNull]: return value is None if self.comparator in [Comparator.Exists, Comparator.IsNotNull]: return value is not None # We need the value for everything else if value is None: return False if isinstance(value, str) and not isinstance(self.value, str): if isinstance(self.value, int): value = int(value) elif isinstance(self.value, float): value = float(value) elif isinstance(self.value, bool): value = value.lower() == "true" elif isinstance(self.value, decimal.Decimal): value = decimal.Decimal.from_float(float(value)) if self.comparator is Comparator.Equals: return value == self.value if self.comparator is Comparator.NotEquals: return value != self.value if self.comparator is Comparator.GreaterThan: return value > self.value if self.comparator is Comparator.GreaterThanOrEqual: return value >= self.value if self.comparator is Comparator.LessThan: return value < self.value if self.comparator is Comparator.LessThanOrEqual: return value <= self.value if self.comparator is Comparator.Contains: return isinstance(value, list) and self.value in value if self.comparator is Comparator.NotContains: return isinstance(value, list) and self.value not in value if self.comparator is Comparator.BeginsWith: if not isinstance(value, str) or not isinstance(self.value, str): return False return value.startswith(self.value) return False class ConditionOperator(str, enum.Enum): """The operator to use when combining multiple conditions.""" And = "AND" Or = "OR" Not = "NOT" class ConditionGroup(pydantic.BaseModel): """A group of conditions that are combined together.""" operator: ConditionOperator conditions: collections.abc.Sequence[typing.Union[Condition, "ConditionGroup"]] def matches(self, target: dict): inner_matches = map(lambda x: x.matches(target), self.conditions) if self.operator is ConditionOperator.And: return all(inner_matches) if self.operator is ConditionOperator.Or: return any(inner_matches) if self.operator is ConditionOperator.Not: return not any(inner_matches) return False ConditionType = typing.Union[Condition, ConditionGroup] class SortDirection(str, enum.Enum): """The direction to sort the results of a query.""" Ascending = "ASC" Descending = "DESC" class QuerySpecification(pydantic.BaseModel): """ Model for specifying a query to the Roboto Platform. Examples: Specify a query with a single condition: >>> from roboto_sdk import query >>> query_spec = query.QuerySpecification( ... condition=query.Condition( ... field="name", ... comparator=query.Comparator.Equals, ... value="Roboto" ... ) ... ) Specify a query with multiple conditions: >>> from roboto_sdk import query >>> query_spec = query.QuerySpecification( ... condition=query.ConditionGroup( ... operator=query.ConditionOperator.And, ... conditions=[ ... query.Condition( ... field="name", ... comparator=query.Comparator.Equals, ... value="Roboto" ... ), ... query.Condition( ... field="age", ... comparator=query.Comparator.GreaterThan, ... value=18 ... ) ... ] ... ) ... ) Arbitrarily nest condition groups: >>> from roboto_sdk import query >>> query_spec = query.QuerySpecification( ... condition=query.ConditionGroup( ... operator=query.ConditionOperator.And, ... conditions=[ ... query.Condition( ... field="name", ... comparator=query.Comparator.Equals, ... value="Roboto" ... ), ... query.ConditionGroup( ... operator=query.ConditionOperator.Or, ... conditions=[ ... query.Condition( ... field="age", ... comparator=query.Comparator.GreaterThan, ... value=18 ... ), ... query.Condition( ... field="age", ... comparator=query.Comparator.LessThan, ... value=30 ... ) ... ] ... ) ... ] ... ) ... ) """ condition: typing.Optional[typing.Union[Condition, ConditionGroup]] = None limit: int = 1000 after: typing.Optional[str] = None # An encoded PaginationToken sort_by: typing.Optional[str] = None sort_direction: typing.Optional[SortDirection] = None class Config: extra = "forbid" @classmethod def protected_from_oldstyle_request( cls, filters: dict, page_token: typing.Optional[str] = None ) -> "QuerySpecification": """ Convert deprecated query format to new format. Not for public use. :meta private: """ conditions: list[typing.Union[Condition, ConditionGroup]] = [] def _iterconditions(field: str, value: typing.Any): if isinstance(value, list): conditions.append( ConditionGroup( operator=ConditionOperator.Or, conditions=[ Condition( field=field, comparator=Comparator.Equals, value=v ) for v in value ], ) ) elif isinstance(value, dict): for k, v in value.items(): _iterconditions(f"{field}.{k}", v) else: conditions.append( Condition(field=field, comparator=Comparator.Equals, value=value) ) for field, value in filters.items(): _iterconditions(field, value) return cls( condition=ConditionGroup( operator=ConditionOperator.And, conditions=conditions ), after=page_token, ) def fields(self) -> set[str]: """Return a set of all fields referenced in the query.""" fields = set() def _iterconditions( condition: typing.Optional[typing.Union[Condition, ConditionGroup]] ): if condition is None: return if isinstance(condition, Condition): fields.add(condition.field) else: for cond in condition.conditions: _iterconditions(cond) _iterconditions(self.condition) return fields
/roboto_sdk-0.1.27.tar.gz/roboto_sdk-0.1.27/src/roboto_sdk/query.py
0.778986
0.230357
query.py
pypi