Table of Contents

Class MujocoEnv

Namespace
Gym.Environments.Envs.MuJoCo
Assembly
Gym.Environments.dll

The base of Gymnasium's MuJoCo envs (MujocoEnv): one embedded model (DR-63) and its simulation, stepped by Gym.NET's own engine bit for bit as MuJoCo 4.0.0 steps it on win-x64 (DR-61, DR-64); the action space from the actuators' control ranges; SetState(NDArray, NDArray), DoSimulation(NDArray, int), StateVector() and GetBodyCom(string) for the envs; the reset that clears the data and lets the env draw its start.

[PyName("MujocoEnv")]
public abstract class MujocoEnv : Env<NDArray, NDArray>, IEnv, IDisposable, IDynamicAttributes
Inheritance
MujocoEnv
Implements
Derived
Inherited Members
Extension Methods

Remarks

Python attributes keep their names through Gym.NET's snake_case mapping: Model is model, Data data, InitQpos init_qpos, FrameSkip frame_skip, MujocoRenderer mujoco_renderer. The model and data expose what Gymnasium's code reads of MuJoCo's, under .NET names (DR-68).

Footgun: only Gymnasium's 14 bundled models exist (FromXmlPath(string)), so an xml_file that is a path is refused rather than compiled. Frames are Gym.NET's own drawing of the scene, compared with Gymnasium's and measured, not required equal (DR-62, DR-67).

Reference: gymnasium/envs/mujoco/mujoco_env.py.

Constructors

MujocoEnv(string, int, Space<NDArray>?, Metadata, string?, int, int, int?, string?, IReadOnlyDictionary<string, object?>?, int, IReadOnlyDictionary<int, bool>?, EnvViewerFactory?)

Loads the model, makes its data and the action space, and the renderer that draws them (Gymnasium's MujocoEnv.init).

protected MujocoEnv(string modelPath, int frameSkip, Space<NDArray>? observationSpace, Metadata classMetadata, string? renderMode = null, int width = 480, int height = 480, int? cameraId = null, string? cameraName = null, IReadOnlyDictionary<string, object?>? defaultCameraConfig = null, int maxGeom = 1000, IReadOnlyDictionary<int, bool>? visualOptions = null, EnvViewerFactory? viewerFactory = null)

Parameters

modelPath string

Gymnasium's model_path: the bundled model's file name ("ant.xml"); see ExpandModelPath(string).

frameSkip int

Gymnasium's frame_skip: physics steps per env step.

observationSpace Space<NDArray>

The observation space, or null for an env that sets it after.

classMetadata Metadata

The class's metadata as Python's class attribute holds it before init: a render_fps in it must equal round(1 / dt), as Gymnasium asserts (its v4 envs carry one, its v5 envs set theirs after).

renderMode string

Gymnasium's render_mode.

width int

The rendered frame's width in pixels (width).

height int

The rendered frame's height in pixels (height).

cameraId int?

The camera to render from (camera_id); -1 is the free camera.

cameraName string

The camera to render from by name (camera_name), exclusive with cameraId.

defaultCameraConfig IReadOnlyDictionary<string, object>

The free camera's settings (default_camera_config): distance, elevation, azimuth, lookat, trackbodyid, type.

maxGeom int

The most geoms a frame draws (max_geom).

visualOptions IReadOnlyDictionary<int, bool>

MuJoCo visual flags to switch (visual_options), by mjtVisFlag value.

viewerFactory EnvViewerFactory

Gym.NET's viewer_factory (DR-20) for human mode; null uses Gymnasium.HumanViewerFactory.

Exceptions

NotSupportedException

modelPath is not one of the bundled models.

AssertionError

The class metadata's render_fps does not match the time step.

OverflowError

A zero time step makes the frame rate infinite (Python's OverflowError of int(inf)).

ValueError

Both a camera id and a camera name, with Gymnasium's message; or a NaN time step (int(nan)).

Fields

DefaultSize

Gymnasium's DEFAULT_SIZE: the default width and height of a rendered frame, 480.

public const int DefaultSize = 480

Field Value

int

Properties

CameraId

The camera id given to the constructor (camera_id), or null; the renderer resolves the one it uses.

public int? CameraId { get; }

Property Value

int?

CameraName

The camera name given to the constructor (camera_name), or null.

public string? CameraName { get; }

Property Value

string

Data

The simulation (data): the state the env steps, with everything computed from it.

public MjData Data { get; }

Property Value

MjData

Dt

The env step's duration in seconds (dt): the model's time step times FrameSkip.

public double Dt { get; }

Property Value

double

FrameSkip

Physics steps per env step (frame_skip).

public int FrameSkip { get; }

Property Value

int

Fullpath

The model's file (fullpath): the bundled file name the model was loaded by, since Gym.NET embeds the compiled models instead of the XML files (Gymnasium's is a path into its package).

public string Fullpath { get; }

Property Value

string

Height

The rendered frame's height in pixels (height).

public int Height { get; }

Property Value

int

InitQpos

The reference positions (init_qpos), a float64 copy of the model's qpos0 made at construction; the resets add their noise to it. The env owns it.

public NDArray InitQpos { get; }

Property Value

NDArray

InitQvel

The reference velocities (init_qvel), zeros, copied at construction; the env owns it.

public NDArray InitQvel { get; }

Property Value

NDArray

Model

The model (model): the bundled model this env loaded, its own copy. Writing it (colours, the offscreen size) changes this env only.

public MjModel Model { get; }

Property Value

MjModel

MujocoRenderer

The renderer that draws the frames (mujoco_renderer).

public MujocoRenderer MujocoRenderer { get; }

Property Value

MujocoRenderer

Width

The rendered frame's width in pixels (width).

public int Width { get; }

Property Value

int

Methods

Close()

Closes the renderer's windows and buffers (close); the simulation stays usable, as in Gymnasium.

public override void Close()

Dispose(bool)

Closes, then releases the model's and data's views and the reference arrays.

protected override void Dispose(bool disposing)

Parameters

disposing bool

true from Dispose().

DoSimulation(NDArray, int)

Steps the simulation nFrames times holding the controls (do_simulation), after checking their shape.

public void DoSimulation(NDArray ctrl, int nFrames)

Parameters

ctrl NDArray

The controls, shape (nu,).

nFrames int

The physics steps.

Exceptions

ArgumentNullException

ctrl is null.

ValueError

Another shape, with Gymnasium's message.

ExpandModelPath(string)

Resolves a model path (expand_model_path) to the bundled model it names. Gym.NET has the 14 models Gymnasium ships, by file name (DR-63), and no MJCF compiler, so any path is refused.

[PyName("expand_model_path")]
public static string ExpandModelPath(string modelPath)

Parameters

modelPath string

A bundled file name, "ant.xml" to "walker2d_v5.xml".

Returns

string

The file name, the key FromXmlPath(string) loads by.

Exceptions

ArgumentNullException

modelPath is null.

NotSupportedException

Not a bundled model's name; the message lists them.

GetBodyCom(string)

A body's position in the world (get_body_com): its frame's origin, data.body(name).xpos, despite the name (not its center of mass). A writable view of the simulation's array, which the caller owns.

public NDArray GetBodyCom(string bodyName)

Parameters

bodyName string

The body's name.

Returns

NDArray

The (3,) view.

Exceptions

KeyError

No body has that name (MuJoCo's message).

GetResetInfo()

The reset's info (_get_reset_info): empty unless the env reports positions at reset.

[PyName("_get_reset_info")]
protected virtual Info GetResetInfo()

Returns

Info

The info.

InitializeSimulation()

Loads the model and makes its data (_initialize_simulation), growing the model's offscreen buffer to the render size and never shrinking it below the model's own.

protected virtual (MjModel Model, MjData Data) InitializeSimulation()

Returns

(MjModel Model, MjData Data)

The model and its data.

Exceptions

NotSupportedException

The model file is not bundled.

MetadataFromDt()

The v5 envs' instance metadata: the render modes and int(np.round(1.0 / self.dt)).

protected Metadata MetadataFromDt()

Returns

Metadata

A new metadata dict.

Exceptions

OverflowError

A zero time step (Python's OverflowError of int(inf)).

ValueError

A NaN time step (int(nan)).

Render()

Draws a frame in the render mode given at construction (render), through MujocoRenderer.

public override RenderResult Render()

Returns

RenderResult

rgb_array, depth_array, rgbd_tuple: the frame; human: nothing.

Exceptions

AttributeError

No render mode was given (Gymnasium's renderer refuses None).

Reset(BigInteger?, IReadOnlyDictionary<string, object?>?)

Starts an episode (reset): the generator reseeded from seed, the data cleared (mj_resetData), then the env's own start (ResetModel()) and reset info; a human-mode env draws the first frame.

public override ResetResult<NDArray> Reset(BigInteger? seed = null, IReadOnlyDictionary<string, object?>? options = null)

Parameters

seed BigInteger?

The seed, or null to continue the generator's stream.

options IReadOnlyDictionary<string, object>

Ignored, as in Gymnasium's MuJoCo envs.

Returns

ResetResult<NDArray>

The first observation and the reset info.

Exceptions

Error

A negative seed, as Gymnasium's seeding refuses it.

ResetModel()

The env's start (reset_model): its positions and velocities drawn from NpRandom in Gymnasium's order and set with SetState(NDArray, NDArray), and the first observation.

protected abstract NDArray ResetModel()

Returns

NDArray

The first observation, a new array.

SetActionSpace()

Sets the action space from the actuators' control ranges cast to float32 (_set_action_space): a float32 Box, one dimension per actuator, which the env owns (read it back from ActionSpace; Gymnasium's also returns it).

protected void SetActionSpace()

SetState(NDArray, NDArray)

Sets the joint positions and velocities, then runs the forward dynamics (set_state), so everything computed from them is current. The arrays are copied.

public void SetState(NDArray qpos, NDArray qvel)

Parameters

qpos NDArray

The positions, shape (nq,).

qvel NDArray

The velocities, shape (nv,).

Remarks

Footgun, as in Gymnasium: the positions and velocities are not the whole state; the warm start and the controls carry over, so MujocoUtils' state functions are the way to restore a step exactly.

Exceptions

ArgumentNullException

A null array.

AssertionError

A wrong shape (Gymnasium's bare assert).

StateVector()

The positions and velocities in one float64 array (state_vector), a new array the caller owns. Not the whole physics state (see SetState(NDArray, NDArray)).

public NDArray StateVector()

Returns

NDArray

The (nq + nv,) array.

StepMujocoSimulation(NDArray, int)

The physics of one env step (_step_mujoco_simulation): the controls set, nFrames physics steps, then the external forces Gymnasium's envs read (mj_rnePostConstraint).

protected void StepMujocoSimulation(NDArray ctrl, int nFrames)

Parameters

ctrl NDArray

The controls, one per actuator, any float dtype (cast to float64 as NumPy assigns).

nFrames int

The physics steps.