# 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
------------------------------
Args:
"""
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,List,Tuple,Iterator,Union,Optional,Dict
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)
import numpy as np
import types
[docs]
class TriangleMesh(object):
r"""
A 3D indexed triangle mesh class.
Args:
Attributes:
vertices (numpy array): an n x 3 array of vertices.
indices (numpy int32 array): an m x 3 list of triangle vertices, given
as indices into the vertices list, i.e., [[a1,b1,c2], [a2,b2,c2], ...]
Examples::
m = TriangleMesh()
m.addVertex((0,0,0))
m.addVertex((1,0,0))
m.addVertex((0,1,0))
m.addTriangle(0,1,2)
print(len(m.vertices)) #prints 3
print(len(m.indices)) #prints 1
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
__swig_destroy__ = _robotsim.delete_TriangleMesh
def __init__(self, *args):
r"""
__init__ (): :class:`~klampt.TriangleMesh`
__init__ (rhs): :class:`~klampt.TriangleMesh`
Args:
rhs (:class:`~klampt.TriangleMesh`, optional):
"""
_robotsim.TriangleMesh_swiginit(self, _robotsim.new_TriangleMesh(*args))
[docs]
def copy(self) -> "TriangleMesh":
r"""
Creates a standalone object that is a copy of this.
Returns:
TriangleMesh:
"""
return _robotsim.TriangleMesh_copy(self)
[docs]
def set(self, arg2: "TriangleMesh") -> None:
r"""
Copies the data of the argument into this.
Args:
arg2 (:class:`~klampt.TriangleMesh`)
"""
return _robotsim.TriangleMesh_set(self, arg2)
[docs]
def getVertices(self) -> "np.ndarray":
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: "np.ndarray") -> 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 addVertex(self, p: Point) -> None:
r"""
Adds a new vertex.
Args:
p (:obj:`list of 3 floats`)
"""
return _robotsim.TriangleMesh_addVertex(self, p)
[docs]
def getIndices(self) -> "np.ndarray":
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 triangle 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 addTriangleIndices(self, t: "int [3]") -> None:
r"""
Adds a new triangle.
Args:
t (:obj:`int [3]`)
"""
return _robotsim.TriangleMesh_addTriangleIndices(self, t)
[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)
dataPtr = property(_robotsim.TriangleMesh_dataPtr_get, _robotsim.TriangleMesh_dataPtr_set, doc=r"""dataPtr : p.void""")
isStandalone = property(_robotsim.TriangleMesh_isStandalone_get, _robotsim.TriangleMesh_isStandalone_set, doc=r"""isStandalone : bool""")
vertices = property(getVertices, setVertices)
"""The vertices of the mesh."""
indices = property(getIndices, setIndices)
"""The triangles of the mesh, given as indices into the vertices array."""
[docs]
def triangle(self, i) -> Tuple[Tuple[float,float,float],Tuple[float,float,float],Tuple[float,float,float]]:
"""
Returns the i'th triangle of the mesh as a tuple of 3 3-tuples.
Args:
"""
a,b,c = self.indices[i]
v = self.vertices
return (v[a],v[b],v[c])
[docs]
def triangleNoormals(self) -> np.ndarray:
"""
Computes outward triangle normals.
Args:
Returns:
An N x 3 matrix of triangle normals with N the number of triangles.
"""
verts=self.vertices
tris=self.indices
dba = verts[tris[:,1]]-verts[tris[:,0]]
dca = verts[tris[:,2]]-verts[tris[:,0]]
n = np.cross(dba,dca)
norms = np.linalg.norm(n,axis=1)[:, np.newaxis]
n = np.divide(n,norms,where=norms!=0)
return n
[docs]
def vertexNormals(self, area_weighted=True) -> np.ndarray:
"""
Computes outward vertex normals.
Args:
area_weighted (bool): whether to compute area-weighted average or
simple average.
Returns:
An N x 3 matrix of vertex normals with N the number of vertices.
"""
verts=self.vertices
tris=self.indices
dba = verts[tris[:,1]]-verts[tris[:,0]]
dca = verts[tris[:,2]]-verts[tris[:,0]]
n = np.cross(dba,dca)
normals = [np.zeros(3) for i in range(len(verts))]
if area_weighted:
for i,t in enumerate(tris):
for j in range(3):
normals[t[j]] += n[i]
else:
norms = np.linalg.norm(n,axis=1)[:, np.newaxis]
n = np.divide(n,norms,where=norms!=0)
for i,t in enumerate(tris):
for j in range(3):
normals[t[j]] += n[i]
normals = np.array(normals)
norms = np.linalg.norm(normals,axis=1)[:, np.newaxis]
return np.divide(normals,norms,where=norms!=0)
def __reduce__(self):
from klampt.io import loader
jsonobj = loader.to_json(self,'TriangleMesh')
return (loader.from_json,(jsonobj,'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.
Args:
Attributes:
points (numpy array): an nx3 numpy array of 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
__swig_destroy__ = _robotsim.delete_ConvexHull
def __init__(self, *args):
r"""
__init__ (): :class:`~klampt.ConvexHull`
__init__ (rhs): :class:`~klampt.ConvexHull`
Args:
rhs (:class:`~klampt.ConvexHull`, optional):
"""
_robotsim.ConvexHull_swiginit(self, _robotsim.new_ConvexHull(*args))
[docs]
def copy(self) -> "ConvexHull":
r"""
Creates a standalone object that is a copy of this.
Returns:
ConvexHull:
"""
return _robotsim.ConvexHull_copy(self)
[docs]
def set(self, arg2: "ConvexHull") -> None:
r"""
Copies the data of the argument into this.
Args:
arg2 (:class:`~klampt.ConvexHull`)
"""
return _robotsim.ConvexHull_set(self, arg2)
[docs]
def getPoints(self) -> "np.ndarray":
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: "np.ndarray") -> 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 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)
dataPtr = property(_robotsim.ConvexHull_dataPtr_get, _robotsim.ConvexHull_dataPtr_set, doc=r"""dataPtr : p.void""")
isStandalone = property(_robotsim.ConvexHull_isStandalone_get, _robotsim.ConvexHull_isStandalone_set, doc=r"""isStandalone : bool""")
points = property(getPoints, setPoints)
"""The points of the convex hull."""
def __reduce__(self):
from klampt.io import loader
jsonobj = loader.to_json(self,'ConvexHull')
return (loader.from_json,(jsonobj,'ConvexHull'))
# Register ConvexHull in _robotsim:
_robotsim.ConvexHull_swigregister(ConvexHull)
[docs]
class PointCloud(object):
r"""
A 3D point cloud class.
Args:
Attributes:
vertices (numpy array): a n x 3 array of vertices.
properties (numpy array): a n x k array of vertex properties. The
name of each property is either anonymous or retrieved by
`getPropertyName`.
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.addProperty('rgb')
#add 1 point with coordinates (0,0,0) and color #000000 (black)
pc.addPoint((0,0,0))
pc.setProperty(0,0)
print(len(pc.points)) # prints 1
#add another point with coordinates (1,2,3)
pc.addPoint([1,2,3])
#this prints 2
print(len(pc.points))
print(pc.points) #prints [[0,0,0],[1,2,3]]
#this prints (2,1), because there is 1 property category x 2 points
print(pc.properties.shape)
#this prints 0; this is the default value added when addPoint was called
print(pc.getProperty(1,0) )
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
__swig_destroy__ = _robotsim.delete_PointCloud
def __init__(self, *args):
r"""
__init__ (): :class:`~klampt.PointCloud`
__init__ (rhs): :class:`~klampt.PointCloud`
Args:
rhs (:class:`~klampt.PointCloud`, optional):
"""
_robotsim.PointCloud_swiginit(self, _robotsim.new_PointCloud(*args))
[docs]
def copy(self) -> "PointCloud":
r"""
Creates a standalone object that is a copy of this.
Returns:
PointCloud:
"""
return _robotsim.PointCloud_copy(self)
[docs]
def set(self, arg2: "PointCloud") -> None:
r"""
Copies the data of the argument into this.
Args:
arg2 (:class:`~klampt.PointCloud`)
"""
return _robotsim.PointCloud_set(self, arg2)
[docs]
def getPoints(self) -> "np.ndarray":
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: "np.ndarray") -> 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 addPoint(self, p: Point) -> int:
r"""
Adds a point. Sets all its properties to 0.
Args:
p (:obj:`list of 3 floats`)
Slow if properties are already set. Setting the points and properties as
matrices is faster.
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) -> Vector3:
r"""
Returns the position of the point at the given index.
Args:
index (int)
"""
return _robotsim.PointCloud_getPoint(self, index)
[docs]
def numProperties(self) -> int:
r"""
Returns the number of properties.
"""
return _robotsim.PointCloud_numProperties(self)
[docs]
def setPointsAndProperties(self, np_array2: "np.ndarray") -> None:
r"""
Sets all the points and m properties from the given n x (3+k) array.
Args:
np_array2 (:obj:`2D Numpy array of floats`)
"""
return _robotsim.PointCloud_setPointsAndProperties(self, np_array2)
[docs]
def setProperties(self, np_array2: "np.ndarray") -> None:
r"""
Sets all the properties of all points to the given nxk array.
Args:
np_array2 (:obj:`2D Numpy array of floats`)
"""
return _robotsim.PointCloud_setProperties(self, np_array2)
[docs]
def getProperties(self) -> "np.ndarray":
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_getProperties(self)
[docs]
def addProperty(self, *args) -> int:
r"""
Adds a new property with name pname, and sets values for this property to the
given length-n array.
addProperty (pname): int
addProperty (pname,np_array): int
Args:
pname (str):
np_array (:obj:`1D Numpy array of floats`, optional):
"""
return _robotsim.PointCloud_addProperty(self, *args)
[docs]
def setPropertyName(self, pindex: int, pname: str) -> None:
r"""
Sets the name of a given property.
Args:
pindex (int)
pname (str)
"""
return _robotsim.PointCloud_setPropertyName(self, pindex, pname)
[docs]
def getPropertyName(self, pindex: int) -> str:
r"""
Returns the name of a given property.
Args:
pindex (int)
"""
return _robotsim.PointCloud_getPropertyName(self, pindex)
[docs]
def propertyIndex(self, pname: str) -> int:
r"""
Returns the index of a named property or -1 if it does not exist.
Args:
pname (str)
"""
return _robotsim.PointCloud_propertyIndex(self, pname)
[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):
"""
return _robotsim.PointCloud_getProperty(self, *args)
[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 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: "np.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_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: "np.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: "np.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: "np.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: "np.ndarray", np_depth2: "np.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: "np.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: "np.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: "np.ndarray", np_depth2: "np.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)
dataPtr = property(_robotsim.PointCloud_dataPtr_get, _robotsim.PointCloud_dataPtr_set, doc=r"""dataPtr : p.void""")
isStandalone = property(_robotsim.PointCloud_isStandalone_get, _robotsim.PointCloud_isStandalone_set, doc=r"""isStandalone : bool""")
points = property(getPoints, setPoints)
"""The points of the point cloud."""
properties = property(getProperties, setProperties)
"""The properties of the point cloud."""
[docs]
def getPropertyNames(self) -> List[str]:
"""
Returns the names of the properties.
Args:
"""
return [self.getPropertyName(i) for i in range(self.numProperties())]
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: Union[Sequence[float],Dict[str,float]], depth : np.ndarray, depth_scale: float=1.0):
"""
Sets a structured point cloud from a depth image.
Args:
intrinsics (list or dict): intrinsics parameters [fx,fy,cx,cy] or a
dictionary containing keys 'fx', 'fy', 'cx', 'cy'.
depth (np.ndarray): the depth values, of shape (h,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.
"""
if isinstance(intrinsics,dict):
try:
intrinsics = intrinsics['fx'],intrinsics['fy'],intrinsics['cx'],intrinsics['cy']
except Exception:
raise ValueError("Invalid value for the intrinsics parameters")
elif 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: Union[Sequence[float],Dict[str,float]], color : np.ndarray, depth : np.ndarray, depth_scale: float=1.0):
"""
Sets a structured point cloud from a color,depth image pair.
Args:
intrinsics (list or dict): intrinsics parameters [fx,fy,cx,cy] or a
dictionary containing keys 'fx', 'fy', 'cx', 'cy'.
color (np.ndarray): the color values, of shape (h,w) or (h,w,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 shape (h,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.
"""
if isinstance(intrinsics,dict):
try:
intrinsics = intrinsics['fx'],intrinsics['fy'],intrinsics['cx'],intrinsics['cy']
except Exception:
raise ValueError("Invalid value for the intrinsics parameters")
elif 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)
[docs]
def getColors(self, format='rgb') -> np.ndarray:
"""
Returns the colors of the point cloud in the given format. If the
point cloud has no colors, this returns None. If the point cloud has no
colors but has opacity, this returns white colors.
Args:
format: describes the output color format, either:
- 'rgb': packed 32bit int, with the hex format 0xrrggbb (only 24
bits used),
- 'bgr': packed 32bit int, with the hex format 0xbbggrr (only 24
bits used),
- 'rgba': packed 32bit int, with the hex format 0xrrggbbaa,
- 'bgra': packed 32bit int, with the hex format 0xbbggrraa,
- 'argb': packed 32bit int, with the hex format 0xaarrggbb,
- 'abgr': packed 32bit int, with the hex format 0xaabbggrr,
- ('r','g','b'): triple with each channel in range [0,1]
- ('r','g','b','a'): tuple with each channel in range [0,1]
- 'channels': returns a list of channels, in the form (r,g,b) or
(r,g,b,a), where each value in the channel has range [0,1].
- 'opacity': returns opacity only, in the range [0,1].
Returns:
A an array of len(pc.points) colors corresponding to
the points in the point cloud. If format='channels', the return
value is a tuple (r,g,b) or (r,g,b,a).
"""
from klampt.model.geometry import point_cloud_colors
return point_cloud_colors(self,format)
[docs]
def setColors(self, colors : Union[list,np.ndarray], color_format='rgb',pc_property='auto'):
"""
Sets the colors of the point cloud.
Args:
colors (list or numpy.ndarray): the array of colors, and each color
can be either ints, tuples, or channels, depending on color_format.
color_format: describes the format of each element of ``colors``, and
can be:
- 'rgb': packed 32bit int, with the hex format 0xrrggbb (only 24
bits used),
- 'bgr': packed 32bit int, with the hex format 0xbbggrr (only 24
bits used),
- 'rgba': packed 32bit int, with the hex format 0xrrggbbaa,
- 'bgra': packed 32bit int, with the hex format 0xbbggrraa,
- 'argb': packed 32bit int, with the hex format 0xaarrggbb,
- 'abgr': packed 32bit int, with the hex format 0xaabbggrr,
- ('r','g','b'): triple with each channel in range [0,1]. Also use
this if colors is an n x 3 numpy array.
- ('r','g','b','a'): tuple with each channel in range [0,1]. Also
use this if colors is an n x 4 numpy array.
- 'channels': ``colors`` is a list of 3 or 4 channels, in the form
(r,g,b) or (r,g,b,a), where each element in a channel has range
[0,1].
- 'opacity': opacity only, in the range [0,1].
pc_property (str): describes to which property the colors should be
set. 'auto' determines chooses the property from the point cloud
if it's already colored, or color_format if not. 'channels' sets
the 'r', 'g', 'b', and optionally 'a' properties.
"""
from klampt.model.geometry import point_cloud_set_colors
return point_cloud_set_colors(self,colors,color_format,pc_property)
# 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.
Args:
Attributes:
type (str): Can be "Point", "Sphere", "Segment", "Triangle",
"Polygon", "AABB", and "Box". Semi-supported types include
"Ellipsoid", and "Cylinder".
properties (numpy array): 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
__swig_destroy__ = _robotsim.delete_GeometricPrimitive
def __init__(self, *args):
r"""
__init__ (): :class:`~klampt.GeometricPrimitive`
__init__ (rhs): :class:`~klampt.GeometricPrimitive`
Args:
rhs (:class:`~klampt.GeometricPrimitive`, optional):
"""
_robotsim.GeometricPrimitive_swiginit(self, _robotsim.new_GeometricPrimitive(*args))
[docs]
def copy(self) -> "GeometricPrimitive":
r"""
Creates a standalone object that is a copy of this.
Returns:
GeometricPrimitive:
"""
return _robotsim.GeometricPrimitive_copy(self)
[docs]
def set(self, arg2: "GeometricPrimitive") -> None:
r"""
Copies the data of the argument into this.
Args:
arg2 (:class:`~klampt.GeometricPrimitive`)
"""
return _robotsim.GeometricPrimitive_set(self, arg2)
[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 getType(self) -> str:
r"""
"""
return _robotsim.GeometricPrimitive_getType(self)
[docs]
def getProperties(self) -> None:
r"""
"""
return _robotsim.GeometricPrimitive_getProperties(self)
[docs]
def setProperties(self, np_array: "np.ndarray") -> None:
r"""
Args:
np_array (:obj:`1D Numpy array of floats`)
"""
return _robotsim.GeometricPrimitive_setProperties(self, np_array)
[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)
dataPtr = property(_robotsim.GeometricPrimitive_dataPtr_get, _robotsim.GeometricPrimitive_dataPtr_set, doc=r"""dataPtr : p.void""")
isStandalone = property(_robotsim.GeometricPrimitive_isStandalone_get, _robotsim.GeometricPrimitive_isStandalone_set, doc=r"""isStandalone : bool""")
type = property(getType)
"""The type of the geometric primitive."""
properties = property(getProperties, setProperties)
"""The properties of the geometric primitive. Type dependent."""
def __reduce__(self):
from klampt.io import loader
jsonobj = loader.to_json(self,'GeometricPrimitive')
return (loader.from_json,(jsonobj,'GeometricPrimitive'))
# Register GeometricPrimitive in _robotsim:
_robotsim.GeometricPrimitive_swigregister(GeometricPrimitive)
[docs]
class ImplicitSurface(object):
r"""
An axis-aligned volumetric grid representing a signed distance transform with >
0 indicating outside and < 0 indicating inside.
Args:
In general, values are associated with cells rather than vertices.
Cell (i,j,k) contains a 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)).
The field should be assumed sampled at the **centers** of cells, i.e., at
(w*(i+1/2),d*(j+1/2),h*(k+1/2)).
Attributes:
bmin (array of 3 doubles): contains the minimum bounds.
bmax (array of 3 doubles): contains the maximum bounds.
values (numpy array): contains a 3D array of
``dims[0] x dims[1] x dims[2]`` values.
truncationDistance (float): inf for SDFs, and the truncation distance
for TSDFs. Cells whose values are >= d are considered "sufficiently
far" and distance / tolerance queries outside of this range are
usually not meaningful.
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
__swig_destroy__ = _robotsim.delete_ImplicitSurface
def __init__(self, *args):
r"""
__init__ (): :class:`~klampt.ImplicitSurface`
__init__ (rhs): :class:`~klampt.ImplicitSurface`
Args:
rhs (:class:`~klampt.ImplicitSurface`, optional):
"""
_robotsim.ImplicitSurface_swiginit(self, _robotsim.new_ImplicitSurface(*args))
[docs]
def copy(self) -> "ImplicitSurface":
r"""
Creates a standalone object that is a copy of this.
Returns:
ImplicitSurface:
"""
return _robotsim.ImplicitSurface_copy(self)
[docs]
def getBmin(self) -> None:
r"""
"""
return _robotsim.ImplicitSurface_getBmin(self)
[docs]
def setBmin(self, bmin: Point) -> None:
r"""
Args:
bmin (:obj:`list of 3 floats`)
"""
return _robotsim.ImplicitSurface_setBmin(self, bmin)
[docs]
def getBmax(self) -> None:
r"""
"""
return _robotsim.ImplicitSurface_getBmax(self)
[docs]
def setBmax(self, bmax: Point) -> None:
r"""
Args:
bmax (:obj:`list of 3 floats`)
"""
return _robotsim.ImplicitSurface_setBmax(self, bmax)
[docs]
def resize(self, sx: int, sy: int, sz: int) -> None:
r"""
Resizes the x, y, and z dimensions of the grid.
Args:
sx (int)
sy (int)
sz (int)
"""
return _robotsim.ImplicitSurface_resize(self, sx, sy, sz)
[docs]
def set(self, *args) -> None:
r"""
Sets a specific element of a cell.
set (arg2)
set (value)
set (i,j,k,value)
Args:
arg2 (:class:`~klampt.ImplicitSurface`, optional):
value (float, optional):
i (int, optional):
j (int, optional):
k (int, optional):
"""
return _robotsim.ImplicitSurface_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.ImplicitSurface_get(self, i, j, k)
[docs]
def shift(self, dv: float) -> None:
r"""
Shifts the value uniformly.
Args:
dv (float)
"""
return _robotsim.ImplicitSurface_shift(self, dv)
[docs]
def scale(self, cv: float) -> None:
r"""
Scales the value uniformly.
Args:
cv (float)
"""
return _robotsim.ImplicitSurface_scale(self, cv)
[docs]
def getValues(self) -> "np.ndarray":
r"""
Returns a 3D Numpy array view of the values.
"""
return _robotsim.ImplicitSurface_getValues(self)
[docs]
def setValues(self, np_array3: "np.ndarray") -> None:
r"""
Sets the values to a 3D numpy array.
Args:
np_array3 (:obj:`3D Numpy array of floats`)
"""
return _robotsim.ImplicitSurface_setValues(self, np_array3)
[docs]
def setTruncationDistance(self, d: float) -> None:
r"""
Sets the truncation distance for TSDFs.
Args:
d (float)
"""
return _robotsim.ImplicitSurface_setTruncationDistance(self, d)
[docs]
def getTruncationDistance(self) -> float:
r"""
Retrieves the truncation distance for TSDFs.
"""
return _robotsim.ImplicitSurface_getTruncationDistance(self)
dataPtr = property(_robotsim.ImplicitSurface_dataPtr_get, _robotsim.ImplicitSurface_dataPtr_set, doc=r"""dataPtr : p.void""")
isStandalone = property(_robotsim.ImplicitSurface_isStandalone_get, _robotsim.ImplicitSurface_isStandalone_set, doc=r"""isStandalone : bool""")
bmin = property(getBmin, setBmin)
"""The lower bound of the domain."""
bmax = property(getBmax, setBmax)
"""The upper bound of the domain."""
[docs]
def setBounds(self, bounds):
"""
@deprecated
Args:
Provided for backwards compatibility
"""
import warnings
warnings.warn("ImplicitSurface.setBounds will be deprecated in favor of bmin, bmax attributes in a future version of Klampt",DeprecationWarning)
self.bmin = bounds[0:3]
self.bmax = bounds[3:6]
[docs]
def getBounds(self):
"""
@deprecated
Args:
Provided for backwards compatibility
"""
import warnings
warnings.warn("ImplicitSurface. getBounds will be deprecated in favor of bmin, bmax attributes in a future version of Klampt",DeprecationWarning)
return list(self.bmin) + list(self.bmax)
bounds = property(getBounds, setBounds)
"""Klampt 0.9 backwards compatibility accessor for the (bmin, bmax) pair."""
values = property(getValues, setValues)
"""The 3D array of values in the grid (numpy.ndarray)"""
def __reduce__(self):
from klampt.io import loader
jsonobj = loader.to_json(self,'ImplicitSurface')
return (loader.from_json,(jsonobj,'ImplicitSurface'))
# Register ImplicitSurface in _robotsim:
_robotsim.ImplicitSurface_swigregister(ImplicitSurface)
[docs]
class OccupancyGrid(object):
r"""
An occupancy grid with 1 indicating inside and 0 indicating outside. Can also be
a fuzzy (probabilistic / density) grid.
Args:
In general, values are associated with cells rather than vertices.
Cell (i,j,k) contains an occupancy / density 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)).
Attributes:
bmin (array of 3 doubles): contains the minimum bounds.
bmax (array of 3 doubles): contains the maximum bounds.
values (numpy array): contains a 3D array of
``dims[0] x dims[1] x dims[2]`` values.
occupancyThreshold (float): set to 0.5 by default. Collision
detection treats all cells whose values are greater than this
value as occupied.
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
__swig_destroy__ = _robotsim.delete_OccupancyGrid
def __init__(self, *args):
r"""
__init__ (): :class:`~klampt.OccupancyGrid`
__init__ (rhs): :class:`~klampt.OccupancyGrid`
Args:
rhs (:class:`~klampt.OccupancyGrid`, optional):
"""
_robotsim.OccupancyGrid_swiginit(self, _robotsim.new_OccupancyGrid(*args))
[docs]
def copy(self) -> "OccupancyGrid":
r"""
Creates a standalone object that is a copy of this.
Returns:
OccupancyGrid:
"""
return _robotsim.OccupancyGrid_copy(self)
[docs]
def getBmin(self) -> None:
r"""
"""
return _robotsim.OccupancyGrid_getBmin(self)
[docs]
def setBmin(self, bmin: Point) -> None:
r"""
Args:
bmin (:obj:`list of 3 floats`)
"""
return _robotsim.OccupancyGrid_setBmin(self, bmin)
[docs]
def getBmax(self) -> None:
r"""
"""
return _robotsim.OccupancyGrid_getBmax(self)
[docs]
def setBmax(self, bmax: Point) -> None:
r"""
Args:
bmax (:obj:`list of 3 floats`)
"""
return _robotsim.OccupancyGrid_setBmax(self, bmax)
[docs]
def resize(self, sx: int, sy: int, sz: int) -> None:
r"""
Resizes the x, y, and z dimensions of the grid.
Args:
sx (int)
sy (int)
sz (int)
"""
return _robotsim.OccupancyGrid_resize(self, sx, sy, sz)
[docs]
def set(self, *args) -> None:
r"""
Sets a specific element of a cell.
set (arg2)
set (value)
set (i,j,k,value)
Args:
arg2 (:class:`~klampt.OccupancyGrid`, optional):
value (float, optional):
i (int, optional):
j (int, optional):
k (int, optional):
"""
return _robotsim.OccupancyGrid_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.OccupancyGrid_get(self, i, j, k)
[docs]
def shift(self, dv: float) -> None:
r"""
Shifts the value uniformly.
Args:
dv (float)
"""
return _robotsim.OccupancyGrid_shift(self, dv)
[docs]
def scale(self, cv: float) -> None:
r"""
Scales the value uniformly.
Args:
cv (float)
"""
return _robotsim.OccupancyGrid_scale(self, cv)
[docs]
def getValues(self) -> "np.ndarray":
r"""
Returns a 3D Numpy array view of the values.
"""
return _robotsim.OccupancyGrid_getValues(self)
[docs]
def setValues(self, np_array3: "np.ndarray") -> None:
r"""
Sets the values to a 3D numpy array.
Args:
np_array3 (:obj:`3D Numpy array of floats`)
"""
return _robotsim.OccupancyGrid_setValues(self, np_array3)
[docs]
def setOccupancyThreshold(self, threshold: float) -> None:
r"""
Sets the threshold for collision detection.
Args:
threshold (float)
"""
return _robotsim.OccupancyGrid_setOccupancyThreshold(self, threshold)
[docs]
def getOccupancyThreshold(self) -> float:
r"""
Gets the threshold for collision detection.
"""
return _robotsim.OccupancyGrid_getOccupancyThreshold(self)
dataPtr = property(_robotsim.OccupancyGrid_dataPtr_get, _robotsim.OccupancyGrid_dataPtr_set, doc=r"""dataPtr : p.void""")
isStandalone = property(_robotsim.OccupancyGrid_isStandalone_get, _robotsim.OccupancyGrid_isStandalone_set, doc=r"""isStandalone : bool""")
bmin = property(getBmin, setBmin)
"""The lower bound of the domain."""
bmax = property(getBmax, setBmax)
"""The upper bound of the domain."""
[docs]
def setBounds(self, bounds):
"""
@deprecated
Args:
Provided for backwards compatibility
"""
import warnings
warnings.warn("OccupancyGrid.setBounds will be deprecated in favor of bmin, bmax attributes in a future version of Klampt",DeprecationWarning)
self.bmin = bounds[0:3]
self.bmax = bounds[3:6]
[docs]
def getBounds(self):
"""
@deprecated
Args:
Provided for backwards compatibility
"""
import warnings
warnings.warn("OccupancyGrid. getBounds will be deprecated in favor of bmin, bmax attributes in a future version of Klampt",DeprecationWarning)
return list(self.bmin) + list(self.bmax)
bounds = property(getBounds, setBounds)
"""Klampt 0.9 backwards compatibility accessor for the (bmin, bmax) pair."""
values = property(getValues, setValues)
"""The 3D array of values in the grid (numpy.ndarray)"""
def __reduce__(self):
from klampt.io import loader
jsonobj = loader.to_json(self,'OccupancyGrid')
return (loader.from_json,(jsonobj,'OccupancyGrid'))
# Register OccupancyGrid in _robotsim:
_robotsim.OccupancyGrid_swigregister(OccupancyGrid)
[docs]
class Heightmap(object):
r"""
A height (elevation) map or a depth map.
Args:
In elevation-map form (`viewport.perspective=false`), the values are the
z-height of the terrain at each grid point. In depth-map form
(`viewport.perspective=true`), the values are the depths of each grid point (not
distance) from the origin in the +z direction.
Note that unlike volume grid types, each grid entry is defined at a vertex, not
a cell. In elevation map form, the (i,j) cell is associated with the vertex
((i-cx)/fx,(n-1-j-cy)/fy,heights[i,j]) where n is `heights.shape[1]`. Note that
the y-axis is flipped in the heightmap compared to the viewport such that the
image is given in standard top-down convention.
In depth map form, the (i,j) cell is associated with the vertex
(d*(i-cx)/fx,d*(j-cy)/fy,d) where d=heights[i,j]. Note that the y-axis is not
flipped in this convention.
Attributes:
viewport (Viewport): contains the size (w,h), projection (perspective)
intrinsics (fx,fy,cx,cy), and pose (pose) of the heightmap
reference coordinate system. Note that to change the viewport, you
will need to use `vp = hm.viewport; vp.w = ...; hm.viewport = vp`.
heights (np.ndarray): contains a 2D array of (w,h) values.
colorImage (np.ndarray): contains a 3D image array of colors in
grayscale (h,w), RGB (h,w,3), or RGBA (h,w,4) format.
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
__swig_destroy__ = _robotsim.delete_Heightmap
def __init__(self, *args):
r"""
__init__ (): :obj:`Heightmap`
__init__ (rhs): :obj:`Heightmap`
Args:
rhs (:obj:`Heightmap`, optional):
"""
_robotsim.Heightmap_swiginit(self, _robotsim.new_Heightmap(*args))
[docs]
def copy(self) -> "Heightmap":
r"""
Creates a standalone object that is a copy of this.
Returns:
Heightmap:
"""
return _robotsim.Heightmap_copy(self)
[docs]
def resize(self, w: int, h: int) -> None:
r"""
Resizes the height map.
Args:
w (int)
h (int)
"""
return _robotsim.Heightmap_resize(self, w, h)
[docs]
def setSize(self, width: float, height: float) -> None:
r"""
Sets an orthographic projection (elevation map) with the given width and height.
Args:
width (float)
height (float)
"""
return _robotsim.Heightmap_setSize(self, width, height)
[docs]
def setFOV(self, fovx: float, fovy: float=-1) -> None:
r"""
Sets an perspective projection (depth map) with the given x and y fields of view
and centered focal point. If fovy=-1, then it will be set so that pixels are
square.
Args:
fovx (float)
fovy (float, optional): default value -1
"""
return _robotsim.Heightmap_setFOV(self, fovx, fovy)
[docs]
def setIntrinsics(self, fx: float, fy: float, cx: float=-1, cy: float=-1) -> None:
r"""
Sets an perspective projection (depth map) with the given intrinsics fx, fy, cx,
cy. If cx or cy are negative, then cx = (w-1)/2, cy = (h-1)/2.
Args:
fx (float)
fy (float)
cx (float, optional): default value -1
cy (float, optional): default value -1
"""
return _robotsim.Heightmap_setIntrinsics(self, fx, fy, cx, cy)
[docs]
def isPerspective(self) -> bool:
r"""
Returns true if the heightmaps is in perspective (depth map) mode.
"""
return _robotsim.Heightmap_isPerspective(self)
[docs]
def isOrthographic(self) -> bool:
r"""
Returns true if the heightmaps is in orthographic (elevation map) mode.
"""
return _robotsim.Heightmap_isOrthographic(self)
[docs]
def getViewport(self) -> "Viewport":
r"""
Retrieves the viewport.
Returns:
Viewport:
"""
return _robotsim.Heightmap_getViewport(self)
[docs]
def setViewport(self, viewport: "Viewport") -> None:
r"""
Sets the viewport.
Args:
viewport (:class:`~klampt.Viewport`)
"""
return _robotsim.Heightmap_setViewport(self, viewport)
[docs]
def set(self, *args) -> None:
r"""
Sets the height of a vertex (note, indices are x and y units, which is reversed
from image convention)
set (arg2)
set (value)
set (i,j,value)
Args:
arg2 (:obj:`Heightmap`, optional):
value (float, optional):
i (int, optional):
j (int, optional):
"""
return _robotsim.Heightmap_set(self, *args)
[docs]
def get(self, i: int, j: int) -> float:
r"""
Gets the height of a vertex (note, indices are x and y units, which is reversed
from image convention)
Args:
i (int)
j (int)
"""
return _robotsim.Heightmap_get(self, i, j)
[docs]
def shift(self, dh: float) -> None:
r"""
Shifts the height uniformly.
Args:
dh (float)
"""
return _robotsim.Heightmap_shift(self, dh)
[docs]
def scale(self, c: float) -> None:
r"""
Scales the height uniformly.
Args:
c (float)
"""
return _robotsim.Heightmap_scale(self, c)
[docs]
def getHeights(self) -> "np.ndarray":
r"""
Returns a 2D Numpy array view of the values. Result has shape w x h and has
float32 dtype.
"""
return _robotsim.Heightmap_getHeights(self)
[docs]
def setHeights_f(self, np_array2: Vector) -> None:
r"""
Sets the values to a 2D numpy array of shape w x h.
Args:
np_array2 (:obj:`2D Numpy array of np.float32`)
"""
return _robotsim.Heightmap_setHeights_f(self, np_array2)
[docs]
def hasColors(self) -> bool:
r"""
Returns true if colors are present.
"""
return _robotsim.Heightmap_hasColors(self)
[docs]
def clearColors(self) -> None:
r"""
Erases all colors.
"""
return _robotsim.Heightmap_clearColors(self)
[docs]
def setColor(self, *args) -> None:
r"""
Gets the RGBA color of a vertex (note, indices are x and y units, which is
reversed from image convention)
setColor (intensity)
setColor (rgba)
setColor (i,j,intensity)
setColor (i,j,rgba)
Args:
intensity (float, optional):
rgba (:obj:`double [4]`, optional):
i (int, optional):
j (int, optional):
"""
return _robotsim.Heightmap_setColor(self, *args)
[docs]
def getColor(self, i: int, j: int) -> "Tuple[float,float,float,float]":
r"""
Gets the RGBA color of a vertex (note, indices are x and y units, which is
reversed from image convention)
Args:
i (int)
j (int)
"""
return _robotsim.Heightmap_getColor(self, i, j)
[docs]
def getColorImage(self) -> "np.ndarray":
r"""
Returns a 3D Numpy array view of the color image (h x w x (1, 3, or 4)), with
rows ordered top to bottom.
"""
return _robotsim.Heightmap_getColorImage(self)
[docs]
def setColorImage_b(self, np_array3: "np.ndarray") -> None:
r"""
Sets the values to a 3D numpy array (h x w x 1, 3, or (1, 3, or 4)), with rows
ordered top to bottom.
Args:
np_array3 (:obj:`unsigned char *`)
"""
return _robotsim.Heightmap_setColorImage_b(self, np_array3)
[docs]
def setColorImage_i(self, np_array2: "np.ndarray") -> None:
r"""
Sets colors to a 32-bit RGBA image (size h x w) with rows ordered top to bottom.
Args:
np_array2 (:obj:`unsigned int *`)
"""
return _robotsim.Heightmap_setColorImage_i(self, np_array2)
[docs]
def getColorImage_i(self) -> "np.ndarray":
r"""
Retrieves a 32-bit RGBA image of the heightmap's colors (h x w)
"""
return _robotsim.Heightmap_getColorImage_i(self)
[docs]
def getColorImage_d(self) -> "np.ndarray":
r"""
Retrieves a floating point RGB, RGBA, or L image (h x w x (1, 3, or 4)) with
rows ordered from top to bottom.
"""
return _robotsim.Heightmap_getColorImage_d(self)
[docs]
def numProperties(self) -> int:
r"""
Returns the number of properties.
"""
return _robotsim.Heightmap_numProperties(self)
[docs]
def addProperty(self, *args) -> int:
r"""
Adds a new property and sets it to an array of size (w x h)
addProperty (pname): int
addProperty (pname,np_array2): int
Args:
pname (str):
np_array2 (:obj:`2D Numpy array of floats`, optional):
"""
return _robotsim.Heightmap_addProperty(self, *args)
[docs]
def propertyIndex(self, pname: str) -> int:
r"""
Retrieves the index associated with a property name.
Args:
pname (str)
"""
return _robotsim.Heightmap_propertyIndex(self, pname)
[docs]
def setProperty(self, i: int, j: int, np_array: "np.ndarray") -> None:
r"""
Retrieves a property index Sets an individual pixel's property vector.
Args:
i (int)
j (int)
np_array (:obj:`1D Numpy array of floats`)
"""
return _robotsim.Heightmap_setProperty(self, i, j, np_array)
[docs]
def getProperty(self, i: int, j: int) -> "np.ndarray":
r"""
Retrieves an individual pixel's property vector.
Args:
i (int)
j (int)
"""
return _robotsim.Heightmap_getProperty(self, i, j)
[docs]
def setProperties(self, pindex: int, np_array2: "np.ndarray") -> None:
r"""
Sets a property to an array of size (w x h)
Args:
pindex (int)
np_array2 (:obj:`2D Numpy array of floats`)
"""
return _robotsim.Heightmap_setProperties(self, pindex, np_array2)
[docs]
def getProperties(self, pindex: int) -> "np.ndarray":
r"""
Retrieves a view of the property of size (w x h)
Args:
pindex (int)
"""
return _robotsim.Heightmap_getProperties(self, pindex)
dataPtr = property(_robotsim.Heightmap_dataPtr_get, _robotsim.Heightmap_dataPtr_set, doc=r"""dataPtr : p.void""")
isStandalone = property(_robotsim.Heightmap_isStandalone_get, _robotsim.Heightmap_isStandalone_set, doc=r"""isStandalone : bool""")
def __reduce__(self):
from klampt.io import loader
jsonobj = loader.to_json(self,'Heightmap')
return (loader.from_json,(jsonobj,'Heightmap'))
[docs]
def setHeights(self, arr : 'np.ndarray'):
"""
Sets heights from a numpy array. Handles conversions to float32.
Note that the x,y indexing differs from image orientation. If you want
to set heights from an image with (row,col) ordering, use
setHeightImage.
Args:
arr (np.ndarray): the height values, of shape (w,h).
"""
self.setHeights_f(arr.astype(np.float32))
[docs]
def setHeightImage(self, img : 'np.ndarray', height_scale : float= 1.0):
"""
Sets heights from a height image. Handles image orientation.
Args:
img (np.ndarray): the height values, of shape (h,w). Should have
dtype float, np.float32, or np.uint16 for best performance.
height_scale (float, optional): converts depth image values to real
depth units.
"""
if len(img.shape) != 2:
raise ValueError("Invalid shape for the height image")
img = img.swapaxes(0,1)
return self.setHeights(img*height_scale)
[docs]
def getHeightImage(self) -> 'np.ndarray':
"""
Gets heights as a height image. Handles image orientation.
Result has float32 dtype.
Args:
Returns:
np.ndarray: the height values, of shape (h,w).
"""
img = self.getHeights()
return img.swapaxes(0,1)
[docs]
def getHeightImage_b(self) -> Tuple['np.ndarray',float]:
"""
Gets heights as a uint8 height image. Handles image orientation.
Args:
Returns:
np.ndarray, float: the height values, of shape (h,w) and dtype
uint8, and the height scale.
"""
himg = self.getHeightImage()
h_max = np.max(himg)
return (np.clip((himg/h_max)*255.0,0,255).astype(np.uint8),h_max)
[docs]
def getHeightImage_s(self) -> Tuple['np.ndarray',float]:
"""
Gets heights as a uint16 height image. Handles image orientation.
Args:
Returns:
np.ndarray, float: the height values, of shape (h,w) and dtype
uint16, and the height scale.
"""
himg = self.getHeightImage()
h_max = np.max(himg)
return (np.clip((himg/h_max)*65535.0,0,65535).astype(np.uint16),h_max)
[docs]
def setColorImage(self, img : 'np.ndarray'):
"""
Sets colors from a color image.
Args:
img (np.ndarray): the color values, of shape (h,w) or (h,w,3) or
(h,w,4). Should have dtype float, np.float32, np.uint32
(RGBA 32-bit), or np.uint8.
"""
if len(img.shape) != 2 and len(img.shape) != 3:
raise ValueError("Invalid shape for the color image")
if len(img.shape) == 2:
if img.dtype == np.uint32:
return self.setColorImage_i(img)
elif img.dtype == np.uint8:
return self.setColorImage_b(img.reshape(img.shape[0],img.shape[1],1))
elif img.dtype == float or img.dtype == np.float32:
return self.setColorImage_b((img.reshape(img.shape[0],img.shape[1],1)*255.0).astype(np.uint8))
else:
raise ValueError("Invalid dtype for the color image, can use np.uint32, np.uint8, or float")
else:
if img.shape[2] != 3 and img.shape[2] != 4:
raise ValueError("Invalid shape for the color image")
if img.dtype == np.uint8:
return self.setColorImage_b(img)
elif img.dtype == float or img.dtype == np.float32:
return self.setColorImage_b((img*255.0).astype(np.uint8))
else:
raise ValueError("Invalid dtype for the height image, can use float or np.uint8")
[docs]
def setPropertyImage(self, pindex : int, img : 'np.ndarray'):
"""
Sets property channel pindex to a numpy image.
Handles image orientation.
Args:
pindex (int): the property index.
img (np.ndarray): the property values, of shape (h,w).
"""
if len(img.shape) != 2:
raise ValueError("Invalid shape for the property image")
img = img.swapaxes(0,1)
return self.setProperties(pindex,img)
heights = property(getHeights, setHeights)
colorImage = property(getColorImage, setColorImage)
viewport = property(getViewport, setViewport)
# Register Heightmap in _robotsim:
_robotsim.Heightmap_swigregister(Heightmap)
[docs]
class DistanceQuerySettings(object):
r"""
Configures the _ext distance queries of :class:`~klampt.Geometry3D`.
Args:
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`.
Args:
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)
# Register ContactQueryResult in _robotsim:
_robotsim.ContactQueryResult_swigregister(ContactQueryResult)
[docs]
class Geometry3D(object):
r"""
The three-D geometry container used throughout Klampt.
Args:
There are eight currently supported types of geometry:
* primitives (:class:`GeometricPrimitive`)
* convex hulls (:class:`ConvexHull`)
* triangle meshes (:class:`TriangleMesh`)
* point clouds (:class:`PointCloud`)
* implicit surfaces (:class:`ImplicitSurface`)
* occupancy grids (:class:`OccupancyGrid`)
* heightmaps (:class:`Heightmap`)
* groups ("Group" type)
For now we also support the "VolumeGrid" identifier which is treated as an
alias for "ImplicitSurface". This will be deprecated in a future version
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,
PointCloud, ImplicitSurface, OccupancyGrid, and Heightmap 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.TriangleMesh` or :class:`~klampt.ImplicitSurface` or :class:`~klampt.Geometry3D` or :class:`~klampt.OccupancyGrid` or :class:`~klampt.ConvexHull` or :class:`~klampt.PointCloud` or :obj:`Heightmap` or :class:`~klampt.GeometricPrimitive`, optional):
"""
_robotsim.Geometry3D_swiginit(self, _robotsim.new_Geometry3D(*args))
__swig_destroy__ = _robotsim.delete_Geometry3D
[docs]
def copy(self) -> "Geometry3D":
r"""
Creates a standalone geometry from this geometry.
Returns:
Geometry3D:
"""
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)
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: GeometricPrimitive, ConvexHull, TriangleMesh,
PointCloud, ImplicitSurface, OccupancyGrid, Heightmap, 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.
Returns:
TriangleMesh:
"""
return _robotsim.Geometry3D_getTriangleMesh(self)
[docs]
def getPointCloud(self) -> "PointCloud":
r"""
Returns a PointCloud if this geometry is of type PointCloud.
Returns:
PointCloud:
"""
return _robotsim.Geometry3D_getPointCloud(self)
[docs]
def getGeometricPrimitive(self) -> "GeometricPrimitive":
r"""
Returns a GeometricPrimitive if this geometry is of type GeometricPrimitive.
Returns:
GeometricPrimitive:
"""
return _robotsim.Geometry3D_getGeometricPrimitive(self)
[docs]
def getConvexHull(self) -> "ConvexHull":
r"""
Returns a ConvexHull if this geometry is of type ConvexHull.
Returns:
ConvexHull:
"""
return _robotsim.Geometry3D_getConvexHull(self)
[docs]
def getImplicitSurface(self) -> "ImplicitSurface":
r"""
Returns the ImplicitSurface if this geometry is of type ImplicitSurface.
Returns:
ImplicitSurface:
"""
return _robotsim.Geometry3D_getImplicitSurface(self)
[docs]
def getOccupancyGrid(self) -> "OccupancyGrid":
r"""
Returns the OccupancyGrid if this geometry is of type OccupancyGrid.
Returns:
OccupancyGrid:
"""
return _robotsim.Geometry3D_getOccupancyGrid(self)
[docs]
def getHeightmap(self) -> "Heightmap":
r"""
Returns the Heightmap if this geometry is of type Heightmap.
Returns:
Heightmap:
"""
return _robotsim.Geometry3D_getHeightmap(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 setImplicitSurface(self, grid: "ImplicitSurface") -> None:
r"""
Sets this Geometry3D to an ImplicitSurface.
Args:
grid (:class:`~klampt.ImplicitSurface`)
"""
return _robotsim.Geometry3D_setImplicitSurface(self, grid)
[docs]
def setOccupancyGrid(self, grid: "OccupancyGrid") -> None:
r"""
Sets this Geometry3D to an OccupancyGrid.
Args:
grid (:class:`~klampt.OccupancyGrid`)
"""
return _robotsim.Geometry3D_setOccupancyGrid(self, grid)
[docs]
def setHeightmap(self, hm: "Heightmap") -> None:
r"""
Sets this Geometry3D to a Heightmap.
Args:
hm (:obj:`Heightmap`)
"""
return _robotsim.Geometry3D_setHeightmap(self, hm)
[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.
Returns:
Geometry3D:
"""
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 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 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) -> "Tuple[Vector3,Vector3]":
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) -> "Tuple[Vector3,Vector3]":
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 -> ImplicitSurface. 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 -> OccupancyGrid. Converted using rasterization. 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.
* TriangleMesh -> Heightmap. Converted using rasterization. param is the grid
resolution, by default set to max mesh dimension / 256.
* 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 -> OccupancyGrid. param is the grid resolution, by default some
reasonable number.
* PointCloud -> ConvexHull. Converted using SOLID / Qhull.
* PointCloud -> Heightmap. param is the grid resolution, by default set to max
point cloud dimension / 256.
* GeometricPrimitive -> anything. param determines the desired resolution.
* ImplicitSurface -> TriangleMesh. param determines the level set for the
marching cubes algorithm.
* ImplicitSurface -> PointCloud. param determines the level set.
* ImplicitSurface -> Heightmap.
* OccupancyGrid -> TriangleMesh. Creates a mesh around each block.
* OccupancyGrid -> PointCloud. Outputs a point for each block.
* OccupancyGrid -> Heightmap.
* ConvexHull -> TriangleMesh.
* ConvexHull -> PointCloud. param is the desired dispersion of the points.
Equivalent to ConvexHull -> TriangleMesh -> PointCloud
Returns:
Geometry3D:
"""
return _robotsim.Geometry3D_convert(self, type, param)
[docs]
def contains_point(self, pt: Point) -> bool:
r"""
Returns true if this geometry contains the given point.
Args:
pt (:obj:`list of 3 floats`)
An approximate method is used for TriangleMesh. For PointCloud, the point is
considered to be contained if it is one of the points in the cloud, or if points
have a radius attribute, within the given radius.
"""
return _robotsim.Geometry3D_contains_point(self, pt)
[docs]
def collides(self, other: "Geometry3D") -> bool:
r"""
Returns true if this geometry collides with the other.
Args:
other (:class:`~klampt.Geometry3D`)
Unsupported types:
* ImplicitSurface - GeometricPrimitive [aabb, box, triangle, polygon]
* ImplicitSurface - ConvexHull
"""
return _robotsim.Geometry3D_collides(self, other)
[docs]
def collides_ext(self, other: "Geometry3D", maxContacts: int) -> "Tuple[list,list]":
r"""
Same as collide, but will also return the elements of each geometry that
collide.
Args:
other (:class:`~klampt.Geometry3D`)
maxContacts (int)
Returns: (elem1, elem2) where elem1 and elem2 are the indices of the elements
that collide. If len(elem1) == 0, then there is no detected collision.
"""
return _robotsim.Geometry3D_collides_ext(self, other, maxContacts)
[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 withinDistance_ext(self, other: "Geometry3D", tol: float, maxContacts: int) -> "Tuple[list,list]":
r"""
Same as withinDistance, but will also return the elements of each geometry that
are within distance tol.
Args:
other (:class:`~klampt.Geometry3D`)
tol (float)
maxContacts (int)
Returns: (elem1, elem2) where elem1 and elem2 are the indices of the elements
that are within distance tol. If len(elem1) == 0, then there is no detected
proximity.
"""
return _robotsim.Geometry3D_withinDistance_ext(self, other, tol, maxContacts)
[docs]
def distance_simple(self, other: "Geometry3D", relErr: float=0, absErr: float=0) -> float:
r"""
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.
Args:
other (:class:`~klampt.Geometry3D`)
relErr (float, optional): default value 0
absErr (float, optional): default value 0
"""
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
* ImplictSurface
* Heightmap (approximate, only accurate in the viewing direction)
* 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.
Returns:
DistanceQueryResult:
"""
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`)
Returns:
DistanceQueryResult:
"""
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 (missing some for boxes, segments, and
tris)
* GeometricPrimitive-TriangleMesh (surface only)
* GeometricPrimitive-PointCloud
* GeometricPrimitive-ImplicitSurface
* TriangleMesh (surface only)-GeometricPrimitive
* PointCloud-ImplicitSurface
* PointCloud-ConvexHull
* ConvexHull-ConvexHull
* ConvexHull-GeometricPrimitive
If penetration is supported, a negative distance is returned and cp1,cp2 are the
deepest penetrating points.
Unsupported types:
* PointCloud-PointCloud
* ImplicitSurface-TriangleMesh
* ImplicitSurface-ImplicitSurface
* OccupancyGrid - anything
* ConvexHull - anything else besides ConvexHull
See the comments of the distance_point function
Returns:
DistanceQueryResult:
"""
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`)
Returns:
DistanceQueryResult:
"""
return _robotsim.Geometry3D_distance_ext(self, other, settings)
[docs]
def rayCast(self, s: Point, d: Point) -> "Tuple[bool,Vector3]":
r"""
Performs a ray cast.
Args:
s (:obj:`list of 3 floats`)
d (:obj:`list of 3 floats`)
All types supported, but PointCloud needs a positive collision margin, or points
need to have a 'radius' property assigned)
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) -> "Tuple[int,Vector3]":
r"""
A more sophisticated ray cast.
Args:
s (:obj:`list of 3 floats`)
d (:obj:`list of 3 floats`)
All types supported, but PointCloud needs a positive collision
margin, or points need to have a 'radius' property assigned) 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 support(self, dir: Point) -> Vector3:
r"""
Calculates the furthest point on this geometry in the direction dir.
Args:
dir (:obj:`list of 3 floats`)
Supported types:
* ConvexHull
* GeometricPrimitive
* PointCloud
* TriangleMesh
* OccupancyGrid
"""
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.
Returns:
Geometry3D:
"""
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
Returns:
Geometry3D:
"""
return _robotsim.Geometry3D_roi(self, query, bmin, bmax)
[docs]
def merge(self, other: "Geometry3D") -> None:
r"""
Merges another geometry into this geometry. The result is stored inplace and the
type of the result is the same as this geometry. This can be used to calculate
the union of PointClouds, TriangleMeshes, ConvexPolytopes, and ImplicitSurfaces,
OccupancyGrids, and Heightmaps.
Args:
other (:class:`~klampt.Geometry3D`)
ImplicitSurface, OccupancyGrid, and Heightmap merges preserve the domain of the
current grid. They can also be merged with many other geometries.
"""
return _robotsim.Geometry3D_merge(self, other)
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.
Args:
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.
Returns:
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)
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):
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) -> "Tuple[float,float,float,float]":
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 getColors(self, feature: int) -> "np.ndarray":
r"""
Retrieves per-element color for elements of the given feature type. If per-
element colors are not enabled, then a 1 x 4 array is returned. Otherwise,
returns an m x 4 array, where m is the number of featuress of that type.
Args:
feature (int)
"""
return _robotsim.Appearance_getColors(self, feature)
[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) -> "Tuple[float,float,float,float]":
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) -> "Tuple[float,float,float,float]":
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: "np.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: "np.ndarray") -> None:
r"""
Sets a 1D texture of the given width. Valid format strings are.
Args:
format (str)
np_array (:obj:`unsigned 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)
[docs]
def setTexture1D_channels(self, format: str, np_array2: "np.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 getTexture1D_format(self) -> str:
r"""
Retrieves a 1D texture format, returning '' if the texture is not set.
"""
return _robotsim.Appearance_getTexture1D_format(self)
[docs]
def getTexture1D_channels(self) -> "np.ndarray":
r"""
Retrieves a view into the 1D texture data. If the texture is not set, throws an
exception.
"""
return _robotsim.Appearance_getTexture1D_channels(self)
[docs]
def setTexture2D_b(self, format: str, np_array2: "np.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: "np.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: "np.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 getTexture2D_format(self) -> str:
r"""
Retrieves a 2D texture format, returning '' if the texture is not set.
"""
return _robotsim.Appearance_getTexture2D_format(self)
[docs]
def getTexture2D_channels(self) -> "np.ndarray":
r"""
Retrieves a view into the 2D texture data. If the texture is not set, throws an
exception.
"""
return _robotsim.Appearance_getTexture2D_channels(self)
[docs]
def setTexcoords1D(self, np_array: "np.ndarray") -> 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 getTexcoords1D(self) -> "np.ndarray":
r"""
Gets per-vertex texture coordinates for a 1D texture. If no 1D texture is set,
throws an exception.
"""
return _robotsim.Appearance_getTexcoords1D(self)
[docs]
def setTexcoords2D(self, np_array2: "np.ndarray") -> 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 getTexcoords2D(self) -> "np.ndarray":
r"""
Gets per-vertex texture coordinates for a 2D texture. If no 2D texture is set,
throws an exception.
"""
return _robotsim.Appearance_getTexcoords2D(self)
[docs]
def setTexgen(self, np_array2: "np.ndarray", 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 getTexgenMatrix(self) -> "np.ndarray":
r"""
Retrieves the texture generation. The array will be size m x 4, with m in the
range 0,...,4. The texture generation is performed in
"""
return _robotsim.Appearance_getTexgenMatrix(self)
[docs]
def isTexgenWorld(self) -> bool:
r"""
Returns whether texture generation is performed in world coordinates.
"""
return _robotsim.Appearance_isTexgenWorld(self)
[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.
"""
array = np.asarray(array)
if len(array.shape) == 1:
if array.dtype == np.uint8:
return self.setTexture1D_b(format,array)
else:
return self.setTexture1D_i(format,array)
elif len(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.
"""
array = np.asarray(array)
if len(array.shape) == 2:
if array.dtype == np.uint8:
return self.setTexture2D_b(format,array)
else:
return self.setTexture2D_i(format,array)
elif len(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.
"""
array = np.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)
# Register Widget in _robotsim:
_robotsim.Widget_swigregister(Widget)
# Register WidgetSet in _robotsim:
_robotsim.WidgetSet_swigregister(WidgetSet)
[docs]
class PointPoser(Widget):
r"""
Args:
"""
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)
# Register TransformPoser in _robotsim:
_robotsim.TransformPoser_swigregister(TransformPoser)
[docs]
class ObjectPoser(Widget):
r"""
Args:
"""
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"""
Args:
"""
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"""
Args:
"""
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"""
Args:
"""
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"""
Args:
"""
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 Viewport(object):
r"""
A class that represents an idealized pinhole camera.
Args:
Duplicates the functioning of KrisLibrary/Camera/Viewport.
C++ includes: viewport.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.Viewport_swiginit(self, _robotsim.new_Viewport())
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 fromText(self, str: str) -> bool:
r"""
Args:
str (str)
"""
return _robotsim.Viewport_fromText(self, str)
def toText(self) -> str:
r"""
"""
return _robotsim.Viewport_toText(self)
def resize(self, w: int, h: int) -> None:
r"""
Resizes the viewport, keeping the same field of view and relative position of
the focal point.
Args:
w (int)
h (int)
"""
return _robotsim.Viewport_resize(self, w, h)
def setFOV(self, xfov: float, yfov: float=-1) -> None:
r"""
Sets the horizontal and optionally the vertical FOV. If yfov < 0, square pixels
will be assumed.
Args:
xfov (float)
yfov (float, optional): default value -1
"""
return _robotsim.Viewport_setFOV(self, xfov, yfov)
def getFOV(self) -> float:
r"""
Returns the horizontal FOV.
"""
return _robotsim.Viewport_getFOV(self)
def getVFOV(self) -> float:
r"""
Returns the vertical FOV.
"""
return _robotsim.Viewport_getVFOV(self)
def setPose(self, R: Rotation, t: Point) -> None:
r"""
Sets the pose of the camera.
Args:
R (:obj:`list of 9 floats (so3 element)`)
t (:obj:`list of 3 floats`)
"""
return _robotsim.Viewport_setPose(self, R, t)
def getPose(self) -> RigidTransform:
r"""
Gets the pose of the camera.
"""
return _robotsim.Viewport_getPose(self)
def viewRectangle(self, depth: float) -> "Tuple[float,float,float,float]":
r"""
Gets the viewing rectangle (xmin,ymin,xmax,ymax) at a given depth.
Args:
depth (float)
"""
return _robotsim.Viewport_viewRectangle(self, depth)
def project(self, pt: Point) -> Vector3:
r"""
Projects into image coordinates.
Args:
pt (:obj:`list of 3 floats`)
"""
return _robotsim.Viewport_project(self, pt)
def clickSource(self, x: float, y: float) -> Vector3:
r"""
Provides the source of a ray for an image coordinate (x,y)
Args:
x (float)
y (float)
"""
return _robotsim.Viewport_clickSource(self, x, y)
def clickDirection(self, x: float, y: float) -> Vector:
r"""
Provides the direction of a ray for an image coordinate (x,y)
Args:
x (float)
y (float)
"""
return _robotsim.Viewport_clickDirection(self, x, y)
perspective = property(_robotsim.Viewport_perspective_get, _robotsim.Viewport_perspective_set, doc=r"""perspective : bool""")
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""")
fx = property(_robotsim.Viewport_fx_get, _robotsim.Viewport_fx_set, doc=r"""fx : double""")
fy = property(_robotsim.Viewport_fy_get, _robotsim.Viewport_fy_set, doc=r"""fy : double""")
cx = property(_robotsim.Viewport_cx_get, _robotsim.Viewport_cx_set, doc=r"""cx : double""")
cy = property(_robotsim.Viewport_cy_get, _robotsim.Viewport_cy_set, doc=r"""cy : double""")
xform = property(_robotsim.Viewport_xform_get, _robotsim.Viewport_xform_set, doc=r"""xform : std::vector<(double,std::allocator<(double)>)>""")
ori = property(_robotsim.Viewport_ori_get, _robotsim.Viewport_ori_set, doc=r"""ori : std::string""")
def setClippingPlanes(self, cp):
"""
@deprecated
Args:
Provided for backwards compatibility.
"""
import warnings
warnings.warn("Viewport. clippingPlanes will be deprecated in favor of n,f attributes in a future version of Klampt",DeprecationWarning)
self.n, self.f = cp
def getClippingPlanes(self):
"""
@deprecated
Args:
Provided for backwards compatibility.
"""
import warnings
warnings.warn("Viewport. clippingPlanes will be deprecated in favor of n,f attributes in a future version of Klampt",DeprecationWarning)
return (self.n, self.f)
fov = property(getFOV, setFOV)
"""Convenience accessor for the field of view, in radians."""
clippingPlanes = property(getClippingPlanes, setClippingPlanes)
"""Klampt 0.9 backwards compatibility accessor for the (n, f) pair."""
__swig_destroy__ = _robotsim.delete_Viewport
# Register Viewport in _robotsim:
_robotsim.Viewport_swigregister(Viewport)
[docs]
class Mass(object):
r"""
Stores mass information for a rigid body or robot link.
Args:
.. note::
Recommended to use the set/get functions rather than changing the members
directly due to strangeness in SWIG's handling of vectors.
.. note:
The inertia matrix is specified in the local frame of the object
and centered at the center of mass.
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) -> Vector3:
r"""
Returns the COM.
"""
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) -> Vector:
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)
"""The object's center of mass in local coordinates (3-list)"""
inertia = property(getInertia, setInertia)
"""The object's inertia in local coordinates (9-list)"""
__swig_destroy__ = _robotsim.delete_Mass
# Register Mass in _robotsim:
_robotsim.Mass_swigregister(Mass)
# Register ContactParameters in _robotsim:
_robotsim.ContactParameters_swigregister(ContactParameters)
[docs]
class RobotModelLink(object):
r"""
A reference to a link of a RobotModel.
Args:
The link stores many mostly-constant items (id, name, parent, geometry,
appearance, mass, joint axes). There are two exceptions:
* the link's current transform, which is affected by the RobotModel's current
configuration, i.e., the last :meth:`RobotModel.setConfig` call.
* The various Jacobians of points on the link, accessed by
:meth:`RobotModelLink.getJacobian` ,
:meth:`RobotModelLink.getPositionJacobian` , and
:meth:`RobotModelLink.getOrientationJacobian` , which are configuration
dependent.
A RobotModelLink is not created by hand, but instead accessed using
:meth:`RobotModel.link` (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.RobotModelLink_swiginit(self, _robotsim.new_RobotModelLink())
[docs]
def getID(self) -> int:
r"""
Returns the ID of the robot link in its world.
.. note::
The world ID is not the same as the link's index, retrieved by
getIndex.
"""
return _robotsim.RobotModelLink_getID(self)
[docs]
def getName(self) -> str:
r"""
Returns the name of the robot link.
"""
return _robotsim.RobotModelLink_getName(self)
[docs]
def setName(self, name: str) -> None:
r"""
Sets the name of the robot link.
Args:
name (str)
"""
return _robotsim.RobotModelLink_setName(self, name)
[docs]
def robot(self) -> "RobotModel":
r"""
Returns a reference to the link's robot.
Returns:
RobotModel:
"""
return _robotsim.RobotModelLink_robot(self)
[docs]
def getIndex(self) -> int:
r"""
Returns the index of the link (on its robot).
"""
return _robotsim.RobotModelLink_getIndex(self)
[docs]
def getParentIndex(self) -> int:
r"""
Returns the index of the link's parent (on its robot). -1 indicates no parent.
"""
return _robotsim.RobotModelLink_getParentIndex(self)
[docs]
def setParentIndex(self, p: int) -> None:
r"""
Sets the index of the link's parent (on its robot).
Args:
p (int)
"""
return _robotsim.RobotModelLink_setParentIndex(self, p)
[docs]
def getParentLink(self) -> "RobotModelLink":
r"""
Returns a reference to the link's parent, or a NULL link if it has no parent.
Returns:
RobotModelLink:
"""
return _robotsim.RobotModelLink_getParentLink(self)
[docs]
def setParentLink(self, l: "RobotModelLink") -> None:
r"""
Sets the link's parent (must be on the same robot).
Args:
l (:class:`~klampt.RobotModelLink`)
"""
return _robotsim.RobotModelLink_setParentLink(self, l)
[docs]
def geometry(self) -> "Geometry3D":
r"""
Returns a reference to the link's geometry.
Returns:
Geometry3D:
"""
return _robotsim.RobotModelLink_geometry(self)
[docs]
def appearance(self) -> "Appearance":
r"""
Returns a reference to the link's appearance.
Returns:
Appearance:
"""
return _robotsim.RobotModelLink_appearance(self)
[docs]
def getMass(self) -> "Mass":
r"""
Returns the inertial properties of the link. (Note that the Mass is given with
origin at the link frame, not about the COM.)
Returns:
Mass:
"""
return _robotsim.RobotModelLink_getMass(self)
[docs]
def setMass(self, mass: "Mass") -> None:
r"""
Sets the inertial proerties of the link. (Note that the Mass is given with
origin at the link frame, not about the COM.)
Args:
mass (:class:`~klampt.Mass`)
"""
return _robotsim.RobotModelLink_setMass(self, mass)
[docs]
def getAxis(self) -> Vector3:
r"""
Gets the local rotational / translational axis.
"""
return _robotsim.RobotModelLink_getAxis(self)
[docs]
def setAxis(self, axis: Point) -> None:
r"""
Sets the local rotational / translational axis.
Args:
axis (:obj:`list of 3 floats`)
"""
return _robotsim.RobotModelLink_setAxis(self, axis)
[docs]
def isPrismatic(self) -> bool:
r"""
Returns whether the joint is prismatic.
"""
return _robotsim.RobotModelLink_isPrismatic(self)
[docs]
def isRevolute(self) -> bool:
r"""
Returns whether the joint is revolute.
"""
return _robotsim.RobotModelLink_isRevolute(self)
[docs]
def setPrismatic(self, prismatic: bool) -> None:
r"""
Changes a link from revolute to prismatic or vice versa.
Args:
prismatic (bool)
"""
return _robotsim.RobotModelLink_setPrismatic(self, prismatic)
[docs]
def getWorldPosition(self, plocal: Point) -> Vector3:
r"""
Converts point from local to world coordinates.
Args:
plocal (:obj:`list of 3 floats`)
Returns:
list of 3 floats: the world coordinates of the local point plocal
"""
return _robotsim.RobotModelLink_getWorldPosition(self, plocal)
[docs]
def getWorldDirection(self, vlocal: Point) -> Vector3:
r"""
Converts direction from local to world coordinates.
Args:
vlocal (:obj:`list of 3 floats`)
Returns:
list of 3 floats: the world coordinates of the local direction
vlocal
"""
return _robotsim.RobotModelLink_getWorldDirection(self, vlocal)
[docs]
def getLocalPosition(self, pworld: Point) -> Vector3:
r"""
Converts point from world to local coordinates.
Args:
pworld (:obj:`list of 3 floats`)
Returns:
list of 3 floats: the local coordinates of the world point pworld
"""
return _robotsim.RobotModelLink_getLocalPosition(self, pworld)
[docs]
def getLocalDirection(self, vworld: Point) -> Vector3:
r"""
Converts direction from world to local coordinates.
Args:
vworld (:obj:`list of 3 floats`)
Returns:
list of 3 floats: the local coordinates of the world direction
vworld
"""
return _robotsim.RobotModelLink_getLocalDirection(self, vworld)
[docs]
def getVelocity(self) -> Vector3:
r"""
Computes the velocity of the link's origin given the robot's current joint
configuration and velocities. Equivalent to getPointVelocity([0,0,0]).
Returns:
list of 3 floats: the current velocity of the link's origin, in
world coordinates
"""
return _robotsim.RobotModelLink_getVelocity(self)
[docs]
def getAngularVelocity(self) -> Vector3:
r"""
Computes the angular velocity of the link given the robot's current joint
configuration and velocities.
Returns:
list of 3 floats: the current angular velocity of the link, in world
coordinates
"""
return _robotsim.RobotModelLink_getAngularVelocity(self)
[docs]
def getPointVelocity(self, plocal: Point) -> Vector3:
r"""
Computes the world velocity of a point attached to the link, given the robot's
current joint configuration and velocities.
Args:
plocal (:obj:`list of 3 floats`)
Returns:
list of 3 floats: the current velocity of the point, in
world coordinates.
"""
return _robotsim.RobotModelLink_getPointVelocity(self, plocal)
[docs]
def getJacobian(self, plocal: Point) -> "np.ndarray":
r"""
Computes the total jacobian of a point on this link w.r.t. the robot's
configuration q.
Args:
plocal (:obj:`list of 3 floats`)
The orientation jacobian is given in the first 3 rows, and is stacked on the
position jacobian, which is given in the last 3 rows.
Returns:
ndarray: the 6xn total Jacobian matrix of the
point given by local coordinates plocal.
"""
return _robotsim.RobotModelLink_getJacobian(self, plocal)
[docs]
def getPositionJacobian(self, plocal: Point) -> "np.ndarray":
r"""
Computes the position jacobian of a point on this link w.r.t. the robot's
configuration q.
Args:
plocal (:obj:`list of 3 floats`)
This matrix J gives the point's velocity (in world coordinates) via
np.dot(J,dq), where dq is the robot's joint velocities.
Returns:
ndarray: the 3xn Jacobian matrix of the
point given by local coordinates plocal.
"""
return _robotsim.RobotModelLink_getPositionJacobian(self, plocal)
[docs]
def getOrientationJacobian(self) -> "np.ndarray":
r"""
Computes the orientation jacobian of this link w.r.t. the robot's configuration
q.
This matrix J gives the link's angular velocity (in world coordinates) via
np.dot(J,dq), where dq is the robot's joint velocities.
Returns:
ndarray:: the 3xn orientation Jacobian matrix of the link.
"""
return _robotsim.RobotModelLink_getOrientationJacobian(self)
[docs]
def getJacobianCols(self, plocal: Point, links: IntArray) -> "np.ndarray":
r"""
Returns the jacobian of a point on this link w.r.t. specified entries of the
robot's configuration q given by `links`.
Args:
plocal (:obj:`list of 3 floats`)
links (:obj:`list of int`)
The orientation jacobian is given in the first 3 rows, and is stacked on the
position jacobian, which is given in the last 3 rows.
Returns:
ndarray: the 6xlen(links) Jacobian matrix of the
point given by local coordinates plocal.
"""
return _robotsim.RobotModelLink_getJacobianCols(self, plocal, links)
[docs]
def getPositionJacobianCols(self, plocal: Point, links: IntArray) -> "np.ndarray":
r"""
Returns the position jacobian of a point on this link w.r.t. specified entries
of the robot's configuration q given by `links`.
Args:
plocal (:obj:`list of 3 floats`)
links (:obj:`list of int`)
This matrix J gives the point's velocity (in world coordinates) via
np.dot(J,dqlinks), where dqlinks are the joint velocities of the links in
`links`
Returns:
ndarray: the 3xlen(links) position Jacobian matrix of the
point given by local coordinates plocal.
"""
return _robotsim.RobotModelLink_getPositionJacobianCols(self, plocal, links)
[docs]
def getOrientationJacobianCols(self, links: IntArray) -> "np.ndarray":
r"""
Returns the orientation jacobian this link w.r.t. specified entries of the
robot's configuration q given by `links`.
Args:
links (:obj:`list of int`)
This matrix J gives the point's angular velocity (in world coordinates) via
np.dot(J,dqlinks), where dqlinks are the joint velocities of the links in
`links`
Returns:
ndarray: the 3xlen(links) orientation Jacobian matrix of the
link.
"""
return _robotsim.RobotModelLink_getOrientationJacobianCols(self, links)
[docs]
def getAcceleration(self, ddq: Vector) -> Vector3:
r"""
Computes the acceleration of the link origin given the robot's current joint
configuration and velocities, and the joint accelerations ddq.
Args:
ddq (:obj:`list of floats`)
ddq can be empty, which calculates the acceleration with acceleration 0, and is
a little faster than setting ddq to [0]*n
Returns:
list of 3 floats: the acceleration of the link's origin, in
world coordinates.
"""
return _robotsim.RobotModelLink_getAcceleration(self, ddq)
[docs]
def getPointAcceleration(self, plocal: Point, ddq: Vector) -> Vector3:
r"""
Computes the acceleration of the point given the robot's current joint
configuration and velocities, and the joint accelerations ddq.
Args:
plocal (:obj:`list of 3 floats`)
ddq (:obj:`list of floats`)
Returns:
list of 3 floats: the acceleration of the point, in
world coordinates.
"""
return _robotsim.RobotModelLink_getPointAcceleration(self, plocal, ddq)
[docs]
def getAngularAcceleration(self, ddq: Vector) -> Vector3:
r"""
Computes the angular acceleration of the link given the robot's current joint
configuration and velocities, and the joint accelerations ddq.
Args:
ddq (:obj:`list of floats`)
Returns:
list of 3 floats: the angular acceleration of the link, in
world coordinates.
"""
return _robotsim.RobotModelLink_getAngularAcceleration(self, ddq)
[docs]
def getPositionHessian(self, plocal: Point) -> "np.ndarray":
r"""
Computes the Hessians of each component of the position p w.r.t the robot's
configuration q.
Args:
plocal (:obj:`list of 3 floats`)
Returns:
ndarray: a 3xnxn array with each of the elements in the first axis
corresponding respectively, to the (x,y,z) components of the Hessian.
"""
return _robotsim.RobotModelLink_getPositionHessian(self, plocal)
[docs]
def getOrientationHessian(self) -> "np.ndarray":
r"""
Computes the pseudo-Hessians of each orientation component of the link w.r.t the
robot's configuration q. The pseudo-Hessian is the derivative of the angular
velocity of this link w.r.t. the joint velocities.
Returns:
ndarray: a 3xnxn array with each of the elements in the first axis
corresponding, respectively, to the (wx,wy,wz) components of the
pseudo-Hessian.
"""
return _robotsim.RobotModelLink_getOrientationHessian(self)
[docs]
def drawLocalGL(self, keepAppearance: bool=True) -> None:
r"""
Draws the link's geometry in its local frame. If keepAppearance=true, the
current Appearance is honored. Otherwise, just the geometry is drawn.
Args:
keepAppearance (bool, optional): default value True
"""
return _robotsim.RobotModelLink_drawLocalGL(self, keepAppearance)
[docs]
def drawWorldGL(self, keepAppearance: bool=True) -> None:
r"""
Draws the link's geometry in the world frame. If keepAppearance=true, the
current Appearance is honored. Otherwise, just the geometry is drawn.
Args:
keepAppearance (bool, optional): default value True
"""
return _robotsim.RobotModelLink_drawWorldGL(self, keepAppearance)
world = property(_robotsim.RobotModelLink_world_get, _robotsim.RobotModelLink_world_set, doc=r"""world : int""")
robotIndex = property(_robotsim.RobotModelLink_robotIndex_get, _robotsim.RobotModelLink_robotIndex_set, doc=r"""robotIndex : int""")
robotPtr = property(_robotsim.RobotModelLink_robotPtr_get, _robotsim.RobotModelLink_robotPtr_set, doc=r"""robotPtr : p.Klampt::RobotModel""")
index = property(_robotsim.RobotModelLink_index_get, _robotsim.RobotModelLink_index_set, doc=r"""index : int""")
[docs]
def setParent(self, index_or_link : Union[int,'RobotModelLink']):
"""
Args:
robot (:obj:`must be on same`)
"""
if isinstance(index_or_link, int):
self.setParentIndex(index_or_link)
else:
self.setParentLink(index_or_link)
[docs]
def getParent(self) -> int:
"""
Args:
robot (:obj:`on its`)
"""
return self.getParentIndex()
name = property(getName, setName)
parent = property(getParentIndex, setParent)
mass = property(getMass, setMass)
parentTransform = property(getParentTransform)
axis = property(getAxis,setAxis)
prismatic = property(isPrismatic,setPrismatic)
transform = property(getTransform)
__swig_destroy__ = _robotsim.delete_RobotModelLink
# Register RobotModelLink in _robotsim:
_robotsim.RobotModelLink_swigregister(RobotModelLink)
class RobotModelDriver(object):
r"""
A reference to a driver of a RobotModel.
Args:
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.
Returns:
RobotModel:
"""
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) -> "List[int]":
r"""
Returns the indices of the driver's affected links.
"""
return _robotsim.RobotModelDriver_getAffectedLinks(self)
def getAffineCoeffs(self) -> "Tuple[Vector,Vector]":
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) -> "Tuple[float,float]":
r"""
Returns velocity limits [vmin,vmax].
"""
return _robotsim.RobotModelDriver_getVelocityLimits(self)
def getAccelerationLimits(self) -> "Tuple[float,float]":
r"""
Returns acceleration limits [amin,amax].
"""
return _robotsim.RobotModelDriver_getAccelerationLimits(self)
def getTorqueLimits(self) -> "Tuple[float,float]":
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.
Args:
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. Geometries may be saved as well.
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"""
Gets the name of the robot.
"""
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 numLinks(self) -> int:
r"""
Returns the number of links = number of DOF's.
"""
return _robotsim.RobotModel_numLinks(self)
[docs]
def link(self, *args) -> "RobotModelLink":
r"""
Returns a reference to the link by index or name.
link (index): :class:`~klampt.RobotModelLink`
link (name): :class:`~klampt.RobotModelLink`
Args:
index (int, optional):
name (str, optional):
Returns:
RobotModelLink:
"""
return _robotsim.RobotModel_link(self, *args)
[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:
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):
"""
return _robotsim.RobotModel_getJointType(self, *args)
[docs]
def getConfig(self) -> Vector:
r"""
Retrieves the current configuration of the robot model.
"""
return _robotsim.RobotModel_getConfig(self)
[docs]
def getVelocity(self) -> Vector:
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) -> "Tuple[Vector,Vector]":
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) -> Vector:
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) -> Vector:
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) -> Vector:
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):
"""
return _robotsim.RobotModel_getDOFPosition(self, *args)
[docs]
def getCom(self) -> Vector3:
r"""
Returns the 3D center of mass at the current config.
"""
return _robotsim.RobotModel_getCom(self)
[docs]
def getComVelocity(self) -> Vector3:
r"""
Returns the 3D velocity of the center of mass at the current config / velocity.
"""
return _robotsim.RobotModel_getComVelocity(self)
[docs]
def getComJacobian(self) -> "np.ndarray":
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) -> "np.ndarray":
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) -> Vector3:
r"""
Computes the 3D linear momentum vector.
"""
return _robotsim.RobotModel_getLinearMomentum(self)
[docs]
def getAngularMomentum(self) -> Vector3:
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) -> "np.ndarray":
r"""
Computes the 3x3 total inertia matrix of the robot.
"""
return _robotsim.RobotModel_getTotalInertia(self)
[docs]
def getMassMatrix(self) -> "np.ndarray":
r"""
Computes the nxn mass matrix B(q).
Takes O(n^2) time
"""
return _robotsim.RobotModel_getMassMatrix(self)
[docs]
def getMassMatrixInv(self) -> "np.ndarray":
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) -> "np.ndarray":
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) -> "np.ndarray":
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) -> "np.ndarray":
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) -> Vector:
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) -> Vector:
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) -> Vector:
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) -> Vector:
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) -> Vector:
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) -> Vector:
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) -> Vector:
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) -> Vector:
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) -> Vector:
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) -> Vector:
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") -> "List[int]":
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 numSensors(self) -> int:
r"""
Returns the number of sensors.
"""
return _robotsim.RobotModel_numSensors(self)
def _sensor(self, *args) -> "SensorModel":
r"""
_sensor (index): :class:`~klampt.SensorModel`
_sensor (name): :class:`~klampt.SensorModel`
Args:
index (int, optional):
name (str, optional):
Returns:
SensorModel:
"""
return _robotsim.RobotModel__sensor(self, *args)
[docs]
def addSensor(self, name: str, type: str) -> "SensorModel":
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""")
[docs]
def getLinks(self) -> Tuple[RobotModelLink]:
"""
Returns a list of all links on the robot.
Args:
"""
return tuple(self.link(i) for i in range(self.numLinks()))
[docs]
def getLinksDict(self) -> Dict[str,RobotModelLink]:
"""
Returns a dictionary mapping link names to RobotModelLink instances.
Args:
"""
return types.MappingProxyType({l.name:l for l in self.getLinks()})
[docs]
def getDrivers(self) -> Tuple[RobotModelDriver]:
"""
Returns a list of all drivers on the robot.
Args:
"""
return tuple(self.driver(i) for i in range(self.numDrivers()))
[docs]
def getDriversDict(self) -> Dict[str,RobotModelDriver]:
"""
Returns a dictionary mapping driver names to RobotModelDriver instances.
Args:
"""
return types.MappingProxyType({d.name:d for d in self.getDrivers()})
[docs]
def sensor(self, index_or_name : Union[int,str]) -> 'SensorModel':
"""
Retrieves the sensor with the given index or name. A KeyError is
raised if it does not exist.
Args:
"""
res = self._sensor(index_or_name)
if len(res.type) == 0:
raise KeyError("Invalid sensor name: {}".format(index_or_name))
return res
[docs]
def getSensors(self) -> Tuple['SensorModel']:
"""
Returns a list of all sensors on the robot.
Args:
"""
return tuple(self.sensor(i) for i in range(self.numSensors()))
[docs]
def getSensorsDict(self) -> Dict[str,'SensorModel']:
"""
Returns a dictionary mapping sensor names to SensorModel instances.
Args:
"""
return types.MappingProxyType({s.name:s for s in self.getSensors()})
name = property(getName, setName)
id = property(getID)
config = property(getConfig,setConfig)
velocity = property(getVelocity,setVelocity)
links = property(getLinks)
linksDict = property(getLinksDict)
drivers = property(getDrivers)
driversDict = property(getDriversDict)
sensors = property(getSensors)
sensorsDict = property(getSensorsDict)
__swig_destroy__ = _robotsim.delete_RobotModel
# Register RobotModel in _robotsim:
_robotsim.RobotModel_swigregister(RobotModel)
[docs]
class SensorModel(object):
r"""
A sensor on a simulated robot.
Args:
Kinematic models of sensors are retrieved using :meth:`RobotModel.sensor` and
can be created using :meth:`RobotModel.addSensor`.
Physically-simulated sensors are retrieved from a controller using
:meth:`SimRobotController.sensor`, and can be created using
:meth:`SimRobotController.addSensor`.
Some types of sensors can be kinematically-simulated such that they make
sensible measurements. To use kinematic simulation, you may arbitrarily set the
robot's position, call :meth:`kinematicReset`, and then call
:meth:`kinematicSimulate`. Subsequent calls assume the robot is being driven
along a coherent trajectory until the next :meth:`kinematicReset` is called.
This is necessary for sensors that estimate accelerations, e.g.,
ForceTorqueSensor, Accelerometer
Physically-simulated sensors are automatically updated through the
:meth:`Simulator.simulate` call.
Use :meth:`getMeasurements` to get the currently simulated measurement vector.
You may get garbage measurements before kinematicSimulate / Simulator.simulate
are 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: 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, robot: "RobotModel", sensor):
r"""
Args:
robot (:class:`~klampt.RobotModel`)
sensor (:obj:`Klampt::SensorBase *`)
"""
_robotsim.SensorModel_swiginit(self, _robotsim.new_SensorModel(robot, sensor))
[docs]
def getName(self) -> str:
r"""
Returns the name of the sensor.
"""
return _robotsim.SensorModel_getName(self)
[docs]
def setName(self, name: str) -> None:
r"""
Sets the name of the sensor.
Args:
name (str)
"""
return _robotsim.SensorModel_setName(self, name)
[docs]
def getType(self) -> str:
r"""
Returns the type of the sensor.
"""
return _robotsim.SensorModel_getType(self)
[docs]
def robot(self) -> "RobotModel":
r"""
Returns the model of the robot to which this belongs.
Returns:
RobotModel:
"""
return _robotsim.SensorModel_robot(self)
[docs]
def measurementNames(self) -> Sequence[str]:
r"""
Returns a list of names for the measurements (one per measurement).
Returns:
stringVector:
"""
return _robotsim.SensorModel_measurementNames(self)
[docs]
def getMeasurements(self) -> "np.ndarray":
r"""
Returns an array of measurements from the previous simulation (or
kinematicSimulate) timestep.
"""
return _robotsim.SensorModel_getMeasurements(self)
[docs]
def settings(self) -> Sequence[str]:
r"""
Returns all setting names.
Returns:
stringVector:
"""
return _robotsim.SensorModel_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.SensorModel_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.SensorModel_setSetting(self, name, val)
[docs]
def getEnabled(self) -> bool:
r"""
Return whether the sensor is enabled during simulation (helper for getSetting)
"""
return _robotsim.SensorModel_getEnabled(self)
[docs]
def setEnabled(self, enabled: bool) -> None:
r"""
Sets whether the sensor is enabled in physics simulation.
Args:
enabled (bool)
"""
return _robotsim.SensorModel_setEnabled(self, enabled)
def _getLink(self) -> "RobotModelLink":
r"""
Returns the link on which the sensor is mounted.
Returns:
RobotModelLink:
"""
return _robotsim.SensorModel__getLink(self)
def _setLink(self, *args) -> None:
r"""
Sets the link on which the sensor is mounted (helper for setSetting)
_setLink (link)
Args:
link (:class:`~klampt.RobotModelLink` or int):
"""
return _robotsim.SensorModel__setLink(self, *args)
[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.SensorModel_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.SensorModel_kinematicSimulate(self, *args)
[docs]
def kinematicReset(self) -> None:
r"""
resets a kinematic simulation so that a new initial condition can be set
"""
return _robotsim.SensorModel_kinematicReset(self)
robotModel = property(_robotsim.SensorModel_robotModel_get, _robotsim.SensorModel_robotModel_set, doc=r"""robotModel : RobotModel""")
sensor = property(_robotsim.SensorModel_sensor_get, _robotsim.SensorModel_sensor_set, doc=r"""sensor : p.Klampt::SensorBase""")
[docs]
def getLink(self) -> Optional[RobotModelLink]:
"""
Retrieves the link that this sensor is mounted on, or None for
world-mounted sensors.
Args:
"""
l = self._getLink()
if l.index < 0:
return None
return l
[docs]
def setLink(self, link : Union[int,None,RobotModelLink]):
"""
Sets the link that this sensor is mounted on, or None / -1 for
world-mounted sensors.
Args:
"""
if link is None:
self._setLink(-1)
elif isinstance(link,RobotModelLink):
self._setLink(link.index)
else:
self._setLink(link)
name = property(getName, setName)
type = property(getType)
"""A string giving the sensor's type. Read-only."""
enabled = property(getEnabled,setEnabled)
"""Whether the sensor is enabled in physical simulation."""
link = property(getLink,setLink)
"""The link that this sensor lies on. May be None."""
__swig_destroy__ = _robotsim.delete_SensorModel
# Register SensorModel in _robotsim:
_robotsim.SensorModel_swigregister(SensorModel)
[docs]
class RigidObjectModel(object):
r"""
A rigid movable object.
Args:
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.
Returns:
Geometry3D:
"""
return _robotsim.RigidObjectModel_geometry(self)
[docs]
def appearance(self) -> "Appearance":
r"""
Returns a reference to the appearance associated with this object.
Returns:
Appearance:
"""
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)``
Returns:
Mass:
"""
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 getVelocity(self) -> "Tuple[Vector3,Vector3]":
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""")
name = property(getName, setName)
id = property(getID)
mass = property(getMass, setMass)
transform = property(getTransform)
__swig_destroy__ = _robotsim.delete_RigidObjectModel
# Register RigidObjectModel in _robotsim:
_robotsim.RigidObjectModel_swigregister(RigidObjectModel)
[docs]
class TerrainModel(object):
r"""
Static environment geometry.
Args:
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.
Returns:
Geometry3D:
"""
return _robotsim.TerrainModel_geometry(self)
[docs]
def appearance(self) -> "Appearance":
r"""
Returns a reference to the appearance associated with this object.
Returns:
Appearance:
"""
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""")
name = property(getName, setName)
id = property(getID)
__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.
Args:
Attributes:
- robots: a list of RobotModel instances
- rigidObjects: a list of RigidObjectModel instances
- terrains: a list of TerrainModel instances
.. 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().
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.
Returns:
WorldModel:
"""
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. Elements in the world will be saved to a folder.
Args:
fn (str)
elementDir (str, optional): default value None
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)
"""
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 numRobotLinks(self, robot: int) -> int:
r"""
Returns the number of links on the given robot.
Args:
robot (int)
"""
return _robotsim.WorldModel_numRobotLinks(self, robot)
[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:
RobotModel:
"""
return _robotsim.WorldModel_robot(self, *args)
[docs]
def robotLink(self, *args) -> "RobotModelLink":
r"""
Returns a RobotModelLink of some RobotModel in the world by index or name.
robotLink (robot,index): :class:`~klampt.RobotModelLink`
robotLink (robot,name): :class:`~klampt.RobotModelLink`
Args:
robot (int or str):
index (int, optional):
name (str, optional):
Returns:
RobotModelLink:
"""
return _robotsim.WorldModel_robotLink(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:
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:
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)
Returns:
RobotModel:
"""
return _robotsim.WorldModel_makeRobot(self, name)
[docs]
def makeRigidObject(self, name: str) -> "RigidObjectModel":
r"""
Creates a new empty rigid object.
Args:
name (str)
Returns:
RigidObjectModel:
"""
return _robotsim.WorldModel_makeRigidObject(self, name)
[docs]
def makeTerrain(self, name: str) -> "TerrainModel":
r"""
Creates a new empty terrain.
Args:
name (str)
Returns:
TerrainModel:
"""
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)
Returns:
RobotModel:
"""
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)
Returns:
RigidObjectModel:
"""
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)
Returns:
TerrainModel:
"""
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.RigidObjectModel` or :class:`~klampt.TerrainModel` or :class:`~klampt.RobotModel`):
"""
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)
Returns:
Geometry3D:
"""
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)
Returns:
Appearance:
"""
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""")
[docs]
def getRobots(self) -> Tuple[RobotModel]:
"""
Returns a list of all robots in the world.
Args:
"""
return tuple(self.robot(i) for i in range(self.numRobots()))
[docs]
def getRobotsDict(self) -> Dict[str,RobotModel]:
"""
Returns a dictionary mapping robot names to RobotModel instances.
Args:
"""
return types.MappingProxyType({r.name:r for r in self.getRobots()})
[docs]
def getRigidObjects(self) -> Tuple[RigidObjectModel]:
"""
Returns a list of all rigid objects in the world.
Args:
"""
return tuple(self.rigidObject(i) for i in range(self.numRigidObjects()))
[docs]
def getRigidObjectsDict(self) -> Dict[str,RigidObjectModel]:
"""
Returns a dictionary mapping rigid object names to RigidObjectModel instances.
Args:
"""
return types.MappingProxyType({r.name:r for r in self.getRigidObjects()})
[docs]
def getTerrains(self) -> Tuple[TerrainModel]:
"""
Returns a list of all rigid objects in the world.
Args:
"""
return tuple(self.terrain(i) for i in range(self.numTerrains()))
[docs]
def getTerrainsDict(self) -> Dict[str,TerrainModel]:
"""
Returns a dictionary mapping rigid object names to RigidObjectModel instances.
Args:
"""
return types.MappingProxyType({r.name:r for r in self.getTerrains()})
robots = property(getRobots)
robotsDict = property(getRobotsDict)
rigidObjects = property(getRigidObjects)
rigidObjectsDict = property(getRigidObjectsDict)
terrains = property(getTerrains)
terrainsDict = property(getTerrainsDict)
# 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.
Args:
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.
Returns:
IKObjective:
"""
return _robotsim.IKObjective_copy(self)
[docs]
def link(self) -> int:
r"""
The index of the robot link that is constrained.
"""
return _robotsim.IKObjective_link(self)
[docs]
def destLink(self) -> int:
r"""
The index of the destination link, or -1 if fixed to the world.
"""
return _robotsim.IKObjective_destLink(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 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 setLinks(self, link: int, link2: int=-1) -> None:
r"""
Manual construction.
Args:
link (int)
link2 (int, optional): default value -1
"""
return _robotsim.IKObjective_setLinks(self, link, link2)
[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) -> "Tuple[Vector3,Vector3]":
r"""
Returns the local and global position of the position constraint.
"""
return _robotsim.IKObjective_getPosition(self)
[docs]
def getPositionDirection(self) -> Vector3:
r"""
For linear and planar constraints, returns the direction.
"""
return _robotsim.IKObjective_getPositionDirection(self)
[docs]
def getRotation(self) -> Matrix3:
r"""
For fixed rotation constraints, returns the orientation.
"""
return _robotsim.IKObjective_getRotation(self)
[docs]
def getRotationAxis(self) -> "Tuple[Vector3,Vector3]":
r"""
For axis rotation constraints, returns the local and global axes.
"""
return _robotsim.IKObjective_getRotationAxis(self)
[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) -> RigidTransform:
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 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.
Args:
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.
Returns:
IKSolver:
"""
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) -> "List[int]":
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) -> "Tuple[Vector,Vector]":
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) -> Vector:
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) -> Vector:
r"""
Returns the vector describing the error of the objective at the current
configuration.
"""
return _robotsim.IKSolver_getResidual(self)
[docs]
def getJacobian(self) -> "np.ndarray":
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) -> Vector:
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
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.
Args: 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.
Args:
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 (:class:`~klampt.RigidObjectModel` or :obj:`GeneralizedIKObjective`, 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)
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.
Args:
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 SimRobotController(object):
r"""
A controller for a simulated robot.
Args:
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.
Returns:
RobotModel:
"""
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 numSensors(self) -> int:
r"""
Returns the number of sensors.
"""
return _robotsim.SimRobotController_numSensors(self)
def _sensor(self, *args) -> "SensorModel":
r"""
_sensor (index): :class:`~klampt.SensorModel`
_sensor (name): :class:`~klampt.SensorModel`
Args:
index (int, optional):
name (str, optional):
Returns:
SensorModel:
"""
return _robotsim.SimRobotController__sensor(self, *args)
[docs]
def addSensor(self, name: str, type: str) -> "SensorModel":
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.
Returns:
stringVector:
"""
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.
Returns:
stringVector:
"""
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""")
[docs]
def sensor(self, index_or_name : Union[int,str]) -> SensorModel:
"""
Retrieves the sensor with the given index or name. A KeyError is
raised if it does not exist.
Args:
"""
res = self._sensor(index_or_name)
if len(res.type) == 0:
raise KeyError("Invalid sensor name: {}".format(index_or_name))
return res
[docs]
def getSensors(self) -> Tuple[SensorModel]:
"""
Returns a list of all sensors on the robot.
Args:
"""
return tuple(self.sensor(i) for i in range(self.numSensors()))
[docs]
def getSensorsDict(self) -> Dict[str,SensorModel]:
"""
Returns a dictionary mapping sensor names to SensorModel instances.
Args:
"""
return types.MappingProxyType({s.name:s for s in self.getSensors()})
rate = property(getRate, setRate)
sensors = property(getSensors)
sensorsDict = property(getSensorsDict)
# 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).
Args:
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. The object's reference frame is retrieved/set by
getObjectTransform()/setObjectTransform().
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 applyForceAtCOMLocalPoint(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_applyForceAtCOMLocalPoint(self, f, plocal)
[docs]
def applyForceAtObjectLocalPoint(self, f: Point, plocal: Point) -> None:
r"""
Applies a force at a given point (in local object-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_applyForceAtObjectLocalPoint(self, f, plocal)
[docs]
def applyForceAtLocalPoint(self, f: Point, plocal_com: Point) -> None:
r"""
Deprecated: use applyForceAtCOMLocalPoint instead to match old behavior.
Args:
f (:obj:`list of 3 floats`)
plocal_com (:obj:`list of 3 floats`)
"""
return _robotsim.SimBody_applyForceAtLocalPoint(self, f, plocal_com)
[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) -> RigidTransform:
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) -> RigidTransform:
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 (of the COM) 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) -> "Tuple[Vector3,Vector3]":
r"""
Returns the angular velocity and translational velocity (of the COM)
"""
return _robotsim.SimBody_getVelocity(self)
[docs]
def setObjectVelocity(self, w: Point, v: Point) -> None:
r"""
Sets the angular velocity and translational velocity (of the object origin) at
the current simulation time step.
Args:
w (:obj:`list of 3 floats`)
v (:obj:`list of 3 floats`)
"""
return _robotsim.SimBody_setObjectVelocity(self, w, v)
[docs]
def getObjectVelocity(self) -> "Tuple[Vector3,Vector3]":
r"""
Returns the angular velocity and translational velocity (of the object origin)
"""
return _robotsim.SimBody_getObjectVelocity(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.
Returns:
ContactParameters:
"""
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. The object's reference frame is retrieved/set by
getObjectTransform()/setObjectTransform().
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.
Args:
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.
Args:
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) -> "Tuple[list,list]":
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) -> Vector:
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) -> Vector:
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) -> Vector:
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 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 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 (int or :class:`~klampt.RobotModel`):
Returns:
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:
SimBody:
"""
return _robotsim.Simulator_body(self, *args)
[docs]
def getJointForces(self, link: "RobotModelLink") -> Vector:
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.
Returns:
stringVector:
"""
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 RobotModel.randomizeConfig() method and
sampling-based motion planners.
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.
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.
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.
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)
Returns:
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 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 (np_array2): bool
force_closure (contactPositions,frictionCones): 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 (np_array2): bool
force_closure_2d (contactPositions,frictionCones): 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 (np_array2,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 (np_array2,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 (np_array2): :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 (np_array2): :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,np_array2,links,fext,norm=0): :obj:`object`
equilibrium_torques (robot,np_array2,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)