mani_skill.envs.sim2real_env#
Classes#
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.EnvSim2RealEnv 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]) –
- _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
- _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
closeon 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) –
- 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_modeduring the initialization of the environment.The environment’s
metadatarender 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_modeis known during__init__, the objects used to render the environment state should be initialised in__init__.By convention, if the
render_modeis: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()andrender()doesn’t need to be called. ReturnsNone.“rgb_array”: Return a single frame representing the current state of the environment. A frame is a
np.ndarraywith shape(x, y, 3)representing RGB values for an x-by-y pixel image.“ansi”: Return a strings (
str) orStringIO.StringIOcontaining 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.RenderCollectionthat is automatically applied duringgymnasium.make(..., render_mode="rgb_array_list"). The frames collected are popped afterrender()is called orreset().
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")
- 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
seedparameter otherwise if the environment already has a random number generator andreset()is called withseed=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 besuper().reset(seed=seed)which implements the seeding correctly.Changed in version v0.25: The
return_infoparameter 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 andseed=Noneis passed, the PRNG will not be reset and the env’snp_random_seedwill 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
inforeturned bystep().
- Observation of the initial state. This will be an element of
- 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
- _env_with_real_step_reset[source]#
a simple object that defines the real step/reset functions for gym wrappers to call and use.
- base_sim_env: mani_skill.envs.sapien_env.BaseEnv[source]#
the unwrapped simulation environment