blueprints.world module#
The World class hosts all Things in a Simulation. It handles the access to Mujoco by implementing a
method, that converts the Constructed World to an xml string and a method used to launch a Mujoco viewer, that
is especially useful during model construction for debugging. You can add and remove Things from the World with
the same methods as in NodeThing i.e. attach
and detach.
>>> world = blue.World()
>>> teapot = blue.geoms.Mesh(filename='utahteapot.stl', pos=[0, 0, 1])
>>> red_teapot = teapot.copy(color='red')
>>> green_teapot = teapot.copy(color='green')
>>> world.attach(red_teapot, green_teapot, copy=False)
>>> world.geoms.color
[Red[#FF0000], Green[#00FF00]]
>>> world.detach(red_teapot)
>>> world.geoms.color
[Green[#00FF00]]
The view method can be used. The perspective of the default camera is set such that all
Things attached to the World are in view.
>>> world.view()
Things that are attached with the background flag argument set to True will not be used to center the
perspective of the camera.
>>> plane = blue.geoms.Plane()
>>> world.attach(plane, background=True)
>>> world.view()
- class blueprints.world.World[source]#
-
This class is available through the shortcut
blueprints.World.Most attribute descriptions are partially taken from Mujoco.
- angle#
Either
'radian'or'degree'(avoid if possible).- Type:
str
- autolimits#
Indicating whether limits are used or not.
- Type:
bool
- contact#
Indicating whether collisions and contacts are ignored in the simulations physics.
- Type:
bool
- gravity#
Indicating whether gravity exists.
- Type:
bool
- integrator#
The name of the integrator use, see
integratorfor a detailed description.- Type:
str
- viscosity#
The viscosity of the Worlds Things.
- Type:
float
- __init__(name='anonymous_model', autolimits=True, viscosity=0.0, timestep=0.002, integrator='implicit', cone='pyramidal', gravity=True, contact=True, angle='radian', texture=None, **kwargs)[source]#
- Parameters:
name (
str, optional) – The user specified name for the Actuator. In the case of a naming conflict the name will be altered by an enumeration scheme.autolimits (
bool, optional) – This attribute affects the behavior of attributes such as'limited'(on <body-joint>'forcelimited','ctrllimited', and'actlimited'(on <actuator>). IfTrue, these attributes are unnecessary and their value will be inferred from the presence of their corresponding'range'attribute. IfFalse, no such inference will happen: For a Joint to be limited, both limited=``True`` and range=``min max`` must be specified. In this mode, it is an error to specify a range without a limit.timestep (
float | int | None, optional) – Simulation time step in seconds. This is the single most important parameter affecting the speed-accuracy trade-off which is inherent in every physics simulation. Smaller values result in better accuracy and stability. To achieve real-time performance, the time step must be larger than the CPU time per step (or 4 times larger when using the RK4 integrator). The CPU time is measured with internal timers. It should be monitored when adjusting the time step.viscosity (
float | int | None, optional) – Viscosity of the medium. This parameter is used to simulate viscous forces, which scale linearly with velocity. In SI units the viscosity of air is around 0.00002 while the viscosity of water is around 0.0009 depending on temperature. Setting viscosity to 0 disables viscous forces. Note that the default Euler integrator handles damping in theJointsimplicitly – which improves stability and accuracy. It does not presently do this with body viscosity. Therefore, if the goal is merely to create a damped simulation (as opposed to modelling the specific effects of viscosity), we recommend using joint damping rather than body viscosity, or switching to the implicit or implicitfastintegrator.cone (
str, optional) – The type of contact friction cone. Elliptic cones are a better model of the physical reality, but pyramidal cones sometimes make the solver faster and more robust.integrator (
str, optional) – This attribute selects the numerical integrator to be used. Currently the available integrators are the semi-implicit Euler method'Euler', the fixed-step 4-th order Runge Kutta method'RK4', the Implicit-in-velocity Euler method'implicit', and'implicitfast', which drops the Coriolis and centrifugal terms.gravity (
bool, optional) – A flag indicating whether gravity exists. Be default the gravitational constant. is set to \(6.674 \times 10^{-11} N \frac{m^2}{kg^2}\).contact (
bool, optional) – IfFalse, collisions and contacts are ignored in the simulations physics.angle (
str, optional) –The angle measure either
'radian'or'degree'. .. warning:At the moment 'degree' is not supported for any manipulations. It is recommended to only use 'degree' if no orientation manipulation is performed on the model! To convert from degrees to radians use the multiplier :attr:`DEGREES_TO_RADIANS <blueprints.utils.geometry.DEGREES_TO_RADIANS>`
**kwargs – Keyword arguments are passed to
super().__init__.texture (SkyboxTextureType | None)
- attach(*items, copy=False, background=False)[source]#
This method attaches *items to the parent Thing. If copy is set true, a copy of the items is created. If copy is set to false, the kinematic graph might no longer be a tree resulting in infinite loops or naming conflicts if the same item is included in the tree twice. All items of a specific type can be accessed via the types attribute.
- Parameters:
*items (
list[blue.ThingType]) – All items that are to be attached.copy (
bool, optional) – A flag indicating whether a copy of the items should be attached.background (
bool, optional) – A flag indicating whether the attached Things belong to the Worlds background.
- Raises:
TypeError – If an item is not a valid child an error is raised.
- Return type:
None
- detach(*items)[source]#
This method is used to detach Things from the kinematic tree. They are afterwards no longer present in this Worlds children attributes and their
parentattribute will be set toNone.
- build()[source]#
This method constructs the xml structure of the kinematic tree. It is called before the World is converted to an xml string if any modification to it was done since the last build. It is not necessary for a user to call this method since it is implicitly called every time the build needs to be updated.
- Return type:
None
- reset()[source]#
This method resets the Mujoco simulation data and initializes a single first step to make all runtime data accessable.
- unbuild()[source]#
Unbuilds the World to anable alterations. This discards the current Mujoco simulation.
- Return type:
None
- view(callback=<function World.<lambda>>)[source]#
Launches an interactive window of the Mujoco simulation.
- Parameters:
callback (
function) – The callback function is called after each timestep. The user can use this function to update World properties during the simulation.- Return type:
None
- step(n_steps=1, seconds=None, pbar=False)[source]#
Performs timesteps in the simmulation. Exactly one argument must be given by the user. All cameras that are recording are taking images during the simulation at their respective times.
- Parameters:
n_steps (
int | None) – The number of steps to be takenseconds (
int | float | None) – The number of seconds to be simulatedpbar (bool)
- Return type:
None
- start_recording(*cameras, filename, fps=60, **kwargs)[source]#
This method starts recordings of the cameras passed to it. The rendering is done by the mujoco.Renderer using OpenGL. The user should make sure, that their OpenGL instance is properly functioning. The video files are written to the
recordingsdirectory next to the file instantiating the World. The format is infered from the file extension in thefilenameusing imageio. To set additional parameters for the video formatting in imageio the user can set the**kwargswhich are passed to the imageio writer.Example
If the user would like to record a gif image that loops forever (instead of the default case of a single loop) the user can set the argument
loopto zero, indicating an infinitely looping gif in the imageio writer:>>> world.start_recording(camera, filename='my.gif', loop=0)
Now the camera has started recording, but there is nothing yet happening in the simulation. Using
World.step()the user can simulate the passage of time with the recording cameras writing images to their respective video files at correpsonding moments (as determined byfpsandWorld.timestep). Additionally the user can apply actions in between timesteps via anAgentor throughActuatorsdirectly.For example, the following lines demonstrate such a simulation loop with some number of steps in MDP space determined by
time_steps, someskip_frames, a blueprintsAgentagentused to interface with theSensorsandActuatorsand an RL-Agentpolicy>>> for t in range(time_steps): >>> world.step(n_steps=skip_frames) >>> agent.force = policy(agent.observations)
Finally the recordings are stopped using
stop_recording()to save the recorded videos to a file.>>> world.stop_recording()
The final video of the users agent can then be found in
'recordings/camera_my.gif'- Parameters:
*cameras (
list [ blue.CameraType ]) – A list ofCamerasfilename (
str) – The name (with a proper file extension indicating the format) of the video. If multiple cameras are passed, multiple videos will be created with the name of each camera prefixed to the filename.fps (
int) – The frames per second**kwargs (
dict) – Additional keyword arguments that are passed to imageio to write the video.
- stop_recording(*cameras)[source]#
This method stops recording for all the cameras passed. If no camera is passed, all recording cameras will be stopped.
- Parameters:
cameras (
list [ blue.CameraType ]) – The cameras to be stopped.
- to_xml_string()[source]#
If not build, this method will first build the world, retrieve the XML string and then unbuild the world again. If the user calls this method repeatedly the world should probably be build first.
- Returns:
The xml string representing the xml model used to launch Mujoco.
- Return type:
str
- classmethod from_xml_string(string)[source]#
This method reconstructs a World from a Mujoco xml string. It currently only supports reading models, that exclusively consist of blueprints supported features. In a future version it will be extended to be compatible to all Mujoco models.
- Parameters:
string (
str) – The xml description of the Mujoco model.- Returns:
The reconstructed World.
- Return type:
blue.WorldType
- property model#
If a feature is not accessable through blueprints you can access the Mujoco model directly.
- Return type:
mj.Model
- property data#
If a feature is not accessable through blueprints you can access the Mujoco data directly.
- Return type:
mj.Data
- property size#
The size is computed to sclae the FreeCamera of the viewer (see
World.view()).- Returns:
The size of the World ignoring background Things.
- Return type:
np.ndarray
- property center#
The center is computed to position the FreeCamera of the viewer (see
World.view()).- Returns:
The center of the World ignoring background Things.
- Return type:
np.ndarray
- property texture: SkyboxTextureType#
Only a
SkyboxTextureare valid for the World.Note
At the moment, Mujoco is only rendering SkyboxTextures of the World, if also another texture is taken by a material refferenced by a Thing within the World.
- Returns:
The Skybox Texture which is applied to the background of the World.
- Return type:
blue.SkyboxTextureType