Source code for klampt.robotsim

# This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.

"""
Klamp't Core Python bindings 
------------------------------
"""

from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
    raise RuntimeError("Python 2.7 or later required")

# Import the low-level C/C++ module
if __package__ or "." in __name__:
    from . import _robotsim
else:
    import _robotsim

try:
    import builtins as __builtin__
except ImportError:
    import __builtin__

from typing import Sequence,Tuple,Iterator
from klampt.model.typing import IntArray,Config,Vector,Vector3,Matrix3,Point,Rotation,RigidTransform


def _swig_repr(self):
    try:
        strthis = "proxy of " + self.this.__repr__()
    except __builtin__.Exception:
        strthis = ""
    return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)


def _swig_setattr_nondynamic_instance_variable(set):
    def set_instance_attr(self, name, value):
        if name == "thisown":
            self.this.own(value)
        elif name == "this":
            set(self, name, value)
        elif hasattr(self, name) and isinstance(getattr(type(self), name), property):
            set(self, name, value)
        else:
            raise AttributeError("You cannot add instance attributes to %s" % self)
    return set_instance_attr


def _swig_setattr_nondynamic_class_variable(set):
    def set_class_attr(cls, name, value):
        if hasattr(cls, name) and not isinstance(getattr(cls, name), property):
            set(cls, name, value)
        else:
            raise AttributeError("You cannot add class attributes to %s" % cls)
    return set_class_attr


def _swig_add_metaclass(metaclass):
    """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass"""
    def wrapper(cls):
        return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())
    return wrapper


class _SwigNonDynamicMeta(type):
    """Meta class to enforce nondynamic attributes (no new attributes) for a class"""
    __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__)


class SwigPyIterator(object):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def __init__(self, *args, **kwargs):
        raise AttributeError("No constructor defined - class is abstract")
    __repr__ = _swig_repr
    __swig_destroy__ = _robotsim.delete_SwigPyIterator

    def value(self) ->object:
        return _robotsim.SwigPyIterator_value(self)

    def incr(self, n: int=1) ->Iterator:
        return _robotsim.SwigPyIterator_incr(self, n)

    def decr(self, n: int=1) ->Iterator:
        return _robotsim.SwigPyIterator_decr(self, n)

    def distance(self, x: Iterator) ->int:
        return _robotsim.SwigPyIterator_distance(self, x)

    def equal(self, x: Iterator) ->bool:
        return _robotsim.SwigPyIterator_equal(self, x)

    def copy(self) ->Iterator:
        return _robotsim.SwigPyIterator_copy(self)

    def next(self) ->object:
        return _robotsim.SwigPyIterator_next(self)

    def __next__(self) ->object:
        return _robotsim.SwigPyIterator___next__(self)

    def previous(self) ->object:
        return _robotsim.SwigPyIterator_previous(self)

    def advance(self, n: int) ->Iterator:
        return _robotsim.SwigPyIterator_advance(self, n)

    def __eq__(self, x: Iterator) ->bool:
        return _robotsim.SwigPyIterator___eq__(self, x)

    def __ne__(self, x: Iterator) ->bool:
        return _robotsim.SwigPyIterator___ne__(self, x)

    def __iadd__(self, n: int) ->Iterator:
        return _robotsim.SwigPyIterator___iadd__(self, n)

    def __isub__(self, n: int) ->Iterator:
        return _robotsim.SwigPyIterator___isub__(self, n)

    def __add__(self, n: int) ->Iterator:
        return _robotsim.SwigPyIterator___add__(self, n)

    def __sub__(self, *args) ->int:
        return _robotsim.SwigPyIterator___sub__(self, *args)
    def __iter__(self):
        return self

# Register SwigPyIterator in _robotsim:
_robotsim.SwigPyIterator_swigregister(SwigPyIterator)

class doubleArray(object):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr

    def __init__(self, nelements: int):
        _robotsim.doubleArray_swiginit(self, _robotsim.new_doubleArray(nelements))
    __swig_destroy__ = _robotsim.delete_doubleArray

    def __getitem__(self, index: int) ->float:
        return _robotsim.doubleArray___getitem__(self, index)

    def __setitem__(self, index: int, value: float) ->None:
        return _robotsim.doubleArray___setitem__(self, index, value)

    def cast(self) ->Vector:
        return _robotsim.doubleArray_cast(self)

    @staticmethod
    def frompointer(t: Vector) ->"doubleArray":
        return _robotsim.doubleArray_frompointer(t)

# Register doubleArray in _robotsim:
_robotsim.doubleArray_swigregister(doubleArray)

def doubleArray_frompointer(t: Vector) ->"doubleArray":
    return _robotsim.doubleArray_frompointer(t)

class floatArray(object):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr

    def __init__(self, nelements: int):
        _robotsim.floatArray_swiginit(self, _robotsim.new_floatArray(nelements))
    __swig_destroy__ = _robotsim.delete_floatArray

    def __getitem__(self, index: int) ->float:
        return _robotsim.floatArray___getitem__(self, index)

    def __setitem__(self, index: int, value: float) ->None:
        return _robotsim.floatArray___setitem__(self, index, value)

    def cast(self) ->Vector:
        return _robotsim.floatArray_cast(self)

    @staticmethod
    def frompointer(t: Vector) ->"floatArray":
        return _robotsim.floatArray_frompointer(t)

# Register floatArray in _robotsim:
_robotsim.floatArray_swigregister(floatArray)

def floatArray_frompointer(t: Vector) ->"floatArray":
    return _robotsim.floatArray_frompointer(t)

class intArray(object):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr

    def __init__(self, nelements: int):
        _robotsim.intArray_swiginit(self, _robotsim.new_intArray(nelements))
    __swig_destroy__ = _robotsim.delete_intArray

    def __getitem__(self, index: int) ->int:
        return _robotsim.intArray___getitem__(self, index)

    def __setitem__(self, index: int, value: int) ->None:
        return _robotsim.intArray___setitem__(self, index, value)

    def cast(self) ->IntArray:
        return _robotsim.intArray_cast(self)

    @staticmethod
    def frompointer(t: IntArray) ->"intArray":
        return _robotsim.intArray_frompointer(t)

# Register intArray in _robotsim:
_robotsim.intArray_swigregister(intArray)

def intArray_frompointer(t: IntArray) ->"intArray":
    return _robotsim.intArray_frompointer(t)

class stringVector(object):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr

    def iterator(self) ->Iterator:
        return _robotsim.stringVector_iterator(self)
    def __iter__(self):
        return self.iterator()

    def __nonzero__(self) ->bool:
        return _robotsim.stringVector___nonzero__(self)

    def __bool__(self) ->bool:
        return _robotsim.stringVector___bool__(self)

    def __len__(self) ->int:
        return _robotsim.stringVector___len__(self)

    def __getslice__(self, i: int, j: int) ->"stringVector":
        return _robotsim.stringVector___getslice__(self, i, j)

    def __setslice__(self, *args) ->None:
        return _robotsim.stringVector___setslice__(self, *args)

    def __delslice__(self, i: int, j: int) ->None:
        return _robotsim.stringVector___delslice__(self, i, j)

    def __delitem__(self, *args) ->None:
        return _robotsim.stringVector___delitem__(self, *args)

    def __getitem__(self, *args) ->str:
        return _robotsim.stringVector___getitem__(self, *args)

    def __setitem__(self, *args) ->None:
        return _robotsim.stringVector___setitem__(self, *args)

    def pop(self) ->str:
        return _robotsim.stringVector_pop(self)

    def append(self, x: str) ->None:
        return _robotsim.stringVector_append(self, x)

    def empty(self) ->bool:
        return _robotsim.stringVector_empty(self)

    def size(self) ->int:
        return _robotsim.stringVector_size(self)

    def swap(self, v:  "stringVector") ->None:
        return _robotsim.stringVector_swap(self, v)

    def begin(self) ->Iterator:
        return _robotsim.stringVector_begin(self)

    def end(self) ->Iterator:
        return _robotsim.stringVector_end(self)

    def rbegin(self) ->Iterator:
        return _robotsim.stringVector_rbegin(self)

    def rend(self) ->Iterator:
        return _robotsim.stringVector_rend(self)

    def clear(self) ->None:
        return _robotsim.stringVector_clear(self)

    def get_allocator(self) :
        return _robotsim.stringVector_get_allocator(self)

    def pop_back(self) ->None:
        return _robotsim.stringVector_pop_back(self)

    def erase(self, *args) ->Iterator:
        return _robotsim.stringVector_erase(self, *args)

    def __init__(self, *args):
        _robotsim.stringVector_swiginit(self, _robotsim.new_stringVector(*args))

    def push_back(self, x: str) ->None:
        return _robotsim.stringVector_push_back(self, x)

    def front(self) ->str:
        return _robotsim.stringVector_front(self)

    def back(self) ->str:
        return _robotsim.stringVector_back(self)

    def assign(self, n: int, x: str) ->None:
        return _robotsim.stringVector_assign(self, n, x)

    def resize(self, *args) ->None:
        return _robotsim.stringVector_resize(self, *args)

    def insert(self, *args) ->None:
        return _robotsim.stringVector_insert(self, *args)

    def reserve(self, n: int) ->None:
        return _robotsim.stringVector_reserve(self, n)

    def capacity(self) ->int:
        return _robotsim.stringVector_capacity(self)
    __swig_destroy__ = _robotsim.delete_stringVector

# Register stringVector in _robotsim:
_robotsim.stringVector_swigregister(stringVector)

class doubleVector(object):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr

    def iterator(self) ->Iterator:
        return _robotsim.doubleVector_iterator(self)
    def __iter__(self):
        return self.iterator()

    def __nonzero__(self) ->bool:
        return _robotsim.doubleVector___nonzero__(self)

    def __bool__(self) ->bool:
        return _robotsim.doubleVector___bool__(self)

    def __len__(self) ->int:
        return _robotsim.doubleVector___len__(self)

    def __getslice__(self, i: int, j: int) ->"doubleVector":
        return _robotsim.doubleVector___getslice__(self, i, j)

    def __setslice__(self, *args) ->None:
        return _robotsim.doubleVector___setslice__(self, *args)

    def __delslice__(self, i: int, j: int) ->None:
        return _robotsim.doubleVector___delslice__(self, i, j)

    def __delitem__(self, *args) ->None:
        return _robotsim.doubleVector___delitem__(self, *args)

    def __getitem__(self, *args) ->float:
        return _robotsim.doubleVector___getitem__(self, *args)

    def __setitem__(self, *args) ->None:
        return _robotsim.doubleVector___setitem__(self, *args)

    def pop(self) ->float:
        return _robotsim.doubleVector_pop(self)

    def append(self, x: float) ->None:
        return _robotsim.doubleVector_append(self, x)

    def empty(self) ->bool:
        return _robotsim.doubleVector_empty(self)

    def size(self) ->int:
        return _robotsim.doubleVector_size(self)

    def swap(self, v: Vector) ->None:
        return _robotsim.doubleVector_swap(self, v)

    def begin(self) ->Iterator:
        return _robotsim.doubleVector_begin(self)

    def end(self) ->Iterator:
        return _robotsim.doubleVector_end(self)

    def rbegin(self) ->Iterator:
        return _robotsim.doubleVector_rbegin(self)

    def rend(self) ->Iterator:
        return _robotsim.doubleVector_rend(self)

    def clear(self) ->None:
        return _robotsim.doubleVector_clear(self)

    def get_allocator(self) :
        return _robotsim.doubleVector_get_allocator(self)

    def pop_back(self) ->None:
        return _robotsim.doubleVector_pop_back(self)

    def erase(self, *args) ->Iterator:
        return _robotsim.doubleVector_erase(self, *args)

    def __init__(self, *args):
        _robotsim.doubleVector_swiginit(self, _robotsim.new_doubleVector(*args))

    def push_back(self, x: float) ->None:
        return _robotsim.doubleVector_push_back(self, x)

    def front(self) ->float:
        return _robotsim.doubleVector_front(self)

    def back(self) ->float:
        return _robotsim.doubleVector_back(self)

    def assign(self, n: int, x: float) ->None:
        return _robotsim.doubleVector_assign(self, n, x)

    def resize(self, *args) ->None:
        return _robotsim.doubleVector_resize(self, *args)

    def insert(self, *args) ->None:
        return _robotsim.doubleVector_insert(self, *args)

    def reserve(self, n: int) ->None:
        return _robotsim.doubleVector_reserve(self, n)

    def capacity(self) ->int:
        return _robotsim.doubleVector_capacity(self)
    __swig_destroy__ = _robotsim.delete_doubleVector

# Register doubleVector in _robotsim:
_robotsim.doubleVector_swigregister(doubleVector)

class floatVector(object):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr

    def iterator(self) ->Iterator:
        return _robotsim.floatVector_iterator(self)
    def __iter__(self):
        return self.iterator()

    def __nonzero__(self) ->bool:
        return _robotsim.floatVector___nonzero__(self)

    def __bool__(self) ->bool:
        return _robotsim.floatVector___bool__(self)

    def __len__(self) ->int:
        return _robotsim.floatVector___len__(self)

    def __getslice__(self, i: int, j: int) ->"floatVector":
        return _robotsim.floatVector___getslice__(self, i, j)

    def __setslice__(self, *args) ->None:
        return _robotsim.floatVector___setslice__(self, *args)

    def __delslice__(self, i: int, j: int) ->None:
        return _robotsim.floatVector___delslice__(self, i, j)

    def __delitem__(self, *args) ->None:
        return _robotsim.floatVector___delitem__(self, *args)

    def __getitem__(self, *args) ->float:
        return _robotsim.floatVector___getitem__(self, *args)

    def __setitem__(self, *args) ->None:
        return _robotsim.floatVector___setitem__(self, *args)

    def pop(self) ->float:
        return _robotsim.floatVector_pop(self)

    def append(self, x: float) ->None:
        return _robotsim.floatVector_append(self, x)

    def empty(self) ->bool:
        return _robotsim.floatVector_empty(self)

    def size(self) ->int:
        return _robotsim.floatVector_size(self)

    def swap(self, v: Vector) ->None:
        return _robotsim.floatVector_swap(self, v)

    def begin(self) ->Iterator:
        return _robotsim.floatVector_begin(self)

    def end(self) ->Iterator:
        return _robotsim.floatVector_end(self)

    def rbegin(self) ->Iterator:
        return _robotsim.floatVector_rbegin(self)

    def rend(self) ->Iterator:
        return _robotsim.floatVector_rend(self)

    def clear(self) ->None:
        return _robotsim.floatVector_clear(self)

    def get_allocator(self) :
        return _robotsim.floatVector_get_allocator(self)

    def pop_back(self) ->None:
        return _robotsim.floatVector_pop_back(self)

    def erase(self, *args) ->Iterator:
        return _robotsim.floatVector_erase(self, *args)

    def __init__(self, *args):
        _robotsim.floatVector_swiginit(self, _robotsim.new_floatVector(*args))

    def push_back(self, x: float) ->None:
        return _robotsim.floatVector_push_back(self, x)

    def front(self) ->float:
        return _robotsim.floatVector_front(self)

    def back(self) ->float:
        return _robotsim.floatVector_back(self)

    def assign(self, n: int, x: float) ->None:
        return _robotsim.floatVector_assign(self, n, x)

    def resize(self, *args) ->None:
        return _robotsim.floatVector_resize(self, *args)

    def insert(self, *args) ->None:
        return _robotsim.floatVector_insert(self, *args)

    def reserve(self, n: int) ->None:
        return _robotsim.floatVector_reserve(self, n)

    def capacity(self) ->int:
        return _robotsim.floatVector_capacity(self)
    __swig_destroy__ = _robotsim.delete_floatVector

# Register floatVector in _robotsim:
_robotsim.floatVector_swigregister(floatVector)

class intVector(object):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr

    def iterator(self) ->Iterator:
        return _robotsim.intVector_iterator(self)
    def __iter__(self):
        return self.iterator()

    def __nonzero__(self) ->bool:
        return _robotsim.intVector___nonzero__(self)

    def __bool__(self) ->bool:
        return _robotsim.intVector___bool__(self)

    def __len__(self) ->int:
        return _robotsim.intVector___len__(self)

    def __getslice__(self, i: int, j: int) ->"intVector":
        return _robotsim.intVector___getslice__(self, i, j)

    def __setslice__(self, *args) ->None:
        return _robotsim.intVector___setslice__(self, *args)

    def __delslice__(self, i: int, j: int) ->None:
        return _robotsim.intVector___delslice__(self, i, j)

    def __delitem__(self, *args) ->None:
        return _robotsim.intVector___delitem__(self, *args)

    def __getitem__(self, *args) ->int:
        return _robotsim.intVector___getitem__(self, *args)

    def __setitem__(self, *args) ->None:
        return _robotsim.intVector___setitem__(self, *args)

    def pop(self) ->int:
        return _robotsim.intVector_pop(self)

    def append(self, x: int) ->None:
        return _robotsim.intVector_append(self, x)

    def empty(self) ->bool:
        return _robotsim.intVector_empty(self)

    def size(self) ->int:
        return _robotsim.intVector_size(self)

    def swap(self, v: IntArray) ->None:
        return _robotsim.intVector_swap(self, v)

    def begin(self) ->Iterator:
        return _robotsim.intVector_begin(self)

    def end(self) ->Iterator:
        return _robotsim.intVector_end(self)

    def rbegin(self) ->Iterator:
        return _robotsim.intVector_rbegin(self)

    def rend(self) ->Iterator:
        return _robotsim.intVector_rend(self)

    def clear(self) ->None:
        return _robotsim.intVector_clear(self)

    def get_allocator(self) :
        return _robotsim.intVector_get_allocator(self)

    def pop_back(self) ->None:
        return _robotsim.intVector_pop_back(self)

    def erase(self, *args) ->Iterator:
        return _robotsim.intVector_erase(self, *args)

    def __init__(self, *args):
        _robotsim.intVector_swiginit(self, _robotsim.new_intVector(*args))

    def push_back(self, x: int) ->None:
        return _robotsim.intVector_push_back(self, x)

    def front(self) ->int:
        return _robotsim.intVector_front(self)

    def back(self) ->int:
        return _robotsim.intVector_back(self)

    def assign(self, n: int, x: int) ->None:
        return _robotsim.intVector_assign(self, n, x)

    def resize(self, *args) ->None:
        return _robotsim.intVector_resize(self, *args)

    def insert(self, *args) ->None:
        return _robotsim.intVector_insert(self, *args)

    def reserve(self, n: int) ->None:
        return _robotsim.intVector_reserve(self, n)

    def capacity(self) ->int:
        return _robotsim.intVector_capacity(self)
    __swig_destroy__ = _robotsim.delete_intVector

# Register intVector in _robotsim:
_robotsim.intVector_swigregister(intVector)

class doubleMatrix(object):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr

    def iterator(self) ->Iterator:
        return _robotsim.doubleMatrix_iterator(self)
    def __iter__(self):
        return self.iterator()

    def __nonzero__(self) ->bool:
        return _robotsim.doubleMatrix___nonzero__(self)

    def __bool__(self) ->bool:
        return _robotsim.doubleMatrix___bool__(self)

    def __len__(self) ->int:
        return _robotsim.doubleMatrix___len__(self)

    def __getslice__(self, i: int, j: int) ->"doubleMatrix":
        return _robotsim.doubleMatrix___getslice__(self, i, j)

    def __setslice__(self, *args) ->None:
        return _robotsim.doubleMatrix___setslice__(self, *args)

    def __delslice__(self, i: int, j: int) ->None:
        return _robotsim.doubleMatrix___delslice__(self, i, j)

    def __delitem__(self, *args) ->None:
        return _robotsim.doubleMatrix___delitem__(self, *args)

    def __getitem__(self, *args) ->Vector:
        return _robotsim.doubleMatrix___getitem__(self, *args)

    def __setitem__(self, *args) ->None:
        return _robotsim.doubleMatrix___setitem__(self, *args)

    def pop(self) ->Vector:
        return _robotsim.doubleMatrix_pop(self)

    def append(self, x: Vector) ->None:
        return _robotsim.doubleMatrix_append(self, x)

    def empty(self) ->bool:
        return _robotsim.doubleMatrix_empty(self)

    def size(self) ->int:
        return _robotsim.doubleMatrix_size(self)

    def swap(self, v: Sequence[Sequence[float]]) ->None:
        return _robotsim.doubleMatrix_swap(self, v)

    def begin(self) ->Iterator:
        return _robotsim.doubleMatrix_begin(self)

    def end(self) ->Iterator:
        return _robotsim.doubleMatrix_end(self)

    def rbegin(self) ->Iterator:
        return _robotsim.doubleMatrix_rbegin(self)

    def rend(self) ->Iterator:
        return _robotsim.doubleMatrix_rend(self)

    def clear(self) ->None:
        return _robotsim.doubleMatrix_clear(self)

    def get_allocator(self) :
        return _robotsim.doubleMatrix_get_allocator(self)

    def pop_back(self) ->None:
        return _robotsim.doubleMatrix_pop_back(self)

    def erase(self, *args) ->Iterator:
        return _robotsim.doubleMatrix_erase(self, *args)

    def __init__(self, *args):
        _robotsim.doubleMatrix_swiginit(self, _robotsim.new_doubleMatrix(*args))

    def push_back(self, x: Vector) ->None:
        return _robotsim.doubleMatrix_push_back(self, x)

    def front(self) ->Vector:
        return _robotsim.doubleMatrix_front(self)

    def back(self) ->Vector:
        return _robotsim.doubleMatrix_back(self)

    def assign(self, n: int, x: Vector) ->None:
        return _robotsim.doubleMatrix_assign(self, n, x)

    def resize(self, *args) ->None:
        return _robotsim.doubleMatrix_resize(self, *args)

    def insert(self, *args) ->None:
        return _robotsim.doubleMatrix_insert(self, *args)

    def reserve(self, n: int) ->None:
        return _robotsim.doubleMatrix_reserve(self, n)

    def capacity(self) ->int:
        return _robotsim.doubleMatrix_capacity(self)
    __swig_destroy__ = _robotsim.delete_doubleMatrix

# Register doubleMatrix in _robotsim:
_robotsim.doubleMatrix_swigregister(doubleMatrix)

class stringMap(object):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr

    def iterator(self) ->Iterator:
        return _robotsim.stringMap_iterator(self)
    def __iter__(self):
        return self.iterator()

    def __nonzero__(self) ->bool:
        return _robotsim.stringMap___nonzero__(self)

    def __bool__(self) ->bool:
        return _robotsim.stringMap___bool__(self)

    def __len__(self) ->int:
        return _robotsim.stringMap___len__(self)
    def __iter__(self):
        return self.key_iterator()
    def iterkeys(self):
        return self.key_iterator()
    def itervalues(self):
        return self.value_iterator()
    def iteritems(self):
        return self.iterator()

    def __getitem__(self, key: str) ->str:
        return _robotsim.stringMap___getitem__(self, key)

    def __delitem__(self, key: str) ->None:
        return _robotsim.stringMap___delitem__(self, key)

    def has_key(self, key: str) ->bool:
        return _robotsim.stringMap_has_key(self, key)

    def keys(self) ->object:
        return _robotsim.stringMap_keys(self)

    def values(self) ->object:
        return _robotsim.stringMap_values(self)

    def items(self) ->object:
        return _robotsim.stringMap_items(self)

    def __contains__(self, key: str) ->bool:
        return _robotsim.stringMap___contains__(self, key)

    def key_iterator(self) ->Iterator:
        return _robotsim.stringMap_key_iterator(self)

    def value_iterator(self) ->Iterator:
        return _robotsim.stringMap_value_iterator(self)

    def __setitem__(self, *args) ->None:
        return _robotsim.stringMap___setitem__(self, *args)

    def asdict(self) ->object:
        return _robotsim.stringMap_asdict(self)

    def __init__(self, *args):
        _robotsim.stringMap_swiginit(self, _robotsim.new_stringMap(*args))

    def empty(self) ->bool:
        return _robotsim.stringMap_empty(self)

    def size(self) ->int:
        return _robotsim.stringMap_size(self)

    def swap(self, v:  "stringMap") ->None:
        return _robotsim.stringMap_swap(self, v)

    def begin(self) ->Iterator:
        return _robotsim.stringMap_begin(self)

    def end(self) ->Iterator:
        return _robotsim.stringMap_end(self)

    def rbegin(self) ->Iterator:
        return _robotsim.stringMap_rbegin(self)

    def rend(self) ->Iterator:
        return _robotsim.stringMap_rend(self)

    def clear(self) ->None:
        return _robotsim.stringMap_clear(self)

    def get_allocator(self) :
        return _robotsim.stringMap_get_allocator(self)

    def count(self, x: str) ->int:
        return _robotsim.stringMap_count(self, x)

    def erase(self, *args) ->None:
        return _robotsim.stringMap_erase(self, *args)

    def find(self, x: str) ->Iterator:
        return _robotsim.stringMap_find(self, x)

    def lower_bound(self, x: str) ->Iterator:
        return _robotsim.stringMap_lower_bound(self, x)

    def upper_bound(self, x: str) ->Iterator:
        return _robotsim.stringMap_upper_bound(self, x)
    __swig_destroy__ = _robotsim.delete_stringMap

# Register stringMap in _robotsim:
_robotsim.stringMap_swigregister(stringMap)

[docs]class TriangleMesh(object): r""" A 3D indexed triangle mesh class. Attributes: vertices (SWIG vector of floats): a list of vertices, given as a flattened coordinate list [x1, y1, z1, x2, y2, ...] indices (SWIG vector of ints): a list of triangle vertices given as indices into the vertices list, i.e., [a1,b1,c2, a2,b2,c2, ...] Note: because the bindings are generated by SWIG, you can access the indices / vertices members via some automatically generated accessors / modifiers. In particular len(), append(), and indexing via [] are useful. Some other methods like resize() are also provided. However, you CANNOT set these items via assignment. Examples:: m = TriangleMesh() m.vertices.append(0) m.vertices.append(0) m.vertices.append(0) print(len(m.vertices)) #prints 3 m.vertices = [0,0,0] #this is an error m.vertices += [1,2,3] #this is also an error To get all vertices as a numpy array:: verts = m.getVertices() To get all indices as a numpy array:: inds = m.getIndices() C++ includes: geometry.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.TriangleMesh_swiginit(self, _robotsim.new_TriangleMesh())
[docs] def getVertices(self) ->None: r""" Retrieves an array view of the vertices. Returns: ndarray: an nx3 Numpy array. Setting elements of this array will change the vertices. """ return _robotsim.TriangleMesh_getVertices(self)
[docs] def setVertices(self, np_array2: Vector) ->None: r""" Sets all vertices to the given nx3 Numpy array. Args: np_array2 (:obj:`2D Numpy array of floats`) """ return _robotsim.TriangleMesh_setVertices(self, np_array2)
[docs] def getIndices(self) ->None: r""" Retrieves an array view of the triangle indices. Returns: ndarray: an mx3 Numpy array of int32 type. Setting elements of this array will change the indices. """ return _robotsim.TriangleMesh_getIndices(self)
[docs] def setIndices(self, np_array2: IntArray) ->None: r""" Sets all indices to the given mx3 Numpy array. Args: np_array2 (:obj:`2D Numpy array of ints`) """ return _robotsim.TriangleMesh_setIndices(self, np_array2)
[docs] def translate(self, t: Point) ->None: r""" Translates all the vertices by v=v+t. Args: t (:obj:`list of 3 floats`) """ return _robotsim.TriangleMesh_translate(self, t)
[docs] def transform(self, R: Rotation, t: Point) ->None: r""" Transforms all the vertices by the rigid transform v=R*v+t. Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.TriangleMesh_transform(self, R, t)
indices = property(_robotsim.TriangleMesh_indices_get, _robotsim.TriangleMesh_indices_set, doc=r"""indices : std::vector<(int,std::allocator<(int)>)>""") vertices = property(_robotsim.TriangleMesh_vertices_get, _robotsim.TriangleMesh_vertices_set, doc=r"""vertices : std::vector<(double,std::allocator<(double)>)>""") def __reduce__(self): from klampt.io import loader jsonobj = loader.to_json(self,'TriangleMesh') return (loader.from_json,(jsonobj,'TriangleMesh')) __swig_destroy__ = _robotsim.delete_TriangleMesh
# Register TriangleMesh in _robotsim: _robotsim.TriangleMesh_swigregister(TriangleMesh)
[docs]class ConvexHull(object): r""" Stores a set of points to be set into a ConvexHull type. Note: These may not actually be the vertices of the convex hull; the actual convex hull may be computed internally for some datatypes. Attributes: points (SWIG vector of floats): a list of points, given as a flattened coordinate list [x1,y1,z1,x2,y2,...] C++ includes: geometry.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.ConvexHull_swiginit(self, _robotsim.new_ConvexHull())
[docs] def numPoints(self) ->int: r""" Returns the # of points. """ return _robotsim.ConvexHull_numPoints(self)
[docs] def getPoints(self) ->None: r""" Retrieves a view of the points. Returns: ndarray: an nx3 Numpy array. Setting elements of this array will change the points. """ return _robotsim.ConvexHull_getPoints(self)
[docs] def setPoints(self, np_array2: Vector) ->None: r""" Sets all points to the given nx3 Numpy array. Args: np_array2 (:obj:`2D Numpy array of floats`) """ return _robotsim.ConvexHull_setPoints(self, np_array2)
[docs] def addPoint(self, pt: Point) ->None: r""" Adds a point. Args: pt (:obj:`list of 3 floats`) """ return _robotsim.ConvexHull_addPoint(self, pt)
[docs] def getPoint(self, index: int) ->None: r""" Retrieves a point. Args: index (int) """ return _robotsim.ConvexHull_getPoint(self, index)
[docs] def translate(self, t: Point) ->None: r""" Translates all the vertices by v=v+t. Args: t (:obj:`list of 3 floats`) """ return _robotsim.ConvexHull_translate(self, t)
[docs] def transform(self, R: Rotation, t: Point) ->None: r""" Transforms all the vertices by the rigid transform v=R*v+t. Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.ConvexHull_transform(self, R, t)
points = property(_robotsim.ConvexHull_points_get, _robotsim.ConvexHull_points_set, doc=r"""points : std::vector<(double,std::allocator<(double)>)>""") def __reduce__(self): from klampt.io import loader jsonobj = loader.to_json(self,'ConvexHull') return (loader.from_json,(jsonobj,'ConvexHull')) __swig_destroy__ = _robotsim.delete_ConvexHull
# Register ConvexHull in _robotsim: _robotsim.ConvexHull_swigregister(ConvexHull)
[docs]class PointCloud(object): r""" A 3D point cloud class. Attributes: vertices (SWIG vector of floats): a list of vertices, given as a list [x1, y1, z1, x2, y2, ... zn] properties (SWIG vector of floats): a list of vertex properties, given as a list [p11, p21, ..., pk1, p12, p22, ..., pk2, ..., p1n, p2n, ..., pkn] where each vertex has k properties. The name of each property is given by the ``propertyNames`` member. propertyNames (SWIG vector of strs): a list of the names of each property settings (SWIG map of strs to strs): a general property map . .. note:: Because the bindings are generated by SWIG, you can access the members via some automatically generated accessors / modifiers. In particular len(), append(), and indexing via [] are useful. Some other methods like resize() and iterators are also provided. However, you CANNOT set these items via assignment, i.e., ``pc.vertices = [0,0,0]`` is not allowed. Property names are usually lowercase but follow PCL naming convention, and often include: * `normal_x`, `normal_y`, `normal_z`: the outward normal * `rgb`, `rgba`: integer encoding of RGB (24 bit int, format 0xrrggbb) or RGBA color (32 bit int, format 0xaarrggbb) * `opacity`: opacity, in range [0,1] * `c`: opacity, in range [0,255] * `r,g,b,a`: color channels, in range [0,1] * `u,v`: texture coordinate * `radius`: treats the point cloud as a collection of balls Settings are usually lowercase but follow PCL naming convention, and often include: * `version`: version of the PCL file, typically "0.7" * `id`: integer id * `width`: the width (in pixels) of a structured point cloud * `height`: the height (in pixels) of a structured point cloud * `viewpoint`: Camera position and orientation in the form `ox oy oz qw qx qy qz`, with (ox,oy,oz) the focal point and (qw,qx,qy,qz) the quaternion representation of the orientation (canonical representation, with X right, Y down, Z forward). Examples:: pc = PointCloud() pc.propertyNames.append('rgb') #add 1 point with coordinates (0,0,0) and color #000000 (black) pc.vertices.append(0) pc.vertices.append(0) pc.vertices.append(0) pc.properties.append(0) print(len(pc.vertices)) #prints 3 print(pc.numPoints()) #prints 1 #add another point with coordinates (1,2,3) pc.addPoint([1,2,3]) #this prints 2 print(pc.numPoints() ) print(pc.getPoints()) #prints [[0,0,0],[1,2,3]] #this prints 2, because there is 1 property category x 2 points print(pc.properties.size()) assert pc.propertyNames.size() == pc.getAllProperties().shape[1] #this prints 0; this is the default value added when addPoint is called print(pc.getProperty(1,0) ) To get all points as an n x 3 numpy array:: points = pc.getPoints() To get all properties as a n x k numpy array:: properties = pc.getAllProperties() C++ includes: geometry.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.PointCloud_swiginit(self, _robotsim.new_PointCloud())
[docs] def numPoints(self) ->int: r""" Returns the number of points. """ return _robotsim.PointCloud_numPoints(self)
[docs] def numProperties(self) ->int: r""" Returns the number of properties. """ return _robotsim.PointCloud_numProperties(self)
[docs] def getPoints(self) ->None: r""" Returns a view of the points. Returns: ndarray: an nx3 Numpy array. Setting elements of this array will change the points. """ return _robotsim.PointCloud_getPoints(self)
[docs] def setPoints(self, np_array2: Vector) ->None: r""" Sets all the points to the given nx3 Numpy array. Args: np_array2 (:obj:`2D Numpy array of floats`) """ return _robotsim.PointCloud_setPoints(self, np_array2)
[docs] def setPointsAndProperties(self, np_array2: Vector) ->None: r""" Sets all the points and m properties from the given n x (3+m) array. Args: np_array2 (:obj:`2D Numpy array of floats`) """ return _robotsim.PointCloud_setPointsAndProperties(self, np_array2)
[docs] def addPoint(self, p: Point) ->int: r""" Adds a point. Sets all its properties to 0. Args: p (:obj:`list of 3 floats`) Returns the point's index. """ return _robotsim.PointCloud_addPoint(self, p)
[docs] def setPoint(self, index: int, p: Point) ->None: r""" Sets the position of the point at the given index to p. Args: index (int) p (:obj:`list of 3 floats`) """ return _robotsim.PointCloud_setPoint(self, index, p)
[docs] def getPoint(self, index: int) ->None: r""" Returns the position of the point at the given index. Args: index (int) """ return _robotsim.PointCloud_getPoint(self, index)
[docs] def addProperty(self, *args) ->None: r""" Adds a new property with name pname, and sets values for this property to the given length-n array. addProperty (pname) addProperty (pname,np_array) Args: pname (str): np_array (:obj:`1D Numpy array of floats`, optional): """ return _robotsim.PointCloud_addProperty(self, *args)
[docs] def setProperties(self, *args) ->None: r""" Sets property pindex of all points to the given length-n array. setProperties (np_array2) setProperties (pindex,np_array) Args: np_array2 (:obj:`2D Numpy array of floats`, optional): pindex (int, optional): np_array (:obj:`1D Numpy array of floats`, optional): """ return _robotsim.PointCloud_setProperties(self, *args)
[docs] def setProperty(self, *args) ->None: r""" Sets the property named pname of point index to the given value. setProperty (index,pindex,value) setProperty (index,pname,value) Args: index (int): pindex (int, optional): value (float): pname (str, optional): """ return _robotsim.PointCloud_setProperty(self, *args)
[docs] def getProperty(self, *args) ->float: r""" Returns the property named pname of point index. getProperty (index,pindex): float getProperty (index,pname): float Args: index (int): pindex (int, optional): pname (str, optional): Returns: float: """ return _robotsim.PointCloud_getProperty(self, *args)
[docs] def getProperties(self, *args) ->None: r""" Returns property named pindex of all points as an array. getProperties (pindex) getProperties (pname) Args: pindex (int, optional): pname (str, optional): Returns: ndarray: an n-D Numpy array. """ return _robotsim.PointCloud_getProperties(self, *args)
[docs] def getAllProperties(self) ->None: r""" Returns all the properties of all points as an array view. Returns: ndarray: an nxk Numpy array. Setting elements of this array will change the vertices. """ return _robotsim.PointCloud_getAllProperties(self)
[docs] def translate(self, t: Point) ->None: r""" Translates all the points by v=v+t. Args: t (:obj:`list of 3 floats`) """ return _robotsim.PointCloud_translate(self, t)
[docs] def transform(self, R: Rotation, t: Point) ->None: r""" Transforms all the points by the rigid transform v=R*v+t. Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.PointCloud_transform(self, R, t)
[docs] def join(self, pc: "PointCloud") ->None: r""" Adds the given point cloud to this one. They must share the same properties or else an exception is raised. Args: pc (:class:`~klampt.PointCloud`) """ return _robotsim.PointCloud_join(self, pc)
[docs] def setSetting(self, key: str, value: str) ->None: r""" Sets the given setting. Args: key (str) value (str) """ return _robotsim.PointCloud_setSetting(self, key, value)
[docs] def getSetting(self, key: str) ->str: r""" Returns the given setting. Args: key (str) """ return _robotsim.PointCloud_getSetting(self, key)
[docs] def setDepthImage_d(self, intrinsics: Sequence[float], np_array2: Vector, depth_scale: float) ->None: r""" Sets a structured point cloud from a depth image. [fx,fy,cx,cy] are the intrinsics parameters. The depth is given as a size hxw array, top to bottom. Args: intrinsics (:obj:`double [4]`) np_array2 (:obj:`2D Numpy array of floats`) depth_scale (float) """ return _robotsim.PointCloud_setDepthImage_d(self, intrinsics, np_array2, depth_scale)
[docs] def setDepthImage_f(self, intrinsics: Sequence[float], np_depth2: Vector, depth_scale: float) ->None: r""" Sets a structured point cloud from a depth image. [fx,fy,cx,cy] are the intrinsics parameters. The depth is given as a size hxw array, top to bottom. Args: intrinsics (:obj:`double [4]`) np_depth2 (:obj:`float *`) depth_scale (float) """ return _robotsim.PointCloud_setDepthImage_f(self, intrinsics, np_depth2, depth_scale)
[docs] def setDepthImage_s(self, intrinsics: Sequence[float], np_depth2: "ndarray", depth_scale: float) ->None: r""" Sets a structured point cloud from a depth image. [fx,fy,cx,cy] are the intrinsics parameters. The depth is given as a size hxw array, top to bottom. Args: intrinsics (:obj:`double [4]`) np_depth2 (:obj:`unsigned short *`) depth_scale (float) """ return _robotsim.PointCloud_setDepthImage_s(self, intrinsics, np_depth2, depth_scale)
[docs] def setRGBDImages_i_d(self, intrinsics: Sequence[float], np_array2: "ndarray", np_depth2: Vector, depth_scale: float) ->None: r""" Sets a structured point cloud from an RGBD (color,depth) image pair. [fx,fy,cx,cy] are the intrinsics parameters. The RGB colors are packed in 0xrrggbb order, size hxw, top to bottom. Args: intrinsics (:obj:`double [4]`) np_array2 (:obj:`unsigned int *`) np_depth2 (:obj:`double *`) depth_scale (float) """ return _robotsim.PointCloud_setRGBDImages_i_d(self, intrinsics, np_array2, np_depth2, depth_scale)
[docs] def setRGBDImages_i_f(self, intrinsics: Sequence[float], np_array2: "ndarray", np_depth2: Vector, depth_scale: float) ->None: r""" Sets a structured point cloud from an RGBD (color,depth) image pair. [fx,fy,cx,cy] are the intrinsics parameters. The RGB colors are packed in 0xrrggbb order, size hxw, top to bottom. Args: intrinsics (:obj:`double [4]`) np_array2 (:obj:`unsigned int *`) np_depth2 (:obj:`float *`) depth_scale (float) """ return _robotsim.PointCloud_setRGBDImages_i_f(self, intrinsics, np_array2, np_depth2, depth_scale)
[docs] def setRGBDImages_i_s(self, intrinsics: Sequence[float], np_array2: "ndarray", np_depth2: "ndarray", depth_scale: float) ->None: r""" Sets a structured point cloud from an RGBD (color,depth) image pair. [fx,fy,cx,cy] are the intrinsics parameters. The RGB colors are packed in 0xrrggbb order, size hxw, top to bottom. Args: intrinsics (:obj:`double [4]`) np_array2 (:obj:`unsigned int *`) np_depth2 (:obj:`unsigned short *`) depth_scale (float) """ return _robotsim.PointCloud_setRGBDImages_i_s(self, intrinsics, np_array2, np_depth2, depth_scale)
[docs] def setRGBDImages_b_d(self, intrinsics: Sequence[float], np_array3: "ndarray", np_depth2: Vector, depth_scale: float) ->None: r""" Sets a structured point cloud from an RGBD (color,depth) image pair. [fx,fy,cx,cy] are the intrinsics parameters. The RGB colors are packed in 0xrrggbb order, size hxw, top to bottom. Args: intrinsics (:obj:`double [4]`) np_array3 (:obj:`unsigned char *`) np_depth2 (:obj:`double *`) depth_scale (float) """ return _robotsim.PointCloud_setRGBDImages_b_d(self, intrinsics, np_array3, np_depth2, depth_scale)
[docs] def setRGBDImages_b_f(self, intrinsics: Sequence[float], np_array3: "ndarray", np_depth2: Vector, depth_scale: float) ->None: r""" Sets a structured point cloud from an RGBD (color,depth) image pair. [fx,fy,cx,cy] are the intrinsics parameters. The RGB colors are an h x w x 3 array, top to bottom. Args: intrinsics (:obj:`double [4]`) np_array3 (:obj:`unsigned char *`) np_depth2 (:obj:`float *`) depth_scale (float) """ return _robotsim.PointCloud_setRGBDImages_b_f(self, intrinsics, np_array3, np_depth2, depth_scale)
[docs] def setRGBDImages_b_s(self, intrinsics: Sequence[float], np_array3: "ndarray", np_depth2: "ndarray", depth_scale: float) ->None: r""" Sets a structured point cloud from an RGBD (color,depth) image pair. [fx,fy,cx,cy] are the intrinsics parameters. The RGB colors are an h x w x 3 array, top to bottom. Args: intrinsics (:obj:`double [4]`) np_array3 (:obj:`unsigned char *`) np_depth2 (:obj:`unsigned short *`) depth_scale (float) """ return _robotsim.PointCloud_setRGBDImages_b_s(self, intrinsics, np_array3, np_depth2, depth_scale)
vertices = property(_robotsim.PointCloud_vertices_get, _robotsim.PointCloud_vertices_set, doc=r"""vertices : std::vector<(double,std::allocator<(double)>)>""") propertyNames = property(_robotsim.PointCloud_propertyNames_get, _robotsim.PointCloud_propertyNames_set, doc=r"""propertyNames : std::vector<(std::string,std::allocator<(std::string)>)>""") properties = property(_robotsim.PointCloud_properties_get, _robotsim.PointCloud_properties_set, doc=r"""properties : std::vector<(double,std::allocator<(double)>)>""") settings = property(_robotsim.PointCloud_settings_get, _robotsim.PointCloud_settings_set, doc=r"""settings : std::map<(std::string,std::string,std::less<(std::string)>,std::allocator<(std::pair<(q(const).std::string,std::string)>)>)>""") def __reduce__(self): from klampt.io import loader jsonobj = loader.to_json(self,'PointCloud') return (loader.from_json,(jsonobj,'PointCloud'))
[docs] def setDepthImage(self,intrinsics,depth,depth_scale=1.0): """ Sets a structured point cloud from a depth image. Args: intrinsics (4-list): the intrinsics parameters [fx,fy,cx,cy]. depth (np.ndarray): the depth values, of size h x w. Should have dtype float, np.float32, or np.uint16 for best performance. depth_scale (float, optional): converts depth image values to real depth units. """ import numpy as np if len(intrinsics) != 4: raise ValueError("Invalid value for the intrinsics parameters") if depth.dtype == float: return self.setDepthImage_d(intrinsics,depth,depth_scale) elif depth.dtype == np.float32: return self.setDepthImage_f(intrinsics,depth,depth_scale) elif depth.dtype == np.uint16: return self.setDepthImage_s(intrinsics,depth,depth_scale) else: return self.setDepthImage_d(intrinsics,depth,depth_scale)
[docs] def setRGBDImages(self,intrinsics,color,depth,depth_scale=1.0): """ Sets a structured point cloud from a color,depth image pair. Args: intrinsics (4-list): the intrinsics parameters [fx,fy,cx,cy]. color (np.ndarray): the color values, of size h x w or h x w x 3. In first case, must have dtype np.uint32 with r,g,b values packed in 0xrrggbb order. In second case, if dtype is np.uint8, min and max are [0,255]. If dtype is float or np.float32, min and max are [0,1]. depth (np.ndarray): the depth values, of size h x w. Should have dtype float, np.float32, or np.uint16 for best performance. depth_scale (float, optional): converts depth image values to real depth units. """ import numpy as np if len(intrinsics) != 4: raise ValueError("Invalid value for the intrinsics parameters") if color.shape[0] != depth.shape[0] or color.shape[1] != depth.shape[1]: raise ValueError("Color and depth images need to have matching dimensions") if len(color.shape)==3: if color.shape[2] != 3: raise ValueError("Color image can only have 3 channels") if color.dtype != np.uint8: color = (color*255.0).astype(np.uint8) if depth.dtype == float: return self.setRGBDImages_b_d(intrinsics,color,depth,depth_scale) elif depth.dtype == np.float32: return self.setRGBDImages_b_f(intrinsics,color,depth,depth_scale) elif depth.dtype == np.uint16: return self.setRGBDImages_b_s(intrinsics,color,depth,depth_scale) else: return self.setRGBDImages_b_d(intrinsics,color,depth,depth_scale) else: if depth.dtype == float: return self.setRGBDImages_i_d(intrinsics,color,depth,depth_scale) elif depth.dtype == np.float32: return self.setRGBDImages_i_f(intrinsics,color,depth,depth_scale) elif depth.dtype == np.uint16: return self.setRGBDImages_i_s(intrinsics,color,depth,depth_scale) else: return self.setRGBDImages_i_d(intrinsics,color,depth,depth_scale)
__swig_destroy__ = _robotsim.delete_PointCloud
# Register PointCloud in _robotsim: _robotsim.PointCloud_swigregister(PointCloud)
[docs]class GeometricPrimitive(object): r""" A geometric primitive. So far only points, spheres, segments, and AABBs can be constructed manually in the Python API. Attributes: type (str): Can be "Point", "Sphere", "Segment", "Triangle", "Polygon", "AABB", and "Box". Semi-supported types include "Ellipsoid", and "Cylinder". properties (SWIG vector): a list of parameters defining the primitive. The interpretation is type-specific. C++ includes: geometry.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.GeometricPrimitive_swiginit(self, _robotsim.new_GeometricPrimitive())
[docs] def setPoint(self, pt: Point) ->None: r""" Args: pt (:obj:`list of 3 floats`) """ return _robotsim.GeometricPrimitive_setPoint(self, pt)
[docs] def setSphere(self, c: Point, r: float) ->None: r""" Args: c (:obj:`list of 3 floats`) r (float) """ return _robotsim.GeometricPrimitive_setSphere(self, c, r)
[docs] def setSegment(self, a: Point, b: Point) ->None: r""" Args: a (:obj:`list of 3 floats`) b (:obj:`list of 3 floats`) """ return _robotsim.GeometricPrimitive_setSegment(self, a, b)
[docs] def setTriangle(self, a: Point, b: Point, c: Point) ->None: r""" Args: a (:obj:`list of 3 floats`) b (:obj:`list of 3 floats`) c (:obj:`list of 3 floats`) """ return _robotsim.GeometricPrimitive_setTriangle(self, a, b, c)
[docs] def setPolygon(self, verts: Vector) ->None: r""" Args: verts (:obj:`list of floats`) """ return _robotsim.GeometricPrimitive_setPolygon(self, verts)
[docs] def setAABB(self, bmin: Point, bmax: Point) ->None: r""" Args: bmin (:obj:`list of 3 floats`) bmax (:obj:`list of 3 floats`) """ return _robotsim.GeometricPrimitive_setAABB(self, bmin, bmax)
[docs] def setBox(self, ori: Point, R: Rotation, dims: Point) ->None: r""" Args: ori (:obj:`list of 3 floats`) R (:obj:`list of 9 floats (so3 element)`) dims (:obj:`list of 3 floats`) """ return _robotsim.GeometricPrimitive_setBox(self, ori, R, dims)
[docs] def loadString(self, str: str) ->bool: r""" Args: str (str) """ return _robotsim.GeometricPrimitive_loadString(self, str)
[docs] def saveString(self) ->str: r""" """ return _robotsim.GeometricPrimitive_saveString(self)
type = property(_robotsim.GeometricPrimitive_type_get, _robotsim.GeometricPrimitive_type_set, doc=r"""type : std::string""") properties = property(_robotsim.GeometricPrimitive_properties_get, _robotsim.GeometricPrimitive_properties_set, doc=r"""properties : std::vector<(double,std::allocator<(double)>)>""") def __reduce__(self): from klampt.io import loader jsonobj = loader.to_json(self,'GeometricPrimitive') return (loader.from_json,(jsonobj,'GeometricPrimitive')) __swig_destroy__ = _robotsim.delete_GeometricPrimitive
# Register GeometricPrimitive in _robotsim: _robotsim.GeometricPrimitive_swigregister(GeometricPrimitive)
[docs]class VolumeGrid(object): r""" An axis-aligned volumetric grid, typically a signed distance transform with > 0 indicating outside and < 0 indicating inside. Can also store an occupancy grid with 1 indicating inside and 0 indicating outside. In general, values are associated with cells rather than vertices. So, cell (i,j,k) is associated with a single value, and has size (w,d,h) = ((bmax[0]-bmin[0])/dims[0], (bmax[1]-bmin[1])/dims[1], (bmax[2]-bmin[2])/dims[2]). It ranges over the box [w*i,w*(i+1)) x [d*j,d*(j+1)) x [h*k,h*(k+1)). For SDFs and TSDFs which assume values at vertices, the values are specified at the **centers** of cells. I.e., at (w*(i+1/2),d*(j+1/2),h*(k+1/2)). Attributes: bbox (SWIG vector of 6 doubles): contains min and max bounds (xmin,ymin,zmin),(xmax,ymax,zmax) dims (SWIG vector of of 3 ints): size of grid in each of 3 dimensions values (SWIG vector of doubles): contains a 3D array of ``dims[0]*dims[1]*dims[1]`` values. The cell index (i,j,k) is flattened to ``i*dims[1]*dims[2] + j*dims[2] + k``. The array index i is associated to cell index ``(i/(dims[1]*dims[2]), (i/dims[2]) % dims[1], i%dims[2])`` C++ includes: geometry.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.VolumeGrid_swiginit(self, _robotsim.new_VolumeGrid())
[docs] def setBounds(self, bmin: Point, bmax: Point) ->None: r""" Args: bmin (:obj:`list of 3 floats`) bmax (:obj:`list of 3 floats`) """ return _robotsim.VolumeGrid_setBounds(self, bmin, bmax)
[docs] def resize(self, sx: int, sy: int, sz: int) ->None: r""" Args: sx (int) sy (int) sz (int) """ return _robotsim.VolumeGrid_resize(self, sx, sy, sz)
[docs] def set(self, *args) ->None: r""" Sets a specific element of a cell. set (value) set (i,j,k,value) Args: value (float): i (int, optional): j (int, optional): k (int, optional): """ return _robotsim.VolumeGrid_set(self, *args)
[docs] def get(self, i: int, j: int, k: int) ->float: r""" Gets a specific element of a cell. Args: i (int) j (int) k (int) """ return _robotsim.VolumeGrid_get(self, i, j, k)
[docs] def shift(self, dv: float) ->None: r""" Args: dv (float) """ return _robotsim.VolumeGrid_shift(self, dv)
[docs] def getValues(self) ->None: r""" Returns a 3D Numpy array view of the values. """ return _robotsim.VolumeGrid_getValues(self)
[docs] def setValues(self, np_array3: Vector) ->None: r""" Sets the values to a 3D numpy array. Args: np_array3 (:obj:`3D Numpy array of floats`) """ return _robotsim.VolumeGrid_setValues(self, np_array3)
bbox = property(_robotsim.VolumeGrid_bbox_get, _robotsim.VolumeGrid_bbox_set, doc=r"""bbox : std::vector<(double,std::allocator<(double)>)>""") dims = property(_robotsim.VolumeGrid_dims_get, _robotsim.VolumeGrid_dims_set, doc=r"""dims : std::vector<(int,std::allocator<(int)>)>""") values = property(_robotsim.VolumeGrid_values_get, _robotsim.VolumeGrid_values_set, doc=r"""values : std::vector<(double,std::allocator<(double)>)>""") values = property(getValues, setValues) def __reduce__(self): from klampt.io import loader jsonobj = loader.to_json(self,'VolumeGrid') return (loader.from_json,(jsonobj,'VolumeGrid')) __swig_destroy__ = _robotsim.delete_VolumeGrid
# Register VolumeGrid in _robotsim: _robotsim.VolumeGrid_swigregister(VolumeGrid)
[docs]class DistanceQuerySettings(object): r""" Configures the _ext distance queries of :class:`~klampt.Geometry3D`. The calculated result satisfies :math:`Dcalc \leq D(1+relErr) + absErr` unless :math:`D \geq upperBound`, in which case Dcalc=upperBound may be returned. Attributes: relErr (float, optional): Allows a relative error in the reported distance to speed up computation. Default 0. absErr (float, optional): Allows an absolute error in the reported distance to speed up computation. Default 0. upperBound (float, optional): The calculation may branch if D exceeds this bound. C++ includes: geometry.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.DistanceQuerySettings_swiginit(self, _robotsim.new_DistanceQuerySettings()) relErr = property(_robotsim.DistanceQuerySettings_relErr_get, _robotsim.DistanceQuerySettings_relErr_set, doc=r"""relErr : double""") absErr = property(_robotsim.DistanceQuerySettings_absErr_get, _robotsim.DistanceQuerySettings_absErr_set, doc=r"""absErr : double""") upperBound = property(_robotsim.DistanceQuerySettings_upperBound_get, _robotsim.DistanceQuerySettings_upperBound_set, doc=r"""upperBound : double""") __swig_destroy__ = _robotsim.delete_DistanceQuerySettings
# Register DistanceQuerySettings in _robotsim: _robotsim.DistanceQuerySettings_swigregister(DistanceQuerySettings)
[docs]class DistanceQueryResult(object): r""" The result from a "fancy" distance query of :class:`~klampt.Geometry3D`. Attributes: d (float): The calculated distance, with negative values indicating penetration. Can also be upperBound if the branch was hit. hasClosestPoints (bool): If true, the closest point information is given in cp0 and cp1, and elem1 and elem2 hasGradients (bool): f true, distance gradient information is given in grad0 and grad1. cp1, cp2 (list of 3 floats, optional): closest points on self vs other, both given in world coordinates grad1, grad2 (list of 3 floats, optional): the gradients of the objects' signed distance fields at the closest points. Given in world coordinates. I.e., to move object1 to touch object2, move it in direction grad1 by distance -d. Note that grad2 is always -grad1. elems1, elems2 (int): for compound objects, these are the element indices corresponding to the closest points. C++ includes: geometry.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.DistanceQueryResult_swiginit(self, _robotsim.new_DistanceQueryResult()) d = property(_robotsim.DistanceQueryResult_d_get, _robotsim.DistanceQueryResult_d_set, doc=r"""d : double""") hasClosestPoints = property(_robotsim.DistanceQueryResult_hasClosestPoints_get, _robotsim.DistanceQueryResult_hasClosestPoints_set, doc=r"""hasClosestPoints : bool""") hasGradients = property(_robotsim.DistanceQueryResult_hasGradients_get, _robotsim.DistanceQueryResult_hasGradients_set, doc=r"""hasGradients : bool""") cp1 = property(_robotsim.DistanceQueryResult_cp1_get, _robotsim.DistanceQueryResult_cp1_set, doc=r"""cp1 : std::vector<(double,std::allocator<(double)>)>""") cp2 = property(_robotsim.DistanceQueryResult_cp2_get, _robotsim.DistanceQueryResult_cp2_set, doc=r"""cp2 : std::vector<(double,std::allocator<(double)>)>""") grad1 = property(_robotsim.DistanceQueryResult_grad1_get, _robotsim.DistanceQueryResult_grad1_set, doc=r"""grad1 : std::vector<(double,std::allocator<(double)>)>""") grad2 = property(_robotsim.DistanceQueryResult_grad2_get, _robotsim.DistanceQueryResult_grad2_set, doc=r"""grad2 : std::vector<(double,std::allocator<(double)>)>""") elem1 = property(_robotsim.DistanceQueryResult_elem1_get, _robotsim.DistanceQueryResult_elem1_set, doc=r"""elem1 : int""") elem2 = property(_robotsim.DistanceQueryResult_elem2_get, _robotsim.DistanceQueryResult_elem2_set, doc=r"""elem2 : int""") __swig_destroy__ = _robotsim.delete_DistanceQueryResult
# Register DistanceQueryResult in _robotsim: _robotsim.DistanceQueryResult_swigregister(DistanceQueryResult)
[docs]class ContactQueryResult(object): r""" The result from a contact query of :class:`~klampt.Geometry3D`. The number of contacts n is variable. Attributes: depths (list of n floats): penetration depths for each contact point. The depth is measured with respect to the padded geometry, and must be nonnegative. A value of 0 indicates that depth cannot be determined accurately. points1, points2 (list of n lists of floats): contact points on self vs other, The top level list has n entries, and each entry is a 3-list expressed in world coordinates. If an object is padded, these points are on the surface of the padded geometry. normals (list of n lists of floats): the outward-facing contact normal from this to other at each contact point, given in world coordinates. Each entry is a 3-list, and can be a unit vector, or [0,0,0] if the the normal cannot be computed properly. elems1, elems2 (list of n ints): for compound objects, these are the element indices corresponding to each contact. C++ includes: geometry.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.ContactQueryResult_swiginit(self, _robotsim.new_ContactQueryResult()) depths = property(_robotsim.ContactQueryResult_depths_get, _robotsim.ContactQueryResult_depths_set, doc=r"""depths : std::vector<(double,std::allocator<(double)>)>""") points1 = property(_robotsim.ContactQueryResult_points1_get, _robotsim.ContactQueryResult_points1_set, doc=r"""points1 : std::vector<(std::vector<(double,std::allocator<(double)>)>,std::allocator<(std::vector<(double,std::allocator<(double)>)>)>)>""") points2 = property(_robotsim.ContactQueryResult_points2_get, _robotsim.ContactQueryResult_points2_set, doc=r"""points2 : std::vector<(std::vector<(double,std::allocator<(double)>)>,std::allocator<(std::vector<(double,std::allocator<(double)>)>)>)>""") normals = property(_robotsim.ContactQueryResult_normals_get, _robotsim.ContactQueryResult_normals_set, doc=r"""normals : std::vector<(std::vector<(double,std::allocator<(double)>)>,std::allocator<(std::vector<(double,std::allocator<(double)>)>)>)>""") elems1 = property(_robotsim.ContactQueryResult_elems1_get, _robotsim.ContactQueryResult_elems1_set, doc=r"""elems1 : std::vector<(int,std::allocator<(int)>)>""") elems2 = property(_robotsim.ContactQueryResult_elems2_get, _robotsim.ContactQueryResult_elems2_set, doc=r"""elems2 : std::vector<(int,std::allocator<(int)>)>""") __swig_destroy__ = _robotsim.delete_ContactQueryResult
# Register ContactQueryResult in _robotsim: _robotsim.ContactQueryResult_swigregister(ContactQueryResult)
[docs]class Geometry3D(object): r""" The three-D geometry container used throughout Klampt. There are five currently supported types of geometry: * primitives (:class:`GeometricPrimitive`) * triangle meshes (:class:`TriangleMesh`) * point clouds (:class:`PointCloud`) * volumetric grids (:class:`VolumeGrid`) * groups ("Group" type) * convex hulls (:class:`ConvexHull`) This class acts as a uniform container of all of these types. There are two modes in which a Geometry3D can be used. It can be a standalone geometry, which means it is a container of geometry data, or it can be a reference to a world item's geometry. For references, modifiers change the world item's geometry. **Current transform** Each geometry stores a "current" transform, which is automatically updated for world items' geometries. Proximity queries are then performed *with respect to the transformed geometries*. Crucially, the underlying geometry is not changed, because that could be computationally expensive. **Creating / modifying the geometry** Use the constructor, the :meth:`set`, or the set[TYPE]() methods to completely change the geometry's data. Note: if you want to set a world item's geometry to be equal to a standalone geometry, use the set(rhs) function rather than the assignment (=) operator. Modifiers include: * :meth:`setCurrentTransform`: updates the current transform. (This call is very fast.) * :meth:`translate`, :meth:`scale`, :meth:`rotate`, and :meth:`transform` transform the underlying geometry. Any collision data structures will be recomputed after transformation. * :meth:`loadFile`: load from OFF, OBJ, STL, PCD, etc. Also supports native Klamp't types .geom and .vol. .. note:: Avoid the use of translate, rotate, and transform to represent object movement. Use setCurrentTransform instead. **Proximity queries** * :meth:`collides`: boolean collision query. * :meth:`withinDistance`: boolean proximity query. * :meth:`distance` and :meth:`distance_ext`: numeric-valued distance query. The distance may be negative to indicate signed distance, available for certain geometry types. Also returns closest points for certain geometry types. * :meth:`distance_point` and :meth:`distance_point_ext`: numeric valued distance-to-point queries. * :meth:`contacts`: estimates the contact region between two objects. * :meth:`rayCast` and :meth:`rayCast_ext`: ray-cast queries. For most geometry types (TriangleMesh, PointCloud, ConvexHull), the first time you perform a query, some collision detection data structures will be initialized. This preprocessing step can take some time for complex geometries. **Collision margins** Each object also has a "collision margin" which may virtually fatten the object, as far as proximity queries are concerned. This is useful for setting collision avoidance margins in motion planning. Use the :meth:`setCollisionMargin` and :meth:`getCollisionMargin` methods to access the margin. By default the margin is zero. .. note:: The geometry margin is NOT the same thing as simulation body collision padding! All proximity queries are affected by the collision padding, inside or outside of simulation. **Conversions** Many geometry types can be converted to and from one another using the :meth:`convert` method. This can also be used to remesh TriangleMesh objects and PointCloud objects. C++ includes: geometry.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__ (): :class:`~klampt.Geometry3D` __init__ (arg2): :class:`~klampt.Geometry3D` Args: arg2 (:class:`~klampt.Geometry3D` or :class:`~klampt.VolumeGrid` or :class:`~klampt.PointCloud` or :class:`~klampt.GeometricPrimitive` or :class:`~klampt.TriangleMesh` or :class:`~klampt.ConvexHull`, optional): """ _robotsim.Geometry3D_swiginit(self, _robotsim.new_Geometry3D(*args)) __swig_destroy__ = _robotsim.delete_Geometry3D
[docs] def clone(self) -> "Geometry3D": r""" Creates a standalone geometry from this geometry (identical to copy... will be deprecated in a future version) """ return _robotsim.Geometry3D_clone(self)
[docs] def copy(self) -> "Geometry3D": r""" Creates a standalone geometry from this geometry. """ return _robotsim.Geometry3D_copy(self)
[docs] def set(self, arg2: "Geometry3D") ->None: r""" Copies the geometry of the argument into this geometry. Args: arg2 (:class:`~klampt.Geometry3D`) """ return _robotsim.Geometry3D_set(self, arg2)
[docs] def isStandalone(self) ->bool: r""" Returns True if this is a standalone geometry. """ return _robotsim.Geometry3D_isStandalone(self)
[docs] def free(self) ->None: r""" Frees the data associated with this geometry, if standalone. """ return _robotsim.Geometry3D_free(self)
[docs] def type(self) ->str: r""" Returns the type of geometry: TriangleMesh, PointCloud, VolumeGrid, GeometricPrimitive, or Group. """ return _robotsim.Geometry3D_type(self)
[docs] def empty(self) ->bool: r""" Returns True if this has no contents (not the same as numElements()==0) """ return _robotsim.Geometry3D_empty(self)
[docs] def getTriangleMesh(self) -> "TriangleMesh": r""" Returns a TriangleMesh if this geometry is of type TriangleMesh. """ return _robotsim.Geometry3D_getTriangleMesh(self)
[docs] def getPointCloud(self) -> "PointCloud": r""" Returns a PointCloud if this geometry is of type PointCloud. """ return _robotsim.Geometry3D_getPointCloud(self)
[docs] def getGeometricPrimitive(self) -> "GeometricPrimitive": r""" Returns a GeometricPrimitive if this geometry is of type GeometricPrimitive. """ return _robotsim.Geometry3D_getGeometricPrimitive(self)
[docs] def getConvexHull(self) -> "ConvexHull": r""" Returns a ConvexHull if this geometry is of type ConvexHull. """ return _robotsim.Geometry3D_getConvexHull(self)
[docs] def getVolumeGrid(self) -> "VolumeGrid": r""" Returns a VolumeGrid if this geometry is of type VolumeGrid. """ return _robotsim.Geometry3D_getVolumeGrid(self)
[docs] def setTriangleMesh(self, arg2: "TriangleMesh") ->None: r""" Sets this Geometry3D to a TriangleMesh. Args: arg2 (:class:`~klampt.TriangleMesh`) """ return _robotsim.Geometry3D_setTriangleMesh(self, arg2)
[docs] def setPointCloud(self, arg2: "PointCloud") ->None: r""" Sets this Geometry3D to a PointCloud. Args: arg2 (:class:`~klampt.PointCloud`) """ return _robotsim.Geometry3D_setPointCloud(self, arg2)
[docs] def setGeometricPrimitive(self, arg2: "GeometricPrimitive") ->None: r""" Sets this Geometry3D to a GeometricPrimitive. Args: arg2 (:class:`~klampt.GeometricPrimitive`) """ return _robotsim.Geometry3D_setGeometricPrimitive(self, arg2)
[docs] def setConvexHull(self, arg2: "ConvexHull") ->None: r""" Sets this Geometry3D to a ConvexHull. Args: arg2 (:class:`~klampt.ConvexHull`) """ return _robotsim.Geometry3D_setConvexHull(self, arg2)
[docs] def setConvexHullGroup(self, g1: "Geometry3D", g2: "Geometry3D") ->None: r""" Sets this Geometry3D to be a convex hull of two geometries. Note: the relative transform of these two objects is frozen in place; i.e., setting the current transform of g2 doesn't do anything to this object. Args: g1 (:class:`~klampt.Geometry3D`) g2 (:class:`~klampt.Geometry3D`) """ return _robotsim.Geometry3D_setConvexHullGroup(self, g1, g2)
[docs] def setVolumeGrid(self, arg2: "VolumeGrid") ->None: r""" Sets this Geometry3D to a volumeGrid. Args: arg2 (:class:`~klampt.VolumeGrid`) """ return _robotsim.Geometry3D_setVolumeGrid(self, arg2)
[docs] def setGroup(self) ->None: r""" Sets this Geometry3D to a group geometry. To add sub-geometries, repeatedly call setElement() with increasing indices. """ return _robotsim.Geometry3D_setGroup(self)
[docs] def getElement(self, element: int) -> "Geometry3D": r""" Returns an element of the Geometry3D if it is a Group, TriangleMesh, or PointCloud. Raises an error if this is of any other type. Args: element (int) The element will be in local coordinates. """ return _robotsim.Geometry3D_getElement(self, element)
[docs] def setElement(self, element: int, data: "Geometry3D") ->None: r""" Sets an element of the Geometry3D if it is a Group, TriangleMesh, or PointCloud. The element will be in local coordinates. Raises an error if this is of any other type. Args: element (int) data (:class:`~klampt.Geometry3D`) """ return _robotsim.Geometry3D_setElement(self, element, data)
[docs] def numElements(self) ->int: r""" Returns the number of sub-elements in this geometry. """ return _robotsim.Geometry3D_numElements(self)
[docs] def loadFile(self, fn: str) ->bool: r""" Loads from file. Standard mesh types, PCD files, and .geom files are supported. Args: fn (str) Returns: True on success, False on failure """ return _robotsim.Geometry3D_loadFile(self, fn)
[docs] def saveFile(self, fn: str) ->bool: r""" Saves to file. Standard mesh types, PCD files, and .geom files are supported. Args: fn (str) """ return _robotsim.Geometry3D_saveFile(self, fn)
[docs] def setCurrentTransform(self, R: Rotation, t: Point) ->None: r""" Sets the current transformation (not modifying the underlying data) Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.Geometry3D_setCurrentTransform(self, R, t)
[docs] def getCurrentTransform(self) ->None: r""" Gets the current transformation. """ return _robotsim.Geometry3D_getCurrentTransform(self)
[docs] def translate(self, t: Point) ->None: r""" Translates the geometry data. Permanently modifies the data and resets any collision data structures. Args: t (:obj:`list of 3 floats`) """ return _robotsim.Geometry3D_translate(self, t)
[docs] def scale(self, *args) ->None: r""" Scales the geometry data with different factors on each axis. Permanently modifies the data and resets any collision data structures. scale (s) scale (sx,sy,sz) Args: s (float, optional): sx (float, optional): sy (float, optional): sz (float, optional): """ return _robotsim.Geometry3D_scale(self, *args)
[docs] def rotate(self, R: Rotation) ->None: r""" Rotates the geometry data. Permanently modifies the data and resets any collision data structures. Args: R (:obj:`list of 9 floats (so3 element)`) """ return _robotsim.Geometry3D_rotate(self, R)
[docs] def transform(self, R: Rotation, t: Point) ->None: r""" Translates/rotates/scales the geometry data. Permanently modifies the data and resets any collision data structures. Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.Geometry3D_transform(self, R, t)
[docs] def setCollisionMargin(self, margin: float) ->None: r""" Sets a padding around the base geometry which affects the results of proximity queries. Args: margin (float) """ return _robotsim.Geometry3D_setCollisionMargin(self, margin)
[docs] def getCollisionMargin(self) ->float: r""" Returns the padding around the base geometry. Default 0. """ return _robotsim.Geometry3D_getCollisionMargin(self)
[docs] def getBB(self) ->None: r""" Returns an axis-aligned bounding box of the object as a tuple (bmin,bmax). Note: O(1) time, but may not be tight """ return _robotsim.Geometry3D_getBB(self)
[docs] def getBBTight(self) ->None: r""" Computes a tighter axis-aligned bounding box of the object than :meth:`Geometry3D.getBB`. Worst case O(n) time. """ return _robotsim.Geometry3D_getBBTight(self)
[docs] def convert(self, type: str, param: float=0) -> "Geometry3D": r""" Converts a geometry to another type, if a conversion is available. The interpretation of param depends on the type of conversion, with 0 being a reasonable default. Args: type (str) param (float, optional): default value 0 Available conversions are: * TriangleMesh -> PointCloud. param is the desired dispersion of the points, by default set to the average triangle diameter. At least all of the mesh's vertices will be returned. * TriangleMesh -> VolumeGrid. Converted using the fast marching method with good results only if the mesh is watertight. param is the grid resolution, by default set to the average triangle diameter. * TriangleMesh -> ConvexHull. If param==0, just calculates a convex hull. Otherwise, uses convex decomposition with the HACD library. * PointCloud -> TriangleMesh. Available if the point cloud is structured. param is the threshold for splitting triangles by depth discontinuity. param is by default infinity. * PointCloud -> ConvexHull. Converted using SOLID / Qhull. * GeometricPrimitive -> anything. param determines the desired resolution. * VolumeGrid -> TriangleMesh. param determines the level set for the marching cubes algorithm. * VolumeGrid -> PointCloud. param determines the level set. * ConvexHull -> TriangleMesh. * ConvexHull -> PointCloud. param is the desired dispersion of the points. Equivalent to ConvexHull -> TriangleMesh -> PointCloud """ return _robotsim.Geometry3D_convert(self, type, param)
[docs] def collides(self, other: "Geometry3D") ->bool: r""" Returns true if this geometry collides with the other. Args: other (:class:`~klampt.Geometry3D`) Unsupported types: * VolumeGrid - GeometricPrimitive [aabb, box, triangle, polygon] * VolumeGrid - TriangleMesh * VolumeGrid - VolumeGrid * ConvexHull - anything else besides ConvexHull """ return _robotsim.Geometry3D_collides(self, other)
[docs] def withinDistance(self, other: "Geometry3D", tol: float) ->bool: r""" Returns true if this geometry is within distance `tol` to other. Args: other (:class:`~klampt.Geometry3D`) tol (float) """ return _robotsim.Geometry3D_withinDistance(self, other, tol)
[docs] def distance_simple(self, other: "Geometry3D", relErr: float=0, absErr: float=0) ->float: r""" Version 0.8: this is the same as the old distance() function. Args: other (:class:`~klampt.Geometry3D`) relErr (float, optional): default value 0 absErr (float, optional): default value 0 Returns the distance from this geometry to the other. If either geometry contains volume information, this value may be negative to indicate penetration. See :meth:`Geometry3D.distance` for more information. """ return _robotsim.Geometry3D_distance_simple(self, other, relErr, absErr)
[docs] def distance_point(self, pt: Point) -> "DistanceQueryResult": r""" Returns the the distance and closest point to the input point, given in world coordinates. An exception is raised if this operation is not supported with the given geometry type. Args: pt (:obj:`list of 3 floats`) The return value contains the distance, closest points, and gradients if available. For some geometry types, the signed distance is returned. The signed distance returns the negative penetration depth if pt is within this. The following geometry types return signed distances: * GeometricPrimitive * PointCloud (approximate, if the cloud is a set of balls with the radius property) * VolumeGrid * ConvexHull For other types, a signed distance will be returned if the geometry has a positive collision margin, and the point penetrates less than this margin. """ return _robotsim.Geometry3D_distance_point(self, pt)
[docs] def distance_point_ext(self, pt: Point, settings: "DistanceQuerySettings") -> "DistanceQueryResult": r""" A customizable version of :meth:`Geometry3D.distance_point`. The settings for the calculation can be customized with relErr, absErr, and upperBound, e.g., to break if the closest points are at least upperBound distance from one another. Args: pt (:obj:`list of 3 floats`) settings (:class:`~klampt.DistanceQuerySettings`) """ return _robotsim.Geometry3D_distance_point_ext(self, pt, settings)
[docs] def distance(self, other: "Geometry3D") -> "DistanceQueryResult": r""" Returns the the distance and closest points between the given geometries. This may be either the normal distance or the signed distance, depending on the geometry type. Args: other (:class:`~klampt.Geometry3D`) The normal distance returns 0 if the two objects are touching (this.collides(other)=True). The signed distance returns the negative penetration depth if the objects are touching. Only the following combinations of geometry types return signed distances: * GeometricPrimitive-GeometricPrimitive (Python-supported sub-types only) * GeometricPrimitive-TriangleMesh (surface only) * GeometricPrimitive-PointCloud * GeometricPrimitive-VolumeGrid * TriangleMesh (surface only)-GeometricPrimitive * PointCloud-VolumeGrid * ConvexHull - ConvexHull If penetration is supported, a negative distance is returned and cp1,cp2 are the deepest penetrating points. Unsupported types: * GeometricPrimitive-GeometricPrimitive subtypes segment vs aabb * PointCloud-PointCloud * VolumeGrid-TriangleMesh * VolumeGrid-VolumeGrid * ConvexHull - anything else besides ConvexHull See the comments of the distance_point function """ return _robotsim.Geometry3D_distance(self, other)
[docs] def distance_ext(self, other: "Geometry3D", settings: "DistanceQuerySettings") -> "DistanceQueryResult": r""" A customizable version of :meth:`Geometry3D.distance`. The settings for the calculation can be customized with relErr, absErr, and upperBound, e.g., to break if the closest points are at least upperBound distance from one another. Args: other (:class:`~klampt.Geometry3D`) settings (:class:`~klampt.DistanceQuerySettings`) """ return _robotsim.Geometry3D_distance_ext(self, other, settings)
[docs] def rayCast(self, s: Point, d: Point) ->bool: r""" Performs a ray cast. Args: s (:obj:`list of 3 floats`) d (:obj:`list of 3 floats`) Supported types: * GeometricPrimitive * TriangleMesh * PointCloud (need a positive collision margin, or points need to have a 'radius' property assigned) * VolumeGrid * Group (groups of the aforementioned types) Returns: (hit,pt) where hit is true if the ray starting at s and pointing in direction d hits the geometry (given in world coordinates); pt is the hit point, in world coordinates. """ return _robotsim.Geometry3D_rayCast(self, s, d)
[docs] def rayCast_ext(self, s: Point, d: Point) ->int: r""" A more sophisticated ray cast. Args: s (:obj:`list of 3 floats`) d (:obj:`list of 3 floats`) Supported types: * GeometricPrimitive * TriangleMesh * PointCloud (need a positive collision margin, or points need to have a 'radius' property assigned) * VolumeGrid * Group (groups of the aforementioned types) Returns: (hit_element,pt) where hit_element is >= 0 if ray starting at s and pointing in direction d hits the geometry (given in world coordinates). - hit_element is -1 if the object is not hit, otherwise it gives the index of the element (triangle, point, sub-object) that was hit. For geometric primitives, this will be 0. - pt is the hit point, in world coordinates. """ return _robotsim.Geometry3D_rayCast_ext(self, s, d)
[docs] def contacts(self, other: "Geometry3D", padding1: float, padding2: float, maxContacts: int=0) -> "ContactQueryResult": r""" Returns the set of contact points between this and other. This set is a discrete representation of the region of surface overlap, which is defined as all pairs of points within distance self.collisionMargin + other.collisionMargin + padding1 + padding2. Args: other (:class:`~klampt.Geometry3D`) padding1 (float) padding2 (float) maxContacts (int, optional): default value 0 For some geometry types (TriangleMesh-TriangleMesh, TriangleMesh-PointCloud, PointCloud-PointCloud) padding must be positive to get meaningful contact poitns and normals. If maxContacts != 0 a clustering postprocessing step is performed. Unsupported types: * GeometricPrimitive-GeometricPrimitive subtypes segment vs aabb * VolumeGrid-GeometricPrimitive any subtypes except point and sphere. also, the results are potentially inaccurate for non-convex VolumeGrids. * VolumeGrid-TriangleMesh * VolumeGrid-VolumeGrid * ConvexHull - anything """ return _robotsim.Geometry3D_contacts(self, other, padding1, padding2, maxContacts)
[docs] def support(self, dir: Point) ->None: r""" Calculates the furthest point on this geometry in the direction dir. Args: dir (:obj:`list of 3 floats`) Supported types: * ConvexHull """ return _robotsim.Geometry3D_support(self, dir)
[docs] def slice(self, R: Rotation, t: Point, tol: float) -> "Geometry3D": r""" Calculates a 2D slice through the data. The slice is given by the local X-Y plane of a transform (R,T) with orientation R and translation t. The return Geometry's data is in the local frame of (R,t), and (R,t) is set as its current transform. Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) tol (float) The geometry's current transform is respected. O(N) time. Supported types: * PointCloud. Needs tol > 0. A PointCloud is returned. * TriangleMesh. tol is ignored. A Group of GeometricPrimitives (segments) is returned. """ return _robotsim.Geometry3D_slice(self, R, t, tol)
[docs] def roi(self, query: str, bmin: Point, bmax: Point) -> "Geometry3D": r""" Calculates a region of interest of the data for the bounding box [bmin,bmax]. The geometry's current transform is respected. Args: query (str) bmin (:obj:`list of 3 floats`) bmax (:obj:`list of 3 floats`) `query` can be "intersect", "touching", or "within". If "intersect", this tries to get a representation of the geometry intersecting the box. If "touching", all elements touching the box are returned. If "within", only elements entirely inside the box are returned. `query` can also be prefaced with a '~' which indicates that the ROI should be inverted, i.e. select everything that does NOT intersect with a box. O(N) time. Supported types: * PointCloud * TriangleMesh """ return _robotsim.Geometry3D_roi(self, query, bmin, bmax)
world = property(_robotsim.Geometry3D_world_get, _robotsim.Geometry3D_world_set, doc=r"""world : int""") id = property(_robotsim.Geometry3D_id_get, _robotsim.Geometry3D_id_set, doc=r"""id : int""") geomPtr = property(_robotsim.Geometry3D_geomPtr_get, _robotsim.Geometry3D_geomPtr_set, doc=r"""geomPtr : p.void""") def __reduce__(self): from klampt.io import loader jsonobj = loader.to_json(self,'Geometry3D') return (loader.from_json,(jsonobj,'Geometry3D'))
# Register Geometry3D in _robotsim: _robotsim.Geometry3D_swigregister(Geometry3D)
[docs]class Appearance(object): r""" Geometry appearance information. Supports vertex/edge/face rendering, per-vertex color, and basic color texture mapping. Uses OpenGL display lists, so repeated calls are fast. For more complex appearances, you will need to call your own OpenGL calls. Appearances can be either references to appearances of objects in the world, or they can be standalone. Performance note: Avoid rebuilding buffers (e.g., via :meth:`refresh`) as much as possible. C++ includes: appearance.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr ALL = _robotsim.Appearance_ALL VERTICES = _robotsim.Appearance_VERTICES EDGES = _robotsim.Appearance_EDGES FACES = _robotsim.Appearance_FACES EMISSIVE = _robotsim.Appearance_EMISSIVE SPECULAR = _robotsim.Appearance_SPECULAR def __init__(self, *args): r""" __init__ (): :class:`~klampt.Appearance` __init__ (app): :class:`~klampt.Appearance` Args: app (:class:`~klampt.Appearance`, optional): """ _robotsim.Appearance_swiginit(self, _robotsim.new_Appearance(*args)) __swig_destroy__ = _robotsim.delete_Appearance
[docs] def refresh(self, deep: bool=True) ->None: r""" call this to rebuild internal buffers, e.g., when the OpenGL context changes. If deep=True, the entire data structure will be revised. Use this for streaming data, for example. Args: deep (bool, optional): default value True """ return _robotsim.Appearance_refresh(self, deep)
[docs] def clone(self) -> "Appearance": r""" Creates a standalone appearance from this appearance. """ return _robotsim.Appearance_clone(self)
[docs] def set(self, arg2: "Appearance") ->None: r""" Copies the appearance of the argument into this appearance. Args: arg2 (:class:`~klampt.Appearance`) """ return _robotsim.Appearance_set(self, arg2)
[docs] def isStandalone(self) ->bool: r""" Returns true if this is a standalone appearance. """ return _robotsim.Appearance_isStandalone(self)
[docs] def free(self) ->None: r""" Frees the data associated with this appearance, if standalone. """ return _robotsim.Appearance_free(self)
[docs] def setDraw(self, *args) ->None: r""" Turns on/off visibility of the object or a feature. setDraw (draw) setDraw (feature,draw) Args: draw (bool): feature (int, optional): If one argument is given, turns the object visibility on or off If two arguments are given, turns the feature (first int argument) visibility on or off. feature can be ALL, VERTICES, EDGES, or FACES. """ return _robotsim.Appearance_setDraw(self, *args)
[docs] def getDraw(self, *args) ->bool: r""" Returns whether this object or feature is visible. getDraw (): bool getDraw (feature): bool Args: feature (int, optional): Returns: bool: If no arguments are given, returns whether the object is visible. If one int argument is given, returns whether the given feature is visible. feature can be ALL, VERTICES, EDGES, or FACES. """ return _robotsim.Appearance_getDraw(self, *args)
[docs] def setColor(self, *args) ->None: r""" Sets color of the object or a feature. setColor (r,g,b,a=1) setColor (feature,r,g,b,a) Args: r (float): g (float): b (float): a (float): default value 1 feature (int, optional): If 3 or 4 arguments are given, changes the object color. If 5 arguments are given, changes the color of the given feature. feature can be ALL, VERTICES, EDGES, FACES, EMISSIVE, or SPECULAR. """ return _robotsim.Appearance_setColor(self, *args)
[docs] def getColor(self, *args) ->None: r""" Gets color of the object or a feature. getColor () getColor (feature) Args: feature (int, optional): If 0 arguments are given, retrieves the main object color. If 1 arguments are given, returns the color of the given feature. feature. feature can be ALL, VERTICES, EDGES, FACES, EMISSIVE, or SPECULAR. """ return _robotsim.Appearance_getColor(self, *args)
[docs] def setColors(self, feature: int, np_array2: Vector) ->None: r""" Sets per-element color for elements of the given feature type. Must be an mxn array. m is the number of features of that type, and n is either 3 or 4. Args: feature (int) np_array2 (:obj:`2D Numpy array of np.float32`) If n == 4, they are assumed to be rgba values, and If n == 3, each row is an rgb value. Only supports feature=VERTICES and feature=FACES """ return _robotsim.Appearance_setColors(self, feature, np_array2)
[docs] def setTintColor(self, color: Sequence[float], strength: float) ->None: r""" Sets a temporary tint color that modulates the appearance of the object. This works with both flat colors and per-vertex / per-face colors. Args: color (:obj:`list of 4 wfloats`) strength (float) """ return _robotsim.Appearance_setTintColor(self, color, strength)
[docs] def getTintColor(self) ->None: r""" Retrieves the tint color. """ return _robotsim.Appearance_getTintColor(self)
[docs] def getTintStrength(self) ->float: r""" Retrieves the tint strength. """ return _robotsim.Appearance_getTintStrength(self)
[docs] def setShininess(self, shininess: float, strength: float=-1) ->None: r""" Sets the specular highlight shininess and strength. To turn off, use `setShininess(0)`. The specular strength can be set via the second argument. `setShininess(20,0.1)`. Note that this changes the specular color. Args: shininess (float) strength (float, optional): default value -1 """ return _robotsim.Appearance_setShininess(self, shininess, strength)
[docs] def getShininess(self) ->float: r""" Retrieves the specular highlight shininess. """ return _robotsim.Appearance_getShininess(self)
[docs] def setElementColor(self, feature: int, element: int, r: float, g: float, b: float, a: float=1) ->None: r""" Sets the per-element color for the given feature. Args: feature (int) element (int) r (float) g (float) b (float) a (float, optional): default value 1 """ return _robotsim.Appearance_setElementColor(self, feature, element, r, g, b, a)
[docs] def getElementColor(self, feature: int, element: int) ->None: r""" Gets the per-element color for the given feature. Args: feature (int) element (int) """ return _robotsim.Appearance_getElementColor(self, feature, element)
[docs] def setTexture1D_b(self, format: str, np_array: "ndarray") ->None: r""" Sets a 1D texture of the given width. Valid format strings are. Args: format (str) np_array (:obj:`unsigned char *`) * "": turn off texture mapping * l8: unsigned byte grayscale colors """ return _robotsim.Appearance_setTexture1D_b(self, format, np_array)
[docs] def setTexture1D_i(self, format: str, np_array: "ndarray", m: int) ->None: r""" Sets a 1D texture of the given width. Valid format strings are. Args: format (str) np_array (:obj:`unsigned int *`) m (int) * "": turn off texture mapping * rgba8: unsigned byte RGBA colors with red in the 1st byte and alpha in the 4th * bgra8: unsigned byte RGBA colors with blue in the 1st byte and alpha in the 4th """ return _robotsim.Appearance_setTexture1D_i(self, format, np_array, m)
[docs] def setTexture1D_channels(self, format: str, np_array2: "ndarray") ->None: r""" Sets a 1D texture of the given width, given a 2D array of channels. Valid format strings are. Args: format (str) np_array2 (:obj:`unsigned char *`) * "": turn off texture mapping * rgb8: unsigned byte RGB colors with red in the 1st column, green in the 2nd, blue in the 3rd * bgr8: unsigned byte RGB colors with blue in the 1st column, green in the 2nd, green in the 3rd * rgba8: unsigned byte RGBA colors with red in the 1st column and alpha in the 4th * bgra8: unsigned byte RGBA colors with blue in the 1st column and alpha in the 4th * l8: unsigned byte grayscale colors, one channel """ return _robotsim.Appearance_setTexture1D_channels(self, format, np_array2)
[docs] def setTexture2D_b(self, format: str, np_array2: "ndarray", topdown: bool=True) ->None: r""" Sets a 2D texture of the given width/height. See :func:`setTexture1D_b` for valid format strings. Args: format (str) np_array2 (:obj:`unsigned char *`) topdown (bool, optional): default value True The array is given in top to bottom order if `topdown==True`. Otherwise, it is given in order bottom to top. """ return _robotsim.Appearance_setTexture2D_b(self, format, np_array2, topdown)
[docs] def setTexture2D_i(self, format: str, np_array2: "ndarray", topdown: bool=True) ->None: r""" Sets a 2D texture of the given width/height. See :func:`setTexture1D_i` for valid format strings. Args: format (str) np_array2 (:obj:`unsigned int *`) topdown (bool, optional): default value True The array is given in top to bottom order if `topdown==True`. Otherwise, it is given in order bottom to top. """ return _robotsim.Appearance_setTexture2D_i(self, format, np_array2, topdown)
[docs] def setTexture2D_channels(self, format: str, np_array3: "ndarray", topdown: bool=True) ->None: r""" Sets a 2D texture of the given width/height from a 3D array of channels. See :func:`setTexture1D_channels` for valid format strings. Args: format (str) np_array3 (:obj:`unsigned char *`) topdown (bool, optional): default value True The array is given in top to bottom order if `topdown==True`. Otherwise, it is given in order bottom to top. """ return _robotsim.Appearance_setTexture2D_channels(self, format, np_array3, topdown)
[docs] def setTexcoords1D(self, np_array: Vector) ->None: r""" Sets per-vertex texture coordinates for a 1D texture. Args: np_array (:obj:`1D Numpy array of floats`) You may also set uvs to be empty, which turns off texture mapping altogether. """ return _robotsim.Appearance_setTexcoords1D(self, np_array)
[docs] def setTexcoords2D(self, np_array2: Vector) ->None: r""" Sets per-vertex texture coordinates for a 2D texture. uvs is an array of shape (nx2) containing U-V coordinates [[u1, v1], [u2, v2], ..., [un, vn]]. Args: np_array2 (:obj:`2D Numpy array of floats`) You may also set uvs to be empty, which turns off texture mapping altogether. """ return _robotsim.Appearance_setTexcoords2D(self, np_array2)
[docs] def setTexgen(self, np_array2: Vector, worldcoordinates: bool=False) ->None: r""" Sets the texture generation. The array must be size m x 4, with m in the range 0,...,4. If worldcoordinates=true, the texture generation is performed in world coordinates rather than object coordinates. Args: np_array2 (:obj:`2D Numpy array of floats`) worldcoordinates (bool, optional): default value False """ return _robotsim.Appearance_setTexgen(self, np_array2, worldcoordinates)
[docs] def setTexWrap(self, wrap: bool) ->None: r""" Sets whether textures are to wrap (default true) Args: wrap (bool) """ return _robotsim.Appearance_setTexWrap(self, wrap)
[docs] def setPointSize(self, size: float) ->None: r""" For point clouds, sets the point size. Args: size (float) """ return _robotsim.Appearance_setPointSize(self, size)
[docs] def setCreaseAngle(self, creaseAngleRads: float) ->None: r""" For meshes, sets the crease angle. Set to 0 to disable smoothing. Args: creaseAngleRads (float) """ return _robotsim.Appearance_setCreaseAngle(self, creaseAngleRads)
[docs] def setSilhouette(self, radius: float, r: float=0, g: float=0, b: float=0, a: float=1) ->None: r""" For meshes sets a silhouette radius and color. Set the radius to 0 to disable silhouette drawing. Args: radius (float) r (float, optional): default value 0 g (float, optional): default value 0 b (float, optional): default value 0 a (float, optional): default value 1 """ return _robotsim.Appearance_setSilhouette(self, radius, r, g, b, a)
[docs] def drawGL(self, *args) ->None: r""" Draws the given geometry with this appearance. NOTE: for best performance, an appearance should only be drawn with a single geometry. Otherwise, the OpenGL display lists will be completely recreated. drawGL () drawGL (geom) Args: geom (:class:`~klampt.Geometry3D`, optional): Note that the geometry's current transform is NOT respected, and this only draws the geometry in its local transform. """ return _robotsim.Appearance_drawGL(self, *args)
[docs] def drawWorldGL(self, geom: "Geometry3D") ->None: r""" Draws the given geometry with this appearance. NOTE: for best performance, an appearance should only be drawn with a single geometry. Otherwise, the OpenGL display lists will be completely recreated. Args: geom (:class:`~klampt.Geometry3D`) Differs from drawGL in that the geometry's current transform is applied before drawing. """ return _robotsim.Appearance_drawWorldGL(self, geom)
world = property(_robotsim.Appearance_world_get, _robotsim.Appearance_world_set, doc=r"""world : int""") id = property(_robotsim.Appearance_id_get, _robotsim.Appearance_id_set, doc=r"""id : int""") appearancePtr = property(_robotsim.Appearance_appearancePtr_get, _robotsim.Appearance_appearancePtr_set, doc=r"""appearancePtr : p.void""")
[docs] def setTexture1D(self,format,array): """Sets a 1D texture. Args: format (str): describes how the array is specified. Valid values include: - '': turn off texture mapping - 'rgb8': unsigned byte RGB colors with red in the 1st column, green in the 2nd, blue in the 3rd. - 'bgr8': unsigned byte RGB colors with blue in the 1st column, green in the 2nd, green in the 3rd - 'rgba8': unsigned byte RGBA colors with red in the 1st column and alpha in the 4th - 'bgra8': unsigned byte RGBA colors with blue in the 1st column and alpha in the 4th - 'l8': unsigned byte grayscale colors, one channel array (np.ndarray): a 1D or 2D array, of size w or w x c where w is the width and c is the number of channels. Datatype is of type uint8, or for rgba8 / bgra8, can also be packed into uint32 elements. In this case, the pixel format is 0xaarrggbb or 0xaabbggrr, respectively. """ import numpy array = numpy.asarray(array) if array.shape == 1: if array.dtype == numpy.uint8: return self.setTexture1D_b(format,array) else: return self.setTexture1D_i(format,array) elif array.shape == 2: return self.setTexture1D_channels(format,array) else: raise ValueError("Can only pass a 1D or 2D array to setTexture1D")
[docs] def setTexture2D(self,format,array): """Sets a 2D texture. Args: format (str): describes how the array is specified. Valid values include: - '': turn off texture mapping - 'rgb8': unsigned byte RGB colors with red in the 1st column, green in the 2nd, blue in the 3rd. - 'bgr8': unsigned byte RGB colors with blue in the 1st column, green in the 2nd, green in the 3rd - 'rgba8': unsigned byte RGBA colors with red in the 1st column and alpha in the 4th - 'bgra8': unsigned byte RGBA colors with blue in the 1st column and alpha in the 4th - 'l8': unsigned byte grayscale colors, one channel array (np.ndarray): a 2D or 3D array, of size h x w or h x w x c where h is the height, w is the width, and c is the number of channels. Datatype is of type uint8, or for rgba8 / bgra8, can also be packed into uint32 elements. In this case, the pixel format is 0xaarrggbb or 0xaabbggrr, respectively. """ import numpy array = numpy.asarray(array) if array.shape == 2: if array.dtype == numpy.uint8: return self.setTexture2D_b(format,array) else: return self.setTexture2D_i(format,array) elif array.shape == 3: return self.setTexture2D_channels(format,array) else: raise ValueError("Can only pass a 2D or 3D array to setTexture2D")
[docs] def setTexcoords(self,array): """Sets texture coordinates for the mesh. Args: array (np.ndarray): a 1D or 2D array, of size N or Nx2, where N is the number of vertices in the mesh. """ import numpy array = numpy.asarray(array) if len(array.shape) == 1: return self.setTexcoords1D(array) elif len(array.shape) == 2: return self.setTexcoords2D(array) else: raise ValueError("Must provide either a 1D or 2D array")
# Register Appearance in _robotsim: _robotsim.Appearance_swigregister(Appearance)
[docs]class Viewport(object): r""" """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def fromJson(self, str: str) ->bool: r""" Args: str (str) """ return _robotsim.Viewport_fromJson(self, str) def toJson(self) ->str: r""" """ return _robotsim.Viewport_toJson(self) def setModelviewMatrix(self, M: Sequence[float]) ->None: r""" Args: M (:obj:`double [16]`) """ return _robotsim.Viewport_setModelviewMatrix(self, M) def setRigidTransform(self, R: Rotation, t: Point) ->None: r""" Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.Viewport_setRigidTransform(self, R, t) def getRigidTransform(self) ->None: r""" """ return _robotsim.Viewport_getRigidTransform(self) perspective = property(_robotsim.Viewport_perspective_get, _robotsim.Viewport_perspective_set, doc=r"""perspective : bool""") scale = property(_robotsim.Viewport_scale_get, _robotsim.Viewport_scale_set, doc=r"""scale : float""") x = property(_robotsim.Viewport_x_get, _robotsim.Viewport_x_set, doc=r"""x : int""") y = property(_robotsim.Viewport_y_get, _robotsim.Viewport_y_set, doc=r"""y : int""") w = property(_robotsim.Viewport_w_get, _robotsim.Viewport_w_set, doc=r"""w : int""") h = property(_robotsim.Viewport_h_get, _robotsim.Viewport_h_set, doc=r"""h : int""") n = property(_robotsim.Viewport_n_get, _robotsim.Viewport_n_set, doc=r"""n : double""") f = property(_robotsim.Viewport_f_get, _robotsim.Viewport_f_set, doc=r"""f : double""") xform = property(_robotsim.Viewport_xform_get, _robotsim.Viewport_xform_set, doc=r"""xform : std::vector<(double,std::allocator<(double)>)>""") def __init__(self): r""" """ _robotsim.Viewport_swiginit(self, _robotsim.new_Viewport()) __swig_destroy__ = _robotsim.delete_Viewport
# Register Viewport in _robotsim: _robotsim.Viewport_swigregister(Viewport)
[docs]class Widget(object): r""" """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.Widget_swiginit(self, _robotsim.new_Widget()) __swig_destroy__ = _robotsim.delete_Widget def hover(self, x: int, y: int, viewport: "Viewport") ->bool: r""" Args: x (int) y (int) viewport (:class:`~klampt.Viewport`) """ return _robotsim.Widget_hover(self, x, y, viewport) def beginDrag(self, x: int, y: int, viewport: "Viewport") ->bool: r""" Args: x (int) y (int) viewport (:class:`~klampt.Viewport`) """ return _robotsim.Widget_beginDrag(self, x, y, viewport) def drag(self, dx: int, dy: int, viewport: "Viewport") ->None: r""" Args: dx (int) dy (int) viewport (:class:`~klampt.Viewport`) """ return _robotsim.Widget_drag(self, dx, dy, viewport) def endDrag(self) ->None: r""" """ return _robotsim.Widget_endDrag(self) def keypress(self, c: str) ->None: r""" Args: c (str) """ return _robotsim.Widget_keypress(self, c) def drawGL(self, viewport: "Viewport") ->None: r""" Args: viewport (:class:`~klampt.Viewport`) """ return _robotsim.Widget_drawGL(self, viewport) def idle(self) ->None: r""" """ return _robotsim.Widget_idle(self) def wantsRedraw(self) ->bool: r""" """ return _robotsim.Widget_wantsRedraw(self) def hasHighlight(self) ->bool: r""" """ return _robotsim.Widget_hasHighlight(self) def hasFocus(self) ->bool: r""" """ return _robotsim.Widget_hasFocus(self) index = property(_robotsim.Widget_index_get, _robotsim.Widget_index_set, doc=r"""index : int""")
# Register Widget in _robotsim: _robotsim.Widget_swigregister(Widget)
[docs]class WidgetSet(Widget): r""" """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.WidgetSet_swiginit(self, _robotsim.new_WidgetSet()) def add(self, subwidget: "Widget") ->None: r""" Args: subwidget (:class:`~klampt.Widget`) """ return _robotsim.WidgetSet_add(self, subwidget) def remove(self, subwidget: "Widget") ->None: r""" Args: subwidget (:class:`~klampt.Widget`) """ return _robotsim.WidgetSet_remove(self, subwidget) def enable(self, subwidget: "Widget", enabled: bool) ->None: r""" Args: subwidget (:class:`~klampt.Widget`) enabled (bool) """ return _robotsim.WidgetSet_enable(self, subwidget, enabled) __swig_destroy__ = _robotsim.delete_WidgetSet
# Register WidgetSet in _robotsim: _robotsim.WidgetSet_swigregister(WidgetSet)
[docs]class PointPoser(Widget): r""" """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.PointPoser_swiginit(self, _robotsim.new_PointPoser()) def set(self, t: Point) ->None: r""" Args: t (:obj:`list of 3 floats`) """ return _robotsim.PointPoser_set(self, t) def get(self) ->None: r""" """ return _robotsim.PointPoser_get(self) def setAxes(self, R: Rotation) ->None: r""" Sets the reference axes (by default aligned to x,y,z) Args: R (:obj:`list of 9 floats (so3 element)`) """ return _robotsim.PointPoser_setAxes(self, R) def enableAxes(self, x: bool, y: bool, z: bool) ->None: r""" Args: x (bool) y (bool) z (bool) """ return _robotsim.PointPoser_enableAxes(self, x, y, z) __swig_destroy__ = _robotsim.delete_PointPoser
# Register PointPoser in _robotsim: _robotsim.PointPoser_swigregister(PointPoser)
[docs]class TransformPoser(Widget): r""" """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.TransformPoser_swiginit(self, _robotsim.new_TransformPoser()) def set(self, R: Rotation, t: Point) ->None: r""" Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.TransformPoser_set(self, R, t) def get(self) ->None: r""" """ return _robotsim.TransformPoser_get(self) def enableTranslation(self, arg2: bool) ->None: r""" Args: arg2 (bool) """ return _robotsim.TransformPoser_enableTranslation(self, arg2) def enableRotation(self, arg2: bool) ->None: r""" Args: arg2 (bool) """ return _robotsim.TransformPoser_enableRotation(self, arg2) def enableTranslationAxes(self, x: bool, y: bool, z: bool) ->None: r""" Args: x (bool) y (bool) z (bool) """ return _robotsim.TransformPoser_enableTranslationAxes(self, x, y, z) def enableRotationAxes(self, x: bool, y: bool, z: bool) ->None: r""" Args: x (bool) y (bool) z (bool) """ return _robotsim.TransformPoser_enableRotationAxes(self, x, y, z) __swig_destroy__ = _robotsim.delete_TransformPoser
# Register TransformPoser in _robotsim: _robotsim.TransformPoser_swigregister(TransformPoser)
[docs]class ObjectPoser(Widget): r""" """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, object: "RigidObjectModel"): r""" Args: object (:class:`~klampt.RigidObjectModel`) """ _robotsim.ObjectPoser_swiginit(self, _robotsim.new_ObjectPoser(object)) def set(self, R: Rotation, t: Point) ->None: r""" Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.ObjectPoser_set(self, R, t) def get(self) ->None: r""" """ return _robotsim.ObjectPoser_get(self) __swig_destroy__ = _robotsim.delete_ObjectPoser
# Register ObjectPoser in _robotsim: _robotsim.ObjectPoser_swigregister(ObjectPoser)
[docs]class RobotPoser(Widget): r""" """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, robot: "RobotModel"): r""" Args: robot (:class:`~klampt.RobotModel`) """ _robotsim.RobotPoser_swiginit(self, _robotsim.new_RobotPoser(robot)) def setActiveDofs(self, dofs: IntArray) ->None: r""" Args: dofs (:obj:`list of int`) """ return _robotsim.RobotPoser_setActiveDofs(self, dofs) def set(self, q: Vector) ->None: r""" Args: q (:obj:`list of floats`) """ return _robotsim.RobotPoser_set(self, q) def get(self) ->None: r""" """ return _robotsim.RobotPoser_get(self) def getConditioned(self, qref: Vector) ->None: r""" Args: qref (:obj:`list of floats`) """ return _robotsim.RobotPoser_getConditioned(self, qref) def addIKConstraint(self, obj: "IKObjective") ->None: r""" Args: obj (:class:`~klampt.IKObjective`) """ return _robotsim.RobotPoser_addIKConstraint(self, obj) def clearIKConstraints(self) ->None: r""" """ return _robotsim.RobotPoser_clearIKConstraints(self) __swig_destroy__ = _robotsim.delete_RobotPoser
# Register RobotPoser in _robotsim: _robotsim.RobotPoser_swigregister(RobotPoser) class AABBPoser(Widget): r""" """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.AABBPoser_swiginit(self, _robotsim.new_AABBPoser()) def set(self, bmin: Point, bmax: Point) ->None: r""" Args: bmin (:obj:`list of 3 floats`) bmax (:obj:`list of 3 floats`) """ return _robotsim.AABBPoser_set(self, bmin, bmax) def setFrame(self, R: Rotation, t: Point) ->None: r""" Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.AABBPoser_setFrame(self, R, t) def get(self) ->None: r""" """ return _robotsim.AABBPoser_get(self) __swig_destroy__ = _robotsim.delete_AABBPoser # Register AABBPoser in _robotsim: _robotsim.AABBPoser_swigregister(AABBPoser) class BoxPoser(Widget): r""" """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.BoxPoser_swiginit(self, _robotsim.new_BoxPoser()) def set(self, R: Rotation, t: Point, dims: Point) ->None: r""" Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) dims (:obj:`list of 3 floats`) """ return _robotsim.BoxPoser_set(self, R, t, dims) def setTransform(self, R: Rotation, t: Point) ->None: r""" Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.BoxPoser_setTransform(self, R, t) def setDims(self, dims: Point) ->None: r""" Args: dims (:obj:`list of 3 floats`) """ return _robotsim.BoxPoser_setDims(self, dims) def getTransform(self) ->None: r""" """ return _robotsim.BoxPoser_getTransform(self) def getDims(self) ->None: r""" """ return _robotsim.BoxPoser_getDims(self) __swig_destroy__ = _robotsim.delete_BoxPoser # Register BoxPoser in _robotsim: _robotsim.BoxPoser_swigregister(BoxPoser) class SpherePoser(Widget): r""" """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.SpherePoser_swiginit(self, _robotsim.new_SpherePoser()) def set(self, cr: Sequence[float]) ->None: r""" Args: cr (:obj:`double [4]`) """ return _robotsim.SpherePoser_set(self, cr) def get(self) ->None: r""" """ return _robotsim.SpherePoser_get(self) __swig_destroy__ = _robotsim.delete_SpherePoser # Register SpherePoser in _robotsim: _robotsim.SpherePoser_swigregister(SpherePoser)
[docs]class Mass(object): r""" Stores mass information for a rigid body or robot link. .. note:: Recommended to use the set/get functions rather than changing the members directly due to strangeness in SWIG's handling of vectors. Attributes: mass (float): the actual mass (typically in kg) com (list of 3 floats): the center of mass position, in local coordinates. inertia (list of 3 floats or 9 floats): the inertia matrix in local coordinates. If 3 floats, this is a diagonal matrix. If 9 floats, this gives all entries of the 3x3 inertia matrix (in column major or row major order, it doesn't matter since inertia matrices are symmetric) C++ includes: robotmodel.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.Mass_swiginit(self, _robotsim.new_Mass())
[docs] def setMass(self, _mass: float) ->None: r""" Args: _mass (float) """ return _robotsim.Mass_setMass(self, _mass)
[docs] def getMass(self) ->float: r""" """ return _robotsim.Mass_getMass(self)
[docs] def setCom(self, _com: Vector) ->None: r""" Args: _com (:obj:`list of floats`) """ return _robotsim.Mass_setCom(self, _com)
[docs] def getCom(self) ->None: r""" Returns the COM as a list of 3 floats. """ return _robotsim.Mass_getCom(self)
[docs] def setInertia(self, _inertia: Vector) ->None: r""" Sets an inertia matrix. Args: _inertia (:obj:`list of floats`) """ return _robotsim.Mass_setInertia(self, _inertia)
[docs] def getInertia(self) ->None: r""" Returns the inertia matrix as a list of 3 floats or 9 floats. """ return _robotsim.Mass_getInertia(self)
[docs] def estimate(self, g: "Geometry3D", mass: float, surfaceFraction: float=0) ->None: r""" Estimates the com and inertia of a geometry, with a given total mass. Args: g (:class:`~klampt.Geometry3D`) mass (float) surfaceFraction (float, optional): default value 0 For TriangleMesh types, surfaceFraction dictates how much of the object's mass is concentrated at the surface rather than the interior. """ return _robotsim.Mass_estimate(self, g, mass, surfaceFraction)
mass = property(_robotsim.Mass_mass_get, _robotsim.Mass_mass_set, doc=r"""mass : double""") com = property(_robotsim.Mass_com_get, _robotsim.Mass_com_set, doc=r"""com : std::vector<(double,std::allocator<(double)>)>""") inertia = property(_robotsim.Mass_inertia_get, _robotsim.Mass_inertia_set, doc=r"""inertia : std::vector<(double,std::allocator<(double)>)>""") com = property(getCom, setCom) inertia = property(getInertia, setInertia) __swig_destroy__ = _robotsim.delete_Mass
# Register Mass in _robotsim: _robotsim.Mass_swigregister(Mass)
[docs]class ContactParameters(object): r""" Stores contact parameters for an entity. Currently only used for simulation, but could be used for contact mechanics in the future. Attributes: kFriction (float): The coefficient of (Coulomb) friction, in range [0,inf). kRestitution (float): The coefficient of restitution, in range [0,1]. kStiffness (float): The stiffness of the material, in range (0,inf) (default inf, perfectly rigid). kDamping (float): The damping of the material, in range (0,inf) (default inf, perfectly rigid). C++ includes: robotmodel.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.ContactParameters_swiginit(self, _robotsim.new_ContactParameters()) kFriction = property(_robotsim.ContactParameters_kFriction_get, _robotsim.ContactParameters_kFriction_set, doc=r"""kFriction : double""") kRestitution = property(_robotsim.ContactParameters_kRestitution_get, _robotsim.ContactParameters_kRestitution_set, doc=r"""kRestitution : double""") kStiffness = property(_robotsim.ContactParameters_kStiffness_get, _robotsim.ContactParameters_kStiffness_set, doc=r"""kStiffness : double""") kDamping = property(_robotsim.ContactParameters_kDamping_get, _robotsim.ContactParameters_kDamping_set, doc=r"""kDamping : double""") __swig_destroy__ = _robotsim.delete_ContactParameters
# Register ContactParameters in _robotsim: _robotsim.ContactParameters_swigregister(ContactParameters) # Register RobotModelLink in _robotsim: _robotsim.RobotModelLink_swigregister(RobotModelLink) class RobotModelDriver(object): r""" A reference to a driver of a RobotModel. A driver corresponds to one of the robot's actuators and encodes how its forces are transmitted to joints. A RobotModelDriver is not created by hand, but instead accessed using :meth:`RobotModel.driver` (index or name) C++ includes: robotmodel.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.RobotModelDriver_swiginit(self, _robotsim.new_RobotModelDriver()) def getName(self) ->str: r""" """ return _robotsim.RobotModelDriver_getName(self) def setName(self, name: str) ->None: r""" Sets the name of the driver. Args: name (str) """ return _robotsim.RobotModelDriver_setName(self, name) def robot(self) -> "RobotModel": r""" Returns a reference to the driver's robot. """ return _robotsim.RobotModelDriver_robot(self) def getType(self) ->str: r""" Gets the type of the driver. Returns: One of "normal", "affine", "rotation", "translation", or "custom" """ return _robotsim.RobotModelDriver_getType(self) def getAffectedLink(self) ->int: r""" Returns the single affected link for "normal" links. """ return _robotsim.RobotModelDriver_getAffectedLink(self) def getAffectedLinks(self) ->None: r""" Returns the indices of the driver's affected links. """ return _robotsim.RobotModelDriver_getAffectedLinks(self) def getAffineCoeffs(self) ->None: r""" For "affine" links, returns the scale and offset of the driver value mapped to the world. Returns a pair (scale,offset), each of length len(getAffectedLinks()). """ return _robotsim.RobotModelDriver_getAffineCoeffs(self) def setValue(self, val: float) ->None: r""" Sets the robot's config to correspond to the given driver value. Args: val (float) .. note:: Does not update the links' forward kinematics. Use robot.setConfig(robot.getConfig()) to update the forward kinematics. """ return _robotsim.RobotModelDriver_setValue(self, val) def getValue(self) ->float: r""" Returns the current driver value from the robot's config. """ return _robotsim.RobotModelDriver_getValue(self) def setVelocity(self, val: float) ->None: r""" Sets the robot's velocity to correspond to the given driver velocity value. Args: val (float) """ return _robotsim.RobotModelDriver_setVelocity(self, val) def getVelocity(self) ->float: r""" Returns the current driver velocity value from the robot's velocity. """ return _robotsim.RobotModelDriver_getVelocity(self) def getLimits(self) ->None: r""" Returns value limits [xmin,xmax]. """ return _robotsim.RobotModelDriver_getLimits(self) def getVelocityLimits(self) ->None: r""" Returns velocity limits [vmin,vmax]. """ return _robotsim.RobotModelDriver_getVelocityLimits(self) def getAccelerationLimits(self) ->None: r""" Returns acceleration limits [amin,amax]. """ return _robotsim.RobotModelDriver_getAccelerationLimits(self) def getTorqueLimits(self) ->None: r""" Returns generalized torque limits [tmin,tmax]. """ return _robotsim.RobotModelDriver_getTorqueLimits(self) world = property(_robotsim.RobotModelDriver_world_get, _robotsim.RobotModelDriver_world_set, doc=r"""world : int""") robotIndex = property(_robotsim.RobotModelDriver_robotIndex_get, _robotsim.RobotModelDriver_robotIndex_set, doc=r"""robotIndex : int""") robotPtr = property(_robotsim.RobotModelDriver_robotPtr_get, _robotsim.RobotModelDriver_robotPtr_set, doc=r"""robotPtr : p.Klampt::RobotModel""") index = property(_robotsim.RobotModelDriver_index_get, _robotsim.RobotModelDriver_index_set, doc=r"""index : int""") name = property(getName, setName) type = property(getType) affectedLink = property(getAffectedLink) affectedLinks = property(getAffectedLinks) value = property(getValue, setValue) velocity = property(getVelocity, setVelocity) __swig_destroy__ = _robotsim.delete_RobotModelDriver # Register RobotModelDriver in _robotsim: _robotsim.RobotModelDriver_swigregister(RobotModelDriver)
[docs]class RobotModel(object): r""" A model of a dynamic and kinematic robot. Stores both constant information, like the reference placement of the links, joint limits, velocity limits, etc, as well as a *current configuration* and *current velocity* which are state-dependent. Several functions depend on the robot's current configuration and/or velocity. To update that, use the setConfig() and setVelocity() functions. setConfig() also update's the robot's link transforms via forward kinematics. You may also use setDOFPosition and setDOFVelocity for individual changes, but these are more expensive because each call updates all of the affected the link transforms. It is important to understand that changing the configuration of the model doesn't actually send a command to the physical / simulated robot. Moreover, the model does not automatically get updated when the physical / simulated robot moves. In essence, the model maintains temporary storage for performing kinematics, dynamics, and planning computations, as well as for visualization. The state of the robot is retrieved using getConfig/getVelocity calls, and is set using setConfig/setVelocity. Because many routines change the robot's configuration, like IK and motion planning, a common design pattern is to save/restore the configuration as follows:: q = robot.getConfig() do some stuff that may touch the robot's configuration... robot.setConfig(q) The model maintains configuration/velocity/acceleration/torque limits. However, these are not enforced by the model, so you can happily set configurations outside the limits. Valid commands must rather be enforced by the planner / controller / simulator. As elsewhere in Klampt, the mapping between links and drivers is not one-to one. A driver is essentially an actuator and transmission, and for most links a link is driven by a unique driver (e.g., a motor and gearbox). However, there do exist certain cases in which a link is not driven at all (e.g., the 6 virtual links of a floating-base robot), or multiple links are driven by a single actuator (e.g., a parallel-bar mechanism or a compliant hand). There are also unusual drivers that introduce underactuated dynamics into the system, such as a differential drive or Dubin's car mobile base. Care must be taken when sending commands to motor controllers (e.g., Klampt Robot Interface Layer), which often work in the actuator space rather than joint space. (See :func:`configToDrivers`, :func:`configFromDrivers`, :func:`velocityToDrivers`, :func:`velocityFromDrivers`). C++ includes: robotmodel.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.RobotModel_swiginit(self, _robotsim.new_RobotModel())
[docs] def loadFile(self, fn: str) ->bool: r""" Loads the robot from the file fn. Args: fn (str) Returns: True if successful, False if failed. """ return _robotsim.RobotModel_loadFile(self, fn)
[docs] def saveFile(self, fn: str, geometryPrefix: str=None) ->bool: r""" Saves the robot to the file fn. Args: fn (str) geometryPrefix (str, optional): default value None If `geometryPrefix == None` (default), the geometry is not saved. Otherwise, the geometry of each link will be saved to files named `geometryPrefix+name`, where `name` is either the name of the geometry file that was loaded, or `[link_name].off` """ return _robotsim.RobotModel_saveFile(self, fn, geometryPrefix)
[docs] def getID(self) ->int: r""" Returns the ID of the robot in its world. .. note:: The world ID is not the same as the robot index. """ return _robotsim.RobotModel_getID(self)
[docs] def getName(self) ->str: r""" """ return _robotsim.RobotModel_getName(self)
[docs] def setName(self, name: str) ->None: r""" Sets the name of the robot. Args: name (str) """ return _robotsim.RobotModel_setName(self, name)
[docs] def numDrivers(self) ->int: r""" Returns the number of drivers. """ return _robotsim.RobotModel_numDrivers(self)
[docs] def driver(self, *args) -> "RobotModelDriver": r""" Returns a reference to the driver by index or name. driver (index): :class:`~klampt.RobotModelDriver` driver (name): :class:`~klampt.RobotModelDriver` Args: index (int, optional): name (str, optional): Returns: :class:`~klampt.RobotModelDriver`: """ return _robotsim.RobotModel_driver(self, *args)
[docs] def getJointType(self, *args) ->str: r""" Returns the joint type of the joint connecting the link to its parent, where the link is identified by index or by name. getJointType (index): str getJointType (name): str Args: index (int, optional): name (str, optional): Returns: str: """ return _robotsim.RobotModel_getJointType(self, *args)
[docs] def getConfig(self) ->None: r""" Retrieves the current configuration of the robot model. """ return _robotsim.RobotModel_getConfig(self)
[docs] def getVelocity(self) ->None: r""" Retreives the current velocity of the robot model. """ return _robotsim.RobotModel_getVelocity(self)
[docs] def setConfig(self, q: Vector) ->None: r""" Sets the current configuration of the robot. Input q is a vector of length numLinks(). This also updates forward kinematics of all links. Args: q (:obj:`list of floats`) Again, it is important to realize that the RobotModel is not the same as a simulated robot, and this will not change the simulation world. Many functions such as IK and motion planning use the RobotModel configuration as a temporary variable, so if you need to keep the configuration through a robot-modifying function call, you should call `q = robot.getConfig()` before the call, and then `robot.setConfig(q)` after it. """ return _robotsim.RobotModel_setConfig(self, q)
[docs] def setVelocity(self, dq: Vector) ->None: r""" Sets the current velocity of the robot model. Like the configuration, this is also essentially a temporary variable. Args: dq (:obj:`list of floats`) """ return _robotsim.RobotModel_setVelocity(self, dq)
[docs] def getJointLimits(self) ->None: r""" Returns a pair (qmin,qmax) of min/max joint limit vectors. """ return _robotsim.RobotModel_getJointLimits(self)
[docs] def setJointLimits(self, qmin: Vector, qmax: Vector) ->None: r""" Sets the min/max joint limit vectors (must have length numLinks()) Args: qmin (:obj:`list of floats`) qmax (:obj:`list of floats`) """ return _robotsim.RobotModel_setJointLimits(self, qmin, qmax)
[docs] def getVelocityLimits(self) ->None: r""" Returns the velocity limit vector vmax, the constraint is :math:`|dq[i]| \leq vmax[i]` """ return _robotsim.RobotModel_getVelocityLimits(self)
[docs] def setVelocityLimits(self, vmax: Vector) ->None: r""" Sets the velocity limit vector vmax, the constraint is :math:`|dq[i]| \leq vmax[i]` Args: vmax (:obj:`list of floats`) """ return _robotsim.RobotModel_setVelocityLimits(self, vmax)
[docs] def getAccelerationLimits(self) ->None: r""" Returns the acceleration limit vector amax, the constraint is :math:`|ddq[i]| \leq amax[i]` """ return _robotsim.RobotModel_getAccelerationLimits(self)
[docs] def setAccelerationLimits(self, amax: Vector) ->None: r""" Sets the acceleration limit vector amax, the constraint is :math:`|ddq[i]| \leq amax[i]` Args: amax (:obj:`list of floats`) """ return _robotsim.RobotModel_setAccelerationLimits(self, amax)
[docs] def getTorqueLimits(self) ->None: r""" Returns the torque limit vector tmax, the constraint is :math:`|torque[i]| \leq tmax[i]` """ return _robotsim.RobotModel_getTorqueLimits(self)
[docs] def setTorqueLimits(self, tmax: Vector) ->None: r""" Sets the torque limit vector tmax, the constraint is :math:`|torque[i]| \leq tmax[i]` Args: tmax (:obj:`list of floats`) """ return _robotsim.RobotModel_setTorqueLimits(self, tmax)
[docs] def setDOFPosition(self, *args) ->None: r""" Sets a single DOF's position (by index or by name). setDOFPosition (i,qi) setDOFPosition (name,qi) Args: i (int, optional): qi (float): name (str, optional): .. note:: If you are setting several joints at once, use setConfig because this function computes forward kinematics for all descendant links each time it is called. """ return _robotsim.RobotModel_setDOFPosition(self, *args)
[docs] def getDOFPosition(self, *args) ->float: r""" Returns a single DOF's position (by name) getDOFPosition (i): float getDOFPosition (name): float Args: i (int, optional): name (str, optional): Returns: float: """ return _robotsim.RobotModel_getDOFPosition(self, *args)
[docs] def getCom(self) ->None: r""" Returns the 3D center of mass at the current config. """ return _robotsim.RobotModel_getCom(self)
[docs] def getComVelocity(self) ->None: r""" Returns the 3D velocity of the center of mass at the current config / velocity. """ return _robotsim.RobotModel_getComVelocity(self)
[docs] def getComJacobian(self) ->None: r""" Computes the Jacobian matrix of the current center of mass. Returns: ndarray: a 3xn matrix J such that np.dot(J,dq) gives the COM velocity at the currene configuration """ return _robotsim.RobotModel_getComJacobian(self)
[docs] def getComJacobianCols(self, links: IntArray) ->None: r""" Returns the Jacobian matrix of the current center of mass w.r.t. some links of the robot. Args: links (:obj:`list of int`) Returns: ndarray: a 3xlen(links) matrix J such that np.dot(J,dqlinks) gives the COM velocity at the current configuration, and dqlinks is the array of velocities of the links given by `links` """ return _robotsim.RobotModel_getComJacobianCols(self, links)
[docs] def getLinearMomentum(self) ->None: r""" Computes the 3D linear momentum vector. """ return _robotsim.RobotModel_getLinearMomentum(self)
[docs] def getAngularMomentum(self) ->None: r""" Computes the 3D angular momentum vector. """ return _robotsim.RobotModel_getAngularMomentum(self)
[docs] def getKineticEnergy(self) ->float: r""" Computes the kinetic energy at the current config / velocity. """ return _robotsim.RobotModel_getKineticEnergy(self)
[docs] def getTotalInertia(self) ->None: r""" Computes the 3x3 total inertia matrix of the robot. """ return _robotsim.RobotModel_getTotalInertia(self)
[docs] def getMassMatrix(self) ->None: r""" Computes the nxn mass matrix B(q). Takes O(n^2) time """ return _robotsim.RobotModel_getMassMatrix(self)
[docs] def getMassMatrixInv(self) ->None: r""" Computes the inverse of the nxn mass matrix B(q)^-1. Takes O(n^2) time, which is much faster than inverting the result of getMassMatrix """ return _robotsim.RobotModel_getMassMatrixInv(self)
[docs] def getMassMatrixDeriv(self, i: int) ->None: r""" Computes the derivative of the nxn mass matrix with respect to q_i. Args: i (int) Takes O(n^3) time. """ return _robotsim.RobotModel_getMassMatrixDeriv(self, i)
[docs] def getMassMatrixTimeDeriv(self) ->None: r""" Computes the derivative of the nxn mass matrix with respect to t, given the robot's current velocity. Takes O(n^4) time. """ return _robotsim.RobotModel_getMassMatrixTimeDeriv(self)
[docs] def getCoriolisForceMatrix(self) ->None: r""" Computes the Coriolis force matrix C(q,dq) for current config and velocity. Takes O(n^2) time. """ return _robotsim.RobotModel_getCoriolisForceMatrix(self)
[docs] def getCoriolisForces(self) ->None: r""" Computes the Coriolis forces C(q,dq)*dq for current config and velocity. Takes O(n) time, which is faster than computing matrix and doing the product. ("Forces" is somewhat of a misnomer; the result is a joint torque vector) """ return _robotsim.RobotModel_getCoriolisForces(self)
[docs] def getGravityForces(self, g: Point) ->None: r""" Computes the generalized gravity vector G(q) for the given workspace gravity vector g (usually (0,0,-9.8)). Args: g (:obj:`list of 3 floats`) .. note:: "Forces" is somewhat of a misnomer; the result is a vector of joint torques. Returns: list of floats: the n-element generalized gravity vector at the robot's current configuration. """ return _robotsim.RobotModel_getGravityForces(self, g)
[docs] def torquesFromAccel(self, ddq: Vector) ->None: r""" Computes the inverse dynamics. Uses Recursive Newton Euler solver and takes O(n) time. Args: ddq (:obj:`list of floats`) Specifically, solves for :math:`\tau` in the (partial) dynamics equation: .. math:: `B(q) \ddot{q} + C(q,@dot {q}) = \tau` .. note:: Does not include gravity term G(q). getGravityForces(g) will need to be added to the result. Returns: list of floats: the n-element torque vector that would produce the joint accelerations ddq in the absence of external forces. """ return _robotsim.RobotModel_torquesFromAccel(self, ddq)
[docs] def accelFromTorques(self, t: Vector) ->None: r""" Computes the foward dynamics. Uses Recursive Newton Euler solver and takes O(n) time. Args: t (:obj:`list of floats`) Specifically, solves for :math:`\ddot{q}` in the (partial) dynamics equation: .. math:: `B(q) \ddot{q} + C(q,@dot {q}) = \tau` .. note:: Does not include gravity term G(q). getGravityForces(g) will need to be subtracted from the argument t. Returns: list of floats: the n-element joint acceleration vector that would result from joint torques t in the absence of external forces. """ return _robotsim.RobotModel_accelFromTorques(self, t)
[docs] def interpolate(self, a: Vector, b: Vector, u: float) ->None: r""" Interpolates smoothly between two configurations, properly taking into account nonstandard joints. Args: a (:obj:`list of floats`) b (:obj:`list of floats`) u (float) Returns: The n-element configuration that is u fraction of the way from a to b. """ return _robotsim.RobotModel_interpolate(self, a, b, u)
[docs] def distance(self, a: Vector, b: Vector) ->float: r""" Computes a distance between two configurations, properly taking into account nonstandard joints. Args: a (:obj:`list of floats`) b (:obj:`list of floats`) """ return _robotsim.RobotModel_distance(self, a, b)
[docs] def interpolateDeriv(self, a: Vector, b: Vector) ->None: r""" Returns the configuration derivative at a as you interpolate toward b at unit speed. Args: a (:obj:`list of floats`) b (:obj:`list of floats`) """ return _robotsim.RobotModel_interpolateDeriv(self, a, b)
[docs] def randomizeConfig(self, unboundedScale: float=1.0) ->None: r""" Samples a random configuration and updates the robot's pose. Properly handles non-normal joints and handles DOFs with infinite bounds using a centered Laplacian distribution with the given scaling term. Args: unboundedScale (float, optional): default value 1.0 .. note:: Python random module seeding does not affect the result. """ return _robotsim.RobotModel_randomizeConfig(self, unboundedScale)
[docs] def configToDrivers(self, config: Vector) ->None: r""" Converts a full configuration (length numLinks()) to a list of driver values (length numDrivers()). Args: config (:obj:`list of floats`) """ return _robotsim.RobotModel_configToDrivers(self, config)
[docs] def velocityToDrivers(self, velocities: Vector) ->None: r""" Converts a full velocity vector (length numLinks()) to a list of driver velocities (length numDrivers()). Args: velocities (:obj:`list of floats`) """ return _robotsim.RobotModel_velocityToDrivers(self, velocities)
[docs] def configFromDrivers(self, driverValues: Vector) ->None: r""" Converts a list of driver values (length numDrivers()) to a full configuration (length numLinks()). Args: driverValues (:obj:`list of floats`) """ return _robotsim.RobotModel_configFromDrivers(self, driverValues)
[docs] def velocityFromDrivers(self, driverVelocities: Vector) ->None: r""" Converts a list of driver velocities (length numDrivers()) to a full velocity vector (length numLinks()). Args: driverVelocities (:obj:`list of floats`) """ return _robotsim.RobotModel_velocityFromDrivers(self, driverVelocities)
[docs] def selfCollisionEnabled(self, link1: int, link2: int) ->bool: r""" Queries whether self collisions between two links is enabled. Args: link1 (int) link2 (int) """ return _robotsim.RobotModel_selfCollisionEnabled(self, link1, link2)
[docs] def enableSelfCollision(self, link1: int, link2: int, value: bool) ->None: r""" Enables/disables self collisions between two links (depending on value) Args: link1 (int) link2 (int) value (bool) """ return _robotsim.RobotModel_enableSelfCollision(self, link1, link2, value)
[docs] def selfCollides(self) ->bool: r""" Returns true if the robot is in self collision (faster than manual testing) """ return _robotsim.RobotModel_selfCollides(self)
[docs] def drawGL(self, keepAppearance: bool=True) ->None: r""" Draws the robot geometry. If keepAppearance=true, the current appearance is honored. Otherwise, only the raw geometry is drawn. Args: keepAppearance (bool, optional): default value True PERFORMANCE WARNING: if keepAppearance is false, then this does not properly reuse OpenGL display lists. A better approach to changing the robot's appearances is to set the link Appearance's directly. """ return _robotsim.RobotModel_drawGL(self, keepAppearance)
[docs] def reduce(self, robot: "RobotModel") ->None: r""" Sets self to a reduced version of robot, where all fixed DOFs are eliminated. The return value is a map from the original robot DOF indices to the reduced DOFs. Args: robot (:class:`~klampt.RobotModel`) Note that any geometries fixed to the world will disappear. """ return _robotsim.RobotModel_reduce(self, robot)
[docs] def mount(self, link: int, subRobot: "RobotModel", R: Rotation, t: Point) ->None: r""" Mounts a sub-robot onto a link, with its origin at a given local transform (R,t). The sub-robot's links will be renamed to subRobot.getName() + ':' + link.getName() unless subRobot.getName() is '', in which case the link names are preserved. Args: link (int) subRobot (:class:`~klampt.RobotModel`) R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.RobotModel_mount(self, link, subRobot, R, t)
[docs] def sensor(self, *args) -> "SimRobotSensor": r""" Returns a sensor by index or by name. sensor (index): :class:`~klampt.SimRobotSensor` sensor (name): :class:`~klampt.SimRobotSensor` Args: index (int, optional): name (str, optional): Returns: :class:`~klampt.SimRobotSensor`: If out of bounds or unavailable, a null sensor is returned (i.e., SimRobotSensor.name() or SimRobotSensor.type()) will return the empty string.) """ return _robotsim.RobotModel_sensor(self, *args)
[docs] def addSensor(self, name: str, type: str) -> "SimRobotSensor": r""" Adds a new sensor with a given name and type. Args: name (str) type (str) Returns: The new sensor. """ return _robotsim.RobotModel_addSensor(self, name, type)
world = property(_robotsim.RobotModel_world_get, _robotsim.RobotModel_world_set, doc=r"""world : int""") index = property(_robotsim.RobotModel_index_get, _robotsim.RobotModel_index_set, doc=r"""index : int""") robot = property(_robotsim.RobotModel_robot_get, _robotsim.RobotModel_robot_set, doc=r"""robot : p.Klampt::RobotModel""") dirty_dynamics = property(_robotsim.RobotModel_dirty_dynamics_get, _robotsim.RobotModel_dirty_dynamics_set, doc=r"""dirty_dynamics : bool""") name = property(getName, setName) id = property(getID) config = property(getConfig,setConfig) velocity = property(getVelocity,setVelocity) __swig_destroy__ = _robotsim.delete_RobotModel
# Register RobotModel in _robotsim: _robotsim.RobotModel_swigregister(RobotModel)
[docs]class RigidObjectModel(object): r""" A rigid movable object. A rigid object has a name, geometry, appearance, mass, surface properties, and current transform / velocity. State is retrieved/set using get/setTransform, and get/setVelocity C++ includes: robotmodel.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.RigidObjectModel_swiginit(self, _robotsim.new_RigidObjectModel())
[docs] def loadFile(self, fn: str) ->bool: r""" Loads the object from the file fn. Args: fn (str) """ return _robotsim.RigidObjectModel_loadFile(self, fn)
[docs] def saveFile(self, fn: str, geometryName: str=None) ->bool: r""" Saves the object to the file fn. If geometryName is given, the geometry is saved to that file. Args: fn (str) geometryName (str, optional): default value None """ return _robotsim.RigidObjectModel_saveFile(self, fn, geometryName)
[docs] def getID(self) ->int: r""" Returns the ID of the rigid object in its world. .. note:: The world ID is not the same as the rigid object index. """ return _robotsim.RigidObjectModel_getID(self)
[docs] def getName(self) ->str: r""" """ return _robotsim.RigidObjectModel_getName(self)
[docs] def setName(self, name: str) ->None: r""" Args: name (str) """ return _robotsim.RigidObjectModel_setName(self, name)
[docs] def geometry(self) -> "Geometry3D": r""" Returns a reference to the geometry associated with this object. """ return _robotsim.RigidObjectModel_geometry(self)
[docs] def appearance(self) -> "Appearance": r""" Returns a reference to the appearance associated with this object. """ return _robotsim.RigidObjectModel_appearance(self)
[docs] def getMass(self) -> "Mass": r""" Returns a copy of the Mass of this rigid object. .. note:: To change the mass properties, you should call ``m=object.getMass()``, change the desired properties in m, and then ``object.setMass(m)`` """ return _robotsim.RigidObjectModel_getMass(self)
[docs] def setMass(self, mass: "Mass") ->None: r""" Args: mass (:class:`~klampt.Mass`) """ return _robotsim.RigidObjectModel_setMass(self, mass)
[docs] def getContactParameters(self) -> "ContactParameters": r""" Returns a copy of the ContactParameters of this rigid object. .. note:: To change the contact parameters, you should call ``p=object.getContactParameters()``, change the desired properties in p, and then call ``object.setContactParameters(p)`` """ return _robotsim.RigidObjectModel_getContactParameters(self)
[docs] def setContactParameters(self, params: "ContactParameters") ->None: r""" Args: params (:class:`~klampt.ContactParameters`) """ return _robotsim.RigidObjectModel_setContactParameters(self, params)
[docs] def getTransform(self) ->None: r""" Retrieves the rotation / translation of the rigid object (R,t) Returns: se3 object: a pair (R,t), with R a 9-list and t a 3-list of floats, giving the transform to world coordinates. """ return _robotsim.RigidObjectModel_getTransform(self)
[docs] def setTransform(self, R: Rotation, t: Point) ->None: r""" Sets the rotation / translation (R,t) of the rigid object. Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.RigidObjectModel_setTransform(self, R, t)
[docs] def getVelocity(self) ->None: r""" Retrieves the (angular velocity, velocity) of the rigid object. Returns: A pair of 3-lists (w,v) where w is the angular velocity vector and v is the translational velocity vector (both in world coordinates) """ return _robotsim.RigidObjectModel_getVelocity(self)
[docs] def setVelocity(self, angularVelocity: Point, velocity: Point) ->None: r""" Sets the (angular velocity, velocity) of the rigid object. Args: angularVelocity (:obj:`list of 3 floats`) velocity (:obj:`list of 3 floats`) """ return _robotsim.RigidObjectModel_setVelocity(self, angularVelocity, velocity)
[docs] def drawGL(self, keepAppearance: bool=True) ->None: r""" Draws the object's geometry. If keepAppearance=true, the current appearance is honored. Otherwise, only the raw geometry is drawn. Args: keepAppearance (bool, optional): default value True PERFORMANCE WARNING: if keepAppearance is false, then this does not properly reuse OpenGL display lists. A better approach is to change the object's Appearance directly. """ return _robotsim.RigidObjectModel_drawGL(self, keepAppearance)
world = property(_robotsim.RigidObjectModel_world_get, _robotsim.RigidObjectModel_world_set, doc=r"""world : int""") index = property(_robotsim.RigidObjectModel_index_get, _robotsim.RigidObjectModel_index_set, doc=r"""index : int""") object = property(_robotsim.RigidObjectModel_object_get, _robotsim.RigidObjectModel_object_set, doc=r"""object : p.Klampt::RigidObjectModel""") __swig_destroy__ = _robotsim.delete_RigidObjectModel
# Register RigidObjectModel in _robotsim: _robotsim.RigidObjectModel_swigregister(RigidObjectModel)
[docs]class TerrainModel(object): r""" Static environment geometry. C++ includes: robotmodel.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.TerrainModel_swiginit(self, _robotsim.new_TerrainModel())
[docs] def loadFile(self, fn: str) ->bool: r""" Loads the terrain from the file fn. Args: fn (str) """ return _robotsim.TerrainModel_loadFile(self, fn)
[docs] def saveFile(self, fn: str, geometryName: str=None) ->bool: r""" Saves the terrain to the file fn. If geometryName is given, the geometry is saved to that file. Args: fn (str) geometryName (str, optional): default value None """ return _robotsim.TerrainModel_saveFile(self, fn, geometryName)
[docs] def getID(self) ->int: r""" Returns the ID of the terrain in its world. .. note:: The world ID is not the same as the terrain index. """ return _robotsim.TerrainModel_getID(self)
[docs] def getName(self) ->str: r""" """ return _robotsim.TerrainModel_getName(self)
[docs] def setName(self, name: str) ->None: r""" Args: name (str) """ return _robotsim.TerrainModel_setName(self, name)
[docs] def geometry(self) -> "Geometry3D": r""" Returns a reference to the geometry associated with this object. """ return _robotsim.TerrainModel_geometry(self)
[docs] def appearance(self) -> "Appearance": r""" Returns a reference to the appearance associated with this object. """ return _robotsim.TerrainModel_appearance(self)
[docs] def setFriction(self, friction: float) ->None: r""" Changes the friction coefficient for this terrain. Args: friction (float) """ return _robotsim.TerrainModel_setFriction(self, friction)
[docs] def drawGL(self, keepAppearance: bool=True) ->None: r""" Draws the object's geometry. If keepAppearance=true, the current appearance is honored. Otherwise, only the raw geometry is drawn. Args: keepAppearance (bool, optional): default value True PERFORMANCE WARNING: if keepAppearance is false, then this does not properly reuse OpenGL display lists. A better approach is to change the object's Appearance directly. """ return _robotsim.TerrainModel_drawGL(self, keepAppearance)
world = property(_robotsim.TerrainModel_world_get, _robotsim.TerrainModel_world_set, doc=r"""world : int""") index = property(_robotsim.TerrainModel_index_get, _robotsim.TerrainModel_index_set, doc=r"""index : int""") terrain = property(_robotsim.TerrainModel_terrain_get, _robotsim.TerrainModel_terrain_set, doc=r"""terrain : p.Klampt::TerrainModel""") __swig_destroy__ = _robotsim.delete_TerrainModel
# Register TerrainModel in _robotsim: _robotsim.TerrainModel_swigregister(TerrainModel)
[docs]class WorldModel(object): r""" The main world class, containing robots, rigid objects, and static environment geometry. .. note: Although a WorldModel instance is typically called a "world" it is just a model and does not have to reflect the state of a physical world. The state of robots and objects in the world can be changed at will -- in fact planners and simulators will query and modify the state of a WorldModel during their operation. To keep around some "authoritative" world, you can keep around a copy (use ``WorldModel.copy()``) or ``config.getConfig(world)`` using the :mod:`klampt.model.config` module. Every robot/robot link/terrain/rigid object is given a unique ID in the world. This is potentially a source of confusion because some functions take IDs and some take indices. Only the WorldModel and Simulator classes use IDs when the argument has 'id' as a suffix, e.g., geometry(), appearance(), Simulator.inContact(). All other functions use indices, e.g. robot(0), terrain(0), etc. To get an object's ID, you can see the value returned by loadElement and/or object.getID(). states. To save/restore the state of the model, you must manually maintain copies of the states of whichever objects you wish to save/restore. C++ includes: robotmodel.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" Creates a WorldModel. __init__ (): :class:`~klampt.WorldModel` __init__ (ptrRobotWorld): :class:`~klampt.WorldModel` __init__ (w): :class:`~klampt.WorldModel` __init__ (fn): :class:`~klampt.WorldModel` Args: ptrRobotWorld (:obj:`void *`, optional): w (:class:`~klampt.WorldModel`, optional): fn (str, optional): * Given no arguments, creates a new world. * Given another WorldModel instance, creates a reference to an existing world. (To create a copy, use the copy() method.) * Given a string, loads from a file. A PyException is raised on failure. * Given a pointer to a C++ RobotWorld structure, a reference to that structure is returned. (This is advanced usage, seen only when interfacing C++ and Python code) """ _robotsim.WorldModel_swiginit(self, _robotsim.new_WorldModel(*args)) __swig_destroy__ = _robotsim.delete_WorldModel
[docs] def copy(self) -> "WorldModel": r""" Creates a copy of the world model. Note that geometries and appearances are shared, so this is very quick. """ return _robotsim.WorldModel_copy(self)
[docs] def readFile(self, fn: str) ->bool: r""" Reads from a world XML file. Args: fn (str) Returns: True if successful, False if failed. """ return _robotsim.WorldModel_readFile(self, fn)
[docs] def loadFile(self, fn: str) ->bool: r""" Alias of readFile. Args: fn (str) """ return _robotsim.WorldModel_loadFile(self, fn)
[docs] def saveFile(self, fn: str, elementDir: str=None) ->bool: r""" Saves to a world XML file. If elementDir is provided, then robots, terrains, etc. will be saved there. Otherwise they will be saved to a folder with the same base name as fn (without the trailing .xml) Args: fn (str) elementDir (str, optional): default value None """ return _robotsim.WorldModel_saveFile(self, fn, elementDir)
[docs] def numRobots(self) ->int: r""" Returns the number of robots. """ return _robotsim.WorldModel_numRobots(self)
[docs] def numRigidObjects(self) ->int: r""" Returns the number of rigid objects. """ return _robotsim.WorldModel_numRigidObjects(self)
[docs] def numTerrains(self) ->int: r""" Returns the number of terrains. """ return _robotsim.WorldModel_numTerrains(self)
[docs] def numIDs(self) ->int: r""" Returns the total number of world ids. """ return _robotsim.WorldModel_numIDs(self)
[docs] def robot(self, *args) -> "RobotModel": r""" Returns a RobotModel in the world by index or name. robot (index): :class:`~klampt.RobotModel` robot (name): :class:`~klampt.RobotModel` Args: index (int, optional): name (str, optional): Returns: :class:`~klampt.RobotModel`: """ return _robotsim.WorldModel_robot(self, *args)
[docs] def rigidObject(self, *args) -> "RigidObjectModel": r""" Returns a RigidObjectModel in the world by index or name. rigidObject (index): :class:`~klampt.RigidObjectModel` rigidObject (name): :class:`~klampt.RigidObjectModel` Args: index (int, optional): name (str, optional): Returns: :class:`~klampt.RigidObjectModel`: """ return _robotsim.WorldModel_rigidObject(self, *args)
[docs] def terrain(self, *args) -> "TerrainModel": r""" Returns a TerrainModel in the world by index or name. terrain (index): :class:`~klampt.TerrainModel` terrain (name): :class:`~klampt.TerrainModel` Args: index (int, optional): name (str, optional): Returns: :class:`~klampt.TerrainModel`: """ return _robotsim.WorldModel_terrain(self, *args)
[docs] def makeRobot(self, name: str) -> "RobotModel": r""" Creates a new empty robot. (Not terribly useful now since you can't resize the number of links yet) Args: name (str) """ return _robotsim.WorldModel_makeRobot(self, name)
[docs] def makeRigidObject(self, name: str) -> "RigidObjectModel": r""" Creates a new empty rigid object. Args: name (str) """ return _robotsim.WorldModel_makeRigidObject(self, name)
[docs] def makeTerrain(self, name: str) -> "TerrainModel": r""" Creates a new empty terrain. Args: name (str) """ return _robotsim.WorldModel_makeTerrain(self, name)
[docs] def loadRobot(self, fn: str) -> "RobotModel": r""" Loads a robot from a .rob or .urdf file. An empty robot is returned if loading fails. Args: fn (str) """ return _robotsim.WorldModel_loadRobot(self, fn)
[docs] def loadRigidObject(self, fn: str) -> "RigidObjectModel": r""" Loads a rigid object from a .obj or a mesh file. An empty rigid object is returned if loading fails. Args: fn (str) """ return _robotsim.WorldModel_loadRigidObject(self, fn)
[docs] def loadTerrain(self, fn: str) -> "TerrainModel": r""" Loads a rigid object from a mesh file. An empty terrain is returned if loading fails. Args: fn (str) """ return _robotsim.WorldModel_loadTerrain(self, fn)
[docs] def loadElement(self, fn: str) ->int: r""" Loads some element from a file, automatically detecting its type. Meshes are interpreted as terrains. Args: fn (str) Returns: The element's ID, or -1 if loading failed. """ return _robotsim.WorldModel_loadElement(self, fn)
[docs] def add(self, *args) -> "TerrainModel": r""" Adds a copy of the given robot, rigid object, or terrain to this world, either from this WorldModel or another. add (name,robot): :class:`~klampt.RobotModel` add (name,obj): :class:`~klampt.RigidObjectModel` add (name,terrain): :class:`~klampt.TerrainModel` Args: name (str): robot (:class:`~klampt.RobotModel`, optional): obj (:class:`~klampt.RigidObjectModel`, optional): terrain (:class:`~klampt.TerrainModel`, optional): Returns: (:class:`~klampt.TerrainModel` or :class:`~klampt.RobotModel` or :class:`~klampt.RigidObjectModel`): """ return _robotsim.WorldModel_add(self, *args)
[docs] def remove(self, *args) ->None: r""" Removes a robot, rigid object, or terrain from the world. It must be in this world or an exception is raised. remove (robot) remove (object) remove (terrain) Args: robot (:class:`~klampt.RobotModel`, optional): object (:class:`~klampt.RigidObjectModel`, optional): terrain (:class:`~klampt.TerrainModel`, optional): IMPORTANT: All other RobotModel, RigidObjectModel, or TerrainModel references will be invalidated. """ return _robotsim.WorldModel_remove(self, *args)
[docs] def getName(self, id: int) ->str: r""" Retrieves the name for a given element ID. Args: id (int) """ return _robotsim.WorldModel_getName(self, id)
[docs] def geometry(self, id: int) -> "Geometry3D": r""" Retrieves a geometry for a given element ID. Args: id (int) """ return _robotsim.WorldModel_geometry(self, id)
[docs] def appearance(self, id: int) -> "Appearance": r""" Retrieves an appearance for a given element ID. Args: id (int) """ return _robotsim.WorldModel_appearance(self, id)
[docs] def drawGL(self) ->None: r""" Draws the entire world using OpenGL. """ return _robotsim.WorldModel_drawGL(self)
[docs] def enableGeometryLoading(self, enabled: bool) ->None: r""" If geometry loading is set to false, then only the kinematics are loaded from disk, and no geometry / visualization / collision detection structures will be loaded. Useful for quick scripts that just use kinematics / dynamics of a robot. Args: enabled (bool) """ return _robotsim.WorldModel_enableGeometryLoading(self, enabled)
[docs] def enableInitCollisions(self, enabled: bool) ->None: r""" If collision detection is set to true, then collision acceleration data structures will be automatically initialized, with debugging information. Useful for scripts that do planning and for which collision initialization may take a long time. Args: enabled (bool) Note that even when this flag is off, the collision acceleration data structures will indeed be initialized the first time that geometry collision, distance, or ray-casting routines are called. """ return _robotsim.WorldModel_enableInitCollisions(self, enabled)
index = property(_robotsim.WorldModel_index_get, _robotsim.WorldModel_index_set, doc=r"""index : int""")
# Register WorldModel in _robotsim: _robotsim.WorldModel_swigregister(WorldModel)
[docs]class IKObjective(object): r""" A class defining an inverse kinematic target. Either a link on a robot can take on a fixed position/orientation in the world frame, or a relative position/orientation to another frame. The positionScale and orientationScale attributes scale the solver's residual vector. This affects whether the convergence tolerance is met, and also controls the emphasis on each objective / component when the objective cannot be reached. By default these are both 1. C++ includes: robotik.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" With no arguments, constructs a blank IKObjective. Given an IKObjective, acts as a copy constructor. __init__ (): :class:`~klampt.IKObjective` __init__ (arg2): :class:`~klampt.IKObjective` Args: arg2 (:class:`~klampt.IKObjective`, optional): """ _robotsim.IKObjective_swiginit(self, _robotsim.new_IKObjective(*args))
[docs] def copy(self) -> "IKObjective": r""" Copy constructor. """ return _robotsim.IKObjective_copy(self)
[docs] def numPosDims(self) ->int: r""" Returns: The number of position dimensions constrained (0-3) """ return _robotsim.IKObjective_numPosDims(self)
[docs] def numRotDims(self) ->int: r""" Returns: The number of rotation dimensions constrained (0-3) """ return _robotsim.IKObjective_numRotDims(self)
[docs] def setFixedPoint(self, link: int, plocal: Point, pworld: Point) ->None: r""" Sets a fixed-point constraint. Args: link (int) plocal (:obj:`list of 3 floats`) pworld (:obj:`list of 3 floats`) """ return _robotsim.IKObjective_setFixedPoint(self, link, plocal, pworld)
[docs] def setFixedPoints(self, link: int, plocals: object, pworlds: object) ->None: r""" Sets a multiple fixed-point constraint. Args: link (int) plocals (:obj:`object`) pworlds (:obj:`object`) """ return _robotsim.IKObjective_setFixedPoints(self, link, plocals, pworlds)
[docs] def setFixedTransform(self, link: int, R: Rotation, t: Point) ->None: r""" Sets a fixed-transform constraint (R,t) Args: link (int) R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.IKObjective_setFixedTransform(self, link, R, t)
[docs] def setRelativePoint(self, link1: int, link2: int, p1: Point, p2: Point) ->None: r""" Sets a fixed-point constraint relative to link2. Args: link1 (int) link2 (int) p1 (:obj:`list of 3 floats`) p2 (:obj:`list of 3 floats`) """ return _robotsim.IKObjective_setRelativePoint(self, link1, link2, p1, p2)
[docs] def setRelativePoints(self, link1: int, link2: int, p1s: object, p2s: object) ->None: r""" Sets a multiple fixed-point constraint relative to link2. Args: link1 (int) link2 (int) p1s (:obj:`object`) p2s (:obj:`object`) """ return _robotsim.IKObjective_setRelativePoints(self, link1, link2, p1s, p2s)
[docs] def setRelativeTransform(self, link: int, linkTgt: int, R: Rotation, t: Point) ->None: r""" Sets a fixed-transform constraint (R,t) relative to linkTgt. Args: link (int) linkTgt (int) R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.IKObjective_setRelativeTransform(self, link, linkTgt, R, t)
[docs] def setFreePosition(self) ->None: r""" Deprecated: use setFreePosConstraint. """ return _robotsim.IKObjective_setFreePosition(self)
[docs] def setFreePosConstraint(self) ->None: r""" Manual: Sets a free position constraint. """ return _robotsim.IKObjective_setFreePosConstraint(self)
[docs] def setFixedPosConstraint(self, tlocal: Point, tworld: Point) ->None: r""" Manual: Sets a fixed position constraint. Args: tlocal (:obj:`list of 3 floats`) tworld (:obj:`list of 3 floats`) """ return _robotsim.IKObjective_setFixedPosConstraint(self, tlocal, tworld)
[docs] def setPlanarPosConstraint(self, tlocal: Point, nworld: Point, oworld: float) ->None: r""" Manual: Sets a planar position constraint nworld^T T(link)*tlocal + oworld = 0. Args: tlocal (:obj:`list of 3 floats`) nworld (:obj:`list of 3 floats`) oworld (float) """ return _robotsim.IKObjective_setPlanarPosConstraint(self, tlocal, nworld, oworld)
[docs] def setLinearPosConstraint(self, tlocal: Point, sworld: Point, dworld: Point) ->None: r""" Manual: Sets a linear position constraint T(link)*tlocal = sworld + u*dworld for some real value u. Args: tlocal (:obj:`list of 3 floats`) sworld (:obj:`list of 3 floats`) dworld (:obj:`list of 3 floats`) """ return _robotsim.IKObjective_setLinearPosConstraint(self, tlocal, sworld, dworld)
[docs] def setFreeRotConstraint(self) ->None: r""" Manual: Sets a free rotation constraint. """ return _robotsim.IKObjective_setFreeRotConstraint(self)
[docs] def setFixedRotConstraint(self, R: Rotation) ->None: r""" Manual: Sets a fixed rotation constraint. Args: R (:obj:`list of 9 floats (so3 element)`) """ return _robotsim.IKObjective_setFixedRotConstraint(self, R)
[docs] def setAxialRotConstraint(self, alocal: Point, aworld: Point) ->None: r""" Manual: Sets an axial rotation constraint. Args: alocal (:obj:`list of 3 floats`) aworld (:obj:`list of 3 floats`) """ return _robotsim.IKObjective_setAxialRotConstraint(self, alocal, aworld)
[docs] def getPosition(self) ->None: r""" Returns the local and global position of the position constraint. """ return _robotsim.IKObjective_getPosition(self)
[docs] def getPositionDirection(self) ->None: r""" For linear and planar constraints, returns the direction. """ return _robotsim.IKObjective_getPositionDirection(self)
[docs] def getRotation(self) ->None: r""" For fixed rotation constraints, returns the orientation. """ return _robotsim.IKObjective_getRotation(self)
[docs] def getRotationAxis(self) ->None: r""" For axis rotation constraints, returns the local and global axes. """ return _robotsim.IKObjective_getRotationAxis(self)
[docs] def getTransform(self) ->None: r""" For fixed-transform constraints, returns the transform (R,t) """ return _robotsim.IKObjective_getTransform(self)
[docs] def transform(self, R: Rotation, t: Point) ->None: r""" Tranforms the target position/rotation of this IK constraint by transform (R,t) Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.IKObjective_transform(self, R, t)
[docs] def transformLocal(self, R: Rotation, t: Point) ->None: r""" Tranforms the local position/rotation of this IK constraint by transform (R,t) Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.IKObjective_transformLocal(self, R, t)
[docs] def matchDestination(self, R: Rotation, t: Point) ->None: r""" Sets the destination coordinates of this constraint to fit the given target transform. In other words, if (R,t) is the current link transform, this sets the destination position / orientation so that this objective has zero error. The current position/rotation constraint types are kept. Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.IKObjective_matchDestination(self, R, t)
[docs] def closestMatch(self, R: Rotation, t: Point) ->None: r""" Gets the transform T that's closest to the transform (R,t) and that satisfies the IK goal's constraints. Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.IKObjective_closestMatch(self, R, t)
[docs] def sampleTransform(self) ->None: r""" Returns a transformation (R,t) from link relative to link2, sampled at random from the space of transforms that satisfies the objective obj. """ return _robotsim.IKObjective_sampleTransform(self)
[docs] def loadString(self, str: str) ->bool: r""" Loads the objective from a Klamp't-native formatted string. For a more readable but verbose format, try the JSON IO routines :meth:`klampt.io.loader.to_json` / :meth:`klampt.io.loader.from_json` Args: str (str) """ return _robotsim.IKObjective_loadString(self, str)
[docs] def saveString(self) ->str: r""" Saves the objective to a Klamp't-native formatted string. For a more readable but verbose format, try the JSON IO routines :meth:`klampt.io.loader.to_json` / :meth:`klampt.io.loader.from_json` """ return _robotsim.IKObjective_saveString(self)
goal = property(_robotsim.IKObjective_goal_get, _robotsim.IKObjective_goal_set, doc=r"""goal : IKGoal""") positionScale = property(_robotsim.IKObjective_positionScale_get, _robotsim.IKObjective_positionScale_set, doc=r"""positionScale : float""") rotationScale = property(_robotsim.IKObjective_rotationScale_get, _robotsim.IKObjective_rotationScale_set, doc=r"""rotationScale : float""") def __reduce__(self): from klampt.io import loader jsonobj = loader.to_json(self,'IKObjective') return (loader.from_json,(jsonobj,'IKObjective')) __swig_destroy__ = _robotsim.delete_IKObjective
# Register IKObjective in _robotsim: _robotsim.IKObjective_swigregister(IKObjective)
[docs]class IKSolver(object): r""" An inverse kinematics solver based on the Newton-Raphson technique. Typical calling pattern is:: s = IKSolver(robot) s.add(objective1) s.add(objective2) s.setMaxIters(100) s.setTolerance(1e-4) res = s.solve() if res: print("IK solution:",robot.getConfig(),"found in", s.lastSolveIters(),"iterations, residual",s.getResidual()) else: print("IK failed:",robot.getConfig(),"found in", s.lastSolveIters(),"iterations, residual",s.getResidual()) C++ includes: robotik.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" Initializes an IK solver. Given a RobotModel, an empty solver is created. Given an IK solver, acts as a copy constructor. __init__ (robot): :class:`~klampt.IKSolver` __init__ (solver): :class:`~klampt.IKSolver` Args: robot (:class:`~klampt.RobotModel`, optional): solver (:class:`~klampt.IKSolver`, optional): """ _robotsim.IKSolver_swiginit(self, _robotsim.new_IKSolver(*args))
[docs] def copy(self) -> "IKSolver": r""" Copy constructor. """ return _robotsim.IKSolver_copy(self)
[docs] def add(self, objective: "IKObjective") ->None: r""" Adds a new simultaneous objective. Args: objective (:class:`~klampt.IKObjective`) """ return _robotsim.IKSolver_add(self, objective)
[docs] def set(self, i: int, objective: "IKObjective") ->None: r""" Assigns an existing objective added by add. Args: i (int) objective (:class:`~klampt.IKObjective`) """ return _robotsim.IKSolver_set(self, i, objective)
[docs] def addSecondary(self, objective: "IKObjective") ->None: r""" Adds a new objective to the secondary objectives list. Args: objective (:class:`~klampt.IKObjective`) """ return _robotsim.IKSolver_addSecondary(self, objective)
[docs] def setSecondary(self, i: int, objective: "IKObjective") ->None: r""" Assigns an existing objective added by addsecondary. Args: i (int) objective (:class:`~klampt.IKObjective`) """ return _robotsim.IKSolver_setSecondary(self, i, objective)
[docs] def clear(self) ->None: r""" Clears objectives. """ return _robotsim.IKSolver_clear(self)
[docs] def setMaxIters(self, iters: int) ->None: r""" Sets the max # of iterations (default 100) Args: iters (int) """ return _robotsim.IKSolver_setMaxIters(self, iters)
[docs] def getMaxIters(self) ->int: r""" Returns the max # of iterations. """ return _robotsim.IKSolver_getMaxIters(self)
[docs] def setTolerance(self, res: float) ->None: r""" Sets the constraint solve tolerance (default 1e-3) Args: res (float) """ return _robotsim.IKSolver_setTolerance(self, res)
[docs] def getTolerance(self) ->float: r""" Returns the constraint solve tolerance. """ return _robotsim.IKSolver_getTolerance(self)
[docs] def setActiveDofs(self, active: IntArray) ->None: r""" Sets the active degrees of freedom. Args: active (:obj:`list of int`) """ return _robotsim.IKSolver_setActiveDofs(self, active)
[docs] def getActiveDofs(self) ->None: r""" Returns the active degrees of freedom. """ return _robotsim.IKSolver_getActiveDofs(self)
[docs] def setJointLimits(self, qmin: Vector, qmax: Vector) ->None: r""" Sets limits on the robot's configuration. If empty, this turns off joint limits. Args: qmin (:obj:`list of floats`) qmax (:obj:`list of floats`) """ return _robotsim.IKSolver_setJointLimits(self, qmin, qmax)
[docs] def getJointLimits(self) ->None: r""" Returns the limits on the robot's configuration (by default this is the robot's joint limits. """ return _robotsim.IKSolver_getJointLimits(self)
[docs] def setBiasConfig(self, biasConfig: Vector) ->None: r""" Biases the solver to approach a given configuration. Setting an empty vector clears the bias term. Args: biasConfig (:obj:`list of floats`) """ return _robotsim.IKSolver_setBiasConfig(self, biasConfig)
[docs] def getBiasConfig(self) ->None: r""" Returns the solvers' bias configuration. """ return _robotsim.IKSolver_getBiasConfig(self)
[docs] def isSolved(self) ->bool: r""" Returns True if the current configuration residual is less than tol. """ return _robotsim.IKSolver_isSolved(self)
[docs] def getResidual(self) ->None: r""" Returns the vector describing the error of the objective at the current configuration. """ return _robotsim.IKSolver_getResidual(self)
[docs] def getJacobian(self) ->None: r""" Computes the matrix describing the instantaneous derivative of the objective with respect to the active Dofs. """ return _robotsim.IKSolver_getJacobian(self)
[docs] def getSecondaryResidual(self) ->None: r""" Returns the vector describing the error of the secondary objective at the current configuration. """ return _robotsim.IKSolver_getSecondaryResidual(self)
[docs] def solve(self) ->bool: r""" Tries to find a configuration that satifies all simultaneous objectives up to the desired tolerance. All of the primary and the secondary objectives are solved simultaneously. Returns: True if x converged. """ return _robotsim.IKSolver_solve(self)
[docs] def minimize(self, *args) ->bool: r""" Tries to find a configuration that satifies all simultaneous objectives up to the desired tolerance or minimizes the residual. minimize (): bool minimize (secondary_objective,secondary_objective_grad): bool Args: secondary_objective (:obj:`object`, optional): secondary_objective_grad (:obj:`object`, optional): The relation to `:func:solve` is that `solve` uses a root-finding method that tries indirectly to minimize the residual, but it may stall out when the objectives are infeasible. If secondary objectives are specified, this tries to minimize them once the primary objectives are satisfied, i.e., it will minimize on the solution manifold of the primary constraints. There are two flavors of secondary objectives. If no arguments are given, then any constraints added via `addSecondary` will have their residuals minimized. If the user provides a pair of functions `(f,grad)`, then a custom objective is specified. Here, `f(q)` is the secondary objective to minimize and `grad(q)` its gradient. This will override the secondary objectives added via `addSecondary`. Specifically, q is a function of all robot DOFs, and `grad(q)` should return a list or tuple of length `len(q)``. .. note:: The minimization will occur only over the current active DOFs, which will include default active DOFs for secondary objectives. Arguments: secondary_objective (callable): a function `f(q)->float` that should be minimized. secondary_objective_grad (callable): a function `grad(q)->`sequence of length `len(q)` giving the gradient of `f` at `q`. Returns: True if x converged on the primary objectives. """ return _robotsim.IKSolver_minimize(self, *args)
[docs] def lastSolveIters(self) ->int: r""" Returns the number of Newton-Raphson iterations used in the last solve() call or the number of Quasi-Newton iterations used in the last minimize() call. """ return _robotsim.IKSolver_lastSolveIters(self)
[docs] def sampleInitial(self) ->None: r""" Samples an initial random configuration. More initial configurations can be sampled in case the prior configs lead to local minima. """ return _robotsim.IKSolver_sampleInitial(self)
robot = property(_robotsim.IKSolver_robot_get, _robotsim.IKSolver_robot_set, doc=r"""robot : RobotModel""") objectives = property(_robotsim.IKSolver_objectives_get, _robotsim.IKSolver_objectives_set, doc=r"""objectives : std::vector<(IKObjective,std::allocator<(IKObjective)>)>""") secondary_objectives = property(_robotsim.IKSolver_secondary_objectives_get, _robotsim.IKSolver_secondary_objectives_set, doc=r"""secondary_objectives : std::vector<(IKObjective,std::allocator<(IKObjective)>)>""") tol = property(_robotsim.IKSolver_tol_get, _robotsim.IKSolver_tol_set, doc=r"""tol : double""") maxIters = property(_robotsim.IKSolver_maxIters_get, _robotsim.IKSolver_maxIters_set, doc=r"""maxIters : int""") activeDofs = property(_robotsim.IKSolver_activeDofs_get, _robotsim.IKSolver_activeDofs_set, doc=r"""activeDofs : std::vector<(int,std::allocator<(int)>)>""") useJointLimits = property(_robotsim.IKSolver_useJointLimits_get, _robotsim.IKSolver_useJointLimits_set, doc=r"""useJointLimits : bool""") qmin = property(_robotsim.IKSolver_qmin_get, _robotsim.IKSolver_qmin_set, doc=r"""qmin : std::vector<(double,std::allocator<(double)>)>""") qmax = property(_robotsim.IKSolver_qmax_get, _robotsim.IKSolver_qmax_set, doc=r"""qmax : std::vector<(double,std::allocator<(double)>)>""") biasConfig = property(_robotsim.IKSolver_biasConfig_get, _robotsim.IKSolver_biasConfig_set, doc=r"""biasConfig : std::vector<(double,std::allocator<(double)>)>""") lastIters = property(_robotsim.IKSolver_lastIters_get, _robotsim.IKSolver_lastIters_set, doc=r"""lastIters : int""") __swig_destroy__ = _robotsim.delete_IKSolver
# Register IKSolver in _robotsim: _robotsim.IKSolver_swigregister(IKSolver)
[docs]class GeneralizedIKObjective(object): r""" An inverse kinematics target for matching points between two robots and/or objects. The objects are chosen upon construction, so the following are valid: * GeneralizedIKObjective(a) is an objective for object a to be constrained relative to the environment. * GeneralizedIKObjective(a,b) is an objective for object a to be constrained relative to b. Here a and b can be links on any robot or rigid objects. Once constructed, call setPoint, setPoints, or setTransform to specify the nature of the constraint. C++ includes: robotik.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__ (obj): :obj:`GeneralizedIKObjective` __init__ (link): :obj:`GeneralizedIKObjective` __init__ (link,link2): :obj:`GeneralizedIKObjective` __init__ (link,obj2): :obj:`GeneralizedIKObjective` __init__ (obj,link2): :obj:`GeneralizedIKObjective` __init__ (obj,obj2): :obj:`GeneralizedIKObjective` Args: obj (:obj:`GeneralizedIKObjective` or :class:`~klampt.RigidObjectModel`, optional): link (:class:`~klampt.RobotModelLink`, optional): link2 (:class:`~klampt.RobotModelLink`, optional): obj2 (:class:`~klampt.RigidObjectModel`, optional): """ _robotsim.GeneralizedIKObjective_swiginit(self, _robotsim.new_GeneralizedIKObjective(*args))
[docs] def setPoint(self, p1: Point, p2: Point) ->None: r""" Args: p1 (:obj:`list of 3 floats`) p2 (:obj:`list of 3 floats`) """ return _robotsim.GeneralizedIKObjective_setPoint(self, p1, p2)
[docs] def setPoints(self, p1s: object, p2s: object) ->None: r""" Args: p1s (:obj:`object`) p2s (:obj:`object`) """ return _robotsim.GeneralizedIKObjective_setPoints(self, p1s, p2s)
[docs] def setTransform(self, R: Rotation, t: Point) ->None: r""" Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.GeneralizedIKObjective_setTransform(self, R, t)
[docs] def sampleTransform(self) ->None: r""" Returns a transformation (R,t) from link relative to link2, sampled at random from the space of transforms that satisfies the objective obj. """ return _robotsim.GeneralizedIKObjective_sampleTransform(self)
link1 = property(_robotsim.GeneralizedIKObjective_link1_get, _robotsim.GeneralizedIKObjective_link1_set, doc=r"""link1 : RobotModelLink""") link2 = property(_robotsim.GeneralizedIKObjective_link2_get, _robotsim.GeneralizedIKObjective_link2_set, doc=r"""link2 : RobotModelLink""") obj1 = property(_robotsim.GeneralizedIKObjective_obj1_get, _robotsim.GeneralizedIKObjective_obj1_set, doc=r"""obj1 : RigidObjectModel""") obj2 = property(_robotsim.GeneralizedIKObjective_obj2_get, _robotsim.GeneralizedIKObjective_obj2_set, doc=r"""obj2 : RigidObjectModel""") isObj1 = property(_robotsim.GeneralizedIKObjective_isObj1_get, _robotsim.GeneralizedIKObjective_isObj1_set, doc=r"""isObj1 : bool""") isObj2 = property(_robotsim.GeneralizedIKObjective_isObj2_get, _robotsim.GeneralizedIKObjective_isObj2_set, doc=r"""isObj2 : bool""") goal = property(_robotsim.GeneralizedIKObjective_goal_get, _robotsim.GeneralizedIKObjective_goal_set, doc=r"""goal : IKGoal""") __swig_destroy__ = _robotsim.delete_GeneralizedIKObjective
# Register GeneralizedIKObjective in _robotsim: _robotsim.GeneralizedIKObjective_swigregister(GeneralizedIKObjective)
[docs]class GeneralizedIKSolver(object): r""" An inverse kinematics solver between multiple robots and/or objects. NOT IMPLEMENTED YET. C++ includes: robotik.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, world: "WorldModel"): r""" Args: world (:class:`~klampt.WorldModel`) """ _robotsim.GeneralizedIKSolver_swiginit(self, _robotsim.new_GeneralizedIKSolver(world))
[docs] def add(self, objective: "GeneralizedIKObjective") ->None: r""" Adds a new simultaneous objective. Args: objective (:obj:`GeneralizedIKObjective`) """ return _robotsim.GeneralizedIKSolver_add(self, objective)
[docs] def setMaxIters(self, iters: int) ->None: r""" Sets the max # of iterations (default 100) Args: iters (int) """ return _robotsim.GeneralizedIKSolver_setMaxIters(self, iters)
[docs] def setTolerance(self, res: float) ->None: r""" Sets the constraint solve tolerance (default 1e-3) Args: res (float) """ return _robotsim.GeneralizedIKSolver_setTolerance(self, res)
[docs] def getResidual(self) ->None: r""" Returns a vector describing the error of the objective. """ return _robotsim.GeneralizedIKSolver_getResidual(self)
[docs] def getJacobian(self) ->None: r""" Returns a matrix describing the instantaneous derivative of the objective with respect to the active parameters. """ return _robotsim.GeneralizedIKSolver_getJacobian(self)
[docs] def solve(self) ->object: r""" Tries to find a configuration that satifies all simultaneous objectives up to the desired tolerance. Returns: res,iters (pair of bool, int): res indicates whether x converged, and iters is the number of iterations used. """ return _robotsim.GeneralizedIKSolver_solve(self)
[docs] def sampleInitial(self) ->None: r""" Samples an initial random configuration. """ return _robotsim.GeneralizedIKSolver_sampleInitial(self)
world = property(_robotsim.GeneralizedIKSolver_world_get, _robotsim.GeneralizedIKSolver_world_set, doc=r"""world : WorldModel""") objectives = property(_robotsim.GeneralizedIKSolver_objectives_get, _robotsim.GeneralizedIKSolver_objectives_set, doc=r"""objectives : std::vector<(GeneralizedIKObjective,std::allocator<(GeneralizedIKObjective)>)>""") tol = property(_robotsim.GeneralizedIKSolver_tol_get, _robotsim.GeneralizedIKSolver_tol_set, doc=r"""tol : double""") maxIters = property(_robotsim.GeneralizedIKSolver_maxIters_get, _robotsim.GeneralizedIKSolver_maxIters_set, doc=r"""maxIters : int""") useJointLimits = property(_robotsim.GeneralizedIKSolver_useJointLimits_get, _robotsim.GeneralizedIKSolver_useJointLimits_set, doc=r"""useJointLimits : bool""") __swig_destroy__ = _robotsim.delete_GeneralizedIKSolver
# Register GeneralizedIKSolver in _robotsim: _robotsim.GeneralizedIKSolver_swigregister(GeneralizedIKSolver)
[docs]class SimRobotSensor(object): r""" A sensor on a simulated robot. Retrieve one from the controller using :meth:`SimRobotController.sensor`, or create a new one using :meth:`SimRobotController.addSensor`. You may also use kinematically-simulated sensors using :meth:`RobotModel.sensor` or create a new one using :meth:`RobotModel.addSensor`. Use :meth:`getMeasurements` to get the currently simulated measurement vector. Sensors are automatically updated through the :meth:`Simulator.simulate` call, and :meth:`getMeasurements` retrieves the updated values. As a result, you may get garbage measurements before the first Simulator.simulate call is made. There is also a mode for doing kinematic simulation, which is supported (i.e., makes sensible measurements) for some types of sensors when just a robot / world model is given. This is similar to Simulation.fakeSimulate but the entire controller structure is bypassed. You can arbitrarily set the robot's position, call :meth:`kinematicReset`, and then call :meth:`kinematicSimulate`. Subsequent calls assume the robot is being driven along a trajectory until the next :meth:`kinematicReset` is called. LaserSensor, CameraSensor, TiltSensor, AccelerometerSensor, GyroSensor, JointPositionSensor, JointVelocitySensor support kinematic simulation mode. FilteredSensor and TimeDelayedSensor also work. The force-related sensors (ContactSensor and ForceTorqueSensor) return 0's in kinematic simulation. To use get/setSetting, you will need to know the sensor attribute names and types as described in `the Klampt sensor documentation <https://github.com/krishauser/Klampt/blob/master/Cpp/docs/Manual- Control.md#sensors>`_ (same as in the world or sensor XML file). Common settings include: * rate (float): how frequently the sensor is simulated * enabled (bool): whether the simulator simulates this sensor * link (int): the link on which this sensor lies (-1 for world) * Tsensor (se3 transform, serialized with loader.write_se3(T)): the transform of the sensor on the robot / world. C++ includes: robotsim.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, robot: "RobotModel", sensor): r""" Args: robot (:class:`~klampt.RobotModel`) sensor (:obj:`Klampt::SensorBase *`) """ _robotsim.SimRobotSensor_swiginit(self, _robotsim.new_SimRobotSensor(robot, sensor))
[docs] def name(self) ->str: r""" Returns the name of the sensor. """ return _robotsim.SimRobotSensor_name(self)
[docs] def type(self) ->str: r""" Returns the type of the sensor. """ return _robotsim.SimRobotSensor_type(self)
[docs] def robot(self) -> "RobotModel": r""" Returns the model of the robot to which this belongs. """ return _robotsim.SimRobotSensor_robot(self)
[docs] def measurementNames(self) ->Sequence[str]: r""" Returns a list of names for the measurements (one per measurement). """ return _robotsim.SimRobotSensor_measurementNames(self)
[docs] def getMeasurements(self) ->None: r""" Returns an array of measurements from the previous simulation (or kinematicSimulate) timestep. """ return _robotsim.SimRobotSensor_getMeasurements(self)
[docs] def settings(self) ->Sequence[str]: r""" Returns all setting names. """ return _robotsim.SimRobotSensor_settings(self)
[docs] def getSetting(self, name: str) ->str: r""" Returns the value of the named setting (you will need to manually parse this) Args: name (str) """ return _robotsim.SimRobotSensor_getSetting(self, name)
[docs] def setSetting(self, name: str, val: str) ->None: r""" Sets the value of the named setting (you will need to manually cast an int/float/etc to a str) Args: name (str) val (str) """ return _robotsim.SimRobotSensor_setSetting(self, name, val)
[docs] def getEnabled(self) ->bool: r""" Return whether the sensor is enabled during simulation (helper for getSetting) """ return _robotsim.SimRobotSensor_getEnabled(self)
[docs] def setEnabled(self, enabled: bool) ->None: r""" Sets whether the sensor is enabled (helper for setSetting) Args: enabled (bool) """ return _robotsim.SimRobotSensor_setEnabled(self, enabled)
[docs] def getTransform(self) ->None: r""" Returns the local transform of the sensor on the robot's link. (helper for getSetting) If the sensor doesn't have a transform (such as a joint position or torque sensor) an exception will be raised. """ return _robotsim.SimRobotSensor_getTransform(self)
[docs] def getTransformWorld(self) ->None: r""" Returns the world transform of the sensor given the robot's current configuration. (helper for getSetting) If the sensor doesn't have a transform (such as a joint position or torque sensor) an exception will be raised. """ return _robotsim.SimRobotSensor_getTransformWorld(self)
[docs] def setTransform(self, R: Rotation, t: Point) ->None: r""" Sets the local transform of the sensor on the robot's link. (helper for setSetting) Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) If the sensor doesn't have a transform (such as a joint position or torque sensor) an exception will be raised. """ return _robotsim.SimRobotSensor_setTransform(self, R, t)
[docs] def drawGL(self, *args) ->None: r""" Draws a sensor indicator using OpenGL. If measurements are given, the indicator is drawn as though these are the latest measurements, otherwise only an indicator is drawn. drawGL () drawGL (np_array) Args: np_array (:obj:`1D Numpy array of floats`, optional): """ return _robotsim.SimRobotSensor_drawGL(self, *args)
[docs] def kinematicSimulate(self, *args) ->None: r""" kinematicSimulate (world,dt) kinematicSimulate (dt) Args: world (:class:`~klampt.WorldModel`, optional): dt (float): """ return _robotsim.SimRobotSensor_kinematicSimulate(self, *args)
[docs] def kinematicReset(self) ->None: r""" resets a kinematic simulation so that a new initial condition can be set """ return _robotsim.SimRobotSensor_kinematicReset(self)
robotModel = property(_robotsim.SimRobotSensor_robotModel_get, _robotsim.SimRobotSensor_robotModel_set, doc=r"""robotModel : RobotModel""") sensor = property(_robotsim.SimRobotSensor_sensor_get, _robotsim.SimRobotSensor_sensor_set, doc=r"""sensor : p.Klampt::SensorBase""") __swig_destroy__ = _robotsim.delete_SimRobotSensor
# Register SimRobotSensor in _robotsim: _robotsim.SimRobotSensor_swigregister(SimRobotSensor)
[docs]class SimRobotController(object): r""" A controller for a simulated robot. By default a SimRobotController has three possible modes: * Motion queue + PID mode: the controller has an internal trajectory queue that may be added to and modified. This queue supports piecewise linear interpolation, cubic interpolation, and time-optimal move-to commands. * PID mode: the user controls the motor's PID setpoints directly * Torque control: the user controlls the motor torques directly. The "standard" way of using this is in move-to mode which accepts a milestone (setMilestone) or list of milestones (repeated calls to addMilestone) and interpolates dynamically from the current configuration/velocity. To handle disturbances, a PID loop is run automatically at the controller's specified rate. To get finer-grained control over the motion queue's timing, you may use the setLinear/setCubic/addLinear/addCubic functions. In these functions it is up to the user to respect velocity, acceleration, and torque limits. Whether in motion queue or PID mode, the constants of the PID loop are initially set in the robot file. You can programmatically tune these via the setPIDGains function. Arbitrary trajectories can be tracked by using setVelocity over short time steps. Force controllers can be implemented using setTorque, again using short time steps. If the setVelocity, setTorque, or setPID command are called, the motion queue behavior will be completely overridden. To reset back to motion queue control, setManualMode(False) must be called first. Individual joints cannot be addressed with mixed motion queue mode and torque/PID mode. However, you can mix PID and torque mode between different joints with a workaround:: # setup by zeroing out PID constants for torque controlled joints pid_joint_indices = [...] torque_joint_indices = [...] # complement of pid_joint_indices kp,ki,kp = controller.getPIDGains() for i in torque_joint_indices: #turn off PID gains here kp[i] = ki[i] = kp[i] = 0 # to send PID command (qcmd,dqcmd) and torque commands tcmd, use # a PID command with feedforward torques. First we build a whole-robot # command: qcmd_whole = [0]*controller.model().numLinks() dqcmd_whole = [0]*controller.model().numLinks() tcmd_whole = [0]*controller.model().numLinks() for i,k in enumerate(pid_joint_indices): qcmd_whole[k],dqcmd_whole[i] = qcmd[i],dqcmd[i] for i,k in enumerate(torque_joint_indices): tcmd_whole[k] = tcmd[i] # Then we send it to the controller controller.setPIDCommand(qcmd_whole,dqcmd_whole,tcmd_whole) C++ includes: robotsim.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.SimRobotController_swiginit(self, _robotsim.new_SimRobotController()) __swig_destroy__ = _robotsim.delete_SimRobotController
[docs] def model(self) -> "RobotModel": r""" Retrieves the robot model associated with this controller. """ return _robotsim.SimRobotController_model(self)
[docs] def setRate(self, dt: float) ->None: r""" Sets the current feedback control rate, in s. Args: dt (float) """ return _robotsim.SimRobotController_setRate(self, dt)
[docs] def getRate(self) ->float: r""" Returns The current feedback control rate, in s. """ return _robotsim.SimRobotController_getRate(self)
[docs] def getCommandedConfig(self) ->None: r""" Returns The current commanded configuration (size model().numLinks()) """ return _robotsim.SimRobotController_getCommandedConfig(self)
[docs] def getCommandedVelocity(self) ->None: r""" Returns The current commanded velocity (size model().numLinks()) """ return _robotsim.SimRobotController_getCommandedVelocity(self)
[docs] def getCommandedTorque(self) ->None: r""" Returns The current commanded (feedforward) torque (size model().numDrivers()) """ return _robotsim.SimRobotController_getCommandedTorque(self)
[docs] def getSensedConfig(self) ->None: r""" Returns The current "sensed" configuration from the simulator (size model().numLinks()) """ return _robotsim.SimRobotController_getSensedConfig(self)
[docs] def getSensedVelocity(self) ->None: r""" Returns The current "sensed" velocity from the simulator (size model().numLinks()) """ return _robotsim.SimRobotController_getSensedVelocity(self)
[docs] def getSensedTorque(self) ->None: r""" Returns The current "sensed" (feedback) torque from the simulator. (size model().numDrivers()) Note: a default robot doesn't have a torque sensor, so this will be 0 """ return _robotsim.SimRobotController_getSensedTorque(self)
[docs] def sensor(self, *args) -> "SimRobotSensor": r""" Returns a sensor by index or by name. If out of bounds or unavailable, a null sensor is returned (i.e., SimRobotSensor.name() or SimRobotSensor.type()) will return the empty string.) sensor (index): :class:`~klampt.SimRobotSensor` sensor (name): :class:`~klampt.SimRobotSensor` Args: index (int, optional): name (str, optional): Returns: :class:`~klampt.SimRobotSensor`: """ return _robotsim.SimRobotController_sensor(self, *args)
[docs] def addSensor(self, name: str, type: str) -> "SimRobotSensor": r""" Adds a new sensor with a given name and type. Args: name (str) type (str) Returns: The new sensor. """ return _robotsim.SimRobotController_addSensor(self, name, type)
[docs] def commands(self) ->Sequence[str]: r""" Returns a custom command list. """ return _robotsim.SimRobotController_commands(self)
[docs] def sendCommand(self, name: str, args: str) ->bool: r""" Sends a custom string command to the controller. Args: name (str) args (str) """ return _robotsim.SimRobotController_sendCommand(self, name, args)
[docs] def settings(self) ->Sequence[str]: r""" Returns all valid setting names. """ return _robotsim.SimRobotController_settings(self)
[docs] def getSetting(self, name: str) ->str: r""" Returns a setting of the controller. Args: name (str) """ return _robotsim.SimRobotController_getSetting(self, name)
[docs] def setSetting(self, name: str, val: str) ->bool: r""" Sets a setting of the controller. Args: name (str) val (str) """ return _robotsim.SimRobotController_setSetting(self, name, val)
[docs] def setMilestone(self, *args) ->None: r""" Uses a dynamic interpolant to get from the current state to the desired milestone (with optional ending velocity). This interpolant is time-optimal with respect to the velocity and acceleration bounds. setMilestone (q) setMilestone (q,dq) Args: q (:obj:`list of floats`): dq (:obj:`list of floats`, optional): """ return _robotsim.SimRobotController_setMilestone(self, *args)
[docs] def addMilestone(self, *args) ->None: r""" Same as setMilestone, but appends an interpolant onto an internal motion queue starting at the current queued end state. addMilestone (q) addMilestone (q,dq) Args: q (:obj:`list of floats`): dq (:obj:`list of floats`, optional): """ return _robotsim.SimRobotController_addMilestone(self, *args)
[docs] def addMilestoneLinear(self, q: Vector) ->None: r""" Same as addMilestone, but enforces that the motion should move along a straight- line joint-space path. Args: q (:obj:`list of floats`) """ return _robotsim.SimRobotController_addMilestoneLinear(self, q)
[docs] def setLinear(self, q: Vector, dt: float) ->None: r""" Uses linear interpolation to get from the current configuration to the desired configuration after time dt. Args: q (:obj:`list of floats`) dt (float) q has size model().numLinks(). dt must be > 0. """ return _robotsim.SimRobotController_setLinear(self, q, dt)
[docs] def setCubic(self, q: Vector, v: Vector, dt: float) ->None: r""" Uses cubic (Hermite) interpolation to get from the current configuration/velocity to the desired configuration/velocity after time dt. Args: q (:obj:`list of floats`) v (:obj:`list of floats`) dt (float) q and v have size model().numLinks(). dt must be > 0. """ return _robotsim.SimRobotController_setCubic(self, q, v, dt)
[docs] def addLinear(self, q: Vector, dt: float) ->None: r""" Same as setLinear but appends an interpolant onto the motion queue. Args: q (:obj:`list of floats`) dt (float) """ return _robotsim.SimRobotController_addLinear(self, q, dt)
[docs] def addCubic(self, q: Vector, v: Vector, dt: float) ->None: r""" Same as setCubic but appends an interpolant onto the motion queue. Args: q (:obj:`list of floats`) v (:obj:`list of floats`) dt (float) """ return _robotsim.SimRobotController_addCubic(self, q, v, dt)
[docs] def remainingTime(self) ->float: r""" Returns the remaining duration of the motion queue. """ return _robotsim.SimRobotController_remainingTime(self)
[docs] def setVelocity(self, dq: Vector, dt: float) ->None: r""" Sets a rate controller from the current commanded config to move at rate dq for time dt > 0. dq has size model().numLinks() Args: dq (:obj:`list of floats`) dt (float) """ return _robotsim.SimRobotController_setVelocity(self, dq, dt)
[docs] def setTorque(self, t: Vector) ->None: r""" Sets a torque command controller. t can have size model().numDrivers() or model().numLinks(). Args: t (:obj:`list of floats`) """ return _robotsim.SimRobotController_setTorque(self, t)
[docs] def setPIDCommand(self, *args) ->None: r""" Sets a PID command controller. If tfeedforward is provided, it is the feedforward torque vector. setPIDCommand (qdes,dqdes) setPIDCommand (qdes,dqdes,tfeedforward) Args: qdes (:obj:`list of floats`): dqdes (:obj:`list of floats`): tfeedforward (:obj:`list of floats`, optional): """ return _robotsim.SimRobotController_setPIDCommand(self, *args)
[docs] def setManualMode(self, enabled: bool) ->None: r""" Turns on/off manual mode, if either the setTorque or setPID command were previously set. Args: enabled (bool) """ return _robotsim.SimRobotController_setManualMode(self, enabled)
[docs] def getControlType(self) ->str: r""" Returns the control type for the active controller. Returns: One of - unknown - off - torque - PID - locked_velocity """ return _robotsim.SimRobotController_getControlType(self)
[docs] def setPIDGains(self, kP: Vector, kI: Vector, kD: Vector) ->None: r""" Sets the PID gains. Arguments have size model().numDrivers(). Args: kP (:obj:`list of floats`) kI (:obj:`list of floats`) kD (:obj:`list of floats`) """ return _robotsim.SimRobotController_setPIDGains(self, kP, kI, kD)
[docs] def getPIDGains(self) ->None: r""" Returns the PID gains for the PID controller. """ return _robotsim.SimRobotController_getPIDGains(self)
index = property(_robotsim.SimRobotController_index_get, _robotsim.SimRobotController_index_set, doc=r"""index : int""") sim = property(_robotsim.SimRobotController_sim_get, _robotsim.SimRobotController_sim_set, doc=r"""sim : p.Simulator""") controller = property(_robotsim.SimRobotController_controller_get, _robotsim.SimRobotController_controller_set, doc=r"""controller : p.Klampt::SimRobotController""")
# Register SimRobotController in _robotsim: _robotsim.SimRobotController_swigregister(SimRobotController)
[docs]class SimBody(object): r""" A reference to a rigid body inside a Simulator (either a RigidObjectModel, TerrainModel, or a link of a RobotModel). Can use this class to directly apply forces to or control positions / velocities of objects in the simulation. .. note:: All changes are applied in the current simulation substep, not the duration provided to Simulation.simulate(). If you need fine-grained control, make sure to call Simulation.simulate() with time steps equal to the value provided to Simulation.setSimStep() (this is 0.001s by default). Or, use a hook from :class:`~klampt.sim.simulation.SimpleSimulator`. .. note:: The transform of the body is centered at the *object's center of mass* rather than the object's reference frame given in the RobotModelLink or RigidObjectModel. C++ includes: robotsim.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr
[docs] def getID(self) ->int: r""" Returns the object ID that this body associated with. """ return _robotsim.SimBody_getID(self)
[docs] def enable(self, enabled: bool=True) ->None: r""" Sets the simulation of this body on/off. Args: enabled (bool, optional): default value True """ return _robotsim.SimBody_enable(self, enabled)
[docs] def isEnabled(self) ->bool: r""" Returns true if this body is being simulated. """ return _robotsim.SimBody_isEnabled(self)
[docs] def enableDynamics(self, enabled: bool=True) ->None: r""" Turns dynamic simulation of the body on/off. If false, velocities will simply be integrated forward, and forces will not affect velocity i.e., it will be pure kinematic simulation. Args: enabled (bool, optional): default value True """ return _robotsim.SimBody_enableDynamics(self, enabled)
[docs] def isDynamicsEnabled(self) ->bool: r""" """ return _robotsim.SimBody_isDynamicsEnabled(self)
[docs] def applyWrench(self, f: Point, t: Point) ->None: r""" Applies a force and torque about the COM over the duration of the next Simulator.simulate(t) call. Args: f (:obj:`list of 3 floats`) t (:obj:`list of 3 floats`) """ return _robotsim.SimBody_applyWrench(self, f, t)
[docs] def applyForceAtPoint(self, f: Point, pworld: Point) ->None: r""" Applies a force at a given point (in world coordinates) over the duration of the next Simulator.simulate(t) call. Args: f (:obj:`list of 3 floats`) pworld (:obj:`list of 3 floats`) """ return _robotsim.SimBody_applyForceAtPoint(self, f, pworld)
[docs] def applyForceAtLocalPoint(self, f: Point, plocal: Point) ->None: r""" Applies a force at a given point (in local center-of-mass-centered coordinates) over the duration of the next Simulator.simulate(t) call. Args: f (:obj:`list of 3 floats`) plocal (:obj:`list of 3 floats`) """ return _robotsim.SimBody_applyForceAtLocalPoint(self, f, plocal)
[docs] def setTransform(self, R: Rotation, t: Point) ->None: r""" Sets the body's transformation at the current simulation time step (in center- of-mass centered coordinates). Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.SimBody_setTransform(self, R, t)
[docs] def getTransform(self) ->None: r""" Gets the body's transformation at the current simulation time step (in center- of-mass centered coordinates). """ return _robotsim.SimBody_getTransform(self)
[docs] def setObjectTransform(self, R: Rotation, t: Point) ->None: r""" Sets the body's transformation at the current simulation time step (in object- native coordinates) Args: R (:obj:`list of 9 floats (so3 element)`) t (:obj:`list of 3 floats`) """ return _robotsim.SimBody_setObjectTransform(self, R, t)
[docs] def getObjectTransform(self) ->None: r""" Gets the body's transformation at the current simulation time step (in object- native coordinates). """ return _robotsim.SimBody_getObjectTransform(self)
[docs] def setVelocity(self, w: Point, v: Point) ->None: r""" Sets the angular velocity and translational velocity at the current simulation time step. Args: w (:obj:`list of 3 floats`) v (:obj:`list of 3 floats`) """ return _robotsim.SimBody_setVelocity(self, w, v)
[docs] def getVelocity(self) ->None: r""" Returns the angular velocity and translational velocity. """ return _robotsim.SimBody_getVelocity(self)
[docs] def setCollisionPadding(self, padding: float) ->None: r""" Sets the collision padding used for contact generation. At 0 padding the simulation will be unstable for triangle mesh and point cloud geometries. A larger value is useful to maintain simulation stability for thin or soft objects. Default is 0.0025. Args: padding (float) """ return _robotsim.SimBody_setCollisionPadding(self, padding)
[docs] def getCollisionPadding(self) ->float: r""" """ return _robotsim.SimBody_getCollisionPadding(self)
[docs] def setCollisionPreshrink(self, shrinkVisualization: bool=False) ->None: r""" If set, preshrinks the geometry so that the padded geometry better matches the original mesh. If shrinkVisualization=true, the underlying mesh is also shrunk (helps debug simulation artifacts due to preshrink) Args: shrinkVisualization (bool, optional): default value False """ return _robotsim.SimBody_setCollisionPreshrink(self, shrinkVisualization)
[docs] def getSurface(self) -> "ContactParameters": r""" Gets (a copy of) the surface properties. """ return _robotsim.SimBody_getSurface(self)
[docs] def setSurface(self, params: "ContactParameters") ->None: r""" Sets the surface properties. Args: params (:class:`~klampt.ContactParameters`) """ return _robotsim.SimBody_setSurface(self, params)
sim = property(_robotsim.SimBody_sim_get, _robotsim.SimBody_sim_set, doc=r"""sim : p.Simulator""") objectID = property(_robotsim.SimBody_objectID_get, _robotsim.SimBody_objectID_set, doc=r"""objectID : int""") geometry = property(_robotsim.SimBody_geometry_get, _robotsim.SimBody_geometry_set, doc=r"""geometry : p.Klampt::ODEGeometry""") body = property(_robotsim.SimBody_body_get, _robotsim.SimBody_body_set, doc=r"""body : dBodyID""") def __init__(self): r""" A reference to a rigid body inside a Simulator (either a RigidObjectModel, TerrainModel, or a link of a RobotModel). Can use this class to directly apply forces to or control positions / velocities of objects in the simulation. .. note:: All changes are applied in the current simulation substep, not the duration provided to Simulation.simulate(). If you need fine-grained control, make sure to call Simulation.simulate() with time steps equal to the value provided to Simulation.setSimStep() (this is 0.001s by default). Or, use a hook from :class:`~klampt.sim.simulation.SimpleSimulator`. .. note:: The transform of the body is centered at the *object's center of mass* rather than the object's reference frame given in the RobotModelLink or RigidObjectModel. C++ includes: robotsim.h """ _robotsim.SimBody_swiginit(self, _robotsim.new_SimBody()) __swig_destroy__ = _robotsim.delete_SimBody
# Register SimBody in _robotsim: _robotsim.SimBody_swigregister(SimBody)
[docs]class SimJoint(object): r""" An interface to ODE's hinge and slider joints. You may use this to create custom objects, e.g., drawers, doors, cabinets, etc. It can also be used to attach objects together, e.g., an object to a robot's gripper. C++ includes: robotsim.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r""" """ _robotsim.SimJoint_swiginit(self, _robotsim.new_SimJoint()) __swig_destroy__ = _robotsim.delete_SimJoint
[docs] def makeHinge(self, *args) ->None: r""" makeHinge (a,b,pt,axis) makeHinge (a,pt,axis) Args: a (:class:`~klampt.SimBody`): b (:class:`~klampt.SimBody`, optional): pt (:obj:`list of 3 floats`): axis (:obj:`list of 3 floats`): """ return _robotsim.SimJoint_makeHinge(self, *args)
[docs] def makeSlider(self, *args) ->None: r""" makeSlider (a,b,axis) makeSlider (a,axis) Args: a (:class:`~klampt.SimBody`): b (:class:`~klampt.SimBody`, optional): axis (:obj:`list of 3 floats`): """ return _robotsim.SimJoint_makeSlider(self, *args)
[docs] def makeFixed(self, a: "SimBody", b: "SimBody") ->None: r""" Creates a fixed joint between `a` and `b`. (There's no method to fix a to the world; just call a.enableDynamics(False)) Args: a (:class:`~klampt.SimBody`) b (:class:`~klampt.SimBody`) """ return _robotsim.SimJoint_makeFixed(self, a, b)
[docs] def destroy(self) ->None: r""" Removes the joint from the simulation. """ return _robotsim.SimJoint_destroy(self)
[docs] def setLimits(self, min: float, max: float) ->None: r""" Sets the joint limits, relative to the initial configuration of the bodies. Units are in radians for hinges and meters for sliders. Args: min (float) max (float) """ return _robotsim.SimJoint_setLimits(self, min, max)
[docs] def setFriction(self, friction: float) ->None: r""" Sets the (dry) friction of the joint. Args: friction (float) """ return _robotsim.SimJoint_setFriction(self, friction)
[docs] def setVelocity(self, vel: float, fmax: float) ->None: r""" Locks velocity of the joint, up to force fmax. Can't be used with setFriction. Args: vel (float) fmax (float) """ return _robotsim.SimJoint_setVelocity(self, vel, fmax)
[docs] def addForce(self, force: float) ->None: r""" Adds a torque for the hinge joint and a force for a slider joint. Args: force (float) """ return _robotsim.SimJoint_addForce(self, force)
type = property(_robotsim.SimJoint_type_get, _robotsim.SimJoint_type_set, doc=r"""type : int""") a = property(_robotsim.SimJoint_a_get, _robotsim.SimJoint_a_set, doc=r"""a : p.q(const).SimBody""") b = property(_robotsim.SimJoint_b_get, _robotsim.SimJoint_b_set, doc=r"""b : p.q(const).SimBody""") joint = property(_robotsim.SimJoint_joint_get, _robotsim.SimJoint_joint_set, doc=r"""joint : dJointID""")
# Register SimJoint in _robotsim: _robotsim.SimJoint_swigregister(SimJoint)
[docs]class Simulator(object): r""" A dynamics simulator for a WorldModel. C++ includes: robotsim.h """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr STATUS_NORMAL = _robotsim.Simulator_STATUS_NORMAL STATUS_ADAPTIVE_TIME_STEPPING = _robotsim.Simulator_STATUS_ADAPTIVE_TIME_STEPPING STATUS_CONTACT_UNRELIABLE = _robotsim.Simulator_STATUS_CONTACT_UNRELIABLE STATUS_UNSTABLE = _robotsim.Simulator_STATUS_UNSTABLE STATUS_ERROR = _robotsim.Simulator_STATUS_ERROR def __init__(self, model: "WorldModel"): r""" Constructs the simulator from a WorldModel. If the WorldModel was loaded from an XML file, then the simulation setup is loaded from it. Args: model (:class:`~klampt.WorldModel`) """ _robotsim.Simulator_swiginit(self, _robotsim.new_Simulator(model)) __swig_destroy__ = _robotsim.delete_Simulator
[docs] def reset(self) ->None: r""" Resets to the initial state (same as setState(initialState)) """ return _robotsim.Simulator_reset(self)
[docs] def getStatus(self) ->int: r""" Returns an indicator code for the simulator status. Returns: One of the STATUS_X flags. (Technically, this returns the *worst* status over the last simulate() call) """ return _robotsim.Simulator_getStatus(self)
[docs] def getStatusString(self, s: int=-1) ->str: r""" Returns a string indicating the simulator's status. If s is provided and >= 0, this function maps the indicator code s to a string. Args: s (int, optional): default value -1 """ return _robotsim.Simulator_getStatusString(self, s)
[docs] def checkObjectOverlap(self) ->None: r""" Checks if any objects are overlapping. Returns: A pair of lists of integers, giving the pairs of object ids that are overlapping. """ return _robotsim.Simulator_checkObjectOverlap(self)
[docs] def getState(self) ->str: r""" Gets the current simulation state, including controller parameters, etc. Returns: A Base64 string representing the binary data for the state """ return _robotsim.Simulator_getState(self)
[docs] def setState(self, str: str) ->None: r""" Sets the current simulation state from a Base64 string returned by a prior getState call. Args: str (str) """ return _robotsim.Simulator_setState(self, str)
[docs] def simulate(self, t: float) ->None: r""" Advances the simulation by time t, and updates the world model from the simulation state. Args: t (float) """ return _robotsim.Simulator_simulate(self, t)
[docs] def fakeSimulate(self, t: float) ->None: r""" Advances a faked simulation by time t, and updates the world model from the faked simulation state. Args: t (float) """ return _robotsim.Simulator_fakeSimulate(self, t)
[docs] def getTime(self) ->float: r""" Returns the simulation time. """ return _robotsim.Simulator_getTime(self)
[docs] def updateWorld(self) ->None: r""" Updates the world model from the current simulation state. This only needs to be called if you change the world model and want to revert back to the simulation state. """ return _robotsim.Simulator_updateWorld(self)
[docs] def getActualConfig(self, robot: int) ->None: r""" Returns the current actual configuration of the robot from the simulator. Args: robot (int) """ return _robotsim.Simulator_getActualConfig(self, robot)
[docs] def getActualVelocity(self, robot: int) ->None: r""" Returns the current actual velocity of the robot from the simulator. Args: robot (int) """ return _robotsim.Simulator_getActualVelocity(self, robot)
[docs] def getActualTorque(self, robot: int) ->None: r""" Returns the current actual torques on the robot's drivers from the simulator. Args: robot (int) """ return _robotsim.Simulator_getActualTorque(self, robot)
[docs] def getActualTorques(self, robot: int) ->None: r""" Deprecated: renamed to getActualTorque to be consistent with SimRobotController methods. Args: robot (int) """ return _robotsim.Simulator_getActualTorques(self, robot)
[docs] def enableContactFeedback(self, obj1: int, obj2: int) ->None: r""" Call this to enable contact feedback between the two objects (arguments are indexes returned by object.getID()). Contact feedback has a small overhead so you may want to do this selectively. This must be called before using inContact, getContacts, getContactForces, contactForce, contactTorque, hadContact, hadSeparation, hadPenetration, and meanContactForce. Args: obj1 (int) obj2 (int) """ return _robotsim.Simulator_enableContactFeedback(self, obj1, obj2)
[docs] def enableContactFeedbackAll(self) ->None: r""" Call this to enable contact feedback between all pairs of objects. Contact feedback has a small overhead so you may want to do this selectively. """ return _robotsim.Simulator_enableContactFeedbackAll(self)
[docs] def inContact(self, aid: int, bid: int) ->bool: r""" Returns true if the objects (indexes returned by object.getID()) are in contact on the current time step. You can set bid=-1 to tell if object `a` is in contact with any object. Args: aid (int) bid (int) """ return _robotsim.Simulator_inContact(self, aid, bid)
[docs] def getContacts(self, aid: int, bid: int) ->None: r""" Returns the nx7 list of contacts (x,n,kFriction) at the last time step. Normals point into object `a`. Each contact point (x,n,kFriction) is represented as a 7-element vector. Args: aid (int) bid (int) """ return _robotsim.Simulator_getContacts(self, aid, bid)
[docs] def getContactForces(self, aid: int, bid: int) ->None: r""" Returns the list of contact forces on object a at the last time step. Result is an nx3 array. Args: aid (int) bid (int) """ return _robotsim.Simulator_getContactForces(self, aid, bid)
[docs] def contactForce(self, aid: int, bid: int) ->None: r""" Returns the contact force on object a at the last time step. You can set bid to -1 to get the overall contact force on object a. Args: aid (int) bid (int) """ return _robotsim.Simulator_contactForce(self, aid, bid)
[docs] def contactTorque(self, aid: int, bid: int) ->None: r""" Returns the contact force on object `a` (about `a`'s origin) at the last time step. You can set `bid` to -1 to get the overall contact force on object `a`. Args: aid (int) bid (int) """ return _robotsim.Simulator_contactTorque(self, aid, bid)
[docs] def hadContact(self, aid: int, bid: int) ->bool: r""" Returns true if the objects had contact over the last simulate() call. You can set `bid` to -1 to determine if object `a` had contact with any other object. Args: aid (int) bid (int) """ return _robotsim.Simulator_hadContact(self, aid, bid)
[docs] def hadSeparation(self, aid: int, bid: int) ->bool: r""" Returns true if the objects had ever separated during the last simulate() call. You can set `bid` to -1 to determine if object `a` had no contact with any other object. Args: aid (int) bid (int) """ return _robotsim.Simulator_hadSeparation(self, aid, bid)
[docs] def hadPenetration(self, aid: int, bid: int) ->bool: r""" Returns true if the objects interpenetrated during the last simulate() call. If so, the simulation may lead to very inaccurate results or artifacts. Args: aid (int) bid (int) You can set `bid` to -1 to determine if object `a` penetrated any object, or you can set `aid=bid=-1` to determine whether any object is penetrating any other (indicating that the simulation will not be functioning properly in general). """ return _robotsim.Simulator_hadPenetration(self, aid, bid)
[docs] def meanContactForce(self, aid: int, bid: int) ->None: r""" Returns the average contact force on object a over the last simulate() call. Args: aid (int) bid (int) """ return _robotsim.Simulator_meanContactForce(self, aid, bid)
[docs] def controller(self, *args) -> "SimRobotController": r""" Returns a controller for the indicated robot, either by index or by RobotModel. controller (robot): :class:`~klampt.SimRobotController` Args: robot (:class:`~klampt.RobotModel` or int): Returns: :class:`~klampt.SimRobotController`: """ return _robotsim.Simulator_controller(self, *args)
[docs] def body(self, *args) -> "SimBody": r""" Return the SimBody corresponding to the given link, rigid object, or terrain. body (link): :class:`~klampt.SimBody` body (object): :class:`~klampt.SimBody` body (terrain): :class:`~klampt.SimBody` Args: link (:class:`~klampt.RobotModelLink`, optional): object (:class:`~klampt.RigidObjectModel`, optional): terrain (:class:`~klampt.TerrainModel`, optional): Returns: :class:`~klampt.SimBody`: """ return _robotsim.Simulator_body(self, *args)
[docs] def getJointForces(self, link: "RobotModelLink") ->None: r""" Returns the joint force and torque local to the link, as would be read by a force-torque sensor mounted at the given link's origin. Args: link (:class:`~klampt.RobotModelLink`) Returns: 6 entries of the wrench (fx,fy,fz,mx,my,mz) """ return _robotsim.Simulator_getJointForces(self, link)
[docs] def setGravity(self, g: Point) ->None: r""" Sets the overall gravity vector. Args: g (:obj:`list of 3 floats`) """ return _robotsim.Simulator_setGravity(self, g)
[docs] def setSimStep(self, dt: float) ->None: r""" Sets the internal simulation substep. Values < 0.01 are recommended. Args: dt (float) """ return _robotsim.Simulator_setSimStep(self, dt)
[docs] def settings(self) ->Sequence[str]: r""" Returns all setting names. """ return _robotsim.Simulator_settings(self)
[docs] def getSetting(self, name: str) ->str: r""" Retrieves some simulation setting. Args: name (str) Valid names are: * gravity: the gravity vector (default "0 0 -9.8") * simStep: the internal simulation step (default "0.001") * autoDisable: whether to disable bodies that don't move much between time steps (default "0", set to "1" for many static objects) * boundaryLayerCollisions: whether to use the Klampt inflated boundaries for contact detection'(default "1", recommended) * rigidObjectCollisions: whether rigid objects should collide (default "1") * robotSelfCollisions: whether robots should self collide (default "0") * robotRobotCollisions: whether robots should collide with other robots (default "1") * adaptiveTimeStepping: whether adaptive time stepping should be used to improve stability. Slower but more stable. (default "1") * minimumAdaptiveTimeStep: the minimum size of an adaptive time step before giving up (default "1e-6") * maxContacts: max # of clustered contacts between pairs of objects (default "20") * clusterNormalScale: a parameter for clustering contacts (default "0.1") * errorReductionParameter: see ODE docs on ERP (default "0.95") * dampedLeastSquaresParameter: see ODE docs on CFM (default "1e-6") * instabilityConstantEnergyThreshold: parameter c0 in instability correction (default "1") * instabilityLinearEnergyThreshold: parameter c1 in instability correction (default "1.5") * instabilityMaxEnergyThreshold: parameter cmax in instability correction (default "100000") * instabilityPostCorrectionEnergy: kinetic energy scaling parameter if instability is detected (default "0.8") Instability correction kicks in whenever the kinetic energy K(t) of an object exceeds min(c0*m + c1*K(t-dt),cmax). m is the object's mass. See `Klampt/Simulation/ODESimulator.h <http://motion.pratt.duke.edu/klampt/klampt_docs/ODESimulator_8h_source.html>`_ for detailed descriptions of these parameters. Returns: A string encoding the data. This will need to be cast to int or float manually. """ return _robotsim.Simulator_getSetting(self, name)
[docs] def setSetting(self, name: str, value: str) ->None: r""" Sets some simulation setting. Raises an exception if the name is unknown or the value is of improper format. Args: name (str) value (str) """ return _robotsim.Simulator_setSetting(self, name, value)
index = property(_robotsim.Simulator_index_get, _robotsim.Simulator_index_set, doc=r"""index : int""") world = property(_robotsim.Simulator_world_get, _robotsim.Simulator_world_set, doc=r"""world : WorldModel""") sim = property(_robotsim.Simulator_sim_get, _robotsim.Simulator_sim_set, doc=r"""sim : p.Klampt::Simulator""") initialState = property(_robotsim.Simulator_initialState_get, _robotsim.Simulator_initialState_set, doc=r"""initialState : std::string""")
# Register Simulator in _robotsim: _robotsim.Simulator_swigregister(Simulator)
[docs]def set_random_seed(seed: int) ->None: r""" Sets the random seed used by the motion planner. Args: seed (int) """ return _robotsim.set_random_seed(seed)
def destroy() ->None: r""" destroys internal data structures """ return _robotsim.destroy()
[docs]def subscribe_to_stream(*args) ->bool: r""" Subscribes a Geometry3D to a stream. Args: g (Geometry3D): the geometry that will be updated protocol (str): only "ros" accepted for now. name (str): the name of the stream, i.e., ROS topic. type (str, optional): If provided, specifies the format of the data to be subscribed to. If not, tries to determine the type automatically. Only ROS point clouds (PointCloud2) are supported for now. Note that you can also call `Geometry3D.loadFile("ros://[ROS_TOPIC]")` or `Geometry3D.loadFile("ros:PointCloud2//[ROS_TOPIC]")` to accomplish the same thing. TODO: It has not yet been determined whether this interferes with Rospy, i.e., klampt.io.ros. Returns: (bool): True if successful. """ return _robotsim.subscribe_to_stream(*args)
[docs]def detach_from_stream(protocol: str, name: str) ->bool: r""" Unsubscribes from a stream previously subscribed to via :func:`SubscribeToStream` Args: protocol (str) name (str) """ return _robotsim.detach_from_stream(protocol, name)
[docs]def process_streams(*args) ->bool: r""" Does some processing on stream subscriptions. Args: protocol (str): either name the protocol to be updated, or "all" for updating all subscribed streams Returns: (bool): True if any stream was updated. """ return _robotsim.process_streams(*args)
[docs]def wait_for_stream(protocol: str, name: str, timeout: float) ->bool: r""" Waits up to timeout seconds for an update on the given stream. Args: protocol (str) name (str) timeout (float) Return: (bool): True if the stream was updated. """ return _robotsim.wait_for_stream(protocol, name, timeout)
[docs]def threejs_get_scene(arg1: "WorldModel") ->str: r""" Exports the WorldModel to a JSON string ready for use in Three.js. Args: arg1 (:class:`~klampt.WorldModel`) """ return _robotsim.threejs_get_scene(arg1)
[docs]def threejs_get_transforms(arg1: "WorldModel") ->str: r""" Exports the WorldModel to a JSON string ready for use in Three.js. Args: arg1 (:class:`~klampt.WorldModel`) """ return _robotsim.threejs_get_transforms(arg1)
[docs]def set_friction_cone_approximation_edges(numEdges: int) ->None: r""" Globally sets the number of edges used in the friction cone approximation. The default value is 4. Args: numEdges (int) """ return _robotsim.set_friction_cone_approximation_edges(numEdges)
[docs]def force_closure(*args) ->bool: r""" Returns true if the list of contact points has force closure. force_closure (contacts,m,n): bool force_closure (contactPositions,frictionCones): bool Returns: bool: In the 1-argument version, each contact point is specified by a list of 7 floats, [x,y,z,nx,ny,nz,k] where (x,y,z) is the position, (nx,ny,nz) is the normal, and k is the coefficient of friction. The 2-argument version is a "fancy" version that allows more control over the constraint planes. Args: contacts (list of 7-float lists or tuples): the list of contacts, each specified as a 7-list or tuple [x,y,z,nx,ny,nz,k], with: * (x,y,z): the contact position * (nx,ny,nz): the contact normal * k: the coefficient of friction (>= 0) contactPositions (list of 3-float lists or tuples): the list of contact point positions. frictionCones (list of lists): Each item of this list specifies linear inequalities that must be met of the force at the corresponding contact point. The item must have length k*4 where k is an integer, and each inequality gives the entries (ax,ay,az,b) of a constraint ax*fx+ay*fy+az*fz <= b that limits the contact force (fx,fy,fz) at the i'th contact. Each of the k 4-tuples is laid out sequentially per-contact. """ return _robotsim.force_closure(*args)
[docs]def force_closure_2d(*args) ->bool: r""" Returns true if the list of 2D contact points has force closure. force_closure_2d (contacts,m,n): bool force_closure_2d (contactPositions,frictionCones): bool Returns: bool: In the 1-argument version, each contact point is given by a list of 4 floats, [x,y,theta,k] where (x,y) is the position, theta is the normal angle, and k is the coefficient of friction The 2-argument version is a "fancy" version that allows more control over the constraint planes. Args: contacts (list of 4-float lists or tuples): the list of contacts, each specified as a 4-list or tuple [x,y,theta,k], with: * (x,y): the contact position * theta: is the normal angle (in radians, CCW to the x axis) * k: the coefficient of friction (>= 0) contactPositions (list of 2-float lists or tuples): the list of contact point positions. frictionCones (list of lists): The i'th element in this list has length k*3 (for some integer k), and gives the contact force constraints (ax,ay,b) where ax*fx+ay*fy <= b limits the contact force (fx,fy) at the i'th contact. Each of the k 3-tuples is laid out sequentially per-contact. """ return _robotsim.force_closure_2d(*args)
[docs]def com_equilibrium(*args) ->object: r""" Tests whether the given COM com is stable for the given contacts and the given external force fext. com_equilibrium (contacts,m,n,fext,com): :obj:`object` com_equilibrium (contactPositions,frictionCones,fext,com): :obj:`object` The 2-argument version is a "fancy" version that allows more control over the constraint planes. Args: contacts (list of 7-float lists or tuples): the list of contacts, each specified as a 7-list or tuple [x,y,z,nx,ny,nz,k], with: * (x,y,z): the contact position * (nx,ny,nz): the contact normal * k: the coefficient of friction (>= 0) contactPositions (list of 3-float lists or tuples): the list of contact point positions. frictionCones (list of lists): Each item of this list specifies linear inequalities that must be met of the force at the corresponding contact point. The item must have length k*4 where k is an integer, and each inequality gives the entries (ax,ay,az,b) of a constraint ax*fx+ay*fy+az*fz <= b that limits the contact force (fx,fy,fz) at the i'th contact. Each of the k 4-tuples is laid out sequentially per-contact. fext (3-tuple or list): the external force vector. com (3-tuple or list, or None): the center of mass coordinates. If None, assumes that you want to test whether ANY COM may be in equilibrium for the given contacts. Returns: bool, None, or list: if com is given, and there are feasible equilibrium forces, this returns a list of 3 tuples giving equilibrium forces at each of the contacts. None is returned if no such forces exist. If com = None, the result is True or False. """ return _robotsim.com_equilibrium(*args)
[docs]def com_equilibrium_2d(*args) ->object: r""" Tests whether the given COM com is stable for the given contacts and the given external force fext. com_equilibrium_2d (contacts,m,n,fext,com): :obj:`object` com_equilibrium_2d (contactPositions,frictionCones,fext,com): :obj:`object` The 2-argument version is a "fancy" version that allows more control over the constraint planes. Args: contacts (list of 4-float lists or tuples): the list of contacts, each specified as a 4-list or tuple [x,y,theta,k], with: * (x,y,z): the contact position * theta: is the normal angle (in radians, CCW to the x axis) * k: the coefficient of friction (>= 0) contactPositions (list of 2-float lists or tuples): the list of contact point positions. frictionCones (list of lists): The i'th element in this list has length k*3 (for some integer k), and gives the contact force constraints (ax,ay,b) where ax*fx+ay*fy <= b limits the contact force (fx,fy) at the i'th contact. Each of the k 3-tuples is laid out sequentially per-contact. fext (2-tuple or list): the external force vector. com (2-tuple or list, or None): the center of mass coordinates. If None, assumes that you want to test whether ANY COM may be in equilibrium for the given contacts. Returns: bool, None, or list: if com is given, and there are feasible equilibrium forces, this returns a list of 2-tuples giving equilibrium forces at each of the contacts. None is returned if no such forces exist. If com = None, the result is True or False. """ return _robotsim.com_equilibrium_2d(*args)
[docs]def support_polygon(*args) ->object: r""" Calculates the support polygon for a given set of contacts and a downward external force (0,0,-g). support_polygon (contacts,m,n): :obj:`object` support_polygon (contactPositions,frictionCones): :obj:`object` In the 1-argument version, a contact point is given by a list of 7 floats, [x,y,z,nx,ny,nz,k] as usual. The 2-argument version is a "fancy" version that allows more control over the constraint planes. Args: contacts (list of 7-float lists or tuples): the list of contacts, each specified as a 7-list or tuple [x,y,z,nx,ny,nz,k], with: * (x,y,z): the contact position * (nx,ny,nz): the contact normal * k: the coefficient of friction (>= 0) contactPositions (list of 3-float lists or tuples): the list of contact point positions. frictionCones (list of lists): Each item of this list specifies linear inequalities that must be met of the force at the corresponding contact point. The item must have length k*4 where k is an integer, and each inequality gives the entries (ax,ay,az,b) of a constraint ax*fx+ay*fy+az*fz <= b that limits the contact force (fx,fy,fz) at the i'th contact. Each of the k 4-tuples is laid out sequentially per-contact. Returns: list of 3-tuples: The sorted plane boundaries of the support polygon. The format of a plane is (nx,ny,ofs) where (nx,ny) are the outward facing normals, and ofs is the offset from 0. In other words to test stability of a com with x-y coordinates [x,y], you can test whether dot([nx,ny],[x,y]) <= ofs for all planes. Hint: with numpy, you can do:: Ab = np.array(supportPolygon(args)) A=Ab[:,0:2] b=Ab[:,2] myComEquilibrium = lambda x: np.all(np.dot(A,x)<=b) """ return _robotsim.support_polygon(*args)
[docs]def support_polygon_2d(*args) ->object: r""" Calculates the support polygon (interval) for a given set of contacts and a downward external force (0,-g). support_polygon_2d (contacts,m,n): :obj:`object` support_polygon_2d (contacts,frictionCones): :obj:`object` The 2-argument version is a "fancy" version that allows more control over the constraint planes. Args: contacts (list of 4-float lists or tuples): the list of contacts, each specified as a 4-list or tuple [x,y,theta,k], with: * (x,y,z): the contact position * theta: is the normal angle (in radians, CCW to the x axis) * k: the coefficient of friction (>= 0) contactPositions (list of 2-float lists or tuples): the list of contact point positions. frictionCones (list of lists): The i'th element in this list has length k*3 (for some integer k), and gives the contact force constraints (ax,ay,b) where ax*fx+ay*fy <= b limits the contact force (fx,fy) at the i'th contact. Each of the k 3-tuples is laid out sequentially per-contact. Returns: 2-tuple: gives the min/max extents of the support polygon. If the support interval is empty, (inf,inf) is returned. """ return _robotsim.support_polygon_2d(*args)
[docs]def equilibrium_torques(*args) ->object: r""" Solves for the torques / forces that keep the robot balanced against gravity. equilibrium_torques (robot,contacts,m,n,links,fext,norm=0): :obj:`object` equilibrium_torques (robot,contacts,m,n,links,fext,internalTorques,norm=0): :obj:`object` The problem being solved is :math:`min_{t,f_1,...,f_N} \|t\|_p` :math:`s.t. t_{int} + G(q) = t + sum_{i=1}^N J_i(q)^T f_i` :math:`|t| \leq t_{max}` :math:`f_i \in FC_i` Args: robot (RobotModel): the robot, posed in its current configuration contacts (ndarray): an N x 7 array of contact points, each given as 7-lists [x,y,z,nx,ny,nz,kFriction] links (list of N ints): a list of the links on which those contact points lie fext (list of 3 floats): the external force (e.g., gravity) norm (double): the torque norm to minimize. * If 0, minimizes the l-infinity norm (default) * If 1, minimizes the l-1 norm. * If 2, minimizes the l-2 norm (experimental, may not get good results). internalTorques (list of robot.numLinks() floats, optional): allows you to solve for dynamic situations, e.g., with coriolis forces taken into account. These are added to the RHS of the torque balance equation. If not given, t_int is assumed to be zero. To use dynamics, set the robot's joint velocities dq, calculate then calculate the torques via robot.torquesFromAccel(ddq), and pass the result into internalTorques. Returns: pair of lists, optional: a pair (torque,force) if a solution exists, giving valid joint torques t and frictional contact forces (f1,...,fn). None is returned if no solution exists. """ return _robotsim.equilibrium_torques(*args)
import warnings def _deprecated_func(oldName,newName): import sys mod = sys.modules[__name__] f = getattr(mod,newName) def depf(*args,**kwargs): warnings.warn("{} will be deprecated in favor of {} in a future version of Klampt".format(oldName,newName),DeprecationWarning) return f(*args,**kwargs) depf.__doc__ = 'Deprecated in a future version of Klampt. Use {} instead'.format(newName) setattr(mod,oldName,depf) _deprecated_func('SubscribeToStream','subscribe_to_stream') _deprecated_func('DetachFromStream','detach_from_stream') _deprecated_func('ProcessStreams','process_streams') _deprecated_func('WaitForStream','wait_for_stream') _deprecated_func('ThreeJSGetScene','threejs_get_scene') _deprecated_func('ThreeJSGetTransforms','threejs_get_transforms') _deprecated_func('setFrictionConeApproximationEdges','set_friction_cone_approximation_edges') _deprecated_func('forceClosure','force_closure') _deprecated_func('forceClosure2D','force_closure_2d') _deprecated_func('comEquilibrium','com_equilibrium') _deprecated_func('comEquilibrium2D','com_equilibrium_2d') _deprecated_func('supportPolygon','support_polygon') _deprecated_func('supportPolygon2D','support_polygon_2d') _deprecated_func('equilibriumTorques','equilibrium_torques') _deprecated_func('setRandomSeed','set_random_seed') def SampleTransform(obj): """Deprecated. Use ``obj.sampleTransform()`` instead. Args: obj (IKObjective or GeneralizedIKObjective) Returns: klampt se3 element. """ return obj.sampleTransform()