Skip to content

minimal_mjx.eval

Rolling out policies and recording what happens. See Rolling out a policy for a walkthrough.

minimal_mjx.eval.rollout

Functions:

Name Description
make_dummy_inference_fn

Makes a 'fake' inference function for simulating the environment without

rollout_policy

make_dummy_inference_fn

make_dummy_inference_fn(env: SwappableBase, mode='zero')

Makes a 'fake' inference function for simulating the environment without a policy. Modes are 'zero' (which sends all zeros as the action) and 'random' (which sends random actions in [-1, 1])

Source code in src/minimal_mjx/eval/rollout.py
def make_dummy_inference_fn(env: mm.envs.SwappableBase, mode='zero'):
    """Makes a 'fake' inference function for simulating the environment without 
    a policy. Modes are 'zero' (which sends all zeros as the action) and 
    'random' (which sends random actions in [-1, 1])"""
    inference_fn = None
    match mode:
        case 'zero':
            inference_fn = lambda obs, rng: (np.zeros(env.action_size), None)
        case 'random':
            inference_fn = lambda obs, rng, size=env.action_size: (2 * np.random.random(size) - 1, None)
        case _:
            raise Exception(f'Unknown inference type {mode}')

    return inference_fn

rollout_policy

rollout_policy(
    inference_fn,
    env: MjxEnv,
    n_steps=100,
    info_init_fn=lambda state: info,
    info_step_fn=lambda state: info,
    info_plot_key=None,
    width=None,
    height=None,
    gen_vid=True,
    show_progress=True,
    camera=None,
) -> tuple[
    list, list, RewardPlotter, MujocoPlotter, InfoPlotter
]
Source code in src/minimal_mjx/eval/rollout.py
def rollout_policy(
    inference_fn,
    env           : MjxEnv,
    n_steps       = 100,
    info_init_fn  = lambda state: state.info,
    info_step_fn  = lambda state: state.info,
    info_plot_key = None,
    width         = None,
    height        = None,
    gen_vid       = True,
    show_progress = True,
    camera        = None,
) -> tuple[list, list, plotting.RewardPlotter, plotting.MujocoPlotter, plotting.InfoPlotter]:
    width, height = plotting.infer_frame_dim(env.mj_model, width, height)
    step, reset = mm.learning.inference.get_step_reset(env)

    # Set up the environment
    rng = jax.random.PRNGKey(np.random.randint(0, 100000))
    state: mm.EnvState = reset(rng)

    # Initialize the state
    initial_info = state.info | info_init_fn(state)
    state = state.replace(info=initial_info)

    # Setup reward plotting
    reward_plotter = plotting.RewardPlotter(state.metrics)
    data_plotter = plotting.MujocoPlotter()
    info_plotter = plotting.InfoPlotter(plotkey=info_plot_key)
    data_plotter.add_row(state.data)

    # Rollout and record data
    N = int(n_steps)
    traj = [state]
    for i in tqdm(range(N), disable=not show_progress):
        ctrl, _ = inference_fn(state.obs, rng)
        state = step(state, ctrl)
        state = state.replace(info=state.info | info_step_fn(state))
        data_plotter.add_row(state.data)
        reward_plotter.add_row(state.metrics, state.reward)
        info_plotter.add_row(state.data.time, state.info)
        traj.append(state)

        if state.done:
            break

    scene_option = plotting.get_mj_scene_option(contacts=False, com=False)

    if gen_vid:
        print('Generating video...')
        frames = env.render(
            trajectory   = traj,
            camera       = camera,
            height       = height,
            width        = width,
            scene_option = scene_option,
        )
    else:
        frames = None
    return frames, traj, reward_plotter, data_plotter, info_plotter

minimal_mjx.eval.policy

Create default, single or parallel instance 'default policies.

Functions:

Name Description
make_zero_policy

Open-loop policy that always emits zero actions.

make_const_policy

Open-loop policy that always emits a constant action.

make_random_policy

Open-loop policy that emits uniform random actions in [-1, 1].

make_sinusoidal_policy

Open-loop sinusoid amp * sin(2*pi*freq*t + phases), identical across envs.

from_inference_fn

Adapt a normal brax policy(obs, key) to a time-based policy

make_open_loop_policy

Build an open-loop policy by name ('zero', 'random', 'sinusoid').

Attributes:

Name Type Description
OPEN_LOOP

OPEN_LOOP module-attribute

OPEN_LOOP = {
    "zero": make_zero_policy,
    "const": make_const_policy,
    "random": make_random_policy,
    "sinusoid": make_sinusoidal_policy,
}

make_zero_policy

make_zero_policy(action_size: int, **kwargs)

Open-loop policy that always emits zero actions.

Source code in src/minimal_mjx/eval/policy.py
def make_zero_policy(action_size: int, **kwargs):
    """Open-loop policy that always emits zero actions."""

    def policy(obs, key, t):
        batch_shape = get_batch_shape(obs)
        return jnp.zeros((*batch_shape, action_size)), {}

    return policy

make_const_policy

make_const_policy(
    action_size: int, value: float = 0.0, **kwargs
)

Open-loop policy that always emits a constant action.

Source code in src/minimal_mjx/eval/policy.py
def make_const_policy(action_size: int, value: float = 0.0, **kwargs):
    """Open-loop policy that always emits a constant action."""

    def policy(obs, key, t):
        batch_shape = get_batch_shape(obs)
        return value*jnp.ones((*batch_shape, action_size)), {}

    return policy

make_random_policy

make_random_policy(action_size: int, **kwargs)

Open-loop policy that emits uniform random actions in [-1, 1].

Source code in src/minimal_mjx/eval/policy.py
def make_random_policy(action_size: int, **kwargs):
    """Open-loop policy that emits uniform random actions in ``[-1, 1]``."""

    def policy(obs, key, t):
        batch_shape = get_batch_shape(obs)
        action = jax.random.uniform(
            key       = key,
            shape     = (*batch_shape, action_size),
            minval    = -1.0,
            maxval    = 1.0
        )
        return action, {}

    return policy

make_sinusoidal_policy

make_sinusoidal_policy(
    action_size: int,
    amp: float = 0.8,
    freq: float = 1.5,
    phases=None,
    **kwargs,
)

Open-loop sinusoid amp * sin(2*pi*freq*t + phases), identical across envs.

Source code in src/minimal_mjx/eval/policy.py
def make_sinusoidal_policy(
    action_size: int, amp: float = 0.8, freq: float = 1.5, phases=None, **kwargs
):
    """Open-loop sinusoid ``amp * sin(2*pi*freq*t + phases)``, identical across envs.
    """
    if phases is None:
        phases = jnp.zeros(action_size)
    else:
        phases = jnp.asarray(phases)

    def policy(obs, key, t):
        batch_shape = get_batch_shape(obs)
        action = amp * jnp.sin(2.0 * jnp.pi * freq * t + phases)  # (action_size,)
        return jnp.broadcast_to(action, (*batch_shape, action_size)), {}

    return policy

from_inference_fn

from_inference_fn(base_policy)

Adapt a normal brax policy(obs, key) to a time-based policy (obs, key, t) protocol.

Source code in src/minimal_mjx/eval/policy.py
def from_inference_fn(base_policy):
    """Adapt a normal brax ``policy(obs, key)`` to a time-based policy
    ``(obs, key, t)`` protocol.
    """

    def policy(obs, key, t): # t is unused
        return base_policy(obs, key)

    return policy

make_open_loop_policy

make_open_loop_policy(
    policy_desc: str, action_size: int, **kwargs
)

Build an open-loop policy by name ('zero', 'random', 'sinusoid').

Extra kwargs are forwarded to the underlying factory.

Source code in src/minimal_mjx/eval/policy.py
def make_open_loop_policy(policy_desc: str, action_size: int, **kwargs):
    """Build an open-loop policy by name (``'zero'``, ``'random'``, ``'sinusoid'``).

    Extra kwargs are forwarded to the underlying factory.
    """
    if policy_desc not in OPEN_LOOP:
        raise ValueError(
            f"Unknown open-loop policy '{policy_desc}'. Expected one of {list(OPEN_LOOP)}."
        )
    factory = OPEN_LOOP[policy_desc]
    return factory(action_size, **kwargs)