# klampt.sim package¶

This package has helper classes for running simulations. The core functionality is in the klampt.robotsim C++ module, in particular the Simulator class.

The batch module allows multiple similar simulations to be run relatively easily.

The settle module lets you easily create piles of objects that are stable.

The simulation and simlog modules let you log, replay, and modify the behavior of simulations more reliably than manually modifying Simulator loops.

## klampt.sim.batch module¶

klampt.sim.batch.batchSim(world, duration, initialConditions, returnItems, simDt=0.01, simInit=None, simStep=None, simTerm=None)[source]

Given a world, a simulation duration, and a list of initial conditions, runs simulations for all initial conditions.

Parameters
• world,duration,returnItems,simDt,simInit,simStep,simTerm – the same as in doSim()

• initialConditions (dict or list) – either a dict mapping named items to lists of initial values, or a list of initial state dictionaries. In the former case, all entries must be of the same length.

Returns

all return values from doSim(). See the doSim()

Return type

(list)

klampt.sim.batch.doSim(world, duration, initialCondition, returnItems=None, trace=False, simDt=0.01, simInit=None, simStep=None, simTerm=None)[source]

Runs a simulation for a given initial condition of a world.

Parameters
• world (WorldModel) – the world

• duration (float) – the maximum duration of simulation, in seconds

• initialCondition (dict) –

a dictionary mapping named items to values. Each named item is specified by a path as used by the access module, e.g. ‘robot[0].config[4]’. See the documentation for access.get_item()/ access.set_item() for details.

Special items include ‘args’ which is a tuple provided to each simInit, simStep, and simTerm call.

• returnItems (list of strs, optional) – a list of named items to return in the final state of the simulation. By default returns everything that is variable in the simulator (simulation time, robot and rigid object configuration / velocity, robot commands, robot sensors).

• trace (bool, optional) – if True, returns the entire trace of the items specified in returnItems rather than just the final state.

• simDt (float, optional, default 0.01) – the outer simulation loop (usually corresponds to the control rate).

• simInit (function, optional) – a function f(sim) called on the simulator after its initial conditions are set but before simulating. You may configure the simulator with this function.

• simStep (function, optional) – a function f(sim) that is called on every outer simulation loop (usually a controller function).

• simTerm (function, optional) – a function f(sim) that returns True if the simulation should terminate early. Called on every outer simulation loop.

Returns

the final state of each returned item upon termination. The dictionary maps named items (specified by the returnItems argument) to their values. Additional returned items are:

• ’status’, which gives the status string of the simulation

• ’time’, which gives the time of the simulation, in s

• ’wall_clock_time’, which gives the time elapsed while computing the simulation, in s

Return type

(dict)

klampt.sim.batch.getWorldSimState(world)[source]

Returns a dict containing a copy of all variables that are simulated in the world. Can be used with setWorldSimState to save/ restore state.

NOTE: this does not perfectly save the state of a Simulator! To do that, you must use the Simulator().getState()/saveState() methods.

klampt.sim.batch.monteCarloSim(world, duration, initialConditionSamplers, N, returnItems, simDt=0.01, simInit=None, simStep=None, simTerm=None)[source]

Given a world, a simulation duration, and dict of sampling functions for world items, runs N monte-carlo simulations.

Parameters
• duration, returnItems, simDt, simInit, simStep, simTerm (world,) – same as for doSim()

• initialConditionSamplers (dict of functions) – a dict mapping named world items to sampling functions that take no arguments (i.e., sample()).

• N (int) – the number of Monte Carlo samples.

Returns

contains N pairs (initCond,returnVal) containing each simulation result:

• initCond: the sampled initial condition

• returnVal: the return value from doSim().

Return type

list

klampt.sim.batch.saveStateCSV(state, f)[source]

Given a state dictionary, saves it to CSV format to the given output stream f

klampt.sim.batch.saveStateHeaderCSV(state, f)[source]

Given a state dictionary, saves the header CSV format to the given output stream f

klampt.sim.batch.saveStateTrajectoryCSV(stateTraj, f)[source]

Given a state trajectory (dict mapping keys to lists), saves it to CSV format to the given output stream f.

klampt.sim.batch.saveStatesCSV(states, f)[source]

Given list of state dictionaries, saves them to CSV format to the given output stream f

klampt.sim.batch.setWorldSimState(world, state)[source]

Sets the world state to the prior saved state (a dict from getWorldSimState())

NOTE: this does not perfectly save simulation state! To do that, you must use the Simulator().getState()/saveState() methods.

## klampt.sim.settle module¶

klampt.sim.settle.settle(world, obj, forcedir=(0, 0, - 1), forcept=(0, 0, 0), settletol=0.0001, orientationDamping=0.0, perturb=0, margin=None, debug=False)[source]

Assuming that all other elements in the world besides object are frozen, this “settles” the object by applying a force in the direction forcedir and simulating until the object stops moving.

An exception is raised if the object is already colliding with the world.

Parameters
• world (WorldModel) – the world containing other static and moving objects

• obj – a RigidObjectModel, RobotModelLink, or floating-base Robot that will be settled.

• forcedir (list of 3 floats, optional) – a vector parallel to the direction of force whose magnitude is the maximum distance this procedure will try to move the object.

• forcept (list of 3 floats, optional) – local coordinates of the center of force application.

• settletol (float, optional) – the simulation will stop when two subsequent transforms lie within this tolerance.

• orientationDamping (float, optional) – a virtual spring will attempt to keep the initial orientation with this torsional spring constant

• perturb (float, optional) – if nonzero, the application force will be perturbed at random by this amount every step. If equal to 1, this means the force is sampled from a 45 degree cone in the direction forcedir.

• margin (float, optional) – the collision detection margin used in simulation. If None, uses the Simulator default. Otherwise, overrides the default. Must be at least settletol.

• debug (bool, optional) – if True, uses the visualization to debug the settling process

Returns

A pair (transform,touched) with:

• transform (se3 transform): The resulting se3 transform of the object, or None if the object didn’t hit anything by the time it translated by ||forcedir|| units.

• touched (dict): a dictionary whose keys are object IDs touched by the object at the final transform, and whose values are lists of ContactPoints (see klampt.model.contact) giving the contacts between obj and the touched object.

To convert the result to a hold, call:

h = Hold()
h.setFixed(obj,sum(touched.values(),[]))


Return type

tuple

## klampt.sim.simlog module¶

class klampt.sim.simlog.SimLogPlayback(sim, state_fn, contact_fn=None)[source]

Bases: object

A replay class for simulation traces from SimLogger or the SimTest app.

Parameters
• sim (Simulator) – the klampt.Simulator object you wish to use. This should be instantiated with all objects that you recorded from.

• state_fn (str) – the state file that you want to load

• contact_fn (str, optional) – the contact file that you want to load

updateSim(time=- 1, timestep=- 1)[source]
class klampt.sim.simlog.SimLogger(sim, state_fn, contact_fn=None, colliding='all', saveheader=True)[source]

Bases: object

A CSV logger for a simulation.

Logs a simulation to a CSV file.

Parameters
• sim (Simulator) – the klampt.Simulator object you wish to use

• state_fn (str) – the file that you want to save state to

• contact_fn (str, optional) – the file that you want to save contacts to (or None if you don’t want them)

• colliding (list, optional) – either ‘all’ (default) or a list of all objects and object ids that you want to check self collisions between

• saveheader (bool, optional) – true if you want a CSV header giving the name of each value. Default = True

close()[source]
saveContactHeader()[source]
saveHeader(extra=[])[source]
saveStep(extra=[])[source]

## klampt.sim.simulation module¶

class klampt.sim.simulation.ActuatorEmulator[source]

Bases: object

A generic actuator emulator. Translates outputs from the Python controller -> the physics simulation. A variety of non-traditional actuators can be simulated here.

The Python controller is assumed to have the structure of BaseController, where outputs a dictionary of commands every control time step. The emulator will read these with the process() methods

drawGL()[source]

Optional: for debugging

process(commands, dt)[source]

Processes the dictionary of commands, which are outputted by the controller. This may involve applying commands to the low-level motor emulator, or applying forces to the simulator.

Parameters
• commands (dict) – a dictionary of commands produced by the controller

• dt (float) – the control time step (not the underlying simulation time step)

To play nicely with other actuators in a nested steup, once a command is processed, the class should remove it from the commands dictionary.

substep(dt)[source]

This is called every simulation substep, which occurs at a higher rate than process() is called. dt is the simulation substep.

class klampt.sim.simulation.DefaultActuatorEmulator(sim, controller)[source]

This default emulator can take the commands

• torquecmd: torque comand

• qcmd: position command

• dqcmd: velocity command

• tcmd: time for a dqcmd

And will also pass any remaining commands to the low-level C controller.

It can also simulate forces, etc. at a higher rate than the control loop rate.

process(commands, dt)[source]

Commands: a dictionary of values outputted from the controller module, or None if no command was issued.

class klampt.sim.simulation.DefaultSensorEmulator(sim, controller)[source]

A sensor emulator that by default provides the robot’s commanded position, velocity, and other sensors defined in the robot or world XML file.

drawGL()[source]

Optional: for debugging

update()[source]

Returns a dictionary mapping named sensors to their outputs.

class klampt.sim.simulation.SensorEmulator[source]

Bases: object

A generic sensor emulator. Translates from the physics simulation -> inputs to a Python controller.

The Python controller is assumed to have the structure of klampt.control.controller.ControllerBase, where it is given as input a dictionary of named items reflecting the most up-to-date readings on each control time-step.

drawGL()[source]

Optional: for debugging

update()[source]

Returns a dictionary mapping named sensors to their outputs.

class klampt.sim.simulation.SimpleSimulator(world)[source]

Bases: klampt.robotsim.Simulator

A convenience class that enables easy logging, definition of simulation hooks, emulators of sensors / actuators, and definition of robot controllers.

Note that for greatest compatibility you should NOT manually apply forces to the simulation except for inside of hooks and emulators. This is because several simulation sub-steps will be taken, and you will have no control over the forces applied except for the first time step.

Parameters

world (WorldModel) – the world that should be simulated.

Constructs the simulator from a WorldModel. If the WorldModel was loaded from an XML file, then the simulation setup is loaded from it.

Parameters

model (WorldModel) –

addEmulator(robot, e)[source]

Adds an emulator to the given robot. e must be of SensorEmulator or ActuatorEmulator type.

addHook(objects, function)[source]

For the world object(s), applies a hook that gets called every simulation loop.

Parameters
• objects

may be an str identifier, a WorldModel entity, or a SimBody. can also be a list of such objects.

• str: ‘time’, or the name of any items in the world. If ‘time’, the simulation time is passed to function. Otherwise, the SimBody object named by this str is passed to function.

• RobotModelLink, RigidObjectModel, TerrainModel: the corresponding SimBody object is passed to function.

• RobotModel: the corresponding SimRobotController object is passed to function.

• Otherwise, object[i] is passed directly to function.

• function (function) – a function f(o1,o2,…,on) that is called every substep with the given object(s) as arguments.

beginLogging()[source]
control_loop(dt)[source]
drawControllersGL()[source]
drawEmulatorsGL()[source]
drawGL()[source]
endLogging()[source]
getStatus()[source]

Returns an indicator code for the simulator status. The return result is one of the STATUS_X flags. (Technically, this returns the worst status over the last simulate() call)

Returns

Return type

int

getStatusString(status=- 1)[source]

Returns a string indicating the simulator’s status. If s is provided and >= 0, this function maps the indicator code s to a string.

getStatusString (s=-1): str

getStatusString (): str

Parameters

s (int, optional) – default value -1

Returns

Return type

(str)

pauseLogging(paused=True)[source]
setController(robot, function)[source]

Sets a robot’s controller function.

Parameters
• robot – either an index, string, or RobotModel.

• function – either 1) a one-argument function that takes the robot’s SimRobotController instance, or 2) an instance of a klampt.control.controller.ControllerBlock class, which must conform to the klampt.control.controller.RobotControllerBase convention.

simulate(dt)[source]

Runs the simulation. Note that this should be called at the rate of the controller. Simulation hooks and emulator substeps will be called at the rate of substep_dt.

Parameters

dt (float) – control timestep

toggleLogging()[source]