timor.utilities.dtypes

Attributes

SupportsOrdering

T

Classes

Comparable

A protocol for comparable objects that support < and ==

DictLexicographic

A dictionary-based version of Lexicographic values.

EternalDict

An immutable dictionary that prevents changing any of its items, but allows adding new ones

IKDebug

Holds data for debugging IK optimization runs and helps you analyze them.

IKMeta

Holds data for IK solvers

IntermediateIkResult

Holds data for the current best IK solution

Lazy

An implementation of lazy variables in python

Lexicographic

A class for comparing tuples lexicographically.

LimitedSizeMap

This class behaves like a dictionary with a limited size of elements it can hold.

SingleSet

A set that does not accept duplicates silently.

SingleSetWithID

A class for SingleSets where every element has a unique ID

SingletonMeta

This is a thread-safe implementation of Singleton (a class that can only have one instance exactly).

TorqueInput

Holds data defining robot control parameters

TypedHeader

A dataclass that ensures and transforms {Module, Task, Solution}-header data to the desired datatypes.

Functions

deep_iter_dict(d[, max_depth, _prev])

Iterators over hierarchical dictionaries

float2array(scalar)

Handle sensitive bindings between C++ eigen and numpy.

fuzzy_dict_key_matching(dict_in[, aliases, ...])

Fuzzy dictionary key matching.

hppfcl_collision2pin_geometry(geometry, transform, ...)

Creates a pinocchio geometry object as used for robot bodies from a hppfcl collision object.

possibly_nest_as_list(value[, tuple_ok])

A utility to wrap a value within a list if it is not already.

randomly(col[, rng])

Returns a random iterator over col.

timeout(timeout_s[, logging_callback])

A decorator to time out a function call after a given time.

Module Contents

class timor.utilities.dtypes.Comparable
Inheritance diagram of timor.utilities.dtypes.Comparable

A protocol for comparable objects that support < and ==

Source:

https://stackoverflow.com/questions/68372599/how-to-type-hint-supportsordering-in-a-function-parameter

abstractmethod __eq__(other)

equal to

Parameters:

other (object)

Return type:

bool

abstractmethod __le__(other)

less than or equal to

Parameters:

other (SupportsOrdering)

Return type:

bool

abstractmethod __lt__(other)

less than

Parameters:

other (SupportsOrdering)

Return type:

bool

class timor.utilities.dtypes.DictLexicographic(values)

A dictionary-based version of Lexicographic values.

Initialize the DictLexicographic with a dictionary of values.

The comparison order is not set here but is provided in the comparison methods.

Parameters:

values (Dict[str, Comparable])

equal_to(other, order)

Check if two dictionaries are equal lexicographically based on a specific key order.

Parameters:
Return type:

bool

less_than(other, order)

Compare two dictionaries lexicographically based on a specific key order.

Parameters:
Return type:

bool

ordered(order)

Cast the dictionary to a Lexicographic object based on a specific key order.

Parameters:

order (Collection[str])

Return type:

Lexicographic

values
class timor.utilities.dtypes.EternalDict
Inheritance diagram of timor.utilities.dtypes.EternalDict

An immutable dictionary that prevents changing any of its items, but allows adding new ones

Initialize self. See help(type(self)) for accurate signature.

__delitem__

Delete self[key].

__hash__()

Custom hash function

__setitem__(key, value)

The only way possible to change this dictionary: Add new values

_immutable(*args, **kws)
clear

D.clear() -> None. Remove all items from D.

pop

D.pop(k[,d]) -> v, remove specified key and return the corresponding value.

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

update

D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

class timor.utilities.dtypes.IKDebug

Holds data for debugging IK optimization runs and helps you analyze them.

Needs to be linked to robot ik via callbacks (inner_callback for inner_callback, outer_callback for outer_callback).

_restarts: int = 0
_steps: List[List[numpy.ndarray]] = [[]]
add_step(q)

Add a step to the list of steps; intended as inner_callback of robot’s ik method

Return type:

timor.utilities.callbacks.CallbackReturn

inc_restarts(_)

Increment the number of restarts; intended as outer_callback of robot’s ik method

Return type:

timor.utilities.callbacks.CallbackReturn

property inner_callback: Callable[[numpy.ndarray], timor.utilities.callbacks.CallbackReturn]

Return the inner callback function

Return type:

Callable[[numpy.ndarray], timor.utilities.callbacks.CallbackReturn]

property outer_callback: Callable[[numpy.ndarray], timor.utilities.callbacks.CallbackReturn]

Return the outer callback function

Return type:

Callable[[numpy.ndarray], timor.utilities.callbacks.CallbackReturn]

plot()

Plot the tested IK candidates over steps + velocity + velocity norm.

property restarts

Return the number of restarts

robot: RobotBase
visualize(viz, animate=False)

Visualize the steps taken during the IK optimization.

Parameters:
  • viz (pinocchio.visualize.MeshcatVisualizer) – The visualizer to use

  • animate (bool) – If True, animate the optimization steps

class timor.utilities.dtypes.IKMeta

Holds data for IK solvers

__post_init__()

Maxes sure the data has the desired types and that all attributes have meaningful values.

allow_random_restart: bool = True
dof: int
intermediate_result: IntermediateIkResult | None = None
joint_mask: bool | Sequence[bool] | None = None
max_iter: int
task: Task.Task | None = None
class timor.utilities.dtypes.IntermediateIkResult

Holds data for the current best IK solution

cost: float
q: numpy.ndarray
class timor.utilities.dtypes.Lazy(func)
Inheritance diagram of timor.utilities.dtypes.Lazy

An implementation of lazy variables in python

Initialize an “empty” lazy variable with the function to be evaluated lazily

Parameters:

func (Callable[[], T])

__call__(*args, **kwargs)

Useful s.t. the variable can be evaluated like lazy()

Return type:

T

__getstate__()

Lazy variables will always be evaluated when serialized

Return type:

T

__mul__(other)

Implemented to prevent evaluation of Lazy variables when multiplied with another lazy variable

__rmul__(other)

Implemented to prevent evaluation of Lazy variables when multiplied with another lazy variable

classmethod from_variable(variable)

Useful wrapper to prevent evaluation of Lazy variables when multiplied with another variable

Parameters:

variable (any)

Return type:

Lazy

func: Callable[[], T]
reset()

Reset the value of the lazy variable s.t. it must be re-evaluated next time the value is requested

value = None
value_or_func()

Evaluates the lazy variable. Is triggered by self()

Return type:

T

class timor.utilities.dtypes.Lexicographic(*args)

A class for comparing tuples lexicographically.

Create a new Lexicographic object.

In a lexicographic comparison, the elements are compared one by one, starting from the first. The values of a lexicographic function can themselves be lexicographic values.

Parameters:

args (Comparable)

__add__(other)

Add the elements of two lexicographic objects

__eq__(other)

Return True if self == other, False otherwise.

__le__(other)

Return True if self <= other, False otherwise.

__lt__(other)

Return True if self < other, False otherwise.

__repr__()

Return a string representation of the Lexicographic object.

__str__()

Return a string representation of the Lexicographic object.

__truediv__(other)

Divide each element of a lexicographic object by a scalar. Required to take a mean over lexicographics.

size_exception
values: Tuple[Comparable] = ()
class timor.utilities.dtypes.LimitedSizeMap(*args, maxsize=None, **kwargs)
Inheritance diagram of timor.utilities.dtypes.LimitedSizeMap

This class behaves like a dictionary with a limited size of elements it can hold.

The implementation is based on an ordered dict that, by default, pops elements in lifo order. In contrast to that, the LimitedSizeMap is FIFO: The most recent element is stored on the left and we pop from the right. The size limit has to be given in the number of elements contained. This class exhibits the following behavior: - If the cache is exceeded, the oldest element is removed (FIFO) - If a key is accessed, the according element is moved to the left end (beginning) of the dictionary - If a key is updated, the according element is moved to the left end (beginning) of the dictionary However, note that this is not subclassing OrderedDict, but MutableMapping, as subclassing of builtins that are not constructed for this kind of behavior can lead to unexpected failure.

Ref:

https://stackoverflow.com/questions/2437617/how-to-limit-the-size-of-a-dictionary

Ref:

https://stackoverflow.com/questions/3387691/how-to-perfectly-override-a-dict

Parameters:

maxsize (int)

Initialize a LimitedSizeDict as any other dictionary

__abc_tpflags__ = 64
__class_getitem__
__contains__(key)
__delitem__(key)

Delete an item from the store

__eq__(other)
__getitem__(key)

Make sure accessing keys moves them to the left end of the dictionary

__iter__()

Return an iterator over the store

__len__()

Return the number of elements currently cached

__marker
__maxsize: int = 0
__reversed__ = None
__setitem__(key, value)

Make sure updating keys moves them to the left end of the store

__slots__ = ()
classmethod __subclasshook__(C)
clear()

D.clear() -> None. Remove all items from D.

get(key, default=None)

D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.

items()

D.items() -> a set-like object providing a view on D’s items

keys()

D.keys() -> a set-like object providing a view on D’s keys

pop(key, default=__marker)

D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.

popitem()

D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty.

reset()

Reset the cache

setdefault(key, default=None)

D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

store: collections.OrderedDict
update(other=(), /, **kwds)

D.update([E, ]**F) -> None. Update D from mapping/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values()

D.values() -> an object providing a view on D’s values

class timor.utilities.dtypes.SingleSet(*elements)
Inheritance diagram of timor.utilities.dtypes.SingleSet

A set that does not accept duplicates silently.

Like a set, but instead of silently ignoring duplicates, it throws an error whenever an element that is already in this set is added. Inspired by: https://stackoverflow.com/questions/41281346/how-to-raise-error-if-user-tries-to-enter-duplicate-entries-in-a-set-in-python # noqa: E501 Only for union it is made sure that a SingleSet is returned. Diff, intersection, … methods will return basic sets!

Custom init function.

Might be slow, but provides safety that every element in the input argument is checked using the tested update and add methods. For sophisticated element checking, consider overriding the __contains__ method in sub-classes.

Parameters:

elements (Iterable)

__eq__(other)

If there is a unique ordering to this set, try to sort the elements and compare them

__hash__()

Hash all the contained elements

__ne__(other)

Override the not equal operatorof a set

_err = 'Element {} already present!'
classmethod _sorting_key(element)
Abstractmethod:

Parameters:

element (any)

Return type:

any

Key function for sorting elements in this set

add(element)

Custom add to set needed s.t. uniqueness is ensured

Return type:

None

copy()

Custom copy should also return a SingleSet

Return type:

SingleSet

filter(func)

Convenience function to avoid set comparison over and over again

Parameters:

func (Callable[[any], bool]) – A filter function that takes an element of this set and evaluates to true if the element should be kept

Returns:

A new set of elements fulfilling the filter criterion

Return type:

SingleSet

intersection(*s)

Intersection should also retutrn a SingleSet

Parameters:

s (Iterable)

Return type:

SingleSet

union(*s)

Returns a SingleSet of the union of this and the input

Parameters:

s (Iterable)

Return type:

SingleSet

update(*s)

Update method that does not change this instance if the input iterable contains duplicates

Parameters:

s (Iterable)

Return type:

None

class timor.utilities.dtypes.SingleSetWithID(*elements)
Inheritance diagram of timor.utilities.dtypes.SingleSetWithID

A class for SingleSets where every element has a unique ID

Custom init function.

Might be slow, but provides safety that every element in the input argument is checked using the tested update and add methods. For sophisticated element checking, consider overriding the __contains__ method in sub-classes.

Parameters:

elements (Iterable)

__contains__(item)

Custom duplicate check (unique ID)

Parameters:

item (any)

__eq__(other)

If there is a unique ordering to this set, try to sort the elements and compare them

__hash__()

Hash all the contained elements

__ne__(other)

Override the not equal operatorof a set

_err = 'Element {} already present!'
classmethod _sorting_key(element)

Key function for sorting elements in this set

Parameters:

element (any)

Return type:

any

add(element)

Custom add to set needed s.t. uniqueness is ensured

Return type:

None

copy()

Custom copy should also return a SingleSet

Return type:

SingleSet

filter(func)

Convenience function to avoid set comparison over and over again

Parameters:

func (Callable[[any], bool]) – A filter function that takes an element of this set and evaluates to true if the element should be kept

Returns:

A new set of elements fulfilling the filter criterion

Return type:

SingleSet

intersection(*s)

Intersection should also retutrn a SingleSet

Parameters:

s (Iterable)

Return type:

SingleSet

union(*s)

Returns a SingleSet of the union of this and the input

Parameters:

s (Iterable)

Return type:

SingleSet

update(*s)

Update method that does not change this instance if the input iterable contains duplicates

Parameters:

s (Iterable)

Return type:

None

class timor.utilities.dtypes.SingletonMeta
Inheritance diagram of timor.utilities.dtypes.SingletonMeta

This is a thread-safe implementation of Singleton (a class that can only have one instance exactly).

Code taken from https://refactoring.guru/design-patterns/singleton/python/example#example-1.

__call__(*args, **kwargs)

Possible changes to the value of the __init__ argument do not affect the returned instance.

_instances
_lock: threading.Lock
timor.utilities.dtypes.SupportsOrdering
timor.utilities.dtypes.T
class timor.utilities.dtypes.TorqueInput

Holds data defining robot control parameters

__post_init__()

Sanity checks after dataclass values are written

goals: Dict[str, float]
t: numpy.ndarray | float
torque: numpy.ndarray
class timor.utilities.dtypes.TypedHeader

A dataclass that ensures and transforms {Module, Task, Solution}-header data to the desired datatypes.

__delattr__(item)

Delete attribute

__post_init__()

Post init function that ensures the correct datatypes

__setattr__(key, value)

Sets an attribute of this class

_raise_immutable(f)

Raises error if objects in this dataclass are to be resetted but the instance is set to immutable

Parameters:

f (Callable)

Return type:

Callable

asdict()

Returns a dictionary representation of this object

Return type:

Dict[str, Any]

static cast(value, cast_to_type)

Casts the value to the dtype

Parameters:
  • value (Any)

  • cast_to_type (Type)

Return type:

Any

static cast_to_date(value)

Casts the value to a datetime.date object

Parameters:

value (Union[str, datetime.date, datetime.datetime])

Return type:

datetime.date

classmethod fields()

Returns the fields of this class

Return type:

Tuple[str, Ellipsis]

static string_list_factory()

Returns a field with a default factory that returns a list with one empty string

Return type:

dataclasses.field

timor.utilities.dtypes.deep_iter_dict(d, max_depth=10, _prev=None)

Iterators over hierarchical dictionaries

Parameters:
  • d (Dict[any, any]) – Any dictionary

  • max_depth – The max recursion depth to dive into the dictionary

  • _prev – Previously seen keys. Usually would not be set by the user.

Returns:

Yields a generator that returns a tuple of:

  • The keys leading to this values in a list like: [key_lvl_1, key_lvl_2, …, key_lvl_n]

  • The value if it is not yet another dictionary

Return type:

Generator[Tuple[List[any], any], None, None]

timor.utilities.dtypes.float2array(scalar)

Handle sensitive bindings between C++ eigen and numpy.

Methods like model.addJoint only accept np ndarrays of shape (1,) for inputs that originally are eigen matrices in C++.

Parameters:

scalar (float) – Could be any scalar really

Returns:

A np array of shape (1,) containing this scalar (as float)

Return type:

numpy.ndarray

timor.utilities.dtypes.fuzzy_dict_key_matching(dict_in, aliases=None, desired_only=None, ignore_casing=True)

Fuzzy dictionary key matching.

This method provides a helper utility to find keys in an input dictionary that are not exactly right, but are an alias for an expected key or differ only by casing.

Parameters:
  • dict_in (Dict[str, any]) – An input dictionary that shall be “fuzzy-matched”. The keys must be strings.

  • aliases (Dict[str, str]) – A mapping from “valid alias key in dict_in” -> “valid real key”

  • desired_only (Tuple) – If given, the returned dictionary will only contain this subset of keys. Useful for discarding aliases after matching

  • ignore_casing (bool) – If true, keys will be matched case-insensitive to aliases AND TO KEYS FROM DESIRED ONLY

Returns:

The resulting dictionary containing all or only the desired mappings, taking aliases into account

Return type:

Dict[str, any]

timor.utilities.dtypes.hppfcl_collision2pin_geometry(geometry, transform, name, parent_joint, parent_frame=None)

Creates a pinocchio geometry object as used for robot bodies from a hppfcl collision object.

Parameters:
  • geometry (hppfcl.hppfcl.CollisionGeometry)

  • transform (timor.utilities.transformation.TransformationLike)

  • name (str)

  • parent_joint (int)

  • parent_frame (int)

Return type:

pinocchio.GeometryObject

timor.utilities.dtypes.possibly_nest_as_list(value, tuple_ok=True)

A utility to wrap a value within a list if it is not already.

Useful for loading jsons where arrays sometimes get unpacked if they contain only one element - which silently causes errors later in the pipeline.

Parameters:
  • value (any) – Basically any python variable

  • tuple_ok (bool) – If true, tuples will not be packed as a list as their behavior in python is very similar.

Returns:

[value] if value was not a list (or possibly a tuple) before, else value

timor.utilities.dtypes.randomly(col, rng=None)

Returns a random iterator over col.

Source:

https://stackoverflow.com/questions/9252373/random-iteration-in-python

Parameters:
  • col (Collection) – A collection to iterate over

  • rng (Optional[numpy.random.Generator]) – A random number generator to use. If None, the python builtin random module is used.

Return type:

Iterable

timor.utilities.dtypes.timeout(timeout_s, logging_callback=logging.warning)

A decorator to time out a function call after a given time.

Note that this will only work on UNIX systems. :param timeout_s: The time after which the function call shall be aborted (in seconds) :param logging_callback: A logging function that takes a string as input - defaults to a warning, but can be changed to another level of None.

Parameters:
  • timeout_s (int)

  • logging_callback (Optional[Callable[[Exception], None]])