klampt.io package

html

An exporter that converts scenes / animations to shareable HTML files.

loader

Functions for loading/saving Klampt’ objects to disk in the same format as the Klampt C++ bindings / JSON formats.

resource

Easy I/O with resources stored on disk and visual editing.

ros

A module for converting between Klamp’t objects and ROS messages.

numpy_convert

Conversions to and from Numpy objects; makes numerical computations much more convenient.

open3d_convert

Conversions to and from the Open3D library.

klampt.io.html module

An exporter that converts scenes / animations to shareable HTML files.

klampt.io.html.make_fixed_precision(obj, digits)[source]
class klampt.io.html.HTMLSharePath(filename=None, name="Klamp't Three.js app", boilerplate='auto', libraries='static')[source]

Bases: object

An exporter that converts scenes / animations to shareable HTML files.

Examples:

sharer = HTMLSharePath("mypath.html",name="My spiffy path")
sharer.start(sim)  #can accept a sim or a world
while [simulation is running]:
    #do whatever control you wish to do here
    sim.simulate(...)
    sharer.animate()
sharer.end() #this saves to the filename given in the constructor
Parameters
  • filename (str, optional) – the HTML file to generate. If None, then the end() method returns the HTML string.

  • name (str) – the title of the HTML page

  • boilerplate (str) – the location of the boilerplate HTML file. If ‘auto’, it’s automatically found in the klampt/data folder.

  • libraries (str) – either ‘static’ or ‘dynamic’. In the latter case, the html file loads the libraries from the Klamp’t website dynamically. This reduces the size of the HTML file by about 600kb, but the viewer needs an internet connection

start(world)[source]

Begins the path saving with the given WorldModel or Simulator

animate(time=None, rpc=None)[source]

Updates the path from the world. If the world wasn’t a simulator, the time argument needs to be provided.

If you want to include extra things, provide them in the rpc argument (as a list of KlamptFrontend rpc calls)

end(rpc=None)[source]

klampt.io.loader module

Functions for loading/saving Klampt’ objects to disk in the same format as the Klampt C++ bindings / JSON formats.

Can read/write objects using the general purpose reader/writer functions ‘read(type,text)’ and ‘write(x,type)’.

Can load/save objects using the general purpose loader/saver functions ‘load(type,fileName)’ and ‘save(x,type,fileName)’. The load functions also support URLs

Json serialization/deserialization are handled using the to_json() and from_json() functions.

Module summary

High level interface

write(obj, type)

General-purpose write of an arbitrary Klampt object to a str.

read(type, text)

General-purpose read of an arbitrary Klampt object from a str.

load(type, fn)

General-purpose load of an arbitrary Klampt object from a file or URL.

save(obj, type, fn)

General-purpose save of an arbitrary Klampt object to a file.

to_json(obj[, type])

Converts from a Klamp’t object to a JSON-compatible structure.

from_json(jsonobj[, type])

Converts from a JSON structure to a Klamp’t object of the appropriate type.

EXTENSION_TO_TYPES

dict mapping file extensions to lists of compatible Klampt types.

TYPE_TO_EXTENSIONS

dict mapping Klamp’t types to lists of compatible file extensions.

UNSUPPORTED_JSON_TYPES

List of Klampt types that cannot currently be exported to JSON

filename_to_types(name)

Returns the Klampt types possibly represented by the given filename’s extension.

filename_to_type(name)

Returns one Klampt type represented by the given filename’s extension.

Implementation

read_Vector(text)

Reads a length-prepended vector from a string ‘n v1 .

write_Vector(q)

Writes a vector to a string in the length-prepended format ‘n v1 .

read_Vector_raw(text)

Reads a vector from a raw string ‘v1 .

write_Vector_raw(x)

Writes a vector to a string in the raw format ‘v1 .

read_VectorList(text)

Reads a list of endline-separated vectors from a string

write_VectorList(x)

Writes a list of vectors to string

read_Matrix(text)

Reads a matrix from a string in the format m n x11 x12 .

write_Matrix(x)

Writes a matrix to a string in the format m n x11 x12 .

read_Matrix3(text)

Reads a 3x3 matrix from a string

write_Matrix3(x)

Writes a 3x3 matrix to a string

read_IntArray(text)

Reads a length-prepended vector from a string ‘n v1 .

read_StringArray(text)

Reads a length-prepended vector from a string ‘n v1 .

read_so3(text)

Reads an so3 element, i.e., rotation matrix, from string in the same format as written to by Klampt C++ bindings (row major).

write_so3(x)

Writes an so3 element, i.e., rotation matrix, to string in the same format as written to by Klampt C++ bindings (row major).

read_se3(text)

Reads an se3 element, i.e., rigid transformation, to string in the same format as written to by Klampt C++ bindings (row major R, followed by t).

write_se3(x)

Writes an se3 element, i.e., rigid transformation, to string in the same format as written to by Klampt C++ bindings (row major R, followed by t).

read_IKObjective(text)

Reads an IKObjective from a string in the Klamp’t native format

write_IKObjective(obj)

read_ContactPoint(text)

Reads a contact point from a string ‘x1 x2 x3 n1 n2 n3 kFriction’

write_ContactPoint(cp)

Writes a contact point to a string ‘x1 x2 x3 n1 n2 n3 kFriction’

read_Hold(text)

Loads a Hold from a string

write_Hold(h)

Writes a Hold to a string

load_WorldModel(fn)

load_Geometry3D(fn)

load_Trajectory(fn)

load_MultiPath(fn)

load_dynamic_xml(fn)

klampt.io.loader.EXTENSION_TO_TYPES = {'.config': ['Config'], '.configs': ['Configs'], '.dae': ['Geometry3D', 'TriangleMesh'], '.env': ['TerrainModel'], '.geom': ['Geometry3D', 'GeometricPrimitive'], '.grasp': ['Grasp'], '.hold': ['Hold'], '.ikgoal': ['IKGoal'], '.matrix3': ['Matrix3'], '.obj': ['Geometry3D', 'RigidObjectModel', 'TriangleMesh'], '.off': ['Geometry3D', 'TriangleMesh'], '.path': ['Trajectory', 'LinearPath', 'SE3Trajectory', 'SO3Trajectory'], '.pcd': ['Geometry3D', 'PointCloud'], '.ply': ['Geometry3D', 'TriangleMesh'], '.poly': ['Geometry3D', 'TriangleMesh'], '.rob': ['RobotModel'], '.stance': ['Stance'], '.stl': ['Geometry3D', 'TriangleMesh'], '.tri': ['Geometry3D', 'TriangleMesh'], '.urdf': ['RobotModel'], '.vector3': ['Vector3'], '.wrl': ['Geometry3D', 'TriangleMesh'], '.xform': ['RigidTransform'], '.xml': ['WorldModel', 'MultiPath']}

dict mapping file extensions to lists of compatible Klampt types.

klampt.io.loader.UNSUPPORTED_JSON_TYPES = ['Geometry3D', 'TriangleMesh', 'PointCloud', 'GeometricPrimitive', 'VolumeGrid', 'RobotModel', 'RigidObjectModel', 'TerrainModel', 'WorldModel']

List of Klampt types that cannot currently be exported to JSON

klampt.io.loader.TYPE_TO_EXTENSIONS = {'Config': ['.config'], 'Configs': ['.configs'], 'GeometricPrimitive': ['.geom'], 'Geometry3D': ['.geom', '.tri', '.obj', '.ply', '.poly', '.wrl', '.dae', '.pcd', '.off', '.stl'], 'Grasp': ['.grasp'], 'Hold': ['.hold'], 'IKGoal': ['.ikgoal'], 'LinearPath': ['.path'], 'Matrix3': ['.matrix3'], 'MultiPath': ['.xml'], 'PointCloud': ['.pcd'], 'RigidObjectModel': ['.obj'], 'RigidTransform': ['.xform'], 'RobotModel': ['.urdf', '.rob'], 'SE3Trajectory': ['.path'], 'SO3Trajectory': ['.path'], 'Stance': ['.stance'], 'TerrainModel': ['.env'], 'Trajectory': ['.path'], 'TriangleMesh': ['.tri', '.obj', '.ply', '.poly', '.wrl', '.dae', '.off', '.stl'], 'Vector3': ['.vector3'], 'WorldModel': ['.xml']}

dict mapping Klamp’t types to lists of compatible file extensions.

klampt.io.loader.filename_to_types(name)[source]

Returns the Klampt types possibly represented by the given filename’s extension.

klampt.io.loader.filename_to_type(name)[source]

Returns one Klampt type represented by the given filename’s extension.

If the file is a dynamic type (.xml or .json), just ‘xml’ or ‘json’ is returned because the type will need to be determined after parsing the file.

If the type is ambiguous (like .obj), the first type in EXTENSION_TO_TYPES is returned.

Returns

The Klamp’t type

Return type

str

klampt.io.loader.write_Vector(q)[source]

Writes a vector to a string in the length-prepended format ‘n v1 … vn’

klampt.io.loader.read_Vector(text)[source]

Reads a length-prepended vector from a string ‘n v1 … vn’

klampt.io.loader.write_Vector_raw(x)[source]

Writes a vector to a string in the raw format ‘v1 … vn’

klampt.io.loader.read_Vector_raw(text)[source]

Reads a vector from a raw string ‘v1 … vn’

klampt.io.loader.write_VectorList(x)[source]

Writes a list of vectors to string

klampt.io.loader.read_VectorList(text)[source]

Reads a list of endline-separated vectors from a string

klampt.io.loader.write_Matrix(x)[source]

Writes a matrix to a string in the format m n x11 x12 … x1n … xm1 xm2 … xmn

klampt.io.loader.read_Matrix(text)[source]

Reads a matrix from a string in the format m n x11 x12 … x1n … xm1 xm2 … xmn

klampt.io.loader.write_so3(x)[source]

Writes an so3 element, i.e., rotation matrix, to string in the same format as written to by Klampt C++ bindings (row major).

klampt.io.loader.read_so3(text)[source]

Reads an so3 element, i.e., rotation matrix, from string in the same format as written to by Klampt C++ bindings (row major).

klampt.io.loader.write_se3(x)[source]

Writes an se3 element, i.e., rigid transformation, to string in the same format as written to by Klampt C++ bindings (row major R, followed by t).

klampt.io.loader.read_se3(text)[source]

Reads an se3 element, i.e., rigid transformation, to string in the same format as written to by Klampt C++ bindings (row major R, followed by t).

klampt.io.loader.write_Matrix3(x)[source]

Writes a 3x3 matrix to a string

klampt.io.loader.read_Matrix3(text)[source]

Reads a 3x3 matrix from a string

klampt.io.loader.read_ContactPoint(text)[source]

Reads a contact point from a string ‘x1 x2 x3 n1 n2 n3 kFriction’

klampt.io.loader.write_ContactPoint(cp)[source]

Writes a contact point to a string ‘x1 x2 x3 n1 n2 n3 kFriction’

klampt.io.loader.read_IKObjective(text)[source]

Reads an IKObjective from a string in the Klamp’t native format

link destLink posConstraintType [pos constraint items] ... rotConstraintType [rot constraint items]

where link and destLink are integers, posConstraintType is one of

  • N: no constraint

  • P: position constrained to a plane

  • L: position constrained to a line

  • F: position constrained to a point

and rotConstraintType is one of

  • N: no constraint

  • T: two-axis constraint (not supported)

  • A: rotation constrained about axis

  • F: fixed rotation

The [pos constraint items] contain a variable number of whitespace- separated items, dependending on posConstraintType:

  • N: 0 items

  • P: the local position xl yl zl, world position x y z on the plane, and plane normal nx,ny,nz

  • L: the local position xl yl zl, world position x y z on the line, and line axis direction nx,ny,nz

  • F: the local position xl yl zl and world position x y z

The [rot constraint items] contain a variable number of whitespace- separated items, dependending on rotConstraintType:

  • N: 0 items

  • T: not supported

  • A: the local axis xl yl zl and the world axis x y z

  • F: the world rotation matrix, in moment (aka exponential map) form mx my mz (see so3.from_moment())

klampt.io.loader.write_IKObjective(obj)[source]
klampt.io.loader.read_Hold(text)[source]

Loads a Hold from a string

klampt.io.loader.write_Hold(h)[source]

Writes a Hold to a string

klampt.io.loader.write_GeometricPrimitive(g)[source]
klampt.io.loader.read_GeometricPrimitive(text)[source]
klampt.io.loader.read_IntArray(text)[source]

Reads a length-prepended vector from a string ‘n v1 … vn’

klampt.io.loader.read_StringArray(text)[source]

Reads a length-prepended vector from a string ‘n v1 … vn’

klampt.io.loader.parse_lines(text)[source]

Returns a list of lines from the given text. Understands end-of-line escapes ‘n’

klampt.io.loader.write(obj, type)[source]

General-purpose write of an arbitrary Klampt object to a str.

Parameters
  • obj – A Klampt object

  • type (str) – Either the Klamp’t type, ‘json’, or ‘auto’. If ‘auto’, the type will be auto-detected from the object.

Returns

The encoding of the object.

Return type

str

klampt.io.loader.read(type, text)[source]

General-purpose read of an arbitrary Klampt object from a str.

Parameters
  • type (str) – Either the Klamp’t type, or ‘json’. Future versions may support ‘xml’ but this is not supported right now. ‘auto’ may not be specified.

  • text (str) – A string containing the object data.

Returns

Klamp’t object

klampt.io.loader.load_WorldModel(fn)[source]
klampt.io.loader.load_Geometry3D(fn)[source]
klampt.io.loader.load_Trajectory(fn)[source]
klampt.io.loader.load_MultiPath(fn)[source]
klampt.io.loader.load_dynamic_xml(fn)[source]
klampt.io.loader.save(obj, type, fn)[source]

General-purpose save of an arbitrary Klampt object to a file.

This also works with RobotModel, RigidObjectModel, and TerrainModel (which don’t work with load).

Parameters
  • obj – a Klamp’t object.

  • type (str) – the Klampt type, ‘json’, or ‘auto’

  • fn (str) – a file name

Returns

True if successful.

Return type

bool

klampt.io.loader.load(type, fn)[source]

General-purpose load of an arbitrary Klampt object from a file or URL.

An exception is raised if there is an error loading or parsing the file. Possible exception types include IOError, ValueError, and HTTPError.

Parameters
  • type (str) – a Klamp’t type, ‘json’, or ‘auto’

  • fn (str) – a filename.

Returns

Klamp’t object

klampt.io.loader.to_json(obj, type='auto')[source]

Converts from a Klamp’t object to a JSON-compatible structure.

The resulting structure can be converted to a JSON string using json.dumps() in the Python builtin json module.

Not all objects are supported yet, notably geometry-related objects and world entities.

Parameters
  • obj – A Klamp’t object.

  • type (str, optional) – the type of the object (see types) If ‘auto’ (default), the type of the object is inferred automatically.

klampt.io.loader.from_json(jsonobj, type='auto')[source]

Converts from a JSON structure to a Klamp’t object of the appropriate type.

Note: a JSON structure can be created from a JSON string using the json.loads() function in the Python builtin json module.

Not all objects are supported yet, notably geometry-related objects and world entities.

Parameters
  • jsonobj – A JSON structure (i.e., one coming from to_json())

  • type (str, optional) – the type of the object (see types) If ‘auto’ (default), the type of the object is inferred automatically.

klampt.io.loader.fromJson(*args, **kwargs)

Deprecated in a future version of Klampt. Use from_json instead

klampt.io.loader.filenameToType(*args, **kwargs)

Deprecated in a future version of Klampt. Use filename_to_type instead

klampt.io.loader.toJson(*args, **kwargs)

Deprecated in a future version of Klampt. Use to_json instead

klampt.io.loader.filenameToTypes(*args, **kwargs)

Deprecated in a future version of Klampt. Use filename_to_type instead

klampt.io.resource module

Easy I/O with resources stored on disk and visual editing.

Use the get(), set(), and edit() functions to retrieve / store / edit resources dynamically.

load() and save() launch a file browser (available in Qt only).

By default, resources are stored in the resources/ subdirectory of the current working directory. Use get_directory() and set_drectory() to change where resources are stored Alternatively, the directory=[DIRNAME] keyword argument can be provided to get, set, load, and save.

Warning

Don’t use from klampt.io.resource import *, because this will override the built-in set class.

Example usage can be seen in Klampt-examples/Python/demos/resourcetest.py.

Functions:

get_directory()

Returns the current resource directory.

set_directory(value)

Sets the current resource directory.

known_extensions()

Returns all known resource file extensions

known_types()

Returns all known resource types

visual_edit_types()

Returns types that can be visually edited

get(name[, type, directory, default, …])

Retrieve a resource of the given name from the current resources directory.

set(name, value[, type, directory])

Saves a resource to disk under the given name.

load([type, directory])

Pops up a dialog that asks the user to load a resource file of a given type.

save(value[, type, directory])

Pops up a dialog that asks the user to save a resource to a file of the correct type.

thumbnail(value, size[, type, world, frame])

Retrieves an image of the given item, resized to the given size.

console_edit(name, value, type[, …])

edit(name, value[, type, description, …])

Launches an editor for the given value.

knownTypes(*args, **kwargs)

Deprecated in a future version of Klampt.

visualEditTypes(*args, **kwargs)

Deprecated in a future version of Klampt.

getDirectory(*args, **kwargs)

Deprecated in a future version of Klampt.

knownExtensions(*args, **kwargs)

Deprecated in a future version of Klampt.

setDirectory(*args, **kwargs)

Deprecated in a future version of Klampt.

Classes:

FileGetter([title])

klampt.io.resource.get_directory()[source]

Returns the current resource directory.

klampt.io.resource.set_directory(value)[source]

Sets the current resource directory.

klampt.io.resource.known_extensions()[source]

Returns all known resource file extensions

klampt.io.resource.known_types()[source]

Returns all known resource types

klampt.io.resource.visual_edit_types()[source]

Returns types that can be visually edited

klampt.io.resource.get(name, type='auto', directory=None, default=None, doedit='auto', description=None, editor='visual', world=None, referenceObject=None, frame=None)[source]

Retrieve a resource of the given name from the current resources directory. If the resource does not already exist, an edit prompt will be shown, and the result from the prompt will be saved to disk under the given name.

Resources may be of type Config, Configs, IKGoal, Hold, Stance, MultiPath, Trajectory/LinearPath, and ContactPoint, or any of the basic Klampt object types, geometry types, and math types.

Resources can also be edited using klampt_browser and RobotPose.

Parameters
  • name (str) – the resource name. If type=’auto’, this is assumed to have a suffix of a file of the desired type. The name can also be nested of the form ‘group/subgroup/name.type’.

  • type (str) – the resource type, or ‘auto’ to determine it automatically.

  • directory (str, optional) – the search directory. If None, uses the current resource directory.

  • default (optional) – the default value if the resource does not exist on disk. If None, some arbitrary default value will be inferred.

  • doedit – if ‘auto’, if the resource does not exist on disk, an edit prompt will be displayed. If False, an RuntimeError will be raised if the resource does not exist on disk. If True, the user will be given an edit prompt to optionally edit the resource before this call returns.

  • description (str, optional) – an optional text description of the resource, for use in the edit prompt.

  • editor (str) – either ‘visual’ or ‘console’, determining whether to use the visual OpenGL or console editor.

  • world (WorldModel, optional) – for a visual editor, this world will be shown along with the item to edit. If this is a string it points to a file that will be loaded for the world (e.g., a world XML file, or a robot file).

  • referenceObject (optional) – to give visual reference points, one or more RobotModels, ObjectModels, Geometry3D’s, or RobotModelLink’s may be designated to follow the edited object. Currently works with Config’s / Configs’ / Trajectories / rigid transforms / rotations / points.

  • frame (optional) – for rigid transforms / rotations / points, the reference frame in which the quantity is represented. This is an element of se3, or an ObjectModel, or a RobotModelLink, or a string indicating a named rigid element of the world.

Returns

If the named resource exists, loads and returns a Klampt object. If the object doesn’t exist and doedit=True and the user presses OK on the editor, then the object will be saved as the resource name. Otherwise, default will be returned.

Return type

Klampt object or None

klampt.io.resource.set(name, value, type='auto', directory=None)[source]

Saves a resource to disk under the given name.

Parameters
  • name (str) – the file name. Please make sure to get the right file extension. .json files are also OK for many types.

  • value – a Klamp’t resource (see list of compatible types in get())

  • type (str, optional) – The resource type. If ‘auto’, the type is determined by the file extension. If this fails, the type is determined by the value.

Returns

True on success, False otherwise

Return type

bool

class klampt.io.resource.FileGetter(title='Open file')[source]

Bases: object

Methods:

getOpen()

getSave()

getOpen()[source]
getSave()[source]
klampt.io.resource.load(type=None, directory=None)[source]

Pops up a dialog that asks the user to load a resource file of a given type.

Parameters
  • type (str, optional) – The Klampt type the user should open. If not given, all resource file types are shown in the dialog as options.

  • directory (str, optional) – if given, overrides the current resources directory.

Returns

a (filename,value) pair if OK is pressed, or None if the operation was canceled

Return type

tuple or None

klampt.io.resource.save(value, type='auto', directory=None)[source]

Pops up a dialog that asks the user to save a resource to a file of the correct type.

Parameters
  • value – a Klamp’t object that has a resource type

  • type (str, optional) – The Klampt type the user should open. If ‘auto’, the type is auto-detected.

  • directory (str, optional) – if given, overrides the current resources directory.

Returns

the file saved to, if OK is pressed, or None if the operation was canceled.

Return type

str or None

klampt.io.resource.thumbnail(value, size, type='auto', world=None, frame=None)[source]

Retrieves an image of the given item, resized to the given size.

Parameters
  • value – a resource type.

  • size (pair of ints) – the (width,height) of the thumbnail, in pixels.

  • type (str, optional) – the type of value

  • world (WorldModel, optional) – if given, the resource will be drawn with this world in the background. If the resource needs an associated object (e.g., Config, Configs, Trajectory), the object will be drawn with that given object.

  • frame (se3 element, optional) – not supported yet. Will eventually let you draw Points or RigidTransforms relative to some reference frame.

Returns

A PIL Image if PIL is available, or just a raw RGBA memory buffer otherwise.

Return type

Image or bytes

klampt.io.resource.console_edit(name, value, type, description=None, world=None, frame=None)[source]
klampt.io.resource.edit(name, value, type='auto', description=None, editor='visual', world=None, referenceObject=None, frame=None)[source]

Launches an editor for the given value.

Parameters
  • name (str) – the displayed name of the edited value. Can be None, in which case ‘Anonymous’ is displayed.

  • value – the value to be edited. Can be None, in which case ‘type’ must be specified and a default value is created.

  • type (str) – the type string of the value to be edited. Usually can be auto-detected from value.

  • description (str, optional) – a descriptive string, displayed to the person editing.

  • editor (str) – either ‘visual’ or ‘console’. If ‘visual’, will display a GUI for visually editing the item. If ‘console’, the user will have to type in the value.

  • world (WorldModel or str, optional) – either a WorldModel instance or a string specifying a world file. This is necessary for visual editing.

  • referenceObject (optional) – a RobotModel or other object to which the value “refers to”. For configurations and trajectories, this is the object that will be moved by the trajectory. In the case of a RigidTransform value, this can be an object or a list of objects that will be transformed by the transform.

  • frame (optional) – for Vector3, Matrix3, Point, Rotation, and RigidTransform types, the returned value will be given relative to this reference frame. The reference frame can be either an element of se3, a RigidObjectModel, a RobotModelLink, or a string indicating a named rigid element of the world.

Returns

A pair (save, result) containing:

  • save (bool): True if the user pressed OK, False if Cancel or the close box were chosen.

  • result: the edited value.

Return type

tuple

klampt.io.resource.knownTypes(*args, **kwargs)

Deprecated in a future version of Klampt. Use known_types instead

klampt.io.resource.visualEditTypes(*args, **kwargs)

Deprecated in a future version of Klampt. Use visual_edit_types instead

klampt.io.resource.getDirectory(*args, **kwargs)

Deprecated in a future version of Klampt. Use get_directory instead

klampt.io.resource.knownExtensions(*args, **kwargs)

Deprecated in a future version of Klampt. Use known_extensions instead

klampt.io.resource.setDirectory(*args, **kwargs)

Deprecated in a future version of Klampt. Use set_directory instead

klampt.io.ros module

A module for converting between Klamp’t objects and ROS messages. Tested on ROS Kinetic.

The easiest way to use this is to use the toMsg(klampt_obj) and fromMsg(ros_obj) functions. However, certain objects, like JointState and JointTrajectory, have several configuration options that may need to be specified.

Another simple way to use this is to use the publisher, subscriber, object_publisher, object_subscriber, broadcast_tf, and listen_tf functions.

The C++ bindings allow you to subscribe to ROS PointCloud messages natively (Geometry3D.loadFile(“ros://…”) or SubscribeToStream()). It has not been determined whether using the functions in this module with rospy interferes with those bindings.

Functions:

from_Vector3(ros_v)

From ROS Vector3 to Klamp’t point

to_Vector3(klampt_pt)

From Klamp’t point to ROS Vector3

from_Point(ros_pt)

From ROS Point to Klamp’t point

to_Point(klampt_pt)

From Klamp’t point to ROS Point

from_Quaternion(ros_q)

From ROS Quaternion to Klamp’t so3 element

to_Quaternion(klampt_so3)

From Klamp’t so3 element to ROS Quaternion

from_Pose(ros_pose)

From ROS Pose to Klamp’t se3 element

to_Pose(klampt_se3)

From Klamp’t se3 element to ROS Pose

from_Transform(ros_transform)

From tf.Transform to Klampt se3 element

to_Transform(klampt_se3)

From Klampt se3 element to ROS Transform

from_PoseStamped(ros_pose)

From ROS PoseStamped to Klamp’t se3 element

to_PoseStamped(klampt_se3[, stamp])

From Klamp’t se3 element to ROS PoseStamped

from_JointState(ros_js, robot[, …])

From ROS JointState to Klamp’t robot configuration.

to_JointState(robot[, q, dq, effort, …])

Returns a ROS JointState message for a Klamp’t robot or controller.

from_Float32MultiArray(ros_msg)

From ROS Float32MultiArray to Klamp’t Config

to_Float32MultiArray(klampt_config)

from_JointTrajectory(ros_traj[, robot, …])

Returns a Klamp’t Trajectory or RobotTrajectory for a JointTrajectory message.

to_JointTrajectory(klampt_traj[, indices, …])

Returns a ROS JointTrajectory message for a Klamp’t Trajectory or RobotTrajectory.

to_Path(klampt_path[, start_time, frame])

Converts a Klampt SE3Trajectory, SO3Trajectory, or 2D or 3D Trajectory to a ROS Path.

from_Path(ros_path)

Converts a ROS Path to a Klamp’t SE3Trajectory.

from_Mesh(ros_mesh)

From a ROS Mesh to a Klampt TriangleMesh

to_Mesh(klampt_mesh)

From a Klampt Geometry3D or TriangleMesh to a ROS Mesh

from_PointCloud2(ros_pc)

From a ROS PointCloud2 to a Klampt PointCloud

to_PointCloud2(klampt_pc[, frame, stamp])

Converts a Klampt Geometry3D or PointCloud to a ROS PointCloud2 message.

to_CameraInfo(klampt_obj)

Converts a Klampt SimRobotSensor, GLViewport, or Viewport to a ROS CameraInfo message.

from_CameraInfo(ros_ci, klampt_obj)

Fills in some information about a Klampt SimRobotSensor, GLViewport, or Viewport using a ROS CameraInfo message.

to_SensorMsg(klampt_sensor[, frame, …])

Converts a sensor’s measurements to a ROS message(s).

to_ShapeMsg(klampt_geom)

fromMsg(ros_obj, *args, **kwargs)

General conversion from ROS messages to corresponding Klamp’t objects.

toMsg(klampt_obj, *args, **kwargs)

General conversion from Klamp’t objects to corresponding ROS messages.

publisher_SimRobotSensor(topic, klampt_sensor)

publisher(topic, klampt_type[, …])

Convenience function.

object_publisher(topic, klampt_object[, …])

Convenience function.

subscriber(topic, klampt_type, callback[, …])

Convenience function.

object_subscriber(topic, klampt_obj[, …])

Convenience function.

broadcast_tf(broadcaster, klampt_obj[, …])

Broadcasts Klampt frames to the ROS tf module.

listen_tf(listener, klampt_obj[, …])

Reads Klampt frames from the ROS tf module.

Classes:

KlamptROSPublisher(converter, *args, **kwargs)

You shouldn’t need to use this explicitly.

KlamptROSCameraPublisher(topic, frame_id, …)

You shouldn’t need to use this explicitly.

klampt.io.ros.from_Vector3(ros_v)[source]

From ROS Vector3 to Klamp’t point

klampt.io.ros.to_Vector3(klampt_pt)[source]

From Klamp’t point to ROS Vector3

klampt.io.ros.from_Point(ros_pt)[source]

From ROS Point to Klamp’t point

klampt.io.ros.to_Point(klampt_pt)[source]

From Klamp’t point to ROS Point

klampt.io.ros.from_Quaternion(ros_q)[source]

From ROS Quaternion to Klamp’t so3 element

klampt.io.ros.to_Quaternion(klampt_so3)[source]

From Klamp’t so3 element to ROS Quaternion

klampt.io.ros.from_Pose(ros_pose)[source]

From ROS Pose to Klamp’t se3 element

klampt.io.ros.to_Pose(klampt_se3)[source]

From Klamp’t se3 element to ROS Pose

klampt.io.ros.from_Transform(ros_transform)[source]

From tf.Transform to Klampt se3 element

klampt.io.ros.to_Transform(klampt_se3)[source]

From Klampt se3 element to ROS Transform

klampt.io.ros.from_PoseStamped(ros_pose)[source]

From ROS PoseStamped to Klamp’t se3 element

klampt.io.ros.to_PoseStamped(klampt_se3, stamp='now')[source]

From Klamp’t se3 element to ROS PoseStamped

klampt.io.ros.from_JointState(ros_js, robot, joint_link_indices=None)[source]

From ROS JointState to Klamp’t robot configuration. The Klamp’t robot must be given, and any indices not specified in ros_js are kept at their current values

Parameters
  • ros_js (sensor_msgs.msg.JointState) – the JointState object

  • robot (RobotModel) – the robot

  • joint_link_indices (dict, optional) – if given, maps ROS joint names to Klampt link indices. Default uses the Klamp’t link names.

Returns

a pair (config,velocity,effort). Each item may be None if the JointState message does not contain position, velocity, or effort info.

Return type

tuple

klampt.io.ros.to_JointState(robot, q='current', dq='current', effort=None, indices='auto', link_joint_names=None)[source]

Returns a ROS JointState message for a Klamp’t robot or controller.

Parameters
  • robot (RobotModel or SimRobotController) – the robot

  • q (str or Config, optional) –

    either ‘current’, ‘commanded’, ‘sensed’, ‘actual’, None, or a configuration of size robot.numLinks().

    ’commanded’, ‘sensed’, and ‘actual’ are available only when robot is a SimRobotController.

  • dq (str or Config, optional) –

    either ‘current’, ‘commanded’, ‘sensed’, ‘actual’, None, or a joint velocity vector of size robot.numLinks()

    ’commanded’, ‘sensed’, and ‘actual’ are available only when robot is a SimRobotController.

  • effort (str or Config, optional) – either ‘commanded’, sensed’, ‘actual’, None, or a torque vector of size robot.numDrivers().

  • indices (str or list of int) – if ‘auto’, all elements are set. Otherwise, only these indices are set.

  • link_joint_names (list of str, optional) – if given, the i’th link is mapped to the ROS joint name link_joint_names[i].

klampt.io.ros.from_Float32MultiArray(ros_msg)[source]

From ROS Float32MultiArray to Klamp’t Config

klampt.io.ros.to_Float32MultiArray(klampt_config)[source]
klampt.io.ros.from_JointTrajectory(ros_traj, robot=None, joint_link_indices=None)[source]

Returns a Klamp’t Trajectory or RobotTrajectory for a JointTrajectory message.

Parameters
  • ros_traj (sensor_msgs.msg.JointTrajectory) – the JointTrajectory object

  • robot (RobotModel) – the robot, optional

  • joint_link_indices (dict, optional) – if given, maps ROS joint names to Klampt link indices. Default uses the Klamp’t link names.

klampt.io.ros.to_JointTrajectory(klampt_traj, indices='auto', link_joint_names=None)[source]

Returns a ROS JointTrajectory message for a Klamp’t Trajectory or RobotTrajectory.

Parameters
  • klampt_traj (Trajectory or RobotTrajectory) – the trajectory

  • indices (str or list of ints) – the indices to send (only valid with RobotTrajectory)

  • link_joint_names (list of str, optional) – if given, the i’th link is mapped to the ROS joint name link_joint_names[i].

klampt.io.ros.to_Path(klampt_path, start_time='now', frame='1')[source]

Converts a Klampt SE3Trajectory, SO3Trajectory, or 2D or 3D Trajectory to a ROS Path.

start_time can be ‘now’ or a rospy.Time object.

frame is the frame_id in the object’s headers (1 means global frame).

klampt.io.ros.from_Path(ros_path)[source]

Converts a ROS Path to a Klamp’t SE3Trajectory.

Times are assigned relative to header’s time stamp.

klampt.io.ros.from_Mesh(ros_mesh)[source]

From a ROS Mesh to a Klampt TriangleMesh

klampt.io.ros.to_Mesh(klampt_mesh)[source]

From a Klampt Geometry3D or TriangleMesh to a ROS Mesh

klampt.io.ros.from_PointCloud2(ros_pc)[source]

From a ROS PointCloud2 to a Klampt PointCloud

klampt.io.ros.to_PointCloud2(klampt_pc, frame='0', stamp='now')[source]

Converts a Klampt Geometry3D or PointCloud to a ROS PointCloud2 message.

If it’s a Geometry3D, the points are first transformed by the current transform.

frame is the ROS frame in the header. Default ‘0’ indicates no frame.

stamp is the ROS timestamp, or ‘now’, or a numeric value.

klampt.io.ros.to_CameraInfo(klampt_obj)[source]

Converts a Klampt SimRobotSensor, GLViewport, or Viewport to a ROS CameraInfo message.

klampt.io.ros.from_CameraInfo(ros_ci, klampt_obj)[source]

Fills in some information about a Klampt SimRobotSensor, GLViewport, or Viewport using a ROS CameraInfo message. Modifies the object in-place.

klampt.io.ros.to_SensorMsg(klampt_sensor, frame=None, frame_prefix='klampt', stamp='now')[source]

Converts a sensor’s measurements to a ROS message(s).

Special types are CameraSensor, ForceTorqueSensor, and LaserRangeSensor.

  • CameraSensor is converted to up to three messages: CameraInfo, Image (rgb, optional), and Image (depth, optional).

  • ForceTorqueSensor is converted to a WrenchStamped.

Generic sensors are converted to a Float32MultiArray.

Parameters
  • klampt_sensor (SimRobotSensor) – the sensor

  • frame (str, optional) – if given, this is the frame_id used in the ROS message(s). Otherwise, the id is determined automatically.

  • frame_prefix (str, optional) – if frame is not given, this is the prefix used in the automatic frame_id assignment (see below)

  • stamp (str, float, or rospy.Time, optional) – can be ‘now’, a float, or a rospy.Time. Will be set in the ROS message header.

The ROS frame_id is set as follows:

  • If frame!=None, then frame_id=frame.

  • If frame==None and frame_prefix==None, then frame_id = [robot_name]/[sensor_name].

  • Otherwise, frame_id = [frame_prefix]/[robot_name]/[sensor_name].

klampt.io.ros.to_ShapeMsg(klampt_geom)[source]
klampt.io.ros.fromMsg(ros_obj, *args, **kwargs)[source]

General conversion from ROS messages to corresponding Klamp’t objects.

klampt.io.ros.toMsg(klampt_obj, *args, **kwargs)[source]

General conversion from Klamp’t objects to corresponding ROS messages.

class klampt.io.ros.KlamptROSPublisher(converter, *args, **kwargs)[source]

Bases: rospy.topics.Publisher

You shouldn’t need to use this explicitly. Use publisher() or object_publisher() instead.

Methods:

publish(klampt_obj[, header])

Publishes a Klamp’t object to the advertised topic.

publish(klampt_obj, header=None)[source]

Publishes a Klamp’t object to the advertised topic.

Parameters
  • klampt_obj – A Klamp’t object of the appropriate type

  • header (Header, optional) – a ROS header that overrides the default which stamps with the current time.

class klampt.io.ros.KlamptROSCameraPublisher(topic, frame_id, frame_prefix, *args, **kwargs)[source]

Bases: object

You shouldn’t need to use this explicitly. Use object_publisher() instead.

Methods:

publish(camera)

Publishes a Klamp’t camera data to the topics:

publish(camera)[source]

Publishes a Klamp’t camera data to the topics:

  • [topic]/rgb/camera_info

  • [topic]/rgb/image_rect_color

  • [topic]/depth_registered/camera_info

  • [topic]/depth_registered/image_rect

Parameters

camera (SimRobotSensor) – an updated sensor of ‘CameraSensor’ type.

klampt.io.ros.publisher_SimRobotSensor(topic, klampt_sensor, convert_kwargs=None, **kwargs)[source]
klampt.io.ros.publisher(topic, klampt_type, convert_kwargs=None, ros_type=None, **kwargs)[source]

Convenience function. The publisher can be called in the form pub.publish(klampt_obj), which will convert a klampt_obj to a ROS message before publishing to a topic.

Returns

KlamptROSPublisher

klampt.io.ros.object_publisher(topic, klampt_object, convert_kwargs=None, **kwargs)[source]

Convenience function. If klampt_object is an object, this sets up the publisher to be of the correct type. You can then call publish on the returned publisher using the same klampt_object (or another compatible Klampt objects).

SimRobotSensors (particularly, cameras) can be published to multiple topics of the form [topic]/[subtopic].

Returns

KlamptROSPublisher

klampt.io.ros.subscriber(topic, klampt_type, callback, convert_kwargs=None, **kwargs)[source]

Convenience function. The subscriber automatically converts ROS messages to a Klampt type to be passed to the callback.

Returns

rospy.Subscriber

klampt.io.ros.object_subscriber(topic, klampt_obj, convert_kwargs=None, **kwargs)[source]

Convenience function. Every time a message arrives on the ROS topic, the given klampt object is updated.

Only valid for:

  • points / transforms provided as lists

  • Config (Float32MultiArray or JointState messages)

  • RobotModel (JointState messages)

  • SimRobotController (JointState messages)

  • Trajectory (JointTrajectory messages)

Returns

rospy.Subscriber

klampt.io.ros.broadcast_tf(broadcaster, klampt_obj, frameprefix='klampt', root='world', stamp=0.0)[source]

Broadcasts Klampt frames to the ROS tf module.

Parameters
  • broadcaster (tf.TransformBroadcaster) – the tf broadcaster

  • klampt_obj – the object to publish. Can be WorldModel, Simulator, RobotModel, SimRobotController, anything with a getTransform or getCurrentTransform method, or se3 element

  • frameprefix (str) – the name of the base frame for this object

  • root (str) – the name of the TF world frame.

Note

If klampt_obj is a Simulator or SimRobotController, then its corresponding model will be updated.

klampt.io.ros.listen_tf(listener, klampt_obj, frameprefix='klampt', root='world', onerror=None)[source]

Reads Klampt frames from the ROS tf module.

Parameters
  • listener (tf.TransformListener) – the tf listener

  • klampt_obj

    the object to update. Can be WorldModel, RobotModel, anything with a setTransform or setCurrentTransform method, or None (in the latter case, a se3 object will be returned).

    Note

    RobotModel configurations will not be changed, just the link transforms.

  • frameprefix (str) – the name of the base frame for this object

  • root (str) – the name of the TF world frame.

  • onerror (str or None) – either ‘raise’ in which case a tf exception is raised, ‘print’, in which case the error is printed, or None, in which case any exception is silently ignored.

klampt.io.numpy_convert module

Conversions to and from Numpy objects; makes numerical computations much more convenient.

Data:

SUPPORTED_TYPES

set of supported types for numpy I/O

Functions:

to_numpy(obj[, type])

Converts a Klamp’t object to a numpy array or multiple numpy arrays.

from_numpy(obj[, type, template])

Converts a numpy array or multiple numpy arrays to a Klamp’t object.

klampt.io.numpy_convert.SUPPORTED_TYPES = {'Config', 'Configs', 'Geometry3D', 'Matrix3', 'Point', 'PointCloud', 'RigidTransform', 'Rotation', 'Trajectory', 'TriangleMesh', 'Vector3', 'VolumeGrid'}

set of supported types for numpy I/O

klampt.io.numpy_convert.to_numpy(obj, type='auto')[source]

Converts a Klamp’t object to a numpy array or multiple numpy arrays.

Supports:

  • lists and tuples

  • RigidTransform: returned as 4x4 homogeneous coordinate transform

  • Matrix3, Rotation: returned as 3x3 matrix. Can’t be determined with ‘auto’, need to specify type=’Matrix3’ or ‘Rotation’.

  • Configs

  • Trajectory: returns a pair (times,milestones)

  • TriangleMesh: returns a pair (verts,indices)

  • PointCloud: returns a n x (3+k) array, where k is the # of properties

  • VolumeGrid: returns a triple (bmin,bmax,array)

  • Geometry3D: returns a pair (T,geomdata)

If you want to get a transformed point cloud or mesh, you can pass in a Geometry3D as the obj, and its geometry data type as the type.

klampt.io.numpy_convert.from_numpy(obj, type='auto', template=None)[source]

Converts a numpy array or multiple numpy arrays to a Klamp’t object.

Supports:

  • lists and tuples

  • RigidTransform: accepts a 4x4 homogeneous coordinate transform

  • Matrix3, Rotation: accepts a 3x3 matrix.

  • Configs

  • Trajectory: accepts a pair (times,milestones)

  • TriangleMesh: accepts a pair (verts,indices)

  • PointCloud: accepts a n x (3+k) array, where k is the # of properties

  • VolumeGrid: accepts a triple (bmin,bmax,array)

  • Geometry3D: accepts a pair (T,geomdata)

klampt.io.open3d_convert module

Conversions to and from the Open3D library.

Open3D is useful for doing various point cloud processing routines. It can be installed using pip as follows:

pip install open3d-python

Functions:

to_open3d(obj)

Converts Klamp’t geometry to an open3d geometry.

from_open3d(obj)

Converts open3d geometry to a Klamp’t geometry.

klampt.io.open3d_convert.to_open3d(obj)[source]

Converts Klamp’t geometry to an open3d geometry.

Geometry3D objects are converted applying the current transform.

If the VolumeGrid is considered to be an occupancy grid (all values between 0 and 1), then it is converted to a VoxelGrid containing a voxel for any positive items. If it is considered to be a SDF, then it contains a voxel of any non-positive items. There may be issues converting from VolumeGrids whose cells are non-cubic.

klampt.io.open3d_convert.from_open3d(obj)[source]

Converts open3d geometry to a Klamp’t geometry.

klampt.io.povray module

Module contents

klampt.io.subscribe_to_stream(*args)[source]

Subscribes a Geometry3D to a stream.

Parameters
  • g (Geometry3D) – the geometry that will be updated

  • protocol (str) – only “ros” accepted for now.

  • name (str) – the name of the stream, i.e., ROS topic.

  • type (str, optional) – If provided, specifies the format of the data to be subscribed to. If not, tries to determine the type automatically.

Only ROS point clouds (PointCloud2) are supported for now. Note that you can also call Geometry3D.loadFile(“ros://[ROS_TOPIC]”) or Geometry3D.loadFile(“ros:PointCloud2//[ROS_TOPIC]”) to accomplish the same thing.

TODO: It has not yet been determined whether this interferes with Rospy, i.e., klampt.io.ros.

Returns: (bool): True if successful.

Return type

bool

klampt.io.detach_from_stream(protocol, name)[source]

Unsubscribes from a stream previously subscribed to via SubscribeToStream()

Parameters
  • protocol (str) –

  • name (str) –

Return type

bool

klampt.io.process_streams(*args)[source]

Does some processing on stream subscriptions.

Parameters

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 type

bool

klampt.io.wait_for_stream(protocol, name, timeout)[source]

Waits up to timeout seconds for an update on the given stream.

Parameters
  • protocol (str) –

  • name (str) –

  • timeout (float) –

Returns

True if the stream was updated.

Return type

(bool)

Return type

bool

klampt.io.threejs_get_scene(arg1)[source]

Exports the WorldModel to a JSON string ready for use in Three.js.

Parameters

arg1 (WorldModel) –

Return type

str

klampt.io.threejs_get_transforms(arg1)[source]

Exports the WorldModel to a JSON string ready for use in Three.js.

Parameters

arg1 (WorldModel) –

Return type

str

klampt.io.load(type, fn)[source]

General-purpose load of an arbitrary Klampt object from a file or URL.

An exception is raised if there is an error loading or parsing the file. Possible exception types include IOError, ValueError, and HTTPError.

Parameters
  • type (str) – a Klamp’t type, ‘json’, or ‘auto’

  • fn (str) – a filename.

Returns

Klamp’t object

klampt.io.save(obj, type, fn)[source]

General-purpose save of an arbitrary Klampt object to a file.

This also works with RobotModel, RigidObjectModel, and TerrainModel (which don’t work with load).

Parameters
  • obj – a Klamp’t object.

  • type (str) – the Klampt type, ‘json’, or ‘auto’

  • fn (str) – a file name

Returns

True if successful.

Return type

bool

klampt.io.write(obj, type)[source]

General-purpose write of an arbitrary Klampt object to a str.

Parameters
  • obj – A Klampt object

  • type (str) – Either the Klamp’t type, ‘json’, or ‘auto’. If ‘auto’, the type will be auto-detected from the object.

Returns

The encoding of the object.

Return type

str

klampt.io.read(type, text)[source]

General-purpose read of an arbitrary Klampt object from a str.

Parameters
  • type (str) – Either the Klamp’t type, or ‘json’. Future versions may support ‘xml’ but this is not supported right now. ‘auto’ may not be specified.

  • text (str) – A string containing the object data.

Returns

Klamp’t object

klampt.io.to_json(obj, type='auto')[source]

Converts from a Klamp’t object to a JSON-compatible structure.

The resulting structure can be converted to a JSON string using json.dumps() in the Python builtin json module.

Not all objects are supported yet, notably geometry-related objects and world entities.

Parameters
  • obj – A Klamp’t object.

  • type (str, optional) – the type of the object (see types) If ‘auto’ (default), the type of the object is inferred automatically.

klampt.io.from_json(jsonobj, type='auto')[source]

Converts from a JSON structure to a Klamp’t object of the appropriate type.

Note: a JSON structure can be created from a JSON string using the json.loads() function in the Python builtin json module.

Not all objects are supported yet, notably geometry-related objects and world entities.

Parameters
  • jsonobj – A JSON structure (i.e., one coming from to_json())

  • type (str, optional) – the type of the object (see types) If ‘auto’ (default), the type of the object is inferred automatically.