mani_skill.envs.sim2real_env ============================ .. py:module:: mani_skill.envs.sim2real_env Classes ------- .. autoapisummary:: mani_skill.envs.sim2real_env.Sim2RealEnv Module Contents --------------- .. py:class:: Sim2RealEnv(sim_env, agent, real_reset_function = None, sensor_data_preprocessing_function = None, render_mode = 'sensors', skip_data_checks = False, control_freq = None) Bases: :py:obj:`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. :param sim_env: The simulation environment that the real environment should be aligned with. :type sim_env: BaseEnv :param agent: The real robot agent to control. This must be an object that inherits from BaseRealAgent. :type agent: BaseRealAgent :param real_reset_function: 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: .. code-block:: python 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") :type real_reset_function: Optional[Callable[[Sim2RealEnv, Optional[int], Optional[dict]], None]] :param sensor_data_preprocessing_function: 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 :type sensor_data_preprocessing_function: Optional[Callable[[dict], dict]] :param skip_data_checks: If False, this will reset the sim and real environments once to check if observations are aligned. It is recommended to keep this False. :type skip_data_checks: bool :param control_freq: The control frequency of the real robot. By default this is None and we use the same control frequency as the simulation environment. :type control_freq: Optional[int] .. py:method:: __getattr__(name) .. py:method:: _check_observations(sample_sim_obs, sample_real_obs) checks if the visual observations are aligned in terms of shape and resolution and expected data types .. py:method:: _flatten_raw_obs(obs) .. py:method:: _get_obs_agent() .. py:method:: _get_obs_extra(info) .. py:method:: _get_obs_sensor_data(apply_texture_transforms = True) .. py:method:: _get_obs_with_sensor_data(info, apply_texture_transforms = True) Get the observation with sensor data .. py:method:: _step_action(action) 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 .. py:method:: close() 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. .. py:method:: compute_dense_reward(obs, action, info) :abstractmethod: .. py:method:: compute_normalized_dense_reward(obs, action, info) :abstractmethod: .. py:method:: compute_sparse_reward(obs, action, info) 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 .. py:method:: get_info() .. py:method:: get_obs(info=None, unflattened=False) .. py:method:: get_reward(obs, action, info) .. py:method:: get_sensor_images() .. py:method:: get_sensor_params() .. py:method:: preprocess_sensor_data(sensor_data, sensor_names = None) .. py:method:: render() Compute the render frames as specified by :attr:`render_mode` during the initialization of the environment. The environment's :attr:`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 :attr:`render_mode` is known during ``__init__``, the objects used to render the environment state should be initialised in ``__init__``. By convention, if the :attr:`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 :meth:`step` and :meth:`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, :py:class:`gymnasium.wrappers.RenderCollection` that is automatically applied during ``gymnasium.make(..., render_mode="rgb_array_list")``. The frames collected are popped after :meth:`render` is called or :meth:`reset`. .. note:: Make sure that your class's :attr:`metadata` ``"render_modes"`` key includes the list of supported modes. .. versionchanged:: 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")`` .. py:method:: render_sensors() .. py:method:: reset(seed=None, options=None) 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 :meth:`reset` is called with ``seed=None``, the RNG is not reset. Therefore, :meth:`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 :meth:`reset` should be ``super().reset(seed=seed)`` which implements the seeding correctly. .. versionchanged:: v0.25 The ``return_info`` parameter was removed and now info is expected to be returned. :param seed: 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 :attr:`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. :type seed: optional int :param options: Additional information to specify how the environment is reset (optional, depending on the specific environment) :type options: optional dict :returns: Observation of the initial state. This will be an element of :attr:`observation_space` (typically a numpy array) and is analogous to the observation returned by :meth:`step`. info (dictionary): This dictionary contains auxiliary information complementing ``observation``. It should be analogous to the ``info`` returned by :meth:`step`. :rtype: observation (ObsType) .. py:method:: step(action) 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 .. py:attribute:: _elapsed_steps .. py:attribute:: _env_with_real_step_reset a simple object that defines the real step/reset functions for gym wrappers to call and use. .. py:attribute:: _handle_wrappers :value: False .. py:attribute:: _obs_mode .. py:attribute:: _orig_single_action_space .. py:attribute:: _reward_mode .. py:attribute:: _sensor_names list of sensors the simulation environment uses .. py:attribute:: action_space .. py:attribute:: agent .. py:attribute:: base_sim_env :type: mani_skill.envs.sapien_env.BaseEnv the unwrapped simulation environment .. py:attribute:: control_dt .. py:attribute:: control_freq .. py:attribute:: device .. py:property:: elapsed_steps .. py:attribute:: last_control_time :type: Optional[float] :value: None .. py:attribute:: metadata .. py:attribute:: num_envs :value: 1 .. py:attribute:: obs_mode .. py:attribute:: obs_mode_struct .. py:attribute:: observation_space .. py:attribute:: real_reset_function .. py:attribute:: render_mode :value: 'sensors' .. py:attribute:: reward_mode .. py:attribute:: sim_env .. py:attribute:: sim_freq