mani_skill.envs.sim2real_env#

Classes#

Sim2RealEnv

Sim2RealEnv is a class that lets you interface with a real robot and align the real robot and environment with a simulation environment. It tries to ensure the action and observation space

Module Contents#

class mani_skill.envs.sim2real_env.Sim2RealEnv(sim_env, agent, real_reset_function=None, sensor_data_preprocessing_function=None, render_mode='sensors', skip_data_checks=False, control_freq=None)[source]#

Bases: gymnasium.Env

Sim2RealEnv is a class that lets you interface with a real robot and align the real robot and environment with a simulation environment. It tries to ensure the action and observation space are the exact same in the real and simulation environments. Any wrappers you apply to the simulation environment are also used in the Sim2RealEnv automatically.

There are some caveats in which you may need to override this class / write your own code instead:

  • If you use privileged features in the simulation environment like an object’s pose then we cannot retrieve those poses in the real environment. You can for example override the _get_obs_extra function to compute those values in the real environment via a perception pipeline.

  • While we align controllers and observation shapes/ordering as much as possible, there can still be distribution shifts between the simulation and real environment. These can include vision gaps (sim images looking not like the real world) and sensor biases and noise.

Parameters:
  • sim_env (BaseEnv) – The simulation environment that the real environment should be aligned with.

  • agent (BaseRealAgent) – The real robot agent to control. This must be an object that inherits from BaseRealAgent.

  • real_reset_function (Optional[Callable[[Sim2RealEnv, Optional[int], Optional[dict]], None]]) –

    The function to call to reset the real robot. By default this is None and we use a default reset function which calls the simulation reset function and resets the agent/robot qpos to whatever the simulation reset function sampled, then prompts the user to press enter before continuing running. This function is given access to the Sim2RealEnv instance, the given seed and options dictionary similar to a standard gym reset function. The default function and example is shown below:

    def real_reset_function(self, seed=None, options=None):
        self.sim_env.reset(seed=seed, options=options)
        self.agent.reset(qpos=self.base_sim_env.agent.robot.qpos.cpu().flatten())
        input("Press enter if the environment is reset")
    

  • sensor_data_preprocessing_function (Optional[Callable[[dict], dict]]) – The function to call to process the sensor data returned by the BaseRealAgent.get_sensor_data function. By default this is None and we use a default processing function which does the following for each sensor type: - Camera: Perform a center crop of the real sensor image (rgb or depth) to have the same aspect ratio as the simulation sensor image. Then resize the image to the simulation sensor image shape using cv2.resize

  • skip_data_checks (bool) – If False, this will reset the sim and real environments once to check if observations are aligned. It is recommended to keep this False.

  • control_freq (Optional[int]) – The control frequency of the real robot. By default this is None and we use the same control frequency as the simulation environment.

  • render_mode (Optional[str]) –

__getattr__(name)[source]#
_check_observations(sample_sim_obs, sample_real_obs)[source]#

checks if the visual observations are aligned in terms of shape and resolution and expected data types

_flatten_raw_obs(obs)[source]#
Parameters:

obs (Any) –

_get_obs_agent()[source]#
_get_obs_extra(info)[source]#
Parameters:

info (dict) –

_get_obs_sensor_data(apply_texture_transforms=True)[source]#
Parameters:

apply_texture_transforms (bool) –

_get_obs_with_sensor_data(info, apply_texture_transforms=True)[source]#

Get the observation with sensor data

Parameters:
  • info (dict) –

  • apply_texture_transforms (bool) –

Return type:

dict

_step_action(action)[source]#

Re-implementation of the simulated BaseEnv._step_action function for real environments. This uses the simulation agent’s controller to compute the joint targets/velocities without stepping the simulator

close()[source]#

After the user has finished using the environment, close contains the code necessary to “clean up” the environment.

This is critical for closing rendering windows, database or HTTP connections. Calling close on an already closed environment has no effect and won’t raise an error.

abstract compute_dense_reward(obs, action, info)[source]#
Parameters:
  • obs (Any) –

  • action (torch.Tensor) –

  • info (dict) –

abstract compute_normalized_dense_reward(obs, action, info)[source]#
Parameters:
  • obs (Any) –

  • action (torch.Tensor) –

  • info (dict) –

compute_sparse_reward(obs, action, info)[source]#

Computes the sparse reward. By default this function tries to use the success/fail information in returned by the evaluate function and gives +1 if success, -1 if fail, 0 otherwise

Parameters:
  • obs (Any) –

  • action (torch.Tensor) –

  • info (dict) –

get_info()[source]#
get_obs(info=None, unflattened=False)[source]#
get_reward(obs, action, info)[source]#
get_sensor_images()[source]#
get_sensor_params()[source]#
preprocess_sensor_data(sensor_data, sensor_names=None)[source]#
Parameters:
  • sensor_data (dict) –

  • sensor_names (Optional[list[str]]) –

render()[source]#

Compute the render frames as specified by render_mode during the initialization of the environment.

The environment’s metadata render modes (env.metadata[“render_modes”]) should contain the possible ways to implement the render modes. In addition, list versions for most render modes is achieved through gymnasium.make which automatically applies a wrapper to collect rendered frames.

Note

As the render_mode is known during __init__, the objects used to render the environment state should be initialised in __init__.

By convention, if the render_mode is:

  • None (default): no render is computed.

  • “human”: The environment is continuously rendered in the current display or terminal, usually for human consumption. This rendering should occur during step() and render() doesn’t need to be called. Returns None.

  • “rgb_array”: Return a single frame representing the current state of the environment. A frame is a np.ndarray with shape (x, y, 3) representing RGB values for an x-by-y pixel image.

  • “ansi”: Return a strings (str) or StringIO.StringIO containing a terminal-style text representation for each time step. The text can include newlines and ANSI escape sequences (e.g. for colors).

  • “rgb_array_list” and “ansi_list”: List based version of render modes are possible (except Human) through the wrapper, gymnasium.wrappers.RenderCollection that is automatically applied during gymnasium.make(..., render_mode="rgb_array_list"). The frames collected are popped after render() is called or reset().

Note

Make sure that your class’s metadata "render_modes" key includes the list of supported modes.

Changed in version 0.25.0: The render function was changed to no longer accept parameters, rather these parameters should be specified in the environment initialised, i.e., gymnasium.make("CartPole-v1", render_mode="human")

render_sensors()[source]#
reset(seed=None, options=None)[source]#

Resets the environment to an initial internal state, returning an initial observation and info.

This method generates a new starting state often with some randomness to ensure that the agent explores the state space and learns a generalised policy about the environment. This randomness can be controlled with the seed parameter otherwise if the environment already has a random number generator and reset() is called with seed=None, the RNG is not reset.

Therefore, reset() should (in the typical use case) be called with a seed right after initialization and then never again.

For Custom environments, the first line of reset() should be super().reset(seed=seed) which implements the seeding correctly.

Changed in version v0.25: The return_info parameter was removed and now info is expected to be returned.

Parameters:
  • seed (optional int) – The seed that is used to initialize the environment’s PRNG (np_random) and the read-only attribute np_random_seed. If the environment does not already have a PRNG and seed=None (the default option) is passed, a seed will be chosen from some source of entropy (e.g. timestamp or /dev/urandom). However, if the environment already has a PRNG and seed=None is passed, the PRNG will not be reset and the env’s np_random_seed will not be altered. If you pass an integer, the PRNG will be reset even if it already exists. Usually, you want to pass an integer right after the environment has been initialized and then never again. Please refer to the minimal example above to see this paradigm in action.

  • options (optional dict) – Additional information to specify how the environment is reset (optional, depending on the specific environment)

Returns:

Observation of the initial state. This will be an element of observation_space

(typically a numpy array) and is analogous to the observation returned by step().

info (dictionary): This dictionary contains auxiliary information complementing observation. It should be analogous to

the info returned by step().

Return type:

observation (ObsType)

step(action)[source]#

In order to make users able to use most gym environment wrappers without having to write extra code for the real environment we temporarily swap the last wrapper’s .env property with the RealEnvStepReset environment that has the real step/reset functions

_elapsed_steps[source]#
_env_with_real_step_reset[source]#

a simple object that defines the real step/reset functions for gym wrappers to call and use.

_handle_wrappers = False[source]#
_obs_mode[source]#
_orig_single_action_space[source]#
_reward_mode[source]#
_sensor_names[source]#

list of sensors the simulation environment uses

action_space[source]#
agent[source]#
base_sim_env: mani_skill.envs.sapien_env.BaseEnv[source]#

the unwrapped simulation environment

control_dt[source]#
control_freq[source]#
device[source]#
property elapsed_steps[source]#
last_control_time: float | None = None[source]#
metadata[source]#
num_envs = 1[source]#
obs_mode[source]#
obs_mode_struct[source]#
observation_space[source]#
real_reset_function[source]#
render_mode = 'sensors'[source]#
reward_mode[source]#
sim_env[source]#
sim_freq[source]#